RynthCore as of 2026-09-27 (internal d359eee): items past the old object-id range, no idle logoff, overlay popups without the panel flash, UI hidden at character select, vendor trading (API 67), Settings rows and Vendoring tab, release 2026.9.27.2
This commit is contained in:
parent
f407326377
commit
9b5e2765b7
43 changed files with 4216 additions and 62 deletions
|
|
@ -126,7 +126,9 @@ they're all opt-in, so use whichever fits the app you end up building:
|
||||||
a private mesh like **Tailscale** (phone hits `http://<tailscale-ip>:8740/status`).
|
a private mesh like **Tailscale** (phone hits `http://<tailscale-ip>:8740/status`).
|
||||||
A `+` bind needs a one-time `netsh http add urlacl url=http://+:8740/ user=Everyone`
|
A `+` bind needs a one-time `netsh http add urlacl url=http://+:8740/ user=Everyone`
|
||||||
(or run the agent elevated).
|
(or run the agent elevated).
|
||||||
- Set `ServeToken` to require `Authorization: Bearer <token>` (or `?token=`).
|
- `ServeToken` is required: with it empty the server stays off, on any bind.
|
||||||
|
Every route but `/healthz` then needs `Authorization: Bearer <token>` (or `?token=`).
|
||||||
|
Use the same token as your DrakBot remote and one DrakRemote entry shows both.
|
||||||
- `GET /healthz` returns `ok` for uptime checks.
|
- `GET /healthz` returns `ok` for uptime checks.
|
||||||
3. **File sync.** Leave `WriteAggregateFile: true` and point iCloud/Dropbox/etc.
|
3. **File sync.** Leave `WriteAggregateFile: true` and point iCloud/Dropbox/etc.
|
||||||
at `Logs\status\aggregate.json`; the app reads the synced copy.
|
at `Logs\status\aggregate.json`; the app reads the synced copy.
|
||||||
|
|
|
||||||
|
|
@ -21,10 +21,14 @@
|
||||||
RynthCore client is closed.
|
RynthCore client is closed.
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
.\Publish-Update.ps1 -Version 2026.9.27.1 -Notes "Arrow crafting covers every head type."
|
.\Publish-Update.ps1 -Version 2026.9.28.1 -Changes "Arrow crafting covers every head type.", "The Tell button works on players too."
|
||||||
#>
|
#>
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)][string]$Version,
|
[Parameter(Mandatory)][string]$Version,
|
||||||
|
# Release notes for players, one line per change: they become this release's entry in
|
||||||
|
# downloads/rynth/releases.json, which the "What's new" list on aelrynth.com/rynth.html shows.
|
||||||
|
[string[]]$Changes = @(),
|
||||||
|
# Short text the launcher shows next to an available update; defaults to the changes.
|
||||||
[string]$Notes = "",
|
[string]$Notes = "",
|
||||||
[switch]$DryRun, # build + sign + verify, upload nothing
|
[switch]$DryRun, # build + sign + verify, upload nothing
|
||||||
[switch]$AllowDirty, # publish with uncommitted changes (don't)
|
[switch]$AllowDirty, # publish with uncommitted changes (don't)
|
||||||
|
|
@ -69,6 +73,9 @@ Step "Checking preconditions"
|
||||||
$p = $Version.Split('.')
|
$p = $Version.Split('.')
|
||||||
if ($p.Count -ne 4 -or ($p | Where-Object { $_ -notmatch '^\d+$' })) { throw "-Version must be yyyy.m.d.n, got '$Version'" }
|
if ($p.Count -ne 4 -or ($p | Where-Object { $_ -notmatch '^\d+$' })) { throw "-Version must be yyyy.m.d.n, got '$Version'" }
|
||||||
$release = [int]$p[0] * 1000000 + [int]$p[1] * 10000 + [int]$p[2] * 100 + [int]$p[3]
|
$release = [int]$p[0] * 1000000 + [int]$p[1] * 10000 + [int]$p[2] * 100 + [int]$p[3]
|
||||||
|
if ($Changes.Count -eq 0 -and $Notes) { $Changes = @($Notes -split ';\s*' | Where-Object { $_ }) }
|
||||||
|
if ($Changes.Count -eq 0) { throw "Give -Changes: the release notes players see on aelrynth.com/rynth.html (one string per change)." }
|
||||||
|
if (-not $Notes) { $Notes = $Changes -join " " }
|
||||||
|
|
||||||
$trusted = [regex]::Matches((Get-Content $TrustFile -Raw), '"([A-Za-z0-9+/=]{80,})"') | ForEach-Object { $_.Groups[1].Value }
|
$trusted = [regex]::Matches((Get-Content $TrustFile -Raw), '"([A-Za-z0-9+/=]{80,})"') | ForEach-Object { $_.Groups[1].Value }
|
||||||
if ($trusted.Count -lt 2) {
|
if ($trusted.Count -lt 2) {
|
||||||
|
|
@ -183,6 +190,15 @@ Set-Content "$rel\update.payload.json" ($manifest | ConvertTo-Json -Depth 5) -En
|
||||||
if (-not (Test-Envelope "$rel\update.json" $trusted)) { throw "Signed feed does not verify against UpdateTrust.cs" }
|
if (-not (Test-Envelope "$rel\update.json" $trusted)) { throw "Signed feed does not verify against UpdateTrust.cs" }
|
||||||
Write-Host " verified against the launcher's trusted keys"
|
Write-Host " verified against the launcher's trusted keys"
|
||||||
|
|
||||||
|
# Release notes: this release on top of the live list (a re-run replaces its own entry).
|
||||||
|
$history = @()
|
||||||
|
try { $history = @((Invoke-RestMethod "$BaseUrl/releases.json" -TimeoutSec 20).releases) }
|
||||||
|
catch [Microsoft.PowerShell.Commands.HttpResponseException] { Write-Host " no releases.json yet — starting one" }
|
||||||
|
$entry = [ordered]@{ version = $Version; date = (Get-Date -Format "yyyy-MM-dd"); changes = @($Changes) }
|
||||||
|
$releaseNotes = [ordered]@{ releases = @($entry) + @($history | Where-Object { $_ -and $_.version -ne $Version }) }
|
||||||
|
Set-Content "$rel\releases.json" ($releaseNotes | ConvertTo-Json -Depth 5) -Encoding utf8NoBOM
|
||||||
|
Write-Host " releases.json: $($releaseNotes.releases.Count) release(s), $($Changes.Count) change(s) in this one"
|
||||||
|
|
||||||
if ($DryRun) {
|
if ($DryRun) {
|
||||||
Write-Host ""; Write-Host "Dry run: release built and signed in $rel; nothing uploaded." -ForegroundColor Yellow
|
Write-Host ""; Write-Host "Dry run: release built and signed in $rel; nothing uploaded." -ForegroundColor Yellow
|
||||||
return
|
return
|
||||||
|
|
@ -220,6 +236,11 @@ scp -q "$rel\update.json" "${SshHost}:$RemoteDir/.update.json.new"
|
||||||
if ($LASTEXITCODE -ne 0) { throw "scp of update.json failed" }
|
if ($LASTEXITCODE -ne 0) { throw "scp of update.json failed" }
|
||||||
ssh $SshHost "mv -f '$RemoteDir/.update.json.new' '$RemoteDir/update.json'"
|
ssh $SshHost "mv -f '$RemoteDir/.update.json.new' '$RemoteDir/update.json'"
|
||||||
if ($LASTEXITCODE -ne 0) { throw "Publishing update.json failed" }
|
if ($LASTEXITCODE -ne 0) { throw "Publishing update.json failed" }
|
||||||
|
# The release notes follow the feed, so the page never lists a release launchers can't get yet.
|
||||||
|
scp -q "$rel\releases.json" "${SshHost}:$RemoteDir/.releases.json.new"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "scp of releases.json failed" }
|
||||||
|
ssh $SshHost "mv -f '$RemoteDir/.releases.json.new' '$RemoteDir/releases.json'"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "Publishing releases.json failed" }
|
||||||
|
|
||||||
# ── 5. Verify ────────────────────────────────────────────────────────────────
|
# ── 5. Verify ────────────────────────────────────────────────────────────────
|
||||||
Step "Verifying the live feed"
|
Step "Verifying the live feed"
|
||||||
|
|
@ -232,4 +253,4 @@ try {
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "Published RynthCore $Version (release $release)." -ForegroundColor Green
|
Write-Host "Published RynthCore $Version (release $release)." -ForegroundColor Green
|
||||||
Write-Host "Launchers pick it up at their next check. Still by hand: the site text (projects.html) and the public source snapshots."
|
Write-Host "Launchers pick it up at their next check, and aelrynth.com/rynth.html lists it. Still by hand: the public source snapshots."
|
||||||
|
|
|
||||||
|
|
@ -85,12 +85,17 @@ internal static class CharacterCacheStore
|
||||||
return;
|
return;
|
||||||
|
|
||||||
List<string> characters = Read(accountName, serverName);
|
List<string> characters = Read(accountName, serverName);
|
||||||
if (!characters.Contains(characterName, StringComparer.OrdinalIgnoreCase))
|
if (!characters.Any(existing => IsSameCharacter(existing, characterName)))
|
||||||
characters.Add(characterName);
|
characters.Add(characterName);
|
||||||
|
|
||||||
Write(accountName, serverName, characters);
|
Write(accountName, serverName, characters);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The client shows admin names with a leading '+' ('+Buffi'); a launch-context
|
||||||
|
// name may lack it. Treat both as one character so the list holds no duplicate.
|
||||||
|
private static bool IsSameCharacter(string a, string b) =>
|
||||||
|
string.Equals(a.Trim().TrimStart('+'), b.Trim().TrimStart('+'), StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
public static void DeleteForAccount(string accountName)
|
public static void DeleteForAccount(string accountName)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(accountName))
|
if (string.IsNullOrWhiteSpace(accountName))
|
||||||
|
|
|
||||||
|
|
@ -268,6 +268,10 @@ internal static class AcMainThreadQueue
|
||||||
DrainChat();
|
DrainChat();
|
||||||
DrainChatCommands();
|
DrainChatCommands();
|
||||||
DrainRequestIds();
|
DrainRequestIds();
|
||||||
|
// 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 { }
|
||||||
|
|
||||||
int head = _head; // only the main thread writes _head
|
int head = _head; // only the main thread writes _head
|
||||||
int tail = Volatile.Read(ref _tail);
|
int tail = Volatile.Read(ref _tail);
|
||||||
|
|
|
||||||
|
|
@ -53,6 +53,22 @@ internal static class CharacterCaptureHooks
|
||||||
private const int AutoLoginDirectFailsBeforeClick = 4;
|
private const int AutoLoginDirectFailsBeforeClick = 4;
|
||||||
private static int _autoLoginPollStarted;
|
private static int _autoLoginPollStarted;
|
||||||
|
|
||||||
|
// Native character-list capture. The 0xF658 packet path is dead (see above),
|
||||||
|
// so ParseAndSaveCharacterList never runs and the launcher's cache
|
||||||
|
// (characters_<server>_<account>.json) was only written by SessionStateRegistry's
|
||||||
|
// login upsert, which records just the launch context's TargetCharacter. An
|
||||||
|
// account launched with no character picked therefore never got a cache file
|
||||||
|
// and its launcher dropdown stayed empty. This poll reads the list straight
|
||||||
|
// from AC's native CharacterSet while char-select is up, whether or not
|
||||||
|
// auto-login is armed. In the world it only checks a managed flag; the native
|
||||||
|
// set is read only in CharacterManagementUI. Logout back to char-select
|
||||||
|
// (LoginLifecycleHooks.ResetObservation) re-arms it, so a new or deleted
|
||||||
|
// character is picked up too. The file is rewritten only when the list changes.
|
||||||
|
private const int CharacterListCapturePollIntervalMs = 500;
|
||||||
|
private static int _characterListCapturePollStarted;
|
||||||
|
private static readonly object CharacterListCaptureLock = new();
|
||||||
|
private static string _lastCharacterListCaptureKey = string.Empty;
|
||||||
|
|
||||||
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||||
|
|
||||||
[DllImport("user32.dll")]
|
[DllImport("user32.dll")]
|
||||||
|
|
@ -86,13 +102,16 @@ internal static class CharacterCaptureHooks
|
||||||
private static int _autoLoginEverFired;
|
private static int _autoLoginEverFired;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Starts the poll-driven auto-login worker. Call once from InitWorker.
|
/// Starts the character-list capture poll (always) and the poll-driven
|
||||||
/// No-ops if no TargetCharacter is configured in the launch context, or if
|
/// auto-login worker. Call once from InitWorker. Auto-login no-ops if no
|
||||||
/// the worker is already running. Safe to call before the client window or
|
/// TargetCharacter is configured in the launch context, or if the worker is
|
||||||
/// char-select UI exists — the worker waits for them.
|
/// already running. Safe to call before the client window or char-select UI
|
||||||
|
/// exists — both workers wait for them.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static void Initialize()
|
public static void Initialize()
|
||||||
{
|
{
|
||||||
|
StartCharacterListCapturePoll();
|
||||||
|
|
||||||
(_, _, string targetCharacter) = ReadLaunchContext();
|
(_, _, string targetCharacter) = ReadLaunchContext();
|
||||||
if (string.IsNullOrWhiteSpace(targetCharacter))
|
if (string.IsNullOrWhiteSpace(targetCharacter))
|
||||||
{
|
{
|
||||||
|
|
@ -175,6 +194,10 @@ internal static class CharacterCaptureHooks
|
||||||
RynthLog.Info($"CharacterCapture: Char-select up — driving direct auto-login for '{targetCharacter}'.");
|
RynthLog.Info($"CharacterCapture: Char-select up — driving direct auto-login for '{targetCharacter}'.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Save the account's character list before logging on, so the
|
||||||
|
// launcher cache is written even when auto-login is quick.
|
||||||
|
TryCaptureNativeCharacterList();
|
||||||
|
|
||||||
// Direct path: read AC's native CharacterSet and call LogOnCharacter.
|
// Direct path: read AC's native CharacterSet and call LogOnCharacter.
|
||||||
// No packet required. Retries every tick if it didn't take.
|
// No packet required. Retries every tick if it didn't take.
|
||||||
if (CharacterManagementHooks.TryLogOnCharacter(
|
if (CharacterManagementHooks.TryLogOnCharacter(
|
||||||
|
|
@ -226,6 +249,79 @@ internal static class CharacterCaptureHooks
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void StartCharacterListCapturePoll()
|
||||||
|
{
|
||||||
|
if (Interlocked.Exchange(ref _characterListCapturePollStarted, 1) != 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var thread = new Thread(CharacterListCapturePollLoop)
|
||||||
|
{
|
||||||
|
Name = "RynthCore.CharacterListCapture",
|
||||||
|
IsBackground = true
|
||||||
|
};
|
||||||
|
thread.Start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CharacterListCapturePollLoop()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (!EngineLifecycle.IsShuttingDown)
|
||||||
|
{
|
||||||
|
Thread.Sleep(CharacterListCapturePollIntervalMs);
|
||||||
|
|
||||||
|
// In the world: no native reads at all.
|
||||||
|
if (LoginLifecycleHooks.HasObservedLoginComplete)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (!CharacterManagementHooks.TryGetCurrentMode(out int mode) || mode != CharacterManagementUIMode)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
TryCaptureNativeCharacterList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
RynthLog.Compat($"CharacterCapture: Character-list capture poll crashed - {ex.Message}");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Interlocked.Exchange(ref _characterListCapturePollStarted, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads the character list from AC's native CharacterSet (char-select only)
|
||||||
|
/// and saves it to the launcher's character cache for this client's
|
||||||
|
/// account/server. Writes only when the list differs from the last one seen
|
||||||
|
/// in this process. Safe to call from any poll thread.
|
||||||
|
/// </summary>
|
||||||
|
private static void TryCaptureNativeCharacterList()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!CharacterManagementHooks.TryReadCharacterNames(out List<string> characters))
|
||||||
|
return;
|
||||||
|
|
||||||
|
lock (CharacterListCaptureLock)
|
||||||
|
{
|
||||||
|
string key = string.Join("\n", characters);
|
||||||
|
if (string.Equals(key, _lastCharacterListCaptureKey, StringComparison.Ordinal))
|
||||||
|
return;
|
||||||
|
|
||||||
|
_lastCharacterListCaptureKey = key;
|
||||||
|
RynthLog.Info($"CharacterCapture: Native character set has {characters.Count} chars: {string.Join(", ", characters)}");
|
||||||
|
|
||||||
|
(string accountName, string serverName, _) = ReadLaunchContext();
|
||||||
|
SaveCharacterList(characters, accountName, serverName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
RynthLog.Compat($"CharacterCapture: Native character-list capture failed - {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Single char-list double-click at the slot for <paramref name="slotIndex"/>.
|
/// Single char-list double-click at the slot for <paramref name="slotIndex"/>.
|
||||||
/// Fallback for when the direct native LogOnCharacter path isn't taking.
|
/// Fallback for when the direct native LogOnCharacter path isn't taking.
|
||||||
|
|
@ -461,7 +557,7 @@ internal static class CharacterCaptureHooks
|
||||||
if (!string.IsNullOrWhiteSpace(accountName))
|
if (!string.IsNullOrWhiteSpace(accountName))
|
||||||
{
|
{
|
||||||
CharacterCacheStore.Write(accountName, serverName, characters);
|
CharacterCacheStore.Write(accountName, serverName, characters);
|
||||||
RynthLog.Verbose(
|
RynthLog.Info(
|
||||||
!string.IsNullOrWhiteSpace(serverName)
|
!string.IsNullOrWhiteSpace(serverName)
|
||||||
? $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' on '{serverName}'."
|
? $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' on '{serverName}'."
|
||||||
: $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' (no server name in context).");
|
: $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' (no server name in context).");
|
||||||
|
|
|
||||||
|
|
@ -184,6 +184,44 @@ internal static class CharacterManagementHooks
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads the character names in AC's native CharacterSet, in slot order
|
||||||
|
/// (the order char-select lists them). Read-only: never calls
|
||||||
|
/// LogOnCharacter. Only reads while CharacterManagementUI is the current
|
||||||
|
/// mode, so the native set is never touched in the world. Returns false
|
||||||
|
/// (empty list) when unbound, not at char-select, or the set isn't filled yet.
|
||||||
|
/// </summary>
|
||||||
|
public static bool TryReadCharacterNames(out List<string> names)
|
||||||
|
{
|
||||||
|
names = new List<string>();
|
||||||
|
|
||||||
|
if (!EnsureBound())
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!TryGetCurrentMode(out int mode) || mode != CharacterManagementUI)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
IntPtr charSetPtr = GetCharacterSetPointer();
|
||||||
|
if (charSetPtr == IntPtr.Zero)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
for (int index = 0; index < MaxCharacterSlots; index++)
|
||||||
|
{
|
||||||
|
IntPtr identityPtr = _characterSetGetIdentity!(charSetPtr, index);
|
||||||
|
if (identityPtr == IntPtr.Zero)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
string? name = ReadAnsiString(_characterSetGetName!(charSetPtr, index));
|
||||||
|
uint avatarId = _characterSetGetGid!(charSetPtr, index);
|
||||||
|
if (string.IsNullOrWhiteSpace(name) || avatarId == 0)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
names.Add(name.Trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
return names.Count > 0;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Returns the count of populated character slots in AC's native
|
/// Returns the count of populated character slots in AC's native
|
||||||
/// CharacterSet (slots where GetIdentity returns non-null). Used by the
|
/// CharacterSet (slots where GetIdentity returns non-null). Used by the
|
||||||
|
|
|
||||||
|
|
@ -338,6 +338,7 @@ internal static class ChatCallbackHooks
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
string? line = ReadWidePString(text);
|
string? line = ReadWidePString(text);
|
||||||
|
LogoffOriginProbe.RecordChat($"AC OutgoingChat src={commandSource}", line);
|
||||||
|
|
||||||
// Capture the chat-manager 'this' + command source from the live submit
|
// Capture the chat-manager 'this' + command source from the live submit
|
||||||
// so ChatCommandDispatcher can re-invoke this function directly later.
|
// so ChatCommandDispatcher can re-invoke this function directly later.
|
||||||
|
|
@ -568,6 +569,7 @@ internal static class ChatCallbackHooks
|
||||||
foreach (char c in line)
|
foreach (char c in line)
|
||||||
if (c < 0x20 && c != '\t')
|
if (c < 0x20 && c != '\t')
|
||||||
return false; // never feed AC control chars
|
return false; // never feed AC control chars
|
||||||
|
LogoffOriginProbe.RecordChat("OutgoingChat direct", line);
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -132,6 +132,7 @@ internal static unsafe class ChatCommandDispatcher
|
||||||
{
|
{
|
||||||
string trimmed = text.Trim();
|
string trimmed = text.Trim();
|
||||||
if (trimmed.Length == 0) return false;
|
if (trimmed.Length == 0) return false;
|
||||||
|
LogoffOriginProbe.RecordChat("ChatCommandDispatcher", trimmed);
|
||||||
|
|
||||||
// RynthCore engine commands (/rc ...) are handled before plugin
|
// RynthCore engine commands (/rc ...) are handled before plugin
|
||||||
// pre-dispatch and before any AC chat routing so they work even
|
// pre-dispatch and before any AC chat routing so they work even
|
||||||
|
|
@ -320,6 +321,7 @@ internal static unsafe class ChatCommandDispatcher
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static bool SimulateChatInput(string command)
|
private static bool SimulateChatInput(string command)
|
||||||
{
|
{
|
||||||
|
LogoffOriginProbe.RecordChat("SimulateChatInput", command);
|
||||||
// Deep-audit finding #18 (2026-06-18): SendToGameWndProc drives
|
// Deep-audit finding #18 (2026-06-18): SendToGameWndProc drives
|
||||||
// CallWindowProcA directly into AC's WndProc — calling that off the
|
// CallWindowProcA directly into AC's WndProc — calling that off the
|
||||||
// window-owning thread is a cross-thread WndProc re-entry. Dispatch()
|
// window-owning thread is a cross-thread WndProc re-entry. Dispatch()
|
||||||
|
|
|
||||||
|
|
@ -65,11 +65,13 @@ internal static class ChatHooks
|
||||||
public static volatile bool ChatPanelShown;
|
public static volatile bool ChatPanelShown;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// RynthChat is standing in for the retail chat: its panel is open AND "Hide retail chat"
|
/// RynthChat is standing in for the retail chat: in the world, its panel is open AND
|
||||||
/// is on. Only then is the retail chatbox hidden and Enter routed to RynthChat — whichever
|
/// "Hide retail chat" is on. Only then is the retail chatbox hidden and Enter routed to
|
||||||
/// chat is visible gets Enter.
|
/// RynthChat — whichever chat is visible gets Enter. Outside the world Enter is AC's:
|
||||||
|
/// at character select it enters the game.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static bool RynthChatOwnsChat => SuppressOriginalChat && ChatPanelShown;
|
public static bool RynthChatOwnsChat =>
|
||||||
|
SuppressOriginalChat && ChatPanelShown && LoginLifecycleHooks.HasObservedLoginComplete;
|
||||||
|
|
||||||
public static IntPtr GmMainChatInstance => _gmMainChatInstance;
|
public static IntPtr GmMainChatInstance => _gmMainChatInstance;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -936,6 +936,7 @@ internal static class ClientHelperHooks
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
RynthLog.Verbose($"Compat: InvokeParser text='{line}'");
|
RynthLog.Verbose($"Compat: InvokeParser text='{line}'");
|
||||||
|
LogoffOriginProbe.RecordChat("InvokeChatParser", line);
|
||||||
return ChatCommandDispatcher.Dispatch(line);
|
return ChatCommandDispatcher.Dispatch(line);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
|
|
|
||||||
|
|
@ -216,6 +216,14 @@ internal static class ClientObjectHooks
|
||||||
private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue;
|
private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue;
|
||||||
private static bool _loggedObjectIdentityServe;
|
private static bool _loggedObjectIdentityServe;
|
||||||
private const int ObjectIdentityPrefetchThrottleMs = 500;
|
private const int ObjectIdentityPrefetchThrottleMs = 500;
|
||||||
|
// Every id the same walk visited, swapped whole (readers never see a half-built array).
|
||||||
|
private static volatile uint[] _liveObjectIds = Array.Empty<uint>();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ids of every weenie object the client knew at the last identity snapshot (main-thread
|
||||||
|
/// walk, at most ~0.5 s old). Empty until the first snapshot.
|
||||||
|
/// </summary>
|
||||||
|
public static uint[] LiveObjectIds => _liveObjectIds;
|
||||||
|
|
||||||
// Position snapshot — mirrors the attackable/identity snapshots, but sampled
|
// Position snapshot — mirrors the attackable/identity snapshots, but sampled
|
||||||
// EVERY EndScene (no throttle) because positions change per-frame. The
|
// EVERY EndScene (no throttle) because positions change per-frame. The
|
||||||
|
|
@ -1457,6 +1465,47 @@ internal static class ClientObjectHooks
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads one 4-byte field of an object's PublicWeenieDesc by its offset from the
|
||||||
|
/// start of the PWD (e.g. +56 _type, +60 _value, +96 _stackSize, +116 _burden; layout
|
||||||
|
/// in Chorizite Weenie.cs:1734, same base as <see cref="TryGetObjectOwnershipInfo"/>).
|
||||||
|
/// MAIN THREAD ONLY: off the main thread it returns false without touching AC memory
|
||||||
|
/// (a snapshot-cached weenie pointer can be freed and reused under us). Both ends of
|
||||||
|
/// the read are page-probed, so a bad pointer fails closed instead of faulting.
|
||||||
|
/// Used by vendor trading to read item value/burden for pack items, whose qualities
|
||||||
|
/// pointer is null (so InqInt can't serve them).
|
||||||
|
/// </summary>
|
||||||
|
internal static bool TryReadPwdInt32(uint objectId, int pwdFieldOffset, out int value)
|
||||||
|
{
|
||||||
|
value = 0;
|
||||||
|
if (pwdFieldOffset < 0 || pwdFieldOffset > 172 || (pwdFieldOffset & 3) != 0)
|
||||||
|
return false;
|
||||||
|
if (!MainThreadGuard.IsOnMainThread())
|
||||||
|
return false;
|
||||||
|
if (_getWeenieObject == null)
|
||||||
|
{
|
||||||
|
if (!Probe() || _getWeenieObject == null)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (_weeniePhysicsObjOffset < 0)
|
||||||
|
return false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
IntPtr weeniePtr = _getWeenieObject(objectId);
|
||||||
|
if (weeniePtr == IntPtr.Zero)
|
||||||
|
return false;
|
||||||
|
IntPtr fieldAddr = weeniePtr + _weeniePhysicsObjOffset + 4 + pwdFieldOffset;
|
||||||
|
if (!IsReadablePointer(fieldAddr) || !IsReadablePointer(fieldAddr + 3))
|
||||||
|
return false;
|
||||||
|
value = Marshal.ReadInt32(fieldAddr);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Reads PublicWeenieDesc._wcid directly from the weenie struct.
|
/// Reads PublicWeenieDesc._wcid directly from the weenie struct.
|
||||||
/// Returns the Weenie Class ID (WCID) for the given object.
|
/// Returns the Weenie Class ID (WCID) for the given object.
|
||||||
|
|
@ -2456,9 +2505,11 @@ internal static class ClientObjectHooks
|
||||||
{
|
{
|
||||||
var nameSnap = new Dictionary<uint, string>();
|
var nameSnap = new Dictionary<uint, string>();
|
||||||
var typeSnap = new Dictionary<uint, uint>();
|
var typeSnap = new Dictionary<uint, uint>();
|
||||||
|
var idSnap = new List<uint>();
|
||||||
|
|
||||||
int n = CObjectMaintHooks.EnumerateLiveWeenieObjectIds(id =>
|
int n = CObjectMaintHooks.EnumerateLiveWeenieObjectIds(id =>
|
||||||
{
|
{
|
||||||
|
idSnap.Add(id);
|
||||||
if (TryGetObjectName(id, out string nm) && nm.Length > 0)
|
if (TryGetObjectName(id, out string nm) && nm.Length > 0)
|
||||||
nameSnap[id] = nm;
|
nameSnap[id] = nm;
|
||||||
if (TryGetItemType(id, out uint typeFlags))
|
if (TryGetItemType(id, out uint typeFlags))
|
||||||
|
|
@ -2477,6 +2528,7 @@ internal static class ClientObjectHooks
|
||||||
foreach (var kv in typeSnap)
|
foreach (var kv in typeSnap)
|
||||||
_objectTypeCache[kv.Key] = kv.Value;
|
_objectTypeCache[kv.Key] = kv.Value;
|
||||||
}
|
}
|
||||||
|
_liveObjectIds = idSnap.ToArray();
|
||||||
|
|
||||||
if (!_loggedObjectIdentityServe)
|
if (!_loggedObjectIdentityServe)
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -100,6 +100,9 @@ internal static class GameTickHooks
|
||||||
// wedges before the new generation's EndScene hook installs.
|
// wedges before the new generation's EndScene hook installs.
|
||||||
try { MainThreadHangWatchdog.MainThreadBeatNoFrame(); }
|
try { MainThreadHangWatchdog.MainThreadBeatNoFrame(); }
|
||||||
catch { }
|
catch { }
|
||||||
|
// Diag (diag/logoff-origin): 1 Hz sample of the client's own input-idle clock.
|
||||||
|
try { LogoffOriginProbe.SampleIdleOnGameThread(); }
|
||||||
|
catch { }
|
||||||
// Drain any queued cast BEFORE AC's game-logic tick: SelectItem sets AC's
|
// Drain any queued cast BEFORE AC's game-logic tick: SelectItem sets AC's
|
||||||
// selection and the cast initiates, then THIS SAME UseTime call processes it to
|
// selection and the cast initiates, then THIS SAME UseTime call processes it to
|
||||||
// completion — mimicking AC's natural input -> UseTime flow. (Draining AFTER the
|
// completion — mimicking AC's natural input -> UseTime flow. (Draining AFTER the
|
||||||
|
|
|
||||||
|
|
@ -98,7 +98,12 @@ internal static class HeartbeatLogger
|
||||||
// Soak health: rec climbs during combat/loot; fcl stays flat.
|
// Soak health: rec climbs during combat/loot; fcl stays flat.
|
||||||
long rec = 0, fcl = 0;
|
long rec = 0, fcl = 0;
|
||||||
try { rec = BusyCountHooks.ReconcileCount; fcl = BusyCountHooks.ForceClearCount; } catch { }
|
try { rec = BusyCountHooks.ReconcileCount; fcl = BusyCountHooks.ForceClearCount; } catch { }
|
||||||
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}");
|
// idle = the client's own input-idle clock (diag/logoff-origin); the retail
|
||||||
|
// client logs itself off past InactiveTimeBeforeLogout. Omitted when unknown.
|
||||||
|
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}");
|
||||||
|
|
||||||
// Cache this client's live metrics so the GetEngineStatusJson host bridge can serve
|
// 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.
|
// them to a plugin (the RynthRemote status export). No file write, no networking.
|
||||||
|
|
|
||||||
802
src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs
Normal file
802
src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs
Normal file
|
|
@ -0,0 +1,802 @@
|
||||||
|
using System;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
|
using RynthCore.Engine.Hooking;
|
||||||
|
|
||||||
|
namespace RynthCore.Engine.Compatibility;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DIAGNOSTIC (branch diag/logoff-origin, 2026-09-27): pins down which client code path
|
||||||
|
/// asks the server to log the character off. Lucy logged off by herself mid-fight at
|
||||||
|
/// 14:28:20, 15:36:52 and 16:43:30; the ExecuteLogOff caller was the server's
|
||||||
|
/// CharacterLogOff (0xF653) handler, and ACE only sends that in reply to a logoff the
|
||||||
|
/// client requested. This probe watches the request side. It changes no behaviour.
|
||||||
|
///
|
||||||
|
/// Hooks (all log caller frames via <see cref="LogoutLifecycleHooks.LogCaller"/>):
|
||||||
|
/// - CPlayerSystem::LogOffCharacter(bool immediate) every client logoff entry point
|
||||||
|
/// - CPlayerSystem::RequestLogOff() prints "Logging off...", sends
|
||||||
|
/// - Proto_UI::LogOffCharacter(uint gid) builds + sends the 0xF653 request
|
||||||
|
/// - CPlayerSystem::SetLogOffStarted() ~3 s after the request (timeline)
|
||||||
|
/// - ClientNet::LogOffServer() transport-level disconnect
|
||||||
|
///
|
||||||
|
/// Context, dumped once when a logoff is requested (or when one completes with no request):
|
||||||
|
/// - client input idle time vs InactiveTimeBeforeLogout (the retail client logs itself
|
||||||
|
/// off from ClientUISystem::UseTime when Timer::cur_time minus CInputManager's
|
||||||
|
/// last-input time exceeds it; 1200 s on the reference client)
|
||||||
|
/// - game-window foreground/focus state and when it last changed
|
||||||
|
/// - ring buffers: the last window messages the WndProc subclass saw (keys, clicks,
|
||||||
|
/// focus, close, syscommand) and the last chat lines through the engine's chat paths
|
||||||
|
/// - an acclient-only stack sweep (return addresses above the detour; may be stale)
|
||||||
|
///
|
||||||
|
/// Idle milestones are also logged as the idle time climbs toward the threshold, and the
|
||||||
|
/// heartbeat line carries idle=Ns.
|
||||||
|
///
|
||||||
|
/// CommandInterpreter::HandleLogOff (0x006B4270) is NOT hooked: it is a two-instruction
|
||||||
|
/// thunk to CommandInterpreter::Disable (vtable +0x84) that runs as a consequence of a
|
||||||
|
/// logoff, not a requester.
|
||||||
|
/// </summary>
|
||||||
|
internal static unsafe class LogoffOriginProbe
|
||||||
|
{
|
||||||
|
// Fallback VAs on the reference retail client (4,841,472 bytes, SizeOfImage 0x56D000).
|
||||||
|
// The patterns below are the source of truth (cut + verified with tools/pe_pattern.py).
|
||||||
|
private const int ProbeLogOffCharacterVa = 0x005642C0; // CPlayerSystem::LogOffCharacter(bool)
|
||||||
|
private const int ProbeRequestLogOffVa = 0x00563B70; // CPlayerSystem::RequestLogOff()
|
||||||
|
private const int ProbeProtoLogOffVa = 0x005475E0; // Proto_UI::LogOffCharacter(uint gid), cdecl
|
||||||
|
private const int ProbeSetLogOffStartedVa = 0x0055E4F0; // CPlayerSystem::SetLogOffStarted()
|
||||||
|
private const int ProbeLogOffServerVa = 0x00544AB0; // ClientNet::LogOffServer()
|
||||||
|
private const int ProbeTimerCurTimeVa = 0x008379A8; // Timer::cur_time (double, seconds)
|
||||||
|
private const int ProbeInputManagerVa = 0x00837FF4; // ICIDM::s_cidm (CInputManager*)
|
||||||
|
private const int ProbeIdleLimitVa = 0x007CEB70; // InactiveTimeBeforeLogout (double, 1200.0)
|
||||||
|
|
||||||
|
private const int ReferenceImageSize = 0x0056D000;
|
||||||
|
|
||||||
|
// push esi; mov esi,ecx; push 0; lea ecx,[esi+0x30]; call; mov al,[esp+8]; test al,al
|
||||||
|
private static readonly byte?[] LogOffCharacterPattern = [ 0x56, 0x8B, 0xF1, 0x6A, 0x00, 0x8D, 0x4E, 0x30, 0xE8, null, null, null, null, 0x8A, 0x44, 0x24, 0x08, 0x84, 0xC0 ];
|
||||||
|
// push ecx; push esi; push edi; push "Logging off...\n"; mov esi,ecx; push 0; lea ecx,[esp+0x10]; call
|
||||||
|
private static readonly byte?[] RequestLogOffPattern = [ 0x51, 0x56, 0x57, 0x68, null, null, null, null, 0x8B, 0xF1, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0xE8 ];
|
||||||
|
// push 8; call alloc; mov ecx,[esp+8]; push 8; mov dword ptr [eax],0xF653
|
||||||
|
private static readonly byte?[] ProtoLogOffPattern = [ 0x6A, 0x08, 0xE8, null, null, null, null, 0x8B, 0x4C, 0x24, 0x08, 0x6A, 0x08, 0xC7, 0x00, 0x53, 0xF6, 0x00, 0x00 ];
|
||||||
|
// mov byte ptr [ecx+0x221],0; ret
|
||||||
|
private static readonly byte?[] SetLogOffStartedPattern = [ 0xC6, 0x81, 0x21, 0x02, 0x00, 0x00, 0x00, 0xC3 ];
|
||||||
|
// push ebp; push esi; push edi; mov ebp,ecx; mov esi,[ebp+0x8820]; push 0x1C; call
|
||||||
|
private static readonly byte?[] LogOffServerPattern = [ 0x55, 0x56, 0x57, 0x8B, 0xE9, 0x8B, 0xB5, 0x20, 0x88, 0x00, 0x00, 0x6A, 0x1C, 0xE8 ];
|
||||||
|
|
||||||
|
// Data globals by code-xref (operand at offset 2).
|
||||||
|
private static readonly byte?[] CurTimeXrefPattern = [ 0xDD, 0x05, null, null, null, null, 0x56, 0xDD ];
|
||||||
|
// ClientUISystem::UseTime: mov ebp,[ICIDM::s_cidm]; push esi; push edi; lea eax,[esp+0x10]
|
||||||
|
private static readonly byte?[] InputManagerXrefPattern = [ 0x8B, 0x2D, null, null, null, null, 0x56, 0x57, 0x8D, 0x44, 0x24, 0x10 ];
|
||||||
|
// ClientUISystem::UseTime: fcomp qword ptr [InactiveTimeBeforeLogout]; fnstsw ax; test ah,0x41; jne; cmp
|
||||||
|
private static readonly byte?[] IdleLimitXrefPattern = [ 0xDC, 0x1D, null, null, null, null, 0xDF, 0xE0, 0xF6, 0xC4, 0x41, 0x75, 0x22, 0x3B ];
|
||||||
|
|
||||||
|
private static IntPtr _origLogOffCharacter;
|
||||||
|
private static IntPtr _origRequestLogOff;
|
||||||
|
private static IntPtr _origProtoLogOff;
|
||||||
|
private static IntPtr _origSetLogOffStarted;
|
||||||
|
private static IntPtr _origLogOffServer;
|
||||||
|
|
||||||
|
private static IntPtr _curTimeVa;
|
||||||
|
private static IntPtr _inputMgrSlotVa;
|
||||||
|
private static IntPtr _idleLimitVa;
|
||||||
|
private static int _lastInputOffset = -1;
|
||||||
|
private static bool _inputOffsetProbed;
|
||||||
|
|
||||||
|
private static long _acBase;
|
||||||
|
private static long _acImageSize;
|
||||||
|
private static long _acTextLo;
|
||||||
|
private static long _acTextHi;
|
||||||
|
private static bool _labelsValid;
|
||||||
|
private static bool _initialized;
|
||||||
|
|
||||||
|
public static void Initialize()
|
||||||
|
{
|
||||||
|
if (_initialized)
|
||||||
|
return;
|
||||||
|
_initialized = true;
|
||||||
|
|
||||||
|
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||||
|
{
|
||||||
|
RynthLog.Compat("LogoffProbe: acclient.exe not available - probe not installed.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_acBase = text.ModuleBase.ToInt64();
|
||||||
|
_acImageSize = text.ImageSize;
|
||||||
|
_acTextLo = text.TextBaseVa;
|
||||||
|
_acTextHi = text.TextBaseVa + (long)text.Bytes.Length;
|
||||||
|
_labelsValid = text.ImageSize == ReferenceImageSize;
|
||||||
|
|
||||||
|
_curTimeVa = HookResolver.ResolveData(text, "LogoffProbe.Timer_cur_time", CurTimeXrefPattern, 2, ProbeTimerCurTimeVa).Address;
|
||||||
|
_inputMgrSlotVa = HookResolver.ResolveData(text, "LogoffProbe.ICIDM_s_cidm", InputManagerXrefPattern, 2, ProbeInputManagerVa).Address;
|
||||||
|
_idleLimitVa = HookResolver.ResolveData(text, "LogoffProbe.InactiveTimeBeforeLogout", IdleLimitXrefPattern, 2, ProbeIdleLimitVa).Address;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
double limit = _idleLimitVa != IntPtr.Zero ? *(double*)_idleLimitVa : double.NaN;
|
||||||
|
RynthLog.Compat($"LogoffProbe: client idle auto-logoff threshold (InactiveTimeBeforeLogout @ 0x{_idleLimitVa.ToInt32():X8}) = {limit:0.#} s. ClientUISystem::UseTime calls LogOffCharacter(0) once Timer::cur_time - last input exceeds it.");
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
|
||||||
|
int hooked = 0;
|
||||||
|
HookResolver.ResolveResult r;
|
||||||
|
|
||||||
|
r = HookResolver.Resolve(text, "LogoffProbe.LogOffCharacter", LogOffCharacterPattern, ProbeLogOffCharacterVa);
|
||||||
|
delegate* unmanaged[Thiscall]<IntPtr, byte, void> dLogOffCharacter = &LogOffCharacterDetour;
|
||||||
|
if (TryHook(r, "CPlayerSystem::LogOffCharacter", (IntPtr)dLogOffCharacter, out _origLogOffCharacter)) hooked++;
|
||||||
|
|
||||||
|
r = HookResolver.Resolve(text, "LogoffProbe.RequestLogOff", RequestLogOffPattern, ProbeRequestLogOffVa);
|
||||||
|
delegate* unmanaged[Thiscall]<IntPtr, void> dRequestLogOff = &RequestLogOffDetour;
|
||||||
|
if (TryHook(r, "CPlayerSystem::RequestLogOff", (IntPtr)dRequestLogOff, out _origRequestLogOff)) hooked++;
|
||||||
|
|
||||||
|
r = HookResolver.Resolve(text, "LogoffProbe.Proto_UI_LogOffCharacter", ProtoLogOffPattern, ProbeProtoLogOffVa);
|
||||||
|
delegate* unmanaged[Cdecl]<uint, int> dProtoLogOff = &ProtoLogOffDetour;
|
||||||
|
if (TryHook(r, "Proto_UI::LogOffCharacter", (IntPtr)dProtoLogOff, out _origProtoLogOff)) hooked++;
|
||||||
|
|
||||||
|
r = HookResolver.Resolve(text, "LogoffProbe.SetLogOffStarted", SetLogOffStartedPattern, ProbeSetLogOffStartedVa);
|
||||||
|
delegate* unmanaged[Thiscall]<IntPtr, void> dSetLogOffStarted = &SetLogOffStartedDetour;
|
||||||
|
if (TryHook(r, "CPlayerSystem::SetLogOffStarted", (IntPtr)dSetLogOffStarted, out _origSetLogOffStarted)) hooked++;
|
||||||
|
|
||||||
|
r = HookResolver.Resolve(text, "LogoffProbe.ClientNet_LogOffServer", LogOffServerPattern, ProbeLogOffServerVa);
|
||||||
|
delegate* unmanaged[Thiscall]<IntPtr, void> dLogOffServer = &LogOffServerDetour;
|
||||||
|
if (TryHook(r, "ClientNet::LogOffServer", (IntPtr)dLogOffServer, out _origLogOffServer)) hooked++;
|
||||||
|
|
||||||
|
RynthLog.Compat($"LogoffProbe: {hooked}/5 logoff-origin hooks installed (labels {(_labelsValid ? "on" : "off - not the reference client")}).");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryHook(HookResolver.ResolveResult r, string name, IntPtr detour, out IntPtr original)
|
||||||
|
{
|
||||||
|
original = IntPtr.Zero;
|
||||||
|
if (!r.Success)
|
||||||
|
{
|
||||||
|
RynthLog.Compat($"LogoffProbe: {name} unresolved - not hooked.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
MinHook.Hook(r.Address, detour, out original);
|
||||||
|
RynthLog.Compat($"LogoffProbe: {name} hooked @ 0x{r.Address.ToInt32():X8} ({r.Detail}).");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
original = IntPtr.Zero;
|
||||||
|
RynthLog.Compat($"LogoffProbe: {name} hook failed: {ex.GetType().Name}: {ex.Message}");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Detours (game thread; must never throw into AC) ──────────────────────
|
||||||
|
|
||||||
|
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||||
|
private static void LogOffCharacterDetour(IntPtr thisPtr, byte immediate)
|
||||||
|
{
|
||||||
|
try { OnRequest("CPlayerSystem::LogOffCharacter", $"immediate={immediate}"); }
|
||||||
|
catch { }
|
||||||
|
((delegate* unmanaged[Thiscall]<IntPtr, byte, void>)_origLogOffCharacter)(thisPtr, immediate);
|
||||||
|
}
|
||||||
|
|
||||||
|
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||||
|
private static void RequestLogOffDetour(IntPtr thisPtr)
|
||||||
|
{
|
||||||
|
try { OnRequest("CPlayerSystem::RequestLogOff", ""); }
|
||||||
|
catch { }
|
||||||
|
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origRequestLogOff)(thisPtr);
|
||||||
|
}
|
||||||
|
|
||||||
|
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||||
|
private static int ProtoLogOffDetour(uint gid)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Volatile.Write(ref _lastProtoSendMs, Environment.TickCount64);
|
||||||
|
OnRequest("Proto_UI::LogOffCharacter", $"gid=0x{gid:X8} (sends 0xF653 to the server)");
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
return ((delegate* unmanaged[Cdecl]<uint, int>)_origProtoLogOff)(gid);
|
||||||
|
}
|
||||||
|
|
||||||
|
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||||
|
private static void SetLogOffStartedDetour(IntPtr thisPtr)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string since = _lastRequestMs != 0 ? $" {(Environment.TickCount64 - _lastRequestMs) / 1000.0:0.00}s after the request" : " (no request seen)";
|
||||||
|
RynthLog.Info($"LogoffProbe: CPlayerSystem::SetLogOffStarted{since}.");
|
||||||
|
LogoutLifecycleHooks.LogCaller("SetLogOffStarted", "LogoffProbe");
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origSetLogOffStarted)(thisPtr);
|
||||||
|
}
|
||||||
|
|
||||||
|
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
|
||||||
|
private static void LogOffServerDetour(IntPtr thisPtr)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
RynthLog.Info("LogoffProbe: ClientNet::LogOffServer (transport disconnect) entered.");
|
||||||
|
LogoutLifecycleHooks.LogCaller("ClientNet::LogOffServer", "LogoffProbe");
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origLogOffServer)(thisPtr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Request / completion tracking ────────────────────────────────────────
|
||||||
|
|
||||||
|
private static long _lastRequestMs;
|
||||||
|
private static string? _lastRequestDesc;
|
||||||
|
private static long _lastProtoSendMs;
|
||||||
|
private static long _lastDumpMs;
|
||||||
|
|
||||||
|
private static void OnRequest(string fn, string args)
|
||||||
|
{
|
||||||
|
long now = Environment.TickCount64;
|
||||||
|
IntPtr caller = LogoutLifecycleHooks.LogCaller(fn, "LogoffProbe");
|
||||||
|
string callerText = DescribeAcclientAddress(caller);
|
||||||
|
|
||||||
|
string idleText = "idle=?";
|
||||||
|
bool idleOver = false;
|
||||||
|
if (TryReadIdle(out double idle, out double limit, out _, out _))
|
||||||
|
{
|
||||||
|
idleOver = idle > limit;
|
||||||
|
idleText = $"idle={idle:0.0}s/{limit:0.#}s{(idleOver ? " (OVER threshold: matches the client idle auto-logoff)" : "")}";
|
||||||
|
}
|
||||||
|
|
||||||
|
string argText = args.Length > 0 ? $"({args})" : "()";
|
||||||
|
RynthLog.Warn($"LogoffProbe: logoff requested - {fn}{argText} caller={callerText} {idleText} {DescribeFocus()}");
|
||||||
|
|
||||||
|
// The first request of a cycle names the path; later ones (RequestLogOff, the send)
|
||||||
|
// are the same logoff continuing, so keep the original description.
|
||||||
|
if (_lastRequestMs == 0 || now - _lastRequestMs > 30_000)
|
||||||
|
{
|
||||||
|
_lastRequestMs = now;
|
||||||
|
_lastRequestDesc = $"{fn}{argText} from {callerText}";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (now - _lastDumpMs > 30_000)
|
||||||
|
{
|
||||||
|
_lastDumpMs = now;
|
||||||
|
DumpContext($"request via {fn}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Called once per logout cycle from the ExecuteLogOff / RecvNotice_Logoff detours.
|
||||||
|
/// Says whether the client asked for this logoff, and if not, dumps the context.
|
||||||
|
/// </summary>
|
||||||
|
internal static void OnLogoffCompleted(string via)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
long now = Environment.TickCount64;
|
||||||
|
long req = _lastRequestMs;
|
||||||
|
if (req != 0 && now - req < 120_000)
|
||||||
|
{
|
||||||
|
long send = Volatile.Read(ref _lastProtoSendMs);
|
||||||
|
string sendText = send != 0 && now - send < 120_000 ? $"{(now - send) / 1000.0:0.00}s after the 0xF653 send" : "no 0xF653 send seen";
|
||||||
|
RynthLog.Info($"LogoffProbe: logoff completed via {via} {(now - req) / 1000.0:0.00}s after the client request ({sendText}). Request: {_lastRequestDesc}.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
RynthLog.Warn($"LogoffProbe: logoff completed via {via} with NO client logoff request in the last 120 s - server-initiated, or a path this probe does not hook.");
|
||||||
|
if (now - _lastDumpMs > 30_000)
|
||||||
|
{
|
||||||
|
_lastDumpMs = now;
|
||||||
|
DumpContext($"completion via {via} without a request");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_lastRequestMs = 0;
|
||||||
|
_lastRequestDesc = null;
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Idle time (client's own idle-logoff clock) ───────────────────────────
|
||||||
|
|
||||||
|
private static long _lastIdleSampleMs;
|
||||||
|
private static int _idleSecondsForHb = -1;
|
||||||
|
private static double _prevIdle;
|
||||||
|
private static int _idleMilestoneIdx;
|
||||||
|
private static bool _idleOverLogged;
|
||||||
|
private static bool _idleDisabledLogged;
|
||||||
|
// Seconds before the threshold at which a milestone line is logged.
|
||||||
|
private static readonly int[] IdleMilestonesBefore = [900, 600, 300, 120, 60, 30, 10];
|
||||||
|
|
||||||
|
/// <summary>Client input idle seconds for the heartbeat line, or -1 when unknown.</summary>
|
||||||
|
internal static int IdleSecondsForHeartbeat => Volatile.Read(ref _idleSecondsForHb);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Called from the Client::UseTime detour (AC's game thread). Samples once a second.
|
||||||
|
/// </summary>
|
||||||
|
internal static void SampleIdleOnGameThread()
|
||||||
|
{
|
||||||
|
long now = Environment.TickCount64;
|
||||||
|
if (now - _lastIdleSampleMs < 1000)
|
||||||
|
return;
|
||||||
|
_lastIdleSampleMs = now;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!TryReadIdle(out double idle, out double limit, out _, out _))
|
||||||
|
{
|
||||||
|
Volatile.Write(ref _idleSecondsForHb, -1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Volatile.Write(ref _idleSecondsForHb, idle < 0 ? 0 : (int)Math.Min(idle, int.MaxValue));
|
||||||
|
|
||||||
|
// Input arrived since the last sample: the client reset its idle clock.
|
||||||
|
if (idle + 1.5 < _prevIdle)
|
||||||
|
{
|
||||||
|
if (_idleMilestoneIdx > 0 || _idleOverLogged)
|
||||||
|
RynthLog.Info($"LogoffProbe: client input idle clock reset after {_prevIdle:0}s (input received). {DescribeFocus()}");
|
||||||
|
_idleMilestoneIdx = 0;
|
||||||
|
_idleOverLogged = false;
|
||||||
|
}
|
||||||
|
_prevIdle = idle;
|
||||||
|
|
||||||
|
// ClientUISystem::UseTime only logs off an in-world player; skip the
|
||||||
|
// milestone lines at character select.
|
||||||
|
bool inWorld = false;
|
||||||
|
try { inWorld = LoginLifecycleHooks.HasObservedLoginComplete; } catch { }
|
||||||
|
if (!inWorld)
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (double.IsNaN(limit) || double.IsInfinity(limit) || limit <= 60)
|
||||||
|
{
|
||||||
|
if (!_idleDisabledLogged)
|
||||||
|
{
|
||||||
|
_idleDisabledLogged = true;
|
||||||
|
RynthLog.Info($"LogoffProbe: idle auto-logoff threshold is {limit} - milestones off.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The client counts only real keyboard/mouse input, so a character a bot is
|
||||||
|
// playing idles out after InactiveTimeBeforeLogout (1200 s) and logs itself off
|
||||||
|
// mid-fight - Lucy, three times on 2026-09-27, each 1206 s after the window lost
|
||||||
|
// focus. Keep the idle clock fresh while in the world (PreventIdleLogoff).
|
||||||
|
if (Plugins.EngineSettings.PreventIdleLogoff && idle > IdleRefreshAfterSec && TryRefreshLastInput())
|
||||||
|
{
|
||||||
|
long nowMs = Environment.TickCount64;
|
||||||
|
if (nowMs - _lastIdleRefreshLogMs > 600_000)
|
||||||
|
{
|
||||||
|
_lastIdleRefreshLogMs = nowMs;
|
||||||
|
RynthLog.Info($"LogoffProbe: reset the client's idle clock at {idle:0}s idle so the {limit:0.#}s idle auto-logoff can't fire (PreventIdleLogoff; logged at most every 10 min). {DescribeFocus()}");
|
||||||
|
}
|
||||||
|
_prevIdle = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (_idleMilestoneIdx < IdleMilestonesBefore.Length && idle >= limit - IdleMilestonesBefore[_idleMilestoneIdx])
|
||||||
|
{
|
||||||
|
RynthLog.Info($"LogoffProbe: client input idle {idle:0}s - the client auto-logs-off at {limit:0.#}s ({limit - idle:0}s left). {DescribeFocus()}");
|
||||||
|
_idleMilestoneIdx++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_idleOverLogged && idle > limit)
|
||||||
|
{
|
||||||
|
_idleOverLogged = true;
|
||||||
|
RynthLog.Warn($"LogoffProbe: client input idle {idle:0.0}s is over the {limit:0.#}s threshold - ClientUISystem::UseTime should call LogOffCharacter(0) now. {DescribeFocus()}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
private const double IdleRefreshAfterSec = 120;
|
||||||
|
private static long _lastIdleRefreshLogMs = -600_000;
|
||||||
|
|
||||||
|
/// <summary>Sets the input manager's last-input time to Timer::cur_time, as real input
|
||||||
|
/// would. Game thread only (called from SampleIdleOnGameThread).</summary>
|
||||||
|
private static bool TryRefreshLastInput()
|
||||||
|
{
|
||||||
|
if (_curTimeVa == IntPtr.Zero || _inputMgrSlotVa == IntPtr.Zero)
|
||||||
|
return false;
|
||||||
|
IntPtr mgr = *(IntPtr*)_inputMgrSlotVa;
|
||||||
|
if (mgr == IntPtr.Zero)
|
||||||
|
return false;
|
||||||
|
int off = ResolveLastInputOffset(mgr);
|
||||||
|
if (off < 0)
|
||||||
|
return false;
|
||||||
|
*(double*)((byte*)mgr + off) = *(double*)_curTimeVa;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reads the same values ClientUISystem::UseTime compares. Game thread only.</summary>
|
||||||
|
private static bool TryReadIdle(out double idle, out double limit, out double curTime, out double lastInput)
|
||||||
|
{
|
||||||
|
idle = 0; limit = double.NaN; curTime = 0; lastInput = 0;
|
||||||
|
if (_curTimeVa == IntPtr.Zero || _inputMgrSlotVa == IntPtr.Zero)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
IntPtr mgr = *(IntPtr*)_inputMgrSlotVa;
|
||||||
|
if (mgr == IntPtr.Zero)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
int off = ResolveLastInputOffset(mgr);
|
||||||
|
if (off < 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
curTime = *(double*)_curTimeVa;
|
||||||
|
lastInput = *(double*)((byte*)mgr + off);
|
||||||
|
if (_idleLimitVa != IntPtr.Zero)
|
||||||
|
limit = *(double*)_idleLimitVa;
|
||||||
|
idle = curTime - lastInput;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ClientUISystem::UseTime gets the last-input time from vtable slot 5 of the input
|
||||||
|
/// manager, CInputManager::GetLastInputTimestamp, which is "fld qword [ecx+off]; ret".
|
||||||
|
/// Read the field offset out of that body so the probe never guesses a layout.
|
||||||
|
/// </summary>
|
||||||
|
private static int ResolveLastInputOffset(IntPtr mgr)
|
||||||
|
{
|
||||||
|
if (_inputOffsetProbed)
|
||||||
|
return _lastInputOffset;
|
||||||
|
_inputOffsetProbed = true;
|
||||||
|
|
||||||
|
long vtbl = (*(IntPtr*)mgr).ToInt64();
|
||||||
|
if (vtbl < _acBase || vtbl + 0x18 > _acBase + _acImageSize)
|
||||||
|
{
|
||||||
|
RynthLog.Compat($"LogoffProbe: input manager vtable 0x{vtbl:X8} is outside acclient - idle probe off.");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
long fn = (*(IntPtr*)(vtbl + 0x14)).ToInt64();
|
||||||
|
if (fn < _acTextLo || fn + 4 > _acTextHi)
|
||||||
|
{
|
||||||
|
RynthLog.Compat($"LogoffProbe: GetLastInputTimestamp 0x{fn:X8} is outside acclient .text - idle probe off.");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
byte* p = (byte*)fn;
|
||||||
|
if (p[0] == 0xDD && p[1] == 0x41 && p[3] == 0xC3)
|
||||||
|
{
|
||||||
|
_lastInputOffset = p[2];
|
||||||
|
RynthLog.Compat($"LogoffProbe: CInputManager last-input time at +0x{_lastInputOffset:X2} (GetLastInputTimestamp @ 0x{fn:X8}).");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
RynthLog.Compat($"LogoffProbe: GetLastInputTimestamp @ 0x{fn:X8} has unexpected bytes {p[0]:X2} {p[1]:X2} {p[2]:X2} {p[3]:X2} - idle probe off.");
|
||||||
|
}
|
||||||
|
return _lastInputOffset;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Ring buffers ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private const uint WM_DESTROY = 0x0002;
|
||||||
|
private const uint WM_ACTIVATE = 0x0006;
|
||||||
|
private const uint WM_SETFOCUS = 0x0007;
|
||||||
|
private const uint WM_KILLFOCUS = 0x0008;
|
||||||
|
private const uint WM_CLOSE = 0x0010;
|
||||||
|
private const uint WM_QUERYENDSESSION = 0x0011;
|
||||||
|
private const uint WM_ENDSESSION = 0x0016;
|
||||||
|
private const uint WM_ACTIVATEAPP = 0x001C;
|
||||||
|
private const uint WM_KEYDOWN = 0x0100;
|
||||||
|
private const uint WM_KEYUP = 0x0101;
|
||||||
|
private const uint WM_SYSKEYDOWN = 0x0104;
|
||||||
|
private const uint WM_SYSKEYUP = 0x0105;
|
||||||
|
private const uint WM_SYSCOMMAND = 0x0112;
|
||||||
|
private const uint WM_MOUSEMOVE = 0x0200;
|
||||||
|
private const uint WM_LBUTTONDOWN = 0x0201;
|
||||||
|
private const uint WM_RBUTTONDOWN = 0x0204;
|
||||||
|
private const uint WM_MBUTTONDOWN = 0x0207;
|
||||||
|
private const uint WM_XBUTTONDOWN = 0x020B;
|
||||||
|
|
||||||
|
private struct MsgEntry
|
||||||
|
{
|
||||||
|
public long Ms;
|
||||||
|
public uint Msg;
|
||||||
|
public int WParam;
|
||||||
|
public int LParam;
|
||||||
|
public bool Synthetic;
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct ChatEntry
|
||||||
|
{
|
||||||
|
public long Ms;
|
||||||
|
public string Source;
|
||||||
|
public string Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private const int MsgRingSize = 24;
|
||||||
|
private const int ChatRingSize = 16;
|
||||||
|
private static readonly MsgEntry[] _msgRing = new MsgEntry[MsgRingSize];
|
||||||
|
private static readonly ChatEntry[] _chatRing = new ChatEntry[ChatRingSize];
|
||||||
|
private static int _msgCount;
|
||||||
|
private static int _chatCount;
|
||||||
|
private static readonly object _ringLock = new();
|
||||||
|
|
||||||
|
private static long _lastMouseMoveMs;
|
||||||
|
private static long _lastRealKeyMs;
|
||||||
|
private static long _lastRealClickMs;
|
||||||
|
private static long _lastKillFocusMs;
|
||||||
|
private static long _lastSetFocusMs;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Records an input/focus/close message seen by the game WndProc subclass
|
||||||
|
/// (<paramref name="synthetic"/> = false) or sent by the engine through
|
||||||
|
/// Win32Backend.SendToGameWndProc (true). Cheap filter first; never throws.
|
||||||
|
/// </summary>
|
||||||
|
internal static void RecordWndMsg(uint msg, IntPtr wParam, IntPtr lParam, bool synthetic)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
long now;
|
||||||
|
switch (msg)
|
||||||
|
{
|
||||||
|
case WM_MOUSEMOVE:
|
||||||
|
if (!synthetic) Volatile.Write(ref _lastMouseMoveMs, Environment.TickCount64);
|
||||||
|
return;
|
||||||
|
case WM_KEYDOWN:
|
||||||
|
case WM_SYSKEYDOWN:
|
||||||
|
// Skip auto-repeat (bit 30 = key was already down) so a held key can't flood the ring.
|
||||||
|
if (((long)lParam & 0x40000000) != 0) return;
|
||||||
|
now = Environment.TickCount64;
|
||||||
|
if (!synthetic) Volatile.Write(ref _lastRealKeyMs, now);
|
||||||
|
break;
|
||||||
|
case WM_KEYUP:
|
||||||
|
case WM_SYSKEYUP:
|
||||||
|
now = Environment.TickCount64;
|
||||||
|
if (!synthetic) Volatile.Write(ref _lastRealKeyMs, now);
|
||||||
|
break;
|
||||||
|
case WM_LBUTTONDOWN:
|
||||||
|
case WM_RBUTTONDOWN:
|
||||||
|
case WM_MBUTTONDOWN:
|
||||||
|
case WM_XBUTTONDOWN:
|
||||||
|
now = Environment.TickCount64;
|
||||||
|
if (!synthetic) Volatile.Write(ref _lastRealClickMs, now);
|
||||||
|
break;
|
||||||
|
case WM_SETFOCUS:
|
||||||
|
now = Environment.TickCount64;
|
||||||
|
Volatile.Write(ref _lastSetFocusMs, now);
|
||||||
|
break;
|
||||||
|
case WM_KILLFOCUS:
|
||||||
|
now = Environment.TickCount64;
|
||||||
|
Volatile.Write(ref _lastKillFocusMs, now);
|
||||||
|
break;
|
||||||
|
case WM_DESTROY:
|
||||||
|
case WM_ACTIVATE:
|
||||||
|
case WM_CLOSE:
|
||||||
|
case WM_QUERYENDSESSION:
|
||||||
|
case WM_ENDSESSION:
|
||||||
|
case WM_ACTIVATEAPP:
|
||||||
|
case WM_SYSCOMMAND:
|
||||||
|
now = Environment.TickCount64;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (_ringLock)
|
||||||
|
{
|
||||||
|
ref MsgEntry e = ref _msgRing[_msgCount % MsgRingSize];
|
||||||
|
e.Ms = now;
|
||||||
|
e.Msg = msg;
|
||||||
|
e.WParam = (int)(long)wParam;
|
||||||
|
e.LParam = (int)(long)lParam;
|
||||||
|
e.Synthetic = synthetic;
|
||||||
|
_msgCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Records a chat line passing through one of the engine's chat paths.</summary>
|
||||||
|
internal static void RecordChat(string source, string? text)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (text == null) return;
|
||||||
|
string t = text.Length > 120 ? text.Substring(0, 120) + "..." : text;
|
||||||
|
lock (_ringLock)
|
||||||
|
{
|
||||||
|
ref ChatEntry e = ref _chatRing[_chatCount % ChatRingSize];
|
||||||
|
e.Ms = Environment.TickCount64;
|
||||||
|
e.Source = source;
|
||||||
|
e.Text = t;
|
||||||
|
_chatCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Context dump ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
|
||||||
|
[DllImport("user32.dll")] private static extern IntPtr GetFocus();
|
||||||
|
[DllImport("user32.dll")] private static extern IntPtr GetActiveWindow();
|
||||||
|
[DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd);
|
||||||
|
[DllImport("kernel32.dll")] private static extern void GetCurrentThreadStackLimits(out IntPtr lowLimit, out IntPtr highLimit);
|
||||||
|
|
||||||
|
private static string Ago(long ms, long now)
|
||||||
|
=> ms == 0 ? "never" : $"{(now - ms) / 1000.0:0.0}s ago";
|
||||||
|
|
||||||
|
private static string DescribeFocus()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
IntPtr game = ImGuiBackend.Win32Backend.GameHwnd;
|
||||||
|
long now = Environment.TickCount64;
|
||||||
|
IntPtr fg = GetForegroundWindow();
|
||||||
|
int fgGame = game != IntPtr.Zero && fg == game ? 1 : 0;
|
||||||
|
int focusGame = game != IntPtr.Zero && GetFocus() == game ? 1 : 0;
|
||||||
|
int iconic = game != IntPtr.Zero && IsIconic(game) ? 1 : 0;
|
||||||
|
return $"fg={fgGame} focus={focusGame} min={iconic} killfocus={Ago(Volatile.Read(ref _lastKillFocusMs), now)} setfocus={Ago(Volatile.Read(ref _lastSetFocusMs), now)}";
|
||||||
|
}
|
||||||
|
catch { return "fg=?"; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DumpContext(string trigger)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
long now = Environment.TickCount64;
|
||||||
|
DateTime wallNow = DateTime.Now;
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
sb.Append($"LogoffProbe: ---- context dump ({trigger}) ----");
|
||||||
|
|
||||||
|
if (TryReadIdle(out double idle, out double limit, out double cur, out double last))
|
||||||
|
sb.Append($"\n idle: Timer::cur_time={cur:0.000} lastInput={last:0.000} idle={idle:0.0}s threshold={limit:0.#}s");
|
||||||
|
else
|
||||||
|
sb.Append("\n idle: unavailable");
|
||||||
|
|
||||||
|
IntPtr game = ImGuiBackend.Win32Backend.GameHwnd;
|
||||||
|
IntPtr fg = GetForegroundWindow();
|
||||||
|
sb.Append($"\n window: game=0x{game.ToInt64():X} foreground=0x{fg.ToInt64():X} active=0x{GetActiveWindow().ToInt64():X} focus=0x{GetFocus().ToInt64():X} minimized={(game != IntPtr.Zero && IsIconic(game) ? 1 : 0)}");
|
||||||
|
sb.Append($"\n engine-seen input: key={Ago(Volatile.Read(ref _lastRealKeyMs), now)} click={Ago(Volatile.Read(ref _lastRealClickMs), now)} mousemove={Ago(Volatile.Read(ref _lastMouseMoveMs), now)} killfocus={Ago(Volatile.Read(ref _lastKillFocusMs), now)} setfocus={Ago(Volatile.Read(ref _lastSetFocusMs), now)}");
|
||||||
|
|
||||||
|
sb.Append("\n acclient stack sweep (may include stale frames):");
|
||||||
|
AppendStackSweep(sb);
|
||||||
|
|
||||||
|
MsgEntry[] msgs;
|
||||||
|
ChatEntry[] chats;
|
||||||
|
int msgCount, chatCount;
|
||||||
|
lock (_ringLock)
|
||||||
|
{
|
||||||
|
msgs = (MsgEntry[])_msgRing.Clone();
|
||||||
|
chats = (ChatEntry[])_chatRing.Clone();
|
||||||
|
msgCount = _msgCount;
|
||||||
|
chatCount = _chatCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
int mn = Math.Min(msgCount, MsgRingSize);
|
||||||
|
sb.Append($"\n last {mn} window messages (of {msgCount}):");
|
||||||
|
for (int i = msgCount - mn; i < msgCount; i++)
|
||||||
|
{
|
||||||
|
MsgEntry e = msgs[i % MsgRingSize];
|
||||||
|
sb.Append($"\n {Clock(wallNow, now, e.Ms)} {(e.Synthetic ? "synth " : "")}{DescribeMsg(e)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
int cn = Math.Min(chatCount, ChatRingSize);
|
||||||
|
sb.Append($"\n last {cn} engine chat lines (of {chatCount}):");
|
||||||
|
for (int i = chatCount - cn; i < chatCount; i++)
|
||||||
|
{
|
||||||
|
ChatEntry e = chats[i % ChatRingSize];
|
||||||
|
sb.Append($"\n {Clock(wallNow, now, e.Ms)} [{e.Source}] '{e.Text}'");
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.Append("\nLogoffProbe: ---- end context dump ----");
|
||||||
|
RynthLog.Info(sb.ToString());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
try { RynthLog.Info($"LogoffProbe: context dump failed: {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Clock(DateTime wallNow, long now, long ms)
|
||||||
|
=> $"{wallNow.AddMilliseconds(-(now - ms)):HH:mm:ss.fff} ({(ms - now) / 1000.0:0.0}s)";
|
||||||
|
|
||||||
|
private static string DescribeMsg(MsgEntry e)
|
||||||
|
{
|
||||||
|
switch (e.Msg)
|
||||||
|
{
|
||||||
|
case WM_KEYDOWN: return $"WM_KEYDOWN vk=0x{e.WParam & 0xFF:X2}{(IsExtended(e.LParam) ? " ext" : "")}";
|
||||||
|
case WM_KEYUP: return $"WM_KEYUP vk=0x{e.WParam & 0xFF:X2}{(IsExtended(e.LParam) ? " ext" : "")}";
|
||||||
|
case WM_SYSKEYDOWN: return $"WM_SYSKEYDOWN vk=0x{e.WParam & 0xFF:X2} alt={((e.LParam >> 29) & 1)}";
|
||||||
|
case WM_SYSKEYUP: return $"WM_SYSKEYUP vk=0x{e.WParam & 0xFF:X2} alt={((e.LParam >> 29) & 1)}";
|
||||||
|
case WM_LBUTTONDOWN: return $"WM_LBUTTONDOWN ({(short)(e.LParam & 0xFFFF)},{(short)((e.LParam >> 16) & 0xFFFF)})";
|
||||||
|
case WM_RBUTTONDOWN: return $"WM_RBUTTONDOWN ({(short)(e.LParam & 0xFFFF)},{(short)((e.LParam >> 16) & 0xFFFF)})";
|
||||||
|
case WM_MBUTTONDOWN: return "WM_MBUTTONDOWN";
|
||||||
|
case WM_XBUTTONDOWN: return "WM_XBUTTONDOWN";
|
||||||
|
case WM_SETFOCUS: return $"WM_SETFOCUS from=0x{e.WParam:X}";
|
||||||
|
case WM_KILLFOCUS: return $"WM_KILLFOCUS to=0x{e.WParam:X}";
|
||||||
|
case WM_ACTIVATE: return $"WM_ACTIVATE state={e.WParam & 0xFFFF} other=0x{e.LParam:X}";
|
||||||
|
case WM_ACTIVATEAPP: return $"WM_ACTIVATEAPP active={e.WParam} tid={e.LParam}";
|
||||||
|
case WM_CLOSE: return "WM_CLOSE";
|
||||||
|
case WM_DESTROY: return "WM_DESTROY";
|
||||||
|
case WM_QUERYENDSESSION: return "WM_QUERYENDSESSION";
|
||||||
|
case WM_ENDSESSION: return $"WM_ENDSESSION ending={e.WParam}";
|
||||||
|
case WM_SYSCOMMAND: return $"WM_SYSCOMMAND cmd=0x{e.WParam & 0xFFF0:X4}{((e.WParam & 0xFFF0) == 0xF060 ? " (SC_CLOSE)" : "")}";
|
||||||
|
default: return $"msg=0x{e.Msg:X4} w=0x{e.WParam:X} l=0x{e.LParam:X}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsExtended(int lParam) => ((lParam >> 24) & 1) != 0;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Scans this thread's stack above the current frame for values that are return
|
||||||
|
/// addresses into acclient .text (preceded by a call instruction). AC is built with
|
||||||
|
/// frame-pointer omission, so the EBP walk in LogCaller stops at the first AC frame;
|
||||||
|
/// this recovers the AC callers above it. Stale values from earlier calls can appear.
|
||||||
|
/// </summary>
|
||||||
|
private static void AppendStackSweep(StringBuilder sb)
|
||||||
|
{
|
||||||
|
int local = 0;
|
||||||
|
long start = (long)(nint)(&local);
|
||||||
|
GetCurrentThreadStackLimits(out IntPtr lowLimit, out IntPtr highLimit);
|
||||||
|
long high = highLimit.ToInt64();
|
||||||
|
if (start < lowLimit.ToInt64() || start >= high)
|
||||||
|
{
|
||||||
|
sb.Append(" <stack limits unavailable>");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
long end = Math.Min(high, start + 0x3000);
|
||||||
|
int hits = 0;
|
||||||
|
for (long a = (start + 3) & ~3L; a + 4 <= end && hits < 16; a += 4)
|
||||||
|
{
|
||||||
|
long v = *(uint*)a;
|
||||||
|
if (v < _acTextLo + 8 || v >= _acTextHi)
|
||||||
|
continue;
|
||||||
|
if (!LooksLikeReturnAddress((byte*)v))
|
||||||
|
continue;
|
||||||
|
hits++;
|
||||||
|
sb.Append($" {DescribeAcclientAddress((IntPtr)v)}");
|
||||||
|
}
|
||||||
|
if (hits == 0)
|
||||||
|
sb.Append(" <none>");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool LooksLikeReturnAddress(byte* ret)
|
||||||
|
{
|
||||||
|
if (ret[-5] == 0xE8) return true; // call rel32
|
||||||
|
if (ret[-2] == 0xFF && ((ret[-1] >> 3) & 7) == 2 && (ret[-1] >> 6) == 3) return true; // call reg
|
||||||
|
if (ret[-3] == 0xFF && ((ret[-2] >> 3) & 7) == 2 && (ret[-2] >> 6) == 1) return true; // call [reg+disp8]
|
||||||
|
if (ret[-2] == 0xFF && ((ret[-1] >> 3) & 7) == 2 && (ret[-1] >> 6) == 0) return true; // call [reg]
|
||||||
|
if (ret[-6] == 0xFF && ((ret[-5] >> 3) & 7) == 2 && ((ret[-5] >> 6) == 2 || (ret[-5] & 0xC7) == 0x05)) return true; // call [reg+disp32] / [abs]
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string DescribeAcclientAddress(IntPtr addr)
|
||||||
|
{
|
||||||
|
if (addr == IntPtr.Zero)
|
||||||
|
return "<no acclient frame>";
|
||||||
|
int rva = (int)(addr.ToInt64() - _acBase);
|
||||||
|
string label = LabelForAcclientRva(rva);
|
||||||
|
return label.Length > 0 ? $"acclient.exe+0x{rva:X}{{{label}}}" : $"acclient.exe+0x{rva:X}";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Names the known logoff-related call sites by return-address RVA. Reference client
|
||||||
|
/// only (labels are off on any other build); the raw module+RVA is always logged.
|
||||||
|
/// </summary>
|
||||||
|
internal static string LabelForAcclientRva(int rva)
|
||||||
|
{
|
||||||
|
if (!_labelsValid)
|
||||||
|
return "";
|
||||||
|
return rva switch
|
||||||
|
{
|
||||||
|
// callers of CPlayerSystem::LogOffCharacter
|
||||||
|
0x166056 => "ClientUISystem::UseTime: idle auto-logoff",
|
||||||
|
0x0EB0E9 => "gmGamePlayUI::UseTime: logout confirmed in the UI",
|
||||||
|
0x0EAEC8 => "gmGamePlayUI::EndSession",
|
||||||
|
0x0EA80F => "gmEpilogueUI ctor",
|
||||||
|
0x15AD39 => "APIManager::EndCharacterSession: plugin API",
|
||||||
|
// callers of CPlayerSystem::RequestLogOff
|
||||||
|
0x1642EE => "CPlayerSystem::LogOffCharacter",
|
||||||
|
0x163FC6 => "CPlayerSystem::UseTime: deferred request",
|
||||||
|
// caller of Proto_UI::LogOffCharacter
|
||||||
|
0x163BC4 => "CPlayerSystem::RequestLogOff",
|
||||||
|
// callers of CPlayerSystem::ExecuteLogOff
|
||||||
|
0x15D676 => "server CharacterLogOff 0xF653 handler",
|
||||||
|
0x1642DC => "CPlayerSystem::LogOffCharacter(immediate)",
|
||||||
|
// caller of CPlayerSystem::SetLogOffStarted
|
||||||
|
0x0D7AF8 => "gmSmartBoxUI::UseTime",
|
||||||
|
// callers of ClientNet::LogOffServer
|
||||||
|
0x01160C => "Client::Disconnect",
|
||||||
|
0x012077 => "Client::CleanupNet",
|
||||||
|
0x145E79 => "ClientNet::ProcessOptionalHeader: server disconnect",
|
||||||
|
0x145FEC => "ClientNet::RemoveConnection",
|
||||||
|
_ => "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -133,7 +133,11 @@ internal static class LogoutLifecycleHooks
|
||||||
{
|
{
|
||||||
RecursionGuard.Tick("LogoutLifecycleHooks.ExecuteLogOff");
|
RecursionGuard.Tick("LogoutLifecycleHooks.ExecuteLogOff");
|
||||||
if (!HasObservedLogout)
|
if (!HasObservedLogout)
|
||||||
|
{
|
||||||
RynthLog.Compat("LogoutLifecycleHooks: ExecuteLogOff detour entered.");
|
RynthLog.Compat("LogoutLifecycleHooks: ExecuteLogOff detour entered.");
|
||||||
|
LogCaller("ExecuteLogOff");
|
||||||
|
LogoffOriginProbe.OnLogoffCompleted("CPlayerSystem::ExecuteLogOff");
|
||||||
|
}
|
||||||
|
|
||||||
try { _originalExecuteLogOff!(thisPtr); }
|
try { _originalExecuteLogOff!(thisPtr); }
|
||||||
catch (Exception ex) { try { RynthLog.Compat($"LogoutLifecycleHooks: ExecuteLogOff original threw {ex.GetType().Name}: {ex.Message}"); } catch { } }
|
catch (Exception ex) { try { RynthLog.Compat($"LogoutLifecycleHooks: ExecuteLogOff original threw {ex.GetType().Name}: {ex.Message}"); } catch { } }
|
||||||
|
|
@ -145,7 +149,11 @@ internal static class LogoutLifecycleHooks
|
||||||
{
|
{
|
||||||
RecursionGuard.Tick("LogoutLifecycleHooks.RecvNoticeLogoff");
|
RecursionGuard.Tick("LogoutLifecycleHooks.RecvNoticeLogoff");
|
||||||
if (!HasObservedLogout)
|
if (!HasObservedLogout)
|
||||||
|
{
|
||||||
RynthLog.Compat("LogoutLifecycleHooks: RecvNotice_Logoff detour entered.");
|
RynthLog.Compat("LogoutLifecycleHooks: RecvNotice_Logoff detour entered.");
|
||||||
|
LogCaller("RecvNotice_Logoff");
|
||||||
|
LogoffOriginProbe.OnLogoffCompleted("gmGamePlayUI::RecvNotice_Logoff");
|
||||||
|
}
|
||||||
|
|
||||||
try { _originalRecvNoticeLogoff!(thisPtr); }
|
try { _originalRecvNoticeLogoff!(thisPtr); }
|
||||||
catch (Exception ex) { try { RynthLog.Compat($"LogoutLifecycleHooks: RecvNotice_Logoff original threw {ex.GetType().Name}: {ex.Message}"); } catch { } }
|
catch (Exception ex) { try { RynthLog.Compat($"LogoutLifecycleHooks: RecvNotice_Logoff original threw {ex.GetType().Name}: {ex.Message}"); } catch { } }
|
||||||
|
|
@ -153,6 +161,49 @@ internal static class LogoutLifecycleHooks
|
||||||
RaiseLogoutCompleteOnce("gmGamePlayUI::RecvNotice_Logoff");
|
RaiseLogoutCompleteOnce("gmGamePlayUI::RecvNotice_Logoff");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll")]
|
||||||
|
private static extern ushort RtlCaptureStackBackTrace(
|
||||||
|
uint FramesToSkip, uint FramesToCapture, IntPtr[] BackTrace, out uint BackTraceHash);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Logs who in the client called the logoff, as module+RVA frames. Characters were
|
||||||
|
/// logging off by themselves (2026-09-27, Lucy, twice mid-route) with no meta, no
|
||||||
|
/// command and nothing from the server, so the next one needs to say which client
|
||||||
|
/// code path confirmed it (UI button, chat /logout, something else). x86 EBP walk:
|
||||||
|
/// deep frames can be unreliable, the first acclient frames are the useful ones.
|
||||||
|
/// Known logoff call sites get a {label} (LogoffOriginProbe). Returns the first
|
||||||
|
/// acclient.exe frame (the immediate AC caller), or Zero if none was captured.
|
||||||
|
/// </summary>
|
||||||
|
internal static IntPtr LogCaller(string hook, string prefix = "LogoutLifecycleHooks")
|
||||||
|
{
|
||||||
|
IntPtr firstAcclient = IntPtr.Zero;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var frames = new IntPtr[24];
|
||||||
|
ushort captured = RtlCaptureStackBackTrace(1, (uint)frames.Length, frames, out _);
|
||||||
|
var sb = new System.Text.StringBuilder($"{prefix}: {hook} caller frames:");
|
||||||
|
for (int i = 0; i < captured && frames[i] != IntPtr.Zero; i++)
|
||||||
|
{
|
||||||
|
string module = ProcessExitHooks.ResolveModule(frames[i], out int rva);
|
||||||
|
sb.Append($" [{i}] {module}+0x{rva:X}");
|
||||||
|
if (string.Equals(module, "acclient.exe", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
if (firstAcclient == IntPtr.Zero)
|
||||||
|
firstAcclient = frames[i];
|
||||||
|
string label = LogoffOriginProbe.LabelForAcclientRva(rva);
|
||||||
|
if (label.Length > 0)
|
||||||
|
sb.Append($"{{{label}}}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RynthLog.Compat(sb.ToString());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
try { RynthLog.Compat($"{prefix}: {hook} caller capture failed: {ex.GetType().Name}"); } catch { }
|
||||||
|
}
|
||||||
|
return firstAcclient;
|
||||||
|
}
|
||||||
|
|
||||||
private static void RaiseLogoutCompleteOnce(string source)
|
private static void RaiseLogoutCompleteOnce(string source)
|
||||||
{
|
{
|
||||||
if (HasObservedLogout)
|
if (HasObservedLogout)
|
||||||
|
|
|
||||||
|
|
@ -424,7 +424,7 @@ internal static class ProcessExitHooks
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string ResolveModule(IntPtr address, out int rva)
|
internal static string ResolveModule(IntPtr address, out int rva)
|
||||||
{
|
{
|
||||||
rva = 0;
|
rva = 0;
|
||||||
try
|
try
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,10 @@ namespace RynthCore.Engine.Compatibility;
|
||||||
/// recovery.</item>
|
/// recovery.</item>
|
||||||
/// <item><c>/rc vitals</c> (alias <c>/rc hud</c>) — toggle the custom D3D9
|
/// <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>
|
/// Health/Stamina/Mana HUD on/off (persisted to engine.json).</item>
|
||||||
|
/// <item><c>/rc vendor [list|info|status|buy <id|sel> [n]|sell <id|sel> [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>
|
||||||
/// </list>
|
/// </list>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal static class RynthCoreChatCommands
|
internal static class RynthCoreChatCommands
|
||||||
|
|
@ -41,6 +45,15 @@ internal static class RynthCoreChatCommands
|
||||||
|
|
||||||
string sub = trimmed.Substring(Prefix.Length).Trim();
|
string sub = trimmed.Substring(Prefix.Length).Trim();
|
||||||
|
|
||||||
|
// /rc vendor [list|info|status|buy <id|sel> [n]|sell <id|sel> [id ...]]
|
||||||
|
if (sub.Equals("vendor", StringComparison.OrdinalIgnoreCase)
|
||||||
|
|| sub.StartsWith("vendor ", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
try { VendorTrade.HandleChatCommand(sub.Length > 6 ? sub.Substring(7) : string.Empty); }
|
||||||
|
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc vendor failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
switch (sub.ToLowerInvariant())
|
switch (sub.ToLowerInvariant())
|
||||||
{
|
{
|
||||||
case "resetbar":
|
case "resetbar":
|
||||||
|
|
|
||||||
|
|
@ -188,9 +188,30 @@ internal static class UpdateObjectInventoryHooks
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static int ScanByContainerId(uint containerId, Span<uint> itemIds)
|
private static int ScanByContainerId(uint containerId, Span<uint> itemIds)
|
||||||
{
|
{
|
||||||
|
// 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
|
||||||
|
// invisible to the bot: no bundles to craft from, inventory lookups finding nothing.
|
||||||
|
uint[] live = ClientObjectHooks.LiveObjectIds;
|
||||||
|
if (live.Length > 0)
|
||||||
|
{
|
||||||
|
int found = 0;
|
||||||
|
foreach (uint id in live)
|
||||||
|
{
|
||||||
|
if (found >= itemIds.Length) break;
|
||||||
|
if (id == containerId) continue;
|
||||||
|
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint c, out uint w, out _))
|
||||||
|
continue;
|
||||||
|
if (c == containerId || w == containerId)
|
||||||
|
itemIds[found++] = id;
|
||||||
|
}
|
||||||
|
itemIds[..found].Sort(); // same ascending order the range scan gave
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
int written = 0;
|
int written = 0;
|
||||||
|
|
||||||
// Scan dynamic object range (0x80000001 – 0x8000FFFF)
|
// No snapshot yet: scan the first dynamic object range (0x80000001 – 0x8000FFFF)
|
||||||
for (uint id = 0x80000001; id <= 0x8000FFFF && written < itemIds.Length; id++)
|
for (uint id = 0x80000001; id <= 0x8000FFFF && written < itemIds.Length; id++)
|
||||||
{
|
{
|
||||||
if (id == containerId) continue;
|
if (id == containerId) continue;
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,10 @@ namespace RynthCore.Engine.Compatibility;
|
||||||
/// RecvNotice_CloseVendor = 0x000BFF40 + 0x00401000 = 0x004C0F40
|
/// RecvNotice_CloseVendor = 0x000BFF40 + 0x00401000 = 0x004C0F40
|
||||||
///
|
///
|
||||||
/// We hook the real impl (0x004C5790, called by the thunk) and the close entry directly.
|
/// We hook the real impl (0x004C5790, called by the thunk) and the close entry directly.
|
||||||
|
///
|
||||||
|
/// The open detour also feeds <see cref="VendorTrade"/> (the vendor snapshot plugins
|
||||||
|
/// read and trade against); the close path goes through <see cref="MarkVendorClosed"/>,
|
||||||
|
/// which VendorTrade's main-thread poll also calls when the vendor window goes away.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal static class VendorHooks
|
internal static class VendorHooks
|
||||||
{
|
{
|
||||||
|
|
@ -104,22 +108,62 @@ internal static class VendorHooks
|
||||||
{
|
{
|
||||||
_statusMessage = ex.Message;
|
_statusMessage = ex.Message;
|
||||||
RynthLog.Compat($"Compat: vendor hooks failed - {ex.Message}");
|
RynthLog.Compat($"Compat: vendor hooks failed - {ex.Message}");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Vendor trading rides on these detours (snapshot + close tracking).
|
||||||
|
try { VendorTrade.Initialize(textSection); }
|
||||||
|
catch (Exception ex) { RynthLog.Warn($"VendorTrade: init failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void OpenVendorDetour(IntPtr thisPtr, uint vendorId, IntPtr vpRef, IntPtr itemsRef, int shopMode)
|
private static void OpenVendorDetour(IntPtr thisPtr, uint vendorId, IntPtr vpRef, IntPtr itemsRef, int shopMode)
|
||||||
{
|
{
|
||||||
|
// Copy the vendor out of the arguments BEFORE the original runs: OpenVendor frees
|
||||||
|
// the item PWDs on its own copy as it turns them into weenie objects.
|
||||||
|
VendorSnapshot? snap = null;
|
||||||
|
if (vendorId != 0)
|
||||||
|
{
|
||||||
|
try { snap = VendorTrade.CaptureFromNotice(vendorId, vpRef, itemsRef, shopMode); }
|
||||||
|
catch { snap = null; }
|
||||||
|
}
|
||||||
|
|
||||||
_originalOpen!(thisPtr, vendorId, vpRef, itemsRef, shopMode);
|
_originalOpen!(thisPtr, vendorId, vpRef, itemsRef, shopMode);
|
||||||
if (vendorId == 0) return;
|
if (vendorId == 0) return;
|
||||||
|
|
||||||
|
try { VendorTrade.OnVendorOpened(thisPtr, vendorId, snap); }
|
||||||
|
catch { }
|
||||||
|
|
||||||
|
// Switching straight to another vendor never sends a close notice; tell plugins.
|
||||||
|
uint prev = _currentVendorId;
|
||||||
_currentVendorId = vendorId;
|
_currentVendorId = vendorId;
|
||||||
|
if (prev != 0 && prev != vendorId)
|
||||||
|
PluginManager.QueueVendorClose(prev);
|
||||||
PluginManager.QueueVendorOpen(vendorId);
|
PluginManager.QueueVendorOpen(vendorId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void CloseVendorDetour(IntPtr thisPtr, int updating)
|
private static void CloseVendorDetour(IntPtr thisPtr, int updating)
|
||||||
{
|
{
|
||||||
_originalClose!(thisPtr, updating);
|
_originalClose!(thisPtr, updating);
|
||||||
|
// The flag is a bool in the low byte (MOV AL,[ESP+4]; TEST AL,AL); the rest of the
|
||||||
|
// stack slot is garbage. With it set, the retail function returns without closing
|
||||||
|
// anything, so neither do we.
|
||||||
|
if ((updating & 0xFF) != 0)
|
||||||
|
return;
|
||||||
|
MarkVendorClosed("close notice");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The vendor is gone: clear the trade snapshot and raise OnVendorClose once. Called
|
||||||
|
/// from the close detour and from VendorTrade's main-thread poll of gmVendorUI's
|
||||||
|
/// shopVendorID, which backs the notice up for any close path that skips it.
|
||||||
|
/// AC's main thread only.
|
||||||
|
/// </summary>
|
||||||
|
internal static void MarkVendorClosed(string reason)
|
||||||
|
{
|
||||||
uint vid = _currentVendorId;
|
uint vid = _currentVendorId;
|
||||||
_currentVendorId = 0;
|
_currentVendorId = 0;
|
||||||
|
try { VendorTrade.OnVendorClosed(reason); }
|
||||||
|
catch { }
|
||||||
if (vid != 0)
|
if (vid != 0)
|
||||||
PluginManager.QueueVendorClose(vid);
|
PluginManager.QueueVendorClose(vid);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
1488
src/RynthCore.Engine/Compatibility/VendorTrade.cs
Normal file
1488
src/RynthCore.Engine/Compatibility/VendorTrade.cs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -334,9 +334,13 @@ internal static class EndSceneHook
|
||||||
// is visible even when ImGui per-frame work is disabled. Driven
|
// is visible even when ImGui per-frame work is disabled. Driven
|
||||||
// here exclusively — EngineFrameController.OnEndScene intentionally
|
// here exclusively — EngineFrameController.OnEndScene intentionally
|
||||||
// does NOT call it (avoids double-blit / TryConsume races).
|
// does NOT call it (avoids double-blit / TryConsume races).
|
||||||
|
// The UI hides between characters: nothing is drawn at character select or
|
||||||
|
// on the way out, and it's back the moment login completes (an engine
|
||||||
|
// reload synthesises login for a player already in the world).
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
OverlayTextureRenderer.Render(pDevice);
|
if (Compatibility.LoginLifecycleHooks.HasObservedLoginComplete)
|
||||||
|
OverlayTextureRenderer.Render(pDevice);
|
||||||
}
|
}
|
||||||
catch (Exception ovEx)
|
catch (Exception ovEx)
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -190,6 +190,9 @@ public static class EntryPoint
|
||||||
private static string? GetEngineDirectory() =>
|
private static string? GetEngineDirectory() =>
|
||||||
GetEngineModulePath() is { } path ? Path.GetDirectoryName(path) : null;
|
GetEngineModulePath() is { } path ? Path.GetDirectoryName(path) : null;
|
||||||
|
|
||||||
|
/// <summary>Folder of the loaded engine DLL (Runtime\, or Runtime\.engine_loads\ on a staged load).</summary>
|
||||||
|
internal static string? EngineDirectory => GetEngineDirectory();
|
||||||
|
|
||||||
/// <summary>Full path of the engine DLL actually loaded (the loader's staged copy on hot reload).</summary>
|
/// <summary>Full path of the engine DLL actually loaded (the loader's staged copy on hot reload).</summary>
|
||||||
private static unsafe string? GetEngineModulePath()
|
private static unsafe string? GetEngineModulePath()
|
||||||
{
|
{
|
||||||
|
|
@ -533,6 +536,7 @@ public static class EntryPoint
|
||||||
// scenarios where keyboard input isn't reaching AC's chat box.
|
// scenarios where keyboard input isn't reaching AC's chat box.
|
||||||
Step("chat file dispatcher", ChatFileDispatcher.Start);
|
Step("chat file dispatcher", ChatFileDispatcher.Start);
|
||||||
Step("logout lifecycle hooks", LogoutLifecycleHooks.Initialize);
|
Step("logout lifecycle hooks", LogoutLifecycleHooks.Initialize);
|
||||||
|
Step("logoff origin probe", LogoffOriginProbe.Initialize);
|
||||||
Step("session state registry", SessionStateRegistry.Initialize);
|
Step("session state registry", SessionStateRegistry.Initialize);
|
||||||
Step("UI lifecycle hooks", UiLifecycleHooks.Initialize);
|
Step("UI lifecycle hooks", UiLifecycleHooks.Initialize);
|
||||||
Step("logo bypass", LogoBypassHooks.Start);
|
Step("logo bypass", LogoBypassHooks.Start);
|
||||||
|
|
|
||||||
|
|
@ -224,11 +224,11 @@ internal static class EngineFrameController
|
||||||
DX9Backend.Shutdown();
|
DX9Backend.Shutdown();
|
||||||
// Do NOT call Win32Backend.Shutdown() here. EngineLifecycle.Shutdown
|
// Do NOT call Win32Backend.Shutdown() here. EngineLifecycle.Shutdown
|
||||||
// owns that step explicitly, AFTER AvaloniaOverlay.Stop — floating
|
// owns that step explicitly, AFTER AvaloniaOverlay.Stop — floating
|
||||||
// panels are destroyed via RunOnGameThread (a SendMessage handled by
|
// panels can only be destroyed on the game thread by our subclass
|
||||||
// our subclass WndProc), so restoring AC's original WndProc this
|
// WndProc (Win32Backend.Shutdown sweeps any still open before it
|
||||||
// early makes that SendMessage land on AC's proc, get ignored, and
|
// unhooks), so restoring AC's original WndProc this early sends
|
||||||
// "succeed" — DestroyWindow never runs and the orphaned panel HWND
|
// those destroys to AC's proc, which ignores them, and the orphaned
|
||||||
// outlives the engine module with its WndProc pointing at freed code.
|
// panel HWND outlives the engine load.
|
||||||
ImGuiNET.ImGui.DestroyContext(contextToDestroy);
|
ImGuiNET.ImGui.DestroyContext(contextToDestroy);
|
||||||
|
|
||||||
_imguiInitialized = false;
|
_imguiInitialized = false;
|
||||||
|
|
|
||||||
|
|
@ -78,6 +78,12 @@ internal static unsafe class Win32Backend
|
||||||
/// finish. wParam carries the HWND to destroy.</summary>
|
/// finish. wParam carries the HWND to destroy.</summary>
|
||||||
public const uint WM_RYNTH_DESTROY_HWND = 0x8003;
|
public const uint WM_RYNTH_DESTROY_HWND = 0x8003;
|
||||||
|
|
||||||
|
/// <summary>Destroys floating-panel HWNDs on the game thread (their owner).
|
||||||
|
/// wParam != 0 includes this engine load's own panels (sent synchronously by
|
||||||
|
/// Shutdown before unhooking); wParam == 0 removes only panels an earlier
|
||||||
|
/// load left behind (posted by Init). See LayeredWindow.DestroyThreadPanelWindows.</summary>
|
||||||
|
public const uint WM_RYNTH_SWEEP_PANELS = 0x8004;
|
||||||
|
|
||||||
private const int VK_CONTROL = 0x11;
|
private const int VK_CONTROL = 0x11;
|
||||||
private const int VK_SHIFT = 0x10;
|
private const int VK_SHIFT = 0x10;
|
||||||
private const int VK_MENU = 0x12; // Alt
|
private const int VK_MENU = 0x12; // Alt
|
||||||
|
|
@ -274,6 +280,8 @@ internal static unsafe class Win32Backend
|
||||||
{
|
{
|
||||||
if (_originalWndProc == IntPtr.Zero || _gameHwnd == IntPtr.Zero)
|
if (_originalWndProc == IntPtr.Zero || _gameHwnd == IntPtr.Zero)
|
||||||
return IntPtr.Zero;
|
return IntPtr.Zero;
|
||||||
|
// Diag (diag/logoff-origin): engine-synthesised input bypasses the subclass.
|
||||||
|
Compatibility.LogoffOriginProbe.RecordWndMsg(msg, wParam, lParam, synthetic: true);
|
||||||
return CallWindowProcA(_originalWndProc, _gameHwnd, msg, wParam, lParam);
|
return CallWindowProcA(_originalWndProc, _gameHwnd, msg, wParam, lParam);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -507,6 +515,12 @@ internal static unsafe class Win32Backend
|
||||||
_initialized = true;
|
_initialized = true;
|
||||||
RynthLog.Render("Win32Backend: Initialized (WndProc subclassed).");
|
RynthLog.Render("Win32Backend: Initialized (WndProc subclassed).");
|
||||||
RynthLog.Render("Win32Backend: UI capture ENABLED by default (Insert to release).");
|
RynthLog.Render("Win32Backend: UI capture ENABLED by default (Insert to release).");
|
||||||
|
|
||||||
|
// A previous engine load may have left floating panels behind (its
|
||||||
|
// teardown predates the synchronous sweep in Shutdown, or the game
|
||||||
|
// thread was stalled past the timeout) — clear them now, while
|
||||||
|
// sparing this load's own.
|
||||||
|
PostMessage(_gameHwnd, WM_RYNTH_SWEEP_PANELS, IntPtr.Zero, IntPtr.Zero);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -517,6 +531,16 @@ internal static unsafe class Win32Backend
|
||||||
{
|
{
|
||||||
if (!_initialized) return;
|
if (!_initialized) return;
|
||||||
|
|
||||||
|
// Destroy floating panels while our hook can still run on the game
|
||||||
|
// thread. LayeredWindow.Dispose only POSTS its destroy, and the game
|
||||||
|
// thread usually hasn't reached that post by the time we unhook below —
|
||||||
|
// AC's own WndProc then drops it and the panel outlives this engine
|
||||||
|
// load, frozen and unclickable (duplicate RynthAi dashboard after RL).
|
||||||
|
IntPtr swept = SendMessageTimeout(_gameHwnd, WM_RYNTH_SWEEP_PANELS, new IntPtr(1), IntPtr.Zero,
|
||||||
|
SMTO_NORMAL, 2000, out _);
|
||||||
|
if (swept == IntPtr.Zero)
|
||||||
|
RynthLog.Info($"Win32Backend: Shutdown — panel sweep didn't run on the game thread (err={Marshal.GetLastWin32Error()}); the next engine load clears what's left.");
|
||||||
|
|
||||||
// Restore the original WndProc ONLY if we are still the head of the
|
// Restore the original WndProc ONLY if we are still the head of the
|
||||||
// chain. If something subclassed on top of us after Init (Decal /
|
// chain. If something subclassed on top of us after Init (Decal /
|
||||||
// DINPUT8 re-hooks, a newer engine generation), a blind restore RIPS
|
// DINPUT8 re-hooks, a newer engine generation), a blind restore RIPS
|
||||||
|
|
@ -695,6 +719,17 @@ internal static unsafe class Win32Backend
|
||||||
return IntPtr.Zero;
|
return IntPtr.Zero;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (msg == WM_RYNTH_SWEEP_PANELS)
|
||||||
|
{
|
||||||
|
try { UI.LayeredWindow.DestroyThreadPanelWindows(includeThisGeneration: wParam != IntPtr.Zero); }
|
||||||
|
catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_SWEEP_PANELS threw {ex.GetType().Name}: {ex.Message}"); }
|
||||||
|
return IntPtr.Zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Diag (diag/logoff-origin): ring of recent key/click/focus/close messages,
|
||||||
|
// dumped when the client requests a logoff. Filters first; never throws.
|
||||||
|
Compatibility.LogoffOriginProbe.RecordWndMsg(msg, wParam, lParam, synthetic: false);
|
||||||
|
|
||||||
// ── User clicked X / Alt+F4 on AC window — tear our overlay down NOW ──
|
// ── User clicked X / Alt+F4 on AC window — tear our overlay down NOW ──
|
||||||
// AC's own shutdown takes 20-30 s (network logout, save, etc.) before
|
// AC's own shutdown takes 20-30 s (network logout, save, etc.) before
|
||||||
// it finally calls ExitProcess and triggers ProcessExitHooks. During
|
// it finally calls ExitProcess and triggers ProcessExitHooks. During
|
||||||
|
|
@ -885,7 +920,14 @@ internal static unsafe class Win32Backend
|
||||||
return IntPtr.Zero;
|
return IntPtr.Zero;
|
||||||
|
|
||||||
// ── Avalonia panel hit-test & input forwarding ────────────────
|
// ── Avalonia panel hit-test & input forwarding ────────────────
|
||||||
if (IsMouseMessage(msg))
|
// Only in the world: between characters the overlay isn't drawn, so its
|
||||||
|
// panels mustn't take clicks meant for character select.
|
||||||
|
bool overlayLive = RynthCore.Engine.Compatibility.LoginLifecycleHooks.HasObservedLoginComplete;
|
||||||
|
if (!overlayLive)
|
||||||
|
{
|
||||||
|
// fall through: AC gets the message
|
||||||
|
}
|
||||||
|
else if (IsMouseMessage(msg))
|
||||||
{
|
{
|
||||||
bool handled = TryForwardToAvalonia(msg, wParam, lParam);
|
bool handled = TryForwardToAvalonia(msg, wParam, lParam);
|
||||||
if (handled)
|
if (handled)
|
||||||
|
|
@ -1108,6 +1150,16 @@ internal static unsafe class Win32Backend
|
||||||
{
|
{
|
||||||
if (msg == WM_LBUTTONUP)
|
if (msg == WM_LBUTTONUP)
|
||||||
_pendingBarButtonTitle = null;
|
_pendingBarButtonTitle = null;
|
||||||
|
|
||||||
|
// An open Flyout / ContextMenu / dropdown is embedded in the
|
||||||
|
// overlay window, but a click on the game world is never
|
||||||
|
// forwarded, so Avalonia's light-dismiss never sees it. Close
|
||||||
|
// it here; the click still goes to AC.
|
||||||
|
if ((msg == WM_LBUTTONDOWN || msg == WM_RBUTTONDOWN || msg == WM_MBUTTONDOWN)
|
||||||
|
&& AvaloniaOverlay.HasOpenLightDismissPopup)
|
||||||
|
{
|
||||||
|
AvaloniaOverlay.DismissLightDismissPopups();
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@ internal static class EngineSettings
|
||||||
private static bool _enableImGuiBackend = true;
|
private static bool _enableImGuiBackend = true;
|
||||||
private static bool _enableHangMinidump = true;
|
private static bool _enableHangMinidump = true;
|
||||||
private static bool _drawCustomVitalBars = true;
|
private static bool _drawCustomVitalBars = true;
|
||||||
|
private static bool _preventIdleLogoff = true;
|
||||||
private static bool _loaded;
|
private static bool _loaded;
|
||||||
|
|
||||||
public static IReadOnlyList<string> PluginPaths
|
public static IReadOnlyList<string> PluginPaths
|
||||||
|
|
@ -178,6 +179,20 @@ internal static class EngineSettings
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>When true (default), the engine keeps the retail client's idle clock fresh
|
||||||
|
/// while in the world, so ClientUISystem::UseTime's 20-minute idle auto-logoff
|
||||||
|
/// (InactiveTimeBeforeLogout) can't log off a character a bot is playing: the bot's
|
||||||
|
/// actions aren't keyboard/mouse input, so the client counted it as idle. Set false in
|
||||||
|
/// engine.json to get the retail behaviour back.</summary>
|
||||||
|
public static bool PreventIdleLogoff
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
EnsureLoaded();
|
||||||
|
return _preventIdleLogoff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public static void AddPluginPath(string path)
|
public static void AddPluginPath(string path)
|
||||||
{
|
{
|
||||||
EnsureLoaded();
|
EnsureLoaded();
|
||||||
|
|
@ -287,6 +302,12 @@ internal static class EngineSettings
|
||||||
{
|
{
|
||||||
_drawCustomVitalBars = cvbEl.GetBoolean();
|
_drawCustomVitalBars = cvbEl.GetBoolean();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
|
||||||
|
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
|
||||||
|
{
|
||||||
|
_preventIdleLogoff = pilEl.GetBoolean();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
|
@ -319,6 +340,7 @@ internal static class EngineSettings
|
||||||
w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend);
|
w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend);
|
||||||
w.WriteBoolean("EnableHangMinidump", _enableHangMinidump);
|
w.WriteBoolean("EnableHangMinidump", _enableHangMinidump);
|
||||||
w.WriteBoolean("DrawCustomVitalBars", _drawCustomVitalBars);
|
w.WriteBoolean("DrawCustomVitalBars", _drawCustomVitalBars);
|
||||||
|
w.WriteBoolean("PreventIdleLogoff", _preventIdleLogoff);
|
||||||
w.WriteEndObject();
|
w.WriteEndObject();
|
||||||
}
|
}
|
||||||
File.WriteAllBytes(SettingsPath, ms.ToArray());
|
File.WriteAllBytes(SettingsPath, ms.ToArray());
|
||||||
|
|
|
||||||
|
|
@ -596,6 +596,138 @@ internal struct RynthCoreAPI
|
||||||
/// owned by the target plugin (valid until its next call on that export); copy it immediately. Requires
|
/// owned by the target plugin (valid until its next call on that export); copy it immediately. Requires
|
||||||
/// API v66+. APPENDED-AT-END for ABI safety.</summary>
|
/// API v66+. APPENDED-AT-END for ABI safety.</summary>
|
||||||
public IntPtr GetPluginExportJsonFn;
|
public IntPtr GetPluginExportJsonFn;
|
||||||
|
|
||||||
|
// ── Vendor trading (v67) ─────────────────────────────────────────────
|
||||||
|
// Decal's WorldFilter.OpenVendor + Actions.VendorBuyAll/VendorSellAll, as
|
||||||
|
// stateless batch calls. Reads come from a snapshot the engine takes on AC's
|
||||||
|
// main thread when the server's vendor list (ApproachVendor 0x0062) is
|
||||||
|
// opened; buy/sell are queued and sent on AC's main thread through the
|
||||||
|
// client's own gmVendorUI::SendShopEvent (CM_Vendor::Event_Buy/Event_Sell).
|
||||||
|
// See Compatibility/VendorTrade.cs. APPENDED-AT-END for ABI safety.
|
||||||
|
|
||||||
|
/// <summary>Function pointer: int GetVendorInfo(VendorInfoNative* info)
|
||||||
|
/// Fills <paramref>info</paramref> for the vendor that is open right now. Returns 1
|
||||||
|
/// if a vendor is open, 0 if not (info is zeroed). Any thread. Requires API v67+.</summary>
|
||||||
|
public IntPtr GetVendorInfoFn;
|
||||||
|
|
||||||
|
/// <summary>Function pointer: int GetVendorItems(VendorItemNative* items, int maxCount)
|
||||||
|
/// Copies up to maxCount of the open vendor's items. Returns the TOTAL item count
|
||||||
|
/// (call with maxCount=0 to size a buffer), or -1 if no vendor is open. Any thread.
|
||||||
|
/// Requires API v67+.</summary>
|
||||||
|
public IntPtr GetVendorItemsFn;
|
||||||
|
|
||||||
|
/// <summary>Function pointer: uint VendorBuy(uint vendorId, VendorTradeEntryNative* entries, int count)
|
||||||
|
/// Buys (objectId, amount) pairs from the open vendor (vendorId 0 = whichever is open).
|
||||||
|
/// Returns a request id (>0) once the request passes the snapshot checks and is
|
||||||
|
/// queued, or 0 if it was refused (reason in GetVendorTradeStatus and the log).
|
||||||
|
/// Funds, pack slots and burden are checked again on AC's main thread before the
|
||||||
|
/// packet goes out; poll GetVendorTradeStatus for the outcome. One transaction is in
|
||||||
|
/// flight at a time. Requires API v67+.</summary>
|
||||||
|
public IntPtr VendorBuyFn;
|
||||||
|
|
||||||
|
/// <summary>Function pointer: uint VendorSell(uint vendorId, uint* itemIds, int count)
|
||||||
|
/// Sells the player's own items (whole stacks) to the open vendor. Same return and
|
||||||
|
/// status contract as VendorBuy. Requires API v67+.</summary>
|
||||||
|
public IntPtr VendorSellFn;
|
||||||
|
|
||||||
|
/// <summary>Function pointer: int GetVendorTradeStatus(VendorTradeStatusNative* status)
|
||||||
|
/// Fills the state of the most recent VendorBuy/VendorSell request. Returns 1 if a
|
||||||
|
/// request has been made this session, 0 if not. Any thread. Requires API v67+.</summary>
|
||||||
|
public IntPtr GetVendorTradeStatusFn;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Vendor trading ABI structs (v67) ───────────────────────────────────
|
||||||
|
// Blittable, Pack=4, 4-byte fields + fixed ANSI buffers only. Mirrored exactly
|
||||||
|
// by RynthCore.PluginSdk/VendorTypes.cs. Never reorder or resize; add new calls
|
||||||
|
// instead of growing these.
|
||||||
|
|
||||||
|
/// <summary>The open vendor (VendorProfile from ApproachVendor 0x0062). 192 bytes.</summary>
|
||||||
|
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||||
|
internal unsafe struct VendorInfoNative
|
||||||
|
{
|
||||||
|
public uint VendorId;
|
||||||
|
/// <summary>Bumps every time the server (re)sends the vendor list: on open and after
|
||||||
|
/// each accepted buy/sell. Compare before/after a trade to see the refresh.</summary>
|
||||||
|
public uint Generation;
|
||||||
|
/// <summary>ShopMode passed to gmVendorUI::OpenVendor (raw client value).</summary>
|
||||||
|
public int ShopMode;
|
||||||
|
/// <summary>ITEM_TYPE mask of what the vendor buys.</summary>
|
||||||
|
public uint ItemTypes;
|
||||||
|
public int MinValue;
|
||||||
|
public int MaxValue;
|
||||||
|
public int DealsMagic;
|
||||||
|
/// <summary>Vendor pays value * BuyRate when you sell.</summary>
|
||||||
|
public float BuyRate;
|
||||||
|
/// <summary>Vendor charges value * SellRate when you buy.</summary>
|
||||||
|
public float SellRate;
|
||||||
|
/// <summary>WCID of the vendor's currency; 0 = pyreals.</summary>
|
||||||
|
public uint AltCurrencyWcid;
|
||||||
|
/// <summary>Alt currency count as the server reported it in the vendor list (-1 if none).</summary>
|
||||||
|
public int AltCurrencyServerCount;
|
||||||
|
/// <summary>Alt currency the engine counted in the player's packs (-1 = not counted yet).</summary>
|
||||||
|
public int AltCurrencyHave;
|
||||||
|
/// <summary>Player's pyreals (CoinValue), refreshed on AC's main thread; -1 unknown.</summary>
|
||||||
|
public int PlayerCoins;
|
||||||
|
public int ItemCount;
|
||||||
|
/// <summary>bit0 = trading available (client functions resolved and layout verified),
|
||||||
|
/// bit1 = a transaction is in flight.</summary>
|
||||||
|
public uint Flags;
|
||||||
|
public uint Reserved0;
|
||||||
|
public fixed byte Name[64];
|
||||||
|
public fixed byte AltCurrencyName[64];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One item on the vendor's list (ItemProfile + its PublicWeenieDesc). 120 bytes.</summary>
|
||||||
|
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||||
|
internal unsafe struct VendorItemNative
|
||||||
|
{
|
||||||
|
public uint ObjectId;
|
||||||
|
public uint Wcid;
|
||||||
|
public uint ItemType;
|
||||||
|
public uint IconId;
|
||||||
|
/// <summary>How many the vendor has; -1 = unlimited.</summary>
|
||||||
|
public int Amount;
|
||||||
|
public int StackSize;
|
||||||
|
public int MaxStackSize;
|
||||||
|
/// <summary>PWD value of the listed stack.</summary>
|
||||||
|
public int Value;
|
||||||
|
/// <summary>Value of one unit (Value / StackSize for stacks).</summary>
|
||||||
|
public int UnitValue;
|
||||||
|
/// <summary>What one unit costs the player here (server rounding; notes at 1.15x).</summary>
|
||||||
|
public int UnitPrice;
|
||||||
|
public int Burden;
|
||||||
|
/// <summary>bit0 unlimited, bit1 stackable, bit2 needs a container slot (pack/foci).</summary>
|
||||||
|
public uint Flags;
|
||||||
|
public uint Reserved0;
|
||||||
|
public uint Reserved1;
|
||||||
|
public fixed byte Name[64];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One buy line: vendor object id + how many.</summary>
|
||||||
|
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||||
|
internal struct VendorTradeEntryNative
|
||||||
|
{
|
||||||
|
public uint ObjectId;
|
||||||
|
public int Amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>State of the most recent trade request. 160 bytes.</summary>
|
||||||
|
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||||
|
internal unsafe struct VendorTradeStatusNative
|
||||||
|
{
|
||||||
|
public uint RequestId;
|
||||||
|
/// <summary>1 queued, 2 sent (waiting for the server), 3 done, 4 refused (never sent).</summary>
|
||||||
|
public int State;
|
||||||
|
/// <summary>With State 3: 1 = server accepted (vendor list re-sent), 2 = server answered
|
||||||
|
/// without re-sending the list (refused: funds/busy/space), 3 = no answer (timed out).</summary>
|
||||||
|
public int Result;
|
||||||
|
public int IsBuy;
|
||||||
|
public uint VendorId;
|
||||||
|
public int EntryCount;
|
||||||
|
/// <summary>Buy: estimated cost (pyreals or alt currency). Sell: estimated payout.</summary>
|
||||||
|
public int Estimate;
|
||||||
|
public uint Reserved0;
|
||||||
|
public fixed byte Message[128];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -603,7 +735,7 @@ internal struct RynthCoreAPI
|
||||||
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
|
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
|
||||||
internal static class PluginContractVersion
|
internal static class PluginContractVersion
|
||||||
{
|
{
|
||||||
public const uint Current = 66;
|
public const uint Current = 67;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static class ClientActionHookFlags
|
internal static class ClientActionHookFlags
|
||||||
|
|
@ -1055,3 +1187,18 @@ internal unsafe delegate int GetObjectDataIdPropertyCallbackDelegate(uint object
|
||||||
|
|
||||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||||
internal delegate IntPtr GetPluginExportJsonCallbackDelegate(IntPtr pluginNameAnsi, IntPtr exportNameAnsi);
|
internal delegate IntPtr GetPluginExportJsonCallbackDelegate(IntPtr pluginNameAnsi, IntPtr exportNameAnsi);
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||||
|
internal unsafe delegate int GetVendorInfoCallbackDelegate(VendorInfoNative* info);
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||||
|
internal unsafe delegate int GetVendorItemsCallbackDelegate(VendorItemNative* items, int maxCount);
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||||
|
internal unsafe delegate uint VendorBuyCallbackDelegate(uint vendorId, VendorTradeEntryNative* entries, int count);
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||||
|
internal unsafe delegate uint VendorSellCallbackDelegate(uint vendorId, uint* itemIds, int count);
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||||
|
internal unsafe delegate int GetVendorTradeStatusCallbackDelegate(VendorTradeStatusNative* status);
|
||||||
|
|
|
||||||
|
|
@ -234,6 +234,11 @@ internal static class PluginManager
|
||||||
private static SendPluginCommandCallbackDelegate? _sendPluginCommandCallback;
|
private static SendPluginCommandCallbackDelegate? _sendPluginCommandCallback;
|
||||||
private static GetObjectDataIdPropertyCallbackDelegate? _getObjectDataIdPropertyCallback;
|
private static GetObjectDataIdPropertyCallbackDelegate? _getObjectDataIdPropertyCallback;
|
||||||
private static GetPluginExportJsonCallbackDelegate? _getPluginExportJsonCallback;
|
private static GetPluginExportJsonCallbackDelegate? _getPluginExportJsonCallback;
|
||||||
|
private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback;
|
||||||
|
private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback;
|
||||||
|
private static VendorBuyCallbackDelegate? _vendorBuyCallback;
|
||||||
|
private static VendorSellCallbackDelegate? _vendorSellCallback;
|
||||||
|
private static GetVendorTradeStatusCallbackDelegate? _getVendorTradeStatusCallback;
|
||||||
private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback;
|
private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback;
|
||||||
private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback;
|
private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback;
|
||||||
private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback;
|
private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback;
|
||||||
|
|
@ -2394,6 +2399,11 @@ internal static class PluginManager
|
||||||
_sendPluginCommandCallback ??= SendPluginCommandAction;
|
_sendPluginCommandCallback ??= SendPluginCommandAction;
|
||||||
_getObjectDataIdPropertyCallback ??= GetObjectDataIdPropertyAction;
|
_getObjectDataIdPropertyCallback ??= GetObjectDataIdPropertyAction;
|
||||||
_getPluginExportJsonCallback ??= GetPluginExportJsonAction;
|
_getPluginExportJsonCallback ??= GetPluginExportJsonAction;
|
||||||
|
_getVendorInfoCallback ??= GetVendorInfoAction;
|
||||||
|
_getVendorItemsCallback ??= GetVendorItemsAction;
|
||||||
|
_vendorBuyCallback ??= VendorBuyAction;
|
||||||
|
_vendorSellCallback ??= VendorSellAction;
|
||||||
|
_getVendorTradeStatusCallback ??= GetVendorTradeStatusAction;
|
||||||
|
|
||||||
_api.Version = PluginContractVersion.Current;
|
_api.Version = PluginContractVersion.Current;
|
||||||
_api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback);
|
_api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback);
|
||||||
|
|
@ -2505,6 +2515,11 @@ internal static class PluginManager
|
||||||
_api.SendPluginCommandFn = Marshal.GetFunctionPointerForDelegate(_sendPluginCommandCallback);
|
_api.SendPluginCommandFn = Marshal.GetFunctionPointerForDelegate(_sendPluginCommandCallback);
|
||||||
_api.GetObjectDataIdPropertyFn = Marshal.GetFunctionPointerForDelegate(_getObjectDataIdPropertyCallback);
|
_api.GetObjectDataIdPropertyFn = Marshal.GetFunctionPointerForDelegate(_getObjectDataIdPropertyCallback);
|
||||||
_api.GetPluginExportJsonFn = Marshal.GetFunctionPointerForDelegate(_getPluginExportJsonCallback);
|
_api.GetPluginExportJsonFn = Marshal.GetFunctionPointerForDelegate(_getPluginExportJsonCallback);
|
||||||
|
_api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback);
|
||||||
|
_api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback);
|
||||||
|
_api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback);
|
||||||
|
_api.VendorSellFn = Marshal.GetFunctionPointerForDelegate(_vendorSellCallback);
|
||||||
|
_api.GetVendorTradeStatusFn = Marshal.GetFunctionPointerForDelegate(_getVendorTradeStatusCallback);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ProbeClientHooks()
|
private static void ProbeClientHooks()
|
||||||
|
|
@ -3270,6 +3285,56 @@ internal static class PluginManager
|
||||||
|
|
||||||
private static int GetUseDoneSeqAction() => SmartBoxHooks.GetUseDoneSeq();
|
private static int GetUseDoneSeqAction() => SmartBoxHooks.GetUseDoneSeq();
|
||||||
|
|
||||||
|
// ── Vendor trading (v67) — see Compatibility/VendorTrade.cs ─────────────
|
||||||
|
// Reads are served from the main-thread snapshot; buy/sell only queue here
|
||||||
|
// (checked against the snapshot) and go out on AC's main thread.
|
||||||
|
private static unsafe int GetVendorInfoAction(VendorInfoNative* info)
|
||||||
|
{
|
||||||
|
try { return VendorTrade.FillInfo(info); }
|
||||||
|
catch { return 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static unsafe int GetVendorItemsAction(VendorItemNative* items, int maxCount)
|
||||||
|
{
|
||||||
|
try { return VendorTrade.FillItems(items, maxCount); }
|
||||||
|
catch { return -1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static unsafe uint VendorBuyAction(uint vendorId, VendorTradeEntryNative* entries, int count)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (entries == null || count <= 0 || count > 1000)
|
||||||
|
return VendorTrade.RefuseRequest(true, vendorId, count, entries == null ? "null entry list" : $"bad line count {count}");
|
||||||
|
var ids = new uint[count];
|
||||||
|
var amounts = new int[count];
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
ids[i] = entries[i].ObjectId;
|
||||||
|
amounts[i] = entries[i].Amount;
|
||||||
|
}
|
||||||
|
return VendorTrade.RequestBuy(vendorId, ids, amounts);
|
||||||
|
}
|
||||||
|
catch { return 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static unsafe uint VendorSellAction(uint vendorId, uint* itemIds, int count)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (itemIds == null || count <= 0 || count > 1000)
|
||||||
|
return VendorTrade.RefuseRequest(false, vendorId, count, itemIds == null ? "null item list" : $"bad line count {count}");
|
||||||
|
return VendorTrade.RequestSell(vendorId, new ReadOnlySpan<uint>(itemIds, count));
|
||||||
|
}
|
||||||
|
catch { return 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static unsafe int GetVendorTradeStatusAction(VendorTradeStatusNative* status)
|
||||||
|
{
|
||||||
|
try { return VendorTrade.FillStatus(status); }
|
||||||
|
catch { return 0; }
|
||||||
|
}
|
||||||
|
|
||||||
private static void ForceResetBusyCountAction() => BusyCountHooks.ForceResetBusyCount();
|
private static void ForceResetBusyCountAction() => BusyCountHooks.ForceResetBusyCount();
|
||||||
|
|
||||||
private static unsafe int GetObjectSpellIdsAction(uint guid, uint* spellIds, int maxCount)
|
private static unsafe int GetObjectSpellIdsAction(uint guid, uint* spellIds, int maxCount)
|
||||||
|
|
|
||||||
|
|
@ -68,6 +68,19 @@ internal static class AvaloniaOverlay
|
||||||
// Same slot pattern as radar, for chat's own Ctrl-gated click-through
|
// Same slot pattern as radar, for chat's own Ctrl-gated click-through
|
||||||
// option (live-testing finding 2026-09-02).
|
// option (live-testing finding 2026-09-02).
|
||||||
private static PhysicalRect? _chatPanelRect;
|
private static PhysicalRect? _chatPanelRect;
|
||||||
|
// Open Flyout / ContextMenu / ComboBox dropdowns, embedded in the overlay
|
||||||
|
// window's OverlayLayer (Win32PlatformOptions.OverlayPopups). They can hang
|
||||||
|
// past their panel's rect, so they're published separately and are always
|
||||||
|
// interactive. ToolTips are left out: they never take clicks.
|
||||||
|
private static PhysicalRect[] _popupRects = Array.Empty<PhysicalRect>();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// True while a light-dismiss popup (Flyout, ContextMenu, ComboBox
|
||||||
|
/// dropdown) is open. A click on the game world is never forwarded to
|
||||||
|
/// Avalonia, so its own light-dismiss can't see it; Win32Backend checks
|
||||||
|
/// this and calls <see cref="DismissLightDismissPopups"/> instead.
|
||||||
|
/// </summary>
|
||||||
|
internal static volatile bool HasOpenLightDismissPopup;
|
||||||
|
|
||||||
[DllImport("user32.dll")]
|
[DllImport("user32.dll")]
|
||||||
private static extern short GetAsyncKeyState(int vKey);
|
private static extern short GetAsyncKeyState(int vKey);
|
||||||
|
|
@ -226,6 +239,13 @@ internal static class AvaloniaOverlay
|
||||||
|
|
||||||
lock (HitTestLock)
|
lock (HitTestLock)
|
||||||
{
|
{
|
||||||
|
// Open popups sit above every panel and are always interactive.
|
||||||
|
foreach (PhysicalRect rect in _popupRects)
|
||||||
|
{
|
||||||
|
if (rect.Contains(gameClientX, gameClientY))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
foreach (PhysicalRect rect in _panelRects)
|
foreach (PhysicalRect rect in _panelRects)
|
||||||
{
|
{
|
||||||
if (rect.Contains(gameClientX, gameClientY))
|
if (rect.Contains(gameClientX, gameClientY))
|
||||||
|
|
@ -348,6 +368,37 @@ internal static class AvaloniaOverlay
|
||||||
Dispatcher.UIThread.Post(() => _window?.OnCustomFrameSubmitted(width, height), DispatcherPriority.Render);
|
Dispatcher.UIThread.Post(() => _window?.OnCustomFrameSubmitted(width, height), DispatcherPriority.Render);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Publish the physical bounds (game client pixels) of every open
|
||||||
|
/// interactive popup in the overlay window's OverlayLayer. Empty = none.
|
||||||
|
/// </summary>
|
||||||
|
internal static void PublishPopupRects(List<(double Left, double Top, double Width, double Height)> rects)
|
||||||
|
{
|
||||||
|
var snapshots = new PhysicalRect[rects.Count];
|
||||||
|
for (int i = 0; i < rects.Count; i++)
|
||||||
|
{
|
||||||
|
snapshots[i] = new PhysicalRect(
|
||||||
|
(int)Math.Round(rects[i].Left),
|
||||||
|
(int)Math.Round(rects[i].Top),
|
||||||
|
(int)Math.Round(rects[i].Left + rects[i].Width),
|
||||||
|
(int)Math.Round(rects[i].Top + rects[i].Height));
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (HitTestLock)
|
||||||
|
_popupRects = snapshots;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Close every open light-dismiss popup (Flyout, ContextMenu, dropdown).
|
||||||
|
/// Called from the game thread when the user clicks the game world while
|
||||||
|
/// one is open; the click itself still goes to AC.
|
||||||
|
/// </summary>
|
||||||
|
internal static void DismissLightDismissPopups()
|
||||||
|
{
|
||||||
|
HasOpenLightDismissPopup = false;
|
||||||
|
Dispatcher.UIThread.Post(() => _window?.CloseLightDismissPopups(), DispatcherPriority.Input);
|
||||||
|
}
|
||||||
|
|
||||||
internal static void PublishPanelRects(params (double Left, double Top, double Width, double Height)[] rects)
|
internal static void PublishPanelRects(params (double Left, double Top, double Width, double Height)[] rects)
|
||||||
{
|
{
|
||||||
var snapshots = new PhysicalRect[rects.Length];
|
var snapshots = new PhysicalRect[rects.Length];
|
||||||
|
|
@ -590,9 +641,11 @@ internal static class AvaloniaOverlay
|
||||||
_window = null;
|
_window = null;
|
||||||
_started = false;
|
_started = false;
|
||||||
AvaloniaHwnd = IntPtr.Zero;
|
AvaloniaHwnd = IntPtr.Zero;
|
||||||
|
HasOpenLightDismissPopup = false;
|
||||||
lock (HitTestLock)
|
lock (HitTestLock)
|
||||||
{
|
{
|
||||||
_panelRects = Array.Empty<PhysicalRect>();
|
_panelRects = Array.Empty<PhysicalRect>();
|
||||||
|
_popupRects = Array.Empty<PhysicalRect>();
|
||||||
_barButtonRects = new Dictionary<string, PhysicalRect>(StringComparer.OrdinalIgnoreCase);
|
_barButtonRects = new Dictionary<string, PhysicalRect>(StringComparer.OrdinalIgnoreCase);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -626,7 +679,19 @@ internal static class AvaloniaOverlay
|
||||||
[
|
[
|
||||||
Win32CompositionMode.RedirectionSurface
|
Win32CompositionMode.RedirectionSurface
|
||||||
],
|
],
|
||||||
ShouldRenderOnUIThread = true
|
ShouldRenderOnUIThread = true,
|
||||||
|
// Popup flash fix: without this every ToolTip, Flyout,
|
||||||
|
// ContextMenu and ComboBox dropdown opens as its own PopupRoot
|
||||||
|
// TopLevel (a native popup HWND), which the custom producer
|
||||||
|
// path rendered through the overlay's one render target - a
|
||||||
|
// popup-only frame reached the game and every docked panel
|
||||||
|
// vanished until the overlay window drew again. With
|
||||||
|
// OverlayPopups the popups live in the overlay window's
|
||||||
|
// OverlayLayer and are drawn in the same frame as the panels
|
||||||
|
// (no extra HWND, readback or focus change). The software
|
||||||
|
// fallback renders each TopLevel into its own framebuffer, so it
|
||||||
|
// keeps native popups as before.
|
||||||
|
OverlayPopups = UseCustomSkiaBridge,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (UseCustomSkiaBridge)
|
if (UseCustomSkiaBridge)
|
||||||
|
|
@ -1004,8 +1069,8 @@ internal class RynthOverlayWindow : Window
|
||||||
// working) but the canvas RTT clips it; the host renders the Border into
|
// working) but the canvas RTT clips it; the host renders the Border into
|
||||||
// its own RTT and pushes the pixels to the layered window via
|
// its own RTT and pushes the pixels to the layered window via
|
||||||
// UpdateLayeredWindow. This sidesteps OverlaySkiaPlatformGraphics
|
// UpdateLayeredWindow. This sidesteps OverlaySkiaPlatformGraphics
|
||||||
// entirely — the bridge is a singleton with one shared render target,
|
// entirely - only the overlay window's render target reaches the game, so
|
||||||
// so a real visible Avalonia Window would thrash that target.
|
// a real Avalonia Window would get a detached target and draw nowhere.
|
||||||
private readonly Dictionary<string, FloatingPanelHost> _floatingPanels = new(StringComparer.OrdinalIgnoreCase);
|
private readonly Dictionary<string, FloatingPanelHost> _floatingPanels = new(StringComparer.OrdinalIgnoreCase);
|
||||||
private readonly Dictionary<string, Control> _panelContents = new(StringComparer.OrdinalIgnoreCase);
|
private readonly Dictionary<string, Control> _panelContents = new(StringComparer.OrdinalIgnoreCase);
|
||||||
// Each floating panel parks its chrome Border past the right edge of
|
// Each floating panel parks its chrome Border past the right edge of
|
||||||
|
|
@ -1177,6 +1242,11 @@ internal class RynthOverlayWindow : Window
|
||||||
|
|
||||||
AvaloniaOverlay.RegisterWindow(this);
|
AvaloniaOverlay.RegisterWindow(this);
|
||||||
|
|
||||||
|
// Popups are embedded in this window's OverlayLayer (OverlayPopups).
|
||||||
|
// Track them for hit-testing, game-world light-dismiss and the
|
||||||
|
// popup-flash diagnostics (see the "Embedded popups" section).
|
||||||
|
InstallPopupTracking();
|
||||||
|
|
||||||
_captureTimer = new DispatcherTimer(TimeSpan.FromMilliseconds(16), DispatcherPriority.Render, (_, _) =>
|
_captureTimer = new DispatcherTimer(TimeSpan.FromMilliseconds(16), DispatcherPriority.Render, (_, _) =>
|
||||||
{
|
{
|
||||||
if (_captureDirty)
|
if (_captureDirty)
|
||||||
|
|
@ -3859,6 +3929,266 @@ internal class RynthOverlayWindow : Window
|
||||||
AvaloniaOverlay.PublishChatPanelRect(chatRect);
|
AvaloniaOverlay.PublishChatPanelRect(chatRect);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Embedded popups ────────────────────────────────────────────────────
|
||||||
|
// With Win32PlatformOptions.OverlayPopups every Popup (ToolTip, Flyout,
|
||||||
|
// ContextMenu, ComboBox dropdown) is an OverlayPopupHost inside this
|
||||||
|
// window's OverlayLayer, so it is drawn in the same frame as the docked
|
||||||
|
// panels. Three things still need help from us:
|
||||||
|
// 1. hit-testing - a Flyout/menu can hang past its panel's rect, and
|
||||||
|
// Win32Backend only forwards clicks that land on published rects;
|
||||||
|
// 2. light-dismiss - a click on the game world never reaches Avalonia;
|
||||||
|
// 3. diagnostics - log whether a popup ever rebuilt the overlay surface
|
||||||
|
// or got its own TopLevel (the old "panel flash").
|
||||||
|
|
||||||
|
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
|
||||||
|
|
||||||
|
private sealed class PopupTrack
|
||||||
|
{
|
||||||
|
public int Serial;
|
||||||
|
public string Kind = "";
|
||||||
|
public string Host = "";
|
||||||
|
public bool Suppressed;
|
||||||
|
public int SurfaceCreatesAtOpen;
|
||||||
|
public int DetachedTargetsAtOpen;
|
||||||
|
}
|
||||||
|
|
||||||
|
private const int PopupLogNormalLineBudget = 40;
|
||||||
|
private const int PopupLogAnomalyLineBudget = 200;
|
||||||
|
private static RynthOverlayWindow? _popupOwner;
|
||||||
|
private static bool _popupClassHandlerInstalled;
|
||||||
|
private readonly Dictionary<Avalonia.Controls.Primitives.Popup, PopupTrack> _openPopups = new();
|
||||||
|
private int _popupSerial;
|
||||||
|
private int _popupNormalLines;
|
||||||
|
private int _popupAnomalyLines;
|
||||||
|
private bool _popupRectsPublished;
|
||||||
|
|
||||||
|
private void InstallPopupTracking()
|
||||||
|
{
|
||||||
|
_popupOwner = this;
|
||||||
|
if (!_popupClassHandlerInstalled)
|
||||||
|
{
|
||||||
|
_popupClassHandlerInstalled = true;
|
||||||
|
Avalonia.Controls.Primitives.Popup.IsOpenProperty.Changed.AddClassHandler<Avalonia.Controls.Primitives.Popup, bool>(
|
||||||
|
(popup, e) => _popupOwner?.OnAnyPopupIsOpenChanged(popup, e.NewValue.GetValueOrDefault()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fires after every layout pass: keeps popup hit rects in step with
|
||||||
|
// Flyout content changes and repositioning. Returns at once when no
|
||||||
|
// popup is open.
|
||||||
|
LayoutUpdated += (_, _) => RefreshPopupHitRects();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnAnyPopupIsOpenChanged(Avalonia.Controls.Primitives.Popup popup, bool isOpen)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (isOpen)
|
||||||
|
{
|
||||||
|
if (_openPopups.ContainsKey(popup))
|
||||||
|
return;
|
||||||
|
|
||||||
|
var track = new PopupTrack
|
||||||
|
{
|
||||||
|
Serial = ++_popupSerial,
|
||||||
|
Kind = DescribePopup(popup),
|
||||||
|
Host = popup.Host?.GetType().Name ?? "none",
|
||||||
|
SurfaceCreatesAtOpen = OverlaySkiaRenderTarget.SurfaceCreateCount,
|
||||||
|
DetachedTargetsAtOpen = OverlaySkiaGpuContext.DetachedTargetCount,
|
||||||
|
};
|
||||||
|
_openPopups[popup] = track;
|
||||||
|
UpdateLightDismissFlag();
|
||||||
|
|
||||||
|
// A ToolTip for a control inside a popped-out panel: that
|
||||||
|
// control lives in the off-bounds canvas strip, so the embedded
|
||||||
|
// tooltip would be clamped onto the edge of the in-game overlay,
|
||||||
|
// nowhere near the floating window. Don't show it.
|
||||||
|
if (popup.Child is ToolTip && popup.PlacementTarget is Control tipTarget && !IsInsideOverlayClientArea(tipTarget))
|
||||||
|
{
|
||||||
|
track.Suppressed = true;
|
||||||
|
Dispatcher.UIThread.Post(() =>
|
||||||
|
{
|
||||||
|
try { ToolTip.SetIsOpen(tipTarget, false); } catch { }
|
||||||
|
}, DispatcherPriority.Send);
|
||||||
|
}
|
||||||
|
|
||||||
|
Dispatcher.UIThread.Post(() =>
|
||||||
|
{
|
||||||
|
RefreshPopupHitRects();
|
||||||
|
LogPopupOpened(track);
|
||||||
|
}, DispatcherPriority.Background);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (!_openPopups.Remove(popup, out PopupTrack? track))
|
||||||
|
return;
|
||||||
|
|
||||||
|
UpdateLightDismissFlag();
|
||||||
|
RefreshPopupHitRects();
|
||||||
|
|
||||||
|
// The old flash rebuilt the overlay surface on the window's next
|
||||||
|
// frame after the popup closed, so check a moment later.
|
||||||
|
DispatcherTimer.RunOnce(() => LogPopupClosed(track), TimeSpan.FromMilliseconds(1000), DispatcherPriority.Background);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
RynthLog.UI($"OverlayPopup: tracking threw {ex.GetType().Name}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string DescribePopup(Avalonia.Controls.Primitives.Popup popup)
|
||||||
|
{
|
||||||
|
string child = popup.Child?.GetType().Name ?? "empty";
|
||||||
|
string? owner = popup.TemplatedParent?.GetType().Name;
|
||||||
|
return owner != null ? $"{owner}/{child}" : child;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsInsideOverlayClientArea(Control control)
|
||||||
|
{
|
||||||
|
Point? origin = control.TranslatePoint(default, this);
|
||||||
|
if (origin == null)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
double width = Bounds.Width > 0 ? Bounds.Width : Width;
|
||||||
|
double height = Bounds.Height > 0 ? Bounds.Height : Height;
|
||||||
|
return origin.Value.X < width && origin.Value.Y < height &&
|
||||||
|
origin.Value.X + control.Bounds.Width > 0 && origin.Value.Y + control.Bounds.Height > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateLightDismissFlag()
|
||||||
|
{
|
||||||
|
bool any = false;
|
||||||
|
foreach (Avalonia.Controls.Primitives.Popup popup in _openPopups.Keys)
|
||||||
|
{
|
||||||
|
if (popup.IsLightDismissEnabled)
|
||||||
|
{
|
||||||
|
any = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
AvaloniaOverlay.HasOpenLightDismissPopup = any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Close open light-dismiss popups because the user clicked the game world.
|
||||||
|
/// Popup.Close is the same call Avalonia's own light-dismiss makes, so
|
||||||
|
/// Flyout/ContextMenu/ComboBox state stays in sync.
|
||||||
|
/// </summary>
|
||||||
|
internal void CloseLightDismissPopups()
|
||||||
|
{
|
||||||
|
foreach (Avalonia.Controls.Primitives.Popup popup in _openPopups.Keys.ToArray())
|
||||||
|
{
|
||||||
|
if (!popup.IsOpen || !popup.IsLightDismissEnabled)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
try { popup.Close(); }
|
||||||
|
catch (Exception ex) { RynthLog.UI($"OverlayPopup: dismiss threw {ex.GetType().Name}: {ex.Message}"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
UpdateLightDismissFlag();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RefreshPopupHitRects()
|
||||||
|
{
|
||||||
|
if (_openPopups.Count == 0)
|
||||||
|
{
|
||||||
|
if (_popupRectsPublished)
|
||||||
|
{
|
||||||
|
AvaloniaOverlay.PublishPopupRects(new List<(double, double, double, double)>());
|
||||||
|
_popupRectsPublished = false;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
float scale = (float)GetEffectiveRenderScale();
|
||||||
|
var rects = new List<(double Left, double Top, double Width, double Height)>(_openPopups.Count);
|
||||||
|
List<Avalonia.Controls.Primitives.Popup>? stale = null;
|
||||||
|
foreach ((Avalonia.Controls.Primitives.Popup popup, PopupTrack track) in _openPopups)
|
||||||
|
{
|
||||||
|
if (!popup.IsOpen)
|
||||||
|
{
|
||||||
|
(stale ??= new()).Add(popup);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToolTips never take clicks; a click over one must reach AC.
|
||||||
|
if (track.Suppressed || popup.Child is ToolTip)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
// OverlayPopupHost is a control in this window's OverlayLayer. A
|
||||||
|
// native PopupRoot (not expected) would be its own root: skipped.
|
||||||
|
if (popup.Host is not Visual host || !host.IsVisible)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
Point? origin = host.TranslatePoint(default, _desktopCanvas);
|
||||||
|
if (origin == null || host.Bounds.Width <= 0 || host.Bounds.Height <= 0)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
rects.Add((origin.Value.X * scale, origin.Value.Y * scale, host.Bounds.Width * scale, host.Bounds.Height * scale));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stale != null)
|
||||||
|
{
|
||||||
|
foreach (Avalonia.Controls.Primitives.Popup popup in stale)
|
||||||
|
_openPopups.Remove(popup);
|
||||||
|
UpdateLightDismissFlag();
|
||||||
|
}
|
||||||
|
|
||||||
|
AvaloniaOverlay.PublishPopupRects(rects);
|
||||||
|
_popupRectsPublished = rects.Count > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TakePopupLogLine(bool anomaly)
|
||||||
|
{
|
||||||
|
if (anomaly)
|
||||||
|
return _popupAnomalyLines++ < PopupLogAnomalyLineBudget;
|
||||||
|
|
||||||
|
if (_popupNormalLines < PopupLogNormalLineBudget)
|
||||||
|
{
|
||||||
|
_popupNormalLines++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_popupNormalLines == PopupLogNormalLineBudget)
|
||||||
|
{
|
||||||
|
_popupNormalLines++;
|
||||||
|
RynthLog.UI("OverlayPopup: normal popup open/close lines muted for this session; anomalies are still logged.");
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LogPopupOpened(PopupTrack track)
|
||||||
|
{
|
||||||
|
// Expected: host=OverlayPopupHost (drawn in the overlay frame). A
|
||||||
|
// PopupRoot here means a native popup TopLevel - the flash path.
|
||||||
|
bool anomaly = !track.Suppressed && track.Host != "OverlayPopupHost";
|
||||||
|
if (!TakePopupLogLine(anomaly))
|
||||||
|
return;
|
||||||
|
|
||||||
|
IntPtr game = Win32Backend.GameHwnd;
|
||||||
|
string fg = game == IntPtr.Zero ? "?" : GetForegroundWindow() == game ? "game" : "other";
|
||||||
|
RynthLog.UI(
|
||||||
|
$"OverlayPopup: open #{track.Serial} {track.Kind} host={track.Host}" +
|
||||||
|
(track.Suppressed ? " (tooltip of a popped-out panel - not shown)" : "") +
|
||||||
|
$" surfaceCreates={track.SurfaceCreatesAtOpen} detachedTargets={track.DetachedTargetsAtOpen} foreground={fg}.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LogPopupClosed(PopupTrack track)
|
||||||
|
{
|
||||||
|
int rebuilds = OverlaySkiaRenderTarget.SurfaceCreateCount - track.SurfaceCreatesAtOpen;
|
||||||
|
int detached = OverlaySkiaGpuContext.DetachedTargetCount - track.DetachedTargetsAtOpen;
|
||||||
|
bool anomaly = rebuilds != 0 || detached != 0;
|
||||||
|
if (!TakePopupLogLine(anomaly))
|
||||||
|
return;
|
||||||
|
|
||||||
|
IntPtr game = Win32Backend.GameHwnd;
|
||||||
|
string fg = game == IntPtr.Zero ? "?" : GetForegroundWindow() == game ? "game" : "other";
|
||||||
|
RynthLog.UI(
|
||||||
|
$"OverlayPopup: close #{track.Serial} {track.Kind} surfaceRebuilds=+{rebuilds} detachedTargets=+{detached} foreground={fg}" +
|
||||||
|
(anomaly ? " - overlay surface was rebuilt or a popup TopLevel appeared (panel flash / resize)." : " - no flash."));
|
||||||
|
}
|
||||||
|
|
||||||
private void QueueCapture()
|
private void QueueCapture()
|
||||||
{
|
{
|
||||||
if (AvaloniaOverlay.ShouldUseCustomSkiaProducer || _captureQueued)
|
if (AvaloniaOverlay.ShouldUseCustomSkiaProducer || _captureQueued)
|
||||||
|
|
@ -3882,6 +4212,16 @@ internal class RynthOverlayWindow : Window
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal void TickFloatingPanels()
|
internal void TickFloatingPanels()
|
||||||
{
|
{
|
||||||
|
// The UI hides between characters: popped-out panels (and a floating bar) are
|
||||||
|
// real windows, so they're hidden outright while not in the world rather than
|
||||||
|
// left sitting over character select. SetShown only acts on a change.
|
||||||
|
bool inWorld = Compatibility.LoginLifecycleHooks.HasObservedLoginComplete;
|
||||||
|
foreach (FloatingPanelHost host in _floatingPanels.Values)
|
||||||
|
host.SetShown(inWorld);
|
||||||
|
_floatingBar?.SetShown(inWorld);
|
||||||
|
if (!inWorld)
|
||||||
|
return;
|
||||||
|
|
||||||
if (_floatingPanels.Count > 0)
|
if (_floatingPanels.Count > 0)
|
||||||
{
|
{
|
||||||
foreach (FloatingPanelHost host in _floatingPanels.Values)
|
foreach (FloatingPanelHost host in _floatingPanels.Values)
|
||||||
|
|
@ -3916,9 +4256,11 @@ internal class RynthOverlayWindow : Window
|
||||||
/// forwarded to the off-screen Avalonia HWND with translated coords so the
|
/// forwarded to the off-screen Avalonia HWND with translated coords so the
|
||||||
/// panel's buttons/scrollbars/etc. behave the same as when docked.
|
/// panel's buttons/scrollbars/etc. behave the same as when docked.
|
||||||
///
|
///
|
||||||
/// This deliberately does NOT use Avalonia's Window — a second Avalonia
|
/// This deliberately does NOT use Avalonia's Window. A second Avalonia
|
||||||
/// top-level routes through OverlaySkiaPlatformGraphics' singleton render
|
/// top-level used to share OverlaySkiaPlatformGraphics' render target and
|
||||||
/// target and thrashes the in-AC capture (the original "flashing" bug).
|
/// blank the in-AC capture (the original "flashing" bug); it now gets a
|
||||||
|
/// detached target (see OverlaySkiaGpuContext.TryCreateRenderTarget), so it
|
||||||
|
/// would draw nowhere at all.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed unsafe class FloatingPanelHost : IDisposable
|
internal sealed unsafe class FloatingPanelHost : IDisposable
|
||||||
{
|
{
|
||||||
|
|
@ -4156,6 +4498,23 @@ internal sealed unsafe class FloatingPanelHost : IDisposable
|
||||||
/// RynthOverlayWindow's _captureTimer so render and panel state stay in
|
/// RynthOverlayWindow's _captureTimer so render and panel state stay in
|
||||||
/// sync. Skips the heavy work if the panel hasn't been arranged yet.
|
/// sync. Skips the heavy work if the panel hasn't been arranged yet.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
// Created shown (the constructor shows the window); SetShown tracks changes from there.
|
||||||
|
private volatile bool _windowShown = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Hide or show the popped-out window (the UI hides between characters). Only acts
|
||||||
|
/// on a change; the window belongs to AC's thread, so the call is marshalled there.
|
||||||
|
/// </summary>
|
||||||
|
internal void SetShown(bool shown)
|
||||||
|
{
|
||||||
|
if (_disposed || _layered.Hwnd == IntPtr.Zero || _windowShown == shown) return;
|
||||||
|
_windowShown = shown;
|
||||||
|
ImGuiBackend.Win32Backend.RunOnGameThread(() =>
|
||||||
|
{
|
||||||
|
if (shown) _layered.Show(); else _layered.Hide();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
public void Tick()
|
public void Tick()
|
||||||
{
|
{
|
||||||
if (_disposed || _layered.Hwnd == IntPtr.Zero) return;
|
if (_disposed || _layered.Hwnd == IntPtr.Zero) return;
|
||||||
|
|
|
||||||
|
|
@ -42,7 +42,8 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
||||||
// class because its WndProc points into the unloaded DLL. So bake a
|
// class because its WndProc points into the unloaded DLL. So bake a
|
||||||
// per-DLL-load Guid into the name — each engine instance gets a fresh
|
// per-DLL-load Guid into the name — each engine instance gets a fresh
|
||||||
// class atom backed by its own WndProc pointer.
|
// class atom backed by its own WndProc pointer.
|
||||||
private static readonly string ClassName = "RynthCoreLayeredPanel_" + Guid.NewGuid().ToString("N");
|
private const string ClassNamePrefix = "RynthCoreLayeredPanel_";
|
||||||
|
private static readonly string ClassName = ClassNamePrefix + Guid.NewGuid().ToString("N");
|
||||||
|
|
||||||
private const int WS_POPUP = unchecked((int)0x80000000);
|
private const int WS_POPUP = unchecked((int)0x80000000);
|
||||||
private const int WS_EX_LAYERED = 0x00080000;
|
private const int WS_EX_LAYERED = 0x00080000;
|
||||||
|
|
@ -273,6 +274,68 @@ internal sealed unsafe class LayeredWindow : IDisposable
|
||||||
return DefWindowProcW(hwnd, msg, wParam, lParam);
|
return DefWindowProcW(hwnd, msg, wParam, lParam);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
private static extern int EnumThreadWindows(uint dwThreadId, delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int> lpfn, IntPtr lParam);
|
||||||
|
|
||||||
|
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||||
|
private static extern int GetClassNameW(IntPtr hWnd, char* lpClassName, int nMaxCount);
|
||||||
|
|
||||||
|
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
|
||||||
|
private static int CollectThreadWindow(IntPtr hwnd, IntPtr lParam)
|
||||||
|
{
|
||||||
|
if (GCHandle.FromIntPtr(lParam).Target is List<IntPtr> found)
|
||||||
|
found.Add(hwnd);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Destroys panel windows owned by the calling thread.
|
||||||
|
/// Must run on AC's game thread — the panels are created there (see
|
||||||
|
/// FloatingPanelHost's RunOnGameThread) and DestroyWindow only works on
|
||||||
|
/// the owning thread.
|
||||||
|
///
|
||||||
|
/// Dispose only posts the destroy, and Win32Backend.Shutdown unhooks the
|
||||||
|
/// game WndProc ~1 ms after the overlay stops — usually before the game
|
||||||
|
/// thread gets to the post. AC's own WndProc then drops it, and because
|
||||||
|
/// the engine module is never unloaded the panel lives on: frozen on its
|
||||||
|
/// last frame, deaf to input, and hidden under the next generation's copy
|
||||||
|
/// of it until that one is moved ("two RynthAi windows").
|
||||||
|
///
|
||||||
|
/// <paramref name="includeThisGeneration"/>=false spares this engine
|
||||||
|
/// load's own windows (class names carry a per-load Guid) and removes only
|
||||||
|
/// ones an earlier load left behind.
|
||||||
|
/// </summary>
|
||||||
|
internal static void DestroyThreadPanelWindows(bool includeThisGeneration)
|
||||||
|
{
|
||||||
|
var found = new List<IntPtr>();
|
||||||
|
GCHandle handle = GCHandle.Alloc(found);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
EnumThreadWindows(GetCurrentThreadId(), &CollectThreadWindow, GCHandle.ToIntPtr(handle));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
handle.Free();
|
||||||
|
}
|
||||||
|
|
||||||
|
char* buffer = stackalloc char[128];
|
||||||
|
foreach (IntPtr hwnd in found)
|
||||||
|
{
|
||||||
|
int length = GetClassNameW(hwnd, buffer, 128);
|
||||||
|
if (length <= 0)
|
||||||
|
continue;
|
||||||
|
string className = new(buffer, 0, length);
|
||||||
|
if (!className.StartsWith(ClassNamePrefix, StringComparison.Ordinal))
|
||||||
|
continue;
|
||||||
|
bool thisGeneration = className == ClassName;
|
||||||
|
if (thisGeneration && !includeThisGeneration)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
bool ok = DestroyWindow(hwnd);
|
||||||
|
RynthCore.Engine.RynthLog.Info($"LayeredWindow: DestroyWindow(0x{hwnd.ToInt64():X}) = {ok} — {(thisGeneration ? "still open at shutdown" : "left over from an earlier engine load")}.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Instance state ────────────────────────────────────────────────────
|
// ─── Instance state ────────────────────────────────────────────────────
|
||||||
public IntPtr Hwnd { get; private set; }
|
public IntPtr Hwnd { get; private set; }
|
||||||
public int Width { get; private set; }
|
public int Width { get; private set; }
|
||||||
|
|
|
||||||
|
|
@ -24,9 +24,18 @@ internal sealed class OverlaySkiaPlatformGraphics : IPlatformGraphicsWithFeature
|
||||||
internal sealed class OverlaySkiaGpuContext : ISkiaGpu
|
internal sealed class OverlaySkiaGpuContext : ISkiaGpu
|
||||||
{
|
{
|
||||||
private static readonly IDisposable NoopLease = new NoopDisposable();
|
private static readonly IDisposable NoopLease = new NoopDisposable();
|
||||||
|
private static int _detachedTargetCount;
|
||||||
private readonly object _sync = new();
|
private readonly object _sync = new();
|
||||||
private OverlaySkiaRenderTarget? _renderTarget;
|
private OverlaySkiaRenderTarget? _renderTarget;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// How many TopLevels other than the overlay window asked for a render
|
||||||
|
/// target this session. Expected to stay 0: popups are embedded in the
|
||||||
|
/// overlay window (Win32PlatformOptions.OverlayPopups). Logged with every
|
||||||
|
/// popup open/close so a regression is visible in the per-pid log.
|
||||||
|
/// </summary>
|
||||||
|
internal static int DetachedTargetCount => Volatile.Read(ref _detachedTargetCount);
|
||||||
|
|
||||||
public bool IsLost => false;
|
public bool IsLost => false;
|
||||||
|
|
||||||
public IDisposable EnsureCurrent() => NoopLease;
|
public IDisposable EnsureCurrent() => NoopLease;
|
||||||
|
|
@ -37,11 +46,53 @@ internal sealed class OverlaySkiaGpuContext : ISkiaGpu
|
||||||
{
|
{
|
||||||
lock (_sync)
|
lock (_sync)
|
||||||
{
|
{
|
||||||
_renderTarget ??= new OverlaySkiaRenderTarget();
|
// Only the overlay window may own the render target whose frames go
|
||||||
|
// to the game. Every Avalonia TopLevel calls this - before the
|
||||||
|
// OverlayPopups fix each ToolTip/Flyout/ContextMenu/ComboBox opened
|
||||||
|
// a PopupRoot TopLevel that got this same target: its render cleared
|
||||||
|
// the shared surface and submitted a popup-only frame (every docked
|
||||||
|
// panel vanished), and closing it disposed the surface under the
|
||||||
|
// overlay window (rebuilt on its next frame). Any other TopLevel now
|
||||||
|
// gets a detached target that renders nowhere.
|
||||||
|
IntPtr hwnd = TryGetHwnd(surfaces);
|
||||||
|
IntPtr overlayHwnd = AvaloniaOverlay.AvaloniaHwnd;
|
||||||
|
bool isOverlayWindow = overlayHwnd != IntPtr.Zero && hwnd != IntPtr.Zero
|
||||||
|
? hwnd == overlayHwnd
|
||||||
|
: _renderTarget == null || _renderTarget.IsDisposed;
|
||||||
|
|
||||||
|
if (!isOverlayWindow)
|
||||||
|
{
|
||||||
|
int n = Interlocked.Increment(ref _detachedTargetCount);
|
||||||
|
RynthLog.UI($"OverlaySkiaGpuContext: TopLevel hwnd=0x{hwnd.ToInt64():X} is not the overlay window (0x{overlayHwnd.ToInt64():X}); gave it detached render target #{n} so it can't blank the docked panels.");
|
||||||
|
return new DetachedOverlayRenderTarget();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_renderTarget == null || _renderTarget.IsDisposed)
|
||||||
|
_renderTarget = new OverlaySkiaRenderTarget();
|
||||||
return _renderTarget;
|
return _renderTarget;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static IntPtr TryGetHwnd(IEnumerable<object> surfaces)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (object surface in surfaces)
|
||||||
|
{
|
||||||
|
if (surface is IPlatformHandle handle &&
|
||||||
|
string.Equals(handle.HandleDescriptor, "HWND", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return handle.Handle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
return IntPtr.Zero;
|
||||||
|
}
|
||||||
|
|
||||||
public ISkiaSurface? TryCreateSurface(PixelSize size, ISkiaGpuRenderSession? session)
|
public ISkiaSurface? TryCreateSurface(PixelSize size, ISkiaGpuRenderSession? session)
|
||||||
{
|
{
|
||||||
if (size.Width <= 0 || size.Height <= 0)
|
if (size.Width <= 0 || size.Height <= 0)
|
||||||
|
|
@ -85,6 +136,20 @@ internal sealed class OverlaySkiaRenderTarget : ISkiaGpuRenderTarget
|
||||||
private int _width;
|
private int _width;
|
||||||
private int _height;
|
private int _height;
|
||||||
private int _loggedSharedTextureDisabled;
|
private int _loggedSharedTextureDisabled;
|
||||||
|
private bool _disposed;
|
||||||
|
private static int _surfaceCreateCount;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Full-size raster surfaces created this session (startup + resizes, and
|
||||||
|
/// the old popup-flash rebuilds). Popup open/close logging compares it
|
||||||
|
/// before and after each popup: anything other than +0 is the flash.
|
||||||
|
/// </summary>
|
||||||
|
internal static int SurfaceCreateCount => Volatile.Read(ref _surfaceCreateCount);
|
||||||
|
|
||||||
|
internal bool IsDisposed
|
||||||
|
{
|
||||||
|
get { lock (_sync) return _disposed; }
|
||||||
|
}
|
||||||
|
|
||||||
public bool IsCorrupted => false;
|
public bool IsCorrupted => false;
|
||||||
|
|
||||||
|
|
@ -105,10 +170,12 @@ internal sealed class OverlaySkiaRenderTarget : ISkiaGpuRenderTarget
|
||||||
{
|
{
|
||||||
lock (_sync)
|
lock (_sync)
|
||||||
{
|
{
|
||||||
|
_disposed = true;
|
||||||
_surface?.Dispose();
|
_surface?.Dispose();
|
||||||
_surface = null;
|
_surface = null;
|
||||||
_softwareBuffer = null;
|
_softwareBuffer = null;
|
||||||
_sharedTexturePublisher?.Dispose();
|
_sharedTexturePublisher?.Dispose();
|
||||||
|
_sharedTexturePublisher = null;
|
||||||
_width = 0;
|
_width = 0;
|
||||||
_height = 0;
|
_height = 0;
|
||||||
}
|
}
|
||||||
|
|
@ -174,13 +241,22 @@ internal sealed class OverlaySkiaRenderTarget : ISkiaGpuRenderTarget
|
||||||
if (_surface != null && width == _width && height == _height)
|
if (_surface != null && width == _width && height == _height)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
// Why the surface is being (re)built. "recreate-after-dispose" at an
|
||||||
|
// unchanged size is the old popup-flash signature: a TopLevel disposed
|
||||||
|
// this target and the overlay window had to rebuild it.
|
||||||
|
string reason = _surface != null
|
||||||
|
? $"resize {_width}x{_height}->{width}x{height}"
|
||||||
|
: _disposed ? "recreate-after-dispose" : "initial";
|
||||||
|
_disposed = false;
|
||||||
|
|
||||||
_surface?.Dispose();
|
_surface?.Dispose();
|
||||||
_width = width;
|
_width = width;
|
||||||
_height = height;
|
_height = height;
|
||||||
|
|
||||||
var info = new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul);
|
var info = new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul);
|
||||||
_surface = SKSurface.Create(info);
|
_surface = SKSurface.Create(info);
|
||||||
RynthLog.UI($"OverlaySkiaRenderTarget: Created raster render surface {_width}x{_height}.");
|
int total = Interlocked.Increment(ref _surfaceCreateCount);
|
||||||
|
RynthLog.UI($"OverlaySkiaRenderTarget: Created raster render surface {_width}x{_height} (reason={reason}, total={total}).");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -259,6 +335,53 @@ internal sealed class OverlaySkiaRenderSession : ISkiaGpuRenderSession
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Render target for any Avalonia TopLevel that is not the overlay window.
|
||||||
|
/// Avalonia needs somewhere to draw, but only the overlay window's frames may
|
||||||
|
/// reach the game: this target draws into a private 1x1 raster surface and
|
||||||
|
/// never submits, reads back or clears anything shared.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class DetachedOverlayRenderTarget : ISkiaGpuRenderTarget
|
||||||
|
{
|
||||||
|
private readonly object _sync = new();
|
||||||
|
private SKSurface? _surface;
|
||||||
|
|
||||||
|
public bool IsCorrupted => false;
|
||||||
|
|
||||||
|
public ISkiaGpuRenderSession BeginRenderingSession()
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
_surface ??= SKSurface.Create(new SKImageInfo(1, 1, SKColorType.Bgra8888, SKAlphaType.Premul))
|
||||||
|
?? throw new InvalidOperationException("Detached overlay render surface could not be created.");
|
||||||
|
return new Session(_surface);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
_surface?.Dispose();
|
||||||
|
_surface = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Session : ISkiaGpuRenderSession
|
||||||
|
{
|
||||||
|
public Session(SKSurface surface) => SkSurface = surface;
|
||||||
|
|
||||||
|
public GRContext GrContext => null!;
|
||||||
|
public double ScaleFactor => 1.0d;
|
||||||
|
public SKSurface SkSurface { get; }
|
||||||
|
public GRSurfaceOrigin SurfaceOrigin => GRSurfaceOrigin.TopLeft;
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal sealed class OverlaySkiaSurface : ISkiaSurface
|
internal sealed class OverlaySkiaSurface : ISkiaSurface
|
||||||
{
|
{
|
||||||
public OverlaySkiaSurface(int width, int height)
|
public OverlaySkiaSurface(int width, int height)
|
||||||
|
|
|
||||||
|
|
@ -111,6 +111,20 @@ internal static class MetaPanel
|
||||||
|
|
||||||
// Composite condition indices: All=2, Any=3, Not=20
|
// Composite condition indices: All=2, Any=3, Not=20
|
||||||
private static bool IsCompositeCondition(int idx) => idx is 2 or 3 or 20;
|
private static bool IsCompositeCondition(int idx) => idx is 2 or 3 or 20;
|
||||||
|
|
||||||
|
/// <summary>One condition as text, nested ones included: "Not No Monsters Within Dist: 5",
|
||||||
|
/// "Any(Chat Message: …, Navroute Empty)".</summary>
|
||||||
|
private static string CondText(MetaRuleDto c, int depth = 0)
|
||||||
|
{
|
||||||
|
string name = c.Condition >= 0 && c.Condition < ConditionNames.Length
|
||||||
|
? ConditionNames[c.Condition] : $"Cond({c.Condition})";
|
||||||
|
if (IsCompositeCondition(c.Condition) && c.Children.Count > 0 && depth < MaxSubConditionDepth)
|
||||||
|
{
|
||||||
|
if (c.Condition == 20) return $"Not {CondText(c.Children[0], depth + 1)}";
|
||||||
|
return $"{name}({string.Join(", ", c.Children.Select(x => CondText(x, depth + 1)))})";
|
||||||
|
}
|
||||||
|
return string.IsNullOrEmpty(c.ConditionData) ? name : $"{name}: {c.ConditionData}";
|
||||||
|
}
|
||||||
// All action index = 4
|
// All action index = 4
|
||||||
private static bool IsAllAction(int idx) => idx == 4;
|
private static bool IsAllAction(int idx) => idx == 4;
|
||||||
|
|
||||||
|
|
@ -796,10 +810,7 @@ internal static class MetaPanel
|
||||||
string condText;
|
string condText;
|
||||||
if (IsCompositeCondition(rule.Condition) && rule.Children.Count > 0)
|
if (IsCompositeCondition(rule.Condition) && rule.Children.Count > 0)
|
||||||
{
|
{
|
||||||
var first = rule.Children[0];
|
string ft = CondText(rule.Children[0]);
|
||||||
string fn = first.Condition >= 0 && first.Condition < ConditionNames.Length
|
|
||||||
? ConditionNames[first.Condition] : $"Cond({first.Condition})";
|
|
||||||
string ft = string.IsNullOrEmpty(first.ConditionData) ? fn : $"{fn}: {first.ConditionData}";
|
|
||||||
condText = rule.Children.Count > 1
|
condText = rule.Children.Count > 1
|
||||||
? $"{condName}: {ft} (+{rule.Children.Count - 1})"
|
? $"{condName}: {ft} (+{rule.Children.Count - 1})"
|
||||||
: $"{condName}: {ft}";
|
: $"{condName}: {ft}";
|
||||||
|
|
@ -869,9 +880,7 @@ internal static class MetaPanel
|
||||||
});
|
});
|
||||||
foreach (var child in rule.Children)
|
foreach (var child in rule.Children)
|
||||||
{
|
{
|
||||||
string cn = child.Condition >= 0 && child.Condition < ConditionNames.Length
|
string ct = CondText(child);
|
||||||
? ConditionNames[child.Condition] : $"Cond({child.Condition})";
|
|
||||||
string ct = string.IsNullOrEmpty(child.ConditionData) ? cn : $"{cn}: {child.ConditionData}";
|
|
||||||
groupPanel.Children.Add(new TextBlock
|
groupPanel.Children.Add(new TextBlock
|
||||||
{
|
{
|
||||||
Text = $" • {ct}", Foreground = ColMute, FontSize = 9,
|
Text = $" • {ct}", Foreground = ColMute, FontSize = 9,
|
||||||
|
|
@ -1133,7 +1142,9 @@ internal static class MetaPanel
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
BuildSubRuleSection(content, ps, picker, rebuild, r.Children, "Sub-Conditions", isAction: false);
|
BuildSubRuleSection(content, ps, picker, rebuild, r.Children,
|
||||||
|
r.Condition == 20 ? "Not (one condition):" : "Sub-Conditions", isAction: false,
|
||||||
|
maxCount: r.Condition == 20 ? 1 : int.MaxValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Action ────────────────────────────────────────────────────────────
|
// ── Action ────────────────────────────────────────────────────────────
|
||||||
|
|
@ -1227,9 +1238,14 @@ internal static class MetaPanel
|
||||||
content.Children.Add(btnRow);
|
content.Children.Add(btnRow);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sub-conditions nest: a Not/All/Any sub-condition gets its own indented list below its
|
||||||
|
// row (a Not takes exactly one). They used to be single flat rows, so a Not under an All
|
||||||
|
// had nowhere to say what it negates. Deep enough for anything a meta writes.
|
||||||
|
private const int MaxSubConditionDepth = 4;
|
||||||
|
|
||||||
private static void BuildSubRuleSection(
|
private static void BuildSubRuleSection(
|
||||||
StackPanel content, PanelState ps, PickerState picker, Action rebuild,
|
StackPanel content, PanelState ps, PickerState picker, Action rebuild,
|
||||||
List<MetaRuleDto> subRules, string label, bool isAction)
|
List<MetaRuleDto> subRules, string label, bool isAction, int depth = 0, int maxCount = int.MaxValue)
|
||||||
{
|
{
|
||||||
content.Children.Add(new TextBlock
|
content.Children.Add(new TextBlock
|
||||||
{
|
{
|
||||||
|
|
@ -1255,11 +1271,30 @@ internal static class MetaPanel
|
||||||
{
|
{
|
||||||
if (isAction) sub.Action = idx; else sub.Condition = idx;
|
if (isAction) sub.Action = idx; else sub.Condition = idx;
|
||||||
typeBtn.Content = names[idx];
|
typeBtn.Content = names[idx];
|
||||||
|
if (!isAction)
|
||||||
|
{
|
||||||
|
// Composite ↔ simple changes the row's shape: redraw it.
|
||||||
|
if (!IsCompositeCondition(idx)) sub.Children.Clear();
|
||||||
|
else if (idx == 20 && sub.Children.Count > 1) sub.Children.RemoveRange(1, sub.Children.Count - 1);
|
||||||
|
rebuild();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
Grid.SetColumn(typeBtn, 0);
|
Grid.SetColumn(typeBtn, 0);
|
||||||
subRow.Children.Add(typeBtn);
|
subRow.Children.Add(typeBtn);
|
||||||
|
|
||||||
|
bool nests = !isAction && IsCompositeCondition(sub.Condition) && depth < MaxSubConditionDepth;
|
||||||
|
if (nests)
|
||||||
|
{
|
||||||
|
subRow.Children.Add(new TextBlock
|
||||||
|
{
|
||||||
|
Text = sub.Condition == 20 ? "(the condition below)" : "(the conditions below)",
|
||||||
|
Foreground = ColTextDim, FontSize = 9, VerticalAlignment = VerticalAlignment.Center,
|
||||||
|
Margin = new Thickness(6, 0, 0, 0),
|
||||||
|
});
|
||||||
|
Grid.SetColumn(subRow.Children[^1], 1);
|
||||||
|
}
|
||||||
|
|
||||||
var dataBox = new TextBox
|
var dataBox = new TextBox
|
||||||
{
|
{
|
||||||
Text = isAction ? sub.ActionData : sub.ConditionData,
|
Text = isAction ? sub.ActionData : sub.ConditionData,
|
||||||
|
|
@ -1270,7 +1305,7 @@ internal static class MetaPanel
|
||||||
};
|
};
|
||||||
dataBox.TextChanged += (_, _) => { if (isAction) sub.ActionData = dataBox.Text ?? ""; else sub.ConditionData = dataBox.Text ?? ""; };
|
dataBox.TextChanged += (_, _) => { if (isAction) sub.ActionData = dataBox.Text ?? ""; else sub.ConditionData = dataBox.Text ?? ""; };
|
||||||
Grid.SetColumn(dataBox, 1);
|
Grid.SetColumn(dataBox, 1);
|
||||||
subRow.Children.Add(dataBox);
|
if (!nests) subRow.Children.Add(dataBox);
|
||||||
|
|
||||||
var rmBtn = new Button
|
var rmBtn = new Button
|
||||||
{
|
{
|
||||||
|
|
@ -1286,8 +1321,19 @@ internal static class MetaPanel
|
||||||
subRow.Children.Add(rmBtn);
|
subRow.Children.Add(rmBtn);
|
||||||
|
|
||||||
content.Children.Add(subRow);
|
content.Children.Add(subRow);
|
||||||
|
|
||||||
|
if (nests)
|
||||||
|
{
|
||||||
|
var nested = new StackPanel { Margin = new Thickness(14, 0, 0, 2) };
|
||||||
|
string nestedLabel = sub.Condition switch { 20 => "Not:", 2 => "All of:", _ => "Any of:" };
|
||||||
|
BuildSubRuleSection(nested, ps, picker, rebuild, sub.Children, nestedLabel, isAction: false,
|
||||||
|
depth + 1, maxCount: sub.Condition == 20 ? 1 : int.MaxValue);
|
||||||
|
content.Children.Add(nested);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (subRules.Count >= maxCount) return; // a Not already has its one operand
|
||||||
|
|
||||||
var addSubBtn = new Button
|
var addSubBtn = new Button
|
||||||
{
|
{
|
||||||
Content = $"+ Add",
|
Content = $"+ Add",
|
||||||
|
|
|
||||||
|
|
@ -1148,10 +1148,11 @@ internal static partial class RadarPanel
|
||||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||||
VerticalContentAlignment = VerticalAlignment.Center,
|
VerticalContentAlignment = VerticalAlignment.Center,
|
||||||
};
|
};
|
||||||
// Tooltip parameter intentionally unused: ToolTip.SetTip() schedules
|
// Tooltip parameter intentionally unused. It was dropped because a
|
||||||
// an Avalonia ToolTip Popup whose hover-enter side effects flash the
|
// ToolTip popup used to blank every docked panel (the "panel flash").
|
||||||
// entire overlay capture pipeline (a one-frame invalidation that's
|
// Popups are now drawn inside the overlay frame (OverlayPopups, see
|
||||||
// very visible against AC's frame). Glyphs are self-descriptive.
|
// AvaloniaOverlay.ThreadMain), so ToolTip.SetTip would be safe here;
|
||||||
|
// the glyphs are self-descriptive, so they stay tooltip-less.
|
||||||
_ = tooltip;
|
_ = tooltip;
|
||||||
// Eat pointer events so they don't bubble through to the radar
|
// Eat pointer events so they don't bubble through to the radar
|
||||||
// surface's drag handler beneath.
|
// surface's drag handler beneath.
|
||||||
|
|
|
||||||
|
|
@ -487,7 +487,22 @@ internal static partial class RynthAiPanel
|
||||||
|
|
||||||
rightStack.Children.Add(BuildSelectorRow("Profile:", profileSelector));
|
rightStack.Children.Add(BuildSelectorRow("Profile:", profileSelector));
|
||||||
rightStack.Children.Add(BuildSelectorRow("Nav:", navSelector));
|
rightStack.Children.Add(BuildSelectorRow("Nav:", navSelector));
|
||||||
rightStack.Children.Add(BuildSelectorRow("Loot:", lootSelector));
|
// ✎ opens the standalone Loot Editor on the loot profile in use - or, while a
|
||||||
|
// vendor is open, on that vendor's AutoVendor profile (both are .utl files).
|
||||||
|
var lootEditButton = new Button
|
||||||
|
{
|
||||||
|
Content = "✎",
|
||||||
|
FontSize = 10,
|
||||||
|
Padding = new Thickness(5, 0),
|
||||||
|
Margin = new Thickness(3, 0, 0, 0),
|
||||||
|
MinHeight = 0,
|
||||||
|
Background = new SolidColorBrush(Color.FromRgb(0x2D, 0x38, 0x47)),
|
||||||
|
Foreground = ColMute,
|
||||||
|
BorderThickness = new Thickness(0),
|
||||||
|
VerticalAlignment = VerticalAlignment.Stretch,
|
||||||
|
};
|
||||||
|
ToolTip.SetTip(lootEditButton, "Edit in the Loot Editor: the loot profile in use, or the open vendor's AutoVendor profile.");
|
||||||
|
rightStack.Children.Add(BuildSelectorRow("Loot:", lootSelector, lootEditButton));
|
||||||
rightStack.Children.Add(BuildSelectorRow("Meta:", metaSelector));
|
rightStack.Children.Add(BuildSelectorRow("Meta:", metaSelector));
|
||||||
|
|
||||||
headerGrid.Children.Add(rightStack);
|
headerGrid.Children.Add(rightStack);
|
||||||
|
|
@ -835,6 +850,12 @@ internal static partial class RynthAiPanel
|
||||||
ShowPicker(navSelector, snap.NavProfiles, snap.SelectedNavIdx, idx => _selectProfile?.Invoke(0, idx));
|
ShowPicker(navSelector, snap.NavProfiles, snap.SelectedNavIdx, idx => _selectProfile?.Invoke(0, idx));
|
||||||
lootSelector.Click += (_, _) =>
|
lootSelector.Click += (_, _) =>
|
||||||
ShowPicker(lootSelector, snap.LootProfiles, snap.SelectedLootIdx, idx => _selectProfile?.Invoke(1, idx));
|
ShowPicker(lootSelector, snap.LootProfiles, snap.SelectedLootIdx, idx => _selectProfile?.Invoke(1, idx));
|
||||||
|
lootEditButton.Click += (_, _) =>
|
||||||
|
{
|
||||||
|
ClosePicker();
|
||||||
|
string path = !string.IsNullOrEmpty(snap.VendorProfilePath) ? snap.VendorProfilePath : snap.CurrentLootPath;
|
||||||
|
LaunchLootEditor(path);
|
||||||
|
};
|
||||||
metaSelector.Click += (_, _) =>
|
metaSelector.Click += (_, _) =>
|
||||||
ShowPicker(metaSelector, snap.MetaProfiles, snap.SelectedMetaIdx, idx => _selectProfile?.Invoke(2, idx));
|
ShowPicker(metaSelector, snap.MetaProfiles, snap.SelectedMetaIdx, idx => _selectProfile?.Invoke(2, idx));
|
||||||
|
|
||||||
|
|
@ -1035,11 +1056,11 @@ internal static partial class RynthAiPanel
|
||||||
return stack;
|
return stack;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Grid BuildSelectorRow(string label, Button selector)
|
private static Grid BuildSelectorRow(string label, Button selector, Button? trailing = null)
|
||||||
{
|
{
|
||||||
var row = new Grid
|
var row = new Grid
|
||||||
{
|
{
|
||||||
ColumnDefinitions = new ColumnDefinitions("36,*"),
|
ColumnDefinitions = new ColumnDefinitions(trailing == null ? "36,*" : "36,*,Auto"),
|
||||||
Margin = new Thickness(0, 0, 0, 0)
|
Margin = new Thickness(0, 0, 0, 0)
|
||||||
};
|
};
|
||||||
row.Children.Add(new TextBlock
|
row.Children.Add(new TextBlock
|
||||||
|
|
@ -1051,9 +1072,52 @@ internal static partial class RynthAiPanel
|
||||||
});
|
});
|
||||||
row.Children.Add(selector);
|
row.Children.Add(selector);
|
||||||
Grid.SetColumn(selector, 1);
|
Grid.SetColumn(selector, 1);
|
||||||
|
if (trailing != null)
|
||||||
|
{
|
||||||
|
row.Children.Add(trailing);
|
||||||
|
Grid.SetColumn(trailing, 2);
|
||||||
|
}
|
||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[DllImport("shell32.dll", CharSet = CharSet.Unicode, EntryPoint = "ShellExecuteW")]
|
||||||
|
private static extern IntPtr ShellExecuteW(IntPtr hwnd, string lpOperation, string lpFile,
|
||||||
|
string? lpParameters, string? lpDirectory, int nShowCmd);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Starts the standalone Loot Editor on <paramref name="profilePath"/> (empty = no file).
|
||||||
|
/// The installer puts it in {app}\Tools\LootEditor next to Runtime\, so walk up from the
|
||||||
|
/// engine module (Runtime\ or Runtime\.engine_loads\) to find it. ShellExecute, not
|
||||||
|
/// Process.Start: the Process API is the documented AV hazard inside acclient.exe.
|
||||||
|
/// </summary>
|
||||||
|
private static void LaunchLootEditor(string? profilePath)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string? exe = null;
|
||||||
|
string? dir = EntryPoint.EngineDirectory;
|
||||||
|
for (int i = 0; i < 4 && !string.IsNullOrEmpty(dir) && exe == null; i++, dir = System.IO.Path.GetDirectoryName(dir))
|
||||||
|
{
|
||||||
|
string candidate = System.IO.Path.Combine(dir, "Tools", "LootEditor", "RynthCore.LootEditor.exe");
|
||||||
|
if (System.IO.File.Exists(candidate)) exe = candidate;
|
||||||
|
}
|
||||||
|
exe ??= @"C:\Games\RynthCore\Tools\LootEditor\RynthCore.LootEditor.exe";
|
||||||
|
if (!System.IO.File.Exists(exe))
|
||||||
|
{
|
||||||
|
RynthLog.Info($"RynthAiPanel: Loot Editor not found (looked for {exe}).");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string? args = string.IsNullOrEmpty(profilePath) ? null : $"\"{profilePath}\"";
|
||||||
|
IntPtr r = ShellExecuteW(IntPtr.Zero, "open", exe, args, System.IO.Path.GetDirectoryName(exe), 1 /* SW_SHOWNORMAL */);
|
||||||
|
RynthLog.Info($"RynthAiPanel: Loot Editor {(r.ToInt64() > 32 ? "started" : $"failed to start (code {r.ToInt64()})")}: {exe} {args}");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
RynthLog.Info($"RynthAiPanel: Loot Editor launch threw {ex.GetType().Name}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static Button CreateSelector(string text)
|
private static Button CreateSelector(string text)
|
||||||
{
|
{
|
||||||
// ImGui dashboard pushes ImGuiCol.FrameBg = (0.18, 0.22, 0.28) → #2D3847
|
// ImGui dashboard pushes ImGuiCol.FrameBg = (0.18, 0.22, 0.28) → #2D3847
|
||||||
|
|
@ -1507,6 +1571,9 @@ internal static partial class RynthAiPanel
|
||||||
[JsonPropertyName("metaProfiles")] public string[] MetaProfiles { get; set; } = Array.Empty<string>();
|
[JsonPropertyName("metaProfiles")] public string[] MetaProfiles { get; set; } = Array.Empty<string>();
|
||||||
[JsonPropertyName("currentNavName")] public string CurrentNavName { get; set; } = string.Empty;
|
[JsonPropertyName("currentNavName")] public string CurrentNavName { get; set; } = string.Empty;
|
||||||
[JsonPropertyName("currentLootName")] public string CurrentLootName { get; set; } = string.Empty;
|
[JsonPropertyName("currentLootName")] public string CurrentLootName { get; set; } = string.Empty;
|
||||||
|
[JsonPropertyName("currentLootPath")] public string CurrentLootPath { get; set; } = string.Empty;
|
||||||
|
// Set while a vendor is open: the AutoVendor profile it would use (may not exist yet).
|
||||||
|
[JsonPropertyName("vendorProfilePath")] public string VendorProfilePath { get; set; } = string.Empty;
|
||||||
[JsonPropertyName("currentMetaName")] public string CurrentMetaName { get; set; } = string.Empty;
|
[JsonPropertyName("currentMetaName")] public string CurrentMetaName { get; set; } = string.Empty;
|
||||||
[JsonPropertyName("selectedNavIdx")] public int SelectedNavIdx { get; set; }
|
[JsonPropertyName("selectedNavIdx")] public int SelectedNavIdx { get; set; }
|
||||||
[JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; }
|
[JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; }
|
||||||
|
|
|
||||||
|
|
@ -61,7 +61,7 @@ internal static class SettingsPanel
|
||||||
|
|
||||||
private static readonly string[] Tabs =
|
private static readonly string[] Tabs =
|
||||||
{ "Display", "UI", "Misc", "Recharge", "Melee Combat", "Spell Combat",
|
{ "Display", "UI", "Misc", "Recharge", "Melee Combat", "Spell Combat",
|
||||||
"Ranges", "Navigation", "Buffing", "Crafting", "Looting" };
|
"Ranges", "Navigation", "Buffing", "Crafting", "Looting", "Vendoring" };
|
||||||
|
|
||||||
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
|
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
|
||||||
private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
|
private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
|
||||||
|
|
@ -93,11 +93,27 @@ internal static class SettingsPanel
|
||||||
public bool EnableRaycasting { get; set; }
|
public bool EnableRaycasting { get; set; }
|
||||||
public bool UseArcs { get; set; }
|
public bool UseArcs { get; set; }
|
||||||
public float BowArcVelocity { get; set; } = 25f;
|
public float BowArcVelocity { get; set; } = 25f;
|
||||||
|
public float MissileArcClearance { get; set; } = 0.5f;
|
||||||
|
// Vendoring (RynthAi AutoVendor; defaults match LegacyUiSettings)
|
||||||
|
public bool AutoVendorEnabled { get; set; }
|
||||||
|
public bool AutoVendorEnableBuying { get; set; } = true;
|
||||||
|
public bool AutoVendorEnableSelling { get; set; } = true;
|
||||||
|
public bool AutoVendorTestMode { get; set; } = true;
|
||||||
|
public bool AutoVendorThink { get; set; }
|
||||||
|
public bool AutoVendorShowMerchantInfo { get; set; } = true;
|
||||||
|
public bool AutoVendorOnlyFromMainPack { get; set; }
|
||||||
|
public int AutoVendorTries { get; set; } = 4;
|
||||||
|
public int AutoVendorTriesTime { get; set; } = 5000;
|
||||||
|
public bool LosDebugLog { get; set; }
|
||||||
public float CrossbowArcVelocity { get; set; } = 40f;
|
public float CrossbowArcVelocity { get; set; } = 40f;
|
||||||
public float AtlatlArcVelocity { get; set; } = 22f;
|
public float AtlatlArcVelocity { get; set; } = 22f;
|
||||||
public float MagicArcVelocity { get; set; } = 25f;
|
public float MagicArcVelocity { get; set; } = 25f;
|
||||||
public int BlacklistAttempts { get; set; } = 3;
|
public int BlacklistAttempts { get; set; } = 3;
|
||||||
public int BlacklistTimeoutSec { get; set; } = 30;
|
public int BlacklistTimeoutSec { get; set; } = 30;
|
||||||
|
// Not shown in this panel, but carried so a save doesn't send them missing:
|
||||||
|
// RynthAi applied the missing value as 0 on every panel click (2026-09-27).
|
||||||
|
public int BlacklistCastSettleMs { get; set; } = 1500;
|
||||||
|
public int MonsterDisengageRange { get; set; }
|
||||||
public int TargetNoProgressTimeoutSec { get; set; }
|
public int TargetNoProgressTimeoutSec { get; set; }
|
||||||
public int GiveQueueIntervalMs { get; set; } = 150;
|
public int GiveQueueIntervalMs { get; set; } = 150;
|
||||||
// Recharge
|
// Recharge
|
||||||
|
|
@ -155,6 +171,7 @@ internal static class SettingsPanel
|
||||||
public float NavDeadZone { get; set; } = 4f;
|
public float NavDeadZone { get; set; } = 4f;
|
||||||
public float NavSweepMult { get; set; } = 2.5f;
|
public float NavSweepMult { get; set; } = 2.5f;
|
||||||
public float NavLookaheadYards { get; set; } = 4f;
|
public float NavLookaheadYards { get; set; } = 4f;
|
||||||
|
public float NavShortcutYards { get; set; } = 1f;
|
||||||
public float NavTurnRateDegPerSec { get; set; } = 270f;
|
public float NavTurnRateDegPerSec { get; set; } = 270f;
|
||||||
public float NavTier1TurnSpeed { get; set; } = 3f;
|
public float NavTier1TurnSpeed { get; set; } = 3f;
|
||||||
public float PostPortalDelaySec { get; set; } = 4f;
|
public float PostPortalDelaySec { get; set; } = 4f;
|
||||||
|
|
@ -168,6 +185,7 @@ internal static class SettingsPanel
|
||||||
public bool EnableBuffing { get; set; } = true;
|
public bool EnableBuffing { get; set; } = true;
|
||||||
public bool RebuffWhenIdle { get; set; }
|
public bool RebuffWhenIdle { get; set; }
|
||||||
public int RebuffSecondsRemaining { get; set; } = 300;
|
public int RebuffSecondsRemaining { get; set; } = 300;
|
||||||
|
public int RebuffTopOffSecondsRemaining { get; set; } = 1200;
|
||||||
public int BuffMinSkillLevelTier1 { get; set; } = 35;
|
public int BuffMinSkillLevelTier1 { get; set; } = 35;
|
||||||
public int BuffMinSkillLevelTier2 { get; set; } = 85;
|
public int BuffMinSkillLevelTier2 { get; set; } = 85;
|
||||||
public int BuffMinSkillLevelTier3 { get; set; } = 135;
|
public int BuffMinSkillLevelTier3 { get; set; } = 135;
|
||||||
|
|
@ -480,6 +498,7 @@ internal static class SettingsPanel
|
||||||
case 8: BuildBuffingTab(state, panel, picker); break;
|
case 8: BuildBuffingTab(state, panel, picker); break;
|
||||||
case 9: BuildCraftingTab(state, panel, picker); break;
|
case 9: BuildCraftingTab(state, panel, picker); break;
|
||||||
case 10: BuildLootingTab(state, panel, picker); break;
|
case 10: BuildLootingTab(state, panel, picker); break;
|
||||||
|
case 11: BuildVendoringTab(state, panel, picker); break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -558,14 +577,20 @@ internal static class SettingsPanel
|
||||||
p.Children.Add(SectionHeader("Missile Arc Velocities (m/s)"));
|
p.Children.Add(SectionHeader("Missile Arc Velocities (m/s)"));
|
||||||
p.Children.Add(BoolRow("Use Arcs for Missile LoS", state.Data.UseArcs,
|
p.Children.Add(BoolRow("Use Arcs for Missile LoS", state.Data.UseArcs,
|
||||||
v => { state.Data.UseArcs = v; Push(state); state.Rebuild?.Invoke(); },
|
v => { state.Data.UseArcs = v; Push(state); state.Rebuild?.Invoke(); },
|
||||||
"When off, all missile LoS checks are linear (eye-to-eye)."));
|
"A missile target must pass both the straight line and the real arrow arc, ceilings included (dungeons too).\nWhen off, all missile LoS checks are linear (eye-to-eye)."));
|
||||||
if (state.Data.UseArcs)
|
if (state.Data.UseArcs)
|
||||||
{
|
{
|
||||||
p.Children.Add(FloatRow("Bow", state.Data.BowArcVelocity, 10f, 60f, 0.5f, v => { state.Data.BowArcVelocity = v; Push(state); }, "Bow projectile speed (m/s). Lower = higher arc."));
|
p.Children.Add(FloatRow("Bow", state.Data.BowArcVelocity, 10f, 60f, 0.5f, v => { state.Data.BowArcVelocity = v; Push(state); }, "Bow projectile speed (m/s). Lower = higher arc."));
|
||||||
p.Children.Add(FloatRow("Crossbow", state.Data.CrossbowArcVelocity, 10f, 80f, 0.5f, v => { state.Data.CrossbowArcVelocity = v; Push(state); }));
|
p.Children.Add(FloatRow("Crossbow", state.Data.CrossbowArcVelocity, 10f, 80f, 0.5f, v => { state.Data.CrossbowArcVelocity = v; Push(state); }));
|
||||||
p.Children.Add(FloatRow("Atlatl", state.Data.AtlatlArcVelocity, 10f, 60f, 0.5f, v => { state.Data.AtlatlArcVelocity = v; Push(state); }));
|
p.Children.Add(FloatRow("Atlatl", state.Data.AtlatlArcVelocity, 10f, 60f, 0.5f, v => { state.Data.AtlatlArcVelocity = v; Push(state); }));
|
||||||
p.Children.Add(FloatRow("Magic Arc", state.Data.MagicArcVelocity, 10f, 60f, 0.5f, v => { state.Data.MagicArcVelocity = v; Push(state); }));
|
p.Children.Add(FloatRow("Magic Arc", state.Data.MagicArcVelocity, 10f, 60f, 0.5f, v => { state.Data.MagicArcVelocity = v; Push(state); }));
|
||||||
|
p.Children.Add(FloatRow("Arc Clearance (m)", state.Data.MissileArcClearance, 0f, 3f, 0.1f,
|
||||||
|
v => { state.Data.MissileArcClearance = MathF.Max(0f, v); Push(state); },
|
||||||
|
"Extra headroom the arc must have at mid-flight. Raise it if arrows still hit ceilings; lower it if reachable mobs get skipped."));
|
||||||
}
|
}
|
||||||
|
p.Children.Add(BoolRow("LoS Debug Log", state.Data.LosDebugLog,
|
||||||
|
v => { state.Data.LosDebugLog = v; Push(state); },
|
||||||
|
"Log each blocked missile target and why (arc peak, where it hits) to the RynthCore log. /ra lostest bow tests the selected mob."));
|
||||||
|
|
||||||
p.Children.Add(Spacer());
|
p.Children.Add(Spacer());
|
||||||
p.Children.Add(SectionHeader("Monster Blacklist"));
|
p.Children.Add(SectionHeader("Monster Blacklist"));
|
||||||
|
|
@ -772,6 +797,9 @@ internal static class SettingsPanel
|
||||||
p.Children.Add(FloatRow("Lookahead (yd)", state.Data.NavLookaheadYards, 0f, 30f, 0.5f,
|
p.Children.Add(FloatRow("Lookahead (yd)", state.Data.NavLookaheadYards, 0f, 30f, 0.5f,
|
||||||
v => { state.Data.NavLookaheadYards = MathF.Max(0f, v); Push(state); },
|
v => { state.Data.NavLookaheadYards = MathF.Max(0f, v); Push(state); },
|
||||||
"Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off."));
|
"Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off."));
|
||||||
|
p.Children.Add(FloatRow("Shortcut Tolerance (yd)", state.Data.NavShortcutYards, 0f, 10f, 0.5f,
|
||||||
|
v => { state.Data.NavShortcutYards = MathF.Max(0f, v); Push(state); },
|
||||||
|
"On reaching a waypoint, skip ahead only past points that all lie within this distance of the straight line to the new target. 0 = visit every waypoint."));
|
||||||
p.Children.Add(FloatRow("Turn Rate (deg/s)", state.Data.NavTurnRateDegPerSec, 30f, 720f, 15f,
|
p.Children.Add(FloatRow("Turn Rate (deg/s)", state.Data.NavTurnRateDegPerSec, 30f, 720f, 15f,
|
||||||
v => { state.Data.NavTurnRateDegPerSec = v; Push(state); },
|
v => { state.Data.NavTurnRateDegPerSec = v; Push(state); },
|
||||||
"Legacy / Mode 0 heading-servo max turn speed. Ignored by Tier 1 and Tier 2."));
|
"Legacy / Mode 0 heading-servo max turn speed. Ignored by Tier 1 and Tier 2."));
|
||||||
|
|
@ -804,6 +832,9 @@ internal static class SettingsPanel
|
||||||
p.Children.Add(IntRow("Rebuff With (seconds left)", state.Data.RebuffSecondsRemaining, 30, 1800, 30,
|
p.Children.Add(IntRow("Rebuff With (seconds left)", state.Data.RebuffSecondsRemaining, 30, 1800, 30,
|
||||||
v => { state.Data.RebuffSecondsRemaining = v; Push(state); },
|
v => { state.Data.RebuffSecondsRemaining = v; Push(state); },
|
||||||
"Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly."));
|
"Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly."));
|
||||||
|
p.Children.Add(IntRow("Also Refresh Under (seconds left)", state.Data.RebuffTopOffSecondsRemaining, 30, 3600, 60,
|
||||||
|
v => { state.Data.RebuffTopOffSecondsRemaining = v; Push(state); },
|
||||||
|
"When a buff is due, also recast every other buff with less than this much time left,\nso they land together. Buffs with more time are left alone. Default 1200 (20 minutes).\nAt or below 'Rebuff With', only the expiring buff is recast."));
|
||||||
|
|
||||||
p.Children.Add(Spacer());
|
p.Children.Add(Spacer());
|
||||||
p.Children.Add(SectionHeader("Buff Difficulty (Min Buffed Skill)"));
|
p.Children.Add(SectionHeader("Buff Difficulty (Min Buffed Skill)"));
|
||||||
|
|
@ -859,6 +890,43 @@ internal static class SettingsPanel
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void BuildVendoringTab(PanelState state, StackPanel p, PickerState picker)
|
||||||
|
{
|
||||||
|
p.Children.Add(SectionHeader("AutoVendor"));
|
||||||
|
p.Children.Add(BoolRow("Enabled", state.Data.AutoVendorEnabled,
|
||||||
|
v => { state.Data.AutoVendorEnabled = v; Push(state); },
|
||||||
|
"Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\nProfile: <Vendor Name>.utl, else default.utl, in the AutoVendor folder."));
|
||||||
|
p.Children.Add(BoolRow("Test Mode (only print what it would do)", state.Data.AutoVendorTestMode,
|
||||||
|
v => { state.Data.AutoVendorTestMode = v; Push(state); },
|
||||||
|
"Lists what would be bought and sold without trading. Leave this on until the lists look right."));
|
||||||
|
p.Children.Add(BoolRow("Buy", state.Data.AutoVendorEnableBuying,
|
||||||
|
v => { state.Data.AutoVendorEnableBuying = v; Push(state); }));
|
||||||
|
p.Children.Add(BoolRow("Sell", state.Data.AutoVendorEnableSelling,
|
||||||
|
v => { state.Data.AutoVendorEnableSelling = v; Push(state); }));
|
||||||
|
p.Children.Add(BoolRow("Only Sell From Main Pack", state.Data.AutoVendorOnlyFromMainPack,
|
||||||
|
v => { state.Data.AutoVendorOnlyFromMainPack = v; Push(state); }));
|
||||||
|
p.Children.Add(BoolRow("Show Merchant Info", state.Data.AutoVendorShowMerchantInfo,
|
||||||
|
v => { state.Data.AutoVendorShowMerchantInfo = v; Push(state); },
|
||||||
|
"Print the vendor's buy/sell rates and max value when it opens."));
|
||||||
|
p.Children.Add(BoolRow("Think When Finished", state.Data.AutoVendorThink,
|
||||||
|
v => { state.Data.AutoVendorThink = v; Push(state); },
|
||||||
|
"Send 'AutoVendor finished: <vendor>' (and failures) as a /tell to yourself, for metas."));
|
||||||
|
|
||||||
|
p.Children.Add(Spacer());
|
||||||
|
p.Children.Add(SectionHeader("/ub vendor open"));
|
||||||
|
p.Children.Add(IntRow("Tries", state.Data.AutoVendorTries, 1, 20, 1,
|
||||||
|
v => { state.Data.AutoVendorTries = v; Push(state); }));
|
||||||
|
p.Children.Add(IntRow("Time Between Tries (ms)", state.Data.AutoVendorTriesTime, 500, 30000, 250,
|
||||||
|
v => { state.Data.AutoVendorTriesTime = v; Push(state); }));
|
||||||
|
|
||||||
|
p.Children.Add(Spacer());
|
||||||
|
p.Children.Add(new TextBlock
|
||||||
|
{
|
||||||
|
Text = "Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match.",
|
||||||
|
Foreground = ColMute, FontSize = 10, TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 0),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private static void BuildLootingTab(PanelState state, StackPanel p, PickerState picker)
|
private static void BuildLootingTab(PanelState state, StackPanel p, PickerState picker)
|
||||||
{
|
{
|
||||||
p.Children.Add(BoolRow("Enable Looting", state.Data.EnableLooting,
|
p.Children.Add(BoolRow("Enable Looting", state.Data.EnableLooting,
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ namespace RynthCore.PluginCore;
|
||||||
|
|
||||||
public abstract class RynthPluginBase
|
public abstract class RynthPluginBase
|
||||||
{
|
{
|
||||||
public virtual uint MinimumApiVersion => RynthCoreHost.CurrentApiVersion;
|
public virtual uint MinimumApiVersion => RynthCoreHost.BaselineApiVersion;
|
||||||
|
|
||||||
protected RynthCoreApiNative Api { get; private set; }
|
protected RynthCoreApiNative Api { get; private set; }
|
||||||
protected RynthCoreHost Host { get; private set; }
|
protected RynthCoreHost Host { get; private set; }
|
||||||
|
|
|
||||||
|
|
@ -119,4 +119,10 @@ public struct RynthCoreApiNative
|
||||||
public IntPtr SendPluginCommandFn; // v64: forward (action,value) to a named plugin's command export
|
public IntPtr SendPluginCommandFn; // v64: forward (action,value) to a named plugin's command export
|
||||||
public IntPtr GetObjectDataIdPropertyFn; // v65: read a PWD DataID property (Icon=8 → _iconID) for inventory icons
|
public IntPtr GetObjectDataIdPropertyFn; // v65: read a PWD DataID property (Icon=8 → _iconID) for inventory icons
|
||||||
public IntPtr GetPluginExportJsonFn; // v66: broker any RynthPluginGet*Json export on a named plugin
|
public IntPtr GetPluginExportJsonFn; // v66: broker any RynthPluginGet*Json export on a named plugin
|
||||||
|
// v67: vendor trading (see VendorTypes.cs / RynthCoreHost vendor section)
|
||||||
|
public IntPtr GetVendorInfoFn; // int GetVendorInfo(VendorInfoNative*)
|
||||||
|
public IntPtr GetVendorItemsFn; // int GetVendorItems(VendorItemNative*, int maxCount)
|
||||||
|
public IntPtr VendorBuyFn; // uint VendorBuy(uint vendorId, VendorTradeEntryNative*, int count)
|
||||||
|
public IntPtr VendorSellFn; // uint VendorSell(uint vendorId, uint* itemIds, int count)
|
||||||
|
public IntPtr GetVendorTradeStatusFn; // int GetVendorTradeStatus(VendorTradeStatusNative*)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,23 @@
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
namespace RynthCore.PluginSdk;
|
namespace RynthCore.PluginSdk;
|
||||||
|
|
||||||
public readonly unsafe struct RynthCoreHost
|
public readonly unsafe struct RynthCoreHost
|
||||||
{
|
{
|
||||||
public const uint CurrentApiVersion = 66;
|
public const uint CurrentApiVersion = 67;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The oldest engine API a plugin built on this SDK loads on by default
|
||||||
|
/// (<see cref="RynthCore.PluginCore.RynthPluginBase.MinimumApiVersion"/>). Players get
|
||||||
|
/// plugin updates automatically but engine updates only when they click, so defaulting
|
||||||
|
/// to <see cref="CurrentApiVersion"/> made every rebuilt plugin refuse the engine most
|
||||||
|
/// players still run. Calls newer than this are version-checked by their wrappers
|
||||||
|
/// (e.g. HasVendorTrade); a plugin that truly needs a newer engine overrides
|
||||||
|
/// MinimumApiVersion. Raise this only with a release that forces the engine update.
|
||||||
|
/// </summary>
|
||||||
|
public const uint BaselineApiVersion = 66;
|
||||||
|
|
||||||
private readonly RynthCoreApiNative _api;
|
private readonly RynthCoreApiNative _api;
|
||||||
|
|
||||||
|
|
@ -1446,4 +1458,206 @@ public readonly unsafe struct RynthCoreHost
|
||||||
Marshal.FreeHGlobal(valuePtr);
|
Marshal.FreeHGlobal(valuePtr);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Vendor trading (API v67) ──────────────────────────────────────────
|
||||||
|
// Decal's WorldFilter.OpenVendor + Actions.VendorBuyAll/VendorSellAll shape as
|
||||||
|
// stateless calls (VendorCart adds the Add/Clear list shape on top). Reads come
|
||||||
|
// from a snapshot the engine takes on AC's main thread when the vendor list
|
||||||
|
// arrives. Buy/sell are checked, queued, re-checked on AC's main thread (funds,
|
||||||
|
// pack slots, burden, ownership) and sent through the client's own
|
||||||
|
// gmVendorUI::SendShopEvent. One transaction is in flight at a time: wait for
|
||||||
|
// GetVendorTradeStatus to finish before sending the next batch.
|
||||||
|
|
||||||
|
/// <summary>True when the engine exposes vendor trading (API v67+).</summary>
|
||||||
|
public bool HasVendorTrade => _api.Version >= 67
|
||||||
|
&& _api.GetVendorInfoFn != IntPtr.Zero && _api.GetVendorItemsFn != IntPtr.Zero
|
||||||
|
&& _api.VendorBuyFn != IntPtr.Zero && _api.VendorSellFn != IntPtr.Zero
|
||||||
|
&& _api.GetVendorTradeStatusFn != IntPtr.Zero;
|
||||||
|
|
||||||
|
/// <summary>The vendor that is open right now, or false if none (or pre-v67 engine).</summary>
|
||||||
|
public bool TryGetVendorInfo(out VendorInfo info)
|
||||||
|
{
|
||||||
|
info = null!;
|
||||||
|
if (_api.Version < 67 || _api.GetVendorInfoFn == IntPtr.Zero)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
VendorInfoNative raw;
|
||||||
|
if (((delegate* unmanaged[Cdecl]<VendorInfoNative*, int>)_api.GetVendorInfoFn)(&raw) == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
info = new VendorInfo
|
||||||
|
{
|
||||||
|
VendorId = raw.VendorId,
|
||||||
|
Name = ReadAnsi(raw.Name, 64),
|
||||||
|
Generation = raw.Generation,
|
||||||
|
ShopMode = raw.ShopMode,
|
||||||
|
ItemTypes = raw.ItemTypes,
|
||||||
|
MinValue = raw.MinValue,
|
||||||
|
MaxValue = raw.MaxValue,
|
||||||
|
DealsMagic = raw.DealsMagic != 0,
|
||||||
|
BuyRate = raw.BuyRate,
|
||||||
|
SellRate = raw.SellRate,
|
||||||
|
AltCurrencyWcid = raw.AltCurrencyWcid,
|
||||||
|
AltCurrencyName = ReadAnsi(raw.AltCurrencyName, 64),
|
||||||
|
AltCurrencyServerCount = raw.AltCurrencyServerCount,
|
||||||
|
AltCurrencyHave = raw.AltCurrencyHave,
|
||||||
|
PlayerCoins = raw.PlayerCoins,
|
||||||
|
ItemCount = raw.ItemCount,
|
||||||
|
TradingAvailable = (raw.Flags & 1u) != 0,
|
||||||
|
TradeInFlight = (raw.Flags & 2u) != 0,
|
||||||
|
};
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The open vendor's items; empty if no vendor is open (or pre-v67 engine).</summary>
|
||||||
|
public VendorItem[] GetVendorItems()
|
||||||
|
{
|
||||||
|
if (_api.Version < 67 || _api.GetVendorItemsFn == IntPtr.Zero)
|
||||||
|
return Array.Empty<VendorItem>();
|
||||||
|
|
||||||
|
var fn = (delegate* unmanaged[Cdecl]<VendorItemNative*, int, int>)_api.GetVendorItemsFn;
|
||||||
|
for (int attempt = 0; attempt < 3; attempt++)
|
||||||
|
{
|
||||||
|
int total = fn(null, 0);
|
||||||
|
if (total <= 0)
|
||||||
|
return Array.Empty<VendorItem>();
|
||||||
|
|
||||||
|
int capacity = total + 8; // headroom in case the list is re-sent between calls
|
||||||
|
IntPtr buf = Marshal.AllocHGlobal(capacity * sizeof(VendorItemNative));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
VendorItemNative* items = (VendorItemNative*)buf;
|
||||||
|
int now = fn(items, capacity);
|
||||||
|
if (now < 0)
|
||||||
|
return Array.Empty<VendorItem>();
|
||||||
|
if (now > capacity)
|
||||||
|
continue; // grew past the headroom; size again
|
||||||
|
|
||||||
|
var result = new VendorItem[now];
|
||||||
|
for (int i = 0; i < now; i++)
|
||||||
|
{
|
||||||
|
VendorItemNative* it = items + i;
|
||||||
|
result[i] = new VendorItem
|
||||||
|
{
|
||||||
|
ObjectId = it->ObjectId,
|
||||||
|
Wcid = it->Wcid,
|
||||||
|
Name = ReadAnsi(it->Name, 64),
|
||||||
|
ItemType = it->ItemType,
|
||||||
|
IconId = it->IconId,
|
||||||
|
Amount = it->Amount,
|
||||||
|
StackSize = it->StackSize,
|
||||||
|
MaxStackSize = it->MaxStackSize,
|
||||||
|
Value = it->Value,
|
||||||
|
UnitValue = it->UnitValue,
|
||||||
|
UnitPrice = it->UnitPrice,
|
||||||
|
Burden = it->Burden,
|
||||||
|
Unlimited = (it->Flags & 1u) != 0,
|
||||||
|
Stackable = (it->Flags & 2u) != 0,
|
||||||
|
NeedsContainerSlot = (it->Flags & 4u) != 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Marshal.FreeHGlobal(buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Array.Empty<VendorItem>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Buy from the open vendor (Decal VendorBuyAll). vendorId 0 = whichever vendor is
|
||||||
|
/// open; pass the id you read to make sure it's still that vendor. Returns the request
|
||||||
|
/// id, or 0 if refused (reason in <see cref="TryGetVendorTradeStatus"/>).
|
||||||
|
/// </summary>
|
||||||
|
public uint VendorBuy(uint vendorId, IReadOnlyList<VendorTradeEntryNative> items)
|
||||||
|
{
|
||||||
|
if (_api.Version < 67 || _api.VendorBuyFn == IntPtr.Zero || items == null || items.Count == 0)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
int n = items.Count;
|
||||||
|
IntPtr buf = Marshal.AllocHGlobal(n * sizeof(VendorTradeEntryNative));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
VendorTradeEntryNative* p = (VendorTradeEntryNative*)buf;
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
p[i] = items[i];
|
||||||
|
return ((delegate* unmanaged[Cdecl]<uint, VendorTradeEntryNative*, int, uint>)_api.VendorBuyFn)(vendorId, p, n);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Marshal.FreeHGlobal(buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Buy <paramref name="amount"/> of one vendor item.</summary>
|
||||||
|
public uint VendorBuy(uint objectId, int amount, uint vendorId = 0) =>
|
||||||
|
VendorBuy(vendorId, new[] { new VendorTradeEntryNative(objectId, amount) });
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sell your own items (whole stacks) to the open vendor (Decal VendorSellAll).
|
||||||
|
/// Items must be in your packs, not equipped, and of a type the vendor buys.
|
||||||
|
/// Returns the request id, or 0 if refused.
|
||||||
|
/// </summary>
|
||||||
|
public uint VendorSell(uint vendorId, IReadOnlyList<uint> itemIds)
|
||||||
|
{
|
||||||
|
if (_api.Version < 67 || _api.VendorSellFn == IntPtr.Zero || itemIds == null || itemIds.Count == 0)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
int n = itemIds.Count;
|
||||||
|
IntPtr buf = Marshal.AllocHGlobal(n * sizeof(uint));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
uint* p = (uint*)buf;
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
p[i] = itemIds[i];
|
||||||
|
return ((delegate* unmanaged[Cdecl]<uint, uint*, int, uint>)_api.VendorSellFn)(vendorId, p, n);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Marshal.FreeHGlobal(buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sell one of your items.</summary>
|
||||||
|
public uint VendorSell(uint itemId) => VendorSell(0, new[] { itemId });
|
||||||
|
|
||||||
|
/// <summary>State of the most recent buy/sell request (check RequestId is yours).</summary>
|
||||||
|
public bool TryGetVendorTradeStatus(out VendorTradeStatus status)
|
||||||
|
{
|
||||||
|
status = null!;
|
||||||
|
if (_api.Version < 67 || _api.GetVendorTradeStatusFn == IntPtr.Zero)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
VendorTradeStatusNative raw;
|
||||||
|
if (((delegate* unmanaged[Cdecl]<VendorTradeStatusNative*, int>)_api.GetVendorTradeStatusFn)(&raw) == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
status = new VendorTradeStatus
|
||||||
|
{
|
||||||
|
RequestId = raw.RequestId,
|
||||||
|
State = (VendorTradeState)raw.State,
|
||||||
|
Result = (VendorTradeResult)raw.Result,
|
||||||
|
IsBuy = raw.IsBuy != 0,
|
||||||
|
VendorId = raw.VendorId,
|
||||||
|
EntryCount = raw.EntryCount,
|
||||||
|
Estimate = raw.Estimate,
|
||||||
|
Message = ReadAnsi(raw.Message, 128),
|
||||||
|
};
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ReadAnsi(byte* p, int capacity)
|
||||||
|
{
|
||||||
|
int len = 0;
|
||||||
|
while (len < capacity && p[len] != 0)
|
||||||
|
len++;
|
||||||
|
if (len == 0)
|
||||||
|
return string.Empty;
|
||||||
|
var chars = new char[len];
|
||||||
|
for (int i = 0; i < len; i++)
|
||||||
|
chars[i] = (char)p[i]; // Latin-1, the client's single-byte names
|
||||||
|
return new string(chars);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
238
src/RynthCore.PluginSdk/VendorTypes.cs
Normal file
238
src/RynthCore.PluginSdk/VendorTypes.cs
Normal file
|
|
@ -0,0 +1,238 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
namespace RynthCore.PluginSdk;
|
||||||
|
|
||||||
|
// ─── Vendor trading ABI structs (engine API v67) ────────────────────────────
|
||||||
|
// Must mirror RynthCore.Engine/Plugins/PluginContract.cs exactly (Pack=4, same
|
||||||
|
// field order, same fixed-buffer sizes). Plugins normally use the managed
|
||||||
|
// VendorInfo / VendorItem / VendorTradeStatus types below instead.
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||||
|
public unsafe struct VendorInfoNative
|
||||||
|
{
|
||||||
|
public uint VendorId;
|
||||||
|
public uint Generation;
|
||||||
|
public int ShopMode;
|
||||||
|
public uint ItemTypes;
|
||||||
|
public int MinValue;
|
||||||
|
public int MaxValue;
|
||||||
|
public int DealsMagic;
|
||||||
|
public float BuyRate;
|
||||||
|
public float SellRate;
|
||||||
|
public uint AltCurrencyWcid;
|
||||||
|
public int AltCurrencyServerCount;
|
||||||
|
public int AltCurrencyHave;
|
||||||
|
public int PlayerCoins;
|
||||||
|
public int ItemCount;
|
||||||
|
public uint Flags;
|
||||||
|
public uint Reserved0;
|
||||||
|
public fixed byte Name[64];
|
||||||
|
public fixed byte AltCurrencyName[64];
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||||
|
public unsafe struct VendorItemNative
|
||||||
|
{
|
||||||
|
public uint ObjectId;
|
||||||
|
public uint Wcid;
|
||||||
|
public uint ItemType;
|
||||||
|
public uint IconId;
|
||||||
|
public int Amount;
|
||||||
|
public int StackSize;
|
||||||
|
public int MaxStackSize;
|
||||||
|
public int Value;
|
||||||
|
public int UnitValue;
|
||||||
|
public int UnitPrice;
|
||||||
|
public int Burden;
|
||||||
|
public uint Flags;
|
||||||
|
public uint Reserved0;
|
||||||
|
public uint Reserved1;
|
||||||
|
public fixed byte Name[64];
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||||
|
public struct VendorTradeEntryNative
|
||||||
|
{
|
||||||
|
public uint ObjectId;
|
||||||
|
public int Amount;
|
||||||
|
|
||||||
|
public VendorTradeEntryNative(uint objectId, int amount)
|
||||||
|
{
|
||||||
|
ObjectId = objectId;
|
||||||
|
Amount = amount;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||||
|
public unsafe struct VendorTradeStatusNative
|
||||||
|
{
|
||||||
|
public uint RequestId;
|
||||||
|
public int State;
|
||||||
|
public int Result;
|
||||||
|
public int IsBuy;
|
||||||
|
public uint VendorId;
|
||||||
|
public int EntryCount;
|
||||||
|
public int Estimate;
|
||||||
|
public uint Reserved0;
|
||||||
|
public fixed byte Message[128];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Managed views ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// <summary>The vendor that is open right now (Decal: WorldFilter.OpenVendor).</summary>
|
||||||
|
public sealed class VendorInfo
|
||||||
|
{
|
||||||
|
public uint VendorId { get; init; }
|
||||||
|
public string Name { get; init; } = string.Empty;
|
||||||
|
/// <summary>Bumps each time the server (re)sends the vendor list: on open and after every accepted buy/sell.</summary>
|
||||||
|
public uint Generation { get; init; }
|
||||||
|
public int ShopMode { get; init; }
|
||||||
|
/// <summary>ITEM_TYPE mask of what the vendor will buy from you.</summary>
|
||||||
|
public uint ItemTypes { get; init; }
|
||||||
|
public int MinValue { get; init; }
|
||||||
|
public int MaxValue { get; init; }
|
||||||
|
public bool DealsMagic { get; init; }
|
||||||
|
/// <summary>The vendor pays value x BuyRate when you sell (promissory notes at 1.0).</summary>
|
||||||
|
public float BuyRate { get; init; }
|
||||||
|
/// <summary>The vendor charges value x SellRate when you buy (promissory notes at 1.15).</summary>
|
||||||
|
public float SellRate { get; init; }
|
||||||
|
/// <summary>WCID of the currency this vendor takes; 0 = pyreals.</summary>
|
||||||
|
public uint AltCurrencyWcid { get; init; }
|
||||||
|
public string AltCurrencyName { get; init; } = string.Empty;
|
||||||
|
/// <summary>Alt currency count as the server put it in the vendor list (-1 if none).</summary>
|
||||||
|
public int AltCurrencyServerCount { get; init; }
|
||||||
|
/// <summary>Alt currency the engine counted in your packs (-1 = not counted yet / not an alt-currency vendor).</summary>
|
||||||
|
public int AltCurrencyHave { get; init; }
|
||||||
|
/// <summary>Your pyreals (CoinValue), refreshed on AC's main thread; -1 unknown.</summary>
|
||||||
|
public int PlayerCoins { get; init; }
|
||||||
|
public int ItemCount { get; init; }
|
||||||
|
/// <summary>The engine can trade with this vendor (client functions found, layout checked).</summary>
|
||||||
|
public bool TradingAvailable { get; init; }
|
||||||
|
/// <summary>A buy/sell is queued or waiting for the server.</summary>
|
||||||
|
public bool TradeInFlight { get; init; }
|
||||||
|
public bool UsesAltCurrency => AltCurrencyWcid != 0;
|
||||||
|
public bool Buys(uint itemType) => (ItemTypes & itemType) != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One item on the open vendor's list.</summary>
|
||||||
|
public sealed class VendorItem
|
||||||
|
{
|
||||||
|
public uint ObjectId { get; init; }
|
||||||
|
public uint Wcid { get; init; }
|
||||||
|
public string Name { get; init; } = string.Empty;
|
||||||
|
public uint ItemType { get; init; }
|
||||||
|
public uint IconId { get; init; }
|
||||||
|
/// <summary>How many the vendor has; -1 = unlimited.</summary>
|
||||||
|
public int Amount { get; init; }
|
||||||
|
public int StackSize { get; init; }
|
||||||
|
public int MaxStackSize { get; init; }
|
||||||
|
/// <summary>Value of the listed stack.</summary>
|
||||||
|
public int Value { get; init; }
|
||||||
|
public int UnitValue { get; init; }
|
||||||
|
/// <summary>What one unit costs you at this vendor (server rounding).</summary>
|
||||||
|
public int UnitPrice { get; init; }
|
||||||
|
public int Burden { get; init; }
|
||||||
|
public bool Unlimited { get; init; }
|
||||||
|
public bool Stackable { get; init; }
|
||||||
|
/// <summary>Packs and foci need a container slot.</summary>
|
||||||
|
public bool NeedsContainerSlot { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Outcome of the most recent VendorBuy / VendorSell request.</summary>
|
||||||
|
public sealed class VendorTradeStatus
|
||||||
|
{
|
||||||
|
public uint RequestId { get; init; }
|
||||||
|
public VendorTradeState State { get; init; }
|
||||||
|
public VendorTradeResult Result { get; init; }
|
||||||
|
public bool IsBuy { get; init; }
|
||||||
|
public uint VendorId { get; init; }
|
||||||
|
public int EntryCount { get; init; }
|
||||||
|
/// <summary>Buy: estimated cost (pyreals or alt currency). Sell: estimated payout in pyreals.</summary>
|
||||||
|
public int Estimate { get; init; }
|
||||||
|
public string Message { get; init; } = string.Empty;
|
||||||
|
/// <summary>Finished one way or the other (done or refused).</summary>
|
||||||
|
public bool IsFinished => State is VendorTradeState.Done or VendorTradeState.Refused;
|
||||||
|
public bool Succeeded => State == VendorTradeState.Done && Result == VendorTradeResult.Accepted;
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum VendorTradeState
|
||||||
|
{
|
||||||
|
None = 0,
|
||||||
|
/// <summary>Passed the snapshot checks; waiting for AC's main thread.</summary>
|
||||||
|
Queued = 1,
|
||||||
|
/// <summary>Sent through the client; waiting for the server.</summary>
|
||||||
|
Sent = 2,
|
||||||
|
/// <summary>The server answered (see Result).</summary>
|
||||||
|
Done = 3,
|
||||||
|
/// <summary>Never sent: no vendor, unknown item, not enough money/space/burden, ... (see Message).</summary>
|
||||||
|
Refused = 4,
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum VendorTradeResult
|
||||||
|
{
|
||||||
|
None = 0,
|
||||||
|
/// <summary>The server re-sent the vendor list: the trade went through.</summary>
|
||||||
|
Accepted = 1,
|
||||||
|
/// <summary>The server answered without re-sending the list: it refused (busy, funds, space...).</summary>
|
||||||
|
AnsweredNoRefresh = 2,
|
||||||
|
/// <summary>No answer within 10 s.</summary>
|
||||||
|
TimedOut = 3,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decal-shaped buy/sell lists (Actions.VendorAddBuyList / VendorBuyAll / VendorClearBuyList
|
||||||
|
/// and the Sell equivalents) on top of the stateless engine calls. Plugin-local: each
|
||||||
|
/// plugin keeps its own cart. BuyAll/SellAll send the whole list as ONE transaction
|
||||||
|
/// (max 100 lines) and return the request id (0 = refused, see GetVendorTradeStatus);
|
||||||
|
/// the list is cleared only when the request is accepted for sending.
|
||||||
|
/// Wait for the status to finish (and the vendor Generation to bump) before the next batch.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class VendorCart
|
||||||
|
{
|
||||||
|
private readonly List<VendorTradeEntryNative> _buy = new();
|
||||||
|
private readonly List<uint> _sell = new();
|
||||||
|
|
||||||
|
public IReadOnlyList<VendorTradeEntryNative> BuyList => _buy;
|
||||||
|
public IReadOnlyList<uint> SellList => _sell;
|
||||||
|
|
||||||
|
/// <summary>Add (or top up) a vendor item on the buy list.</summary>
|
||||||
|
public void AddBuy(uint objectId, int amount)
|
||||||
|
{
|
||||||
|
if (objectId == 0 || amount <= 0) return;
|
||||||
|
for (int i = 0; i < _buy.Count; i++)
|
||||||
|
{
|
||||||
|
if (_buy[i].ObjectId == objectId)
|
||||||
|
{
|
||||||
|
_buy[i] = new VendorTradeEntryNative(objectId, _buy[i].Amount + amount);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_buy.Add(new VendorTradeEntryNative(objectId, amount));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Add one of your own items (whole stack) to the sell list.</summary>
|
||||||
|
public void AddSell(uint objectId)
|
||||||
|
{
|
||||||
|
if (objectId != 0 && !_sell.Contains(objectId))
|
||||||
|
_sell.Add(objectId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ClearBuy() => _buy.Clear();
|
||||||
|
public void ClearSell() => _sell.Clear();
|
||||||
|
|
||||||
|
public uint BuyAll(RynthCoreHost host, uint vendorId = 0)
|
||||||
|
{
|
||||||
|
uint id = host.VendorBuy(vendorId, _buy);
|
||||||
|
if (id != 0) _buy.Clear();
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public uint SellAll(RynthCoreHost host, uint vendorId = 0)
|
||||||
|
{
|
||||||
|
uint id = host.VendorSell(vendorId, _sell);
|
||||||
|
if (id != 0) _sell.Clear();
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -58,9 +58,9 @@ internal sealed class AgentConfig
|
||||||
/// netsh urlacl or running elevated). Must end in '/'.</summary>
|
/// netsh urlacl or running elevated). Must end in '/'.</summary>
|
||||||
[JsonPropertyName("ServePrefix")] public string ServePrefix { get; set; } = "http://127.0.0.1:8740/";
|
[JsonPropertyName("ServePrefix")] public string ServePrefix { get; set; } = "http://127.0.0.1:8740/";
|
||||||
|
|
||||||
/// <summary>Optional shared secret. When set, GET /status requires
|
/// <summary>Shared secret, required when <see cref="ServeHttp"/> is on: every route but
|
||||||
/// <c>Authorization: Bearer <token></c> or <c>?token=</c>. Empty = open
|
/// /healthz needs <c>Authorization: Bearer <token></c> or <c>?token=</c>. Empty =
|
||||||
/// (fine for a 127.0.0.1 / private-tailnet bind).</summary>
|
/// the server stays off, on any bind (it can stream the screens and click in them).</summary>
|
||||||
[JsonPropertyName("ServeToken")] public string ServeToken { get; set; } = "";
|
[JsonPropertyName("ServeToken")] public string ServeToken { get; set; } = "";
|
||||||
|
|
||||||
/// <summary>When true, also write the latest rollup to
|
/// <summary>When true, also write the latest rollup to
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Net.WebSockets;
|
using System.Net.WebSockets;
|
||||||
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
|
|
@ -74,6 +75,14 @@ internal sealed class LocalStatusServer : IDisposable
|
||||||
|
|
||||||
public bool TryStart(out string error)
|
public bool TryStart(out string error)
|
||||||
{
|
{
|
||||||
|
// Never serve without a token, loopback included: every route but /healthz is behind it.
|
||||||
|
if (_token == null)
|
||||||
|
{
|
||||||
|
error = "no ServeToken set";
|
||||||
|
Running = false;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_listener.Start();
|
_listener.Start();
|
||||||
|
|
@ -741,13 +750,17 @@ internal sealed class LocalStatusServer : IDisposable
|
||||||
{
|
{
|
||||||
string? header = req.Headers["Authorization"];
|
string? header = req.Headers["Authorization"];
|
||||||
if (header != null && header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) &&
|
if (header != null && header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) &&
|
||||||
string.Equals(header.Substring("Bearer ".Length).Trim(), _token, StringComparison.Ordinal))
|
TokenMatches(header.Substring("Bearer ".Length).Trim()))
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
string? q = req.QueryString["token"];
|
string? q = req.QueryString["token"];
|
||||||
return q != null && string.Equals(q, _token, StringComparison.Ordinal);
|
return q != null && TokenMatches(q);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private bool TokenMatches(string candidate)
|
||||||
|
=> _token != null && CryptographicOperations.FixedTimeEquals(
|
||||||
|
Encoding.UTF8.GetBytes(candidate), Encoding.UTF8.GetBytes(_token));
|
||||||
|
|
||||||
private static void Write(HttpListenerResponse res, int status, string contentType, byte[] body)
|
private static void Write(HttpListenerResponse res, int status, string contentType, byte[] body)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|
|
||||||
|
|
@ -57,7 +57,15 @@ else
|
||||||
LocalStatusServer? server = null;
|
LocalStatusServer? server = null;
|
||||||
WebRtcVideoService? video = null; // HD WebRTC video mode (opt-in); disposed in finally
|
WebRtcVideoService? video = null; // HD WebRTC video mode (opt-in); disposed in finally
|
||||||
IconService? icons = null; // item-icon decoder (GET /icon); disposed in finally
|
IconService? icons = null; // item-icon decoder (GET /icon); disposed in finally
|
||||||
if (cfg.ServeHttp)
|
if (cfg.ServeHttp && string.IsNullOrWhiteSpace(cfg.ServeToken))
|
||||||
|
{
|
||||||
|
// Same rule as DrakBot's remote: no token, no server, loopback included. The server can show
|
||||||
|
// the game screens, click in them and close clients.
|
||||||
|
AgentLog.Warn("ServeHttp is on but ServeToken is empty, so the status server stays off.");
|
||||||
|
AgentLog.Warn($"Set \"ServeToken\" in {configPath} and restart the agent. Use the same token as your");
|
||||||
|
AgentLog.Warn("DrakBot remote and one DrakRemote entry shows both.");
|
||||||
|
}
|
||||||
|
else if (cfg.ServeHttp)
|
||||||
{
|
{
|
||||||
string? commandDir = cfg.EnableRemoteControl ? Path.Combine(cfg.StatusDirectory, "commands") : null;
|
string? commandDir = cfg.EnableRemoteControl ? Path.Combine(cfg.StatusDirectory, "commands") : null;
|
||||||
VideoSocketService? videoSocket = null;
|
VideoSocketService? videoSocket = null;
|
||||||
|
|
|
||||||
|
|
@ -25,8 +25,9 @@
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<!-- Screen-stream capture (GDI BitBlt + JPEG encode). Windows-only; the agent is net*-windows. -->
|
<!-- Screen-stream capture (GDI BitBlt + JPEG encode). Windows-only; the agent is net*-windows. -->
|
||||||
<PackageReference Include="System.Drawing.Common" Version="9.0.0" />
|
<PackageReference Include="System.Drawing.Common" Version="9.0.0" />
|
||||||
<!-- WebRTC HD video mode: pure-managed RTCPeerConnection + H.264 RTP packetisation (proven in the spike). -->
|
<!-- WebRTC HD video mode: pure-managed RTCPeerConnection + H.264 RTP packetisation (proven in the spike).
|
||||||
<PackageReference Include="SIPSorcery" Version="8.0.14" />
|
10.0.14 is the floor: it fixes GHSA-jwjp-4649-v8jp (SCTP SACK) and GHSA-28gm-jrmw-xx93 (RTP/STUN). -->
|
||||||
|
<PackageReference Include="SIPSorcery" Version="10.0.14" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|
|
||||||
|
|
@ -56,6 +56,7 @@ MUTATOR_DELEGATES = {
|
||||||
"_eventStackableMerge", "_addTextToScroll",
|
"_eventStackableMerge", "_addTextToScroll",
|
||||||
"_setAutoRun", "_turnToHeading", "_stopCompletely", "_setMotion",
|
"_setAutoRun", "_turnToHeading", "_stopCompletely", "_setMotion",
|
||||||
"_changeCombatMode",
|
"_changeCombatMode",
|
||||||
|
"_sendShopEvent", # VendorTrade: gmVendorUI::SendShopEvent (vendor buy/sell + busy count)
|
||||||
}
|
}
|
||||||
GATE = "MainThreadGuard.IsOnMainThread"
|
GATE = "MainThreadGuard.IsOnMainThread"
|
||||||
ENQUEUE = "AcMainThreadQueue.Enqueue"
|
ENQUEUE = "AcMainThreadQueue.Enqueue"
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue