RynthCore as of 2026-10-04 (internal 843c801): RynthNav auto-travel and the navigation map, plugin API v75 (server and titles), launcher with Available plugins, download progress and the update on the front page, opt-in usage statistics, NPC names, radar colours, title-bar text size, FPS limiter, client action unlocks, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:27 -04:00
commit a24ed6df7c
322 changed files with 83009 additions and 7504 deletions

View file

@ -0,0 +1,128 @@
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using RynthCore.App;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Small code-built dialogs for the Decal bridge: the "Check Decal bridge" report (with
/// Repair / Copy) and the yes/no before the one administrator step.
/// </summary>
internal static class DecalBridgeDialog
{
private static readonly IBrush Back = new SolidColorBrush(Color.Parse("#132028"));
private static readonly IBrush Text = new SolidColorBrush(Color.Parse("#EAF0F4"));
private static readonly IBrush Muted = new SolidColorBrush(Color.Parse("#9AA8B3"));
private static readonly IBrush Accent = new SolidColorBrush(Color.Parse("#26C1A6"));
/// <summary>Yes/no. True = the person pressed <paramref name="yes"/>.</summary>
public static async Task<bool> AskAsync(Window owner, string title, string message, string yes, string no)
{
var dialog = NewWindow(title, 560);
var yesButton = new Button { Content = yes, IsDefault = true };
var noButton = new Button { Content = no, IsCancel = true };
yesButton.Click += (_, _) => dialog.Close(true);
noButton.Click += (_, _) => dialog.Close(false);
dialog.Content = Layout(title,
new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap, Foreground = Text },
yesButton, noButton);
bool? result = await dialog.ShowDialog<bool?>(owner);
return result == true;
}
/// <summary>
/// Shows the check's report. With <paramref name="offerRepair"/>, a Repair button; returns
/// true when the person pressed it.
/// </summary>
public static async Task<bool> ShowReportAsync(Window owner, DecalBridgeCheck.Result check, bool offerRepair)
{
string title = check.Blocking ? "Decal bridge check: it would NOT load" : "Decal bridge check: OK";
string report = check.ToReport();
var dialog = NewWindow(title, 760);
var body = new TextBox
{
Text = report,
IsReadOnly = true,
TextWrapping = TextWrapping.Wrap,
FontFamily = new FontFamily("Consolas, Cascadia Mono, monospace"),
FontSize = 12,
MaxHeight = 420,
Foreground = Text,
Background = new SolidColorBrush(Color.Parse("#0F161D")),
};
var copy = new Button { Content = "Copy report" };
copy.Click += async (_, _) =>
{
try
{
var clipboard = TopLevel.GetTopLevel(dialog)?.Clipboard;
if (clipboard != null) await clipboard.SetTextAsync(report);
copy.Content = "Copied";
}
catch { copy.Content = "Copy failed"; }
};
var close = new Button { Content = "Close", IsCancel = true };
close.Click += (_, _) => dialog.Close(false);
Control[] buttons;
if (offerRepair)
{
var repair = new Button { Content = check.NeedsMachineWideRegistration ? "Repair (asks for administrator)" : "Repair", IsDefault = true };
repair.Click += (_, _) => dialog.Close(true);
buttons = new Control[] { repair, copy, close };
}
else
{
buttons = new Control[] { copy, close };
}
string hint = check.Blocking
? "A Decal + RynthCore client started now would run without the bridge: no RynthCore overlay, then a crash. " +
(offerRepair ? "Repair registers the bridge where Decal reads on this PC and checks again." : "Fix the FAIL lines, then check again.")
: "A Decal + RynthCore client started now will load the bridge.";
dialog.Content = Layout(title,
new StackPanel
{
Spacing = 8,
Children =
{
new TextBlock { Text = hint, TextWrapping = TextWrapping.Wrap, Foreground = Muted },
body,
},
},
buttons);
bool? result = await dialog.ShowDialog<bool?>(owner);
return result == true;
}
private static Window NewWindow(string title, double width) => new()
{
Title = title,
Width = width,
SizeToContent = SizeToContent.Height,
CanResize = false,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Background = Back,
};
private static Control Layout(string title, Control body, params Control[] buttons)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right };
foreach (Control b in buttons) row.Children.Add(b);
return new StackPanel
{
Margin = new Thickness(18),
Spacing = 12,
Children =
{
new TextBlock { Text = title, FontSize = 16, FontWeight = FontWeight.SemiBold, Foreground = Accent },
body,
row,
},
};
}
}

View file

@ -0,0 +1,146 @@
using System;
using System.Diagnostics;
using System.Globalization;
namespace RynthCore.App.Avalonia;
/// <summary>The step a launcher download is on.</summary>
public enum DownloadStage
{
/// <summary>Bytes arriving: Done/Total are bytes, against the signed size from the feed.</summary>
Downloading,
/// <summary>The download finished and matched the signed size and SHA-256.</summary>
Verified,
/// <summary>Unpacking an archive: Done/Total are files.</summary>
Unpacking,
/// <summary>Putting the files in place (no measurable progress).</summary>
Installing,
}
/// <summary>
/// One progress report for the launcher's download area. <see cref="What"/> names the download
/// ("RynthNav map", "RynthOracle", "RynthCore 2026.10.5.1"). Reports come from the updater at a
/// few a second at most (<see cref="DownloadMeter"/>); the first, the last and every stage change
/// always come through.
/// </summary>
public sealed record DownloadProgress(string What, DownloadStage Stage, long Done, long Total,
double BytesPerSecond = 0, TimeSpan? Remaining = null, TimeSpan Elapsed = default)
{
/// <summary>0..100, or null when the step has no measurable progress.</summary>
public double? Percent => Total > 0 ? Math.Clamp(Done * 100.0 / Total, 0, 100) : null;
/// <summary>The line under the progress bar.</summary>
public string Detail => Stage switch
{
DownloadStage.Downloading => FormatDownloading(),
DownloadStage.Verified => $"{FormatMb(Total)} downloaded and verified against the signed feed.",
DownloadStage.Unpacking => Total > 0
? $"Unpacking {Done.ToString("N0", CultureInfo.InvariantCulture)} of {Total.ToString("N0", CultureInfo.InvariantCulture)} files…"
: "Unpacking…",
_ => "Installing…",
};
/// <summary>The activity-log line when a download is done: "RynthNav map: 539 MB in 2m10s, verified".</summary>
public string Summary => $"{What}: {FormatMb(Total)} in {FormatDuration(Elapsed)}, verified";
private string FormatDownloading()
{
string s = $"{FormatMb(Done, withUnit: false)} of {FormatMb(Total)}";
if (BytesPerSecond > 0) s += $" · {FormatMb((long)BytesPerSecond)}/s";
if (Remaining is { } r) s += $" · about {FormatDuration(r)} left";
return s;
}
/// <summary>"539 MB", "12.4 MB", "0.3 MB" (one decimal under 100 MB).</summary>
public static string FormatMb(long bytes, bool withUnit = true)
{
double mb = bytes / (1024.0 * 1024.0);
string n = mb >= 100 ? mb.ToString("N0", CultureInfo.InvariantCulture) : mb.ToString("0.0", CultureInfo.InvariantCulture);
return withUnit ? n + " MB" : n;
}
/// <summary>"8s", "2m10s", "1h05m".</summary>
public static string FormatDuration(TimeSpan t)
{
if (t < TimeSpan.Zero) t = TimeSpan.Zero;
if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h{t.Minutes:00}m";
if (t.TotalMinutes >= 1) return $"{(int)t.TotalMinutes}m{t.Seconds:00}s";
return $"{Math.Max(0, (int)Math.Round(t.TotalSeconds))}s";
}
}
/// <summary>
/// Measures one download: speed over the last few seconds, time left, and throttling so the UI
/// gets a handful of reports a second rather than one per 80 KB read. The clock is injectable
/// for tests.
/// </summary>
public sealed class DownloadMeter
{
public static readonly TimeSpan ReportEvery = TimeSpan.FromMilliseconds(250);
private static readonly TimeSpan SpeedWindow = TimeSpan.FromSeconds(4);
private readonly string _what;
private readonly long _total;
private readonly IProgress<DownloadProgress>? _progress;
private readonly Func<TimeSpan> _clock;
private readonly TimeSpan _start;
private TimeSpan _lastReport = TimeSpan.MinValue;
// A ring of (time, bytes) samples for the speed over the last few seconds.
private readonly (TimeSpan T, long Bytes)[] _samples = new (TimeSpan, long)[32];
private int _sampleCount, _sampleHead;
public DownloadMeter(string what, long total, IProgress<DownloadProgress>? progress, Func<TimeSpan>? clock = null)
{
_what = what;
_total = total;
_progress = progress;
if (clock == null)
{
var sw = Stopwatch.StartNew();
clock = () => sw.Elapsed;
}
_clock = clock;
_start = _clock();
AddSample(_start, 0);
}
public TimeSpan Elapsed => _clock() - _start;
/// <summary>Called after each read; reports at most every <see cref="ReportEvery"/>, and always at the end.</summary>
public void Report(long done)
{
if (_progress == null) return;
TimeSpan now = _clock();
bool last = done >= _total;
if (!last && _lastReport != TimeSpan.MinValue && now - _lastReport < ReportEvery) return;
_lastReport = now;
AddSample(now, done);
double speed = Speed(now, done);
TimeSpan? remaining = speed > 0 && !last ? TimeSpan.FromSeconds((_total - done) / speed) : last ? TimeSpan.Zero : null;
_progress.Report(new DownloadProgress(_what, DownloadStage.Downloading, done, _total, speed, remaining, now - _start));
}
/// <summary>The download matched the signed size and hash.</summary>
public void Verified() =>
_progress?.Report(new DownloadProgress(_what, DownloadStage.Verified, _total, _total, 0, TimeSpan.Zero, Elapsed));
private void AddSample(TimeSpan t, long bytes)
{
_samples[_sampleHead] = (t, bytes);
_sampleHead = (_sampleHead + 1) % _samples.Length;
if (_sampleCount < _samples.Length) _sampleCount++;
}
private double Speed(TimeSpan now, long done)
{
// The oldest sample still inside the window (or the oldest kept) is the baseline.
(TimeSpan T, long Bytes) baseline = (now, done);
for (int i = 0; i < _sampleCount; i++)
{
var s = _samples[(_sampleHead - _sampleCount + i + _samples.Length) % _samples.Length];
if (now - s.T <= SpeedWindow || i == _sampleCount - 1) { baseline = s; break; }
}
double secs = (now - baseline.T).TotalSeconds;
return secs > 0.05 ? (done - baseline.Bytes) / secs : 0;
}
}

View file

@ -108,10 +108,39 @@
</Border>
<Grid Grid.Row="1" ColumnDefinitions="3*,Auto,2*">
<TabControl Grid.Column="0" Margin="14,0,0,0" Padding="0">
<TabControl x:Name="MainTabs" Grid.Column="0" Margin="14,0,0,0" Padding="0">
<TabItem Header="Launcher">
<ScrollViewer>
<StackPanel Spacing="12" Margin="6">
<!-- Updates: the card is built by UpdateCardModel (MainWindow.RefreshUpdateCard). -->
<Border x:Name="UpdateCardBorder" Background="#132028" CornerRadius="16" Padding="18"
BorderBrush="#243742" BorderThickness="1">
<StackPanel Spacing="8">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Grid.Column="0" Spacing="4" VerticalAlignment="Center">
<TextBlock x:Name="UpdateCardTitle" Text="Updates" FontSize="16" FontWeight="SemiBold"
Foreground="#26C1A6" TextWrapping="Wrap" />
<TextBlock x:Name="UpdateCardDetail" Text="Not checked yet." TextWrapping="Wrap" Foreground="#9AA8B3" />
</StackPanel>
<WrapPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Top" Margin="12,0,0,0">
<Button x:Name="UpdateCardActionButton" IsVisible="False" Margin="0,0,8,6"
Background="#26C1A6" Foreground="#0B1218" FontWeight="SemiBold" />
<Button x:Name="CheckUpdatesButton" Content="Check for updates" Margin="0,0,0,6" />
</WrapPanel>
</Grid>
<StackPanel x:Name="UpdateCardWhatsNewPanel" Spacing="2" IsVisible="False" />
<Grid x:Name="DownloadArea" ColumnDefinitions="*,Auto" IsVisible="False">
<ProgressBar x:Name="DownloadProgressBar" Grid.Column="0" Minimum="0" Maximum="100"
Height="10" MinHeight="10" VerticalAlignment="Center"
Foreground="#26C1A6" Background="#0F161D" />
<Button x:Name="CancelDownloadButton" Grid.Column="1" Content="Cancel" Margin="10,0,0,0"
ToolTip.Tip="Stops the download. Nothing half-installed is left behind: the partial file is deleted and what you have stays as it is." />
</Grid>
<Button x:Name="UpdateCardNewPluginsButton" IsVisible="False" HorizontalAlignment="Left"
Background="Transparent" BorderThickness="0" Padding="0" Foreground="#F2C14E" />
</StackPanel>
</Border>
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Launch Targets" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
@ -234,36 +263,58 @@
</ScrollViewer>
</TabItem>
<TabItem Header="Plugins">
<ScrollViewer>
<TabItem x:Name="PluginsTab" Header="Plugins">
<ScrollViewer x:Name="PluginsScroll">
<StackPanel Spacing="12" Margin="6">
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Updates" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
<!-- Compact: the update card with its buttons is on the Launcher tab. -->
<TextBlock x:Name="UpdateStatusText"
Text="Not checked yet."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<WrapPanel Orientation="Horizontal">
<Button x:Name="CheckUpdatesButton" Content="Check for updates" Margin="0,0,8,6" />
<Button x:Name="UpdatePluginsButton" Content="Update plugins" IsVisible="False" Margin="0,0,8,6" />
<Button x:Name="InstallCoreUpdateButton" Content="Install RynthCore update" IsVisible="False" Margin="0,0,8,6" />
</WrapPanel>
<ProgressBar x:Name="PluginsTabProgressBar" Minimum="0" Maximum="100" Height="6" MinHeight="6"
IsVisible="False" Foreground="#26C1A6" Background="#0F161D" />
<Button x:Name="ShowUpdateCardButton" Content="Updates on the Launcher tab" HorizontalAlignment="Left"
Background="Transparent" BorderThickness="0" Padding="0" Foreground="#26C1A6" />
<CheckBox x:Name="AutoUpdatePluginsCheckBox"
Content="Update plugins automatically (a running bot keeps its version until AC restarts)"
Foreground="#EAF0F4" />
</StackPanel>
</Border>
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Usage statistics" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
<CheckBox x:Name="UsageStatsCheckBox"
Content="Help improve RynthCore: send an anonymous usage report once a day"
Foreground="#EAF0F4" />
<TextBlock x:Name="UsageStatsWhatText" TextWrapping="Wrap" Foreground="#9AA8B3" />
<TextBlock x:Name="UsageStatsNeverText" TextWrapping="Wrap" Foreground="#9AA8B3" />
<TextBlock x:Name="UsageStatsStopText" TextWrapping="Wrap" Foreground="#9AA8B3" />
<Button x:Name="ShowUsageReportButton" Content="Show what is sent" HorizontalAlignment="Left" />
</StackPanel>
</Border>
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Plugins" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
<TextBlock Text="Manage the runtime modules loaded into RynthCore. Add plugins by browsing for their DLL file."
<TextBlock Text="The plugins RynthCore loads. Untick one to skip it; the X takes it out of the list (its files stay on disk). RynthSuite plugins you don't have are under Available plugins below; Add Plugin is for any other plugin DLL."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<StackPanel x:Name="PluginLoadoutPanel" Spacing="10" />
<Button x:Name="AddPluginDllButton" Content="Add Plugin" HorizontalAlignment="Left" />
</StackPanel>
</Border>
<Border x:Name="AvailablePluginsBorder" Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<TextBlock Text="Available plugins" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
<TextBlock x:Name="AvailablePluginsHint"
Text="Plugins you can add appear here after the first update check."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<StackPanel x:Name="AvailablePluginsPanel" Spacing="10" />
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</TabItem>
@ -352,6 +403,9 @@
<CheckBox x:Name="EnableDcompOverlayCheckBox"
Content="Use DComp overlay (experimental, GPU-rendered)"
ToolTip.Tip="When ON, the engine starts the new DirectComposition overlay instead of the production AvaloniaOverlay. Mutually exclusive — Avalonia is single-app-per-process. Toggle takes effect on next AC client launch (a hot reload won't switch overlays)." />
<CheckBox x:Name="EnableImGuiBackendCheckBox"
Content="ImGui panels (preview)"
ToolTip.Tip="When ON, the engine runs its in-client ImGui layer, which docked panels move to as their ImGui versions are finished (choose per panel with /rc ui). Popped-out panels stay Avalonia windows. Costs nothing while no ImGui panel is open. Takes effect on next AC client launch or engine reload (RL)." />
</StackPanel>
</Border>
@ -366,6 +420,8 @@
<Button x:Name="RefreshSessionsButton" Content="Refresh Sessions" Margin="0,0,8,8" />
<Button x:Name="ResetOverlayBarButton" Content="Reset Overlay Bar" Margin="0,0,8,8"
ToolTip.Tip="Drags the in-game RynthCore overlay bar back to the top-left corner. Use this if the bar was moved off-screen and can no longer be reached. Applies to every running RynthCore client." />
<Button x:Name="CheckDecalBridgeButton" Content="Check Decal bridge" Margin="0,0,8,8"
ToolTip.Tip="For Decal + RynthCore (experimental): checks whether a client started now will load the RynthCore Decal bridge - where Decal reads its plugin list on this PC, whether the bridge is listed and enabled there, Decal's version and its .NET part. Changes nothing unless you press Repair." />
</WrapPanel>
<TextBlock Text="Manual inject targets the first detected acclient.exe session. Reset Overlay Bar signals all running RynthCore clients via the dispatch file."
TextWrapping="Wrap"

File diff suppressed because it is too large Load diff

View file

@ -7,7 +7,67 @@ namespace RynthCore.App.Avalonia;
internal static class Program
{
[STAThread]
public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
public static int Main(string[] args)
{
// The uninstaller removes the Decal bridge registration (docs/DECAL_BRIDGE_PLAN.md):
// no window, just the per-user registry entries this launcher added.
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-unregister", StringComparison.OrdinalIgnoreCase)))
{
bool ok = RynthCore.App.DecalBridgeRegistration.Unregister(out string report);
LauncherDiag.Info($"DECALBRIDGE: unregister (command line): {report}");
// A machine-wide entry (added with administrator rights when AC runs elevated on this
// PC) goes too: the uninstaller removes the DLL it points at. Ask for the rights only
// when there is one.
if (RynthCore.App.DecalBridgeRegistration.MachineEntryIsOurs())
{
var outcome = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out string mReport);
if (outcome == RynthCore.App.DecalBridgeRegistration.Outcome.NeedsAdmin && Environment.ProcessPath is string self)
outcome = RynthCore.App.DecalBridgeRegistration.RunElevated(self, "--decal-bridge-unregister-machine", out mReport);
LauncherDiag.Info($"DECALBRIDGE: unregister machine-wide (command line): {mReport}");
ok &= outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered;
}
return ok ? 0 : 1;
}
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-unregister-machine", StringComparison.OrdinalIgnoreCase)))
{
var outcome = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out string report);
LauncherDiag.Info($"DECALBRIDGE: unregister machine-wide (elevated step): {report}");
return outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered ? 0 : 1;
}
// The launcher's elevated step for "AC reads Decal's filter list for all users"
// (MainWindow.EnsureDecalBridgeAsync): --decal-bridge-register-machine "<bridge folder>".
int rm = Array.FindIndex(args, a => string.Equals(a, "--decal-bridge-register-machine", StringComparison.OrdinalIgnoreCase));
if (rm >= 0)
{
string dir = rm + 1 < args.Length ? args[rm + 1] : RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory;
var outcome = RynthCore.App.DecalBridgeRegistration.RegisterMachineWide(dir, out string report);
LauncherDiag.Info($"DECALBRIDGE: register machine-wide (elevated step): {report}");
return outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered ? 0 : 1;
}
// The installer's per-user half (installer\RynthCore.iss, as the installing user, every
// install and update): our entry into an EXISTING per-user copy of Decal's filter list.
int iu = Array.FindIndex(args, a => string.Equals(a, "--decal-bridge-install-user", StringComparison.OrdinalIgnoreCase));
if (iu >= 0)
{
string dir = iu + 1 < args.Length ? args[iu + 1] : RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory;
bool ok = RynthCore.App.DecalBridgeRegistration.InstallPerUser(dir, out string report);
LauncherDiag.Info($"DECALBRIDGE: install per-user (installer): {report}");
return ok ? 0 : 1;
}
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-status", StringComparison.OrdinalIgnoreCase)))
{
LauncherDiag.Info($"DECALBRIDGE: status (command line): {RynthCore.App.DecalBridgeRegistration.GetStatus()}");
return 0;
}
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-check", StringComparison.OrdinalIgnoreCase)))
{
var check = RynthCore.App.RealDecalCheckHost.Check(RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory,
RynthCore.App.DecalLocator.TryGetDecalAcClientPath(), EngineJsonStore.Path);
LauncherDiag.Info($"DECALBRIDGE: check (command line):{Environment.NewLine}{check.ToReport()}");
return check.Blocking ? 1 : 0;
}
return BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()

View file

@ -32,6 +32,9 @@
<Compile Include="..\RynthCore.App\LaunchAccountProfile.cs" Link="Shared\LaunchAccountProfile.cs" />
<Compile Include="..\RynthCore.App\InjectionMode.cs" Link="Shared\InjectionMode.cs" />
<Compile Include="..\RynthCore.App\DecalLocator.cs" Link="Shared\DecalLocator.cs" />
<Compile Include="..\RynthCore.App\DecalBridgeRegistration.cs" Link="Shared\DecalBridgeRegistration.cs" />
<Compile Include="..\RynthCore.App\DecalBridgeCheck.cs" Link="Shared\DecalBridgeCheck.cs" />
<Compile Include="..\RynthCore.App\RealDecalCheckHost.cs" Link="Shared\RealDecalCheckHost.cs" />
<Compile Include="..\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="Shared\AcLaunchArgumentBuilder.cs" />
<Compile Include="..\RynthCore.App\AcClientLaunchSettingsService.cs" Link="Shared\AcClientLaunchSettingsService.cs" />
<Compile Include="..\RynthCore.App\AcClientLoginAutomationService.cs" Link="Shared\AcClientLoginAutomationService.cs" />
@ -41,6 +44,7 @@
<Compile Include="..\RynthCore.App\BuildVersion.cs" Link="Shared\BuildVersion.cs" />
<Compile Include="..\RynthCore.App\AppSettings.cs" Link="Shared\AppSettings.cs" />
<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" />
<Compile Include="..\RynthCore.Injector\EngineInjectionService.cs" Link="Shared\EngineInjectionService.cs" />
<Compile Include="..\RynthCore.Injector\InjectionResult.cs" Link="Shared\InjectionResult.cs" />

View file

@ -0,0 +1,301 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.App.Avalonia;
/// <summary>
/// "Available plugins": every plugin in the signed feed that isn't in the player's plugin list,
/// for the player to install or not.
///
/// Install downloads the feed's file (verified against the signed size and SHA-256, like every
/// update) into C:\Games\RynthSuite\&lt;Name&gt;\&lt;File&gt; - the folder beside RynthAi's, or the
/// default - and the caller adds it to the plugin list. Only plugins named in the signed manifest
/// can be installed, from the URLs it carries; nothing else.
///
/// Removing a plugin from the list never deletes its files; a feed plugin that leaves the list is
/// simply available again.
///
/// "New": a plugin the launcher sees in the feed for the first time is marked New for a month and
/// said once in the activity log. The first time this runs (no update-seen-plugins.json yet),
/// what the feed already had counts as old except <see cref="RecentlyAdded"/>, which a player
/// who never got them should hear about.
/// </summary>
internal sealed partial class RynthUpdater
{
public const string DefaultSuiteDir = @"C:\Games\RynthSuite";
private const string RynthAiFile = "RynthCore.Plugin.RynthAi.dll";
private const int MaxDescriptionLength = 160;
private const int MaxChanges = 20;
private static readonly TimeSpan NewBadgeFor = TimeSpan.FromDays(30);
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);
/// <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);
/// <summary>
/// Plugins new in the feed before this list existed (2026.10.3.4). 2026.10.4.3 installed them
/// beside RynthAi automatically; from this launcher on they are offered, not forced.
/// </summary>
private static readonly string[] RecentlyAdded = { "RynthOracle", "RynthInventory" };
/// <summary>One line per plugin for feeds that carry no "description" (every feed before 2026.10.5).</summary>
private static readonly Dictionary<string, string> BuiltInDescriptions = new(StringComparer.OrdinalIgnoreCase)
{
["RynthAi"] = "The bot: combat, buffs, looting, navigation routes and metas.",
["RynthChat"] = "A chat window that sorts messages into tabs.",
["RynthTracker"] = "Kills, experience and luminance per hour for each session.",
["RynthNav"] = "Walks you to coordinates and towns, with route planning and the Atlas. Downloads its map (about 540 MB).",
["RynthVision"] = "Shows unclimbable slopes, impassable water and your radar range in the world.",
["RynthLua"] = "Lua scripting for metas and your own scripts.",
["RynthOracle"] = "Quests, character, titles and leaderboards.",
["RynthInventory"] = "Search every character's items.",
};
/// <summary>The feed's description, else the launcher's own line, else "".</summary>
public static string DescribePlugin(PluginEntry e) =>
e.Description.Length > 0 ? e.Description
: BuiltInDescriptions.TryGetValue(e.Name, out string? d) ? d : "";
private string? _suiteDirOverride;
/// <summary>Tests: the folder to use when no plugin in the list shows where RynthSuite lives.</summary>
internal void SetDefaultSuiteDir(string dir) => _suiteDirOverride = dir;
/// <summary>Tests: the clock for the New badge.</summary>
internal Func<DateTime> UtcNow { get; set; } = () => DateTime.UtcNow;
/// <summary>
/// Where RynthSuite plugins go: beside RynthAi (C:\Games\RynthSuite\RynthAi\x.dll -> C:\Games\RynthSuite),
/// else beside any feed plugin that sits in a folder named after it, else the default.
/// </summary>
public string SuiteDir(Manifest manifest, IEnumerable<string> pluginPaths)
{
List<string> paths = pluginPaths.ToList();
string? FromPlugin(string path)
{
string? folder = Path.GetDirectoryName(path);
string? suite = Path.GetDirectoryName(folder);
return string.IsNullOrEmpty(folder) || string.IsNullOrEmpty(suite) ? null : suite;
}
string? ai = paths.FirstOrDefault(p => string.Equals(Path.GetFileName(p), RynthAiFile, StringComparison.OrdinalIgnoreCase));
if (ai != null && FromPlugin(ai) is { } s1) return s1;
foreach (string p in paths)
{
PluginEntry? e = manifest.Plugins.FirstOrDefault(x => string.Equals(x.File, Path.GetFileName(p), StringComparison.OrdinalIgnoreCase));
if (e != null && string.Equals(Path.GetFileName(Path.GetDirectoryName(p)), e.Name, StringComparison.OrdinalIgnoreCase)
&& FromPlugin(p) is { } s2)
return s2;
}
return _suiteDirOverride ?? DefaultSuiteDir;
}
/// <summary>C:\Games\RynthSuite\&lt;Name&gt;\&lt;File&gt;; null for a name that isn't a plain folder name.</summary>
private static string? TargetPath(PluginEntry e, string suiteDir) =>
SafeFolderName.IsMatch(e.Name) && e.Name != "." && e.Name != ".." ? Path.Combine(suiteDir, e.Name, e.File) : null;
/// <summary>
/// Every feed plugin whose file isn't in <paramref name="pluginPaths"/> (by file name, like the
/// updates), except companions about to be installed anyway.
/// </summary>
public List<AvailablePlugin> GetAvailable(Manifest manifest, IEnumerable<string> pluginPaths, IEnumerable<CompanionInstall>? pending = null)
{
List<string> paths = pluginPaths.ToList();
var listed = new HashSet<string>(paths.Select(Path.GetFileName).OfType<string>(), StringComparer.OrdinalIgnoreCase);
var skip = new HashSet<string>((pending ?? Array.Empty<CompanionInstall>()).Select(c => c.Entry.File), StringComparer.OrdinalIgnoreCase);
string suite = SuiteDir(manifest, paths);
Dictionary<string, DateTime> seen = ReadSeenPlugins(out _);
DateTime now = UtcNow();
var result = new List<AvailablePlugin>();
foreach (PluginEntry e in manifest.Plugins)
{
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));
}
// New ones first, then by name.
return result.OrderByDescending(a => a.IsNew).ThenBy(a => a.Entry.Name, StringComparer.OrdinalIgnoreCase).ToList();
}
/// <summary>The Available list for a check, against the plugin list as it is now.</summary>
public List<AvailablePlugin> GetAvailable(CheckResult check, IEnumerable<string> pluginPaths) =>
GetAvailable(check.Manifest, pluginPaths, check.Companions);
/// <summary>
/// Installs one plugin from the signed feed for the caller to add to the plugin list. A file
/// already at the target is kept when it is the release build or newer (someone's own build);
/// an older one is replaced and kept beside it as .previous. Throws, with nothing changed,
/// when the download doesn't match the signed size and hash or is cancelled.
/// </summary>
public async Task<PluginInstall> InstallPluginAsync(CheckResult check, string name, IEnumerable<string> pluginPaths,
IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
List<string> paths = pluginPaths.ToList();
PluginEntry e = check.Manifest.Plugins.FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))
?? throw new InvalidOperationException($"{name} is not in the update feed");
if (paths.Any(p => string.Equals(Path.GetFileName(p), e.File, StringComparison.OrdinalIgnoreCase)))
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");
if (File.Exists(target))
{
bool same = string.Equals(Sha256File(target), e.Sha256, StringComparison.OrdinalIgnoreCase);
bool localBuild = File.GetLastWriteTimeUtc(target) > check.Manifest.PublishedUtc.AddMinutes(1);
if (same || localBuild)
return new PluginInstall(e, target, DescribePlugin(e), Downloaded: false);
}
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll");
try
{
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct, e.Name, progress);
progress?.Report(new DownloadProgress(e.Name, DownloadStage.Installing, 0, 0));
// Stamp the release time so a later check never mistakes it for a local build.
File.SetLastWriteTimeUtc(temp, check.Manifest.PublishedUtc);
if (File.Exists(target)) File.Copy(target, target + ".previous", overwrite: true);
File.Move(temp, target, overwrite: true);
}
finally
{
try { File.Delete(temp); } catch { }
}
return new PluginInstall(e, target, DescribePlugin(e), Downloaded: true);
}
// ── Manifest fields (optional, backward-compatible) ───────────────────────
/// <summary>The plugin entry's optional "description": one line, plain text, at most 160 characters.</summary>
private static string ReadDescription(JsonElement p)
{
if (!p.TryGetProperty("description", out JsonElement d) || d.ValueKind != JsonValueKind.String) return "";
return OneLine(d.GetString(), MaxDescriptionLength);
}
/// <summary>The manifest's optional "changes": up to 20 lines.</summary>
private static IReadOnlyList<string> ReadChanges(JsonElement r)
{
if (!r.TryGetProperty("changes", out JsonElement c) || c.ValueKind != JsonValueKind.Array) return Array.Empty<string>();
var list = new List<string>();
foreach (JsonElement e in c.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.String) continue;
string line = OneLine(e.GetString(), 300);
if (line.Length > 0) list.Add(line);
if (list.Count >= MaxChanges) break;
}
return list;
}
private static string OneLine(string? s, int max)
{
if (string.IsNullOrWhiteSpace(s)) return "";
var sb = new StringBuilder(Math.Min(s.Length, max + 1));
bool space = false;
foreach (char ch in s)
{
if (char.IsWhiteSpace(ch) || char.IsControl(ch)) { space = sb.Length > 0; continue; }
if (space) { sb.Append(' '); space = false; }
sb.Append(ch);
if (sb.Length > max) break;
}
string line = sb.ToString();
return line.Length > max ? line[..(max - 1)].TrimEnd() + "…" : line;
}
// ── Seen plugins (the New badge) ──────────────────────────────────────────
private string SeenPath => Path.Combine(_stateDir, "update-seen-plugins.json");
private Dictionary<string, DateTime> ReadSeenPlugins(out bool existed)
{
var map = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
existed = false;
try
{
if (!File.Exists(SeenPath)) return map;
using var doc = JsonDocument.Parse(File.ReadAllText(SeenPath));
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
if (p.Value.ValueKind == JsonValueKind.String && DateTime.TryParse(p.Value.GetString(), null,
System.Globalization.DateTimeStyles.AdjustToUniversal | System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime t))
map[p.Name] = t;
existed = true;
}
catch { map.Clear(); existed = false; }
return map;
}
/// <summary>Records the feed's plugins as seen; returns the ones seen for the first time that count as new.</summary>
private HashSet<string> RecordSeenPlugins(Manifest manifest)
{
var fresh = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, DateTime> seen = ReadSeenPlugins(out bool existed);
HashSet<string> offered = ReadOfferedCompanions();
DateTime now = UtcNow();
bool changed = !existed;
foreach (PluginEntry e in manifest.Plugins)
{
if (seen.ContainsKey(e.Name)) continue;
// First run of this list: only the recent additions are news, and not to a player who
// already had them offered (2026.10.4.3 installed them; removing one keeps it removed).
bool isNew = existed || (RecentlyAdded.Contains(e.Name, StringComparer.OrdinalIgnoreCase) && !offered.Contains(e.Name));
seen[e.Name] = isNew ? now : DateTime.UnixEpoch;
if (isNew) fresh.Add(e.Name);
changed = true;
}
if (changed)
{
try
{
Directory.CreateDirectory(_stateDir);
string tmp = SeenPath + ".tmp";
var ordered = seen.OrderBy(kv => kv.Key, StringComparer.OrdinalIgnoreCase)
.ToDictionary(kv => kv.Key, kv => kv.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"));
File.WriteAllText(tmp, JsonSerializer.Serialize(ordered, new JsonSerializerOptions { WriteIndented = true }), Encoding.UTF8);
File.Move(tmp, SeenPath, overwrite: true);
}
catch { }
}
return fresh;
}
}
/// <summary>Edits to the launcher's plugin list (kept apart from the window so tests can run them).</summary>
internal static class PluginListEdits
{
/// <summary>Adds <paramref name="path"/> once; false when it was already listed.</summary>
public static bool Add(IList<string> paths, string path)
{
if (paths.Any(p => string.Equals(p, path, StringComparison.OrdinalIgnoreCase))) return false;
paths.Add(path);
return true;
}
/// <summary>
/// Takes <paramref name="path"/> out of the list, and out of the disabled list so adding it back
/// later starts it enabled. Never touches the file.
/// </summary>
public static bool Remove(IList<string> paths, IList<string>? disabled, string path)
{
bool removed = RemoveAll(paths, path) > 0;
if (disabled != null) RemoveAll(disabled, path);
return removed;
}
private static int RemoveAll(IList<string> list, string path)
{
int n = 0;
for (int i = list.Count - 1; i >= 0; i--)
if (string.Equals(list[i], path, StringComparison.OrdinalIgnoreCase)) { list.RemoveAt(i); n++; }
return n;
}
}

View file

@ -0,0 +1,298 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.App.Avalonia;
/// <summary>
/// RynthNav's data folder (C:\Games\RynthCore\NavData by default): the navmesh tiles, portals.tsv
/// and locations.json, shipped as one archive.
///
/// Feed: an optional "navdata" object in the signed manifest —
/// {"id": hash of the tile set, "release": n, "url", "size", "sha256", "files": file count,
/// "bytes": unpacked size}.
/// The signature covers it exactly like the plugins; the archive is checked against the signed
/// size and SHA-256 before it is opened, and only plain file names RynthNav reads
/// (nav_XXXX.tile, portals.tsv, locations.json, navgraph.bin: the long-range route graph,
/// townnet.json: the Town Network's portals and the walks inside) are
/// accepted from it.
///
/// Install: only when RynthNav is in the plugin list and the folder's navdata.id differs from the
/// feed's id. The archive is unpacked beside the folder (NavData.new), the player's own files there
/// (atlas.txt, recalls.txt, anything else not shipped) are copied across, then the folders swap:
/// the old one is kept as NavData.previous (one generation). Old tiles never mix with new ones —
/// tiles from different bakes don't link. A folder with a navdata.local file in it is never touched
/// (someone baking their own tiles). Running clients keep the tiles they already loaded; new ones
/// load as they move (a relog picks up everything).
/// </summary>
internal sealed partial class RynthUpdater
{
public const string NavDataDefaultDir = @"C:\Games\RynthCore\NavData";
public const string NavDataIdFile = "navdata.id";
public const string NavDataLocalMarker = "navdata.local";
private const string RynthNavFile = "RynthCore.Plugin.RynthNav.dll";
private const long MaxNavDataBytes = 3L << 30; // the archive
private const long MaxNavDataEntryBytes = 32L << 20; // one file in it
private static readonly Regex ShippedName = new(@"^(nav_[0-9A-Fa-f]{4}\.tile|portals\.tsv|locations\.json|navgraph\.bin|townnet\.json)$", RegexOptions.CultureInvariant);
private static readonly Regex IdPattern = new(@"^[0-9a-f]{16,64}$", RegexOptions.CultureInvariant);
public sealed record NavDataEntry(string Id, int Release, string Url, long Size, string Sha256, int Files, long Bytes);
public enum NavDataState { UpToDate, NeedsUpdate, LocalTiles }
public sealed record NavDataStatus(NavDataEntry Entry, string Dir, string InstalledId, NavDataState State);
/// <summary>True for a file name the archive may carry (and that an update replaces).</summary>
public static bool IsShippedNavFile(string name) => ShippedName.IsMatch(name);
/// <summary>
/// A whole number written either way: 1383002945 or 1383002945.0. PowerShell's ConvertTo-Json writes
/// a double with ".0", and GetInt64 refused it - which failed the whole update check for every
/// launcher on 2026.10.3.1/2 ("One of the identified items was in an invalid format").
/// </summary>
private static long WholeNumber(JsonElement e)
{
if (e.TryGetInt64(out long l)) return l;
double d = e.GetDouble();
if (d < 0 || d > long.MaxValue || d != Math.Floor(d)) throw new InvalidDataException($"not a whole number: {e.GetRawText()}");
return (long)d;
}
/// <summary>A navdata entry that can't be read leaves the tiles out of this check; the core and plugins still update.</summary>
private NavDataEntry? TryParseNavData(JsonElement nd)
{
try { return ParseNavData(nd); }
catch (Exception ex) when (ex is InvalidDataException or FormatException or InvalidOperationException or KeyNotFoundException)
{
System.Diagnostics.Debug.WriteLine($"RynthUpdater: navdata entry unreadable ({ex.Message}); tiles skipped this check.");
return null;
}
}
private NavDataEntry ParseNavData(JsonElement nd)
{
string id = (nd.GetProperty("id").GetString() ?? "").ToLowerInvariant();
if (!IdPattern.IsMatch(id)) throw new InvalidDataException($"bad navdata id '{id}'");
int files = (int)WholeNumber(nd.GetProperty("files"));
if (files <= 0) throw new InvalidDataException("navdata lists no files");
return new NavDataEntry(id, (int)WholeNumber(nd.GetProperty("release")), CheckUrl(nd.GetProperty("url").GetString()),
WholeNumber(nd.GetProperty("size")), nd.GetProperty("sha256").GetString() ?? "", files,
nd.TryGetProperty("bytes", out JsonElement b) ? WholeNumber(b) : 0);
}
/// <summary>
/// Where RynthNav reads its data: "navDataDir" in %APPDATA%\RynthCore\rynthnav.json (the same
/// file the plugin reads; see the plugin's NavDataConfig), else the default.
/// </summary>
public string NavDataDir
{
get
{
try
{
string settings = Path.Combine(_stateDir, "rynthnav.json");
if (File.Exists(settings))
{
using var doc = JsonDocument.Parse(File.ReadAllText(settings),
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
if (doc.RootElement.ValueKind == JsonValueKind.Object)
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
if (p.Name.Equals("navDataDir", StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.String
&& p.Value.GetString() is { } dir && Path.IsPathFullyQualified(dir.Trim()))
return dir.Trim().TrimEnd('\\', '/');
}
}
catch { }
return _navDataDirOverride ?? NavDataDefaultDir;
}
}
private string? _navDataDirOverride;
/// <summary>Where the archive is downloaded to; null = %LOCALAPPDATA%\RynthCore\updates (tests set their own).</summary>
internal string? NavDataCacheDir { get; set; }
/// <summary>Tests: the folder to use when rynthnav.json doesn't name one.</summary>
internal void SetDefaultNavDataDir(string dir) => _navDataDirOverride = dir;
private NavDataStatus? CheckNavData(Manifest manifest, IEnumerable<string> pluginPaths)
{
if (manifest.NavData is not { } e) return null;
bool hasNav = pluginPaths.Any(p => string.Equals(Path.GetFileName(p), RynthNavFile, StringComparison.OrdinalIgnoreCase) && File.Exists(p));
if (!hasNav) return null;
string dir = NavDataDir;
string installed = "";
try { if (File.Exists(Path.Combine(dir, NavDataIdFile))) installed = File.ReadAllText(Path.Combine(dir, NavDataIdFile)).Trim().ToLowerInvariant(); }
catch { }
NavDataState state = File.Exists(Path.Combine(dir, NavDataLocalMarker)) ? NavDataState.LocalTiles
: installed == e.Id ? NavDataState.UpToDate : NavDataState.NeedsUpdate;
return new NavDataStatus(e, dir, installed, state);
}
/// <summary>
/// Downloads, verifies and installs the feed's RynthNav data (see the class notes). Returns a
/// line for the activity log. Throws on anything wrong, leaving the installed folder as it was.
/// </summary>
public const string NavDataDisplayName = "RynthNav map";
/// <summary>
/// Cancel is safe at any point before the folder swap: the partial download is deleted, an
/// unpacked staging folder is removed, and the installed tiles stay as they were. A fully
/// downloaded, verified archive stays in the cache and is reused by the next try. The swap
/// itself (two folder renames) doesn't stop half way.
/// </summary>
public async Task<string> UpdateNavDataAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
if (check.NavData is not { State: NavDataState.NeedsUpdate } st) return "";
NavDataEntry e = st.Entry;
string dir = st.Dir.TrimEnd('\\', '/');
string parent = Path.GetDirectoryName(dir) ?? throw new InvalidOperationException($"bad NavData folder {dir}");
Directory.CreateDirectory(parent);
// Room for the archive, the unpacked copy and the old folder kept as .previous.
long need = e.Size + Math.Max(e.Bytes, e.Size * 3) + (64L << 20);
long free = new DriveInfo(Path.GetPathRoot(Path.GetFullPath(dir))!).AvailableFreeSpace;
if (free < need)
throw new IOException($"not enough disk space for the navmesh tiles: {need >> 20} MB needed, {free >> 20} MB free on {Path.GetPathRoot(dir)}");
string cache = NavDataCacheDir ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "updates");
Directory.CreateDirectory(cache);
string zip = Path.Combine(cache, $"navdata-{e.Id}.zip");
if (!(File.Exists(zip) && new FileInfo(zip).Length == e.Size && string.Equals(Sha256File(zip), e.Sha256, StringComparison.OrdinalIgnoreCase)))
{
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxNavDataBytes, zip + ".part", ct, NavDataDisplayName, progress);
File.Move(zip + ".part", zip, overwrite: true);
}
// Unpacking tens of thousands of files takes a while: off the caller's (UI) thread.
await Task.Run(() =>
{
progress?.Report(new DownloadProgress(NavDataDisplayName, DownloadStage.Unpacking, 0, e.Files));
string staging = dir + ".new";
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
Directory.CreateDirectory(staging);
try
{
int count = ExtractNavData(zip, staging, ct,
n => progress?.Report(new DownloadProgress(NavDataDisplayName, DownloadStage.Unpacking, n, e.Files)));
if (count != e.Files) throw new InvalidDataException($"the tile archive has {count} files, the feed says {e.Files}");
// The player's own files (atlas.txt, recalls.txt, …) and anything else not shipped come along.
if (Directory.Exists(dir)) CopyUnshipped(dir, staging);
File.WriteAllText(Path.Combine(staging, NavDataIdFile), e.Id);
// Last chance to cancel: from here the swap runs to the end.
ct.ThrowIfCancellationRequested();
progress?.Report(new DownloadProgress(NavDataDisplayName, DownloadStage.Installing, 0, 0));
SwapNavData(dir, staging);
}
catch
{
try { if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true); } catch { }
throw;
}
}, ct);
try { File.Delete(zip); } catch { }
return $"RynthNav navmesh tiles updated: {e.Files} files into {dir} (the old ones are in {Path.GetFileName(dir)}.previous). Running clients load the new tiles as they move; a relog picks up all of them.";
}
/// <summary>Unpacks only plain, known file names; returns how many files were written.</summary>
internal static int ExtractNavData(string zipPath, string dest, CancellationToken ct = default, Action<int>? unpacked = null)
{
int n = 0;
var sinceReport = System.Diagnostics.Stopwatch.StartNew();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
using ZipArchive za = ZipFile.OpenRead(zipPath);
foreach (ZipArchiveEntry z in za.Entries)
{
ct.ThrowIfCancellationRequested();
if (z.FullName.EndsWith('/') && z.Length == 0) continue; // a folder entry
string name = z.FullName;
if (name != z.Name || !IsShippedNavFile(name))
throw new InvalidDataException($"unexpected file in the tile archive: '{name}'");
if (!seen.Add(name)) throw new InvalidDataException($"'{name}' is in the tile archive twice");
if (z.Length > MaxNavDataEntryBytes) throw new InvalidDataException($"'{name}' is too large ({z.Length} bytes)");
string target = Path.Combine(dest, name);
using (Stream src = z.Open())
using (var f = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
byte[] buf = new byte[81920];
long total = 0; int r;
while ((r = src.Read(buf, 0, buf.Length)) > 0)
{
total += r;
if (total > MaxNavDataEntryBytes) throw new InvalidDataException($"'{name}' unpacks larger than it says");
f.Write(buf, 0, r);
}
}
n++;
if (unpacked != null && sinceReport.Elapsed >= DownloadMeter.ReportEvery)
{
unpacked(n);
sinceReport.Restart();
}
}
unpacked?.Invoke(n);
return n;
}
private static void CopyUnshipped(string from, string to)
{
foreach (string f in Directory.GetFiles(from))
{
string name = Path.GetFileName(f);
if (IsShippedNavFile(name) || name.Equals(NavDataIdFile, StringComparison.OrdinalIgnoreCase)) continue;
string target = Path.Combine(to, name);
if (!File.Exists(target)) File.Copy(f, target);
}
foreach (string d in Directory.GetDirectories(from))
{
string target = Path.Combine(to, Path.GetFileName(d));
Directory.CreateDirectory(target);
CopyTree(d, target);
}
}
private static void CopyTree(string from, string to)
{
foreach (string f in Directory.GetFiles(from)) File.Copy(f, Path.Combine(to, Path.GetFileName(f)), overwrite: false);
foreach (string d in Directory.GetDirectories(from))
{
string t = Path.Combine(to, Path.GetFileName(d));
Directory.CreateDirectory(t);
CopyTree(d, t);
}
}
// dir -> dir.previous, staging -> dir. A client reading a tile at that moment holds it open for
// a few milliseconds, so each move is retried; if the second fails the first is undone.
private static void SwapNavData(string dir, string staging)
{
string previous = dir + ".previous";
bool hadOld = Directory.Exists(dir);
if (hadOld)
{
if (Directory.Exists(previous)) Directory.Delete(previous, recursive: true);
Retry(() => Directory.Move(dir, previous));
}
try { Retry(() => Directory.Move(staging, dir)); }
catch
{
if (hadOld && !Directory.Exists(dir)) { try { Directory.Move(previous, dir); } catch { } }
throw;
}
}
private static void Retry(Action a)
{
for (int i = 0; ; i++)
{
try { a(); return; }
catch (IOException) when (i < 9) { Thread.Sleep(500); }
catch (UnauthorizedAccessException) when (i < 9) { Thread.Sleep(500); }
}
}
}

View file

@ -25,8 +25,12 @@ namespace RynthCore.App.Avalonia;
/// touches a running bot: the new version loads the next time AC starts, or on RL if the player
/// chooses — the updater never reloads anything. The core (engine, Loader, launcher) updates by
/// running the release's installer, and only while no RynthCore client is running.
///
/// RynthNav's data (navmesh tiles, portals.tsv, locations.json) is an optional signed archive in
/// the same manifest ("navdata"), installed only for players who have RynthNav in their plugin
/// list, and only when its id (a hash of the tile set) changes. See RynthUpdater.NavData.cs.
/// </summary>
internal sealed class RynthUpdater
internal sealed partial class RynthUpdater
{
public const string DefaultFeedUrl = "https://aelrynth.com/downloads/rynth/update.json";
@ -34,21 +38,60 @@ internal sealed class RynthUpdater
private const long MaxPluginBytes = 64L << 20;
private const long MaxInstallerBytes = 256L << 20;
public sealed record PluginEntry(string Name, string File, string Url, long Size, string Sha256);
/// <summary>
/// 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.
/// </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 Manifest(int Release, string Version, DateTime PublishedUtc, string Notes,
InstallerEntry Core, IReadOnlyList<PluginEntry> Plugins);
InstallerEntry Core, IReadOnlyList<PluginEntry> Plugins, NavDataEntry? NavData = null)
{
/// <summary>
/// The release's changes, one line each: the optional "changes" array (written since 2026.10.5;
/// signed with the rest). Empty for older feeds, which only have <see cref="Notes"/>.
/// </summary>
public IReadOnlyList<string> Changes { get; init; } = Array.Empty<string>();
}
/// <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 }
/// <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);
public sealed record CheckResult(Manifest Manifest, int InstalledCoreRelease, IReadOnlyList<PluginStatus> Plugins)
{
public bool CoreUpdateAvailable => Manifest.Core.Release > InstalledCoreRelease;
public IEnumerable<PluginStatus> PluginsToUpdate => Plugins.Where(p => p.State == PluginState.NeedsUpdate);
/// <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>
public IReadOnlyList<AvailablePlugin> Available { get; init; } = Array.Empty<AvailablePlugin>();
/// <summary>Available plugins this launcher sees in the feed for the first time: said once in the activity log.</summary>
public IReadOnlyList<AvailablePlugin> NewlyAnnounced { get; init; } = Array.Empty<AvailablePlugin>();
/// <summary>RynthNav's tiles: null when the feed has none or RynthNav isn't in the plugin list.</summary>
public NavDataStatus? NavData { get; init; }
public bool NavDataUpdateAvailable => NavData is { State: NavDataState.NeedsUpdate };
}
/// <summary>
/// Features that moved out of a plugin into their own. When the player has the parent and not the
/// child, the child is installed in a sibling folder and registered, once: a player who removes it
/// afterwards keeps it removed.
///
/// Only for a split, where the player's scripts stop working without the child. A plugin that is
/// simply new (RynthOracle, RynthInventory: 2026.10.4.3 auto-installed them this way) is offered
/// instead, under Available plugins with a "New" badge (<see cref="RecentlyAdded"/>); players who
/// already got them keep them.
/// </summary>
private static readonly (string ParentFile, string ChildName, string Reason)[] Companions =
{
("RynthCore.Plugin.RynthAi.dll", "RynthLua", "Lua scripting, which moved out of RynthAi"),
};
private static readonly HttpClient Http = CreateHttp();
private readonly string _feedUrl;
@ -124,7 +167,71 @@ internal sealed class RynthUpdater
statuses.Add(new PluginStatus(entry, path, state));
}
return new CheckResult(manifest, InstalledCoreRelease, statuses);
List<CompanionInstall> companions = FindCompanions(manifest, pluginPaths);
HashSet<string> fresh = RecordSeenPlugins(manifest); // before GetAvailable: it reads the New badges
List<AvailablePlugin> available = GetAvailable(manifest, pluginPaths, companions);
return new CheckResult(manifest, InstalledCoreRelease, statuses)
{
Companions = companions,
NavData = CheckNavData(manifest, pluginPaths),
Available = available,
NewlyAnnounced = available.Where(a => fresh.Contains(a.Entry.Name)).ToList(),
};
}
private List<CompanionInstall> FindCompanions(Manifest manifest, IEnumerable<string> pluginPaths)
{
var result = new List<CompanionInstall>();
List<string> paths = pluginPaths.ToList();
HashSet<string> offered = ReadOfferedCompanions();
foreach (var (parentFile, childName, reason) in Companions)
{
if (offered.Contains(childName)) continue;
string? parent = paths.FirstOrDefault(p =>
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 (paths.Any(p => string.Equals(Path.GetFileName(p), child.File, StringComparison.OrdinalIgnoreCase)))
{
MarkCompanionOffered(childName); // already there: nothing to do, ever
continue;
}
// C:\Games\RynthSuite\RynthAi\x.dll -> C:\Games\RynthSuite\RynthLua\<file>
string? suiteDir = Path.GetDirectoryName(Path.GetDirectoryName(parent));
if (string.IsNullOrEmpty(suiteDir)) continue;
result.Add(new CompanionInstall(child, Path.Combine(suiteDir, childName, child.File), reason));
}
return result;
}
/// <summary>
/// Installs <see cref="CheckResult.Companions"/> (verified like every plugin; an existing file at the
/// target is kept) and returns their paths for the caller to register in the plugin list.
/// </summary>
public async Task<List<CompanionInstall>> InstallCompanionsAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
var done = new List<CompanionInstall>();
foreach (CompanionInstall c in check.Companions)
{
if (!File.Exists(c.Path))
{
Directory.CreateDirectory(Path.GetDirectoryName(c.Path)!);
string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll");
try
{
await DownloadVerifiedAsync(c.Entry.Url, c.Entry.Size, c.Entry.Sha256, MaxPluginBytes, temp, ct, c.Entry.Name, progress);
File.SetLastWriteTimeUtc(temp, check.Manifest.PublishedUtc);
File.Move(temp, c.Path, overwrite: false);
}
finally
{
try { File.Delete(temp); } catch { }
}
}
MarkCompanionOffered(c.Entry.Name);
done.Add(c);
}
return done;
}
// ── Plugins ───────────────────────────────────────────────────────────────
@ -133,7 +240,7 @@ internal sealed class RynthUpdater
/// Swaps each outdated plugin DLL for the verified release build. The previous file is kept
/// beside it as .previous. Running clients keep the version they started with.
/// </summary>
public async Task<List<string>> UpdatePluginsAsync(CheckResult check, CancellationToken ct = default)
public async Task<List<string>> UpdatePluginsAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
var done = new List<string>();
foreach (var group in check.PluginsToUpdate.GroupBy(p => p.Entry))
@ -142,7 +249,7 @@ internal sealed class RynthUpdater
string temp = Path.Combine(Path.GetTempPath(), $"rynth-{Guid.NewGuid():N}.dll");
try
{
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct);
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, temp, ct, e.Name, progress);
foreach (PluginStatus p in group)
{
string staged = p.Path + ".new";
@ -165,7 +272,7 @@ internal sealed class RynthUpdater
// ── Core ──────────────────────────────────────────────────────────────────
/// <summary>Downloads (or reuses) the release installer, verified, and returns its path.</summary>
public async Task<string> DownloadInstallerAsync(CheckResult check, CancellationToken ct = default)
public async Task<string> DownloadInstallerAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
InstallerEntry core = check.Manifest.Core;
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
@ -177,7 +284,7 @@ internal sealed class RynthUpdater
return path;
string temp = path + ".part";
await DownloadVerifiedAsync(core.Url, core.Size, core.Sha256, MaxInstallerBytes, temp, ct);
await DownloadVerifiedAsync(core.Url, core.Size, core.Sha256, MaxInstallerBytes, temp, ct, $"RynthCore {core.Version}", progress);
File.Move(temp, path, overwrite: true);
return path;
}
@ -238,12 +345,17 @@ internal sealed class RynthUpdater
if (file.Length == 0 || file != Path.GetFileName(file) || !file.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
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() ?? ""));
CheckUrl(p.GetProperty("url").GetString()), p.GetProperty("size").GetInt64(), p.GetProperty("sha256").GetString() ?? "",
ReadDescription(p)));
}
return new Manifest(r.GetProperty("release").GetInt32(), r.GetProperty("version").GetString() ?? "",
r.GetProperty("published").GetDateTime().ToUniversalTime(),
r.TryGetProperty("notes", out JsonElement n) ? n.GetString() ?? "" : "", core, plugins);
r.TryGetProperty("notes", out JsonElement n) ? n.GetString() ?? "" : "", core, plugins,
r.TryGetProperty("navdata", out JsonElement nd) && nd.ValueKind == JsonValueKind.Object ? TryParseNavData(nd) : null)
{
Changes = ReadChanges(r),
};
}
private string CheckUrl(string? url)
@ -271,31 +383,49 @@ internal sealed class RynthUpdater
return ms.ToArray();
}
private static async Task DownloadVerifiedAsync(string url, long size, string sha256, long max, string dest, CancellationToken ct)
/// <summary>
/// Downloads to <paramref name="dest"/> and checks it against the signed size and SHA-256. On any
/// failure (a wrong hash, a lost connection, Cancel) the partial file is deleted. Progress, when
/// asked for, goes to <paramref name="progress"/> a few times a second (<see cref="DownloadMeter"/>),
/// then one <see cref="DownloadStage.Verified"/> report once the hash matched.
/// </summary>
private static async Task DownloadVerifiedAsync(string url, long size, string sha256, long max, string dest, CancellationToken ct,
string? what = null, IProgress<DownloadProgress>? progress = null)
{
if (size <= 0 || size > max) throw new InvalidDataException($"{url}: size {size} out of range");
using var resp = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct);
resp.EnsureSuccessStatusCode();
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
long total = 0;
await using (var s = await resp.Content.ReadAsStreamAsync(ct))
await using (var f = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None))
var meter = new DownloadMeter(what ?? Path.GetFileName(url), size, progress);
try
{
byte[] buf = new byte[81920];
int n;
while ((n = await s.ReadAsync(buf, ct)) > 0)
using var resp = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct);
resp.EnsureSuccessStatusCode();
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
long total = 0;
meter.Report(0);
await using (var s = await resp.Content.ReadAsStreamAsync(ct))
await using (var f = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None))
{
total += n;
if (total > size) throw new InvalidDataException($"{url} is larger than the signed size");
hash.AppendData(buf, 0, n);
await f.WriteAsync(buf.AsMemory(0, n), ct);
byte[] buf = new byte[81920];
int n;
while ((n = await s.ReadAsync(buf, ct)) > 0)
{
ct.ThrowIfCancellationRequested();
total += n;
if (total > size) throw new InvalidDataException($"{url} is larger than the signed size");
hash.AppendData(buf, 0, n);
await f.WriteAsync(buf.AsMemory(0, n), ct);
meter.Report(total);
}
}
string got = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
if (total != size || !string.Equals(got, sha256, StringComparison.OrdinalIgnoreCase))
throw new InvalidDataException($"{Path.GetFileName(url)} does not match the signed hash — not installed");
meter.Verified();
}
string got = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
if (total != size || !string.Equals(got, sha256, StringComparison.OrdinalIgnoreCase))
catch
{
// The file stream is closed by now (its using block ended), so the delete can't be refused by it.
try { File.Delete(dest); } catch { }
throw new InvalidDataException($"{Path.GetFileName(url)} does not match the signed hash — not installed");
throw;
}
}
@ -315,6 +445,35 @@ internal sealed class RynthUpdater
// ── State ─────────────────────────────────────────────────────────────────
private string StatePath => Path.Combine(_stateDir, "update-state.json");
private string CompanionsPath => Path.Combine(_stateDir, "update-companions.json");
private HashSet<string> ReadOfferedCompanions()
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
try
{
if (!File.Exists(CompanionsPath)) return set;
using var doc = JsonDocument.Parse(File.ReadAllText(CompanionsPath));
foreach (JsonElement e in doc.RootElement.EnumerateArray())
if (e.GetString() is { Length: > 0 } s) set.Add(s);
}
catch { }
return set;
}
private void MarkCompanionOffered(string name)
{
try
{
HashSet<string> set = ReadOfferedCompanions();
if (!set.Add(name)) return;
Directory.CreateDirectory(_stateDir);
string tmp = CompanionsPath + ".tmp";
File.WriteAllText(tmp, "[" + string.Join(", ", set.OrderBy(s => s).Select(s => JsonSerializer.Serialize(s))) + "]", Encoding.UTF8);
File.Move(tmp, CompanionsPath, overwrite: true);
}
catch { }
}
private int ReadHighestRelease()
{

View file

@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace RynthCore.App.Avalonia;
/// <summary>What the update card on the launcher's front page is showing.</summary>
public enum UpdateCardKind { NotConfigured, NotChecked, Checking, Error, UpToDate, CoreUpdate, PluginUpdates, Downloading }
/// <summary>Everything the card needs to know, gathered by the window (no UI types, so tests can build it).</summary>
public sealed record UpdateCardInput
{
public bool Configured { get; init; } = true;
public bool Checking { get; init; }
/// <summary>The last check's error; null when it worked.</summary>
public string? Error { get; init; }
/// <summary>When the last check succeeded (local time); null before the first.</summary>
public DateTime? LastChecked { get; init; }
/// <summary>True once a check has succeeded this session.</summary>
public bool HasCheck { get; init; }
public string InstalledVersion { get; init; } = "";
public bool CoreUpdateAvailable { get; init; }
public string AvailableVersion { get; init; } = "";
public string Notes { get; init; } = "";
public IReadOnlyList<string> Changes { get; init; } = Array.Empty<string>();
/// <summary>Plugin updates (and new companions, the RynthNav map) waiting to be installed.</summary>
public IReadOnlyList<string> PendingPluginUpdates { get; init; } = Array.Empty<string>();
/// <summary>Available plugins with the New badge.</summary>
public IReadOnlyList<string> NewPlugins { get; init; } = Array.Empty<string>();
/// <summary>Game clients running RynthCore (a RynthCore update waits for them to close).</summary>
public int ClientsRunning { get; init; }
/// <summary>The download in progress, if any.</summary>
public DownloadProgress? Download { get; init; }
public bool CanCancel { get; init; }
}
/// <summary>The card's text and which buttons show.</summary>
public sealed record UpdateCard(
UpdateCardKind Kind,
string Title,
string Detail,
IReadOnlyList<string> WhatsNew,
bool ShowCheckButton,
string? ActionButton,
bool ShowProgress,
double? ProgressPercent,
bool ShowCancel,
string? NewPluginsLine,
/// <summary>One line for the Plugins tab and the header.</summary>
string Compact);
/// <summary>
/// The front page's update card as a pure function of <see cref="UpdateCardInput"/>: up to date,
/// RynthCore update (installs once every game client is closed), plugin updates, downloading
/// (bar, MB, speed, time left, step), errors, and a line about new plugins.
/// </summary>
public static class UpdateCardModel
{
public const int MaxWhatsNew = 4;
public const string UpdateCoreButton = "Update RynthCore";
public const string UpdatePluginsButton = "Update plugins";
public static UpdateCard Build(UpdateCardInput i)
{
string? newLine = i.NewPlugins.Count > 0
? $"New plugins available: {string.Join(", ", i.NewPlugins)}. See Available plugins on the Plugins tab."
: null;
string installed = i.InstalledVersion.Length > 0 ? i.InstalledVersion : "unknown";
if (!i.Configured)
return new UpdateCard(UpdateCardKind.NotConfigured, "Updates", "Updates aren't set up in this build.",
Array.Empty<string>(), false, null, false, null, false, null, "Updates aren't set up in this build.");
if (i.Download is { } d)
{
string title = d.Stage switch
{
DownloadStage.Downloading => $"Downloading {d.What}",
DownloadStage.Verified => $"{d.What}: verified",
DownloadStage.Unpacking => $"Unpacking {d.What}",
_ => $"Installing {d.What}",
};
// Installing is the last step (files moving into place): it always runs to the end.
bool cancel = i.CanCancel && d.Stage != DownloadStage.Installing;
return new UpdateCard(UpdateCardKind.Downloading, title, d.Detail, Array.Empty<string>(), false, null,
true, d.Percent, cancel, newLine, $"{title}: {d.Detail}");
}
if (i.Checking)
return new UpdateCard(UpdateCardKind.Checking, "Checking for updates…", $"RynthCore {installed}",
Array.Empty<string>(), false, null, false, null, false, newLine, "Checking for updates…");
if (i.Error != null)
{
string when = i.LastChecked is { } t ? $" Last good check: {FormatWhen(t)}." : "";
return new UpdateCard(UpdateCardKind.Error, "Couldn't check for updates", i.Error.TrimEnd('.', ' ') + "." + when,
Array.Empty<string>(), true, null, false, null, false, newLine, $"Update check failed: {i.Error}");
}
if (!i.HasCheck)
return new UpdateCard(UpdateCardKind.NotChecked, $"RynthCore {installed}", "Not checked for updates yet.",
Array.Empty<string>(), true, null, false, null, false, newLine, "Not checked yet.");
string checkedLine = i.LastChecked is { } lc ? $"Last checked {FormatWhen(lc)}." : "";
IReadOnlyList<string> whatsNew = WhatsNew(i.Changes, i.Notes);
if (i.CoreUpdateAvailable)
{
var detail = new List<string> { $"You have {installed}. The update installs once every game client is closed." };
if (i.ClientsRunning > 0)
detail.Add($"Close your {i.ClientsRunning} game client{(i.ClientsRunning == 1 ? "" : "s")} running RynthCore first.");
if (i.PendingPluginUpdates.Count > 0)
detail.Add($"Plugin updates ready too: {string.Join(", ", i.PendingPluginUpdates)}.");
if (checkedLine.Length > 0) detail.Add(checkedLine);
return new UpdateCard(UpdateCardKind.CoreUpdate, $"RynthCore {i.AvailableVersion} is available", string.Join(" ", detail),
whatsNew, true, UpdateCoreButton, false, null, false, newLine, $"Update available: RynthCore {i.AvailableVersion}");
}
if (i.PendingPluginUpdates.Count > 0)
{
string detail = $"{string.Join(", ", i.PendingPluginUpdates)}. Running bots keep their version until AC restarts.";
if (checkedLine.Length > 0) detail += " " + checkedLine;
return new UpdateCard(UpdateCardKind.PluginUpdates, "Plugin updates ready", detail,
whatsNew, true, UpdatePluginsButton, false, null, false, newLine, $"Plugin updates ready: {string.Join(", ", i.PendingPluginUpdates)}");
}
return new UpdateCard(UpdateCardKind.UpToDate, $"RynthCore {installed} - up to date", checkedLine,
Array.Empty<string>(), true, null, false, null, false, newLine, $"RynthCore {installed} - up to date.");
}
/// <summary>A few of the release's changes; the notes when the feed has no list (feeds before 2026.10.5).</summary>
public static IReadOnlyList<string> WhatsNew(IReadOnlyList<string> changes, string notes)
{
if (changes.Count > 0)
{
var list = changes.Take(MaxWhatsNew).ToList();
if (changes.Count > MaxWhatsNew) list.Add($"…and {changes.Count - MaxWhatsNew} more.");
return list;
}
if (string.IsNullOrWhiteSpace(notes)) return Array.Empty<string>();
string n = notes.Trim();
return new[] { n.Length > 300 ? n[..299].TrimEnd() + "…" : n };
}
/// <summary>"at 14:05" today, else "Oct 3 at 14:05".</summary>
public static string FormatWhen(DateTime local, DateTime? now = null)
{
DateTime today = (now ?? DateTime.Now).Date;
string time = local.ToString("HH:mm", CultureInfo.InvariantCulture);
return local.Date == today ? $"at {time}" : $"{local.ToString("MMM d", CultureInfo.InvariantCulture)} at {time}";
}
}

View file

@ -0,0 +1,292 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Opt-in, anonymous usage statistics ("Help improve RynthCore"). OFF unless the player turns it on.
///
/// When on, at most one small report a day goes to aelrynth.com (never to a game server), sent
/// after a successful update check. The report holds exactly:
/// - a random install ID (a GUID made when the player opts in, stored only in usage-stats.json,
/// tied to nothing else);
/// - the RynthCore version;
/// - the enabled plugins the update feed ships (RynthSuite), with their versions; other plugins
/// only as a count, never by name (a private plugin's name could identify its author);
/// - how many crash_*.dmp files the engine wrote since the last report (a count only);
/// - the Windows major version ("10" or "11").
/// Never: character, account or server names, file paths, or anything else identifying.
///
/// Turning it off deletes usage-stats.json (and with it the install ID) and cancels a report in
/// flight. Every failure is silent, and nothing here ever delays or fails the update check.
/// </summary>
internal sealed class UsageStats
{
public const string DefaultEndpoint = "https://aelrynth.com/rynth/ping";
/// <summary>Where the engine writes crash/hang minidumps (RynthCore.Engine CrashDump / LogPaths).</summary>
public const string DefaultDumpDirectory = @"C:\Games\RynthCore\Logs\dumps";
public const int Schema = 1;
private const int MaxCrashes = 1000;
private const int MaxPlugins = 32;
public sealed record PluginInfo(string Name, string Version);
private static readonly HttpClient Http = CreateHttp();
private static readonly Regex ReleaseVersion = new(@"^\d{4}\.\d{1,2}\.\d{1,2}(\.\d{1,4})?$", RegexOptions.CultureInvariant);
private static readonly Regex SafeName = new(@"^[A-Za-z0-9 ._-]{1,40}$", RegexOptions.CultureInvariant);
private readonly string _endpoint;
private readonly string _stateDir;
private readonly string _dumpDir;
private CancellationTokenSource _cts = new();
private int _sending;
public UsageStats(string endpoint = DefaultEndpoint, string? stateDir = null, string dumpDir = DefaultDumpDirectory)
{
_endpoint = endpoint;
_stateDir = stateDir ?? Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
_dumpDir = dumpDir;
}
public string StatePath => Path.Combine(_stateDir, "usage-stats.json");
// ── Opt in / out ──────────────────────────────────────────────────────────
/// <summary>Called when the player turns statistics on: makes the install ID if there is none.</summary>
public void OptIn(DateTime utcNow)
{
if (ReadState() != null) return;
// Crashes count from the moment of opting in, never from before.
WriteState(new State(Guid.NewGuid().ToString("D"), "", utcNow));
}
/// <summary>Called when the player turns statistics off: cancels a report in flight and deletes the ID.</summary>
public void OptOut()
{
try { _cts.Cancel(); } catch { }
_cts = new CancellationTokenSource();
try { File.Delete(StatePath); } catch { }
try { File.Delete(StatePath + ".tmp"); } catch { }
}
/// <summary>The install ID, or null when the player hasn't opted in (or it was deleted).</summary>
public string? InstallId => ReadState()?.InstallId;
// ── Report ────────────────────────────────────────────────────────────────
/// <summary>
/// Sends today's report if one hasn't gone out yet (UTC day). <paramref name="stillEnabled"/> is
/// asked again right before sending, so turning it off mid-way stops it. Returns true only
/// when a report was accepted. Never throws.
/// </summary>
public async Task<bool> MaybeSendAsync(Func<bool> stillEnabled, string coreVersion,
IReadOnlyList<PluginInfo> plugins, int otherPlugins, DateTime utcNow)
{
if (Interlocked.Exchange(ref _sending, 1) == 1) return false;
try
{
if (!stillEnabled()) return false;
State? state = ReadState();
if (state == null)
{
OptIn(utcNow); // enabled but the file is gone (deleted by hand): start a new ID
state = ReadState();
if (state == null) return false;
}
string today = utcNow.ToString("yyyy-MM-dd");
if (state.LastPingDay == today) return false;
int crashes = CountCrashDumps(_dumpDir, state.CrashesSinceUtc, utcNow);
string json = BuildPayload(state.InstallId, coreVersion, plugins, otherPlugins, crashes, WindowsMajor());
CancellationToken ct = _cts.Token;
if (!stillEnabled() || ct.IsCancellationRequested) return false;
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var resp = await Http.PostAsync(_endpoint, content, ct).ConfigureAwait(false);
if (!resp.IsSuccessStatusCode) return false;
// Opted out while the request was out: the file is gone, keep it gone.
if (!stillEnabled() || ct.IsCancellationRequested || ReadState()?.InstallId != state.InstallId) return true;
WriteState(state with { LastPingDay = today, CrashesSinceUtc = utcNow });
return true;
}
catch
{
return false;
}
finally
{
Interlocked.Exchange(ref _sending, 0);
}
}
/// <summary>The report that would go out now (for "Show what is sent"); nothing is sent or saved.</summary>
public string Preview(string coreVersion, IReadOnlyList<PluginInfo> plugins, int otherPlugins, DateTime utcNow)
{
State? state = ReadState();
string id = state?.InstallId ?? "(a random ID, made when you turn this on)";
int crashes = state == null ? 0 : CountCrashDumps(_dumpDir, state.CrashesSinceUtc, utcNow);
return BuildPayload(id, coreVersion, plugins, otherPlugins, crashes, WindowsMajor());
}
/// <summary>The report body, exactly as sent. Public for the launcher's "Show what is sent" and the tests.</summary>
public static string BuildPayload(string installId, string coreVersion, IReadOnlyList<PluginInfo> plugins,
int otherPlugins, int crashes, string windows)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("schema", Schema);
w.WriteString("install", installId);
w.WriteString("version", ShortVersion(coreVersion));
w.WriteString("windows", windows);
w.WriteNumber("crashes", Math.Clamp(crashes, 0, MaxCrashes));
w.WriteStartArray("plugins");
foreach (PluginInfo p in plugins
.Where(p => SafeName.IsMatch(p.Name))
.GroupBy(p => p.Name, StringComparer.OrdinalIgnoreCase).Select(g => g.First())
.OrderBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
.Take(MaxPlugins))
{
w.WriteStartObject();
w.WriteString("name", p.Name);
w.WriteString("version", ShortVersion(p.Version));
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteNumber("otherPlugins", Math.Clamp(otherPlugins, 0, 100));
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
/// <summary>
/// The enabled plugins to report: those whose file name the update feed ships (by the feed's name
/// for them, with the DLL's own version), and a count of every other enabled plugin.
/// </summary>
public static (List<PluginInfo> Known, int Other) DescribePlugins(IEnumerable<string> enabledPaths,
IReadOnlyDictionary<string, string> feedNameByFile)
{
var known = new List<PluginInfo>();
int other = 0;
foreach (string path in enabledPaths.Distinct(StringComparer.OrdinalIgnoreCase))
{
string file = Path.GetFileName(path);
if (feedNameByFile.TryGetValue(file, out string? name) && File.Exists(path))
{
string version;
try { version = FileVersionInfo.GetVersionInfo(path).ProductVersion ?? ""; }
catch { version = ""; }
known.Add(new PluginInfo(name, version));
}
else
{
other++;
}
}
return (known, other);
}
/// <summary>"2026.10.2.1" for a release build, "dev" for an unversioned build, else "unknown". Drops the commit.</summary>
public static string ShortVersion(string? productVersion)
{
string v = (productVersion ?? "").Trim();
int plus = v.IndexOf('+');
if (plus >= 0) v = v[..plus];
int space = v.IndexOf(' ');
if (space >= 0) v = v[..space];
if (v is "1.0.0" or "1.0.0.0" or "dev") return "dev";
return ReleaseVersion.IsMatch(v) ? v : "unknown";
}
/// <summary>"11" (build 22000 and up), "10", or "other".</summary>
public static string WindowsMajor()
{
Version os = Environment.OSVersion.Version;
if (!OperatingSystem.IsWindows()) return "other";
if (os.Major == 10) return os.Build >= 22000 ? "11" : "10";
return "other";
}
/// <summary>crash_*.dmp files written after <paramref name="sinceUtc"/> (hang dumps are not crashes).</summary>
public static int CountCrashDumps(string dir, DateTime sinceUtc, DateTime utcNow)
{
try
{
if (!Directory.Exists(dir)) return 0;
int n = 0;
foreach (string f in Directory.EnumerateFiles(dir, "crash_*.dmp"))
{
DateTime t = File.GetLastWriteTimeUtc(f);
if (t > sinceUtc && t <= utcNow.AddMinutes(5)) n++;
if (n >= MaxCrashes) break;
}
return n;
}
catch { return 0; }
}
// ── State file ────────────────────────────────────────────────────────────
private sealed record State(string InstallId, string LastPingDay, DateTime CrashesSinceUtc);
private State? ReadState()
{
try
{
if (!File.Exists(StatePath)) return null;
using var doc = JsonDocument.Parse(File.ReadAllText(StatePath));
JsonElement r = doc.RootElement;
string id = r.GetProperty("installId").GetString() ?? "";
if (!Guid.TryParseExact(id, "D", out _)) return null;
string last = r.TryGetProperty("lastPingDay", out JsonElement l) ? l.GetString() ?? "" : "";
DateTime since = r.TryGetProperty("crashesSinceUtc", out JsonElement s) && s.TryGetDateTime(out DateTime d)
? d.ToUniversalTime() : DateTime.UtcNow;
return new State(id, last, since);
}
catch { return null; }
}
private void WriteState(State s)
{
try
{
Directory.CreateDirectory(_stateDir);
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteString("about", "RynthCore usage statistics (opt-in). Deleted when you turn them off.");
w.WriteString("installId", s.InstallId);
w.WriteString("lastPingDay", s.LastPingDay);
w.WriteString("crashesSinceUtc", DateTime.SpecifyKind(s.CrashesSinceUtc, DateTimeKind.Utc));
w.WriteEndObject();
}
string tmp = StatePath + ".tmp";
File.WriteAllBytes(tmp, ms.ToArray());
File.Move(tmp, StatePath, overwrite: true);
}
catch { }
}
private static HttpClient CreateHttp()
{
// Short: a slow stats server must never hold anything up (and nothing awaits this anyway).
var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
http.DefaultRequestHeaders.UserAgent.ParseAdd("RynthCore-Launcher");
return http;
}
}

View file

@ -0,0 +1,121 @@
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace RynthCore.App.Avalonia;
/// <summary>
/// The one-time "Help improve RynthCore?" question and the "Show what is sent" window.
/// Plain words; "No thanks" is the safe answer (Escape and closing the window both mean no).
/// </summary>
internal static class UsageStatsDialog
{
private static readonly IBrush Back = new SolidColorBrush(Color.Parse("#132028"));
private static readonly IBrush Text = new SolidColorBrush(Color.Parse("#EAF0F4"));
private static readonly IBrush Muted = new SolidColorBrush(Color.Parse("#9AA8B3"));
private static readonly IBrush Accent = new SolidColorBrush(Color.Parse("#26C1A6"));
public const string WhatIsSent =
"Sent once a day, only if you turn it on: a random ID made just for this, the RynthCore version, " +
"which RynthSuite plugins you have enabled and their versions (other plugins only as a number), " +
"how many times RynthCore crashed since the last report (a number), and whether you run Windows 10 or 11.";
public const string NeverSent =
"Never sent: character, account or server names, file paths, or anything else about you or your game. " +
"It goes to aelrynth.com only, never to a game server.";
public const string HowToStop =
"Turning it off stops the reports at once and deletes the random ID from this PC.";
/// <summary>True when the player chose to turn statistics on.</summary>
public static async Task<bool> AskAsync(Window owner)
{
var dialog = NewWindow("Help improve RynthCore?", 560);
var on = new Button { Content = "Turn it on" };
var off = new Button { Content = "No thanks", IsCancel = true };
on.Click += (_, _) => dialog.Close(true);
off.Click += (_, _) => dialog.Close(false);
dialog.Content = Layout("Help improve RynthCore?",
new StackPanel
{
Spacing = 10,
Children =
{
Para("RynthCore can send a small anonymous report once a day, so we can see how many people use it, " +
"which versions and plugins are in use, and whether a new release crashes more than the last one.", Text),
Para(WhatIsSent, Muted),
Para(NeverSent, Muted),
Para("It stays off unless you turn it on. You can change your mind any time on the Plugins tab, " +
"under Usage statistics. " + HowToStop, Muted),
},
},
on, off);
bool? result = await dialog.ShowDialog<bool?>(owner);
return result == true;
}
/// <summary>Shows the report exactly as it would be sent now.</summary>
public static async Task ShowPayloadAsync(Window owner, string json, bool enabled)
{
var dialog = NewWindow("Usage statistics: what is sent", 620);
var body = new TextBox
{
Text = json,
IsReadOnly = true,
TextWrapping = TextWrapping.Wrap,
FontFamily = new FontFamily("Consolas, Cascadia Mono, monospace"),
FontSize = 12,
MaxHeight = 380,
Foreground = Text,
Background = new SolidColorBrush(Color.Parse("#0F161D")),
};
var close = new Button { Content = "Close", IsCancel = true, IsDefault = true };
close.Click += (_, _) => dialog.Close(null);
dialog.Content = Layout("Usage statistics: what is sent",
new StackPanel
{
Spacing = 8,
Children =
{
Para(enabled
? "This is today's report, exactly as it goes to aelrynth.com (at most once a day)."
: "Statistics are off, so nothing is sent. If you turned them on, this is what would go out.", Muted),
body,
},
},
close);
await dialog.ShowDialog<object?>(owner);
}
private static TextBlock Para(string text, IBrush brush) =>
new() { Text = text, TextWrapping = TextWrapping.Wrap, Foreground = brush };
private static Window NewWindow(string title, double width) => new()
{
Title = title,
Width = width,
SizeToContent = SizeToContent.Height,
CanResize = false,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Background = Back,
};
private static Control Layout(string title, Control body, params Control[] buttons)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right };
foreach (Control b in buttons) row.Children.Add(b);
return new StackPanel
{
Margin = new Thickness(18),
Spacing = 12,
Children =
{
new TextBlock { Text = title, FontSize = 16, FontWeight = FontWeight.SemiBold, Foreground = Accent },
body,
row,
},
};
}
}

View file

@ -27,6 +27,13 @@ internal sealed class AppSettings
/// with; the new one loads on the next AC start. Core updates always ask first.
public bool AutoUpdatePlugins { get; set; } = true;
/// "Help improve RynthCore": one anonymous usage report a day (see the launcher's
/// UsageStats.cs for exactly what is sent). OFF unless the player turns it on.
public bool UsageStatsEnabled { get; set; }
/// True once the launcher has explained usage statistics and asked (shown once).
public bool UsageStatsAsked { get; set; }
/// When true, the launcher kills any RynthCore-mode acclient.exe it
/// launched that hasn't reached IsLoggedIn within
/// <see cref="StuckClientTimeoutSeconds"/>. Catches stuck char-select,

View file

@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
@ -12,15 +14,22 @@ internal static class AppSettingsStore
WriteIndented = true,
Converters =
{
// Before the general enum converter: InjectionMode is written so that every
// launcher can read it ("Decal + RynthCore" lives in decal-accounts.json).
new SharedInjectionModeConverter(),
new JsonStringEnumConverter()
}
};
private static string SettingsDirectory =>
/// <summary>Tests only (tools\LauncherSettingsTests): a folder used instead of %APPDATA%\RynthCore.</summary>
internal static string? DirectoryOverride { get; set; }
private static string SettingsDirectory => DirectoryOverride ??
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
private static string SettingsPath => Path.Combine(SettingsDirectory, "appsettings.json");
private static string BackupPath => SettingsPath + ".bak";
private static string DecalAccountsPath => DecalAccountModes.PathIn(SettingsDirectory);
/// <summary>
/// Set when the last Load() hit a corrupt/unreadable file (quarantined it,
@ -30,10 +39,22 @@ internal static class AppSettingsStore
/// </summary>
public static string? LastLoadDiagnostic { get; private set; }
/// <summary>
/// Set when the last Load() moved "Decal + RynthCore" accounts out of appsettings.json
/// into decal-accounts.json (a file written by a pre-release Decal bridge build), or found
/// decal-accounts.json unreadable. Null otherwise.
/// </summary>
public static string? LastMigrationNote { get; private set; }
public static AppSettings Load()
{
LastLoadDiagnostic = null;
LastMigrationNote = null;
return ApplyDecalAccounts(LoadShared());
}
private static AppSettings LoadShared()
{
if (!File.Exists(SettingsPath))
return new AppSettings();
@ -85,13 +106,56 @@ internal static class AppSettingsStore
}
}
/// <summary>
/// Puts back the "Decal + RynthCore" accounts listed in decal-accounts.json (those that
/// appsettings.json still lists as RynthCore). An appsettings.json that itself says
/// "DecalBridge" (written by a pre-release bridge build) is rewritten at once, .bak
/// included, so no launcher finds that value there again.
/// </summary>
private static AppSettings ApplyDecalAccounts(AppSettings settings)
{
List<LaunchAccountProfile> accounts = settings.AccountProfiles ?? new List<LaunchAccountProfile>();
int legacy = accounts.Count(a => a.InjectionMode == InjectionMode.DecalBridge);
HashSet<string> ids = DecalAccountModes.ReadIds(DecalAccountsPath, out string? error);
if (error != null)
LastMigrationNote = error;
foreach (LaunchAccountProfile account in accounts)
if (DecalAccountModes.IsDecalBridge(ids, account.Id, account.InjectionMode))
account.InjectionMode = InjectionMode.DecalBridge;
if (legacy > 0)
{
try
{
Save(settings);
File.Copy(SettingsPath, BackupPath, overwrite: true);
LastMigrationNote = $"Moved {legacy} \"Decal + RynthCore\" account(s) from appsettings.json to " +
$"{DecalAccountModes.FileName}, so older launchers can still read appsettings.json.";
}
catch (Exception ex)
{
LastMigrationNote = $"Could not move \"Decal + RynthCore\" accounts to {DecalAccountModes.FileName} " +
$"({ex.GetType().Name}: {ex.Message}); the next save retries.";
}
}
return settings;
}
public static void Save(AppSettings settings)
{
// "Decal + RynthCore" accounts go to decal-accounts.json first; appsettings.json
// lists them as RynthCore (SharedInjectionModeConverter).
Directory.CreateDirectory(SettingsDirectory);
DecalAccountModes.WriteIds(DecalAccountsPath,
(settings.AccountProfiles ?? new List<LaunchAccountProfile>())
.Where(a => a.InjectionMode == InjectionMode.DecalBridge)
.Select(a => a.Id));
// Atomic write: serialize to a temp file, then swap it in. A crash or
// power cut mid-write can no longer truncate the live file (which holds
// every server/account profile and is rewritten constantly); the swap
// also maintains a .bak Load() can recover from.
Directory.CreateDirectory(SettingsDirectory);
string tmp = SettingsPath + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(settings, JsonOptions));
if (File.Exists(SettingsPath))
@ -99,4 +163,32 @@ internal static class AppSettingsStore
else
File.Move(tmp, SettingsPath);
}
/// <summary>
/// InjectionMode in appsettings.json. Writes only names every launcher knows: DecalBridge is
/// written as <see cref="DecalAccountModes.SharedMode"/> (decal-accounts.json holds the real
/// choice). Reads names and numbers; a name or number this build doesn't know reads as RynthCore
/// instead of making the whole file unreadable.
/// </summary>
private sealed class SharedInjectionModeConverter : JsonConverter<InjectionMode>
{
public override InjectionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt32(out int number))
return Enum.IsDefined((InjectionMode)number) ? (InjectionMode)number : InjectionMode.RynthCore;
if (reader.TokenType == JsonTokenType.String)
{
return Enum.TryParse(reader.GetString(), ignoreCase: true, out InjectionMode mode) && Enum.IsDefined(mode)
? mode
: InjectionMode.RynthCore;
}
throw new JsonException($"InjectionMode: unexpected {reader.TokenType}.");
}
public override void Write(Utf8JsonWriter writer, InjectionMode value, JsonSerializerOptions options)
{
InjectionMode shared = value == InjectionMode.DecalBridge ? DecalAccountModes.SharedMode : value;
writer.WriteStringValue(shared.ToString());
}
}
}

View file

@ -46,6 +46,13 @@ internal static class CharacterCacheStore
List<string> serverCharacters = ReadCharacterFile(GetServerScopedPath(safeServer, safeAccount));
if (serverCharacters.Count > 0)
return serverCharacters;
// The same account name can exist on several servers. The legacy
// account-only file predates server scoping, so it is only trusted
// while no server-scoped file exists for this account at all;
// otherwise it would hand one server's characters to another.
if (HasAnyServerScopedFile(safeAccount))
return [];
}
return ReadCharacterFile(GetAccountScopedPath(safeAccount));
@ -84,7 +91,11 @@ internal static class CharacterCacheStore
if (string.IsNullOrWhiteSpace(accountName) || string.IsNullOrWhiteSpace(characterName))
return;
List<string> characters = Read(accountName, serverName);
// With a server, seed only from that server's own file so a legacy
// account-only list cannot be merged into the wrong server.
List<string> characters = string.IsNullOrWhiteSpace(serverName)
? Read(accountName, serverName)
: ReadStrict(accountName, serverName);
if (!characters.Any(existing => IsSameCharacter(existing, characterName)))
characters.Add(characterName);
@ -96,27 +107,34 @@ internal static class CharacterCacheStore
private static bool IsSameCharacter(string a, string b) =>
string.Equals(a.Trim().TrimStart('+'), b.Trim().TrimStart('+'), StringComparison.OrdinalIgnoreCase);
public static void DeleteForAccount(string accountName)
/// Deletes the character cache for one (account, server) pair. Other servers'
/// files for the same account name are left alone. The legacy account-only
/// file is removed only when <paramref name="includeLegacy"/> is set (the
/// caller knows whether another profile still uses this account name).
public static void DeleteForAccount(string accountName, string serverName, bool includeLegacy)
{
if (string.IsNullOrWhiteSpace(accountName))
return;
try
{
string rootDirectory = GetRootDirectory();
if (!Directory.Exists(rootDirectory))
return;
string safeAccount = SanitizeFileName(accountName);
foreach (string file in Directory.GetFiles(rootDirectory, $"characters_*_{safeAccount}.json"))
if (!string.IsNullOrWhiteSpace(serverName))
{
try { File.Delete(file); } catch { }
string serverScopedPath = GetServerScopedPath(SanitizeFileName(serverName), safeAccount);
if (File.Exists(serverScopedPath))
{
try { File.Delete(serverScopedPath); } catch { }
}
}
string accountScopedPath = GetAccountScopedPath(safeAccount);
if (File.Exists(accountScopedPath))
if (includeLegacy)
{
try { File.Delete(accountScopedPath); } catch { }
string accountScopedPath = GetAccountScopedPath(safeAccount);
if (File.Exists(accountScopedPath))
{
try { File.Delete(accountScopedPath); } catch { }
}
}
}
catch
@ -124,6 +142,20 @@ internal static class CharacterCacheStore
}
}
private static bool HasAnyServerScopedFile(string safeAccountName)
{
try
{
string rootDirectory = GetRootDirectory();
return Directory.Exists(rootDirectory) &&
Directory.EnumerateFiles(rootDirectory, $"characters_*_{safeAccountName}.json").Any();
}
catch
{
return false;
}
}
private static string GetRootDirectory() =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");

View file

@ -0,0 +1,113 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace RynthCore.App;
/// <summary>
/// Which accounts run as "Decal + RynthCore" (<see cref="InjectionMode.DecalBridge"/>), kept in
/// <c>decal-accounts.json</c> next to <c>%APPDATA%\RynthCore\appsettings.json</c> and keyed by
/// account profile id.
///
/// Why a file of its own: every launcher of this Windows user shares appsettings.json, and a
/// launcher released before the Decal bridge has no "DecalBridge" value in its InjectionMode.
/// Its AppSettingsStore takes a file with that value for corrupt, quarantines it and falls back
/// to the .bak, or to empty defaults (and then saves those). So appsettings.json always lists a
/// "Decal + RynthCore" account as <see cref="SharedMode"/> (RynthCore), and this file says which
/// of those are really "Decal + RynthCore".
///
/// An entry only counts while appsettings.json still says RynthCore for that account: an older
/// launcher that switched the account to Decal (or that deleted it) wins, and the next save of a
/// newer launcher drops the stale entry. Shared with the injector (LaunchCommand).
/// </summary>
internal static class DecalAccountModes
{
public const string FileName = "decal-accounts.json";
/// <summary>What appsettings.json says for a "Decal + RynthCore" account.</summary>
public const InjectionMode SharedMode = InjectionMode.RynthCore;
private const int SchemaVersion = 1;
private const string Note =
"Accounts the RynthCore launcher runs as \"Decal + RynthCore\" (experimental). " +
"appsettings.json lists them as RynthCore, so launchers without that mode can still read it. " +
"Delete this file to set them all back to RynthCore.";
private sealed class FileModel
{
public int Version { get; set; } = SchemaVersion;
public string Note { get; set; } = DecalAccountModes.Note;
public List<string> DecalBridgeAccountIds { get; set; } = new();
}
private static readonly JsonSerializerOptions WriteOptions = new() { WriteIndented = true };
public static string PathIn(string settingsDirectory) => Path.Combine(settingsDirectory, FileName);
/// <summary>
/// The account ids listed in <paramref name="path"/>. An absent file is an empty set; an
/// unreadable one too, with the reason in <paramref name="error"/> (the accounts then run
/// as appsettings.json says, which is RynthCore).
/// </summary>
public static HashSet<string> ReadIds(string path, out string? error)
{
error = null;
var ids = new HashSet<string>(StringComparer.Ordinal);
try
{
if (!File.Exists(path))
return ids;
FileModel? model = JsonSerializer.Deserialize<FileModel>(File.ReadAllText(path));
foreach (string id in model?.DecalBridgeAccountIds ?? new List<string>())
if (!string.IsNullOrWhiteSpace(id))
ids.Add(id);
}
catch (Exception ex)
{
error = $"{FileName} could not be read ({ex.GetType().Name}: {ex.Message}); " +
"its accounts run as RynthCore until the mode is picked again.";
ids.Clear();
}
return ids;
}
/// <summary>
/// True when an account that appsettings.json lists with <paramref name="sharedMode"/> is a
/// "Decal + RynthCore" account: it is in <paramref name="ids"/> and still says RynthCore.
/// </summary>
public static bool IsDecalBridge(IReadOnlySet<string> ids, string? accountId, InjectionMode sharedMode) =>
sharedMode == SharedMode && !string.IsNullOrEmpty(accountId) && ids.Contains(accountId);
/// <summary>
/// Records <paramref name="ids"/> as the "Decal + RynthCore" accounts. Writes only when the
/// list changed; with no accounts left, the file is removed. Atomic (temp file + swap).
/// </summary>
public static void WriteIds(string path, IEnumerable<string> ids)
{
List<string> sorted = ids.Where(id => !string.IsNullOrWhiteSpace(id))
.Distinct(StringComparer.Ordinal)
.OrderBy(id => id, StringComparer.Ordinal)
.ToList();
if (sorted.Count == 0)
{
if (File.Exists(path))
File.Delete(path);
return;
}
if (File.Exists(path))
{
HashSet<string> current = ReadIds(path, out string? error);
if (error == null && current.SetEquals(sorted))
return;
}
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(new FileModel { DecalBridgeAccountIds = sorted }, WriteOptions));
File.Move(tmp, path, overwrite: true);
}
}

View file

@ -0,0 +1,495 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
namespace RynthCore.App;
/// <summary>Registry roots the Decal check reads. "32" = the 32-bit view (WOW6432Node on 64-bit Windows).</summary>
internal enum RegRoot { Machine32, Machine64, User32, User64 }
/// <summary>A read-only registry key (real one, or a fake in tools\DecalBridgeCheckTests).</summary>
internal interface IRegKey : IDisposable
{
object? GetValue(string name);
string[] GetSubKeyNames();
string[] GetValueNames();
}
/// <summary>
/// Everything <see cref="DecalBridgeCheck"/> reads from the machine. The real one is
/// <see cref="RealDecalCheckHost"/>; the offline tests use a fake.
/// </summary>
internal interface IDecalCheckHost
{
bool Is64BitOs { get; }
/// <summary>The launcher (or injector) runs elevated. A client it starts is elevated too.</summary>
bool LauncherElevated { get; }
/// <summary>UAC registry virtualization is on for this process (as it is for a non-elevated AC).</summary>
bool LauncherVirtualized { get; }
/// <summary>The real registry: no UAC virtualization (HKLM is HKLM, the VirtualStore is its own key).</summary>
IRegKey? OpenReal(RegRoot root, string subKey);
/// <summary>
/// HKLM (32-bit view) as THIS process sees it, virtualized when the process is. Only the
/// bridge's own entry is asked for (the real host snapshots it before virtualization is
/// switched off for the rest of the check).
/// </summary>
IRegKey? OpenOwnViewMachine32(string subKey);
bool FileExists(string path);
/// <summary>The file carries a Zone.Identifier stream ("downloaded from the internet").</summary>
bool HasZoneIdentifier(string path);
Version? AssemblyVersionOf(string path);
Version? ReferenceVersionOf(string assemblyPath, string referenceName);
/// <summary>requestedExecutionLevel from the exe's embedded manifest or its .manifest file, null if none.</summary>
string? ExecutionLevelOf(string exePath);
string? ReadTextFile(string path);
}
/// <summary>
/// "Check Decal bridge": can a Decal + RynthCore client started now load the RynthCore Decal
/// bridge? (docs/DECAL_BRIDGE_PLAN.md, "Where Decal reads its filters").
///
/// Decal lists network filters from HKLM\SOFTWARE\Decal\NetworkFilters (decalnet.dll), read
/// by the 32-bit client through the 32-bit view (WOW6432Node), and Decal.Adapter reads each
/// .NET filter's Path/Assembly/Object from SOFTWARE\Decal\NetworkFilters\{id}. Which key that
/// really is depends on the CLIENT's token:
/// - a non-elevated acclient.exe (no manifest, UAC on) is virtualized: when the per-user copy
/// HKCU\Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\NetworkFilters
/// exists, Decal reads ONLY that copy; otherwise the real HKLM key;
/// - an elevated client (the launcher runs as administrator, acclient.exe set to "Run as
/// administrator", UAC off), or one with a manifest, or with virtualization off by policy,
/// is not virtualized and reads the real HKLM key - a per-user registration is invisible.
/// The check predicts that, reads our entry from where Decal will read it, and where it can
/// (the launcher's token is virtualized exactly when the client's will be) reads it again
/// through the launcher's own view, which is the client's view.
/// </summary>
internal static class DecalBridgeCheck
{
public enum Level { Ok, Info, Warn, Fail }
public sealed record Line(Level Level, string Text);
public sealed class Result
{
public List<Line> Lines { get; } = new();
public bool DecalInstalled { get; set; }
public string? DecalVersion { get; set; }
public bool ClientVirtualized { get; set; }
public string ClientReason { get; set; } = string.Empty;
/// <summary>Where Decal reads its filter list on this machine, for people.</summary>
public string FiltersReadFrom { get; set; } = string.Empty;
public bool ReadsPerUserCopy { get; set; }
/// <summary>Our entry is where Decal reads, enabled, with the DLL in place.</summary>
public bool BridgeVisibleToDecal { get; set; }
/// <summary>Not registered where Decal reads, and that place is HKLM: needs administrator rights once.</summary>
public bool NeedsMachineWideRegistration { get; set; }
public bool Blocking => Lines.Any(l => l.Level == Level.Fail);
public void Add(Level level, string text) => Lines.Add(new Line(level, text));
public string Summary => Blocking
? "Decal bridge check: FAILED - " + string.Join(" ", Lines.Where(l => l.Level == Level.Fail).Select(l => l.Text))
: "Decal bridge check: OK - " + FiltersReadFrom + (DecalVersion != null ? $"; Decal {DecalVersion}" : "");
public string ToReport()
{
var sb = new StringBuilder();
foreach (Line l in Lines)
{
string tag = l.Level switch { Level.Ok => "OK ", Level.Info => " ", Level.Warn => "WARN", _ => "FAIL" };
sb.Append(tag).Append(" ").AppendLine(l.Text);
}
sb.AppendLine();
sb.AppendLine(Blocking
? "Result: a Decal + RynthCore client started now would NOT load the bridge (no RynthCore overlay, then a crash). Fix the FAIL lines first."
: "Result: a Decal + RynthCore client started now will load the bridge.");
return sb.ToString();
}
}
/// <summary>Decal's .NET surrogate CLSID (Decal.Adapter.Surrogate).</summary>
public const string SurrogateClsid = "{71A69713-6593-47EC-0002-0000000DECA1}";
/// <summary>The bridge targets .NET Framework 4.8 (Release key 528040).</summary>
private const int Net48Release = 528040;
public static string VirtualStoreDecalPath(bool is64BitOs, string group) => is64BitOs
? @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\" + group
: @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\Decal\" + group;
public static string MachineDecalPath(string group) => @"SOFTWARE\Decal\" + group;
/// <summary>
/// Will a client started by this launcher get UAC registry virtualization? False when it
/// runs elevated or Windows doesn't virtualize it (reason says which).
/// </summary>
public static bool PredictClientVirtualized(IDecalCheckHost host, string? acClientPath, out string reason)
{
int? lua = DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableLUA");
if (lua == 0)
{
reason = "UAC is turned off on this PC (EnableLUA=0), so Windows gives every program the real machine registry";
return false;
}
int? virt = DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableVirtualization");
if (virt == 0)
{
reason = "UAC registry virtualization is turned off by policy (EnableVirtualization=0)";
return false;
}
if (host.LauncherElevated)
{
reason = "RynthCore runs as administrator, so the AC client it starts does too, and Windows gives it the real machine registry";
return false;
}
if (!string.IsNullOrEmpty(acClientPath))
{
string? level = host.ExecutionLevelOf(acClientPath);
if (level != null)
{
reason = $"{Path.GetFileName(acClientPath)} has a manifest (requestedExecutionLevel={level}), so Windows doesn't virtualize it";
return false;
}
string? layer = RunAsAdminLayer(host, acClientPath);
if (layer != null)
{
reason = $"{acClientPath} is set to \"Run this program as an administrator\" ({layer})";
return false;
}
}
reason = "AC runs without administrator rights, so Windows virtualizes its registry";
return true;
}
/// <summary>
/// Where a client (virtualized or not) reads SOFTWARE\Decal\&lt;group&gt;: the per-user
/// VirtualStore copy when it is virtualized and the copy exists, else the real HKLM key.
/// </summary>
public static (RegRoot Root, string Path, bool PerUser) WhereDecalReads(IDecalCheckHost host, bool clientVirtualized, string group)
{
if (clientVirtualized)
{
string vs = VirtualStoreDecalPath(host.Is64BitOs, group);
using IRegKey? k = host.OpenReal(RegRoot.User64, vs);
if (k != null)
return (RegRoot.User64, vs, true);
}
return (RegRoot.Machine32, MachineDecalPath(group), false);
}
/// <summary>
/// What the installer (and every update) writes, so a client finds the bridge whatever
/// its rights (installer\RynthCore.iss: <see cref="DecalBridgeRegistration.RegisterMachineWide"/>
/// elevated, <see cref="DecalBridgeRegistration.InstallPerUser"/> as the installing user):
/// - Machine: always (when Decal is installed). Elevated and unvirtualized clients read
/// only HKLM; a virtualized client without a per-user copy reads HKLM too.
/// - PerUser: only into a per-user copy that ALREADY exists. A virtualized client then
/// reads that copy and nothing else, so the HKLM entry is hidden from it. Creating a
/// copy that doesn't exist would be harmful: it would hide every HKLM filter added later
/// (a Decal plugin installed for all users) from this user's non-elevated clients.
/// </summary>
public static (bool Machine, bool PerUser) PlanInstall(IDecalCheckHost host)
{
bool decal = StringOf(host, RegRoot.Machine32, MachineDecalPath("Agent"), "AgentPath") != null;
if (!decal) return (false, false);
using IRegKey? copy = host.OpenReal(RegRoot.User64, VirtualStoreDecalPath(host.Is64BitOs, "NetworkFilters"));
return (true, copy != null);
}
public static string Describe(bool is64BitOs, RegRoot root, string path) => root switch
{
RegRoot.Machine32 => is64BitOs ? @"HKLM\SOFTWARE\WOW6432Node\" + path.Substring("SOFTWARE\\".Length) : @"HKLM\" + path,
RegRoot.Machine64 => @"HKLM\" + path,
_ => @"HKCU\" + path,
};
/// <summary>Runs every check. Reads only; changes nothing.</summary>
public static Result Run(IDecalCheckHost host, string bridgeDirectory, string? acClientPath, string? engineJsonPath)
{
var r = new Result();
string dir = bridgeDirectory.TrimEnd('\\');
// 1. Decal and its version.
string? agentPath = StringOf(host, RegRoot.Machine32, MachineDecalPath("Agent"), "AgentPath");
r.DecalInstalled = agentPath != null && host.FileExists(Path.Combine(agentPath, "Inject.dll"));
if (!r.DecalInstalled)
{
r.Add(Level.Fail, @"Decal is not installed (HKLM\SOFTWARE\Decal\Agent AgentPath\Inject.dll not found).");
return r;
}
string adapter = Path.Combine(agentPath!, "Decal.Adapter.dll");
Version? installed = host.FileExists(adapter) ? host.AssemblyVersionOf(adapter) : null;
string bridgeDll = Path.Combine(dir, DecalBridgeRegistration.AssemblyFile);
bool bridgePresent = host.FileExists(bridgeDll);
Version? needed = bridgePresent ? host.ReferenceVersionOf(bridgeDll, "Decal.Adapter") : null;
r.DecalVersion = installed?.ToString();
if (installed == null)
r.Add(Level.Fail, $"Decal.Adapter.dll is missing or unreadable in {agentPath} - reinstall Decal.");
else if (needed != null && installed < needed)
r.Add(Level.Fail, $"Decal {installed} is older than the {needed} the bridge is built for - update Decal (decaldev.com), then check again.");
else
r.Add(Level.Ok, $"Decal {installed} in {agentPath}" + (needed != null ? $" (bridge built for {needed})." : "."));
// 2. The bridge DLL itself.
if (!bridgePresent)
r.Add(Level.Fail, $"{DecalBridgeRegistration.AssemblyFile} is missing from {dir} - reinstall RynthCore.");
else if (host.HasZoneIdentifier(bridgeDll))
r.Add(Level.Warn, $"{bridgeDll} is marked as downloaded from the internet; .NET may refuse to load it. Repair removes the mark (or: right-click > Properties > Unblock).");
else
r.Add(Level.Ok, $"Bridge DLL present: {bridgeDll}.");
// 3. How the client will see the registry.
r.ClientVirtualized = PredictClientVirtualized(host, acClientPath, out string why);
r.ClientReason = why;
r.Add(Level.Info, "AC client: " + why + ".");
// 4. Where Decal reads its filters, and our entry there.
var where = WhereDecalReads(host, r.ClientVirtualized, "NetworkFilters");
r.ReadsPerUserCopy = where.PerUser;
string whereText = Describe(host.Is64BitOs, where.Root, where.Path);
r.FiltersReadFrom = "Decal reads its filters from " + whereText + (where.PerUser ? " (your Windows user's copy)" : "");
r.Add(Level.Info, r.FiltersReadFrom + ".");
string? entryProblem = EntryProblem(host, where.Root, where.Path + "\\" + DecalBridgeRegistration.FilterGuid, out string? registeredPath);
if (entryProblem == null)
{
r.BridgeVisibleToDecal = true;
r.Add(Level.Ok, $"RynthCore Decal Bridge is registered there and enabled ({registeredPath}).");
}
else
{
r.NeedsMachineWideRegistration = !where.PerUser;
r.Add(Level.Fail, $"Decal will not load the bridge: {entryProblem} in {whereText}." +
(where.PerUser
? " Repair (or a Decal + RynthCore launch) registers it for your Windows user."
: " That key is shared by all users: Repair adds it there once and Windows asks for administrator permission."));
}
// Other places, for people (a registration Decal won't read explains a "registered but nothing happens").
if (where.PerUser)
{
using IRegKey? m = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid);
if (m != null && IsOurs(m) && entryProblem != null)
r.Add(Level.Info, "(A machine-wide entry exists, but your per-user copy hides it from AC.)");
}
else
{
using IRegKey? u = host.OpenReal(RegRoot.User64, VirtualStoreDecalPath(host.Is64BitOs, "NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid);
if (u != null && IsOurs(u) && entryProblem != null)
r.Add(Level.Info, "(A per-user registration exists, but this AC client doesn't read it: " + why + ".)");
}
// 5. The same entry through this process's own view, when that view IS the client's.
bool sameView = host.LauncherVirtualized == r.ClientVirtualized;
if (sameView)
{
using IRegKey? live = host.OpenOwnViewMachine32(MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid);
bool liveOk = live != null && IsOurs(live) && IsEnabled(live);
if (liveOk == r.BridgeVisibleToDecal)
r.Add(Level.Ok, $"Read back as AC will see it: {(liveOk ? "bridge listed and enabled" : "bridge not listed")}.");
else
r.Add(liveOk ? Level.Warn : Level.Fail,
$"Read back as AC will see it: {(liveOk ? "bridge listed" : "bridge NOT listed")}, which disagrees with {whereText}. Windows serves this PC's registry differently than expected.");
}
else
{
r.Add(Level.Info, "Not read back live: AC will run with other rights than this launcher.");
}
// 6. Hidden machine filters (a per-user list hides every HKLM entry it lacks).
if (where.PerUser)
{
List<string> hidden = HiddenMachineFilters(host, where.Path);
if (hidden.Count > 0)
r.Add(Level.Warn, "Hidden from AC by your per-user filter list (in HKLM, not in the copy): " + string.Join(", ", hidden) +
". If 'World Object Filter' is among them, VTank won't start.");
}
// 7. Decal's .NET surrogate: Decal must be able to create it, and must not have it disabled.
var surWhere = WhereDecalReads(host, r.ClientVirtualized, "Surrogates");
using (IRegKey? s = host.OpenReal(surWhere.Root, surWhere.Path + "\\" + SurrogateClsid))
{
if (s == null)
r.Add(Level.Fail, $"Decal's .NET surrogate is not listed in {Describe(host.Is64BitOs, surWhere.Root, surWhere.Path)} - no .NET filter or plugin can load. Reinstall Decal.");
else if (!IsEnabled(s))
r.Add(Level.Fail, "Decal's .NET surrogate (Decal.Adapter Surrogate) is disabled in Decal - enable it in Decal's agent (or reinstall Decal).");
else
r.Add(Level.Ok, "Decal's .NET surrogate is enabled.");
}
string? comProblem = SurrogateComProblem(host, clientElevated: !r.ClientVirtualized && IsClientElevated(host, acClientPath), out string comWhere);
if (comProblem != null)
r.Add(Level.Fail, comProblem);
else
r.Add(Level.Ok, $"Decal.Adapter's COM class resolves ({comWhere}). The bridge itself needs no COM registration: Decal.Adapter loads it from Path\\Assembly.");
// 8. .NET Framework 4.8.
int? release = DwordOf(host, RegRoot.Machine32, @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", "Release");
if (release == null)
r.Add(Level.Fail, ".NET Framework 4 is not installed (Decal needs it).");
else if (release < Net48Release)
r.Add(Level.Warn, $".NET Framework older than 4.8 (Release {release}); the bridge targets 4.8 - install .NET Framework 4.8.");
// 9. engine.json settings that turn bridge mode off.
if (engineJsonPath != null)
{
(string? mode, bool? inGame) = ReadEngineSettings(host, engineJsonPath);
if (mode != null && (mode.Equals("Off", StringComparison.OrdinalIgnoreCase) || mode.Equals("false", StringComparison.OrdinalIgnoreCase)))
r.Add(Level.Fail, $"engine.json has \"DecalBridge\": {mode} - bridge mode is off for every client. Remove that line ({engineJsonPath}).");
if (inGame == false)
r.Add(Level.Warn, "engine.json has \"DecalInGameImGui\": false - no RynthCore overlay under Decal (by choice).");
}
return r;
}
// ── pieces (internal for the tests) ─────────────────────────────────────
internal static string? EntryProblem(IDecalCheckHost host, RegRoot root, string entryPath, out string? registeredPath)
{
registeredPath = null;
using IRegKey? k = host.OpenReal(root, entryPath);
if (k == null) return "the RynthCore Decal Bridge is not registered";
if (!IsOurs(k)) return "another filter uses the bridge's id";
registeredPath = k.GetValue("Path") as string;
if (!IsEnabled(k)) return "the RynthCore Decal Bridge is registered but disabled";
if (!string.Equals(k.GetValue("Surrogate") as string, SurrogateClsid, StringComparison.OrdinalIgnoreCase))
return "the bridge entry has the wrong Surrogate";
string? file = k.GetValue("Assembly") as string;
if (string.IsNullOrEmpty(registeredPath) || string.IsNullOrEmpty(file))
return "the bridge entry has no Path/Assembly";
if (!host.FileExists(Path.Combine(registeredPath, file)))
return $"the registered bridge DLL is missing ({Path.Combine(registeredPath, file)})";
return null;
}
internal static List<string> HiddenMachineFilters(IDecalCheckHost host, string perUserPath)
{
var hidden = new List<string>();
using IRegKey? machine = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters"));
using IRegKey? user = host.OpenReal(RegRoot.User64, perUserPath);
if (machine == null || user == null) return hidden;
var seen = new HashSet<string>(user.GetSubKeyNames(), StringComparer.OrdinalIgnoreCase);
foreach (string name in machine.GetSubKeyNames())
{
if (seen.Contains(name) || string.Equals(name, DecalBridgeRegistration.FilterGuid, StringComparison.OrdinalIgnoreCase))
continue;
using IRegKey? k = host.OpenReal(RegRoot.Machine32, MachineDecalPath("NetworkFilters") + "\\" + name);
hidden.Add(k?.GetValue("") is string friendly && friendly.Length > 0 ? friendly : name);
}
return hidden;
}
/// <summary>
/// Decal.Adapter's surrogate is an mscoree COM class. A non-elevated client resolves it
/// per-user first (HKCU\Software\Classes), then machine-wide; an elevated one ignores
/// per-user COM registrations.
/// </summary>
internal static string? SurrogateComProblem(IDecalCheckHost host, bool clientElevated, out string where)
{
where = string.Empty;
string sub = @"\CLSID\" + SurrogateClsid + @"\InprocServer32";
var candidates = new List<(RegRoot Root, string Path, string Label)>();
if (!clientElevated) candidates.Add((RegRoot.User32, @"Software\Classes" + sub, "per-user"));
candidates.Add((RegRoot.Machine32, @"SOFTWARE\Classes" + sub, "machine-wide"));
foreach (var c in candidates)
{
using IRegKey? k = host.OpenReal(c.Root, c.Path);
if (k == null) continue;
where = c.Label;
string server = k.GetValue("") as string ?? string.Empty;
if (!server.EndsWith("mscoree.dll", StringComparison.OrdinalIgnoreCase))
return $"Decal.Adapter's COM class ({c.Label}) points at '{server}', not mscoree.dll - reinstall Decal.";
if (string.IsNullOrEmpty(k.GetValue("Assembly") as string))
return $"Decal.Adapter's COM class ({c.Label}) names no assembly - reinstall Decal.";
if (k.GetValue("CodeBase") is string cb && cb.Length > 0)
{
string file = cb.StartsWith("file:", StringComparison.OrdinalIgnoreCase) ? cb.Substring(5).TrimStart('/') : cb;
if (!host.FileExists(file.Replace('/', '\\')))
return $"Decal.Adapter's COM class ({c.Label}) points at a missing file ({file}) - reinstall Decal.";
}
return null;
}
bool perUserOnly = clientElevated && OpenExists(host, RegRoot.User32, @"Software\Classes" + sub);
return perUserOnly
? "Decal.Adapter's COM class is registered only for your Windows user, and an AC running as administrator ignores per-user COM classes - reinstall Decal for all users."
: "Decal.Adapter's COM class (Decal.Adapter.Surrogate) is not registered - reinstall Decal.";
}
private static bool IsClientElevated(IDecalCheckHost host, string? acClientPath)
{
if (host.LauncherElevated) return true;
if (string.IsNullOrEmpty(acClientPath)) return false;
string? level = host.ExecutionLevelOf(acClientPath);
if (level != null && (level.Equals("requireAdministrator", StringComparison.OrdinalIgnoreCase) || level.Equals("highestAvailable", StringComparison.OrdinalIgnoreCase)))
return true;
if (RunAsAdminLayer(host, acClientPath) != null) return true;
// UAC off: an administrator's programs run with the full token.
return DwordOf(host, RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableLUA") == 0;
}
private static string? RunAsAdminLayer(IDecalCheckHost host, string exePath)
{
foreach ((RegRoot root, string key) in new[]
{
(RegRoot.User64, @"Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"),
(RegRoot.Machine64, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"),
})
{
using IRegKey? k = host.OpenReal(root, key);
if (k == null) continue;
foreach (string name in k.GetValueNames())
{
if (!string.Equals(name, exePath, StringComparison.OrdinalIgnoreCase)) continue;
string flags = k.GetValue(name) as string ?? string.Empty;
string[] parts = flags.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Any(p => p.Equals("RUNASADMIN", StringComparison.OrdinalIgnoreCase) || p.Equals("RUNASHIGHEST", StringComparison.OrdinalIgnoreCase)))
return (root == RegRoot.User64 ? "your compatibility settings" : "compatibility settings for all users") + ": " + flags.Trim();
}
}
return null;
}
private static (string? Mode, bool? InGame) ReadEngineSettings(IDecalCheckHost host, string path)
{
try
{
string? text = host.ReadTextFile(path);
if (text == null) return (null, null);
using JsonDocument doc = JsonDocument.Parse(text, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
string? mode = null;
bool? inGame = null;
if (doc.RootElement.TryGetProperty("DecalBridge", out JsonElement m))
mode = m.ValueKind switch { JsonValueKind.String => m.GetString(), JsonValueKind.True => "true", JsonValueKind.False => "false", _ => null };
if (doc.RootElement.TryGetProperty("DecalInGameImGui", out JsonElement g) && (g.ValueKind == JsonValueKind.True || g.ValueKind == JsonValueKind.False))
inGame = g.GetBoolean();
return (mode, inGame);
}
catch
{
return (null, null);
}
}
internal static bool IsOurs(IRegKey k) =>
string.Equals(k.GetValue("Object") as string, DecalBridgeRegistration.FilterObject, StringComparison.Ordinal);
internal static bool IsEnabled(IRegKey k) => k.GetValue("Enabled") is int e && e != 0;
private static bool OpenExists(IDecalCheckHost host, RegRoot root, string path)
{
using IRegKey? k = host.OpenReal(root, path);
return k != null;
}
private static int? DwordOf(IDecalCheckHost host, RegRoot root, string path, string name)
{
using IRegKey? k = host.OpenReal(root, path);
return k?.GetValue(name) is int v ? v : null;
}
private static string? StringOf(IDecalCheckHost host, RegRoot root, string path, string name)
{
using IRegKey? k = host.OpenReal(root, path);
return k?.GetValue(name) is string s && s.Length > 0 ? s : null;
}
}

View file

@ -0,0 +1,810 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using Microsoft.Win32;
namespace RynthCore.App;
/// <summary>
/// Registers (and cleanly unregisters) the RynthCore Decal bridge - the small Decal
/// network filter in src\RynthCore.DecalBridge - in Decal's filter list. See
/// docs\DECAL_BRIDGE_PLAN.md, "Where Decal reads its filters".
///
/// <see cref="RegisterForClients"/> picks the place: the per-user copy below when the AC
/// client will be virtualized (the usual, non-elevated case), the machine-wide HKLM list
/// (administrator rights, once) when it won't be. An elevated or unvirtualized client never
/// reads the per-user copy (2026-10-03: a player's Decal + RynthCore client never loaded the
/// bridge). <see cref="DecalBridgeCheck"/> verifies the result.
///
/// Per-user. The launcher runs without admin rights, so it can't write Decal's own
/// key (HKLM\SOFTWARE\WOW6432Node\Decal\NetworkFilters). acclient.exe is a legacy 32-bit
/// program that Windows "virtualizes": its reads of that HKLM key are served from the
/// per-user copy under HKCU\Software\Classes\VirtualStore when one exists. Registering
/// there makes every Decal client this user starts load the bridge (it stays idle unless
/// RynthCore is in the same client).
///
/// The trap (measured 2026-09-29): once the per-user NetworkFilters key exists, Decal
/// sees ONLY its entries - HKLM's filters (World Object Filter, Echo Filter, ...) vanish,
/// Decal's WorldFilter is null and VTank refuses to start. So when this class has to
/// create that key, it first mirrors every HKLM filter entry into it, and on each
/// Register call it copies over HKLM entries added since.
///
/// What it adds is recorded in %APPDATA%\RynthCore\decal-bridge-registration.json;
/// Unregister removes exactly that: the bridge's own entry, the mirrored copies nobody has
/// changed since, and the per-user key itself only if this class created it and nothing
/// else is left in it. Register is idempotent.
///
/// Opt-in only: nothing calls Register unless the user picked "Decal + RynthCore" for an
/// account (or ran the injector's --decal-bridge register).
/// </summary>
internal static class DecalBridgeRegistration
{
/// <summary>The bridge's fixed filter id (one entry, whatever the install path).</summary>
public const string FilterGuid = "{5B3E0D57-2C41-4F8A-9D6E-8C1B70DECA11}";
public const string FilterObject = "RynthCore.DecalBridge.BridgeFilter";
public const string AssemblyFile = "RynthCore.DecalBridge.dll";
public const string FilterName = "RynthCore Decal Bridge";
/// <summary>Decal's .NET surrogate, the value every Decal.Adapter filter registers with.</summary>
private const string DotNetSurrogate = "{71A69713-6593-47EC-0002-0000000DECA1}";
private const string DecalFiltersSubKey = @"SOFTWARE\Decal\NetworkFilters"; // seen through the 32-bit view
private const RegistryView MachineView = RegistryView.Registry32; // what the 32-bit client reads
private static string StatePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "decal-bridge-registration.json");
/// <summary>HKCU path of the per-user copy the virtualized 32-bit client reads.</summary>
public static string VirtualStoreFiltersSubKey => Environment.Is64BitOperatingSystem
? @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal\NetworkFilters"
: @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\Decal\NetworkFilters";
/// <summary>The folder the launcher registers: &lt;install&gt;\DecalBridge.</summary>
public static string DefaultBridgeDirectory => Path.Combine(AppContext.BaseDirectory, "DecalBridge");
public sealed class Status
{
public bool DecalInstalled;
public bool PerUserKeyExists;
public bool PerUserKeyCreatedByUs;
public bool RegisteredPerUser;
public bool RegisteredMachineWide;
public bool Enabled;
public bool MachineEnabled;
public string? RegisteredPath;
public bool DllPresent;
/// <summary>A client started by this process gets UAC registry virtualization (reads the per-user copy when it exists).</summary>
public bool ClientVirtualized = true;
public string ClientReason = string.Empty;
/// <summary>HKLM filters a Decal client of this user can't see (hidden by the per-user key).</summary>
public List<string> HiddenMachineFilters = new();
/// <summary>What a Decal client started now will load (see DecalBridgeCheck for the full check).</summary>
public bool EffectiveForClients => ClientVirtualized && PerUserKeyExists
? RegisteredPerUser && Enabled
: RegisteredMachineWide && MachineEnabled;
public override string ToString()
{
var sb = new StringBuilder();
sb.Append($"Decal installed: {DecalInstalled}. ");
sb.Append($"Bridge registered for clients started now: {(EffectiveForClients ? "yes" : "no")}");
if (RegisteredPerUser) sb.Append(" (per-user entry present)");
if (RegisteredMachineWide) sb.Append(" (machine-wide entry present)");
if (RegisteredPath != null) sb.Append($", path {RegisteredPath}{(DllPresent ? "" : " (DLL MISSING)")}");
sb.Append('.');
if (ClientReason.Length > 0) sb.Append($" Client: {ClientReason}.");
if (PerUserKeyExists)
sb.Append($" Per-user filter list: {(PerUserKeyCreatedByUs ? "created by RynthCore" : "existed before RynthCore")}.");
if (HiddenMachineFilters.Count > 0)
sb.Append($" Hidden from Decal clients (in HKLM, not in the per-user list): {string.Join(", ", HiddenMachineFilters)}.");
return sb.ToString();
}
}
private sealed class State
{
public bool CreatedFiltersKey { get; set; }
public string BridgePath { get; set; } = string.Empty;
public DateTime RegisteredUtc { get; set; }
/// <summary>Mirrored HKLM subkey -> fingerprint of the copy as written.</summary>
public Dictionary<string, string> MirroredKeys { get; set; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Mirrored values of the NetworkFilters key itself -> fingerprint.</summary>
public Dictionary<string, string> MirroredValues { get; set; } = new(StringComparer.OrdinalIgnoreCase);
}
// ── public API ───────────────────────────────────────────────────────────
public static Status GetStatus(string? acClientPath = null)
{
bool virt = RealDecalCheckHost.PredictClientVirtualized(acClientPath ?? DecalLocator.TryGetDecalAcClientPath(), out string reason, out _);
Status s;
using (RealRegistryView.Enter()) s = GetStatusCore();
s.ClientVirtualized = virt;
s.ClientReason = reason;
return s;
}
private static Status GetStatusCore()
{
var s = new Status { DecalInstalled = DecalLocator.IsInstalled() };
State? state = LoadState();
using RegistryKey? machine = OpenMachineFilters();
using RegistryKey? user = OpenUserFilters(writable: false);
s.PerUserKeyExists = user != null;
s.PerUserKeyCreatedByUs = user != null && state?.CreatedFiltersKey == true;
using (RegistryKey? m = machine?.OpenSubKey(FilterGuid))
{
if (m != null && IsOurs(m))
{
s.RegisteredMachineWide = true;
s.MachineEnabled = Enabled(m);
if (user == null) ReadEntry(m, s);
}
}
using (RegistryKey? u = user?.OpenSubKey(FilterGuid))
{
if (u != null && IsOurs(u))
{
s.RegisteredPerUser = true;
ReadEntry(u, s);
}
}
if (machine != null && user != null)
{
HashSet<string> seen = new(user.GetSubKeyNames(), StringComparer.OrdinalIgnoreCase);
foreach (string name in machine.GetSubKeyNames())
if (!seen.Contains(name))
s.HiddenMachineFilters.Add(DescribeFilter(machine, name));
}
return s;
}
public enum Outcome { Registered, NeedsAdmin, Failed }
/// <summary>
/// Registers the bridge where a Decal client started now reads its filter list, then
/// verifies it with <see cref="DecalBridgeCheck"/> (reading back from that place, and
/// through this process's own view when it is the client's).
/// - Client virtualized (non-elevated AC, the usual case): the per-user VirtualStore copy,
/// as before (no administrator rights needed).
/// - Client not virtualized (RynthCore/AC run as administrator, UAC off, a manifest,
/// virtualization off by policy): Decal reads the real
/// HKLM\SOFTWARE\(WOW6432Node\)Decal\NetworkFilters, where a per-user entry is
/// invisible. Written directly when this process may; otherwise <see cref="Outcome.NeedsAdmin"/>,
/// and the caller runs <c>--decal-bridge-register-machine</c> elevated (<see cref="RunElevated"/>).
/// Idempotent. Also removes a "downloaded from the internet" mark from the bridge DLL.
/// </summary>
public static Outcome RegisterForClients(string bridgeDirectory, string? acClientPath, string? engineJsonPath,
out string report, out DecalBridgeCheck.Result? check)
{
check = null;
var log = new List<string>();
string dir;
try { dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\'); }
catch (Exception ex) { report = $"Bad bridge folder '{bridgeDirectory}': {ex.Message}"; return Outcome.Failed; }
string dll = Path.Combine(dir, AssemblyFile);
if (File.Exists(dll) && File.Exists(dll + ":Zone.Identifier"))
log.Add(RealDecalCheckHost.RemoveZoneIdentifier(dll)
? "removed the 'downloaded from the internet' mark from the bridge DLL"
: "could not remove the 'downloaded from the internet' mark from the bridge DLL");
bool virtualized = RealDecalCheckHost.PredictClientVirtualized(acClientPath, out string why, out _);
bool ok;
string step;
if (virtualized)
{
ok = RegisterPerUser(dir, out step);
}
else
{
Outcome mw = RegisterMachineWide(dir, out step);
if (mw == Outcome.NeedsAdmin)
{
log.Add($"AC reads Decal's filter list for all users on this PC ({why}); adding the bridge there needs administrator rights once.");
report = string.Join(" ", log);
return Outcome.NeedsAdmin;
}
ok = mw == Outcome.Registered;
step = $"({why}) " + step;
}
log.Add(step);
check = RealDecalCheckHost.Check(dir, acClientPath, engineJsonPath);
log.Add(check.Summary);
report = string.Join(" ", log);
if (!ok) return Outcome.Failed;
if (check.Blocking) return check.NeedsMachineWideRegistration ? Outcome.NeedsAdmin : Outcome.Failed;
return Outcome.Registered;
}
/// <summary>
/// <see cref="RegisterForClients"/> for Decal's own acclient.exe (PortalPath). False (with
/// the reason) when it needs administrator rights or the check fails.
/// </summary>
public static bool Register(string bridgeDirectory, out string report) =>
RegisterForClients(bridgeDirectory, DecalLocator.TryGetDecalAcClientPath(), null, out report, out _) == Outcome.Registered;
/// <summary>
/// Adds the bridge to the machine-wide list, HKLM\SOFTWARE\(WOW6432Node\)Decal\NetworkFilters
/// (32-bit view). Needs administrator rights: run elevated (--decal-bridge-register-machine).
/// Virtualization is off while it writes, so a non-elevated process gets "access denied"
/// (NeedsAdmin) instead of a silent write into the per-user copy. Idempotent; nothing to mirror
/// (the machine list is the one every other filter is in).
/// </summary>
public static Outcome RegisterMachineWide(string bridgeDirectory, out string report)
{
var log = new List<string>();
using (RealRegistryView.Enter())
{
try
{
if (!DecalLocator.IsInstalled())
{
report = "Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent) - nothing registered.";
return Outcome.Failed;
}
string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\');
if (!File.Exists(Path.Combine(dir, AssemblyFile)))
{
report = $"{AssemblyFile} not found in {dir} - nothing registered.";
return Outcome.Failed;
}
using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView);
using RegistryKey filters = hklm.CreateSubKey(DecalFiltersSubKey, writable: true);
using (RegistryKey? existing = filters.OpenSubKey(FilterGuid))
{
if (existing != null && !IsOurs(existing))
{
report = $"another filter uses the bridge's id {FilterGuid} in the machine-wide list - nothing changed.";
return Outcome.Failed;
}
}
using (RegistryKey entry = filters.CreateSubKey(FilterGuid, writable: true))
{
SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log);
SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log);
SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log);
SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log);
SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log);
SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log);
}
report = log.Count == 0
? $"Decal bridge already registered for all users ({dir}); nothing changed."
: $"Decal bridge registered for all users ({dir}): {string.Join("; ", log)}.";
return Outcome.Registered;
}
catch (Exception ex) when (ex is UnauthorizedAccessException or System.Security.SecurityException)
{
report = "Registering the Decal bridge for all users needs administrator rights.";
return Outcome.NeedsAdmin;
}
catch (Exception ex)
{
report = $"Decal bridge registration for all users failed: {Describe(ex)}";
return Outcome.Failed;
}
}
}
/// <summary>
/// The installer's per-user half (installer\RynthCore.iss, run as the installing user on
/// every install and update; the elevated half is <see cref="RegisterMachineWide"/>).
/// Writes our entry into this user's VirtualStore copy of Decal's filter list ONLY when
/// that copy already exists - see <see cref="DecalBridgeCheck.PlanInstall"/> for why both
/// places are written and why a missing copy is never created here. The entry is ours
/// (Object = <see cref="FilterObject"/>), so <see cref="Unregister"/> removes it.
/// </summary>
public static bool InstallPerUser(string bridgeDirectory, out string report)
{
try
{
var plan = RealDecalCheckHost.PlanInstall();
if (!plan.Machine)
{
report = "Decal is not installed - nothing to do for this user.";
return true;
}
if (!plan.PerUser)
{
report = "This user has no per-user copy of Decal's filter list - the machine-wide entry is the one AC reads; nothing written.";
return true;
}
string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\');
if (!File.Exists(Path.Combine(dir, AssemblyFile)))
{
report = $"{AssemblyFile} not found in {dir} - nothing written.";
return false;
}
var log = new List<string>();
using (RealRegistryView.Enter())
{
using RegistryKey? user = OpenUserFilters(writable: true);
if (user == null)
{
report = "The per-user copy disappeared - nothing written.";
return true;
}
using (RegistryKey? existing = user.OpenSubKey(FilterGuid))
{
if (existing != null && !IsOurs(existing))
{
report = $"another filter uses the bridge's id {FilterGuid} in the per-user copy - nothing changed.";
return false;
}
}
using RegistryKey entry = user.CreateSubKey(FilterGuid, writable: true);
SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log);
SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log);
SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log);
SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log);
SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log);
SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log);
}
report = log.Count == 0
? $"Decal bridge already in this user's per-user copy ({dir}); nothing changed."
: $"Decal bridge added to this user's existing per-user copy ({dir}): {string.Join("; ", log)}.";
return true;
}
catch (Exception ex)
{
report = $"Per-user Decal bridge entry failed: {Describe(ex)}";
return false;
}
}
/// <summary>The machine-wide list holds our entry (the launcher/injector never adds it without being asked).</summary>
public static bool MachineEntryIsOurs()
{
using (RealRegistryView.Enter())
{
try
{
using RegistryKey? machine = OpenMachineFilters();
using RegistryKey? m = machine?.OpenSubKey(FilterGuid);
return m != null && IsOurs(m);
}
catch { return false; }
}
}
/// <summary>Removes our machine-wide entry (only ours). Needs administrator rights.</summary>
public static Outcome UnregisterMachineWide(out string report)
{
using (RealRegistryView.Enter())
{
try
{
using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView);
using RegistryKey? probe = hklm.OpenSubKey(DecalFiltersSubKey);
using RegistryKey? m = probe?.OpenSubKey(FilterGuid);
if (m == null || !IsOurs(m))
{
report = "No machine-wide Decal bridge entry; nothing to remove.";
return Outcome.Registered;
}
using RegistryKey filters = hklm.OpenSubKey(DecalFiltersSubKey, writable: true)!;
filters.DeleteSubKeyTree(FilterGuid, throwOnMissingSubKey: false);
report = "Removed the machine-wide Decal bridge entry.";
return Outcome.Registered;
}
catch (Exception ex) when (ex is UnauthorizedAccessException or System.Security.SecurityException)
{
report = "Removing the machine-wide Decal bridge entry needs administrator rights.";
return Outcome.NeedsAdmin;
}
catch (Exception ex)
{
report = $"Removing the machine-wide Decal bridge entry failed: {Describe(ex)}";
return Outcome.Failed;
}
}
}
/// <summary>
/// Runs <paramref name="exePath"/> elevated (Windows shows its administrator prompt) and
/// waits for it. NeedsAdmin when the person said no at the prompt.
/// </summary>
public static Outcome RunElevated(string exePath, string arguments, out string report)
{
try
{
var psi = new System.Diagnostics.ProcessStartInfo(exePath, arguments)
{
UseShellExecute = true,
Verb = "runas",
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
};
using System.Diagnostics.Process? p = System.Diagnostics.Process.Start(psi);
if (p == null)
{
report = "Windows did not start the administrator step.";
return Outcome.Failed;
}
if (!p.WaitForExit(120_000))
{
report = "The administrator step did not finish within 2 minutes.";
return Outcome.Failed;
}
report = p.ExitCode == 0 ? "The administrator step finished." : $"The administrator step failed (exit code {p.ExitCode}).";
return p.ExitCode == 0 ? Outcome.Registered : Outcome.Failed;
}
catch (System.ComponentModel.Win32Exception ex) when (ex.NativeErrorCode == 1223)
{
report = "Cancelled at the Windows administrator prompt.";
return Outcome.NeedsAdmin;
}
catch (Exception ex)
{
report = $"Could not start the administrator step: {ex.Message}";
return Outcome.Failed;
}
}
/// <summary>
/// Makes Decal clients of this user load the bridge from <paramref name="bridgeDirectory"/>
/// through the per-user VirtualStore copy (virtualized clients only: see
/// <see cref="RegisterForClients"/>). Idempotent. Returns false (with the reason in
/// <paramref name="report"/>) when Decal isn't installed or the bridge DLL isn't there.
/// </summary>
public static bool RegisterPerUser(string bridgeDirectory, out string report)
{
using (RealRegistryView.Enter()) return RegisterCore(bridgeDirectory, out report);
}
private static bool RegisterCore(string bridgeDirectory, out string report)
{
var log = new List<string>();
try
{
if (!DecalLocator.IsInstalled())
{
report = "Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent) - nothing registered.";
return false;
}
string dir = Path.GetFullPath(bridgeDirectory).TrimEnd('\\');
if (!File.Exists(Path.Combine(dir, AssemblyFile)))
{
report = $"{AssemblyFile} not found in {dir} - nothing registered.";
return false;
}
State state = LoadState() ?? new State();
using RegistryKey? machine = OpenMachineFilters();
using RegistryKey? existingUser = OpenUserFilters(writable: true);
if (existingUser == null && state.CreatedFiltersKey)
{
// Someone removed the key we created; start the record over.
state = new State();
}
RegistryKey? user = existingUser;
try
{
if (user == null)
{
// No per-user list yet. If an administrator already registered the bridge in
// HKLM with this path, clients see it without us creating anything.
using (RegistryKey? m = machine?.OpenSubKey(FilterGuid))
{
if (m != null && IsOurs(m) && Enabled(m) &&
string.Equals((m.GetValue("Path") as string)?.TrimEnd('\\'), dir, StringComparison.OrdinalIgnoreCase))
{
report = "Already registered machine-wide (HKLM) with this path; nothing changed.";
return true;
}
}
user = UserHive().CreateSubKey(VirtualStoreFiltersSubKey, writable: true);
state.CreatedFiltersKey = true;
log.Add($"created HKCU\\{VirtualStoreFiltersSubKey}");
}
if (state.CreatedFiltersKey && machine != null)
SyncMirror(machine, user, state, log);
using (RegistryKey entry = user.CreateSubKey(FilterGuid, writable: true))
{
SetIfDifferent(entry, "", FilterName, RegistryValueKind.String, log);
SetIfDifferent(entry, "Enabled", 1, RegistryValueKind.DWord, log);
SetIfDifferent(entry, "Assembly", AssemblyFile, RegistryValueKind.String, log);
SetIfDifferent(entry, "Path", dir, RegistryValueKind.String, log);
SetIfDifferent(entry, "Object", FilterObject, RegistryValueKind.String, log);
SetIfDifferent(entry, "Surrogate", DotNetSurrogate, RegistryValueKind.String, log);
}
}
finally
{
if (!ReferenceEquals(user, existingUser)) user?.Dispose();
}
state.BridgePath = dir;
state.RegisteredUtc = DateTime.UtcNow;
SaveState(state);
report = log.Count == 0
? $"Decal bridge already registered for this user ({dir}); nothing changed."
: $"Decal bridge registered for this user ({dir}): {string.Join("; ", log)}.";
return true;
}
catch (Exception ex)
{
report = $"Decal bridge registration failed: {ex.GetType().Name}: {ex.Message}" +
(log.Count > 0 ? $" (done before the failure: {string.Join("; ", log)})" : "");
return false;
}
}
/// <summary>
/// Removes what <see cref="Register"/> added: the bridge's entry, the mirrored copies of
/// HKLM filters, and the per-user key if this class created it and nothing foreign is
/// left in it. A mirrored copy that changed since (Decal plugins write to "HKLM" through
/// UAC virtualization, so their writes land in our per-user copy) is removed as well when
/// RynthCore created the key: HKLM still holds the original, and a per-user list left with
/// a few entries would hide every other HKLM filter from Decal clients (VTank then has no
/// WorldFilter). Anything RynthCore didn't add is left in place and reported, and the
/// record (%APPDATA%\RynthCore\decal-bridge-registration.json) is kept until nothing of
/// ours remains, so a later unregister can finish the job.
/// </summary>
public static bool Unregister(out string report)
{
using (RealRegistryView.Enter()) return UnregisterCore(out report);
}
private static bool UnregisterCore(out string report)
{
var log = new List<string>();
var failed = new List<string>();
try
{
State? state = LoadState();
bool done = true;
using RegistryKey? user = OpenUserFilters(writable: true);
if (user != null)
{
foreach (string name in user.GetSubKeyNames())
{
try
{
bool ours;
using (RegistryKey? k = user.OpenSubKey(name))
ours = k != null && IsOurs(k);
if (!ours) continue;
user.DeleteSubKeyTree(name, throwOnMissingSubKey: false);
log.Add($"removed bridge entry {name}");
}
catch (Exception ex) { failed.Add($"{name}: {Describe(ex)}"); }
}
if (state?.CreatedFiltersKey == true)
{
int same = 0, changed = 0;
foreach (KeyValuePair<string, string> kv in state.MirroredKeys)
{
try
{
bool unchanged;
using (RegistryKey? k = user.OpenSubKey(kv.Key))
{
if (k == null) continue;
unchanged = Fingerprint(k) == kv.Value;
}
user.DeleteSubKeyTree(kv.Key, throwOnMissingSubKey: false);
if (unchanged) same++; else changed++;
}
catch (Exception ex) { failed.Add($"{kv.Key}: {Describe(ex)}"); }
}
foreach (KeyValuePair<string, string> kv in state.MirroredValues)
{
try { user.DeleteValue(kv.Key, throwOnMissingValue: false); }
catch (Exception ex) { failed.Add($"value {kv.Key}: {Describe(ex)}"); }
}
log.Add($"removed {same + changed} mirrored filter entr{(same + changed == 1 ? "y" : "ies")}" +
(changed > 0 ? $" ({changed} changed by Decal plugins since; HKLM keeps the originals)" : ""));
var foreign = new List<string>();
foreach (string n in user.GetSubKeyNames()) foreign.Add(n);
foreach (string n in user.GetValueNames()) if (n.Length > 0) foreign.Add(n);
if (foreign.Count == 0 && failed.Count == 0)
{
user.Dispose();
UserHive().DeleteSubKey(VirtualStoreFiltersSubKey, throwOnMissingSubKey: false);
log.Add($"removed HKCU\\{VirtualStoreFiltersSubKey} (created by RynthCore)");
}
else
{
done = false;
log.Add($"left HKCU\\{VirtualStoreFiltersSubKey} in place" +
(foreign.Count > 0 ? $": it holds entries RynthCore didn't add ({string.Join(", ", foreign)})" : ""));
}
}
}
if (failed.Count > 0)
done = false;
if (done && File.Exists(StatePath))
File.Delete(StatePath);
else if (!done)
log.Add($"kept {StatePath} for the next unregister");
if (failed.Count > 0)
{
report = $"Decal bridge unregistration incomplete: {string.Join("; ", failed)}" +
(log.Count > 0 ? $" (done: {string.Join("; ", log)})" : "");
return false;
}
report = log.Count == 0 ? "Decal bridge was not registered for this user; nothing to remove." : string.Join("; ", log) + ".";
return true;
}
catch (Exception ex)
{
report = $"Decal bridge unregistration failed: {Describe(ex)}" +
(log.Count > 0 ? $" (done before the failure: {string.Join("; ", log)})" : "");
return false;
}
}
// Exception type, message and the innermost frame, for a one-line report.
private static string Describe(Exception ex)
{
string? frame = ex.StackTrace?.Split('\n').Select(l => l.Trim()).FirstOrDefault(l => l.Length > 0);
return $"{ex.GetType().Name}: {ex.Message}" + (frame != null ? $" [{frame}]" : "");
}
// ── mirror ───────────────────────────────────────────────────────────────
// Copies HKLM entries the per-user list lacks, and refreshes copies nobody changed
// since we wrote them (so a filter the user enables/disables machine-wide follows).
private static void SyncMirror(RegistryKey machine, RegistryKey user, State state, List<string> log)
{
int added = 0, refreshed = 0;
foreach (string name in machine.GetValueNames())
{
if (name.Length == 0) continue;
object? v = machine.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (v == null) continue;
RegistryValueKind kind = machine.GetValueKind(name);
object? have = user.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
bool ours = state.MirroredValues.TryGetValue(name, out string? print);
if (have == null || (ours && ValuePrint(user.GetValueKind(name), have) == print))
{
user.SetValue(name, v, kind);
state.MirroredValues[name] = ValuePrint(kind, v);
}
}
foreach (string name in machine.GetSubKeyNames())
{
if (string.Equals(name, FilterGuid, StringComparison.OrdinalIgnoreCase)) continue;
using RegistryKey? src = machine.OpenSubKey(name);
if (src == null) continue;
string srcPrint = Fingerprint(src);
using RegistryKey? existing = user.OpenSubKey(name);
if (existing == null)
{
using RegistryKey dst = user.CreateSubKey(name, writable: true);
CopyTree(src, dst);
state.MirroredKeys[name] = Fingerprint(dst);
added++;
}
else if (state.MirroredKeys.TryGetValue(name, out string? written) &&
Fingerprint(existing) == written && srcPrint != written)
{
existing.Dispose();
user.DeleteSubKeyTree(name, throwOnMissingSubKey: false);
using RegistryKey dst = user.CreateSubKey(name, writable: true);
CopyTree(src, dst);
state.MirroredKeys[name] = Fingerprint(dst);
refreshed++;
}
}
if (added > 0) log.Add($"mirrored {added} HKLM filter entr{(added == 1 ? "y" : "ies")} (so Decal still sees them)");
if (refreshed > 0) log.Add($"refreshed {refreshed} mirrored entr{(refreshed == 1 ? "y" : "ies")} from HKLM");
}
private static void CopyTree(RegistryKey src, RegistryKey dst)
{
foreach (string name in src.GetValueNames())
{
object? v = src.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (v != null) dst.SetValue(name, v, src.GetValueKind(name));
}
foreach (string sub in src.GetSubKeyNames())
{
using RegistryKey? s = src.OpenSubKey(sub);
if (s == null) continue;
using RegistryKey d = dst.CreateSubKey(sub, writable: true);
CopyTree(s, d);
}
}
/// <summary>A stable text form of a key's values and subkeys, to tell "still as we wrote it".</summary>
private static string Fingerprint(RegistryKey key)
{
var sb = new StringBuilder();
foreach (string name in key.GetValueNames().OrderBy(n => n, StringComparer.OrdinalIgnoreCase))
{
object? v = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (v == null) continue;
RegistryValueKind kind;
try { kind = key.GetValueKind(name); }
catch (IOException) { continue; } // removed between the listing and the read
sb.Append(name.ToLowerInvariant()).Append('=').Append(ValuePrint(kind, v)).Append(';');
}
foreach (string sub in key.GetSubKeyNames().OrderBy(n => n, StringComparer.OrdinalIgnoreCase))
{
using RegistryKey? s = key.OpenSubKey(sub);
if (s != null) sb.Append('[').Append(sub.ToLowerInvariant()).Append(':').Append(Fingerprint(s)).Append(']');
}
return sb.ToString();
}
private static string ValuePrint(RegistryValueKind kind, object v) => kind + ":" + v switch
{
byte[] b => Convert.ToHexString(b),
string[] a => string.Join("\u0001", a),
_ => Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty,
};
// ── registry helpers ─────────────────────────────────────────────────────
private static RegistryKey UserHive() => RegistryKey.OpenBaseKey(RegistryHive.CurrentUser,
Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Default);
private static RegistryKey? OpenUserFilters(bool writable) => UserHive().OpenSubKey(VirtualStoreFiltersSubKey, writable);
private static RegistryKey? OpenMachineFilters() =>
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, MachineView).OpenSubKey(DecalFiltersSubKey);
private static bool IsOurs(RegistryKey k) =>
string.Equals(k.GetValue("Object") as string, FilterObject, StringComparison.Ordinal);
private static bool Enabled(RegistryKey k) => k.GetValue("Enabled") is int e && e != 0;
private static void ReadEntry(RegistryKey k, Status s)
{
s.Enabled = Enabled(k);
s.RegisteredPath = k.GetValue("Path") as string;
s.DllPresent = s.RegisteredPath != null && File.Exists(Path.Combine(s.RegisteredPath, AssemblyFile));
}
private static string DescribeFilter(RegistryKey parent, string name)
{
using RegistryKey? k = parent.OpenSubKey(name);
return k?.GetValue("") is string friendly && friendly.Length > 0 ? friendly : name;
}
private static void SetIfDifferent(RegistryKey key, string name, object value, RegistryValueKind kind, List<string> log)
{
object? have = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (have != null && key.GetValueKind(name) == kind && Equals(have, value))
return;
key.SetValue(name, value, kind);
log.Add($"set {(name.Length == 0 ? "(default)" : name)}");
}
private static State? LoadState()
{
try
{
if (!File.Exists(StatePath)) return null;
State? s = JsonSerializer.Deserialize<State>(File.ReadAllText(StatePath));
if (s == null) return null;
// Dictionary comparers don't survive serialization.
s.MirroredKeys = new Dictionary<string, string>(s.MirroredKeys, StringComparer.OrdinalIgnoreCase);
s.MirroredValues = new Dictionary<string, string>(s.MirroredValues, StringComparer.OrdinalIgnoreCase);
return s;
}
catch
{
return null;
}
}
private static void SaveState(State s)
{
string? dir = Path.GetDirectoryName(StatePath);
if (dir != null) Directory.CreateDirectory(dir);
File.WriteAllText(StatePath, JsonSerializer.Serialize(s, new JsonSerializerOptions { WriteIndented = true }));
}
}

View file

@ -14,4 +14,10 @@ internal enum InjectionMode
/// account runs against Decal + UBService + VTank or whatever Decal plugins
/// the user has registered.</summary>
Decal = 1,
/// <summary>Decal first, then RynthCore in the same client ("Decal + RynthCore"). The
/// engine takes chat from Decal through the RynthCore Decal bridge, which the launcher
/// registers for this Windows user before the launch (DecalBridgeRegistration;
/// docs/DECAL_BRIDGE_PLAN.md).</summary>
DecalBridge = 2,
}

View file

@ -0,0 +1,274 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
namespace RynthCore.App;
/// <summary>A registry key copied into memory (also the tests' fake key).</summary>
internal sealed class RegSnapshot : IRegKey
{
public Dictionary<string, object> Values { get; } = new(StringComparer.OrdinalIgnoreCase);
public List<string> SubKeys { get; } = new();
public object? GetValue(string name) => Values.TryGetValue(name, out object? v) ? v : null;
public string[] GetSubKeyNames() => SubKeys.ToArray();
public string[] GetValueNames() => new List<string>(Values.Keys).ToArray();
public void Dispose() { }
public static RegSnapshot? Of(RegistryKey? key)
{
if (key == null) return null;
var s = new RegSnapshot();
foreach (string n in key.GetValueNames())
{
object? v = key.GetValue(n, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (v != null) s.Values[n] = v;
}
s.SubKeys.AddRange(key.GetSubKeyNames());
return s;
}
}
/// <summary>The real machine for <see cref="DecalBridgeCheck"/>.</summary>
internal sealed class RealDecalCheckHost : IDecalCheckHost
{
private const int TokenElevation = 20, TokenVirtualizationEnabled = 24;
private static readonly string BridgeEntryMachinePath =
DecalBridgeCheck.MachineDecalPath("NetworkFilters") + "\\" + DecalBridgeRegistration.FilterGuid;
private readonly RegSnapshot? _ownViewBridgeEntry;
private readonly Dictionary<string, string?> _levels = new(StringComparer.OrdinalIgnoreCase);
public bool Is64BitOs => Environment.Is64BitOperatingSystem;
public bool LauncherElevated { get; }
public bool LauncherVirtualized { get; }
/// <summary>Construct OUTSIDE a <see cref="RealRegistryView"/> scope: it reads the process's own view.</summary>
private RealDecalCheckHost()
{
LauncherElevated = TokenFlag(TokenElevation);
LauncherVirtualized = TokenFlag(TokenVirtualizationEnabled);
try
{
using RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, Is64BitOs ? RegistryView.Registry32 : RegistryView.Default);
using RegistryKey? k = hklm.OpenSubKey(BridgeEntryMachinePath);
_ownViewBridgeEntry = RegSnapshot.Of(k);
}
catch { _ownViewBridgeEntry = null; }
}
/// <summary>Runs the check against this machine. Reads only.</summary>
public static DecalBridgeCheck.Result Check(string bridgeDirectory, string? acClientPath, string? engineJsonPath)
{
var host = new RealDecalCheckHost();
using (RealRegistryView.Enter())
return DecalBridgeCheck.Run(host, bridgeDirectory, acClientPath, engineJsonPath);
}
/// <summary>Only the client-virtualization prediction (registration uses it to pick the key).</summary>
public static bool PredictClientVirtualized(string? acClientPath, out string reason, out bool launcherElevated)
{
var host = new RealDecalCheckHost();
launcherElevated = host.LauncherElevated;
using (RealRegistryView.Enter())
return DecalBridgeCheck.PredictClientVirtualized(host, acClientPath, out reason);
}
public static bool IsProcessElevated() => TokenFlag(TokenElevation);
/// <summary><see cref="DecalBridgeCheck.PlanInstall"/> on this machine.</summary>
public static (bool Machine, bool PerUser) PlanInstall()
{
var host = new RealDecalCheckHost();
using (RealRegistryView.Enter())
return DecalBridgeCheck.PlanInstall(host);
}
public IRegKey? OpenReal(RegRoot root, string subKey)
{
try
{
(RegistryHive hive, RegistryView view) = root switch
{
RegRoot.Machine32 => (RegistryHive.LocalMachine, Is64BitOs ? RegistryView.Registry32 : RegistryView.Default),
RegRoot.Machine64 => (RegistryHive.LocalMachine, Is64BitOs ? RegistryView.Registry64 : RegistryView.Default),
RegRoot.User32 => (RegistryHive.CurrentUser, Is64BitOs ? RegistryView.Registry32 : RegistryView.Default),
_ => (RegistryHive.CurrentUser, Is64BitOs ? RegistryView.Registry64 : RegistryView.Default),
};
using RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, view);
using RegistryKey? k = baseKey.OpenSubKey(subKey);
return RegSnapshot.Of(k);
}
catch
{
return null;
}
}
public IRegKey? OpenOwnViewMachine32(string subKey) =>
string.Equals(subKey, BridgeEntryMachinePath, StringComparison.OrdinalIgnoreCase) ? _ownViewBridgeEntry : null;
public bool FileExists(string path)
{
try { return File.Exists(path); } catch { return false; }
}
public bool HasZoneIdentifier(string path)
{
try { return File.Exists(path + ":Zone.Identifier"); } catch { return false; }
}
/// <summary>Removes the "downloaded from the internet" mark. True if none is left.</summary>
public static bool RemoveZoneIdentifier(string path)
{
try
{
string ads = path + ":Zone.Identifier";
if (File.Exists(ads)) File.Delete(ads);
return !File.Exists(ads);
}
catch { return false; }
}
public Version? AssemblyVersionOf(string path)
{
try { return AssemblyName.GetAssemblyName(path).Version; } catch { return null; }
}
public Version? ReferenceVersionOf(string assemblyPath, string referenceName)
{
try
{
using FileStream fs = File.OpenRead(assemblyPath);
using var pe = new PEReader(fs);
if (!pe.HasMetadata) return null;
MetadataReader md = pe.GetMetadataReader();
foreach (AssemblyReferenceHandle h in md.AssemblyReferences)
{
AssemblyReference r = md.GetAssemblyReference(h);
if (string.Equals(md.GetString(r.Name), referenceName, StringComparison.OrdinalIgnoreCase))
return r.Version;
}
}
catch { }
return null;
}
public string? ExecutionLevelOf(string exePath)
{
if (_levels.TryGetValue(exePath, out string? cached)) return cached;
string? level = null;
try
{
if (File.Exists(exePath))
level = LevelIn(Encoding.UTF8.GetString(File.ReadAllBytes(exePath)));
// An external manifest counts only when the exe has none embedded.
if (level == null && File.Exists(exePath + ".manifest"))
level = LevelIn(File.ReadAllText(exePath + ".manifest"));
}
catch { }
_levels[exePath] = level;
return level;
}
/// <summary>The level="..." of a requestedExecutionLevel element, or null.</summary>
internal static string? LevelIn(string text)
{
int i = text.IndexOf("requestedExecutionLevel", StringComparison.Ordinal);
if (i < 0) return null;
int end = text.IndexOf('>', i);
string element = end > i ? text.Substring(i, end - i) : text.Substring(i, Math.Min(200, text.Length - i));
int l = element.IndexOf("level=", StringComparison.Ordinal);
if (l < 0) return null;
int q = l + 6;
if (q >= element.Length) return null;
char quote = element[q];
int close = element.IndexOf(quote, q + 1);
return close > q ? element.Substring(q + 1, close - q - 1) : null;
}
public string? ReadTextFile(string path)
{
try { return File.Exists(path) ? File.ReadAllText(path) : null; } catch { return null; }
}
private static bool TokenFlag(int infoClass)
{
try
{
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, out IntPtr token)) return false;
try
{
int v = 0;
return GetTokenInformation(token, infoClass, ref v, sizeof(int), out _) && v != 0;
}
finally { CloseHandle(token); }
}
catch { return false; }
}
private const uint TOKEN_QUERY = 0x0008;
[DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool GetTokenInformation(IntPtr token, int infoClass, ref int info, int length, out int returned);
}
/// <summary>
/// The launcher has no requestedExecutionLevel in its manifest, so Windows runs it with UAC
/// registry virtualization: its HKLM reads return the per-user VirtualStore copy where one
/// exists, and its HKLM writes land there silently (measured 2026-09-30). Registration and
/// the check have to see (and write) the real HKLM and the real per-user copy, so
/// virtualization is switched off for this process while they run and switched back on
/// after. A process without virtualization (the injector, an elevated launcher) is left alone.
/// </summary>
internal sealed class RealRegistryView : IDisposable
{
private const int TokenVirtualizationEnabled = 24;
private const uint TOKEN_QUERY = 0x0008, TOKEN_ADJUST_DEFAULT = 0x0080;
private IntPtr _token;
public static IDisposable Enter()
{
var scope = new RealRegistryView();
try
{
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_DEFAULT, out IntPtr token))
return scope;
int on = 0;
if (GetTokenInformation(token, TokenVirtualizationEnabled, ref on, sizeof(int), out _) && on != 0)
{
int off = 0;
if (SetTokenInformation(token, TokenVirtualizationEnabled, ref off, sizeof(int)))
{
scope._token = token; // restored in Dispose
return scope;
}
}
CloseHandle(token);
}
catch { }
return scope;
}
public void Dispose()
{
if (_token == IntPtr.Zero) return;
int on = 1;
SetTokenInformation(_token, TokenVirtualizationEnabled, ref on, sizeof(int));
CloseHandle(_token);
_token = IntPtr.Zero;
}
[DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool GetTokenInformation(IntPtr token, int infoClass, ref int info, int length, out int returned);
[DllImport("advapi32.dll", SetLastError = true)] private static extern bool SetTokenInformation(IntPtr token, int infoClass, ref int info, int length);
}

View file

@ -0,0 +1,394 @@
// ============================================================================
// RynthCore.DecalBridge - BridgeFilter.cs
//
// A Decal network filter written only against Decal's PUBLIC plugin API
// (Decal.Adapter: FilterBase, CoreManager, WorldFilter, CharacterFilter, HooksWrapper).
// It lets the RynthCore engine run in the same acclient.exe as Decal without the two
// patching the same AC functions ("bridge mode", docs/DECAL_BRIDGE_PLAN.md):
//
// events -> engine: chat lines, chat-bar commands (and eats the engine's own
// commands), login/logoff; optionally object create/release/change and
// raw server messages. The engine says which kinds it wants (want mask).
// commands <- engine: run on AC's main thread through Decal's public API - chat lines
// (InvokeChatParser) and the salvage panel (SalvagePanelAdd/Salvage).
//
// A network filter (not a plugin) so it starts with Decal, before login.
//
// Idle unless RynthCore is in the same client: registering it (the launcher does, for
// "Decal + RynthCore" accounts) makes every Decal client of that Windows user load it,
// but until the RynthCore loader shows up in the process it only counts frames. It never
// blocks, never throws into Decal, and holds nothing of the engine's.
// RYNTHCORE_DECAL_BRIDGE=0 in a client's environment keeps it off entirely.
// ============================================================================
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Decal.Adapter;
using Decal.Adapter.Wrappers;
namespace RynthCore.DecalBridge
{
[FriendlyName("RynthCore Decal Bridge")]
public sealed unsafe class BridgeFilter : FilterBase
{
private const string LogDir = @"C:\Games\RynthCore\Logs";
private const string LoaderModule = "RynthCore.Loader.dll";
private const int ArmCheckEveryFrames = 120; // ~2 s at 60 fps
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr GetModuleHandleW(string name);
private BridgeChannel _ch;
private int _pid;
private bool _disabled;
private bool _worldWired;
private bool _invoking; // true while a command of ours runs InvokeChatParser
private int _frames;
private string[] _prefixes = new string[0];
private int _prefixStamp = -1;
private long _serverMessages;
private int _loggedServer;
private int _loggedChatBar;
private bool _devicePublished;
protected override void Startup()
{
_pid = Process.GetCurrentProcess().Id;
if (Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_BRIDGE") == "0")
{
_disabled = true;
return;
}
try
{
Core.RenderFrame += OnRenderFrame;
TryArm();
}
catch (Exception ex)
{
Log("startup failed: " + ex);
}
}
protected override void Shutdown()
{
if (_disabled)
return;
try
{
Core.RenderFrame -= OnRenderFrame;
if (_ch != null)
{
ServerDispatch -= OnServerDispatch;
Core.ChatBoxMessage -= OnChatBoxMessage;
Core.CommandLineText -= OnCommandLineText;
Core.ItemSelected -= OnItemSelected;
Core.FilterInitComplete -= OnFilterInitComplete;
Core.PluginInitComplete -= OnFilterInitComplete;
}
if (_worldWired)
{
Core.WorldFilter.CreateObject -= OnCreateObject;
Core.WorldFilter.ReleaseObject -= OnReleaseObject;
Core.WorldFilter.ChangeObject -= OnChangeObject;
Core.CharacterFilter.LoginComplete -= OnLoginComplete;
Core.CharacterFilter.Logoff -= OnLogoff;
}
}
catch { }
if (_ch != null)
{
Log("shutdown after " + _serverMessages + " server messages, " +
_ch.ReadLong(BridgeLayout.OffRecords) + " records, " + _ch.ReadLong(BridgeLayout.OffDropped) + " dropped, " +
_ch.ReadLong(BridgeLayout.OffCmdDone) + " commands run");
_ch.WriteInt(BridgeLayout.OffBridgeState, 0);
_ch.Dispose();
_ch = null;
}
}
// Arms once the RynthCore loader is in this client (injected with Decal, or later).
private void TryArm()
{
if (_ch != null || GetModuleHandleW(LoaderModule) == IntPtr.Zero)
return;
BridgeChannel ch = BridgeChannel.OpenOrCreate(_pid);
if (!ch.Valid)
{
Log("mapping has another protocol version (magic 0x" + ch.ReadInt(BridgeLayout.OffMagic).ToString("X8") +
", version " + ch.ReadInt(BridgeLayout.OffVersion) + ", ours " + BridgeLayout.Version +
") - the engine and the bridge are from different builds; staying idle.");
ch.Dispose();
_disabled = true;
return;
}
_ch = ch;
_ch.WriteInt(BridgeLayout.OffBridgePid, _pid);
_ch.WriteString(BridgeRecordKind.Hello, BridgeLayout.Version, 0,
"RynthCore Decal Bridge " + typeof(BridgeFilter).Assembly.GetName().Version + " on " +
Environment.Version + " (" + (IntPtr.Size * 8) + "-bit)");
ServerDispatch += OnServerDispatch;
Core.ChatBoxMessage += OnChatBoxMessage;
Core.CommandLineText += OnCommandLineText;
Core.ItemSelected += OnItemSelected;
// WorldFilter / CharacterFilter exist once Decal's filters are up.
Core.FilterInitComplete += OnFilterInitComplete;
Core.PluginInitComplete += OnFilterInitComplete;
TryWireWorld();
_ch.WriteInt(BridgeLayout.OffBridgeState, 1); // the engine waits for this
Log("armed (RynthCore is in this client); mapping " + BridgeLayout.MappingName(_pid) + ", world wired=" + _worldWired);
}
private void OnFilterInitComplete(object sender, EventArgs e)
{
TryWireWorld();
}
private void TryWireWorld()
{
if (_worldWired) return;
try
{
WorldFilter wf = Core.WorldFilter;
CharacterFilter cf = Core.CharacterFilter;
if (wf == null || cf == null) return;
wf.CreateObject += OnCreateObject;
wf.ReleaseObject += OnReleaseObject;
wf.ChangeObject += OnChangeObject;
cf.LoginComplete += OnLoginComplete;
cf.Logoff += OnLogoff;
_worldWired = true;
Log("WorldFilter and CharacterFilter wired (Decal's world filters are up).");
}
catch (Exception ex)
{
Log("wiring WorldFilter failed: " + ex.Message);
}
}
// ── once per frame, AC's main thread ─────────────────────────────────
private void OnRenderFrame(object sender, EventArgs e)
{
try
{
if (_disabled)
return;
if (_ch == null)
{
if (++_frames % ArmCheckEveryFrames == 0)
TryArm();
return;
}
if (!_devicePublished)
PublishDevice();
if (_ch.HasCommands)
_ch.DrainCommands(RunCommand, 64);
ServeReplay();
}
catch (Exception ex)
{
Log("frame handler failed: " + ex.Message);
}
}
// The device Decal renders with, through Decal's public IDecalCore.GetD3DDevice: an
// address for the engine to read (its vtable says whether Decal wraps AC's device).
// No reference is kept and nothing is called on it here.
private void PublishDevice()
{
_devicePublished = true;
try
{
Guid iid = new Guid("D0223B96-BF7A-43FD-92BD-A43B0D82B9EB"); // IID_IDirect3DDevice9
object dev = Core.Decal.Underlying.GetD3DDevice(ref iid);
if (dev == null) { Log("GetD3DDevice returned null"); return; }
IntPtr unk = Marshal.GetIUnknownForObject(dev);
IntPtr d3d;
int hr = Marshal.QueryInterface(unk, ref iid, out d3d);
if (hr >= 0 && d3d != IntPtr.Zero)
{
_ch.WriteInt(BridgeLayout.OffD3DDevice, d3d.ToInt32());
Marshal.Release(d3d);
}
Marshal.Release(unk);
Marshal.ReleaseComObject(dev);
_ch.WriteInt(BridgeLayout.OffDecalHwnd, Core.Decal.Hwnd.ToInt32());
Log("Decal's D3D device 0x" + _ch.ReadInt(BridgeLayout.OffD3DDevice).ToString("X8") + " (QI hr=0x" + hr.ToString("X8") +
"), hwnd 0x" + Core.Decal.Hwnd.ToInt32().ToString("X"));
}
catch (Exception ex)
{
Log("GetD3DDevice failed: " + ex.GetType().Name + ": " + ex.Message);
}
}
// An engine generation that takes objects from the bridge starts with none (a hot
// reload, or an engine injected late): it bumps the replay request.
private void ServeReplay()
{
int want = _ch.ReadInt(BridgeLayout.OffReplayRequest);
if (want == 0 || want == _ch.ReadInt(BridgeLayout.OffReplayDone) || !_worldWired)
return;
int n = 0;
if (_ch.Wants(BridgeRecordKind.CreateObject))
{
foreach (WorldObject o in Core.WorldFilter.GetAll())
{
_ch.Write(BridgeRecordKind.CreateObject, unchecked((uint)o.Id), 1, null, 0);
n++;
}
}
_ch.WriteInt(BridgeLayout.OffReplayDone, want);
Log("replayed " + n + " world objects for engine request " + want);
}
private void RunCommand(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int len)
{
string failure = null;
try
{
switch (kind)
{
case BridgeRecordKind.CmdInvokeChatParser:
string line = len >= 2 ? new string((char*)payload, 0, len / 2) : string.Empty;
_invoking = true;
try { Core.Actions.InvokeChatParser(line); }
finally { _invoking = false; }
break;
case BridgeRecordKind.CmdSalvagePanelAdd:
Core.Actions.SalvagePanelAdd(unchecked((int)arg0));
break;
case BridgeRecordKind.CmdSalvagePanelSalvage:
Core.Actions.SalvagePanelSalvage();
break;
default:
failure = "unknown command " + (int)kind;
break;
}
}
catch (Exception ex)
{
failure = ex.GetType().Name + ": " + ex.Message;
}
if (failure != null)
{
Log("command " + kind + " failed: " + failure);
_ch.WriteString(BridgeRecordKind.CommandResult, (uint)kind, 0, failure);
}
}
// ── forwarders (AC's main thread; never block, never throw) ──────────
private void OnServerDispatch(object sender, NetworkMessageEventArgs e)
{
try
{
_serverMessages++;
if (!_ch.Wants(BridgeRecordKind.ServerMessage))
return; // the engine reads these from its own hooks: don't copy them
Message m = e.Message;
byte[] raw = m.RawData;
if (_loggedServer < 4)
{
_loggedServer++;
Log("server message type=0x" + m.Type.ToString("X4") + " len=" + (raw == null ? 0 : raw.Length));
}
_ch.WriteBytes(BridgeRecordKind.ServerMessage, unchecked((uint)m.Type), 0, raw);
}
catch { }
}
private void OnChatBoxMessage(object sender, ChatTextInterceptEventArgs e)
{
try { _ch.WriteString(BridgeRecordKind.ChatText, unchecked((uint)e.Color), unchecked((uint)e.Target), e.Text); }
catch { }
}
private void OnCommandLineText(object sender, ChatParserInterceptEventArgs e)
{
try
{
// A line the engine sent through InvokeChatParser: it already went through the
// engine's own dispatch; let Decal and AC have it.
if (_invoking)
return;
string text = e.Text ?? string.Empty;
// The engine's commands (and its plugins') must not reach the server: eat the
// lines whose prefix the engine published; forward every line either way.
bool eat = MatchesPrefix(text);
if (eat) e.Eat = true;
if (_loggedChatBar < 10)
{
_loggedChatBar++;
Log("chat bar: '" + text + "' eaten=" + eat);
}
_ch.WriteString(BridgeRecordKind.ChatBarEnter, eat ? 1u : 0u, 0, text);
}
catch { }
}
private void OnItemSelected(object sender, ItemSelectedEventArgs e)
{
try { _ch.Write(BridgeRecordKind.ItemSelected, unchecked((uint)e.ItemGuid), 0, null, 0); } catch { }
}
private void OnCreateObject(object sender, CreateObjectEventArgs e)
{
try { _ch.Write(BridgeRecordKind.CreateObject, unchecked((uint)e.New.Id), 0, null, 0); } catch { }
}
private void OnReleaseObject(object sender, ReleaseObjectEventArgs e)
{
try { _ch.Write(BridgeRecordKind.ReleaseObject, unchecked((uint)e.Released.Id), 0, null, 0); } catch { }
}
private void OnChangeObject(object sender, ChangeObjectEventArgs e)
{
try { _ch.Write(BridgeRecordKind.ChangeObject, unchecked((uint)e.Changed.Id), (uint)e.Change, null, 0); } catch { }
}
private void OnLoginComplete(object sender, EventArgs e)
{
try { _ch.Write(BridgeRecordKind.LoginComplete, unchecked((uint)Core.CharacterFilter.Id), 0, null, 0); } catch { }
}
private void OnLogoff(object sender, LogoffEventArgs e)
{
try { _ch.Write(BridgeRecordKind.Logoff, (uint)e.Type, 0, null, 0); } catch { }
}
// ── helpers ────────────────────────────────────────────────────────────
private bool MatchesPrefix(string text)
{
if (_ch.ReadInt(BridgeLayout.OffEngineAttached) == 0)
return false; // no engine to run it: let AC have the line
// The engine rewrites the prefix list when it attaches; re-read it when it changes.
int gen = _ch.ReadInt(BridgeLayout.OffEngineGeneration);
if (gen != _prefixStamp)
{
_prefixStamp = gen;
char* p = (char*)(_ch.Header + BridgeLayout.OffPrefixes);
int n = 0;
while (n < BridgeLayout.PrefixChars && p[n] != '\0') n++;
_prefixes = new string(p, 0, n).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
}
foreach (string pre in _prefixes)
{
if (text.StartsWith(pre, StringComparison.OrdinalIgnoreCase) &&
(text.Length == pre.Length || text[pre.Length] == ' '))
return true;
}
return false;
}
private void Log(string msg)
{
try
{
File.AppendAllText(System.IO.Path.Combine(LogDir, "DecalBridge." + _pid + ".log"),
"[" + DateTime.Now.ToString("HH:mm:ss.fff") + "] " + msg + Environment.NewLine);
}
catch { }
}
}
}

View file

@ -0,0 +1,302 @@
// ============================================================================
// RynthCore.DecalBridge - BridgeProtocol.cs
//
// The in-process channel between the Decal bridge filter (.NET Framework, Decal's
// desktop CLR) and the RynthCore engine (CoreCLR, unloadable). Compiled into BOTH
// assemblies (the engine links this file), so it stays C# 9 / net48-compatible.
// docs/DECAL_BRIDGE_PLAN.md has the design.
//
// A named, pagefile-backed file mapping holds a header and two single-producer /
// single-consumer byte rings:
// event ring (bridge -> engine): producer = the bridge, on AC's main thread (Decal
// raises its events there); consumer = the engine's plugin pump thread.
// command ring (engine -> bridge): producer = the engine (any thread, serialised by
// the engine); consumer = the bridge, on AC's main thread (RenderFrame),
// which runs each command through Decal's public API.
// Nothing crosses the runtimes but bytes: no function pointer, delegate or COM object
// is ever handed from one runtime to the other. That is what makes it safe with the
// unloadable engine - a generation that goes away leaves nothing behind that the
// bridge could call into, and neither side ever blocks on the other (a full ring
// drops the record and counts it). The mapping lives as long as either side holds it,
// so the read positions survive an engine hot reload.
//
// The engine publishes which event kinds it wants (OffWantMask); the bridge writes
// only those, so a stream the engine takes from its own hooks costs Decal nothing.
//
// Record: [int length (multiple of 4, header included)][ushort kind][ushort pad bytes]
// [uint arg0][uint arg1][payload...]
// Write/read positions are monotonic byte counts (64-bit, Interlocked on x86).
//
// Version 2 (2026-09-30): want mask, command ring, bridge hello/state fields.
// ============================================================================
#nullable disable
using System;
using System.IO.MemoryMappedFiles;
using System.Threading;
namespace RynthCore.DecalBridge
{
internal enum BridgeRecordKind : ushort
{
Pad = 0,
// ── events, bridge -> engine ──
Hello = 1, // arg0 = protocol version, payload = UTF-16 bridge description (always written)
ChatText = 2, // arg0 = Decal ChatBoxMessage.Color (AC chat type), arg1 = Target, payload = UTF-16 text
ChatBarEnter = 3, // arg0 = 1 when the bridge ate the line, payload = UTF-16 text
CreateObject = 4, // arg0 = object id, arg1 = 1 when part of a replay (WorldFilter.GetAll)
ReleaseObject = 5, // arg0 = object id
ChangeObject = 6, // arg0 = object id, arg1 = WorldChangeType
ServerMessage = 7, // arg0 = message type (opcode), payload = Message.RawData
LoginComplete = 8, // arg0 = character id
Logoff = 9, // arg0 = LogoffEventType
ItemSelected = 10, // arg0 = object id
CommandResult = 11, // arg0 = command kind, arg1 = 1 ok / 0 failed, payload = UTF-16 detail (failures only)
// ── commands, engine -> bridge (run on AC's main thread through Decal's public API) ──
CmdInvokeChatParser = 100, // payload = UTF-16 line -> Actions.InvokeChatParser
CmdSalvagePanelAdd = 101, // arg0 = item id -> Actions.SalvagePanelAdd
CmdSalvagePanelSalvage = 102,// -> Actions.SalvagePanelSalvage
}
internal static unsafe class BridgeLayout
{
public const uint Magic = 0x42444352; // "RCDB"
public const int Version = 2;
public const int HeaderSize = 4096;
public const int CommandRingSize = 64 * 1024;
public const int EventRingSize = 16 * 1024 * 1024;
public const int TotalSize = HeaderSize + CommandRingSize + EventRingSize;
public const int RecordHeaderSize = 16;
public const int MaxRecord = 256 * 1024;
// Header offsets.
public const int OffMagic = 0;
public const int OffVersion = 4;
public const int OffBridgeState = 8; // 1 while a bridge is started (its "hello")
public const int OffBridgeBeats = 12; // bridge: bumped per record written
public const int OffWritePos = 16; // long, event ring, producer-owned
public const int OffReadPos = 24; // long, event ring, consumer-owned
public const int OffDropped = 32; // long, event records the bridge dropped (ring full)
public const int OffRecords = 40; // long, event records written
public const int OffEngineAttached = 48; // 1 while an engine generation drains
public const int OffEngineGeneration = 52;
public const int OffBridgePid = 56;
public const int OffReplayRequest = 60; // engine -> bridge: bump to get WorldFilter.GetAll() as CreateObject records
public const int OffReplayDone = 64; // bridge -> engine: the request value last served
public const int OffWantMask = 68; // engine -> bridge: bit (1 << kind) for each event kind to forward
public const int OffCmdWritePos = 72; // long, command ring, engine-owned
public const int OffCmdReadPos = 80; // long, command ring, bridge-owned
public const int OffCmdDropped = 88; // long, commands the engine dropped (ring full)
public const int OffCmdDone = 96; // long, commands the bridge ran
// Added in v2 without a version bump (zero from an older bridge = unknown):
public const int OffD3DDevice = 104; // bridge -> engine: IDirect3DDevice9* Decal renders with (IDecalCore.GetD3DDevice), 0 = unknown
public const int OffDecalHwnd = 108; // bridge -> engine: the game window as Decal knows it
public const int OffPrefixes = 256; // engine -> bridge: ';'-separated chat prefixes to eat, UTF-16, 0-terminated
public const int PrefixChars = 1024;
public static string MappingName(int pid) { return "Local\\RynthCore.DecalBridge.p" + pid; }
public static int Align4(int n) { return (n + 3) & ~3; }
public static uint Bit(BridgeRecordKind kind) { return (uint)kind < 32 ? 1u << (int)kind : 0u; }
}
/// <summary>One side's view of the mapping (the bridge and the engine each open their own).</summary>
internal sealed unsafe class BridgeChannel : IDisposable
{
private MemoryMappedFile _file;
private MemoryMappedViewAccessor _view;
private byte* _base;
public byte* Header { get { return _base; } }
private byte* CommandRing { get { return _base + BridgeLayout.HeaderSize; } }
private byte* EventRing { get { return _base + BridgeLayout.HeaderSize + BridgeLayout.CommandRingSize; } }
public static BridgeChannel OpenOrCreate(int pid)
{
var c = new BridgeChannel();
c._file = MemoryMappedFile.CreateOrOpen(BridgeLayout.MappingName(pid), BridgeLayout.TotalSize);
c._view = c._file.CreateViewAccessor(0, BridgeLayout.TotalSize);
byte* p = null;
c._view.SafeMemoryMappedViewHandle.AcquirePointer(ref p);
c._base = p + c._view.PointerOffset;
// The first opener stamps the header; the pages start zeroed either way.
Interlocked.CompareExchange(ref *(int*)(c._base + BridgeLayout.OffVersion), BridgeLayout.Version, 0);
Interlocked.CompareExchange(ref *(int*)(c._base + BridgeLayout.OffMagic), unchecked((int)BridgeLayout.Magic), 0);
return c;
}
/// <summary>True when some side already created the mapping for <paramref name="pid"/>.</summary>
public static bool Exists(int pid)
{
try
{
using (MemoryMappedFile f = MemoryMappedFile.OpenExisting(BridgeLayout.MappingName(pid)))
return true;
}
catch
{
return false;
}
}
public int ReadInt(int off) { return Volatile.Read(ref *(int*)(_base + off)); }
public void WriteInt(int off, int v) { Volatile.Write(ref *(int*)(_base + off), v); }
public long ReadLong(int off) { return Interlocked.Read(ref *(long*)(_base + off)); }
public void WriteLong(int off, long v) { Interlocked.Exchange(ref *(long*)(_base + off), v); }
public void AddLong(int off, long v) { Interlocked.Add(ref *(long*)(_base + off), v); }
public bool Valid { get { return (uint)ReadInt(BridgeLayout.OffMagic) == BridgeLayout.Magic && ReadInt(BridgeLayout.OffVersion) == BridgeLayout.Version; } }
/// <summary>Whether the engine asked for <paramref name="kind"/> (Hello always goes).</summary>
public bool Wants(BridgeRecordKind kind)
{
return kind == BridgeRecordKind.Hello || (unchecked((uint)ReadInt(BridgeLayout.OffWantMask)) & BridgeLayout.Bit(kind)) != 0;
}
// ── event ring (bridge -> engine) ─────────────────────────────────────
public bool Write(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int payloadLen)
{
if (!Wants(kind))
return false;
bool ok = Put(EventRing, BridgeLayout.EventRingSize, BridgeLayout.OffWritePos, BridgeLayout.OffReadPos,
BridgeLayout.OffDropped, kind, arg0, arg1, payload, payloadLen);
if (ok)
{
AddLong(BridgeLayout.OffRecords, 1);
Interlocked.Increment(ref *(int*)(_base + BridgeLayout.OffBridgeBeats));
}
return ok;
}
public bool WriteString(BridgeRecordKind kind, uint arg0, uint arg1, string text)
{
if (text == null) text = string.Empty;
fixed (char* c = text)
return Write(kind, arg0, arg1, (byte*)c, text.Length * 2);
}
public bool WriteBytes(BridgeRecordKind kind, uint arg0, uint arg1, byte[] data)
{
if (data == null || data.Length == 0)
return Write(kind, arg0, arg1, null, 0);
fixed (byte* b = data)
return Write(kind, arg0, arg1, b, data.Length);
}
public delegate void RecordHandler(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int payloadLen);
/// <summary>Hands every event written so far to <paramref name="handler"/> (payload valid only during the call).</summary>
public int Drain(RecordHandler handler, int maxRecords)
{
return Take(EventRing, BridgeLayout.EventRingSize, BridgeLayout.OffWritePos, BridgeLayout.OffReadPos, handler, maxRecords);
}
// ── command ring (engine -> bridge) ───────────────────────────────────
/// <summary>Queues a command for the bridge. One producer at a time (the engine serialises).</summary>
public bool WriteCommand(BridgeRecordKind kind, uint arg0, uint arg1, string text)
{
if (text == null)
return Put(CommandRing, BridgeLayout.CommandRingSize, BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos,
BridgeLayout.OffCmdDropped, kind, arg0, arg1, null, 0);
fixed (char* c = text)
return Put(CommandRing, BridgeLayout.CommandRingSize, BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos,
BridgeLayout.OffCmdDropped, kind, arg0, arg1, (byte*)c, text.Length * 2);
}
/// <summary>Bridge: runs every queued command through <paramref name="handler"/>.</summary>
public int DrainCommands(RecordHandler handler, int maxRecords)
{
int n = Take(CommandRing, BridgeLayout.CommandRingSize, BridgeLayout.OffCmdWritePos, BridgeLayout.OffCmdReadPos, handler, maxRecords);
if (n > 0) AddLong(BridgeLayout.OffCmdDone, n);
return n;
}
public bool HasCommands { get { return ReadLong(BridgeLayout.OffCmdWritePos) != ReadLong(BridgeLayout.OffCmdReadPos); } }
// ── ring primitives ───────────────────────────────────────────────────
private bool Put(byte* ring, int size, int offWrite, int offRead, int offDropped,
BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int payloadLen)
{
if (payloadLen < 0 || payloadLen > BridgeLayout.MaxRecord || payloadLen > size / 4)
{
AddLong(offDropped, 1);
return false;
}
int recLen = BridgeLayout.Align4(BridgeLayout.RecordHeaderSize + payloadLen);
long w = ReadLong(offWrite);
long r = ReadLong(offRead);
int pos = (int)(w % size);
int tail = size - pos;
int need = recLen + (tail < recLen ? tail : 0);
if (need > size - (w - r))
{
AddLong(offDropped, 1);
return false;
}
if (tail < recLen)
{
// Doesn't fit before the end: pad to the end, start again at 0. A tail shorter
// than a record header is skipped by the reader without being read.
if (tail >= BridgeLayout.RecordHeaderSize)
{
*(int*)(ring + pos) = tail;
*(ushort*)(ring + pos + 4) = (ushort)BridgeRecordKind.Pad;
}
pos = 0;
}
byte* rec = ring + pos;
*(int*)rec = recLen;
*(ushort*)(rec + 4) = (ushort)kind;
*(ushort*)(rec + 6) = (ushort)(recLen - BridgeLayout.RecordHeaderSize - payloadLen); // pad bytes
*(uint*)(rec + 8) = arg0;
*(uint*)(rec + 12) = arg1;
for (int i = 0; i < payloadLen; i++)
rec[BridgeLayout.RecordHeaderSize + i] = payload[i];
WriteLong(offWrite, w + need); // publish (full fence)
return true;
}
private int Take(byte* ring, int size, int offWrite, int offRead, RecordHandler handler, int maxRecords)
{
long r = ReadLong(offRead);
long w = ReadLong(offWrite);
int n = 0;
while (r < w && n < maxRecords)
{
int pos = (int)(r % size);
int tail = size - pos;
if (tail < BridgeLayout.RecordHeaderSize) { r += tail; continue; }
int len = *(int*)(ring + pos);
if (len < BridgeLayout.RecordHeaderSize || len > tail || (len & 3) != 0)
{
r = w; // corrupt: resynchronise at the writer
break;
}
var kind = (BridgeRecordKind)(*(ushort*)(ring + pos + 4));
if (kind != BridgeRecordKind.Pad)
{
int pad = *(ushort*)(ring + pos + 6) & 3;
handler(kind, *(uint*)(ring + pos + 8), *(uint*)(ring + pos + 12),
ring + pos + BridgeLayout.RecordHeaderSize, len - BridgeLayout.RecordHeaderSize - pad);
n++;
}
r += len;
}
WriteLong(offRead, r);
return n;
}
public void Dispose()
{
if (_view != null)
{
if (_base != null) _view.SafeMemoryMappedViewHandle.ReleasePointer();
_view.Dispose();
_view = null;
}
_base = null;
if (_file != null) { _file.Dispose(); _file = null; }
}
}
}

View file

@ -0,0 +1,71 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
RynthCore Decal Bridge: a Decal network filter that lets the RynthCore engine run in
the same acclient.exe as Decal (docs/DECAL_BRIDGE_PLAN.md).
net48 / x86: it loads into Decal's desktop CLR inside the 32-bit client. Built only
against Decal's public reference assemblies (Decal.Adapter and the interop PIAs it
exposes in its signatures), never shipped with them (Private=false).
dotnet build -c Release (also part of RynthCore.sln)
Needs Decal installed (default C:\Program Files (x86)\Decal 3.0, or -p:DecalDir=...).
Without it the project builds nothing useful: a warning, and an empty assembly under
bin\<Configuration>-NoDecal\ (never the real output folder), so a machine without
Decal can still build the whole solution.
-->
<PropertyGroup>
<TargetFramework>net48</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<Platforms>AnyCPU;x86</Platforms>
<OutputType>Library</OutputType>
<AssemblyName>RynthCore.DecalBridge</AssemblyName>
<RootNamespace>RynthCore.DecalBridge</RootNamespace>
<LangVersion>9.0</LangVersion>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
<Deterministic>true</Deterministic>
<Version>0.2.0</Version>
<DecalDir Condition="'$(DecalDir)' == ''">C:\Program Files (x86)\Decal 3.0</DecalDir>
<DecalAvailable Condition="Exists('$(DecalDir)\Decal.Adapter.dll')">true</DecalAvailable>
<OutputPath>bin\$(Configuration)\</OutputPath>
<OutputPath Condition="'$(DecalAvailable)' != 'true'">bin\$(Configuration)-NoDecal\</OutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
</ItemGroup>
<ItemGroup Condition="'$(DecalAvailable)' == 'true'">
<Reference Include="Decal.Adapter">
<HintPath>$(DecalDir)\Decal.Adapter.dll</HintPath>
<Private>false</Private>
</Reference>
<!-- Public interop assemblies that appear in Decal.Adapter's own signatures. -->
<Reference Include="Decal.Interop.Core"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Core.DLL</HintPath><Private>false</Private></Reference>
<Reference Include="Decal.Interop.Filters"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Filters.DLL</HintPath><Private>false</Private></Reference>
<Reference Include="Decal.Interop.Net"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Net.DLL</HintPath><Private>false</Private></Reference>
<Reference Include="Decal.Interop.Inject"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Inject.dll</HintPath><Private>false</Private></Reference>
<Reference Include="Decal.Interop.D3DService"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.D3DService.DLL</HintPath><Private>false</Private></Reference>
<Reference Include="Decal.Interop.Render"><HintPath>$(DecalDir)\.NET 4.0 PIA\Decal.Interop.Render.DLL</HintPath><Private>false</Private></Reference>
<Reference Include="System.Drawing" />
</ItemGroup>
<ItemGroup Condition="'$(DecalAvailable)' != 'true'">
<Compile Remove="**\*.cs" />
</ItemGroup>
<Target Name="WarnNoDecal" BeforeTargets="CoreCompile" Condition="'$(DecalAvailable)' != 'true' and '$(RequireDecal)' != 'true'">
<Warning Text="RynthCore.DecalBridge: Decal.Adapter.dll not found in '$(DecalDir)' - the Decal bridge is not built (install Decal or pass -p:DecalDir=...)." />
</Target>
<!-- Release builds (installer\Build-Installer.ps1) pass -p:RequireDecal=true: no Decal, no build. -->
<Target Name="RequireDecal" BeforeTargets="BeforeBuild" Condition="'$(RequireDecal)' == 'true' and '$(DecalAvailable)' != 'true'">
<Error Text="RynthCore.DecalBridge: Decal.Adapter.dll not found in '$(DecalDir)'. The release ships the Decal bridge, so it must be built against Decal's reference assemblies: install Decal 3.0 or pass -p:DecalDir=..." />
</Target>
</Project>

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-2021 Phosphor Icons
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.

Binary file not shown.

View file

@ -106,6 +106,46 @@ internal static class AcMainThreadQueue
// class. Carries the 5 hold-flags packed into A (bit0=shift, bit1=W,
// bit2=X, bit3=Z, bit4=C).
LaunchJumpWithMotion,
// v70 WieldItem: CM_Inventory::Event_GetAndWieldItem (the 0x001A GetAndWieldItem
// game action) is an inventory send like GiveObjectTo, so it runs here too.
WieldItem,
// v72 player-to-player trade: CM_Trade::Event_* / ClientTradeSystem::Accept/DeclineTrade
// send trade game actions (and Accept/Decline touch the client's Trade object), so they
// run here too. A = PlayerTrade.TradeOp, B/C = its arguments.
Trade,
// Salvage panel marshalled 2026-09-29: CM_Inventory::SendNotice_OpenSalvagePanel,
// gmSalvageUI::AddNewItem and gmSalvageUI::Salvage were called straight from
// the plugin pump (RynthAi SalvageManager, Meta expressions). AddNewItem and
// Salvage are thiscall on the live gmSalvageUI and mutate its UIElement tree
// (same class as the SetSelectedObject 0x60D1D AV). A = toolId / itemId.
// The instance pointer is NOT carried: the drain re-enters the helper, which
// re-reads SalvageHooks.GmSalvageUIInstance on the main thread.
SalvageOpen,
SalvageAddItem,
SalvageExecute,
// CancelAttack marshalled 2026-09-29: CM_Combat::Event_CancelAttack (0x1B7) is
// the same CM_Combat game-action sender class as Melee/Missile/ChangeCombatMode
// but was called straight from the plugin pump. It rides the RING (not a side
// queue) on purpose: every RynthAi caller pairs it with ring actions
// (StopCompletely, ChangeCombatMode, MoveItemInternal) and it must land after
// any attack already queued, so FIFO order with those is what matters. When a
// gesture defers the ring, the paired actions wait too, so the teardown stays
// one ordered group.
CancelAttack,
// SetAutonomyLevel marshalled 2026-09-29: CM_Movement::Event_AutonomyLevel
// (0xF752 game-action send) is exported to plugins as SetAutonomyLevelFn and
// was the only movement sender still called straight from the plugin pump.
// Rides the ring beside DoMovement/StopMovement/Jump so it stays ordered with
// them. A = level.
SetAutonomyLevel,
// DropItem (2026-09-30, Inventory panel): CM_Inventory::Event_DropItem (0x001B game
// action) is an inventory send like WieldItem / GiveObjectTo. A = item id.
DropItem,
// Skills panel raises (2026-09-30): CM_Train::Event_TrainAttribute / _TrainAttribute2nd /
// _TrainSkill send the RaiseAttribute / RaiseVital / RaiseSkill game actions. A game-action
// send like Trade, so it rides the ring too. A = PlayerTraining.TrainKind, B = stype, C = XP
// (skill credits for TrainKind.TrainWithCredits: Event_TrainSkillAdvancementClass, 0x0047).
Train,
}
// Four payload slots cover every routed action (the 4th was added for
@ -167,6 +207,9 @@ internal static class AcMainThreadQueue
Enqueue(ActionKind.MissileAttack, targetId, unchecked((uint)attackHeight),
BitConverter.SingleToUInt32Bits(accuracyLevel));
public static bool EnqueueCancelAttack() =>
Enqueue(ActionKind.CancelAttack, 0, 0, 0);
public static bool EnqueueDoMovement(uint motion, float speed, int holdKey) =>
Enqueue(ActionKind.DoMovement, motion, unchecked((uint)holdKey),
BitConverter.SingleToUInt32Bits(speed));
@ -183,12 +226,82 @@ internal static class AcMainThreadQueue
public static bool EnqueueStopCompletely() =>
Enqueue(ActionKind.StopCompletely, 0, 0, 0);
// ── Direct-heading slot (coalesced, latest value wins) ──────────────────────
// PlayerPhysicsHooks.SetPlayerHeadingDirect snaps the player's CPhysicsObj
// orientation quaternion with two raw stores (qw, then qz). Plugins call it
// (Host.TurnToHeading) from the pump thread on every nav tick; run there it
// raced AC's own physics integration and could leave a torn, non-unit
// quaternion (new qw with old qz). Off-thread callers now park the heading
// here and Drain applies it on the main thread. One slot, not a ring entry:
// nav re-issues the heading every tick and only the newest one matters, so a
// steering bot can never fill the action ring with headings. Lock-free and
// allocation-free; never drops (a newer heading simply replaces an older one).
// Deliberately NOT ActionKind.TurnToHeading: that dispatches the gradual
// CommandInterpreter turn, which would change the steering behaviour.
private static int _directHeadingPending;
private static uint _directHeadingBits;
public static bool EnqueueDirectHeading(float headingDegrees)
{
Volatile.Write(ref _directHeadingBits, BitConverter.SingleToUInt32Bits(headingDegrees));
Volatile.Write(ref _directHeadingPending, 1);
return true;
}
// Main thread only (from Drain). Same order as the pre-queue code: the direct
// snap first, the CommandInterpreter turn only when there is no player.
private static void DrainDirectHeading()
{
if (Interlocked.Exchange(ref _directHeadingPending, 0) == 0) return;
float heading = BitConverter.UInt32BitsToSingle(Volatile.Read(ref _directHeadingBits));
try
{
if (!PlayerPhysicsHooks.SetPlayerHeadingDirect(heading))
CommandInterpreterHooks.TurnToHeading(heading);
}
catch { }
}
// ── Overlay click-to-select slot (coalesced, latest click wins) ─────────────
// A click on a Radar dot or a monster nameplate (ImGui overlays, 2026-09-30)
// parks the object id here; Drain runs ClientHelperHooks.SelectFromOverlay on
// the main thread, which re-checks that the object still exists and that the
// client isn't portaling or logging out right before AC's SetSelectedObject.
// The faces always park here (never select inside the ImGui frame build), so
// the select runs in the same main-thread phase as every other queued action.
// One slot, not a ring entry: a click is one select, two clicks in one frame
// collapse to the newer one, and the slot sits before the ring's gesture
// defer (a selection is a UI change, not a motion; a click in the 3D world
// selects mid-gesture too). Lock-free and allocation-free.
private static int _overlaySelectPending;
private static uint _overlaySelectId;
public static bool EnqueueOverlaySelect(uint objectId)
{
if (objectId == 0) return false;
Volatile.Write(ref _overlaySelectId, objectId);
Volatile.Write(ref _overlaySelectPending, 1);
return true;
}
// Main thread only (from Drain).
private static void DrainOverlaySelect()
{
if (Interlocked.Exchange(ref _overlaySelectPending, 0) == 0) return;
uint id = Volatile.Read(ref _overlaySelectId);
try { ClientHelperHooks.SelectFromOverlay(id); }
catch { }
}
public static bool EnqueueSetMotion(uint motion, bool enabled) =>
Enqueue(ActionKind.SetMotion, motion, enabled ? 1u : 0u, 0);
public static bool EnqueueJump(float extent) =>
Enqueue(ActionKind.Jump, BitConverter.SingleToUInt32Bits(extent), 0, 0);
public static bool EnqueueSetAutonomyLevel(uint level) =>
Enqueue(ActionKind.SetAutonomyLevel, level, 0, 0);
public static bool EnqueueUseObject(uint objectId) =>
Enqueue(ActionKind.UseObject, objectId, 0, 0);
@ -213,6 +326,27 @@ internal static class AcMainThreadQueue
public static bool EnqueueGiveObjectTo(uint objectId, uint targetId, int amount) =>
Enqueue(ActionKind.GiveObjectTo, objectId, targetId, unchecked((uint)amount));
public static bool EnqueueWieldItem(uint objectId, uint equipMask) =>
Enqueue(ActionKind.WieldItem, objectId, equipMask, 0);
public static bool EnqueueDropItem(uint objectId) =>
Enqueue(ActionKind.DropItem, objectId, 0, 0);
public static bool EnqueueTrade(uint op, uint a, uint b) =>
Enqueue(ActionKind.Trade, op, a, b);
public static bool EnqueueTrain(uint kind, uint stype, uint xp) =>
Enqueue(ActionKind.Train, kind, stype, xp);
public static bool EnqueueSalvageOpen(uint toolId) =>
Enqueue(ActionKind.SalvageOpen, toolId, 0, 0);
public static bool EnqueueSalvageAddItem(uint itemId) =>
Enqueue(ActionKind.SalvageAddItem, itemId, 0, 0);
public static bool EnqueueSalvageExecute() =>
Enqueue(ActionKind.SalvageExecute, 0, 0, 0);
public static bool EnqueueSetSelectedObject(uint objectId) =>
Enqueue(ActionKind.SetSelectedObject, objectId, 0, 0);
@ -243,6 +377,9 @@ internal static class AcMainThreadQueue
/// <summary>Stop executing queued actions/casts permanently (engine teardown).</summary>
public static void Disarm() => _disarmed = true;
/// <summary>Engine teardown has begun (ChatCallbackHooks stops holding chat).</summary>
public static bool IsDisarmed => _disarmed;
// Single-consumer drain on AC's main thread (EngineFrameController.OnEndScene).
// Re-invokes the public action methods; on the main thread they execute the
// real AC call directly (their IsOnMainThread gate is satisfied here).
@ -254,7 +391,25 @@ internal static class AcMainThreadQueue
public static void Drain()
{
if (_disarmed) return;
if (_disarmed)
{
// Held incoming chat still prints during teardown (the AddTextToScroll detour
// stays live until MH_DisableHook(ALL)): it is AC's own line, not a plugin action.
try { ChatCallbackHooks.OnMainThreadDrain(disarmed: true); } catch { }
return;
}
// We are on AC's main thread by definition. Latch it here too: after a hot
// reload the first SmartBox/combat detour (the other latches) can come well
// after the first drain, and until the latch is set every dispatch below
// thinks it's off-thread and re-queues itself. A chat command a plugin queued
// straight after the reload then spun the main thread forever
// (DrainChatCommands -> Dispatch -> EnqueueChatCommand, 2026-09-29).
MainThreadGuard.RecordIfFirst();
// Incoming chat held for the plugins' verdict prints first, before anything below
// writes its own lines, so the chat window keeps the order lines arrived in.
try { ChatCallbackHooks.OnMainThreadDrain(disarmed: false); } catch { }
// Deep-audit finding #22 (2026-06-18): these three queues are
// documented as deliberately separate from the gesture-gated action
@ -268,12 +423,27 @@ internal static class AcMainThreadQueue
DrainChat();
DrainChatCommands();
DrainRequestIds();
DrainQueryHealth();
// Vendor buy/sell: a packet send through the client's own SendShopEvent, not a
// motion, so it sits with the non-gesture queues above. Also polls whether the
// vendor window is still open. Idle fast path when no vendor is open.
try { VendorTrade.MainThreadTick(); } catch { }
// Char-select service: publishes the UIFlow mode, runs a pending auto-login
// LogOnCharacter request and snapshots the native character list (throttled).
// Pre-login this runs from the Client::UseTime drain (EndScene is not hooked
// until after login). Idle in the world.
try { CharacterManagementHooks.MainThreadTick(); } catch { }
int head = _head; // only the main thread writes _head
// Plugin heading snap (coalesced slot). Before the ring and its gesture
// defer: the pre-queue raw write landed immediately, gesture or not, and
// ahead of the SetAutoRun a nav tick queues right after it. Keep both.
DrainDirectHeading();
// Overlay click-to-select (Radar dot / nameplate click): also before the
// gesture defer, so a click selects at once even while the bot swings.
DrainOverlaySelect();
int head = _head; // only the main thread writes _head
int tail = Volatile.Read(ref _tail);
// ── Gesture-phase serialization (extends the 56e6946 anim-walk guard
@ -315,6 +485,9 @@ internal static class AcMainThreadQueue
CombatActionHooks.MissileAttack(e.A, unchecked((int)e.B),
BitConverter.UInt32BitsToSingle(e.C));
break;
case ActionKind.CancelAttack:
CombatActionHooks.CancelAttack();
break;
case ActionKind.DoMovement:
MovementActionHooks.DoMovement(e.A,
BitConverter.UInt32BitsToSingle(e.C), unchecked((int)e.B));
@ -325,6 +498,9 @@ internal static class AcMainThreadQueue
case ActionKind.Jump:
MovementActionHooks.JumpNonAutonomous(BitConverter.UInt32BitsToSingle(e.A));
break;
case ActionKind.SetAutonomyLevel:
MovementActionHooks.SetAutonomyLevel(e.A);
break;
case ActionKind.UseObject:
ClientHelperHooks.UseObject(e.A);
break;
@ -349,6 +525,27 @@ internal static class AcMainThreadQueue
case ActionKind.GiveObjectTo:
ClientHelperHooks.GiveObjectTo(e.A, e.B, unchecked((int)e.C));
break;
case ActionKind.WieldItem:
ClientHelperHooks.WieldItem(e.A, e.B);
break;
case ActionKind.DropItem:
ClientHelperHooks.DropItem(e.A);
break;
case ActionKind.Trade:
PlayerTrade.RunQueued(e.A, e.B, e.C);
break;
case ActionKind.Train:
PlayerTraining.RunQueued(e.A, e.B, e.C);
break;
case ActionKind.SalvageOpen:
ClientHelperHooks.SalvagePanelOpen(e.A);
break;
case ActionKind.SalvageAddItem:
ClientHelperHooks.SalvagePanelAddItem(e.A);
break;
case ActionKind.SalvageExecute:
ClientHelperHooks.SalvagePanelExecute();
break;
case ActionKind.SetSelectedObject:
// On the main thread now -> SetSelectedObjectId's gate is
// satisfied and it calls AC's SetSelectedObject directly.
@ -400,7 +597,9 @@ internal static class AcMainThreadQueue
}
}
// ── RequestId slot (0xC8 appraisal sends from AutoIdService) ──────────────────
// ── RequestId slot (0xC8 appraisal sends from AutoIdService, and every other
// off-thread CombatActionHooks.RequestId caller: plugin RequestIdFn, the
// PluginManager.TickAll login self-identify) ─────────────────────────────
// AutoIdService runs on a Timer thread; sending 0xC8 directly there does AC heap
// allocation + a non-atomic shared UI-counter increment off AC's main thread (the
// off-thread-send class flagged for RequestId). Marshal onto the main thread here.
@ -431,7 +630,10 @@ internal static class AcMainThreadQueue
// CombatActionHooks.RequestId sends the 0xC8 directly.
private static void DrainRequestIds()
{
while (true)
// Bounded like DrainChatCommands: a re-queue never spins the main thread.
int budget;
lock (_requestIdLock) budget = _requestIdQueue.Count;
while (budget-- > 0)
{
uint id;
lock (_requestIdLock)
@ -443,6 +645,58 @@ internal static class AcMainThreadQueue
}
}
// ── QueryHealth slot (0x1BF CM_Combat::Event_QueryHealth sends) ─────────────────
// Plugins (RynthAi CombatManager, once per fight target) call QueryHealthFn from the
// plugin pump; the send allocates an AC blob and pushes AC's send queue, so it is
// main-thread-only like 0xC8. Same shape as the RequestId slot: its own small
// queue, NOT the gesture-deferred action ring (a packet send doesn't perturb the
// motion graph and a health query must not wait out a swing). Callers ignore the
// result and only want the async 0x01C0 reply, so a target already waiting here is
// not queued twice. Pre-sized, so enqueue does not allocate.
private const int MaxQueryHealthQueue = 64;
private static readonly System.Collections.Generic.Queue<uint> _queryHealthQueue = new(MaxQueryHealthQueue);
private static readonly object _queryHealthLock = new();
private static int _queryHealthPending; // lock-free "anything queued?" for the per-frame drain
// Pump-thread enqueue. Drops (returns false) if the queue is full.
public static bool EnqueueQueryHealth(uint targetId)
{
if (targetId == 0) return false;
lock (_queryHealthLock)
{
if (_queryHealthQueue.Contains(targetId))
return true; // already pending; one reply answers both
if (_queryHealthQueue.Count >= MaxQueryHealthQueue)
{
Interlocked.Increment(ref _dropped);
return false;
}
_queryHealthQueue.Enqueue(targetId);
Volatile.Write(ref _queryHealthPending, _queryHealthQueue.Count);
return true;
}
}
// Single-consumer drain on AC's main thread (from Drain()). On the main thread
// CombatActionHooks.QueryHealth sends the 0x1BF directly.
private static void DrainQueryHealth()
{
if (Volatile.Read(ref _queryHealthPending) == 0) return;
int budget;
lock (_queryHealthLock) budget = _queryHealthQueue.Count;
while (budget-- > 0)
{
uint id;
lock (_queryHealthLock)
{
if (_queryHealthQueue.Count == 0) { Volatile.Write(ref _queryHealthPending, 0); return; }
id = _queryHealthQueue.Dequeue();
Volatile.Write(ref _queryHealthPending, _queryHealthQueue.Count);
}
try { CombatActionHooks.QueryHealth(id); } catch { }
}
}
// ── Chat slot (WriteToChat strings) ──────────────────────────────────────────
// WriteToChat carries a string, which can't ride the uint Entry queue. Off-thread
// AddTextToScroll races AC's chat-scroll buffer and corrupts it (the recurring
@ -473,7 +727,10 @@ internal static class AcMainThreadQueue
// IsOnMainThread gate is satisfied here so it runs AddTextToScroll directly.
private static void DrainChat()
{
while (true)
// Bounded like DrainChatCommands: a re-queue never spins the main thread.
int budget;
lock (_chatLock) budget = _chatQueue.Count;
while (budget-- > 0)
{
(string Text, int ChatType) item;
lock (_chatLock)
@ -522,7 +779,11 @@ internal static class AcMainThreadQueue
// instead of re-enqueuing.
private static void DrainChatCommands()
{
while (true)
// Only what was queued before this drain: anything a dispatch queues again
// waits for the next frame instead of spinning here.
int budget;
lock (_chatCommandLock) budget = _chatCommandQueue.Count;
while (budget-- > 0)
{
string text;
lock (_chatCommandLock)

View file

@ -75,6 +75,7 @@ internal static class AccountHooks
private static SendNoticeWorldNameDelegate? _sendNoticeWorldNameDetour;
private static string? _cachedAccountName;
private static string? _cachedWorldName;
private static volatile string? _announcedWorldName;
public static bool IsInitialized { get; private set; }
public static bool WorldHookInstalled { get; private set; }
@ -153,6 +154,7 @@ internal static class AccountHooks
if (!string.IsNullOrEmpty(name))
{
_cachedWorldName = name;
_announcedWorldName = name;
RynthLog.Verbose($"Compat: world name captured - \"{name}\".");
}
}
@ -161,9 +163,21 @@ internal static class AccountHooks
}
catch { }
// The account id is set by now (login): warm the account-name cache here
// on the main thread so off-thread readers find it filled.
try { WarmFromMainThread(); }
catch { }
return result;
}
/// <summary>
/// The world name the server itself announced at login (the SendNotice_WorldName hook),
/// or null. Unlike TryGetWorldName it never falls back to the launcher's profile name,
/// which the player chose (ServerInfo's detection wants what the server said). Any thread.
/// </summary>
public static string? AnnouncedWorldName => _announcedWorldName;
/// <summary>
/// Returns the current account name. Result is cached after the first successful read.
/// </summary>
@ -171,12 +185,50 @@ internal static class AccountHooks
{
name = string.Empty;
if (_cachedAccountName != null)
string? cached = Volatile.Read(ref _cachedAccountName);
if (cached != null)
{
name = _cachedAccountName;
name = cached;
return true;
}
// Cold cache off AC's main thread (host GetAccountNameFn on the plugin pump:
// RynthNet identity push, meta expressions, RynthLua): report "not yet".
// Client::GetInstance / Client::GetAccountName and the PSRefBuffer read run
// on the main thread only (WarmFromMainThread), which fills the cache
// during login, normally before any plugin asks.
if (!MainThreadGuard.IsOnMainThread())
return false;
return TryReadAccountNameNative(out name);
}
private static long _nextAccountNameWarmMs;
/// <summary>
/// Main thread only (MainThreadSnapshots.Tick, and the end of the
/// SendNotice_WorldName detour). Fills the account-name cache while it is cold,
/// at most every 500 ms; a single null check once it is warm.
/// </summary>
internal static void WarmFromMainThread()
{
if (Volatile.Read(ref _cachedAccountName) != null || !MainThreadGuard.IsOnMainThread())
return;
long now = Environment.TickCount64;
if (now < _nextAccountNameWarmMs)
return;
_nextAccountNameWarmMs = now + 500;
TryReadAccountNameNative(out _);
}
// The native read (body unchanged). MAIN THREAD ONLY.
private static bool TryReadAccountNameNative(out string name)
{
name = string.Empty;
if (!MainThreadGuard.IsOnMainThread())
return false;
if (_getClientInstance == null || _getAccountName == null)
return false;
@ -205,7 +257,7 @@ internal static class AccountHooks
if (string.IsNullOrEmpty(str))
return false;
_cachedAccountName = str;
Volatile.Write(ref _cachedAccountName, str);
name = str;
return true;
}

View file

@ -0,0 +1,403 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AelrynthWire.cs
//
// Pure parsing for the Aelrynth-only features: no AC, no engine state, so the
// offline tests (tools/AelrynthTests) compile this file as is.
//
// ServerDetect which server the client is on, from the launch command line
// (-h host[:port] -p port), the world name the server announced
// at login, and the Bank mod's custom player properties.
// MasteryWire the SkillMastery mod's /mastery-data reply: ONE chat line,
// "~ael1 " + a JSON object (Mods/src/Aeshnidae.SkillMastery,
// DataCommand.cs + CompanionFeed.cs), and ACE's "Unknown
// command: <name>" refusal.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.Json;
namespace RynthCore.Engine.Compatibility;
/// <summary>Where the launch command line says the client connects.</summary>
internal enum ServerHostKind
{
/// <summary>No -h on the command line (or it couldn't be read).</summary>
Unknown,
/// <summary>aelrynth.com (or a subdomain) / 144.217.84.148, any port.</summary>
Aelrynth,
/// <summary>Loopback or a private LAN address: a developer's own server.</summary>
Local,
/// <summary>Any other host: somebody else's server.</summary>
Other,
}
/// <summary>One detection result. Immutable.</summary>
internal sealed class ServerVerdict
{
public bool IsAelrynth { get; init; }
public bool IsStaging { get; init; }
/// <summary>Plain-English why, for /rc server and the log.</summary>
public string Reason { get; init; } = "";
public static readonly ServerVerdict Unknown = new() { Reason = "nothing known yet" };
}
internal static class ServerDetect
{
public const string AelrynthDomain = "aelrynth.com";
public const string AelrynthIp = "144.217.84.148";
/// <summary>The live world (9020, 9021 the second socket ACE opens).</summary>
public const int LivePortLow = 9020, LivePortHigh = 9021;
/// <summary>The staging world on the same VPS (ops/staging.sh).</summary>
public const int StagingPort = 9030;
/// <summary>The Bank mod's custom PropertyInt64 ids (Aeshnidae.Bank ClientTotals): Radiance earned, Luminance banked, Luminance drawn this session.</summary>
public const uint RadianceEarnedProperty = 9101, LuminanceBankedProperty = 9102, LuminanceDrawnProperty = 9103;
/// <summary>
/// The host and port from acclient's command line: "-h host:port" (the RynthCore
/// launcher's ACE form) or "-h host -p port" (GDLE form, other launchers). Only
/// -h and -p are read; the rest (account, password) is never kept.
/// </summary>
public static bool TryParseLaunchHost(string? commandLine, out string host, out int port)
{
host = "";
port = 0;
if (string.IsNullOrEmpty(commandLine))
return false;
List<string> args = SplitArgs(commandLine);
for (int i = 0; i + 1 < args.Count; i++)
{
if (string.Equals(args[i], "-h", StringComparison.OrdinalIgnoreCase))
{
string v = args[i + 1].Trim();
int colon = v.LastIndexOf(':');
if (colon > 0 && v.IndexOf(':') == colon
&& int.TryParse(v.AsSpan(colon + 1), NumberStyles.None, CultureInfo.InvariantCulture, out int p))
{
host = v.Substring(0, colon);
if (port == 0) port = p;
}
else
{
host = v;
}
}
else if (string.Equals(args[i], "-p", StringComparison.OrdinalIgnoreCase)
&& int.TryParse(args[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out int p))
{
port = p;
}
}
host = host.Trim().TrimEnd('.').ToLowerInvariant();
return host.Length > 0;
}
/// <summary>Windows command-line splitting, enough for the launchers' quoting (quotes group, \" is a quote).</summary>
private static List<string> SplitArgs(string s)
{
var list = new List<string>();
var cur = new System.Text.StringBuilder();
bool inQuotes = false, any = false;
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (c == '\\' && i + 1 < s.Length && s[i + 1] == '"') { cur.Append('"'); i++; any = true; continue; }
if (c == '"') { inQuotes = !inQuotes; any = true; continue; }
if (!inQuotes && char.IsWhiteSpace(c))
{
if (any) { list.Add(cur.ToString()); cur.Clear(); any = false; }
continue;
}
cur.Append(c);
any = true;
}
if (any) list.Add(cur.ToString());
return list;
}
public static ServerHostKind ClassifyHost(string? host)
{
if (string.IsNullOrWhiteSpace(host))
return ServerHostKind.Unknown;
string h = host.Trim().TrimEnd('.').ToLowerInvariant();
if (h == AelrynthDomain || h.EndsWith("." + AelrynthDomain, StringComparison.Ordinal) || h == AelrynthIp)
return ServerHostKind.Aelrynth;
if (h == "localhost" || h == "::1" || h == "[::1]" || h.StartsWith("127.", StringComparison.Ordinal)
|| h.StartsWith("10.", StringComparison.Ordinal) || h.StartsWith("192.168.", StringComparison.Ordinal)
|| IsPrivate172(h))
return ServerHostKind.Local;
return ServerHostKind.Other;
}
private static bool IsPrivate172(string h)
{
if (!h.StartsWith("172.", StringComparison.Ordinal)) return false;
int dot = h.IndexOf('.', 4);
return dot > 4 && int.TryParse(h.AsSpan(4, dot - 4), NumberStyles.None, CultureInfo.InvariantCulture, out int b)
&& b >= 16 && b <= 31;
}
/// <summary>The server's own name for the world: Aelrynth, or Aeshnidae (its earlier name, still in the live config).</summary>
public static bool IsAelrynthWorldName(string? name)
{
if (string.IsNullOrWhiteSpace(name)) return false;
string n = name.Trim();
return n.StartsWith("Aelrynth", StringComparison.OrdinalIgnoreCase)
|| n.StartsWith("Aeshnidae", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Combines the signals. Unknown means not Aelrynth.
/// - Aelrynth's host (domain or IP, any port): yes. Port 9030 or a world name
/// with "Staging" in it is the staging world (same mods, IsStaging).
/// - Somebody else's public host: no, unless BOTH server-sent signals agree
/// (the announced world name and the Bank mod's properties) - Aelrynth on a
/// new address before this list knows it.
/// - A local/LAN host or no host at all: yes when the server announced an
/// Aelrynth world name or sends the Bank mod's properties (a dev copy).
/// </summary>
public static ServerVerdict Decide(ServerHostKind hostKind, string? host, int port, string? announcedWorld, bool bankProperties)
{
bool worldMatch = IsAelrynthWorldName(announcedWorld);
bool stagingName = announcedWorld != null && announcedWorld.IndexOf("staging", StringComparison.OrdinalIgnoreCase) >= 0;
string where = host is { Length: > 0 } ? (port > 0 ? $"{host}:{port}" : host) : "no host on the command line";
string world = announcedWorld is { Length: > 0 } ? $"world \"{announcedWorld}\"" : "no world name yet";
string bank = bankProperties ? "Bank properties seen" : "no Bank properties";
switch (hostKind)
{
case ServerHostKind.Aelrynth:
{
bool staging = port == StagingPort || stagingName;
return new ServerVerdict
{
IsAelrynth = true,
IsStaging = staging,
Reason = $"Aelrynth{(staging ? " staging" : "")}: connected to {where} ({world}, {bank})",
};
}
case ServerHostKind.Other:
if (worldMatch && bankProperties)
return new ServerVerdict
{
IsAelrynth = true,
IsStaging = stagingName,
Reason = $"Aelrynth: {where} is not a known Aelrynth address, but the server says {world} and sends Bank properties",
};
return new ServerVerdict { Reason = $"not Aelrynth: connected to {where} ({world}, {bank})" };
default:
if (worldMatch || bankProperties)
return new ServerVerdict
{
IsAelrynth = true,
IsStaging = stagingName,
Reason = $"Aelrynth (local copy): {where}, {world}, {bank}",
};
return new ServerVerdict { Reason = $"not Aelrynth: {where}, {world}, {bank}" };
}
}
}
/// <summary>One trained skill's mastery, as /mastery-data sends it.</summary>
internal sealed class MasterySkill
{
public int Id; // STypeSkill
public string Key = ""; // Skill enum name, lower case: what /raise takes
public string Name = "";
public bool Specialized;
public long Base, Current; // the server's, mastery bonus included
public int Ranks; // mastery ranks bought (RanksPerSkillPoint of them make a point)
public string Points = ""; // ranks as points, "3.7"
public int Bonus; // whole points on the skill now
public long Next; // Radiance for the next raise; 0 at the ceiling
public int Afford; // raises in a row the banked Radiance pays for (capped at 999)
public bool Ceiling; // at the server's mastery ceiling
public bool Locked; // the server wants the retail maximum first
}
/// <summary>One /mastery-data reply. Immutable once parsed.</summary>
internal sealed class MasteryData
{
public bool Ok;
public string Why = "";
public bool Enabled;
public long Radiance; // banked Radiance on the account: what a raise spends
public int PerPoint = 1; // raises per skill point
public int CeilingPoints; // 0 = no ceiling
public bool RequireCap;
public Dictionary<int, MasterySkill> Skills = new();
}
internal static class MasteryWire
{
/// <summary>The Companion wire prefix (CompanionFeed.Prefix in the server mods).</summary>
public const string Prefix = "~ael1 ";
public const string DataCommand = "mastery-data";
/// <summary>
/// The prefix within the line's first 32 characters (in case the client puts
/// something in front), with no quote before it: a player who SAYS "~ael1 {...}"
/// arrives as Name says, "~ael1 ..." and is not a server line.
/// </summary>
public static bool IsDataLine(string? line) => PrefixAt(line) >= 0;
private static int PrefixAt(string? line)
{
if (line == null || line.Length < Prefix.Length) return -1;
int at = line.IndexOf(Prefix, StringComparison.Ordinal);
return at >= 0 && at <= 32 && line.LastIndexOf('"', at) < 0 ? at : -1;
}
/// <summary>The data line's "t" (what it is), or "" when it isn't one or can't be read.</summary>
public static string TypeOf(string? line)
{
int at = PrefixAt(line);
if (at < 0) return "";
try
{
using JsonDocument doc = JsonDocument.Parse(Body(line!, at));
return doc.RootElement.ValueKind == JsonValueKind.Object ? Str(doc.RootElement, "t") : "";
}
catch { return ""; }
}
private static string Body(string line, int at)
{
string body = line.Substring(at + Prefix.Length);
int end = body.LastIndexOf('}');
return end >= 0 ? body.Substring(0, end + 1) : body;
}
/// <summary>
/// Parses a /mastery-data line ("t":"mastery"). False for any other line, another
/// "t", or JSON that can't be read. Fields the server adds later are ignored;
/// missing ones keep their defaults.
/// </summary>
public static bool TryParse(string? line, out MasteryData? data)
{
data = null;
int at = PrefixAt(line);
if (at < 0) return false;
try
{
using JsonDocument doc = JsonDocument.Parse(Body(line!, at));
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object || Str(root, "t") != "mastery")
return false;
var d = new MasteryData
{
Ok = Bool(root, "ok"),
Why = Str(root, "why"),
Enabled = Bool(root, "enabled"),
Radiance = Math.Max(0, Long(root, "radiance")),
PerPoint = (int)Math.Clamp(Long(root, "perPoint", 1), 1, 1_000_000),
CeilingPoints = (int)Math.Clamp(Long(root, "ceiling"), 0, int.MaxValue),
RequireCap = Bool(root, "requireCap"),
};
if (root.TryGetProperty("skills", out JsonElement skills) && skills.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement s in skills.EnumerateArray())
{
if (s.ValueKind != JsonValueKind.Object) continue;
int id = (int)Math.Clamp(Long(s, "id"), 0, int.MaxValue);
string key = Str(s, "k");
if (id <= 0 || !IsSkillKey(key)) continue;
d.Skills[id] = new MasterySkill
{
Id = id,
Key = key,
Name = Str(s, "name"),
Specialized = Str(s, "adv") == "spec",
Base = Long(s, "base"),
Current = Long(s, "cur"),
Ranks = (int)Math.Clamp(Long(s, "ranks"), 0, int.MaxValue),
Points = Str(s, "points"),
Bonus = (int)Math.Clamp(Long(s, "bonus"), 0, int.MaxValue),
Next = Math.Max(0, Long(s, "next")),
Afford = (int)Math.Clamp(Long(s, "afford"), 0, int.MaxValue),
Ceiling = Bool(s, "ceiling"),
Locked = Bool(s, "locked"),
};
}
}
data = d;
return true;
}
catch
{
return false;
}
}
/// <summary>
/// ACE's refusal of a command it doesn't have: "Unknown command: &lt;name&gt;"
/// (GameActionTalk). True when <paramref name="line"/> is that for <paramref name="command"/>.
/// </summary>
public static bool IsUnknownCommand(string? line, string command)
{
const string marker = "Unknown command: ";
if (line == null) return false;
int at = line.IndexOf(marker, StringComparison.Ordinal);
if (at < 0 || at > 32 || (at > 0 && line.LastIndexOf('"', at - 1) >= 0)) return false;
return string.Equals(line.Substring(at + marker.Length).Trim(), command, StringComparison.OrdinalIgnoreCase);
}
/// <summary>A Skill enum name in lower case ("meleedefense"): what the mod's /raise matches.</summary>
public static bool IsSkillKey(string? key)
{
if (string.IsNullOrEmpty(key) || key.Length > 40) return false;
foreach (char c in key)
if (c < 'a' || c > 'z') return false;
return true;
}
/// <summary>
/// The server command text for a raise, as the client sends a typed "/raise ..."
/// (ACE runs Talk text that starts with '@' as a command): "@raise meleedefense 1".
/// Null when the key or count isn't one the mod's parser reads unambiguously.
/// </summary>
public static string? RaiseCommand(string? key, int count)
{
if (!IsSkillKey(key) || count < 1 || count > 999) return null;
return "@raise " + key + " " + count.ToString(CultureInfo.InvariantCulture);
}
/// <summary>The server command text that asks for the data line.</summary>
public const string DataRequest = "@" + DataCommand;
// ── JSON helpers: tolerant of type drift (a number sent as a string, and the reverse) ──
private static string Str(JsonElement o, string name)
{
if (!o.TryGetProperty(name, out JsonElement v)) return "";
return v.ValueKind switch
{
JsonValueKind.String => v.GetString() ?? "",
JsonValueKind.Number => v.GetRawText(),
JsonValueKind.True => "true",
JsonValueKind.False => "false",
_ => "",
};
}
private static long Long(JsonElement o, string name, long fallback = 0)
{
if (!o.TryGetProperty(name, out JsonElement v)) return fallback;
if (v.ValueKind == JsonValueKind.Number)
{
if (v.TryGetInt64(out long l)) return l;
if (v.TryGetDouble(out double d)) return d >= long.MaxValue ? long.MaxValue : d <= long.MinValue ? long.MinValue : (long)d;
return fallback;
}
if (v.ValueKind == JsonValueKind.String
&& long.TryParse(v.GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out long s))
return s;
return fallback;
}
private static bool Bool(JsonElement o, string name) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True;
}

View file

@ -1,10 +1,13 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AppraisalHooks.cs
//
// Hooks CM_Examine::SendNotice_SetAppraiseInfo to cache appraisal bool
// properties for inventory items whose m_pQualities is null.
// CBaseQualities::InqBool returns 0 for such items because the property
// setter skips CBaseQualities storage when m_pQualities is null.
// Caches what the last identify of each object carried, for objects whose
// m_pQualities is null (CBaseQualities::Inq* return 0 for them) and for every
// read off AC's main thread (where no Inq* may run). Two feeds: the identify
// message itself (OnIdentifyWire, from SmartBoxHooks.ParseGameEvent: all six
// tables plus the armour/weapon/hook profiles, see PropertyWire) and, merged
// over it, AC's parsed AppraisalProfile via a hook on
// CM_Examine::SendNotice_SetAppraiseInfo (int, bool, string, spells, vitals).
//
// VA derivation (map_offset + 0x00401000 = live VA):
// 002AF5B0 CM_Examine::SendNotice_SetAppraiseInfo → 0x006B05B0
@ -57,12 +60,23 @@ internal static class AppraisalHooks
private static readonly HashSet<uint> _appraisedGuids = new();
// Unix timestamp (seconds) of last appraisal receipt per guid
private static readonly Dictionary<uint, long> _lastIdTime = new();
// Int property cache: guid → (stype → value)
private static readonly Dictionary<uint, Dictionary<uint, int>> _intCache = new();
// Bool property cache: guid → (stype → value)
private static readonly Dictionary<uint, Dictionary<uint, bool>> _boolCache = new();
// String property cache: guid → (stype → value)
private static readonly Dictionary<uint, Dictionary<uint, string>> _stringCache = new();
// Every property the last identify of an object carried: guid → bag (2026-09-30).
// Two sources, both on AC's main thread inside UIQueueManager::ProcessNetBlobData:
// - the identify message itself (SmartBoxHooks.ParseGameEvent → OnIdentifyWire, before
// AC handles it): all six tables (int, int64, bool, float, string, data id) plus the
// armour/weapon/hook profile values filed under their property ids (PropertyWire);
// - AC's parsed AppraisalProfile (SendNoticeDetour, after): int, bool and string, the
// long-proven path, merged over the wire values.
// Before, only the second existed, so int64, float and data id properties never answered
// off the main thread (the float capture of 2026-09-30 sat in a parser nothing called).
private static readonly Dictionary<uint, PropertyBag> _bags = new();
// The guid whose wire record ParseGameEvent stored in the current dispatch (main thread only):
// SendNoticeDetour then merges AC's tables into it instead of replacing them.
private static uint _wireGuidThisDispatch;
private static int _wireLogCount, _wireMissLogCount;
// Hard cap on identified objects kept (they are also evicted on delete and cleared on
// logout). Past it the oldest identify is dropped.
private const int MaxAppraisedObjects = 4096;
// Spell book cache: guid → spell ID array (from AppraisalProfile._spellBook PSmartArray<UInt32> at +0x30)
private static readonly Dictionary<uint, uint[]> _spellIdCache = new();
private static readonly object _cacheLock = new();
@ -97,14 +111,138 @@ internal static class AppraisalHooks
{
_appraisedGuids.Clear();
_lastIdTime.Clear();
_intCache.Clear();
_boolCache.Clear();
_stringCache.Clear();
_bags.Clear();
_spellIdCache.Clear();
_failedRollLogged.Clear();
}
}
/// <summary>Drops everything cached for an object AC deleted (PropertyUpdateHooks' BeingDeleted hook).</summary>
public static void EvictObject(uint guid)
{
lock (_cacheLock)
{
_appraisedGuids.Remove(guid);
_lastIdTime.Remove(guid);
_bags.Remove(guid);
_spellIdCache.Remove(guid);
_failedRollLogged.Remove(guid);
}
}
public static int CachedObjectCount
{
get { lock (_cacheLock) return _bags.Count; }
}
// Caller holds _cacheLock. Keeps the bag count under MaxAppraisedObjects by dropping the
// object identified longest ago (a scan, only when the cap is hit).
private static void EnforceCapLocked(uint keep)
{
while (_bags.Count >= MaxAppraisedObjects)
{
uint oldest = 0;
long oldestTime = long.MaxValue;
foreach (uint g in _bags.Keys)
{
if (g == keep) continue;
long t = _lastIdTime.TryGetValue(g, out long v) ? v : 0;
if (t < oldestTime) { oldestTime = t; oldest = g; }
}
if (oldest == 0) return;
_bags.Remove(oldest);
_appraisedGuids.Remove(oldest);
_lastIdTime.Remove(oldest);
_spellIdCache.Remove(oldest);
}
}
// Caller holds _cacheLock.
private static PropertyBag GetOrAddBagLocked(uint guid)
{
if (!_bags.TryGetValue(guid, out PropertyBag? bag))
{
EnforceCapLocked(guid);
_bags[guid] = bag = new PropertyBag();
}
return bag;
}
/// <summary>
/// Stores what an identify message carried (PropertyWire.TryParseIdentify), replacing the
/// object's previous identify. AC's main thread, from SmartBoxHooks.ParseGameEvent, just
/// before AC handles the message; SendNoticeDetour then merges AC's own tables in.
/// </summary>
internal static void StoreIdentify(IdentifyRecord rec)
{
lock (_cacheLock)
{
if (!_bags.ContainsKey(rec.ObjectId))
EnforceCapLocked(rec.ObjectId);
_bags[rec.ObjectId] = rec.Properties;
}
_wireGuidThisDispatch = rec.ObjectId;
if (_wireLogCount < 20)
{
_wireLogCount++;
PropertyBag b = rec.Properties;
RynthLog.Compat($"Compat: identify wire obj=0x{rec.ObjectId:X8} flags=0x{rec.Flags:X4} ok={rec.Success} " +
$"int={b.Ints.Count} int64={b.Int64s.Count} bool={b.Bools.Count} float={b.Floats.Count} " +
$"string={b.Strings.Count} did={b.DataIds.Count} armor={rec.HasArmorProfile} weapon={rec.HasWeaponProfile} " +
$"hook={rec.HasHookProfile} creature={rec.HasCreatureProfile}{(rec.Truncated ? " TRUNCATED" : "")}");
}
}
/// <summary>
/// The identify message (game event 0xC9) as UIQueueManager::ProcessNetBlobData received it,
/// from its event type on. AC's main thread, before AC handles it. Never touches AC state.
/// </summary>
internal static unsafe void OnIdentifyWire(IntPtr data, int size)
{
_wireGuidThisDispatch = 0;
if (data == IntPtr.Zero || size < 16)
return;
if (PropertyWire.TryParseIdentify(new ReadOnlySpan<byte>((void*)data, size), out IdentifyRecord rec))
StoreIdentify(rec);
}
/// <summary>
/// Folds a property update into an already-identified object so the cache doesn't keep
/// serving the value from the last identify (a used pet essence's Structure, a changed
/// float or string). Objects never identified are left alone; PropertyUpdateHooks keeps
/// their updates.
/// </summary>
internal static void ApplyUpdate(uint guid, in PropertyUpdate u)
{
lock (_cacheLock)
{
if (_bags.TryGetValue(guid, out PropertyBag? bag))
bag.Apply(u);
}
}
public static bool TryGetCachedInt64Property(uint guid, uint stype, out long value)
{
value = 0;
lock (_cacheLock)
return _bags.TryGetValue(guid, out PropertyBag? b) && b.Int64s.TryGetValue(stype, out value);
}
public static bool TryGetCachedDataIdProperty(uint guid, uint stype, out uint value)
{
value = 0;
lock (_cacheLock)
return _bags.TryGetValue(guid, out PropertyBag? b) && b.DataIds.TryGetValue(stype, out value);
}
public static bool TryGetCachedInstanceIdProperty(uint guid, uint stype, out uint value)
{
value = 0;
lock (_cacheLock)
return _bags.TryGetValue(guid, out PropertyBag? b) && b.InstanceIds.TryGetValue(stype, out value);
}
/// <summary>
/// Returns the Unix timestamp (seconds) of when appraisal data was last received for this guid, or 0 if never.
/// </summary>
@ -122,11 +260,7 @@ internal static class AppraisalHooks
{
value = 0;
lock (_cacheLock)
{
if (!_intCache.TryGetValue(guid, out Dictionary<uint, int>? props))
return false;
return props.TryGetValue(stype, out value);
}
return _bags.TryGetValue(guid, out PropertyBag? b) && b.Ints.TryGetValue(stype, out value);
}
/// <summary>
@ -137,11 +271,15 @@ internal static class AppraisalHooks
{
value = false;
lock (_cacheLock)
{
if (!_boolCache.TryGetValue(guid, out Dictionary<uint, bool>? props))
return false;
return props.TryGetValue(stype, out value);
}
return _bags.TryGetValue(guid, out PropertyBag? b) && b.Bools.TryGetValue(stype, out value);
}
/// <summary>A float (double) property from the last server appraisal of this object.</summary>
public static bool TryGetCachedDoubleProperty(uint guid, uint stype, out double value)
{
value = 0;
lock (_cacheLock)
return _bags.TryGetValue(guid, out PropertyBag? b) && b.Floats.TryGetValue(stype, out value);
}
/// <summary>
@ -153,9 +291,27 @@ internal static class AppraisalHooks
value = string.Empty;
lock (_cacheLock)
{
if (!_stringCache.TryGetValue(guid, out Dictionary<uint, string>? props))
return false;
return props.TryGetValue(stype, out value!);
if (_bags.TryGetValue(guid, out PropertyBag? b) && b.Strings.TryGetValue(stype, out string? s))
{
value = s;
return true;
}
return false;
}
}
// SendNoticeDetour's tables from AC's AppraisalProfile. When this dispatch's wire record is
// in place they are merged over it (same keys win, the profile-derived values stay); when
// the wire parse didn't run, they replace the table as they always did.
private static void StoreProfileTable<T>(uint guid, Dictionary<uint, T> props, Func<PropertyBag, Dictionary<uint, T>> table)
{
lock (_cacheLock)
{
PropertyBag bag = GetOrAddBagLocked(guid);
Dictionary<uint, T> dst = table(bag);
if (_wireGuidThisDispatch != guid)
dst.Clear();
foreach (var kv in props) dst[kv.Key] = kv.Value;
}
}
@ -218,6 +374,14 @@ internal static class AppraisalHooks
_lastIdTime[guid] = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
}
if (_wireGuidThisDispatch != guid && _wireMissLogCount < 5 && SmartBoxHooks.IsGameEventHookInstalled)
{
// The identify reached AC's handler without its wire record: int64, float and data
// id properties (and the profile values) are missing for it. Seen once per few ids.
_wireMissLogCount++;
RynthLog.Compat($"Compat: identify 0x{guid:X8} reached SetAppraiseInfo without its wire record - only int/bool/string cached.");
}
try
{
CacheIntProps(guid, profilePtr);
@ -263,6 +427,7 @@ internal static class AppraisalHooks
try { RynthLog.Compat($"Compat: appraisal creature-vitals error guid=0x{guid:X8} - {ex.GetType().Name}: {ex.Message}"); } catch { }
}
_wireGuidThisDispatch = 0;
return result;
}
@ -315,10 +480,7 @@ internal static class AppraisalHooks
if (props.Count == 0)
return;
lock (_cacheLock)
{
_intCache[guid] = props;
}
StoreProfileTable(guid, props, b => b.Ints);
RynthLog.Verbose($"Compat: cached {props.Count} int prop(s) for guid=0x{guid:X8}");
}
@ -372,10 +534,7 @@ internal static class AppraisalHooks
if (props.Count == 0)
return;
lock (_cacheLock)
{
_boolCache[guid] = props;
}
StoreProfileTable(guid, props, b => b.Bools);
RynthLog.Verbose($"Compat: cached {props.Count} bool prop(s) for guid=0x{guid:X8}");
}
@ -447,10 +606,7 @@ internal static class AppraisalHooks
if (props.Count == 0)
return;
lock (_cacheLock)
{
_stringCache[guid] = props;
}
StoreProfileTable(guid, props, b => b.Strings);
RynthLog.Verbose($"Compat: cached {props.Count} string prop(s) for guid=0x{guid:X8}");
}
@ -564,6 +720,10 @@ internal static class AppraisalHooks
}
else
{
// CreatureAppraisalProfile.enchantment_bitfield (+0x34): low 9 bits = attribute / vital
// modified, bits 16..24 = modified upward. The nameplates' "debuffed by others" marker.
ImGuiBackend.Hud.HudFeed.OnAppraisal(guid, unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x34)));
int log = Interlocked.Increment(ref _creatureVitalsLogCount);
if (log <= 50)
RynthLog.Compat($"Compat: appraisal creature vitals guid=0x{guid:X8} hp={health}/{maxHealth} stam={stamina}/{maxStamina} mana={mana}/{maxMana}");

View file

@ -113,6 +113,13 @@ internal static class AutoIdService
// Object may have been destroyed between enqueue and drain
if (objectId == 0)
continue;
// Deleted since it was queued: Evict took it out of _sent. Skip it without
// spending one of the 3 requests per tick. After a big landblock change (the
// 585 deletes of 2026-10-02) the queue otherwise kept asking the server to
// appraise gone objects at 30 a second for half a minute, and live ones waited.
// A delete-then-recreate is queued again by Enqueue, so nothing live is lost.
if (!_sent.ContainsKey(objectId))
continue;
// Marshal onto AC's main thread (EndScene drain) — the Timer thread must
// not call the native 0xC8 send directly (off-thread heap alloc + non-atomic

View file

@ -132,10 +132,17 @@ internal static class BusyCountHooks
int was = _netBusyCount;
if (_originalDecrementBusyCount != null)
// Decrement exactly what the REAL field holds, never past zero. This used
// to call the original decrement max(shadow, 3) times: with the real field
// already 0 (AC's UseDone decrements it inline, which the shadow never
// sees) that walked it to -1..-3 before the write below put it back.
// m_cBusy only drives the cursor (UpdateCursorState: != 0 = busy cursor),
// so this was never the item-action lock, but there is no reason to
// write below zero. See ClientActionGates for the gates AC really checks.
int real = Marshal.ReadInt32(_lastThisPtr + OffsetMCBusy);
if (_originalDecrementBusyCount != null && real > 0)
{
int calls = Math.Max(was, 3);
for (int i = 0; i < calls && i < 20; i++)
for (int i = 0; i < real && i < 20; i++)
_originalDecrementBusyCount(_lastThisPtr);
}
@ -171,11 +178,72 @@ internal static class BusyCountHooks
catch { /* non-fatal */ }
}
RynthLog.Verbose($"Compat: force-reset busy count (was {was})");
RynthLog.Verbose($"Compat: force-reset busy count (was real {real}, shadow {was})");
}
// ── Negative m_cBusy repair ─────────────────────────────────────────────
// AC never takes m_cBusy below what it added; only a zeroing of ours can:
// a force-clear (or the direct-action reconciler) zeroes a count whose
// action is still in flight, then the server's UseDone decrements it
// inline (Handle_Item::UseDone, not through DecrementBusyCount) to -1.
// The real-field watchdog only looks at > 0, so the negative value stayed
// for the session: a permanent busy cursor. Repair it after a short grace.
private static long _realBusyNegativeSince;
private static long _negativeRepairCount;
private const long NegativeBusyRepairMs = 2_000;
public static long NegativeRepairCount => Interlocked.Read(ref _negativeRepairCount);
public static int ShadowBusyCount => Volatile.Read(ref _netBusyCount);
public static int PendingReconcileDelta => _pendingCastBusyDelta;
/// <summary>Read AC's real m_cBusy. False when the ClientUISystem isn't known/readable.</summary>
public static bool TryReadRealBusy(out int value)
{
value = 0;
IntPtr p = _lastThisPtr;
if (p == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(p + OffsetMCBusy))
return false;
try { value = Marshal.ReadInt32(p + OffsetMCBusy); return true; }
catch { return false; }
}
/// <summary>
/// If AC's m_cBusy is negative, set it to 0 and refresh the cursor. Main
/// thread only (returns false elsewhere). <paramref name="was"/> is the
/// value found.
/// </summary>
public static bool RepairNegativeBusy(out int was)
{
was = 0;
if (!MainThreadGuard.IsOnMainThread())
return false;
IntPtr p = _lastThisPtr;
if (!TryReadRealBusy(out was) || was >= 0)
return false;
if (!ClientObjectHooks.IsWritablePointer(p + OffsetMCBusy))
return false;
Marshal.WriteInt32(p + OffsetMCBusy, 0);
Interlocked.Exchange(ref _netBusyCount, 0);
Interlocked.Increment(ref _negativeRepairCount);
if (_updateCursorStateAddress != IntPtr.Zero)
{
try
{
var updateCursor = Marshal.GetDelegateForFunctionPointer<UpdateCursorStateDelegate>(_updateCursorStateAddress);
updateCursor(p);
}
catch { /* non-fatal */ }
}
return true;
}
public static void Initialize()
{
// The item-action gates (pending request / attacking flag) resolve on
// their own; they don't need the busy-count hooks below.
try { ClientActionGates.Initialize(); }
catch (Exception ex) { RynthLog.Compat($"ClientActionGates: init threw {ex.GetType().Name}: {ex.Message}"); }
if (IsInstalled)
return;
@ -290,8 +358,10 @@ internal static class BusyCountHooks
{
_lastThisPtr = IntPtr.Zero;
Volatile.Write(ref _realBusyPositiveTickMs, 0);
_realBusyNegativeSince = 0;
_pendingCastBusyDelta = 0;
_pendingCastGestureSeen = false;
try { ClientActionGates.ResetTracking(); } catch { }
}
// ── Direct-action busy reconciliation (source fix for the per-action leak) ──
@ -398,6 +468,29 @@ internal static class BusyCountHooks
{
long now = Environment.TickCount64;
// The gates AC actually checks before an item use/move/equip (pending
// inventory request, attacking flag). Runs on every call — before each
// inbound game event and after each tick — so the attacking flag's
// zero window between AttackDone and the next CommenceAttack is seen.
if (MainThreadGuard.IsOnMainThread())
{
try { ClientActionGates.Tick(now, PlayerLifecycleLog.InWorldTransition); }
catch { }
}
// Dead or portaling (and just after): the busy count moves on its own
// while AC rebuilds the world, and force-clearing it then writes into
// AC mid-transition — every death today crashed inside AC during the
// death portal (2026-09-28). Restart the timers so a genuinely stuck
// count is judged afresh once the world has settled.
if (PlayerLifecycleLog.InWorldTransition)
{
Volatile.Write(ref _realBusyPositiveTickMs, 0);
if (Volatile.Read(ref _busyBecamePositiveTickMs) != 0)
Volatile.Write(ref _busyBecamePositiveTickMs, now);
return;
}
// ── Real-field watchdog (catches counter desync) ─────────────────────
// Trust AC's REAL m_cBusy over our shadow counter: when they diverge a
// pinned real field is what actually wedges the client (mode-change /
@ -445,6 +538,40 @@ internal static class BusyCountHooks
// (e.g. first beat after the next login).
Volatile.Write(ref _realBusyPositiveTickMs, 0);
}
// Negative real field (ReadRealBusy folds every negative into its -1
// "unreadable" sentinel, so read it directly). See RepairNegativeBusy.
bool haveReal = TryReadRealBusy(out int signedBusy);
if (haveReal && signedBusy < 0)
{
if (_realBusyNegativeSince == 0)
_realBusyNegativeSince = now;
else if (now - _realBusyNegativeSince >= NegativeBusyRepairMs && RepairNegativeBusy(out int neg))
{
_realBusyNegativeSince = 0;
RynthLog.Compat($"BusyCountHooks: REAL m_cBusy was negative ({neg}) — reset to 0 (a zeroed count's own UseDone arrived later).");
}
}
else
{
_realBusyNegativeSince = 0;
}
// Counter-based watchdog below: the shadow counter never sees AC's
// inline UseDone decrement, so it reads "stuck" after nearly every use
// and cast even though the real field is back at 0. When the real
// field is readable and idle, just resync the shadow — force-clearing
// there only zeroed the next in-flight action (thousands of needless
// force-clears a session). A real field > 0 is the real-field
// watchdog's job above.
long shadowSince = Volatile.Read(ref _busyBecamePositiveTickMs);
if (shadowSince != 0 && haveReal && signedBusy <= 0
&& now - shadowSince >= BusyWatchdogTimeoutMs)
{
Interlocked.Exchange(ref _netBusyCount, 0);
Volatile.Write(ref _busyBecamePositiveTickMs, 0);
return;
}
}
// ── Counter-based watchdog (original) ────────────────────────────────

View file

@ -89,29 +89,7 @@ internal static class CObjectMaintHooks
int count = 0;
try
{
for (uint i = 0; i < tableSize; i++)
{
IntPtr bucketSlot = buckets + (int)(i * 4);
if (!SmartBoxLocator.IsMemoryReadable(bucketSlot, 4))
break;
IntPtr node = Marshal.ReadIntPtr(bucketSlot);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket)
{
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4))
break;
uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET);
if (id != 0)
{
visit(id);
count++;
}
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4))
break;
node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET);
}
}
WalkBuckets(buckets, tableSize, visit, ref count);
}
catch (Exception ex)
{
@ -122,6 +100,44 @@ internal static class CObjectMaintHooks
return count;
}
/// <summary>
/// The bucket/chain walk both enumerators share. One probe covers the whole bucket array
/// and one covers each node's hash_next + id (adjacent, +4..+12), where the walk used to
/// probe every bucket slot and each node twice: a table of 4096 buckets cost 4096+ probes
/// per walk, ten walks a second (2026-10-02 flood fix; see MemoryProbe). When a combined
/// probe fails it falls back to the old per-slot / per-field probes, so the walk stops at
/// exactly the same place as before on bad memory. <paramref name="count"/> is by ref so a
/// visitor that throws still leaves the partial count (the callers' old behaviour).
/// </summary>
private static void WalkBuckets(IntPtr buckets, uint tableSize, Action<uint> visit, ref int count)
{
bool arrayReadable = SmartBoxLocator.IsMemoryReadable(buckets, (int)(tableSize * 4));
for (uint i = 0; i < tableSize; i++)
{
IntPtr bucketSlot = buckets + (int)(i * 4);
if (!arrayReadable && !SmartBoxLocator.IsMemoryReadable(bucketSlot, 4))
break;
IntPtr node = Marshal.ReadIntPtr(bucketSlot);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket)
{
bool nodeReadable = SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 8);
if (!nodeReadable && !SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4))
break;
uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET);
if (id != 0)
{
visit(id);
count++;
}
if (!nodeReadable && !SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4))
break;
node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET);
}
}
}
// DIAGNOSTIC (temporary): same walk as EnumerateLiveWeenieObjectIds but over
// an arbitrary CObjectMaint table (object_table +0x84 / null_object_table
// +0x9C / weenie_object_table +0xB4). Duplicated rather than refactoring the
@ -151,29 +167,7 @@ internal static class CObjectMaintHooks
int count = 0;
try
{
for (uint i = 0; i < tableSize; i++)
{
IntPtr bucketSlot = buckets + (int)(i * 4);
if (!SmartBoxLocator.IsMemoryReadable(bucketSlot, 4))
break;
IntPtr node = Marshal.ReadIntPtr(bucketSlot);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket)
{
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4))
break;
uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET);
if (id != 0)
{
visit(id);
count++;
}
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4))
break;
node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET);
}
}
WalkBuckets(buckets, tableSize, visit, ref count);
}
catch (Exception ex)
{

View file

@ -19,9 +19,10 @@ namespace RynthCore.Engine.Compatibility;
/// <see cref="PlayerPhysicsHooks.TryGetCastGestureInProgress"/>).
///
/// This is a SAMPLED gate — no acclient.exe hook is installed. <see cref="Sample"/>
/// runs on the existing 30 Hz NormalPluginPump heartbeat (PluginManager.TickAll)
/// and reads a single CMotionInterp scalar through the already-proven
/// PlayerPhysicsHooks accessor. No new detour, no pattern-scan-and-call (the
/// runs on AC's main thread (MainThreadSnapshots.Tick, from the Client::UseTime
/// drain and EndScene; it ran on the 30 Hz plugin pump until 2026-09-30, which
/// walked the player's MovementManager chain off-thread) and reads a single
/// CMotionInterp scalar through the already-proven PlayerPhysicsHooks accessor. No new detour, no pattern-scan-and-call (the
/// ACE crash class), no list walk (UAF-safe). The consumer polls the gate at
/// the same tick rate, so the busy→idle edge is observed without any new
/// engine→plugin callback (avoids the NativeAOT reverse-P/Invoke crash class).
@ -46,7 +47,7 @@ internal static class CastGate
public static int GetCastBusyState() => Volatile.Read(ref _castBusy);
/// <summary>
/// Sampled from the 30 Hz plugin pump (PluginManager.TickAll). Cheap, fully
/// Sampled on AC's main thread (MainThreadSnapshots.Tick). Cheap, fully
/// guarded, never throws. If CMotionInterp isn't reachable (pre-login /
/// between worlds) the gate reports "clear to cast" so the consumer falls
/// back to its own throttle/park, which is the hard anti-spam guarantee.

View file

@ -122,12 +122,7 @@ internal static class CharacterCaptureHooks
if (Interlocked.Exchange(ref _autoLoginPollStarted, 1) != 0)
return;
var thread = new Thread(AutoLoginPollLoop)
{
Name = "RynthCore.AutoLoginPoll",
IsBackground = true
};
thread.Start();
EngineThreads.Start("RynthCore.AutoLoginPoll", AutoLoginPollLoop);
RynthLog.Info($"CharacterCapture: Poll-driven auto-login armed for '{targetCharacter}'.");
}
@ -139,6 +134,10 @@ internal static class CharacterCaptureHooks
/// Hard-stops the instant mode==GamePlayUI or LoginComplete is observed:
/// poking LogOn pointers while in-game has been correlated with AC self-
/// exiting (see ScheduleAutoLoginIfRequested's notes).
/// Thread note (2026-09-30): this thread never touches AC itself any more.
/// CharacterManagementHooks serves the mode and the character list from its
/// main-thread snapshot, and TryLogOnCharacter hands the real LogOnCharacter
/// to AC's main thread and waits at most ~1.5 s for the result.
/// </summary>
private static void AutoLoginPollLoop()
{
@ -152,9 +151,8 @@ internal static class CharacterCaptureHooks
try
{
while (true)
while (EngineThreads.Sleep(AutoLoginPollIntervalMs))
{
Thread.Sleep(AutoLoginPollIntervalMs);
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
@ -254,21 +252,15 @@ internal static class CharacterCaptureHooks
if (Interlocked.Exchange(ref _characterListCapturePollStarted, 1) != 0)
return;
var thread = new Thread(CharacterListCapturePollLoop)
{
Name = "RynthCore.CharacterListCapture",
IsBackground = true
};
thread.Start();
EngineThreads.Start("RynthCore.CharacterListCapture", CharacterListCapturePollLoop);
}
private static void CharacterListCapturePollLoop()
{
try
{
while (!EngineLifecycle.IsShuttingDown)
while (!EngineLifecycle.IsShuttingDown && EngineThreads.Sleep(CharacterListCapturePollIntervalMs))
{
Thread.Sleep(CharacterListCapturePollIntervalMs);
// In the world: no native reads at all.
if (LoginLifecycleHooks.HasObservedLoginComplete)
@ -529,7 +521,16 @@ internal static class CharacterCaptureHooks
return (sessionHint.AccountName, sessionHint.ServerName, sessionHint.TargetCharacter);
}
return ReadLaunchContextFile(Path.Combine(rootDir, "launch_context.json"));
// The shared launch_context.json names whatever the launcher last started.
// Only trust it for a client started at about that moment (an old launcher
// that wrote no per-process file). A client the launcher didn't start - one
// from ThwargLauncher that "watch for AC start" injected into - otherwise
// auto-logged into the launcher's last character and was knocked back to
// the desktop (2026-09-30, a player's Thwarg main closing seconds after login).
string sharedPath = Path.Combine(rootDir, "launch_context.json");
if (!SharedContextIsForThisLaunch(sharedPath))
return (string.Empty, string.Empty, string.Empty);
return ReadLaunchContextFile(sharedPath);
}
catch
{
@ -537,6 +538,29 @@ internal static class CharacterCaptureHooks
}
}
private static int _sharedContextLogged;
/// <summary>True when the shared launch_context.json was written within two minutes of this process starting.</summary>
private static bool SharedContextIsForThisLaunch(string sharedPath)
{
if (!File.Exists(sharedPath)) return false;
DateTime? created = null;
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(sharedPath));
if (doc.RootElement.TryGetProperty("CreatedAtUtc", out JsonElement c) && c.TryGetDateTime(out DateTime t))
created = t.ToUniversalTime();
}
catch { }
DateTime started = System.Diagnostics.Process.GetCurrentProcess().StartTime.ToUniversalTime();
bool ours = created.HasValue && created.Value >= started.AddMinutes(-2) && created.Value <= started.AddSeconds(30);
if (Interlocked.Exchange(ref _sharedContextLogged, 1) == 0)
RynthLog.Info(ours
? $"CharacterCapture: no per-process launch context; using the shared one (written {created:HH:mm:ss}Z, this client started {started:HH:mm:ss}Z)."
: $"CharacterCapture: no launch context for this client (not started by the RynthCore launcher; shared one from {(created.HasValue ? created.Value.ToString("HH:mm:ss") + "Z" : "?")} is another launch) - no auto-login.");
return ours;
}
private static (string accountName, string serverName, string targetCharacter) ReadLaunchContextFile(string filePath)
{
if (!File.Exists(filePath))
@ -623,8 +647,8 @@ internal static class CharacterCaptureHooks
{
try
{
Thread.Sleep(scheduledDelayMs);
PerformAutoLogin(fallbackCharacters, finalSlots, targetCharacter);
if (EngineThreads.Sleep(scheduledDelayMs))
PerformAutoLogin(fallbackCharacters, finalSlots, targetCharacter);
}
finally
{
@ -635,6 +659,7 @@ internal static class CharacterCaptureHooks
Name = "RynthCore.AutoLogin",
IsBackground = true
};
EngineThreads.Track(thread);
thread.Start();
RynthLog.Verbose(

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
@ -77,8 +78,226 @@ internal static class CharacterManagementHooks
public static string StatusMessage => _statusMessage;
// ── Main-thread char-select service (2026-09-30 main-thread audit) ─────────
// The two char-select poll threads (RynthCore.AutoLoginPoll and
// RynthCore.CharacterListCapture, plus the dormant RynthCore.AutoLogin) used to
// call UIFlow::GetPersistantData, the CharacterSet GetIdentity/GetName/GetGid
// accessors and CPlayerSystem::LogOnCharacter straight from their own threads,
// and PtrToStringAnsi'd name buffers AC frees when char-select rebuilds the
// set (create / delete / reconnect). A freed buffer there is an uncatchable
// AV. Now:
// * MainThreadTick (AcMainThreadQueue.Drain, AC's main thread; pre-login it
// runs from the Client::UseTime drain) publishes the UIFlow mode every call
// and, at char-select, an immutable name/slot-count snapshot every 250 ms.
// * Off-thread TryReadCharacterNames / GetNativeCharacterSetSlotCount serve
// that snapshot; off-thread TryGetCurrentMode serves the published mode.
// * Off-thread TryLogOnCharacter parks the target in a one-request slot and
// waits a bounded time for the main thread to run the real call; on a
// timeout it withdraws the request (it can never fire late) and reports
// failure, which the poll loops already retry.
// The main thread never waits on anyone: it only consumes what is there.
private sealed class CharSelectSnapshot
{
public static readonly CharSelectSnapshot Empty = new(Array.Empty<string>(), 0);
public readonly string[] Names;
public readonly int SlotCount;
public CharSelectSnapshot(string[] names, int slotCount) { Names = names; SlotCount = slotCount; }
}
private sealed class LogOnResult
{
public bool Ok;
public string Matched = string.Empty;
public uint AvatarId;
public int SlotIndex = -1;
public string Status = string.Empty;
}
private const int CharSelectSnapshotIntervalMs = 250;
private const int LogOnRequestWaitMs = 500; // one frame at char-select is ~16-50 ms
private const int LogOnRunningGraceMs = 1000; // extra wait once the main thread has taken it
private static volatile CharSelectSnapshot _charSelectSnapshot = CharSelectSnapshot.Empty;
private static long _nextCharSelectSnapshotMs;
private static int _publishedMode;
private static int _modePublished; // 1 once MainThreadTick has read the mode
// Login request slot: 0 idle, 1 pending (off-thread caller armed it),
// 2 running (main thread took it), 3 done (result published).
private static int _logOnState;
private static string _logOnTarget = string.Empty;
private static LogOnResult? _logOnResult;
private static readonly object LogOnCallerLock = new(); // serialises OFF-thread callers only
private static int _loggedNoMainThreadService;
/// <summary>
/// Main thread only (AcMainThreadQueue.Drain). Publishes the UIFlow mode, runs a
/// pending login request, and refreshes the char-select snapshot (throttled).
/// Idle in the world: a flag check and one aligned read.
/// </summary>
public static void MainThreadTick()
{
if (!MainThreadGuard.IsOnMainThread())
return;
if (TryReadModeRaw(out int mode))
{
Volatile.Write(ref _publishedMode, mode);
Volatile.Write(ref _modePublished, 1);
}
else
{
Volatile.Write(ref _modePublished, 0);
}
// A pending login request is serviced on the next drain, not throttled.
if (Volatile.Read(ref _logOnState) == 1)
RunPendingLogOn();
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
if (_charSelectSnapshot.Names.Length != 0)
_charSelectSnapshot = CharSelectSnapshot.Empty;
return;
}
long now = Environment.TickCount64;
if (now < Volatile.Read(ref _nextCharSelectSnapshotMs))
return;
Volatile.Write(ref _nextCharSelectSnapshotMs, now + CharSelectSnapshotIntervalMs);
// Never bind here: EnsureBound pattern-scans .text under a lock the poll
// threads also take. They bind on their first pass; until then, skip.
if (!Volatile.Read(ref _bound) || mode != CharacterManagementUI)
{
if (_charSelectSnapshot.Names.Length != 0 || _charSelectSnapshot.SlotCount != 0)
_charSelectSnapshot = CharSelectSnapshot.Empty;
return;
}
try
{
var names = new List<string>();
ReadCharacterNamesCore(names);
int slotCount = SlotCountCore();
_charSelectSnapshot = new CharSelectSnapshot(names.ToArray(), slotCount);
}
catch
{
_charSelectSnapshot = CharSelectSnapshot.Empty;
}
}
// Main thread: take the request (1 -> 2), run the real call, publish (-> 3).
private static void RunPendingLogOn()
{
if (Interlocked.CompareExchange(ref _logOnState, 2, 1) != 1)
return; // withdrawn by its caller in the meantime
var result = new LogOnResult();
try
{
string target = Volatile.Read(ref _logOnTarget);
result.Ok = TryLogOnCharacterCore(target, out result.Matched, out result.AvatarId, out result.SlotIndex, out result.Status);
}
catch (Exception ex)
{
result.Ok = false;
result.Status = $"LogOnCharacter threw {ex.GetType().Name}: {ex.Message}";
}
Volatile.Write(ref _logOnResult, result);
Volatile.Write(ref _logOnState, 3);
}
// Off-thread: arm the slot and wait (bounded) for the main thread's result.
private static bool RequestLogOnFromMainThread(string targetCharacter, out string matchedCharacter, out uint avatarId, out int slotIndex, out string status)
{
matchedCharacter = string.Empty;
avatarId = 0;
slotIndex = -1;
lock (LogOnCallerLock)
{
// A result a previous caller gave up on: discard it, the slot is ours.
if (Volatile.Read(ref _logOnState) == 3)
Volatile.Write(ref _logOnState, 0);
if (Volatile.Read(ref _logOnState) != 0)
{
status = "Main thread is still running the previous LogOnCharacter request.";
return false;
}
Volatile.Write(ref _logOnResult, null);
Volatile.Write(ref _logOnTarget, targetCharacter);
Volatile.Write(ref _logOnState, 1);
long start = Environment.TickCount64;
while (true)
{
int state = Volatile.Read(ref _logOnState);
if (state == 3)
{
LogOnResult? r = Volatile.Read(ref _logOnResult);
Volatile.Write(ref _logOnState, 0);
if (r == null) { status = "LogOnCharacter produced no result."; return false; }
matchedCharacter = r.Matched;
avatarId = r.AvatarId;
slotIndex = r.SlotIndex;
status = r.Status;
return r.Ok;
}
long waited = Environment.TickCount64 - start;
if (state == 1 && waited >= LogOnRequestWaitMs)
{
// Not taken yet: withdraw it so it can never run late.
if (Interlocked.CompareExchange(ref _logOnState, 0, 1) == 1)
{
if (Interlocked.Exchange(ref _loggedNoMainThreadService, 1) == 0)
RynthLog.Compat("CharacterManagement: LogOnCharacter request not serviced by AC's main thread within 500 ms (is the Client::UseTime drain hooked?); retrying on the next poll.");
status = "AC's main thread did not service the LogOnCharacter request in time.";
return false;
}
continue; // taken just now; wait for it
}
if (state == 2 && waited >= LogOnRequestWaitMs + LogOnRunningGraceMs)
{
// Running on the main thread; its result is picked up (and
// discarded) by the next caller. Never blocks longer than this.
status = "LogOnCharacter still running on AC's main thread.";
return false;
}
if (!EngineThreads.Sleep(10))
{
Interlocked.CompareExchange(ref _logOnState, 0, 1);
status = "Engine shutting down.";
return false;
}
}
}
}
private static bool TryReadModeRaw(out int mode)
{
mode = 0;
IntPtr uiFlowPtr = GetUiFlowPointer();
if (uiFlowPtr == IntPtr.Zero)
return false;
mode = Marshal.ReadInt32(IntPtr.Add(uiFlowPtr, UIFlowCurModeOffset));
return true;
}
public static bool TryGetCurrentMode(out int mode)
{
// Off the main thread, serve the mode MainThreadTick published (at most a
// frame old). Before the first tick has run, fall back to the raw read:
// one aligned 4-byte load from the long-lived UIFlow singleton.
if (!MainThreadGuard.IsOnMainThread() && Volatile.Read(ref _modePublished) != 0)
{
mode = Volatile.Read(ref _publishedMode);
return true;
}
mode = 0;
IntPtr uiFlowPtr = GetUiFlowPointer();
if (uiFlowPtr == IntPtr.Zero)
@ -109,12 +328,49 @@ internal static class CharacterManagementHooks
return false;
}
// Bind here, on the caller's thread: pattern resolve reads only acclient's
// .text, and doing it off-thread keeps the scan off AC's main thread.
if (!EnsureBound())
{
status = _statusMessage;
return false;
}
// Off AC's main thread (the auto-login poll threads): the CharacterSet reads
// and CPlayerSystem::LogOnCharacter run on the main thread via the request
// slot; this thread waits a bounded time for the result.
if (!MainThreadGuard.IsOnMainThread())
return RequestLogOnFromMainThread(targetCharacter, out matchedCharacter, out avatarId, out slotIndex, out status);
return TryLogOnCharacterCore(targetCharacter, out matchedCharacter, out avatarId, out slotIndex, out status);
}
// The real lookup + LogOnCharacter. MAIN THREAD ONLY (MainThreadTick's request
// slot, or a caller already on AC's main thread).
private static bool TryLogOnCharacterCore(string targetCharacter, out string matchedCharacter, out uint avatarId, out int slotIndex, out string status)
{
matchedCharacter = string.Empty;
avatarId = 0;
slotIndex = -1;
if (!MainThreadGuard.IsOnMainThread())
{
status = "Off AC's main thread.";
return false;
}
if (string.IsNullOrWhiteSpace(targetCharacter))
{
status = "No target character requested.";
return false;
}
if (!Volatile.Read(ref _bound))
{
status = _statusMessage;
return false;
}
bool hasMode = TryGetCurrentMode(out int mode);
if (hasMode && mode == GamePlayUI)
{
@ -198,12 +454,35 @@ internal static class CharacterManagementHooks
if (!EnsureBound())
return false;
// Off AC's main thread (the capture/auto-login polls): the main-thread
// snapshot, taken only while CharacterManagementUI was up (<= 250 ms old).
if (!MainThreadGuard.IsOnMainThread())
{
CharSelectSnapshot snap = _charSelectSnapshot;
if (snap.Names.Length == 0)
return false;
if (!TryGetCurrentMode(out int offMode) || offMode != CharacterManagementUI)
return false;
names.AddRange(snap.Names);
return true;
}
if (!TryGetCurrentMode(out int mode) || mode != CharacterManagementUI)
return false;
ReadCharacterNamesCore(names);
return names.Count > 0;
}
// MAIN THREAD ONLY. Appends the native set's names in slot order.
private static void ReadCharacterNamesCore(List<string> names)
{
if (!MainThreadGuard.IsOnMainThread())
return;
IntPtr charSetPtr = GetCharacterSetPointer();
if (charSetPtr == IntPtr.Zero)
return false;
return;
for (int index = 0; index < MaxCharacterSlots; index++)
{
@ -218,8 +497,6 @@ internal static class CharacterManagementHooks
names.Add(name.Trim());
}
return names.Count > 0;
}
/// <summary>
@ -234,6 +511,19 @@ internal static class CharacterManagementHooks
if (!EnsureBound())
return 0;
// Off AC's main thread: the slot count from the main-thread snapshot.
if (!MainThreadGuard.IsOnMainThread())
return _charSelectSnapshot.SlotCount;
return SlotCountCore();
}
// MAIN THREAD ONLY.
private static int SlotCountCore()
{
if (!MainThreadGuard.IsOnMainThread())
return 0;
IntPtr charSetPtr = GetCharacterSetPointer();
if (charSetPtr == IntPtr.Zero)
return 0;
@ -289,8 +579,10 @@ internal static class CharacterManagementHooks
_uiFlowAddr = HookResolver.ResolveData(text, "CharMgmt.UIFlow", PatXrefUIFlow, 2, UIFlowInstanceVa).Address.ToInt32();
_playerSystemAddr = HookResolver.ResolveData(text, "CharMgmt.CPlayerSystem", PatXrefCPlayerSystem, 2, PlayerSystemVa).Address.ToInt32();
_bound = _uiFlowGetPersistantData != null && _getPlayerSystem != null && _logOnCharacter != null
&& _characterSetGetIdentity != null && _characterSetGetName != null && _characterSetGetGid != null;
// Published last (volatile): MainThreadTick reads _bound without the
// lock and then uses the delegates, so they must be visible first.
Volatile.Write(ref _bound, _uiFlowGetPersistantData != null && _getPlayerSystem != null && _logOnCharacter != null
&& _characterSetGetIdentity != null && _characterSetGetName != null && _characterSetGetGid != null);
_statusMessage = _bound ? "Bound." : "One or more character-management addresses failed to resolve.";
if (_bound)
RynthLog.Verbose("CharacterManagement: Bound UIFlow and direct LogOnCharacter entry points.");
@ -322,6 +614,11 @@ internal static class CharacterManagementHooks
private static IntPtr GetCharacterSetPointer()
{
// Calls UIFlow::GetPersistantData; the set it returns is rebuilt by the
// main thread. Main thread only (every caller is a *Core method).
if (!MainThreadGuard.IsOnMainThread())
return IntPtr.Zero;
IntPtr uiFlowPtr = GetUiFlowPointer();
if (uiFlowPtr == IntPtr.Zero)
return IntPtr.Zero;
@ -355,6 +652,9 @@ internal static class CharacterManagementHooks
private static IntPtr GetPlayerSystemPointer()
{
if (!MainThreadGuard.IsOnMainThread())
return IntPtr.Zero;
try
{
IntPtr playerSystemPtr = _getPlayerSystem!();

View file

@ -0,0 +1,192 @@
// ============================================================================
// RynthCore.Engine - Compatibility/CharacterTitles.cs
//
// The titles the character holds, for plugins (API v75 GetCharacterTitles).
// The server sends them only in game events, never as properties:
// 0x0029 CharacterTitle at login (ACE GameEventCharacterTitle):
// [u32 1][u32 current title][u32 count][count x u32 title id]
// 0x002B UpdateTitle for each new or newly displayed title (GameEventUpdateTitle):
// [u32 title id][u32 set as display title]
// Both reach SmartBoxHooks.ParseGameEvent ([event type][payload]) on AC's main
// thread, or the Decal bridge's copy on the pump. Parsing only: nothing here
// touches AC.
//
// Owner: a 0x0029 is sent once per login, so it belongs to whoever is logging
// in; the player id is noted when known and adopted at the first read when it
// wasn't yet. A list for another character is never served.
//
// Survives a hot reload: the list is mirrored into this process's environment
// (RYNTHCORE_CHAR_TITLES), as VTankWatch does, because the server won't send
// it again until the next login.
// ============================================================================
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class CharacterTitles
{
public const uint EventCharacterTitle = 0x0029;
public const uint EventUpdateTitle = 0x002B;
private const int MaxTitles = 4096;
private const string EnvName = "RYNTHCORE_CHAR_TITLES";
private static readonly object Lock = new();
private static uint _owner;
private static uint _current;
private static List<uint>? _titles; // null = nothing received for this process yet
private static int _seq;
private static bool _restored;
public static bool IsTitleEvent(uint eventType) => eventType is EventCharacterTitle or EventUpdateTitle;
/// <summary>A title game event: <paramref name="data"/> is [event type][payload], <paramref name="size"/> bytes.</summary>
public static unsafe void OnGameEvent(uint eventType, IntPtr data, uint size, uint playerId)
{
if (data == IntPtr.Zero || size < 4 || size > 0x10000) return;
var span = new ReadOnlySpan<byte>((void*)data, (int)size);
lock (Lock)
{
RestoreOnce();
if (eventType == EventCharacterTitle)
{
if (!TryParseTitleList(span, out uint current, out List<uint> titles)) return;
_owner = playerId;
_current = current;
_titles = titles;
}
else
{
if (!TryParseUpdate(span, out uint title, out bool display)) return;
if (_titles == null || (_owner != 0 && playerId != 0 && _owner != playerId)) return;
if (!_titles.Contains(title) && _titles.Count < MaxTitles) _titles.Add(title);
if (display) _current = title;
}
_seq++;
Persist();
}
}
/// <summary>
/// For the plugin API: copies up to <paramref name="max"/> title ids and returns how many
/// the character holds (which may be more than were copied), or -1 when the list for this
/// character isn't known (not received since the client started, or another character's).
/// </summary>
public static unsafe int Copy(uint playerId, uint* ids, int max, uint* current)
{
lock (Lock)
{
RestoreOnce();
if (_titles == null || playerId == 0) return -1;
if (_owner == 0) _owner = playerId; // received before the id was known
else if (_owner != playerId) return -1;
if (current != null) *current = _current;
if (ids != null)
for (int i = 0; i < _titles.Count && i < max; i++) ids[i] = _titles[i];
return _titles.Count;
}
}
public static int Sequence => Volatile.Read(ref _seq);
/// <summary>For /rc: what the engine holds.</summary>
public static string Describe()
{
lock (Lock)
{
RestoreOnce();
return _titles == null
? "no title list received since this client started"
: $"{_titles.Count} titles for 0x{_owner:X8}, current {_current}";
}
}
// ── Wire (pure) ─────────────────────────────────────────────────────────
/// <summary>0x0029: [type][u32 1][u32 current][u32 count][count x u32]. False when it doesn't fit.</summary>
internal static bool TryParseTitleList(ReadOnlySpan<byte> msg, out uint current, out List<uint> titles)
{
current = 0;
titles = new List<uint>();
if (msg.Length < 16) return false;
current = BinaryPrimitives.ReadUInt32LittleEndian(msg[8..]);
uint count = BinaryPrimitives.ReadUInt32LittleEndian(msg[12..]);
if (count > MaxTitles || 16 + (long)count * 4 > msg.Length) return false;
for (int i = 0; i < (int)count; i++)
{
uint id = BinaryPrimitives.ReadUInt32LittleEndian(msg[(16 + i * 4)..]);
if (!titles.Contains(id)) titles.Add(id);
}
return true;
}
/// <summary>0x002B: [type][u32 title][u32 set as display title].</summary>
internal static bool TryParseUpdate(ReadOnlySpan<byte> msg, out uint title, out bool display)
{
title = 0;
display = false;
if (msg.Length < 12) return false;
title = BinaryPrimitives.ReadUInt32LittleEndian(msg[4..]);
display = BinaryPrimitives.ReadUInt32LittleEndian(msg[8..]) != 0;
return true;
}
// ── Hot-reload mirror: "owner;current;id,id,..." (hex owner, decimal ids) ──
private static void Persist()
{
try
{
var sb = new StringBuilder();
sb.Append(_owner.ToString("X8", CultureInfo.InvariantCulture)).Append(';')
.Append(_current.ToString(CultureInfo.InvariantCulture)).Append(';');
for (int i = 0; i < _titles!.Count; i++)
{
if (i > 0) sb.Append(',');
sb.Append(_titles[i].ToString(CultureInfo.InvariantCulture));
}
Environment.SetEnvironmentVariable(EnvName, sb.ToString());
}
catch { }
}
private static void RestoreOnce()
{
if (_restored) return;
_restored = true;
try
{
if (TryParseMirror(Environment.GetEnvironmentVariable(EnvName), out uint owner, out uint current, out List<uint> titles))
{
_owner = owner;
_current = current;
_titles = titles;
_seq++;
}
}
catch { }
}
internal static bool TryParseMirror(string? s, out uint owner, out uint current, out List<uint> titles)
{
owner = 0;
current = 0;
titles = new List<uint>();
if (string.IsNullOrEmpty(s)) return false;
string[] parts = s.Split(';');
if (parts.Length != 3) return false;
if (!uint.TryParse(parts[0], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out owner)) return false;
if (!uint.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out current)) return false;
foreach (string p in parts[2].Split(',', StringSplitOptions.RemoveEmptyEntries))
{
if (!uint.TryParse(p, NumberStyles.None, CultureInfo.InvariantCulture, out uint id)) return false;
if (titles.Count < MaxTitles && !titles.Contains(id)) titles.Add(id);
}
return true;
}
}

View file

@ -18,6 +18,7 @@ internal static class ChatCallbackHooks
private const int PsRefBufferWideDataOffset = 20;
private const int MaxIncomingChatChars = 1024;
private const int MaxDataLineChars = 65536;
private const int IncomingChatAddTextToScrollVa = 0x005649F0;
private const int IncomingChatWrapperVa = 0x0058A000;
private const int OutgoingChatVa = 0x005821A0;
@ -70,6 +71,19 @@ internal static class ChatCallbackHooks
private static int _incomingChatSuppressionEnabled;
private static int _incomingCallCount;
// ── Held incoming chat (IncomingChatHold.cs) ─────────────────────────────
// AddTextToScroll lines wait for the plugins' verdict before AC prints them, so a
// line a plugin eats never reaches AC's chat window. Main-thread only, except the
// beats and the switch.
private static readonly HeldChatQueue _held = new();
private static readonly Action<HeldChatLine> _printHeld = PrintHeldLine;
private static bool _incomingByPattern; // AddTextToScroll itself was found by its pattern
private static bool _replayReady; // PStringBase<wchar_t> ctor/dtor/null buffer found by pattern
private static int _holdSwitch = 1; // /rc chathold on|off (not saved; on at every start)
private static long _drainBeatMs; // last AcMainThreadQueue.Drain on AC's main thread
private static int _eatLogCount;
[ThreadStatic] private static int _replayDepth; // inside our own print of a held line
// Captured live from the outgoing-chat detour so we can re-invoke AC's outgoing
// chat function DIRECTLY (deterministic) instead of simulating keystrokes into
// the native chat bar. Keystroke simulation depends on the bar's open/closed
@ -116,6 +130,9 @@ internal static class ChatCallbackHooks
{
incomingVerified = true;
incomingStatus = $"0x{_incomingAddress.ToInt32():X8} ({incomingMode})";
if (_originalIncomingChatAddTextPtr != IntPtr.Zero)
_replayReady = _incomingByPattern && TryPrepareReplay(textSection);
RynthLog.Compat($"Compat: incoming chat hold {(_replayReady ? "ready" : "unavailable (lines print before plugins hear them, as before)")}.");
}
if (EnableOutgoingHook && !OutgoingInstalled)
@ -237,6 +254,7 @@ internal static class ChatCallbackHooks
unsafe
{
_incomingAddress = resolved.Address;
_incomingByPattern = resolved.Source == HookResolver.ResolveSource.PatternScan;
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int> pDetour = &IncomingChatAddTextDetour;
MinHook.Hook(_incomingAddress, (IntPtr)pDetour, out _originalIncomingChatAddTextPtr);
}
@ -277,23 +295,199 @@ internal static class ChatCallbackHooks
private static unsafe int IncomingChatAddTextDetour(IntPtr thisPtr, IntPtr text, uint chatType, uint unknown, IntPtr stringInfo)
{
RecursionGuard.Tick("ChatCallbackHooks.IncomingChatAddText");
// 1. Read string BEFORE original — buffer may be freed after
string? line = (text != IntPtr.Zero) ? ReadIncomingChatLine(text, chatType) : null;
// 2. Call original
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int>)_originalIncomingChatAddTextPtr;
// 1. Read string BEFORE original — buffer may be freed after
bool truncated = false;
string? raw = (text != IntPtr.Zero) ? ReadIncomingChatRaw(text, chatType, out truncated) : null;
string? line = raw?.TrimEnd('\r', '\n');
// 1b. The engine's own server-data replies (Aelrynth /mastery-data it asked for):
// not drawn, not held and not passed on. Every caller of AddTextToScroll ignores its
// return value (all 394 call sites in the retail client, checked 2026-10-01).
// Not inside our own reprint of a held line: that line was already offered here when
// it first arrived (and wasn't ours, or it wouldn't have been held), so offering it
// again could take a stale line for the answer to a request sent since.
if (line != null && _replayDepth == 0 && EatOwnReply(line))
return 0;
// 2. Hold the line until the plugins have heard it (IncomingChatHold.cs): AC prints it
// from the next main-thread drain unless a plugin eats it. Anything unexpected here
// falls through to the old path: print now, plugins hear it afterwards.
ChatHoldDecision decision = ChatHoldDecision.PassThrough;
bool handedOver = false; // QueueChatWindowText already saw the line (engine HUD feed and plugins)
try
{
decision = DecideHold(raw, truncated, stringInfo);
if (decision == ChatHoldDecision.Hold)
{
var held = new HeldChatLine(raw!, chatType, unknown, thisPtr, Environment.TickCount64);
handedOver = true;
if (PluginManager.QueueChatWindowText(line, chatType, held))
{
_held.Add(held);
return 1; // what AddTextToScroll returns for a line it handled
}
decision = ChatHoldDecision.FlushThenPassThrough; // plugins aren't taking chat right now
}
if (decision == ChatHoldDecision.FlushThenPassThrough)
ReleaseHeld(flushAll: true);
}
catch
{
// Fall through and print. (If the line was handed over, it isn't handed over twice.)
}
// 3. Call original
int result = pOriginal(thisPtr, text, chatType, unknown, stringInfo);
// 3. Queue AFTER original returns — game state is consistent
if (line != null)
// 4. Queue AFTER original returns — game state is consistent
if (line != null && !handedOver)
QueueIncomingChatLine(line, chatType);
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static string? ReadIncomingChatLine(IntPtr pStringBase, uint chatType)
private static bool EatOwnReply(string line)
{
try { return MasteryFeed.OnIncomingLine(line); }
catch { return false; }
}
/// <summary>Hold this line, print it now, or print everything held and then it. AC's main thread or not.</summary>
private static ChatHoldDecision DecideHold(string? raw, bool truncated, IntPtr stringInfo)
{
bool onMain = MainThreadGuard.IsOnMainThread();
bool replaying = _replayDepth > 0;
// Lines whose verdict is in print first, so a line printed now keeps its place after them.
if (onMain && !replaying && _held.Count > 0)
ReleaseHeld(flushAll: false);
var inputs = new ChatHoldInputs(
Enabled: HoldActive,
Disarmed: AcMainThreadQueue.IsDisarmed,
OnMainThread: onMain,
Replaying: replaying,
HasText: !string.IsNullOrEmpty(raw),
Truncated: truncated,
HasStringInfo: stringInfo != IntPtr.Zero,
NowMs: Environment.TickCount64,
PumpBeatMs: PluginManager.ChatPumpBeatMs,
DrainBeatMs: Volatile.Read(ref _drainBeatMs),
HeldCount: _held.Count);
return HeldChatQueue.Decide(inputs);
}
private static bool HoldActive => _replayReady && Volatile.Read(ref _holdSwitch) != 0;
/// <summary>
/// Called by AcMainThreadQueue.Drain (Client::UseTime and EndScene, AC's main thread): the
/// beat that says held lines will be printed, then prints the ones that may print now.
/// After teardown starts it prints everything still held.
/// </summary>
internal static void OnMainThreadDrain(bool disarmed)
{
if (!MainThreadGuard.IsOnMainThread())
return;
if (!disarmed)
Volatile.Write(ref _drainBeatMs, Environment.TickCount64);
if (_held.Count == 0 || _replayDepth > 0)
return;
try { ReleaseHeld(flushAll: disarmed || !HoldActive); }
catch { }
}
/// <summary>Prints held lines that may print now (AC's main thread, never inside our own print).</summary>
private static void ReleaseHeld(bool flushAll)
{
long eatenBefore = _held.EatenTotal;
long lateBefore = _held.TimedOutTotal;
_held.Release(Environment.TickCount64, flushAll, _printHeld);
if (_held.EatenTotal != eatenBefore && _eatLogCount < 5)
{
_eatLogCount++;
RynthLog.Compat($"Compat: chat hold kept {_held.EatenTotal - eatenBefore} line(s) a plugin ate out of AC's chat window (total {_held.EatenTotal}).");
}
if (_held.TimedOutTotal != lateBefore && _held.TimedOutTotal <= 5)
RynthLog.Compat($"Compat: chat hold printed {_held.TimedOutTotal - lateBefore} line(s) without a plugin verdict after {HeldChatQueue.HoldTimeoutMs} ms (plugin pump slow; total {_held.TimedOutTotal}).");
}
/// <summary>Prints one held line through AC's own AddTextToScroll, exactly as it came in.</summary>
private static unsafe void PrintHeldLine(HeldChatLine h)
{
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int>)_originalIncomingChatAddTextPtr;
_replayDepth++;
try
{
fixed (char* chars = h.Raw) // .NET strings end in a NUL, as the PStringBase ctor needs
{
var wide = OutgoingWidePString.Create((ushort*)chars);
try
{
// StringInfo is always null here: lines that came with one are never held.
pOriginal(h.This, (IntPtr)(&wide), h.ChatType, h.Unknown, IntPtr.Zero);
}
finally { wide.Dispose(); }
}
}
finally { _replayDepth--; }
}
/// <summary>
/// Holding needs to build AC strings itself to print a held line: the PStringBase&lt;wchar_t&gt;
/// ctor, dtor and empty buffer, all found by pattern (never a guessed address).
/// </summary>
private static bool TryPrepareReplay(AcClientTextSection textSection)
{
try
{
var ctor = HookResolver.Resolve(textSection, "ChatCallback.PStringW_ctor", PatWidePStringCtor, 0x00402730);
var dtor = HookResolver.Resolve(textSection, "ChatCallback.PStringW_dtor", PatWidePStringDtor, 0x004011B0);
var nul = HookResolver.ResolveData(textSection, "ChatCallback.PStringW_NullBuffer", PatXrefWideNullBuffer, 2, 0x00818340);
if (ctor.Source != HookResolver.ResolveSource.PatternScan
|| dtor.Source != HookResolver.ResolveSource.PatternScan
|| nul.Source != HookResolver.ResolveSource.PatternScan)
return false;
// Resolve OutgoingWidePString's statics now, not on AC's thread at the first held line.
return OutgoingWidePString.Warm();
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: chat hold setup failed - {ex.GetType().Name}: {ex.Message}");
return false;
}
}
/// <summary>/rc chathold on|off.</summary>
internal static void SetHoldEnabled(bool on) => Volatile.Write(ref _holdSwitch, on ? 1 : 0);
internal static bool HoldSwitchOn => Volatile.Read(ref _holdSwitch) != 0;
/// <summary>One line for /rc chathold status.</summary>
internal static string HoldStatusText()
{
string state = !IncomingInstalled ? "unavailable (incoming chat isn't hooked; in Decal bridge mode Decal owns it)"
: !_replayReady ? "unavailable (the client's string functions weren't found, or another hook sits on AddTextToScroll)"
: HoldSwitchOn ? "ON" : "OFF";
return $"Chat hold is {state}. Since start: {_held.HeldTotal} held, {_held.ShownTotal} shown, " +
$"{_held.EatenTotal} eaten by plugins, {_held.TimedOutTotal} shown late (no verdict in {HeldChatQueue.HoldTimeoutMs} ms), " +
$"{_held.PrintFailedTotal} print errors; {_held.Count} waiting now.";
}
/// <summary>
/// Reads the line exactly as AC got it (line breaks kept). <paramref name="truncated"/> is
/// true when it is longer than <see cref="MaxIncomingChatChars"/>: plugins get the first
/// part, as before, but such a line is never held (it couldn't be printed back whole).
/// A server data line ("~ael1 ...") is read in full instead (up to
/// <see cref="MaxDataLineChars"/>) but still reports truncated, so it is never held either.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
private static string? ReadIncomingChatRaw(IntPtr pStringBase, uint chatType, out bool truncated)
{
truncated = false;
try
{
// PStringBase<ushort> is a 4-byte struct: a single pointer to
@ -311,16 +505,32 @@ internal static class ChatCallbackHooks
break;
length++;
}
// Lines this long are never held (chat-eat's limit, unchanged): they print at once
// and plugins hear them afterwards, as before. Set from the usual cap BEFORE the
// data-line read below, so a long data line read in full still counts as too long.
truncated = length >= MaxIncomingChatChars;
string? line = length > 0
? Marshal.PtrToStringUni(charData, length)?.TrimEnd('\r', '\n')
: null;
// A server data line ("~ael1 {json}", one line for every skill) runs past the
// usual cap: read it to its terminator, up to 64K characters.
if (length == MaxIncomingChatChars
&& MasteryWire.IsDataLine(Marshal.PtrToStringUni(charData, 40)))
{
while (length < MaxDataLineChars)
{
short ch = Marshal.ReadInt16(charData, length * 2);
if (ch == 0)
break;
length++;
}
}
string? raw = length > 0 ? Marshal.PtrToStringUni(charData, length) : null;
int count = Interlocked.Increment(ref _incomingCallCount);
if (count <= 0)
RynthLog.Verbose($"Compat: incoming chat #{count} type={chatType} len={length}");
return line;
return raw;
}
catch { return null; }
}
@ -642,6 +852,17 @@ internal static class ChatCallbackHooks
return value;
}
/// <summary>From a NUL-terminated buffer the caller keeps pinned for the call.</summary>
public static OutgoingWidePString Create(ushort* chars)
{
var value = new OutgoingWidePString { CharBuffer = Marshal.ReadIntPtr(NullWideBufferVa) };
Ctor(&value, chars);
return value;
}
/// <summary>Runs the static resolution now; true when all three addresses are set.</summary>
public static bool Warm() => NullWideBufferVa != IntPtr.Zero && Ctor != null && Dtor != null;
public void Dispose()
{
fixed (OutgoingWidePString* ptr = &this)

View file

@ -211,6 +211,35 @@ internal static unsafe class ChatCommandDispatcher
}
}
/// <summary>
/// Sends a server command quietly: Talk text that starts with '@', which ACE runs as
/// a command (GameActionTalk) exactly as it runs a typed "/command" the client
/// forwards. Straight to CM_Communication::Event_Talk: no plugin pre-dispatch, no
/// chat-bar keystrokes, nothing said aloud. Printable ASCII only. AC's main thread
/// only (the Aelrynth mastery feed calls it from MainThreadSnapshots.Tick); refuses
/// anywhere else rather than queueing.
/// </summary>
public static bool SendServerCommand(string atCommand)
{
if (!MainThreadGuard.IsOnMainThread())
return false;
if (string.IsNullOrEmpty(atCommand) || atCommand.Length < 2 || atCommand[0] != '@' || atCommand.Length > 200)
return false;
foreach (char c in atCommand)
if (c < 0x20 || c > 0x7E)
return false;
try
{
LogoffOriginProbe.RecordChat("ServerCommand", atCommand);
return DispatchSay(atCommand);
}
catch (Exception ex)
{
RynthLog.Compat($"ChatDispatch: server command '{atCommand}' failed - {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static string ExpandShorthand(string text)
{
if (StartsWithCmd(text, "/s ")) return "/say " + text.Substring(3);
@ -310,6 +339,11 @@ internal static unsafe class ChatCommandDispatcher
/// </summary>
private static bool DispatchRaw(string command)
{
// Decal bridge mode: AC's outgoing-chat function belongs to Decal (our hook is not
// installed) and there is no window subclass for keystrokes, so the line goes to
// Decal's InvokeChatParser, which the bridge runs on AC's main thread.
if (DecalBridgeHost.Active)
return DecalBridgeHost.TryInvokeChatParser(command);
if (ChatCallbackHooks.TryDispatchDirect(command))
return true;
return SimulateChatInput(command);

View file

@ -41,10 +41,15 @@ internal static class ChatFileDispatcher
private const int DebounceMs = 200;
public static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"dispatch.txt");
// RYNTHCORE_DISPATCH_FILE gives a test client its own file: the default one is
// watched by every running client.
public static string FilePath =>
Environment.GetEnvironmentVariable("RYNTHCORE_DISPATCH_FILE") is { Length: > 0 } overridePath
? overridePath
: Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"dispatch.txt");
public static void Start()
{

View file

@ -52,6 +52,11 @@ internal static class ChatHooks
private static ListenToElementMessageDelegate? _listenDetour;
private static IntPtr _gmMainChatInstance;
private static IntPtr _gmMainChatVtable; // the instance's vtable when captured
// Set when a logoff is requested, cleared when the logout completes: AC frees
// the chatbox during the logoff, and ListenToElementMessage can still fire on
// the dying one, so it is not captured again in between.
private static volatile bool _logoffInProgress;
private static IntPtr _uiElementSetVisibleAddress;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
@ -123,8 +128,11 @@ internal static class ChatHooks
private static void ListenDetour(IntPtr thisPtr, IntPtr msgInfo)
{
RecursionGuard.Tick("ChatHooks.Listen");
if (thisPtr != IntPtr.Zero)
if (thisPtr != IntPtr.Zero && !_logoffInProgress && thisPtr != _gmMainChatInstance)
{
_gmMainChatVtable = ClientObjectHooks.IsReadablePointer(thisPtr) ? Marshal.ReadIntPtr(thisPtr) : IntPtr.Zero;
_gmMainChatInstance = thisPtr;
}
if (++_listenFires <= 3)
RynthLog.Compat($"ChatHooks: Listen fired #{_listenFires} this=0x{thisPtr.ToInt32():X8}");
try { _originalListen!(thisPtr, msgInfo); }
@ -145,6 +153,12 @@ internal static class ChatHooks
IntPtr inst = _gmMainChatInstance;
if (inst == IntPtr.Zero) return;
if (_uiElementSetVisibleAddress == IntPtr.Zero) return;
if (!StillAlive(inst))
{
RynthLog.Compat($"ChatHooks: chatbox 0x{inst.ToInt32():X8} is gone (freed); dropped until it is captured again.");
_gmMainChatInstance = IntPtr.Zero;
return;
}
if (RynthChatOwnsChat)
{
@ -168,9 +182,40 @@ internal static class ChatHooks
}
}
/// <summary>
/// Second guard against a freed chatbox: its memory must still be readable
/// and still start with the vtable it had when captured. (A freed object's
/// first bytes are overwritten by the heap; the 2026-09-28 14:41 crash called
/// SetVisible on one and jumped to 0x0000FFFF.)
/// </summary>
private static bool StillAlive(IntPtr inst)
{
if (!ClientObjectHooks.IsReadablePointer(inst)) return false;
IntPtr vtable = Marshal.ReadIntPtr(inst);
if (_gmMainChatVtable == IntPtr.Zero) _gmMainChatVtable = vtable;
return vtable == _gmMainChatVtable;
}
/// <summary>
/// A logoff was requested (LogoffOriginProbe): drop the chatbox now. The logout
/// notice (ResetCachedInstance) comes after AC has already freed it, and the
/// per-frame SetVisible in between crashed on the freed object (2026-09-28).
/// AC's main thread.
/// </summary>
public static void OnLogoffRequested()
{
_logoffInProgress = true;
_gmMainChatInstance = IntPtr.Zero;
_gmMainChatVtable = IntPtr.Zero;
_isHiddenAsserted = true;
}
/// <summary>The logout completed (PluginManager's logout dispatch): the next chatbox is a new one.</summary>
public static void ResetCachedInstance()
{
_gmMainChatInstance = IntPtr.Zero;
_gmMainChatVtable = IntPtr.Zero;
_logoffInProgress = false;
_isHiddenAsserted = true; // re-assert on the next instance, as at start-up
}
}

View file

@ -0,0 +1,572 @@
// ============================================================================
// RynthCore.Engine - Compatibility/ClientActionGates.cs
//
// The acclient's own item-action gates, which lock the player out of using,
// equipping and moving items while chat, clicks and the inventory still work.
//
// Every item action the client makes (double-click use, equip, drag to a pack,
// pick up, drop, give, split, merge, vendor buy/sell) first asks
// ACCWeenieObject::IsPlayerReadyToMakeInventoryRequest. That refuses when
// either of two globals is set, and prints a line in chat:
//
// 1. The PENDING INVENTORY REQUEST slot (4 dwords in .data, 0x00871ED0..DC on
// the 4,841,472-byte client): request type, object id and the time it was
// sent. ACCWeenieObject::RecordRequest (and the UIAttempt* callers, inline)
// fill it when the client sends an inventory request. Only the server's
// answer ABOUT THAT SAME OBJECT empties it: ServerSaysMoveItem,
// ServerSaysSetStackSize, ServerSaysAttemptFailed (0x00A0), the ground
// container view/close (RecordResponse) or the vendor list re-send. Those
// are ACCWeenieObject methods, so when the object is no longer in the
// client's object table (the corpse decayed, a later corpse open queued the
// previous corpse's contents for destruction, a stack merged away) the
// answer finds nothing and the slot is never emptied. The time field is
// written and never read: there is no timeout. Logging off does not empty
// it either, and CPlayerSystem::LogOffCharacter/UseTime wait for it, so the
// logoff sits at "Logging off..." forever. Refusal text:
// "You can only move or use one item at a time".
//
// 2. The ATTACKING flag (0x00871EE0): set by
// ClientCombatSystem::HandleCommenceAttackEvent (0x01B8), cleared only by
// HandleAttackDoneEvent (0x01A7). A lost AttackDone leaves it set for the
// rest of the process. Refusal text:
// "You cannot move or use an item while attacking".
//
// Neither is the busy count (ClientUISystem m_cBusy): AC only reads m_cBusy to
// pick the cursor (UpdateCursorState: != 0 shows the busy cursor), so a zeroed
// or negative count changes the cursor and nothing else. That is why every
// busy-count reset (/ra clearbusy, /ra panic, the watchdogs) left this lock
// in place.
//
// This file:
// * resolves both gates by pattern (two independent code sites each, which
// must agree, or the gate is left alone);
// * reads them for /rc actionstate and the heartbeat (read-only, any thread);
// * on AC's main thread, empties a pending request whose object has been
// gone from the client for MissingObjectGraceMs, or that has had no answer
// for PendingTimeoutMs, and clears an attacking flag that has stayed set
// with no AttackDone for AttackStaleMs. Emptying the slot is exactly what
// AC's own RecordResponse does when an answer arrives; a late real answer
// after that finds nothing pending and changes nothing;
// * does the same on demand for /rc unlockactions (latched when off-thread).
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class ClientActionGates
{
// ACCWeenieObject::RecordRequest(objectId, type) — the whole function:
// mov eax,[esp+4]; mov ecx,[esp+8]; mov edx,[TimerCurTime]; mov [reqObj],eax;
// mov eax,[TimerCurTime+4]; mov [reqType],ecx; mov [reqTime],edx; mov [reqTime+4],eax; ret
private static readonly byte?[] RecordRequestPattern =
[
0x8B, 0x44, 0x24, 0x04,
0x8B, 0x4C, 0x24, 0x08,
0x8B, 0x15, null, null, null, null, // +10 TimerCurTime (low dword)
0xA3, null, null, null, null, // +15 reqObj
0xA1, null, null, null, null, // +20 TimerCurTime (high dword)
0x89, 0x0D, null, null, null, null, // +26 reqType
0x89, 0x15, null, null, null, null, // +32 reqTime (low)
0xA3, null, null, null, null, // +37 reqTime (high)
0xC3
];
// ACCWeenieObject::RecordResponse(objectId) — clears the slot when the id matches:
// mov eax,[esp+4]; cmp eax,[reqObj]; jne +16h; xor eax,eax;
// mov [reqObj],eax; mov [reqType],eax; mov [reqTime],eax; mov [reqTime+4],eax; ret
private static readonly byte?[] RecordResponsePattern =
[
0x8B, 0x44, 0x24, 0x04,
0x3B, 0x05, null, null, null, null, // +6 reqObj
0x75, 0x16,
0x33, 0xC0,
0xA3, null, null, null, null, // +15 reqObj
0xA3, null, null, null, null, // +20 reqType
0xA3, null, null, null, null, // +25 reqTime (low)
0xA3, null, null, null, null, // +30 reqTime (high)
0xC3
];
// ClientCombatSystem::HandleAttackDoneEvent: mov [esi+3C],bl; cmp [esp+0C],ebx;
// mov [esi+3D],bl; mov [attacking],ebx
private static readonly byte?[] AttackDonePattern =
[
0x88, 0x5E, 0x3C, 0x39, 0x5C, 0x24, 0x0C, 0x88, 0x5E, 0x3D,
0x89, 0x1D, null, null, null, null // +12 attacking
];
// ClientCombatSystem::HandleCommenceAttackEvent tail: mov [attacking],1;
// call GetUISystem; mov ecx,eax; pop esi; add esp,4; jmp IncrementBusyCount
private static readonly byte?[] CommenceAttackPattern =
[
0xC7, 0x05, null, null, null, null, // +2 attacking
0x01, 0x00, 0x00, 0x00,
0xE8, null, null, null, null,
0x8B, 0xC8, 0x5E, 0x83, 0xC4, 0x04, 0xE9
];
// Resolved addresses (0 = not resolved; the gate is then read-only-unavailable).
private static int _reqTypeVa, _reqObjVa, _reqTimeVa, _timerVa, _attackVa;
private static bool _requestReady, _attackReady, _initialized;
private static string _status = "Not initialized.";
// Repair policy. A normal request is answered within a network round trip
// (a ground pickup adds the walk to the item); a single attack swing lasts a
// few seconds and every AttackDone empties the flag between swings. CheckWatchdog
// runs before every inbound game event and after every game tick, so the
// flag's zero window between AttackDone and the next CommenceAttack is always
// sampled at least once.
// 10 s (was 60): a real answer comes within about a second, and with healing interrupting
// melee/looting (2026.10.4.2) a lost answer locked every item action for a full minute.
private const long PendingTimeoutMs = 10_000;
private const long MissingObjectGraceMs = 5_000;
// 12 s in melee/missile (was 30); outside them no attack can be running, so 1.5 s.
private const long AttackStaleMs = 12_000;
private const long AttackStaleOutOfStanceMs = 1_500;
private const long PendingCheckIntervalMs = 500;
private const long ChatNoticeCooldownMs = 10 * 60_000;
// Main-thread tracking state.
private static long _trackedKey;
private static long _pendingSeenAt;
private static long _objectMissingSince;
private static long _lastPendingCheck;
private static long _attackSetSince;
private static long _lastChatNoticeAt = long.MinValue / 2;
private static long _pendingClears;
private static long _attackClears;
private static int _unlockRequested;
public static bool IsRequestGateAvailable => _requestReady;
public static bool IsAttackGateAvailable => _attackReady;
public static string StatusMessage => _status;
public static long PendingClearCount => Interlocked.Read(ref _pendingClears);
public static long AttackClearCount => Interlocked.Read(ref _attackClears);
public static void Initialize()
{
if (_initialized)
return;
_initialized = true;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
_status = "acclient .text not readable.";
RynthLog.Compat($"ClientActionGates: {_status}");
return;
}
string req = ResolveRequestSlot(text);
string atk = ResolveAttackFlag(text);
_status = $"request slot: {req}; attack flag: {atk}.";
RynthLog.Compat($"ClientActionGates: {_status}");
}
private static string ResolveRequestSlot(AcClientTextSection text)
{
if (!TryFindUnique(text, RecordRequestPattern, out int a))
return "RecordRequest pattern not found (unique)";
if (!TryFindUnique(text, RecordResponsePattern, out int b))
return "RecordResponse pattern not found (unique)";
byte[] t = text.Bytes;
int obj = BitConverter.ToInt32(t, a + 15);
int type = BitConverter.ToInt32(t, a + 26);
int time = BitConverter.ToInt32(t, a + 32);
int timeHi = BitConverter.ToInt32(t, a + 37);
int timerLo = BitConverter.ToInt32(t, a + 10);
int timerHi = BitConverter.ToInt32(t, a + 20);
bool consistent =
type == obj - 4 && time == obj + 4 && timeHi == obj + 8 && timerHi == timerLo + 4
&& BitConverter.ToInt32(t, b + 6) == obj && BitConverter.ToInt32(t, b + 15) == obj
&& BitConverter.ToInt32(t, b + 20) == type && BitConverter.ToInt32(t, b + 25) == time
&& BitConverter.ToInt32(t, b + 30) == timeHi;
if (!consistent)
return $"code sites disagree (obj=0x{obj:X8} type=0x{type:X8})";
if (!ClientObjectHooks.IsWritablePointer(new IntPtr(type))
|| !ClientObjectHooks.IsWritablePointer(new IntPtr(timeHi))
|| !ClientObjectHooks.IsReadablePointer(new IntPtr(timerLo)))
return $"globals not mapped (type=0x{type:X8})";
_reqTypeVa = type;
_reqObjVa = obj;
_reqTimeVa = time;
_timerVa = timerLo;
_requestReady = true;
return $"0x{type:X8} (type) / 0x{obj:X8} (object)";
}
private static string ResolveAttackFlag(AcClientTextSection text)
{
if (!TryFindUnique(text, AttackDonePattern, out int a))
return "HandleAttackDoneEvent pattern not found (unique)";
if (!TryFindUnique(text, CommenceAttackPattern, out int b))
return "HandleCommenceAttackEvent pattern not found (unique)";
int flagA = BitConverter.ToInt32(text.Bytes, a + 12);
int flagB = BitConverter.ToInt32(text.Bytes, b + 2);
if (flagA != flagB)
return $"code sites disagree (0x{flagA:X8} vs 0x{flagB:X8})";
if (!ClientObjectHooks.IsWritablePointer(new IntPtr(flagA)))
return $"global 0x{flagA:X8} not mapped";
_attackVa = flagA;
_attackReady = true;
return $"0x{flagA:X8}";
}
private static bool TryFindUnique(AcClientTextSection text, byte?[] pattern, out int offset)
{
offset = PatternScanner.FindPattern(text.Bytes, pattern);
if (offset < 0)
return false;
return PatternScanner.FindPatternInRegion(text.Bytes, pattern, offset + 1, text.Bytes.Length) < 0;
}
// ── Reads (any thread: plain loads from acclient .data, which never unmaps) ──
public static bool TryReadPending(out uint type, out uint objectId, out double ageSeconds)
{
type = 0;
objectId = 0;
ageSeconds = -1;
if (!_requestReady)
return false;
type = unchecked((uint)Marshal.ReadInt32(new IntPtr(_reqTypeVa)));
objectId = unchecked((uint)Marshal.ReadInt32(new IntPtr(_reqObjVa)));
double issued = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(new IntPtr(_reqTimeVa)));
double now = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(new IntPtr(_timerVa)));
if (type != 0 && issued > 0 && now >= issued && now - issued < 1e7)
ageSeconds = now - issued;
return true;
}
public static bool TryReadAttacking(out bool attacking)
{
attacking = false;
if (!_attackReady)
return false;
attacking = Marshal.ReadInt32(new IntPtr(_attackVa)) != 0;
return true;
}
public static string RequestTypeName(uint type) => type switch
{
0 => "none",
1 => "merge",
2 => "split",
3 => "move",
4 => "pick up",
5 => "put in container",
6 => "drop",
7 => "wield",
9 => "give",
10 => "vendor buy/sell",
_ => $"request {type}",
};
/// <summary>Short heartbeat field, empty when both gates are open.</summary>
public static string HeartbeatField()
{
try
{
string s = string.Empty;
if (TryReadPending(out uint type, out _, out double age) && type != 0)
s = age >= 0 ? $" req={type}/{age:0}s" : $" req={type}";
if (TryReadAttacking(out bool attacking) && attacking)
s += " atk=1";
return s;
}
catch { return string.Empty; }
}
// ── Main-thread watchdog ─────────────────────────────────────────────────
/// <summary>Drop the tracking state at logout / client close (the slot itself is AC's).</summary>
public static void ResetTracking()
{
_trackedKey = 0;
_pendingSeenAt = 0;
_objectMissingSince = 0;
_attackSetSince = 0;
}
/// <summary>
/// Called from BusyCountHooks.CheckWatchdog on every game tick and before every
/// inbound game event. Main thread only; any other thread returns at once.
/// </summary>
public static void Tick(long now, bool inWorldTransition)
{
if (!MainThreadGuard.IsOnMainThread())
return;
if (Interlocked.Exchange(ref _unlockRequested, 0) == 1)
{
foreach (string line in UnlockNow("manual (/rc unlockactions)"))
RynthLog.Compat($"ClientActionGates: {line}");
}
TickAttackFlag(now, inWorldTransition);
if (now - _lastPendingCheck < PendingCheckIntervalMs)
return;
_lastPendingCheck = now;
TickPendingRequest(now, inWorldTransition);
}
private static void TickAttackFlag(long now, bool inWorldTransition)
{
if (!_attackReady)
return;
bool attacking = Marshal.ReadInt32(new IntPtr(_attackVa)) != 0;
if (!attacking || inWorldTransition)
{
_attackSetSince = 0;
return;
}
if (_attackSetSince == 0)
{
_attackSetSince = now;
return;
}
// Peace or Magic mode (kits, looting, casting happen here): no melee/missile attack
// can be in progress, so a set flag is a lost AttackDone. Clear it quickly.
int mode = CombatModeHooks.ReadCurrentCombatMode();
bool attackStance = mode == CombatActionHooks.CombatModeMelee || mode == CombatActionHooks.CombatModeMissile;
if (now - _attackSetSince < (attackStance ? AttackStaleMs : AttackStaleOutOfStanceMs))
return;
long heldMs = now - _attackSetSince;
_attackSetSince = 0;
if (ClearAttackFlag())
{
RynthLog.Compat($"ClientActionGates: attacking flag held {heldMs / 1000}s with no AttackDone — cleared. AC was refusing every item use/move ('while attacking').");
NotifyChat("Item actions were locked (the client never got the end of an attack). Unlocked.");
}
}
private static void TickPendingRequest(long now, bool inWorldTransition)
{
if (!_requestReady)
return;
TryReadPending(out uint type, out uint objectId, out double acAge);
if (type == 0)
{
_trackedKey = 0;
_objectMissingSince = 0;
return;
}
long issuedBits = Marshal.ReadInt64(new IntPtr(_reqTimeVa));
long key = unchecked(((long)type << 56) ^ ((long)objectId << 24) ^ issuedBits);
if (key != _trackedKey || _pendingSeenAt == 0)
{
_trackedKey = key;
_pendingSeenAt = now;
_objectMissingSince = 0;
}
// Portal / death: objects leave and re-enter the client wholesale and
// answers can arrive after the world settles. Judge afresh afterwards.
if (inWorldTransition)
{
_pendingSeenAt = now;
_objectMissingSince = 0;
return;
}
string? reason = null;
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
bool exists = objectId != 0 && ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out _);
if (exists)
_objectMissingSince = 0;
else if (_objectMissingSince == 0)
_objectMissingSince = now;
else if (now - _objectMissingSince >= MissingObjectGraceMs)
reason = "its object is no longer in the client, so no answer can clear it";
}
if (reason == null && now - _pendingSeenAt >= PendingTimeoutMs)
reason = $"no answer for {(now - _pendingSeenAt) / 1000}s";
if (reason == null)
return;
if (ClearPendingRequest())
{
RynthLog.Compat(
$"ClientActionGates: cleared a stuck item request — {RequestTypeName(type)} (type {type}) on 0x{objectId:X8}" +
$"{(acAge >= 0 ? $", sent {acAge:0}s ago" : string.Empty)}: {reason}. AC was refusing every item use/move/equip ('one item at a time').");
NotifyChat("Item actions were locked (the client was still waiting on an old item request). Unlocked.");
}
_trackedKey = 0;
_objectMissingSince = 0;
}
private static void NotifyChat(string text)
{
// Called from the main-thread watchdog only; the chat line itself is
// written by the queue's drain.
if (!MainThreadGuard.IsOnMainThread())
return;
long now = Environment.TickCount64;
if (now - _lastChatNoticeAt < ChatNoticeCooldownMs)
return;
_lastChatNoticeAt = now;
AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, 1);
}
/// <summary>
/// Empty AC's pending-inventory-request slot, the same four stores
/// RecordResponse makes when the server answers. Main thread only.
/// </summary>
private static bool ClearPendingRequest()
{
if (!MainThreadGuard.IsOnMainThread() || !_requestReady)
return false;
Marshal.WriteInt32(new IntPtr(_reqObjVa), 0);
Marshal.WriteInt32(new IntPtr(_reqTypeVa), 0);
Marshal.WriteInt32(new IntPtr(_reqTimeVa), 0);
Marshal.WriteInt32(new IntPtr(_reqTimeVa + 4), 0);
Interlocked.Increment(ref _pendingClears);
return true;
}
/// <summary>Clear AC's attacking flag, as HandleAttackDoneEvent does. Main thread only.</summary>
private static bool ClearAttackFlag()
{
if (!MainThreadGuard.IsOnMainThread() || !_attackReady)
return false;
Marshal.WriteInt32(new IntPtr(_attackVa), 0);
Interlocked.Increment(ref _attackClears);
return true;
}
/// <summary>
/// /rc unlockactions: open both gates now and repair a negative busy count.
/// On AC's main thread it runs at once and returns what it did; elsewhere it
/// latches for the next watchdog tick and says so.
/// </summary>
public static string[] RequestUnlock()
{
if (!MainThreadGuard.IsOnMainThread())
{
Interlocked.Exchange(ref _unlockRequested, 1);
return ["Unlock queued for the next game tick."];
}
return UnlockNow("manual (/rc unlockactions)");
}
private static string[] UnlockNow(string why)
{
if (!MainThreadGuard.IsOnMainThread())
return ["Unlock skipped: not on the game thread."];
var done = new System.Collections.Generic.List<string>();
if (TryReadPending(out uint type, out uint objectId, out double age) && type != 0)
{
if (ClearPendingRequest())
done.Add($"cleared the pending item request ({RequestTypeName(type)} on 0x{objectId:X8}{(age >= 0 ? $", {age:0}s old" : string.Empty)})");
}
if (TryReadAttacking(out bool attacking) && attacking)
{
if (ClearAttackFlag())
done.Add("cleared the attacking flag");
}
if (BusyCountHooks.RepairNegativeBusy(out int was))
done.Add($"reset a negative busy count ({was} -> 0)");
ResetTracking();
string summary = done.Count == 0
? "Nothing to unlock: no pending item request, no attacking flag, busy count not negative."
: "Unlocked: " + string.Join("; ", done) + ".";
RynthLog.Compat($"ClientActionGates: {why}: {summary}");
return [summary];
}
// ── /rc actionstate ─────────────────────────────────────────────────────
public static string[] DescribeLines()
{
var lines = new System.Collections.Generic.List<string>();
lines.Add("Action state (what the client checks before a use, equip or move):");
// 1. Pending inventory request.
if (!_requestReady)
{
lines.Add($" Item request: unavailable ({_status})");
}
else
{
TryReadPending(out uint type, out uint objectId, out double age);
if (type == 0)
{
lines.Add(" Item request: none (open)");
}
else
{
string name = string.Empty;
bool exists = false;
if (MainThreadGuard.IsOnMainThread() && objectId != 0)
{
exists = ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out _);
if (exists) ClientObjectHooks.TryGetObjectName(objectId, out name);
}
lines.Add($" Item request: WAITING - {RequestTypeName(type)} (type {type}) on 0x{objectId:X8}" +
$"{(name.Length > 0 ? $" '{name}'" : string.Empty)}" +
$"{(age >= 0 ? $", sent {age:0.0}s ago" : string.Empty)}, object {(exists ? "still in client" : "GONE from client")}.");
lines.Add(" While this is set the client refuses every use/equip/move ('You can only move or use one item at a time') and a logoff waits forever.");
}
}
// 2. Attacking flag.
if (!_attackReady)
lines.Add(" Attacking flag: unavailable");
else
{
TryReadAttacking(out bool attacking);
long held = _attackSetSince == 0 ? 0 : (Environment.TickCount64 - _attackSetSince) / 1000;
lines.Add(attacking
? $" Attacking flag: SET{(held > 0 ? $" ({held}s)" : string.Empty)} - item use/move refused ('while attacking') until the server's AttackDone."
: " Attacking flag: clear");
}
// 3. Busy count (cursor only).
string busy = BusyCountHooks.TryReadRealBusy(out int real) ? real.ToString() : "unreadable";
lines.Add($" Busy count m_cBusy: {busy} (engine shadow {BusyCountHooks.ShadowBusyCount}, pending reconcile {BusyCountHooks.PendingReconcileDelta}, force-clears {BusyCountHooks.ForceClearCount}, reconciles {BusyCountHooks.ReconcileCount}, negative repairs {BusyCountHooks.NegativeRepairCount}). Non-zero only shows the busy cursor.");
// 4. ClientUISystem: target mode / open container / vendor.
IntPtr ui = ClientHelperHooks.ReadUiSystemPtr();
if (ui != IntPtr.Zero && ClientObjectHooks.IsReadableSpan(ui, 0x40))
{
uint ground = unchecked((uint)Marshal.ReadInt32(ui + 0x18));
uint vendor = unchecked((uint)Marshal.ReadInt32(ui + 0x20));
int targetMode = Marshal.ReadInt32(ui + 0x2C);
string tm = targetMode switch { 0 => "none", 1 => "1 (use: pick an object)", 3 => "3 (choose a target for an item: next click is the target, Esc cancels)", _ => targetMode.ToString() };
lines.Add($" Target mode: {tm}; open container 0x{ground:X8}; vendor 0x{vendor:X8}");
}
else
{
lines.Add(" UI system: not available");
}
// 5. Combat system.
IntPtr combat = CombatModeHooks.ReadCombatSystemPtr();
if (combat != IntPtr.Zero && ClientObjectHooks.IsReadableSpan(combat, 0x48))
{
int mode = Marshal.ReadInt32(combat + 0x1C);
string modeName = mode switch { 1 => "NonCombat", 2 => "Melee", 4 => "Missile", 8 => "Magic", _ => mode.ToString() };
byte busyHeld = Marshal.ReadByte(combat + 0x3C);
byte inAttack = Marshal.ReadByte(combat + 0x3D);
byte autoRepeat = Marshal.ReadByte(combat + 0x44);
lines.Add($" Combat: mode {modeName}; attack holds busy {busyHeld}; attack in progress {inAttack}; auto-repeat {autoRepeat}");
}
lines.Add($" World transition (portal/death): {(PlayerLifecycleLog.InWorldTransition ? "yes" : "no")}; logged in: {(LoginLifecycleHooks.HasObservedLoginComplete ? "yes" : "no")}");
lines.Add($" Auto-unlocks this session: item request {PendingClearCount}, attacking flag {AttackClearCount}. Unlock now: /rc unlockactions");
return lines.ToArray();
}
}

View file

@ -165,6 +165,9 @@ internal static class ClientActionHooks
{
// Direct quaternion write — instant snap, most reliable (uses proven SmartBox offsets).
// Equivalent to old Decal Actions.Heading = value.
// 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;

View file

@ -1,5 +1,6 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
@ -212,10 +213,53 @@ internal static class ClientCombatHooks
if (_playerInReadyPosition == null || _getCombatSystem == null)
return false;
// Off AC's main thread (host IsPlayerReadyFn: RynthNet's login probe polls it
// every 2 s from the plugin pump): the value sampled on the main thread
// (<= ~200 ms old). ClientCombatSystem::PlayerInReadyPosition walks the
// player's motion state and the combat singleton, both freed and rebuilt
// around login / logout, exactly when this is polled.
if (!MainThreadGuard.IsOnMainThread())
return Volatile.Read(ref _readySnapshot) != 0;
bool ready = ReadPlayerReadyLive();
Volatile.Write(ref _readySnapshot, ready ? 1 : 0);
return ready;
}
// 1 = the main thread last saw the player in a ready position.
private static int _readySnapshot;
private static long _nextReadySampleMs;
private const int ReadySampleIntervalMs = 200;
/// <summary>
/// Main thread only (MainThreadSnapshots.Tick). Samples PlayerInReadyPosition for
/// off-thread IsPlayerReady callers, about five times a second. With no player
/// object (char-select, portal teardown) it publishes "not ready" without
/// calling into the combat system.
/// </summary>
internal static void SampleReady()
{
if (!MainThreadGuard.IsOnMainThread() || _playerInReadyPosition == null || _getCombatSystem == null)
return;
long now = Environment.TickCount64;
if (now < _nextReadySampleMs)
return;
_nextReadySampleMs = now + ReadySampleIntervalMs;
bool ready = ClientHelperHooks.GetPlayerId() != 0 && ReadPlayerReadyLive();
Volatile.Write(ref _readySnapshot, ready ? 1 : 0);
}
// MAIN THREAD ONLY.
private static bool ReadPlayerReadyLive()
{
if (!MainThreadGuard.IsOnMainThread() || _playerInReadyPosition == null || _getCombatSystem == null)
return false;
try
{
IntPtr cs = _getCombatSystem();
if (cs == IntPtr.Zero) return false;
if (!ClientObjectHooks.IsReadablePointer(cs)) return false;
return _playerInReadyPosition(cs, 1) != 0;
}
catch { return false; }
@ -257,5 +301,6 @@ internal static class ClientCombatHooks
_autoTarget = null;
_sendAttackHeightChanged = null;
_initialized = false;
Volatile.Write(ref _readySnapshot, 0);
}
}

View file

@ -66,10 +66,33 @@ internal static class ClientHelperHooks
// Byte-identical sibling of Event_StackableMerge (differs only in the action
// opcode immediate: give writes 0xCD, merge 0x54). Cdecl, returns bool.
// Chorizite map: 002ACA60 -> live VA 0x006ACA60. Sends the F7B1 give
// GameAction. amount = stack count to give (0 = whole object).
// Args (live-disasm + call-site UIAttemptGive confirmed): item, targetNpc, amount.
// GameAction. amount = stack count to give (ACE refuses amount <= 0).
// Args: TARGET FIRST, then the item, then amount. The function writes 0xCD, then
// [esp+0x1C], [esp+0x20], [esp+0x24] in that order, and ACE's GiveObjectRequest reads
// targetGuid, objectGuid, amount. Its one caller, ACCWeenieObject::UIAttemptGive
// (call at 0x0058E46F), pushes amount, this->id (the item, [esi+8]), then the target.
// (Re-checked 2026-10-01; the old delegate had the two ids swapped.)
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte EventGiveObjectRequestDelegate(uint objectId, uint targetId, int amount);
private delegate byte EventGiveObjectRequestDelegate(uint targetId, uint objectId, int amount);
// CM_Inventory::Event_GetAndWieldItem(ulong itemId, ulong equipMask) — the 0x001A
// GetAndWieldItem game action ("wield this item at these locations"). Same generated
// shape as its two siblings above (cdecl, returns bool), opcode immediate 0x1A.
// Chorizite map: 002AB950 -> live VA 0x006AC950 (the "FUN_006AC950" once mistaken for
// the merge helper, which is why that attempt tried to equip Pyreals). Arg order from
// the disassembly (itemId at [esp+0x1C], mask at [esp+0x20] after the prologue) and the
// one caller, ACCWeenieObject::UIAttemptWield @0x0058E3C0: push mask; push this->id.
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte EventGetAndWieldItemDelegate(uint objectId, uint equipMask);
// CM_Inventory::Event_DropItem(ulong itemId) — the 0x001B DropItem game action (put the
// item on the ground at the player's feet). Same generated shape as the three above
// (cdecl, returns bool) with one argument, so +0x08 after the first inner call and the
// 0x1B opcode as the last pattern byte. Chorizite map entrypoint 0x006AC880; its caller
// is ACCWeenieObject::UIAttemptPutIn3D (call at 0x0058E545). Arg: itemId at [esp+0x1C]
// after the prologue (sub esp,0Ch + three pushes).
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte EventDropItemDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void UseObjectDelegate(IntPtr clientUiSystem, uint objectId);
@ -105,6 +128,10 @@ internal static class ClientHelperHooks
private const int EventStackableMergeVa = 0x006ACDD0;
// CM_Inventory::Event_GiveObjectRequest — public give-to-NPC API (FALLBACK only; pattern-scanned).
private const int EventGiveObjectRequestVa = 0x006ACA60;
// CM_Inventory::Event_GetAndWieldItem — wield into a chosen slot (FALLBACK only; pattern-scanned).
private const int EventGetAndWieldItemVa = 0x006AC950;
// CM_Inventory::Event_DropItem — drop an item on the ground (FALLBACK only; pattern-scanned).
private const int EventDropItemVa = 0x006AC880;
private const int UseObjectVa = 0x00565750;
private const int PlayerSystemVa = 0x0087119C;
private const int InqPlayerCoordsVa = 0x00560E00;
@ -126,6 +153,8 @@ internal static class ClientHelperHooks
private static MoveItemInternalDelegate? _moveItemInternal;
private static EventStackableMergeDelegate? _eventStackableMerge;
private static EventGiveObjectRequestDelegate? _eventGiveObjectRequest;
private static EventGetAndWieldItemDelegate? _eventGetAndWieldItem;
private static EventDropItemDelegate? _eventDropItem;
private static InqPlayerCoordsDelegate? _inqPlayerCoords;
private static GetPlayerIdDelegate? _getPlayerId;
private static AddTextToScrollDelegate? _addTextToScroll;
@ -151,6 +180,8 @@ internal static class ClientHelperHooks
public static bool HasSplitStackInternal => _moveItemInternal != null;
public static bool HasMergeStackInternal => _eventStackableMerge != null;
public static bool HasGiveObjectTo => _eventGiveObjectRequest != null;
public static bool HasWieldItem => _eventGetAndWieldItem != null;
public static bool HasDropItem => _eventDropItem != null;
public static bool HasGetCurCoords => _inqPlayerCoords != null;
public static bool HasGetPlayerId => _getPlayerId != null;
public static bool HasGetGroundContainerId => true;
@ -178,7 +209,17 @@ internal static class ClientHelperHooks
// so do NOT trim it. Generated + verified unique (1 match @0x006ACA60) via
// pe_pattern.py GEN against both acclient copies.
private static readonly byte?[] PatEventGiveObjectRequest = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x10, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0xCD ];
private static readonly byte?[] PatInqPlayerCoords = [ 0x83, 0xEC, 0x10, 0x53, 0x8B, 0x5C, 0x24, 0x1C, 0x55, 0x56 ];
// CM_Inventory::Event_GetAndWieldItem @0x006AC950. Same template as the two above but with
// one fewer argument (so +0x0C, not +0x10, after the first inner call) and the 0x1A opcode
// as the last byte. Generated + verified unique (1 match @0x006AC950) via pe_pattern.py GEN
// against both acclient copies (C:\Turbine and C:\Games\RynthCore\AcClient).
private static readonly byte?[] PatEventGetAndWieldItem = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x1A ];
// CM_Inventory::Event_DropItem @0x006AC880. The same template again with one argument
// (+0x08 after the first inner call) and the 0x1B opcode as the last byte. Verified
// unique (1 match @0x006AC880) over the engine's scan window against both acclient
// copies (C:\Turbine and C:\Games\RynthCore\AcClient), 2026-09-30.
private static readonly byte?[] PatEventDropItem = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x1B ];
private static readonly byte?[] PatInqPlayerCoords =[ 0x83, 0xEC, 0x10, 0x53, 0x8B, 0x5C, 0x24, 0x1C, 0x55, 0x56 ];
private static readonly byte?[] PatGetPlayerId = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x85, 0xC0, 0x74, 0x07 ];
private static readonly byte?[] PatAddTextToScroll = [ 0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84 ];
private static readonly byte?[] PatUseWithTargetEvent = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x35 ];
@ -238,6 +279,8 @@ internal static class ClientHelperHooks
_moveItemInternal = Bind<MoveItemInternalDelegate>(text, "ClientHelper.MoveItemInternal", PatMoveItemInternal, MoveItemInternalVa);
_eventStackableMerge = Bind<EventStackableMergeDelegate>(text, "ClientHelper.Event_StackableMerge", PatEventStackableMerge, EventStackableMergeVa);
_eventGiveObjectRequest = Bind<EventGiveObjectRequestDelegate>(text, "ClientHelper.Event_GiveObjectRequest", PatEventGiveObjectRequest, EventGiveObjectRequestVa);
_eventGetAndWieldItem = Bind<EventGetAndWieldItemDelegate>(text, "ClientHelper.Event_GetAndWieldItem", PatEventGetAndWieldItem, EventGetAndWieldItemVa);
_eventDropItem = Bind<EventDropItemDelegate>(text, "ClientHelper.Event_DropItem", PatEventDropItem, EventDropItemVa);
_inqPlayerCoords = Bind<InqPlayerCoordsDelegate>(text, "ClientHelper.InqPlayerCoords", PatInqPlayerCoords, InqPlayerCoordsVa);
_getPlayerId = Bind<GetPlayerIdDelegate>(text, "ClientHelper.GetPlayerId", PatGetPlayerId, GetPlayerIdVa);
_addTextToScroll = Bind<AddTextToScrollDelegate>(text, "ClientHelper.AddTextToScroll", PatAddTextToScroll, AddTextToScrollVa);
@ -252,6 +295,12 @@ internal static class ClientHelperHooks
_totalStackAddr = HookResolver.ResolveData(text, "ClientHelper.total_stack", PatXrefTotalStack, 2, TotalStackVa).Address.ToInt32();
_playerSystemAddr = HookResolver.ResolveData(text, "ClientHelper.CPlayerSystem", PatXrefPlayerSystem, 2, PlayerSystemVa).Address.ToInt32();
_commSystemAddr = HookResolver.ResolveData(text, "ClientHelper.CommunicationSystem", PatXrefCommunicationSystem, 2, CommunicationSystemVa).Address.ToInt32();
// v72 player-to-player trade actions (CM_Trade / ClientTradeSystem).
try { PlayerTrade.Probe(text); }
catch (Exception ex) { RynthLog.Compat($"Compat: player trade binding failed - {ex.Message}"); }
// Skills panel raises (CM_Train senders).
try { PlayerTraining.Probe(text); }
catch (Exception ex) { RynthLog.Compat($"Compat: raise senders binding failed - {ex.Message}"); }
_initialized = true;
_statusMessage = "Ready.";
RynthLog.Verbose("Compat: helper hooks ready - validated select/state/chat helpers plus mapped interaction and inventory helpers.");
@ -300,6 +349,35 @@ internal static class ClientHelperHooks
}
}
/// <summary>
/// Click-to-select from an ImGui overlay (a Radar dot, a monster nameplate):
/// selects <paramref name="objectId"/> the way a click on it in the 3D world
/// does. The faces park the id with AcMainThreadQueue.EnqueueOverlaySelect;
/// its drain lands here on AC's main thread, where the checks run right
/// before the select: the client is in the world (logged in, no logout or
/// DB-cache teardown under way, not portaling) and the object still exists
/// (the client still resolves its weenie). Off-thread it marshals like
/// every other mutator. False when nothing was selected.
/// </summary>
public static bool SelectFromOverlay(uint objectId)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueOverlaySelect(objectId);
if (objectId == 0 || _setSelectedObject == null)
return false;
if (!LoginLifecycleHooks.HasObservedLoginComplete || LogoutLifecycleHooks.HasObservedLogout
|| DbCacheTeardownHooks.TeardownActive || TeleportStateHooks.IsPortaling || GetPlayerId() == 0)
return false;
if (!ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out _))
return false; // despawned / died / left range since the click
if (GetSelectedItemId() == objectId)
return true; // already the selection: nothing to redo
AcActionTrace.Record("OverlaySelect", objectId);
return SetSelectedObjectId(objectId);
}
public static uint GetSelectedItemId()
{
return ReadUInt32(_selectedIdAddr);
@ -593,7 +671,9 @@ internal static class ClientHelperHooks
/// CM_Inventory::Event_GiveObjectRequest (cdecl) at 0x006ACA60 — the F7B1 give
/// GameAction, the same path the drag-onto-NPC UI uses. This is the CORRECT
/// give-to-NPC primitive; MoveItemExternal is move-to-container and does not
/// give. amount=0 gives the whole object; positive = partial stack.
/// give. amount=0 gives the whole object; positive = partial stack. The wire needs a
/// real count (ACE answers "Give amount not valid!" to 0), so 0 is turned into the
/// item's stack size here (1 for a single item).
/// </summary>
public static bool GiveObjectTo(uint objectId, uint targetId, int amount = 0)
{
@ -610,7 +690,9 @@ internal static class ClientHelperHooks
try
{
byte rv = _eventGiveObjectRequest(objectId, targetId, amount);
if (amount == 0)
amount = WholeStackAmount(objectId);
byte rv = _eventGiveObjectRequest(targetId, objectId, amount);
RynthLog.Verbose($"Compat: Event_GiveObjectRequest item=0x{objectId:X8} -> target=0x{targetId:X8} amount={amount} rv={rv}");
return rv != 0;
}
@ -621,6 +703,79 @@ internal static class ClientHelperHooks
}
}
/// <summary>
/// The count that gives a whole object: its stack size, or 1 for a single item (or
/// when the item can't be read). Main thread (TryReadItemFields is false off it).
/// </summary>
internal static int WholeStackAmount(uint objectId) =>
ClientObjectHooks.TryReadItemFields(objectId, out ClientObjectHooks.ItemPwdFields f) && f.StackSize > 1
? (int)Math.Min(f.StackSize, int.MaxValue)
: 1;
/// <summary>
/// Wield an item into the given equip slot(s) through CM_Inventory::Event_GetAndWieldItem
/// (cdecl) at 0x006AC950 — the 0x001A GetAndWieldItem game action, the packet the
/// paperdoll drag sends (ACCWeenieObject::UIAttemptWield calls it). equipMask is an
/// EquipMask / INVENTORY_LOC value (e.g. 0x00100000 MeleeWeapon, 0x00200000 Shield,
/// 0x00400000 MissileWeapon, 0x01000000 Held, 0x02000000 TwoHanded; rings/bracelets
/// have a left and a right bit). The server checks the slot against the item's
/// ValidLocations and answers with the wield, or InventoryServerSaveFailed (0x00A0) plus
/// a WeenieError. Unlike UIAttemptWield this sends the packet only: no client busy count,
/// no pending-wield UI state — the same raw-send contract as GiveObjectTo.
/// </summary>
public static bool WieldItem(uint objectId, uint equipMask)
{
// Inventory sends run on AC's main thread, like MoveItemExternal / GiveObjectTo.
if (!MainThreadGuard.IsOnMainThread())
return _eventGetAndWieldItem != null && IsValidObjectId(objectId) && equipMask != 0
&& AcMainThreadQueue.EnqueueWieldItem(objectId, equipMask);
if (_eventGetAndWieldItem == null) return false;
if (!IsValidObjectId(objectId) || equipMask == 0) return false;
try
{
byte rv = _eventGetAndWieldItem(objectId, equipMask);
RynthLog.Verbose($"Compat: Event_GetAndWieldItem item=0x{objectId:X8} mask=0x{equipMask:X8} rv={rv}");
return rv != 0;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: Event_GetAndWieldItem threw - {ex.Message}");
return false;
}
}
/// <summary>
/// Drop an item on the ground through CM_Inventory::Event_DropItem (cdecl) at 0x006AC880,
/// the 0x001B DropItem game action that ACCWeenieObject::UIAttemptPutIn3D sends. The
/// server walks nothing (it drops at the player's feet) and answers with the item's new
/// place, or InventoryServerSaveFailed (0x00A0). Packet only, like WieldItem: no client
/// busy count, no pending-request UI state. Used by the Inventory panel.
/// </summary>
public static bool DropItem(uint objectId)
{
// Inventory sends run on AC's main thread, like WieldItem / GiveObjectTo.
if (!MainThreadGuard.IsOnMainThread())
return _eventDropItem != null && IsValidObjectId(objectId)
&& AcMainThreadQueue.EnqueueDropItem(objectId);
if (_eventDropItem == null) return false;
if (!IsValidObjectId(objectId)) return false;
try
{
byte rv = _eventDropItem(objectId);
RynthLog.Verbose($"Compat: Event_DropItem item=0x{objectId:X8} rv={rv}");
return rv != 0;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: Event_DropItem threw - {ex.Message}");
return false;
}
}
public static bool TryGetCurCoords(out double northSouth, out double eastWest)
{
northSouth = 0;
@ -629,6 +784,15 @@ internal static class ClientHelperHooks
if (_inqPlayerCoords == null)
return false;
// Off AC's main thread: no coords. The only caller (PluginManager.GetCurCoords,
// on the plugin pump) reaches this as the fallback when the raw SmartBox pose
// read fails, i.e. during login/portal/logout while AC's player state is
// changing. Calling CPlayerSystem::InqPlayerCoords there runs AC code
// off-thread and try/catch cannot stop a native AV. Plugins already handle
// "no coords", and InqPlayerCoords only returns cached data anyway.
if (!MainThreadGuard.IsOnMainThread())
return false;
try
{
IntPtr playerSystem = ReadPointer(_playerSystemAddr);
@ -653,14 +817,29 @@ internal static class ClientHelperHooks
}
}
// Last player id read on AC's main thread. The native leaf (0x0048E5F0) reads
// the SmartBox global and then a field of it; off-thread that dereferences an
// AC object the main thread can free during logout/teardown, and try/catch
// cannot stop a native AV. Off-thread callers (host GetPlayerIdFn on the pump,
// snapshot owner checks, HUDs) get this value instead: at most one frame old,
// refreshed every EndScene by EngineFrameController, 0 = no player / not ready.
private static int _cachedPlayerId;
public static uint GetPlayerId()
{
if (_getPlayerId == null)
return 0;
// Main-thread callers (PrefetchPlayerStats, IsFullOwnedContainer, the EndScene
// prefetches) keep the live native read exactly as before, and publish it.
if (!MainThreadGuard.IsOnMainThread())
return unchecked((uint)Volatile.Read(ref _cachedPlayerId));
try
{
return _getPlayerId();
uint id = _getPlayerId();
Volatile.Write(ref _cachedPlayerId, unchecked((int)id));
return id;
}
catch
{
@ -716,6 +895,12 @@ internal static class ClientHelperHooks
// MoveItemInternal/External early-return-enqueue off-thread), so the PWD ownership
// read, ITEMS_CAPACITY read, and GetNumContainedItems walk are all authoritative
// and the off-thread read-AV class does not apply.
/// <summary>
/// The full-pack guard MoveItemInternal / MoveItemExternal apply, for callers that send
/// through another path (the Inventory panel's split). Main thread.
/// </summary>
internal static bool IsOwnedContainerFull(uint target) => IsFullOwnedContainer(target);
private static bool IsFullOwnedContainer(uint target)
{
uint player = GetPlayerId();
@ -854,6 +1039,15 @@ internal static class ClientHelperHooks
if (_sendNoticeOpenSalvagePanel == null || toolId == 0)
return false;
// Off AC's main thread (RynthAi SalvageManager / Meta tick on the plugin
// pump): marshal. The salvage trio posts a UI notice and mutates the live
// gmSalvageUI UIElement tree; off-thread it races AC's own UI walk, the
// same class as the SetSelectedObject 0x60D1D AV. The ring is FIFO with
// one consumer, so open -> add -> execute keep their order. Drain calls
// back into this method on the main thread, where the gate is satisfied.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSalvageOpen(toolId);
try
{
_sendNoticeOpenSalvagePanel(toolId);
@ -874,6 +1068,10 @@ internal static class ClientHelperHooks
/// </summary>
public static bool SalvagePanelAddItem(uint itemId)
{
// Decal bridge mode: salvage is left to Decal (our OpenSalvagePanel hook isn't
// installed, so the instance is never captured) - Decal's SalvagePanelAdd instead.
if (DecalBridgeHost.Active && !SalvageHooks.IsInstalled)
return DecalBridgeHost.TrySalvagePanelAdd(itemId);
if (_gmSalvageUIAddNewItem == null || itemId == 0)
return false;
@ -884,6 +1082,14 @@ internal static class ClientHelperHooks
return false;
}
// Off-thread: enqueue AFTER the instance pre-check, so a false still means
// "panel not captured" (SalvageManager re-queues the item on it). The
// queued entry carries only the item id: on the main thread this method
// runs again and re-reads the instance, since the panel may have closed
// or been rebuilt in between.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSalvageAddItem(itemId);
try
{
_gmSalvageUIAddNewItem(inst, itemId);
@ -902,6 +1108,8 @@ internal static class ClientHelperHooks
/// </summary>
public static bool SalvagePanelExecute()
{
if (DecalBridgeHost.Active && !SalvageHooks.IsInstalled)
return DecalBridgeHost.TrySalvagePanelSalvage(); // bridge mode: Decal's SalvagePanelSalvage
if (_gmSalvageUISalvage == null)
return false;
@ -912,6 +1120,11 @@ internal static class ClientHelperHooks
return false;
}
// Off-thread: same shape as SalvagePanelAddItem (instance re-read on the
// main thread when the entry drains).
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSalvageExecute();
try
{
_gmSalvageUISalvage(inst);
@ -957,8 +1170,11 @@ internal static class ClientHelperHooks
_moveItemInternal = null;
_eventStackableMerge = null;
_eventGiveObjectRequest = null;
_eventGetAndWieldItem = null;
_eventDropItem = null;
_inqPlayerCoords = null;
_getPlayerId = null;
Volatile.Write(ref _cachedPlayerId, 0);
_addTextToScroll = null;
_useWithTargetEvent = null;
_sendNoticeOpenSalvagePanel = null;
@ -1001,6 +1217,13 @@ internal static class ClientHelperHooks
return Marshal.ReadIntPtr(new IntPtr(address));
}
/// <summary>The ClientUISystem singleton, or Zero before the UI exists. Read-only (diagnostics).</summary>
internal static IntPtr ReadUiSystemPtr()
{
IntPtr slot = new IntPtr(_uiSystemAddr);
return ClientObjectHooks.IsReadablePointer(slot) ? Marshal.ReadIntPtr(slot) : IntPtr.Zero;
}
// WidePString (AC1Legacy::PStringBase<ushort>) helper fns — pattern-resolved (1a, 2026-06-05).
private static readonly byte?[] PatWidePStringCtor = [ 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x85, 0xFF, 0x8B, 0xF1, 0x74, 0x2C ];
private static readonly byte?[] PatWidePStringDtor = [ 0x56, 0x8B, 0x31, 0x83, 0xEE, 0x14, 0x8D, 0x46 ];

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
@ -407,6 +408,13 @@ internal static class CombatActionHooks
if (_cancelAttack == null)
return false;
// 0x1B7 CM_Combat::Event_CancelAttack: same sender class as MeleeAttack, so the
// same gate. Queued in the action ring so it keeps FIFO order after an attack
// that is already queued (it used to run at once and could overtake it). The
// drain re-enters here on the main thread, where the gate passes.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueCancelAttack();
try
{
return _cancelAttack();
@ -422,6 +430,14 @@ internal static class CombatActionHooks
if (_queryHealth == null)
return false;
// 0x1BF CM_Combat::Event_QueryHealth is a game-action send (AC blob alloc +
// send queue): main thread only. The plugin QueryHealthFn arrives on the pump,
// so off-thread calls go to the non-gesture QueryHealth queue and the drain
// re-enters here on the main thread. Callers ignore the result and read the
// async 0x01C0 reply, so "queued" is enough.
if (!MainThreadGuard.IsOnMainThread())
return targetId != 0 && AcMainThreadQueue.EnqueueQueryHealth(targetId);
try
{
return _queryHealth(targetId);
@ -437,6 +453,17 @@ internal static class CombatActionHooks
if (_requestId == null || objectId == 0)
return false;
// The 0xC8 IdentifyObject send allocates on AC's heap and bumps the
// ClientUISystem busy count (non-atomic, via BusyCountHooks) - main thread
// only. Plugin RequestIdFn calls and the PluginManager.TickAll login
// self-identify arrive on the plugin pump, so off-thread callers go through
// the same non-gesture queue AutoIdService uses. DrainRequestIds re-enters
// here on the main thread, where this gate passes and the packet is sent.
// Fire-and-forget: the appraisal reply is async anyway, so "queued" keeps
// the bool's meaning ("requested").
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueRequestId(objectId);
try
{
return _requestId(objectId);
@ -451,6 +478,8 @@ internal static class CombatActionHooks
{
if (spellId <= 0) return false;
if (_castSpellClient == null) return false;
// Nameplate debuffs: pairs "You cast <spell> on <name>" with this target id.
ImGuiBackend.Hud.HudFeed.OnCast(targetId, spellId);
// P2 cast marshalling — drain-BEFORE-tick variant (2026-06-03, attempt 2).
// Off the main thread, enqueue the cast; GameTickHooks drains it on AC's
@ -615,8 +644,13 @@ internal static class CombatActionHooks
_castSpellClientPtr = IntPtr.Zero;
_getMagicSystemPtr = IntPtr.Zero;
_freeHandsCastPtr = IntPtr.Zero;
_queryHealthResponseDetour = null;
_originalQueryHealthResponse = null;
// _queryHealthResponseDetour / _originalQueryHealthResponse are deliberately
// NOT cleared (2026-09-30): the MinHook detour on Handle_Combat__QueryHealthResponse
// stays enabled across a re-probe, so clearing them unrooted the detour
// delegate while AC could still jump to it, made a detour call in that
// window skip AC's original handler, and let InstallQueryHealthResponseHook
// re-run HookCreate on a live target (the remove-and-retry path, safe only
// after shutdown joined every caller). Kept, the install guard is a no-op.
_identifyObjectDetour = null;
_originalIdentifyObject = null;
IsInitialized = false;
@ -757,10 +791,6 @@ internal static class CombatActionHooks
if (success == 0 || objectId == 0)
return;
const uint CreatureProfile = 0x0100;
if ((flags & CreatureProfile) == 0)
return;
int offset = 16; // Past the header
int iSize = (int)size;
@ -773,6 +803,13 @@ internal static class CombatActionHooks
return; // BoolStatsTable
if ((flags & 0x0004) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 12))
return; // FloatStatsTable
// The identify's properties (every table and profile) are cached from the live
// seam, SmartBoxHooks.ParseGameEvent -> PropertyWire (2026-09-30); this parser only
// runs from the disabled inner-dispatcher hook and reads the creature vitals.
const uint CreatureProfile = 0x0100;
if ((flags & CreatureProfile) == 0)
return;
if ((flags & 0x0008) != 0 && !SkipStringHashTable(buffer, iSize, ref offset))
return; // StringStatsTable
if ((flags & 0x1000) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))

View file

@ -49,6 +49,13 @@ internal static class CombatModeHooks
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
/// <summary>The ClientCombatSystem singleton, or Zero. Read-only (diagnostics).</summary>
internal static IntPtr ReadCombatSystemPtr()
{
IntPtr slot = (IntPtr)_combatSystemPtrAddr;
return ClientObjectHooks.IsReadablePointer(slot) ? Marshal.ReadIntPtr(slot) : IntPtr.Zero;
}
// Deep-audit finding #4 (2026-06-18): this used to raw-dereference the
// ClientCombatSystem singleton unconditionally, including off AC's main
// thread — a teardown-window read (relog/portal, singleton being torn

View file

@ -0,0 +1,570 @@
// ============================================================================
// RynthCore.Engine - Compatibility/DecalBridgeHost.cs
//
// "Bridge mode" (docs/DECAL_BRIDGE_PLAN.md): when Decal runs in the same acclient.exe
// AND the RynthCore Decal bridge (src/RynthCore.DecalBridge, a Decal network filter)
// is loaded, the engine leaves the AC functions Decal itself patches to Decal and
// gets what it needed from them through the bridge instead:
//
// AC function (Decal patches it too) bridge mode
// ClientSystem::AddTextToScroll 0x005649F0 chat lines <- Decal ChatBoxMessage
// OutgoingChat 0x005821A0 chat-bar lines <- Decal CommandLineText
// sending lines -> Decal InvokeChatParser
// gmSalvageUI::OpenSalvagePanel 0x004CBF70 salvage add/go -> Decal SalvagePanelAdd/Salvage
//
// Every other hook stays native: Decal doesn't patch those functions (measured patch
// map, 2026-09-29), and the native hooks run on AC's main thread with the live reads
// the bridge can't do. RYNTHCORE_DECAL_BRIDGE_STREAMS=all brings back the spike's
// routing (object create/delete/change and game events from Decal too) for A/B tests.
//
// Transport: BridgeProtocol.cs (byte rings in a named mapping). Events are drained on
// the plugin pump thread, before ProcessPendingActions, into the same queues the hooks
// feed. Commands are queued here and run by the bridge on AC's main thread. No thread,
// timer or callback the bridge could hold: Shutdown just unmaps the view.
//
// Cost without Decal: Initialize makes two GetModuleHandle calls and returns; nothing
// else here runs (every other entry point checks Active first).
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using RynthCore.DecalBridge;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class DecalBridgeHost
{
// Chat-bar prefixes the bridge eats for us. NOT /vt, /ub, /mt: RynthAi answers those
// as compat commands, but with Decal loaded they belong to the real VTank/UB/MagTools.
private const string EatPrefixes = "/rc;/ra;/rv;/rn;/rnav;/lua";
// Same id DecalBridgeRegistration writes (RynthCore.App).
private const string FilterKey = @"SOFTWARE\Decal\NetworkFilters\{5B3E0D57-2C41-4F8A-9D6E-8C1B70DECA11}";
private const int HelloWaitMs = 20000;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr GetModuleHandleW(string name);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern uint GetModuleFileNameW(IntPtr module, char* buffer, uint size);
private static readonly object Sync = new();
private static readonly object CommandSync = new();
private static BridgeChannel? _ch;
private static DecalBridgeMode _mode;
private static bool _allStreams;
private static long _lastSummaryTick;
private static readonly long[] _kindCounts = new long[16];
private static readonly Dictionary<uint, long> _opcodeCounts = new();
private static readonly Dictionary<uint, long> _gameEventCounts = new();
private static long _serverBytes;
private static int _logged;
private static bool _sawHello;
private static int _salvageLogged;
private static int _commandDropLogged;
/// <summary>Bridge mode is on for this generation (decided at init; false without Decal).</summary>
public static bool Active { get; private set; }
/// <summary>
/// Init steps bridge mode leaves to Decal: the two whose AC functions Decal patches.
/// With RYNTHCORE_DECAL_BRIDGE_STREAMS=all, also the spike's create/delete/game-event/raw sources.
/// </summary>
public static bool SkipsInitStep(string step) => Active && (step switch
{
"chat callback hooks" => true, // AddTextToScroll + OutgoingChat: Decal patches both entries
"salvage hooks" => true, // gmSalvageUI::OpenSalvagePanel: Decal patches it
"create-object hooks" or "delete-object hooks" or "smartbox hooks" or "raw packet hooks" => _allStreams,
_ => false,
});
/// <summary>Decides bridge mode. Top of InitWorker, before any hook step.</summary>
public static void Initialize()
{
Active = false;
InactiveReason = null;
string? decal = FindDecalModule();
if (decal == null)
return; // no Decal: nothing below ever runs
_mode = ModeFromEnvironment() ?? EngineSettings.DecalBridgeMode;
if (_mode == DecalBridgeMode.Off)
{
RynthLog.Info($"DecalBridge: Decal in the process ({decal}) and DecalBridge=Off - old coexistence mode (every hook installs).");
NoteInactive("DecalBridge=Off (engine.json or RYNTHCORE_DECAL_BRIDGE=0)",
"RynthCore: the Decal bridge is switched off (DecalBridge Off in engine.json), so RynthCore's overlay is off in this Decal client.");
return;
}
int pid = Environment.ProcessId;
bool mappingExists = BridgeChannel.Exists(pid);
bool registered = IsBridgeRegistered(out string registration);
if (_mode == DecalBridgeMode.Auto && !registered && !mappingExists)
{
RynthLog.Info($"DecalBridge: Decal in the process ({decal}) but the RynthCore Decal bridge isn't registered ({registration}) - old coexistence mode. " +
"Set the account to \"Decal + RynthCore\" in the launcher to use bridge mode.");
NoteInactive($"Decal won't load the bridge in this client (its entry, read as this client sees the registry: {registration})", NotLoadedChat);
return;
}
_allStreams = string.Equals(Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_BRIDGE_STREAMS"), "all", StringComparison.OrdinalIgnoreCase);
try
{
var ch = BridgeChannel.OpenOrCreate(pid);
if (!ch.Valid)
{
RynthLog.Warn($"DecalBridge: the bridge mapping has another protocol version ({ch.ReadInt(BridgeLayout.OffVersion)}, engine {BridgeLayout.Version}) - " +
"the bridge and the engine are from different builds; old coexistence mode.");
ch.Dispose();
NoteInactive("the Decal bridge and the engine are from different builds (protocol version)",
"RynthCore: the Decal bridge and the engine are from different builds - restart the client once the update has finished, or reinstall RynthCore.");
return;
}
uint want = BridgeLayout.Bit(BridgeRecordKind.ChatText) | BridgeLayout.Bit(BridgeRecordKind.ChatBarEnter) |
BridgeLayout.Bit(BridgeRecordKind.LoginComplete) | BridgeLayout.Bit(BridgeRecordKind.Logoff) |
BridgeLayout.Bit(BridgeRecordKind.CommandResult);
if (_allStreams)
want |= BridgeLayout.Bit(BridgeRecordKind.CreateObject) | BridgeLayout.Bit(BridgeRecordKind.ReleaseObject) |
BridgeLayout.Bit(BridgeRecordKind.ChangeObject) | BridgeLayout.Bit(BridgeRecordKind.ServerMessage);
ch.WriteInt(BridgeLayout.OffWantMask, unchecked((int)want));
WritePrefixes(ch, EatPrefixes);
ch.WriteInt(BridgeLayout.OffEngineGeneration, EntryPoint.InitCount);
ch.WriteInt(BridgeLayout.OffEngineAttached, 1);
if (_allStreams)
{
// A new generation has no objects (a hot reload, or an engine injected late):
// ask the bridge to replay Decal's WorldFilter. Duplicates are harmless.
ch.WriteInt(BridgeLayout.OffReplayRequest, ch.ReadInt(BridgeLayout.OffReplayRequest) + 1);
}
lock (Sync) _ch = ch;
Active = true;
RynthLog.Info($"DecalBridge: BRIDGE MODE ({_mode}; Decal: {decal}; bridge {registration}; gen {EntryPoint.InitCount}). " +
$"Bridge state={ch.ReadInt(BridgeLayout.OffBridgeState)}, records so far={ch.ReadLong(BridgeLayout.OffRecords)}. " +
(_allStreams
? "Streams=all: chat, salvage, create/delete, game-event and raw-packet hooks are left to Decal."
: "The chat and salvage hooks are left to Decal; every other hook installs as usual."));
}
catch (Exception ex)
{
RynthLog.Warn($"DecalBridge: could not open the bridge mapping ({ex.GetType().Name}: {ex.Message}) - old coexistence mode.");
NoteInactive($"could not open the bridge mapping ({ex.GetType().Name})", NotLoadedChat);
}
}
/// <summary>
/// After the hook steps: waits (bounded) for the bridge to say hello. True = bridge mode
/// stands. False = it fell back (Auto only) and the caller installs the skipped steps.
/// </summary>
public static bool WaitForBridge(Func<bool> aborted)
{
BridgeChannel? ch;
lock (Sync) ch = _ch;
if (!Active || ch == null)
return true;
long start = Environment.TickCount64;
while (ch.ReadInt(BridgeLayout.OffBridgeState) != 1)
{
if (aborted() || Environment.TickCount64 - start >= HelloWaitMs)
break;
Thread.Sleep(100);
}
long waited = Environment.TickCount64 - start;
if (ch.ReadInt(BridgeLayout.OffBridgeState) == 1)
{
RynthLog.Info($"DecalBridge: bridge is up (bridge pid {ch.ReadInt(BridgeLayout.OffBridgePid)}, waited {waited} ms).");
return true;
}
if (_mode == DecalBridgeMode.On)
{
RynthLog.Warn($"DecalBridge: no hello from the bridge after {waited} ms and DecalBridge=On - staying in bridge mode; " +
"chat, chat commands and salvage stay dark until the bridge loads.");
NoteInactive($"registered, but Decal didn't load the bridge (no hello after {waited} ms; DecalBridge=On keeps bridge mode)", NotLoadedChat);
return true;
}
RynthLog.Warn($"DecalBridge: no hello from the bridge after {waited} ms - falling back to the old coexistence mode " +
"(the chat and salvage hooks install now). Check Logs\\DecalBridge.<pid>.log and the registration (RynthCore.Injector --decal-bridge status).");
Detach(logSummary: false);
NoteInactive($"registered, but Decal didn't load the bridge (no hello after {waited} ms) - see Logs\\DecalBridge.<pid>.log", NotLoadedChat);
return false;
}
/// <summary>
/// The IDirect3DDevice9* Decal renders with, as the bridge read it from Decal's public
/// IDecalCore.GetD3DDevice on its first frame. Zero when not in bridge mode or not yet
/// known. Never waits (read on AC's thread at login).
/// </summary>
public static IntPtr DecalDevice
{
get
{
BridgeChannel? ch;
lock (Sync) ch = _ch;
return ch == null ? IntPtr.Zero : new IntPtr(ch.ReadInt(BridgeLayout.OffD3DDevice));
}
}
/// <summary>Feeds everything the bridge wrote since the last call into the plugin queues. Pump thread.</summary>
public static int Drain()
{
BridgeChannel? ch;
lock (Sync) ch = _ch;
if (ch == null)
return 0;
int n = 0;
try
{
n = ch.Drain(Handle, 20000);
}
catch (Exception ex)
{
RynthLog.Warn($"DecalBridge: drain threw {ex.GetType().Name}: {ex.Message}");
}
long now = Environment.TickCount64;
if (now - _lastSummaryTick >= 60000)
{
_lastSummaryTick = now;
LogSummary(ch);
}
return n;
}
public static void Shutdown() => Detach(logSummary: true);
private static void Detach(bool logSummary)
{
BridgeChannel? ch;
lock (Sync) { ch = _ch; _ch = null; }
Active = false;
if (ch == null)
return;
try
{
if (logSummary) LogSummary(ch);
ch.WriteInt(BridgeLayout.OffEngineAttached, 0);
ch.WriteInt(BridgeLayout.OffWantMask, 0);
}
catch { }
lock (CommandSync) ch.Dispose();
if (logSummary)
RynthLog.Info("DecalBridge: detached (mapping view released; the bridge keeps the rings for the next generation).");
}
// ── "Decal is here but the bridge isn't" (2026-10-03) ────────────────────────
//
// Without the bridge a Decal client takes the old coexistence path (no overlay; it has
// ended in crashes). The launcher's pre-launch check blocks that, but a client started
// another way (an older launcher, the injector, a registration Decal doesn't read) still
// gets here, so say it once: one clear log line, and one chat line after login.
private const string NotLoadedChat =
"RynthCore: the Decal bridge isn't loaded - open the launcher's Decal check (Recovery Actions > Check Decal bridge). RynthCore's overlay is off in this client.";
private const string NoticeShownVar = "RYNTHCORE_DECAL_BRIDGE_NOTICE_SHOWN"; // once per client, across hot reloads
private static int _noticeScheduled;
private static string? _noticeText;
/// <summary>
/// Why bridge mode is off although Decal is in this client (null: bridge mode, or no
/// Decal). Set at init by <see cref="Initialize"/> or the <see cref="WaitForBridge"/> fallback.
/// </summary>
public static string? InactiveReason { get; private set; }
/// <summary>
/// The engine should stand down in this client (EntryPoint.InitWorker): Decal is here, the
/// bridge isn't active, the mode isn't an explicit DecalBridge=Off (engine.json or
/// RYNTHCORE_DECAL_BRIDGE=0 - the old coexistence path, for tests), and engine.json
/// DecalStandDown isn't false. Never true without Decal.
/// </summary>
public static bool ShouldStandDown =>
InactiveReason != null && !Active && _mode != DecalBridgeMode.Off && EngineSettings.DecalStandDown;
private static void NoteInactive(string reason, string chatLine)
{
InactiveReason = reason;
RynthLog.Warn($"DecalBridge: NOT ACTIVE in this Decal client - {reason}. No RynthCore overlay here: the old coexistence path runs " +
"(known to end in a crash). Fix: the launcher's Recovery Actions > Check Decal bridge (or RynthCore.Injector --decal-bridge check).");
if (Environment.GetEnvironmentVariable(NoticeShownVar) == "1")
return;
if (Interlocked.Exchange(ref _noticeScheduled, 1) != 0)
return;
_noticeText = chatLine;
if (LoginLifecycleHooks.HasObservedLoginComplete)
PostNotice();
else
LoginLifecycleHooks.LoginComplete += OnLoginForNotice;
}
private static void OnLoginForNotice()
{
LoginLifecycleHooks.LoginComplete -= OnLoginForNotice;
PostNotice();
}
// Queued for AC's main thread (drained from Client::UseTime); never calls AC from here.
private static void PostNotice()
{
string? text = _noticeText;
if (text == null) return;
try
{
if (AcMainThreadQueue.EnqueueWriteToChat(text, 2))
Environment.SetEnvironmentVariable(NoticeShownVar, "1");
}
catch { }
}
// ── commands (engine -> bridge -> Decal's public API on AC's main thread) ─────
/// <summary>Sends a chat line as if typed, through Decal's InvokeChatParser. Any thread.</summary>
public static bool TryInvokeChatParser(string line)
{
if (!Active || string.IsNullOrEmpty(line))
return false;
bool sent = SendCommand(BridgeRecordKind.CmdInvokeChatParser, 0, line);
// The bridge doesn't echo our own lines back as ChatBarEnter, so a /vt start|stop
// the engine or a plugin sends is noted here.
if (sent)
VTankWatch.ObserveSentLine(line);
return sent;
}
/// <summary>Salvage panel add, left to Decal in bridge mode (SalvagePanelAdd). Any thread.</summary>
public static bool TrySalvagePanelAdd(uint itemId)
{
if (!Active || itemId == 0)
return false;
NoteSalvage();
return SendCommand(BridgeRecordKind.CmdSalvagePanelAdd, itemId, null);
}
/// <summary>Salvage button, left to Decal in bridge mode (SalvagePanelSalvage). Any thread.</summary>
public static bool TrySalvagePanelSalvage()
{
if (!Active)
return false;
NoteSalvage();
return SendCommand(BridgeRecordKind.CmdSalvagePanelSalvage, 0, null);
}
private static void NoteSalvage()
{
if (Interlocked.Exchange(ref _salvageLogged, 1) == 0)
RynthLog.Info("DecalBridge: salvage is left to Decal in bridge mode (our OpenSalvagePanel hook is not installed): " +
"adding items and pressing Salvage go through Decal's SalvagePanelAdd/SalvagePanelSalvage. The panel must be open (use an Ust).");
}
private static bool SendCommand(BridgeRecordKind kind, uint arg0, string? text)
{
lock (CommandSync)
{
BridgeChannel? ch;
lock (Sync) ch = _ch;
if (ch == null)
return false;
bool ok = ch.WriteCommand(kind, arg0, 0, text);
if (!ok && Interlocked.Exchange(ref _commandDropLogged, 1) == 0)
RynthLog.Warn($"DecalBridge: command ring full - {kind} dropped (is the bridge running? it drains once per frame).");
return ok;
}
}
// ── record handling ──────────────────────────────────────────────────────
private static void Handle(BridgeRecordKind kind, uint arg0, uint arg1, byte* payload, int len)
{
int k = (int)kind;
if (k >= 0 && k < _kindCounts.Length) _kindCounts[k]++;
switch (kind)
{
case BridgeRecordKind.Hello:
_sawHello = true;
RynthLog.Info($"DecalBridge: hello from bridge v{arg0}: {Utf16(payload, len)}");
break;
case BridgeRecordKind.ChatText:
{
string text = Utf16(payload, len);
FirstFew($"chat type={arg0} target={arg1} '{Trim(text)}'");
VTankWatch.ObserveChatText(text); // diagnostic log only
PluginManager.QueueChatWindowText(text, arg0);
break;
}
case BridgeRecordKind.ChatBarEnter:
{
// Runs on the pump thread (the hook ran it on AC's thread, synchronously,
// so it could eat the line; the bridge now does the eating by prefix).
string text = Utf16(payload, len);
FirstFew($"chat-bar '{Trim(text)}' eatenByBridge={arg0 != 0}");
// Every parser line, eaten or not: /vt start|stop went on to VTank, and is
// how RynthAi learns that VTank's macro runs (one bot per client).
VTankWatch.ObserveParserLine(text);
// Only the lines the bridge ate (our prefixes) are ours to run. Every other
// line already went on to Decal and AC: handing it to the plugins too would
// run it twice (RynthAi answers /vt, /ub and /mt as compat commands, and
// VTank, UB and MagTools already ran them).
if (arg0 == 0)
break;
if (RynthCoreChatCommands.TryHandle(text))
break;
PluginManager.DispatchChatBarEnter(text);
break;
}
case BridgeRecordKind.CommandResult:
RynthLog.Warn($"DecalBridge: command {(BridgeRecordKind)arg0} failed in the bridge: {Utf16(payload, len)}");
break;
// Streams=all only (the spike's routing). Same side effects as CreateObjectHooks /
// DeleteObjectHooks: the auto-appraisal queue is what gives RynthAi its creature
// classification (measured in world 2026-09-29).
case BridgeRecordKind.CreateObject:
PluginManager.QueueCreateObject(arg0);
AutoIdService.Enqueue(arg0);
break;
case BridgeRecordKind.ReleaseObject:
PaletteCache.Remove(arg0);
PluginManager.QueueDeleteObject(arg0);
AutoIdService.Evict(arg0);
break;
case BridgeRecordKind.ChangeObject:
PluginManager.QueueUpdateObject(arg0);
break;
case BridgeRecordKind.ServerMessage:
{
_serverBytes += len;
_opcodeCounts[arg0] = _opcodeCounts.TryGetValue(arg0, out long c) ? c + 1 : 1;
// Decal's Message.RawData for a game event: [F7B0][objectId][sequence][eventType][payload].
if (arg0 == 0xF7B0 && len >= 16 && *(uint*)payload == 0xF7B0)
{
uint ev = *(uint*)(payload + 12);
_gameEventCounts[ev] = _gameEventCounts.TryGetValue(ev, out long g) ? g + 1 : 1;
SmartBoxHooks.ProcessBridgeGameEvent(payload + 12, len - 12);
}
break;
}
case BridgeRecordKind.LoginComplete:
RynthLog.Info($"DecalBridge: Decal LoginComplete (character 0x{arg0:X8}); engine login seen={LoginLifecycleHooks.HasObservedLoginComplete}.");
break;
case BridgeRecordKind.Logoff:
RynthLog.Info($"DecalBridge: Decal Logoff type={arg0}.");
VTankWatch.OnLogoff();
break;
}
}
private static void LogSummary(BridgeChannel ch)
{
var sb = new StringBuilder();
sb.Append($"DecalBridge: summary - hello={_sawHello} records={ch.ReadLong(BridgeLayout.OffRecords)} dropped={ch.ReadLong(BridgeLayout.OffDropped)} ");
sb.Append($"chat={_kindCounts[2]} chatBar={_kindCounts[3]} commands sent={ch.ReadLong(BridgeLayout.OffCmdWritePos) > 0} run={ch.ReadLong(BridgeLayout.OffCmdDone)} dropped={ch.ReadLong(BridgeLayout.OffCmdDropped)}");
if (_allStreams)
{
sb.Append($" create={_kindCounts[4]} release={_kindCounts[5]} change={_kindCounts[6]} server={_kindCounts[7]} ({_serverBytes / 1024} KB); top opcodes:");
foreach (var kv in Top(_opcodeCounts, 8)) sb.Append($" {kv.Key:X4}x{kv.Value}");
sb.Append("; game events:");
foreach (var kv in Top(_gameEventCounts, 12)) sb.Append($" {kv.Key:X4}x{kv.Value}");
}
sb.Append($"; plugins live objects={PluginManager.LiveObjectCount}");
RynthLog.Info(sb.ToString());
}
private static IEnumerable<KeyValuePair<uint, long>> Top(Dictionary<uint, long> d, int n)
{
var list = new List<KeyValuePair<uint, long>>(d);
list.Sort((a, b) => b.Value.CompareTo(a.Value));
return list.Count > n ? list.GetRange(0, n) : list;
}
private static void FirstFew(string line)
{
if (_logged >= 20) return;
_logged++;
RynthLog.Info("DecalBridge: " + line);
}
private static string Trim(string s) => s.Length > 80 ? s.Substring(0, 80) + "..." : s.TrimEnd('\n', '\r');
private static string Utf16(byte* p, int len) => len >= 2 ? new string((char*)p, 0, len / 2) : string.Empty;
private static void WritePrefixes(BridgeChannel ch, string prefixes)
{
char* dst = (char*)(ch.Header + BridgeLayout.OffPrefixes);
int n = Math.Min(prefixes.Length, BridgeLayout.PrefixChars - 1);
for (int i = 0; i < n; i++) dst[i] = prefixes[i];
dst[n] = '\0';
}
// ── decisions ────────────────────────────────────────────────────────────
/// <summary>RYNTHCORE_DECAL_BRIDGE (test override): 1/on, 0/off, auto.</summary>
private static DecalBridgeMode? ModeFromEnvironment()
{
string? v = Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_BRIDGE");
if (string.IsNullOrWhiteSpace(v)) return null;
v = v.Trim();
if (v == "1" || v.Equals("on", StringComparison.OrdinalIgnoreCase)) return DecalBridgeMode.On;
if (v == "0" || v.Equals("off", StringComparison.OrdinalIgnoreCase)) return DecalBridgeMode.Off;
if (v.Equals("auto", StringComparison.OrdinalIgnoreCase)) return DecalBridgeMode.Auto;
return null;
}
/// <summary>
/// Whether Decal will load the bridge in this client: its filter entry, read through
/// this (virtualized, 32-bit) process's own view of HKLM - the view Decal reads, which
/// includes the per-user copy the launcher writes.
/// </summary>
private static bool IsBridgeRegistered(out string detail)
{
try
{
using Microsoft.Win32.RegistryKey? k = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(FilterKey);
if (k == null) { detail = "not registered"; return false; }
bool enabled = k.GetValue("Enabled") is int e && e != 0;
string? dir = k.GetValue("Path") as string;
string? file = k.GetValue("Assembly") as string;
bool present = dir != null && file != null && File.Exists(Path.Combine(dir, file));
detail = $"registered, {(enabled ? "enabled" : "DISABLED")}, {(present ? dir : $"DLL missing at {dir}")}";
return enabled && present;
}
catch (Exception ex)
{
detail = $"registry read failed: {ex.GetType().Name}";
return false;
}
}
/// <summary>
/// Decal in this process? Two GetModuleHandle calls (no module walk). decal.dll, or
/// Decal's Inject.dll (the first thing a Decal launch loads) next to Decal.Adapter.dll.
/// Deliberately not DecalDetection: that caches its first answer, and asking it this
/// early (before decal.dll loads) would cache "no Decal" for the post-login check.
/// </summary>
private static string? FindDecalModule()
{
try
{
IntPtr m = GetModuleHandleW("decal.dll");
if (m == IntPtr.Zero)
{
m = GetModuleHandleW("Inject.dll");
if (m == IntPtr.Zero)
return null;
}
char* buf = stackalloc char[520];
uint n = GetModuleFileNameW(m, buf, 520);
string path = new string(buf, 0, (int)n);
string? dir = Path.GetDirectoryName(path);
return dir != null && File.Exists(Path.Combine(dir, "Decal.Adapter.dll")) ? path : null;
}
catch
{
return null;
}
}
}

View file

@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
@ -80,7 +82,14 @@ internal static class EnchantmentHooks
IntPtr qualPtr = PlayerVitalsHooks.KnownPlayerQualitiesPtr;
if (qualPtr == IntPtr.Zero) return -1;
int count = ReadEnchantmentsFromQualities(qualPtr, spellIds, expiryTimes, maxCount);
// Off AC's main thread (plugin pump: RynthAi BuffManager, meta expressions,
// RynthLua): copy the main-thread snapshot. Walking the registry's linked
// lists here raced AC adding/removing/expiring buffs on its own thread (a
// freed node on a still-committed page passes every probe), which the
// double walk only detected, never prevented.
int count = MainThreadGuard.IsOnMainThread()
? ReadEnchantmentsFromQualities(qualPtr, spellIds, expiryTimes, maxCount)
: CopyPlayerSnapshot(qualPtr, spellIds, expiryTimes, maxCount);
if (_enchReadLogCount < 8)
{
@ -92,6 +101,262 @@ internal static class EnchantmentHooks
}
private static int _enchReadLogCount;
// ── Main-thread enchantment snapshots (2026-09-30 main-thread audit) ─────────
// Player: MainThreadSnapshots.Tick walks the player's registry every 250 ms (at
// once after an enchantment game event marks it dirty) into preallocated
// back buffers, then swaps them in under _playerEnchLock. Zero-alloc.
private const int MaxSnapshotEnchantments = 1024;
private const int PlayerEnchRefreshMs = 250;
private static readonly object _playerEnchLock = new();
private static uint[] _pEnchIdsFront = new uint[MaxSnapshotEnchantments];
private static double[] _pEnchExpFront = new double[MaxSnapshotEnchantments];
private static uint[] _pEnchIdsBack = new uint[MaxSnapshotEnchantments];
private static double[] _pEnchExpBack = new double[MaxSnapshotEnchantments];
// The same entries' StatMod (type, key, value) and spell category, for the Skills
// panel's per-stat buff lists (CopyPlayerStatMods). Swapped with the arrays above.
private static uint[] _pEnchTypeFront = new uint[MaxSnapshotEnchantments];
private static uint[] _pEnchKeyFront = new uint[MaxSnapshotEnchantments];
private static float[] _pEnchValFront = new float[MaxSnapshotEnchantments];
private static uint[] _pEnchCatFront = new uint[MaxSnapshotEnchantments];
private static uint[] _pEnchTypeBack = new uint[MaxSnapshotEnchantments];
private static uint[] _pEnchKeyBack = new uint[MaxSnapshotEnchantments];
private static float[] _pEnchValBack = new float[MaxSnapshotEnchantments];
private static uint[] _pEnchCatBack = new uint[MaxSnapshotEnchantments];
private static int _pEnchCountFront = -1; // -1 = nothing valid published
private static IntPtr _pEnchOwnerFront;
private static long _nextPlayerEnchRefreshMs;
private static int _playerEnchDirty;
/// <summary>
/// Main thread only: an enchantment game event was just applied by AC. Refresh
/// the player snapshot immediately (SmartBoxHooks calls this before it queues
/// the event to plugins, so their re-read sees the change).
/// </summary>
internal static void RefreshPlayerSnapshotNow()
{
Volatile.Write(ref _playerEnchDirty, 1);
PrefetchPlayerEnchantments(allowWalk: !LogoutLifecycleHooks.HasObservedLogout);
}
// Off-thread copy of the player snapshot; -1 when it is missing, belongs to
// another qualities object, or a DB-cache teardown is running.
private static unsafe int CopyPlayerSnapshot(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount)
{
if (DbCacheTeardownHooks.TeardownActive)
return -1;
lock (_playerEnchLock)
{
int n = _pEnchCountFront;
if (n < 0 || _pEnchOwnerFront != qualPtr)
return -1;
if (n > maxCount) n = maxCount;
for (int i = 0; i < n; i++)
{
spellIds[i] = _pEnchIdsFront[i];
expiryTimes[i] = _pEnchExpFront[i];
}
return n;
}
}
/// <summary>
/// The player snapshot with each entry's StatMod and spell category (the Skills
/// panel). Fills up to the arrays' length; returns the count, or -1 when nothing
/// valid is published (no player, another qualities object, a teardown). Any thread.
/// </summary>
internal static int CopyPlayerStatMods(uint[] spellIds, double[] expiryTimes, uint[] modTypes, uint[] modKeys,
float[] modVals, uint[] categories)
{
if (DbCacheTeardownHooks.TeardownActive)
return -1;
IntPtr qualPtr = PlayerVitalsHooks.KnownPlayerQualitiesPtr;
lock (_playerEnchLock)
{
int n = _pEnchCountFront;
if (n < 0 || qualPtr == IntPtr.Zero || _pEnchOwnerFront != qualPtr)
return -1;
n = Math.Min(n, Math.Min(Math.Min(spellIds.Length, expiryTimes.Length), Math.Min(modTypes.Length,
Math.Min(modKeys.Length, Math.Min(modVals.Length, categories.Length)))));
Array.Copy(_pEnchIdsFront, spellIds, n);
Array.Copy(_pEnchExpFront, expiryTimes, n);
Array.Copy(_pEnchTypeFront, modTypes, n);
Array.Copy(_pEnchKeyFront, modKeys, n);
Array.Copy(_pEnchValFront, modVals, n);
Array.Copy(_pEnchCatFront, categories, n);
return n;
}
}
/// <summary>
/// Main thread only (MainThreadSnapshots.Tick). Refreshes the player snapshot
/// every 250 ms, or on the next tick after an enchantment event. With
/// <paramref name="allowWalk"/> false (no live player: logout window, teardown)
/// it publishes "nothing valid" instead of walking the cached qualities pointer.
/// </summary>
internal static unsafe void PrefetchPlayerEnchantments(bool allowWalk)
{
if (!MainThreadGuard.IsOnMainThread())
return;
long now = Environment.TickCount64;
bool dirty = Volatile.Read(ref _playerEnchDirty) != 0;
if (!dirty && now < _nextPlayerEnchRefreshMs)
return;
Volatile.Write(ref _playerEnchDirty, 0);
_nextPlayerEnchRefreshMs = now + PlayerEnchRefreshMs;
IntPtr qualPtr = PlayerVitalsHooks.KnownPlayerQualitiesPtr;
int count = -1;
if (qualPtr != IntPtr.Zero && allowWalk)
{
fixed (uint* ids = _pEnchIdsBack)
fixed (double* exp = _pEnchExpBack)
fixed (uint* types = _pEnchTypeBack)
fixed (uint* keys = _pEnchKeyBack)
fixed (float* vals = _pEnchValBack)
fixed (uint* cats = _pEnchCatBack)
count = ReadEnchantmentsFromQualities(qualPtr, ids, exp, MaxSnapshotEnchantments, types, keys, vals, cats);
}
lock (_playerEnchLock)
{
(_pEnchIdsFront, _pEnchIdsBack) = (_pEnchIdsBack, _pEnchIdsFront);
(_pEnchExpFront, _pEnchExpBack) = (_pEnchExpBack, _pEnchExpFront);
(_pEnchTypeFront, _pEnchTypeBack) = (_pEnchTypeBack, _pEnchTypeFront);
(_pEnchKeyFront, _pEnchKeyBack) = (_pEnchKeyBack, _pEnchKeyFront);
(_pEnchValFront, _pEnchValBack) = (_pEnchValBack, _pEnchValFront);
(_pEnchCatFront, _pEnchCatBack) = (_pEnchCatBack, _pEnchCatFront);
_pEnchCountFront = count;
_pEnchOwnerFront = qualPtr;
}
}
// Objects: request-driven. An off-thread ReadObjectEnchantments registers the
// id and gets -1 (every caller already treats -1 as "skip this tick") until the
// main thread has walked it; after that it gets the last main-thread result,
// refreshed every 500 ms while it keeps being asked for. Ids not asked for in
// 5 s are dropped. At most 64 watched ids.
private sealed class ObjEnchEntry
{
public uint[] Ids = Array.Empty<uint>();
public double[] Exp = Array.Empty<double>();
public int Count = -1; // -1 = not walked yet / unreadable
public long LastRequestMs;
}
private const int MaxWatchedObjects = 64;
private const int ObjectEnchRefreshMs = 500;
private const int ObjectEnchIdleDropMs = 5000;
private static readonly object _objEnchLock = new();
private static readonly Dictionary<uint, ObjEnchEntry> _objEnch = new(MaxWatchedObjects);
private static readonly uint[] _objEnchWork = new uint[MaxWatchedObjects];
private static readonly uint[] _objEnchScratchIds = new uint[MaxSnapshotEnchantments];
private static readonly double[] _objEnchScratchExp = new double[MaxSnapshotEnchantments];
private static long _nextObjectEnchRefreshMs;
private static IntPtr _objEnchSessionOwner;
private static unsafe int CopyObjectSnapshot(uint objectId, uint* spellIds, double* expiryTimes, int maxCount)
{
if (DbCacheTeardownHooks.TeardownActive)
return -1;
long now = Environment.TickCount64;
lock (_objEnchLock)
{
if (!_objEnch.TryGetValue(objectId, out ObjEnchEntry? e))
{
if (_objEnch.Count >= MaxWatchedObjects)
{
// Full: evict the id asked for least recently.
uint oldest = 0; long oldestMs = long.MaxValue;
foreach (KeyValuePair<uint, ObjEnchEntry> kv in _objEnch)
if (kv.Value.LastRequestMs < oldestMs) { oldestMs = kv.Value.LastRequestMs; oldest = kv.Key; }
_objEnch.Remove(oldest);
}
_objEnch[objectId] = new ObjEnchEntry { LastRequestMs = now };
return -1;
}
e.LastRequestMs = now;
int n = e.Count;
if (n < 0)
return -1;
if (n > maxCount) n = maxCount;
for (int i = 0; i < n; i++)
{
spellIds[i] = e.Ids[i];
expiryTimes[i] = e.Exp[i];
}
return n;
}
}
/// <summary>
/// Main thread only (MainThreadSnapshots.Tick). Walks the watched objects'
/// registries every 500 ms. Idle (one lock, empty dictionary) when nothing asks.
/// </summary>
internal static unsafe void PrefetchWatchedObjectEnchantments()
{
if (!MainThreadGuard.IsOnMainThread())
return;
long now = Environment.TickCount64;
if (now < _nextObjectEnchRefreshMs)
return;
_nextObjectEnchRefreshMs = now + ObjectEnchRefreshMs;
int n = 0;
lock (_objEnchLock)
{
// A new character (or none): nothing watched belongs to it.
IntPtr owner = PlayerVitalsHooks.KnownPlayerQualitiesPtr;
if (owner != _objEnchSessionOwner)
{
_objEnch.Clear();
_objEnchSessionOwner = owner;
}
if (_objEnch.Count == 0)
return;
// Live ids fill the work buffer from the front, idle ones from the back
// (Count <= MaxWatchedObjects, so the two never meet); then drop the idle.
int drop = 0;
foreach (KeyValuePair<uint, ObjEnchEntry> kv in _objEnch)
{
if (now - kv.Value.LastRequestMs <= ObjectEnchIdleDropMs)
_objEnchWork[n++] = kv.Key;
else
_objEnchWork[_objEnchWork.Length - 1 - drop++] = kv.Key;
}
for (int i = 0; i < drop; i++)
_objEnch.Remove(_objEnchWork[_objEnchWork.Length - 1 - i]);
}
if (DbCacheTeardownHooks.TeardownActive)
return;
for (int i = 0; i < n; i++)
{
uint id = _objEnchWork[i];
int count;
fixed (uint* ids = _objEnchScratchIds)
fixed (double* exp = _objEnchScratchExp)
count = ReadObjectEnchantmentsLive(id, ids, exp, MaxSnapshotEnchantments);
lock (_objEnchLock)
{
if (!_objEnch.TryGetValue(id, out ObjEnchEntry? e))
continue; // dropped meanwhile
if (count > 0 && e.Ids.Length < count)
{
// Grow once per object (rare: only when its buff count rises).
e.Ids = new uint[Math.Max(count, 16)];
e.Exp = new double[e.Ids.Length];
}
for (int k = 0; k < count; k++)
{
e.Ids[k] = _objEnchScratchIds[k];
e.Exp[k] = _objEnchScratchExp[k];
}
e.Count = count;
}
}
}
/// <summary>
/// Reads active enchantments from any game object's CEnchantmentRegistry.
/// Path: GetWeenieObject(objectId) → weenie+qualitiesOffset → CACQualities+0x70.
@ -104,6 +369,22 @@ internal static class EnchantmentHooks
{
if (maxCount <= 0) return 0;
// Off AC's main thread (host ReadObjectEnchantmentsFn: RynthAi's opt-in
// registry diagnostic, RynthLua): the request-driven main-thread snapshot.
// The live walk below started from a cached, possibly freed weenie pointer.
if (!MainThreadGuard.IsOnMainThread())
return CopyObjectSnapshot(objectId, spellIds, expiryTimes, maxCount);
return ReadObjectEnchantmentsLive(objectId, spellIds, expiryTimes, maxCount);
}
// MAIN THREAD ONLY: resolve the weenie natively and walk its registry.
private static unsafe int ReadObjectEnchantmentsLive(uint objectId, uint* spellIds, double* expiryTimes, int maxCount)
{
if (maxCount <= 0) return 0;
if (!MainThreadGuard.IsOnMainThread())
return -1;
if (!ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out IntPtr weeniePtr))
return -1;
@ -141,8 +422,13 @@ internal static class EnchantmentHooks
/// <summary>
/// Core: reads enchantments from a CACQualities pointer's enchantment registry.
/// </summary>
private static unsafe int ReadEnchantmentsFromQualities(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount)
private static unsafe int ReadEnchantmentsFromQualities(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount,
uint* modTypes = null, uint* modKeys = null, float* modVals = null, uint* categories = null)
{
// MAIN THREAD ONLY: see the note at the end of this method.
if (!MainThreadGuard.IsOnMainThread())
return -1;
// While AC is inside a DB object-cache teardown (DbCacheTeardownHooks sets this
// on AC's main thread for the duration of DestroyObjectCaches — which fires at
// world-load, zone change, logout, AND final close), refuse to walk the
@ -180,43 +466,36 @@ internal static class EnchantmentHooks
if (!SmartBoxLocator.IsPointerInModule(registryVtable))
return -1;
// Stability check (2026-09-02 "infinite buffing loop" bug): AC's own
// main thread mutates these linked lists as buffs land/expire, and in
// Decal-coexistence mode this reader runs off-thread on the 30Hz
// plugin pump (no EndScene-driven main-thread tick exists there) — a
// walk here can race that mutation. A torn/truncated walk silently
// under-reports the active buff set; BuffManager.RefreshFromLiveMemory
// treats a short read as "buffs expired" and clears its timers,
// making a just-completed rebuff pass look like nothing landed and
// instantly restarting it. Walk twice and only trust an exact match;
// on a mismatch, skip this tick (return -1, already a safe no-op for
// every caller) rather than report a truncated set.
int countA = WalkAllLists(registryPtr, spellIds, expiryTimes, maxCount);
uint* idsB = stackalloc uint[maxCount];
double* expB = stackalloc double[maxCount];
int countB = WalkAllLists(registryPtr, idsB, expB, maxCount);
if (countA != countB)
return -1;
for (int i = 0; i < countA; i++)
{
if (spellIds[i] != idsB[i] || expiryTimes[i] != expB[i])
return -1;
}
return countA;
// Stability check history (2026-09-02 "infinite buffing loop" bug): when this
// walk ran off-thread on the plugin pump it could race AC mutating these
// lists as buffs landed/expired, so it walked twice and trusted only an
// exact match. Since 2026-09-30 it only runs on AC's main thread (the
// snapshot prefetches and main-thread callers), where nothing mutates the
// lists during the walk, so one walk is exact.
return WalkAllLists(registryPtr, spellIds, expiryTimes, maxCount, modTypes, modKeys, modVals, categories);
}
private static unsafe int WalkAllLists(IntPtr registryPtr, uint* spellIds, double* expiryTimes, int maxCount)
private static unsafe int WalkAllLists(IntPtr registryPtr, uint* spellIds, double* expiryTimes, int maxCount,
uint* modTypes, uint* modKeys, float* modVals, uint* categories)
{
int count = 0;
count = WalkEnchantList(registryPtr + RegistryMultListOffset, spellIds, expiryTimes, maxCount, count);
count = WalkEnchantList(registryPtr + RegistryAddListOffset, spellIds, expiryTimes, maxCount, count);
count = WalkEnchantList(registryPtr + RegistryCooldownListOffset, spellIds, expiryTimes, maxCount, count);
count = WalkEnchantList(registryPtr + RegistryMultListOffset, spellIds, expiryTimes, maxCount, count, modTypes, modKeys, modVals, categories);
count = WalkEnchantList(registryPtr + RegistryAddListOffset, spellIds, expiryTimes, maxCount, count, modTypes, modKeys, modVals, categories);
count = WalkEnchantList(registryPtr + RegistryCooldownListOffset, spellIds, expiryTimes, maxCount, count, modTypes, modKeys, modVals, categories);
return count;
}
private static unsafe int WalkEnchantList(IntPtr listPtrAddress, uint* spellIds, double* expiryTimes, int maxCount, int count)
// Optional per-enchantment detail (the Skills panel's buffs): the spell category and
// the StatMod. With the pack(8) padding after _power_level and after _degrade_limit,
// _last_time_degraded sits at +56 and the StatMod at +64: vtable, type +68, key +72,
// val +76 (float); sizeof 80 = NodeNextOffset. All inside the node span checked below.
private const int EnchantmentCategoryOffset = 12;
private const int EnchantmentStatModTypeOffset = 68;
private const int EnchantmentStatModKeyOffset = 72;
private const int EnchantmentStatModValOffset = 76;
private static unsafe int WalkEnchantList(IntPtr listPtrAddress, uint* spellIds, double* expiryTimes, int maxCount, int count,
uint* modTypes, uint* modKeys, float* modVals, uint* categories)
{
if (!SmartBoxLocator.IsMemoryReadable(listPtrAddress, 4))
return count;
@ -245,6 +524,13 @@ internal static class EnchantmentHooks
{
spellIds[count] = spellId;
expiryTimes[count] = duration > 0 ? start + duration : double.MaxValue;
if (modTypes != null)
{
modTypes[count] = unchecked((uint)Marshal.ReadInt32(nodePtr + EnchantmentStatModTypeOffset));
modKeys[count] = unchecked((uint)Marshal.ReadInt32(nodePtr + EnchantmentStatModKeyOffset));
modVals[count] = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(nodePtr + EnchantmentStatModValOffset));
categories[count] = unchecked((uint)Marshal.ReadInt32(nodePtr + EnchantmentCategoryOffset));
}
count++;
}

View file

@ -87,6 +87,10 @@ internal static class EngineStatusMetrics
w.WriteString("ts", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'"));
w.WriteString("host", SafeMachineName());
w.WriteNumber("pid", Environment.ProcessId);
// The engine's build ("2026.9.26.3 (8ca322f)", "dev (...)") and plugin API version, so a
// plugin can say which engine it runs on (RynthAi /ra version). Additive fields.
w.WriteString("engineVersion", EntryPoint.BuildStamp);
w.WriteNumber("apiVersion", Plugins.PluginContractVersion.Current);
w.WriteString("account", SessionStateRegistry.LastAccountName ?? string.Empty);
w.WriteString("character", SessionStateRegistry.LastCharacterName ?? string.Empty);

View file

@ -30,6 +30,11 @@ namespace RynthCore.Engine.Compatibility;
/// </summary>
internal static class GameTickHooks
{
/// <summary>Set once the Decal-coexistence plugin pump starts (no EndScene hook in that
/// client): the UseTime detour then also runs EngineFrameController.RunHeadlessPrefetch.
/// Never set in a client without Decal.</summary>
internal static volatile bool HeadlessPrefetch;
private const int UseTimeVa = 0x00411FA0; // Client::UseTime — thiscall, returns bool in AL
// Client::UseTime returns a bool (AL): AC's main loop drives it as
@ -118,7 +123,12 @@ internal static class GameTickHooks
// off-thread callers of IsPortaling in coexistence mode would see a
// perpetually stale cache since nothing else ever reads it on-thread.
// The getter itself does the guarded read + cache write; discard the value.
try { _ = TeleportStateHooks.IsPortaling; }
bool portaling = false;
try { portaling = TeleportStateHooks.IsPortaling; }
catch { }
// Death / portal space / teleport lines, for lining crashes up with what
// the character was doing (PlayerLifecycleLog).
try { PlayerLifecycleLog.SampleOnGameThread(portaling); }
catch { }
// Run AC's own game-logic + physics + animation pass.
@ -174,6 +184,17 @@ internal static class GameTickHooks
// requirement, and they go through the separate cast slot.)
try { AcMainThreadQueue.Drain(); }
catch { }
// Main-thread snapshots the pump reads instead of AC memory (player id,
// cast gate, pose, ...). Post-tick, so they reflect this tick's physics.
try { MainThreadSnapshots.Tick(); }
catch { }
// Decal clients only (no EndScene hook): the prefetches EngineFrameController
// runs per frame. False for every other client - one flag check.
if (HeadlessPrefetch)
{
try { ImGuiBackend.EngineFrameController.RunHeadlessPrefetch(); }
catch { }
}
// Busy watchdog: also post-tick now. Its decrement / cursor-refresh
// touch m_cBusy, not the motion sequence, so order is immaterial here;
// keeping all engine-issued mutations after AC's pass is the invariant.

View file

@ -1,4 +1,5 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
@ -22,10 +23,40 @@ internal static class HeartbeatLogger
private static int _exited;
private static Thread? _thread;
[StructLayout(LayoutKind.Sequential)]
private struct MEMORYSTATUSEX
{
public uint dwLength, dwMemoryLoad;
public ulong ullTotalPhys, ullAvailPhys, ullTotalPageFile, ullAvailPageFile,
ullTotalVirtual, ullAvailVirtual, ullAvailExtendedVirtual;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer);
/// <summary>
/// Free and total user address space of this (32-bit) process, in MB, or
/// (-1, -1). Every reload leaks the old engine and plugin copies, each a
/// NativeAOT runtime with its own reservations, so this only goes down;
/// 2026-09-28 13:57 a client vanished while its 5th engine loaded plugins.
/// </summary>
public static (long FreeMb, long TotalMb) AddressSpaceMb()
{
var m = new MEMORYSTATUSEX { dwLength = (uint)Marshal.SizeOf<MEMORYSTATUSEX>() };
if (!GlobalMemoryStatusEx(ref m)) return (-1, -1);
return ((long)(m.ullAvailVirtual >> 20), (long)(m.ullTotalVirtual >> 20));
}
public static void Start()
{
if (Interlocked.CompareExchange(ref _started, 1, 0) != 0)
return;
try
{
var (free, total) = AddressSpaceMb();
RynthLog.Info($"HeartbeatLogger: address space at engine start: {free} MB free of {total} MB (initCount={EntryPoint.InitCount}).");
}
catch { }
_thread = new Thread(Run)
{
@ -62,6 +93,7 @@ internal static class HeartbeatLogger
{
long tick = 0;
int lastFrames = 0;
int lastDrawn = 0;
int lastPlugTicks = 0;
long lastMs = Environment.TickCount64;
long startMs = lastMs;
@ -83,15 +115,24 @@ internal static class HeartbeatLogger
int fps = (int)((frames - lastFrames) * 1000L / dtMs);
int pps = (int)((plug - lastPlugTicks) * 1000L / dtMs);
lastFrames = frames; lastPlugTicks = plug; lastMs = nowMs;
// fps counts every EndScene, including the offscreen passes Decal's views,
// VVS and UB render each frame (2-3 per frame in bridge mode), so it read
// 40-130 while the game drew 19-42 (2026-10-03). draw= is frames on screen.
int drawn = D3D9.EndSceneHook.BackBufferFrames;
int draw = drawn >= lastDrawn ? (int)((drawn - lastDrawn) * 1000L / dtMs) : 0;
lastDrawn = drawn;
long wsMb = 0;
try { wsMb = Environment.WorkingSet / (1024 * 1024); } catch { }
int login = 0;
try { login = LoginLifecycleHooks.HasObservedLoginComplete ? 1 : 0; } catch { }
// qd = marshalled actions silently dropped (ring full). A
// climbing qd with healthy fps means the consumer phase is
// dead — exactly the silent blackhole class the review found.
// qdrop = marshalled actions dropped (ring full) since start: a running
// TOTAL, not a queue depth. Named qdrop, not qd, since 2026-10-01: launchers
// read "qd" as a depth and killed healthy 60 fps clients once the total
// passed 2000 (a loot loop had flooded the ring), and an old launcher
// doesn't parse qdrop. A total climbing with healthy fps = a producer
// flooding the ring; flat = fine.
long dropped = 0;
try { dropped = AcMainThreadQueue.DroppedCount; } catch { }
// rec = busy reconciles (cast/item-action), fcl = force-clears.
@ -103,7 +144,38 @@ internal static class HeartbeatLogger
int idle = -1;
try { idle = LogoffOriginProbe.IdleSecondsForHeartbeat; } catch { }
string idleField = idle >= 0 ? $" idle={idle}s" : "";
RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} plug={pps}/s ws={wsMb}MB login={login} qd={dropped} rec={rec} fcl={fcl}{idleField}");
// ui = ImGui cost on AC's render thread per frame, p95/max over the
// last second (docs/IMGUI_PARITY_PLAN.md §4.5). Only while ImGui is on.
string uiField = "";
try
{
if (Plugins.EngineSettings.EnableImGuiBackend)
uiField = $" ui={ImGuiBackend.UiFrameStats.P95Ms:0.0}/{ImGuiBackend.UiFrameStats.MaxMs:0.0}ms";
}
catch { }
// vafree = free address space (MB): reloads leak engine/plugin copies,
// so a client that dies mid-reload can be checked for running out.
string vaField = "";
try { long free = AddressSpaceMb().FreeMb; if (free >= 0) vaField = $" vafree={free}MB"; }
catch { }
// req=<type>/<age>s = the client is waiting on an item request (it refuses
// every use/move/equip meanwhile); atk=1 = its attacking flag is set. Both
// omitted while open, so a long run of req= in a log is the item-action lock.
string gateField = ClientActionGates.HeartbeatField();
RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}");
// Every 60 s: garbage collections and the time they paused the process.
// Under the CoreCLR host the engine and managed plugins share one GC, so a
// blocking gen2 stalls AC's main thread whenever it is in managed code.
if (tick % 60 == 0)
LogGcStats();
// Every 5 s: hide and destroy any panel window no live panel owns
// (the "double UI" orphans).
if (tick % 5 == 0)
{
try { RynthCore.Engine.UI.LayeredWindow.SweepOrphans(); } catch { }
}
// Cache this client's live metrics so the GetEngineStatusJson host bridge can serve
// them to a plugin (the RynthRemote status export). No file write, no networking.
@ -140,4 +212,22 @@ internal static class HeartbeatLogger
Interlocked.Exchange(ref _exited, 1);
}
}
private static int _gc0, _gc1, _gc2;
private static TimeSpan _gcPause;
private static void LogGcStats()
{
try
{
int g0 = GC.CollectionCount(0), g1 = GC.CollectionCount(1), g2 = GC.CollectionCount(2);
TimeSpan pause = GC.GetTotalPauseDuration();
GCMemoryInfo info = GC.GetGCMemoryInfo(GCKind.Any);
RynthLog.Info($"gc: last 60s g0={g0 - _gc0} g1={g1 - _gc1} g2={g2 - _gc2} paused={(pause - _gcPause).TotalMilliseconds:0}ms " +
$"(last GC gen{info.Generation}{(info.Concurrent ? " background" : "")} {info.PauseDurations[0].TotalMilliseconds:0}ms) " +
$"heap={GC.GetTotalMemory(false) / 1048576}MB concurrent={System.Runtime.GCSettings.LatencyMode != System.Runtime.GCLatencyMode.Batch}");
_gc0 = g0; _gc1 = g1; _gc2 = g2; _gcPause = pause;
}
catch { }
}
}

View file

@ -0,0 +1,196 @@
// ============================================================================
// RynthCore.Engine - Compatibility/IncomingChatHold.cs
//
// Lets a plugin's "eat" (the eatFlag of OnChatWindowText) keep a line out of
// AC's own chat window, not just out of RynthChat.
//
// AC prints chat on its main thread (ClientCommunicationSystem::AddTextToScroll,
// hooked in ChatCallbackHooks). Plugins hear chat on the plugin pump thread, and
// their handlers touch plugin state that only the pump may touch, so they can't
// be called inline from AC's thread. Instead the AddTextToScroll detour HOLDS
// the line (AC doesn't print it yet), the pump hands it to the plugins as
// before, the plugins' verdict is stored on the held line, and AC's main thread
// prints the lines nobody ate, in arrival order, from the next main-thread
// drain (Client::UseTime / EndScene) or the next incoming line, whichever is
// first. A line still waiting after HoldTimeoutMs prints anyway, so a stalled
// pump can delay chat by at most that long and never loses it.
//
// This file is the pure part (no AC, no native calls) so tools\ChatHoldTests can
// compile it in and test the decisions offline. The native part (reading the
// line, calling AC's original to print it) is in ChatCallbackHooks.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>One incoming chat line AC has not printed yet, waiting for the plugins' verdict.</summary>
internal sealed class HeldChatLine
{
public const int Pending = 0;
public const int Show = 1;
public const int Eat = 2;
public HeldChatLine(string raw, uint chatType, uint unknown, IntPtr thisPtr, long heldAtMs)
{
Raw = raw;
ChatType = chatType;
Unknown = unknown;
This = thisPtr;
HeldAtMs = heldAtMs;
}
/// <summary>The text exactly as AC was given it (line breaks included); printed as is.</summary>
public string Raw { get; }
public uint ChatType { get; }
/// <summary>AddTextToScroll's third argument (the client's "offer to the plugin API" flag), passed back unchanged.</summary>
public uint Unknown { get; }
/// <summary>AddTextToScroll's this (the communication system).</summary>
public IntPtr This { get; }
public long HeldAtMs { get; }
private int _verdict;
/// <summary>Pending, Show or Eat. Written once by the pump, read by AC's main thread.</summary>
public int Verdict => Volatile.Read(ref _verdict);
/// <summary>The plugins' verdict (pump thread). The first verdict wins; later ones are ignored.</summary>
public void Decide(bool eat) => Interlocked.CompareExchange(ref _verdict, eat ? Eat : Show, Pending);
}
/// <summary>What the AddTextToScroll detour does with one line.</summary>
internal enum ChatHoldDecision
{
/// <summary>Hold it: AC prints it after the plugins' verdict (unless a plugin eats it).</summary>
Hold,
/// <summary>Print it now, plugins hear it afterwards (the old behaviour). Lines already held stay held.</summary>
PassThrough,
/// <summary>Print every held line now (no verdict needed), then print this one: holding is off or unsafe.</summary>
FlushThenPassThrough,
}
/// <summary>Everything the hold decision looks at, so it can be tested without AC.</summary>
internal readonly record struct ChatHoldInputs(
bool Enabled, // the /rc chathold switch, and the replay path resolved at install
bool Disarmed, // engine teardown has begun
bool OnMainThread, // the detour runs on AC's main thread (the held list is main-thread only)
bool Replaying, // we are inside our own print of a held line (AC re-entered AddTextToScroll)
bool HasText, // the line was read and is not empty
bool Truncated, // the line is longer than we read, so it can't be printed back exactly
bool HasStringInfo, // the caller passed a StringInfo pointer, which won't outlive the call
long NowMs,
long PumpBeatMs, // last time the plugin pump looked at the chat queue (0 = never)
long DrainBeatMs, // last main-thread drain (0 = never)
int HeldCount);
/// <summary>
/// The held lines, oldest first. Only AC's main thread adds to or releases from it; the pump
/// only writes verdicts on the lines themselves, so no lock is needed here.
/// </summary>
internal sealed class HeldChatQueue
{
/// <summary>A line still waiting this long prints anyway.</summary>
public const long HoldTimeoutMs = 400;
/// <summary>Hold only while the plugin pump has looked at the chat queue this recently.</summary>
public const long PumpStaleMs = 250;
/// <summary>Hold only while the main-thread drain (which prints held lines) ran this recently.</summary>
public const long DrainStaleMs = 500;
/// <summary>Never hold more than this many lines; past it, everything prints at once.</summary>
public const int MaxHeld = 256;
private readonly Queue<HeldChatLine> _lines = new();
public int Count => _lines.Count;
// Counters for /rc chathold status. Written on AC's main thread only.
public long HeldTotal { get; private set; }
public long ShownTotal { get; private set; }
public long EatenTotal { get; private set; }
public long TimedOutTotal { get; private set; }
public long PrintFailedTotal { get; private set; }
public static ChatHoldDecision Decide(in ChatHoldInputs i)
{
// Inside our own print (AC calls AddTextToScroll again from inside it): print in place,
// and never touch the held list while a release is walking it.
if (i.Replaying)
return ChatHoldDecision.PassThrough;
// The held list belongs to AC's main thread. A line from any other thread prints as before.
if (!i.OnMainThread)
return ChatHoldDecision.PassThrough;
// Holding is off, the engine is going away, or nobody would answer or print the line in
// time: print what is held (keeps the order) and stop holding.
if (!i.Enabled || i.Disarmed)
return ChatHoldDecision.FlushThenPassThrough;
if (i.PumpBeatMs == 0 || i.NowMs - i.PumpBeatMs > PumpStaleMs)
return ChatHoldDecision.FlushThenPassThrough;
if (i.DrainBeatMs == 0 || i.NowMs - i.DrainBeatMs > DrainStaleMs)
return ChatHoldDecision.FlushThenPassThrough;
if (i.HeldCount >= MaxHeld)
return ChatHoldDecision.FlushThenPassThrough;
// A line we couldn't print back exactly prints now. Lines still waiting for a verdict
// stay held (they print a frame later), so a line a plugin eats stays hidden.
if (!i.HasText || i.Truncated || i.HasStringInfo)
return ChatHoldDecision.PassThrough;
return ChatHoldDecision.Hold;
}
/// <summary>
/// The plugins' verdict on one line: eaten when any plugin set the eat flag and none of
/// them threw on it. A plugin that throws can't be trusted to have meant it, so the line shows.
/// </summary>
public static bool PluginsAteIt(int eatFlag, bool anyPluginThrew) => eatFlag != 0 && !anyPluginThrew;
public void Add(HeldChatLine line)
{
_lines.Enqueue(line);
HeldTotal++;
}
/// <summary>
/// Prints the lines that may print now, oldest first: shown lines, and lines that waited
/// longer than <see cref="HoldTimeoutMs"/> (all of them when <paramref name="flushAll"/>).
/// Eaten lines are dropped. Stops at the first line still waiting, so the order never
/// changes. A print that throws is counted and skipped. Returns how many lines printed.
/// </summary>
public int Release(long nowMs, bool flushAll, Action<HeldChatLine> print)
{
int printed = 0;
while (_lines.Count > 0)
{
HeldChatLine line = _lines.Peek();
int verdict = line.Verdict;
if (verdict == HeldChatLine.Pending && !flushAll && nowMs - line.HeldAtMs < HoldTimeoutMs)
break;
_lines.Dequeue();
if (verdict == HeldChatLine.Eat)
{
EatenTotal++;
continue;
}
if (verdict == HeldChatLine.Pending)
TimedOutTotal++;
else
ShownTotal++;
try
{
print(line);
printed++;
}
catch
{
PrintFailedTotal++;
}
}
return printed;
}
}

File diff suppressed because it is too large Load diff

View file

@ -82,6 +82,23 @@ internal static class LogoBypassHooks
return;
}
// An engine hot reload (gen 2+) runs this step long before the reload marks the login
// complete, while the character stands in the world. The early burst then clicked
// (350, 100) up to 12 times, 400 ms apart, into the 3D view: AC reads two clicks that
// close together as a double-click and USES whatever is under that spot, so a door or a
// corpse there opened, closed, opened... "before the bot is on" (2026-10-04). The logo
// screens only exist when the client starts, so a reload never needs a dismiss click.
if (EntryPoint.InitCount >= 2)
{
RynthLog.Compat($"LogoBypass: engine hot reload (initCount={EntryPoint.InitCount}) - the client is past the logo screens, no dismiss clicks.");
return;
}
if (IsInGameWorld(out string where))
{
RynthLog.Compat($"LogoBypass: the client is already in the game world ({where}) - no dismiss clicks.");
return;
}
_started = true;
lock (StateLock)
{
@ -90,12 +107,7 @@ internal static class LogoBypassHooks
_recommendedAutoLoginTick = 0;
}
var thread = new Thread(BypassThread)
{
Name = "RynthCore.LogoBypass",
IsBackground = true
};
thread.Start();
EngineThreads.Start("RynthCore.LogoBypass", BypassThread);
RynthLog.Compat("LogoBypass: Started - waiting for post-connect or character-list signal before dismiss clicks.");
}
@ -151,7 +163,8 @@ internal static class LogoBypassHooks
if (LoginLifecycleHooks.HasObservedLoginComplete)
return;
SendDismissInput(hwnd);
Thread.Sleep(EarlyBurstIntervalMs);
if (!EngineThreads.Sleep(EarlyBurstIntervalMs))
return;
}
}
@ -204,7 +217,8 @@ internal static class LogoBypassHooks
if (found != IntPtr.Zero)
return found;
Thread.Sleep(HwndPollMs);
if (!EngineThreads.Sleep(HwndPollMs))
return IntPtr.Zero;
elapsed += HwndPollMs;
}
@ -221,13 +235,14 @@ internal static class LogoBypassHooks
{
if (TryTakeDueDismissClick())
SendDismissInput(hwnd);
else
Thread.Sleep(IdlePollMs);
else if (!EngineThreads.Sleep(IdlePollMs))
break;
}
}
finally
{
string reason = LoginLifecycleHooks.HasObservedLoginComplete ? "login complete" : "timeout";
string reason = LoginLifecycleHooks.HasObservedLoginComplete ? "login complete"
: EngineThreads.Stopping ? "engine shutdown" : "timeout";
RynthLog.Verbose($"LogoBypass: Stopped ({reason}).");
}
}
@ -249,8 +264,40 @@ internal static class LogoBypassHooks
}
}
private static int _withheldClicks;
/// <summary>
/// True when the character is in the game world: AC's UI flow is in GamePlayUI, or the
/// login has completed. A click there lands in the 3D view, where two of them make a
/// double-click that uses the object under the cursor.
/// </summary>
private static bool IsInGameWorld(out string where)
{
where = "";
if (LoginLifecycleHooks.HasObservedLoginComplete) { where = "login complete"; return true; }
try
{
if (CharacterManagementHooks.TryGetCurrentMode(out int mode) && mode == GamePlayUIMode)
{
where = $"UI mode 0x{mode:X8} (GamePlayUI)";
return true;
}
}
catch { }
return false;
}
private const int GamePlayUIMode = 0x10000008; // same value CharacterCaptureHooks checks
private static void SendDismissInput(IntPtr hwnd)
{
// Last guard before every click: never into the game world (see Start).
if (IsInGameWorld(out string where))
{
if (Interlocked.Increment(ref _withheldClicks) == 1)
RynthLog.Compat($"LogoBypass: dismiss click withheld - the client is in the game world ({where}).");
return;
}
IntPtr lParam = MakeLParam(DismissClickX, DismissClickY);
PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam);
PostMessage(hwnd, WM_LBUTTONDOWN, (IntPtr)0x0001, lParam);

View file

@ -230,6 +230,10 @@ internal static unsafe class LogoffOriginProbe
private static void OnRequest(string fn, string args)
{
// First, before any logging: AC frees UI objects during the logoff.
ChatHooks.OnLogoffRequested();
RadarHooks.OnLogoffRequested();
RetailVitalsHooks.OnLogoffRequested();
long now = Environment.TickCount64;
IntPtr caller = LogoutLifecycleHooks.LogCaller(fn, "LogoffProbe");
string callerText = DescribeAcclientAddress(caller);

View file

@ -0,0 +1,119 @@
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// One main-thread refresh point for the small per-frame snapshots that the
/// plugin pump (and other engine threads) read instead of touching AC.
///
/// AC's client is single-threaded. The plugin pump ("RynthCore.NormalPluginPump")
/// and the helper threads must not call AC functions or read AC memory that the
/// main thread mutates or frees; they read values sampled here instead. Called
/// from two places that both run on AC's main thread:
/// * GameTickHooks.UseTimeDetour, after AC's own tick and the queue drain. It
/// fires in every mode, before login too.
/// * EngineFrameController.OnEndScene, next to the other prefetches (EndScene
/// is only hooked after login).
/// Each step throttles itself, so running from both is cheap. Nothing here may
/// allocate per call or wait on another thread.
/// </summary>
internal static class MainThreadSnapshots
{
// Host ProbeClientHooksFn from the plugin pump: re-probe on the main thread.
private static int _clientHookProbeRequested;
private static long _nextSmartBoxProbeMs;
public static void RequestClientHookProbe() =>
System.Threading.Volatile.Write(ref _clientHookProbeRequested, 1);
public static void Tick()
{
// Both call sites are AC's main thread by construction (same reasoning as
// AcMainThreadQueue.Drain, which latches here too).
MainThreadGuard.RecordIfFirst();
if (!MainThreadGuard.IsOnMainThread())
return;
// Teardown: the detours stay live until MH_DisableHook(ALL) and Shutdown is
// resetting hook state; nobody reads these snapshots any more (the pump is
// stopped first), so stop touching AC here, like AcMainThreadQueue.Disarm.
if (EngineLifecycle.IsShuttingDown)
return;
if (System.Threading.Volatile.Read(ref _clientHookProbeRequested) != 0
&& System.Threading.Interlocked.Exchange(ref _clientHookProbeRequested, 0) != 0)
{
try
{
ClientActionHooks.Probe();
RynthLog.Compat("ProbeClientHooks: re-probed on AC's main thread (plugin request).");
}
catch { }
}
// Player id cache (off-thread GetPlayerId callers). Two loads, unthrottled.
try { ClientHelperHooks.GetPlayerId(); } catch { }
// The two SmartBox-based samples below must not trigger SmartBoxLocator's
// lazy re-probe (a .text pattern scan) on every frame if the bootstrap probe
// failed: retry it here at most every 10 s instead.
bool smartBoxReady = SmartBoxLocator.IsInitialized;
if (!smartBoxReady)
{
long now = System.Environment.TickCount64;
if (now >= _nextSmartBoxProbeMs)
{
_nextSmartBoxProbeMs = now + 10_000;
try { smartBoxReady = SmartBoxLocator.Probe(); } catch { }
}
}
// Cast gate: CMotionInterp's pending-motion head, read here instead of on
// the pump (the SmartBox player -> MovementManager -> CMotionInterp chain
// dies with the player's physics object at logout / char switch).
if (smartBoxReady)
{
try { CastGate.Sample(); } catch { }
}
// Player pose + heading (seqlock copy): nav, radar, Jumper, Nav3D, GetCurCoords.
// Publishes "no pose" while SmartBox is not located.
try { PlayerPhysicsHooks.PublishPoseSnapshot(smartBoxReady); } catch { }
// The qualities walks below (base vitals, enchantment registries) need a
// live player object. Between gmGamePlayUI::RecvNotice_Logoff and the pump's
// logout dispatch (which zeroes KnownPlayerQualitiesPtr) the cached pointer
// can outlive the object, and during a DB-cache teardown AC is freeing them.
bool playerLive = !LogoutLifecycleHooks.HasObservedLogout
&& !DbCacheTeardownHooks.TeardownActive
&& ClientHelperHooks.GetPlayerId() != 0;
// Base (unbuffed) max vitals for host GetPlayerBaseVitalsFn (~1 Hz).
if (playerLive)
{
try { PlayerVitalsHooks.PrefetchBaseVitals(); } catch { }
}
// PlayerInReadyPosition for host IsPlayerReadyFn (~5 Hz).
try { ClientCombatHooks.SampleReady(); } catch { }
// Account name cache (host GetAccountNameFn): only while still cold.
try { AccountHooks.WarmFromMainThread(); } catch { }
// Enchantment registries: the player's (250 ms, or next tick after an
// enchantment event) and any objects plugins asked about (500 ms).
try { EnchantmentHooks.PrefetchPlayerEnchantments(playerLive); } catch { }
if (playerLive)
{
try { EnchantmentHooks.PrefetchWatchedObjectEnchantments(); } catch { }
// Inventory panel: sends the one requested item action, watches it, and
// captures the packs (throttled; returns at once while the panel is closed
// and nothing is in flight). Only while the player object is live.
try { InventoryModel.MainThreadTick(); } catch { }
// Skills panel: ranks, XP spent and buffs (500 ms, only while the panel is open).
// After the enchantment snapshot so its buffs are this tick's.
try { PlayerProgressHooks.Prefetch(); } catch { }
}
// Aelrynth skill mastery: the /mastery-data request after login, on panel open
// and after a raise (only on Aelrynth; a few compares when nothing is wanted).
try { MasteryFeed.MainThreadTick(playerLive); } catch { }
}
}

View file

@ -0,0 +1,340 @@
// ============================================================================
// RynthCore.Engine - Compatibility/MasteryFeed.cs
//
// Aelrynth skill mastery for the Skills panel. The numbers exist only on the
// server: the SkillMastery mod answers "/mastery-data" with ONE chat line,
// "~ael1 " + JSON (AelrynthWire.cs parses it). This feed asks for that line,
// reads it, and hides it from chat.
//
// Only ever on Aelrynth (ServerInfo.IsAelrynth): anywhere else nothing is sent,
// because another server would answer "Unknown command". If an Aelrynth server
// answers that anyway (the mod switched off), the feed stops asking until the
// next login.
//
// When it asks (each rate limited: one request in flight, 4 s apart at least):
// - once, 4 s after login (waits up to a minute for detection to settle);
// - when the Skills panel opens and the last reply is over 30 s old;
// - 2 s after a mastery raise this feed sent;
// - "/rc mastery".
//
// Hiding: the incoming-chat hook (ChatCallbackHooks.IncomingChatAddTextDetour)
// offers every line to OnIncomingLine first. A data line that answers OUR
// request (sent in the last 15 s), and ACE's "Unknown command: mastery-data"
// for it, are eaten: not drawn, not passed on. A line the player asked for by
// typing /mastery-data is read but left in chat.
//
// Threads: MainThreadTick and OnIncomingLine run on AC's main thread (the only
// place a command is sent). The panel's calls (PanelOpened, RequestRefresh,
// QueueRaise, Snapshot) are any-thread: they set fields under a small lock and
// the main thread does the sending.
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>One published reply with what the panel needs beside it. Immutable.</summary>
internal sealed class MasterySnapshot
{
public required MasteryData Data { get; init; }
public required int Version { get; init; }
public required long ReceivedMs { get; init; }
/// <summary>The Bank mod's Radiance-earned property (9101) when the reply arrived; -1 when the server doesn't send it.</summary>
public required long EarnedAtReceipt { get; init; }
}
internal static class MasteryFeed
{
private const int LoginDelayMs = 4000;
private const int LoginGiveUpMs = 60_000;
private const int MinIntervalMs = 4000;
private const int ReplyWindowMs = 15_000;
private const int StaleMs = 30_000;
private const int AfterRaiseMs = 2000;
private const int MinRaiseIntervalMs = 1500;
private const int MaxSendFailures = 3;
private static readonly object Gate = new();
// Any thread, under Gate.
private static long _wantAtMs; // 0 = no request wanted
private static string? _raiseCommand;
private static string _raiseLabel = "";
// Main thread only.
private static uint _playerId;
private static long _loginAtMs;
private static bool _loginPending;
private static long _lastDataSendMs = -MinIntervalMs;
private static long _lastRaiseMs = -MinRaiseIntervalMs;
private static int _sendFailures;
private static int _version;
// Read anywhere.
private static volatile MasterySnapshot? _snapshot;
private static long _awaitingUntilMs; // our request's reply window (Volatile)
private static volatile bool _unsupported;
private static volatile string _status = "not asked yet";
/// <summary>The last reply, or null (none this login). Any thread.</summary>
public static MasterySnapshot? Snapshot => _snapshot;
/// <summary>This login's Aelrynth server answered "Unknown command": nothing more is asked until the next login.</summary>
public static bool Unsupported => _unsupported;
/// <summary>
/// Our incoming-chat hook isn't installed (Decal bridge mode leaves AddTextToScroll to
/// Decal), so a reply could be neither read nor hidden: nothing is asked or raised, and
/// the server's JSON line never lands in the player's chat. Any thread.
/// </summary>
public static bool NoChatHook => !ChatCallbackHooks.IncomingInstalled;
/// <summary>A request is out and its reply not in yet.</summary>
public static bool Awaiting => Environment.TickCount64 < Volatile.Read(ref _awaitingUntilMs);
/// <summary>What the feed did last, for /rc mastery and the panel.</summary>
public static string Status => _status;
// ── Any thread: the panel and /rc ───────────────────────────────────
/// <summary>The Skills panel opened: ask unless the last reply is fresh. Does nothing off Aelrynth.</summary>
public static void PanelOpened()
{
if (!ServerInfo.IsAelrynth || _unsupported) return;
MasterySnapshot? s = _snapshot;
if (s == null || Environment.TickCount64 - s.ReceivedMs > StaleMs)
RequestAt(Environment.TickCount64);
}
/// <summary>Ask now (still rate limited). Does nothing off Aelrynth.</summary>
public static void RequestRefresh()
{
if (!ServerInfo.IsAelrynth || _unsupported) return;
RequestAt(Environment.TickCount64);
}
private static void RequestAt(long atMs)
{
lock (Gate)
{
if (_wantAtMs == 0 || atMs < _wantAtMs)
_wantAtMs = Math.Max(1, atMs);
}
}
/// <summary>
/// Queues one "/raise &lt;skill&gt; &lt;count&gt;" for the main thread (the caller has
/// confirmed with the player). False with the reason when it can't be sent.
/// </summary>
public static bool QueueRaise(MasterySkill skill, int count, out string why)
{
if (!ServerInfo.IsAelrynth) { why = "Not on Aelrynth."; return false; }
if (_unsupported) { why = "This server has no mastery commands."; return false; }
if (NoChatHook) { why = "Not available under Decal (Decal owns incoming chat, so the reply can't be read)."; return false; }
string? cmd = MasteryWire.RaiseCommand(skill.Key, count);
if (cmd == null) { why = "That skill's name can't be sent to the server."; return false; }
lock (Gate)
{
if (_raiseCommand != null) { why = "A raise is already on its way."; return false; }
_raiseCommand = cmd;
_raiseLabel = $"{skill.Name} +{count}";
}
why = "";
return true;
}
/// <summary>
/// The Radiance a raise can spend now, as near as the client knows: the balance in
/// the last reply plus what the Bank mod says was earned since (property 9101 rising).
/// Earnings from the last few seconds may not be banked yet, so the server can still
/// refuse a raise this says fits. Any thread (dictionary reads); call it about once a second.
/// </summary>
public static long EstimateRadiance(MasterySnapshot s)
{
long r = s.Data.Radiance;
if (s.EarnedAtReceipt >= 0 && ServerInfo.TryGetRadianceEarned(out long earned) && earned > s.EarnedAtReceipt)
r += earned - s.EarnedAtReceipt;
return r;
}
// ── AC's main thread ────────────────────────────────────────────────
/// <summary>
/// MainThreadSnapshots.Tick, every tick. <paramref name="playerLive"/>: the player
/// object is usable (commands are only sent then); a logout (or no player) ends the
/// login, so the next one asks again even on the same character. A few compares when
/// nothing is wanted; sends at most one command per call.
/// </summary>
internal static void MainThreadTick(bool playerLive)
{
if (!MainThreadGuard.IsOnMainThread())
return;
long now = Environment.TickCount64;
uint me = LogoutLifecycleHooks.HasObservedLogout ? 0 : ClientHelperHooks.GetPlayerId();
if (me != _playerId)
NewLogin(me, now);
if (me == 0 || !playerLive)
return;
// Idle: two volatile loads, no lock.
if (!_loginPending && Volatile.Read(ref _wantAtMs) == 0 && Volatile.Read(ref _raiseCommand) == null)
return;
string? raise;
long wantAt;
lock (Gate)
{
raise = _raiseCommand;
wantAt = _wantAtMs;
}
if (!_loginPending && wantAt == 0 && raise == null)
return;
if (NoChatHook)
{
// Decal bridge mode: the reply would show in chat and never reach us.
_loginPending = false;
if (wantAt != 0 || raise != null)
lock (Gate) { _wantAtMs = 0; _raiseCommand = null; }
_status = "not asked: Decal owns incoming chat (bridge mode), so the reply can't be read or hidden";
return;
}
if (!ServerInfo.IsAelrynth || _unsupported)
{
// Detection can settle a few seconds into the login (the Bank properties, the
// world name): the login request waits for it, up to a minute.
if (_loginPending && now - _loginAtMs > LoginGiveUpMs)
_loginPending = false;
if (wantAt != 0 || raise != null)
{
lock (Gate) { _wantAtMs = 0; _raiseCommand = null; }
if (raise != null)
_status = _unsupported ? "raise not sent: this server has no mastery commands" : "raise not sent: not on Aelrynth";
}
return;
}
if (raise != null && now - _lastRaiseMs >= MinRaiseIntervalMs)
{
string label;
lock (Gate) { _raiseCommand = null; label = _raiseLabel; }
_lastRaiseMs = now;
if (ChatCommandDispatcher.SendServerCommand(raise))
{
_status = $"sent: raise {label}";
RynthLog.Compat($"MasteryFeed: sent {raise}");
RequestAt(now + AfterRaiseMs);
}
else
{
_status = $"raise {label} could not be sent";
}
return; // one command per tick
}
if (_loginPending && now - _loginAtMs >= LoginDelayMs)
{
_loginPending = false;
RequestAt(now);
wantAt = now;
}
if (wantAt != 0 && now >= wantAt && now - _lastDataSendMs >= MinIntervalMs && !Awaiting)
{
lock (Gate) { _wantAtMs = 0; }
_lastDataSendMs = now;
_loginPending = false; // the panel asked first: that covers the login request
if (ChatCommandDispatcher.SendServerCommand(MasteryWire.DataRequest))
{
Volatile.Write(ref _awaitingUntilMs, now + ReplyWindowMs);
_sendFailures = 0;
_status = "asked the server";
}
else if (++_sendFailures < MaxSendFailures)
{
RequestAt(now + 10_000);
_status = "could not send the request; trying again shortly";
}
else
{
_status = "could not send the request (the client's talk function isn't bound)";
}
}
}
private static void NewLogin(uint me, long now)
{
_playerId = me;
_loginAtMs = now;
_loginPending = me != 0;
_snapshot = null;
_unsupported = false;
_sendFailures = 0;
Volatile.Write(ref _awaitingUntilMs, 0);
lock (Gate) { _wantAtMs = 0; _raiseCommand = null; }
_status = me != 0 ? "waiting to ask after login" : "logged out";
}
/// <summary>
/// Every incoming chat line, from the chat hook (AC's main thread), before AC draws
/// it. True = eat it (our own request's reply). Never throws.
/// </summary>
internal static bool OnIncomingLine(string line)
{
try
{
if (line.Length < 8)
return false;
bool awaiting = Awaiting;
if (MasteryWire.IsDataLine(line))
{
if (!ServerInfo.IsAelrynth)
return false;
if (MasteryWire.TryParse(line, out MasteryData? data) && data != null)
{
Publish(data);
Volatile.Write(ref _awaitingUntilMs, 0);
return awaiting;
}
// Not a mastery line (another mod's data line), or one too damaged to read.
if (awaiting && line.Contains("\"t\":\"mastery\"", StringComparison.Ordinal))
{
Volatile.Write(ref _awaitingUntilMs, 0);
_status = "the server's reply could not be read";
RynthLog.Compat($"MasteryFeed: unreadable reply ({line.Length} chars)");
return true;
}
return false;
}
if (awaiting && MasteryWire.IsUnknownCommand(line, MasteryWire.DataCommand))
{
_unsupported = true;
Volatile.Write(ref _awaitingUntilMs, 0);
_status = "this server has no mastery commands (asked once; not again until the next login)";
RynthLog.Compat("MasteryFeed: the server answered Unknown command: mastery-data - not asking again this login.");
return true;
}
return false;
}
catch
{
return false;
}
}
private static void Publish(MasteryData data)
{
long earned = ServerInfo.TryGetRadianceEarned(out long e) ? e : -1;
_snapshot = new MasterySnapshot
{
Data = data,
Version = ++_version,
ReceivedMs = Environment.TickCount64,
EarnedAtReceipt = earned,
};
_status = data.Ok
? $"{data.Skills.Count} skills, {data.Radiance:N0} Radiance banked"
: "the server could not read your mastery" + (data.Why.Length > 0 ? $" ({data.Why})" : "");
}
}

View file

@ -0,0 +1,294 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// "Can I read (or write) this AC memory without an access violation?" for NativeAOT, where an
/// AV cannot be caught. Every IsReadablePointer / IsReadableSpan / IsMemoryReadable /
/// IsWritablePointer in the engine answers through here.
///
/// WHY NOT JUST VirtualQuery (what they all used until 2026-10-02): in a 32-bit process on
/// 64-bit Windows, VirtualQuery's cost grows with the size of the committed region AFTER the
/// address asked about - the kernel walks the page tables to work out RegionSize. Measured on
/// the i7-4770K (tools/FloodProbeBench): 10 us on a small heap block, 0.35 ms 16 MB from the end
/// of a committed run, 2.6 ms at 64 MB, 11 ms at 256 MB, 19 ms at 512 MB. AC's heap reaches
/// 1.0-1.4 GB in a crowded dungeon, and the main-thread snapshot walks probed every hash bucket
/// and 3-4 spots of every object 10 times a second (identity/attackable walks 2 more times),
/// so a big heap turned each walk into tens to hundreds of milliseconds on AC's thread: the
/// 3-10 fps collapse in Matron Hive South (Lucy, 2026-10-02), still there after logout because
/// the heap stays committed.
///
/// HOW: QueryWorkingSetEx answers per PAGE (about 2 us for one call, under 0.1 us per extra
/// page in the same call) no matter how big the region is. A page that is resident ("Valid")
/// is committed, and the call returns its protection, so the old rule is checked exactly:
/// committed, not NOACCESS, not GUARD, plus readable/writable where the caller asked. Only when
/// a page is NOT resident (trimmed to the standby list, never touched, reserved, free) does it
/// fall back to the old VirtualQuery test, which then decides exactly as before. A span is
/// accepted when every page in it passes (VirtualQuery additionally insisted on one region;
/// two adjacent readable regions read just as safely).
///
/// Thread-safe and allocation-free (stackalloc). Counters are for the [SnapshotDiag] line.
/// The snapshot walks open a <see cref="BeginWalk"/> scope so each page is queried once per
/// walk rather than once per probe.
/// </summary>
internal static unsafe class MemoryProbe
{
private const uint MEM_COMMIT = 0x1000;
private const uint PAGE_NOACCESS = 0x01;
private const uint PAGE_GUARD = 0x100;
/// <summary>Any page protection that can be read (READONLY, READWRITE, WRITECOPY, EXECUTE_READ, ...).</summary>
internal const uint ReadableMask = 0x02 | 0x04 | 0x08 | 0x20 | 0x40 | 0x80;
/// <summary>Any page protection that can be written (READWRITE, WRITECOPY, EXECUTE_READWRITE, EXECUTE_WRITECOPY).</summary>
internal const uint WritableMask = 0x04 | 0x08 | 0x40 | 0x80;
private const int PageShift = 12;
private const long PageSize = 1L << PageShift;
/// <summary>Spans longer than this many pages go straight to VirtualQuery. 80 pages = 320 KB covers the
/// largest CObjectMaint bucket array the walk accepts (65536 buckets x 4 bytes = 64 pages).</summary>
private const int MaxFastPages = 80;
private static readonly IntPtr CurrentProcess = new(-1);
// 1 = QueryWorkingSetEx unavailable or failing: every probe uses VirtualQuery (old behaviour).
private static int _fastDisabled;
private static long _fastPages;
private static long _slowCalls;
private static long _slowTicks;
[StructLayout(LayoutKind.Sequential)]
private struct WorkingSetExInfo
{
public IntPtr VirtualAddress;
public UIntPtr Flags;
}
[StructLayout(LayoutKind.Sequential)]
private struct MemoryBasicInformation
{
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public uint AllocationProtect;
public IntPtr RegionSize;
public uint State;
public uint Protect;
public uint Type;
}
[DllImport("kernel32.dll", EntryPoint = "K32QueryWorkingSetEx")]
private static extern int QueryWorkingSetEx(IntPtr process, WorkingSetExInfo* info, uint size);
[DllImport("kernel32.dll")]
private static extern int VirtualQuery(IntPtr address, MemoryBasicInformation* info, int length);
/// <summary>Committed, not NOACCESS/GUARD (the old IsReadablePointer / IsReadableSpan rule).</summary>
public static bool IsAccessible(IntPtr ptr, int length = 1) => Check(ptr, length, 0);
/// <summary>Committed, not NOACCESS/GUARD, and a readable protection (the old SmartBoxLocator rule).</summary>
public static bool IsReadable(IntPtr ptr, int length = 1) => Check(ptr, length, ReadableMask);
/// <summary>Committed, not NOACCESS/GUARD, and a writable protection (the old IsWritablePointer rule).</summary>
public static bool IsWritable(IntPtr ptr, int length = 1) => Check(ptr, length, WritableMask);
/// <summary>
/// Probe counters since the last call: pages answered by QueryWorkingSetEx, and the
/// VirtualQuery fallbacks with their total time. Resets them.
/// </summary>
public static (long FastPages, long SlowCalls, double SlowMs) TakeStats()
{
long fast = Interlocked.Exchange(ref _fastPages, 0);
long slow = Interlocked.Exchange(ref _slowCalls, 0);
long ticks = Interlocked.Exchange(ref _slowTicks, 0);
return (fast, slow, ticks * 1000.0 / System.Diagnostics.Stopwatch.Frequency);
}
/// <summary>True while the QueryWorkingSetEx path is in use (false = every probe is a VirtualQuery).</summary>
public static bool FastPathActive => Volatile.Read(ref _fastDisabled) == 0;
// ── Walk scope: remember resident pages for the length of one snapshot walk ──────────
// A walk over every object probes 3-10 spots per object, almost all on one or two pages.
// Inside a scope (AC's main thread, inside one walk, AC itself not running) a page found
// resident keeps its answer until the scope ends, so a page costs one query per walk
// instead of one per probe. Only the thread that opened the scope uses the cache; a probe
// from any other thread asks the system as usual. Plain statics with an owner thread, not
// [ThreadStatic]: the engine can live in a collectible context (CoreCLR host).
private const int CacheSlots = 1024;
private static readonly uint[] _cachePage = new uint[CacheSlots]; // page number + 1 (0 = empty slot)
private static readonly ushort[] _cacheProt = new ushort[CacheSlots]; // that page's Win32Protection
private static int _scopeOwner; // managed thread id that holds the scope (0 = none)
private static int _scopeDepth; // nesting on the owner thread
/// <summary>
/// Opens a page cache for one main-thread snapshot walk (dispose to close; nests). Only
/// for code that reads AC memory while AC is not running (the EndScene / UseTime walks).
/// A second thread asking while another holds the scope just gets no cache.
/// </summary>
public static WalkScope BeginWalk()
{
int me = Environment.CurrentManagedThreadId;
if (Volatile.Read(ref _scopeOwner) == me)
{
_scopeDepth++;
return new WalkScope(true);
}
if (Interlocked.CompareExchange(ref _scopeOwner, me, 0) != 0)
return new WalkScope(false);
_scopeDepth = 1;
Array.Clear(_cachePage);
return new WalkScope(true);
}
internal readonly struct WalkScope : IDisposable
{
private readonly bool _open;
public WalkScope(bool open) => _open = open;
public void Dispose()
{
if (!_open || Volatile.Read(ref _scopeOwner) != Environment.CurrentManagedThreadId)
return;
if (--_scopeDepth <= 0)
{
_scopeDepth = 0;
Volatile.Write(ref _scopeOwner, 0);
}
}
}
private static bool InScope => _scopeDepth > 0 && Volatile.Read(ref _scopeOwner) == Environment.CurrentManagedThreadId;
// Protection of a resident page from the walk cache, or 0 when not cached.
private static uint CachedProtection(ulong page)
{
int slot = (int)(page & (CacheSlots - 1));
return _cachePage[slot] == (uint)page + 1 ? _cacheProt[slot] : 0u;
}
private static void RememberProtection(ulong page, uint protect)
{
int slot = (int)(page & (CacheSlots - 1));
_cachePage[slot] = (uint)page + 1;
_cacheProt[slot] = (ushort)protect;
}
private static int Judge(uint protect, uint requiredMask)
{
if ((protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0)
return 0;
if (requiredMask != 0 && (protect & requiredMask) == 0)
return 0;
return 1;
}
private static bool Check(IntPtr ptr, int length, uint requiredMask)
{
if (ptr == IntPtr.Zero || length <= 0)
return false;
if (Volatile.Read(ref _fastDisabled) == 0)
{
int verdict = TryFast(ptr, length, requiredMask);
if (verdict >= 0)
return verdict == 1;
}
return Slow(ptr, length, requiredMask);
}
// 1 = every page resident and acceptable, 0 = a resident page is refused,
// -1 = can't tell here (a page is not resident, span too long, or the call failed).
private static int TryFast(IntPtr ptr, int length, uint requiredMask)
{
ulong start = unchecked((ulong)(nuint)ptr);
ulong last = start + (ulong)(length - 1);
if (last > uint.MaxValue)
return 0; // runs past the 32-bit address space: never readable
ulong firstPage = start >> PageShift;
ulong lastPage = last >> PageShift;
ulong pageCount = lastPage - firstPage + 1;
if (pageCount > MaxFastPages)
return -1;
int n = (int)pageCount;
// Inside a walk scope: answer from the pages already seen in this walk.
bool inScope = InScope;
if (inScope)
{
bool allCached = true;
for (int i = 0; i < n && allCached; i++)
{
uint cached = CachedProtection(firstPage + (ulong)i);
if (cached == 0) allCached = false;
else if (Judge(cached, requiredMask) == 0) return 0;
}
if (allCached)
return 1;
}
WorkingSetExInfo* info = stackalloc WorkingSetExInfo[n];
for (int i = 0; i < n; i++)
{
info[i].VirtualAddress = (IntPtr)(nint)(long)((firstPage + (ulong)i) << PageShift);
info[i].Flags = UIntPtr.Zero;
}
int ok;
try
{
ok = QueryWorkingSetEx(CurrentProcess, info, (uint)(n * sizeof(WorkingSetExInfo)));
}
catch
{
// Entry point missing (pre-Windows 7 kernel32) or the call itself failed: VirtualQuery from now on.
Interlocked.Exchange(ref _fastDisabled, 1);
return -1;
}
if (ok == 0)
return -1;
Interlocked.Add(ref _fastPages, n);
for (int i = 0; i < n; i++)
{
ulong flags = (ulong)(nuint)info[i].Flags;
if ((flags & 1) == 0)
return -1; // not resident: committed-but-trimmed, untouched, reserved or free - ask VirtualQuery
uint protect = (uint)((flags >> 4) & 0x7FF); // PSAPI_WORKING_SET_EX_BLOCK.Win32Protection
if (protect == 0)
return -1; // resident but no protection reported: let VirtualQuery decide
if (inScope) RememberProtection(firstPage + (ulong)i, protect);
if (Judge(protect, requiredMask) == 0)
return 0;
}
return 1;
}
// The pre-2026-10-02 rule, unchanged: one VirtualQuery, the span inside that one region.
private static bool Slow(IntPtr ptr, int length, uint requiredMask)
{
long t0 = System.Diagnostics.Stopwatch.GetTimestamp();
try
{
MemoryBasicInformation mbi;
if (VirtualQuery(ptr, &mbi, sizeof(MemoryBasicInformation)) == 0)
return false;
if (mbi.State != MEM_COMMIT)
return false;
if ((mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0)
return false;
if (requiredMask != 0 && (mbi.Protect & requiredMask) == 0)
return false;
if (length <= 1)
return true;
ulong regionEnd = unchecked((ulong)(nuint)mbi.BaseAddress + (ulong)(nuint)mbi.RegionSize);
ulong spanEnd = unchecked((ulong)(nuint)ptr + (ulong)length);
return spanEnd <= regionEnd;
}
finally
{
Interlocked.Increment(ref _slowCalls);
Interlocked.Add(ref _slowTicks, System.Diagnostics.Stopwatch.GetTimestamp() - t0);
}
}
}

View file

@ -0,0 +1,177 @@
// ============================================================================
// RynthCore.Engine - Compatibility/MessageBoxHooks.cs
// Logs every message box shown in this process (user32!MessageBoxW / A):
// caption, text, style and the calling module, when it opens and when it
// closes.
//
// Why: AC reports some errors in a modal MessageBox on its main thread
// (acclient+0x3CE80, formatted by the caller at acclient+0x1558B5). The main
// thread then waits on the dialog, MainThreadHangWatchdog reports a wedge,
// and the launcher kills and relaunches the client - with the dialog's text
// lost (the 2026-09-28 Drakkon6 close: heap isn't in the hang minidump).
// Now the text is in the log, and the watchdog names the open dialog in its
// hang report (see Describe).
//
// The detour only observes: it always calls the original and returns its
// result. Installed per engine generation; EngineLifecycle's
// MH_DisableHook(ALL) removes it on reload.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static class MessageBoxHooks
{
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int MessageBoxDelegate(IntPtr hWnd, IntPtr text, IntPtr caption, uint type);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr LoadLibraryW(string lpLibFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[DllImport("kernel32.dll")]
private static extern ushort RtlCaptureStackBackTrace(uint framesToSkip, uint framesToCapture, IntPtr[] backTrace, out uint hash);
[DllImport("kernel32.dll")]
private static extern uint GetCurrentThreadId();
private static MessageBoxDelegate? _detourW, _detourA, _originalW, _originalA;
private static int _installed;
// The dialog currently open (last one wins if several nest). Read by the
// hang watchdog's thread; written on the thread showing the dialog.
private static volatile string? _openDescription;
private static long _openedAtTicks;
private static int _openCount;
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0) return;
try
{
IntPtr user32 = GetModuleHandleW("user32.dll");
if (user32 == IntPtr.Zero) user32 = LoadLibraryW("user32.dll");
if (user32 == IntPtr.Zero)
{
RynthLog.Compat("MessageBoxHooks: user32 not found.");
return;
}
_detourW = MessageBoxWDetour;
_detourA = MessageBoxADetour;
_originalW = Hook(user32, "MessageBoxW", _detourW);
_originalA = Hook(user32, "MessageBoxA", _detourA);
}
catch (Exception ex)
{
RynthLog.Compat($"MessageBoxHooks: install failed - {ex.GetType().Name}: {ex.Message}");
}
}
private static MessageBoxDelegate? Hook(IntPtr user32, string name, MessageBoxDelegate detour)
{
IntPtr target = GetProcAddress(user32, name);
if (target == IntPtr.Zero)
{
RynthLog.Compat($"MessageBoxHooks: GetProcAddress({name}) failed.");
return null;
}
IntPtr trampoline = MinHook.HookCreate(target, Marshal.GetFunctionPointerForDelegate(detour));
var original = Marshal.GetDelegateForFunctionPointer<MessageBoxDelegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(target);
RynthLog.Info($"MessageBoxHooks: hooked user32!{name} @ 0x{target.ToInt32():X8}.");
return original;
}
/// <summary>
/// The message box open right now, e.g. "AC message box open 12s on the
/// main thread: 'Asheron's Call' - '…'", or null. Any thread.
/// </summary>
public static string? Describe()
{
string? open = _openDescription;
if (open == null) return null;
long secs = (Environment.TickCount64 - Interlocked.Read(ref _openedAtTicks)) / 1000;
return $"message box open {secs}s: {open}";
}
private static int MessageBoxWDetour(IntPtr hWnd, IntPtr text, IntPtr caption, uint type) =>
Show(hWnd, text, caption, type, wide: true);
private static int MessageBoxADetour(IntPtr hWnd, IntPtr text, IntPtr caption, uint type) =>
Show(hWnd, text, caption, type, wide: false);
private static int Show(IntPtr hWnd, IntPtr text, IntPtr caption, uint type, bool wide)
{
MessageBoxDelegate? original = wide ? _originalW : _originalA;
string? description = null;
long opened = Environment.TickCount64;
try
{
description = Opened(text, caption, type, wide);
}
catch { /* observation only: never block the dialog */ }
int result = original != null ? original(hWnd, text, caption, type) : 0;
try
{
long secs = (Environment.TickCount64 - opened) / 1000;
RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}");
if (Interlocked.Decrement(ref _openCount) <= 0)
{
Interlocked.Exchange(ref _openCount, 0);
_openDescription = null;
}
}
catch { }
return result;
}
private static string Opened(IntPtr text, IntPtr caption, uint type, bool wide)
{
string body = Read(text, wide);
string title = Read(caption, wide);
bool mainThread = MainThreadGuard.IsOnMainThread();
// The first frame outside user32 and this file: who asked for the dialog.
string caller = "?";
var frames = new IntPtr[8];
int n = RtlCaptureStackBackTrace(1, (uint)frames.Length, frames, out _);
for (int i = 0; i < n; i++)
{
string module = ProcessExitHooks.ResolveModule(frames[i], out int rva);
if (module.Contains("RynthCore.Engine", StringComparison.OrdinalIgnoreCase)
|| module.Contains("user32", StringComparison.OrdinalIgnoreCase))
continue;
caller = $"{module}+0x{rva:X}";
break;
}
string description = $"'{title}' - '{Flatten(body)}' (style=0x{type:X}, {(mainThread ? "AC main thread" : $"thread {GetCurrentThreadId()}")}, caller {caller})";
Interlocked.Exchange(ref _openedAtTicks, Environment.TickCount64);
Interlocked.Increment(ref _openCount);
_openDescription = description;
RynthLog.Error($"MessageBoxHooks: MESSAGE BOX OPENED {description}");
return description;
}
private static string Read(IntPtr p, bool wide)
{
if (p == IntPtr.Zero) return "";
string? s = wide ? Marshal.PtrToStringUni(p) : Marshal.PtrToStringAnsi(p);
if (s == null) return "";
return s.Length > 2000 ? s.Substring(0, 2000) + "…" : s;
}
private static string Flatten(string s) => s.Replace("\r\n", " | ").Replace('\n', ' ').Replace('\r', ' ');
}

View file

@ -225,9 +225,15 @@ internal static class MovementActionHooks
public static bool SetAutonomyLevel(uint level)
{
// A missing delegate stays a false return on every thread (it would only
// no-op in the drain), then off-thread callers queue the 0xF752 send like
// StopMovement/Jump do; true there means "queued".
if (_autonomyLevel == null)
return false;
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSetAutonomyLevel(level);
try
{
return _autonomyLevel(level);

View file

@ -0,0 +1,104 @@
// ============================================================================
// RynthCore.Engine - Compatibility/PlayerLifecycleLog.cs
// One log line per player lifecycle edge: death (health reaches 0), revival,
// portal space entered/exited, and landblock jumps (a teleport, not walking
// into the next landblock), each with the landblock.
//
// Why: 2026-09-28 a client crashed in AC's own teardown code
// (acclient+0x18712F, null read in a hash-table clear) during the death
// portal to the lifestone, and nothing in the log recorded the death or the
// teleport. With these lines a crash can be lined up with what the character
// was doing.
//
// Sampled from GameTickHooks.UseTimeDetour on AC's main thread, before AC's
// tick, so the reads see a consistent world. Alloc-free except on an edge.
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class PlayerLifecycleLog
{
private static bool _init;
private static volatile bool _portaling, _dead;
private static long _transitionUntil;
private const long TransitionSettleMs = 5_000;
/// <summary>
/// Dead, in portal space, or within 5 s after either: AC is tearing down and
/// loading the world, so nothing should poke at its state (BusyCountHooks'
/// force-clear). As of the last game tick; any thread.
/// </summary>
public static bool InWorldTransition =>
_dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _transitionUntil);
private static uint _landblock;
private static long _portalEnteredAt, _diedAt;
/// <summary>AC main thread, once per game tick.</summary>
public static void SampleOnGameThread(bool portaling)
{
bool dead = false;
uint health = 0, maxHealth = 0;
if (PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot v))
{
health = v.Health;
maxHealth = v.MaxHealth;
dead = v.MaxHealth > 0 && v.Health == 0;
}
uint cell = 0;
if (PlayerPhysicsHooks.TryGetPlayerPose(out uint c, out _, out _, out _, out _, out _, out _, out _))
cell = c;
uint landblock = cell >> 16;
if (!_init)
{
_init = true;
_portaling = portaling;
_dead = dead;
_landblock = landblock;
return;
}
long now = Environment.TickCount64;
if (dead || portaling || _dead || _portaling)
Interlocked.Exchange(ref _transitionUntil, now + TransitionSettleMs);
if (dead != _dead)
{
if (dead)
{
_diedAt = now;
RynthLog.Info($"[Lifecycle] player DIED (health 0/{maxHealth}) in landblock 0x{landblock:X4} (cell 0x{cell:X8}).");
}
else
RynthLog.Info($"[Lifecycle] player alive again (health {health}/{maxHealth}) {Ago(_diedAt, now)} after death, landblock 0x{landblock:X4}.");
_dead = dead;
}
if (portaling != _portaling)
{
if (portaling)
{
_portalEnteredAt = now;
string why = _diedAt != 0 && now - _diedAt < 30_000 ? " (death portal)" : "";
RynthLog.Info($"[Lifecycle] portal space ENTERED{why} from landblock 0x{landblock:X4} (cell 0x{cell:X8}).");
}
else
RynthLog.Info($"[Lifecycle] portal space EXITED into landblock 0x{landblock:X4} (cell 0x{cell:X8}) after {Ago(_portalEnteredAt, now)}.");
_portaling = portaling;
}
if (landblock != 0 && _landblock != 0 && landblock != _landblock)
{
int dx = (int)((landblock >> 8) & 0xFF) - (int)((_landblock >> 8) & 0xFF);
int dy = (int)(landblock & 0xFF) - (int)(_landblock & 0xFF);
if (Math.Abs(dx) > 1 || Math.Abs(dy) > 1)
RynthLog.Info($"[Lifecycle] landblock jump 0x{_landblock:X4} -> 0x{landblock:X4}{(portaling ? " (in portal space)" : "")}.");
}
if (landblock != 0) _landblock = landblock;
}
private static string Ago(long since, long now) =>
since == 0 ? "?" : $"{(now - since) / 1000.0:0.0}s";
}

View file

@ -87,6 +87,118 @@ internal static class PlayerPhysicsHooks
return ready;
}
// ── Player pose snapshot (2026-09-30 main-thread audit) ─────────────────────
// The plugin pump (RynthAi nav / radar / Jumper / meta, RynthLua), Nav3DRenderer's
// Clear/CommitFrame and UI threads read the player's pose and heading many times
// a second. Read live off-thread that walked the SmartBox player (unprobed vtable
// read), read cell and origin as separate loads (a landblock crossing could pair
// the new cell with the old x/y, ~192 m off for a tick) and called AC's
// CPhysicsObj::get_heading off-thread. The main thread now publishes one
// consistent copy per frame (MainThreadSnapshots.Tick) under a seqlock: the
// writer never waits and never allocates; readers retry a few times and fail
// closed. Main-thread callers (GameMatrixCapture, MonsterHud, PlateDebuffs,
// PlayerLifecycleLog) keep the live read.
private static int _poseSeq; // odd while the main thread is writing
private static bool _poseValid;
private static bool _poseHeadingValid;
private static uint _poseCell;
private static float _poseX, _poseY, _poseZ, _poseQw, _poseQx, _poseQy, _poseQz, _poseHeading;
private static long _lastPosePublishTs;
private static long _nextHeadingBindAttemptMs;
private static readonly long PosePublishMinTicks = System.Diagnostics.Stopwatch.Frequency / 250; // <= 250 Hz
/// <summary>
/// Main thread only (MainThreadSnapshots.Tick). Reads the live pose and heading
/// once and publishes them together. An unreadable player (portal, logout,
/// char-select) publishes "invalid", so off-thread readers fail closed as the
/// live read did.
/// </summary>
internal static void PublishPoseSnapshot(bool smartBoxReady)
{
if (!MainThreadGuard.IsOnMainThread())
return;
long ts = System.Diagnostics.Stopwatch.GetTimestamp();
if (ts - _lastPosePublishTs < PosePublishMinTicks)
return; // UseTime and EndScene both call in; once per few ms is plenty
_lastPosePublishTs = ts;
uint cell = 0;
float x = 0, y = 0, z = 0, qw = 1f, qx = 0, qy = 0, qz = 0;
// Not located: publish "no pose" without TryGetPlayer (which would re-run
// the SmartBox probe's pattern scan on every call).
bool ok = smartBoxReady &&
TryGetPlayerPoseLive(out cell, out x, out y, out z, out qw, out qx, out qy, out qz);
float heading = 0f;
bool headingOk = false;
if (ok)
{
// Bind the heading thunk at most every 5 s while it is missing: the bind
// runs a SmartBox probe + pattern resolve, far too heavy for every frame.
if (_getHeading == null)
{
long now = Environment.TickCount64;
if (now >= _nextHeadingBindAttemptMs)
{
_nextHeadingBindAttemptMs = now + 5000;
EnsurePhysicsDelegates();
}
}
if (_getHeading != null)
headingOk = TryGetPlayerHeadingLive(out heading);
}
System.Threading.Interlocked.Increment(ref _poseSeq); // odd: writing
_poseValid = ok;
_poseHeadingValid = headingOk;
_poseCell = cell;
_poseX = x; _poseY = y; _poseZ = z;
_poseQw = qw; _poseQx = qx; _poseQy = qy; _poseQz = qz;
_poseHeading = heading;
System.Threading.Interlocked.Increment(ref _poseSeq); // even: published
}
// Seqlock read. False when nothing valid is published, or (vanishingly rarely)
// when the writer kept the lock for every retry.
private static bool TryReadPoseSnapshot(out uint cell, out float x, out float y, out float z,
out float qw, out float qx, out float qy, out float qz,
out bool headingValid, out float heading)
{
for (int attempt = 0; attempt < 8; attempt++)
{
int s1 = System.Threading.Volatile.Read(ref _poseSeq);
if ((s1 & 1) != 0)
{
System.Threading.Thread.SpinWait(8);
continue;
}
bool valid = _poseValid;
headingValid = _poseHeadingValid;
cell = _poseCell;
x = _poseX; y = _poseY; z = _poseZ;
qw = _poseQw; qx = _poseQx; qy = _poseQy; qz = _poseQz;
heading = _poseHeading;
System.Threading.Interlocked.MemoryBarrier();
if (System.Threading.Volatile.Read(ref _poseSeq) != s1)
continue;
if (!valid)
break;
return true;
}
cell = 0; x = y = z = 0; qw = 1f; qx = qy = qz = 0;
headingValid = false; heading = 0;
return false;
}
/// <summary>
/// The per-frame main-thread pose copy (cell, cell-local origin, yaw quaternion
/// qw/qz and AC's heading, 0 = North, clockwise), read from any thread without
/// calling into AC. headingValid is false while AC's get_heading isn't bound;
/// derive the heading from qw/qz then. False when nothing valid is published.
/// </summary>
public static bool TryGetPlayerPoseSnapshot(out uint objCellId, out float x, out float y, out float z,
out float qw, out float qz, out bool headingValid, out float heading)
=> TryReadPoseSnapshot(out objCellId, out x, out y, out z, out qw, out _, out _, out qz, out headingValid, out heading);
public static bool TryGetPlayerPose(
out uint objCellId,
out float x,
@ -96,6 +208,26 @@ internal static class PlayerPhysicsHooks
out float qx,
out float qy,
out float qz)
{
// Off AC's main thread: the per-frame main-thread copy (one consistent
// cell/origin/quaternion set, at most a frame old).
if (!MainThreadGuard.IsOnMainThread())
return TryReadPoseSnapshot(out objCellId, out x, out y, out z, out qw, out qx, out qy, out qz, out _, out _);
return TryGetPlayerPoseLive(out objCellId, out x, out y, out z, out qw, out qx, out qy, out qz);
}
// Live pose read. Page-probes every field. Called on the main thread (the
// snapshot publisher and main-thread callers of TryGetPlayerPose).
private static bool TryGetPlayerPoseLive(
out uint objCellId,
out float x,
out float y,
out float z,
out float qw,
out float qx,
out float qy,
out float qz)
{
objCellId = 0;
x = y = z = 0;
@ -152,9 +284,32 @@ internal static class PlayerPhysicsHooks
}
public static bool TryGetPlayerHeading(out float headingDegrees)
{
// Off AC's main thread (host GetPlayerHeadingFn on the pump: Jumper, radar,
// dungeon map, AutoVendor): the heading the main thread read with AC's own
// get_heading this frame. Never calls into AC from here.
if (!MainThreadGuard.IsOnMainThread())
{
if (TryReadPoseSnapshot(out _, out _, out _, out _, out _, out _, out _, out _, out bool hv, out float h) && hv)
{
headingDegrees = h;
return true;
}
headingDegrees = 0;
return false;
}
return TryGetPlayerHeadingLive(out headingDegrees);
}
// Main thread only: AC's CPhysicsObj::get_heading on the SmartBox player.
private static bool TryGetPlayerHeadingLive(out float headingDegrees)
{
headingDegrees = 0;
if (!MainThreadGuard.IsOnMainThread())
return false;
if (!EnsurePhysicsDelegates())
return false;
@ -180,6 +335,12 @@ internal static class PlayerPhysicsHooks
public static bool SetPlayerHeading(float headingDegrees)
{
// CPhysicsObj::set_heading (with sendEvent) writes the live physics object
// and can send a movement event: main thread only. No callers today; an
// off-thread caller gets false (use TurnToHeading, which marshals).
if (!MainThreadGuard.IsOnMainThread())
return false;
if (!EnsurePhysicsDelegates() || _setHeading == null)
return false;
@ -217,6 +378,16 @@ internal static class PlayerPhysicsHooks
public static bool SetPlayerHeadingDirect(float decalHeadingDeg)
{
// Plugins reach this from the pump thread on every nav tick
// (Host.TurnToHeading -> ClientActionHooks.TurnToHeading). Two raw stores
// into the live quaternion there raced AC's physics integration (torn,
// non-unit orientation), and the SmartBox player walk ran off-thread too.
// Park the heading in the coalesced slot instead; AcMainThreadQueue.Drain
// calls back in here on the main thread (and falls back to the
// CommandInterpreter turn there when there is no player, as before).
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueDirectHeading(decalHeadingDeg);
int n = System.Threading.Interlocked.Increment(ref _setHeadingCalls);
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out _, out string failure))
{
@ -237,6 +408,17 @@ internal static class PlayerPhysicsHooks
float newQz = (float)Math.Sin(physYawRad * 0.5);
IntPtr pos = player + PhysicsPositionOffset;
// Probe both stores (they can straddle a page) so a player pointer that
// went stale between the SmartBox lookup and here fails closed rather
// than taking an uncatchable NativeAOT write AV.
if (!ClientObjectHooks.IsWritablePointer(pos + PositionQwOffset) ||
!ClientObjectHooks.IsWritablePointer(pos + PositionQzOffset))
{
_statusMessage = "Player position struct not writable.";
if (ShouldLogHeading(n))
RynthLog.Compat($"Move: SetPlayerHeadingDirect({decalHeadingDeg:0.0}) #{n} — position not writable (player=0x{player.ToInt32():X8})");
return false;
}
WriteFloat(pos + PositionQwOffset, newQw);
WriteFloat(pos + PositionQzOffset, newQz);
@ -363,6 +545,13 @@ internal static class PlayerPhysicsHooks
{
inProgress = false;
// Main thread only: the SmartBox player -> MovementManager -> CMotionInterp
// hops are unprobed reads through objects AC frees at logout / char switch.
// Every caller (queue drain, busy watchdog, CastGate.Sample) is on the main
// thread; an off-thread caller gets "couldn't read" (no opinion) instead.
if (!MainThreadGuard.IsOnMainThread())
return false;
if (!TryGetCMotionInterp(out IntPtr cmi) || cmi == IntPtr.Zero)
return false;

View file

@ -0,0 +1,252 @@
// ============================================================================
// RynthCore.Engine - Compatibility/PlayerProgressHooks.cs
//
// The Skills panel's data (docs/IMGUI_SKILLS.md): the player's skills,
// attributes and vitals with the numbers a raise needs (ranks, XP spent,
// innate level, buffed and base values), level, XP, skill credits, and the
// buffs on each stat (the enchantment snapshot's StatMods).
//
// Threads:
// Prefetch AC's main thread (MainThreadSnapshots.Tick, player live). All the
// AC reads are in ClientObjectHooks.ReadPlayerProgressLive.
// 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
// snapshot object is published (and allocated) only when something changed,
// so an idle open panel costs a compare every half second.
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// One read of the player's progress. Published copies are never written again
/// (readers may keep them); the work buffer is private to the prefetch.
/// Index conventions: skills by STypeSkill (1..MaxSkill), attributes by
/// STypeAttribute (1..6), vitals 1 = health, 2 = stamina, 3 = mana.
/// </summary>
internal sealed class PlayerProgress
{
public const int MaxSkill = 54;
public const int MaxBuffs = 256;
public int Version;
public uint PlayerId;
// Skills: the qualities' skill table (class 0 when the skill isn't in it) and InqSkill.
public bool SkillTableRead;
public readonly bool[] SkillInTable = new bool[MaxSkill + 1];
public readonly uint[] SkillClass = new uint[MaxSkill + 1]; // 1 untrained, 2 trained, 3 specialized
public readonly uint[] SkillXpSpent = new uint[MaxSkill + 1];
public readonly uint[] SkillRanks = new uint[MaxSkill + 1];
public readonly uint[] SkillInit = new uint[MaxSkill + 1];
public readonly bool[] SkillLevelKnown = new bool[MaxSkill + 1];
public readonly int[] SkillBuffed = new int[MaxSkill + 1];
public readonly int[] SkillBase = new int[MaxSkill + 1];
// Attributes 1..6 and vitals 1..3 (health, stamina, mana): the AttributeCache and Inq*.
public bool AttributeCacheRead;
public readonly uint[] AttrRanks = new uint[7];
public readonly uint[] AttrInit = new uint[7];
public readonly uint[] AttrXpSpent = new uint[7];
public readonly uint[] AttrBuffed = new uint[7];
public readonly uint[] AttrBase = new uint[7];
public readonly uint[] VitalRanks = new uint[4];
public readonly uint[] VitalInit = new uint[4];
public readonly uint[] VitalXpSpent = new uint[4];
public readonly uint[] VitalBuffed = new uint[4];
public readonly uint[] VitalBase = new uint[4];
public int Level;
public int SkillCredits;
public long TotalXp;
public long UnassignedXp;
public long Luminance;
public long MaxLuminance;
public float Vitae = 1f;
// Buffs that change a skill, attribute or vital (StatMod type has 0x1, 0x2 or 0x10).
public int BuffCount;
public readonly uint[] BuffSpell = new uint[MaxBuffs];
public readonly double[] BuffExpiry = new double[MaxBuffs]; // server time; double.MaxValue = no end
public readonly uint[] BuffType = new uint[MaxBuffs];
public readonly uint[] BuffKey = new uint[MaxBuffs];
public readonly float[] BuffVal = new float[MaxBuffs];
public readonly uint[] BuffCategory = new uint[MaxBuffs];
public void Clear()
{
PlayerId = 0;
SkillTableRead = false;
Array.Clear(SkillInTable);
Array.Clear(SkillClass);
Array.Clear(SkillXpSpent);
Array.Clear(SkillRanks);
Array.Clear(SkillInit);
Array.Clear(SkillLevelKnown);
Array.Clear(SkillBuffed);
Array.Clear(SkillBase);
AttributeCacheRead = false;
Array.Clear(AttrRanks);
Array.Clear(AttrInit);
Array.Clear(AttrXpSpent);
Array.Clear(AttrBuffed);
Array.Clear(AttrBase);
Array.Clear(VitalRanks);
Array.Clear(VitalInit);
Array.Clear(VitalXpSpent);
Array.Clear(VitalBuffed);
Array.Clear(VitalBase);
Level = SkillCredits = 0;
TotalXp = UnassignedXp = Luminance = MaxLuminance = 0;
Vitae = 1f;
BuffCount = 0;
}
public void CopyFrom(PlayerProgress o)
{
PlayerId = o.PlayerId;
SkillTableRead = o.SkillTableRead;
o.SkillInTable.CopyTo(SkillInTable, 0);
o.SkillClass.CopyTo(SkillClass, 0);
o.SkillXpSpent.CopyTo(SkillXpSpent, 0);
o.SkillRanks.CopyTo(SkillRanks, 0);
o.SkillInit.CopyTo(SkillInit, 0);
o.SkillLevelKnown.CopyTo(SkillLevelKnown, 0);
o.SkillBuffed.CopyTo(SkillBuffed, 0);
o.SkillBase.CopyTo(SkillBase, 0);
AttributeCacheRead = o.AttributeCacheRead;
o.AttrRanks.CopyTo(AttrRanks, 0);
o.AttrInit.CopyTo(AttrInit, 0);
o.AttrXpSpent.CopyTo(AttrXpSpent, 0);
o.AttrBuffed.CopyTo(AttrBuffed, 0);
o.AttrBase.CopyTo(AttrBase, 0);
o.VitalRanks.CopyTo(VitalRanks, 0);
o.VitalInit.CopyTo(VitalInit, 0);
o.VitalXpSpent.CopyTo(VitalXpSpent, 0);
o.VitalBuffed.CopyTo(VitalBuffed, 0);
o.VitalBase.CopyTo(VitalBase, 0);
Level = o.Level;
SkillCredits = o.SkillCredits;
TotalXp = o.TotalXp;
UnassignedXp = o.UnassignedXp;
Luminance = o.Luminance;
MaxLuminance = o.MaxLuminance;
Vitae = o.Vitae;
BuffCount = o.BuffCount;
Array.Copy(o.BuffSpell, BuffSpell, o.BuffCount);
Array.Copy(o.BuffExpiry, BuffExpiry, o.BuffCount);
Array.Copy(o.BuffType, BuffType, o.BuffCount);
Array.Copy(o.BuffKey, BuffKey, o.BuffCount);
Array.Copy(o.BuffVal, BuffVal, o.BuffCount);
Array.Copy(o.BuffCategory, BuffCategory, o.BuffCount);
}
/// <summary>True when every value equals <paramref name="o"/>'s (Version aside). No allocation.</summary>
public bool SameAs(PlayerProgress o)
{
if (PlayerId != o.PlayerId || SkillTableRead != o.SkillTableRead || AttributeCacheRead != o.AttributeCacheRead
|| Level != o.Level || SkillCredits != o.SkillCredits || TotalXp != o.TotalXp || UnassignedXp != o.UnassignedXp
|| Luminance != o.Luminance || MaxLuminance != o.MaxLuminance || Vitae != o.Vitae || BuffCount != o.BuffCount)
return false;
return Eq(SkillInTable, o.SkillInTable) && Eq(SkillClass, o.SkillClass) && Eq(SkillXpSpent, o.SkillXpSpent)
&& Eq(SkillRanks, o.SkillRanks) && Eq(SkillInit, o.SkillInit) && Eq(SkillLevelKnown, o.SkillLevelKnown)
&& Eq(SkillBuffed, o.SkillBuffed) && Eq(SkillBase, o.SkillBase)
&& Eq(AttrRanks, o.AttrRanks) && Eq(AttrInit, o.AttrInit) && Eq(AttrXpSpent, o.AttrXpSpent)
&& Eq(AttrBuffed, o.AttrBuffed) && Eq(AttrBase, o.AttrBase)
&& Eq(VitalRanks, o.VitalRanks) && Eq(VitalInit, o.VitalInit) && Eq(VitalXpSpent, o.VitalXpSpent)
&& Eq(VitalBuffed, o.VitalBuffed) && Eq(VitalBase, o.VitalBase)
&& EqN(BuffSpell, o.BuffSpell, BuffCount) && EqN(BuffExpiry, o.BuffExpiry, BuffCount)
&& EqN(BuffType, o.BuffType, BuffCount) && EqN(BuffKey, o.BuffKey, BuffCount)
&& EqN(BuffVal, o.BuffVal, BuffCount) && EqN(BuffCategory, o.BuffCategory, BuffCount);
}
private static bool Eq<T>(T[] a, T[] b) where T : IEquatable<T> => a.AsSpan().SequenceEqual(b);
private static bool EqN<T>(T[] a, T[] b, int n) where T : IEquatable<T> => a.AsSpan(0, n).SequenceEqual(b.AsSpan(0, n));
}
internal static class PlayerProgressHooks
{
private const int RefreshMs = 500;
private const int WantWindowMs = 2000;
// StatMod type flags (ACE EnchantmentTypeFlags) that mark a buff on a stat.
internal const uint ModAttribute = 0x1, ModSecondAttribute = 0x2, ModSkill = 0x10;
internal const uint ModMultiplicative = 0x4000, ModAdditive = 0x8000, ModVitae = 0x800000;
private const uint ModAnyStat = ModAttribute | ModSecondAttribute | ModSkill;
private static long _wantedUntilMs;
private static long _nextReadMs;
private static int _version;
private static PlayerProgress? _published;
// Main thread only: the work buffer and the enchantment copy's scratch.
private static readonly PlayerProgress Work = new();
private const int EnchScratch = 1024;
private static readonly uint[] ScratchSpell = new uint[EnchScratch];
private static readonly double[] ScratchExpiry = new double[EnchScratch];
private static readonly uint[] ScratchType = new uint[EnchScratch];
private static readonly uint[] ScratchKey = new uint[EnchScratch];
private static readonly float[] ScratchVal = new float[EnchScratch];
private static readonly uint[] ScratchCategory = new uint[EnchScratch];
/// <summary>A reader wants fresh data for the next 2 s. Any thread; call it each frame the panel draws.</summary>
public static void Want() =>
Volatile.Write(ref _wantedUntilMs, Environment.TickCount64 + WantWindowMs);
/// <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>The last published read, or null. Never written again once published. Any thread.</summary>
public static PlayerProgress? Current => Volatile.Read(ref _published);
/// <summary>
/// AC's main thread (MainThreadSnapshots.Tick, only while the player is live).
/// Reads when wanted and due; publishes only a changed result.
/// </summary>
internal static void Prefetch()
{
if (!MainThreadGuard.IsOnMainThread())
return;
long now = Environment.TickCount64;
if (now > Volatile.Read(ref _wantedUntilMs) || now < Volatile.Read(ref _nextReadMs))
return;
Volatile.Write(ref _nextReadMs, now + RefreshMs);
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);
}
/// <summary>The player's enchantments that change a skill, attribute or vital (not vitae).</summary>
private static void CopyStatBuffs(PlayerProgress dst)
{
dst.BuffCount = 0;
int n = EnchantmentHooks.CopyPlayerStatMods(ScratchSpell, ScratchExpiry, ScratchType, ScratchKey, ScratchVal, ScratchCategory);
for (int i = 0; i < n && dst.BuffCount < PlayerProgress.MaxBuffs; i++)
{
uint type = ScratchType[i];
if ((type & ModAnyStat) == 0 || (type & ModVitae) != 0)
continue;
int k = dst.BuffCount++;
dst.BuffSpell[k] = ScratchSpell[i];
dst.BuffExpiry[k] = ScratchExpiry[i];
dst.BuffType[k] = type;
dst.BuffKey[k] = ScratchKey[i];
dst.BuffVal[k] = ScratchVal[i];
dst.BuffCategory[k] = ScratchCategory[i];
}
}
}

View file

@ -0,0 +1,480 @@
// ============================================================================
// RynthCore.Engine - Compatibility/PlayerTrade.cs
//
// Player-to-player trade (plugin API v72): the state of the trade window, read
// from the server's trade GameEvents, and the trade actions, sent through the
// retail client's own CM_Trade / ClientTradeSystem functions.
//
// STATE UIQueueManager::ProcessNetBlobData (SmartBoxHooks' existing game-event
// detour, AC's main thread) hands every trade GameEvent to OnGameEvent
// before AC handles it. No new hook. Payloads (event type at +0, payload
// from +4), checked against ACE's writers (GameEvent*Trade.cs) and the
// client's CM_Trade::DispatchUI_Recv_* readers:
// 0x01FD RegisterTrade u32 initiator, u32 partner, f64 stamp
// 0x01FE OpenTrade u32 objectId (ACE never sends it)
// 0x01FF CloseTrade u32 EndTradeReason (1 normal, 2 combat, 0x51 cancelled)
// 0x0200 AddToTrade u32 item, u32 side (1 you, 2 partner), u32 slot
// 0x0201 RemoveFromTrade u32 item, u32 side (ACE never sends it)
// 0x0202 AcceptTrade u32 who accepted
// 0x0203 DeclineTrade u32 who declined
// 0x0205 ResetTrade u32 who reset (both windows empty; also sent
// to both sides after a completed trade)
// 0x0207 TradeFailure u32 item, u32 WeenieError
// 0x0208 ClearTradeAcceptance (none)
// plus WeenieError 0x0529 TradeComplete (counted). ACE sends the second
// party RegisterTrade(initiator, initiator), so the partner is "the
// initiator unless that's you, else the partner field".
//
// The state lives in fixed arrays under one lock: the detour never
// allocates and never calls a plugin. Plugins read a copy on their pump
// (GetTradeState / GetTradeItems) and compare Generation / Sequence /
// counters between reads; nothing is queued for them.
//
// ACTIONS Bound by byte pattern (tools/pe_pattern.py CHECK), VAs from the
// Chorizite acclient map (+0x401000), verified on both acclient copies:
// CM_Trade::Event_OpenTradeNegotiations(ulong) 0x006AE260 0x01F6
// CM_Trade::Event_AddToTrade(ulong item, ulong loc) 0x006AE030 0x01F8
// CM_Trade::Event_ResetTrade() 0x006AE330 0x0204
// CM_Trade::Event_CloseTradeNegotiations() 0x006AE140 0x01F7
// ClientTradeSystem::AcceptTrade() (thiscall) 0x0056E7A0 0x01FA
// ClientTradeSystem::DeclineTrade() (thiscall) 0x0056E7C0 0x01FB
// The Event_* functions are cdecl, return bool, and only build and send
// the game action (the same generated shape as Event_GetAndWieldItem).
// Accept goes through ClientTradeSystem because CM_Trade::Event_AcceptTrade
// packs the client's own Trade object (ClientTradeSystem+0x10); the wrapper
// also sets that object's accepted flag (+0x38) the way the trade window's
// Accept button does. Decline clears it the same way. The ClientTradeSystem
// instance is the global ClientTradeSystem::GetTradeSystem returns
// (0x0087174C), resolved by code xref.
//
// Every action runs on AC's main thread: from any other thread it is queued
// on AcMainThreadQueue (ActionKind.Trade) and the drain calls back in here.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class PlayerTrade
{
// ── Actions ─────────────────────────────────────────────────────────────
internal enum TradeOp : uint
{
Open = 1,
Add = 2,
Reset = 3,
Accept = 4,
Decline = 5,
Close = 6,
}
private const int EventOpenTradeNegotiationsVa = 0x006AE260;
private const int EventAddToTradeVa = 0x006AE030;
private const int EventResetTradeVa = 0x006AE330;
private const int EventCloseTradeNegotiationsVa = 0x006AE140;
private const int TradeSystemAcceptTradeVa = 0x0056E7A0;
private const int TradeSystemDeclineTradeVa = 0x0056E7C0;
private const int TradeSystemGlobalVa = 0x0087174C;
// The four CM_Trade events share one generated template (see Event_GiveObjectRequest in
// ClientHelperHooks); what tells them apart is the arg-block size after the first inner
// call (+0x08 one arg, +0x0C two, +0x04 none) and the opcode immediate at the end, so the
// patterns run to that byte. Generated + verified unique via pe_pattern.py GEN against both
// acclient copies (C:\Turbine and C:\Games\RynthCore\AcClient).
private static readonly byte?[] PatEventOpenTradeNegotiations = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0xF6 ];
private static readonly byte?[] PatEventAddToTrade = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0xF8 ];
private static readonly byte?[] PatEventResetTrade = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0xC7, 0x02, 0x04 ];
private static readonly byte?[] PatEventCloseTradeNegotiations = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0xC7, 0x02, 0xF7 ];
// ClientTradeSystem::AcceptTrade: mov eax,[ecx+10h]; mov dword [eax+38h],1; mov ecx,[ecx+10h];
// push ecx; call Event_AcceptTrade; pop ecx; ret. DeclineTrade: the same flag write with 0,
// then jmp Event_DeclineTrade. Unique at 8 bytes; run on to the call/jmp for margin.
private static readonly byte?[] PatTradeSystemAcceptTrade = [ 0x8B, 0x41, 0x10, 0xC7, 0x40, 0x38, 0x01, 0x00, 0x00, 0x00, 0x8B, 0x49, 0x10, 0x51, 0xE8, null, null, null, null, 0x59, 0xC3 ];
private static readonly byte?[] PatTradeSystemDeclineTrade = [ 0x8B, 0x41, 0x10, 0xC7, 0x40, 0x38, 0x00, 0x00, 0x00, 0x00, 0xE9 ];
// mov [ClientTradeSystem::s_pTradeSystem], esi; call [import]; xor edi, edi (operand at +2).
private static readonly byte?[] PatXrefTradeSystem = [ 0x89, 0x35, null, null, null, null, 0xFF, 0x15, 0xFC, 0x31, 0x79, 0x00, 0x33, 0xFF ];
private static delegate* unmanaged[Cdecl]<uint, byte> _eventOpenTradeNegotiations;
private static delegate* unmanaged[Cdecl]<uint, uint, byte> _eventAddToTrade;
private static delegate* unmanaged[Cdecl]<byte> _eventResetTrade;
private static delegate* unmanaged[Cdecl]<byte> _eventCloseTradeNegotiations;
private static delegate* unmanaged[Thiscall]<IntPtr, void> _tradeSystemAcceptTrade;
private static delegate* unmanaged[Thiscall]<IntPtr, void> _tradeSystemDeclineTrade;
private static int _tradeSystemAddr;
public static bool HasOpen => _eventOpenTradeNegotiations != null;
public static bool HasAdd => _eventAddToTrade != null;
public static bool HasReset => _eventResetTrade != null;
public static bool HasClose => _eventCloseTradeNegotiations != null;
public static bool HasAccept => _tradeSystemAcceptTrade != null;
public static bool HasDecline => _tradeSystemDeclineTrade != null;
public static bool ActionsAvailable => HasOpen && HasAdd && HasReset && HasClose && HasAccept && HasDecline;
/// <summary>Bind the trade functions. Called from ClientHelperHooks.Probe (engine init).</summary>
public static void Probe(AcClientTextSection text)
{
_eventOpenTradeNegotiations = (delegate* unmanaged[Cdecl]<uint, byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTrade.Event_OpenTradeNegotiations", PatEventOpenTradeNegotiations, EventOpenTradeNegotiationsVa));
_eventAddToTrade = (delegate* unmanaged[Cdecl]<uint, uint, byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTrade.Event_AddToTrade", PatEventAddToTrade, EventAddToTradeVa));
_eventResetTrade = (delegate* unmanaged[Cdecl]<byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTrade.Event_ResetTrade", PatEventResetTrade, EventResetTradeVa));
_eventCloseTradeNegotiations = (delegate* unmanaged[Cdecl]<byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTrade.Event_CloseTradeNegotiations", PatEventCloseTradeNegotiations, EventCloseTradeNegotiationsVa));
_tradeSystemAcceptTrade = (delegate* unmanaged[Thiscall]<IntPtr, void>)ResolveFn(HookResolver.Resolve(text, "PlayerTrade.ClientTradeSystem_AcceptTrade", PatTradeSystemAcceptTrade, TradeSystemAcceptTradeVa));
_tradeSystemDeclineTrade = (delegate* unmanaged[Thiscall]<IntPtr, void>)ResolveFn(HookResolver.Resolve(text, "PlayerTrade.ClientTradeSystem_DeclineTrade", PatTradeSystemDeclineTrade, TradeSystemDeclineTradeVa));
HookResolver.ResolveResult system = HookResolver.ResolveData(text, "PlayerTrade.ClientTradeSystem", PatXrefTradeSystem, 2, TradeSystemGlobalVa);
_tradeSystemAddr = system.Source == HookResolver.ResolveSource.PatternScan ? system.Address.ToInt32() : 0;
if (_tradeSystemAddr == 0)
{
// Without the instance Accept / Decline can't run; don't offer them.
_tradeSystemAcceptTrade = null;
_tradeSystemDeclineTrade = null;
}
RynthLog.Verbose($"Compat: player trade {(ActionsAvailable ? "ready" : "partly bound")} (open={HasOpen} add={HasAdd} reset={HasReset} close={HasClose} accept={HasAccept} decline={HasDecline}).");
}
// Fail closed: these send game actions, so only a unique pattern match binds. The resolver's
// fixed-VA fallback (a pattern miss on some other client build) leaves the action unavailable.
private static void* ResolveFn(HookResolver.ResolveResult r) =>
r.Success && r.Source == HookResolver.ResolveSource.PatternScan ? (void*)r.Address : null;
/// <summary>Ask <paramref name="targetId"/> to trade (0x01F6 OpenTradeNegotiations).</summary>
public static bool Open(uint targetId)
{
if (!MainThreadGuard.IsOnMainThread())
return _eventOpenTradeNegotiations != null && targetId != 0
&& AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Open, targetId, 0);
if (_eventOpenTradeNegotiations == null || targetId == 0) return false;
byte rv = _eventOpenTradeNegotiations(targetId);
LogAction($"Event_OpenTradeNegotiations target=0x{targetId:X8} rv={rv}");
return rv != 0;
}
/// <summary>Put one of your items in the trade window (0x01F8 AddToTrade). slot 0 = next free.</summary>
public static bool Add(uint itemId, uint slot)
{
if (!MainThreadGuard.IsOnMainThread())
return _eventAddToTrade != null && itemId != 0
&& AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Add, itemId, slot);
if (_eventAddToTrade == null || itemId == 0) return false;
byte rv = _eventAddToTrade(itemId, slot);
LogAction($"Event_AddToTrade item=0x{itemId:X8} slot={slot} rv={rv}");
return rv != 0;
}
/// <summary>Empty both sides of the window (0x0204 ResetTrade).</summary>
public static bool Reset()
{
if (!MainThreadGuard.IsOnMainThread())
return _eventResetTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Reset, 0, 0);
if (_eventResetTrade == null) return false;
byte rv = _eventResetTrade();
LogAction($"Event_ResetTrade rv={rv}");
return rv != 0;
}
/// <summary>Close the trade (0x01F7 CloseTradeNegotiations).</summary>
public static bool Close()
{
if (!MainThreadGuard.IsOnMainThread())
return _eventCloseTradeNegotiations != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Close, 0, 0);
if (_eventCloseTradeNegotiations == null) return false;
byte rv = _eventCloseTradeNegotiations();
LogAction($"Event_CloseTradeNegotiations rv={rv}");
return rv != 0;
}
/// <summary>Accept the trade as it stands (the window's Accept button, 0x01FA AcceptTrade).</summary>
public static bool Accept()
{
if (!MainThreadGuard.IsOnMainThread())
return _tradeSystemAcceptTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Accept, 0, 0);
if (_tradeSystemAcceptTrade == null) return false;
IntPtr system = TradeSystemWithTrade();
if (system == IntPtr.Zero) { LogAction("AcceptTrade skipped: no ClientTradeSystem / Trade object"); return false; }
_tradeSystemAcceptTrade(system);
LogAction($"ClientTradeSystem::AcceptTrade this=0x{system.ToInt32():X8}");
return true;
}
/// <summary>Withdraw your acceptance (the window's Decline button, 0x01FB DeclineTrade).</summary>
public static bool Decline()
{
if (!MainThreadGuard.IsOnMainThread())
return _tradeSystemDeclineTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Decline, 0, 0);
if (_tradeSystemDeclineTrade == null) return false;
IntPtr system = TradeSystemWithTrade();
if (system == IntPtr.Zero) { LogAction("DeclineTrade skipped: no ClientTradeSystem / Trade object"); return false; }
_tradeSystemDeclineTrade(system);
LogAction($"ClientTradeSystem::DeclineTrade this=0x{system.ToInt32():X8}");
return true;
}
/// <summary>AcMainThreadQueue drain (main thread): run a queued trade action.</summary>
public static void RunQueued(uint op, uint a, uint b)
{
switch ((TradeOp)op)
{
case TradeOp.Open: Open(a); break;
case TradeOp.Add: Add(a, b); break;
case TradeOp.Reset: Reset(); break;
case TradeOp.Accept: Accept(); break;
case TradeOp.Decline: Decline(); break;
case TradeOp.Close: Close(); break;
}
}
/// <summary>The ClientTradeSystem, when it and its Trade object (+0x10) exist; else zero.</summary>
private static IntPtr TradeSystemWithTrade()
{
if (_tradeSystemAddr == 0) return IntPtr.Zero;
IntPtr system = Marshal.ReadIntPtr(new IntPtr(_tradeSystemAddr));
if (system == IntPtr.Zero) return IntPtr.Zero;
IntPtr trade = Marshal.ReadIntPtr(IntPtr.Add(system, 0x10));
return trade == IntPtr.Zero ? IntPtr.Zero : system;
}
private static int _actionLogCount;
private static void LogAction(string message)
{
if (_actionLogCount >= 200) return;
_actionLogCount++;
RynthLog.Compat($"Trade: {message}");
}
// ── State ───────────────────────────────────────────────────────────────
private const int MaxItemsPerSide = 256;
private const uint TradeSideSelf = 1;
private const uint TradeSidePartner = 2;
private static readonly object _lock = new();
private static readonly uint[] _selfItems = new uint[MaxItemsPerSide];
private static readonly uint[] _partnerItems = new uint[MaxItemsPerSide];
private static int _selfCount, _partnerCount;
private static bool _open, _selfAccepted, _partnerAccepted;
private static uint _generation, _sequence, _partnerId, _initiatorId, _lastEventType;
private static uint _failureCount, _failureItem, _failureReason;
private static uint _closeReason, _acceptedBy, _declinedBy, _resetBy;
private static uint _completedCount, _partnerAcceptCount;
private static int _eventLogCount;
/// <summary>True for the GameEvent types this file tracks.</summary>
public static bool IsTradeEvent(uint eventType) => eventType >= 0x01FD && eventType <= 0x0208;
/// <summary>
/// A trade GameEvent (SmartBoxHooks.ParseGameEvent, AC's main thread, before AC handles it).
/// <paramref name="size"/> counts the 4-byte event type. No allocation on the state path.
/// </summary>
public static void OnGameEvent(uint eventType, IntPtr data, uint size)
{
uint a = size >= 8 ? Rd(data, 4) : 0;
uint b = size >= 12 ? Rd(data, 8) : 0;
uint self = ClientHelperHooks.GetPlayerId();
lock (_lock)
{
switch (eventType)
{
case 0x01FD: // RegisterTrade: initiator, partner, stamp
if (size < 12) return;
_open = true;
_generation++;
_initiatorId = a;
_partnerId = a != 0 && a != self ? a : b;
ClearWindow();
_closeReason = 0;
break;
case 0x01FE: // OpenTrade: objectId
if (!_open)
{
_open = true;
_generation++;
ClearWindow();
_closeReason = 0;
}
if (_partnerId == 0 && a != 0 && a != self)
_partnerId = a;
break;
case 0x01FF: // CloseTrade: EndTradeReason
_open = false;
_closeReason = a;
_partnerId = 0;
_initiatorId = 0;
ClearWindow();
break;
case 0x0200: // AddToTrade: item, side, slot
if (size < 12 || a == 0) return;
if (b == TradeSidePartner) AddUnique(_partnerItems, ref _partnerCount, a);
else AddUnique(_selfItems, ref _selfCount, a);
// The server clears both acceptances whenever the window changes.
_selfAccepted = _partnerAccepted = false;
break;
case 0x0201: // RemoveFromTrade: item, side
if (a == 0) return;
if (b != TradeSideSelf) RemoveItem(_partnerItems, ref _partnerCount, a);
if (b != TradeSidePartner) RemoveItem(_selfItems, ref _selfCount, a);
_selfAccepted = _partnerAccepted = false;
break;
case 0x0202: // AcceptTrade: who
_acceptedBy = a;
// Who is "you": the player id when known, else "not the partner".
if (self != 0 ? a != self : (a != 0 && a == _partnerId))
{
_partnerAccepted = true;
_partnerAcceptCount++;
}
else
{
_selfAccepted = true;
}
break;
case 0x0203: // DeclineTrade: who
_declinedBy = a;
_selfAccepted = _partnerAccepted = false;
break;
case 0x0205: // ResetTrade: who
_resetBy = a;
ClearWindow();
break;
case 0x0207: // TradeFailure: item, WeenieError
_failureCount++;
_failureItem = a;
_failureReason = b;
if (a != 0) RemoveItem(_selfItems, ref _selfCount, a);
break;
case 0x0208: // ClearTradeAcceptance
_selfAccepted = _partnerAccepted = false;
break;
default:
return;
}
_sequence++;
_lastEventType = eventType;
}
if (_eventLogCount < 200)
{
_eventLogCount++;
RynthLog.Compat($"Trade: evt=0x{eventType:X4} a=0x{a:X8} b=0x{b:X8} len={size} partner=0x{_partnerId:X8} you={_selfCount} them={_partnerCount}");
}
}
/// <summary>WeenieError 0x0529 TradeComplete (AC's main thread).</summary>
public static void OnTradeComplete()
{
lock (_lock)
{
_completedCount++;
_sequence++;
}
if (_eventLogCount < 200)
{
_eventLogCount++;
RynthLog.Compat("Trade: complete (WeenieError 0x0529)");
}
}
private static void ClearWindow()
{
_selfCount = 0;
_partnerCount = 0;
_selfAccepted = false;
_partnerAccepted = false;
}
private static void AddUnique(uint[] list, ref int count, uint id)
{
for (int i = 0; i < count; i++)
if (list[i] == id) return;
if (count < list.Length) list[count++] = id;
}
private static void RemoveItem(uint[] list, ref int count, uint id)
{
for (int i = 0; i < count; i++)
{
if (list[i] != id) continue;
for (int j = i + 1; j < count; j++) list[j - 1] = list[j];
count--;
return;
}
}
private static uint Rd(IntPtr data, int offset) => unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, offset)));
/// <summary>
/// v72 GetTradeState: copy the state into <paramref name="state"/> (up to state->Size bytes).
/// Returns the bytes written, 0 on a bad argument. Any thread.
/// </summary>
public static int GetState(TradeStateNative* state)
{
if (state == null) return 0;
uint want = state->Size;
if (want < 8) return 0;
TradeStateNative s = default;
lock (_lock)
{
uint flags = 0;
if (_open) flags |= TradeStateFlags.Open;
if (_selfAccepted) flags |= TradeStateFlags.YouAccepted;
if (_partnerAccepted) flags |= TradeStateFlags.PartnerAccepted;
s.Flags = flags;
s.Generation = _generation;
s.Sequence = _sequence;
s.PartnerId = _partnerId;
s.InitiatorId = _initiatorId;
s.SelfItemCount = _selfCount;
s.PartnerItemCount = _partnerCount;
s.LastEventType = _lastEventType;
s.FailureCount = _failureCount;
s.LastFailureItemId = _failureItem;
s.LastFailureReason = _failureReason;
s.LastCloseReason = _closeReason;
s.LastAcceptedBy = _acceptedBy;
s.LastDeclinedBy = _declinedBy;
s.LastResetBy = _resetBy;
s.CompletedCount = _completedCount;
s.PartnerAcceptCount = _partnerAcceptCount;
}
if (SmartBoxHooks.IsGameEventHookInstalled) s.Flags |= TradeStateFlags.Watching;
if (ActionsAvailable) s.Flags |= TradeStateFlags.ActionsAvailable;
uint n = Math.Min(want, (uint)sizeof(TradeStateNative));
s.Size = n;
Buffer.MemoryCopy(&s, state, want, n);
return (int)n;
}
/// <summary>
/// v72 GetTradeItems: copy up to <paramref name="capacity"/> item ids from one side
/// (1 = yours, 2 = the partner's) and return that side's total count; -1 for a bad side.
/// </summary>
public static int GetItems(int side, uint* buffer, int capacity)
{
if (side != (int)TradeSideSelf && side != (int)TradeSidePartner) return -1;
lock (_lock)
{
uint[] list = side == (int)TradeSideSelf ? _selfItems : _partnerItems;
int count = side == (int)TradeSideSelf ? _selfCount : _partnerCount;
if (buffer != null && capacity > 0)
{
int n = Math.Min(capacity, count);
for (int i = 0; i < n; i++) buffer[i] = list[i];
}
return count;
}
}
}

View file

@ -0,0 +1,145 @@
// ============================================================================
// RynthCore.Engine - Compatibility/PlayerTraining.cs
//
// Spending unassigned XP on an attribute, a vital or a skill (the Skills panel,
// docs/IMGUI_SKILLS.md), through the retail client's own senders, bound the
// way PlayerTrade binds CM_Trade:
//
// CM_Train::Event_TrainAttribute(atype, xp) 0x006A8E90 0x0045 RaiseAttribute
// CM_Train::Event_TrainAttribute2nd(vtype, xp) 0x006A8FA0 0x0044 RaiseVital
// CM_Train::Event_TrainSkill(stype, xp) 0x006A90B0 0x0046 RaiseSkill
// CM_Train::Event_TrainSkillAdvancementClass(stype, credits)
// 0x006A91C0 0x0047 TrainSkill
//
// The last is what the retail skills window's train dialog sends
// (gmSkillUI::TrainSkillDialogCallback 0x0049C480 calls it with the skill and
// the credits). ACE's handler (Player.HandleActionTrainSkill) only trains an
// untrained skill, and only when the credits sent equal the portal SkillTable's
// TrainedCost and you have them. Specializing has no game action on ACE: it
// takes the skill's Gem of Enlightenment (SkillAlterationDevice).
//
// bool __cdecl (Chorizite acclient map); each only builds and sends the game
// action, in the generated CM_* sender shape Event_AddToTrade has (two
// arguments: arg block +0x0C), so the patterns run to the opcode immediate.
// Cut with tools/pe_pattern.py GEN and unique on both acclient copies
// (C:\Turbine and C:\Games\RynthCore\AcClient). Bound only by a unique pattern
// match: a miss leaves raising unavailable, never a fixed-VA call.
//
// The server (ACE Player.HandleActionRaise*) checks the XP against unassigned XP
// and the XP left to the top rank, and raises as many ranks as it covers.
// Vitals are addressed by their maximum: 1 health, 3 stamina, 5 mana.
//
// 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.
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class PlayerTraining
{
internal enum TrainKind : uint
{
Attribute = 1,
Vital = 2,
Skill = 3,
// Untrained -> trained with skill credits (the amount is credits, not XP).
TrainWithCredits = 4,
}
private const int EventTrainAttributeVa = 0x006A8E90;
private const int EventTrainAttribute2ndVa = 0x006A8FA0;
private const int EventTrainSkillVa = 0x006A90B0;
private const int EventTrainSkillAdvancementClassVa = 0x006A91C0;
// The CM_* generated sender template (see PlayerTrade); the last byte is the opcode.
private static readonly byte?[] PatEventTrainAttribute = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x45 ];
private static readonly byte?[] PatEventTrainAttribute2nd = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x44 ];
private static readonly byte?[] PatEventTrainSkill = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x46 ];
private static readonly byte?[] PatEventTrainSkillAdvancementClass = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x0C, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x47 ];
private static delegate* unmanaged[Cdecl]<uint, uint, byte> _eventTrainAttribute;
private static delegate* unmanaged[Cdecl]<uint, uint, byte> _eventTrainAttribute2nd;
private static delegate* unmanaged[Cdecl]<uint, uint, byte> _eventTrainSkill;
private static delegate* unmanaged[Cdecl]<uint, uint, byte> _eventTrainSkillAdvancementClass;
/// <summary>True when all three raise senders are bound. Any thread.</summary>
public static bool Available => _eventTrainAttribute != null && _eventTrainAttribute2nd != null && _eventTrainSkill != null;
/// <summary>True when the train-with-credits sender is bound. Any thread.</summary>
public static bool TrainAvailable => _eventTrainSkillAdvancementClass != null;
/// <summary>Bind the senders. Called from ClientHelperHooks.Probe (engine init).</summary>
public static void Probe(AcClientTextSection text)
{
_eventTrainAttribute = (delegate* unmanaged[Cdecl]<uint, uint, byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTraining.Event_TrainAttribute", PatEventTrainAttribute, EventTrainAttributeVa));
_eventTrainAttribute2nd = (delegate* unmanaged[Cdecl]<uint, uint, byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTraining.Event_TrainAttribute2nd", PatEventTrainAttribute2nd, EventTrainAttribute2ndVa));
_eventTrainSkill = (delegate* unmanaged[Cdecl]<uint, uint, byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTraining.Event_TrainSkill", PatEventTrainSkill, EventTrainSkillVa));
_eventTrainSkillAdvancementClass = (delegate* unmanaged[Cdecl]<uint, uint, byte>)ResolveFn(HookResolver.Resolve(text, "PlayerTraining.Event_TrainSkillAdvancementClass", PatEventTrainSkillAdvancementClass, EventTrainSkillAdvancementClassVa));
RynthLog.Verbose($"Compat: raise senders {(Available ? "ready" : "partly bound")} (attribute={_eventTrainAttribute != null} vital={_eventTrainAttribute2nd != null} skill={_eventTrainSkill != null} train={_eventTrainSkillAdvancementClass != null}).");
}
// Fail closed: these send game actions, so only a unique pattern match binds.
private static void* ResolveFn(HookResolver.ResolveResult r) =>
r.Success && r.Source == HookResolver.ResolveSource.PatternScan ? (void*)r.Address : null;
private static bool Bound(TrainKind kind) => kind switch
{
TrainKind.Attribute => _eventTrainAttribute != null,
TrainKind.Vital => _eventTrainAttribute2nd != null,
TrainKind.Skill => _eventTrainSkill != null,
TrainKind.TrainWithCredits => _eventTrainSkillAdvancementClass != null,
_ => false,
};
private static bool ValidTarget(TrainKind kind, uint stype) => kind switch
{
TrainKind.Attribute => stype >= 1 && stype <= 6,
TrainKind.Vital => stype is 1 or 3 or 5,
TrainKind.Skill or TrainKind.TrainWithCredits => stype >= 1 && stype <= 54,
_ => false,
};
/// <summary>
/// Spend <paramref name="xp"/> unassigned XP on one attribute (1..6), vital maximum
/// (1 health, 3 stamina, 5 mana) or skill. Off AC's main thread, or with
/// <paramref name="defer"/> (a UI click inside the ImGui frame), it is queued and sent
/// from the drain. Returns false when unbound, the target is invalid or the queue is full.
/// With TrainKind.TrainWithCredits the amount is skill credits (see <see cref="TrainSkill"/>).
/// </summary>
public static bool Raise(TrainKind kind, uint stype, uint xp, bool defer = false)
{
if (!Bound(kind) || !ValidTarget(kind, stype) || xp == 0)
return false;
if (defer || !MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueTrain((uint)kind, stype, xp);
byte rv = kind switch
{
TrainKind.Attribute => _eventTrainAttribute(stype, xp),
TrainKind.Vital => _eventTrainAttribute2nd(stype, xp),
TrainKind.TrainWithCredits => _eventTrainSkillAdvancementClass(stype, xp),
_ => _eventTrainSkill(stype, xp),
};
RynthLog.Compat(kind == TrainKind.TrainWithCredits
? $"PlayerTraining: train skill {stype} with {xp} credits rv={rv}"
: $"PlayerTraining: raise {kind} {stype} with {xp:N0} XP rv={rv}");
PlayerProgressHooks.RefreshSoon();
return rv != 0;
}
/// <summary>
/// Train an untrained skill with <paramref name="credits"/> skill credits (0x0047 TrainSkill).
/// The server wants exactly the portal SkillTable's TrainedCost. Same threading as Raise.
/// </summary>
public static bool TrainSkill(uint stype, uint credits, bool defer = false) =>
Raise(TrainKind.TrainWithCredits, stype, credits, defer);
/// <summary>AcMainThreadQueue drain (AC's main thread): A = TrainKind, B = stype, C = XP.</summary>
internal static void RunQueued(uint kind, uint stype, uint xp)
{
try { Raise((TrainKind)kind, stype, xp); }
catch (Exception ex) { RynthLog.Compat($"PlayerTraining: queued raise failed - {ex.Message}"); }
}
}

View file

@ -40,6 +40,16 @@ internal static class PlayerVitalsHooks
internal static void ResetSession()
{
KnownPlayerQualitiesPtr = IntPtr.Zero;
// The off-thread base-vitals copy belongs to the old character.
lock (CacheLock)
{
_baseVitalsHp = _baseVitalsStam = _baseVitalsMana = 0;
_baseVitalsOwner = IntPtr.Zero;
// The vitals snapshot is the old character's too. Kept, the next character showed
// its health until a vital changed, and the login seed's "highest max seen" rule
// kept the old character's larger maximums for good (2026-10-01).
_snapshot = default;
}
// Creature health is keyed by object id — ids don't survive the
// session, and without this clear the 1024-entry cap filled over a
// long session and every NEW creature was silently never tracked.
@ -326,6 +336,80 @@ internal static class PlayerVitalsHooks
if (ptr == IntPtr.Zero)
return false;
// Off AC's main thread (host GetPlayerBaseVitalsFn on the pump: RynthAi meta
// getcharvital_base, RynthLua): serve the main-thread copy. Calling
// CACQualities::InqAttribute2nd here walked the player's attribute table
// while the main thread can rebuild it (the 0x00416C86 class). Base max only
// changes when XP is spent or gear/augs change, so ~1 s old is fine. The
// copy must belong to the current qualities object (a relog swaps it).
if (!MainThreadGuard.IsOnMainThread())
{
lock (CacheLock)
{
if (_baseVitalsOwner != ptr)
return false;
baseMaxHp = _baseVitalsHp;
baseMaxStam = _baseVitalsStam;
baseMaxMana = _baseVitalsMana;
}
return baseMaxHp > 0 || baseMaxStam > 0 || baseMaxMana > 0;
}
return TryReadPlayerBaseVitalsLive(ptr, out baseMaxHp, out baseMaxStam, out baseMaxMana);
}
// Main-thread base-vitals copy for the off-thread path above. Separate from the
// vital snapshot and from ClientObjectHooks.PrefetchPlayerStats on purpose: it
// must not change either one's semantics.
private static uint _baseVitalsHp, _baseVitalsStam, _baseVitalsMana;
private static IntPtr _baseVitalsOwner;
private static long _nextBaseVitalsPrefetchMs;
private const int BaseVitalsPrefetchIntervalMs = 1000;
/// <summary>
/// Main thread only (MainThreadSnapshots.Tick). Refreshes the base-vitals copy
/// about once a second from the live qualities table.
/// </summary>
internal static void PrefetchBaseVitals()
{
if (!MainThreadGuard.IsOnMainThread() || _inqAttribute2ndStruct == null)
return;
IntPtr ptr = KnownPlayerQualitiesPtr;
if (ptr == IntPtr.Zero)
return;
// A new qualities object (login / relog / reseed) is read within ~250 ms
// rather than waiting out the 1 s refresh, so off-thread callers see values
// about as soon as they did when the read was live.
long now = Environment.TickCount64;
if (now < _nextBaseVitalsPrefetchMs)
return;
bool ownerCurrent;
lock (CacheLock) ownerCurrent = _baseVitalsOwner == ptr;
_nextBaseVitalsPrefetchMs = now + (ownerCurrent ? BaseVitalsPrefetchIntervalMs : 250);
if (!ClientObjectHooks.IsCacQualitiesObject(ptr))
return;
if (TryReadPlayerBaseVitalsLive(ptr, out uint hp, out uint stam, out uint mana))
{
lock (CacheLock)
{
_baseVitalsHp = hp;
_baseVitalsStam = stam;
_baseVitalsMana = mana;
_baseVitalsOwner = ptr;
}
}
}
// The live read (unchanged from the pre-2026-09-30 body). MAIN THREAD ONLY.
private static unsafe bool TryReadPlayerBaseVitalsLive(IntPtr ptr, out uint baseMaxHp, out uint baseMaxStam, out uint baseMaxMana)
{
baseMaxHp = baseMaxStam = baseMaxMana = 0;
if (!MainThreadGuard.IsOnMainThread() || _inqAttribute2ndStruct == null || ptr == IntPtr.Zero)
return false;
try
{
SecondaryAttributeNative v = default;

View file

@ -115,6 +115,11 @@ internal static class PowerbarHooks
public static void Initialize()
{
// "Hide retail vitals" rides this init step (EntryPoint's list of steps is
// not edited for it); it resolves and hooks on its own and never throws.
try { RetailVitalsHooks.Initialize(); }
catch (Exception ex) { RynthLog.Compat($"PowerbarHooks: RetailVitalsHooks.Initialize threw {ex.GetType().Name}: {ex.Message}"); }
if (_hookInstalled)
return;

View file

@ -290,11 +290,31 @@ internal static class ProcessExitHooks
// hProcess == -1 (pseudo-handle for current process) or == GetCurrentProcess() handle.
bool selfKill = hProcess == new IntPtr(-1) || hProcess == GetCurrentProcessHandle();
if (selfKill)
{
LogTermination("TerminateProcess", hProcess, exitCode);
DumpCrashOnce("TerminateProcess", exitCode);
}
try { return _terminateOriginal!(hProcess, exitCode); }
catch { return false; }
}
// A crash exit (an NTSTATUS error code, 0xC0000000 and up: 0xC0000005 is an access
// violation) on the way out: write a minidump once, while the faulting frames are still on
// the stack. The runtime ends the process with TerminateProcess after a native AV under one
// of our detours, so no unhandled exception ever reaches a crash watcher (procdump -e saw
// nothing for Lucy's Town Network crashes, 10-01 19:46 and 10-02 15:55).
private static int _crashDumped;
private static void DumpCrashOnce(string via, uint code)
{
if (code < 0xC0000000u || System.Threading.Interlocked.Exchange(ref _crashDumped, 1) != 0) return;
try
{
if (CrashDump.WriteSelfDump($"{via} 0x{code:X8}", out string path, "crash"))
RynthLog.Info($"ProcessExit: crash dump written {path} ({via} 0x{code:X8})");
}
catch { }
}
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
private static IntPtr GetCurrentProcessHandle() => GetCurrentProcess();
@ -312,7 +332,10 @@ internal static class ProcessExitHooks
{
bool selfKill = processHandle == new IntPtr(-1) || processHandle == GetCurrentProcessHandle();
if (selfKill)
{
LogTermination("NtTerminateProcess", processHandle, exitStatus);
DumpCrashOnce("NtTerminateProcess", exitStatus);
}
try { return _ntTermOriginal!(processHandle, exitStatus); }
catch { return 0xC0000001; /* STATUS_UNSUCCESSFUL */ }
}
@ -361,6 +384,9 @@ internal static class ProcessExitHooks
HardTerminateNoReentry(code);
}
/// <summary>ExitProcess/TerminateProcess was called: the process is closing.</summary>
public static bool TerminationIntercepted => Volatile.Read(ref _logged) != 0;
private static void LogTermination(string func, IntPtr hProcess, uint exitCode)
{
if (Interlocked.Exchange(ref _logged, 1) != 0)

View file

@ -0,0 +1,120 @@
// ============================================================================
// RynthCore.Engine - Compatibility/PropertyCaches.cs
//
// One lookup over the engine's property caches, in the order every
// TryGetObject*Property uses them (2026-09-30). Pure dictionary reads under
// their owners' locks: safe on any thread, never touches AC.
//
// the player: PlayerDescription + private updates (PropertyUpdateHooks self
// record), then public updates about the player, then the
// client's own qualities tables (ClientObjectHooks' 1 s
// main-thread snapshot), then the player's last identify;
// any other: its last identify (with later updates folded in), then the
// public updates the server sent for it.
//
// What the client knows beyond these (PublicWeenieDesc fields, AC's live
// qualities on the main thread) stays with ClientObjectHooks.
// ============================================================================
namespace RynthCore.Engine.Compatibility;
internal static class PropertyCaches
{
private static bool IsPlayer(uint objectId)
{
if (objectId == 0) return false;
uint me = ClientHelperHooks.GetPlayerId();
return me != 0 && me == objectId;
}
public static bool TryGetInt(uint objectId, uint stype, out int value)
{
if (IsPlayer(objectId))
{
if (PropertyUpdateHooks.TryGetSelfInt(stype, out value)) return true;
if (PropertyUpdateHooks.TryGetCachedIntProperty(objectId, stype, out value)) return true;
if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId)?.Ints.TryGetValue(stype, out value) == true) return true;
return AppraisalHooks.TryGetCachedIntProperty(objectId, stype, out value);
}
return AppraisalHooks.TryGetCachedIntProperty(objectId, stype, out value)
|| PropertyUpdateHooks.TryGetCachedIntProperty(objectId, stype, out value);
}
public static bool TryGetInt64(uint objectId, uint stype, out long value)
{
if (IsPlayer(objectId))
{
if (PropertyUpdateHooks.TryGetSelfInt64(stype, out value)) return true;
if (PropertyUpdateHooks.TryGetCachedInt64Property(objectId, stype, out value)) return true;
if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId)?.Int64s.TryGetValue(stype, out value) == true) return true;
return AppraisalHooks.TryGetCachedInt64Property(objectId, stype, out value);
}
return AppraisalHooks.TryGetCachedInt64Property(objectId, stype, out value)
|| PropertyUpdateHooks.TryGetCachedInt64Property(objectId, stype, out value);
}
public static bool TryGetBool(uint objectId, uint stype, out bool value)
{
if (IsPlayer(objectId))
{
if (PropertyUpdateHooks.TryGetSelfBool(stype, out value)) return true;
if (PropertyUpdateHooks.TryGetCachedBoolProperty(objectId, stype, out value)) return true;
if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId)?.Bools.TryGetValue(stype, out value) == true) return true;
return AppraisalHooks.TryGetCachedBoolProperty(objectId, stype, out value);
}
return AppraisalHooks.TryGetCachedBoolProperty(objectId, stype, out value)
|| PropertyUpdateHooks.TryGetCachedBoolProperty(objectId, stype, out value);
}
public static bool TryGetFloat(uint objectId, uint stype, out double value)
{
if (IsPlayer(objectId))
{
if (PropertyUpdateHooks.TryGetSelfFloat(stype, out value)) return true;
if (PropertyUpdateHooks.TryGetCachedDoubleProperty(objectId, stype, out value)) return true;
if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId)?.Floats.TryGetValue(stype, out value) == true) return true;
return AppraisalHooks.TryGetCachedDoubleProperty(objectId, stype, out value);
}
return AppraisalHooks.TryGetCachedDoubleProperty(objectId, stype, out value)
|| PropertyUpdateHooks.TryGetCachedDoubleProperty(objectId, stype, out value);
}
public static bool TryGetString(uint objectId, uint stype, out string value)
{
if (IsPlayer(objectId))
{
if (PropertyUpdateHooks.TryGetSelfString(stype, out value)) return true;
if (PropertyUpdateHooks.TryGetCachedStringProperty(objectId, stype, out value)) return true;
if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId) is { } q && q.Strings.TryGetValue(stype, out string? qs)) { value = qs; return true; }
return AppraisalHooks.TryGetCachedStringProperty(objectId, stype, out value);
}
return AppraisalHooks.TryGetCachedStringProperty(objectId, stype, out value)
|| PropertyUpdateHooks.TryGetCachedStringProperty(objectId, stype, out value);
}
public static bool TryGetDataId(uint objectId, uint stype, out uint value)
{
if (IsPlayer(objectId))
{
if (PropertyUpdateHooks.TryGetSelfDataId(stype, out value)) return true;
if (PropertyUpdateHooks.TryGetCachedDataIdProperty(objectId, stype, out value)) return true;
if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId)?.DataIds.TryGetValue(stype, out value) == true) return true;
return AppraisalHooks.TryGetCachedDataIdProperty(objectId, stype, out value);
}
return AppraisalHooks.TryGetCachedDataIdProperty(objectId, stype, out value)
|| PropertyUpdateHooks.TryGetCachedDataIdProperty(objectId, stype, out value);
}
public static bool TryGetInstanceId(uint objectId, uint stype, out uint value)
{
if (IsPlayer(objectId))
{
if (PropertyUpdateHooks.TryGetSelfInstanceId(stype, out value)) return true;
if (PropertyUpdateHooks.TryGetCachedInstanceIdProperty(objectId, stype, out value)) return true;
if (ClientObjectHooks.PlayerQualitiesSnapshot(objectId)?.InstanceIds.TryGetValue(stype, out value) == true) return true;
return AppraisalHooks.TryGetCachedInstanceIdProperty(objectId, stype, out value);
}
return PropertyUpdateHooks.TryGetCachedInstanceIdProperty(objectId, stype, out value)
|| AppraisalHooks.TryGetCachedInstanceIdProperty(objectId, stype, out value);
}
}

View file

@ -1,36 +1,34 @@
// ============================================================================
// RynthCore.Engine - Compatibility/PropertyUpdateHooks.cs
//
// Hooks CM_Qualities network message dispatchers to cache property updates
// broadcast by the server. This solves the problem where
// CBaseQualities::InqInt/InqBool fail for static world objects (doors, signs,
// etc.) because m_pQualities is null — those objects never get a qualities
// block allocated in client memory, but the server still sends property
// update messages that are processed and discarded.
// Caches the property update messages the server sends (UpdateProperty*,
// public and private, every type) and the player's own properties from
// PlayerDescription. This solves the problem where CBaseQualities::Inq* fail
// for objects whose m_pQualities is null (doors, signs, pack items), and where
// off AC's main thread no Inq* may run at all: plugins, metas and Lua read
// from these caches instead.
//
// Hooked functions (all cdecl, from Chorizite CM.cs):
// CM_Qualities::DispatchUI_UpdateInt @ 0x006B0000
// CM_Qualities::DispatchUI_UpdateBool @ 0x006AFF00
// CM_Qualities::DispatchUI_PrivateUpdateInt @ 0x006AF960
// CM_Qualities::DispatchUI_PrivateUpdateBool@ 0x006AF880
// Sources (all on AC's main thread):
// - SmartBoxHooks.ParseGameEvent (UIQueueManager::ProcessNetBlobData) hands
// every UpdateProperty* message (0x02CD-0x02DA) to OnUpdateWire and the
// PlayerDescription (game event 0x13) to OnPlayerDescriptionWire, parsed by
// PropertyWire in ACE's exact formats. This is the one path for int64,
// float, string, data id and instance id updates (2026-09-30).
// - The older CM_Qualities::DispatchUI_Update{Int,Bool} hooks (from Chorizite
// CM.cs) stay installed: they cache int/bool updates only when the
// game-event hook is missing, so nothing is lost if it fails to install.
// CM_Qualities::DispatchUI_UpdateInt @ 0x006B0000
// CM_Qualities::DispatchUI_UpdateBool @ 0x006AFF00
// CM_Qualities::DispatchUI_PrivateUpdateInt @ 0x006AF960
// CM_Qualities::DispatchUI_PrivateUpdateBool@ 0x006AF880
//
// Eviction via:
// ECM_Physics::SendNotice_BeingDeleted @ 0x00693960
//
// Public message buffer layout:
// [0..3] sequence (uint)
// [4..7] objectGUID (uint)
// [8..11] stype (uint)
// [12..15] value (int / int-as-bool)
//
// Private message buffer layout (player implied):
// [0..3] sequence (uint)
// [4..7] stype (uint)
// [8..11] value (int / int-as-bool)
// Bounds: evicted on ECM_Physics::SendNotice_BeingDeleted @ 0x00693960,
// cleared on logout (PluginManager.DispatchPendingLogout), and pruned to the
// live objects when more than MaxObjects are cached.
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
@ -76,43 +74,226 @@ internal static class PropertyUpdateHooks
private static string _statusMessage = "Not initialized.";
private static int _hookCount; // how many of the 5 hooks succeeded
// --- Property caches ---
// guid → (stype → value)
private static readonly ConcurrentDictionary<uint, ConcurrentDictionary<uint, int>> _intCache = new();
private static readonly ConcurrentDictionary<uint, ConcurrentDictionary<uint, int>> _boolCache = new();
// --- Property caches (all under _lock) ---
// Public updates: guid → every property the server updated for it this session.
private static readonly Dictionary<uint, PropertyBag> _bags = new();
// The player: PlayerDescription's tables, then every private update (they carry no guid).
private static PropertyBag _self = new();
private static bool _selfDescribed;
private static readonly object _lock = new();
private const int MaxObjects = 4096;
private static int _updateLogCount;
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
// --- Public query API ---
// --- Public query API (any thread: dictionary reads under _lock) ---
public static bool TryGetCachedIntProperty(uint objectId, uint stype, out int value)
{
value = 0;
if (_intCache.TryGetValue(objectId, out var props))
return props.TryGetValue(stype, out value);
return false;
lock (_lock)
return _bags.TryGetValue(objectId, out PropertyBag? b) && b.Ints.TryGetValue(stype, out value);
}
public static bool TryGetCachedBoolProperty(uint objectId, uint stype, out bool value)
{
value = false;
if (_boolCache.TryGetValue(objectId, out var props))
lock (_lock)
return _bags.TryGetValue(objectId, out PropertyBag? b) && b.Bools.TryGetValue(stype, out value);
}
public static bool TryGetCachedInt64Property(uint objectId, uint stype, out long value)
{
value = 0;
lock (_lock)
return _bags.TryGetValue(objectId, out PropertyBag? b) && b.Int64s.TryGetValue(stype, out value);
}
public static bool TryGetCachedDoubleProperty(uint objectId, uint stype, out double value)
{
value = 0;
lock (_lock)
return _bags.TryGetValue(objectId, out PropertyBag? b) && b.Floats.TryGetValue(stype, out value);
}
public static bool TryGetCachedStringProperty(uint objectId, uint stype, out string value)
{
value = string.Empty;
lock (_lock)
{
if (props.TryGetValue(stype, out int raw))
if (_bags.TryGetValue(objectId, out PropertyBag? b) && b.Strings.TryGetValue(stype, out string? s))
{
value = raw != 0;
value = s;
return true;
}
return false;
}
return false;
}
public static bool TryGetCachedDataIdProperty(uint objectId, uint stype, out uint value)
{
value = 0;
lock (_lock)
return _bags.TryGetValue(objectId, out PropertyBag? b) && b.DataIds.TryGetValue(stype, out value);
}
public static bool TryGetCachedInstanceIdProperty(uint objectId, uint stype, out uint value)
{
value = 0;
lock (_lock)
return _bags.TryGetValue(objectId, out PropertyBag? b) && b.InstanceIds.TryGetValue(stype, out value);
}
// The player's own record (PlayerDescription + private updates).
public static bool TryGetSelfInt(uint stype, out int value) { lock (_lock) return _self.Ints.TryGetValue(stype, out value); }
public static bool TryGetSelfInt64(uint stype, out long value) { lock (_lock) return _self.Int64s.TryGetValue(stype, out value); }
public static bool TryGetSelfBool(uint stype, out bool value) { lock (_lock) return _self.Bools.TryGetValue(stype, out value); }
public static bool TryGetSelfFloat(uint stype, out double value) { lock (_lock) return _self.Floats.TryGetValue(stype, out value); }
public static bool TryGetSelfDataId(uint stype, out uint value) { lock (_lock) return _self.DataIds.TryGetValue(stype, out value); }
public static bool TryGetSelfInstanceId(uint stype, out uint value) { lock (_lock) return _self.InstanceIds.TryGetValue(stype, out value); }
public static bool TryGetSelfString(uint stype, out string value)
{
value = string.Empty;
lock (_lock)
{
if (!_self.Strings.TryGetValue(stype, out string? s)) return false;
value = s;
return true;
}
}
/// <summary>True once this session's PlayerDescription was read.</summary>
public static bool HasPlayerDescription
{
get { lock (_lock) return _selfDescribed; }
}
public static int CachedObjectCount
{
get { lock (_lock) return _bags.Count; }
}
public static int SelfPropertyCount
{
get { lock (_lock) return _self.Count; }
}
/// <summary>Evict all cached properties for an object (e.g. when it is destroyed).</summary>
public static void EvictObject(uint objectId)
{
_intCache.TryRemove(objectId, out _);
_boolCache.TryRemove(objectId, out _);
lock (_lock)
_bags.Remove(objectId);
}
/// <summary>Logout: nothing here survives the session (guids and the player change).</summary>
public static void ClearSession()
{
lock (_lock)
{
_bags.Clear();
_self = new PropertyBag();
_selfDescribed = false;
}
ClientObjectHooks.ClearPlayerQualitiesSnapshot();
}
// --- Wire entry points (AC's main thread, SmartBoxHooks.ParseGameEvent) ---
/// <summary>One UpdateProperty* message (0x02CD-0x02DA), from its opcode on.</summary>
internal static unsafe void OnUpdateWire(IntPtr data, int size)
{
if (data == IntPtr.Zero || size < 9)
return;
if (PropertyWire.TryParsePropertyUpdate(new ReadOnlySpan<byte>((void*)data, size), out PropertyUpdate u))
Apply(u);
}
/// <summary>The player's PlayerDescription (game event 0x13), from its event type on.</summary>
internal static unsafe void OnPlayerDescriptionWire(IntPtr data, int size)
{
if (data == IntPtr.Zero || size < 12)
return;
if (!PropertyWire.TryParsePlayerDescription(new ReadOnlySpan<byte>((void*)data, size), out PropertyBag bag, out bool truncated))
return;
lock (_lock)
{
// Private updates that raced ahead of the description are newer: keep them on top.
bag.MergeFrom(_self);
_self = bag;
_selfDescribed = true;
}
RynthLog.Compat($"Compat: PlayerDescription properties int={bag.Ints.Count} int64={bag.Int64s.Count} bool={bag.Bools.Count} " +
$"float={bag.Floats.Count} string={bag.Strings.Count} did={bag.DataIds.Count} iid={bag.InstanceIds.Count}{(truncated ? " TRUNCATED" : "")}");
}
/// <summary>
/// Files one update: a private one into the player's record, a public one under its object;
/// either way it is also folded into that object's identify record so the appraisal cache
/// (read first) doesn't serve a stale value.
/// </summary>
internal static void Apply(in PropertyUpdate u)
{
uint target;
if (u.IsPrivate)
{
lock (_lock)
_self.Apply(u);
target = ClientHelperHooks.GetPlayerId();
}
else
{
if (u.ObjectId == 0)
return;
lock (_lock)
{
if (!_bags.TryGetValue(u.ObjectId, out PropertyBag? bag))
{
if (_bags.Count >= MaxObjects)
PruneToLiveLocked();
_bags[u.ObjectId] = bag = new PropertyBag();
}
bag.Apply(u);
}
target = u.ObjectId;
}
if (target != 0)
AppraisalHooks.ApplyUpdate(target, u);
if (_updateLogCount < 8)
{
_updateLogCount++;
RynthLog.Info($"[PropUpd] {(u.IsPrivate ? "private" : "public")} {u.Kind} obj=0x{target:X8} key={u.Key} " +
$"value={(u.Kind == PropertyKind.Float ? u.Real.ToString(System.Globalization.CultureInfo.InvariantCulture) : u.Kind == PropertyKind.String ? u.Text : u.Integer.ToString(System.Globalization.CultureInfo.InvariantCulture))}");
}
}
// Caller holds _lock. Drops objects the client no longer knows (the identity walk's id list),
// or everything if that list is empty; the player's own public updates are kept.
private static void PruneToLiveLocked()
{
uint[] live = ClientObjectHooks.LiveObjectIds;
uint me = ClientHelperHooks.GetPlayerId();
if (live.Length == 0)
{
PropertyBag? mine = me != 0 && _bags.TryGetValue(me, out PropertyBag? m) ? m : null;
_bags.Clear();
if (mine != null) _bags[me] = mine;
return;
}
var keep = new HashSet<uint>(live);
var drop = new List<uint>();
foreach (uint id in _bags.Keys)
if (id != me && !keep.Contains(id))
drop.Add(id);
foreach (uint id in drop)
_bags.Remove(id);
if (_bags.Count >= MaxObjects) // everything is live: make room anyway
{
PropertyBag? mine = me != 0 && _bags.TryGetValue(me, out PropertyBag? m) ? m : null;
_bags.Clear();
if (mine != null) _bags[me] = mine;
}
}
// --- Initialization ---
@ -226,77 +407,39 @@ internal static class PropertyUpdateHooks
// --- Detour implementations ---
// The CM_Qualities dispatchers receive the message from its opcode on (acclient.exe:
// each begins `mov edx,[buf]; add buf,4; cmp edx,<its opcode>`), the same bytes
// ProcessNetBlobData hands SmartBoxHooks.ParseGameEvent - which caches every update type
// when the game-event hook is installed. These detours are the fallback for when it isn't.
private static unsafe void ApplyFromDispatcher(IntPtr buf, uint size)
{
if (SmartBoxHooks.IsGameEventHookInstalled || buf == IntPtr.Zero || size < 9 || size > 0x1000)
return;
if (PropertyWire.TryParsePropertyUpdate(new ReadOnlySpan<byte>((void*)buf, (int)size), out PropertyUpdate u))
Apply(u);
}
private static uint DetourUpdateInt(IntPtr uiPtr, IntPtr bufPtr, uint size)
{
try
{
// Public: seq(4) + guid(4) + stype(4) + value(4) = 16 bytes minimum
if (bufPtr != IntPtr.Zero && size >= 16)
{
uint guid = (uint)Marshal.ReadInt32(bufPtr + 4);
uint stype = (uint)Marshal.ReadInt32(bufPtr + 8);
int val = Marshal.ReadInt32(bufPtr + 12);
CacheInt(guid, stype, val);
}
}
catch { }
try { ApplyFromDispatcher(bufPtr, size); } catch { }
return _origUpdateInt!(uiPtr, bufPtr, size);
}
private static uint DetourUpdateBool(IntPtr uiPtr, IntPtr bufPtr, uint size)
{
try
{
// Public: seq(4) + guid(4) + stype(4) + value(4) = 16 bytes minimum
if (bufPtr != IntPtr.Zero && size >= 16)
{
uint guid = (uint)Marshal.ReadInt32(bufPtr + 4);
uint stype = (uint)Marshal.ReadInt32(bufPtr + 8);
int val = Marshal.ReadInt32(bufPtr + 12);
CacheBool(guid, stype, val);
}
}
catch { }
try { ApplyFromDispatcher(bufPtr, size); } catch { }
return _origUpdateBool!(uiPtr, bufPtr, size);
}
private static uint DetourPrivateUpdateInt(IntPtr uiPtr, IntPtr bufPtr, uint size)
{
try
{
// Private: seq(4) + stype(4) + value(4) = 12 bytes minimum
if (bufPtr != IntPtr.Zero && size >= 12)
{
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId != 0)
{
uint stype = (uint)Marshal.ReadInt32(bufPtr + 4);
int val = Marshal.ReadInt32(bufPtr + 8);
CacheInt(playerId, stype, val);
}
}
}
catch { }
try { ApplyFromDispatcher(bufPtr, size); } catch { }
return _origPrivateUpdateInt!(uiPtr, bufPtr, size);
}
private static uint DetourPrivateUpdateBool(IntPtr uiPtr, IntPtr bufPtr, uint size)
{
try
{
// Private: seq(4) + stype(4) + value(4) = 12 bytes minimum
if (bufPtr != IntPtr.Zero && size >= 12)
{
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId != 0)
{
uint stype = (uint)Marshal.ReadInt32(bufPtr + 4);
int val = Marshal.ReadInt32(bufPtr + 8);
CacheBool(playerId, stype, val);
}
}
}
catch { }
try { ApplyFromDispatcher(bufPtr, size); } catch { }
return _origPrivateUpdateBool!(uiPtr, bufPtr, size);
}
@ -311,25 +454,14 @@ internal static class PropertyUpdateHooks
{
uint objectId = (uint)Marshal.ReadInt32(idAddr);
if (objectId != 0)
{
EvictObject(objectId);
AppraisalHooks.EvictObject(objectId);
}
}
}
}
catch { }
return _origBeingDeleted!(weenieObjPtr);
}
// --- Cache helpers ---
private static void CacheInt(uint guid, uint stype, int value)
{
var props = _intCache.GetOrAdd(guid, _ => new ConcurrentDictionary<uint, int>());
props[stype] = value;
}
private static void CacheBool(uint guid, uint stype, int value)
{
var props = _boolCache.GetOrAdd(guid, _ => new ConcurrentDictionary<uint, int>());
props[stype] = value;
}
}

View file

@ -0,0 +1,629 @@
// ============================================================================
// RynthCore.Engine - Compatibility/PropertyWire.cs
//
// Pure parsers for every message that carries an object's properties to the
// client, in ACE's exact wire formats (ACE.Server: AppraiseInfo.cs and the
// Armor/Creature/Weapon/HookProfile writers, GameEventPlayerDescription.cs,
// GameMessagePrivate/PublicUpdateProperty*.cs, WorldObject_Networking.cs for
// the PublicWeenieDesc fields). No AC memory, no engine state: the engine feeds
// them from UIQueueManager::ProcessNetBlobData (SmartBoxHooks.ParseGameEvent),
// and the offline tests (tools\PropertyWireTests) compile
// this file in and feed them hand-built messages.
//
// ProcessNetBlobData hands its handlers the message from its type on: a game
// event (0xF7B0) arrives as [event type][payload], a top-level message as
// [opcode][body]. Verified against acclient.exe: the function compares [data]
// with 0x2D5/0x2D6 (string updates, @0x55CD72) and calls
// CM_Examine::SendNotice_SetAppraiseInfo (@0x55C862) and
// CPlayerSystem::Handle_PlayerDescription (@0x55BE35); the CM_Qualities
// DispatchUI_* handlers it calls read the opcode at buf+0.
// ============================================================================
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Engine.Compatibility;
/// <summary>The seven AC property types (STypeInt, STypeInt64, ...).</summary>
internal enum PropertyKind : byte
{
Int,
Int64,
Bool,
Float,
String,
DataId,
InstanceId,
}
/// <summary>One property update message (UpdateProperty* public or private).</summary>
internal readonly struct PropertyUpdate
{
public PropertyUpdate(PropertyKind kind, bool isPrivate, uint objectId, uint key, long integer, double real, string? text)
{
Kind = kind;
IsPrivate = isPrivate;
ObjectId = objectId;
Key = key;
Integer = integer;
Real = real;
Text = text;
}
public PropertyKind Kind { get; }
/// <summary>A private update is about the player and carries no object id.</summary>
public bool IsPrivate { get; }
/// <summary>The object a public update is about; 0 for a private one.</summary>
public uint ObjectId { get; }
public uint Key { get; }
/// <summary>Int, Int64, Bool (0/1), DataId and InstanceId values.</summary>
public long Integer { get; }
/// <summary>Float values.</summary>
public double Real { get; }
/// <summary>String values.</summary>
public string? Text { get; }
}
/// <summary>
/// An object's properties, one table per type. Not thread-safe: the engine's caches
/// guard every bag with their own lock.
/// </summary>
internal sealed class PropertyBag
{
public readonly Dictionary<uint, int> Ints = new();
public readonly Dictionary<uint, long> Int64s = new();
public readonly Dictionary<uint, bool> Bools = new();
public readonly Dictionary<uint, double> Floats = new();
public readonly Dictionary<uint, string> Strings = new();
public readonly Dictionary<uint, uint> DataIds = new();
public readonly Dictionary<uint, uint> InstanceIds = new();
public int Count => Ints.Count + Int64s.Count + Bools.Count + Floats.Count + Strings.Count + DataIds.Count + InstanceIds.Count;
public void Apply(in PropertyUpdate u)
{
switch (u.Kind)
{
case PropertyKind.Int: Ints[u.Key] = unchecked((int)u.Integer); break;
case PropertyKind.Int64: Int64s[u.Key] = u.Integer; break;
case PropertyKind.Bool: Bools[u.Key] = u.Integer != 0; break;
case PropertyKind.Float: Floats[u.Key] = u.Real; break;
case PropertyKind.String: Strings[u.Key] = u.Text ?? string.Empty; break;
case PropertyKind.DataId: DataIds[u.Key] = unchecked((uint)u.Integer); break;
case PropertyKind.InstanceId: InstanceIds[u.Key] = unchecked((uint)u.Integer); break;
}
}
/// <summary>Copies every value of <paramref name="other"/> in, replacing same-key values.</summary>
public void MergeFrom(PropertyBag other)
{
foreach (var kv in other.Ints) Ints[kv.Key] = kv.Value;
foreach (var kv in other.Int64s) Int64s[kv.Key] = kv.Value;
foreach (var kv in other.Bools) Bools[kv.Key] = kv.Value;
foreach (var kv in other.Floats) Floats[kv.Key] = kv.Value;
foreach (var kv in other.Strings) Strings[kv.Key] = kv.Value;
foreach (var kv in other.DataIds) DataIds[kv.Key] = kv.Value;
foreach (var kv in other.InstanceIds) InstanceIds[kv.Key] = kv.Value;
}
}
/// <summary>What one identify reply (game event 0xC9, SetAppraiseInfo) told the client.</summary>
internal sealed class IdentifyRecord
{
public uint ObjectId;
public uint Flags;
public bool Success;
/// <summary>The six tables, plus the armour/weapon/hook profile values filed under their property ids.</summary>
public readonly PropertyBag Properties = new();
public int SpellCount;
public bool HasArmorProfile, HasCreatureProfile, HasWeaponProfile, HasHookProfile;
public uint CreatureHealth, CreatureHealthMax;
/// <summary>A flagged section ran past the end of the message; everything before it was kept.</summary>
public bool Truncated;
}
internal static class PropertyWire
{
// Game events (ProcessNetBlobData: [event type][payload]).
public const uint EventPlayerDescription = 0x0013;
public const uint EventIdentifyObjectResponse = 0x00C9;
// Top-level messages (ACE GameMessageOpcode).
public const uint OpPrivateUpdateInt = 0x02CD, OpPublicUpdateInt = 0x02CE;
public const uint OpPrivateUpdateInt64 = 0x02CF, OpPublicUpdateInt64 = 0x02D0;
public const uint OpPrivateUpdateBool = 0x02D1, OpPublicUpdateBool = 0x02D2;
public const uint OpPrivateUpdateFloat = 0x02D3, OpPublicUpdateFloat = 0x02D4;
public const uint OpPrivateUpdateString = 0x02D5, OpPublicUpdateString = 0x02D6;
public const uint OpPrivateUpdateDataId = 0x02D7, OpPublicUpdateDataId = 0x02D8;
public const uint OpPrivateUpdateInstanceId = 0x02D9, OpPublicUpdateInstanceId = 0x02DA;
// IdentifyResponseFlags (ACE.Entity.Enum.IdentifyResponseFlags).
public const uint IdIntStats = 0x0001, IdBoolStats = 0x0002, IdFloatStats = 0x0004, IdStringStats = 0x0008,
IdSpellBook = 0x0010, IdWeaponProfile = 0x0020, IdHookProfile = 0x0040, IdArmorProfile = 0x0080,
IdCreatureProfile = 0x0100, IdDidStats = 0x1000, IdInt64Stats = 0x2000;
// PlayerDescription DescriptionPropertyFlag.
public const uint PdInt = 0x0001, PdBool = 0x0002, PdDouble = 0x0004, PdDid = 0x0008, PdString = 0x0010,
PdIid = 0x0040, PdInt64 = 0x0080;
// Property ids the profiles are filed under (ACE PropertyInt / PropertyFloat / PropertyBool).
public const uint IntValidLocations = 9, IntDamage = 44, IntDamageType = 45, IntWeaponSkill = 48, IntWeaponTime = 49, IntAmmoType = 50;
public const uint FloatWeaponLength = 21, FloatDamageVariance = 22, FloatMaximumVelocity = 26, FloatWeaponOffense = 62, FloatDamageMod = 63;
public const uint BoolInscribable = 22;
/// <summary>
/// ArmorProfile floats in wire order (ACE ArmorProfile.Write: slash, pierce, bludgeon, cold,
/// fire, acid, nether, lightning) and the PropertyFloat ids they are filed under
/// (ArmorModVsSlash 13 .. ArmorModVsAcid 18, ArmorModVsNether 165, ArmorModVsElectric 19).
/// </summary>
public static readonly uint[] ArmorProfileFloatIds = { 13, 14, 15, 16, 17, 18, 165, 19 };
public static bool IsPropertyUpdateOpcode(uint opcode) => opcode >= OpPrivateUpdateInt && opcode <= OpPublicUpdateInstanceId;
/// <summary>
/// Parses one UpdateProperty* message, starting at its opcode. Layouts (ACE):
/// private: [op][seq u8][key u32][value]
/// public: [op][seq u8][guid u32][key u32][value]
/// strings: private [op][seq][key][align 4][str16L], public [op][seq][key][guid][align 4][str16L]
/// (the public string update has the key BEFORE the guid, unlike every other type).
/// Values: int i32, int64 i64, bool u32, float f64, data id u32, instance id u32.
/// </summary>
public static bool TryParsePropertyUpdate(ReadOnlySpan<byte> msg, out PropertyUpdate update)
{
update = default;
var r = new WireReader(msg);
if (!r.U32(out uint op) || !IsPropertyUpdateOpcode(op) || !r.Skip(1)) // sequence byte
return false;
bool isPrivate = (op & 1) != 0; // every private opcode is odd, every public one even
uint guid = 0, key;
switch (op)
{
case OpPrivateUpdateString:
case OpPublicUpdateString:
{
if (!r.U32(out key)) return false;
if (!isPrivate && !r.U32(out guid)) return false;
if (!r.Align4() || !r.String16L(out string text)) return false;
update = new PropertyUpdate(PropertyKind.String, isPrivate, guid, key, 0, 0, text);
return true;
}
}
if (!isPrivate && !r.U32(out guid)) return false;
if (!r.U32(out key)) return false;
switch (op)
{
case OpPrivateUpdateInt:
case OpPublicUpdateInt:
if (!r.I32(out int i)) return false;
update = new PropertyUpdate(PropertyKind.Int, isPrivate, guid, key, i, 0, null);
return true;
case OpPrivateUpdateInt64:
case OpPublicUpdateInt64:
if (!r.I64(out long q)) return false;
update = new PropertyUpdate(PropertyKind.Int64, isPrivate, guid, key, q, 0, null);
return true;
case OpPrivateUpdateBool:
case OpPublicUpdateBool:
if (!r.U32(out uint b)) return false;
update = new PropertyUpdate(PropertyKind.Bool, isPrivate, guid, key, b != 0 ? 1 : 0, 0, null);
return true;
case OpPrivateUpdateFloat:
case OpPublicUpdateFloat:
if (!r.F64(out double d) || !double.IsFinite(d)) return false;
update = new PropertyUpdate(PropertyKind.Float, isPrivate, guid, key, 0, d, null);
return true;
case OpPrivateUpdateDataId:
case OpPublicUpdateDataId:
if (!r.U32(out uint did)) return false;
update = new PropertyUpdate(PropertyKind.DataId, isPrivate, guid, key, did, 0, null);
return true;
case OpPrivateUpdateInstanceId:
case OpPublicUpdateInstanceId:
if (!r.U32(out uint iid)) return false;
update = new PropertyUpdate(PropertyKind.InstanceId, isPrivate, guid, key, iid, 0, null);
return true;
}
return false;
}
/// <summary>
/// Parses an identify reply, starting at its event type (0xC9): [type][guid][flags][success],
/// then in ACE's write order the int, int64, bool, float, string and data id tables, the
/// spell book, the armour, creature, weapon and hook profiles. The tables are kept as sent;
/// the armour profile's ratings, the weapon profile's numbers and the hook profile's
/// locations/ammo/inscribable are added under their property ids, where the tables don't
/// already hold them (as the retail client's appraisal panel reads them, and UtilityBelt
/// exposes them). A section that runs past the end stops the parse; what came before is kept.
/// </summary>
public static bool TryParseIdentify(ReadOnlySpan<byte> msg, out IdentifyRecord record)
{
record = new IdentifyRecord();
var r = new WireReader(msg);
if (!r.U32(out uint type) || type != EventIdentifyObjectResponse)
return false;
if (!r.U32(out record.ObjectId) || !r.U32(out record.Flags) || !r.U32(out uint success) || record.ObjectId == 0)
return false;
record.Success = success != 0;
uint f = record.Flags;
PropertyBag bag = record.Properties;
if (!ReadSections(ref r, record, bag, f))
record.Truncated = true;
return true;
}
private static bool ReadSections(ref WireReader r, IdentifyRecord rec, PropertyBag bag, uint f)
{
if ((f & IdIntStats) != 0 && !ReadIntTable(ref r, bag.Ints)) return false;
if ((f & IdInt64Stats) != 0 && !ReadInt64Table(ref r, bag.Int64s)) return false;
if ((f & IdBoolStats) != 0 && !ReadBoolTable(ref r, bag.Bools)) return false;
if ((f & IdFloatStats) != 0 && !ReadFloatTable(ref r, bag.Floats)) return false;
if ((f & IdStringStats) != 0 && !ReadStringTable(ref r, bag.Strings)) return false;
if ((f & IdDidStats) != 0 && !ReadUIntTable(ref r, bag.DataIds)) return false;
if ((f & IdSpellBook) != 0)
{
if (!r.I32(out int n) || n < 0 || n > 100_000 || !r.Skip(n * 4)) return false;
rec.SpellCount = n;
}
if ((f & IdArmorProfile) != 0)
{
Span<float> prot = stackalloc float[8];
for (int i = 0; i < 8; i++)
if (!r.F32(out prot[i])) return false;
rec.HasArmorProfile = true;
for (int i = 0; i < 8; i++)
if (float.IsFinite(prot[i])) bag.Floats.TryAdd(ArmorProfileFloatIds[i], prot[i]);
}
if ((f & IdCreatureProfile) != 0)
{
// cpFlags, Health, HealthMax; ShowAttributes(0x8): Str, End, Quick, Coord, Focus, Self,
// Stamina, Mana, StaminaMax, ManaMax; HasBuffsDebuffs(0x1): u16 highlights, u16 colors.
if (!r.U32(out uint cp) || !r.U32(out rec.CreatureHealth) || !r.U32(out rec.CreatureHealthMax)) return false;
if ((cp & 0x8) != 0 && !r.Skip(40)) return false;
if ((cp & 0x1) != 0 && !r.Skip(4)) return false;
rec.HasCreatureProfile = true;
}
if ((f & IdWeaponProfile) != 0)
{
// ACE WeaponProfile.Write: DamageType, WeaponTime, WeaponSkill, Damage (u32 each),
// DamageVariance, DamageMod, WeaponLength, MaxVelocity, WeaponOffense (f64 each),
// MaxVelocityEstimated (u32; no property of its own).
if (!r.U32(out uint dmgType) || !r.U32(out uint time) || !r.U32(out uint skill) || !r.U32(out uint dmg)) return false;
if (!r.F64(out double variance) || !r.F64(out double dmgMod) || !r.F64(out double length)
|| !r.F64(out double maxVel) || !r.F64(out double offense) || !r.Skip(4)) return false;
rec.HasWeaponProfile = true;
bag.Ints.TryAdd(IntDamageType, unchecked((int)dmgType));
bag.Ints.TryAdd(IntWeaponTime, unchecked((int)time));
bag.Ints.TryAdd(IntWeaponSkill, unchecked((int)skill));
bag.Ints.TryAdd(IntDamage, unchecked((int)dmg));
AddFinite(bag.Floats, FloatDamageVariance, variance);
AddFinite(bag.Floats, FloatDamageMod, dmgMod);
AddFinite(bag.Floats, FloatWeaponLength, length);
AddFinite(bag.Floats, FloatMaximumVelocity, maxVel);
AddFinite(bag.Floats, FloatWeaponOffense, offense);
}
if ((f & IdHookProfile) != 0)
{
// ACE HookProfile.Write: Flags (Inscribable 1, IsHealer 2, IsFood 4, IsLockpick 8),
// ValidLocations, AmmoType. Sent when a house hook holds an item: the tables above
// are that item's.
if (!r.U32(out uint hookFlags) || !r.U32(out uint locations) || !r.U32(out uint ammo)) return false;
rec.HasHookProfile = true;
if (locations != 0) bag.Ints.TryAdd(IntValidLocations, unchecked((int)locations));
if (ammo != 0) bag.Ints.TryAdd(IntAmmoType, unchecked((int)ammo));
if ((hookFlags & 0x1) != 0) bag.Bools.TryAdd(BoolInscribable, true);
}
// The enchantment bitfields and armour levels that may follow carry no properties.
return true;
}
/// <summary>
/// Parses the property tables at the start of the player's PlayerDescription (game event
/// 0x13), starting at its event type: [type][property flags][weenie type], then the int,
/// int64, bool, double, string, data id and instance id tables (ACE
/// GameEventPlayerDescription.WriteEventBody order). Everything after them (positions,
/// attributes, skills, spells, options, inventory) is ignored. A table that runs past the
/// end stops the parse; the tables before it are kept (<paramref name="truncated"/>).
/// </summary>
public static bool TryParsePlayerDescription(ReadOnlySpan<byte> msg, out PropertyBag bag, out bool truncated)
{
bag = new PropertyBag();
truncated = false;
var r = new WireReader(msg);
if (!r.U32(out uint type) || type != EventPlayerDescription || !r.U32(out uint f) || !r.Skip(4))
return false;
bool ok = ((f & PdInt) == 0 || ReadIntTable(ref r, bag.Ints))
&& ((f & PdInt64) == 0 || ReadInt64Table(ref r, bag.Int64s))
&& ((f & PdBool) == 0 || ReadBoolTable(ref r, bag.Bools))
&& ((f & PdDouble) == 0 || ReadFloatTable(ref r, bag.Floats))
&& ((f & PdString) == 0 || ReadStringTable(ref r, bag.Strings))
&& ((f & PdDid) == 0 || ReadUIntTable(ref r, bag.DataIds))
&& ((f & PdIid) == 0 || ReadUIntTable(ref r, bag.InstanceIds));
truncated = !ok;
return true;
}
private static void AddFinite(Dictionary<uint, double> d, uint key, double v)
{
if (double.IsFinite(v)) d.TryAdd(key, v);
}
// PackableHashTable on the wire: u16 count, u16 bucket count, then count entries.
private static bool ReadHeader(ref WireReader r, out int count)
{
count = 0;
if (!r.U16(out ushort n) || !r.Skip(2)) return false;
count = n;
return true;
}
private static bool ReadIntTable(ref WireReader r, Dictionary<uint, int> d)
{
if (!ReadHeader(ref r, out int n) || !r.Has(n * 8)) return false;
for (int i = 0; i < n; i++) { r.U32(out uint k); r.I32(out int v); d[k] = v; }
return true;
}
private static bool ReadUIntTable(ref WireReader r, Dictionary<uint, uint> d)
{
if (!ReadHeader(ref r, out int n) || !r.Has(n * 8)) return false;
for (int i = 0; i < n; i++) { r.U32(out uint k); r.U32(out uint v); d[k] = v; }
return true;
}
private static bool ReadBoolTable(ref WireReader r, Dictionary<uint, bool> d)
{
if (!ReadHeader(ref r, out int n) || !r.Has(n * 8)) return false;
for (int i = 0; i < n; i++) { r.U32(out uint k); r.U32(out uint v); d[k] = v != 0; }
return true;
}
private static bool ReadInt64Table(ref WireReader r, Dictionary<uint, long> d)
{
if (!ReadHeader(ref r, out int n) || !r.Has(n * 12)) return false;
for (int i = 0; i < n; i++) { r.U32(out uint k); r.I64(out long v); d[k] = v; }
return true;
}
private static bool ReadFloatTable(ref WireReader r, Dictionary<uint, double> d)
{
if (!ReadHeader(ref r, out int n) || !r.Has(n * 12)) return false;
for (int i = 0; i < n; i++)
{
r.U32(out uint k);
r.F64(out double v);
if (double.IsFinite(v)) d[k] = v;
}
return true;
}
private static bool ReadStringTable(ref WireReader r, Dictionary<uint, string> d)
{
if (!ReadHeader(ref r, out int n)) return false;
for (int i = 0; i < n; i++)
{
if (!r.U32(out uint k) || !r.String16L(out string v)) return false;
d[k] = v;
}
return true;
}
/// <summary>Bounds-checked little-endian reader over one message.</summary>
private ref struct WireReader
{
private readonly ReadOnlySpan<byte> _s;
private int _pos;
public WireReader(ReadOnlySpan<byte> s) { _s = s; _pos = 0; }
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 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 I64(out long v)
{
v = 0;
if (!Has(8)) return false;
v = BinaryPrimitives.ReadInt64LittleEndian(_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>Pads to a 4-byte boundary from the message start (ACE Writer.Align()).</summary>
public bool Align4() => Skip((4 - (_pos & 3)) & 3);
/// <summary>
/// ACE WriteString16L: u16 length, the bytes (code page 1252), then zero padding so
/// that 2 + length is a multiple of 4.
/// </summary>
public bool String16L(out string v)
{
v = string.Empty;
if (!U16(out ushort len) || !Has(len)) return false;
v = Encoding.Latin1.GetString(_s.Slice(_pos, len));
_pos += len;
return Skip((4 - ((2 + len) & 3)) & 3);
}
}
}
/// <summary>
/// The PublicWeenieDesc fields every object carries from its CreateObject, filed under the
/// property ids they come from on the server (ACE WorldObject_Networking.SerializeCreateObject)
/// - the only properties the client holds for an object that was never identified. Offsets are
/// from the start of the client's PublicWeenieDesc (Chorizite Weenie.cs PublicWeenieDesc; the
/// engine copies the first <see cref="Size"/> bytes of it in its 10 Hz main-thread walk).
/// A zero field is "not sent" (the header flag was clear), so it answers nothing.
/// </summary>
internal static class PwdLayout
{
public const int Size = 176;
public const int Wcid = 12, Icon = 16, IconOverlay = 20, IconUnderlay = 24, Container = 28, Wielder = 32,
Priority = 36, ValidLocations = 40, Location = 44, ItemsCapacity = 48, ContainersCapacity = 52,
Type = 56, Value = 60, Useability = 64, UseRadius = 68, TargetType = 72, Effects = 76,
AmmoType = 80, CombatUse = 84, Structure = 88, MaxStructure = 92, StackSize = 96,
MaxStackSize = 100, Bitfield = 104, BlipColor = 108, RadarEnum = 112, Burden = 116,
SpellId = 120, HouseOwner = 124, HookType = 136, HookItemTypes = 140, Monarch = 144,
MaterialType = 148, Workmanship = 152, CooldownId = 156, CooldownDuration = 160, PetOwner = 168;
public static int IntOffset(uint stype) => stype switch
{
1 => Type, // ItemType
4 => Priority, // ClothingPriority
5 => Burden, // EncumbranceVal
6 => ItemsCapacity,
7 => ContainersCapacity,
9 => ValidLocations,
10 => Location, // CurrentWieldedLocation
11 => MaxStackSize,
12 => StackSize,
16 => Useability, // ItemUseable
18 => Effects, // UiEffects
19 => Value,
50 => AmmoType,
51 => CombatUse,
91 => MaxStructure,
92 => Structure,
94 => TargetType,
95 => BlipColor, // RadarBlipColor
131 => MaterialType,
133 => RadarEnum, // ShowableOnRadar
151 => HookType,
152 => HookItemTypes, // HookItemType
280 => CooldownId, // SharedCooldown
_ => -1,
};
public static int DataIdOffset(uint stype) => stype switch
{
8 => Icon,
28 => SpellId, // Spell
50 => IconOverlay,
52 => IconUnderlay,
_ => -1,
};
public static int InstanceIdOffset(uint stype) => stype switch
{
2 => Container,
3 => Wielder,
26 => Monarch,
32 => HouseOwner,
44 => PetOwner,
_ => -1,
};
public static bool TryGetInt(ReadOnlySpan<byte> pwd, uint stype, out int value)
{
value = 0;
int off = IntOffset(stype);
if (off < 0 || off + 4 > pwd.Length) return false;
value = BinaryPrimitives.ReadInt32LittleEndian(pwd.Slice(off));
return value != 0;
}
public static bool TryGetDataId(ReadOnlySpan<byte> pwd, uint stype, out uint value)
{
value = 0;
int off = DataIdOffset(stype);
if (off < 0 || off + 4 > pwd.Length) return false;
value = BinaryPrimitives.ReadUInt32LittleEndian(pwd.Slice(off));
return value != 0;
}
public static bool TryGetInstanceId(ReadOnlySpan<byte> pwd, uint stype, out uint value)
{
value = 0;
int off = InstanceIdOffset(stype);
if (off < 0 || off + 4 > pwd.Length) return false;
value = BinaryPrimitives.ReadUInt32LittleEndian(pwd.Slice(off));
return value != 0;
}
/// <summary>
/// UseRadius (54, f32), CooldownDuration (167, f64), and 280, the engine's long-standing
/// read of the item's workmanship (f32; UtilityBelt's SalvageWorkmanship 0xA000009 maps to it).
/// </summary>
public static bool TryGetFloat(ReadOnlySpan<byte> pwd, uint stype, out double value)
{
value = 0;
switch (stype)
{
case 54:
if (UseRadius + 4 > pwd.Length) return false;
value = BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(pwd.Slice(UseRadius)));
break;
case 167:
if (CooldownDuration + 8 > pwd.Length) return false;
value = BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64LittleEndian(pwd.Slice(CooldownDuration)));
break;
case 280:
if (Workmanship + 4 > pwd.Length) return false;
value = BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(pwd.Slice(Workmanship)));
break;
default:
return false;
}
return value != 0 && double.IsFinite(value);
}
}

View file

@ -85,6 +85,8 @@ internal static class RadarHooks
private static GmRadarUIDrawChildrenDelegate? _drawChildrenDetour;
private static IntPtr _gmRadarUIInstance;
// Logoff requested, logout not yet complete: the radar is being freed (see ChatHooks).
private static volatile bool _logoffInProgress;
private static IntPtr _uiElementSetVisibleAddress;
private static IntPtr _uiElementGetSurfaceBoxAddress;
private static bool _hookInstalled;
@ -205,7 +207,7 @@ internal static class RadarHooks
private static void DrawObjectsDetour(IntPtr thisPtr, IntPtr uiSurface)
{
RecursionGuard.Tick("RadarHooks.DrawObjects");
if (thisPtr != IntPtr.Zero)
if (thisPtr != IntPtr.Zero && !_logoffInProgress)
_gmRadarUIInstance = thisPtr;
int hit = Interlocked.Increment(ref _drawObjectsHits);
@ -231,7 +233,7 @@ internal static class RadarHooks
private static void DrawChildrenDetour(IntPtr thisPtr, IntPtr clipRect, IntPtr clipInside, IntPtr boxArray, IntPtr uiSurface)
{
RecursionGuard.Tick("RadarHooks.DrawChildren");
if (thisPtr != IntPtr.Zero)
if (thisPtr != IntPtr.Zero && !_logoffInProgress)
_gmRadarUIInstance = thisPtr;
int hit = Interlocked.Increment(ref _drawChildrenHits);
@ -292,9 +294,17 @@ internal static class RadarHooks
}
}
/// <summary>A logoff was requested: drop the radar before AC frees it (see ChatHooks.OnLogoffRequested).</summary>
public static void OnLogoffRequested()
{
_logoffInProgress = true;
_gmRadarUIInstance = IntPtr.Zero;
}
public static void ResetCachedInstance()
{
_gmRadarUIInstance = IntPtr.Zero;
_logoffInProgress = false;
_isHiddenAsserted = false;
}

View file

@ -0,0 +1,451 @@
// ============================================================================
// RynthCore.Engine - Compatibility/RetailVitalsHooks.cs
//
// "Hide retail vitals": hides AC's own health/stamina/mana bars, now that the
// RynthVision player plate and the RynthAi dashboard bars replace them. Same
// shape as ChatHooks / RadarHooks: capture the UIElement, then EndSceneHook
// calls TickHide every frame, which calls UIElement::SetVisible on it.
//
// What the bars are (Ghidra symbols + disassembly of the 4,841,472-byte client):
// gmVitalsUI (element class 0x10000009, 0x618 bytes) derives from
// UIElement_Field, so the UIElement is at offset 0; NoticeHandler sits at
// +0x5F8 and the QualityChangeHandler at +0x5FC. Two subclasses carry the
// bars on screen: gmFloatyVitalsUI (0x1000004D, stacked) and
// gmFloatySideVitalsUI (0x10000056, side by side). Both exist at once and AC
// shows one and hides the other with UIElement::SetVisible (vtable slot 0x18),
// per the "Side by side vitals" option (gmGamePlayUI::
// RecvNotice_PlayerOptionChanged, 0x004EAA30).
//
// Capture: gmVitalsUI::Update (0x004C0AB0), thiscall with no arguments. It is
// only reached through two thunks, OnQualityChanged (add ecx,-0x5FC) and
// RecvNotice_PlayerDescReceived (add ecx,-0x5F8), so its 'this' is always the
// primary (UIElement) pointer - unlike gmPowerbarUI's RecvNotice_* hooks, whose
// 'this' was the NoticeHandler sub-object and crashed SetVisible
// (PowerbarHooks.TickHide). It runs at login (player description) and on every
// health/stamina/mana change, for every gmVitalsUI-family instance.
// As a second check, an instance is only kept if its vtable's slot 0x18 is
// UIElement::SetVisible (directly or through a one-jmp thunk): exactly the
// function TickHide calls, and the one AC itself calls on these objects.
//
// Restore: TickHide hides only instances whose own visible flag is set, and
// remembers which ones it hid; with the option off it shows exactly those
// again, once. The hidden sibling (stacked vs side by side) is never shown.
//
// Freed instances: dropped when a logoff is requested (LogoffOriginProbe) and
// when the logout completes (PluginManager), as the chat and radar are; and
// every tick checks the object is still readable and still has the vtable it
// had when captured (MSVC destructors reset the vtable to the base class's,
// so a destroyed gmFloaty*VitalsUI fails the check).
//
// Installed from PowerbarHooks.Initialize (the "powerbar hooks" init step)
// because EntryPoint.cs is not edited for this. Both addresses go through
// HookResolver: pattern first, fallback VA second.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class RetailVitalsHooks
{
// Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth.
private const int GmVitalsUIUpdateFallbackVa = 0x004C0AB0;
private const int UIElementSetVisibleFallbackVa = 0x00462390;
// gmVitalsUI::Update() - 0xA4-byte frame, then InterfaceSystem::GetInstance for
// the PlayerDesc (push imm32 = its interface id). Unique in the text window
// (checked with tools\pe_pattern.py; the first 11 bytes alone are unique).
private static readonly byte?[] UpdatePattern =
[
0x81, 0xEC, 0xA4, 0x00, 0x00, 0x00, // sub esp, 0xA4
0x53, 0x55, 0x56, 0x57, // push ebx/ebp/esi/edi
0x8D, 0x44, 0x24, 0x10, 0x50, // lea eax,[esp+10h]; push eax
0x8B, 0xF1, // mov esi, ecx
0x8D, 0x4C, 0x24, 0x18, // lea ecx,[esp+18h]
0x68, null, null, null, null, // push imm32 (interface id)
0x33, 0xFF, 0x51, // xor edi,edi; push ecx
0x89, 0x7C, 0x24, 0x1C, // mov [esp+1Ch], edi
0xE8, null, null, null, null, // call rel32 (InterfaceSystem::GetInstance)
0x8B, 0xC8, // mov ecx, eax
0xE8, null, null, null, null // call rel32 (InterfaceSystem::GetClass)
];
// UIElement::SetVisible(bool) - the same pattern ChatHooks / RadarHooks /
// PowerbarHooks resolve; each consumer resolves it independently.
private static readonly byte?[] UIElementSetVisiblePattern =
[
0x51, 0x53, 0x56, 0x57,
0x8B, 0x3D, null, null, null, null, // mov edi, ds:[imm32]
0x8B, 0xF1,
0xE8, null, null, null, null, // call rel32
0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00,
0x88, 0x44, 0x24, 0x0F
];
// UIRegion's own "visible" flag: bit 1 of the dword at +0xA4. UIRegion::SetVisible
// writes it and UIElement::SetVisible reads it before and after; reading it here
// has no side effects (UIElement::IsVisible walks the parents and calls virtuals).
private const int RegionFlagsOffset = 0xA4;
private const int RegionVisibleBit = 0x2;
private const int SetVisibleVtableSlot = 0x18;
// Up to four gmVitalsUI-family objects at once (AC builds two: stacked + side by side).
private const int MaxInstances = 4;
private struct Slot
{
public IntPtr Instance;
public IntPtr Vtable; // the instance's vtable when captured
public bool HiddenByUs; // TickHide turned it off; show it again when the option goes off
}
// Written by UpdateDetour and read by TickHide, both on AC's main thread only.
private static readonly Slot[] Slots = new Slot[MaxInstances];
// Set when a logoff is requested, cleared when the logout completes: AC frees the
// vitals UI during the logoff and Update can still fire on a dying one, so nothing
// is captured in between (as ChatHooks).
private static volatile bool _logoffInProgress;
private static IntPtr _uiElementSetVisibleAddress;
private static IntPtr _originalUpdate;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
private static int _updateFires;
private static int _rejectLogs;
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
// ── The setting ───────────────────────────────────────────────────────────
private static readonly object SettingSync = new();
private static volatile bool _hide;
private static bool _settingLoaded;
private static string SettingPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "retail_ui.txt");
private const string HideVitalsKey = "HideRetailVitals";
/// <summary>
/// The "Hide retail vitals" option. Stored for the whole PC in
/// %LOCALAPPDATA%\RynthCore\retail_ui.txt ("HideRetailVitals=1"), beside the
/// engine's other in-client UI settings (panel_text_size.txt,
/// nameplate_settings.txt). Set from Settings > UI or /rc ui retailvitals.
/// Any thread: it only flips a flag and writes the file; TickHide applies it
/// on AC's main thread.
/// </summary>
public static bool HideRetailVitals
{
get { EnsureSettingLoaded(); return _hide; }
set
{
EnsureSettingLoaded();
lock (SettingSync)
{
if (_hide == value) return;
_hide = value;
SaveSetting();
}
RynthLog.Compat($"RetailVitalsHooks: Hide retail vitals -> {value} (installed={_hookInstalled}, captured={CountCaptured()}).");
}
}
public static void EnsureSettingLoaded()
{
if (_settingLoaded) return;
lock (SettingSync)
{
if (_settingLoaded) return;
_settingLoaded = true;
try
{
string path = SettingPath;
if (!File.Exists(path)) return;
foreach (string line in File.ReadAllLines(path))
{
int eq = line.IndexOf('=');
if (eq <= 0 || !line[..eq].Trim().Equals(HideVitalsKey, StringComparison.OrdinalIgnoreCase)) continue;
if (int.TryParse(line.AsSpan(eq + 1).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int v))
_hide = v != 0;
}
}
catch (Exception ex)
{
RynthLog.Compat($"RetailVitalsHooks: could not read {SettingPath}: {ex.GetType().Name}: {ex.Message}");
}
}
}
// Caller holds SettingSync. Keeps any other key=value lines in the file.
private static void SaveSetting()
{
try
{
string path = SettingPath;
var lines = new List<string>();
if (File.Exists(path))
{
foreach (string line in File.ReadAllLines(path))
{
int eq = line.IndexOf('=');
if (eq > 0 && line[..eq].Trim().Equals(HideVitalsKey, StringComparison.OrdinalIgnoreCase)) continue;
if (line.Trim().Length > 0) lines.Add(line);
}
}
lines.Add($"{HideVitalsKey}={(_hide ? 1 : 0)}");
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllLines(path, lines);
}
catch (Exception ex)
{
RynthLog.Compat($"RetailVitalsHooks: could not save {SettingPath}: {ex.GetType().Name}: {ex.Message}");
}
}
// ── Install ───────────────────────────────────────────────────────────────
public static void Initialize()
{
EnsureSettingLoaded();
if (_hookInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
var setVisible = HookResolver.Resolve(textSection, "RetailVitalsHooks.UIElement::SetVisible",
UIElementSetVisiblePattern, UIElementSetVisibleFallbackVa);
if (!setVisible.Success)
{
_statusMessage = $"UIElement::SetVisible resolve failed ({setVisible.Detail}).";
RynthLog.Compat($"RetailVitalsHooks: {_statusMessage} Not hooked.");
return;
}
var update = HookResolver.Resolve(textSection, "RetailVitalsHooks.gmVitalsUI::Update",
UpdatePattern, GmVitalsUIUpdateFallbackVa);
if (!update.Success)
{
_statusMessage = $"gmVitalsUI::Update resolve failed ({update.Detail}).";
RynthLog.Compat($"RetailVitalsHooks: {_statusMessage} Not hooked.");
return;
}
// Only hook through a pattern match: a guessed address for a hook target is
// worse than no "Hide retail vitals" (the fallback VA is logged as RISKY and
// refused here; the option then does nothing).
if (update.Source != HookResolver.ResolveSource.PatternScan)
{
_statusMessage = $"gmVitalsUI::Update only resolved by fallback VA ({update.Detail}); not hooked.";
RynthLog.Compat($"RetailVitalsHooks: {_statusMessage}");
return;
}
try
{
_uiElementSetVisibleAddress = setVisible.Address;
delegate* unmanaged[Thiscall]<IntPtr, void> detour = &UpdateDetour;
MinHook.Hook(update.Address, (IntPtr)detour, out _originalUpdate);
_hookInstalled = true;
_statusMessage = $"Hooked gmVitalsUI::Update @ 0x{update.Address.ToInt32():X8} ({update.Detail}); SetVisible @ 0x{setVisible.Address.ToInt32():X8}.";
RynthLog.Compat($"RetailVitalsHooks: {_statusMessage} Hide retail vitals={_hide}.");
}
catch (Exception ex)
{
_originalUpdate = IntPtr.Zero;
_statusMessage = ex.Message;
RynthLog.Compat($"RetailVitalsHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
// ── Capture (AC's main thread; must never throw into AC) ─────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static void UpdateDetour(IntPtr thisPtr)
{
try
{
RecursionGuard.Tick("RetailVitalsHooks.Update");
if (thisPtr != IntPtr.Zero && !_logoffInProgress && MainThreadGuard.IsOnMainThread())
Capture(thisPtr);
}
catch { }
((delegate* unmanaged[Thiscall]<IntPtr, void>)_originalUpdate)(thisPtr);
}
private static void Capture(IntPtr inst)
{
int free = -1;
for (int i = 0; i < Slots.Length; i++)
{
if (Slots[i].Instance == inst) return; // already have it
if (free < 0 && Slots[i].Instance == IntPtr.Zero) free = i;
}
if (++_updateFires <= 6)
RynthLog.Compat($"RetailVitalsHooks: Update fired on new instance 0x{inst.ToInt32():X8}.");
if (!ClientObjectHooks.IsReadableSpan(inst, RegionFlagsOffset + 4))
{
Reject(inst, "object not readable");
return;
}
IntPtr vtable = Marshal.ReadIntPtr(inst);
if (!IsSetVisibleSlot(vtable))
{
Reject(inst, $"vtable 0x{vtable.ToInt32():X8} slot 0x{SetVisibleVtableSlot:X} is not UIElement::SetVisible");
return;
}
if (free < 0)
{
// Full: reuse a slot whose object is gone. With none, keep the ones we have.
for (int i = 0; i < Slots.Length; i++)
{
if (!StillAlive(Slots[i])) { free = i; break; }
}
if (free < 0)
{
Reject(inst, "all slots hold live instances");
return;
}
}
Slots[free] = new Slot { Instance = inst, Vtable = vtable, HiddenByUs = false };
RynthLog.Compat($"RetailVitalsHooks: captured vitals element 0x{inst.ToInt32():X8} (vtable 0x{vtable.ToInt32():X8}, visible={IsOwnVisible(inst)}).");
}
private static void Reject(IntPtr inst, string why)
{
if (++_rejectLogs <= 8)
RynthLog.Compat($"RetailVitalsHooks: not capturing 0x{inst.ToInt32():X8}: {why}.");
}
/// <summary>
/// The vtable's SetVisible slot must be UIElement::SetVisible itself, or a
/// one-instruction "jmp rel32" thunk to it (incremental-link thunks: the
/// floaty classes' slot is 0x004CF950: jmp 0x00462390).
/// </summary>
private static bool IsSetVisibleSlot(IntPtr vtable)
{
IntPtr setVisible = _uiElementSetVisibleAddress;
if (setVisible == IntPtr.Zero) return false;
if (!ClientObjectHooks.IsReadableSpan(vtable, SetVisibleVtableSlot + 4)) return false;
IntPtr fn = Marshal.ReadIntPtr(vtable, SetVisibleVtableSlot);
if (fn == setVisible) return true;
if (!ClientObjectHooks.IsReadableSpan(fn, 5)) return false;
if (Marshal.ReadByte(fn) != 0xE9) return false;
int rel = Marshal.ReadInt32(fn, 1);
return unchecked(fn.ToInt32() + 5 + rel) == setVisible.ToInt32();
}
// ── Per-frame visibility (EndSceneHook, AC's main thread) ─────────────────
public static void TickHide()
{
if (!_hookInstalled) return;
if (!LoginLifecycleHooks.HasObservedLoginComplete) return;
if (_logoffInProgress) return;
if (!MainThreadGuard.IsOnMainThread()) return;
IntPtr setVisible = _uiElementSetVisibleAddress;
if (setVisible == IntPtr.Zero) return;
bool hide = _hide;
for (int i = 0; i < Slots.Length; i++)
{
IntPtr inst = Slots[i].Instance;
if (inst == IntPtr.Zero) continue;
if (!StillAlive(Slots[i]))
{
RynthLog.Compat($"RetailVitalsHooks: vitals element 0x{inst.ToInt32():X8} is gone (freed); dropped until it is captured again.");
Slots[i] = default;
continue;
}
bool visible = IsOwnVisible(inst);
if (hide)
{
// Only the one AC is showing; its hidden sibling stays AC's business.
if (visible)
{
try { ((delegate* unmanaged[Thiscall]<IntPtr, int, void>)setVisible)(inst, 0); }
catch { /* best-effort */ }
Slots[i].HiddenByUs = true;
}
}
else if (Slots[i].HiddenByUs)
{
if (!visible)
{
try { ((delegate* unmanaged[Thiscall]<IntPtr, int, void>)setVisible)(inst, 1); }
catch { /* best-effort */ }
}
Slots[i].HiddenByUs = false;
}
}
}
private static bool IsOwnVisible(IntPtr inst) =>
(Marshal.ReadInt32(inst, RegionFlagsOffset) & RegionVisibleBit) != 0;
/// <summary>
/// The object is still readable and still starts with the vtable it had when
/// captured. A destroyed gmVitalsUI-family object has had its vtable reset to
/// a base class's by the destructor chain (or its memory reused/decommitted).
/// </summary>
private static bool StillAlive(in Slot s)
{
if (s.Instance == IntPtr.Zero) return false;
if (!ClientObjectHooks.IsReadableSpan(s.Instance, RegionFlagsOffset + 4)) return false;
return Marshal.ReadIntPtr(s.Instance) == s.Vtable;
}
private static int CountCaptured()
{
int n = 0;
for (int i = 0; i < Slots.Length; i++)
if (Slots[i].Instance != IntPtr.Zero) n++;
return n;
}
/// <summary>One line for /rc ui retailvitals.</summary>
public static string Describe()
{
int hidden = 0;
for (int i = 0; i < Slots.Length; i++)
if (Slots[i].Instance != IntPtr.Zero && Slots[i].HiddenByUs) hidden++;
string state = !_hookInstalled
? $"not available ({_statusMessage})"
: $"{CountCaptured()} vitals element(s) captured, {hidden} hidden by RynthCore";
return $"Hide retail vitals is {(HideRetailVitals ? "ON" : "OFF")} - {state}.";
}
// ── Logout / relog ────────────────────────────────────────────────────────
/// <summary>
/// A logoff was requested (LogoffOriginProbe): drop the vitals elements now,
/// before AC frees them (see ChatHooks.OnLogoffRequested). AC's main thread.
/// </summary>
public static void OnLogoffRequested()
{
_logoffInProgress = true;
for (int i = 0; i < Slots.Length; i++) Slots[i] = default;
}
/// <summary>The logout completed (PluginManager's logout dispatch): the next login builds new ones.</summary>
public static void ResetCachedInstance()
{
for (int i = 0; i < Slots.Length; i++) Slots[i] = default;
_logoffInProgress = false;
}
}

View file

@ -1,4 +1,5 @@
using System;
using S = RynthCore.Engine.ImGuiBackend.Hud.MonsterHudSettings;
namespace RynthCore.Engine.Compatibility;
@ -17,12 +18,33 @@ namespace RynthCore.Engine.Compatibility;
/// button rides the bar itself, so it's unreachable once the bar is).
/// The launcher button writes this to dispatch.txt as the out-of-band
/// recovery.</item>
/// <item><c>/rc actionstate</c> (alias <c>/rc actions</c>) — read-only: the client's
/// item-action gates (pending item request, attacking flag, busy count,
/// target mode, combat state), see <see cref="ClientActionGates"/>.
/// <c>/rc unlockactions</c> (alias <c>/rc unlock</c>) opens those gates now.</item>
/// <item><c>/rc vitals</c> (alias <c>/rc hud</c>) — toggle the custom D3D9
/// Health/Stamina/Mana HUD on/off (persisted to engine.json).</item>
/// <item><c>/rc ui retailvitals [on|off|status]</c> — hide AC's own
/// health/stamina/mana bars (<see cref="RetailVitalsHooks"/>; saved for the
/// PC, also in Settings &gt; UI). Alone it reports the state.</item>
/// <item><c>/rc vendor [list|info|status|buy &lt;id|sel&gt; [n]|sell &lt;id|sel&gt; [id ...]]</c>
/// — read / trade with the open vendor through the engine's vendor
/// primitives (<see cref="VendorTrade"/>); a manual test hook for the
/// plugin API. Replies go to chat from the main-thread drain and to the log.</item>
/// <item><c>/rc chathold [on|off|status]</c> — incoming chat waits for the plugins'
/// verdict before AC prints it, so a line a plugin eats is kept out of AC's chat
/// window too (<see cref="ChatCallbackHooks"/>). On at every start; not saved.</item>
/// <item><c>/rv plates</c> (aliases <c>/rv nameplates</c>, <c>/rc plates</c>) — the
/// RynthVision nameplates and combat text: monster plates on|off, self, debuffs,
/// numbers, gains [on|off] (with their sub-switches), all on|off, all|engaged,
/// dist/max/scale/opacity/lift &lt;n&gt;, field toggles, reset, status
/// (<see cref="ImGuiBackend.Hud.MonsterHud"/>). "/rv plates" is caught here,
/// before plugin pre-dispatch, so the RynthVision plugin's own "/rv" handler
/// 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 mastery</c> — the Aelrynth mastery feed's state (<see cref="MasteryFeed"/>),
/// and ask the server for /mastery-data again.</item>
/// </list>
/// </summary>
internal static class RynthCoreChatCommands
@ -40,6 +62,21 @@ internal static class RynthCoreChatCommands
return false;
string trimmed = line.Trim();
// /rv plates ... : the RynthVision overlays live engine-side, so the engine answers
// before the plugin's "/rv" prefix handler would (it runs after this, on pre-dispatch).
if (trimmed.StartsWith("/rv ", StringComparison.OrdinalIgnoreCase))
{
string rv = trimmed.Substring(4).Trim();
if (IsVerb(rv, "plates", out string rvArgs) || IsVerb(rv, "nameplates", out rvArgs))
{
try { HandlePlatesCommand(rvArgs); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rv plates failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
return false;
}
if (!trimmed.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase))
return false;
@ -54,23 +91,128 @@ internal static class RynthCoreChatCommands
return true;
}
// /rc imgui [on|off|fonttest]
if (sub.Equals("imgui", StringComparison.OrdinalIgnoreCase)
|| sub.StartsWith("imgui ", StringComparison.OrdinalIgnoreCase))
{
try { HandleImGuiCommand(sub.Length > 5 ? sub.Substring(6).Trim() : string.Empty); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc imgui failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc ui list | /rc ui <Panel> avalonia|imgui|both
if (sub.Equals("ui", StringComparison.OrdinalIgnoreCase)
|| sub.StartsWith("ui ", StringComparison.OrdinalIgnoreCase))
{
try { HandleUiCommand(sub.Length > 2 ? sub.Substring(3).Trim() : string.Empty); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc ui failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc chathold [on|off|status]: lines a plugin eats stay out of AC's chat window too
if (IsVerb(sub, "chathold", out string holdArgs))
{
try { HandleChatHoldCommand(holdArgs); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc chathold failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc plates [on|off|all|engaged|dist N|max N|scale X|opacity X|lift X|names|hp|level|weak|distance|fade|reset|status]
if (IsVerb(sub, "plates", out string platesArgs) || IsVerb(sub, "nameplates", out platesArgs))
{
try { HandlePlatesCommand(platesArgs); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc plates failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc server [auto|aelrynth|other] : which server the engine thinks this is (testing override)
if (IsVerb(sub, "server", out string serverArgs))
{
try { HandleServerCommand(serverArgs); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc server failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc mastery : the Aelrynth mastery feed's state, and ask the server again
if (IsVerb(sub, "mastery", out _))
{
try { HandleMasteryCommand(); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc mastery 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))
{
if (vtankArgs.Equals("clear", StringComparison.OrdinalIgnoreCase))
Reply(VTankWatch.Clear() ? "VTank marked as not running; RynthAi's macro can start again." : "VTank was already marked as not running.");
Reply(VTankWatch.Describe());
return true;
}
switch (sub.ToLowerInvariant())
{
case "rl":
case "reload":
// Same as the bar's RL button. Signalled from a pool thread: the
// loader's reload shuts this engine down, and this handler runs
// inside AC's outgoing-chat hook.
RynthLog.Compat("RynthCoreChatCommands: /rc rl — engine reload requested.");
System.Threading.ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null);
return true;
case "inv":
case "inventory":
// The ImGui Inventory panel (open/close), like its bar button.
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.InventoryFace.Title))
Reply("The Inventory panel isn't available (the ImGui layer is off?).");
else
UI.PanelRouter.Toggle(ImGuiBackend.Panels.InventoryFace.Title);
return true;
case "sense":
// The ImGui Sense panel (open/close), like its bar button.
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SenseFace.Title))
Reply("The Sense panel isn't available (the ImGui layer is off?).");
else
UI.PanelRouter.Toggle(ImGuiBackend.Panels.SenseFace.Title);
return true;
case "resetbar":
case "barreset":
RynthLog.Compat("RynthCoreChatCommands: /rc resetbar — resetting overlay bar position.");
ImGuiBackend.RynthCoreShell.RequestExternalReset();
return true;
case "actionstate":
case "actions":
// Read-only: every client-side gate on item use/equip/move
// (ClientActionGates). Works while those are locked — chat still does.
try
{
foreach (string stateLine in ClientActionGates.DescribeLines())
Reply(stateLine);
}
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc actionstate failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
case "unlockactions":
case "unlock":
try
{
foreach (string unlockLine in ClientActionGates.RequestUnlock())
Reply(unlockLine);
}
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc unlockactions failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
case "vitals":
case "hud":
{
// Toggle the custom D3D9 vital HUD. Setter persists to engine.json
// so it survives relaunch. (No AC-chat echo — the AddTextToScroll
// path has a known AV risk; the HUD appearing/vanishing confirms.)
bool now = !Plugins.EngineSettings.DrawCustomVitalBars;
Plugins.EngineSettings.DrawCustomVitalBars = now;
RynthLog.Compat($"RynthCoreChatCommands: /rc vitals — custom vital HUD {(now ? "ON" : "OFF")}.");
// The old D3D9 vitals HUD is gone (2026-09-29): your vitals are the
// RynthVision player plate now.
Reply("The old vitals HUD was removed. Your health/stamina/mana bars are the RynthVision player plate: /rv plates self [on|off].");
return true;
}
@ -81,4 +223,404 @@ internal static class RynthCoreChatCommands
return true;
}
}
/// <summary>
/// /rc ui list, or /rc ui &lt;Panel&gt; avalonia|imgui|both: which face shows a
/// panel while it is docked in the client (UI.PanelRouter). Replies are
/// queued to chat, not written from inside this outgoing-chat hook.
/// </summary>
private static void HandleUiCommand(string args)
{
string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0 || parts[0].Equals("list", StringComparison.OrdinalIgnoreCase))
{
foreach (string line in UI.PanelRouter.Describe())
Reply(line);
return;
}
// /rc ui retailvitals [on|off]: hide AC's own health/stamina/mana bars
// (RetailVitalsHooks). Alone it reports; anything but on/off toggles.
if (parts[0].Equals("retailvitals", StringComparison.OrdinalIgnoreCase))
{
if (parts.Length >= 2 && parts[1].Equals("status", StringComparison.OrdinalIgnoreCase))
{
Reply(RetailVitalsHooks.Describe());
return;
}
if (parts.Length >= 2)
RetailVitalsHooks.HideRetailVitals = Flag(parts[1], RetailVitalsHooks.HideRetailVitals);
Reply(RetailVitalsHooks.Describe());
return;
}
// /rc ui open|close|popout|redock|snap <Panel>: drive a panel by name (tests,
// dispatch.txt). Names may have spaces ("Monster Detail").
string verb = parts[0].ToLowerInvariant();
if (verb is "open" or "close" or "popout" or "redock" or "snap" && parts.Length >= 2)
{
// "Monsters" (the retired basic panel) is the Damage panel now.
string title = UI.PanelRouter.Canonical(string.Join(' ', parts, 1, parts.Length - 1));
if (title.Equals("bar", StringComparison.OrdinalIgnoreCase) && verb is "popout" or "redock")
{
ImGuiBackend.ImGuiBar.SetPoppedOut(verb == "popout");
Reply($"/rc ui {verb} bar: requested.");
return;
}
if (title.Equals("bar", StringComparison.OrdinalIgnoreCase) && verb == "snap") title = "__bar";
else if (!ImGuiBackend.ImGuiPanelHost.HasFace(title)) { Reply($"No ImGui panel named '{title}'."); return; }
switch (verb)
{
case "open": ImGuiBackend.ImGuiPanelHost.Open(title); break;
case "close": ImGuiBackend.ImGuiPanelHost.Close(title); break;
case "popout": ImGuiBackend.ImGuiPanelHost.PopOut(title); break;
case "redock": ImGuiBackend.ImGuiPanelHost.Redock(title); break;
case "snap":
ImGuiBackend.Win32Backend.PostToGameThread(() =>
RynthLog.UI($"/rc ui snap {title}: " + (ImGuiBackend.ImGuiPopOuts.RequestSnapshot(title) ?? "not popped out")));
break;
}
Reply($"/rc ui {verb} {title}: requested.");
return;
}
if (parts.Length != 2 || !UI.PanelFaceStore.TryParseFace(parts[1], out UI.PanelFace face))
{
Reply("Usage: /rc ui list | /rc ui <Panel|bar> avalonia|imgui|both | /rc ui open|close|popout|redock|snap <Panel> | /rc ui retailvitals [on|off]");
return;
}
Reply(UI.PanelRouter.SetDockedFace(parts[0], face));
}
/// <summary>
/// /rc imgui on|off switches the engine's in-client ImGui layer live and
/// saves it to engine.json; /rc imgui fonttest toggles the font/theme test
/// window; /rc imgui alone reports the state.
/// </summary>
private static void HandleImGuiCommand(string arg)
{
switch (arg.ToLowerInvariant())
{
case "on":
Plugins.EngineSettings.EnableImGuiBackend = true;
ImGuiBackend.ImGuiBar.ApplyFace();
Reply("ImGui layer ON (saved). The self-test result is in the log (ImGuiSelfTest:). Panels: /rc ui list.");
return;
case "off":
Plugins.EngineSettings.EnableImGuiBackend = false;
ImGuiBackend.Win32Backend.ClearCaptureFlags();
ImGuiBackend.Win32Backend.DiscardQueuedInput();
ImGuiBackend.ImGuiBar.ApplyFace(); // the Avalonia bar comes back
Reply("ImGui layer OFF (saved).");
return;
case "fonttest":
ImGuiBackend.ImGuiFontTest.Enabled = !ImGuiBackend.ImGuiFontTest.Enabled;
Reply($"ImGui font test window {(ImGuiBackend.ImGuiFontTest.Enabled ? "shown" : "hidden")}"
+ (Plugins.EngineSettings.EnableImGuiBackend ? "." : " (the ImGui layer is off: /rc imgui on)."));
return;
case "diag":
foreach (string line in ImGuiBackend.EngineFrameController.DescribeState())
RynthLog.Info("ImGuiDiag: " + line);
foreach (string line in ImGuiBackend.ImGuiPanelHost.DescribeFaces())
RynthLog.Info("ImGuiDiag: " + line);
foreach (string line in UI.ScriptWindows.ScriptWindowRegistry.Describe())
RynthLog.Info("ImGuiDiag: " + line);
RynthLog.Info($"ImGuiDiag: bar visible={ImGuiBackend.ImGuiBar.Visible} face={UI.PanelFaceStore.FaceName(ImGuiBackend.ImGuiBar.ResolveFace())} avaloniaBarSuppressed={UI.AvaloniaOverlay.DockedBarSuppressed}");
Reply("ImGui diagnostics written to the RynthCore log (ImGuiDiag:).");
return;
case "":
Reply($"ImGui layer is {(Plugins.EngineSettings.EnableImGuiBackend ? "ON" : "OFF")}. Usage: /rc imgui on|off|fonttest|diag");
return;
default:
Reply("Usage: /rc imgui on|off|fonttest|diag");
return;
}
}
/// <summary>
/// /rc chathold on|off|status: incoming chat waits for the plugins before AC prints it,
/// so a line a plugin eats (RynthAi's Meta Manager eats the reply to its own /myquests)
/// is not shown in AC's chat window either (ChatCallbackHooks, IncomingChatHold.cs).
/// On at every start; off prints every line at once, as before, and plugins can then
/// only keep a line out of RynthChat.
/// </summary>
private static void HandleChatHoldCommand(string arg)
{
switch (arg.ToLowerInvariant())
{
case "on":
ChatCallbackHooks.SetHoldEnabled(true);
break;
case "off":
ChatCallbackHooks.SetHoldEnabled(false);
break;
case "":
case "status":
break;
default:
Reply("Usage: /rc chathold [on|off|status]");
return;
}
Reply(ChatCallbackHooks.HoldStatusText());
}
/// <summary>"verb" or "verb args..." (case-insensitive); args trimmed.</summary>
/// <summary>
/// /rc server: the detection verdict and its signals. "aelrynth" / "other" force it
/// for this session (to test the Aelrynth-only features anywhere, or to see a
/// non-Aelrynth client on Aelrynth); "auto" goes back to detecting. Never saved.
/// </summary>
private static void HandleServerCommand(string args)
{
switch (args.Trim().ToLowerInvariant())
{
case "aelrynth": case "on": ServerInfo.Override = ServerInfo.Mode.ForceAelrynth; break;
case "other": case "off": ServerInfo.Override = ServerInfo.Mode.ForceOther; break;
case "auto": ServerInfo.Override = ServerInfo.Mode.Auto; break;
case "": break;
default:
Reply("Usage: /rc server [auto|aelrynth|other]");
return;
}
ServerVerdict v = ServerInfo.Current;
Reply($"Server: {(v.IsAelrynth ? (v.IsStaging ? "Aelrynth (staging)" : "Aelrynth") : "not Aelrynth")} - {v.Reason}.");
Reply($"Signals: host {ServerInfo.HostDescription}; world name {AccountHooks.AnnouncedWorldName ?? "(not announced)"}; "
+ $"override {ServerInfo.Override}.");
Reply($"Titles (plugin API v75): {CharacterTitles.Describe()}.");
}
private static void HandleMasteryCommand()
{
if (!ServerInfo.IsAelrynth)
{
Reply("Mastery: not on Aelrynth, so nothing is asked (/rc server for why).");
return;
}
MasterySnapshot? s = MasteryFeed.Snapshot;
Reply($"Mastery: {MasteryFeed.Status}"
+ (s != null ? $"; last reply {(Environment.TickCount64 - s.ReceivedMs) / 1000}s ago" : "; no reply this login")
+ (MasteryFeed.Unsupported ? "" : ". Asking again."));
MasteryFeed.RequestRefresh();
}
private static bool IsVerb(string sub, string verb, out string args)
{
args = string.Empty;
if (sub.Equals(verb, StringComparison.OrdinalIgnoreCase)) return true;
if (!sub.StartsWith(verb + " ", StringComparison.OrdinalIgnoreCase)) return false;
args = sub.Substring(verb.Length + 1).Trim();
return true;
}
/// <summary>
/// /rv plates (alias /rc plates): the RynthVision nameplates and combat text
/// (ImGui/MonsterHud). Alone it toggles the monster plates; on|off, all on|off,
/// self|debuffs|others|numbers|gains [sub] [on|off], all|engaged, dist|max|scale|
/// opacity|lift &lt;n&gt;, names|hp|level|weak|distance|fade|click [on|off], reset, status.
/// Every change is saved.
/// </summary>
private static void HandlePlatesCommand(string args)
{
const string usage = "Usage: /rv plates [on|off] | all on|off | self [numbers|name|firstperson] [on|off] | " +
"debuffs [on|off] | others [on|off] | numbers [dealt|taken|heals|kills] [on|off] | " +
"gains [xp|lum|radiance] [on|off] | npcs [on|off] | npcs dist <yd>|max <n> | players [on|off] | all|engaged |dist <yd>|max <n>|scale <x>|opacity <x>|lift <m> | " +
"names|hp|level|weak|distance|fade|click [on|off] | reset | status | test";
if (!ImGuiBackend.Hud.HudFeed.VisionInstalled)
{
Reply("RynthVision isn't in the plugin list (launcher, Plugins tab), so its nameplates and combat text are off.");
return;
}
if (!ImGuiBackend.Hud.MonsterHudSettings.Loaded)
{
ImGuiBackend.Hud.MonsterHudSettings.EnsureLoadQueued();
Reply("Nameplate settings are still loading - try again in a moment.");
return;
}
string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : "";
string? value = parts.Length > 1 ? parts[1] : null;
string? sub = value != null && !IsOnOff(value) ? value.ToLowerInvariant() : null;
string? subValue = sub != null ? (parts.Length > 2 ? parts[2] : null) : value;
bool save = true;
switch (verb)
{
case "":
S.Enabled = !S.Enabled;
break;
case "on": S.Enabled = true; break;
case "off": S.Enabled = false; break;
case "all":
// "all on|off": every overlay; "all" alone: plates for all monsters (the filter).
if (value != null && IsOnOff(value)) S.SetAll(Flag(value, true));
else S.Filter = ImGuiBackend.Hud.PlateFilter.All;
break;
case "engaged":
case "combat":
case "target":
S.Filter = ImGuiBackend.Hud.PlateFilter.Engaged; break;
case "self":
case "me":
switch (sub)
{
case null: S.SelfPlate = Flag(subValue, S.SelfPlate); break;
case "numbers": case "text": S.SelfNumbers = Flag(subValue, S.SelfNumbers); break;
case "name": S.SelfName = Flag(subValue, S.SelfName); break;
case "firstperson": case "fp": S.SelfHideFirstPerson = Flag(subValue, S.SelfHideFirstPerson); break;
case "position": case "pos":
{
string? w = subValue?.ToLowerInvariant();
ImGuiBackend.Hud.SelfPlatePosition? p = w switch
{
"above" or "over" or "top" or "head" => ImGuiBackend.Hud.SelfPlatePosition.Above,
"below" or "under" or "feet" or "bottom" => ImGuiBackend.Hud.SelfPlatePosition.Below,
"left" => ImGuiBackend.Hud.SelfPlatePosition.Left,
"right" => ImGuiBackend.Hud.SelfPlatePosition.Right,
_ => null,
};
if (p == null) { Reply("usage: /rv plates self position above|below|left|right"); return; }
S.SelfPosition = p.Value;
break;
}
default: Reply(usage); return;
}
break;
case "click":
case "clickselect":
S.ClickToSelect = Flag(value, S.ClickToSelect); break;
case "onscreen":
case "keeponscreen":
S.KeepOnScreen = Flag(value, S.KeepOnScreen); break;
case "debuffs":
case "debuff":
S.ShowDebuffs = Flag(value, S.ShowDebuffs); break;
case "others":
S.ShowOthersDebuff = Flag(value, S.ShowOthersDebuff); break;
case "numbers":
case "juice":
switch (sub)
{
case null: S.Numbers = Flag(subValue, S.Numbers); break;
case "dealt": case "damage": S.NumDealt = Flag(subValue, S.NumDealt); break;
case "taken": S.NumTaken = Flag(subValue, S.NumTaken); break;
case "heals": case "heal": S.NumHeals = Flag(subValue, S.NumHeals); break;
case "kills": case "kill": case "burst": S.NumKills = Flag(subValue, S.NumKills); break;
case "restores": case "stamina": case "mana": S.NumRestores = Flag(subValue, S.NumRestores); break;
case "size":
if (!TryNum(subValue, out float nsz)) { Reply("usage: /rv plates numbers size 0.5-2.5"); return; }
S.NumSize = Math.Clamp(nsz, S.MinNumSize, S.MaxNumSize); break;
case "time": case "duration":
if (!TryNum(subValue, out float ntm)) { Reply("usage: /rv plates numbers time 0.5-3"); return; }
S.NumTime = Math.Clamp(ntm, S.MinNumTime, S.MaxNumTime); break;
default: Reply(usage); return;
}
break;
case "gains":
case "gain":
switch (sub)
{
case "size":
if (!TryNum(subValue, out float gsz)) { Reply("usage: /rv plates gains size 0.5-2.5"); return; }
S.GainSize = Math.Clamp(gsz, S.MinNumSize, S.MaxNumSize); break;
case "time": case "duration":
if (!TryNum(subValue, out float gtm)) { Reply("usage: /rv plates gains time 0.5-3"); return; }
S.GainTime = Math.Clamp(gtm, S.MinNumTime, S.MaxNumTime); break;
case null: S.Gains = Flag(subValue, S.Gains); break;
case "xp": S.GainXp = Flag(subValue, S.GainXp); break;
case "lum": case "luminance": S.GainLum = Flag(subValue, S.GainLum); break;
case "radiance": S.GainRadiance = Flag(subValue, S.GainRadiance); break;
default: Reply(usage); return;
}
break;
case "dist":
case "range":
if (!TryNum(value, out float d)) { Reply(usage); return; }
S.MaxDistance = Math.Clamp(d, S.MinDistance, S.MaxDistanceLimit);
break;
case "max":
if (!TryNum(value, out float n)) { Reply(usage); return; }
S.MaxPlates = Math.Clamp((int)Math.Round(n), S.MinPlates, S.MaxPlatesLimit);
break;
case "scale":
if (!TryNum(value, out float sc)) { Reply(usage); return; }
S.Scale = Math.Clamp(sc, S.MinScale, S.MaxScale);
break;
case "opacity":
case "alpha":
if (!TryNum(value, out float o)) { Reply(usage); return; }
if (o > 1f) o /= 100f; // "opacity 80" means 80 %
S.Opacity = Math.Clamp(o, S.MinOpacity, S.MaxOpacity);
break;
case "lift":
case "height":
if (!TryNum(value, out float h)) { Reply(usage); return; }
S.HeightLift = Math.Clamp(h, S.MinLift, S.MaxLift);
break;
case "npcs":
case "npc":
switch (sub)
{
case null: S.NpcNames = Flag(subValue, S.NpcNames); break;
case "dist": case "range":
if (!TryNum(subValue, out float nd)) { Reply("usage: /rv plates npcs dist 5-80"); return; }
S.NpcMaxDistance = Math.Clamp(nd, S.MinNpcDistance, S.MaxNpcDistanceLimit); break;
case "max":
if (!TryNum(subValue, out float nm)) { Reply("usage: /rv plates npcs max 1-40"); return; }
S.MaxNpcLabels = Math.Clamp((int)Math.Round(nm), S.MinNpcLabels, S.MaxNpcLabelsLimit); break;
default: Reply(usage); return;
}
break;
case "players":
S.PlayerNames = Flag(value, S.PlayerNames); break;
case "names": S.ShowNames = Flag(value, S.ShowNames); break;
case "hp": S.ShowHpNumbers = Flag(value, S.ShowHpNumbers); break;
case "level": S.ShowLevel = Flag(value, S.ShowLevel); break;
case "weak": S.ShowWeakness = Flag(value, S.ShowWeakness); break;
case "distance": S.ShowDistance = Flag(value, S.ShowDistance); break;
case "fade": S.FadeWithDistance = Flag(value, S.FadeWithDistance); break;
case "reset":
S.ResetToDefaults();
save = false;
break;
case "status":
case "diag":
foreach (string line in ImGuiBackend.Hud.MonsterHud.DescribeLines())
Reply(line);
return;
case "test":
ImGuiBackend.Hud.CombatText.SpawnTest();
Reply("Sample combat numbers, a kill burst and gains spawned around you.");
return;
default:
Reply(usage);
return;
}
if (save) S.Save();
Reply(S.Describe()
+ (Plugins.EngineSettings.EnableImGuiBackend ? "" : " (The ImGui layer is off, so nothing draws: /rc imgui on.)"));
}
private static bool IsOnOff(string v) =>
v.Equals("on", StringComparison.OrdinalIgnoreCase) || v.Equals("off", StringComparison.OrdinalIgnoreCase) ||
v == "1" || v == "0" || v.Equals("true", StringComparison.OrdinalIgnoreCase) || v.Equals("false", StringComparison.OrdinalIgnoreCase) ||
v.Equals("toggle", StringComparison.OrdinalIgnoreCase);
private static bool TryNum(string? s, out float v)
{
v = 0;
return s != null && float.TryParse(s, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out v);
}
/// <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 };
private static void Reply(string text)
{
RynthLog.Compat($"RynthCoreChatCommands: {text}");
AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, 1);
}
}

View file

@ -0,0 +1,163 @@
// ============================================================================
// RynthCore.Engine - Compatibility/ServerInfo.cs
//
// Which server this client is on: ServerInfo.IsAelrynth is the one flag the
// Aelrynth-only features (the Skills panel's mastery) check before they show
// anything or send a server command another server wouldn't know.
//
// Signals (combined by ServerDetect.Decide, AelrynthWire.cs):
// - the launch command line's -h host[:port] / -p port (read once);
// - the world name the server announced at login (AccountHooks, the
// SendNotice_WorldName hook; not the launcher's own profile name);
// - the Bank mod's custom player properties 9101-9103 (PropertyCaches).
// Unknown means not Aelrynth. "/rc server aelrynth|other|auto" overrides it
// for this session (testing), never saved.
//
// Threads: any. Re-evaluated at most once a second; each read in between is a
// volatile load and a compare. Never touches AC (dictionary reads only).
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class ServerInfo
{
public enum Mode { Auto, ForceAelrynth, ForceOther }
private const int RefreshMs = 1000;
private static volatile ServerVerdict _verdict = ServerVerdict.Unknown;
private static long _nextRefreshMs;
private static int _mode; // Mode
private static int _hostRead;
private static readonly object HostLock = new();
private static string _host = "";
private static int _port;
private static ServerHostKind _hostKind = ServerHostKind.Unknown;
private static volatile bool _bankSeen; // sticky: the properties only ever appear on Aelrynth
private static volatile bool _lastAelrynth;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr GetCommandLineW();
/// <summary>True when the client is on Aelrynth (live, staging or a dev copy) - or the override says so. Any thread.</summary>
public static bool IsAelrynth => Current.IsAelrynth;
/// <summary>Aelrynth's staging world (port 9030 / "Staging" world name). Any thread.</summary>
public static bool IsStaging => Current.IsStaging;
public static Mode Override
{
get => (Mode)Volatile.Read(ref _mode);
set
{
Volatile.Write(ref _mode, (int)value);
Volatile.Write(ref _nextRefreshMs, 0);
}
}
/// <summary>The current verdict (re-evaluated at most once a second). Any thread.</summary>
public static ServerVerdict Current
{
get
{
long now = Environment.TickCount64;
if (now >= Volatile.Read(ref _nextRefreshMs))
{
Volatile.Write(ref _nextRefreshMs, now + RefreshMs);
Refresh();
}
return _verdict;
}
}
/// <summary>The connect host and port from the command line, for /rc server. Any thread.</summary>
public static string HostDescription
{
get
{
ReadHostOnce();
return _host.Length == 0 ? "(none)" : _port > 0 ? $"{_host}:{_port}" : _host;
}
}
private static void Refresh()
{
try
{
ReadHostOnce();
if (!_bankSeen)
_bankSeen = HasBankProperties();
ServerVerdict v = Override switch
{
Mode.ForceAelrynth => new ServerVerdict { IsAelrynth = true, Reason = "forced on with /rc server aelrynth (testing)" },
Mode.ForceOther => new ServerVerdict { Reason = "forced off with /rc server other (testing)" },
_ => ServerDetect.Decide(_hostKind, _host, _port, AccountHooks.AnnouncedWorldName, _bankSeen),
};
_verdict = v;
if (v.IsAelrynth != _lastAelrynth)
{
_lastAelrynth = v.IsAelrynth;
RynthLog.Compat($"ServerInfo: {v.Reason}");
}
}
catch (Exception ex)
{
RynthLog.Compat($"ServerInfo: refresh failed - {ex.GetType().Name}: {ex.Message}");
}
}
private static void ReadHostOnce()
{
if (Volatile.Read(ref _hostRead) != 0)
return;
lock (HostLock)
{
if (_hostRead != 0)
return;
ReadHost();
Volatile.Write(ref _hostRead, 1);
}
}
private static void ReadHost()
{
try
{
IntPtr p = GetCommandLineW();
string? cmd = p == IntPtr.Zero ? null : Marshal.PtrToStringUni(p);
// Only -h / -p are kept: the command line also carries the account password.
if (ServerDetect.TryParseLaunchHost(cmd, out string host, out int port))
{
_host = host;
_port = port;
}
_hostKind = ServerDetect.ClassifyHost(_host);
}
catch
{
_hostKind = ServerHostKind.Unknown;
}
}
private static bool HasBankProperties()
{
uint me = ClientHelperHooks.GetPlayerId();
if (me == 0) return false;
return PropertyCaches.TryGetInt64(me, ServerDetect.RadianceEarnedProperty, out _)
|| PropertyCaches.TryGetInt64(me, ServerDetect.LuminanceBankedProperty, out _)
|| PropertyCaches.TryGetInt64(me, ServerDetect.LuminanceDrawnProperty, out _);
}
/// <summary>The Bank mod's "Radiance earned this session" (9101), when the server sends it. Any thread.</summary>
public static bool TryGetRadianceEarned(out long value)
{
value = 0;
uint me = ClientHelperHooks.GetPlayerId();
return me != 0 && PropertyCaches.TryGetInt64(me, ServerDetect.RadianceEarnedProperty, out value);
}
}

View file

@ -93,6 +93,7 @@ internal static class SmartBoxHooks
{
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, uint> pGeDetour = &DispatchGameEventDetour;
MinHook.Hook(geAddr, (IntPtr)pGeDetour, out _originalDispatchGameEventPtr);
_gameEventHookInstalled = true;
RynthLog.Verbose($"Compat: game-event hook ready @ 0x{geAddr.ToInt32():X8}");
}
else RynthLog.Compat("Compat: game-event pattern matched already-hooked address.");
@ -164,6 +165,7 @@ internal static class SmartBoxHooks
RecursionGuard.Tick("SmartBoxHooks.DispatchGameEvent");
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, uint>)_originalDispatchGameEventPtr;
EnchantmentChange? enchantment = null;
try
{
// Reject undersized payloads instead of clamping up: an inflated
@ -173,17 +175,84 @@ internal static class SmartBoxHooks
{
uint eventType = unchecked((uint)Marshal.ReadInt32(data));
int len = size > 0x4000 ? 0x4000 : size;
// Property messages (2026-09-30): the identify reply, PlayerDescription and every
// UpdateProperty* message pass through here, from their type on. `size` is the
// real length (the function bounds itself with data+size), so the two large ones
// get all of it (PlayerDescription runs to ~29 KB) instead of the 16 KB clamp.
ParsePropertyMessage(eventType, data, size > 0x10000 ? 0x10000 : size);
ParseGameEvent(eventType, data, (uint)len);
if ((eventType >= 0x02C2 && eventType <= 0x02C8) || eventType == 0x0312)
enchantment = CaptureEnchantmentEvent(eventType, data, (uint)len);
}
}
catch { }
return pOriginal(thisPtr, data, size);
uint status = pOriginal(thisPtr, data, size);
// Enchantment events are queued AFTER the original ran: by then AC's
// CEnchantmentRegistry holds the change (ClientMagicSystem::Handle_Magic__*
// update it synchronously), so a plugin that re-reads the registry when the
// event reaches it on the pump sees the new state. Queue only, never call
// plugins from here (AC's main thread).
if (enchantment != null)
{
try { FlushEnchantmentEvent(enchantment); } catch { }
}
return status;
}
// spike/decal-bridge: set while a game event from the Decal bridge is parsed on the
// plugin pump thread, where the main-thread-only live reads must not run.
[ThreadStatic] private static bool _fromBridge;
/// <summary>
/// spike/decal-bridge: a game event taken from Decal's raw server message instead of
/// the ProcessNetBlobData hook. <paramref name="data"/> is [eventType][payload], as the
/// hook sees it. Runs on the pump thread after AC has already applied the event, so an
/// enchantment is queued at once, and a purge (no ids on the wire) can't be diffed.
/// </summary>
internal static unsafe void ProcessBridgeGameEvent(byte* data, int size)
{
if (data == null || size < 4)
return;
uint eventType = *(uint*)data;
int len = size > 0x4000 ? 0x4000 : size;
_fromBridge = true;
try
{
ParseGameEvent(eventType, (IntPtr)data, (uint)len);
if ((eventType >= 0x02C2 && eventType <= 0x02C8) && eventType != 0x02C6)
{
EnchantmentChange? c = CaptureEnchantmentEvent(eventType, (IntPtr)data, (uint)len);
if (c != null)
FlushEnchantmentEvent(c);
}
}
catch { }
finally { _fromBridge = false; }
}
private static int _geEventLogCount;
private static int _hpReadLogCount;
// Feeds the property caches (AppraisalHooks, PropertyUpdateHooks) from the messages that
// carry properties. Parsing only: nothing here touches AC state. Each parser is
// bounds-checked against `size` and ignores a message it can't read.
private static void ParsePropertyMessage(uint eventType, IntPtr data, int size)
{
try
{
if (eventType == PropertyWire.EventIdentifyObjectResponse)
AppraisalHooks.OnIdentifyWire(data, size);
else if (eventType == PropertyWire.EventPlayerDescription)
PropertyUpdateHooks.OnPlayerDescriptionWire(data, size);
else if (PropertyWire.IsPropertyUpdateOpcode(eventType))
PropertyUpdateHooks.OnUpdateWire(data, size);
}
catch { }
}
// Parse an inbound GameEvent for the events combat cares about. `data` points
// at the event blob: inner type @ +0, payload @ +4. `size` bounds reads.
private static void ParseGameEvent(uint eventType, IntPtr data, uint size)
@ -199,6 +268,20 @@ internal static class SmartBoxHooks
RynthLog.Compat($"GE evt=0x{eventType:X4} len={size} p=[{d1:X8} {d2:X8} {d3:X8}]");
}
// v75: the character's titles (0x0029 at login, 0x002B per new title; see CharacterTitles).
if (CharacterTitles.IsTitleEvent(eventType))
{
try { CharacterTitles.OnGameEvent(eventType, data, size, ClientHelperHooks.GetPlayerId()); } catch { }
return;
}
// v72: the player-to-player trade events (0x01FD-0x0208; see PlayerTrade).
if (PlayerTrade.IsTradeEvent(eventType))
{
PlayerTrade.OnGameEvent(eventType, data, size);
return;
}
switch (eventType)
{
case 0x01C0: // UpdateHealth: [targetId u32][ratio f32]
@ -213,7 +296,8 @@ internal static class SmartBoxHooks
// The plugin QueryHealth()s its combat target on lock, which is
// what makes this fire for the mobs it's actually fighting.
// Falls back to the wire-parsed appraisal cache if the read fails.
bool gotReal = ClientObjectHooks.TryReadCreatureMaxHealth(targetId, out uint realMax) && realMax > 0;
uint realMax = 0;
bool gotReal = !_fromBridge && ClientObjectHooks.TryReadCreatureMaxHealth(targetId, out realMax) && realMax > 0;
if (gotReal)
maxHealth = realMax;
else if (ObjectQualityCache.TryGetCreatureVitals(targetId, out CreatureVitals exact) && exact.MaxHealth > 0)
@ -245,6 +329,7 @@ internal static class SmartBoxHooks
RynthLog.Compat($"Combat: kill notify '{msg}'");
}
PluginManager.QueueKillNotification(msg);
ImGuiBackend.Hud.HudFeed.OnKillMessage(msg); // kill burst
}
break;
}
@ -259,6 +344,9 @@ internal static class SmartBoxHooks
{
uint err = size >= 8 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))) : 0;
int seq = System.Threading.Interlocked.Increment(ref _useDoneSeq);
// 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)
{
_useDoneLogCount++;
@ -266,6 +354,33 @@ internal static class SmartBoxHooks
}
break;
}
case 0x028A: // WeenieError: [errorType u32]. "Your spell fizzled",
// "You don't know that spell", ... — AC's own refusal lines.
// A cast that fizzles ends with this AND a UseDone(None).
if (size >= 8)
{
uint code = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4)));
RecordWeenieError(eventType, code, 0);
if (code == 0x0529) // TradeComplete (v72 trade state)
PlayerTrade.OnTradeComplete();
}
break;
case 0x028B: // WeenieErrorWithString: [errorType u32][string16 text]
if (size >= 8)
RecordWeenieError(eventType, unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))), 0);
break;
case 0x00A0: // InventoryServerSaveFailed: [objectId u32][errorType u32] —
// the server refused an inventory change (wield, move, ...).
// Layout from UIQueueManager::ProcessNetBlobData's inline case
// @0x0055C012 (edx=[p], esi=[p+4]) and ACE's writer.
if (size >= 12)
RecordWeenieError(eventType,
unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 8))),
unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))));
break;
}
}
@ -273,8 +388,225 @@ internal static class SmartBoxHooks
// at cast time and re-reads it to detect the server finishing the cast.
private static int _useDoneSeq;
private static int _useDoneLogCount;
// (seq << 32) | errorType of the most recent UseDone; 0 until the first one.
private static long _useDoneLast;
private static bool _gameEventHookInstalled;
/// <summary>True once the game-event detour (UIQueueManager::ProcessNetBlobData) is installed.</summary>
public static bool IsGameEventHookInstalled => _gameEventHookInstalled;
public static int GetUseDoneSeq() => System.Threading.Volatile.Read(ref _useDoneSeq);
/// <summary>
/// v70: the most recent UseDone's sequence number (as GetUseDoneSeq counts them) and its
/// WeenieError code (0 = the action completed). Any thread. False when the game-event
/// hook isn't installed; seq 0 = no UseDone yet this session.
/// </summary>
public static bool TryGetLastUseDone(out int seq, out uint error)
{
long v = System.Threading.Interlocked.Read(ref _useDoneLast);
seq = unchecked((int)(v >> 32));
error = unchecked((uint)v);
return _gameEventHookInstalled;
}
// ── Weenie errors (v70) ─────────────────────────────────────────────
// The last refusal the server sent: WeenieError (0x028A), WeenieErrorWithString
// (0x028B) or InventoryServerSaveFailed (0x00A0, with the item id). Written on AC's
// main thread, read from the plugin pump: four fields, so a lock (never contended).
private static readonly object _weenieErrorLock = new();
private static int _weenieErrorSeq;
private static uint _weenieErrorCode, _weenieErrorEvent, _weenieErrorObject;
private static int _weenieErrorLogCount;
private static void RecordWeenieError(uint eventType, uint code, uint objectId)
{
int seq;
lock (_weenieErrorLock)
{
seq = ++_weenieErrorSeq;
_weenieErrorCode = code;
_weenieErrorEvent = eventType;
_weenieErrorObject = objectId;
}
if (_weenieErrorLogCount < 25)
{
_weenieErrorLogCount++;
RynthLog.Compat($"WeenieError seq={seq} evt=0x{eventType:X3} err=0x{code:X4} obj=0x{objectId:X8}");
}
}
/// <summary>
/// v70: the most recent server refusal (see RecordWeenieError). seq counts them (0 = none
/// yet); eventType says which message carried it; objectId is the item for 0x00A0, else 0.
/// Any thread. False when the game-event hook isn't installed.
/// </summary>
public static bool TryGetLastWeenieError(out int seq, out uint error, out uint eventType, out uint objectId)
{
lock (_weenieErrorLock)
{
seq = _weenieErrorSeq;
error = _weenieErrorCode;
eventType = _weenieErrorEvent;
objectId = _weenieErrorObject;
}
return _gameEventHookInstalled;
}
// ── Enchantment events (v70) ────────────────────────────────────────
// The player's enchantment changes arrive as these GameEvents (all dispatched by
// UIQueueManager::ProcessNetBlobData, the function this file hooks; the case targets
// were traced to CM_Magic::DispatchUI_* in the Chorizite map):
// 0x02C2 UpdateEnchantment Enchantment
// 0x02C4 UpdateMultipleEnchantments u32 count + Enchantment[]
// 0x02C3 RemoveEnchantment LayeredSpellId (u16 spell, u16 layer)
// 0x02C5 RemoveMultipleEnchantments u32 count + LayeredSpellId[]
// 0x02C7 DispelEnchantment LayeredSpellId (silent removal)
// 0x02C8 DispelMultipleEnchantments u32 count + LayeredSpellId[]
// 0x02C6 PurgeEnchantments (none: all but vitae go, e.g. on death)
// 0x0312 PurgeBadEnchantments (none: the harmful ones go)
// The purges carry no ids, so the player's registry is read just before and just after
// AC applies them and the spells that disappeared are reported. Removals report the spell
// id (layer stripped), which is what OnEnchantmentRemoved's plugins key on.
//
// Enchantment on the wire (ACE's writer, 60 bytes, +4 when HasSpellSetId != 0):
// +0 u16 spellId +2 u16 layer +4 u16 category +6 u16 hasSpellSetId +8 u32 power
// +12 f64 startTime +20 f64 duration +28 u32 caster +32 f32 degradeMod
// +36 f32 degradeLimit +40 f64 lastDegraded +48 u32 statModType +52 u32 key
// +56 f32 value [+60 u32 spellSetId]
private const int EnchantmentWireSize = 60;
private const int MaxEnchantmentsPerEvent = 256;
private static int _enchantmentEventLogCount;
private sealed class EnchantmentChange
{
public uint EventType;
public bool Added;
public int Count;
public uint[] SpellIds = Array.Empty<uint>();
public double[] Durations = Array.Empty<double>();
/// <summary>Purges: the player's spell ids before AC applied it (null = unreadable).</summary>
public uint[]? Before;
}
private static EnchantmentChange? CaptureEnchantmentEvent(uint eventType, IntPtr data, uint size)
{
// Payload starts at data+4; `size` counts the 4-byte event type too.
switch (eventType)
{
case 0x02C2: // UpdateEnchantment
{
if (size < 4 + EnchantmentWireSize) return null;
var c = new EnchantmentChange { EventType = eventType, Added = true, Count = 1, SpellIds = new uint[1], Durations = new double[1] };
ReadWireEnchantment(data, 4, out c.SpellIds[0], out c.Durations[0]);
return c.SpellIds[0] != 0 ? c : null;
}
case 0x02C4: // UpdateMultipleEnchantments
{
if (size < 8) return null;
uint count = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4)));
if (count == 0 || count > MaxEnchantmentsPerEvent) return null;
var c = new EnchantmentChange { EventType = eventType, Added = true, SpellIds = new uint[count], Durations = new double[count] };
uint off = 8;
for (uint i = 0; i < count; i++)
{
if (off + EnchantmentWireSize > size) break;
ushort hasSet = unchecked((ushort)Marshal.ReadInt16(IntPtr.Add(data, (int)off + 6)));
ReadWireEnchantment(data, (int)off, out uint spellId, out double duration);
off += EnchantmentWireSize + (hasSet != 0 ? 4u : 0u);
if (spellId == 0) continue;
c.SpellIds[c.Count] = spellId;
c.Durations[c.Count] = duration;
c.Count++;
}
return c.Count > 0 ? c : null;
}
case 0x02C3: // RemoveEnchantment
case 0x02C7: // DispelEnchantment
{
if (size < 8) return null;
uint spellId = (uint)(ushort)Marshal.ReadInt16(IntPtr.Add(data, 4));
if (spellId == 0) return null;
return new EnchantmentChange { EventType = eventType, Count = 1, SpellIds = new[] { spellId } };
}
case 0x02C5: // RemoveMultipleEnchantments
case 0x02C8: // DispelMultipleEnchantments
{
if (size < 8) return null;
uint count = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4)));
if (count == 0 || count > MaxEnchantmentsPerEvent) return null;
var c = new EnchantmentChange { EventType = eventType, SpellIds = new uint[count] };
for (uint i = 0; i < count && 8 + i * 4 + 4 <= size; i++)
{
uint spellId = (uint)(ushort)Marshal.ReadInt16(IntPtr.Add(data, (int)(8 + i * 4)));
if (spellId != 0) c.SpellIds[c.Count++] = spellId;
}
return c.Count > 0 ? c : null;
}
case 0x02C6: // PurgeEnchantments
case 0x0312: // PurgeBadEnchantments
return new EnchantmentChange { EventType = eventType, Before = SnapshotPlayerSpellIds() };
}
return null;
}
private static void ReadWireEnchantment(IntPtr data, int off, out uint spellId, out double duration)
{
spellId = (uint)(ushort)Marshal.ReadInt16(IntPtr.Add(data, off));
duration = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(IntPtr.Add(data, off + 20)));
}
private static void FlushEnchantmentEvent(EnchantmentChange c)
{
// The registry just changed: refresh the off-thread player snapshot NOW (we
// are on the main thread, after AC applied the change), before the event is
// queued, so a plugin re-reading on the event sees the new state as before.
EnchantmentHooks.RefreshPlayerSnapshotNow();
if (c.Before != null)
{
// A purge: whatever left the registry.
uint[]? after = SnapshotPlayerSpellIds();
if (after == null) return;
var remaining = new HashSet<uint>(after);
var reported = new HashSet<uint>();
foreach (uint id in c.Before)
if (!remaining.Contains(id) && reported.Add(id))
PluginManager.QueueEnchantmentRemoved(id);
LogEnchantmentEvent(c.EventType, reported.Count, 0);
return;
}
for (int i = 0; i < c.Count; i++)
{
if (c.Added) PluginManager.QueueEnchantmentAdded(c.SpellIds[i], c.Durations[i]);
else PluginManager.QueueEnchantmentRemoved(c.SpellIds[i]);
}
LogEnchantmentEvent(c.EventType, c.Count, c.SpellIds[0]);
}
private static void LogEnchantmentEvent(uint eventType, int count, uint firstSpellId)
{
if (_enchantmentEventLogCount >= 25) return;
_enchantmentEventLogCount++;
RynthLog.Compat($"Enchantment evt=0x{eventType:X3} count={count} first={firstSpellId}");
}
/// <summary>The player's enchantment spell ids (main thread here), or null when unreadable.</summary>
private static unsafe uint[]? SnapshotPlayerSpellIds()
{
const int Max = 512;
uint* ids = stackalloc uint[Max];
double* expiry = stackalloc double[Max];
int n = EnchantmentHooks.ReadPlayerEnchantments(ids, expiry, Max);
if (n < 0) return null;
var result = new uint[n];
for (int i = 0; i < n; i++) result[i] = ids[i];
return result;
}
// AttackerNotification (0x01B1) / DefenderNotification (0x01B2). Payload at
// data+4: string16 name, u32 damageType, f64 percent, u32 damage,
// [u32 damageLocation (defender only),] u32 crit, …. Read-only byte math.
@ -282,6 +614,9 @@ internal static class SmartBoxHooks
{
if (size < 24) return;
bool attacker = eventType == 0x01B1;
// "X hits you": the nameplates' engaged filter keys attackers by name (no id on the wire).
if (!attacker)
ImGuiBackend.Hud.MonsterHudData.RecordAttacker(ReadString16Latin1(data, 4, size));
int nameLen = (ushort)Marshal.ReadInt16(IntPtr.Add(data, 4));
int strBlock = ((2 + nameLen + 3) / 4) * 4; // u16 len + chars, padded to a multiple of 4
@ -300,6 +635,8 @@ internal static class SmartBoxHooks
RynthLog.Compat($"Combat: damage evt 0x{eventType:X3} dmg={damage} crit={crit} atk={attacker} len={size}");
}
PluginManager.QueueCombatDamage(damage, damageType, crit != 0, attacker);
// RynthVision combat text: the attacker event names the monster hit.
ImGuiBackend.Hud.HudFeed.OnDamageEvent(attacker, attacker ? ReadString16Latin1(data, 4, size) : null, damage, crit != 0);
}
private static SmartBoxEventInfo ReadSmartBoxEventInfo(IntPtr blob)
@ -417,6 +754,7 @@ internal static class SmartBoxHooks
}
PluginManager.QueueCombatDamage(damage, damageType, crit != 0, attacker);
ImGuiBackend.Hud.HudFeed.OnDamageEvent(attacker, attacker ? ReadString16Latin1(payloadPtr, nameOff, info.BlobSize) : null, damage, crit != 0);
}
catch
{

View file

@ -42,34 +42,10 @@ internal static class SmartBoxLocator
/// Uses VirtualQuery — safe to call on any address including unmapped pages.
/// Critical for NativeAOT where AccessViolationException cannot be caught.
/// </summary>
public static bool IsMemoryReadable(IntPtr address, int size)
{
if (address == IntPtr.Zero || size <= 0)
return false;
if (VirtualQuery(address, out MEMORY_BASIC_INFORMATION mbi,
Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0)
return false;
if (mbi.State != MEM_COMMIT)
return false;
if ((mbi.Protect & PAGE_NOACCESS) != 0)
return false;
if ((mbi.Protect & PAGE_GUARD) != 0)
return false;
if ((mbi.Protect & READABLE_MASK) == 0)
return false;
// Ensure the committed region covers the full requested range.
// Deep-audit finding #32 (2026-06-18): this used signed 32-bit
// arithmetic (ToInt32()) — acclient.exe is LARGE_ADDRESS_AWARE so
// addresses above 0x7FFFFFFF are reachable, and ToInt32() on those
// can wrap. Do the comparison in 64-bit (every caller passes a small
// compile-time size, so no overflow risk on that side).
long regionEnd = mbi.BaseAddress.ToInt64() + mbi.RegionSize.ToInt64();
long requestEnd = address.ToInt64() + size;
return requestEnd <= regionEnd;
}
public static bool IsMemoryReadable(IntPtr address, int size) => MemoryProbe.IsReadable(address, size);
// Was a VirtualQuery per call (one per CObjectMaint hash bucket and two per node in the
// snapshot walks); see MemoryProbe for why that collapsed the frame rate once AC's heap grew.
// Same rule: committed, not NOACCESS/GUARD, readable, the whole span (64-bit arithmetic).
public static bool IsInitialized { get; private set; }
public static int CandidateCount => _smartboxStaticCandidates.Count;

View file

@ -102,6 +102,7 @@ internal static class UpdateObjectInventoryHooks
{
if (objectId != 0)
PluginManager.QueueUpdateObjectInventory(objectId);
InventoryModel.MarkDirty(); // Inventory panel: capture again soon (one volatile write)
}
catch { }
}
@ -188,6 +189,18 @@ internal static class UpdateObjectInventoryHooks
/// </summary>
private static int ScanByContainerId(uint containerId, Span<uint> itemIds)
{
// Off AC's main thread (host GetContainerContentsFn on the plugin pump): one
// pass over the main-thread PWD snapshot under a single lock, no AC memory.
// Per-id TryGetObjectOwnershipInfo would serve the same snapshot but take the
// lock once per id; the fixed-range fallback below (65k ids) is pointless
// off-thread, so an empty snapshot just means "nothing yet".
if (!MainThreadGuard.IsOnMainThread())
{
int n = ClientObjectHooks.CollectOwnedIdsFromSnapshot(containerId, itemIds);
itemIds[..n].Sort(); // same ascending order as below
return n;
}
// Check every object the client knows, from the identity snapshot. The old fixed
// range stopped at 0x8000FFFF, but a server hands out ids well past that once it
// has run a while, so newer items (and packs, with everything in them) were
@ -264,17 +277,5 @@ internal static class UpdateObjectInventoryHooks
private const uint PageNoAccess = 0x01;
private const uint PageGuard = 0x100;
private static bool IsReadablePointer(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return false;
if (VirtualQuery(ptr, out MEMORY_BASIC_INFORMATION mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0)
return false;
if (mbi.State != MemCommit)
return false;
return (mbi.Protect & (PageNoAccess | PageGuard)) == 0;
}
private static bool IsReadablePointer(IntPtr ptr) => MemoryProbe.IsAccessible(ptr);
}

View file

@ -0,0 +1,73 @@
// ============================================================================
// RynthCore.Engine - Compatibility/VTankSignal.cs
//
// Pure parsing for VTankWatch (no engine state, no AC, no Decal), so the offline
// tests in tools\VTankWatchTests compile this file directly.
//
// The signal is VTank's own DOCUMENTED chat commands, as they go through Decal's
// chat parser (typed in the chat bar, sent by a meta's Chat Command action, by a
// login command, or by another plugin through InvokeChatParser):
// /vt start - "Turns the macro on"
// /vt stop - "Turns the macro off"
// (VirindiPlugins wiki, "Virindi Tank Commands", /vt commands - Actions.)
// Nothing here reads, loads or inspects VTank itself (its licence forbids reverse
// engineering; docs/LEGAL_COMPATIBILITY.md).
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
internal static class VTankSignal
{
/// <summary>The line turns VTank's macro on.</summary>
public const int Start = 1;
/// <summary>The line turns VTank's macro off.</summary>
public const int Stop = -1;
/// <summary>Not a VTank start/stop command.</summary>
public const int None = 0;
/// <summary>
/// <see cref="Start"/> for "/vt start", <see cref="Stop"/> for "/vt stop" (any case,
/// any spacing, leading/trailing blanks ignored); <see cref="None"/> for anything else,
/// including other /vt commands ("/vt startx", "/vt opt set ...") and lines that only
/// mention the words ("tell X /vt start").
/// </summary>
public static int ParseCommand(string? line)
{
if (string.IsNullOrEmpty(line))
return None;
ReadOnlySpan<char> s = line.AsSpan().Trim();
if (s.Length < 4 || s[0] != '/' || !s.Slice(1, 2).Equals("vt", StringComparison.OrdinalIgnoreCase))
return None;
s = s.Slice(3);
// "/vt" must be a whole word: "/vtank start" is not VTank's command.
if (s.Length == 0 || !char.IsWhiteSpace(s[0]))
return None;
s = s.TrimStart();
int end = 0;
while (end < s.Length && !char.IsWhiteSpace(s[end])) end++;
ReadOnlySpan<char> verb = s.Slice(0, end);
// The documented forms take no argument; tolerate trailing words anyway (VTank's own
// parser decides), but the verb itself must match exactly.
if (verb.Equals("start", StringComparison.OrdinalIgnoreCase)) return Start;
if (verb.Equals("stop", StringComparison.OrdinalIgnoreCase)) return Stop;
return None;
}
/// <summary>
/// A chat-window line that looks like VTank's own output (for the diagnostic log only:
/// it is never used to decide anything, because VTank documents no on/off chat line).
/// Lines other players send ("X tells you, ...", channel chat) are excluded.
/// </summary>
public static bool LooksLikeVTankChat(string? text)
{
if (string.IsNullOrEmpty(text))
return false;
if (text.Contains(" tells you, ", StringComparison.Ordinal) || text.Contains(" says, ", StringComparison.Ordinal))
return false;
return text.Contains("VTank", StringComparison.OrdinalIgnoreCase)
|| text.Contains("Virindi Tank", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("[VT]", StringComparison.OrdinalIgnoreCase);
}
}

View file

@ -0,0 +1,123 @@
// ============================================================================
// RynthCore.Engine - Compatibility/VTankWatch.cs
//
// "Is VTank's macro running in this client?" for the Decal bridge, so RynthAi can
// follow the one-bot-per-client rule (docs/DECAL_BRIDGE_PLAN.md, "What's lost or
// different under Decal"): when VTank starts, RynthAi's macro stops.
//
// Signal (VTankSignal.cs): VTank's documented /vt start and /vt stop commands, seen
// - in every line Decal's chat parser hands the bridge (CommandLineText ->
// ChatBarEnter record, eaten or not): typed lines, VTank meta Chat Command
// actions and other plugins' InvokeChatParser calls;
// - in the lines the engine itself sends through Decal (TryInvokeChatParser), which
// the bridge doesn't echo back (RynthAi metas, on-login commands, plugins).
// Cleared at Decal's Logoff (Decal plugins, VTank included, end with the session).
// NOT seen: VTank's own "Run Macro" button and its own stops (death with
// StopMacroOnDeath, a meta that stops it internally). VTank documents no chat line
// for those, so there is nothing legal to read; see the report for options.
//
// Survives a hot reload: the state is mirrored into this process's environment
// (RYNTHCORE_VTANK_MACRO), which outlives an engine generation.
//
// Without Decal nothing here runs: every entry point is called from DecalBridgeHost
// after its Active check, and GetPluginState answers 0 ("not watching").
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class VTankWatch
{
/// <summary>Plugin API v74 GetVTankState flags.</summary>
public const uint FlagWatching = 1u << 0;
public const uint FlagRunning = 1u << 1;
private const string EnvName = "RYNTHCORE_VTANK_MACRO";
private const int MaxChatLogLines = 30;
private static int _running = ReadEnv();
private static int _seq = _running; // a restored "running" is a change the plugins haven't seen
private static string _lastChange = _running != 0 ? "restored after a reload" : "none yet";
private static int _chatLogged;
/// <summary>True while VTank's macro was last seen turned on (bridge mode only).</summary>
public static bool Running => DecalBridgeHost.Active && Volatile.Read(ref _running) != 0;
/// <summary>Bumped on every change of <see cref="Running"/>.</summary>
public static int Sequence => Volatile.Read(ref _seq);
/// <summary>
/// Plugin API v74: bit0 = the engine watches VTank (Decal bridge mode), bit1 = VTank's
/// macro is running as far as the engine saw. 0 without Decal. Any thread.
/// </summary>
public static uint GetPluginState(out int sequence)
{
sequence = Volatile.Read(ref _seq);
if (!DecalBridgeHost.Active)
return 0;
return FlagWatching | (Volatile.Read(ref _running) != 0 ? FlagRunning : 0);
}
/// <summary>A line Decal's chat parser saw (typed, meta, plugin). Pump thread.</summary>
public static void ObserveParserLine(string text) => Observe(text, "Decal's chat parser");
/// <summary>A line the engine sent through Decal's InvokeChatParser. Any thread.</summary>
public static void ObserveSentLine(string text) => Observe(text, "sent by RynthCore");
/// <summary>Decal ended the session: VTank (a Decal plugin) ends with it.</summary>
public static void OnLogoff()
{
if (Set(false, "logoff"))
RynthLog.Info("VTankWatch: logoff - VTank's macro counts as stopped.");
}
/// <summary>Diagnostic only: log the first VTank-looking chat lines, so a test shows what VTank prints.</summary>
public static void ObserveChatText(string text)
{
if (Volatile.Read(ref _chatLogged) >= MaxChatLogLines || !VTankSignal.LooksLikeVTankChat(text))
return;
if (Interlocked.Increment(ref _chatLogged) > MaxChatLogLines)
return;
string t = text.TrimEnd('\r', '\n');
if (t.Length > 160) t = t.Substring(0, 160) + "...";
RynthLog.Info($"VTankWatch: chat line '{t}' (logged for reference; not used as a signal)");
}
/// <summary>/rc vtank clear: the player says VTank isn't running (it was stopped with its own button).</summary>
public static bool Clear() => Set(false, "/rc vtank clear");
public static string Describe() =>
!DecalBridgeHost.Active
? "VTank watch: off (no Decal bridge in this client; RynthAi is never stopped for VTank)."
: $"VTank watch: on. VTank macro {(Volatile.Read(ref _running) != 0 ? "RUNNING" : "not running")} (last change: {Volatile.Read(ref _lastChange)}). " +
"Signal: /vt start and /vt stop through Decal's chat parser; VTank's own button is not seen.";
private static void Observe(string text, string source)
{
int verb = VTankSignal.ParseCommand(text);
if (verb == VTankSignal.None)
return;
bool on = verb == VTankSignal.Start;
if (Set(on, $"'{text.Trim()}' ({source})"))
RynthLog.Info($"VTankWatch: VTank macro {(on ? "STARTED" : "STOPPED")} - '{text.Trim()}' ({source}).");
}
private static bool Set(bool on, string why)
{
int v = on ? 1 : 0;
if (Interlocked.Exchange(ref _running, v) == v)
return false;
Volatile.Write(ref _lastChange, $"{(on ? "started" : "stopped")} by {why} at {DateTime.Now:HH:mm:ss}");
Interlocked.Increment(ref _seq);
try { Environment.SetEnvironmentVariable(EnvName, on ? "1" : null); } catch { }
return true;
}
private static int ReadEnv()
{
try { return Environment.GetEnvironmentVariable(EnvName) == "1" ? 1 : 0; }
catch { return 0; }
}
}

View file

@ -50,7 +50,7 @@ internal static class CrashDump
/// Write a minidump of the current process to Logs\dumps\. Best-effort;
/// never throws. Returns true on success and sets <paramref name="dumpPath"/>.
/// </summary>
internal static bool WriteSelfDump(string reason, out string dumpPath)
internal static bool WriteSelfDump(string reason, out string dumpPath, string prefix = "hang")
{
dumpPath = string.Empty;
try
@ -59,7 +59,7 @@ internal static class CrashDump
Directory.CreateDirectory(dir);
string stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
dumpPath = Path.Combine(dir, $"hang_{Environment.ProcessId}_{stamp}.dmp");
dumpPath = Path.Combine(dir, $"{prefix}_{Environment.ProcessId}_{stamp}.dmp");
using var fs = new FileStream(dumpPath, FileMode.Create, FileAccess.Write, FileShare.None);
bool ok = MiniDumpWriteDump(

View file

@ -1,168 +0,0 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — D3D9/BitmapFont.cs
// Dependency-free 5x7 bitmap font, ported from RynthCore2's bitmap_font.cpp.
//
// Standard 5x7 glyph cells. Each glyph is 7 rows; the low 5 bits of each row
// are the columns, bit 4 = leftmost. A set bit is a lit pixel cell. Lit cells
// are emitted as rectangles through a caller-supplied sink so the renderer
// (VitalHud) can turn each into a colored quad. No allocation, no texture.
// ═══════════════════════════════════════════════════════════════════════════
using System;
namespace RynthCore.Engine.D3D9;
internal static class BitmapFont
{
/// <summary>Receives one lit pixel cell as an inclusive-exclusive rect.</summary>
internal delegate void CellSink(int x0, int y0, int x1, int y1);
public const int GlyphW = 5;
public const int GlyphH = 7;
private const int Advance = GlyphW + 1; // one-cell gap between glyphs
// Glyph table row, in a fixed order; IndexOf maps a character to a row.
// 0 = space
// 1..10 = '0'..'9'
// 11..36 = 'A'..'Z'
// 37..45 = '/' ':' '.' ',' '-' '+' '%' '(' ')'
private const int GSpace = 0;
private const int GDigit0 = 1;
private const int GLetterA = 11;
private const int GSlash = 37;
private const int GColon = 38;
private const int GDot = 39;
private const int GComma = 40;
private const int GDash = 41;
private const int GPlus = 42;
private const int GPercent = 43;
private const int GLParen = 44;
private const int GRParen = 45;
// 5x7 cells, bit 4 leftmost — transcribed verbatim from bitmap_font.cpp.
private static readonly byte[][] Glyphs =
[
/* space */ [0, 0, 0, 0, 0, 0, 0],
/* 0 */ [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110],
/* 1 */ [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
/* 2 */ [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111],
/* 3 */ [0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110],
/* 4 */ [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],
/* 5 */ [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],
/* 6 */ [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],
/* 7 */ [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000],
/* 8 */ [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],
/* 9 */ [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100],
/* A */ [0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
/* B */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110],
/* C */ [0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110],
/* D */ [0b11100, 0b10010, 0b10001, 0b10001, 0b10001, 0b10010, 0b11100],
/* E */ [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111],
/* F */ [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000],
/* G */ [0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01111],
/* H */ [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
/* I */ [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
/* J */ [0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100],
/* K */ [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001],
/* L */ [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111],
/* M */ [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001],
/* N */ [0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001],
/* O */ [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
/* P */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000],
/* Q */ [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101],
/* R */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001],
/* S */ [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110],
/* T */ [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],
/* U */ [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
/* V */ [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100],
/* W */ [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b10101, 0b01010],
/* X */ [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001],
/* Y */ [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100],
/* Z */ [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111],
/* / */ [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000],
/* : */ [0b00000, 0b00100, 0b00100, 0b00000, 0b00100, 0b00100, 0b00000],
/* . */ [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b01100],
/* , */ [0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b00100, 0b01000],
/* - */ [0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000],
/* + */ [0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000],
/* % */ [0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011],
/* ( */ [0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010],
/* ) */ [0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000],
];
// Maps an ASCII character to a glyph row, or -1 if unsupported (advance blank).
private static int IndexOf(char c)
{
if (c >= '0' && c <= '9') return GDigit0 + (c - '0');
if (c >= 'A' && c <= 'Z') return GLetterA + (c - 'A');
if (c >= 'a' && c <= 'z') return GLetterA + (c - 'a'); // fold to uppercase
return c switch
{
' ' => GSpace,
'/' => GSlash,
':' => GColon,
'.' => GDot,
',' => GComma,
'-' => GDash,
'+' => GPlus,
'%' => GPercent,
'(' => GLParen,
')' => GRParen,
_ => -1,
};
}
/// <summary>Pixel height of a glyph at the given cell size.</summary>
public static int Height(int cellPx)
{
if (cellPx < 1) cellPx = 1;
return GlyphH * cellPx;
}
/// <summary>Pixel width of a rendered string at the given cell size. Takes a
/// span so callers can measure stack-formatted text without allocating.</summary>
public static int MeasureWidth(ReadOnlySpan<char> s, int cellPx)
{
if (s.IsEmpty) return 0;
if (cellPx < 1) cellPx = 1;
int n = s.Length;
// n glyphs, each GlyphW wide, with (n-1) single-cell gaps between them.
return (n * GlyphW + (n - 1)) * cellPx;
}
/// <summary>
/// Emits the lit cells of <paramref name="s"/> at (x, y) at the given cell
/// size by invoking <paramref name="sink"/> once per lit cell. Takes a span
/// (string literals convert implicitly) so it stays allocation-free; the sink
/// is a cached delegate on the caller side.
/// </summary>
public static void Emit(ReadOnlySpan<char> s, int x, int y, int cellPx, CellSink sink)
{
if (s.IsEmpty || sink == null) return;
if (cellPx < 1) cellPx = 1;
int penX = x;
foreach (char ch in s)
{
int gi = IndexOf(ch);
if (gi >= 0 && gi != GSpace)
{
byte[] rows = Glyphs[gi];
for (int r = 0; r < GlyphH; r++)
{
int bits = rows[r];
for (int c = 0; c < GlyphW; c++)
{
if (((bits >> (GlyphW - 1 - c)) & 1) != 0)
{
int x0 = penX + c * cellPx;
int y0 = y + r * cellPx;
sink(x0, y0, x0 + cellPx, y0 + cellPx);
}
}
}
}
penX += Advance * cellPx;
}
}
}

View file

@ -30,6 +30,15 @@ internal static class D3D9Bootstrapper
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
/// <summary>
/// Decal is in this client and the in-game renderer was asked for (EntryPoint,
/// DecalInGameImGui). Decal detours Direct3DCreate9 and IDirect3D9::CreateDevice, so the
/// throwaway-device discovery would hand a second device to Decal: the EndScene address
/// comes from AC's live device (heap scan) or d3d9.dll's image instead. Never set
/// without Decal.
/// </summary>
internal static volatile bool DecalInProcess;
private static int _started;
private static bool _d3dCreateHookInstalled;
private static bool _createDeviceHookInstalled;
@ -46,18 +55,23 @@ internal static class D3D9Bootstrapper
if (Interlocked.CompareExchange(ref _started, 1, 0) != 0)
return;
var thread = new Thread(BootstrapWorker)
{
Name = "RynthCore.D3D9Bootstrap",
IsBackground = true
};
thread.Start();
EngineThreads.Start("RynthCore.D3D9Bootstrap", BootstrapWorker);
}
private static void BootstrapWorker()
{
try
{
if (DecalInProcess)
{
while (GetModuleHandleA("d3d9.dll") == IntPtr.Zero)
if (!EngineThreads.Sleep(PollIntervalMs))
return;
RynthLog.D3D9("D3D9Bootstrapper: Decal in the process - discovering EndScene without creating a device.");
EndSceneHook.InstallWithoutDevice("decal-live-device");
return;
}
// This runs after character login, so d3d9.dll and the game's
// device are fully initialized. Use the NULLREF throwaway device
// for vtable discovery — it's safe post-login because the
@ -91,7 +105,8 @@ internal static class D3D9Bootstrapper
return;
}
Thread.Sleep(PollIntervalMs);
if (!EngineThreads.Sleep(PollIntervalMs))
return; // engine shutting down: don't install hooks for a dying generation
}
}
catch (Exception ex)

View file

@ -421,6 +421,68 @@ internal static unsafe class D3D9VTable
return null;
}
/// <summary>
/// Decal clients: Decal gives AC's device its own copy of the vtable (EndScene and Reset
/// point into Inject.dll, the rest still into d3d9.dll). This finds the d3d9.dll vtable the
/// copy was made from - the vtable in d3d9's image that agrees with the copy in the most
/// slots - so the engine can hook d3d9's own functions and never Decal's. Read-only.
/// Returns null when no candidate agrees in at least 100 slots.
/// </summary>
public static IntPtr[]? MatchOriginalDeviceVTable(IntPtr copiedVTable, int numEntries = 119)
{
IntPtr hModule = GetModuleHandleA("d3d9.dll");
if (hModule == IntPtr.Zero || copiedVTable == IntPtr.Zero)
return null;
if (!TryReadModuleImageSize(hModule, out int imageSize) || imageSize < 0x2000 || imageSize > 50 * 1024 * 1024)
return null;
var copy = new int[numEntries];
for (int i = 0; i < numEntries; i++)
copy[i] = Marshal.ReadInt32(copiedVTable, i * 4);
byte[] image = new byte[imageSize];
const int PageSize = 0x1000;
for (int off = 0; off < imageSize; off += PageSize)
{
int chunk = Math.Min(PageSize, imageSize - off);
IntPtr addr = IntPtr.Add(hModule, off);
if (SmartBoxLocator.IsMemoryReadable(addr, chunk))
Marshal.Copy(addr, image, off, chunk);
}
int bestOff = -1, bestMatches = 0;
for (int off = 0x1000; off <= imageSize - numEntries * 4; off += 4)
{
// Cheap reject: QueryInterface and AddRef of the copy must match.
if (BitConverter.ToInt32(image, off) != copy[0] || BitConverter.ToInt32(image, off + 4) != copy[1])
continue;
int matches = 0;
for (int i = 0; i < numEntries; i++)
if (BitConverter.ToInt32(image, off + i * 4) == copy[i])
matches++;
if (matches > bestMatches)
{
bestMatches = matches;
bestOff = off;
}
}
if (bestOff < 0 || bestMatches < 100)
{
RynthLog.D3D9($"D3D9VTable: no d3d9.dll vtable matches the copied one (best {bestMatches}/{numEntries}).");
return null;
}
var vtable = new IntPtr[numEntries];
var differs = new System.Text.StringBuilder();
for (int i = 0; i < numEntries; i++)
{
vtable[i] = new IntPtr(BitConverter.ToInt32(image, bestOff + i * 4));
if (vtable[i].ToInt32() != copy[i])
differs.Append(' ').Append(i);
}
RynthLog.D3D9($"D3D9VTable: the copied device vtable came from d3d9+0x{bestOff:X} ({bestMatches}/{numEntries} slots equal; replaced slots:{differs}). " +
$"d3d9's EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8}.");
return vtable;
}
private static bool IsRecognizedPrologue(byte[] image, int offset)
{
byte b = image[offset];

View file

@ -0,0 +1,129 @@
// ============================================================================
// RynthCore.Engine - D3D9/DecalD3D9.cs
//
// Decal clients with the in-game renderer only (DecalInGameImGui, docs/DECAL_BRIDGE_PLAN.md).
// Decal gives AC's device its own copy of the vtable, with Reset, BeginScene, EndScene and a
// few more slots pointing into Inject.dll (measured 2026-09-30). The engine hooks d3d9.dll's
// own functions (which Decal's wrappers call) and never Decal's code: HookTarget resolves a
// device slot through d3d9's original vtable. Without Decal, Enabled stays false and
// HookTarget is the plain vtable read it always was.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.D3D9;
internal static unsafe class DecalD3D9
{
/// <summary>Set by EndSceneHook.InstallWithoutDevice (Decal clients only).</summary>
internal static bool Enabled;
/// <summary>d3d9.dll's own EndScene for AC's device, from <see cref="TryResolve"/>.</summary>
internal static IntPtr ResolvedEndScene;
/// <summary>
/// Decides, before any hook goes in, whether the in-game renderer can run in this Decal
/// client: AC's device from the bridge (Decal's public IDecalCore.GetD3DDevice; read
/// without waiting), and d3d9.dll's EndScene for it - directly when its vtable is d3d9's,
/// or through the d3d9 vtable Decal's per-device copy was made from. Read-only. False =
/// stay on the Decal-coexistence path (no D3D9). Called once per generation.
/// </summary>
internal static bool TryResolve()
{
if (ResolvedEndScene != IntPtr.Zero)
return true;
IntPtr device = Compatibility.DecalBridgeHost.DecalDevice;
if (device == IntPtr.Zero)
{
RynthLog.D3D9("DecalD3D9: the bridge hasn't reported Decal's device - staying on the coexistence path.");
return false;
}
IntPtr es = DescribeDevice(device, "Decal's device (GetD3DDevice)", out bool inD3d9);
if (inD3d9 && es != IntPtr.Zero)
{
ResolvedEndScene = es;
return true;
}
// Decal swapped the device's vtable for its own copy: find d3d9's original.
IntPtr[]? original = D3D9VTable.MatchOriginalDeviceVTable(Marshal.ReadIntPtr(device));
if (original == null)
{
RynthLog.D3D9("DecalD3D9: d3d9.dll's original device vtable wasn't found - staying on the coexistence path.");
return false;
}
OriginalVTable = original;
ResolvedEndScene = original[DeviceVTableIndex.EndScene];
RynthLog.D3D9($"DecalD3D9: Decal wraps EndScene; d3d9's own EndScene is {Describe(ResolvedEndScene)} (Decal's wrapper calls it).");
return true;
}
/// <summary>Decal clients: d3d9.dll's own device vtable (the one Decal's per-device copy
/// was made from), when found. Hooks on device methods resolve through it.</summary>
internal static IntPtr[]? OriginalVTable;
private static int _refusedLogged;
/// <summary>
/// The address to hook for a device method. Without Decal: the device's vtable slot, as
/// always. With Decal: d3d9.dll's own function for that slot, and zero (do not hook) if
/// it isn't in d3d9.dll - the engine never hooks Decal's code.
/// </summary>
internal static IntPtr HookTarget(IntPtr device, int index)
{
IntPtr fn = Marshal.ReadIntPtr(Marshal.ReadIntPtr(device), index * IntPtr.Size);
if (!Enabled)
return fn;
if (OriginalVTable != null && index < OriginalVTable.Length)
fn = OriginalVTable[index];
string where = Describe(fn);
if (where.StartsWith("d3d9.dll+", StringComparison.OrdinalIgnoreCase))
return fn;
if (Interlocked.Increment(ref _refusedLogged) <= 8)
RynthLog.D3D9($"DecalD3D9: device slot {index} resolves to {where}, not d3d9.dll - not hooked (Decal's code is never patched).");
return IntPtr.Zero;
}
[DllImport("kernel32.dll")]
private static extern bool GetModuleHandleExW(uint flags, IntPtr address, out IntPtr module);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern uint GetModuleFileNameW(IntPtr module, char* buffer, uint size);
/// <summary>"module+0xRVA" for a code or data address.</summary>
internal static string Describe(IntPtr address)
{
const uint FROM_ADDRESS = 0x4, UNCHANGED_REFCOUNT = 0x2;
if (address == IntPtr.Zero)
return "null";
if (!GetModuleHandleExW(FROM_ADDRESS | UNCHANGED_REFCOUNT, address, out IntPtr module) || module == IntPtr.Zero)
return $"0x{address.ToInt32():X8} (no module)";
char* buf = stackalloc char[260];
uint n = GetModuleFileNameW(module, buf, 260);
return $"{System.IO.Path.GetFileName(new string(buf, 0, (int)n))}+0x{address.ToInt32() - module.ToInt32():X}";
}
/// <summary>Logs a device's vtable owner and EndScene/Reset/Present slots; returns its EndScene.</summary>
internal static IntPtr DescribeDevice(IntPtr device, string what, out bool endSceneInD3d9)
{
endSceneInD3d9 = false;
try
{
IntPtr vtable = Marshal.ReadIntPtr(device);
IntPtr endScene = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.EndScene * IntPtr.Size);
IntPtr reset = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.Reset * IntPtr.Size);
IntPtr present = Marshal.ReadIntPtr(vtable, 17 * IntPtr.Size);
string es = Describe(endScene);
endSceneInD3d9 = es.StartsWith("d3d9.dll+", StringComparison.OrdinalIgnoreCase);
RynthLog.D3D9($"DecalD3D9: {what} 0x{device.ToInt32():X8}: vtable {Describe(vtable)}, EndScene {es}, Reset {Describe(reset)}, Present {Describe(present)}.");
return endScene;
}
catch (Exception ex)
{
RynthLog.D3D9($"DecalD3D9: reading {what} threw {ex.GetType().Name}: {ex.Message}");
return IntPtr.Zero;
}
}
/// <summary>First backbuffer frame in our EndScene detour (AC's thread): which device our
/// d3d9 hook is called with, and whose code its vtable points at.</summary>
internal static void FirstFrame(IntPtr device) => DescribeDevice(device, "EndScene called with device", out _);
}

View file

@ -0,0 +1,88 @@
// ============================================================================
// RynthCore.Engine - D3D9/DeviceResetHook.cs
// IDirect3DDevice9::Reset: release the engine's D3DPOOL_DEFAULT resources
// (the pop-outs' render targets) just before AC resets a lost device.
//
// A plain D3D9 device can't be Reset while any default-pool resource is
// alive: Reset fails, and AC shows "Could not initialize Direct3D" and stops
// (2026-09-30 15:06, Lucy, PID 9384: the ImGui bar was popped out when the
// device was lost — screen lock / display change). The resources are
// recreated on the next frame, so nothing else changes.
//
// AC's main thread (Reset is called where EndScene is). Installed from the
// device when the frame controller first sees it; removed at shutdown.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.ImGuiBackend;
namespace RynthCore.Engine.D3D9;
internal static class DeviceResetHook
{
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int ResetDelegate(IntPtr device, IntPtr presentationParameters);
private static ResetDelegate? _original;
private static ResetDelegate? _detour;
private static IntPtr _address;
private static bool _installed;
private static int _resets;
public static void InstallFromDevice(IntPtr device)
{
if (_installed || device == IntPtr.Zero) return;
try
{
// Without Decal: the device's vtable slot, as before. With Decal: d3d9's own Reset
// (Decal wraps Reset; its code is never hooked) - zero means not hooked.
_address = DecalD3D9.HookTarget(device, DeviceVTableIndex.Reset);
if (_address == IntPtr.Zero) return;
_detour = ResetDetour;
_original = Marshal.GetDelegateForFunctionPointer<ResetDelegate>(
MinHook.HookCreate(_address, Marshal.GetFunctionPointerForDelegate(_detour)));
Thread.MemoryBarrier();
MinHook.Enable(_address);
_installed = true;
RynthLog.D3D9($"DeviceResetHook: installed at 0x{_address.ToInt32():X8}.");
}
catch (Exception ex)
{
RynthLog.D3D9($"DeviceResetHook: install failed - {ex.Message}");
}
}
public static void Uninstall()
{
if (!_installed) return;
RynthLog.D3D9($"DeviceResetHook: disable = {MinHook.StatusString(MinHook.MH_DisableHook(_address))}, remove = {MinHook.StatusString(MinHook.MH_RemoveHook(_address))}.");
_installed = false;
_original = null;
_detour = null;
}
private static int ResetDetour(IntPtr device, IntPtr presentationParameters)
{
int n = Interlocked.Increment(ref _resets);
try
{
int released = ImGuiPopOuts.ReleaseDeviceResources();
if (n <= 20)
RynthLog.D3D9($"DeviceResetHook: device Reset #{n}: released {released} pop-out surface set(s) first.");
}
catch (Exception ex)
{
try { RynthLog.D3D9($"DeviceResetHook: releasing before Reset threw {ex.GetType().Name}: {ex.Message}"); } catch { }
}
int hr = _original!(device, presentationParameters);
if (n <= 20 || hr < 0)
{
try { RynthLog.D3D9($"DeviceResetHook: Reset #{n} returned 0x{hr:X8}."); } catch { }
}
return hr;
}
}

View file

@ -14,6 +14,10 @@ internal static class EndSceneHook
private const int MaxOffscreenSkipsBeforeFallback = 120;
private const int OffscreenFallbackDelayMs = 3000;
private const int UiInitWarmupFrames = 180;
// After a hot reload the device and the game have been running all along: a few
// frames is enough (180 was ~1 s more of no overlay on every reload).
private const int UiInitWarmupFramesReload = 5;
private static int WarmupFrames => EntryPoint.InitCount >= 2 ? UiInitWarmupFramesReload : UiInitWarmupFrames;
// ── FPS Governor — set by plugins via API ───────────────────────
internal static bool FpsLimitEnabled;
@ -46,6 +50,62 @@ internal static class EndSceneHook
[DllImport("kernel32.dll")]
private static extern uint GetCurrentProcessId();
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr CreateWaitableTimerExW(IntPtr attributes, string? name, uint flags, uint access);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWaitableTimer(IntPtr timer, ref long dueTime, int period, IntPtr completion, IntPtr arg, [MarshalAs(UnmanagedType.Bool)] bool resume);
[DllImport("kernel32.dll")]
private static extern uint WaitForSingleObject(IntPtr handle, uint ms);
[DllImport("winmm.dll")]
private static extern uint timeBeginPeriod(uint ms);
private const uint CREATE_WAITABLE_TIMER_HIGH_RESOLUTION = 0x2;
private const uint TIMER_ALL_ACCESS = 0x1F0003;
private static IntPtr _frameTimer;
private static bool _frameTimerTried;
/// <summary>
/// Waits <paramref name="ms"/> without burning the CPU. The governor used to wait with
/// Sleep(0) in a loop when focused (Sleep(0) returns at once when nothing else is ready,
/// so a "capped" focused client spun a whole core) and Sleep(1) in the background (15.6 ms
/// timer steps, so a 30 fps cap gave 19 fps, 2026-10-03). A high-resolution waitable timer
/// (Windows 10 1803+) wakes within about half a millisecond; without one, timeBeginPeriod(1)
/// makes Sleep(1) a 1 ms sleep. The last 0.3 ms is a yield loop for accuracy.
/// </summary>
private static void WaitFrame(double ms)
{
if (!_frameTimerTried)
{
_frameTimerTried = true;
try { _frameTimer = CreateWaitableTimerExW(IntPtr.Zero, null, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); } catch { }
if (_frameTimer == IntPtr.Zero) { try { timeBeginPeriod(1); } catch { } }
RynthLog.D3D9($"EndSceneHook: FPS governor waits with {(_frameTimer != IntPtr.Zero ? "a high-resolution timer" : "1 ms sleeps")}.");
}
long start = Stopwatch.GetTimestamp();
double waitMs = ms - 0.3;
if (waitMs > 0.5)
{
if (_frameTimer != IntPtr.Zero)
{
long due = -(long)(waitMs * 10_000); // negative = relative, in 100 ns units
if (SetWaitableTimer(_frameTimer, ref due, 0, IntPtr.Zero, IntPtr.Zero, false))
WaitForSingleObject(_frameTimer, (uint)Math.Ceiling(waitMs) + 50);
}
else
{
while ((Stopwatch.GetTimestamp() - start) * 1000.0 / Stopwatch.Frequency < waitMs - 1.0)
Thread.Sleep(1);
}
}
while ((Stopwatch.GetTimestamp() - start) * 1000.0 / Stopwatch.Frequency < ms)
Thread.Yield();
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int EndSceneDelegate(IntPtr pDevice);
@ -54,6 +114,8 @@ internal static class EndSceneHook
private static IntPtr _endSceneAddr;
private static bool _installed;
private static int _frameCount;
/// <summary>Back-buffer frames drawn (offscreen passes - Decal views, VVS, UB - not counted). Resets on reinstall.</summary>
internal static int BackBufferFrames => Volatile.Read(ref _frameCount);
private static int _renderCount;
private static int _skipCount;
private static int _uiFrameCount;
@ -101,6 +163,30 @@ internal static class EndSceneHook
RynthLog.D3D9("EndSceneHook: FAILED - could not discover vtable after all attempts.");
}
/// <summary>
/// Decal clients (D3D9Bootstrapper.DecalInProcess): no D3D9 object is created (Decal
/// detours Direct3DCreate9 and CreateDevice). AC's device comes from the Decal bridge
/// (Decal's public IDecalCore.GetD3DDevice); Decal has swapped its vtable for a copy, so
/// d3d9.dll's original vtable is found by matching and d3d9's own EndScene is hooked
/// (DecalD3D9.TryResolve). A heap or image scan is not used: it can't tell AC's device
/// from the ones Decal plugins create (measured: it picked another device).
/// </summary>
public static void InstallWithoutDevice(string installSource)
{
if (_installed)
return;
ResetInstallState(installSource);
DecalD3D9.Enabled = true;
// Resolved (read-only) by EntryPoint before it chose this path; never Decal's code.
if (!DecalD3D9.TryResolve())
{
RynthLog.D3D9("EndSceneHook: FAILED - AC's device couldn't be identified through the Decal bridge; no in-game UI in this client.");
return;
}
RynthLog.D3D9($"EndSceneHook: hooking d3d9's own EndScene @ 0x{DecalD3D9.ResolvedEndScene.ToInt32():X8} ({DecalD3D9.Describe(DecalD3D9.ResolvedEndScene)}).");
InstallFromEndSceneAddress(DecalD3D9.ResolvedEndScene);
}
public static void InstallFromDevice(IntPtr pDevice)
{
if (_installed)
@ -161,6 +247,7 @@ internal static class EndSceneHook
// Let the render thread return through the trampoline.
Thread.Sleep(80);
DeviceResetHook.Uninstall();
EngineFrameController.Shutdown();
status = MinHook.MH_RemoveHook(_endSceneAddr);
@ -225,7 +312,12 @@ internal static class EndSceneHook
_skipCount++;
long offscreenElapsedMs = Environment.TickCount64 - _firstOffscreenTick;
if (_skipCount < MaxOffscreenSkipsBeforeFallback && offscreenElapsedMs < OffscreenFallbackDelayMs)
// Decal clients: Decal's views, VVS and UB render into their own targets every
// frame, so an offscreen EndScene is normal there and the fallback below would
// draw our UI (and nav rings) into their textures (measured 2026-09-30). Never
// fall back with Decal; without Decal nothing changes.
if (DecalD3D9.Enabled ||
(_skipCount < MaxOffscreenSkipsBeforeFallback && offscreenElapsedMs < OffscreenFallbackDelayMs))
return _originalEndScene!(pDevice);
_offscreenFilterDisabled = true;
@ -241,6 +333,8 @@ internal static class EndSceneHook
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)
{
@ -260,8 +354,16 @@ internal static class EndSceneHook
IntPtr actualEndScene = Marshal.ReadIntPtr(deviceVtable, DeviceVTableIndex.EndScene * IntPtr.Size);
bool match = actualEndScene == _endSceneAddr;
RynthLog.D3D9($"EndSceneHook: Device vtable EndScene=0x{actualEndScene:X8}, hooked=0x{_endSceneAddr:X8} — {(match ? "MATCH" : "MISMATCH")}");
if (DecalD3D9.Enabled)
DecalD3D9.FirstFrame(pDevice);
if (!match && actualEndScene != IntPtr.Zero)
if (!match && DecalD3D9.Enabled)
{
// Decal client: the device's slot is Decal's wrapper (we hooked d3d9's own
// EndScene, which that wrapper calls). Never rehook onto Decal's code.
RynthLog.D3D9($"EndSceneHook: mismatch expected with Decal (slot is {DecalD3D9.Describe(actualEndScene)}) - keeping the d3d9 hook.");
}
else if (!match && actualEndScene != IntPtr.Zero)
{
// Deep-audit finding #8 (2026-06-18): the old sequence
// disabled+REMOVED the old hook (freeing the trampoline
@ -303,11 +405,11 @@ internal static class EndSceneHook
{
if (!_warmupLogged)
{
RynthLog.D3D9($"EndSceneHook: Backbuffer detected. Warming up {UiInitWarmupFrames} frame(s) before UI init.");
RynthLog.D3D9($"EndSceneHook: Backbuffer detected. Warming up {WarmupFrames} frame(s) before UI init.");
_warmupLogged = true;
}
if (_renderCount < UiInitWarmupFrames)
if (_renderCount < WarmupFrames)
return _originalEndScene!(pDevice);
_uiActivated = true;
@ -324,7 +426,7 @@ internal static class EndSceneHook
if (_uiFrameCount == 60 && RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend)
RynthLog.D3D9("EndSceneHook: 60 UI frames - ImGui is stable.");
if (_renderCount == UiInitWarmupFrames && !RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend)
if (_renderCount == WarmupFrames && !RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend)
RynthLog.D3D9("EndSceneHook: ImGui backend disabled via engine.json (EnableImGuiBackend=false). Always-on engine work still runs; only ImGui draw calls are skipped.");
// Avalonia compositor: independent of ImGui. Reads the latest
@ -383,8 +485,8 @@ internal static class EndSceneHook
int targetFps = isFocused ? FpsTargetFocused : FpsTargetBackground;
double minFrameMs = 1000.0 / Math.Max(targetFps, 1);
while (_fpsTimer.Elapsed.TotalMilliseconds < minFrameMs)
Thread.Sleep(isFocused ? 0 : 1);
double leftMs = minFrameMs - _fpsTimer.Elapsed.TotalMilliseconds;
if (leftMs > 0) WaitFrame(leftMs);
_fpsTimer.Restart();
if (!_fpsLimiterLoggedOnce)

View file

@ -70,6 +70,33 @@ internal static unsafe class GameMatrixCapture
private static bool _loggedFirstCapture;
public static bool HasCapturedFrame => _hasValidViewProj;
// Landblock whose local frame the current view matrix is built in: the
// anchor (submission / player) landblock when the camera was shifted into
// it, else the viewer's own. Anything projecting a world point must first
// move that point into this landblock's frame (192 m per landblock step).
private static uint _frameLandblock;
/// <summary>
/// Landblock (cellId &gt;&gt; 16) whose local coordinates WorldToScreen expects,
/// as of the last CaptureFrame; 0 when unknown. AC's render thread.
/// </summary>
public static uint FrameLandblock => _frameLandblock;
// Camera position in the same frame as the view matrix (D3D axes: x = east,
// y = up, z = north, FrameLandblock-local), as of the last CaptureFrame.
private static float _camX, _camY, _camZ;
/// <summary>
/// The camera's position in WorldToScreen's frame (D3D axes, FrameLandblock-local).
/// False before the first capture. AC's render thread.
/// </summary>
public static bool TryGetCameraPosition(out float x, out float y, out float z)
{
x = _camX; y = _camY; z = _camZ;
return _hasValidViewProj;
}
public static uint ViewportWidth => _vpWidth;
public static uint ViewportHeight => _vpHeight;
@ -100,6 +127,10 @@ internal static unsafe class GameMatrixCapture
if (pMatrix != null && state == D3DTS_PROJECTION)
{
bool isPerspective = Math.Abs(pMatrix[11]) > 0.01f;
// Decal clients: a Virindi/Decal/UB 3D pass into its own render target must not
// replace AC's projection. Projection sets are rare; only checked with Decal.
if (isPerspective && DecalD3D9.Enabled && !ImGuiBackend.DX9Backend.IsRenderingToBackBuffer(dev))
isPerspective = false;
if (isPerspective)
{
for (int i = 0; i < 16; i++)
@ -198,6 +229,7 @@ internal static unsafe class GameMatrixCapture
uint viewerCellId = unchecked((uint)Marshal.ReadInt32(camFrame + CamCellIdOffset));
uint viewerLandblock = viewerCellId >> 16;
viewerLbForLog = viewerLandblock;
uint frameLandblock = viewerLandblock; // replaced by the anchor when the shift applies
// Prefer the landblock the plugin tick LOCKED IN when it submitted
// its Nav3D geometry (see Nav3DRenderer.ClearFrame). If we use the
@ -235,6 +267,7 @@ internal static unsafe class GameMatrixCapture
cx += dXBlocks * 192f; // EW shift back into player-landblock frame
cy += dYBlocks * 192f; // NS
shiftApplied = (dXBlocks != 0 || dYBlocks != 0);
frameLandblock = playerLandblock;
}
else
{
@ -299,6 +332,8 @@ internal static unsafe class GameMatrixCapture
RynthLog.D3D9($"GameMatrixCapture: viewport={_vpWidth}x{_vpHeight}");
}
_camX = px; _camY = py; _camZ = pz;
_frameLandblock = frameLandblock;
_hasValidViewProj = true;
}
@ -354,8 +389,8 @@ internal static unsafe class GameMatrixCapture
{
try
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
IntPtr setTransformAddr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.SetTransform * IntPtr.Size);
IntPtr setTransformAddr = DecalD3D9.HookTarget(pDevice, DeviceVTableIndex.SetTransform);
if (setTransformAddr == IntPtr.Zero) return; // Decal client and the slot isn't d3d9's: not hooked
_hookDelegate = new SetTransformD(SetTransformDetour);
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);

View file

@ -46,8 +46,8 @@ internal static class Nav3DRenderInjector
try
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
IntPtr addr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.DrawIndexedPrimitive * IntPtr.Size);
IntPtr addr = DecalD3D9.HookTarget(pDevice, DeviceVTableIndex.DrawIndexedPrimitive);
if (addr == IntPtr.Zero) return; // Decal client and the slot isn't d3d9's: not hooked
_hookDelegate = new DrawIndexedPrimitiveD(Detour);
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
@ -79,7 +79,11 @@ internal static class Nav3DRenderInjector
_seen3D = true;
// Detect 3D→UI transition: ZENABLE goes from 1→0 after 3D draws
if (!_markersRenderedThisFrame && _seen3D && _lastZEnable != 0 && zEnable == 0)
// Decal clients: VVS/Decal/UB draw 3D into their own render targets too; only AC's
// back buffer gets the markers and nameplates (measured 2026-09-30: without this they
// showed up inside a Virindi window). Evaluated only at a transition, and only with Decal.
if (!_markersRenderedThisFrame && _seen3D && _lastZEnable != 0 && zEnable == 0 &&
(!DecalD3D9.Enabled || ImGuiBackend.DX9Backend.IsRenderingToBackBuffer(dev)))
{
_markersRenderedThisFrame = true;
_inRender = true;
@ -90,6 +94,15 @@ internal static class Nav3DRenderInjector
catch
{
}
// The world overlays (nameplates, combat text) go here too, over the
// markers and under AC's UI. Its own frame flag: drawn at most once.
try
{
ImGuiBackend.UnderUiLayer.PresentAtTransition(dev);
}
catch
{
}
_inRender = false;
}

View file

@ -13,9 +13,11 @@
// invisible).
//
// Pattern:
// pump: BeginFrame() → AddX(...) × N → CommitFrame()
// render: reads from the "ready" buffer only; never touches "pending"
// CommitFrame atomically swaps the index reads see.
// pump: ClearFrame() → AddX(...) × N → CommitFrame()
// render: Ready once per draw, then reads only that buffer; never
// touches "pending"
// CommitFrame atomically swaps the buffer reads see. A tick during which the
// player crossed a landblock boundary is dropped (see CommitFrame).
// ═══════════════════════════════════════════════════════════════════════════
using System.Threading;
@ -34,7 +36,8 @@ internal static class Nav3DRenderer
private const float DefaultRingHeight = 0.5f; // back-compat default for AddRing
private sealed class NavBuffer
/// <summary>One tick's submissions. Render side: read-only.</summary>
internal sealed class NavBuffer
{
public readonly float[] RingX = new float[MaxRings];
public readonly float[] RingY = new float[MaxRings];
@ -99,38 +102,14 @@ internal static class Nav3DRenderer
// ── Render-side reads ────────────────────────────────────────────────────
public static int RingCount => _ready.RingCount;
public static int LineCount => _ready.LineCount;
public static int TriangleCount => _ready.TriCount;
public static void GetRing(int i, out float x, out float y, out float z,
out float radius, out float thickness, out float height, out uint color)
{
var r = _ready;
x = r.RingX[i]; y = r.RingY[i]; z = r.RingZ[i];
radius = r.RingRadius[i]; thickness = r.RingThick[i];
height = r.RingHeight[i]; color = r.RingColor[i];
}
public static void GetLine(int i, out float x1, out float y1, out float z1,
out float x2, out float y2, out float z2, out float thickness, out uint color)
{
var r = _ready;
x1 = r.LineX1[i]; y1 = r.LineY1[i]; z1 = r.LineZ1[i];
x2 = r.LineX2[i]; y2 = r.LineY2[i]; z2 = r.LineZ2[i];
thickness = r.LineThick[i]; color = r.LineColor[i];
}
public static void GetTriangle(int i, out float x1, out float y1, out float z1,
out float x2, out float y2, out float z2,
out float x3, out float y3, out float z3, out uint color)
{
var r = _ready;
x1 = r.TriX1[i]; y1 = r.TriY1[i]; z1 = r.TriZ1[i];
x2 = r.TriX2[i]; y2 = r.TriY2[i]; z2 = r.TriZ2[i];
x3 = r.TriX3[i]; y3 = r.TriY3[i]; z3 = r.TriZ3[i];
color = r.TriColor[i];
}
/// <summary>
/// The latest committed frame. Take it once per draw and read everything
/// from it: re-reading this (volatile) property per item would mix two
/// ticks if a commit landed mid-draw (a count from one, contents from the
/// other). The triple buffer keeps a taken frame untouched for a full
/// tick after it stops being ready.
/// </summary>
public static NavBuffer Ready => _ready;
// The landblock the plugin tick that produced the ready buffer was using.
// Render thread uses this for view-matrix shifting so geometry stays
@ -197,9 +176,26 @@ internal static class Nav3DRenderer
/// spare becomes the next pending. Render reads of the new ready buffer
/// become visible across cores via the volatile field. Called by
/// PluginManager.TickAll AFTER all plugins have submitted.
///
/// The pump runs off AC's thread, so the player can cross a landblock
/// boundary between ClearFrame and here. Plugins sample the pose during
/// their tick, so some of this tick's geometry may then be in the old
/// landblock's frame and some in the new one, while the frame is anchored
/// to the old — whatever was sampled after the crossing would draw 192 m
/// off for a tick. Such a tick is dropped: the previous frame stays ready
/// (one tick stale, consistent) and the next tick is anchored correctly.
/// </summary>
public static void CommitFrame()
{
uint anchored = _pending.SubmissionPlayerLandblock;
if (anchored != 0 &&
PlayerPhysicsHooks.TryGetPlayerPose(out uint cellId, out _, out _, out _, out _, out _, out _, out _) &&
(cellId >> 16) != 0 && (cellId >> 16) != anchored)
{
_pending.Reset();
return;
}
NavBuffer newReady = _pending;
NavBuffer newSpare = _ready;
NavBuffer newPending = _spare;

View file

@ -1,706 +0,0 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — D3D9/VitalHud.cs
//
// "Hot HUD" — draws player Health / Stamina / Mana bars directly in the D3D9
// EndScene path, on AC's render thread, every frame. Ported from RynthCore2's
// overlay/hud_overlay.cpp; the D3D9 plumbing mirrors TestRenderer.cs (cached
// vtable delegates + full render-state save/restore).
//
// Visuals: a translucent panel with a drop shadow, three gradient-filled bars
// (track + fill + gloss + border) with an HP/STAM/MANA label and a right-
// aligned "cur/max" number drawn from the dependency-free BitmapFont.
// Everything is colored 2D quads (D3DFVF_XYZRHW | D3DFVF_DIFFUSE, no texture)
// accumulated into one static vertex batch flushed with a single
// DrawPrimitiveUP — no per-frame heap allocation (avoids the LFH per-frame-
// alloc AV class).
//
// Interactive: drag the panel to move it, drag the bottom-right grip to resize.
// Win32Backend routes mouse messages to TryHandleMouse, which consumes the ones
// that land on the HUD so they never reach AC (no stray camera spin). Position +
// scale persist to %APPDATA%\RynthCore\vitalhud.cfg.
//
// Data source: Compatibility.PlayerVitalsHooks.TryGetSnapshot — the same
// buffed-effective values AC's own bars render, maintained on AC's main thread.
// Draw and TryHandleMouse both run on that thread (EndScene / WndProc), so the
// shared geometry state needs no cross-thread synchronization.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.D3D9;
internal static unsafe class VitalHud
{
// ─── D3D9 constants ───────────────────────────────────────────────
private const uint D3DFVF_XYZRHW = 0x0004;
private const uint D3DFVF_DIFFUSE = 0x0040;
private const uint HudFvf = D3DFVF_XYZRHW | D3DFVF_DIFFUSE;
private const uint D3DPT_TRIANGLELIST = 4;
// D3DRENDERSTATETYPE
private const uint D3DRS_ZENABLE = 7;
private const uint D3DRS_ZWRITEENABLE = 14;
private const uint D3DRS_ALPHATESTENABLE = 15;
private const uint D3DRS_SRCBLEND = 19;
private const uint D3DRS_DESTBLEND = 20;
private const uint D3DRS_CULLMODE = 22;
private const uint D3DRS_ALPHABLENDENABLE = 27;
private const uint D3DRS_FOGENABLE = 28;
private const uint D3DRS_STENCILENABLE = 52;
private const uint D3DRS_LIGHTING = 137;
private const uint D3DRS_COLORWRITEENABLE = 168;
private const uint D3DRS_BLENDOP = 171;
private const uint D3DRS_SCISSORTESTENABLE = 174;
// D3DTEXTURESTAGESTATETYPE
private const uint D3DTSS_COLOROP = 1;
private const uint D3DTSS_COLORARG1 = 2;
private const uint D3DTSS_ALPHAOP = 4;
private const uint D3DTSS_ALPHAARG1 = 6;
// values
private const uint D3DBLEND_SRCALPHA = 5;
private const uint D3DBLEND_INVSRCALPHA = 6;
private const uint D3DBLENDOP_ADD = 1;
private const uint D3DCULL_NONE = 1;
private const uint D3DTOP_DISABLE = 1;
private const uint D3DTOP_SELECTARG1 = 2;
private const uint D3DTA_DIFFUSE = 0;
// ─── Win32 messages + capture P/Invoke ────────────────────────────
private const uint WM_LBUTTONDOWN = 0x0201;
private const uint WM_LBUTTONUP = 0x0202;
private const uint WM_MOUSEMOVE = 0x0200;
[DllImport("user32.dll")]
private static extern IntPtr SetCapture(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ReleaseCapture();
// ─── Vertex ───────────────────────────────────────────────────────
[StructLayout(LayoutKind.Sequential)]
private struct Vertex
{
public float X, Y, Z, Rhw;
public uint Color; // ARGB
}
[StructLayout(LayoutKind.Sequential)]
private struct D3DVIEWPORT9
{
public uint X, Y, Width, Height;
public float MinZ, MaxZ;
}
// ─── Device method delegates (COM/stdcall) ────────────────────────
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetRenderStateDelegate(IntPtr dev, uint state, uint value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetRenderStateDelegate(IntPtr dev, uint state, out uint pValue);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetTextureStageStateDelegate(IntPtr dev, uint stage, uint type, uint value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetTextureStageStateDelegate(IntPtr dev, uint stage, uint type, out uint pValue);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetTextureDelegate(IntPtr dev, uint stage, IntPtr pTexture);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetTextureDelegate(IntPtr dev, uint stage, out IntPtr ppTexture);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetFVFDelegate(IntPtr dev, uint fvf);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetFVFDelegate(IntPtr dev, out uint fvf);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetVertexShaderDelegate(IntPtr dev, IntPtr pShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetVertexShaderDelegate(IntPtr dev, out IntPtr ppShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetPixelShaderDelegate(IntPtr dev, IntPtr pShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetPixelShaderDelegate(IntPtr dev, out IntPtr ppShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int DrawPrimitiveUPDelegate(IntPtr dev, uint primitiveType, uint primitiveCount, IntPtr pData, uint stride);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetViewportDelegate(IntPtr dev, out D3DVIEWPORT9 vp);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseComDelegate(IntPtr pUnk);
private static SetRenderStateDelegate? _setRenderState;
private static GetRenderStateDelegate? _getRenderState;
private static SetTextureStageStateDelegate? _setTextureStageState;
private static GetTextureStageStateDelegate? _getTextureStageState;
private static SetTextureDelegate? _setTexture;
private static GetTextureDelegate? _getTexture;
private static SetFVFDelegate? _setFVF;
private static GetFVFDelegate? _getFVF;
private static SetVertexShaderDelegate? _setVertexShader;
private static GetVertexShaderDelegate? _getVertexShader;
private static SetPixelShaderDelegate? _setPixelShader;
private static GetPixelShaderDelegate? _getPixelShader;
private static DrawPrimitiveUPDelegate? _drawPrimitiveUP;
private static GetViewportDelegate? _getViewport;
private static bool _delegatesCached;
// ─── Geometry / interaction state (AC main thread only) ───────────
private const float MinScale = 0.6f;
private const float MaxScale = 2.5f;
private static float _hudX = 16f, _hudY = 16f, _scale = 1f;
private static float _vpW, _vpH; // last viewport, for input clamp
private static bool _geomInit;
private static bool _firstDrawLogged;
private static int _dragMode; // 0 none, 1 move, 2 resize
private static float _grabDX, _grabDY;
private static float _resizeStartScale = 1f, _resizeStartDist = 1f;
/// <summary>True while the user is dragging or resizing the HUD. Win32Backend
/// keeps routing mouse messages to <see cref="TryHandleMouse"/> while set.</summary>
public static bool IsDragging => _dragMode != 0;
// ─── Vertex batch (single static buffer; no per-frame heap alloc) ──
// Text is the big consumer — the outline pass below draws each number 9×.
private const int MaxVerts = 48000;
private static readonly Vertex[] _batch = new Vertex[MaxVerts];
private static int _batchCount;
// Cached text sink + color so BitmapFont.Emit allocates nothing per call.
private static readonly BitmapFont.CellSink _cellSink = TextCell;
private static uint _textColor;
// ─── Layout derived from the uniform scale ────────────────────────
private struct Metrics
{
public float Scale, Pad, BarW, BarH, Gap, PanelW, PanelH, Grip;
}
private static Metrics Metric(float s)
{
if (s < MinScale) s = MinScale;
if (s > MaxScale) s = MaxScale;
Metrics m;
m.Scale = s;
m.Pad = 8f * s;
m.BarW = 228f * s; // wide enough for a big "cur/max" number
m.BarH = 26f * s; // taller bars → bigger, retail-legible numbers
m.Gap = 6f * s;
m.PanelW = m.Pad * 2f + m.BarW;
m.PanelH = m.Pad * 2f + m.BarH * 3f + m.Gap * 2f;
m.Grip = 16f * s;
return m;
}
// ─── Color helpers ────────────────────────────────────────────────
private static uint Argb(int a, int r, int g, int b)
=> ((uint)a << 24) | ((uint)r << 16) | ((uint)g << 8) | (uint)b;
private static uint Lighten(uint c, int add)
{
static int Cl(int v) => v < 0 ? 0 : (v > 255 ? 255 : v);
int a = (int)((c >> 24) & 0xFF);
int r = (int)((c >> 16) & 0xFF);
int g = (int)((c >> 8) & 0xFF);
int b = (int)(c & 0xFF);
return Argb(a, Cl(r + add), Cl(g + add), Cl(b + add));
}
// ─── Batch builders ───────────────────────────────────────────────
private static void BatchReset() => _batchCount = 0;
private static void PushQuad(float x0, float y0, float x1, float y1,
uint cTL, uint cTR, uint cBR, uint cBL)
{
if (_batchCount + 6 > MaxVerts) return;
Set(ref _batch[_batchCount + 0], x0, y0, cTL);
Set(ref _batch[_batchCount + 1], x1, y0, cTR);
Set(ref _batch[_batchCount + 2], x1, y1, cBR);
Set(ref _batch[_batchCount + 3], x0, y0, cTL);
Set(ref _batch[_batchCount + 4], x1, y1, cBR);
Set(ref _batch[_batchCount + 5], x0, y1, cBL);
_batchCount += 6;
static void Set(ref Vertex v, float x, float y, uint c)
{
v.X = x; v.Y = y; v.Z = 0f; v.Rhw = 1f; v.Color = c;
}
}
private static void PushRect(float x0, float y0, float x1, float y1, uint c)
=> PushQuad(x0, y0, x1, y1, c, c, c, c);
private static void PushVGrad(float x0, float y0, float x1, float y1, uint top, uint bot)
=> PushQuad(x0, y0, x1, y1, top, top, bot, bot);
// ─── Text → batched quads via the bitmap font ─────────────────────
private static void TextCell(int x0, int y0, int x1, int y1)
=> PushRect(x0, y0, x1, y1, _textColor);
// Draws text with a full dark outline (all 8 neighbour offsets) then the
// foreground on top, so it stays legible over any bar fill color — the
// single drop-shadow was washed out on the light (yellow) bar.
private static void DrawText(ReadOnlySpan<char> s, int x, int y, int cellPx, uint color)
{
int o = cellPx >= 4 ? 2 : 1; // outline thickness in px
_textColor = Argb(235, 0, 0, 0);
BitmapFont.Emit(s, x - o, y - o, cellPx, _cellSink);
BitmapFont.Emit(s, x, y - o, cellPx, _cellSink);
BitmapFont.Emit(s, x + o, y - o, cellPx, _cellSink);
BitmapFont.Emit(s, x - o, y, cellPx, _cellSink);
BitmapFont.Emit(s, x + o, y, cellPx, _cellSink);
BitmapFont.Emit(s, x - o, y + o, cellPx, _cellSink);
BitmapFont.Emit(s, x, y + o, cellPx, _cellSink);
BitmapFont.Emit(s, x + o, y + o, cellPx, _cellSink);
_textColor = color;
BitmapFont.Emit(s, x, y, cellPx, _cellSink);
}
// "cur/max" formatted into the caller's buffer without allocating; returns
// the number of chars written (≤ buf.Length).
private static int FormatVital(uint cur, uint mx, Span<char> buf)
{
int len = 0;
if (cur.TryFormat(buf, out int w1)) len += w1;
if (len < buf.Length) buf[len++] = '/';
if (mx.TryFormat(buf.Slice(len), out int w2)) len += w2;
return len;
}
private static void EmitBar(float x, float y, in Metrics m,
uint cur, uint mx, uint baseColor)
{
float w = m.BarW, h = m.BarH;
PushRect(x, y, x + w, y + h, Argb(205, 18, 20, 26)); // track
if (mx > 0)
{
float ratio = (float)cur / mx;
if (ratio < 0f) ratio = 0f;
if (ratio > 1f) ratio = 1f;
float fw = w * ratio;
PushVGrad(x, y, x + fw, y + h, Lighten(baseColor, 55), baseColor); // fill
PushRect(x, y, x + fw, y + h * 0.32f, Argb(60, 255, 255, 255)); // gloss
}
float bw = m.Scale >= 1.5f ? 2f : 1f; // border
uint bc = Argb(180, 90, 100, 120);
PushRect(x, y, x + w, y + bw, bc);
PushRect(x, y + h - bw, x + w, y + h, bc);
PushRect(x, y, x + bw, y + h, bc);
PushRect(x + w - bw, y, x + w, y + h, bc);
// Number only (no label — the red/yellow/blue color identifies the bar).
// Sized as large as fits the bar, centered, with a dark outline so it
// reads clearly over any fill color (especially white-on-yellow).
Span<char> numBuf = stackalloc char[24];
ReadOnlySpan<char> num = numBuf[..FormatVital(cur, mx, numBuf)];
int innerPad = (int)(m.Pad * 0.4f);
if (innerPad < 2) innerPad = 2;
int availW = (int)w - 2 * innerPad;
int cellPx = (int)(h * 0.82f / BitmapFont.GlyphH); // tallest that fits the bar
if (cellPx < 1) cellPx = 1;
while (cellPx > 1 && BitmapFont.MeasureWidth(num, cellPx) > availW) cellPx--;
int tw = BitmapFont.MeasureWidth(num, cellPx);
int th = BitmapFont.Height(cellPx);
int tx = (int)(x + (w - tw) * 0.5f); // center horizontally
int ty = (int)(y + (h - th) * 0.5f); // center vertically
DrawText(num, tx, ty, cellPx, Argb(255, 245, 250, 255));
}
// ─── Public API ───────────────────────────────────────────────────
public static void Draw(IntPtr pDevice)
{
if (pDevice == IntPtr.Zero) return;
if (!PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot snap)) return;
if (!_delegatesCached)
CacheDelegates(pDevice);
if (_drawPrimitiveUP == null) return; // delegate cache failed
if (_getViewport!(pDevice, out D3DVIEWPORT9 vp) < 0) return;
float wF = vp.Width;
float hF = vp.Height;
if (wF < 1f || hF < 1f) return;
if (!_firstDrawLogged)
{
_firstDrawLogged = true;
RynthLog.D3D9("VitalHud: first draw.");
}
// First-draw placement: prefer the saved config, else default top-right.
if (!_geomInit)
{
_geomInit = true;
if (LoadCfg(out float lx, out float ly, out float ls))
{
_scale = ls; _hudX = lx; _hudY = ly;
}
else
{
_scale = 1f;
Metrics dm = Metric(1f);
_hudX = wF - dm.PanelW - 16f;
_hudY = 16f;
}
}
// ── Save the device state we are about to clobber ──────────────
_getRenderState!(pDevice, D3DRS_ZENABLE, out uint svZE);
_getRenderState(pDevice, D3DRS_ZWRITEENABLE, out uint svZWE);
_getRenderState(pDevice, D3DRS_ALPHATESTENABLE, out uint svATE);
_getRenderState(pDevice, D3DRS_ALPHABLENDENABLE, out uint svABE);
_getRenderState(pDevice, D3DRS_SRCBLEND, out uint svSB);
_getRenderState(pDevice, D3DRS_DESTBLEND, out uint svDB);
_getRenderState(pDevice, D3DRS_BLENDOP, out uint svBO);
_getRenderState(pDevice, D3DRS_CULLMODE, out uint svCull);
_getRenderState(pDevice, D3DRS_LIGHTING, out uint svLit);
_getRenderState(pDevice, D3DRS_FOGENABLE, out uint svFog);
_getRenderState(pDevice, D3DRS_STENCILENABLE, out uint svSte);
_getRenderState(pDevice, D3DRS_SCISSORTESTENABLE, out uint svSci);
_getRenderState(pDevice, D3DRS_COLORWRITEENABLE, out uint svCW);
_getFVF!(pDevice, out uint svFvf);
_getTextureStageState!(pDevice, 0, D3DTSS_COLOROP, out uint svT0CO);
_getTextureStageState(pDevice, 0, D3DTSS_COLORARG1, out uint svT0CA1);
_getTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, out uint svT0AO);
_getTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, out uint svT0AA1);
_getTextureStageState(pDevice, 1, D3DTSS_COLOROP, out uint svT1CO);
_getVertexShader!(pDevice, out IntPtr svVS);
_getPixelShader!(pDevice, out IntPtr svPS);
_getTexture!(pDevice, 0, out IntPtr svTex0);
try
{
// ── Set HUD state: 2D, alpha-blended, colored verts, no tex/shaders ──
_setRenderState!(pDevice, D3DRS_ZENABLE, 0);
_setRenderState(pDevice, D3DRS_ZWRITEENABLE, 0);
_setRenderState(pDevice, D3DRS_ALPHATESTENABLE, 0);
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, 1);
_setRenderState(pDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
_setRenderState(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
_setRenderState(pDevice, D3DRS_BLENDOP, D3DBLENDOP_ADD);
_setRenderState(pDevice, D3DRS_CULLMODE, D3DCULL_NONE);
_setRenderState(pDevice, D3DRS_LIGHTING, 0);
_setRenderState(pDevice, D3DRS_FOGENABLE, 0);
_setRenderState(pDevice, D3DRS_STENCILENABLE, 0);
_setRenderState(pDevice, D3DRS_SCISSORTESTENABLE, 0);
_setRenderState(pDevice, D3DRS_COLORWRITEENABLE, 0xF);
_setTextureStageState!(pDevice, 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
_setTextureStageState(pDevice, 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE);
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
_setTextureStageState(pDevice, 1, D3DTSS_COLOROP, D3DTOP_DISABLE);
_setTexture!(pDevice, 0, IntPtr.Zero);
_setVertexShader!(pDevice, IntPtr.Zero);
_setPixelShader!(pDevice, IntPtr.Zero);
_setFVF!(pDevice, HudFvf);
BuildBatch(in snap, wF, hF);
if (_batchCount >= 3)
{
fixed (Vertex* p = _batch)
{
_drawPrimitiveUP(pDevice, D3DPT_TRIANGLELIST,
(uint)(_batchCount / 3), (IntPtr)p, (uint)sizeof(Vertex));
}
}
_vpW = wF; // for input hit-test clamping
_vpH = hF;
}
finally
{
// ── Restore the saved state ────────────────────────────────
_setRenderState!(pDevice, D3DRS_ZENABLE, svZE);
_setRenderState(pDevice, D3DRS_ZWRITEENABLE, svZWE);
_setRenderState(pDevice, D3DRS_ALPHATESTENABLE, svATE);
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, svABE);
_setRenderState(pDevice, D3DRS_SRCBLEND, svSB);
_setRenderState(pDevice, D3DRS_DESTBLEND, svDB);
_setRenderState(pDevice, D3DRS_BLENDOP, svBO);
_setRenderState(pDevice, D3DRS_CULLMODE, svCull);
_setRenderState(pDevice, D3DRS_LIGHTING, svLit);
_setRenderState(pDevice, D3DRS_FOGENABLE, svFog);
_setRenderState(pDevice, D3DRS_STENCILENABLE, svSte);
_setRenderState(pDevice, D3DRS_SCISSORTESTENABLE, svSci);
_setRenderState(pDevice, D3DRS_COLORWRITEENABLE, svCW);
_setTextureStageState!(pDevice, 0, D3DTSS_COLOROP, svT0CO);
_setTextureStageState(pDevice, 0, D3DTSS_COLORARG1, svT0CA1);
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, svT0AO);
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, svT0AA1);
_setTextureStageState(pDevice, 1, D3DTSS_COLOROP, svT1CO);
_setFVF!(pDevice, svFvf);
_setVertexShader!(pDevice, svVS);
_setPixelShader!(pDevice, svPS);
_setTexture!(pDevice, 0, svTex0);
// GetVertexShader / GetPixelShader / GetTexture each AddRef — release.
ReleaseCom(svVS);
ReleaseCom(svPS);
ReleaseCom(svTex0);
}
}
private static void BuildBatch(in PlayerVitalsSnapshot snap, float wF, float hF)
{
Metrics m = Metric(_scale);
float px = _hudX;
float py = _hudY;
if (px > wF - m.PanelW) px = wF - m.PanelW; // keep on-screen (draw-only)
if (py > hF - m.PanelH) py = hF - m.PanelH;
if (px < 0f) px = 0f;
if (py < 0f) py = 0f;
BatchReset();
float so = 5f * m.Scale; // shadow
PushRect(px + so, py + so, px + m.PanelW + so, py + m.PanelH + so, Argb(110, 0, 0, 0));
PushVGrad(px, py, px + m.PanelW, py + m.PanelH, // backing
Argb(205, 28, 30, 38), Argb(205, 16, 17, 22));
PushRect(px, py, px + m.PanelW, py + m.Pad * 0.6f, Argb(45, 255, 255, 255)); // header hint
float pbw = m.Scale >= 1.5f ? 2f : 1f; // panel border
uint pbc = Argb(200, 120, 130, 150);
PushRect(px, py, px + m.PanelW, py + pbw, pbc);
PushRect(px, py + m.PanelH - pbw, px + m.PanelW, py + m.PanelH, pbc);
PushRect(px, py, px + pbw, py + m.PanelH, pbc);
PushRect(px + m.PanelW - pbw, py, px + m.PanelW, py + m.PanelH, pbc);
float bx = px + m.Pad;
float by = py + m.Pad;
EmitBar(bx, by, in m, snap.Health, snap.MaxHealth, Argb(235, 200, 45, 45));
by += m.BarH + m.Gap;
EmitBar(bx, by, in m, snap.Stamina, snap.MaxStamina, Argb(235, 205, 170, 45));
by += m.BarH + m.Gap;
EmitBar(bx, by, in m, snap.Mana, snap.MaxMana, Argb(235, 55, 115, 235));
// resize grip (three dots) bottom-right
float d = 3f * m.Scale;
if (d < 2f) d = 2f;
float gx = px + m.PanelW - m.Pad * 0.5f;
float gy = py + m.PanelH - m.Pad * 0.5f;
uint gc = Argb(200, 200, 205, 215);
for (int i = 1; i <= 3; i++)
{
float ox = gx - i * (d + 1f);
float oy = gy - i * (d + 1f);
PushRect(ox, oy, ox + d, oy + d, gc);
}
}
// ─── Input ────────────────────────────────────────────────────────
/// <summary>
/// Handles left-button drag (anywhere on the panel) + grip resize. Returns
/// true when the message landed on the HUD and should be swallowed so it
/// never reaches AC. Called from Win32Backend.WndProcHook on AC's main
/// thread, before the Avalonia forward. No-op (returns false) when the HUD
/// is not being drawn.
/// </summary>
public static bool TryHandleMouse(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
if (!_geomInit || !EngineSettings.DrawCustomVitalBars)
return false;
switch (msg)
{
case WM_LBUTTONDOWN:
{
float mxf = (short)((long)lParam & 0xFFFF);
float myf = (short)(((long)lParam >> 16) & 0xFFFF);
Metrics m = Metric(_scale);
// Clamp the same way Draw does so the hit-test matches the pixels.
float px = _hudX, py = _hudY;
if (_vpW > 0f && px > _vpW - m.PanelW) px = _vpW - m.PanelW;
if (_vpH > 0f && py > _vpH - m.PanelH) py = _vpH - m.PanelH;
if (px < 0f) px = 0f;
if (py < 0f) py = 0f;
bool inPanel = mxf >= px && mxf <= px + m.PanelW &&
myf >= py && myf <= py + m.PanelH;
if (!inPanel) return false;
// Pin the (clamped) top-left so move/resize anchor to the pixels.
_hudX = px; _hudY = py;
bool inGrip = mxf >= px + m.PanelW - m.Grip && myf >= py + m.PanelH - m.Grip;
if (inGrip)
{
float dx = mxf - px, dy = myf - py;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist < 8f) dist = 8f;
_resizeStartDist = dist;
_resizeStartScale = m.Scale;
_dragMode = 2;
}
else
{
_grabDX = mxf - px;
_grabDY = myf - py;
_dragMode = 1;
}
SetCapture(hWnd);
return true;
}
case WM_MOUSEMOVE:
{
if (_dragMode == 0) return false;
// Left button no longer held (we missed the UP — e.g. capture
// stolen by alt-tab): end the drag and let the move through so the
// HUD can't get stuck following the cursor.
if (((long)wParam & 0x0001 /* MK_LBUTTON */) == 0)
{
_dragMode = 0;
ReleaseCapture();
SaveCfg();
return false;
}
float mxf = (short)((long)lParam & 0xFFFF);
float myf = (short)(((long)lParam >> 16) & 0xFFFF);
if (_dragMode == 1) // move
{
float nx = mxf - _grabDX;
float ny = myf - _grabDY;
Metrics m = Metric(_scale);
if (_vpW > 0f && nx > _vpW - m.PanelW) nx = _vpW - m.PanelW;
if (_vpH > 0f && ny > _vpH - m.PanelH) ny = _vpH - m.PanelH;
if (nx < 0f) nx = 0f;
if (ny < 0f) ny = 0f;
_hudX = nx; _hudY = ny;
}
else // resize
{
float dx = mxf - _hudX, dy = myf - _hudY;
float dist = MathF.Sqrt(dx * dx + dy * dy);
float s = _resizeStartScale * dist / _resizeStartDist;
if (s < MinScale) s = MinScale;
if (s > MaxScale) s = MaxScale;
_scale = s;
}
return true;
}
case WM_LBUTTONUP:
{
if (_dragMode == 0) return false;
_dragMode = 0;
ReleaseCapture();
SaveCfg();
return true;
}
default:
return false;
}
}
// ─── Persistence: %APPDATA%\RynthCore\vitalhud.cfg ("x y scale") ──
private static string? CfgPath()
{
string? appData = Environment.GetEnvironmentVariable("APPDATA");
if (string.IsNullOrEmpty(appData)) return null;
return Path.Combine(appData, "RynthCore", "vitalhud.cfg");
}
private static bool LoadCfg(out float x, out float y, out float s)
{
x = 0f; y = 0f; s = 1f;
try
{
string? path = CfgPath();
if (path == null || !File.Exists(path)) return false;
string[] parts = File.ReadAllText(path)
.Split([' ', '\t', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 3) return false;
if (!float.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out float fx) ||
!float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out float fy) ||
!float.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out float fs))
return false;
if (fs < MinScale) fs = MinScale;
if (fs > MaxScale) fs = MaxScale;
if (fx < 0f) fx = 0f;
if (fy < 0f) fy = 0f;
x = fx; y = fy; s = fs;
return true;
}
catch (Exception ex)
{
RynthLog.D3D9($"VitalHud: LoadCfg failed - {ex.Message}");
return false;
}
}
private static void SaveCfg()
{
try
{
string? path = CfgPath();
if (path == null) return;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string body = string.Format(CultureInfo.InvariantCulture, "{0:F1} {1:F1} {2:F4}", _hudX, _hudY, _scale);
File.WriteAllText(path, body);
}
catch (Exception ex)
{
RynthLog.D3D9($"VitalHud: SaveCfg failed - {ex.Message}");
}
}
// ─── Internals ────────────────────────────────────────────────────
private static void CacheDelegates(IntPtr pDevice)
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
_setRenderState = Get<SetRenderStateDelegate>(vtable, DeviceVTableIndex.SetRenderState);
_getRenderState = Get<GetRenderStateDelegate>(vtable, DeviceVTableIndex.GetRenderState);
_setTextureStageState = Get<SetTextureStageStateDelegate>(vtable, DeviceVTableIndex.SetTextureStageState);
_getTextureStageState = Get<GetTextureStageStateDelegate>(vtable, DeviceVTableIndex.GetTextureStageState);
_setTexture = Get<SetTextureDelegate>(vtable, DeviceVTableIndex.SetTexture);
_getTexture = Get<GetTextureDelegate>(vtable, DeviceVTableIndex.GetTexture);
_setFVF = Get<SetFVFDelegate>(vtable, DeviceVTableIndex.SetFVF);
_getFVF = Get<GetFVFDelegate>(vtable, DeviceVTableIndex.GetFVF);
_setVertexShader = Get<SetVertexShaderDelegate>(vtable, DeviceVTableIndex.SetVertexShader);
_getVertexShader = Get<GetVertexShaderDelegate>(vtable, DeviceVTableIndex.GetVertexShader);
_setPixelShader = Get<SetPixelShaderDelegate>(vtable, DeviceVTableIndex.SetPixelShader);
_getPixelShader = Get<GetPixelShaderDelegate>(vtable, DeviceVTableIndex.GetPixelShader);
_drawPrimitiveUP = Get<DrawPrimitiveUPDelegate>(vtable, DeviceVTableIndex.DrawPrimitiveUP);
_getViewport = Get<GetViewportDelegate>(vtable, DeviceVTableIndex.GetViewport);
_delegatesCached = true;
RynthLog.D3D9("VitalHud: D3D9 delegates cached.");
}
private static T Get<T>(IntPtr vtable, int index) where T : Delegate
{
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(addr);
}
private static void ReleaseCom(IntPtr pUnk)
{
if (pUnk == IntPtr.Zero) return;
IntPtr vtbl = Marshal.ReadIntPtr(pUnk);
IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size); // IUnknown::Release
var release = Marshal.GetDelegateForFunctionPointer<ReleaseComDelegate>(releaseAddr);
release(pUnk);
}
}

View file

@ -7,8 +7,7 @@
//
// 1. EndSceneHook.Uninstall — chains into EngineFrameController.Shutdown which
// tears down PluginManager (RynthPluginShutdown + FreeLibrary plugins),
// OverlayTextureRenderer, ViewportRendererBackend, ViewportPlatformBackend,
// DX9Backend, Win32Backend (restores WndProc), and destroys ImGui context.
// OverlayTextureRenderer, DX9Backend, and destroys the ImGui context.
// 2. Drain — sleep so any in-flight EndScene call has returned through the
// trampoline before we tear down anything else.
// 3. AvaloniaOverlay.Stop — Dispatcher shutdown, join STA thread.
@ -106,6 +105,15 @@ internal static class EngineLifecycle
RynthLog.Info("EngineLifecycle: Shutdown beginning.");
// A reload can come while this generation is still initializing (two RL clicks,
// or a file-watcher reload during login). Let InitWorker reach its next step and
// stop before tearing anything down under it.
Step("InitWorker join", () =>
{
if (!EntryPoint.WaitForInitWorker(15000))
RynthLog.Info("EngineLifecycle: InitWorker still running after 15 s; tearing down anyway.");
});
// Stop the hang watchdog BEFORE its beat source (the EndScene detour)
// is uninstalled. A still-running old-generation watchdog sees the beat
// go silent, declares a false hang ~4s later, suspends AC's healthy main
@ -121,6 +129,10 @@ internal static class EngineLifecycle
// 2026-06-11 DINPUT8 reload wedge.
Step("AcMainThreadQueue.Disarm", () => Compatibility.AcMainThreadQueue.Disarm());
// Same for queued panel commands (UI.Data.UiDataHub): never run a
// plugin-mutating UI command while the plugins are shutting down.
Step("UiDataHub.Disarm", () => UI.Data.UiDataHub.Disarm());
Step("EndSceneHook.Uninstall", () => EndSceneHook.Uninstall());
// Give in-flight EndScene calls a chance to drain. AC's render thread
@ -151,6 +163,12 @@ internal static class EngineLifecycle
// Otherwise the pump's TickAll/ProcessPendingActions can be mid-call
// into a plugin whose code pages we're about to unmap → AV.
Step("TickPump.StopAndJoin", () => EntryPoint.StopTickPumpAndJoin());
// spike/decal-bridge: after the pump (its only reader) has stopped.
Step("DecalBridgeHost.Shutdown", () => Compatibility.DecalBridgeHost.Shutdown());
// 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("PluginManager.ShutdownAll (defensive)", () => PluginManager.ShutdownAll());
@ -161,6 +179,14 @@ internal static class EngineLifecycle
// module's code at the moment of FreeLibrary.
Step("HeartbeatLogger.StopAndJoin", () => Compatibility.HeartbeatLogger.StopAndJoin());
// Every other engine thread (init, pumps, login helpers, D3D9 bootstrap...).
// Their sleeps wake at once; a thread still running engine code afterwards
// keeps this generation from unloading under the CoreCLR host.
Step("EngineThreads.StopAndJoinAll", () => EngineThreads.StopAndJoinAll(3000));
// Process-wide events: under CoreCLR they would hold this generation.
Step("EntryPoint.UninstallManagedExceptionHandlers", EntryPoint.UninstallManagedExceptionHandlers);
Step("MH_DisableHook(ALL)", () =>
{
// DisableHook restores the original code at every hooked function — that's
@ -175,6 +201,10 @@ internal static class EngineLifecycle
RynthLog.Info($"MH_DisableHook(ALL) = {MinHook.StatusString(disable)}");
});
// Managed plugins' contexts go last: nothing in the engine may call into them
// after this (every thread is joined, the hooks are off).
Step("ManagedPlugins.UnloadRetired", ManagedPlugins.UnloadRetired);
Volatile.Write(ref _hasShutDown, 1);
RynthLog.Info("EngineLifecycle: Shutdown complete.");
}

View file

@ -0,0 +1,78 @@
// ============================================================================
// RynthCore.Engine - EngineThreads.cs
//
// Every long-lived thread the engine starts goes through here, so shutdown can wake
// them and join them. Under the CoreCLR host (docs/UNLOADABLE_ENGINE_PLAN.md) a
// thread with a frame in engine code keeps the whole engine generation from
// unloading; under NativeAOT it keeps running old code after a reload. Either way
// EngineLifecycle.Shutdown must leave none behind.
//
// Loops sleep with EngineThreads.Sleep(ms), which returns false (at once) when the
// engine is shutting down: `if (!EngineThreads.Sleep(250)) return;`.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Threading;
namespace RynthCore.Engine;
internal static class EngineThreads
{
private static readonly object Sync = new();
private static readonly List<Thread> Threads = new();
private static readonly ManualResetEvent StopEvent = new(false);
/// <summary>True once shutdown has asked every engine thread to stop.</summary>
public static bool Stopping => StopEvent.WaitOne(0);
/// <summary>Starts a background thread the engine's shutdown will wait for.</summary>
public static Thread Start(string name, ThreadStart body, ApartmentState apartment = ApartmentState.Unknown)
{
var thread = new Thread(body) { Name = name, IsBackground = true };
if (apartment != ApartmentState.Unknown)
thread.SetApartmentState(apartment);
Track(thread);
thread.Start();
return thread;
}
/// <summary>Registers a thread created elsewhere (call before Start).</summary>
public static void Track(Thread thread)
{
lock (Sync)
{
Threads.RemoveAll(t => t.ThreadState.HasFlag(ThreadState.Stopped));
Threads.Add(thread);
}
}
/// <summary>Sleeps; false (immediately) once the engine is shutting down.</summary>
public static bool Sleep(int milliseconds) => !StopEvent.WaitOne(Math.Max(0, milliseconds));
public static bool Sleep(TimeSpan duration) => Sleep((int)Math.Min(int.MaxValue, duration.TotalMilliseconds));
/// <summary>
/// Wakes every tracked thread and waits up to <paramref name="budgetMs"/> in total for
/// them to finish. Logs the ones still running: each keeps its engine generation alive.
/// </summary>
public static void StopAndJoinAll(int budgetMs)
{
StopEvent.Set();
List<Thread> threads;
lock (Sync) threads = new List<Thread>(Threads);
long deadline = Environment.TickCount64 + budgetMs;
var stuck = new List<string>();
foreach (Thread t in threads)
{
if (t == Thread.CurrentThread) continue;
int remaining = (int)Math.Max(0, deadline - Environment.TickCount64);
if (!t.Join(remaining))
stuck.Add(t.Name ?? $"#{t.ManagedThreadId}");
}
RynthLog.Info(stuck.Count == 0
? $"EngineThreads: all {threads.Count} engine thread(s) finished."
: $"EngineThreads: {stuck.Count} of {threads.Count} thread(s) still running after {budgetMs} ms: {string.Join(", ", stuck)}");
}
}

View file

@ -39,8 +39,11 @@ public static class EntryPoint
private static int _initCount;
private static bool _imGuiResolverConfigured;
private static IntPtr _imGuiNativeHandle;
/// <summary>Module handle of the loaded cimgui.dll (zero until preloaded).</summary>
internal static IntPtr ImGuiNativeHandle => _imGuiNativeHandle;
private static readonly object LogLock = new();
private static readonly Queue<string> RecentLogLines = new();
private static long _recentLogSeq;
/// <summary>Set true to enable verbose startup logging (hook ready messages, plugin lifecycle, etc.).</summary>
internal static bool VerboseLogging = false;
@ -63,6 +66,24 @@ public static class EntryPoint
/// from inside an EndScene detour — the caller should run on a background
/// thread so the render thread's call into our hook can return cleanly.
/// </summary>
/// <summary>
/// The loader refused a hot-reload because this client is short of address
/// space (each reload keeps the old engine and plugins mapped). Says so in
/// chat. Loader thread.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthCoreReloadRefused")]
public static uint ReloadRefused(int freeMb)
{
try
{
RynthLog.Warn($"Hot-reload refused by the loader: {freeMb} MB of address space free.");
Compatibility.AcMainThreadQueue.EnqueueWriteToChat(
$"[RynthCore] A new RynthCore build is ready but wasn't loaded: this client has only {freeMb} MB of memory address space left, and reloading could crash it. Restart the client to use the new build.", 2);
}
catch { }
return 0;
}
[UnmanagedCallersOnly(EntryPoint = "RynthCoreShutdown")]
public static uint Shutdown(IntPtr lpParam)
{
@ -149,18 +170,16 @@ public static class EntryPoint
// and our VEH (NativeAOT __fastfail, AC self-exit on disconnect,
// etc.). Install early so we catch even very-early-startup kills.
RunInitStep("early process-exit hooks", ProcessExitHooks.Initialize);
// Logs the text of any message box (AC shows some errors in one on
// its main thread, which then looks like a wedge to the watchdog).
RunInitStep("message-box hooks", MessageBoxHooks.Initialize);
// Heartbeat: one log line per second so we have a hard upper-bound
// timestamp for when AC went silent if it dies via a path our
// termination hooks don't catch (kernel-level kill, int 0x29 not
// routed through RtlFailFast, hardware fault, etc.).
RunInitStep("heartbeat logger", HeartbeatLogger.Start);
var thread = new Thread(InitWorker)
{
Name = "RynthCore.Init",
IsBackground = true
};
thread.Start();
_initThread = EngineThreads.Start("RynthCore.Init", InitWorker);
return 0;
}
@ -204,6 +223,13 @@ public static class EntryPoint
// GetModuleHandleA("RynthCore.Engine.dll") fails when the loader has
// staged us under a unique filename (RynthCore.Engine.gen2.dll etc.)
// for hot-reload, so this is the path that always works.
#if ENGINE_CORECLR
// A managed engine is an assembly, not a module: the loader staged it and the
// Shim loaded it from that path.
string location = typeof(EntryPoint).Assembly.Location;
if (!string.IsNullOrEmpty(location))
return location;
#endif
IntPtr hEngine = IntPtr.Zero;
try
{
@ -499,6 +525,14 @@ public static class EntryPoint
RynthLog.Info("WARNING: cimgui runtime not found - ImGui will not be available.");
RynthLog.Info(" Ship RynthCore.cimgui.dll (or cimgui.dll) alongside RynthCore.Engine.dll");
}
else if (Plugins.EngineSettings.EnableImGuiBackend)
{
// Read the ImGui font files and the panel state here, off AC's
// render thread (the ImGui faces read both from memory).
ImGuiBackend.ImGuiFonts.Preload();
UI.PanelStateStore.TryGetPanel("", out _);
UI.PanelFaceStore.TryGet("", out _);
}
if (!Plugins.EngineSettings.EnableEngine)
{
@ -510,13 +544,44 @@ public static class EntryPoint
// user has dropped a candidate-string list at
// %APPDATA%\RynthCore\string_anchors.txt — otherwise no-ops.
// No hooks installed, no AC code modified; pure pattern read.
StringAnchorDiagnostic.RunIfConfigured();
// A diagnostic (runs when its config file exists); ~0.8 s of scanning, so the
// first load does it and a hot reload skips it.
if (_initCount < 2)
StringAnchorDiagnostic.RunIfConfigured();
int hookBudget = Plugins.EngineSettings.EngineHookCount;
int hookIndex = 0;
// Decal bridge mode (docs/DECAL_BRIDGE_PLAN.md) is decided before any hook goes
// in. Without Decal in the process this is two GetModuleHandle calls, Active
// stays false and no step is skipped.
DecalBridgeHost.Initialize();
// Decal stand-down (2026-10-03, docs/DECAL_BRIDGE_PLAN.md "Where Decal reads its
// filters"): Decal is in this client but the bridge isn't (not registered as this
// client sees the registry, protocol mismatch, mapping failure). The old coexistence
// path that used to run here never worked - no overlay, then a crash. Stand down
// instead: install only what DecalBridgeHost's "the Decal bridge isn't loaded" chat
// line needs - the login event, AddTextToScroll's address (a probe, no hook) and the
// Client::UseTime drain that runs queued chat writes on AC's main thread - and load
// no plugins. None of those is a function Decal patches. The client then runs as a
// plain Decal client. DecalBridge=Off (tests) and engine.json "DecalStandDown": false
// keep the old path. Without Decal this is false (InactiveReason stays null).
bool decalStandDown = DecalBridgeHost.ShouldStandDown;
if (decalStandDown)
RynthLog.Warn($"InitWorker: Decal without the bridge ({DecalBridgeHost.InactiveReason}) - standing down: " +
"only the login, chat-address and UseTime-drain steps install; no plugins, no overlay.");
List<(string Name, Action Action)>? bridgeSkipped = null;
RynthLog.Info($"InitWorker: starting hook init steps (budget={hookBudget})");
void Step(string name, Action action)
{
if (InitAborted()) return;
if (decalStandDown && name is not ("client helper hooks" or "login lifecycle hooks" or "game-tick cast drain hook"))
return; // stand-down (above): logged once there
if (DecalBridgeHost.SkipsInitStep(name))
{
RynthLog.Info($"InitWorker: '{name}' skipped - bridge mode leaves this to Decal.");
(bridgeSkipped ??= new()).Add((name, action));
return;
}
int idx = hookIndex++;
if (idx >= hookBudget)
{
@ -598,6 +663,34 @@ public static class EntryPoint
Step("raw packet hooks", RawPacketHooks.Initialize);
Step("property-update hooks", PropertyUpdateHooks.Initialize);
Step("auto-id service", AutoIdService.Start);
// 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))
{
// No hello: Decal didn't load the bridge. Stand down (see above) rather than
// install the chat/salvage hooks over Decal's own patches. The other native
// hooks went in during the 20 s wait and stay; nothing loads plugins to use them.
if (DecalBridgeHost.ShouldStandDown)
{
decalStandDown = true;
RynthLog.Warn($"InitWorker: Decal without the bridge ({DecalBridgeHost.InactiveReason}) - standing down: " +
"the chat and salvage hooks stay out; no plugins, no overlay.");
}
else
{
foreach ((string name, Action action) in bridgeSkipped)
RunInitStep(name + " (bridge fallback)", action);
}
}
if (InitAborted()) return;
if (decalStandDown)
{
// No LoadPlugins, no RunPostLoginBootstrap (EndScene hook, plugin pump), and no
// hot-reload bootstrap below: a reload of this client stands down again (the
// registry hasn't changed). DecalBridgeHost posts the chat line at login.
RynthLog.Info("InitWorker: stand-down complete - this client runs as a Decal client; RynthCore stays idle.");
return;
}
if (Plugins.EngineSettings.EnablePlugins)
{
RynthLog.Info("InitWorker DIAG — calling PluginManager.LoadPlugins.");
@ -621,6 +714,7 @@ public static class EntryPoint
// viewport platform/renderer. Avalonia floating panels still
// work because they ride a separate LayeredWindow (GDI), not
// the D3D9 swap chain.
if (InitAborted()) return;
LoginLifecycleHooks.LoginComplete += RunPostLoginBootstrap;
// ── Fast-login race guard (first launch, initCount==1) ───────────
@ -643,6 +737,7 @@ public static class EntryPoint
}
RynthLog.Info($"InitWorker: post-init checkpoint, _initCount={_initCount}");
if (InitAborted()) return;
// On a hot reload (initCount >= 2) the game's already past the
// login gate, so SendLoginCompleteNotification won't fire again.
@ -650,7 +745,7 @@ public static class EntryPoint
// protects against can't happen post-login.
if (_initCount >= 2)
{
if (DecalDetection.IsDecalLoaded)
if (UseDecalCoexistencePath())
{
RynthLog.Info(
$"D3D9: Hot reload (initCount={_initCount}) — Decal coexistence " +
@ -693,7 +788,13 @@ public static class EntryPoint
RynthLog.Info("PlayerVitals: hot reload — could not derive qualities ptr (will fall back to event-driven path).");
}
if (Plugins.EngineSettings.EnableAvaloniaOverlay)
// Avalonia (the older panel UI, now only a fallback) and the ImGui faces are
// set up separately: the ImGui faces, the chat settings and the dashboard state
// don't depend on Avalonia, and the CoreCLR engine runs without it (Avalonia
// can't be unloaded; docs/UNLOADABLE_ENGINE_PLAN.md).
bool avalonia = Plugins.EngineSettings.EnableAvaloniaOverlay;
bool dcompTest = avalonia && UI.Dcomp.DcompOverlayBootstrap.IsEnabled;
if (avalonia)
{
PreloadNativeDll(engineDir, "libSkiaSharp.dll");
PreloadNativeDll(engineDir, "libHarfBuzzSharp.dll");
@ -703,88 +804,133 @@ public static class EntryPoint
// skip the production AvaloniaOverlay and start the DComp test
// path instead. Both paths cannot coexist in one process (Avalonia
// is single-app-per-process). Default behavior is unchanged.
if (UI.Dcomp.DcompOverlayBootstrap.IsEnabled)
if (dcompTest)
{
RynthLog.Info("InitWorker: RYNTHCORE_DCOMP_OVERLAY=1 — starting DComp test overlay instead of production AvaloniaOverlay.");
UI.Dcomp.DcompOverlayBootstrap.Start();
}
else
{
// Engine-builtin panels (no plugin DLL pairing) — always register.
OverlayHost.RegisterPanel("Status", StatusPanel.Create);
OverlayHost.RegisterPanel("Log", LogPanel.Create);
OverlayHost.RegisterPanel("Monsters", MonstersPanel.Create);
OverlayHost.RegisterPanel("Items", ItemsPanel.Create);
OverlayHost.RegisterPanel("Settings", SettingsPanel.Create);
OverlayHost.RegisterPanel("Nav", NavPanel.Create);
OverlayHost.RegisterPanel("Meta", MetaPanel.Create);
OverlayHost.RegisterPanel("Radar", RadarPanel.Create);
// Plugin-paired panels: register only if the matching plugin DLL is
// listed in engine.json PluginPaths (controlled by the launcher Plugins
// tab). The panel UI is engine-side per the Avalonia-overlay design
// (plugin DLLs feed data via C exports) — unchecking a plugin in the
// launcher must take its entire surface area out of process so the
// diagnostic "is plugin X the off-thread caller?" question is testable.
if (HasPluginDll("RynthCore.Plugin.RynthAi.dll"))
{
OverlayHost.RegisterPanel("RynthAi", RynthAiPanel.Create);
OverlayHost.RegisterPanel("Damage", MonsterDamagePanel.Create);
}
else
RynthLog.Info("InitWorker: RynthAi panel skipped — DLL not in engine.json PluginPaths.");
if (HasPluginDll("RynthCore.Plugin.RynthChat.dll"))
{
OverlayHost.RegisterPanel("Chat", RynthChatPanel.Create);
// Regex filter-rule editor — its own panel (opened from
// the chat panel's Filters button or the bar).
OverlayHost.RegisterPanel("ChatFilters", RynthChatFiltersPanel.Create);
// Apply persisted RynthChat settings (incl. "Hide retail chat" ->
// ChatHooks.SuppressOriginalChat) at init so suppression takes effect
// on login without the user having to open the Chat panel first.
//
// ⚠ INVARIANT: this is the ONLY place that invokes a panel's static
// method BEFORE AvaloniaOverlay.Start() (below) sets up the Win32
// platform. Doing so runs that panel's static ctor on THIS (InitWorker)
// thread. A panel whose static ctor eagerly constructs Avalonia objects
// (SolidColorBrush etc.) would then create Dispatcher.UIThread with the
// wrong (non-controlled) impl → the overlay thread's Dispatcher.MainLoop
// throws PlatformNotSupportedException → the ENTIRE overlay dies and no
// RynthCore/plugin UI renders (game + plugin pump still run). This bit us
// 2026-06-30; fixed by making RynthChatPanel's brush statics LAZY.
// Before adding any EnsureSettingsLoaded-style early call for another
// panel, confirm that panel's static ctor constructs NO Avalonia objects
// (make its brushes lazy), OR move the settings-load off the panel class.
// OverlayHost.RegisterPanel above is safe: a method-group does NOT trigger
// the static ctor. See rynthcore memory "overlay no-UI = dispatcher poison".
RynthChatPanel.EnsureSettingsLoaded();
}
else
RynthLog.Info("InitWorker: RynthChat panel skipped — DLL not in engine.json PluginPaths.");
if (HasPluginDll("RynthCore.Plugin.RynthVision.dll"))
OverlayHost.RegisterPanel("Vision", RynthVisionPanel.Create);
else
RynthLog.Info("InitWorker: RynthVision panel skipped — DLL not in engine.json PluginPaths.");
if (HasPluginDll("RynthCore.Plugin.RynthTracker.dll"))
OverlayHost.RegisterPanel("Tracker", RynthTrackerPanel.Create);
else
RynthLog.Info("InitWorker: RynthTracker panel skipped — DLL not in engine.json PluginPaths.");
if (HasPluginDll("RynthCore.Plugin.RynthNav.dll"))
OverlayHost.RegisterPanel("RynthNav", RynthNavPanel.Create);
else
RynthLog.Info("InitWorker: RynthNav panel skipped — DLL not in engine.json PluginPaths.");
AvaloniaOverlay.Start();
}
}
else
{
RynthLog.Info("InitWorker: AvaloniaOverlay disabled via engine.json (EnableAvaloniaOverlay=false). No panels, no Skia, no offscreen window.");
RynthLog.Info("InitWorker: AvaloniaOverlay disabled (engine.json EnableAvaloniaOverlay=false, or the CoreCLR engine). ImGui faces only; no Skia, no offscreen window.");
}
if (!dcompTest)
{
// The panel list (titles + Avalonia view factories). Registering creates no
// Avalonia object and starts nothing; the ImGui bar builds its buttons from it
// and PanelRouter resolves titles with it, Avalonia on or off.
// Engine-builtin panels (no plugin DLL pairing) — always register.
OverlayHost.RegisterPanel("Status", StatusPanel.Create);
OverlayHost.RegisterPanel("Log", LogPanel.Create);
OverlayHost.RegisterPanel("Monsters", MonstersPanel.Create);
OverlayHost.RegisterPanel("Items", ItemsPanel.Create);
OverlayHost.RegisterPanel("Settings", SettingsPanel.Create);
OverlayHost.RegisterPanel("Nav", NavPanel.Create);
OverlayHost.RegisterPanel("Meta", MetaPanel.Create);
OverlayHost.RegisterPanel("Radar", RadarPanel.Create);
// Plugin-paired panels: register only if the matching plugin DLL is
// listed in engine.json PluginPaths (controlled by the launcher Plugins
// tab). The panel UI is engine-side per the Avalonia-overlay design
// (plugin DLLs feed data via C exports) — unchecking a plugin in the
// launcher must take its entire surface area out of process so the
// diagnostic "is plugin X the off-thread caller?" question is testable.
if (HasPluginDll("RynthCore.Plugin.RynthAi.dll"))
{
OverlayHost.RegisterPanel("RynthAi", RynthAiPanel.Create);
OverlayHost.RegisterPanel("Damage", MonsterDamagePanel.Create);
}
// Lua: the RynthLua plugin (or an older RynthAi that still carries it).
if (HasPluginDll("RynthCore.Plugin.RynthLua.dll") || HasPluginDll("RynthCore.Plugin.RynthAi.dll"))
OverlayHost.RegisterPanel("Lua", LuaPanel.Create);
else
RynthLog.Info("InitWorker: RynthAi panel skipped — DLL not in engine.json PluginPaths.");
if (HasPluginDll("RynthCore.Plugin.RynthChat.dll"))
{
OverlayHost.RegisterPanel("Chat", RynthChatPanel.Create);
// Regex filter-rule editor — its own panel (opened from
// the chat panel's Filters button or the bar).
OverlayHost.RegisterPanel("ChatFilters", RynthChatFiltersPanel.Create);
}
else
RynthLog.Info("InitWorker: RynthChat panel skipped — DLL not in engine.json PluginPaths.");
if (HasPluginDll("RynthCore.Plugin.RynthVision.dll"))
OverlayHost.RegisterPanel("Vision", RynthVisionPanel.Create);
else
RynthLog.Info("InitWorker: RynthVision panel skipped — DLL not in engine.json PluginPaths.");
if (HasPluginDll("RynthCore.Plugin.RynthTracker.dll"))
OverlayHost.RegisterPanel("Tracker", RynthTrackerPanel.Create);
else
RynthLog.Info("InitWorker: RynthTracker panel skipped — DLL not in engine.json PluginPaths.");
if (HasPluginDll("RynthCore.Plugin.RynthNav.dll"))
OverlayHost.RegisterPanel("RynthNav", RynthNavPanel.Create);
else
RynthLog.Info("InitWorker: RynthNav panel skipped — DLL not in engine.json PluginPaths.");
// Apply persisted RynthChat settings (incl. "Hide retail chat" ->
// ChatHooks.SuppressOriginalChat) at init so suppression takes effect
// on login without the user having to open the Chat panel first; the
// chat keys feed ChatModel's input line whichever chat face is up.
//
// ⚠ INVARIANT: this runs BEFORE AvaloniaOverlay.Start() (below) sets up
// the Win32 platform, on THIS (InitWorker) thread. Nothing here may run a
// panel's static ctor that constructs Avalonia objects (SolidColorBrush
// etc.): that creates Dispatcher.UIThread with the wrong impl → the
// overlay thread's Dispatcher.MainLoop throws PlatformNotSupportedException
// → the ENTIRE overlay dies (bit us 2026-06-30). Hence ChatModel
// (UI/Data/ChatData.cs), which touches no Avalonia type, not the panel
// class. OverlayHost.RegisterPanel above is safe: a method group does NOT
// trigger the static ctor. See rynthcore memory "overlay no-UI = dispatcher poison".
if (HasPluginDll("RynthCore.Plugin.RynthChat.dll"))
{
UI.Data.ChatModel.EnsureSettingsLoaded();
UI.Data.ChatModel.InstallInput();
}
// ImGui faces for panels docked in the client (UI.PanelRouter
// picks the face). Registered even while the ImGui layer is off,
// so /rc imgui on can use them without a reload.
bool trackerPresent = HasPluginDll("RynthCore.Plugin.RynthTracker.dll");
ImGuiBackend.Panels.P1Faces.Register(trackerPresent);
if (HasPluginDll("RynthCore.Plugin.RynthVision.dll"))
ImGuiBackend.Panels.VisionFace.Register();
if (HasPluginDll("RynthCore.Plugin.RynthNav.dll"))
ImGuiBackend.Panels.RynthNavFace.Register();
if (HasPluginDll("RynthCore.Plugin.RynthChat.dll"))
{
ImGuiBackend.Panels.ChatFace.Register();
ImGuiBackend.Panels.ChatFiltersFace.Register();
}
ImGuiBackend.Panels.RadarFace.Register();
ImGuiBackend.Panels.SettingsFace.Register();
ImGuiBackend.Panels.MetaFace.Register();
RadarSettingsStore.Load(); // file read here, not on AC's thread
if (HasPluginDll("RynthCore.Plugin.RynthLua.dll") || HasPluginDll("RynthCore.Plugin.RynthAi.dll"))
ImGuiBackend.Panels.LuaFace.Register();
if (HasPluginDll("RynthCore.Plugin.RynthAi.dll"))
{
ImGuiBackend.Panels.RynthAiFace.Register();
ImGuiBackend.Panels.DamageFace.Register();
ImGuiBackend.Panels.DamageDetailFace.Register();
ImGuiBackend.Panels.MonstersFace.Register();
ImGuiBackend.Panels.NavFace.Register();
ImGuiBackend.Panels.ItemsFace.Register();
// Load the dashboard state file here, not on AC's thread. NOT through
// RynthAiPanel: see the dispatcher invariant above ChatModel.EnsureSettingsLoaded.
RynthAiDashboardState.EnsureLoaded();
}
if (trackerPresent)
TrackerSettings.EnsureLoaded();
// Hide the docked Avalonia bar before it is built if the ImGui bar stands in.
ImGuiBackend.ImGuiBar.ApplyFace();
}
if (avalonia && !dcompTest)
AvaloniaOverlay.Start();
RynthLog.Info("RynthCore bootstrap initialized.");
}
catch (Exception ex)
@ -825,8 +971,20 @@ public static class EntryPoint
/// that need them already null-check, and headless plugins (Avalonia-
/// rendered like RynthAi) work fine without them.
/// </summary>
private static int _decalCoexistenceStarted;
private static void InitPluginsForDecalCoexistence()
{
// Once per generation. A hot reload reaches this twice - from the initCount>=2
// branch in InitWorker and again from RunPostLoginBootstrap via
// MarkAlreadyComplete - and used to start TWO tick pumps (two concurrent
// PluginManager.TickAll drivers; _tickPumpThread only remembered the second).
// Measured on a Decal test client 2026-09-29 (spike/decal-bridge).
if (Interlocked.CompareExchange(ref _decalCoexistenceStarted, 1, 0) != 0)
{
RynthLog.Info("DecalCoexistence: plugin init/pump already started in this generation - not starting a second pump.");
return;
}
IntPtr hwnd = global::RynthCore.Engine.ImGuiBackend.EngineFrameController.FindGameWindow();
if (hwnd != IntPtr.Zero)
{
@ -845,7 +1003,8 @@ public static class EntryPoint
{
try
{
Thread.Sleep(DecalCoexistencePluginInitDelay);
if (!EngineThreads.Sleep(DecalCoexistencePluginInitDelay))
return;
// Reseed the qualities pointer from the live player object
// before plugins look at vitals. Auto-inject lands AFTER AC
@ -870,6 +1029,17 @@ public static class EntryPoint
$"dispatchCount={Compatibility.CreateObjectHooks.DispatchCount}, " +
$"liveObjects={Plugins.PluginManager.LiveObjectCount}");
// Bridge mode: queue what the bridge buffered before InitPlugins, so its
// replay includes it.
if (DecalBridgeHost.Active)
RynthLog.Info($"DecalBridge: drained {DecalBridgeHost.Drain()} buffered record(s) before plugin init.");
// No EndScene hook in this mode, so the per-frame main-thread prefetches the
// pump reads (skills, spells, attackable, names/types, positions, stats, the
// cold-login object seed) run from the Client::UseTime detour instead.
Compatibility.GameTickHooks.HeadlessPrefetch = true;
RynthLog.Info("DecalCoexistence: main-thread prefetches now run from Client::UseTime (no EndScene hook).");
Plugins.PluginManager.InitPlugins(IntPtr.Zero, IntPtr.Zero, hwnd);
// Drive the plugin tick loop. Without this, the macro
@ -880,7 +1050,8 @@ public static class EntryPoint
int consecutiveFailures = 0;
while (Volatile.Read(ref _tickPumpStopRequested) == 0)
{
Thread.Sleep(DecalCoexistenceTickInterval);
if (!EngineThreads.Sleep(DecalCoexistenceTickInterval))
break;
if (Volatile.Read(ref _tickPumpStopRequested) != 0)
break;
try
@ -892,8 +1063,15 @@ public static class EntryPoint
// NO TARGET, BuffManager never sees enchantments land, combat
// events evaporate. Historically driven from EngineFrameController's
// per-frame loop; this is the headless equivalent.
if (DecalBridgeHost.Active)
DecalBridgeHost.Drain(); // bridge events into the same queues
Plugins.PluginManager.ProcessPendingActions(IntPtr.Zero, IntPtr.Zero, hwnd);
Plugins.PluginManager.FlushPendingDeletes(); // as PumpPluginFrame: closes the create->delete race
Plugins.PluginManager.TickAll();
// Panel data (UiDataHub): published on the plugin-tick thread, as
// PumpPluginFrame does in the normal pump. Without it the panels'
// snapshots never refreshed with Decal loaded.
UI.Data.UiDataHub.Step();
consecutiveFailures = 0;
}
catch (Exception tickEx)
@ -928,6 +1106,7 @@ public static class EntryPoint
IsBackground = true,
};
_tickPumpThread = worker;
EngineThreads.Track(worker);
worker.Start();
}
@ -971,8 +1150,10 @@ public static class EntryPoint
{
if (Interlocked.CompareExchange(ref _postLoginBootstrapStarted, 1, 0) != 0)
return;
if (EngineLifecycle.IsShuttingDown)
return; // no EndScene hook / plugin pump for a generation being torn down
if (DecalDetection.IsDecalLoaded)
if (UseDecalCoexistencePath())
{
RynthLog.Info(
$"D3D9: Decal coexistence — '{DecalDetection.DetectedModule}' loaded, " +
@ -1011,6 +1192,37 @@ public static class EntryPoint
RynthLog.Info("NormalPluginPump: disabled via engine.json (EnablePlugins=false).");
}
private static int _decalInGameLogged;
/// <summary>
/// True: Decal is in this client and the old coexistence path runs (no EndScene hook, no
/// ImGui, the 30 Hz Decal pump). False without Decal, and with Decal when engine.json
/// DecalInGameImGui (or RYNTHCORE_DECAL_IMGUI=1) asks for the normal EndScene hook and
/// ImGui renderer there (docs/DECAL_BRIDGE_PLAN.md, step 3): the bootstrapper then finds
/// AC's device without creating one (Decal detours Direct3DCreate9 and CreateDevice).
/// Without Decal the setting is never read.
/// </summary>
private static bool UseDecalCoexistencePath()
{
if (!DecalDetection.IsDecalLoaded && !DecalBridgeHost.Active)
return false;
if (!Plugins.EngineSettings.DecalInGameImGui)
return true;
// AC's device must be known through the bridge first (bridge mode only); otherwise
// the old coexistence path, so plugins still get their pump.
if (!DecalBridgeHost.Active || !D3D9.DecalD3D9.TryResolve())
{
if (Interlocked.Exchange(ref _decalInGameLogged, 1) == 0)
RynthLog.Info($"D3D9: DecalInGameImGui is on, but AC's device isn't known through the Decal bridge (bridge mode={DecalBridgeHost.Active}) - Decal coexistence path instead.");
return true;
}
D3D9Bootstrapper.DecalInProcess = true;
if (Interlocked.Exchange(ref _decalInGameLogged, 1) == 0)
RynthLog.Info($"D3D9: Decal in the process ('{DecalDetection.DetectedModule ?? "Decal"}', bridge mode={DecalBridgeHost.Active}) and DecalInGameImGui is on - " +
"installing the normal EndScene hook and ImGui renderer (device found without creating one).");
return false;
}
private static void StartNormalPluginPump()
{
if (Interlocked.CompareExchange(ref _normalPumpStarted, 1, 0) != 0)
@ -1024,7 +1236,8 @@ public static class EntryPoint
int consecutiveFailures = 0;
while (Volatile.Read(ref _tickPumpStopRequested) == 0)
{
Thread.Sleep(NormalPluginPumpInterval);
if (!EngineThreads.Sleep(NormalPluginPumpInterval))
break;
if (Volatile.Read(ref _tickPumpStopRequested) != 0)
break;
try
@ -1060,6 +1273,7 @@ public static class EntryPoint
IsBackground = true,
};
_tickPumpThread = worker;
EngineThreads.Track(worker);
worker.Start();
}
@ -1077,6 +1291,7 @@ public static class EntryPoint
/// </summary>
internal static bool StopTickPumpAndJoin(int timeoutMs = 2000)
{
Compatibility.GameTickHooks.HeadlessPrefetch = false; // no more prefetch work once teardown starts
if (_tickPumpThread == null)
return true;
@ -1106,8 +1321,34 @@ public static class EntryPoint
Interlocked.Exchange(ref _tickPumpStopRequested, 1);
}
private static Thread? _initThread;
private static int _initAbortLogged;
/// <summary>
/// Waits for InitWorker to finish. A reload can arrive while it is still installing
/// hooks and loading plugins; teardown must not run under it (it would keep
/// installing hooks and starting the D3D9 bootstrap for a generation being torn
/// down). InitWorker stops at its next step once shutdown has begun.
/// </summary>
internal static bool WaitForInitWorker(int timeoutMs)
{
Thread? t = _initThread;
if (t == null || t == Thread.CurrentThread) return true;
return t.Join(timeoutMs);
}
/// <summary>True (and logged once) when shutdown began while InitWorker was running.</summary>
private static bool InitAborted()
{
if (!EngineLifecycle.IsShuttingDown) return false;
if (Interlocked.Exchange(ref _initAbortLogged, 1) == 0)
RynthLog.Info("InitWorker: engine shutting down — stopping init here.");
return true;
}
private static void RunInitStep(string name, Action action)
{
if (InitAborted()) return;
try
{
action();
@ -1168,6 +1409,20 @@ public static class EntryPoint
}
}
/// <summary>
/// Removes the handlers above. They are process-wide events, so under the CoreCLR
/// host they would keep this engine generation alive after a reload (and keep its
/// handlers running next to the new generation's).
/// </summary>
internal static void UninstallManagedExceptionHandlers()
{
if (Interlocked.CompareExchange(ref _managedHandlersInstalled, 0, 1) != 1)
return;
AppDomain.CurrentDomain.UnhandledException -= OnUnhandledException;
System.Threading.Tasks.TaskScheduler.UnobservedTaskException -= OnUnobservedTaskException;
AppDomain.CurrentDomain.FirstChanceException -= OnFirstChanceException;
}
[ThreadStatic] private static bool _inFirstChanceHandler;
/// <summary>
@ -1285,6 +1540,7 @@ public static class EntryPoint
lock (LogLock)
{
RecentLogLines.Enqueue(line);
System.Threading.Interlocked.Increment(ref _recentLogSeq); // 64-bit: atomic for the lock-free RecentLogSeq read
while (RecentLogLines.Count > MaxRecentLogLines)
RecentLogLines.Dequeue();
@ -1341,4 +1597,21 @@ public static class EntryPoint
lock (LogLock)
return RecentLogLines.ToArray();
}
/// <summary>
/// The recent-log ring plus the sequence number of its last line (lines are
/// numbered from 1 since load). Lets a viewer "clear" by remembering a
/// sequence number, which keeps working after the ring wraps.
/// </summary>
internal static string[] GetRecentLogLines(out long lastSeq)
{
lock (LogLock)
{
lastSeq = _recentLogSeq;
return RecentLogLines.ToArray();
}
}
/// <summary>Sequence number of the newest log line (0 before any). Lock-free read.</summary>
internal static long RecentLogSeq => System.Threading.Interlocked.Read(ref _recentLogSeq);
}

View file

@ -0,0 +1,58 @@
// ============================================================================
// RynthCore.Engine - Hooking/LoaderServices.cs
//
// The native loader (native/Loader/Services.c, loader 2.0+) owns the permanent native
// entry points the engine used to hand out itself: the game window's subclass proc and
// the plugin API table's function pointers. With them, nothing native ever points into
// an engine generation after its shutdown, so the CoreCLR host can unload it
// (docs/UNLOADABLE_ENGINE_PLAN.md). Under an older loader (or none) Available is false
// and callers keep their old behaviour.
// ============================================================================
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Hooking;
internal static unsafe class LoaderServices
{
private static readonly delegate* unmanaged[Stdcall]<IntPtr, IntPtr, IntPtr*, int> s_subclassInstall;
private static readonly delegate* unmanaged[Stdcall]<IntPtr, int> s_subclassRelease;
private static readonly delegate* unmanaged[Stdcall]<int, IntPtr, IntPtr> s_apiStub;
static LoaderServices()
{
IntPtr loader = GetModuleHandleW("RynthCore.Loader.dll");
if (loader == IntPtr.Zero || GetProcAddress(loader, "RcServices_Version") == IntPtr.Zero)
return;
s_subclassInstall = (delegate* unmanaged[Stdcall]<IntPtr, IntPtr, IntPtr*, int>)GetProcAddress(loader, "RcSubclass_Install");
s_subclassRelease = (delegate* unmanaged[Stdcall]<IntPtr, int>)GetProcAddress(loader, "RcSubclass_Release");
s_apiStub = (delegate* unmanaged[Stdcall]<int, IntPtr, IntPtr>)GetProcAddress(loader, "RcApiStub");
}
public static bool Available => s_subclassInstall != null && s_subclassRelease != null && s_apiStub != null;
/// <summary>
/// Routes <paramref name="hwnd"/>'s messages to <paramref name="handler"/> through the
/// loader's permanent subclass. <paramref name="previous"/> is the proc to forward to.
/// </summary>
public static bool SubclassInstall(IntPtr hwnd, IntPtr handler, out IntPtr previous)
{
IntPtr prev = IntPtr.Zero;
bool ok = s_subclassInstall(hwnd, handler, &prev) != 0;
previous = prev;
return ok;
}
/// <summary>The loader's subclass passes everything straight to the previous proc again.</summary>
public static void SubclassRelease(IntPtr hwnd) => s_subclassRelease(hwnd);
/// <summary>A permanent stub for plugin API slot <paramref name="index"/> that calls <paramref name="fn"/>.</summary>
public static IntPtr ApiStub(int index, IntPtr fn) => s_apiStub(index, fn);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr GetModuleHandleW(string lpModuleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
}

View file

@ -13,9 +13,10 @@ using System.Threading;
namespace RynthCore.Engine.Hooking;
internal static class MinHook
internal static unsafe class MinHook
{
private const string DLL = "minhook.x86.dll";
private const string LoaderDll = "RynthCore.Loader.dll";
// ─── Status codes (must match MinHook's MH_STATUS enum) ────────────
public const int MH_OK = 0;
@ -25,35 +26,86 @@ internal static class MinHook
public const int MH_ERROR_NOT_CREATED = 4;
// ─── Core API ─────────────────────────────────────────────────────
//
// The native loader (native/Loader, 2.0+) exports MinHook's API itself: every
// target gets a permanent stub and a reload only re-points it, so no hook ever
// points into an unloaded engine (docs/UNLOADABLE_ENGINE_PLAN.md). The engine uses
// that facade when the loader has it (RcHooks_Version), else minhook.x86.dll as
// before (the NativeAOT loader, or the engine loaded directly).
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
public static extern int MH_Initialize();
private static readonly Api s_api = ResolveApi();
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
public static extern int MH_Uninitialize();
/// <summary>True when hooks go through the native loader's facade.</summary>
public static bool UsesLoaderFacade => s_api.IsFacade;
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
public static extern int MH_CreateHook(
IntPtr pTarget,
IntPtr pDetour,
out IntPtr ppOriginal);
public static int MH_Initialize() => s_api.Initialize();
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
public static extern int MH_RemoveHook(IntPtr pTarget);
public static int MH_Uninitialize() => s_api.Uninitialize();
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
public static extern int MH_EnableHook(IntPtr pTarget);
public static int MH_CreateHook(IntPtr pTarget, IntPtr pDetour, out IntPtr ppOriginal)
{
IntPtr original = IntPtr.Zero;
int status = s_api.Create(pTarget, pDetour, &original);
ppOriginal = original;
return status;
}
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
public static extern int MH_DisableHook(IntPtr pTarget);
public static int MH_RemoveHook(IntPtr pTarget) => s_api.Remove(pTarget);
public static int MH_EnableHook(IntPtr pTarget) => s_api.Enable(pTarget);
public static int MH_DisableHook(IntPtr pTarget) => s_api.Disable(pTarget);
/// <summary>Enable/disable all hooks at once.</summary>
public static readonly IntPtr MH_ALL_HOOKS = IntPtr.Zero;
// ─── Status to string ─────────────────────────────────────────────
private static IntPtr MH_StatusToString(int status) => s_api.StatusToString(status);
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr MH_StatusToString(int status);
private sealed class Api
{
public bool IsFacade;
public delegate* unmanaged[Stdcall]<int> Initialize;
public delegate* unmanaged[Stdcall]<int> Uninitialize;
public delegate* unmanaged[Stdcall]<IntPtr, IntPtr, IntPtr*, int> Create;
public delegate* unmanaged[Stdcall]<IntPtr, int> Remove;
public delegate* unmanaged[Stdcall]<IntPtr, int> Enable;
public delegate* unmanaged[Stdcall]<IntPtr, int> Disable;
public delegate* unmanaged[Stdcall]<int, IntPtr> StatusToString;
}
private static Api ResolveApi()
{
IntPtr module = GetModuleHandleW(LoaderDll);
bool facade = module != IntPtr.Zero && GetProcAddress(module, "RcHooks_Version") != IntPtr.Zero;
if (!facade)
module = NativeLibrary.Load(DLL, typeof(MinHook).Assembly, null);
IntPtr Get(string name)
{
IntPtr fn = GetProcAddress(module, name);
if (fn == IntPtr.Zero)
throw new EntryPointNotFoundException($"{(facade ? LoaderDll : DLL)} has no export {name}");
return fn;
}
return new Api
{
IsFacade = facade,
Initialize = (delegate* unmanaged[Stdcall]<int>)Get("MH_Initialize"),
Uninitialize = (delegate* unmanaged[Stdcall]<int>)Get("MH_Uninitialize"),
Create = (delegate* unmanaged[Stdcall]<IntPtr, IntPtr, IntPtr*, int>)Get("MH_CreateHook"),
Remove = (delegate* unmanaged[Stdcall]<IntPtr, int>)Get("MH_RemoveHook"),
Enable = (delegate* unmanaged[Stdcall]<IntPtr, int>)Get("MH_EnableHook"),
Disable = (delegate* unmanaged[Stdcall]<IntPtr, int>)Get("MH_DisableHook"),
StatusToString = (delegate* unmanaged[Stdcall]<int, IntPtr>)Get("MH_StatusToString"),
};
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr GetModuleHandleW(string lpModuleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
public static string StatusString(int status)
{

View file

@ -0,0 +1,296 @@
// ============================================================================
// RynthCore.Engine - ImGui/CodeEditor.cs
// A syntax-coloured source editor for ImGui faces: ImGuiColorTextEdit
// compiled into our cimgui.dll (native/cimgui/rynth_textedit_ext.cpp),
// called through function pointers resolved from that module.
//
// AC's render thread only, inside the ImGui frame. The native editor is
// created on the first Render (it reads the ImGui style) and destroyed by
// Dispose. Text crosses the boundary only on SetText/GetText, never per
// frame: IsDirty compares the editor's change counter, so a 50 KB meta costs
// nothing while it is being typed in.
// ============================================================================
using System;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
namespace RynthCore.Engine.ImGuiBackend;
internal enum CodeLanguage { None = 0, Meta = 1, Lua = 2 }
internal sealed unsafe class CodeEditor : IDisposable
{
// ── Exports ────────────────────────────────────────────────────────────
private static bool _resolved, _available;
private static delegate* unmanaged[Cdecl]<IntPtr> _create;
private static delegate* unmanaged[Cdecl]<IntPtr, void> _destroy;
private static delegate* unmanaged[Cdecl]<byte*, byte*, byte*, void> _setMetaVocabulary;
private static delegate* unmanaged[Cdecl]<IntPtr, int, void> _setLanguage;
private static delegate* unmanaged[Cdecl]<IntPtr, uint*, int, void> _setPalette;
private static delegate* unmanaged[Cdecl]<IntPtr, int, int, int, int, void> _setOptions;
private static delegate* unmanaged[Cdecl]<IntPtr, byte*, void> _setText;
private static delegate* unmanaged[Cdecl]<IntPtr, int*, byte*> _getText;
private static delegate* unmanaged[Cdecl]<IntPtr, uint> _getChangeCount;
private static delegate* unmanaged[Cdecl]<IntPtr, byte*, float, float, int, int> _render;
private static delegate* unmanaged[Cdecl]<IntPtr, int*, int*, void> _getCursor;
private static delegate* unmanaged[Cdecl]<IntPtr, int, int, void> _setCursor;
private static delegate* unmanaged[Cdecl]<IntPtr, float*, float*, void> _getCursorScreenPos;
private static delegate* unmanaged[Cdecl]<IntPtr, int*, byte*> _getLinePrefix;
private static delegate* unmanaged[Cdecl]<IntPtr, int, byte*, void> _replaceBeforeCursor;
private static delegate* unmanaged[Cdecl]<IntPtr, int, void> _setCompletionKeysHeld;
private static delegate* unmanaged[Cdecl]<IntPtr, void> _requestFocus;
/// <summary>False when the loaded cimgui.dll was built without the editor.</summary>
public static bool Available
{
get
{
if (!_resolved) Resolve();
return _available;
}
}
private static void Resolve()
{
_resolved = true;
IntPtr module = EntryPoint.ImGuiNativeHandle;
if (module == IntPtr.Zero) return;
IntPtr Get(string name) => NativeLibrary.TryGetExport(module, name, out IntPtr p) ? p : IntPtr.Zero;
_create = (delegate* unmanaged[Cdecl]<IntPtr>)Get("RynthTE_Create");
_destroy = (delegate* unmanaged[Cdecl]<IntPtr, void>)Get("RynthTE_Destroy");
_setMetaVocabulary = (delegate* unmanaged[Cdecl]<byte*, byte*, byte*, void>)Get("RynthTE_SetMetaVocabulary");
_setLanguage = (delegate* unmanaged[Cdecl]<IntPtr, int, void>)Get("RynthTE_SetLanguage");
_setPalette = (delegate* unmanaged[Cdecl]<IntPtr, uint*, int, void>)Get("RynthTE_SetPalette");
_setOptions = (delegate* unmanaged[Cdecl]<IntPtr, int, int, int, int, void>)Get("RynthTE_SetOptions");
_setText = (delegate* unmanaged[Cdecl]<IntPtr, byte*, void>)Get("RynthTE_SetText");
_getText = (delegate* unmanaged[Cdecl]<IntPtr, int*, byte*>)Get("RynthTE_GetText");
_getChangeCount = (delegate* unmanaged[Cdecl]<IntPtr, uint>)Get("RynthTE_GetChangeCount");
_render = (delegate* unmanaged[Cdecl]<IntPtr, byte*, float, float, int, int>)Get("RynthTE_Render");
_getCursor = (delegate* unmanaged[Cdecl]<IntPtr, int*, int*, void>)Get("RynthTE_GetCursor");
_setCursor = (delegate* unmanaged[Cdecl]<IntPtr, int, int, void>)Get("RynthTE_SetCursor");
_getCursorScreenPos = (delegate* unmanaged[Cdecl]<IntPtr, float*, float*, void>)Get("RynthTE_GetCursorScreenPos");
_getLinePrefix = (delegate* unmanaged[Cdecl]<IntPtr, int*, byte*>)Get("RynthTE_GetLinePrefix");
_replaceBeforeCursor = (delegate* unmanaged[Cdecl]<IntPtr, int, byte*, void>)Get("RynthTE_ReplaceBeforeCursor");
_setCompletionKeysHeld = (delegate* unmanaged[Cdecl]<IntPtr, int, void>)Get("RynthTE_SetCompletionKeysHeld");
_requestFocus = (delegate* unmanaged[Cdecl]<IntPtr, void>)Get("RynthTE_RequestFocus");
_available = _create != null && _destroy != null && _setMetaVocabulary != null && _setLanguage != null
&& _setPalette != null && _setOptions != null && _setText != null && _getText != null
&& _getChangeCount != null && _render != null && _getCursor != null && _setCursor != null
&& _getCursorScreenPos != null && _getLinePrefix != null && _replaceBeforeCursor != null
&& _setCompletionKeysHeld != null && _requestFocus != null;
if (!_available)
RynthLog.UI("CodeEditor: this cimgui.dll has no RynthTE_* exports; ImGui source editors are unavailable.");
}
private static bool _vocabularySet;
/// <summary>The Meta language's keywords (all Meta editors share them). Set once.</summary>
public static void SetMetaVocabulary(string[] structWords, string[] conditionWords, string[] actionWords)
{
if (_vocabularySet || !Available) return;
_vocabularySet = true;
byte[] s = Utf8Z(string.Join('\n', structWords));
byte[] c = Utf8Z(string.Join('\n', conditionWords));
byte[] a = Utf8Z(string.Join('\n', actionWords));
fixed (byte* ps = s, pc = c, pa = a)
_setMetaVocabulary(ps, pc, pa);
}
// ── Instance ───────────────────────────────────────────────────────────
private IntPtr _handle;
private readonly byte[] _id;
private readonly CodeLanguage _language;
private readonly uint[] _palette;
private string? _pendingText;
private uint _cleanCount;
private bool _held;
/// <param name="palette">ImGui colours (ABGR) in ImGuiColorTextEdit's PaletteIndex order.</param>
public CodeEditor(string id, CodeLanguage language, uint[] palette)
{
_id = Utf8Z(id);
_language = language;
_palette = palette;
}
public bool Created => _handle != IntPtr.Zero;
private bool Ensure()
{
if (_handle != IntPtr.Zero) return true;
if (!Available) return false;
_handle = _create();
if (_handle == IntPtr.Zero) return false;
_setLanguage(_handle, (int)_language);
fixed (uint* p = _palette)
_setPalette(_handle, p, _palette.Length);
_setOptions(_handle, 0, 0, 1, 4);
SetTextNow(_pendingText ?? string.Empty);
_pendingText = null;
return true;
}
/// <summary>Replaces the text (and the undo history); the editor is clean afterwards.</summary>
public void SetText(string text)
{
if (_handle == IntPtr.Zero) { _pendingText = text; return; }
SetTextNow(text);
}
private void SetTextNow(string text)
{
byte[] bytes = Utf8Z(text);
fixed (byte* p = bytes)
_setText(_handle, p);
_cleanCount = _getChangeCount(_handle);
}
public string GetText()
{
if (_handle == IntPtr.Zero) return _pendingText ?? string.Empty;
int len;
byte* p = _getText(_handle, &len);
return len <= 0 ? string.Empty : Encoding.UTF8.GetString(p, len);
}
/// <summary>Counts text changes (edits, undo, redo, SetText).</summary>
public uint ChangeCount => _handle == IntPtr.Zero ? 0 : _getChangeCount(_handle);
/// <summary>Edited since the last SetText or MarkClean.</summary>
public bool IsDirty => _handle != IntPtr.Zero && _getChangeCount(_handle) != _cleanCount;
public void MarkClean()
{
if (_handle != IntPtr.Zero) _cleanCount = _getChangeCount(_handle);
}
/// <summary>Draws the editor as a child window of <paramref name="size"/>; returns whether it has keyboard focus.</summary>
public bool Render(Vector2 size)
{
if (!Ensure()) return false;
fixed (byte* id = _id)
return _render(_handle, id, size.X, size.Y, 1) != 0;
}
/// <summary>Zero-based line and (tab-expanded) column of the cursor.</summary>
public (int Line, int Column) Cursor
{
get
{
if (_handle == IntPtr.Zero) return (0, 0);
int line, column;
_getCursor(_handle, &line, &column);
return (line, column);
}
}
public void SetCursor(int line, int charIndex)
{
if (_handle != IntPtr.Zero) _setCursor(_handle, line, charIndex);
}
/// <summary>Screen position of the bottom-left corner of the cursor's cell (after Render).</summary>
public Vector2 CursorScreenPos
{
get
{
if (_handle == IntPtr.Zero) return Vector2.Zero;
float x, y;
_getCursorScreenPos(_handle, &x, &y);
return new Vector2(x, y);
}
}
/// <summary>The cursor's line up to the cursor.</summary>
public string LinePrefix()
{
if (_handle == IntPtr.Zero) return string.Empty;
int len;
byte* p = _getLinePrefix(_handle, &len);
return len <= 0 ? string.Empty : Encoding.UTF8.GetString(p, len);
}
/// <summary>Replaces the <paramref name="bytes"/> UTF-8 bytes before the cursor with <paramref name="text"/> (one undo step).</summary>
public void ReplaceBeforeCursor(int bytes, string text)
{
if (_handle == IntPtr.Zero) return;
byte[] t = Utf8Z(text);
fixed (byte* p = t)
_replaceBeforeCursor(_handle, bytes, p);
}
/// <summary>While true the editor leaves Up/Down/PageUp/PageDown/Enter/Tab/Escape to a completion list.</summary>
public bool CompletionKeysHeld
{
get => _held;
set
{
if (_held == value || _handle == IntPtr.Zero) return;
_held = value;
_setCompletionKeysHeld(_handle, value ? 1 : 0);
}
}
public void RequestFocus()
{
if (_handle != IntPtr.Zero) _requestFocus(_handle);
}
public void Dispose()
{
if (_handle == IntPtr.Zero) return;
_pendingText = GetText();
_destroy(_handle);
_handle = IntPtr.Zero;
_held = false;
}
private static byte[] Utf8Z(string s)
{
byte[] bytes = new byte[Encoding.UTF8.GetByteCount(s) + 1];
Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0);
return bytes;
}
// ── Palettes ───────────────────────────────────────────────────────────
/// <summary>
/// The Meta editor's colours (MetaSourceEditor's): STATE:/IF:/DO:/NAV: teal
/// (Keyword), conditions amber (KnownIdentifier), actions blue
/// (PreprocIdentifier), braces violet, numbers green, "~~" comments grey.
/// Lua uses the same slots (keywords teal, built-ins amber).
/// </summary>
public static uint[] RynthPalette()
{
static uint C(uint argb) => RynthTheme.Argb(argb);
return new[]
{
C(0xFFD9E6F2), // Default
C(0xFF26D9E6), // Keyword
C(0xFF99E699), // Number
C(0xFFE6C07B), // String
C(0xFFE6C07B), // CharLiteral
C(0xFFCC88CC), // Punctuation
C(0xFF8CA6BF), // Preprocessor
C(0xFFD9E6F2), // Identifier
C(0xFFE8B333), // KnownIdentifier
C(0xFF7BB8FF), // PreprocIdentifier
C(0xFF6A7A8A), // Comment
C(0xFF6A7A8A), // MultiLineComment
C(0xFF141F29), // Background
C(0xFFE6F2FF), // Cursor
C(0x80305A80), // Selection
C(0x80B02020), // ErrorMarker
C(0xFF3A4A5A), // ControlCharacter
C(0x40F08000), // Breakpoint
C(0xFF4F6478), // LineNumber
C(0x40263A50), // CurrentLineFill
C(0x20263A50), // CurrentLineFillInactive
C(0x40264059), // CurrentLineEdge
};
}
}

View file

@ -6,7 +6,6 @@
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Engine.D3D9;
@ -17,30 +16,36 @@ internal static unsafe class DX9Backend
{
private static readonly Guid IID_IUnknown = new("00000000-0000-0000-C000-000000000046");
// ─── Native ImDrawData layout (pre-1.90 cimgui, x86) ─────────────
// Our cimgui.dll uses the old layout where CmdLists is a raw pointer (4 bytes)
// rather than ImVector (12 bytes). All offsets confirmed by memory dump.
private static Vector2 GetDisplayPos(IntPtr drawDataNative)
// Draw data is read through ImGui.NET's native structs (ImDrawData,
// ImDrawList, ImDrawCmd). That is only valid because Native\cimgui.dll is
// the exact 1.91.6 build ImGui.NET 1.91.6.1 was generated against;
// ImGuiSelfTest refuses to start ImGui if the loaded DLL is anything else.
// Converted-vertex scratch buffer, grown on demand and reused every frame
// (no per-frame native allocation on AC's thread). Freed in Shutdown.
private static CustomVertex* _vtxScratch;
private static int _vtxScratchCapacity;
private static CustomVertex* EnsureVertexScratch(int needed)
{
float x = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(drawDataNative, 20));
float y = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(drawDataNative, 24));
return new Vector2(x, y);
}
private static Vector2 GetDisplaySize(IntPtr drawDataNative)
{
float x = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(drawDataNative, 28));
float y = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(drawDataNative, 32));
return new Vector2(x, y);
}
private static int GetCmdListsCount(IntPtr drawDataNative)
{
return Marshal.ReadInt32(drawDataNative, 4);
}
private static IntPtr GetCmdListsArray(IntPtr drawDataNative)
{
return Marshal.ReadIntPtr(drawDataNative, 16);
if (needed > _vtxScratchCapacity)
{
int cap = _vtxScratchCapacity == 0 ? 8192 : _vtxScratchCapacity;
while (cap < needed) cap *= 2;
if (_vtxScratch != null) NativeMemory.Free(_vtxScratch);
_vtxScratch = (CustomVertex*)NativeMemory.Alloc((nuint)cap, (nuint)sizeof(CustomVertex));
_vtxScratchCapacity = cap;
}
return _vtxScratch;
}
// ── Diagnostics (/rc imgui diag): what the last RenderDrawData did ──
private static int _diagLists, _diagVtx, _diagCmds, _diagDraws, _diagSkipped, _diagFailed, _diagLastHr;
private static long _diagFrames;
public static string DescribeLastFrame() =>
$"render: initialized={_initialized} frames={_diagFrames} lastFrame lists={_diagLists} vtx={_diagVtx} cmds={_diagCmds} draws={_diagDraws} skipped={_diagSkipped} failedDraws={_diagFailed} lastFailHr=0x{_diagLastHr:X8} fontTex=0x{_fontTexture:X8}";
// ─── D3D9 constants ───────────────────────────────────────────────
private const uint D3DPT_TRIANGLELIST = 4;
private const uint D3DFMT_INDEX16 = 101;
@ -125,6 +130,12 @@ internal static unsafe class DX9Backend
// D3DSAMPLERSTATETYPE
private const uint D3DSAMP_MINFILTER = 5;
private const uint D3DSAMP_MAGFILTER = 6;
private const uint D3DSAMP_ADDRESSU = 1;
private const uint D3DSAMP_ADDRESSV = 2;
private const uint D3DSAMP_MIPFILTER = 7;
private const uint D3DTADDRESS_CLAMP = 3;
private const uint D3DTEXF_NONE = 0;
private const uint D3DRS_WRAP0 = 128;
// D3DTEXTUREFILTERTYPE
private const uint D3DTEXF_LINEAR = 2;
@ -133,16 +144,24 @@ internal static unsafe class DX9Backend
private const uint D3DFVF_XYZ = 0x002;
private const uint D3DFVF_DIFFUSE = 0x040;
private const uint D3DFVF_TEX1 = 0x100;
private const uint D3DFVF_CUSTOM = D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1;
private const uint D3DFVF_XYZRHW = 0x004;
private const uint D3DFVF_CUSTOM = D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1;
private const uint D3DRS_VERTEXBLEND = 151;
private const uint D3DRS_CLIPPLANEENABLE = 152;
// D3DBLENDOP
private const uint D3DBLENDOP_ADD = 1;
// ─── Vertex structure (D3D9 layout) ───────────────────────────────
[StructLayout(LayoutKind.Sequential)]
// Pre-transformed (screen-space) vertices, like VitalHud and the Avalonia
// quad. The first in-game test drew ImGui with XYZ vertices through the
// fixed-function transform stage and nothing appeared, although every
// draw call succeeded: state AC leaves in that stage (user clip planes,
// vertex blending) can discard the geometry. XYZRHW skips it entirely.
private struct CustomVertex
{
public float X, Y, Z;
public float X, Y, Z, Rhw;
public uint Col; // ARGB
public float U, V;
}
@ -358,6 +377,11 @@ internal static unsafe class DX9Backend
if (!CreateFontTexture(pDevice))
return false;
// Draw lists may exceed 64K vertices (radar walls); with this flag ImGui
// splits them into commands that carry a VtxOffset, which
// RenderDrawData applies, so 16-bit indices stay valid.
ImGuiNET.ImGui.GetIO().BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset;
_initialized = true;
RynthLog.Render("DX9Backend: ImGui resources initialized.");
return true;
@ -372,12 +396,19 @@ internal static unsafe class DX9Backend
public static void Shutdown()
{
ReleaseRetiredFontTexture();
if (_fontTexture != IntPtr.Zero)
{
var release = GetTexMethod<ReleaseD>(_fontTexture, TextureVTableIndex.Release);
release(_fontTexture);
_fontTexture = IntPtr.Zero;
}
if (_vtxScratch != null)
{
NativeMemory.Free(_vtxScratch);
_vtxScratch = null;
_vtxScratchCapacity = 0;
}
_initialized = false;
_coreInitialized = false;
}
@ -466,21 +497,54 @@ internal static unsafe class DX9Backend
public static void RenderDrawData(ImDrawDataPtr drawData, IntPtr pDevice)
{
if (!_initialized) return;
if (drawData.NativePtr == null) return;
ImDrawData* dd = drawData.NativePtr;
if (dd == null) return;
RenderLists((ImDrawList**)dd->CmdLists.Data, dd->CmdListsCount, dd->TotalVtxCount, dd->DisplayPos, dd->DisplaySize,
pDevice, midFrame: false);
}
IntPtr ddNative = (IntPtr)drawData.NativePtr;
int cmdListsCount = GetCmdListsCount(ddNative);
Vector2 displaySize = GetDisplaySize(ddNative);
Vector2 displayPos = GetDisplayPos(ddNative);
/// <summary>
/// Renders one draw list built outside ImGui's draw data (UnderUiLayer: the
/// world overlays drawn at AC's 3D→UI transition, in the middle of AC's frame).
/// Same state save/restore as <see cref="RenderDrawData"/>, plus the few
/// states a 3D pass can leave that the UI pass at EndScene never does.
/// Doesn't count in /rc imgui diag. AC's render thread.
/// </summary>
public static void RenderDrawList(ImDrawList* list, Vector2 displaySize, IntPtr pDevice)
{
if (!_initialized || list == null || pDevice == IntPtr.Zero) return;
RenderLists(&list, 1, -1, Vector2.Zero, displaySize, pDevice, midFrame: true);
}
/// <param name="totalVtx">For the diagnostics; -1: not a frame of ImGui's own (not counted).</param>
private static void RenderLists(ImDrawList** cmdLists, int cmdListsCount, int totalVtx, Vector2 displayPos, Vector2 displaySize,
IntPtr pDevice, bool midFrame)
{
if (cmdListsCount == 0) return;
if (displaySize.X <= 0 || displaySize.Y <= 0) return;
if (cmdLists == null) return;
IntPtr cmdListsArray = GetCmdListsArray(ddNative);
if (cmdListsArray == IntPtr.Zero) return;
if (totalVtx >= 0)
{
_diagFrames++;
_diagLists = cmdListsCount; _diagVtx = totalVtx;
_diagCmds = 0; _diagDraws = 0; _diagSkipped = 0; _diagFailed = 0;
}
if (false && _logCount < 3)
RynthLog.Render($"DX9: Rendering {cmdListsCount} lists, display={displaySize.X}x{displaySize.Y}");
// Mid-frame only (the 3D pass's leftovers): texture-coordinate wrapping,
// and sampler 0's addressing and mip filter.
uint oldWrap0 = 0, oldSamp0AddrU = 0, oldSamp0AddrV = 0, oldSamp0Mip = 0;
if (midFrame)
{
_getRenderState!(pDevice, D3DRS_WRAP0, out oldWrap0);
_getSamplerState!(pDevice, 0, D3DSAMP_ADDRESSU, out oldSamp0AddrU);
_getSamplerState!(pDevice, 0, D3DSAMP_ADDRESSV, out oldSamp0AddrV);
_getSamplerState!(pDevice, 0, D3DSAMP_MIPFILTER, out oldSamp0Mip);
_setRenderState!(pDevice, D3DRS_WRAP0, 0);
_setSamplerState!(pDevice, 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
_setSamplerState!(pDevice, 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
_setSamplerState!(pDevice, 0, D3DSAMP_MIPFILTER, D3DTEXF_NONE);
}
// ── Manual state save ────────────────────────────────────────
D3DVIEWPORT9 oldVp = default;
@ -500,6 +564,7 @@ internal static unsafe class DX9Backend
uint oldFillMode = 0, oldZWriteEnable = 0, oldAlphaTestEnable = 0;
uint oldClipping = 0, oldRangeFog = 0, oldSpecular = 0;
uint oldSrcBlendAlpha = 0, oldDestBlendAlpha = 0;
uint oldVertexBlend = 0, oldClipPlanes = 0;
uint oldTss0TexCoordIdx = 0, oldTss0TexTransFlags = 0;
// Stream source and index buffer — DrawIndexedPrimitiveUP sets these to NULL internally
IntPtr oldStreamData = IntPtr.Zero;
@ -548,6 +613,8 @@ internal static unsafe class DX9Backend
_getRenderState!(pDevice, D3DRS_SPECULARENABLE, out oldSpecular);
_getRenderState!(pDevice, D3DRS_SRCBLENDALPHA, out oldSrcBlendAlpha);
_getRenderState!(pDevice, D3DRS_DESTBLENDALPHA, out oldDestBlendAlpha);
_getRenderState!(pDevice, D3DRS_VERTEXBLEND, out oldVertexBlend);
_getRenderState!(pDevice, D3DRS_CLIPPLANEENABLE, out oldClipPlanes);
_getTexStageState!(pDevice, 0, D3DTSS_TEXCOORDINDEX, out oldTss0TexCoordIdx);
_getTexStageState!(pDevice, 0, D3DTSS_TEXTURETRANSFORMFLAGS, out oldTss0TexTransFlags);
_getStreamSource!(pDevice, 0, out oldStreamData, out oldStreamOffset, out oldStreamStride);
@ -555,153 +622,89 @@ internal static unsafe class DX9Backend
try
{
// Set up render state with correct display size
if (false && _logCount < 3) RynthLog.Render("DX9: step SetupRenderState");
SetupRenderStateNative(pDevice, displayPos, displaySize);
if (false && _logCount < 3) RynthLog.Render("DX9: step SetupRenderState done");
// ── Native ImDrawCmd offsets (imgui.h 1.91.6, x86) ──────────
// +0 ClipRect (4 floats, 16 bytes)
// +16 TextureId (ptr, 4 bytes)
// +20 VtxOffset (uint32)
// +24 IdxOffset (uint32)
// +28 ElemCount (uint32)
// +32 UserCallback (ptr, 4 bytes)
// +36 UserCallbackData (ptr, 4 bytes)
// Total = 40 bytes. The C# ImDrawCmd wrapper adds UserCallbackDataSize
// and UserCallbackDataOffset (8 more bytes = 48), but the native cimgui.dll
// does NOT have those fields. We read at stride 40 to match the native layout.
const int CmdStride = 40;
const int ResetRenderStateSentinel = -8; // ImDrawCallback_ResetRenderState
for (int n = 0; n < cmdListsCount; n++)
{
IntPtr listPtr = Marshal.ReadIntPtr(cmdListsArray, n * IntPtr.Size);
if (listPtr == IntPtr.Zero) continue;
ImDrawList* list = cmdLists[n];
if (list == null) continue;
// Read ImDrawList fields directly from native memory.
// ImDrawList starts with three ImVectors (each 12 bytes: Size/Capacity/Data).
// [0] CmdBuffer — ImVector<ImDrawCmd>
// [12] IdxBuffer — ImVector<ImDrawIdx>
// [24] VtxBuffer — ImVector<ImDrawVert>
int cmdCount = Marshal.ReadInt32(listPtr, 0); // CmdBuffer.Size
IntPtr cmdData = Marshal.ReadIntPtr(listPtr, 8); // CmdBuffer.Data
int idxCount = Marshal.ReadInt32(listPtr, 12); // IdxBuffer.Size
IntPtr idxBase = Marshal.ReadIntPtr(listPtr, 20); // IdxBuffer.Data
int vtxCount = Marshal.ReadInt32(listPtr, 24); // VtxBuffer.Size
IntPtr vtxBase = Marshal.ReadIntPtr(listPtr, 32); // VtxBuffer.Data
if (false && _logCount < 3)
RynthLog.Render($"DX9: list[{n}] vtx={vtxCount} idx={idxCount} cmds={cmdCount}");
int vtxCount = list->VtxBuffer.Size;
int cmdCount = list->CmdBuffer.Size;
if (vtxCount == 0 || cmdCount == 0) continue;
// One-time stride diagnostic — log what each cmd stride gives for cmd[1]
if (false && _logCount == 0 && n == 0 && cmdCount >= 2)
{
RynthLog.Render($"DX9: C# ImDrawCmd size = {Unsafe.SizeOf<ImDrawCmd>()}");
for (int ts = 32; ts <= 64; ts += 4)
{
IntPtr tp = cmdData + ts;
uint te = (uint)Marshal.ReadInt32(tp, 28);
float tx = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(tp, 0));
float tz = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(tp, 8));
uint tcb = (uint)Marshal.ReadInt32(tp, 32);
RynthLog.Render($"DX9: stride={ts}: elems={te} clipX={tx} clipZ={tz} cb=0x{tcb:X8}");
}
}
// One-time vertex diagnostic — verify ImDrawVert layout
if (false && _logCount == 0 && n == 0)
{
RynthLog.Render($"DX9: C# ImDrawVert size = {Unsafe.SizeOf<ImDrawVert>()}");
// Read first 3 vertices as raw bytes to verify layout
for (int vi = 0; vi < Math.Min(3, vtxCount); vi++)
{
IntPtr vp = vtxBase + vi * Unsafe.SizeOf<ImDrawVert>();
float px = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(vp, 0));
float py = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(vp, 4));
float ux = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(vp, 8));
float uy = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(vp, 12));
uint col = (uint)Marshal.ReadInt32(vp, 16);
RynthLog.Render($"DX9: vtx[{vi}] pos=({px},{py}) uv=({ux},{uy}) col=0x{col:X8}");
}
}
CustomVertex* vtxBuf = (CustomVertex*)NativeMemory.Alloc((nuint)(vtxCount * sizeof(CustomVertex)));
ImDrawVert* srcVtx = (ImDrawVert*)vtxBase;
ImDrawVert* srcVtx = (ImDrawVert*)list->VtxBuffer.Data;
ushort* idxBase = (ushort*)list->IdxBuffer.Data;
ImDrawCmd* cmds = (ImDrawCmd*)list->CmdBuffer.Data;
// ImGui vertices are pos/uv/RGBA; D3D9's FVF wants xyz/ARGB/uv.
CustomVertex* vtxBuf = EnsureVertexScratch(vtxCount);
for (int i = 0; i < vtxCount; i++)
{
vtxBuf[i].X = srcVtx[i].pos.X;
vtxBuf[i].Y = srcVtx[i].pos.Y;
// Screen pixels relative to the viewport; -0.5 is D3D9's
// half-pixel offset (the XYZ path put it in the projection).
vtxBuf[i].X = srcVtx[i].pos.X - displayPos.X - 0.5f;
vtxBuf[i].Y = srcVtx[i].pos.Y - displayPos.Y - 0.5f;
vtxBuf[i].Z = 0f;
vtxBuf[i].Rhw = 1f;
uint c = srcVtx[i].col;
vtxBuf[i].Col = (c & 0xFF00FF00) | ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16);
vtxBuf[i].U = srcVtx[i].uv.X;
vtxBuf[i].V = srcVtx[i].uv.Y;
}
if (false && _logCount < 3) RynthLog.Render($"DX9: list[{n}] vertex copy done");
for (int cmdI = 0; cmdI < cmdCount; cmdI++)
{
IntPtr cmdPtr = cmdData + cmdI * CmdStride;
ImDrawCmd* cmd = &cmds[cmdI];
// Read fields at known native offsets
float clipX = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(cmdPtr, 0));
float clipY = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(cmdPtr, 4));
float clipZ = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(cmdPtr, 8));
float clipW = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(cmdPtr, 12));
IntPtr textureId = Marshal.ReadIntPtr(cmdPtr, 16);
uint nativeIdxOff = (uint)Marshal.ReadInt32(cmdPtr, 24);
uint elemCount = (uint)Marshal.ReadInt32(cmdPtr, 28);
IntPtr userCallback = Marshal.ReadIntPtr(cmdPtr, 32);
if (userCallback != IntPtr.Zero)
if (cmd->UserCallback != IntPtr.Zero)
{
if (false && _logCount < 3)
RynthLog.Render($"DX9: cmd[{cmdI}] CALLBACK elems={elemCount} cb=0x{userCallback:X}");
if ((int)userCallback == ResetRenderStateSentinel)
if ((int)cmd->UserCallback == ResetRenderStateSentinel)
SetupRenderStateNative(pDevice, displayPos, displaySize);
// Non-sentinel callbacks: skip (no draw data, ElemCount expected 0)
// Other callbacks are not supported (no managed callbacks
// from inside the render path); they carry no geometry.
continue;
}
if (elemCount == 0)
{
if (false && _logCount < 3)
RynthLog.Render($"DX9: cmd[{cmdI}] ZERO-ELEM skip tex=0x{textureId:X}");
continue;
}
if (false && _logCount < 3)
RynthLog.Render($"DX9: cmd[{cmdI}] tex=0x{textureId:X} elems={elemCount} clip={clipX},{clipY},{clipZ},{clipW}");
uint elemCount = cmd->ElemCount;
_diagCmds++;
if (elemCount == 0) continue;
Vector4 clip = cmd->ClipRect;
RECT sr;
sr.Left = (int)(clipX - displayPos.X);
sr.Top = (int)(clipY - displayPos.Y);
sr.Right = (int)(clipZ - displayPos.X);
sr.Bottom = (int)(clipW - displayPos.Y);
sr.Left = (int)(clip.X - displayPos.X);
sr.Top = (int)(clip.Y - displayPos.Y);
sr.Right = (int)(clip.Z - displayPos.X);
sr.Bottom = (int)(clip.W - displayPos.Y);
// Inside the viewport (0,0,displaySize; set above): a pop-out's picture is
// only part of its ImGui display, so a full-display clip rect reaches past
// it on every side. Nothing outside the viewport is drawn anyway.
if (sr.Left < 0) sr.Left = 0;
if (sr.Top < 0) sr.Top = 0;
if (sr.Right > (int)displaySize.X) sr.Right = (int)displaySize.X;
if (sr.Bottom > (int)displaySize.Y) sr.Bottom = (int)displaySize.Y;
if (sr.Right <= sr.Left || sr.Bottom <= sr.Top) { _diagSkipped++; continue; }
_setScissorRect!(pDevice, &sr);
_setTexture!(pDevice, 0, textureId);
_setTexture!(pDevice, 0, cmd->TextureId);
ushort* pIdxData = (ushort*)idxBase + nativeIdxOff;
if (false && _logCount < 3)
RynthLog.Render($"DX9: cmd[{cmdI}] DrawIndexedPrimUP primCount={elemCount / 3}");
_drawIndexedPrimUP!(pDevice,
D3DPT_TRIANGLELIST, 0, (uint)vtxCount,
// DrawIndexedPrimitiveUP has no base-vertex argument, so the
// command's VtxOffset is applied by offsetting the vertex pointer.
uint vtxOffset = cmd->VtxOffset;
if (vtxOffset >= (uint)vtxCount) { _diagSkipped++; continue; }
int hr = _drawIndexedPrimUP!(pDevice,
D3DPT_TRIANGLELIST, 0, (uint)vtxCount - vtxOffset,
elemCount / 3,
(IntPtr)pIdxData, D3DFMT_INDEX16,
(IntPtr)vtxBuf, (uint)sizeof(CustomVertex));
if (false && _logCount < 3) RynthLog.Render($"DX9: cmd[{cmdI}] draw done");
(IntPtr)(idxBase + cmd->IdxOffset), D3DFMT_INDEX16,
(IntPtr)(vtxBuf + vtxOffset), (uint)sizeof(CustomVertex));
_diagDraws++;
if (hr < 0) { _diagFailed++; _diagLastHr = hr; }
}
NativeMemory.Free(vtxBuf);
}
}
finally
{
_logCount++;
// ── Manual state restore ─────────────────────────────────
_setRenderState!(pDevice, D3DRS_CULLMODE, oldCull);
_setRenderState!(pDevice, D3DRS_LIGHTING, oldLighting);
@ -745,10 +748,19 @@ internal static unsafe class DX9Backend
_setRenderState!(pDevice, D3DRS_SPECULARENABLE, oldSpecular);
_setRenderState!(pDevice, D3DRS_SRCBLENDALPHA, oldSrcBlendAlpha);
_setRenderState!(pDevice, D3DRS_DESTBLENDALPHA, oldDestBlendAlpha);
_setRenderState!(pDevice, D3DRS_VERTEXBLEND, oldVertexBlend);
_setRenderState!(pDevice, D3DRS_CLIPPLANEENABLE, oldClipPlanes);
_setTexStageState!(pDevice, 0, D3DTSS_TEXCOORDINDEX, oldTss0TexCoordIdx);
_setTexStageState!(pDevice, 0, D3DTSS_TEXTURETRANSFORMFLAGS, oldTss0TexTransFlags);
_setStreamSource!(pDevice, 0, oldStreamData, oldStreamOffset, oldStreamStride);
_setIndices!(pDevice, oldIndexBuffer);
if (midFrame)
{
_setRenderState!(pDevice, D3DRS_WRAP0, oldWrap0);
_setSamplerState!(pDevice, 0, D3DSAMP_ADDRESSU, oldSamp0AddrU);
_setSamplerState!(pDevice, 0, D3DSAMP_ADDRESSV, oldSamp0AddrV);
_setSamplerState!(pDevice, 0, D3DSAMP_MIPFILTER, oldSamp0Mip);
}
// Release COM refs we obtained
if (oldTexture != IntPtr.Zero)
@ -842,28 +854,35 @@ internal static unsafe class DX9Backend
// FVF — SetStreamSource is NOT called here; DrawIndexedPrimitiveUP uses user-memory
// pointers directly and does not require a bound vertex stream.
_setFVF!(dev, D3DFVF_CUSTOM);
_setRenderState!(dev, D3DRS_VERTEXBLEND, 0); // D3DVBF_DISABLE
_setRenderState!(dev, D3DRS_CLIPPLANEENABLE, 0); // no user clip planes
// Orthographic projection — D3D9 pixel centers are at +0.5 (not +0.0 like D3D10+)
float L = displayPos.X + 0.5f;
float R = displayPos.X + displaySize.X + 0.5f;
float T = displayPos.Y + 0.5f;
float B = displayPos.Y + displaySize.Y + 0.5f;
// No transforms: XYZRHW vertices are already in viewport pixels (see CustomVertex).
}
D3DMATRIX identity;
identity.M11 = 1; identity.M12 = 0; identity.M13 = 0; identity.M14 = 0;
identity.M21 = 0; identity.M22 = 1; identity.M23 = 0; identity.M24 = 0;
identity.M31 = 0; identity.M32 = 0; identity.M33 = 1; identity.M34 = 0;
identity.M41 = 0; identity.M42 = 0; identity.M43 = 0; identity.M44 = 1;
/// <summary>
/// After the font atlas was rebuilt: replace the font texture. Render thread.
/// The old texture is kept one more frame: UnderUiLayer's list from the frame
/// before may still be drawn by this frame's fallback, and it names the old one.
/// </summary>
public static bool RebuildFontTexture(IntPtr pDevice)
{
ReleaseRetiredFontTexture();
_retiredFontTexture = _fontTexture;
_fontTexture = IntPtr.Zero;
return CreateFontTexture(pDevice);
}
D3DMATRIX projection;
projection.M11 = 2f / (R - L); projection.M12 = 0f; projection.M13 = 0f; projection.M14 = 0f;
projection.M21 = 0f; projection.M22 = 2f / (T - B); projection.M23 = 0f; projection.M24 = 0f;
projection.M31 = 0f; projection.M32 = 0f; projection.M33 = 0.5f; projection.M34 = 0f;
projection.M41 = (L + R) / (L - R); projection.M42 = (T + B) / (B - T); projection.M43 = 0.5f; projection.M44 = 1f;
// The font texture a rebuild replaced; released at the next frame's build.
private static IntPtr _retiredFontTexture;
_setTransform!(dev, D3DTS_WORLD, &identity);
_setTransform!(dev, D3DTS_VIEW, &identity);
_setTransform!(dev, D3DTS_PROJECTION, &projection);
/// <summary>Releases the texture the last rebuild replaced. Render thread, at the start of a frame's build.</summary>
public static void ReleaseRetiredFontTexture()
{
if (_retiredFontTexture == IntPtr.Zero) return;
var release = GetTexMethod<ReleaseD>(_retiredFontTexture, TextureVTableIndex.Release);
release(_retiredFontTexture);
_retiredFontTexture = IntPtr.Zero;
}
private static bool CreateFontTexture(IntPtr pDevice)
@ -921,27 +940,52 @@ internal static unsafe class DX9Backend
// Store texture ID for ImGui
io.Fonts.SetTexID(_fontTexture);
// Force native TexID write — managed wrapper can mismatch on x86
nint texId = io.Fonts.TexID;
unsafe
{
byte* ioPtr = (byte*)ImGuiNET.ImGui.GetIO().NativePtr;
IntPtr fontsPtr = *(IntPtr*)(ioPtr + 36);
*(IntPtr*)(fontsPtr + 4) = _fontTexture;
}
if (texId == 0)
{
unsafe
{
byte* ioPtr = (byte*)ImGuiNET.ImGui.GetIO().NativePtr;
IntPtr fontsPtr = *(IntPtr*)(ioPtr + 36);
*(IntPtr*)(fontsPtr + 4) = _fontTexture;
}
}
return true;
}
/// <summary>
/// A managed-pool A8R8G8B8 texture (it survives a device reset) holding RGBA pixels
/// (script window icons). Zero on failure. AC's render thread, after <see cref="InitCore"/>.
/// </summary>
public static IntPtr CreateTextureRgba(IntPtr pDevice, int width, int height, ReadOnlySpan<byte> rgba)
{
if (_createTexture == null || pDevice == IntPtr.Zero || width <= 0 || height <= 0
|| rgba.Length < width * height * 4)
return IntPtr.Zero;
int hr = _createTexture(pDevice, (uint)width, (uint)height, 1, 0,
D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out IntPtr tex, IntPtr.Zero);
if (hr < 0 || tex == IntPtr.Zero)
return IntPtr.Zero;
var lockRect = GetTexMethod<TexLockRectD>(tex, TextureVTableIndex.LockRect);
var unlockRect = GetTexMethod<TexUnlockRectD>(tex, TextureVTableIndex.UnlockRect);
D3DLOCKED_RECT locked;
if (lockRect(tex, 0, &locked, IntPtr.Zero, 0) < 0 || locked.pBits == IntPtr.Zero)
{
ReleaseComObject(tex);
return IntPtr.Zero;
}
byte* dst = (byte*)locked.pBits;
for (int y = 0; y < height; y++)
{
ReadOnlySpan<byte> srcRow = rgba.Slice(y * width * 4, width * 4);
byte* dstRow = dst + y * locked.Pitch;
for (int x = 0; x < width; x++)
{
int i = x * 4;
dstRow[i + 0] = srcRow[i + 2]; // B
dstRow[i + 1] = srcRow[i + 1]; // G
dstRow[i + 2] = srcRow[i + 0]; // R
dstRow[i + 3] = srcRow[i + 3]; // A
}
}
unlockRect(tex, 0);
return tex;
}
/// <summary>Releases a texture made by <see cref="CreateTextureRgba"/>. AC's render thread.</summary>
public static void ReleaseTexture(IntPtr tex) => ReleaseComObject(tex);
private static void CacheDelegates(IntPtr pDevice)
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
@ -1067,7 +1111,11 @@ internal static unsafe class DX9Backend
// core init flag so this path runs even when EnableImGuiBackend=false.
if (!_coreInitialized || pDevice == IntPtr.Zero) return;
if (!D3D9.GameMatrixCapture.HasCapturedFrame) return;
if (D3D9.Nav3DRenderer.RingCount == 0 && D3D9.Nav3DRenderer.LineCount == 0 && D3D9.Nav3DRenderer.TriangleCount == 0) return;
// One snapshot of the committed frame for the whole draw (the pump may
// commit a new one meanwhile; this one stays intact for a tick).
D3D9.Nav3DRenderer.NavBuffer frame = D3D9.Nav3DRenderer.Ready;
int triCount = frame.TriCount, lineCount = frame.LineCount, ringCount = frame.RingCount;
if (ringCount == 0 && lineCount == 0 && triCount == 0) return;
EnsureNavTrig();
@ -1163,39 +1211,33 @@ internal static unsafe class DX9Backend
// vertex buffer and submitted in a single DrawPrimitiveUP — at
// high slope-radius settings we can have 4000+ triangles per
// frame, and one DP-UP per triangle was visibly frame-dropping.
int triCount = D3D9.Nav3DRenderer.TriangleCount;
if (triCount > 0)
{
EnsureNavTriBatch(triCount * 3);
NavVertex* batch = (NavVertex*)_navTriBatch;
for (int i = 0; i < triCount; i++)
{
D3D9.Nav3DRenderer.GetTriangle(i,
out float x1, out float y1, out float z1,
out float x2, out float y2, out float z2,
out float x3, out float y3, out float z3, out uint color);
uint color = frame.TriColor[i];
int b = i * 3;
batch[b ].X = x1; batch[b ].Y = y1; batch[b ].Z = z1; batch[b ].Col = color;
batch[b + 1].X = x2; batch[b + 1].Y = y2; batch[b + 1].Z = z2; batch[b + 1].Col = color;
batch[b + 2].X = x3; batch[b + 2].Y = y3; batch[b + 2].Z = z3; batch[b + 2].Col = color;
batch[b ].X = frame.TriX1[i]; batch[b ].Y = frame.TriY1[i]; batch[b ].Z = frame.TriZ1[i]; batch[b ].Col = color;
batch[b + 1].X = frame.TriX2[i]; batch[b + 1].Y = frame.TriY2[i]; batch[b + 1].Z = frame.TriZ2[i]; batch[b + 1].Col = color;
batch[b + 2].X = frame.TriX3[i]; batch[b + 2].Y = frame.TriY3[i]; batch[b + 2].Z = frame.TriZ3[i]; batch[b + 2].Col = color;
}
_drawPrimUP!(pDevice, D3DPT_TRIANGLELIST, (uint)triCount, (IntPtr)batch, (uint)sizeof(NavVertex));
}
// Draw lines (extruded XZ-plane quads — for edges/strips)
for (int i = 0; i < D3D9.Nav3DRenderer.LineCount; i++)
for (int i = 0; i < lineCount; i++)
{
D3D9.Nav3DRenderer.GetLine(i, out float x1, out float y1, out float z1,
out float x2, out float y2, out float z2, out float thick, out uint color);
DrawNavLine(pDevice, x1, y1, z1, x2, y2, z2, thick, color);
DrawNavLine(pDevice, frame.LineX1[i], frame.LineY1[i], frame.LineZ1[i],
frame.LineX2[i], frame.LineY2[i], frame.LineZ2[i], frame.LineThick[i], frame.LineColor[i]);
}
// Draw rings
for (int i = 0; i < D3D9.Nav3DRenderer.RingCount; i++)
for (int i = 0; i < ringCount; i++)
{
D3D9.Nav3DRenderer.GetRing(i, out float x, out float y, out float z,
out float radius, out float thick, out float height, out uint color);
DrawNavRing(pDevice, x, y, z, radius, thick, height, color);
DrawNavRing(pDevice, frame.RingX[i], frame.RingY[i], frame.RingZ[i],
frame.RingRadius[i], frame.RingThick[i], frame.RingHeight[i], frame.RingColor[i]);
}
if (_nav3DLogCount == 0)

View file

@ -11,7 +11,7 @@
// * ImGui-gated (only when EngineSettings.EnableImGuiBackend is true):
// Win32Backend.NewFrame / DX9Backend.NewFrame, ImGui.NewFrame/EndFrame/
// Render, RynthCoreShell + plugin RenderAll, DX9Backend.RenderDrawData,
// mouse/keyboard capture flag updates, multi-viewport platform pump.
// mouse/keyboard capture flag updates.
//
// Renamed 2026-05-10 from ImGuiController — the type now owns more than
// ImGui's frame; the ImGui block is just one branch of its work.
@ -42,17 +42,6 @@ internal static class EngineFrameController
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool GetClientRect(IntPtr hWnd, out ClientRect lpRect);
[DllImport("user32.dll")]
private static extern bool ClientToScreen(IntPtr hWnd, ref ClientPoint lpPoint);
[StructLayout(LayoutKind.Sequential)]
private struct ClientRect { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
private struct ClientPoint { public int X, Y; }
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
private static bool _imguiInitialized;
@ -103,6 +92,8 @@ internal static class EngineFrameController
RynthLog.Render($"EngineFrameController: Game HWND = 0x{_gameHwnd:X8}");
EntryPoint.GameHwnd = _gameHwnd;
_coreResolved = true;
// Pop-outs hold D3DPOOL_DEFAULT render targets: release them before AC resets a lost device.
D3D9.DeviceResetHook.InstallFromDevice(pDevice);
return true;
}
@ -114,6 +105,11 @@ internal static class EngineFrameController
if (!EnsureCore(pDevice))
return false;
// Before any context exists: the loaded cimgui.dll must be the exact
// build ImGui.NET wraps, or every struct read below is at wrong offsets.
if (!ImGuiSelfTest.Run(EntryPoint.ImGuiNativeHandle))
return false;
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
if (previousContext != IntPtr.Zero)
RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context.");
@ -143,23 +139,20 @@ internal static class EngineFrameController
}
io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
// ViewportsEnable was enabling ImGui multi-viewport platform/renderer
// callbacks against a cimgui.dll that is NOT built with
// IMGUI_ENABLE_VIEWPORTS. The platform/renderer callback chain then
// recursed (Platform → Renderer → Platform → ...) on AC's render
// thread, eating the 1MB stack in ~17s and AV'ing in ntdll mid-push.
// CLAUDE.md flags this: Multi-viewport "requires cimgui built with
// IMGUI_ENABLE_VIEWPORTS" — flag re-introduced this in the engine
// and triggered the silent stack-overflow on every login.
// io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable;
// Popped-out plugin windows use WS_EX_TOOLWINDOW so they don't show
// up as extra "Asheron's Call" entries in the taskbar — critical for
// users running many clients side by side.
io.ConfigViewportsNoTaskBarIcon = true;
ImGuiNET.ImGui.StyleColorsDark();
// Multi-viewport (ViewportsEnable) is deliberately never enabled: it
// runs many native->managed platform/renderer callbacks per frame on
// AC's thread and creates HWNDs from inside EndScene. Pop-out panels,
// if built, are driven explicitly by the engine instead
// (docs/IMGUI_PARITY_PLAN.md section 4.2).
// One-shot offset probe for diagnostics — safe to keep installed.
ViewportProbe.Run();
// DPI scale for fonts and style metrics. Logged next to Avalonia's
// scale: docked positions are stored in Avalonia logical units, so
// the two must agree for a panel to land in the same place in
// either face (plan section 4.4).
_uiScale = UiScale.ForWindow(_gameHwnd);
RynthLog.UI($"EngineFrameController: ImGui scale {_uiScale:0.##} (Avalonia input scale {UI.AvaloniaOverlay.InputScale:0.##}).");
RynthTheme.Apply(ImGuiNET.ImGui.GetStyle(), _uiScale);
ImGuiFonts.Build(io, _uiScale);
if (!Win32Backend.Init(_gameHwnd))
return false;
@ -167,26 +160,11 @@ internal static class EngineFrameController
if (!DX9Backend.InitImGui(pDevice))
return false;
// Viewport backends only run when ViewportsEnable is on. Installing
// their callbacks on PlatformIO without the flag has no upside and
// just expands the crash surface.
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
bool platformOk = ViewportPlatformBackend.Init(_gameHwnd);
bool rendererOk = platformOk && ViewportRendererBackend.Init(pDevice);
if (!platformOk || !rendererOk)
{
RynthLog.Render($"EngineFrameController: viewport init failed (platform={platformOk}, renderer={rendererOk}) — disabling ViewportsEnable.");
io.ConfigFlags &= ~ImGuiConfigFlags.ViewportsEnable;
}
ViewportPlatformBackend.ImGuiContext = _context;
}
_lastFrameTicks = Stopwatch.GetTimestamp();
_imguiInitialized = true;
initSucceeded = true;
RynthLog.Render("EngineFrameController: Fully initialized - RynthCore shell active.");
RynthLog.UI("EngineFrameController: ImGui initialized.");
return true;
}
finally
@ -213,14 +191,16 @@ internal static class EngineFrameController
{
ImGuiNET.ImGui.SetCurrentContext(contextToDestroy);
// Zero the WndProc context guard BEFORE DestroyContext so any
// deferred OS messages that arrive at viewport HWNDs during or
// after teardown don't try to call into freed ImGui memory.
ViewportPlatformBackend.ImGuiContext = IntPtr.Zero;
PluginManager.ShutdownAll();
// No context may be destroyed while a font worker runs (ImGuiFonts, re-bake note).
ImGuiFonts.WaitForWorkers();
// Pop-outs share the main font atlas: their contexts go before the main one.
ImGuiPopOuts.Shutdown();
OverlayTextureRenderer.Shutdown();
ViewportRendererBackend.Shutdown();
ViewportPlatformBackend.Shutdown();
// Its lists are drawn by DX9Backend from the DIP hook, which is still live.
UnderUiLayer.Shutdown();
ScriptIcons.Shutdown(); // script window icon textures, before the backend goes
RetailSprites.Shutdown(); // retail UI pictures (Inventory Classic view), likewise
DX9Backend.Shutdown();
// Do NOT call Win32Backend.Shutdown() here. EngineLifecycle.Shutdown
// owns that step explicitly, AFTER AvaloniaOverlay.Stop — floating
@ -230,6 +210,7 @@ internal static class EngineFrameController
// those destroys to AC's proc, which ignores them, and the orphaned
// panel HWND outlives the engine load.
ImGuiNET.ImGui.DestroyContext(contextToDestroy);
ImGuiFonts.Free(); // the atlas referenced these buffers; the context is gone now
_imguiInitialized = false;
_coreResolved = false;
@ -299,6 +280,11 @@ internal static class EngineFrameController
// is the dump-verified 0x0067E779 READ-AV when done on the pump thread.
// Sampled every frame (positions are volatile), zero-alloc.
Compatibility.ClientObjectHooks.PrefetchPositions();
// Refresh the cached player id every frame (unthrottled: the native leaf is
// two loads) and the other small main-thread snapshots (cast gate, pose,
// ...). Off-thread callers are served from these instead of reading AC
// memory from the pump thread. Also runs from the Client::UseTime drain.
Compatibility.MainThreadSnapshots.Tick();
// Same main-thread guard: snapshot XP/luminance/deaths/vitae (main-thread-only
// Inq* reads) so the GetEngineStatusJson host bridge can serve them off-thread (throttled).
Compatibility.ClientObjectHooks.PrefetchPlayerStats();
@ -363,8 +349,21 @@ internal static class EngineFrameController
// calls it at all.
// ── ImGui-gated work ─────────────────────────────────────────
if (Plugins.EngineSettings.EnableImGuiBackend)
RunImGuiFrame(pDevice);
// The frame is BUILT here and SUBMITTED after the Nav3D fallback and
// the vital HUD, so ImGui windows sit above both. The Avalonia quad
// (EndSceneHook, after this returns) stays topmost while both stacks
// run, matching input order: Avalonia gets the first hit test.
bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend;
bool imguiBuilt = false;
long uiTicks = 0;
if (!imguiEnabled)
_imguiIdle = true; // switched off in game: input state resets when it comes back
else
{
long t0 = Stopwatch.GetTimestamp();
imguiBuilt = BuildImGuiFrame(pDevice);
uiTicks = Stopwatch.GetTimestamp() - t0;
}
// Fallback render — only fires when the injector missed this
// frame's 3D→UI transition. _coreInitialized is enough — this
@ -372,13 +371,22 @@ internal static class EngineFrameController
if (!nav3DAlreadyRendered)
DX9Backend.RenderNav3D(pDevice);
// Custom D3D9 vital HUD (Health/Stamina/Mana). Always-on (independent
// of EnableImGuiBackend) so it shows even in Avalonia-only mode; drawn
// last so it sits on top of the world + AC UI. Reads the vitals
// snapshot maintained on this same (AC main) thread and does its own
// device state save/restore. No-op until vitals are seeded.
if (Plugins.EngineSettings.DrawCustomVitalBars)
D3D9.VitalHud.Draw(pDevice);
// The world overlays built last frame (nameplates, combat text) normally
// drew at this frame's 3D->UI transition, under AC's UI. If that wasn't
// seen, they draw here - still under the ImGui panels. No-op when they
// already drew (UnderUiLayer presents a list once).
UnderUiLayer.PresentFallback(pDevice);
if (imguiEnabled)
{
long t0 = Stopwatch.GetTimestamp();
if (imguiBuilt)
SubmitImGuiFrame(pDevice);
// Popped-out panels: their own contexts, windows and render targets.
if (_imguiInitialized)
ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive);
UiFrameStats.Record(uiTicks + (Stopwatch.GetTimestamp() - t0));
}
}
catch (Exception ex)
{
@ -392,9 +400,30 @@ internal static class EngineFrameController
// never fires again — every subsequent frame falls back to the
// end-of-frame draw (which paints over the UI).
D3D9.Nav3DRenderInjector.ResetFrame();
// What this frame built for the world overlays is presented next frame.
UnderUiLayer.EndFrame();
}
}
/// <summary>
/// The main-thread prefetches of the always-on pipeline above, for a client without
/// the EndScene hook (Decal in the process): called from the Client::UseTime detour
/// (AC's main thread) once GameTickHooks.HeadlessPrefetch is set. Same calls, same
/// order, each throttled and main-thread-gated internally. The EndScene path doesn't
/// use this (it runs the calls inline, unchanged).
/// </summary>
internal static void RunHeadlessPrefetch()
{
Compatibility.ClientObjectHooks.PrefetchPlayerSkills();
Compatibility.ClientObjectHooks.PrefetchKnownSpells();
Compatibility.ClientObjectHooks.PrefetchAttackable();
Compatibility.ClientObjectHooks.PrefetchObjectIdentity();
Compatibility.ClientObjectHooks.PrefetchPositions();
Compatibility.ClientObjectHooks.PrefetchPlayerStats();
try { Plugins.PluginManager.TrySeedLiveObjectsFromCObjectMaintOnce(); }
catch (Exception ex) { RynthLog.Plugin($"CObjectMaint seed threw {ex.GetType().Name}: {ex.Message}"); }
}
/// <summary>
/// The plugin lifecycle/tick work that used to run inline in
/// <see cref="OnEndScene"/>. Driven by the dedicated managed plugin pump
@ -419,15 +448,28 @@ internal static class EngineFrameController
return; // never re-enter PluginManager from two stacks
try
{
// Plugins only get the ImGui context when they may draw with it
// (EnableImGuiShell, FORCE-gated). The engine's own ImGui panels
// don't need plugins to see it, and handing it over switched
// RynthAi into its legacy-ImGui setup (first ImGui-on test,
// 2026-09-28) - plugins must behave exactly as in Avalonia-only mode.
IntPtr pluginContext = Plugins.EngineSettings.EnableImGuiShell ? _context : IntPtr.Zero;
if (!_pluginsInitialized)
{
_pluginsInitialized = true;
PluginManager.InitPlugins(_context, device, _gameHwnd);
PluginManager.InitPlugins(pluginContext, device, _gameHwnd);
}
PluginManager.ProcessPendingActions(_context, device, _gameHwnd);
// Decal bridge mode with the in-game renderer (DecalInGameImGui): chat and
// chat-bar lines come from the bridge. One flag check in every other client.
if (Compatibility.DecalBridgeHost.Active)
Compatibility.DecalBridgeHost.Drain();
PluginManager.ProcessPendingActions(pluginContext, device, _gameHwnd);
PluginManager.FlushPendingDeletes(); // closes the create→delete race window
PluginManager.TickAll();
// Panel data: plugin exports for the UI are called here, on the same
// thread as the plugin tick, and published as immutable snapshots.
UI.Data.UiDataHub.Step();
}
catch (Exception ex)
{
@ -439,26 +481,97 @@ internal static class EngineFrameController
}
}
/// <summary>
/// Runs the ImGui-specific portion of the per-frame pipeline:
/// backend NewFrame plumbing, ImGui frame open/close, RynthCore shell +
/// plugin RenderAll, draw-data submission, capture flag update, and the
/// multi-viewport platform pump. Bypassed entirely when
/// EngineSettings.EnableImGuiBackend is false.
/// </summary>
private static void RunImGuiFrame(IntPtr pDevice)
/// <summary>True when anything ImGui should be drawn this frame.</summary>
private static bool HasImGuiContent()
{
if (_imguiInitFailed) return;
if (Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled) return true;
if (!PanelsLive) return false;
ImGuiPanelHost.RestoreOnce();
return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame;
}
/// <summary>
/// Panel faces show only in the world, like the Avalonia overlay (hidden
/// between characters, not closed).
/// </summary>
private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete;
/// <summary>DPI scale the fonts and style were built for (see Init).</summary>
private static float _uiScale = 1f;
/// <summary>The scale the fonts and style were built for.</summary>
internal static float FontScale => _uiScale;
/// <summary>A popped-out panel was clicked: the main context's text edit ends next frame. AC thread.</summary>
internal static void DropMainTextFocus() => _dropImGuiTextFocus = true;
// ── Diagnostics (/rc imgui diag) ─────────────────────────────────
private static long _framesBuilt;
private static System.Numerics.Vector2 _lastDisplaySize;
/// <summary>One line per fact about the ImGui layer's state. Game thread (reads plain fields).</summary>
internal static System.Collections.Generic.List<string> DescribeState()
{
var lines = new System.Collections.Generic.List<string>
{
$"layer={(Plugins.EngineSettings.EnableImGuiBackend ? "on" : "off")} initialized={_imguiInitialized} initFailed={_imguiInitFailed} selfTest={ImGuiSelfTest.LastResult}",
$"inWorld={PanelsLive} content={HasImGuiContentNoRestore()} idle={_imguiIdle} framesBuilt={_framesBuilt} uiScale={_uiScale:0.##} avaloniaScale={UI.AvaloniaOverlay.InputScale:0.##} display={_lastDisplaySize.X:0}x{_lastDisplaySize.Y:0}",
DX9Backend.DescribeLastFrame(),
UnderUiLayer.Describe(),
$"capture: {Win32Backend.DescribeCapture()}",
};
lines.AddRange(ImGuiPopOuts.Describe());
return lines;
}
private static bool HasImGuiContentNoRestore() =>
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame));
// Keyboard owner between the stacks (plan §3.2 d): whichever side started
// text entry most recently keeps the keyboard.
private static bool _prevImGuiText, _prevAvaloniaText, _dropImGuiTextFocus;
/// <summary>True while frames are being skipped because nothing ImGui is open.</summary>
private static bool _imguiIdle = true;
/// <summary>
/// Builds the ImGui frame (NewFrame ... Render) and publishes the capture
/// flags. Returns true when there is draw data for <see cref="SubmitImGuiFrame"/>.
/// Only called while EngineSettings.EnableImGuiBackend is true.
///
/// Early-out: with no ImGui content there is no ImGui frame at all. Queued
/// input is dropped (nothing would drain it) and capture flags are cleared,
/// so the idle cost is one GetClientRect.
/// </summary>
private static bool BuildImGuiFrame(IntPtr pDevice)
{
if (_imguiInitFailed) return false;
if (!_imguiInitialized)
{
// Initialised as soon as the backend is enabled (not lazily on first
// content), so the cimgui self-test result is in the log at startup.
if (!Init(pDevice))
{
_imguiInitFailed = true;
return;
return false;
}
}
Win32Backend.UpdateClientMetrics(out int clientW, out int clientH);
// Monster nameplates: pick the monsters (throttled) before deciding
// whether there is a frame to build, so plates alone can ask for one.
Hud.MonsterHud.Update(PanelsLive);
if (!HasImGuiContent())
{
_imguiIdle = true;
Win32Backend.DiscardQueuedInput();
Win32Backend.ClearCaptureFlags();
return false;
}
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
ImGuiNET.ImGui.SetCurrentContext(_context);
bool frameStarted = false;
@ -466,11 +579,36 @@ internal static class EngineFrameController
try
{
_frameCount++;
DX9Backend.NewFrame();
Win32Backend.NewFrame();
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
long now = Stopwatch.GetTimestamp();
if (_imguiIdle)
{
// Resuming: keys/buttons released while idle must not read as held,
// and the idle gap must not become one huge DeltaTime.
_imguiIdle = false;
Win32Backend.ResetImGuiInputState(io);
_lastFrameTicks = now;
}
_frameCount++;
// A panel's text size changed: re-bake the fonts (only the sizes in
// use) and replace the font texture, between frames.
// The new atlas is baked on a worker (ImGuiFonts.PumpRebuild), once per run of
// changes (RequestRebuild debounces); here it is swapped in and its texture made.
DX9Backend.ReleaseRetiredFontTexture(); // the texture a rebuild replaced last frame
long rebuildStart = Stopwatch.GetTimestamp();
if (ImGuiFonts.PumpRebuild(io, _uiScale, out string rebuilt))
{
DX9Backend.RebuildFontTexture(pDevice);
double rebuildMs = (Stopwatch.GetTimestamp() - rebuildStart) * 1000.0 / Stopwatch.Frequency;
RynthLog.UI($"ImGuiFonts: text size change: {rebuilt}; render thread {rebuildMs:0.0} ms (swap + texture).");
}
// Script window icons decoded since the last frame become textures, and the least
// recently drawn go, before anything draws (no draw list points at them any more).
ScriptIcons.BeginFrame(pDevice);
RetailSprites.BeginFrame(pDevice); // retail UI pictures decoded since the last frame (kept, never evicted)
DX9Backend.NewFrame();
Win32Backend.NewFrame(clientW, clientH);
// Fallback: if Win32Backend could not determine display size, read from the D3D9 viewport.
if (io.DisplaySize.X <= 1 || io.DisplaySize.Y <= 1)
@ -480,65 +618,52 @@ internal static class EngineFrameController
io.DisplaySize = new System.Numerics.Vector2(vpW, vpH);
}
long now = Stopwatch.GetTimestamp();
float dt = (float)(now - _lastFrameTicks) / Stopwatch.Frequency;
_lastFrameTicks = now;
io.DeltaTime = dt > 0f ? dt : 1f / 60f;
// With ViewportsEnable on, ImGui routes mouse and window positions in
// absolute screen coords. The main viewport's Pos must equal the game
// client's screen origin so clicks over the main viewport map to the
// correct windows, and popped-out viewports share a coord system with
// the main one.
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
int screenX = 0, screenY = 0;
if (_gameHwnd != IntPtr.Zero)
{
ClientPoint p = new ClientPoint { X = 0, Y = 0 };
if (ClientToScreen(_gameHwnd, ref p)) { screenX = p.X; screenY = p.Y; }
}
ImGuiViewportPtr mainVp = ImGuiNET.ImGui.GetMainViewport();
mainVp.Pos = new System.Numerics.Vector2(screenX, screenY);
mainVp.Size = io.DisplaySize;
mainVp.WorkPos = new System.Numerics.Vector2(screenX, screenY);
mainVp.WorkSize = io.DisplaySize;
}
ImGuiNET.ImGui.NewFrame();
frameStarted = true;
// EnableImGuiShell gates the in-AC ImGui surface as a whole: both the
// RynthCore overlay bar and any plugin-drawn ImGui windows. Plugins
// still load, init, and tick when this is off — they just don't
// draw, so Avalonia panels can drive them via the plugin's C exports.
if (_dropImGuiTextFocus)
{
// An Avalonia TextBox took the keyboard: end ImGui's text edit.
_dropImGuiTextFocus = false;
ImGuiNET.ImGui.SetWindowFocus(null);
}
// EnableImGuiShell gates the old diagnostic shell and plugin-drawn
// ImGui windows (plugin code on AC's thread: FORCE-gated, stays off).
if (Plugins.EngineSettings.EnableImGuiShell)
{
RynthCoreShell.Render(_frameCount);
PluginManager.RenderAll();
}
bool captureMouse =
ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow) ||
ImGuiNET.ImGui.IsAnyItemActive();
bool captureKeyboard = ImGuiNET.ImGui.IsAnyItemActive();
if (PanelsLive)
{
// World overlays: built into UnderUiLayer's list, drawn next frame at
// AC's 3D->UI transition (under AC's UI and every panel), no input.
Hud.MonsterHud.Draw(_uiScale);
if (ImGuiBar.Visible)
ImGuiBar.Draw(_uiScale);
ImGuiPanelHost.DrawAll(_uiScale);
ImGuiBar.SyncPopOut(_uiScale);
}
if (ImGuiFontTest.Enabled)
ImGuiFontTest.Draw(_uiScale);
ImGuiNET.ImGui.EndFrame();
frameEnded = true;
ImGuiNET.ImGui.Render();
Win32Backend.UpdateCaptureFlags(captureMouse, captureKeyboard);
ImGuiAssertLog.Poll();
_framesBuilt++;
_lastDisplaySize = io.DisplaySize;
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
DX9Backend.RenderDrawData(drawData, pDevice);
// OverlayTextureRenderer.Render is now driven from EndSceneHook.EndSceneDetour
// directly so the Avalonia compositor runs even when EnableImGuiBackend=false.
// Leaving it out of this call site avoids double-blit when ImGui is also active.
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
ImGuiNET.ImGui.UpdatePlatformWindows();
ImGuiNET.ImGui.RenderPlatformWindowsDefault();
}
// io.WantCaptureMouse already applies ImGui's own button-ownership
// rule; io.WantTextInput is true only while a text field is edited.
// MonsterHud.WantsMouse: the cursor is on a clickable nameplate (or a
// press that began on one is held), so that click is the plate's.
Win32Backend.UpdateCaptureFlags(io.WantCaptureMouse || Hud.MonsterHud.WantsMouse, io.WantTextInput);
ArbitrateTextFocus(io.WantTextInput);
return true;
}
catch (Exception ex)
{
@ -552,7 +677,46 @@ internal static class EngineFrameController
{
}
Win32Backend.ClearCaptureFlags();
RynthLog.Info($"EngineFrameController: frame {_frameCount} ImGui error: {ex.GetType().Name}: {ex.Message}");
return false;
}
finally
{
ImGuiNET.ImGui.SetCurrentContext(previousContext);
}
}
private static void ArbitrateTextFocus(bool imguiText)
{
bool avaloniaText = Win32Backend.AvaloniaTextInputActive;
if (imguiText && !_prevImGuiText && avaloniaText)
{
// An ImGui field just started typing: Avalonia gives up the keyboard.
Win32Backend.AvaloniaTextInputActive = false;
UI.AvaloniaOverlay.ClearTextFocus();
avaloniaText = false;
}
else if (avaloniaText && !_prevAvaloniaText && imguiText)
{
_dropImGuiTextFocus = true;
}
_prevImGuiText = imguiText;
_prevAvaloniaText = avaloniaText;
}
/// <summary>Draws the frame <see cref="BuildImGuiFrame"/> produced.</summary>
private static void SubmitImGuiFrame(IntPtr pDevice)
{
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
ImGuiNET.ImGui.SetCurrentContext(_context);
try
{
DX9Backend.RenderDrawData(ImGuiNET.ImGui.GetDrawData(), pDevice);
}
catch (Exception ex)
{
RynthLog.Info($"EngineFrameController: frame {_frameCount} ImGui submit error: {ex.GetType().Name}: {ex.Message}");
}
finally
{

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