Snapshot for release 2026.10.13.1 (internal 90a2f4a)
This commit is contained in:
parent
b0f9d74b21
commit
1d86acdf27
218 changed files with 24019 additions and 1517 deletions
74
src/RynthCore.Engine/Compatibility/AcKeyboardFocus.cs
Normal file
74
src/RynthCore.Engine/Compatibility/AcKeyboardFocus.cs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/AcKeyboardFocus.cs
|
||||
//
|
||||
// "Is the player typing into one of AC's own text boxes?" - for the user
|
||||
// hotkeys (Hotkeys/HotkeyService.cs), which must never fire while the chat
|
||||
// entry (or a quantity box, a name field...) has the keyboard.
|
||||
//
|
||||
// Evidence (AC client decompile, C:\Projects\GhidraTools\decompiled):
|
||||
// UIElementManager::SetFocusElement (0x0045B970) keeps the element with the
|
||||
// keyboard focus at manager +0x328 (tells the old one it lost focus with
|
||||
// element message 0x2F / vtable +0xB4, the new one with 0x2F / +0xB0).
|
||||
// UIElementManager::KeyPressEvent (0x0045C3E0) and ::ActionHandler (0x0045CD80)
|
||||
// offer every key to +0x328 first (then +0x32C) and only broadcast it to the
|
||||
// game (movement, shortcuts) when that element doesn't take it: a non-zero
|
||||
// +0x328 is the element typed keys go to.
|
||||
// UIElement::TakeFocus (0x004602C0) sets it; UIElement::Deactivate (0x00461E30)
|
||||
// and UIElement::RelinquishFocus (0x00461EC0) clear it to 0.
|
||||
// Only the pointer is read (never dereferenced on the key path). The manager is
|
||||
// UiElementHooks.Manager (the tooltip hooks' `this`, as AcMouseOver uses); no
|
||||
// manager = unknown, and the hotkeys then fire only for Ctrl/Alt/F-key combos.
|
||||
//
|
||||
// Threads: AC's main thread (the WndProc and EndScene run there).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static unsafe class AcKeyboardFocus
|
||||
{
|
||||
private const int MgrFocusElement = 0x328;
|
||||
private const int ElementIdOffset = 0x2E4;
|
||||
|
||||
/// <summary>The element with AC's keyboard focus (0 = none), or null when AC's UI manager isn't readable.</summary>
|
||||
public static IntPtr? FocusElement()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread()) return null;
|
||||
IntPtr mgr = UiElementHooks.Manager;
|
||||
if (mgr == IntPtr.Zero || !ClientObjectHooks.IsReadableSpan(mgr + MgrFocusElement, 4)) return null;
|
||||
return *(IntPtr*)(mgr + MgrFocusElement);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True: an AC text box has the keyboard; false: none; null: unknown.</summary>
|
||||
public static bool? HasTextFocus()
|
||||
{
|
||||
IntPtr? e = FocusElement();
|
||||
return e == null ? null : e.Value != IntPtr.Zero;
|
||||
}
|
||||
|
||||
/// <summary>For /rc hotkey status: AC's focus element and its id.</summary>
|
||||
public static string Describe()
|
||||
{
|
||||
IntPtr? e = FocusElement();
|
||||
if (e == null)
|
||||
return UiElementHooks.Manager == IntPtr.Zero
|
||||
? "AC keyboard focus: unknown (AC's UI manager not seen yet: the tooltip hooks are off or haven't run)."
|
||||
: "AC keyboard focus: unknown (not readable).";
|
||||
if (e.Value == IntPtr.Zero) return "AC keyboard focus: none (keys go to the game).";
|
||||
uint id = 0;
|
||||
try
|
||||
{
|
||||
if (ClientObjectHooks.IsReadableSpan(e.Value + ElementIdOffset, 4)) id = *(uint*)(e.Value + ElementIdOffset);
|
||||
}
|
||||
catch { }
|
||||
return $"AC keyboard focus: element 0x{e.Value.ToInt64():X8} id 0x{id:X8} (typing: hotkeys held back).";
|
||||
}
|
||||
}
|
||||
|
|
@ -152,6 +152,13 @@ internal static class AcMainThreadQueue
|
|||
// send like DropItem; in the ring so a close queued before the next corpse's UseObject
|
||||
// goes out first, in the same drain. A = container id.
|
||||
CloseContainer,
|
||||
// v82 SalvageDirect (2026-10-12): CM_Inventory::Event_CreateTinkeringTool (the 0x027D salvage
|
||||
// game action, without the panel). An inventory send like DropItem. The item list doesn't fit
|
||||
// the four slots: A = the UST, B = the index of the list in _salvageDirectLists.
|
||||
SalvageDirect,
|
||||
// v83 RemoveClientObject (2026-10-12): drop a ghost creature from the client
|
||||
// (DeleteObjectHooks.RemoveNow re-checks on the main thread).
|
||||
RemoveClientObject,
|
||||
}
|
||||
|
||||
// Four payload slots cover every routed action (the 4th was added for
|
||||
|
|
@ -246,6 +253,35 @@ internal static class AcMainThreadQueue
|
|||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Stops and cancels: the teardown group that still runs after a world transition (every
|
||||
/// other entry queued during one is dropped). Never dropped as stale either.
|
||||
/// </summary>
|
||||
private static bool IsTeardown(in Entry e) => IsTeardownKind(e.Kind, e.A, e.B);
|
||||
|
||||
/// <summary>
|
||||
/// The ONE teardown predicate: the enqueue side (ActionRing admission, the teardown reserve)
|
||||
/// and the drain side (which entries survive a world transition) both ask it.
|
||||
/// </summary>
|
||||
internal static bool IsTeardownKind(ActionKind kind, uint a, uint b) => kind switch
|
||||
{
|
||||
ActionKind.SetAutoRun => a == 0,
|
||||
ActionKind.SetMotion => b == 0,
|
||||
ActionKind.StopMovement or ActionKind.StopCompletely or ActionKind.CancelAttack
|
||||
or ActionKind.CloseContainer => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
// World-transition drops: counted, and folded into the rate-limited stale summary line.
|
||||
private static long _transitionDropped;
|
||||
public static long TransitionDroppedCount => Interlocked.Read(ref _transitionDropped);
|
||||
|
||||
private static void NoteTransitionDrop(string what, long ageMs)
|
||||
{
|
||||
Interlocked.Increment(ref _transitionDropped);
|
||||
NoteStale(what + " (queued during a death/portal/teleport)", ageMs, dropped: true);
|
||||
}
|
||||
|
||||
private static string Describe(in Entry e) => e.Kind switch
|
||||
{
|
||||
ActionKind.SetAutoRun => e.A != 0 ? "SetAutoRun(on)" : "SetAutoRun(off)",
|
||||
|
|
@ -256,38 +292,64 @@ internal static class AcMainThreadQueue
|
|||
_ => e.Kind.ToString(),
|
||||
};
|
||||
|
||||
// The ring (ActionRing: storage, FIFO, admission). 256 entries, the top 32 for teardown
|
||||
// only, so a ring a bot filled with starts still takes its stops and cancels.
|
||||
private const int Capacity = 256; // power of two
|
||||
private const int Mask = Capacity - 1;
|
||||
private static readonly Entry[] _slots = new Entry[Capacity];
|
||||
private static readonly object _producerLock = new();
|
||||
|
||||
// Monotonic counters. Producers advance _tail under _producerLock; the sole
|
||||
// consumer (main thread) advances _head.
|
||||
private static int _head;
|
||||
private static int _tail;
|
||||
private const int TeardownReserve = 32;
|
||||
private static readonly ActionRing<Entry> _ring = new(Capacity, TeardownReserve);
|
||||
private static long _dropped;
|
||||
private static long _transitionRejected;
|
||||
|
||||
/// <summary>Entries refused because the ring was full (a running total; the heartbeat's qdrop).</summary>
|
||||
public static long DroppedCount => Interlocked.Read(ref _dropped);
|
||||
|
||||
/// <summary>Non-teardown entries refused while the player was in a world transition.</summary>
|
||||
public static long TransitionRejectedCount => Interlocked.Read(ref _transitionRejected);
|
||||
|
||||
// -- The mutator gate ----------------------------------------------------------
|
||||
// Every AC-mutating helper (ClientHelperHooks, CombatActionHooks, MovementActionHooks,
|
||||
// CommandInterpreterHooks, ClientCombatHooks, PlayerPhysicsHooks, PlayerTrade,
|
||||
// PlayerTraining) opens with the same line:
|
||||
// if (AcMainThreadQueue.MustQueue(teardown: <is this a stop/cancel>)) return Enqueue...;
|
||||
// Off AC's main thread it queues (as always). ON the main thread it also queues while a
|
||||
// world transition holds the drains, unless it is being called BY a drain (IsDraining)
|
||||
// or is teardown: render-thread host actions (ImGui panels, the EndScene plugin calls)
|
||||
// used to run straight into a world AC was tearing down, around the gate. The queue
|
||||
// then refuses or holds it like any other queued work (WorldTransitionState).
|
||||
private static int _drainDepth; // AC main thread only
|
||||
|
||||
/// <summary>AC main thread only: a drain is dispatching queued work right now.</summary>
|
||||
public static bool IsDraining => _drainDepth > 0;
|
||||
|
||||
/// <summary>AC main thread only: a direct call now would run into a world transition.</summary>
|
||||
public static bool ShouldDefer() => !IsDraining && PlayerLifecycleLog.HoldQueuedWork(NowMs);
|
||||
|
||||
/// <summary>
|
||||
/// The one gate every mutator opens with: true = queue instead of calling AC now.
|
||||
/// <paramref name="teardown"/>: a stop or cancel (IsTeardownKind), which runs at once on
|
||||
/// the main thread even in a transition.
|
||||
/// </summary>
|
||||
public static bool MustQueue(bool teardown) =>
|
||||
MutatorGate.MustQueue(MainThreadGuard.IsOnMainThread(), teardown, IsDraining, HoldNow);
|
||||
|
||||
// Cached (no allocation per call): main thread only, asked only by MutatorGate on it.
|
||||
private static readonly Func<bool> HoldNow = () => PlayerLifecycleLog.HoldQueuedWork(NowMs);
|
||||
|
||||
private static bool Enqueue(ActionKind kind, uint a, uint b, uint c, uint d = 0)
|
||||
{
|
||||
lock (_producerLock)
|
||||
{
|
||||
int tail = _tail;
|
||||
int head = Volatile.Read(ref _head);
|
||||
if (tail - head >= Capacity)
|
||||
{
|
||||
// Full. Drop rather than block or fall back to an off-thread AC
|
||||
// mutation — a dropped movement/attack tick self-corrects on the
|
||||
// next bot tick; an off-thread mutation can crash the client.
|
||||
Interlocked.Increment(ref _dropped);
|
||||
return false;
|
||||
}
|
||||
|
||||
_slots[tail & Mask] = new Entry(kind, a, b, c, d, NowMs, Volatile.Read(ref _loginEpoch));
|
||||
Volatile.Write(ref _tail, tail + 1);
|
||||
return true;
|
||||
}
|
||||
bool teardown = IsTeardownKind(kind, a, b);
|
||||
// Dead / portaling / settling: a start queued now would be dropped when the window
|
||||
// ends anyway (WorldTransitionState), so it is refused here and never takes a slot a
|
||||
// stop needs. Stops and cancels are always taken (the reserve keeps room for them).
|
||||
var r = _ring.TryEnqueue(new Entry(kind, a, b, c, d, NowMs, Volatile.Read(ref _loginEpoch)),
|
||||
teardown, PlayerLifecycleLog.InWorldTransition);
|
||||
if (r == ActionRing<Entry>.Admit.Queued) return true;
|
||||
// Full: drop rather than block or fall back to an off-thread AC mutation - a dropped
|
||||
// movement/attack tick self-corrects on the next bot tick; an off-thread mutation can
|
||||
// crash the client.
|
||||
if (r == ActionRing<Entry>.Admit.Full) Interlocked.Increment(ref _dropped);
|
||||
else Interlocked.Increment(ref _transitionRejected);
|
||||
return false;
|
||||
}
|
||||
|
||||
// ── Typed enqueue helpers (called by the public action methods when they
|
||||
|
|
@ -336,19 +398,33 @@ internal static class AcMainThreadQueue
|
|||
// CommandInterpreter turn, which would change the steering behaviour.
|
||||
private static int _directHeadingPending;
|
||||
private static uint _directHeadingBits;
|
||||
private static long _directHeadingAt;
|
||||
|
||||
public static bool EnqueueDirectHeading(float headingDegrees)
|
||||
{
|
||||
Volatile.Write(ref _directHeadingBits, BitConverter.SingleToUInt32Bits(headingDegrees));
|
||||
Interlocked.Exchange(ref _directHeadingAt, NowMs);
|
||||
Volatile.Write(ref _directHeadingPending, 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Main thread only (from Drain). Same order as the pre-queue code: the direct
|
||||
// snap first, the CommandInterpreter turn only when there is no player.
|
||||
// World transition: the pending heading is held; once the window ends a heading set
|
||||
// during it is stale (the bot steers again from where it landed) and is dropped.
|
||||
private static void DrainDirectHeading()
|
||||
{
|
||||
if (Volatile.Read(ref _directHeadingPending) == 0) return;
|
||||
long now = NowMs;
|
||||
long at = Interlocked.Read(ref _directHeadingAt);
|
||||
WorldTransitionState.Verdict v = PlayerLifecycleLog.DecideQueued(now, at, teardown: false);
|
||||
if (v == WorldTransitionState.Verdict.Hold) return;
|
||||
if (Interlocked.Exchange(ref _directHeadingPending, 0) == 0) return;
|
||||
if (v == WorldTransitionState.Verdict.Drop)
|
||||
{
|
||||
NoteTransitionDrop("heading", now - at);
|
||||
return;
|
||||
}
|
||||
float heading = BitConverter.UInt32BitsToSingle(Volatile.Read(ref _directHeadingBits));
|
||||
try
|
||||
{
|
||||
|
|
@ -371,18 +447,25 @@ internal static class AcMainThreadQueue
|
|||
// selects mid-gesture too). Lock-free and allocation-free.
|
||||
private static int _overlaySelectPending;
|
||||
private static uint _overlaySelectId;
|
||||
private static long _overlaySelectAt;
|
||||
|
||||
public static bool EnqueueOverlaySelect(uint objectId)
|
||||
{
|
||||
if (objectId == 0) return false;
|
||||
Volatile.Write(ref _overlaySelectId, objectId);
|
||||
Interlocked.Exchange(ref _overlaySelectAt, NowMs);
|
||||
Volatile.Write(ref _overlaySelectPending, 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Main thread only (from Drain).
|
||||
// Main thread only (from Drain). World transition: held, and kept when the window ends:
|
||||
// it is the user's own click, and SelectFromOverlay re-checks the object still exists.
|
||||
private static void DrainOverlaySelect()
|
||||
{
|
||||
if (Volatile.Read(ref _overlaySelectPending) == 0) return;
|
||||
if (PlayerLifecycleLog.DecideQueued(NowMs, Interlocked.Read(ref _overlaySelectAt), teardown: true)
|
||||
== WorldTransitionState.Verdict.Hold)
|
||||
return;
|
||||
if (Interlocked.Exchange(ref _overlaySelectPending, 0) == 0) return;
|
||||
uint id = Volatile.Read(ref _overlaySelectId);
|
||||
try { ClientHelperHooks.SelectFromOverlay(id); }
|
||||
|
|
@ -449,6 +532,48 @@ internal static class AcMainThreadQueue
|
|||
public static bool EnqueueSalvageExecute() =>
|
||||
Enqueue(ActionKind.SalvageExecute, 0, 0, 0);
|
||||
|
||||
// ── Salvage-without-panel item lists (v82) ──────────────────────────────────
|
||||
// A SalvageDirect entry carries its item list here: the producer copies the ids into a fresh
|
||||
// array and parks it in a free slot (under _salvageDirectLock), the ring entry carries the slot
|
||||
// index, and the drain takes it back with one Interlocked.Exchange (lock-free, no allocation on
|
||||
// the main thread). Eight slots: the bot has one request in flight at a time; a full set refuses.
|
||||
private const int SalvageDirectSlots = 8;
|
||||
private static readonly uint[]?[] _salvageDirectLists = new uint[]?[SalvageDirectSlots];
|
||||
private static int _salvageDirectNext;
|
||||
// Serializes slot claims (the ring has its own lock since ActionRing<T>, PR #8).
|
||||
private static readonly object _salvageDirectLock = new();
|
||||
|
||||
public static bool EnqueueSalvageDirect(uint toolId, uint[] itemIds)
|
||||
{
|
||||
if (toolId == 0 || itemIds == null || itemIds.Length == 0) return false;
|
||||
uint[] copy = (uint[])itemIds.Clone();
|
||||
lock (_salvageDirectLock)
|
||||
{
|
||||
for (int k = 0; k < SalvageDirectSlots; k++)
|
||||
{
|
||||
int i = (_salvageDirectNext + k) % SalvageDirectSlots;
|
||||
if (Volatile.Read(ref _salvageDirectLists[i]) != null) continue;
|
||||
Volatile.Write(ref _salvageDirectLists[i], copy);
|
||||
if (!Enqueue(ActionKind.SalvageDirect, toolId, (uint)i, 0))
|
||||
{
|
||||
Volatile.Write(ref _salvageDirectLists[i], null);
|
||||
return false;
|
||||
}
|
||||
_salvageDirectNext = (i + 1) % SalvageDirectSlots;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Interlocked.Increment(ref _dropped);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Main thread: takes the list a SalvageDirect entry parked (null if none).</summary>
|
||||
private static uint[]? TakeSalvageDirectList(uint slot) =>
|
||||
slot < SalvageDirectSlots ? Interlocked.Exchange(ref _salvageDirectLists[slot], null) : null;
|
||||
|
||||
public static bool EnqueueRemoveClientObject(uint objectId) =>
|
||||
Enqueue(ActionKind.RemoveClientObject, objectId, 0, 0);
|
||||
|
||||
public static bool EnqueueSetSelectedObject(uint objectId) =>
|
||||
Enqueue(ActionKind.SetSelectedObject, objectId, 0, 0);
|
||||
|
||||
|
|
@ -491,6 +616,14 @@ internal static class AcMainThreadQueue
|
|||
private static long _drainDeferSinceMs;
|
||||
|
||||
public static void Drain()
|
||||
{
|
||||
// IsDraining: the helpers this dispatches run their AC call directly (MustQueue).
|
||||
_drainDepth++;
|
||||
try { DrainCore(); }
|
||||
finally { _drainDepth--; }
|
||||
}
|
||||
|
||||
private static void DrainCore()
|
||||
{
|
||||
if (_disarmed)
|
||||
{
|
||||
|
|
@ -524,14 +657,23 @@ internal static class AcMainThreadQueue
|
|||
// and 0xC8 appraisal sends too, contradicting that invariant. Each
|
||||
// drains only while ITS OWN queue is non-empty, so moving them here
|
||||
// costs nothing when they're empty (the common case).
|
||||
// World transition gate (dead / portal / landblock jump, WorldTransitionState): AC is
|
||||
// tearing objects down and loading new ones, so nothing queued that mutates the game
|
||||
// runs now. Chat output (AC's own text window) and the char-select service still do.
|
||||
long gateNow = NowMs;
|
||||
bool holding = PlayerLifecycleLog.HoldQueuedWork(gateNow);
|
||||
|
||||
DrainChat();
|
||||
DrainChatCommands();
|
||||
if (!holding) DrainChatCommands(); // held: their own 15 s age limit still applies
|
||||
DrainRequestIds();
|
||||
DrainQueryHealth();
|
||||
// Vendor buy/sell: a packet send through the client's own SendShopEvent, not a
|
||||
// motion, so it sits with the non-gesture queues above. Also polls whether the
|
||||
// vendor window is still open. Idle fast path when no vendor is open.
|
||||
try { VendorTrade.MainThreadTick(); } catch { }
|
||||
if (!holding)
|
||||
{
|
||||
try { VendorTrade.MainThreadTick(); } catch { }
|
||||
}
|
||||
// Char-select service: publishes the UIFlow mode, runs a pending auto-login
|
||||
// LogOnCharacter request and snapshots the native character list (throttled).
|
||||
// Pre-login this runs from the Client::UseTime drain (EndScene is not hooked
|
||||
|
|
@ -541,14 +683,19 @@ internal static class AcMainThreadQueue
|
|||
// Plugin heading snap (coalesced slot). Before the ring and its gesture
|
||||
// defer: the pre-queue raw write landed immediately, gesture or not, and
|
||||
// ahead of the SetAutoRun a nav tick queues right after it. Keep both.
|
||||
// Both are latest-value slots (a heading, a select): held through a world transition,
|
||||
// then decided by their own drains (a stale heading dropped, a user's select kept).
|
||||
DrainDirectHeading();
|
||||
|
||||
// Overlay click-to-select (Radar dot / nameplate click): also before the
|
||||
// gesture defer, so a click selects at once even while the bot swings.
|
||||
DrainOverlaySelect();
|
||||
|
||||
int head = _head; // only the main thread writes _head
|
||||
int tail = Volatile.Read(ref _tail);
|
||||
// In a world transition the ring is held whole (FIFO kept): nothing runs, nothing is
|
||||
// dropped yet. Once it ends, the loop below drops what was queued during it, except
|
||||
// stops and cancels, which run in order as one teardown group.
|
||||
if (holding)
|
||||
return;
|
||||
|
||||
// ── Gesture-phase serialization (extends the 56e6946 anim-walk guard
|
||||
// to the whole ring) ─────────────────────────────────────────────────
|
||||
|
|
@ -562,7 +709,7 @@ internal static class AcMainThreadQueue
|
|||
// drop: dropping arbitrary item/movement actions desyncs the bot far
|
||||
// worse than a late injection, and the pre-2026-06-12 behavior was
|
||||
// "always inject" anyway, so proceeding past the cap is never worse).
|
||||
if (head != tail)
|
||||
if (_ring.Count > 0)
|
||||
{
|
||||
// In milliseconds (was 250 Drain calls: 2 s to over 10 s depending on the frame rate).
|
||||
if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight)
|
||||
|
|
@ -576,16 +723,22 @@ internal static class AcMainThreadQueue
|
|||
}
|
||||
long runAt = NowMs;
|
||||
int epochNow = Volatile.Read(ref _loginEpoch);
|
||||
while (head != tail)
|
||||
// Bounded to what is queued now plus a capacity's worth: an action that re-queues
|
||||
// itself can never spin the main thread.
|
||||
int budget = Capacity * 2;
|
||||
while (budget-- > 0 && _ring.TryDequeue(out Entry e))
|
||||
{
|
||||
Entry e = _slots[head & Mask];
|
||||
Volatile.Write(ref _head, ++head);
|
||||
|
||||
long age = runAt - e.At;
|
||||
if (PlayerLifecycleLog.DecideQueued(runAt, e.At, IsTeardown(e)) == WorldTransitionState.Verdict.Drop)
|
||||
{
|
||||
NoteTransitionDrop(Describe(e), age);
|
||||
if (e.Kind == ActionKind.SalvageDirect) TakeSalvageDirectList(e.B); // free its list slot
|
||||
continue;
|
||||
}
|
||||
if (e.Epoch != epochNow || (age > StaleActionMs && DropsWhenStale(e)))
|
||||
{
|
||||
NoteStale(Describe(e) + (e.Epoch != epochNow ? " (queued before this login)" : ""), age, dropped: true);
|
||||
tail = Volatile.Read(ref _tail);
|
||||
if (e.Kind == ActionKind.SalvageDirect) TakeSalvageDirectList(e.B); // free its list slot
|
||||
continue;
|
||||
}
|
||||
if (age > LateActionLogMs)
|
||||
|
|
@ -673,6 +826,13 @@ internal static class AcMainThreadQueue
|
|||
case ActionKind.SalvageExecute:
|
||||
ClientHelperHooks.SalvagePanelExecute();
|
||||
break;
|
||||
case ActionKind.SalvageDirect:
|
||||
if (TakeSalvageDirectList(e.B) is uint[] salvageItems)
|
||||
ClientHelperHooks.SalvageDirect(e.A, salvageItems);
|
||||
break;
|
||||
case ActionKind.RemoveClientObject:
|
||||
DeleteObjectHooks.RemoveNow(e.A);
|
||||
break;
|
||||
case ActionKind.SetSelectedObject:
|
||||
// On the main thread now -> SetSelectedObjectId's gate is
|
||||
// satisfied and it calls AC's SetSelectedObject directly.
|
||||
|
|
@ -719,8 +879,6 @@ internal static class AcMainThreadQueue
|
|||
// not managed exceptions and won't be caught here — but these
|
||||
// now run on the correct thread, which is the whole point.)
|
||||
}
|
||||
|
||||
tail = Volatile.Read(ref _tail);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -733,22 +891,43 @@ internal static class AcMainThreadQueue
|
|||
// Kept in its OWN queue — NOT the gesture-deferred action ring above — so a backlog
|
||||
// of appraisals can never crowd out combat/movement actions or get gesture-deferred:
|
||||
// an appraisal is just a packet send and doesn't perturb AC's motion/UI state.
|
||||
private static readonly System.Collections.Generic.Queue<(uint Id, long At, int Epoch)> _requestIdQueue = new();
|
||||
private static readonly object _requestIdLock = new();
|
||||
// A request for an object that already has one pending is merged into it, as the
|
||||
// QueryHealth slot does: the one appraisal reply answers every caller (PendingIdQueue).
|
||||
private const int MaxRequestIdQueue = 256;
|
||||
private static readonly PendingIdQueue _requestIdQueue = new(MaxRequestIdQueue);
|
||||
private static readonly object _requestIdLock = new();
|
||||
// Merge only into an entry the drain will still send: half the stale limit leaves room
|
||||
// for a drain that runs late (a stalled main thread).
|
||||
private const long RequestIdMergeMaxAgeMs = RequestIdMaxAgeMs / 2;
|
||||
|
||||
// Pump/Timer-thread enqueue. Drops (returns false) if the queue is full.
|
||||
public static bool EnqueueRequestId(uint objectId)
|
||||
/// <summary>RequestId calls absorbed by an already-pending request for the same object.</summary>
|
||||
public static long RequestIdMergedCount
|
||||
{
|
||||
get { lock (_requestIdLock) return _requestIdQueue.MergedTotal; }
|
||||
}
|
||||
|
||||
// Pump/Timer-thread enqueue. Drops (returns false) if the queue is full. A request for an
|
||||
// object already waiting returns true without queueing a second send.
|
||||
// <paramref name="who"/> rides with the entry so the drain can mark the real send as the
|
||||
// engine's (Net/IdRequester.cs); a merge keeps the first requester.
|
||||
public static bool EnqueueRequestId(uint objectId, Net.IdRequester who = Net.IdRequester.None)
|
||||
{
|
||||
if (objectId == 0) return false;
|
||||
// Dead / portaling / settling: an appraisal queued now is dropped when the window
|
||||
// ends, so it is refused here (the caller sees false and may ask again later). Nor
|
||||
// does a request merge into an entry from before the last held drain: that entry is
|
||||
// dropped when the drain reaches it, and the merged request would go with it.
|
||||
if (PlayerLifecycleLog.InWorldTransition) return false;
|
||||
long mergeOnlyAfter = PlayerLifecycleLog.LastBlockedMs;
|
||||
lock (_requestIdLock)
|
||||
{
|
||||
if (_requestIdQueue.Count >= MaxRequestIdQueue)
|
||||
PendingIdQueue.Result r = _requestIdQueue.Enqueue(objectId, NowMs, Volatile.Read(ref _loginEpoch),
|
||||
RequestIdMergeMaxAgeMs, mergeOnlyAfter, (byte)who);
|
||||
if (r == PendingIdQueue.Result.Full)
|
||||
{
|
||||
Interlocked.Increment(ref _dropped);
|
||||
return false;
|
||||
}
|
||||
_requestIdQueue.Enqueue((objectId, NowMs, Volatile.Read(ref _loginEpoch)));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -760,22 +939,42 @@ internal static class AcMainThreadQueue
|
|||
// Bounded like DrainChatCommands: a re-queue never spins the main thread.
|
||||
int budget;
|
||||
lock (_requestIdLock) budget = _requestIdQueue.Count;
|
||||
if (budget == 0) return;
|
||||
long now = NowMs;
|
||||
// World transition (dead / portal / landblock jump): hold every appraisal; once it
|
||||
// ends, those queued during it are dropped (WorldTransitionState).
|
||||
if (PlayerLifecycleLog.HoldQueuedWork(now)) return;
|
||||
int epoch = Volatile.Read(ref _loginEpoch);
|
||||
while (budget-- > 0)
|
||||
{
|
||||
(uint Id, long At, int Epoch) item;
|
||||
PendingIdQueue.Item item;
|
||||
lock (_requestIdLock)
|
||||
{
|
||||
if (_requestIdQueue.Count == 0) return;
|
||||
item = _requestIdQueue.Dequeue();
|
||||
if (!_requestIdQueue.TryDequeue(out item)) return;
|
||||
}
|
||||
if (item.Epoch != epoch || now - item.At > RequestIdMaxAgeMs)
|
||||
{
|
||||
NoteStale($"RequestId(0x{item.Id:X8})", now - item.At, dropped: true);
|
||||
continue;
|
||||
}
|
||||
try { CombatActionHooks.RequestId(item.Id); } catch { }
|
||||
if (PlayerLifecycleLog.DecideQueued(now, item.At, teardown: false) == WorldTransitionState.Verdict.Drop)
|
||||
{
|
||||
NoteTransitionDrop($"RequestId(0x{item.Id:X8})", now - item.At);
|
||||
continue;
|
||||
}
|
||||
bool sent = false;
|
||||
try
|
||||
{
|
||||
using (Net.EngineSendMarker.Enter((Net.IdRequester)item.Source))
|
||||
sent = CombatActionHooks.RequestId(item.Id);
|
||||
}
|
||||
catch { }
|
||||
// AutoId's re-appraisal window starts at the real send, not at the queueing:
|
||||
// a request dropped here (stale, transition) leaves the object due again.
|
||||
if (sent)
|
||||
{
|
||||
try { AutoIdService.OnSent(item.Id, now); } catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -819,6 +1018,7 @@ internal static class AcMainThreadQueue
|
|||
int budget;
|
||||
lock (_queryHealthLock) budget = _queryHealthQueue.Count;
|
||||
long now = NowMs;
|
||||
if (PlayerLifecycleLog.HoldQueuedWork(now)) return; // world transition: hold
|
||||
int epoch = Volatile.Read(ref _loginEpoch);
|
||||
while (budget-- > 0)
|
||||
{
|
||||
|
|
@ -834,6 +1034,11 @@ internal static class AcMainThreadQueue
|
|||
NoteStale($"QueryHealth(0x{item.Id:X8})", now - item.At, dropped: true);
|
||||
continue;
|
||||
}
|
||||
if (PlayerLifecycleLog.DecideQueued(now, item.At, teardown: false) == WorldTransitionState.Verdict.Drop)
|
||||
{
|
||||
NoteTransitionDrop($"QueryHealth(0x{item.Id:X8})", now - item.At);
|
||||
continue;
|
||||
}
|
||||
try { CombatActionHooks.QueryHealth(item.Id); } catch { }
|
||||
}
|
||||
}
|
||||
|
|
@ -958,9 +1163,7 @@ internal static class AcMainThreadQueue
|
|||
// tick — they already handle a false return without wedging. At ~frame-rate drain
|
||||
// the slot clears within ~1 frame. This is the LAST off-thread AC mutator to be
|
||||
// marshalled, closing the off-thread object-graph corruption class at its source.
|
||||
private static int _castPending;
|
||||
private static uint _castTargetId;
|
||||
private static uint _castSpellId;
|
||||
private static readonly CastSlot _cast = new(); // writes under _castLock
|
||||
private static readonly object _castLock = new();
|
||||
|
||||
// Ticks DrainCasts has deferred the pending cast because a motion gesture was
|
||||
|
|
@ -969,30 +1172,27 @@ internal static class AcMainThreadQueue
|
|||
// plugin's no-chat-resolve machinery already retries casts that produce no
|
||||
// chat, so a drop degrades to one retry cycle, never a wedge.
|
||||
private static long _castDeferDrops;
|
||||
private static long _castQueuedAt; // TickCount64 when the pending cast was queued (2026-10-06)
|
||||
|
||||
|
||||
/// <summary>Casts dropped after deferring CastDeferTickCap ticks (stuck gesture).</summary>
|
||||
public static long CastDeferDropCount => Interlocked.Read(ref _castDeferDrops);
|
||||
|
||||
// Pump-thread enqueue. Returns false (caller retries next tick) if a cast is
|
||||
// already pending.
|
||||
// already pending, or during a world transition (CastSlot): the drain would only hold
|
||||
// it and then drop it, and the slot would refuse every newer cast meanwhile.
|
||||
public static bool EnqueueCast(uint targetId, uint spellId)
|
||||
{
|
||||
CastSlot.Admit admit;
|
||||
lock (_castLock)
|
||||
{
|
||||
if (_castPending != 0) return false;
|
||||
_castTargetId = targetId;
|
||||
_castSpellId = spellId;
|
||||
_castQueuedAt = NowMs;
|
||||
_castStopWaitNoted = false;
|
||||
_castPending = 1;
|
||||
return true;
|
||||
}
|
||||
admit = _cast.TryEnqueue(targetId, spellId, NowMs, PlayerLifecycleLog.InWorldTransition);
|
||||
if (admit == CastSlot.Admit.RejectedTransition)
|
||||
Interlocked.Increment(ref _transitionRejected);
|
||||
return admit == CastSlot.Admit.Queued;
|
||||
}
|
||||
|
||||
// Casts that waited for a movement stop queued ahead of them (counted once per cast).
|
||||
// Casts that waited for a movement stop queued ahead of them (counted once per cast;
|
||||
// the per-cast flag is CastSlot.StopWaitNoted, reset by each new cast).
|
||||
private static long _castStopWaits;
|
||||
private static bool _castStopWaitNoted;
|
||||
|
||||
/// <summary>Casts that waited one or more ticks for a stop queued ahead of them.</summary>
|
||||
public static long CastStopWaitCount => Interlocked.Read(ref _castStopWaits);
|
||||
|
|
@ -1008,29 +1208,28 @@ internal static class AcMainThreadQueue
|
|||
|
||||
/// <summary>
|
||||
/// True when the action ring holds a movement stop queued at or before <paramref name="castQueuedAt"/>.
|
||||
/// Main thread only (the ring's sole consumer). Entries are stamped under the producer lock, so
|
||||
/// their times rise from head to tail and the walk stops at the first newer one.
|
||||
/// Main thread only (the ring's sole consumer). An entry's time is taken before ActionRing's
|
||||
/// producer lock, so two producers can land slightly out of time order: the walk checks every
|
||||
/// queued entry (at most Capacity) instead of stopping at the first newer one (CastStopRules).
|
||||
/// </summary>
|
||||
private static bool StopQueuedAtOrBefore(long castQueuedAt)
|
||||
{
|
||||
int head = _head;
|
||||
int tail = Volatile.Read(ref _tail);
|
||||
for (int i = head; i != tail; i++)
|
||||
{
|
||||
ref readonly Entry e = ref _slots[i & Mask];
|
||||
if (e.At > castQueuedAt) return false;
|
||||
if (IsMovementStop(e)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
private static bool StopQueuedAtOrBefore(long castQueuedAt) =>
|
||||
CastStopRules.AnyStopAtOrBefore(_ring, castQueuedAt, static e => e.At, static e => IsMovementStop(e));
|
||||
|
||||
// Drained on AC's MAIN thread from the Client::UseTime detour (game-logic tick).
|
||||
// Re-invokes CombatActionHooks.CastSpell, which on the main thread executes the
|
||||
// cast directly (SelectItem + ClientMagicSystem::CastSpell via the SEH trampoline).
|
||||
// cast directly via the SEH trampoline (targeted: FreeHandsAndCastSpell with the target
|
||||
// passed explicitly, no SelectItem; self: ClientMagicSystem::CastSpell).
|
||||
public static void DrainCasts()
|
||||
{
|
||||
_drainDepth++;
|
||||
try { DrainCastsCore(); }
|
||||
finally { _drainDepth--; }
|
||||
}
|
||||
|
||||
private static void DrainCastsCore()
|
||||
{
|
||||
if (_disarmed) return; // engine teardown in progress
|
||||
if (Volatile.Read(ref _castPending) == 0) return; // alloc-free fast path
|
||||
if (Volatile.Read(ref _cast.Pending) == 0) return; // alloc-free fast path
|
||||
|
||||
// ── Anim-walk race guard (dump-proven 2026-06-12) ────────────────────
|
||||
// DrainCasts runs PRE-tick (selection timing), but a cast initiates a
|
||||
|
|
@ -1049,7 +1248,23 @@ internal static class AcMainThreadQueue
|
|||
// CastDeferMaxMs the cast is dropped and logged with its age. RynthAi waits up to 7 s
|
||||
// for a cast's answer before it sends another (ActionPacer), so a drop here can't
|
||||
// leave two casts in flight.
|
||||
long castAge = NowMs - Volatile.Read(ref _castQueuedAt);
|
||||
// World transition (dead / portal / landblock jump): hold the cast; a cast queued
|
||||
// during it is dropped once it ends (WorldTransitionState). Before the gesture check:
|
||||
// nothing about the player's motion is read while AC is tearing the world down.
|
||||
long nowCast = NowMs;
|
||||
long queuedAt = Volatile.Read(ref _cast.QueuedAt);
|
||||
WorldTransitionState.Verdict castVerdict = PlayerLifecycleLog.DecideQueued(nowCast, queuedAt, teardown: false);
|
||||
if (castVerdict == WorldTransitionState.Verdict.Hold)
|
||||
return;
|
||||
if (castVerdict == WorldTransitionState.Verdict.Drop)
|
||||
{
|
||||
uint droppedSpell;
|
||||
lock (_castLock) { droppedSpell = _cast.SpellId; _cast.Pending = 0; }
|
||||
NoteTransitionDrop($"CastSpell({droppedSpell})", nowCast - queuedAt);
|
||||
return;
|
||||
}
|
||||
|
||||
long castAge = nowCast - queuedAt;
|
||||
if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight)
|
||||
{
|
||||
if (castAge <= CastDeferMaxMs)
|
||||
|
|
@ -1057,7 +1272,7 @@ internal static class AcMainThreadQueue
|
|||
// Gesture stuck past the deadline — drop the cast instead of injecting
|
||||
// into a wedged motion graph; the plugin retries via no-chat-resolve.
|
||||
uint dropped;
|
||||
lock (_castLock) { dropped = _castSpellId; _castPending = 0; }
|
||||
lock (_castLock) { dropped = _cast.SpellId; _cast.Pending = 0; }
|
||||
Interlocked.Increment(ref _castDeferDrops);
|
||||
NoteStale($"CastSpell({dropped}) behind a gesture", castAge, dropped: true);
|
||||
return;
|
||||
|
|
@ -1070,13 +1285,13 @@ internal static class AcMainThreadQueue
|
|||
// locomotion still on, and the queued stops followed as extra MoveToStates. Wait (at
|
||||
// most until EndScene drains the ring, about one frame; the ring's own gesture defer
|
||||
// is shorter than CastDeferMaxMs) while one is queued; past the limit cast anyway.
|
||||
if (StopQueuedAtOrBefore(Volatile.Read(ref _castQueuedAt)))
|
||||
if (StopQueuedAtOrBefore(queuedAt))
|
||||
{
|
||||
if (castAge <= CastDeferMaxMs)
|
||||
{
|
||||
if (!_castStopWaitNoted)
|
||||
if (!_cast.StopWaitNoted)
|
||||
{
|
||||
_castStopWaitNoted = true;
|
||||
_cast.StopWaitNoted = true;
|
||||
Interlocked.Increment(ref _castStopWaits);
|
||||
try { Net.FlightRecorder.Mark(Net.FlightMark.Note, text: "cast waits for a movement stop queued before it"); } catch { }
|
||||
}
|
||||
|
|
@ -1085,7 +1300,7 @@ internal static class AcMainThreadQueue
|
|||
}
|
||||
|
||||
// ── The stop goes a server answer ahead of the cast (2026-10-12, PreCastStopRules) ──
|
||||
long castStamp = Volatile.Read(ref _castQueuedAt);
|
||||
long castStamp = queuedAt;
|
||||
if (_preStopFor != castStamp) { _preStopFor = castStamp; _preStopSent = false; }
|
||||
long nowMs = NowMs;
|
||||
PreCastStep step = PreCastStopRules.Decide(
|
||||
|
|
@ -1122,10 +1337,10 @@ internal static class AcMainThreadQueue
|
|||
uint target, spell;
|
||||
lock (_castLock)
|
||||
{
|
||||
if (_castPending == 0) return;
|
||||
target = _castTargetId;
|
||||
spell = _castSpellId;
|
||||
_castPending = 0;
|
||||
if (_cast.Pending == 0) return;
|
||||
target = _cast.TargetId;
|
||||
spell = _cast.SpellId;
|
||||
_cast.Pending = 0;
|
||||
}
|
||||
if (castAge > LateActionLogMs)
|
||||
NoteStale($"CastSpell({spell})", castAge, dropped: false);
|
||||
|
|
|
|||
123
src/RynthCore.Engine/Compatibility/ActionRing.cs
Normal file
123
src/RynthCore.Engine/Compatibility/ActionRing.cs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/ActionRing.cs
|
||||
//
|
||||
// The storage and admission policy of AcMainThreadQueue's action ring: a fixed ring of
|
||||
// entries, many producers (under one lock), ONE consumer (AC's main thread), FIFO.
|
||||
//
|
||||
// Admission: during a world transition the drain holds the ring
|
||||
// (WorldTransitionState), and a bot keeps queueing starts at ~60 Hz meanwhile, so the
|
||||
// ring used to fill and then refuse the stops and cancels that matter most. Now:
|
||||
// - while the caller says a transition is on, non-teardown entries are refused at
|
||||
// once (they would be dropped when it ends anyway);
|
||||
// - the top TeardownReserve slots only take teardown entries (stops and cancels), so a
|
||||
// ring filled by starts before the transition was seen still takes a stop.
|
||||
// What counts as teardown is the caller's (AcMainThreadQueue.IsTeardownKind, the same
|
||||
// predicate its drain uses).
|
||||
//
|
||||
// Pure: no engine state. Compiled into tools\EngineRobustnessTests.
|
||||
// ============================================================================
|
||||
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal sealed class ActionRing<T> where T : struct
|
||||
{
|
||||
public enum Admit
|
||||
{
|
||||
Queued,
|
||||
/// <summary>No room (for a non-teardown entry: none below the teardown reserve).</summary>
|
||||
Full,
|
||||
/// <summary>A world transition is on and the entry is not teardown.</summary>
|
||||
RejectedTransition,
|
||||
}
|
||||
|
||||
private readonly T[] _slots;
|
||||
private readonly int _mask;
|
||||
private readonly int _reserve;
|
||||
private readonly object _lock = new();
|
||||
// Monotonic counters. Producers advance _tail under _lock; the sole consumer advances _head.
|
||||
private int _head;
|
||||
private int _tail;
|
||||
|
||||
public ActionRing(int capacityPowerOfTwo, int teardownReserve)
|
||||
{
|
||||
if (capacityPowerOfTwo <= 0 || (capacityPowerOfTwo & (capacityPowerOfTwo - 1)) != 0)
|
||||
throw new System.ArgumentOutOfRangeException(nameof(capacityPowerOfTwo));
|
||||
if (teardownReserve < 0 || teardownReserve >= capacityPowerOfTwo)
|
||||
throw new System.ArgumentOutOfRangeException(nameof(teardownReserve));
|
||||
_slots = new T[capacityPowerOfTwo];
|
||||
_mask = capacityPowerOfTwo - 1;
|
||||
_reserve = teardownReserve;
|
||||
}
|
||||
|
||||
public int Capacity => _slots.Length;
|
||||
public int TeardownReserve => _reserve;
|
||||
|
||||
/// <summary>Entries waiting (any thread; a snapshot).</summary>
|
||||
public int Count => Volatile.Read(ref _tail) - Volatile.Read(ref _head);
|
||||
|
||||
/// <summary>Producer side, any thread.</summary>
|
||||
public Admit TryEnqueue(in T entry, bool teardown, bool inTransition)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (inTransition && !teardown)
|
||||
return Admit.RejectedTransition;
|
||||
int tail = _tail;
|
||||
int used = tail - Volatile.Read(ref _head);
|
||||
int limit = teardown ? _slots.Length : _slots.Length - _reserve;
|
||||
if (used >= limit)
|
||||
return Admit.Full;
|
||||
_slots[tail & _mask] = entry;
|
||||
Volatile.Write(ref _tail, tail + 1);
|
||||
return Admit.Queued;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Consumer only: the oldest entry, without removing it.</summary>
|
||||
public bool TryPeek(out T entry)
|
||||
{
|
||||
int head = _head;
|
||||
if (head == Volatile.Read(ref _tail))
|
||||
{
|
||||
entry = default;
|
||||
return false;
|
||||
}
|
||||
entry = _slots[head & _mask];
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Consumer only: the entry <paramref name="offset"/> places behind the oldest (0 = the
|
||||
/// oldest), without removing anything. False past the newest entry.
|
||||
/// </summary>
|
||||
public bool TryPeekAt(int offset, out T entry)
|
||||
{
|
||||
int head = _head;
|
||||
if (offset < 0 || offset >= Volatile.Read(ref _tail) - head)
|
||||
{
|
||||
entry = default;
|
||||
return false;
|
||||
}
|
||||
entry = _slots[(head + offset) & _mask];
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Consumer only: removes the oldest entry (after a successful TryPeek).</summary>
|
||||
public void Pop()
|
||||
{
|
||||
int head = _head;
|
||||
if (head == Volatile.Read(ref _tail)) return;
|
||||
_slots[head & _mask] = default;
|
||||
Volatile.Write(ref _head, head + 1);
|
||||
}
|
||||
|
||||
/// <summary>Consumer only: removes and returns the oldest entry.</summary>
|
||||
public bool TryDequeue(out T entry)
|
||||
{
|
||||
if (!TryPeek(out entry)) return false;
|
||||
Pop();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
87
src/RynthCore.Engine/Compatibility/AddressSpace.cs
Normal file
87
src/RynthCore.Engine/Compatibility/AddressSpace.cs
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/AddressSpace.cs
|
||||
//
|
||||
// Free user address space and the LARGEST free block, in MB. acclient is 32-bit, so
|
||||
// "out of memory" usually means fragmentation, not exhaustion: 300 MB may be free in
|
||||
// total while no single block can take a 16 MB allocation. vafree alone (the
|
||||
// heartbeat's GlobalMemoryStatusEx total) cannot show that; valargest can.
|
||||
//
|
||||
// Walks the regions with VirtualQuery (a few thousand calls, no allocation). Any
|
||||
// thread; the heartbeat thread calls it once a second and PluginManager around each
|
||||
// plugin load and unload during a reload. Compiled into tools\EngineRobustnessTests.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class AddressSpace
|
||||
{
|
||||
private const uint MEM_FREE = 0x10000;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct MEMORY_BASIC_INFORMATION
|
||||
{
|
||||
public nuint BaseAddress;
|
||||
public nuint AllocationBase;
|
||||
public uint AllocationProtect;
|
||||
public nuint RegionSize; // sequential layout pads after the uint on x64
|
||||
public uint State;
|
||||
public uint Protect;
|
||||
public uint Type;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern nuint VirtualQuery(nuint lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, nuint dwLength);
|
||||
|
||||
/// <summary>
|
||||
/// Total free and largest free block of this process's address space, in MB, or
|
||||
/// (-1, -1) on failure. Never throws.
|
||||
/// </summary>
|
||||
public static (long FreeMb, long LargestFreeMb) FreeAndLargestMb()
|
||||
{
|
||||
try
|
||||
{
|
||||
ulong free = 0, largest = 0;
|
||||
nuint addr = 0;
|
||||
nuint size = (nuint)Marshal.SizeOf<MEMORY_BASIC_INFORMATION>();
|
||||
int guard = 0;
|
||||
while (guard++ < 1_000_000)
|
||||
{
|
||||
if (VirtualQuery(addr, out MEMORY_BASIC_INFORMATION mbi, size) == 0)
|
||||
break;
|
||||
ulong region = mbi.RegionSize;
|
||||
if (region == 0)
|
||||
break;
|
||||
Accumulate(mbi.State == MEM_FREE, region, ref free, ref largest);
|
||||
nuint next = mbi.BaseAddress + mbi.RegionSize;
|
||||
if (next <= addr)
|
||||
break; // wrapped past the top
|
||||
addr = next;
|
||||
}
|
||||
if (guard <= 1)
|
||||
return (-1, -1);
|
||||
return ((long)(free >> 20), (long)(largest >> 20));
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (-1, -1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pure: fold one region into the running totals.</summary>
|
||||
public static void Accumulate(bool isFree, ulong regionBytes, ref ulong freeBytes, ref ulong largestBytes)
|
||||
{
|
||||
if (!isFree) return;
|
||||
freeBytes += regionBytes;
|
||||
if (regionBytes > largestBytes) largestBytes = regionBytes;
|
||||
}
|
||||
|
||||
/// <summary>"free=NNNMB largest=NNNMB", for the reload log lines.</summary>
|
||||
public static string Describe()
|
||||
{
|
||||
var (free, largest) = FreeAndLargestMb();
|
||||
return free < 0 ? "free=? largest=?" : $"free={free}MB largest={largest}MB";
|
||||
}
|
||||
}
|
||||
|
|
@ -80,6 +80,9 @@ internal static class AppraisalHooks
|
|||
// Spell book cache: guid → spell ID array (from AppraisalProfile._spellBook PSmartArray<UInt32> at +0x30)
|
||||
private static readonly Dictionary<uint, uint[]> _spellIdCache = new();
|
||||
private static readonly object _cacheLock = new();
|
||||
// Objects the CLIENT released, whose data is kept a while (ReleasedObjectRetention).
|
||||
private static readonly ReleasedObjectRetention _released = new();
|
||||
private static readonly List<uint> _expiredScratch = new();
|
||||
|
||||
public static bool IsInstalled => _hookInstalled;
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
|
@ -114,19 +117,64 @@ internal static class AppraisalHooks
|
|||
_bags.Clear();
|
||||
_spellIdCache.Clear();
|
||||
_failedRollLogged.Clear();
|
||||
_released.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drops everything cached for an object AC deleted (PropertyUpdateHooks' BeingDeleted hook).</summary>
|
||||
/// <summary>
|
||||
/// Drops everything cached for an object: the SERVER deleted it (0xF747, SmartBoxHooks /
|
||||
/// ServerMessageStream), or its kept-after-release time ran out. Any thread.
|
||||
/// </summary>
|
||||
public static void EvictObject(uint guid)
|
||||
{
|
||||
lock (_cacheLock)
|
||||
EvictLocked(guid);
|
||||
}
|
||||
|
||||
// Caller holds _cacheLock.
|
||||
private static void EvictLocked(uint guid)
|
||||
{
|
||||
_appraisedGuids.Remove(guid);
|
||||
_lastIdTime.Remove(guid);
|
||||
_bags.Remove(guid);
|
||||
_spellIdCache.Remove(guid);
|
||||
_failedRollLogged.Remove(guid);
|
||||
_released.Forget(guid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The CLIENT released an object (AC's BeingDeleted: it left the client's view). Its data is
|
||||
/// kept for ReleasedObjectRetention.RetainMs, so a re-create inside that time still finds it
|
||||
/// (AutoId then skips the re-appraisal). Main thread (the BeingDeleted detour).
|
||||
/// </summary>
|
||||
public static void OnClientRelease(uint guid, long nowMs)
|
||||
{
|
||||
lock (_cacheLock)
|
||||
{
|
||||
_appraisedGuids.Remove(guid);
|
||||
_lastIdTime.Remove(guid);
|
||||
_bags.Remove(guid);
|
||||
_spellIdCache.Remove(guid);
|
||||
_failedRollLogged.Remove(guid);
|
||||
if (!_appraisedGuids.Contains(guid) && !_bags.ContainsKey(guid)) return;
|
||||
if (!_released.OnRelease(guid, nowMs))
|
||||
EvictLocked(guid); // the kept-released bound is full: drop it now
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The object was created again: its data is current, not merely kept.</summary>
|
||||
public static void MarkLive(uint guid)
|
||||
{
|
||||
lock (_cacheLock)
|
||||
_released.Forget(guid);
|
||||
}
|
||||
|
||||
/// <summary>Drops the data of objects released longer ago than the retention time. Timer thread.</summary>
|
||||
public static int ExpireReleased(long nowMs)
|
||||
{
|
||||
lock (_cacheLock)
|
||||
{
|
||||
_expiredScratch.Clear();
|
||||
int n = _released.Expire(nowMs, _expiredScratch);
|
||||
foreach (uint g in _expiredScratch)
|
||||
EvictLocked(g);
|
||||
_expiredScratch.Clear();
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -150,10 +198,7 @@ internal static class AppraisalHooks
|
|||
if (t < oldestTime) { oldestTime = t; oldest = g; }
|
||||
}
|
||||
if (oldest == 0) return;
|
||||
_bags.Remove(oldest);
|
||||
_appraisedGuids.Remove(oldest);
|
||||
_lastIdTime.Remove(oldest);
|
||||
_spellIdCache.Remove(oldest);
|
||||
EvictLocked(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
319
src/RynthCore.Engine/Compatibility/AutoIdDrain.cs
Normal file
319
src/RynthCore.Engine/Compatibility/AutoIdDrain.cs
Normal file
|
|
@ -0,0 +1,319 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/AutoIdDrain.cs
|
||||
//
|
||||
// AutoIdService's backlog: candidates in (any thread), decisions and sends out (the
|
||||
// drain timer). Everything it needs from the engine comes through IAutoIdWorld, so it
|
||||
// runs in tools\EngineRobustnessTests against a fake world and a fake clock.
|
||||
//
|
||||
// Per tick: take the new candidates, the one-shot login sweep, then look at the pending
|
||||
// list in order (at most MaxEvaluatedPerTick, at most MaxPerTick sends) and decide each
|
||||
// one with AutoIdPolicy. Waits stay; skips leave; a send leaves only when the main-thread
|
||||
// queue took it (a refusal, in a transition or with the ring full, keeps the entry and
|
||||
// ends this tick's sending).
|
||||
//
|
||||
// Login sweep: the pack is created before the 10 Hz object
|
||||
// snapshot is warm (ClientObjectHooks.PrefetchPositions only starts after the post-login
|
||||
// bootstrap), so a pack item created at login may still be unplaceable when its create
|
||||
// candidate is decided. Once per login (and per hot reload, which marks a login), at
|
||||
// login-complete + DeferMs and with the snapshot warm, every uncached item the player
|
||||
// owns, and every item in a pack the player owns, becomes a candidate. The 5 a second
|
||||
// Inventory cap still applies. An Unknown candidate also waits for the snapshot (up to
|
||||
// AutoIdPolicy.UnknownMaxWaitMs) instead of being dropped at MinAgeMs. Only containers are
|
||||
// looked into, and a sweep that overflowed the pending list counts as not done: it runs
|
||||
// again once there is room.
|
||||
//
|
||||
// Combat: Inventory sends wait while a cast or attack is in flight
|
||||
// (Context.CombatBusy, AutoIdPolicy.InCombat; a selected target alone does not count). Each 0xC8 raises AC's busy count, and plugins gate
|
||||
// their casts on it. The selected target and an open container are not held.
|
||||
//
|
||||
// Bounds: _incoming is capped at MaxIncoming (oldest dropped, counted) because the drain
|
||||
// returns early through a world transition (a long death); the pending list is capped at
|
||||
// MaxPendingLimited in Limited mode only (All keeps the old unbounded backlog).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Net;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>What AutoIdDrain reads and does in the engine (a fake in the tests).</summary>
|
||||
internal interface IAutoIdWorld
|
||||
{
|
||||
/// <summary>The object's container and wielder from the object snapshot; false when it is not in it.</summary>
|
||||
bool TryGetOwnership(uint id, out uint container, out uint wielder);
|
||||
/// <summary>The object snapshot has been filled at least once (it holds any object at all).</summary>
|
||||
bool SnapshotWarm { get; }
|
||||
/// <summary>Ids whose container or wielder is <paramref name="container"/>, from the snapshot.</summary>
|
||||
int CollectOwned(uint container, Span<uint> dest);
|
||||
/// <summary>Created and not released (AutoIdEligibility).</summary>
|
||||
bool IsLive(uint id);
|
||||
/// <summary>Its appraisal is cached.</summary>
|
||||
bool HasAppraisal(uint id);
|
||||
/// <summary>Its appraisal is cached and recent.</summary>
|
||||
bool IsFresh(uint id);
|
||||
/// <summary>Queue the 0xC8 for AC's main thread; false = refused (transition, ring full).</summary>
|
||||
bool QueueIdentify(uint id, IdRequester who);
|
||||
/// <summary>It holds items (a pack, a chest): only these are looked into by the login sweep.</summary>
|
||||
bool IsContainer(uint id);
|
||||
}
|
||||
|
||||
internal sealed class AutoIdDrain
|
||||
{
|
||||
public const int MaxPerTick = 3;
|
||||
public const int MaxEvaluatedPerTick = 512;
|
||||
public const int MaxPendingLimited = 4096;
|
||||
public const int MaxIncoming = 16384;
|
||||
public const int MaxSweepItems = 512;
|
||||
|
||||
/// <summary>One tick's view of the engine (read by AutoIdService each tick).</summary>
|
||||
public struct Context
|
||||
{
|
||||
public long Now;
|
||||
public AutoIdMode Mode;
|
||||
public uint PlayerId;
|
||||
public uint OpenContainer;
|
||||
public long OpenedAtMs; // when OpenContainer was opened (0 = unknown)
|
||||
public long SettleUntilMs; // PlayerLifecycleLog.SettleUntilMs
|
||||
public long LoginCompleteAtMs; // LoginLifecycleHooks.LoginCompleteAtMs
|
||||
public bool CombatBusy; // a cast or attack in flight, AutoIdPolicy.InCombat (Inventory waits)
|
||||
}
|
||||
|
||||
private struct Pending
|
||||
{
|
||||
public uint Id;
|
||||
public long AtMs; // created (or moved, or its container opened, or swept) at
|
||||
public byte Counted; // waits already counted: 1 = age, 2 = defer, 4 = rate, 8 = combat
|
||||
}
|
||||
|
||||
private readonly IAutoIdWorld _w;
|
||||
private readonly ConcurrentQueue<(uint Id, long AtMs)> _incoming = new();
|
||||
private int _incomingCount;
|
||||
private readonly List<Pending> _pending = new(256);
|
||||
private readonly HashSet<uint> _pendingIds = new();
|
||||
private int _pendingCount;
|
||||
private long _lastInventorySendMs;
|
||||
private long _sweptLoginAt;
|
||||
|
||||
private long _skipMode, _skipAge, _skipDefer, _skipFresh, _skipRate, _skipCombat, _overflow, _incomingDropped, _refused, _swept;
|
||||
|
||||
public AutoIdDrain(IAutoIdWorld world) { _w = world; }
|
||||
|
||||
public long SkipMode => Interlocked.Read(ref _skipMode);
|
||||
public long SkipAge => Interlocked.Read(ref _skipAge);
|
||||
public long SkipDefer => Interlocked.Read(ref _skipDefer);
|
||||
public long SkipFresh => Interlocked.Read(ref _skipFresh);
|
||||
public long SkipRate => Interlocked.Read(ref _skipRate);
|
||||
/// <summary>Inventory candidates that waited for combat to end (counted once each).</summary>
|
||||
public long SkipCombat => Interlocked.Read(ref _skipCombat);
|
||||
/// <summary>Candidates not taken because the Limited pending list was full.</summary>
|
||||
public long Overflow => Interlocked.Read(ref _overflow);
|
||||
/// <summary>Oldest new candidates dropped because _incoming was full (the drain was held).</summary>
|
||||
public long IncomingDropped => Interlocked.Read(ref _incomingDropped);
|
||||
/// <summary>Sends the main-thread queue refused (kept and tried again).</summary>
|
||||
public long Refused => Interlocked.Read(ref _refused);
|
||||
/// <summary>Items the login sweeps made candidates.</summary>
|
||||
public long Swept => Interlocked.Read(ref _swept);
|
||||
public int PendingCount => Volatile.Read(ref _pendingCount);
|
||||
|
||||
/// <summary>The selected-target path counts its fresh / mode skips here too.</summary>
|
||||
public void CountSkipFresh() => Interlocked.Increment(ref _skipFresh);
|
||||
public void CountSkipMode() => Interlocked.Increment(ref _skipMode);
|
||||
|
||||
/// <summary>A new candidate (any thread). Past MaxIncoming the oldest waiting one is dropped.</summary>
|
||||
public void Offer(uint id, long atMs)
|
||||
{
|
||||
if (id == 0) return;
|
||||
_incoming.Enqueue((id, atMs));
|
||||
if (Interlocked.Increment(ref _incomingCount) > MaxIncoming && _incoming.TryDequeue(out _))
|
||||
{
|
||||
Interlocked.Decrement(ref _incomingCount);
|
||||
Interlocked.Increment(ref _incomingDropped);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drain thread: the items in <paramref name="container"/> with nothing cached become candidates.</summary>
|
||||
public void AddContainerContents(uint container, long atMs, AutoIdMode mode)
|
||||
{
|
||||
if (container == 0) return;
|
||||
Span<uint> ids = stackalloc uint[256];
|
||||
int n = _w.CollectOwned(container, ids);
|
||||
for (int i = 0; i < n; i++)
|
||||
if (_w.IsLive(ids[i]) && !_w.HasAppraisal(ids[i]))
|
||||
AddPending(ids[i], atMs, mode);
|
||||
}
|
||||
|
||||
/// <summary>Drain thread, once per timer tick. Returns the sends so far (starting at <paramref name="sent"/>).</summary>
|
||||
public int Tick(in Context c, int sent)
|
||||
{
|
||||
TakeIncoming(c.Mode);
|
||||
LoginSweep(c);
|
||||
return DrainPending(c, sent);
|
||||
}
|
||||
|
||||
private void TakeIncoming(AutoIdMode mode)
|
||||
{
|
||||
while (_incoming.TryDequeue(out (uint Id, long AtMs) x))
|
||||
{
|
||||
Interlocked.Decrement(ref _incomingCount);
|
||||
AddPending(x.Id, x.AtMs, mode);
|
||||
}
|
||||
}
|
||||
|
||||
private void AddPending(uint id, long atMs, AutoIdMode mode)
|
||||
{
|
||||
if (id == 0 || _pendingIds.Contains(id))
|
||||
return;
|
||||
if (mode != AutoIdMode.All && _pending.Count >= MaxPendingLimited)
|
||||
{
|
||||
Interlocked.Increment(ref _overflow);
|
||||
return;
|
||||
}
|
||||
_pendingIds.Add(id);
|
||||
_pending.Add(new Pending { Id = id, AtMs = atMs });
|
||||
}
|
||||
|
||||
/// <summary>Once per login-complete stamp, at login + DeferMs with the snapshot warm: the uncached pack.</summary>
|
||||
private void LoginSweep(in Context c)
|
||||
{
|
||||
if (c.Mode != AutoIdMode.Limited || c.LoginCompleteAtMs <= 0 || c.LoginCompleteAtMs == _sweptLoginAt)
|
||||
return;
|
||||
if (c.Now < c.LoginCompleteAtMs + AutoIdPolicy.DeferMs || c.PlayerId == 0 || !_w.SnapshotWarm)
|
||||
return;
|
||||
// A full pending list: try again on a later tick (no walk, no overflow counted).
|
||||
if (_pending.Count >= MaxPendingLimited)
|
||||
return;
|
||||
Span<uint> top = stackalloc uint[MaxSweepItems];
|
||||
Span<uint> inner = stackalloc uint[MaxSweepItems];
|
||||
int n = _w.CollectOwned(c.PlayerId, top);
|
||||
int before = _pending.Count;
|
||||
long overflowBefore = Interlocked.Read(ref _overflow);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
uint id = top[i];
|
||||
if (_w.IsLive(id) && !_w.HasAppraisal(id))
|
||||
AddPending(id, c.LoginCompleteAtMs, c.Mode);
|
||||
// A side pack: its contents are the pack too. Only a container is looked into.
|
||||
if (!_w.IsContainer(id))
|
||||
continue;
|
||||
int m = _w.CollectOwned(id, inner);
|
||||
for (int k = 0; k < m; k++)
|
||||
if (_w.IsLive(inner[k]) && !_w.HasAppraisal(inner[k]))
|
||||
AddPending(inner[k], c.LoginCompleteAtMs, c.Mode);
|
||||
}
|
||||
Interlocked.Add(ref _swept, _pending.Count - before);
|
||||
// Done only when everything fit; an overflowed sweep runs again once there is room
|
||||
// (what it already added is not added twice: AddPending skips ids already pending).
|
||||
if (Interlocked.Read(ref _overflow) == overflowBefore)
|
||||
_sweptLoginAt = c.LoginCompleteAtMs;
|
||||
}
|
||||
|
||||
private int DrainPending(in Context c, int sent)
|
||||
{
|
||||
if (_pending.Count == 0)
|
||||
{
|
||||
Volatile.Write(ref _pendingCount, 0);
|
||||
return sent;
|
||||
}
|
||||
|
||||
long transitionEnd = AutoIdPolicy.TransitionEndMs(c.SettleUntilMs, c.LoginCompleteAtMs);
|
||||
bool inDefer = AutoIdPolicy.InDefer(c.Now, c.SettleUntilMs, c.LoginCompleteAtMs, inTransition: false);
|
||||
bool openedAfterSettle = AutoIdPolicy.OpenedAfterSettle(c.OpenedAtMs, transitionEnd);
|
||||
bool snapshotWarm = _w.SnapshotWarm;
|
||||
bool sending = true;
|
||||
|
||||
int keep = 0, evaluated = 0;
|
||||
for (int i = 0; i < _pending.Count; i++)
|
||||
{
|
||||
Pending p = _pending[i];
|
||||
if (!sending || sent >= MaxPerTick || evaluated >= MaxEvaluatedPerTick)
|
||||
{
|
||||
_pending[keep++] = p;
|
||||
continue;
|
||||
}
|
||||
evaluated++;
|
||||
|
||||
// Released since it was queued: gone, without spending a send.
|
||||
if (!_w.IsLive(p.Id))
|
||||
{
|
||||
_pendingIds.Remove(p.Id);
|
||||
continue;
|
||||
}
|
||||
|
||||
AutoIdPolicy.Class cls = Classify(p.Id, c.PlayerId, c.OpenContainer);
|
||||
bool cached = _w.HasAppraisal(p.Id);
|
||||
bool fresh = cached && _w.IsFresh(p.Id);
|
||||
bool rateOk = AutoIdPolicy.InventoryRateAllows(c.Now, _lastInventorySendMs);
|
||||
AutoIdPolicy.Verdict v = AutoIdPolicy.Decide(c.Mode, cls, c.Now - p.AtMs, inDefer, openedAfterSettle,
|
||||
fresh, cached, rateOk, snapshotWarm, c.CombatBusy);
|
||||
switch (v)
|
||||
{
|
||||
case AutoIdPolicy.Verdict.Send:
|
||||
if (!_w.QueueIdentify(p.Id, RequesterFor(cls)))
|
||||
{
|
||||
// Refused (a transition began, or the ring is full): keep it, and
|
||||
// stop sending this tick.
|
||||
Interlocked.Increment(ref _refused);
|
||||
_pending[keep++] = p;
|
||||
sending = false;
|
||||
break;
|
||||
}
|
||||
sent++;
|
||||
if (cls == AutoIdPolicy.Class.Inventory && c.Mode == AutoIdMode.Limited)
|
||||
_lastInventorySendMs = c.Now;
|
||||
_pendingIds.Remove(p.Id);
|
||||
break;
|
||||
case AutoIdPolicy.Verdict.WaitAge:
|
||||
case AutoIdPolicy.Verdict.WaitSnapshot:
|
||||
if ((p.Counted & 1) == 0) { p.Counted |= 1; Interlocked.Increment(ref _skipAge); }
|
||||
_pending[keep++] = p;
|
||||
break;
|
||||
case AutoIdPolicy.Verdict.WaitDefer:
|
||||
if ((p.Counted & 2) == 0) { p.Counted |= 2; Interlocked.Increment(ref _skipDefer); }
|
||||
_pending[keep++] = p;
|
||||
break;
|
||||
case AutoIdPolicy.Verdict.WaitRate:
|
||||
if ((p.Counted & 4) == 0) { p.Counted |= 4; Interlocked.Increment(ref _skipRate); }
|
||||
_pending[keep++] = p;
|
||||
break;
|
||||
case AutoIdPolicy.Verdict.WaitCombat:
|
||||
if ((p.Counted & 8) == 0) { p.Counted |= 8; Interlocked.Increment(ref _skipCombat); }
|
||||
_pending[keep++] = p;
|
||||
break;
|
||||
case AutoIdPolicy.Verdict.SkipFresh:
|
||||
Interlocked.Increment(ref _skipFresh);
|
||||
_pendingIds.Remove(p.Id);
|
||||
break;
|
||||
default:
|
||||
Interlocked.Increment(ref _skipMode);
|
||||
_pendingIds.Remove(p.Id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
_pending.RemoveRange(keep, _pending.Count - keep);
|
||||
Volatile.Write(ref _pendingCount, _pending.Count);
|
||||
return sent;
|
||||
}
|
||||
|
||||
/// <summary>Where the object is now, from the snapshot.</summary>
|
||||
private AutoIdPolicy.Class Classify(uint id, uint playerId, uint open)
|
||||
{
|
||||
if (!_w.TryGetOwnership(id, out uint container, out uint wielder))
|
||||
return AutoIdPolicy.Classify(false, playerId, open, 0, 0, 0);
|
||||
uint parent = 0;
|
||||
if (container != 0 && container != playerId && container != open
|
||||
&& _w.TryGetOwnership(container, out uint cc, out _))
|
||||
parent = cc;
|
||||
return AutoIdPolicy.Classify(true, playerId, open, container, wielder, parent);
|
||||
}
|
||||
|
||||
public static IdRequester RequesterFor(AutoIdPolicy.Class cls) => cls switch
|
||||
{
|
||||
AutoIdPolicy.Class.Target => IdRequester.AutoIdTarget,
|
||||
AutoIdPolicy.Class.Container => IdRequester.AutoIdContainer,
|
||||
AutoIdPolicy.Class.Inventory => IdRequester.AutoIdInventory,
|
||||
_ => IdRequester.AutoIdWorld,
|
||||
};
|
||||
}
|
||||
191
src/RynthCore.Engine/Compatibility/AutoIdEligibility.cs
Normal file
191
src/RynthCore.Engine/Compatibility/AutoIdEligibility.cs
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/AutoIdEligibility.cs
|
||||
//
|
||||
// Which created objects AutoIdService appraises (the decision only; AutoIdService
|
||||
// does the queueing and the sends).
|
||||
//
|
||||
// Before: a client-side release of an object (ACCObjectMaint::DeleteObject, or the
|
||||
// Decal bridge's delete event) forgot that it had been appraised, so every time the
|
||||
// client re-created it the engine appraised it again: some objects 16 times in 26
|
||||
// minutes. Now each object keeps the time its last appraisal was SENT, across client
|
||||
// releases, and a re-create inside the window (default 10 minutes) is not appraised
|
||||
// again, unless:
|
||||
// - the SERVER deleted the object (0xF747 ObjectDelete): it really went away, and
|
||||
// what comes back under that id is appraised fresh; or
|
||||
// - the appraisal data is no longer cached (the caller says so): re-appraising is
|
||||
// then the only way to get it back, so the window never leaves an object with
|
||||
// nothing cached.
|
||||
// A release before the queued appraisal went out records no time, so the next create
|
||||
// is appraised. A create while the object is still live is a duplicate and ignored.
|
||||
//
|
||||
// Bounded: at most MaxTracked objects. Prune (from the drain timer, never the create
|
||||
// path) drops entries that no longer decide anything (released and outside the window
|
||||
// or never sent), then the oldest released ones. Past the bound a create is still
|
||||
// admitted, only not tracked.
|
||||
//
|
||||
// Pure: no engine state, no locking (the caller locks), and no allocation after
|
||||
// construction (pre-sized; Dictionary.Remove during enumeration is allowed on
|
||||
// .NET Core 3+). Compiled into tools\EngineRobustnessTests.
|
||||
// ============================================================================
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal sealed class AutoIdEligibility
|
||||
{
|
||||
public const long DefaultWindowMs = 10L * 60 * 1000;
|
||||
public const int DefaultMaxTracked = 8192;
|
||||
|
||||
public enum CreateDecision
|
||||
{
|
||||
/// <summary>Queue an appraisal.</summary>
|
||||
Appraise,
|
||||
/// <summary>Appraised recently and still cached: skip.</summary>
|
||||
SkipRecent,
|
||||
/// <summary>Already live (a second create for it): skip.</summary>
|
||||
SkipDuplicate,
|
||||
}
|
||||
|
||||
private struct Entry
|
||||
{
|
||||
public bool Live; // created and not released since
|
||||
public long LastSentMs; // when its last appraisal was sent; 0 = none since tracking (re)started
|
||||
}
|
||||
|
||||
private readonly Dictionary<uint, Entry> _map;
|
||||
private readonly long _windowMs;
|
||||
private readonly int _maxTracked;
|
||||
|
||||
public AutoIdEligibility(long windowMs = DefaultWindowMs, int maxTracked = DefaultMaxTracked)
|
||||
{
|
||||
_windowMs = windowMs;
|
||||
_maxTracked = maxTracked;
|
||||
_map = new Dictionary<uint, Entry>(maxTracked + 1);
|
||||
}
|
||||
|
||||
public int Count => _map.Count;
|
||||
public int MaxTracked => _maxTracked;
|
||||
public long WindowMs => _windowMs;
|
||||
|
||||
/// <summary>Re-creates skipped because the last appraisal is recent and still cached.</summary>
|
||||
public long SkippedRecentTotal { get; private set; }
|
||||
|
||||
/// <summary>Creates admitted while the map was full (appraised, not tracked).</summary>
|
||||
public long UntrackedAdmits { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The client created <paramref name="id"/>. <paramref name="appraisalCached"/>: the
|
||||
/// engine still holds appraisal data for it (AppraisalHooks).
|
||||
/// </summary>
|
||||
public CreateDecision OnCreate(uint id, long nowMs, bool appraisalCached)
|
||||
{
|
||||
if (_map.TryGetValue(id, out Entry e))
|
||||
{
|
||||
if (e.Live)
|
||||
return CreateDecision.SkipDuplicate;
|
||||
e.Live = true;
|
||||
bool recent = e.LastSentMs != 0 && nowMs - e.LastSentMs < _windowMs;
|
||||
_map[id] = e;
|
||||
if (recent && appraisalCached)
|
||||
{
|
||||
SkippedRecentTotal++;
|
||||
return CreateDecision.SkipRecent;
|
||||
}
|
||||
return CreateDecision.Appraise;
|
||||
}
|
||||
|
||||
if (_map.Count >= _maxTracked)
|
||||
{
|
||||
UntrackedAdmits++;
|
||||
return CreateDecision.Appraise;
|
||||
}
|
||||
_map[id] = new Entry { Live = true, LastSentMs = 0 };
|
||||
return CreateDecision.Appraise;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The appraisal for <paramref name="id"/> was sent: called from the main-thread drain
|
||||
/// after CombatActionHooks.RequestId succeeded, never at queue time, so a request the
|
||||
/// drain dropped (stale, a world transition, a new login) records nothing.
|
||||
/// </summary>
|
||||
public void OnSent(uint id, long nowMs)
|
||||
{
|
||||
if (_map.TryGetValue(id, out Entry e))
|
||||
{
|
||||
e.LastSentMs = nowMs == 0 ? 1 : nowMs;
|
||||
_map[id] = e;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The client released <paramref name="id"/>; its appraisal time is kept.</summary>
|
||||
public void OnClientRelease(uint id)
|
||||
{
|
||||
if (_map.TryGetValue(id, out Entry e) && e.Live)
|
||||
{
|
||||
e.Live = false;
|
||||
_map[id] = e;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The server deleted <paramref name="id"/>: the next create under that id is appraised.
|
||||
/// Liveness is left to the client's own release (it may come before or after this).
|
||||
/// </summary>
|
||||
public void OnServerDelete(uint id)
|
||||
{
|
||||
if (_map.TryGetValue(id, out Entry e))
|
||||
{
|
||||
e.LastSentMs = 0;
|
||||
_map[id] = e;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True while <paramref name="id"/> is created and not released (or untracked).</summary>
|
||||
public bool IsLive(uint id) => !_map.TryGetValue(id, out Entry e) || e.Live;
|
||||
|
||||
/// <summary>
|
||||
/// Keep the map under its bound. First drops entries that decide nothing any more
|
||||
/// (released, and never sent or outside the window), then, if still at the bound,
|
||||
/// the released entries sent longest ago. Live entries are never dropped.
|
||||
/// Returns how many were removed.
|
||||
/// </summary>
|
||||
public int Prune(long nowMs)
|
||||
{
|
||||
int removed = 0;
|
||||
foreach (KeyValuePair<uint, Entry> kv in _map)
|
||||
{
|
||||
Entry e = kv.Value;
|
||||
if (!e.Live && (e.LastSentMs == 0 || nowMs - e.LastSentMs >= _windowMs))
|
||||
{
|
||||
_map.Remove(kv.Key);
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
|
||||
// Still over three quarters full: drop released entries oldest first, in a few
|
||||
// passes with a shrinking age cut (window/2, /4, /8, then any age). One linear
|
||||
// pass each, so a prune never costs more than five walks of the map.
|
||||
int target = _maxTracked * 3 / 4;
|
||||
for (int pass = 1; pass <= 4 && _map.Count > target; pass++)
|
||||
{
|
||||
long minAge = pass < 4 ? _windowMs >> pass : long.MinValue;
|
||||
foreach (KeyValuePair<uint, Entry> kv in _map)
|
||||
{
|
||||
if (_map.Count <= target) break;
|
||||
if (kv.Value.Live) continue;
|
||||
if (pass < 4 && nowMs - kv.Value.LastSentMs < minAge) continue;
|
||||
_map.Remove(kv.Key);
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fix 2 rule for the selected-target priority appraisal: the target's appraisal is
|
||||
/// cached and was received less than <paramref name="windowMs"/> ago.
|
||||
/// </summary>
|
||||
public static bool IsAppraisalFresh(bool cached, long lastIdUnixSec, long nowUnixSec, long windowMs) =>
|
||||
cached && lastIdUnixSec > 0 && (nowUnixSec - lastIdUnixSec) * 1000 < windowMs;
|
||||
}
|
||||
233
src/RynthCore.Engine/Compatibility/AutoIdPolicy.cs
Normal file
233
src/RynthCore.Engine/Compatibility/AutoIdPolicy.cs
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/AutoIdPolicy.cs
|
||||
//
|
||||
// Which background appraisals AutoIdService sends (the decision only; AutoIdService
|
||||
// does the queueing, the lookups and the sends).
|
||||
//
|
||||
// Why: in one 26-minute session (1585 s) the client sent 3211 IdentifyObject (0xC8),
|
||||
// about three quarters of everything it sent, for 2479 objects against 28
|
||||
// kills. AutoId appraised every object the client created. The bot (RynthAi) already
|
||||
// appraises what it needs at the point of use (corpse items its loot rules need, the
|
||||
// selected creature, equipment, meta conditions), so most of that was traffic for
|
||||
// nothing; it is now limited (engine.json "AutoIdMode", /rc autoid).
|
||||
//
|
||||
// Modes:
|
||||
// All the old behaviour: every created object except the player, the selected
|
||||
// target with its fresh-cache skip.
|
||||
// Limited (default) only
|
||||
// Target the selected target (fresh-cache skip, no age, no defer);
|
||||
// Container items in the container the player has open now (a corpse,
|
||||
// a chest, a pack opened through ViewContents);
|
||||
// Inventory items in the player's own inventory (worn, in the main pack
|
||||
// or in a side pack) that have no cached appraisal.
|
||||
// Container and Inventory wait until the object is MinAgeMs old, and until
|
||||
// DeferMs after a world transition's settle window ends (death, portal,
|
||||
// teleport, landblock jump; walking into the next landblock is not one),
|
||||
// and until DeferMs after login completes (login is a transition too:
|
||||
// a client crashed in AC's CreateObject handling during the
|
||||
// login create burst). A container the player opened after the last
|
||||
// transition ended is not deferred. Inventory sends are capped at 5 a
|
||||
// second and wait while a cast or attack is in flight (a selected
|
||||
// target alone does not hold them). Creatures, ground items, other players: never.
|
||||
// Off nothing, the selected target included.
|
||||
// Plugins calling the host RequestId are not limited by any of this.
|
||||
//
|
||||
// Pure: no engine state, no locking. Compiled into tools\EngineRobustnessTests and
|
||||
// tools\EngineSettingsTests.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>engine.json "AutoIdMode" (see <see cref="AutoIdPolicy"/>).</summary>
|
||||
internal enum AutoIdMode { All = 0, Limited = 1, Off = 2 }
|
||||
|
||||
internal static class AutoIdPolicy
|
||||
{
|
||||
public const AutoIdMode DefaultMode = AutoIdMode.Limited;
|
||||
|
||||
/// <summary>Container and Inventory appraisals wait until the object is this old.</summary>
|
||||
public const long MinAgeMs = 2_000;
|
||||
|
||||
/// <summary>Container and Inventory appraisals wait this long after a transition's settle window ends,
|
||||
/// and after login completes.</summary>
|
||||
public const long DeferMs = 30_000;
|
||||
|
||||
/// <summary>
|
||||
/// Inventory appraisals go out at most one per this many ms (5 a second). In one case
|
||||
/// a client crashed in AC's CreateObject handling during the login create burst, 47 s after
|
||||
/// start, and the pack's appraisals at 30 a second are what that burst must not carry.
|
||||
/// </summary>
|
||||
public const long InventoryMinIntervalMs = 200;
|
||||
|
||||
/// <summary>
|
||||
/// An object whose place is unknown because the object snapshot has not been filled yet
|
||||
/// (at login the pack is created before ClientObjectHooks.PrefetchPositions starts) waits
|
||||
/// for it this long at most before it is dropped.
|
||||
/// </summary>
|
||||
public const long UnknownMaxWaitMs = 120_000;
|
||||
|
||||
public enum Class
|
||||
{
|
||||
/// <summary>The selected target (the priority path).</summary>
|
||||
Target,
|
||||
/// <summary>In the container the player has open now.</summary>
|
||||
Container,
|
||||
/// <summary>In the player's own inventory (worn, main pack, side pack).</summary>
|
||||
Inventory,
|
||||
/// <summary>Anything else the client knows where it is: a creature, a ground item, another player.</summary>
|
||||
World,
|
||||
/// <summary>Not in the engine's object snapshot yet (created moments ago), so its place is unknown.</summary>
|
||||
Unknown,
|
||||
}
|
||||
|
||||
public enum Verdict
|
||||
{
|
||||
/// <summary>Appraise it now.</summary>
|
||||
Send,
|
||||
/// <summary>The mode does not appraise this: drop it.</summary>
|
||||
SkipMode,
|
||||
/// <summary>Too young: keep it and ask again later.</summary>
|
||||
WaitAge,
|
||||
/// <summary>Inside the post-transition defer: keep it and ask again later.</summary>
|
||||
WaitDefer,
|
||||
/// <summary>Its appraisal is cached (fresh): drop it.</summary>
|
||||
SkipFresh,
|
||||
/// <summary>Inventory over its send rate (InventoryMinIntervalMs): keep it and ask again later.</summary>
|
||||
WaitRate,
|
||||
/// <summary>Place unknown and the object snapshot still empty: keep it (up to UnknownMaxWaitMs).</summary>
|
||||
WaitSnapshot,
|
||||
/// <summary>Inventory while in combat (a cast or an attack in flight, InCombat): keep it.</summary>
|
||||
WaitCombat,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The decision for one candidate.
|
||||
/// <paramref name="ageMs"/>: how long the object has existed (or since it moved, for a move).
|
||||
/// <paramref name="inDefer"/>: inside the post-transition defer window (<see cref="InDefer"/>).
|
||||
/// <paramref name="openedAfterSettle"/>: Container only, the player opened it after the last
|
||||
/// settle window ended (<see cref="OpenedAfterSettle"/>), which exempts it from the defer.
|
||||
/// <paramref name="fresh"/>: its appraisal is cached and recent (Target, Container).
|
||||
/// <paramref name="cached"/>: its appraisal is cached at all (Inventory).
|
||||
/// <paramref name="inventoryRateOk"/>: Inventory only, the send rate allows one now (<see cref="InventoryRateAllows"/>).
|
||||
/// <paramref name="snapshotWarm"/>: Unknown only, the object snapshot has been filled (an
|
||||
/// object missing from a warm snapshot is not coming; one missing from a cold one may be).
|
||||
/// <paramref name="combatBusy"/>: Inventory only, a cast or attack is in flight (<see cref="InCombat"/>). Each 0xC8 raises AC's busy count, which plugins gate casts on, so the pack waits.
|
||||
/// </summary>
|
||||
public static Verdict Decide(AutoIdMode mode, Class cls, long ageMs, bool inDefer, bool openedAfterSettle,
|
||||
bool fresh, bool cached, bool inventoryRateOk = true, bool snapshotWarm = true,
|
||||
bool combatBusy = false)
|
||||
{
|
||||
switch (mode)
|
||||
{
|
||||
case AutoIdMode.Off:
|
||||
return Verdict.SkipMode;
|
||||
|
||||
case AutoIdMode.All:
|
||||
// The old behaviour: the create-time eligibility already decided; only the
|
||||
// selected target has the fresh-cache skip.
|
||||
if (cls == Class.Target && fresh) return Verdict.SkipFresh;
|
||||
return Verdict.Send;
|
||||
|
||||
default: // Limited
|
||||
switch (cls)
|
||||
{
|
||||
case Class.Target:
|
||||
return fresh ? Verdict.SkipFresh : Verdict.Send;
|
||||
case Class.Container:
|
||||
if (fresh) return Verdict.SkipFresh;
|
||||
if (ageMs < MinAgeMs) return Verdict.WaitAge;
|
||||
if (inDefer && !openedAfterSettle) return Verdict.WaitDefer;
|
||||
return Verdict.Send;
|
||||
case Class.Inventory:
|
||||
if (cached) return Verdict.SkipFresh;
|
||||
if (ageMs < MinAgeMs) return Verdict.WaitAge;
|
||||
if (inDefer) return Verdict.WaitDefer;
|
||||
if (combatBusy) return Verdict.WaitCombat;
|
||||
if (!inventoryRateOk) return Verdict.WaitRate;
|
||||
return Verdict.Send;
|
||||
case Class.Unknown:
|
||||
// Its place shows up in the snapshot within a tick or two; until it is
|
||||
// MinAgeMs old it may still turn out to be in the open container or the pack.
|
||||
// While the snapshot has never been filled (login), it waits for it.
|
||||
if (ageMs < MinAgeMs) return Verdict.WaitAge;
|
||||
if (!snapshotWarm && ageMs < UnknownMaxWaitMs) return Verdict.WaitSnapshot;
|
||||
return Verdict.SkipMode;
|
||||
default: // World
|
||||
return Verdict.SkipMode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// In combat for the Inventory hold: a cast in flight (<paramref name="castBusy"/>, CastGate) or an
|
||||
/// attack running. A selected target alone is NOT combat (<paramref name="selectedTarget"/> is taken
|
||||
/// only so the tests can show that): a hunting bot nearly always has something selected, and the
|
||||
/// pack (mana stones included) would never be appraised.
|
||||
/// </summary>
|
||||
public static bool InCombat(uint selectedTarget, int castBusy, bool attacking) =>
|
||||
castBusy != 0 || attacking;
|
||||
|
||||
/// <summary>
|
||||
/// When the last transition ended: the later of the settle window's end
|
||||
/// (WorldTransitionState.SettleUntilMs, 0 = none yet; it only moves on a death, a portal,
|
||||
/// a teleport or a landblock jump, never on a walk into the next landblock) and login
|
||||
/// completing (<paramref name="loginCompleteAtMs"/>; login counts as a transition).
|
||||
/// </summary>
|
||||
public static long TransitionEndMs(long settleUntilMs, long loginCompleteAtMs) =>
|
||||
Math.Max(settleUntilMs, loginCompleteAtMs);
|
||||
|
||||
/// <summary>
|
||||
/// Inside the defer: in a transition now, login not complete yet
|
||||
/// (<paramref name="loginCompleteAtMs"/> 0: the login create burst), or less than
|
||||
/// <see cref="DeferMs"/> after <see cref="TransitionEndMs"/>.
|
||||
/// </summary>
|
||||
public static bool InDefer(long nowMs, long settleUntilMs, long loginCompleteAtMs, bool inTransition) =>
|
||||
inTransition || loginCompleteAtMs <= 0 || nowMs < TransitionEndMs(settleUntilMs, loginCompleteAtMs) + DeferMs;
|
||||
|
||||
/// <summary>The player opened the container (at <paramref name="openedAtMs"/>) after the last transition ended
|
||||
/// (<paramref name="transitionEndMs"/>, <see cref="TransitionEndMs"/>).</summary>
|
||||
public static bool OpenedAfterSettle(long openedAtMs, long transitionEndMs) =>
|
||||
openedAtMs > 0 && openedAtMs >= transitionEndMs;
|
||||
|
||||
/// <summary>An Inventory appraisal may go out now: none yet, or the last was at least InventoryMinIntervalMs ago.</summary>
|
||||
public static bool InventoryRateAllows(long nowMs, long lastInventorySendMs) =>
|
||||
lastInventorySendMs <= 0 || nowMs - lastInventorySendMs >= InventoryMinIntervalMs;
|
||||
|
||||
/// <summary>
|
||||
/// Where an object is, from its PublicWeenieDesc ownership fields (<paramref name="known"/> =
|
||||
/// the snapshot had it). <paramref name="containerParent"/> is the container's own container
|
||||
/// (a side pack's owner), 0 when unknown or none. <paramref name="openContainer"/> is the
|
||||
/// container the player has open now (0 = none).
|
||||
/// </summary>
|
||||
public static Class Classify(bool known, uint playerId, uint openContainer,
|
||||
uint container, uint wielder, uint containerParent)
|
||||
{
|
||||
if (!known) return Class.Unknown;
|
||||
if (playerId != 0 && (container == playerId || wielder == playerId || (container != 0 && containerParent == playerId)))
|
||||
return Class.Inventory;
|
||||
// openContainer != 0 also keeps a ground item (container 0) out of here.
|
||||
if (openContainer != 0 && (container == openContainer || containerParent == openContainer))
|
||||
return Class.Container;
|
||||
return Class.World;
|
||||
}
|
||||
|
||||
public static bool TryParseMode(string? text, out AutoIdMode mode)
|
||||
{
|
||||
switch ((text ?? "").Trim().ToLowerInvariant())
|
||||
{
|
||||
case "all": mode = AutoIdMode.All; return true;
|
||||
case "limited": case "limit": mode = AutoIdMode.Limited; return true;
|
||||
case "off": case "none": mode = AutoIdMode.Off; return true;
|
||||
default: mode = DefaultMode; return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static string Name(AutoIdMode mode) => mode switch
|
||||
{
|
||||
AutoIdMode.All => "all",
|
||||
AutoIdMode.Off => "off",
|
||||
_ => "limited",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,17 +1,35 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/AutoIdService.cs
|
||||
//
|
||||
// Automatically sends RequestId (appraisal) for newly-created world objects
|
||||
// so that property caches (AppraisalHooks int/bool/string) are populated
|
||||
// without requiring the player to manually select each object.
|
||||
// Automatically sends RequestId (appraisal) for objects so that property caches
|
||||
// (AppraisalHooks int/bool/string) are populated without requiring the player to
|
||||
// manually select each object.
|
||||
//
|
||||
// Objects are queued from CreateObjectHooks and drained by a background timer
|
||||
// with rate-limiting to avoid flooding the server.
|
||||
// Candidates come from CreateObjectHooks (and the Decal bridge's create event), from
|
||||
// items the server puts into a container (InventoryPutObjInContainer, SmartBoxHooks'
|
||||
// game-event hook), from a rescan of a container the player opened, and from the
|
||||
// one-shot login sweep of the pack. A background timer drains them (AutoIdDrain), at
|
||||
// most AutoIdDrain.MaxPerTick sends per DrainIntervalMs.
|
||||
//
|
||||
// WHICH of them get an appraisal is two rules:
|
||||
// - AutoIdEligibility (on create): an object the client released and re-created is
|
||||
// not appraised again within 10 minutes of the last one while its data is still
|
||||
// cached, unless the server deleted it;
|
||||
// - AutoIdPolicy (on drain): the AutoIdMode (engine.json "AutoIdMode", /rc autoid).
|
||||
// Limited (the default) appraises only the selected target, the
|
||||
// items in the container the player has open, and items in the player's own
|
||||
// inventory with nothing cached (at most 5 a second); the last two wait for a
|
||||
// minimum object age and a defer after login and after every world transition.
|
||||
// All is the old behaviour; Off sends nothing.
|
||||
//
|
||||
// Every send is queued with who asked (Net/IdRequester.cs), so the flight recorder tags
|
||||
// it [eng:autoid-target|autoid-container|autoid-inventory|autoid-world].
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Net;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
|
|
@ -20,25 +38,101 @@ internal static class AutoIdService
|
|||
// How often the drain timer fires (ms)
|
||||
private const int DrainIntervalMs = 100;
|
||||
|
||||
// Max RequestId calls per drain tick
|
||||
private const int MaxPerTick = 3;
|
||||
// A container the player opened is rescanned this long after the open, so items the
|
||||
// client already knew (created before the open, or by an earlier open) are candidates too.
|
||||
private const long ContainerRescanDelayMs = AutoIdPolicy.MinAgeMs + 500;
|
||||
|
||||
// Skip objects already appraised this session
|
||||
private static readonly ConcurrentDictionary<uint, byte> _sent = new();
|
||||
// How long an appraisal stays good enough not to repeat: a client re-create inside
|
||||
// this window, and the selected-target priority appraisal, skip an object whose
|
||||
// appraisal is cached and this recent.
|
||||
private const long ReappraiseWindowMs = AutoIdEligibility.DefaultWindowMs;
|
||||
|
||||
// Pending queue
|
||||
private static readonly ConcurrentQueue<uint> _queue = new();
|
||||
// Per-object appraisal bookkeeping. Written on AC's main thread (create, client
|
||||
// release), the plugin pump (server delete) and the drain timer; every access holds
|
||||
// _gate, for a few dictionary operations only.
|
||||
private static readonly AutoIdEligibility _eligibility = new(ReappraiseWindowMs);
|
||||
private static readonly object _gate = new();
|
||||
|
||||
private static readonly AutoIdDrain _drain = new(new LiveWorld());
|
||||
private static int _draining;
|
||||
|
||||
private static Timer? _drainTimer;
|
||||
private static bool _started;
|
||||
|
||||
private static volatile int _mode = (int)AutoIdPolicy.DefaultMode;
|
||||
|
||||
// The container the player opened last (ViewObjectContents), and when.
|
||||
private static int _openedContainerId;
|
||||
private static long _openedAtMs;
|
||||
private static long _rescanDueMs;
|
||||
|
||||
private static long _skippedPriorityFresh;
|
||||
|
||||
/// <summary>The engine behind AutoIdDrain: the PWD snapshot, the appraisal cache, eligibility, the main-thread queue.</summary>
|
||||
private sealed class LiveWorld : IAutoIdWorld
|
||||
{
|
||||
public bool TryGetOwnership(uint id, out uint container, out uint wielder) =>
|
||||
ClientObjectHooks.TryGetObjectOwnershipInfo(id, out container, out wielder, out _);
|
||||
|
||||
public bool SnapshotWarm => ClientObjectHooks.HasPwdSnapshot;
|
||||
|
||||
public int CollectOwned(uint container, Span<uint> dest) =>
|
||||
ClientObjectHooks.CollectOwnedIdsFromSnapshot(container, dest);
|
||||
|
||||
public bool IsLive(uint id)
|
||||
{
|
||||
lock (_gate) return _eligibility.IsLive(id);
|
||||
}
|
||||
|
||||
public bool HasAppraisal(uint id) => AppraisalHooks.HasAppraisalData(id);
|
||||
|
||||
public bool IsFresh(uint id) => AutoIdEligibility.IsAppraisalFresh(
|
||||
AppraisalHooks.HasAppraisalData(id), AppraisalHooks.GetLastIdTime(id),
|
||||
DateTimeOffset.UtcNow.ToUnixTimeSeconds(), ReappraiseWindowMs);
|
||||
|
||||
// Marshal onto AC's main thread (EndScene drain): the Timer thread must not call the
|
||||
// native 0xC8 send directly (off-thread heap alloc + non-atomic UI-counter increment).
|
||||
// The appraisal counts as sent only when the main thread sends it (OnSent, from
|
||||
// AcMainThreadQueue.DrainRequestIds): a queued request dropped there leaves it due again.
|
||||
// Block-bodied, and named apart from the create-path Enqueue, so
|
||||
// tools/check_offthread_mutators.py scans it and its allow-list entry covers only this.
|
||||
public bool QueueIdentify(uint id, IdRequester who)
|
||||
{
|
||||
return AcMainThreadQueue.EnqueueRequestId(id, who);
|
||||
}
|
||||
|
||||
public bool IsContainer(uint id) => ClientObjectHooks.IsContainerInSnapshot(id);
|
||||
}
|
||||
|
||||
/// <summary>Re-creates not appraised because a recent appraisal is still cached.</summary>
|
||||
public static long SkippedRecentCount
|
||||
{
|
||||
get { lock (_gate) return _eligibility.SkippedRecentTotal; }
|
||||
}
|
||||
|
||||
/// <summary>Selected-target priority appraisals skipped because the target's data is cached and fresh.</summary>
|
||||
public static long SkippedPriorityFreshCount => Interlocked.Read(ref _skippedPriorityFresh);
|
||||
|
||||
/// <summary>The live mode (engine.json "AutoIdMode", /rc autoid).</summary>
|
||||
public static AutoIdMode Mode => (AutoIdMode)_mode;
|
||||
|
||||
/// <summary>Switch the mode now; <paramref name="persist"/> also saves it to engine.json.</summary>
|
||||
public static void SetMode(AutoIdMode mode, bool persist)
|
||||
{
|
||||
_mode = (int)mode;
|
||||
if (persist)
|
||||
EngineSettings.AutoIdMode = mode;
|
||||
RynthLog.Compat($"Compat: AutoId mode {AutoIdPolicy.Name(mode)}.");
|
||||
}
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
if (_started)
|
||||
return;
|
||||
_started = true;
|
||||
try { _mode = (int)EngineSettings.AutoIdMode; } catch { }
|
||||
_drainTimer = new Timer(DrainTick, null, DrainIntervalMs, DrainIntervalMs);
|
||||
RynthLog.Verbose("Compat: AutoIdService started.");
|
||||
RynthLog.Verbose($"Compat: AutoIdService started (mode {AutoIdPolicy.Name(Mode)}).");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -56,7 +150,8 @@ internal static class AutoIdService
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enqueue an object for automatic appraisal. Called from CreateObjectHooks detour.
|
||||
/// Enqueue an object for automatic appraisal. Called from CreateObjectHooks detour
|
||||
/// (AC's main thread) and the Decal bridge's create event.
|
||||
/// </summary>
|
||||
public static void Enqueue(uint objectId)
|
||||
{
|
||||
|
|
@ -68,66 +163,291 @@ internal static class AutoIdService
|
|||
if (playerId != 0 && objectId == playerId)
|
||||
return;
|
||||
|
||||
// Skip if already sent this session
|
||||
if (!_sent.TryAdd(objectId, 0))
|
||||
return;
|
||||
// Created again: data kept since a client release is current again (and still cached
|
||||
// if the release was inside ReleasedObjectRetention's time).
|
||||
AppraisalHooks.MarkLive(objectId);
|
||||
bool cached = AppraisalHooks.HasAppraisalData(objectId);
|
||||
long now = Environment.TickCount64;
|
||||
AutoIdEligibility.CreateDecision decision;
|
||||
lock (_gate)
|
||||
decision = _eligibility.OnCreate(objectId, now, cached);
|
||||
|
||||
_queue.Enqueue(objectId);
|
||||
if (decision == AutoIdEligibility.CreateDecision.Appraise)
|
||||
_drain.Offer(objectId, now);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove an object from the sent set (e.g. when it's destroyed and may be recreated).
|
||||
/// The server put <paramref name="itemId"/> into <paramref name="containerId"/>
|
||||
/// (InventoryPutObjInContainer, game event 0x0022; SmartBoxHooks' game-event hook on AC's
|
||||
/// main thread, or the Decal bridge on the pump). In Limited mode an item that landed in
|
||||
/// the player's inventory with nothing cached is a candidate; where it landed is decided
|
||||
/// at the drain, from the object snapshot.
|
||||
/// </summary>
|
||||
public static void Evict(uint objectId)
|
||||
public static void OnPutInContainer(uint itemId, uint containerId)
|
||||
{
|
||||
_sent.TryRemove(objectId, out _);
|
||||
if (itemId == 0 || containerId == 0 || Mode != AutoIdMode.Limited)
|
||||
return;
|
||||
if (AppraisalHooks.HasAppraisalData(itemId))
|
||||
return;
|
||||
_drain.Offer(itemId, Environment.TickCount64);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The client opened <paramref name="containerId"/>'s contents (ViewObjectContents, AC's
|
||||
/// main thread). Its time decides the defer exemption, and a rescan after the minimum
|
||||
/// age makes the items already known in it candidates.
|
||||
/// </summary>
|
||||
public static void OnContainerOpened(uint containerId)
|
||||
{
|
||||
if (containerId == 0) return;
|
||||
long now = Environment.TickCount64;
|
||||
Interlocked.Exchange(ref _openedAtMs, now);
|
||||
Interlocked.Exchange(ref _openedContainerId, unchecked((int)containerId));
|
||||
Interlocked.Exchange(ref _rescanDueMs, now + ContainerRescanDelayMs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The CLIENT released an object (ACCObjectMaint::DeleteObject, or the Decal bridge's
|
||||
/// delete event). A queued appraisal for it is skipped; its last appraisal time is kept,
|
||||
/// so a re-create inside the window is not appraised again.
|
||||
/// </summary>
|
||||
public static void OnClientRelease(uint objectId)
|
||||
{
|
||||
if (objectId == 0) return;
|
||||
lock (_gate)
|
||||
_eligibility.OnClientRelease(objectId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The SERVER deleted an object (0xF747 ObjectDelete, from the server message stream on
|
||||
/// the plugin pump). Whatever is created under that id next is appraised.
|
||||
/// </summary>
|
||||
public static void OnServerDelete(uint objectId)
|
||||
{
|
||||
if (objectId == 0) return;
|
||||
lock (_gate)
|
||||
_eligibility.OnServerDelete(objectId);
|
||||
// It really went away: its kept identify data goes too.
|
||||
AppraisalHooks.EvictObject(objectId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The 0xC8 for <paramref name="objectId"/> really went out (AcMainThreadQueue's drain, on
|
||||
/// AC's main thread, for every RequestId caller). Starts its re-appraisal window.
|
||||
/// </summary>
|
||||
public static void OnSent(uint objectId, long nowMs)
|
||||
{
|
||||
if (objectId == 0) return;
|
||||
lock (_gate)
|
||||
_eligibility.OnSent(objectId, nowMs);
|
||||
}
|
||||
|
||||
// Last target we issued a priority appraisal for (fires once per target change).
|
||||
private static uint _lastPriorityTarget;
|
||||
private static long _lastPruneMs;
|
||||
|
||||
private static void DrainTick(object? state)
|
||||
{
|
||||
// A slow tick must not overlap the next one: the drain's pending list is this timer's alone.
|
||||
if (Interlocked.CompareExchange(ref _draining, 1, 0) != 0)
|
||||
return;
|
||||
try
|
||||
{
|
||||
if (!CombatActionHooks.HasRequestId)
|
||||
return;
|
||||
// Dead / portaling / settling: AcMainThreadQueue refuses appraisals now, so the
|
||||
// backlog waits here instead of being dequeued into a refusal and lost.
|
||||
if (PlayerLifecycleLog.InWorldTransition)
|
||||
return;
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
AutoIdMode mode = Mode;
|
||||
int sent = 0;
|
||||
uint playerId = ClientHelperHooks.GetPlayerId();
|
||||
|
||||
// Combat-target priority: when the selected target CHANGES, appraise it
|
||||
// immediately — enqueued ahead of the create-order backlog so a fast kill
|
||||
// still gets its max-HP appraisal out first instead of waiting behind the
|
||||
// whole spawn. Fires once per change (guarded), so no per-tick re-appraisal.
|
||||
// immediately, ahead of the backlog, so a fast kill still gets its max-HP
|
||||
// appraisal out first. Fires once per change (guarded), so no per-tick
|
||||
// re-appraisal. Skipped when the target's appraisal is already cached and
|
||||
// fresh. Exempt from the minimum age, the defers and the inventory cap. A
|
||||
// refused enqueue forgets the change, so the next tick tries again.
|
||||
uint target = SelectedTargetHooks.ReadCurrentSelectedId();
|
||||
if (target != 0 && target != _lastPriorityTarget)
|
||||
{
|
||||
_lastPriorityTarget = target;
|
||||
uint playerId = ClientHelperHooks.GetPlayerId();
|
||||
if (target != playerId && AcMainThreadQueue.EnqueueRequestId(target))
|
||||
sent++;
|
||||
if (target != playerId)
|
||||
{
|
||||
bool cached = AppraisalHooks.HasAppraisalData(target);
|
||||
bool fresh = AutoIdEligibility.IsAppraisalFresh(
|
||||
cached, AppraisalHooks.GetLastIdTime(target), DateTimeOffset.UtcNow.ToUnixTimeSeconds(), ReappraiseWindowMs);
|
||||
switch (AutoIdPolicy.Decide(mode, AutoIdPolicy.Class.Target, 0, false, false, fresh, cached))
|
||||
{
|
||||
case AutoIdPolicy.Verdict.SkipFresh:
|
||||
Interlocked.Increment(ref _skippedPriorityFresh);
|
||||
_drain.CountSkipFresh();
|
||||
break;
|
||||
case AutoIdPolicy.Verdict.Send:
|
||||
if (AcMainThreadQueue.EnqueueRequestId(target, IdRequester.AutoIdTarget))
|
||||
sent++;
|
||||
else
|
||||
_lastPriorityTarget = 0;
|
||||
break;
|
||||
default:
|
||||
_drain.CountSkipMode();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while (sent < MaxPerTick && _queue.TryDequeue(out uint objectId))
|
||||
{
|
||||
// Object may have been destroyed between enqueue and drain
|
||||
if (objectId == 0)
|
||||
continue;
|
||||
// Deleted since it was queued: Evict took it out of _sent. Skip it without
|
||||
// spending one of the 3 requests per tick. After a big landblock change (the
|
||||
// 585 deletes of 2026-10-02) the queue otherwise kept asking the server to
|
||||
// appraise gone objects at 30 a second for half a minute, and live ones waited.
|
||||
// A delete-then-recreate is queued again by Enqueue, so nothing live is lost.
|
||||
if (!_sent.ContainsKey(objectId))
|
||||
continue;
|
||||
RescanOpenedContainer(now, mode);
|
||||
|
||||
// Marshal onto AC's main thread (EndScene drain) — the Timer thread must
|
||||
// not call the native 0xC8 send directly (off-thread heap alloc + non-atomic
|
||||
// UI-counter increment). EnqueueRequestId is the marshalled path.
|
||||
AcMainThreadQueue.EnqueueRequestId(objectId);
|
||||
sent++;
|
||||
uint open = ClientHelperHooks.GetGroundContainerId();
|
||||
var ctx = new AutoIdDrain.Context
|
||||
{
|
||||
Now = now,
|
||||
Mode = mode,
|
||||
PlayerId = playerId,
|
||||
OpenContainer = open,
|
||||
OpenedAtMs = open != 0 && unchecked((uint)Volatile.Read(ref _openedContainerId)) == open
|
||||
? Interlocked.Read(ref _openedAtMs) : 0,
|
||||
SettleUntilMs = PlayerLifecycleLog.SettleUntilMs,
|
||||
LoginCompleteAtMs = LoginLifecycleHooks.LoginCompleteAtMs,
|
||||
// Each 0xC8 raises AC's busy count, which plugins gate their casts on: the
|
||||
// pack waits while a cast is in flight or an attack runs (not for a selection alone).
|
||||
CombatBusy = AutoIdPolicy.InCombat(target, CastGate.GetCastBusyState(),
|
||||
ClientActionGates.TryReadAttacking(out bool attacking) && attacking),
|
||||
};
|
||||
_drain.Tick(ctx, sent);
|
||||
|
||||
// Keep the bookkeeping bounded. Here, off AC's main thread: the create path
|
||||
// never prunes.
|
||||
if (now - _lastPruneMs >= 10_000)
|
||||
{
|
||||
_lastPruneMs = now;
|
||||
int removed;
|
||||
lock (_gate)
|
||||
removed = _eligibility.Count > _eligibility.MaxTracked / 2 ? _eligibility.Prune(now) : 0;
|
||||
if (removed > 0)
|
||||
RynthLog.Verbose($"Compat: AutoIdService pruned {removed} appraisal record(s).");
|
||||
// Identify data kept after a client release: dropped once its time is up.
|
||||
int expired = AppraisalHooks.ExpireReleased(now);
|
||||
if (expired > 0)
|
||||
RynthLog.Verbose($"Compat: AppraisalHooks dropped {expired} released object(s) past the retention time.");
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref _draining, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Limited mode: the items already in a container the player opened become candidates.</summary>
|
||||
private static void RescanOpenedContainer(long now, AutoIdMode mode)
|
||||
{
|
||||
long due = Interlocked.Read(ref _rescanDueMs);
|
||||
if (due == 0 || now < due)
|
||||
return;
|
||||
Interlocked.CompareExchange(ref _rescanDueMs, 0, due);
|
||||
if (mode != AutoIdMode.Limited)
|
||||
return;
|
||||
uint container = unchecked((uint)Volatile.Read(ref _openedContainerId));
|
||||
if (container == 0 || ClientHelperHooks.GetGroundContainerId() != container)
|
||||
return; // closed again (or another one opened: its own rescan follows)
|
||||
_drain.AddContainerContents(container, Interlocked.Read(ref _openedAtMs), mode);
|
||||
}
|
||||
|
||||
// -- counters: /rc autoid and the per-minute log line --
|
||||
|
||||
private static readonly IdRequester[] Sources =
|
||||
{
|
||||
IdRequester.AutoIdTarget, IdRequester.AutoIdContainer, IdRequester.AutoIdInventory, IdRequester.AutoIdWorld,
|
||||
IdRequester.Plugin, IdRequester.Self, IdRequester.Ui, IdRequester.None,
|
||||
};
|
||||
private static readonly long[] _lastSent = new long[IdRequesters.Count];
|
||||
private static long _lastForeign, _lastSkipMode, _lastSkipAge, _lastSkipDefer, _lastSkipFresh, _lastSkipRate, _lastSkipCombat;
|
||||
|
||||
/// <summary>
|
||||
/// The last minute's IdentifyObject counts (heartbeat thread, once a minute): sent per
|
||||
/// requester, cli = sent by AC or Decal (from the flight recorder; ? while it is off),
|
||||
/// and AutoId's skips by reason. None of its fields contains fps=, plug=, login= or qd=
|
||||
/// (the launcher's heartbeat regex), and the line does not start with "hb #".
|
||||
/// </summary>
|
||||
public static string TakeMinuteLine()
|
||||
{
|
||||
long foreign = FlightRecorder.ForeignIdentifyTotal;
|
||||
long sm = _drain.SkipMode, sa = _drain.SkipAge, sd = _drain.SkipDefer, sf = _drain.SkipFresh, sr = _drain.SkipRate, sc = _drain.SkipCombat;
|
||||
var sb = new System.Text.StringBuilder(176);
|
||||
sb.Append("autoid 60s: mode=").Append(AutoIdPolicy.Name(Mode)).Append(" sent");
|
||||
long total = 0;
|
||||
foreach (IdRequester who in Sources)
|
||||
{
|
||||
long now = IdSendStats.Sent(who);
|
||||
long d = now - _lastSent[(int)who];
|
||||
_lastSent[(int)who] = now;
|
||||
total += d;
|
||||
if (who == IdRequester.None && d == 0) continue; // unmarked engine sends: shown only when there are any
|
||||
sb.Append(' ').Append(IdRequesters.Short(who)).Append('=').Append(d);
|
||||
}
|
||||
if (foreign >= 0)
|
||||
{
|
||||
long d = foreign - _lastForeign;
|
||||
_lastForeign = foreign;
|
||||
total += d;
|
||||
sb.Append(" cli=").Append(d);
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.Append(" cli=?");
|
||||
}
|
||||
sb.Append(" tot=").Append(total);
|
||||
sb.Append(" skip mode=").Append(sm - _lastSkipMode).Append(" age=").Append(sa - _lastSkipAge)
|
||||
.Append(" defer=").Append(sd - _lastSkipDefer).Append(" fresh=").Append(sf - _lastSkipFresh)
|
||||
.Append(" rate=").Append(sr - _lastSkipRate).Append(" combat=").Append(sc - _lastSkipCombat);
|
||||
sb.Append(" pend=").Append(_drain.PendingCount);
|
||||
_lastSkipMode = sm; _lastSkipAge = sa; _lastSkipDefer = sd; _lastSkipFresh = sf; _lastSkipRate = sr; _lastSkipCombat = sc;
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>/rc autoid [all|limited|off|status]</summary>
|
||||
public static string[] HandleCommand(string args)
|
||||
{
|
||||
string verb = (args ?? "").Trim();
|
||||
if (verb.Length > 0 && !verb.Equals("status", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!AutoIdPolicy.TryParseMode(verb, out AutoIdMode mode))
|
||||
return new[] { "Usage: /rc autoid [all|limited|off] (alone: status)" };
|
||||
SetMode(mode, persist: true);
|
||||
}
|
||||
return StatusLines();
|
||||
}
|
||||
|
||||
public static string[] StatusLines()
|
||||
{
|
||||
var sent = new System.Text.StringBuilder();
|
||||
foreach (IdRequester who in Sources)
|
||||
{
|
||||
long n = IdSendStats.Sent(who);
|
||||
if (who == IdRequester.None && n == 0) continue;
|
||||
sent.Append(sent.Length > 0 ? ", " : "").Append(IdRequesters.Short(who)).Append(' ').Append(n);
|
||||
}
|
||||
long foreign = FlightRecorder.ForeignIdentifyTotal;
|
||||
string modeText = Mode switch
|
||||
{
|
||||
AutoIdMode.All => "all (every created object, the old behaviour)",
|
||||
AutoIdMode.Off => "off (no background appraisals, not even the selected target)",
|
||||
_ => $"limited (selected target; open container and own inventory after {AutoIdPolicy.MinAgeMs / 1000} s, {AutoIdPolicy.DeferMs / 1000} s after login or a portal/death/teleport; inventory at most {1000 / AutoIdPolicy.InventoryMinIntervalMs}/s, and not while a cast or attack is in flight)",
|
||||
};
|
||||
string extra = "";
|
||||
if (_drain.Overflow > 0) extra += $", overflow {_drain.Overflow}";
|
||||
if (_drain.IncomingDropped > 0) extra += $", dropped while held {_drain.IncomingDropped}";
|
||||
return new[]
|
||||
{
|
||||
$"AutoId: {modeText}. Saved in engine.json; /rc autoid all|limited|off switches it now. Plugins' own identifies are never limited.",
|
||||
$"Identifies sent since start: {sent}; by AC or Decal: {(foreign >= 0 ? foreign.ToString() : "? (flight recorder off)")}.",
|
||||
$"AutoId skipped: mode {_drain.SkipMode}, fresh {_drain.SkipFresh}, recent re-create {SkippedRecentCount}; " +
|
||||
$"waited: age {_drain.SkipAge}, defer {_drain.SkipDefer}, rate {_drain.SkipRate}, combat {_drain.SkipCombat}; refused {_drain.Refused} (kept); " +
|
||||
$"login sweep {_drain.Swept}; pending now {_drain.PendingCount}{extra}.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
59
src/RynthCore.Engine/Compatibility/CastSlot.cs
Normal file
59
src/RynthCore.Engine/Compatibility/CastSlot.cs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/CastSlot.cs
|
||||
//
|
||||
// AcMainThreadQueue's single-outstanding cast slot (SelectItem + CastSpell pair): one
|
||||
// pending cast at a time, taken by DrainCasts on AC's game-logic tick.
|
||||
//
|
||||
// A cast is refused outright during a world transition (dead, in portal space, or the
|
||||
// settle window after a teleport): the drain would only hold it and then drop it, and
|
||||
// meanwhile the slot would refuse every newer cast. The caller (BuffManager /
|
||||
// CombatManager) already treats false as "retry next tick". Refused like the action ring
|
||||
// refuses non-teardown work during a transition (ActionRing.Admit.RejectedTransition).
|
||||
//
|
||||
// Pure: no engine state, no locking (AcMainThreadQueue holds _castLock for every write;
|
||||
// DrainCasts reads Pending and QueuedAt with Volatile, hence public fields). Compiled
|
||||
// into tools\EngineRobustnessTests.
|
||||
// ============================================================================
|
||||
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal sealed class CastSlot
|
||||
{
|
||||
public enum Admit
|
||||
{
|
||||
Queued,
|
||||
/// <summary>A cast is already pending; nothing changed.</summary>
|
||||
Busy,
|
||||
/// <summary>A world transition is in progress; nothing changed.</summary>
|
||||
RejectedTransition,
|
||||
}
|
||||
|
||||
public int Pending;
|
||||
public uint TargetId;
|
||||
public uint SpellId;
|
||||
/// <summary>TickCount64 when the pending cast was queued.</summary>
|
||||
public long QueuedAt;
|
||||
/// <summary>
|
||||
/// The drain has counted this cast's wait for a movement stop queued before it (once per
|
||||
/// cast). Reset by every queued cast; set by DrainCasts on the main thread.
|
||||
/// </summary>
|
||||
public bool StopWaitNoted;
|
||||
|
||||
/// <summary>Under the caller's lock. The slot is written only when this returns Queued.</summary>
|
||||
public Admit TryEnqueue(uint targetId, uint spellId, long nowMs, bool inTransition)
|
||||
{
|
||||
if (inTransition) return Admit.RejectedTransition;
|
||||
if (Pending != 0) return Admit.Busy;
|
||||
TargetId = targetId;
|
||||
SpellId = spellId;
|
||||
// Volatile: DrainCasts reads both without the lock, and a plain 64-bit store can
|
||||
// tear on x86. The time and the stop-wait reset first, then the flag that publishes
|
||||
// them (a release store, so the drain's Volatile.Read of Pending sees both).
|
||||
Volatile.Write(ref QueuedAt, nowMs);
|
||||
StopWaitNoted = false;
|
||||
Volatile.Write(ref Pending, 1);
|
||||
return Admit.Queued;
|
||||
}
|
||||
}
|
||||
38
src/RynthCore.Engine/Compatibility/CastStopRules.cs
Normal file
38
src/RynthCore.Engine/Compatibility/CastStopRules.cs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/CastStopRules.cs
|
||||
//
|
||||
// The cast drain's question about the action ring: is a movement stop queued at or
|
||||
// before the pending cast? (AcMainThreadQueue.StopQueuedAtOrBefore: such a stop runs
|
||||
// first, so the cast's own stop is not sent while AC's locomotion is still on.)
|
||||
//
|
||||
// Every queued entry is checked. An entry's time is taken before ActionRing's producer
|
||||
// lock, so two producers can land slightly out of time order, and a walk that stopped
|
||||
// at the first entry newer than the cast could miss an older stop queued behind it.
|
||||
//
|
||||
// Pure: no engine state. Consumer side of the ring only (AC's main thread). Compiled
|
||||
// into tools\EngineRobustnessTests.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class CastStopRules
|
||||
{
|
||||
/// <summary>
|
||||
/// True when any entry in <paramref name="ring"/> was queued at or before
|
||||
/// <paramref name="castQueuedAt"/> (by <paramref name="queuedAt"/>) and is a movement stop
|
||||
/// (by <paramref name="isStop"/>). Pass static lambdas: nothing is allocated per call.
|
||||
/// </summary>
|
||||
public static bool AnyStopAtOrBefore<T>(ActionRing<T> ring, long castQueuedAt,
|
||||
Func<T, long> queuedAt, Func<T, bool> isStop) where T : struct
|
||||
{
|
||||
int count = ring.Count;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if (!ring.TryPeekAt(i, out T e)) break;
|
||||
if (queuedAt(e) <= castQueuedAt && isStop(e)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -51,6 +51,17 @@ internal static class CharacterCaptureHooks
|
|||
private const int AutoLoginPollIntervalMs = 600;
|
||||
private const int AutoLoginPollHardTimeoutMs = 120_000;
|
||||
private const int AutoLoginDirectFailsBeforeClick = 4;
|
||||
|
||||
// Bounced back to char-select (2026-10-13): a client relaunched right after a crash got
|
||||
// into the world and was sent back to char-select 7 s later (the server still held the
|
||||
// old session), and auto-login had already stood down, so it sat there for 5 hours.
|
||||
// After entering the world the poll now watches for BounceWindowMs; back at char-select
|
||||
// inside that window it waits (BounceRetryBaseMs x the bounce count, at most
|
||||
// BounceRetryMaxMs) and logs on again, up to MaxBounceRetries times.
|
||||
private const int BounceWindowMs = 90_000;
|
||||
private const int BounceRetryBaseMs = 20_000;
|
||||
private const int BounceRetryMaxMs = 120_000;
|
||||
private const int MaxBounceRetries = 8;
|
||||
private static int _autoLoginPollStarted;
|
||||
|
||||
// Native character-list capture. The 0xF658 packet path is dead (see above),
|
||||
|
|
@ -148,17 +159,38 @@ internal static class CharacterCaptureHooks
|
|||
long charSelectFirstSeenTick = 0;
|
||||
int directFailCount = 0;
|
||||
bool issuedDirect = false;
|
||||
int bounces = 0;
|
||||
string status = string.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
while (EngineThreads.Sleep(AutoLoginPollIntervalMs))
|
||||
{
|
||||
|
||||
if (LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
bool loginComplete = LoginLifecycleHooks.HasObservedLoginComplete;
|
||||
bool inWorld = CharacterManagementHooks.TryGetCurrentMode(out int worldMode) && worldMode == GamePlayUIMode;
|
||||
if (loginComplete || inWorld)
|
||||
{
|
||||
RynthLog.Info($"CharacterCapture: Auto-login complete for '{targetCharacter}' (LoginComplete observed).");
|
||||
Interlocked.Exchange(ref _autoLoginEverFired, 1);
|
||||
return;
|
||||
RynthLog.Info($"CharacterCapture: '{targetCharacter}' is in the world ({(loginComplete ? "LoginComplete observed" : "GamePlayUI")}); watching {BounceWindowMs / 1000}s for a bounce back to char-select.");
|
||||
if (!WatchForBounce(targetCharacter))
|
||||
{
|
||||
Interlocked.Exchange(ref _autoLoginEverFired, 1);
|
||||
return; // stayed in the world (or the engine is stopping)
|
||||
}
|
||||
if (++bounces > MaxBounceRetries)
|
||||
{
|
||||
RynthLog.Warn($"CharacterCapture: '{targetCharacter}' was sent back to char-select {bounces} times; auto-login gives up.");
|
||||
Interlocked.Exchange(ref _autoLoginEverFired, 1);
|
||||
return;
|
||||
}
|
||||
int waitMs = Math.Min(BounceRetryBaseMs * bounces, BounceRetryMaxMs);
|
||||
RynthLog.Warn($"CharacterCapture: '{targetCharacter}' was sent back to char-select right after entering the world (bounce {bounces}/{MaxBounceRetries}, probably the server still holding the last session); logging on again in {waitMs / 1000}s.");
|
||||
if (!WaitAtCharSelect(waitMs))
|
||||
continue; // the player went in by hand: the next pass watches that
|
||||
charSelectFirstSeenTick = 0;
|
||||
directFailCount = 0;
|
||||
issuedDirect = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
// One-shot: if the (currently dead) packet path ever fires and
|
||||
|
|
@ -173,11 +205,7 @@ internal static class CharacterCaptureHooks
|
|||
continue; // UIFlow not ready yet — keep waiting.
|
||||
|
||||
if (mode == GamePlayUIMode)
|
||||
{
|
||||
RynthLog.Compat($"CharacterCapture: Poll stopping for '{targetCharacter}' - client already in GamePlayUI.");
|
||||
Interlocked.Exchange(ref _autoLoginEverFired, 1);
|
||||
return;
|
||||
}
|
||||
continue; // the in-world watch at the top of the loop takes it
|
||||
|
||||
if (mode != CharacterManagementUIMode)
|
||||
{
|
||||
|
|
@ -199,7 +227,7 @@ internal static class CharacterCaptureHooks
|
|||
// Direct path: read AC's native CharacterSet and call LogOnCharacter.
|
||||
// No packet required. Retries every tick if it didn't take.
|
||||
if (CharacterManagementHooks.TryLogOnCharacter(
|
||||
targetCharacter, out string matched, out uint avatarId, out int slotIndex, out string status))
|
||||
targetCharacter, out string matched, out uint avatarId, out int slotIndex, out status))
|
||||
{
|
||||
if (!issuedDirect)
|
||||
{
|
||||
|
|
@ -247,6 +275,39 @@ internal static class CharacterCaptureHooks
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// In the world: true if the client is back at char-select within BounceWindowMs,
|
||||
/// false once it has stayed in the world that long (or the engine is stopping).
|
||||
/// </summary>
|
||||
private static bool WatchForBounce(string targetCharacter)
|
||||
{
|
||||
long since = Environment.TickCount64;
|
||||
while (EngineThreads.Sleep(1000))
|
||||
{
|
||||
if (Environment.TickCount64 - since >= BounceWindowMs)
|
||||
{
|
||||
RynthLog.Info($"CharacterCapture: Auto-login complete for '{targetCharacter}' ({BounceWindowMs / 1000}s in the world).");
|
||||
return false;
|
||||
}
|
||||
if (CharacterManagementHooks.TryGetCurrentMode(out int mode) && mode == CharacterManagementUIMode)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Waits <paramref name="ms"/> at char-select; false if the client entered the world meanwhile.</summary>
|
||||
private static bool WaitAtCharSelect(int ms)
|
||||
{
|
||||
long until = Environment.TickCount64 + ms;
|
||||
while (Environment.TickCount64 < until)
|
||||
{
|
||||
if (!EngineThreads.Sleep(1000)) return false;
|
||||
if (CharacterManagementHooks.TryGetCurrentMode(out int mode) && mode == GamePlayUIMode)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void StartCharacterListCapturePoll()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _characterListCapturePollStarted, 1) != 0)
|
||||
|
|
|
|||
|
|
@ -177,7 +177,7 @@ internal static class ClientCombatHooks
|
|||
// MeleeAttack/MissileAttack, this ran un-marshalled every fight. Marshal
|
||||
// as ONE queue entry (not split into four) so the sequence stays atomic
|
||||
// relative to the drain loop's other actions.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueNativeAttack(attackHeight, power);
|
||||
|
||||
try
|
||||
|
|
|
|||
|
|
@ -36,6 +36,16 @@ internal static class ClientHelperHooks
|
|||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void GmSalvageUISalvageDelegate(IntPtr thisPtr);
|
||||
|
||||
// CM_Inventory::Event_CreateTinkeringTool(ulong toolId, PackableList<ulong> const& items) - cdecl,
|
||||
// returns bool. The 0x027D CreateTinkeringTool game action: what gmSalvageUI::Salvage (the panel's
|
||||
// Salvage button) sends, with the panel's tool (+0x608) and the ids of the items in its list. Chorizite
|
||||
// map 002AB790 -> live VA 0x006AC790; its one caller is gmSalvageUI::Salvage (call at 0x004CC4DB).
|
||||
// Same generated Event_* template as Event_DropItem etc., except the list is packed through its own
|
||||
// vtable (slot 3, PackableList<ulong>::Pack, called once with size 0 for the size, then to write):
|
||||
// wire = opcode, toolId, count, ids. ACE: GameActionCreateTinkeringTool -> Player.HandleSalvaging.
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate byte EventCreateTinkeringToolDelegate(uint toolId, IntPtr packableList);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||
private delegate void UseEquippedItemDelegate(IntPtr acPlugin, uint sourceObjectId, uint targetObjectId);
|
||||
|
||||
|
|
@ -170,6 +180,11 @@ internal static class ClientHelperHooks
|
|||
private const int SendNoticeOpenSalvagePanelVa = 0x006AD4F0;
|
||||
private const int GmSalvageUIAddNewItemVa = 0x004CC020;
|
||||
private const int GmSalvageUISalvageVa = 0x004CC430;
|
||||
// CM_Inventory::Event_CreateTinkeringTool (FALLBACK only; pattern-scanned).
|
||||
private const int EventCreateTinkeringToolVa = 0x006AC790;
|
||||
// PackableList<ulong>'s vtable (.rdata), FALLBACK only: read from the immediate gmSalvageUI::Salvage
|
||||
// writes into its local list (mov [esp+10h], offset vtable @0x004CC448).
|
||||
private const int PackableListULongVtableVa = 0x007A4ED0;
|
||||
|
||||
private static SetSelectedObjectDelegate? _setSelectedObject;
|
||||
private static UseObjectDelegate? _useObject;
|
||||
|
|
@ -191,6 +206,8 @@ internal static class ClientHelperHooks
|
|||
private static SendNoticeOpenSalvagePanelDelegate? _sendNoticeOpenSalvagePanel;
|
||||
private static GmSalvageUIAddNewItemDelegate? _gmSalvageUIAddNewItem;
|
||||
private static GmSalvageUISalvageDelegate? _gmSalvageUISalvage;
|
||||
private static EventCreateTinkeringToolDelegate? _eventCreateTinkeringTool;
|
||||
private static IntPtr _packableListULongVtable;
|
||||
private static bool _initialized;
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
private static int _interactionLogCount;
|
||||
|
|
@ -219,6 +236,11 @@ internal static class ClientHelperHooks
|
|||
public static bool HasWriteToChat => _addTextToScroll != null;
|
||||
public static bool HasInvokeParser => true;
|
||||
public static bool HasSalvagePanel => _sendNoticeOpenSalvagePanel != null && _gmSalvageUIAddNewItem != null && _gmSalvageUISalvage != null;
|
||||
/// <summary>v82: <see cref="SalvageDirect"/> (the 0x027D salvage request without the panel).</summary>
|
||||
public static bool HasSalvageDirect => _eventCreateTinkeringTool != null && _packableListULongVtable != IntPtr.Zero;
|
||||
/// <summary>Most item ids one <see cref="SalvageDirect"/> request carries. ACE reads any count; 100 ids
|
||||
/// keep the game action (header + tool + count + ids, 420 bytes) inside one network fragment.</summary>
|
||||
public const int MaxSalvageDirectItems = 100;
|
||||
private static int _currentGroundContainerId;
|
||||
|
||||
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
|
||||
|
|
@ -263,6 +285,17 @@ internal static class ClientHelperHooks
|
|||
private static readonly byte?[] PatSendNoticeOpenSalvagePanel = [ 0xE8, null, null, null, null, 0x8B, 0x10, 0x68, 0x22 ];
|
||||
private static readonly byte?[] PatGmSalvageUIAddNewItem = [ 0x8B, 0x44, 0x24, 0x04, 0x56, 0x57, 0x50, 0x8B, 0xF9 ];
|
||||
private static readonly byte?[] PatGmSalvageUISalvage = [ 0x83, 0xEC, 0x14, 0x53, 0x56, 0x8B, 0xF1, 0x8B, 0x8E ];
|
||||
// CM_Inventory::Event_CreateTinkeringTool @0x006AC790. The Event_* template with the list argument:
|
||||
// `mov edi,[esp+20h]` (the list) right after the first call, `call [eax+0Ch]` (the list's Pack), and the
|
||||
// 0x027D opcode write (C7 01 7D 02 00 00) at the end. Verified unique (1 match @0x006AC790) via
|
||||
// pe_pattern.py against C:\Games\RynthCore\AcClient and C:\Turbine acclient.exe, 2026-10-12.
|
||||
private static readonly byte?[] PatEventCreateTinkeringTool = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x7C, 0x24, 0x20, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x89, 0x44, 0x24, 0x18, 0x8B, 0x07, 0x51, 0x8B, 0xCF, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x50, 0x0C, 0x6A, 0x00, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x89, 0x44, 0x24, 0x0C, 0x8B, 0xD8, 0x56, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xE8, null, null, null, null, 0x8B, 0x4C, 0x24, 0x0C, 0x8B, 0x54, 0x24, 0x1C, 0xC7, 0x01, 0x7D, 0x02 ];
|
||||
// Data xref for PackableList<ulong>'s vtable: gmSalvageUI::Salvage builds its local list with
|
||||
// `mov [esp+10h], vtable` then zeroes head/tail/count (`mov [esp+14h/18h/1Ch], ebx`) and calls
|
||||
// GetNumUIItems. Operand at +4. Unique (1 site @0x004CC448) in both acclient copies, 2026-10-12.
|
||||
private static readonly byte?[] PatXrefPackableListULongVtable = [ 0xC7, 0x44, 0x24, 0x10, null, null, null, null, 0x89, 0x5C, 0x24, 0x14, 0x89, 0x5C, 0x24, 0x18, 0x89, 0x5C, 0x24, 0x1C, 0xE8 ];
|
||||
// PackableList<ulong>::Pack (vtable slot 3) starts push esi; push edi; mov esi,ecx; call pack_size.
|
||||
private static readonly byte[] PackableListULongPackPrologue = [ 0x56, 0x57, 0x8B, 0xF1, 0xE8 ];
|
||||
|
||||
private static T? Bind<T>(AcClientTextSection text, string name, byte?[] pattern, int fallbackVa) where T : Delegate
|
||||
{
|
||||
|
|
@ -327,6 +360,7 @@ internal static class ClientHelperHooks
|
|||
_sendNoticeOpenSalvagePanel = Bind<SendNoticeOpenSalvagePanelDelegate>(text, "ClientHelper.SendNotice_OpenSalvagePanel", PatSendNoticeOpenSalvagePanel, SendNoticeOpenSalvagePanelVa);
|
||||
_gmSalvageUIAddNewItem = Bind<GmSalvageUIAddNewItemDelegate>(text, "ClientHelper.gmSalvageUI_AddNewItem", PatGmSalvageUIAddNewItem, GmSalvageUIAddNewItemVa);
|
||||
_gmSalvageUISalvage = Bind<GmSalvageUISalvageDelegate>(text, "ClientHelper.gmSalvageUI_Salvage", PatGmSalvageUISalvage, GmSalvageUISalvageVa);
|
||||
BindSalvageDirect(text);
|
||||
_selectedIdAddr = HookResolver.ResolveData(text, "ClientHelper.s_selected_id", PatXrefSelectedId, 2, SelectedIdVa).Address.ToInt32();
|
||||
_prevSelectedIdAddr = HookResolver.ResolveData(text, "ClientHelper.s_previous_selected_id", PatXrefPrevSelectedId, 2, PreviousSelectedIdVa).Address.ToInt32();
|
||||
_uiSystemAddr = HookResolver.ResolveData(text, "ClientHelper.ClientUISystem", PatXrefUiSystem, 2, UiSystemVa).Address.ToInt32();
|
||||
|
|
@ -371,7 +405,7 @@ internal static class ClientHelperHooks
|
|||
// (every UseObject/MoveItem/cast sibling already marshals). Drain re-invokes
|
||||
// this on the main thread, where the gate is satisfied and it runs directly.
|
||||
// SelectItem() funnels through here, so this one gate covers both.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueSetSelectedObject(objectId);
|
||||
|
||||
if (_setSelectedObject == null)
|
||||
|
|
@ -400,7 +434,7 @@ internal static class ClientHelperHooks
|
|||
/// </summary>
|
||||
public static bool SelectFromOverlay(uint objectId)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueOverlaySelect(objectId);
|
||||
|
||||
if (objectId == 0 || _setSelectedObject == null)
|
||||
|
|
@ -433,7 +467,7 @@ internal static class ClientHelperHooks
|
|||
// main thread (via the OnEndScene drain), not off the pump thread. Off-thread
|
||||
// UseObject mutated AC's animation sequence (CSequence) and corrupted it ->
|
||||
// the CSequence::update_internal AV captured after looting was enabled.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueUseObject(objectId);
|
||||
|
||||
if (_useObject == null || !IsValidObjectId(objectId))
|
||||
|
|
@ -466,7 +500,7 @@ internal static class ClientHelperHooks
|
|||
// Marshal onto AC's main thread (off-thread use-on-target mutates AC's
|
||||
// object/animation graph and corrupts it — see UseObject). Drain re-invokes
|
||||
// this on the main thread, where the gate is satisfied and it runs directly.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueUseObjectOn(sourceObjectId, targetObjectId);
|
||||
|
||||
if (_useWithTargetEvent == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
|
||||
|
|
@ -492,7 +526,7 @@ internal static class ClientHelperHooks
|
|||
|
||||
public static bool UseEquippedItem(uint sourceObjectId, uint targetObjectId)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueUseEquippedItem(sourceObjectId, targetObjectId);
|
||||
|
||||
if (_useEquippedItem == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
|
||||
|
|
@ -517,7 +551,7 @@ internal static class ClientHelperHooks
|
|||
{
|
||||
// Marshal onto AC's main thread — off-thread item moves race AC's per-tick
|
||||
// object/container bookkeeping (the looting null-deref AV class).
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueMoveItemExternal(objectId, targetContainerId, amount);
|
||||
|
||||
if (_moveItemExternal == null || !IsValidObjectId(objectId) || !IsValidContainerId(targetContainerId) || amount < 0)
|
||||
|
|
@ -547,7 +581,7 @@ internal static class ClientHelperHooks
|
|||
|
||||
public static bool MoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueMoveItemInternal(objectId, targetContainerId, slot, amount);
|
||||
|
||||
if (_moveItemInternal == null) return false;
|
||||
|
|
@ -604,7 +638,7 @@ internal static class ClientHelperHooks
|
|||
/// </summary>
|
||||
public static bool SplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueSplitStackInternal(objectId, targetContainerId, slot, amount);
|
||||
|
||||
if (_moveItemInternal == null) return false;
|
||||
|
|
@ -656,12 +690,21 @@ internal static class ClientHelperHooks
|
|||
/// </summary>
|
||||
public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId);
|
||||
// Every exit records its outcome in MergeStackResults so the plugin can poll
|
||||
// GetMergeStackResult instead of guessing from a later inventory snapshot.
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
{
|
||||
bool queued = AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId);
|
||||
MergeStackResults.Record(sourceObjectId, targetObjectId,
|
||||
queued ? MergeStackResults.Queued : MergeStackResults.QueueFull);
|
||||
return queued;
|
||||
}
|
||||
|
||||
if (_eventStackableMerge == null) return false;
|
||||
if (!IsValidObjectId(sourceObjectId)) return false;
|
||||
if (!IsValidObjectId(targetObjectId)) return false;
|
||||
if (_eventStackableMerge == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
|
||||
{
|
||||
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read counts via the PWD fast path (stypes 11/12 are served from
|
||||
// PublicWeenieDesc directly — no broken InqInt for inventory items).
|
||||
|
|
@ -680,6 +723,7 @@ internal static class ClientHelperHooks
|
|||
if (room <= 0)
|
||||
{
|
||||
RynthLog.Verbose($"Compat: Event_StackableMerge skipped - target 0x{targetObjectId:X8}({targetCount}) is full (max={maxStack})");
|
||||
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.TargetFull);
|
||||
return false;
|
||||
}
|
||||
amount = Math.Min(sourceCount, room);
|
||||
|
|
@ -690,17 +734,24 @@ internal static class ClientHelperHooks
|
|||
amount = sourceCount;
|
||||
}
|
||||
|
||||
if (amount <= 0) return false;
|
||||
if (amount <= 0)
|
||||
{
|
||||
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
byte rv = _eventStackableMerge(sourceObjectId, targetObjectId, amount);
|
||||
RynthLog.Verbose($"Compat: Event_StackableMerge from=0x{sourceObjectId:X8}({sourceCount}) to=0x{targetObjectId:X8}({targetCount}) amount={amount}/{maxStack} rv={rv}");
|
||||
MergeStackResults.Record(sourceObjectId, targetObjectId,
|
||||
rv != 0 ? MergeStackResults.Sent : MergeStackResults.Failed, rv != 0 ? amount : 0);
|
||||
return rv != 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Compat: Event_StackableMerge threw - {ex.Message}");
|
||||
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -714,7 +765,7 @@ internal static class ClientHelperHooks
|
|||
/// </summary>
|
||||
public static bool PutItemInContainerAt(uint objectId, uint containerId, int slot)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueuePutItemInContainer(objectId, containerId, slot);
|
||||
|
||||
if (_eventPutItemInContainer == null) return false;
|
||||
|
|
@ -749,7 +800,7 @@ internal static class ClientHelperHooks
|
|||
// Marshal onto AC's main thread — off-thread F7B1 inventory sends race AC's
|
||||
// per-tick object/container bookkeeping (the looting null-deref AV class),
|
||||
// exactly like MoveItemExternal / MergeStackInternal.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueGiveObjectTo(objectId, targetId, amount);
|
||||
|
||||
if (_eventGiveObjectRequest == null) return false;
|
||||
|
|
@ -795,7 +846,7 @@ internal static class ClientHelperHooks
|
|||
public static bool WieldItem(uint objectId, uint equipMask)
|
||||
{
|
||||
// Inventory sends run on AC's main thread, like MoveItemExternal / GiveObjectTo.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return _eventGetAndWieldItem != null && IsValidObjectId(objectId) && equipMask != 0
|
||||
&& AcMainThreadQueue.EnqueueWieldItem(objectId, equipMask);
|
||||
|
||||
|
|
@ -825,7 +876,7 @@ internal static class ClientHelperHooks
|
|||
public static bool DropItem(uint objectId)
|
||||
{
|
||||
// Inventory sends run on AC's main thread, like WieldItem / GiveObjectTo.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return _eventDropItem != null && IsValidObjectId(objectId)
|
||||
&& AcMainThreadQueue.EnqueueDropItem(objectId);
|
||||
|
||||
|
|
@ -859,7 +910,7 @@ internal static class ClientHelperHooks
|
|||
public static bool CloseContainer(uint containerId)
|
||||
{
|
||||
// An inventory game-action send, like DropItem / WieldItem: main thread only.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: true))
|
||||
return _eventNoLongerViewingContents != null && IsValidObjectId(containerId)
|
||||
&& AcMainThreadQueue.EnqueueCloseContainer(containerId);
|
||||
|
||||
|
|
@ -964,6 +1015,7 @@ internal static class ClientHelperHooks
|
|||
return;
|
||||
|
||||
Interlocked.Exchange(ref _currentGroundContainerId, unchecked((int)objectId));
|
||||
AutoIdService.OnContainerOpened(objectId);
|
||||
}
|
||||
|
||||
public static void NotifyStopViewingObjectContents(uint objectId)
|
||||
|
|
@ -1151,7 +1203,7 @@ internal static class ClientHelperHooks
|
|||
// same class as the SetSelectedObject 0x60D1D AV. The ring is FIFO with
|
||||
// one consumer, so open -> add -> execute keep their order. Drain calls
|
||||
// back into this method on the main thread, where the gate is satisfied.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueSalvageOpen(toolId);
|
||||
|
||||
try
|
||||
|
|
@ -1193,7 +1245,7 @@ internal static class ClientHelperHooks
|
|||
// queued entry carries only the item id: on the main thread this method
|
||||
// runs again and re-reads the instance, since the panel may have closed
|
||||
// or been rebuilt in between.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueSalvageAddItem(itemId);
|
||||
|
||||
try
|
||||
|
|
@ -1228,7 +1280,7 @@ internal static class ClientHelperHooks
|
|||
|
||||
// Off-thread: same shape as SalvagePanelAddItem (instance re-read on the
|
||||
// main thread when the entry drains).
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueSalvageExecute();
|
||||
|
||||
try
|
||||
|
|
@ -1243,6 +1295,120 @@ internal static class ClientHelperHooks
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Binds CM_Inventory::Event_CreateTinkeringTool and finds PackableList<ulong>'s vtable (the
|
||||
/// sender packs the item list through it). The vtable is accepted only when its slot 3 lands in the
|
||||
/// scanned window on PackableList<ulong>::Pack's prologue, so a wrong address leaves
|
||||
/// <see cref="HasSalvageDirect"/> false instead of handing AC a bad list.
|
||||
/// </summary>
|
||||
private static void BindSalvageDirect(AcClientTextSection text)
|
||||
{
|
||||
_eventCreateTinkeringTool = null;
|
||||
_packableListULongVtable = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
var send = Bind<EventCreateTinkeringToolDelegate>(text, "ClientHelper.Event_CreateTinkeringTool",
|
||||
PatEventCreateTinkeringTool, EventCreateTinkeringToolVa);
|
||||
int vtable = HookResolver.ResolveData(text, "ClientHelper.PackableList_ulong_vtable",
|
||||
PatXrefPackableListULongVtable, 4, PackableListULongVtableVa).Address.ToInt32();
|
||||
|
||||
int slotOff = vtable + 3 * 4 - text.TextBaseVa;
|
||||
if (send == null || slotOff < 0 || slotOff + 4 > text.Bytes.Length)
|
||||
{
|
||||
RynthLog.Compat($"Compat: salvage without the panel unavailable (sender {(send == null ? "not found" : "ok")}, vtable 0x{vtable:X8}).");
|
||||
return;
|
||||
}
|
||||
int pack = BitConverter.ToInt32(text.Bytes, slotOff);
|
||||
int packOff = pack - text.TextBaseVa;
|
||||
bool prologueOk = packOff >= 0 && packOff + PackableListULongPackPrologue.Length <= text.Bytes.Length;
|
||||
for (int i = 0; prologueOk && i < PackableListULongPackPrologue.Length; i++)
|
||||
prologueOk = text.Bytes[packOff + i] == PackableListULongPackPrologue[i];
|
||||
if (!prologueOk)
|
||||
{
|
||||
RynthLog.Compat($"Compat: salvage without the panel unavailable - vtable 0x{vtable:X8} slot 3 (0x{pack:X8}) is not PackableList<ulong>::Pack.");
|
||||
return;
|
||||
}
|
||||
|
||||
_packableListULongVtable = new IntPtr(vtable);
|
||||
_eventCreateTinkeringTool = send;
|
||||
RynthLog.Verbose($"Compat: salvage without the panel ready (PackableList<ulong> vtable 0x{vtable:X8}, Pack 0x{pack:X8}).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_eventCreateTinkeringTool = null;
|
||||
_packableListULongVtable = IntPtr.Zero;
|
||||
RynthLog.Compat($"Compat: salvage-without-panel binding failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Salvage without the salvage panel: sends the 0x027D CreateTinkeringTool game action (what the
|
||||
/// panel's Salvage button sends) through AC's own sender, CM_Inventory::Event_CreateTinkeringTool,
|
||||
/// with <paramref name="toolId"/> (the UST) and <paramref name="itemIds"/> (at most
|
||||
/// <see cref="MaxSalvageDirectItems"/>). The list is a PackableList<ulong> built on this
|
||||
/// stack frame (AC's layout: vtable, head, tail, count; nodes of value, next, prev) and only read by
|
||||
/// the sender, so nothing is allocated in AC's heap and nothing outlives the call. The panel is
|
||||
/// never opened, nothing in the UI changes, and the client's busy count is not touched.
|
||||
///
|
||||
/// ACE (Player.HandleSalvaging) checks the tool is a UST (wcid 20646) the player owns (else
|
||||
/// "That is not a salvaging tool." / "You do not own that salvage tool!"), then for each id an item
|
||||
/// in the player's packs (not worn), with a material and workmanship and not retained, is consumed;
|
||||
/// ids that fail are skipped silently. Salvage bags in the list are merged with the new salvage.
|
||||
/// The answer: the items' removal, new salvage bags created in the pack, and one "You obtain ..."
|
||||
/// line per skill (SalvageOperationsResult, printed by ClientUISystem, not the panel).
|
||||
///
|
||||
/// Off AC's main thread it is queued (the list is copied); true = sent, or queued.
|
||||
/// </summary>
|
||||
public static bool SalvageDirect(uint toolId, uint[] itemIds)
|
||||
{
|
||||
if (!HasSalvageDirect || toolId == 0 || itemIds == null || itemIds.Length == 0 || itemIds.Length > MaxSalvageDirectItems)
|
||||
return false;
|
||||
foreach (uint id in itemIds)
|
||||
if (id == 0 || id == toolId) return false;
|
||||
|
||||
// PR #8's gate: also queued on the main thread while a death/portal transition holds work.
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueSalvageDirect(toolId, itemIds);
|
||||
|
||||
return SendCreateTinkeringTool(toolId, itemIds);
|
||||
}
|
||||
|
||||
private static unsafe bool SendCreateTinkeringTool(uint toolId, uint[] itemIds)
|
||||
{
|
||||
// Main thread only (SalvageDirect marshals; this is its main-thread half).
|
||||
if (!MainThreadGuard.IsOnMainThread()) return false;
|
||||
IntPtr vtable = _packableListULongVtable;
|
||||
if (_eventCreateTinkeringTool == null || vtable == IntPtr.Zero) return false;
|
||||
|
||||
int n = itemIds.Length;
|
||||
// Header (4 dwords) + n nodes of 3 dwords, all on this frame (n <= 100: at most 1216 bytes).
|
||||
uint* buf = stackalloc uint[4 + 3 * MaxSalvageDirectItems];
|
||||
uint* nodes = buf + 4;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
uint* node = nodes + 3 * i;
|
||||
node[0] = itemIds[i]; // value
|
||||
node[1] = i + 1 < n ? (uint)(nint)(nodes + 3 * (i + 1)) : 0u; // next
|
||||
node[2] = i > 0 ? (uint)(nint)(nodes + 3 * (i - 1)) : 0u; // prev
|
||||
}
|
||||
buf[0] = (uint)vtable.ToInt32(); // vtable
|
||||
buf[1] = (uint)(nint)nodes; // head
|
||||
buf[2] = (uint)(nint)(nodes + 3 * (n - 1)); // tail
|
||||
buf[3] = (uint)n; // count
|
||||
|
||||
try
|
||||
{
|
||||
byte rv = _eventCreateTinkeringTool(toolId, (IntPtr)buf);
|
||||
RynthLog.Verbose($"Compat: Event_CreateTinkeringTool tool=0x{toolId:X8} items={n} rv={rv}");
|
||||
return rv != 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Compat: Event_CreateTinkeringTool threw - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool InvokeParser(string? text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
|
|
@ -1288,6 +1454,8 @@ internal static class ClientHelperHooks
|
|||
_sendNoticeOpenSalvagePanel = null;
|
||||
_gmSalvageUIAddNewItem = null;
|
||||
_gmSalvageUISalvage = null;
|
||||
_eventCreateTinkeringTool = null;
|
||||
_packableListULongVtable = IntPtr.Zero;
|
||||
_initialized = false;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -241,6 +241,24 @@ internal static class ClientObjectHooks
|
|||
private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue;
|
||||
private static bool _loggedObjectIdentityServe;
|
||||
private const int ObjectIdentityPrefetchThrottleMs = 500;
|
||||
|
||||
// Create-time identity seeds. ACCObjectMaint::CreateObject receives the server's
|
||||
// PublicWeenieDesc, which already carries the object's name and ITEM_TYPE before
|
||||
// qualities/appraisal exist. The main-thread snapshot above can't resolve names for
|
||||
// ~10 s after login (qualities not populated yet), so off-thread readers fall back to
|
||||
// these seeds when the snapshot has no entry (or reports type 0). Entries live from
|
||||
// create until delete; the cap only guards against a missed delete hook.
|
||||
private static readonly object _createSeedLock = new();
|
||||
private static readonly Dictionary<uint, string> _createSeedNames = new(1024);
|
||||
private static readonly Dictionary<uint, uint> _createSeedTypes = new(1024);
|
||||
private const int CreateSeedCap = 16384;
|
||||
// PublicWeenieDesc field offsets (Chorizite Weenie.cs; same layout the PWD-direct
|
||||
// fallbacks in TryGetObjectName / TryGetItemType read from the embedded copy).
|
||||
// PwdTypeOffset is declared with the other PublicWeenieDesc offsets further down.
|
||||
private const int PwdNameOffset = 4;
|
||||
private static int _createSeedCount;
|
||||
private static bool _loggedCreateSeedServe;
|
||||
|
||||
// Every id the same walk visited, swapped whole (readers never see a half-built array).
|
||||
private static volatile uint[] _liveObjectIds = Array.Empty<uint>();
|
||||
|
||||
|
|
@ -393,6 +411,7 @@ internal static class ClientObjectHooks
|
|||
private static readonly object _weeniePtrSwapLock = new();
|
||||
private static Dictionary<uint, IntPtr> _weeniePtrFront = new(512);
|
||||
private static Dictionary<uint, IntPtr> _weeniePtrBack = new(512);
|
||||
|
||||
// Diagnostic (temporary): periodic snapshot-size log + live-read probe of
|
||||
// objects with a position but no cached name. Remove once the missing-
|
||||
// monsters cause is pinned. _diagSampleBuf preallocated to stay low-alloc.
|
||||
|
|
@ -2019,8 +2038,9 @@ internal static class ClientObjectHooks
|
|||
value = 0;
|
||||
if (pwdFieldOffset < 0 || pwdFieldOffset > 172 || (pwdFieldOffset & 3) != 0)
|
||||
return false;
|
||||
// Off-thread: served from the main-thread PWD byte snapshot, never from AC memory.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return false;
|
||||
return TryGetPwdSnapshotRawInt32(objectId, pwdFieldOffset, out value);
|
||||
if (_getWeenieObject == null)
|
||||
{
|
||||
if (!Probe() || _getWeenieObject == null)
|
||||
|
|
@ -2393,6 +2413,19 @@ internal static class ClientObjectHooks
|
|||
// Off-thread: serve from the main-thread snapshot populated by PrefetchObjectIdentity().
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
{
|
||||
lock (_objectIdentityCacheLock)
|
||||
{
|
||||
// A zero snapshot value means qualities weren't populated when the walk
|
||||
// ran; prefer the create-time descriptor type in that case.
|
||||
if (_objectTypeCache.TryGetValue(objectId, out typeFlags) && typeFlags != 0)
|
||||
return true;
|
||||
}
|
||||
if (TryGetCreateSeedType(objectId, out uint seeded))
|
||||
{
|
||||
typeFlags = seeded;
|
||||
return true;
|
||||
}
|
||||
// Snapshot hit with flags=0 is still an answer (static scenery often has no type).
|
||||
lock (_objectIdentityCacheLock)
|
||||
{
|
||||
if (_objectTypeCache.TryGetValue(objectId, out typeFlags))
|
||||
|
|
@ -2592,36 +2625,7 @@ internal static class ClientObjectHooks
|
|||
return TryGetPwdSnapshotInt(objectId, stype, out value);
|
||||
}
|
||||
|
||||
if (pwdFieldOffset >= 0 && _weeniePhysicsObjOffset >= 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr weeniePtr = _getWeenieObject(objectId);
|
||||
if (weeniePtr == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
int pwdBase = _weeniePhysicsObjOffset + 4;
|
||||
IntPtr fieldAddr = weeniePtr + pwdBase + pwdFieldOffset;
|
||||
// Page-probe BOTH ends of the 4-byte read span (mirrors
|
||||
// TryGetObjectOwnershipInfo's dual-end probe): a freed-but-decommitted
|
||||
// weenie whose field straddles a committed/decommitted page boundary is
|
||||
// an uncatchable AV under NativeAOT; the catch below only covers
|
||||
// null-page faults. All stypes served here are Marshal.ReadInt32
|
||||
// (4 bytes), so the span is [fieldAddr, fieldAddr+3].
|
||||
if (!IsReadablePointer(fieldAddr) || !IsReadablePointer(fieldAddr + 3))
|
||||
return false;
|
||||
|
||||
value = Marshal.ReadInt32(fieldAddr);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Fall through to CBaseQualities::InqInt for stypes not in PWD.
|
||||
// (IsOnMainThread already checked above, before the PWD fast path.)
|
||||
// CBaseQualities::InqInt for stypes not in PWD.
|
||||
if (_inqInt == null)
|
||||
{
|
||||
if (!Probe() || _inqInt == null)
|
||||
|
|
@ -3341,6 +3345,101 @@ internal static class ClientObjectHooks
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records an object's name and ITEM_TYPE straight from the PublicWeenieDesc passed
|
||||
/// to ACCObjectMaint::CreateObject. Called from the create hook on AC's main thread,
|
||||
/// after the original returns. The descriptor is server data that exists before the
|
||||
/// object's qualities do, so this makes names/types readable off-thread immediately
|
||||
/// instead of after the first successful identity snapshot (~10 s at login).
|
||||
/// Every read is pointer-validated; a bad descriptor simply records nothing.
|
||||
/// </summary>
|
||||
internal static void SeedIdentityFromCreate(uint objectId, IntPtr weenieDesc)
|
||||
{
|
||||
if (objectId == 0 || weenieDesc == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
// PublicWeenieDesc derives from PackObj, so a real descriptor starts with an
|
||||
// acclient.exe vtable; reject anything else before reading fields.
|
||||
if (!LooksLikeAcHeapObject(weenieDesc))
|
||||
return;
|
||||
|
||||
bool gotName = TryReadPwdString(weenieDesc, PwdNameOffset, out string name);
|
||||
|
||||
uint typeFlags = 0;
|
||||
IntPtr typeAddr = weenieDesc + PwdTypeOffset;
|
||||
bool gotType = IsReadablePointer(typeAddr);
|
||||
if (gotType)
|
||||
typeFlags = unchecked((uint)Marshal.ReadInt32(typeAddr));
|
||||
|
||||
if (!gotName && (!gotType || typeFlags == 0))
|
||||
return;
|
||||
|
||||
lock (_createSeedLock)
|
||||
{
|
||||
// Safety valve for a missed delete: drop everything rather than grow forever.
|
||||
// The live snapshot covers anything still in the world.
|
||||
if (_createSeedNames.Count >= CreateSeedCap || _createSeedTypes.Count >= CreateSeedCap)
|
||||
{
|
||||
_createSeedNames.Clear();
|
||||
_createSeedTypes.Clear();
|
||||
}
|
||||
if (gotName)
|
||||
_createSeedNames[objectId] = name;
|
||||
if (gotType && typeFlags != 0)
|
||||
_createSeedTypes[objectId] = typeFlags;
|
||||
}
|
||||
|
||||
int seedNo = System.Threading.Interlocked.Increment(ref _createSeedCount);
|
||||
// First few samples let a log reader confirm the descriptor offsets resolve
|
||||
// to sensible names/types on this client build.
|
||||
if (seedNo <= 5)
|
||||
RynthLog.Compat($"[CreateSeed] #{seedNo} 0x{objectId:X8} name='{(gotName ? name : "")}' type=0x{typeFlags:X8}");
|
||||
if (!_loggedCreateSeedServe && seedNo >= 50)
|
||||
{
|
||||
_loggedCreateSeedServe = true;
|
||||
int names, types;
|
||||
lock (_createSeedLock) { names = _createSeedNames.Count; types = _createSeedTypes.Count; }
|
||||
RynthLog.Compat($"ClientObjectHooks: create-descriptor identity seeds active — {names} names, {types} types captured at CreateObject.");
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Descriptor read failures are non-fatal; the periodic snapshot still runs.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drops create-time seeds for a deleted object (called from the delete hook).</summary>
|
||||
internal static void ForgetCreateSeed(uint objectId)
|
||||
{
|
||||
lock (_createSeedLock)
|
||||
{
|
||||
_createSeedNames.Remove(objectId);
|
||||
_createSeedTypes.Remove(objectId);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryGetCreateSeedName(uint objectId, out string name)
|
||||
{
|
||||
lock (_createSeedLock)
|
||||
{
|
||||
if (_createSeedNames.TryGetValue(objectId, out string? seeded) && seeded.Length > 0)
|
||||
{
|
||||
name = seeded;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
name = string.Empty;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryGetCreateSeedType(uint objectId, out uint typeFlags)
|
||||
{
|
||||
lock (_createSeedLock)
|
||||
return _createSeedTypes.TryGetValue(objectId, out typeFlags);
|
||||
}
|
||||
|
||||
public static bool TryGetObjectName(uint objectId, out string name)
|
||||
{
|
||||
name = string.Empty;
|
||||
|
|
@ -3356,6 +3455,10 @@ internal static class ClientObjectHooks
|
|||
return true;
|
||||
}
|
||||
}
|
||||
// Snapshot miss (login burst / object newer than the last walk): serve the
|
||||
// name captured from the create descriptor.
|
||||
if (TryGetCreateSeedName(objectId, out name))
|
||||
return true;
|
||||
name = string.Empty;
|
||||
return false;
|
||||
}
|
||||
|
|
@ -3809,6 +3912,21 @@ internal static class ClientObjectHooks
|
|||
&& PwdLayout.TryGetInt(e.Bytes, stype, out value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Off-thread read of one 4-byte PWD field by raw offset (the <see cref="TryReadPwdInt32"/>
|
||||
/// contract) from the main-thread snapshot. False for objects the last walk didn't see.
|
||||
/// </summary>
|
||||
private static bool TryGetPwdSnapshotRawInt32(uint objectId, int pwdFieldOffset, out int value)
|
||||
{
|
||||
value = 0;
|
||||
if (pwdFieldOffset < 0 || pwdFieldOffset + 4 > PwdLayout.Size)
|
||||
return false;
|
||||
if (!TryGetPwdSnapshot(objectId, out PwdEntry e))
|
||||
return false;
|
||||
value = System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(((ReadOnlySpan<byte>)e.Bytes).Slice(pwdFieldOffset));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryGetPwdSnapshotFloat(uint objectId, uint stype, out double value)
|
||||
{
|
||||
value = 0;
|
||||
|
|
@ -3830,6 +3948,16 @@ internal static class ClientObjectHooks
|
|||
&& PwdLayout.TryGetInstanceId(e.Bytes, stype, out value);
|
||||
}
|
||||
|
||||
/// <summary>The PWD snapshot has been filled at least once (AutoId: an object missing from it may still come).</summary>
|
||||
internal static bool HasPwdSnapshot
|
||||
{
|
||||
get { lock (_weeniePtrSwapLock) return _pwdFront.Count > 0; }
|
||||
}
|
||||
|
||||
/// <summary>The object holds items (ItemsCapacity, stype 6, > 0 in the PWD snapshot: a pack, a chest).</summary>
|
||||
internal static bool IsContainerInSnapshot(uint objectId) =>
|
||||
TryGetPwdSnapshotInt(objectId, 6, out int capacity) && capacity > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Off-thread helper for UpdateObjectInventoryHooks: writes the ids whose PWD
|
||||
/// container or wielder is <paramref name="containerId"/> from the main-thread
|
||||
|
|
|
|||
|
|
@ -332,7 +332,7 @@ internal static class CombatActionHooks
|
|||
|
||||
public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueMeleeAttack(targetId, attackHeight, powerLevel);
|
||||
|
||||
if (_meleeAttack == null)
|
||||
|
|
@ -350,7 +350,7 @@ internal static class CombatActionHooks
|
|||
|
||||
public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueMissileAttack(targetId, attackHeight, accuracyLevel);
|
||||
|
||||
if (_missileAttack == null)
|
||||
|
|
@ -373,7 +373,7 @@ internal static class CombatActionHooks
|
|||
// (CSequence) state on the thread that updates it — eliminating the
|
||||
// off-thread-mutation corruption class (e.g. the CSequence::update_internal
|
||||
// AV). On the main thread (incl. the drain) this executes directly.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueChangeCombatMode(combatMode);
|
||||
|
||||
// Prefer the CLIENT-level entry point. _changeCombatMode is bound by
|
||||
|
|
@ -412,7 +412,7 @@ internal static class CombatActionHooks
|
|||
// same gate. Queued in the action ring so it keeps FIFO order after an attack
|
||||
// that is already queued (it used to run at once and could overtake it). The
|
||||
// drain re-enters here on the main thread, where the gate passes.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: true))
|
||||
return AcMainThreadQueue.EnqueueCancelAttack();
|
||||
|
||||
try
|
||||
|
|
@ -435,7 +435,7 @@ internal static class CombatActionHooks
|
|||
// so off-thread calls go to the non-gesture QueryHealth queue and the drain
|
||||
// re-enters here on the main thread. Callers ignore the result and read the
|
||||
// async 0x01C0 reply, so "queued" is enough.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return targetId != 0 && AcMainThreadQueue.EnqueueQueryHealth(targetId);
|
||||
|
||||
try
|
||||
|
|
@ -461,15 +461,27 @@ internal static class CombatActionHooks
|
|||
// here on the main thread, where this gate passes and the packet is sent.
|
||||
// Fire-and-forget: the appraisal reply is async anyway, so "queued" keeps
|
||||
// the bool's meaning ("requested").
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueRequestId(objectId);
|
||||
// The caller's EngineSendMarker (Net/IdRequester.cs) says who asked: it rides with a
|
||||
// queued request, and a send made under it is registered with the flight recorder so
|
||||
// the 0xC8 shows as [eng:<who>]. Without a marker the send stays [cli].
|
||||
Net.IdRequester who = Net.EngineSendMarker.Current;
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueRequestId(objectId, who);
|
||||
|
||||
// Registered BEFORE the call, so the tag is in place whether AC puts the 0xC8 on the
|
||||
// wire inside the call or later. A call that fails or throws retires its entry, so it
|
||||
// cannot mis-tag a later 0xC8 for the same object.
|
||||
int tag = who != Net.IdRequester.None ? Net.FlightRecorder.EngineSend((byte)who, objectId) : -1;
|
||||
try
|
||||
{
|
||||
return _requestId(objectId);
|
||||
bool sent = _requestId(objectId);
|
||||
if (sent) Net.IdSendStats.CountSent(who);
|
||||
else Net.FlightRecorder.EngineSendFailed(tag, objectId);
|
||||
return sent;
|
||||
}
|
||||
catch
|
||||
{
|
||||
Net.FlightRecorder.EngineSendFailed(tag, objectId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -504,24 +516,23 @@ internal static class CombatActionHooks
|
|||
// which the drain-before order is intended to fix. On the main thread (the
|
||||
// UseTime drain, or any main-thread caller) this falls through to the direct
|
||||
// cast below.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueCast(targetId, (uint)spellId);
|
||||
|
||||
// Call ClientMagicSystem::CastSpell directly off the plugin pump thread.
|
||||
// This is the proven-working casting path (buffs + combat resolve in
|
||||
// chat). The earlier EndScene-marshalled variant (AcMainThreadQueue,
|
||||
// drained from OnEndScene) was REVERTED 2026-05-19: EndScene fires AC's
|
||||
// IncrementBusyCount but is not the context that drives the cast state
|
||||
// machine to completion, so combat casts never produced a projectile /
|
||||
// damage / "You cast" chat — busy leaked, AC's single cast slot jammed
|
||||
// "Casting <spell>" client-wide, and even manual casting died. Do NOT
|
||||
// re-introduce queue/EndScene marshalling for casts.
|
||||
// The documented object-teardown AV (0x0055FA24 [null+0x40] /
|
||||
// 0x00416C86 [null+0x28]) is contained per-callsite by the SEH
|
||||
// trampoline below (__try/__except in RynthCore.SehTrampoline.dll),
|
||||
// which is the correct fix for that AV. AC's CastSpell reads its
|
||||
// "currently selected target" when targetIsSelected=1; SelectItem
|
||||
// first so AC's selection matches the caller's intent.
|
||||
// From here on we are ON AC's main thread: the Client::UseTime cast drain
|
||||
// (AcMainThreadQueue.DrainCasts, before AC's tick) or another main-thread caller.
|
||||
// Nothing below runs on the plugin pump. What was REVERTED earlier is the
|
||||
// EndScene drain for casts: EndScene is not the context that drives the cast state
|
||||
// machine to completion (busy leaked, AC's single cast slot jammed client-wide);
|
||||
// EngineFrameController's EndScene drain still never runs casts.
|
||||
// Two native paths, each through the SEH trampoline (__try/__except in
|
||||
// RynthCore.SehTrampoline.dll), which contains the object-teardown AV
|
||||
// (0x0055FA24 [null+0x40] / 0x00416C86 [null+0x28]) per call:
|
||||
// targeted (targetId != 0): GetMagicSystem() -> FreeHandsAndCastSpell(mgr, spell,
|
||||
// target), the target passed explicitly, NO SelectItem;
|
||||
// self (targetId == 0): ClientMagicSystem::CastSpell(spell, targetIsSelected=0).
|
||||
// While the player is dead, portaling or settling after a landblock jump the drain
|
||||
// holds the cast and drops it once the transition ends (WorldTransitionState).
|
||||
if (_castSpellClient != null)
|
||||
{
|
||||
try
|
||||
|
|
|
|||
|
|
@ -163,7 +163,7 @@ internal static class CommandInterpreterHooks
|
|||
// motion graph the CSequence-AV corruption class kills. Off-thread
|
||||
// callers marshal through the action ring (drained post-tick,
|
||||
// gesture-gated) like every other mutator.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: !enabled))
|
||||
return AcMainThreadQueue.EnqueueSetAutoRun(enabled);
|
||||
int n = System.Threading.Interlocked.Increment(ref _setAutoRunCalls);
|
||||
if (!TryBindDelegates())
|
||||
|
|
@ -269,7 +269,7 @@ internal static class CommandInterpreterHooks
|
|||
|
||||
public static bool SetMotion(uint motion, bool enabled)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: !enabled))
|
||||
return AcMainThreadQueue.EnqueueSetMotion(motion, enabled); // same off-thread class as SetAutoRun
|
||||
if (!TryBindDelegates() || _setMotion == null)
|
||||
return false;
|
||||
|
|
@ -287,7 +287,7 @@ internal static class CommandInterpreterHooks
|
|||
|
||||
public static bool StopCompletely()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: true))
|
||||
return AcMainThreadQueue.EnqueueStopCompletely(); // same off-thread class as SetAutoRun
|
||||
if (!TryBindDelegates() || _stopCompletely == null)
|
||||
return false;
|
||||
|
|
@ -305,7 +305,7 @@ internal static class CommandInterpreterHooks
|
|||
|
||||
public static bool TurnToHeading(float headingDegrees)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueTurnToHeading(headingDegrees); // same off-thread class as SetAutoRun
|
||||
int n = System.Threading.Interlocked.Increment(ref _turnToHeadingCalls);
|
||||
if (!TryBindDelegates() || _turnToHeading == null)
|
||||
|
|
@ -398,7 +398,7 @@ internal static class CommandInterpreterHooks
|
|||
|
||||
public static bool TapJump()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueTapJump();
|
||||
if (!TryBindDelegates())
|
||||
return false;
|
||||
|
|
@ -419,7 +419,7 @@ internal static class CommandInterpreterHooks
|
|||
|
||||
public static bool CommenceJump()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueCommenceJump();
|
||||
if (!TryBindDelegates())
|
||||
return false;
|
||||
|
|
@ -437,7 +437,7 @@ internal static class CommandInterpreterHooks
|
|||
|
||||
public static bool DoJump(bool autonomous)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueDoJumpAutonomous(autonomous);
|
||||
if (!TryBindDelegates())
|
||||
return false;
|
||||
|
|
|
|||
24
src/RynthCore.Engine/Compatibility/CrashExitRule.cs
Normal file
24
src/RynthCore.Engine/Compatibility/CrashExitRule.cs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/CrashExitRule.cs
|
||||
//
|
||||
// Is a process exit code a CRASH exit? ProcessExitHooks passes a crash exit straight to
|
||||
// the original (no managed work on a dying process) after flushing the native crash
|
||||
// logger's recent first-chance records.
|
||||
//
|
||||
// A crash exit is an error-severity status or exception code (both top bits set,
|
||||
// 0xC0000000 and up): 0xC0000005 an access violation, 0xC0000409 a stack buffer overrun,
|
||||
// 0xC0000374 heap corruption, and the software exception codes a runtime exits with on an
|
||||
// unhandled exception, 0xE0434352 (CLR) and 0xE06D7363 (C++).
|
||||
// EXCEPT 0xFFFFFFFF: ExitProcess(-1) is an ordinary "exit with failure", not a fault. The
|
||||
// old rule (code >= 0xC0000000) took it for a crash and skipped the orderly shutdown
|
||||
// of the process.
|
||||
//
|
||||
// Pure. Compiled into tools\EngineRobustnessTests.
|
||||
// ============================================================================
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class CrashExitRule
|
||||
{
|
||||
public static bool IsCrashExit(uint code) => (code & 0xC0000000u) == 0xC0000000u && code != 0xFFFFFFFFu;
|
||||
}
|
||||
|
|
@ -81,6 +81,9 @@ internal static class CreateObjectHooks
|
|||
if (count <= 0)
|
||||
RynthLog.Verbose($"Compat: create object #{count} id=0x{objectId:X8} ptr=0x{result.ToInt32():X8}");
|
||||
|
||||
// Capture name/type from the create descriptor BEFORE the plugin is told about the
|
||||
// object, so its off-thread classifier can read them on the very first attempt.
|
||||
ClientObjectHooks.SeedIdentityFromCreate(objectId, weenieDesc);
|
||||
PluginManager.QueueCreateObject(objectId);
|
||||
AutoIdService.Enqueue(objectId);
|
||||
return result;
|
||||
|
|
|
|||
|
|
@ -426,7 +426,7 @@ internal static unsafe class DecalBridgeHost
|
|||
case BridgeRecordKind.ReleaseObject:
|
||||
PaletteCache.Remove(arg0);
|
||||
PluginManager.QueueDeleteObject(arg0);
|
||||
AutoIdService.Evict(arg0);
|
||||
AutoIdService.OnClientRelease(arg0);
|
||||
break;
|
||||
|
||||
case BridgeRecordKind.ChangeObject:
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ internal static class DeleteObjectHooks
|
|||
private static DeleteObjectDelegate? _originalDeleteObject;
|
||||
private static DeleteObjectDelegate? _deleteObjectDetour;
|
||||
private static IntPtr _targetAddress;
|
||||
private static IntPtr _objectMaint; // ACCObjectMaint* seen on AC's own deletes (RemoveClientObject)
|
||||
private static string _statusMessage = "Not probed yet.";
|
||||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
|
|
@ -68,13 +69,91 @@ internal static class DeleteObjectHooks
|
|||
private static int DeleteObjectDetour(IntPtr thisPtr, uint objectId)
|
||||
{
|
||||
RecursionGuard.Tick("DeleteObjectHooks.DeleteObject");
|
||||
if (thisPtr != IntPtr.Zero) _objectMaint = thisPtr;
|
||||
if (objectId != 0)
|
||||
{
|
||||
ObjectFreshness.Forget(objectId);
|
||||
PaletteCache.Remove(objectId);
|
||||
ClientObjectHooks.ForgetCreateSeed(objectId);
|
||||
PluginManager.QueueDeleteObject(objectId);
|
||||
AutoIdService.Evict(objectId);
|
||||
AutoIdService.OnClientRelease(objectId);
|
||||
}
|
||||
|
||||
return _originalDeleteObject!(thisPtr, objectId);
|
||||
}
|
||||
|
||||
// ── v83 RemoveClientObject: drop a "ghost" from the client (2026-10-12) ──────────────
|
||||
// A ghost is an object the client still draws but the server no longer has for this player
|
||||
// (Drakkon in 0x6146: four Olthoi he stood and swung at for 25 minutes; every attack was
|
||||
// answered by an immediate AttackDone, they never moved and never died). Nothing ever deletes
|
||||
// them: only the server's DeleteObject would, and it doesn't know the client still has them.
|
||||
// This runs the same client function every server DeleteObject ends in -
|
||||
// ACCObjectMaint::DeleteObject(this, id), the one this hook watches - so the client forgets
|
||||
// the object the way it forgets a corpse that decays. If the object is real after all, the
|
||||
// server's next CreateObject for it (when it comes back into view) brings it back.
|
||||
// Refused: no ACCObjectMaint seen yet (no delete since the hook went in), the player, anything
|
||||
// that isn't a creature, players, and any object the server sent a message about in the last
|
||||
// RemoveMinQuietMs (it is real).
|
||||
|
||||
/// <summary>An object the server talked about this recently is never removed.</summary>
|
||||
public const long RemoveMinQuietMs = 5000;
|
||||
|
||||
public enum RemoveResult { Removed = 1, Refused = 0, Unavailable = -1, Queued = 2 }
|
||||
|
||||
/// <summary>True once AC's own DeleteObject has run (the ACCObjectMaint pointer is known).</summary>
|
||||
public static bool CanRemove => IsInstalled && _objectMaint != IntPtr.Zero;
|
||||
|
||||
/// <summary>Why <paramref name="objectId"/> may not be removed, or null when it may.</summary>
|
||||
public static string? RemoveRefusal(uint objectId, long nowMs)
|
||||
{
|
||||
if (objectId == 0) return "no object";
|
||||
uint player = ClientHelperHooks.CachedPlayerId;
|
||||
if (player == 0 || objectId == player) return "the player";
|
||||
if (!ClientObjectHooks.TryGetSnapshotItemType(objectId, out uint type)) return "not in the client's object table";
|
||||
if ((type & 0x10) == 0) return "not a creature";
|
||||
if (ClientObjectHooks.TryGetSnapshotPwdInfo(objectId, out uint bf, out _, out _) && (bf & 0x8) != 0) return "a player";
|
||||
long age = ObjectFreshness.AgeMs(objectId, nowMs);
|
||||
if (age >= 0 && age < RemoveMinQuietMs) return $"the server sent a message about it {age} ms ago";
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Remove <paramref name="objectId"/> from the client (see above). Off AC's main thread
|
||||
/// it is queued and checked again when it runs.</summary>
|
||||
public static RemoveResult RemoveClientObject(uint objectId, out string? refusal)
|
||||
{
|
||||
refusal = null;
|
||||
if (!CanRemove) { refusal = "the client's DeleteObject isn't bound yet"; return RemoveResult.Unavailable; }
|
||||
refusal = RemoveRefusal(objectId, Environment.TickCount64);
|
||||
if (refusal != null) return RemoveResult.Refused;
|
||||
// PR #8's gate: also queued on the main thread while a death/portal transition holds work
|
||||
// (the queue refuses it then, so the caller sees Refused and asks again later).
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueRemoveClientObject(objectId) ? RemoveResult.Queued : RemoveResult.Refused;
|
||||
return RemoveNow(objectId) ? RemoveResult.Removed : RemoveResult.Refused;
|
||||
}
|
||||
|
||||
/// <summary>AC's main thread: the checks again, then ACCObjectMaint::DeleteObject.</summary>
|
||||
internal static bool RemoveNow(uint objectId)
|
||||
{
|
||||
if (!CanRemove || !MainThreadGuard.IsOnMainThread()) return false;
|
||||
string? why = RemoveRefusal(objectId, Environment.TickCount64);
|
||||
if (why != null)
|
||||
{
|
||||
RynthLog.Compat($"RemoveClientObject 0x{objectId:X8}: not removed - {why}.");
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
// Through the detour's original: the hook's own bookkeeping (plugins' OnDeleteObject,
|
||||
// caches) runs as for a server delete.
|
||||
DeleteObjectDetour(_objectMaint, objectId);
|
||||
RynthLog.Compat($"RemoveClientObject 0x{objectId:X8}: removed from the client (ghost).");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"RemoveClientObject 0x{objectId:X8} failed - {ex.GetType().Name}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
110
src/RynthCore.Engine/Compatibility/DragDropHooks.cs
Normal file
110
src/RynthCore.Engine/Compatibility/DragDropHooks.cs
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/DragDropHooks.cs
|
||||
// Hooks UIElementManager::StartDragandDrop so the engine knows which item AC
|
||||
// is actually dragging. AC does not change the selected object when a drag
|
||||
// starts, so the selection is the previously clicked item, not the dragged one.
|
||||
//
|
||||
// The dragged UI element is resolved to an object id with AC's own
|
||||
// UIElement_ItemList::InqDropIconInfo (the same call AC makes when the drop
|
||||
// lands), then handed to ItemDragBridge, which republishes it to ImGui.
|
||||
//
|
||||
// Threads: AC's main thread (AC's input / UI processing).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static unsafe class DragDropHooks
|
||||
{
|
||||
// bool __thiscall UIElementManager::StartDragandDrop(UIElementManager*, UIElement* elem, int clickX, int clickY)
|
||||
private const int StartDragandDropVa = 0x0045E120;
|
||||
// void __cdecl UIElement_ItemList::InqDropIconInfo(const UIElement* icon, uint& itemId, uint& spellId, DropItemFlags& flags)
|
||||
private const int InqDropIconInfoVa = 0x004E3380;
|
||||
|
||||
// Both verified unique in the shipped client (sub esp,34h / mov edi,[esp+48h] / mov esi,ecx prologue;
|
||||
// InqDropIconInfo zeroes its out-params up front).
|
||||
private static readonly byte?[] StartDragandDropPattern =
|
||||
[
|
||||
0x83, 0xEC, 0x34, 0x53, 0x55, 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x48, 0x85, 0xFF, 0x8B, 0xF1, 0x0F, 0x84,
|
||||
null, null, null, null, 0xA1, null, null, null, null, 0x85, 0xC0
|
||||
];
|
||||
private static readonly byte?[] InqDropIconInfoPattern =
|
||||
[
|
||||
0x8B, 0x44, 0x24, 0x10, 0x83, 0xEC, 0x3C, 0x53, 0x55, 0x8B, 0x6C, 0x24, 0x50, 0x56, 0x8B, 0x74, 0x24, 0x4C,
|
||||
0x33, 0xDB, 0x3B, 0xF3, 0x57, 0x8B, 0x7C, 0x24, 0x54, 0x89, 0x1F
|
||||
];
|
||||
|
||||
private static IntPtr _originalStartDrag;
|
||||
private static delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void> _inqDropIconInfo;
|
||||
private static int _logCount;
|
||||
|
||||
/// <summary>The drag-start hook is live, so ItemDragBridge gets the real dragged item.</summary>
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static string StatusMessage { get; private set; } = "Not probed yet.";
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (IsInstalled) return;
|
||||
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
|
||||
{
|
||||
StatusMessage = "acclient.exe not available.";
|
||||
return;
|
||||
}
|
||||
|
||||
var inq = HookResolver.Resolve(text, "DragDrop.InqDropIconInfo", InqDropIconInfoPattern, InqDropIconInfoVa);
|
||||
var start = HookResolver.Resolve(text, "DragDrop.StartDragandDrop", StartDragandDropPattern, StartDragandDropVa);
|
||||
// A guessed address for either would mean calling or patching the wrong code: pattern hits only.
|
||||
if (inq.Source != HookResolver.ResolveSource.PatternScan || start.Source != HookResolver.ResolveSource.PatternScan)
|
||||
{
|
||||
StatusMessage = $"drag-start hook skipped (InqDropIconInfo {inq.Detail}, StartDragandDrop {start.Detail}).";
|
||||
RynthLog.Compat($"Compat: {StatusMessage}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_inqDropIconInfo = (delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void>)inq.Address;
|
||||
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte> detour = &StartDragandDropDetour;
|
||||
MinHook.Hook(start.Address, (IntPtr)detour, out _originalStartDrag);
|
||||
IsInstalled = true;
|
||||
StatusMessage = $"Hooked UIElementManager::StartDragandDrop @ 0x{start.Address.ToInt32():X8}.";
|
||||
RynthLog.Info($"Compat: drag-start hook ready - StartDragandDrop=0x{start.Address.ToInt32():X8}, InqDropIconInfo=0x{inq.Address.ToInt32():X8}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StatusMessage = ex.Message;
|
||||
RynthLog.Compat($"Compat: drag-start hook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
|
||||
private static byte StartDragandDropDetour(IntPtr manager, IntPtr element, int clickX, int clickY)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (element != IntPtr.Zero && _inqDropIconInfo != null)
|
||||
{
|
||||
uint itemId = 0, spellId = 0, flags = 0;
|
||||
_inqDropIconInfo(element, &itemId, &spellId, &flags);
|
||||
// Spell-bar drags carry a spell id and no item.
|
||||
if (itemId != 0)
|
||||
{
|
||||
if (_logCount < 20) { _logCount++; RynthLog.UI($"DragDropHooks: AC drag start item=0x{itemId:X8} flags=0x{flags:X}"); }
|
||||
ItemDragBridge.OnNativeDragStart(itemId);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Compat($"Compat: drag-start detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
}
|
||||
|
||||
var original = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte>)_originalStartDrag;
|
||||
return original(manager, element, clickX, clickY);
|
||||
}
|
||||
}
|
||||
|
|
@ -104,6 +104,15 @@ internal static class EngineStatusMetrics
|
|||
w.WriteNumber("queueDropped", queueDropped);
|
||||
w.WriteNumber("reconciles", reconciles);
|
||||
w.WriteNumber("forceClears", forceClears);
|
||||
// AC's main thread frozen (message box or stale beat) and plugin ticks paused for it
|
||||
// (MainThreadFreeze). pluginTicksPausedMs is a running total: a plugin's stall
|
||||
// detector subtracts its change over the window it measured.
|
||||
bool frozen = false; long stallMs = 0, pausedMs = 0;
|
||||
try { frozen = MainThreadFreeze.Paused; stallMs = MainThreadFreeze.MainThreadStallMs; pausedMs = MainThreadFreeze.PausedTotalMs; }
|
||||
catch { }
|
||||
w.WriteBoolean("mainThreadFrozen", frozen);
|
||||
w.WriteNumber("mainThreadStallMs", stallMs);
|
||||
w.WriteNumber("pluginTicksPausedMs", pausedMs);
|
||||
|
||||
// Player stats, read on the main thread by PrefetchPlayerStats and served here off-thread
|
||||
// (the plugin pump can't read these live). deaths all-time; rates/session = whole-session.
|
||||
|
|
|
|||
|
|
@ -49,10 +49,21 @@ internal static class GameTickHooks
|
|||
|
||||
private static ThisCallBoolDelegate? _originalUseTime;
|
||||
private static ThisCallBoolDelegate? _useTimeDetour;
|
||||
private static IntPtr _originalUseTimePtr;
|
||||
private static IntPtr _targetAddress;
|
||||
private static int _installed;
|
||||
private static int _exitLatch;
|
||||
|
||||
// Native SEH guard around AC's tick (SehTrampoline v4+). A native AV that unwinds into
|
||||
// this managed detour is fatal under CoreCLR; caught natively, it drops one tick instead.
|
||||
// More than MaxTickFaults within TickFaultWindowMs means AC's state is broken rather than
|
||||
// one bad message, so the guard turns itself off and the next fault ends the client.
|
||||
private const int MaxTickFaults = 5;
|
||||
private const long TickFaultWindowMs = 30_000;
|
||||
private static bool _tickGuard;
|
||||
private static int _tickFaults;
|
||||
private static long _tickFaultWindowStart;
|
||||
|
||||
// Verified unique + lands exactly at UseTimeVa offline (tools/pe_pattern.py).
|
||||
// Replaces the prior warn-only prologue check; null = wildcard (rel32 call operand).
|
||||
private static readonly byte?[] UseTimePattern = [ 0x56, 0x8B, 0xF1, 0xE8, null, null, null, null, 0xE8, null, null, null, null, 0x84, 0xC0, 0x74 ];
|
||||
|
|
@ -87,12 +98,14 @@ internal static class GameTickHooks
|
|||
_targetAddress = resolved.Address;
|
||||
_useTimeDetour = UseTimeDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_useTimeDetour);
|
||||
_originalUseTime = Marshal.GetDelegateForFunctionPointer<ThisCallBoolDelegate>(
|
||||
MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
_originalUseTimePtr = MinHook.HookCreate(_targetAddress, detourPtr);
|
||||
_originalUseTime = Marshal.GetDelegateForFunctionPointer<ThisCallBoolDelegate>(_originalUseTimePtr);
|
||||
_tickGuard = SehTrampoline.IsAvailable && SehTrampoline.NativeVersion >= 4;
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
Volatile.Write(ref _installed, 1);
|
||||
RynthLog.Compat($"GameTickHooks: Client::UseTime hooked @ 0x{_targetAddress.ToInt32():X8} ({resolved.Detail}) — cast drain on game-logic tick.");
|
||||
RynthLog.Compat($"GameTickHooks: Client::UseTime hooked @ 0x{_targetAddress.ToInt32():X8} ({resolved.Detail}) — cast drain on game-logic tick; " +
|
||||
(_tickGuard ? "native AV guard on." : $"native AV guard OFF (SehTrampoline v{SehTrampoline.NativeVersion}, needs v4)."));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -111,15 +124,6 @@ internal static class GameTickHooks
|
|||
// 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
|
||||
// selection and the cast initiates, then THIS SAME UseTime call processes it to
|
||||
// completion — mimicking AC's natural input -> UseTime flow. (Draining AFTER the
|
||||
// tick landed self-buffs but not targeted casts: the selection set at the end of
|
||||
// tick N was clobbered before tick N+1 read it.) Alloc-free when no cast is
|
||||
// pending. Must never throw into AC's native frame.
|
||||
try { AcMainThreadQueue.DrainCasts(); }
|
||||
catch { }
|
||||
|
||||
// Refresh TeleportStateHooks' main-thread cache every real game tick. This
|
||||
// detour (unlike EndScene) fires on AC's true main thread in EVERY mode
|
||||
// including Decal-coexistence (no D3D9 hook there) — without this,
|
||||
|
|
@ -130,14 +134,36 @@ internal static class GameTickHooks
|
|||
try { portaling = TeleportStateHooks.IsPortaling; }
|
||||
catch { }
|
||||
// Death / portal space / teleport lines, for lining crashes up with what
|
||||
// the character was doing (PlayerLifecycleLog).
|
||||
// the character was doing (PlayerLifecycleLog). Also the world-transition state the
|
||||
// AcMainThreadQueue drains gate on: sampled BEFORE the cast drain below, so a cast queued
|
||||
// as the player dies is held in this same tick, not run into the death.
|
||||
try { PlayerLifecycleLog.SampleOnGameThread(portaling); }
|
||||
catch { }
|
||||
|
||||
// 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
|
||||
// completion — mimicking AC's natural input -> UseTime flow. (Draining AFTER the
|
||||
// tick landed self-buffs but not targeted casts: the selection set at the end of
|
||||
// tick N was clobbered before tick N+1 read it.) Alloc-free when no cast is
|
||||
// pending. Must never throw into AC's native frame.
|
||||
try { AcMainThreadQueue.DrainCasts(); }
|
||||
catch { }
|
||||
|
||||
// Run AC's own game-logic + physics + animation pass.
|
||||
int result;
|
||||
try { result = _originalUseTime!(thisPtr); }
|
||||
catch { result = 0; }
|
||||
if (_tickGuard)
|
||||
{
|
||||
result = SehTrampoline.GameTickThiscall(_originalUseTimePtr, thisPtr, out bool avCaught,
|
||||
out uint exAddr, out uint dataAddr, out string module);
|
||||
// 0 would end AC's game loop; a dropped tick must keep it running.
|
||||
if (avCaught)
|
||||
result = OnTickFault(exAddr, dataAddr, module);
|
||||
}
|
||||
else
|
||||
{
|
||||
try { result = _originalUseTime!(thisPtr); }
|
||||
catch { result = 0; }
|
||||
}
|
||||
|
||||
// ── Game loop is exiting — quiesce BEFORE AC's teardown ──────────────
|
||||
// AC's main loop is `do { } while (UseTime() != 0)`; a 0 return means
|
||||
|
|
@ -185,6 +211,18 @@ internal static class GameTickHooks
|
|||
// site) is already post-physics in the frame, so it was never the
|
||||
// trigger. (Casts stay PRE-tick above — their selection-timing
|
||||
// requirement, and they go through the separate cast slot.)
|
||||
// Re-sample the world-transition state first: a death, a portal entry or a
|
||||
// landblock jump can begin INSIDE AC's tick above, and the pre-tick sample would
|
||||
// let this drain run queued work into it. Edges are logged once whichever sample
|
||||
// sees them.
|
||||
try
|
||||
{
|
||||
bool portalingAfter = false;
|
||||
try { portalingAfter = TeleportStateHooks.IsPortaling; }
|
||||
catch { }
|
||||
PlayerLifecycleLog.SampleOnGameThread(portalingAfter);
|
||||
}
|
||||
catch { }
|
||||
try { AcMainThreadQueue.Drain(); }
|
||||
catch { }
|
||||
// Main-thread snapshots the pump reads instead of AC memory (player id,
|
||||
|
|
@ -214,4 +252,34 @@ internal static class GameTickHooks
|
|||
// MUST return Client::UseTime's own bool — AC loops do/while on it.
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs a native AV caught inside Client::UseTime and returns the value the detour hands
|
||||
/// back to AC's loop (always 1: keep running). Turns the guard off once faults exceed
|
||||
/// the budget, so a client with corrupted state still dies instead of spinning.
|
||||
/// </summary>
|
||||
private static int OnTickFault(uint exAddr, uint dataAddr, string module)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (_tickFaults == 0 || now - _tickFaultWindowStart > TickFaultWindowMs)
|
||||
{
|
||||
_tickFaultWindowStart = now;
|
||||
_tickFaults = 0;
|
||||
}
|
||||
_tickFaults++;
|
||||
|
||||
string where = module.Length > 0 ? $"{module}+0x{exAddr:X}" : $"0x{exAddr:X8}";
|
||||
try
|
||||
{
|
||||
RynthLog.Error($"GameTickHooks: access violation inside Client::UseTime at {where} (data 0x{dataAddr:X8}); " +
|
||||
$"tick dropped, client kept running (fault {_tickFaults}/{MaxTickFaults} in {TickFaultWindowMs / 1000}s). Full record in native-crash.log.");
|
||||
if (_tickFaults >= MaxTickFaults)
|
||||
{
|
||||
_tickGuard = false;
|
||||
RynthLog.Error("GameTickHooks: Client::UseTime fault budget exhausted; native AV guard OFF for this session.");
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -135,6 +135,11 @@ internal static class HeartbeatLogger
|
|||
// flooding the ring; flat = fine.
|
||||
long dropped = 0;
|
||||
try { dropped = AcMainThreadQueue.DroppedCount; } catch { }
|
||||
// qrej = marshalled actions and casts refused during a world transition
|
||||
// (dead / portal / settle window), a running total kept apart from qdrop: a
|
||||
// jump in qrej around a teleport is the gate working, not a flood.
|
||||
long rejected = 0;
|
||||
try { rejected = AcMainThreadQueue.TransitionRejectedCount; } catch { }
|
||||
// rec = busy reconciles (cast/item-action), fcl = force-clears.
|
||||
// Soak health: rec climbs during combat/loot; fcl stays flat.
|
||||
long rec = 0, fcl = 0;
|
||||
|
|
@ -155,8 +160,28 @@ internal static class HeartbeatLogger
|
|||
catch { }
|
||||
// vafree = free address space (MB): reloads leak engine/plugin copies,
|
||||
// so a client that dies mid-reload can be checked for running out.
|
||||
// valargest = the largest free block (MB): a 32-bit client fails an
|
||||
// allocation on fragmentation long before vafree reaches 0.
|
||||
string vaField = "";
|
||||
try { long free = AddressSpaceMb().FreeMb; if (free >= 0) vaField = $" vafree={free}MB"; }
|
||||
try
|
||||
{
|
||||
long free = AddressSpaceMb().FreeMb;
|
||||
if (free >= 0) vaField = $" vafree={free}MB";
|
||||
long largest = AddressSpace.FreeAndLargestMb().LargestFreeMb;
|
||||
if (largest >= 0) vaField += $" valargest={largest}MB";
|
||||
}
|
||||
catch { }
|
||||
// Crash logger module cache (native): rebuilt every 10 s here, so a fault
|
||||
// never has to call the loader to name a module.
|
||||
if (tick % 10 == 1)
|
||||
{
|
||||
try { SehTrampoline.RefreshCrashLoggerModules(); } catch { }
|
||||
}
|
||||
// Safety net for the main-thread message box count (MainThreadFreeze).
|
||||
MessageBoxHooks.ReconcileStaleMainThreadCount();
|
||||
// pump=paused = plugin ticks paused because AC's main thread is frozen
|
||||
// (MainThreadFreeze); omitted while running.
|
||||
try { if (MainThreadFreeze.Paused) vaField += $" pump=paused stall={MainThreadFreeze.MainThreadStallMs}ms"; }
|
||||
catch { }
|
||||
// req=<type>/<age>s = the client is waiting on an item request (it refuses
|
||||
// every use/move/equip meanwhile); atk=1 = its attacking flag is set. Both
|
||||
|
|
@ -168,7 +193,8 @@ internal static class HeartbeatLogger
|
|||
string vpField = "";
|
||||
try { vpField = D3D9.VideoPatch.OnHeartbeat(draw); }
|
||||
catch { }
|
||||
RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}");
|
||||
// Unfiltered on purpose: it is the launcher's liveness signal (see RynthLog.Heartbeat).
|
||||
RynthLog.Heartbeat($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} qrej={rejected} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}");
|
||||
|
||||
// Every 60 s: garbage collections and the time they paused the process.
|
||||
// Under the CoreCLR host the engine and managed plugins share one GC, so a
|
||||
|
|
@ -176,6 +202,13 @@ internal static class HeartbeatLogger
|
|||
if (tick % 60 == 0)
|
||||
LogGcStats();
|
||||
|
||||
// Every 60 s: IdentifyObject (0xC8) sends by who asked, and AutoId's skips
|
||||
// (AutoIdService.TakeMinuteLine). Its own line, never part of "hb #".
|
||||
if (tick % 60 == 0)
|
||||
{
|
||||
try { RynthLog.Info(AutoIdService.TakeMinuteLine()); } catch { }
|
||||
}
|
||||
|
||||
// Every 5 s: hide and destroy any panel window no live panel owns
|
||||
// (the "double UI" orphans).
|
||||
if (tick % 5 == 0)
|
||||
|
|
|
|||
527
src/RynthCore.Engine/Compatibility/InventoryAttributeFilter.cs
Normal file
527
src/RynthCore.Engine/Compatibility/InventoryAttributeFilter.cs
Normal file
|
|
@ -0,0 +1,527 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/InventoryAttributeFilter.cs
|
||||
// The Inventory panel's attribute filter: rules on an item's attributes
|
||||
// ("Armor Level >= 300", "Spells contain Legendary", "Fits slot Neck"),
|
||||
// matched all or any. Pure: no AC reads. The panel supplies each item's
|
||||
// values through IInventoryFilterFacts (InventoryFilterFacts.cs), so the host
|
||||
// tests link this file alone.
|
||||
//
|
||||
// Two kinds of attribute:
|
||||
// public what every item sends (value, burden, material, slots...)
|
||||
// appraised what only an identify returns (armor level, ratings, spells...).
|
||||
// An item never identified can't be judged on these: Unknown,
|
||||
// which the panel hides and counts ("N not identified").
|
||||
// An appraised attribute the item doesn't have counts as 0 / no / "" (a
|
||||
// weapon's armor level is 0), so "Level to wield <= 150" keeps items with no
|
||||
// requirement.
|
||||
//
|
||||
// Threads: the panel's (render) thread only; the rules are edited and read
|
||||
// there. Saved as one line in inventory_settings.txt (Serialize / Parse).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>How a rule compares the attribute.</summary>
|
||||
internal enum FilterAttrKind : byte { Number, Flag, Text, Choice }
|
||||
|
||||
/// <summary>Where the value comes from and how it is turned into what the rule shows.</summary>
|
||||
internal enum FilterSource : byte
|
||||
{
|
||||
/// <summary>From the item's public description (the panel's InventoryItem).</summary>
|
||||
Public,
|
||||
/// <summary>An appraised int property (0 when absent).</summary>
|
||||
Int,
|
||||
/// <summary>An appraised float property, shown as is.</summary>
|
||||
Float,
|
||||
/// <summary>An appraised float multiplier shown as a bonus percent: 1.15 -> 15.</summary>
|
||||
FloatModPercent,
|
||||
/// <summary>An appraised float fraction shown as a percent: 0.05 -> 5.</summary>
|
||||
FloatPercent,
|
||||
/// <summary>An appraised int that counts as "yes" when not 0.</summary>
|
||||
IntNonZero,
|
||||
/// <summary>An appraised bool property.</summary>
|
||||
Bool,
|
||||
/// <summary>Worked out by the facts provider (level to wield, set name, spells).</summary>
|
||||
Special,
|
||||
}
|
||||
|
||||
/// <summary>Every attribute a rule can test. The persisted key is <see cref="FilterAttrInfo.Key"/>, not the number.</summary>
|
||||
internal enum FilterAttr : byte
|
||||
{
|
||||
// Public
|
||||
Name, Value, Burden, Workmanship, Stack, Material, Slot, Equipped, CastsSpell,
|
||||
// Appraised
|
||||
ArmorLevel, MaxDamage, Speed, AttackBonus, MeleeDefense, MissileDefense, MagicDefense,
|
||||
ElementalDamage, ManaConversion, DamageRating, DamageResistRating, CritRating, CritResistRating,
|
||||
CritDamageRating, CritDamageResistRating, HealingBoostRating, VitalityRating, WieldLevel,
|
||||
ArcaneLore, Spellcraft, MaxMana, Tinkers, MaxItemLevel, SetName, Spells, Imbued, Bonded,
|
||||
Attuned, Retained,
|
||||
}
|
||||
|
||||
/// <summary>One attribute's description: its key, label, kind and where its value lives.</summary>
|
||||
internal sealed class FilterAttrInfo
|
||||
{
|
||||
public FilterAttr Id;
|
||||
public string Key = string.Empty;
|
||||
public string Label = string.Empty;
|
||||
public FilterAttrKind Kind;
|
||||
public FilterSource Source;
|
||||
/// <summary>The appraisal property id (STypeInt / STypeFloat / STypeBool); 0 for public and special.</summary>
|
||||
public uint Stype;
|
||||
public string Tip = string.Empty;
|
||||
/// <summary>Needs an identify (any source but Public).</summary>
|
||||
public bool NeedsId => Source != FilterSource.Public;
|
||||
}
|
||||
|
||||
/// <summary>How a rule tests its attribute. The persisted key is in <see cref="InventoryAttributeFilter.OpKey"/>.</summary>
|
||||
internal enum FilterOp : byte { AtLeast, AtMost, Equal, NotEqual, Yes, No, Contains, NotContains, Is, IsNot }
|
||||
|
||||
/// <summary>What one rule (or the whole filter) says about an item.</summary>
|
||||
internal enum FilterVerdict : byte { Match, NoMatch, Unknown }
|
||||
|
||||
/// <summary>One item's values as a rule sees them. Absent values are 0 / false / "".</summary>
|
||||
internal interface IInventoryFilterFacts
|
||||
{
|
||||
/// <summary>The server's identify answer is cached for this item.</summary>
|
||||
bool Identified { get; }
|
||||
double Number(FilterAttrInfo attr);
|
||||
bool Flag(FilterAttrInfo attr);
|
||||
string Text(FilterAttrInfo attr);
|
||||
/// <summary>The item's ValidLocations (EquipMask) bits, for the Slot choice.</summary>
|
||||
uint SlotMask { get; }
|
||||
}
|
||||
|
||||
/// <summary>One rule. Mutable: the panel's editor changes it in place and bumps the filter's version.</summary>
|
||||
internal sealed class InventoryFilterRule
|
||||
{
|
||||
public FilterAttr Attr;
|
||||
public FilterOp Op;
|
||||
public double Number;
|
||||
public string Text = string.Empty;
|
||||
/// <summary>The choice's index (Slot: into <see cref="InventoryAttributeFilter.SlotNames"/>).</summary>
|
||||
public int Choice;
|
||||
|
||||
public InventoryFilterRule Clone() => new() { Attr = Attr, Op = Op, Number = Number, Text = Text, Choice = Choice };
|
||||
}
|
||||
|
||||
/// <summary>The rule list, its match mode and on/off; evaluation, description and persistence.</summary>
|
||||
internal sealed class InventoryAttributeFilter
|
||||
{
|
||||
public const int MaxRules = 12;
|
||||
|
||||
/// <summary>Off keeps the rules but shows every item.</summary>
|
||||
public bool Enabled;
|
||||
/// <summary>True: any rule matching keeps the item. False: every rule must.</summary>
|
||||
public bool MatchAny;
|
||||
public readonly List<InventoryFilterRule> Rules = new();
|
||||
/// <summary>Bumped on every edit, so the panel knows to rebuild its list.</summary>
|
||||
public int Version { get; private set; }
|
||||
|
||||
/// <summary>On, with at least one rule.</summary>
|
||||
public bool Active => Enabled && Rules.Count > 0;
|
||||
|
||||
/// <summary>Some rule needs an identify (so unknown items can exist and appraisals change matches).</summary>
|
||||
public bool NeedsIdentify
|
||||
{
|
||||
get
|
||||
{
|
||||
foreach (InventoryFilterRule r in Rules)
|
||||
if (Info(r.Attr).NeedsId) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void Touch() => Version++;
|
||||
|
||||
// ── Attributes ──────────────────────────────────────────────────────
|
||||
|
||||
public static readonly FilterAttrInfo[] Attributes = BuildAttributes();
|
||||
|
||||
private static FilterAttrInfo[] BuildAttributes()
|
||||
{
|
||||
var list = new FilterAttrInfo[(int)FilterAttr.Retained + 1];
|
||||
void Add(FilterAttr id, string key, string label, FilterAttrKind kind, FilterSource src, uint stype, string tip) =>
|
||||
list[(int)id] = new FilterAttrInfo { Id = id, Key = key, Label = label, Kind = kind, Source = src, Stype = stype, Tip = tip };
|
||||
|
||||
Add(FilterAttr.Name, "name", "Name", FilterAttrKind.Text, FilterSource.Public, 0, "The item's name.");
|
||||
Add(FilterAttr.Value, "value", "Value", FilterAttrKind.Number, FilterSource.Public, 0, "Pyreal value.");
|
||||
Add(FilterAttr.Burden, "burden", "Burden", FilterAttrKind.Number, FilterSource.Public, 0, "Burden units (a stack's total).");
|
||||
Add(FilterAttr.Workmanship, "work", "Workmanship", FilterAttrKind.Number, FilterSource.Public, 0, "1 to 10; 0 for items without one.");
|
||||
Add(FilterAttr.Stack, "stack", "Stack size", FilterAttrKind.Number, FilterSource.Public, 0, "1 for a single item.");
|
||||
Add(FilterAttr.Material, "material", "Material", FilterAttrKind.Text, FilterSource.Public, 0, "Steel, Silk, Ruby...");
|
||||
Add(FilterAttr.Slot, "slot", "Fits slot", FilterAttrKind.Choice, FilterSource.Public, 0, "Where the item can be worn or wielded.");
|
||||
Add(FilterAttr.Equipped, "equipped", "Equipped", FilterAttrKind.Flag, FilterSource.Public, 0, "Worn or wielded now.");
|
||||
Add(FilterAttr.CastsSpell, "casts", "Casts a spell", FilterAttrKind.Flag, FilterSource.Public, 0, "Has a use spell (scrolls, gems, wands).");
|
||||
|
||||
Add(FilterAttr.ArmorLevel, "al", "Armor level", FilterAttrKind.Number, FilterSource.Int, 28, "Base armor level.");
|
||||
Add(FilterAttr.MaxDamage, "dmg", "Max damage", FilterAttrKind.Number, FilterSource.Int, 44, "A weapon's maximum damage.");
|
||||
Add(FilterAttr.Speed, "speed", "Speed", FilterAttrKind.Number, FilterSource.Int, 49, "Weapon speed (lower is faster).");
|
||||
Add(FilterAttr.AttackBonus, "attack", "Attack bonus %", FilterAttrKind.Number, FilterSource.FloatModPercent, 62, "A weapon's attack skill bonus.");
|
||||
Add(FilterAttr.MeleeDefense, "meleed", "Melee defense %", FilterAttrKind.Number, FilterSource.FloatModPercent, 29, "Melee defense bonus.");
|
||||
Add(FilterAttr.MissileDefense, "missiled", "Missile defense %", FilterAttrKind.Number, FilterSource.FloatModPercent, 149, "Missile defense bonus.");
|
||||
Add(FilterAttr.MagicDefense, "magicd", "Magic defense %", FilterAttrKind.Number, FilterSource.FloatModPercent, 150, "Magic defense bonus.");
|
||||
Add(FilterAttr.ElementalDamage, "elem", "Elemental damage %", FilterAttrKind.Number, FilterSource.FloatModPercent, 152, "A caster's elemental damage bonus.");
|
||||
Add(FilterAttr.ManaConversion, "manac", "Mana conversion %", FilterAttrKind.Number, FilterSource.FloatPercent, 144, "A caster's mana conversion bonus.");
|
||||
Add(FilterAttr.DamageRating, "dr", "Damage rating", FilterAttrKind.Number, FilterSource.Int, 370, "Gear damage rating.");
|
||||
Add(FilterAttr.DamageResistRating, "drr", "Damage resist rating", FilterAttrKind.Number, FilterSource.Int, 371, "Gear damage resistance rating.");
|
||||
Add(FilterAttr.CritRating, "cr", "Crit rating", FilterAttrKind.Number, FilterSource.Int, 372, "Gear critical rating.");
|
||||
Add(FilterAttr.CritResistRating, "crr", "Crit resist rating", FilterAttrKind.Number, FilterSource.Int, 373, "Gear critical resistance rating.");
|
||||
Add(FilterAttr.CritDamageRating, "cdr", "Crit damage rating", FilterAttrKind.Number, FilterSource.Int, 374, "Gear critical damage rating.");
|
||||
Add(FilterAttr.CritDamageResistRating, "cdrr", "Crit damage resist rating", FilterAttrKind.Number, FilterSource.Int, 375, "Gear critical damage resistance rating.");
|
||||
Add(FilterAttr.HealingBoostRating, "heal", "Healing boost rating", FilterAttrKind.Number, FilterSource.Int, 376, "Gear healing boost rating.");
|
||||
Add(FilterAttr.VitalityRating, "vit", "Vitality rating", FilterAttrKind.Number, FilterSource.Int, 379, "Gear max health (vitality) rating.");
|
||||
Add(FilterAttr.WieldLevel, "wieldlvl", "Level to wield", FilterAttrKind.Number, FilterSource.Special, 0, "Character level needed; 0 when none.");
|
||||
Add(FilterAttr.ArcaneLore, "lore", "Arcane lore", FilterAttrKind.Number, FilterSource.Int, 109, "Arcane lore needed to use it.");
|
||||
Add(FilterAttr.Spellcraft, "spellcraft", "Spellcraft", FilterAttrKind.Number, FilterSource.Int, 106, "The item's spellcraft.");
|
||||
Add(FilterAttr.MaxMana, "mana", "Max mana", FilterAttrKind.Number, FilterSource.Int, 108, "The item's mana pool.");
|
||||
Add(FilterAttr.Tinkers, "tinks", "Times tinkered", FilterAttrKind.Number, FilterSource.Int, 171, "Tinkers applied so far.");
|
||||
Add(FilterAttr.MaxItemLevel, "maxlvl", "Max item level", FilterAttrKind.Number, FilterSource.Int, 319, "Aetheria / cloak / leveling items.");
|
||||
Add(FilterAttr.SetName, "set", "Armor set", FilterAttrKind.Text, FilterSource.Special, 265, "Soldier's, Adept's, Cloak War Magic...");
|
||||
Add(FilterAttr.Spells, "spells", "Spells", FilterAttrKind.Text, FilterSource.Special, 0, "Any of the item's spells contains the text.");
|
||||
Add(FilterAttr.Imbued, "imbued", "Imbued", FilterAttrKind.Flag, FilterSource.IntNonZero, 179, "Has an imbue (crushing blow, armor rend...).");
|
||||
Add(FilterAttr.Bonded, "bonded", "Bonded", FilterAttrKind.Flag, FilterSource.IntNonZero, 33, "Bonded, sticky or destroyed on drop.");
|
||||
Add(FilterAttr.Attuned, "attuned", "Attuned", FilterAttrKind.Flag, FilterSource.IntNonZero, 114, "Can't be given away.");
|
||||
Add(FilterAttr.Retained, "retained", "Retained", FilterAttrKind.Flag, FilterSource.Bool, 91, "Won't be sold or salvaged by accident.");
|
||||
return list;
|
||||
}
|
||||
|
||||
public static FilterAttrInfo Info(FilterAttr a) => Attributes[(int)a];
|
||||
|
||||
public static FilterAttrInfo? InfoByKey(string key)
|
||||
{
|
||||
foreach (FilterAttrInfo i in Attributes)
|
||||
if (string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase)) return i;
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── Operators ───────────────────────────────────────────────────────
|
||||
|
||||
private static readonly FilterOp[] NumberOps = { FilterOp.AtLeast, FilterOp.AtMost, FilterOp.Equal, FilterOp.NotEqual };
|
||||
private static readonly FilterOp[] FlagOps = { FilterOp.Yes, FilterOp.No };
|
||||
private static readonly FilterOp[] TextOps = { FilterOp.Contains, FilterOp.NotContains };
|
||||
private static readonly FilterOp[] ChoiceOps = { FilterOp.Is, FilterOp.IsNot };
|
||||
|
||||
/// <summary>The operators that make sense for an attribute kind; the first is the default.</summary>
|
||||
public static FilterOp[] OpsFor(FilterAttrKind kind) => kind switch
|
||||
{
|
||||
FilterAttrKind.Number => NumberOps,
|
||||
FilterAttrKind.Flag => FlagOps,
|
||||
FilterAttrKind.Text => TextOps,
|
||||
_ => ChoiceOps,
|
||||
};
|
||||
|
||||
public static string OpLabel(FilterOp op) => op switch
|
||||
{
|
||||
FilterOp.AtLeast => ">=",
|
||||
FilterOp.AtMost => "<=",
|
||||
FilterOp.Equal => "=",
|
||||
FilterOp.NotEqual => "!=",
|
||||
FilterOp.Yes => "yes",
|
||||
FilterOp.No => "no",
|
||||
FilterOp.Contains => "contains",
|
||||
FilterOp.NotContains => "doesn't contain",
|
||||
FilterOp.Is => "is",
|
||||
_ => "is not",
|
||||
};
|
||||
|
||||
public static string OpKey(FilterOp op) => op switch
|
||||
{
|
||||
FilterOp.AtLeast => "ge",
|
||||
FilterOp.AtMost => "le",
|
||||
FilterOp.Equal => "eq",
|
||||
FilterOp.NotEqual => "ne",
|
||||
FilterOp.Yes => "yes",
|
||||
FilterOp.No => "no",
|
||||
FilterOp.Contains => "has",
|
||||
FilterOp.NotContains => "nothas",
|
||||
FilterOp.Is => "is",
|
||||
_ => "isnot",
|
||||
};
|
||||
|
||||
private static bool TryOpFromKey(string key, out FilterOp op)
|
||||
{
|
||||
for (FilterOp o = FilterOp.AtLeast; o <= FilterOp.IsNot; o++)
|
||||
if (OpKey(o) == key) { op = o; return true; }
|
||||
op = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>A new rule on <paramref name="attr"/> with that attribute's default operator.</summary>
|
||||
public static InventoryFilterRule NewRule(FilterAttr attr) => new() { Attr = attr, Op = OpsFor(Info(attr).Kind)[0] };
|
||||
|
||||
/// <summary>Points <paramref name="rule"/> at another attribute, keeping its operator when it still fits.</summary>
|
||||
public static void SetAttr(InventoryFilterRule rule, FilterAttr attr)
|
||||
{
|
||||
rule.Attr = attr;
|
||||
if (Array.IndexOf(OpsFor(Info(attr).Kind), rule.Op) < 0) rule.Op = OpsFor(Info(attr).Kind)[0];
|
||||
if (Info(attr).Kind == FilterAttrKind.Choice) rule.Choice = Math.Clamp(rule.Choice, 0, SlotNames.Length - 1);
|
||||
}
|
||||
|
||||
// ── Evaluation ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The whole filter on one item. All: any NoMatch wins, then any Unknown. Any: any Match
|
||||
/// wins, then any Unknown. Off or empty: Match.
|
||||
/// </summary>
|
||||
public FilterVerdict Evaluate(IInventoryFilterFacts facts)
|
||||
{
|
||||
if (!Active) return FilterVerdict.Match;
|
||||
bool unknown = false;
|
||||
foreach (InventoryFilterRule r in Rules)
|
||||
{
|
||||
FilterVerdict v = EvaluateRule(r, facts);
|
||||
if (v == FilterVerdict.Unknown) unknown = true;
|
||||
else if (MatchAny && v == FilterVerdict.Match) return FilterVerdict.Match;
|
||||
else if (!MatchAny && v == FilterVerdict.NoMatch) return FilterVerdict.NoMatch;
|
||||
}
|
||||
if (unknown) return FilterVerdict.Unknown;
|
||||
return MatchAny ? FilterVerdict.NoMatch : FilterVerdict.Match;
|
||||
}
|
||||
|
||||
/// <summary>One rule on one item. Unknown when it needs an identify the item doesn't have.</summary>
|
||||
public static FilterVerdict EvaluateRule(InventoryFilterRule rule, IInventoryFilterFacts facts)
|
||||
{
|
||||
FilterAttrInfo info = Info(rule.Attr);
|
||||
// A text rule with no text tests nothing: it never hides an item.
|
||||
if (info.Kind == FilterAttrKind.Text && rule.Text.Length == 0) return FilterVerdict.Match;
|
||||
if (info.NeedsId && !facts.Identified) return FilterVerdict.Unknown;
|
||||
bool ok = info.Kind switch
|
||||
{
|
||||
FilterAttrKind.Number => CompareNumber(facts.Number(info), rule.Op, rule.Number),
|
||||
FilterAttrKind.Flag => facts.Flag(info) == (rule.Op == FilterOp.Yes),
|
||||
FilterAttrKind.Text => facts.Text(info).Contains(rule.Text, StringComparison.OrdinalIgnoreCase) == (rule.Op == FilterOp.Contains),
|
||||
_ => FitsSlot(facts.SlotMask, rule.Choice) == (rule.Op == FilterOp.Is),
|
||||
};
|
||||
return ok ? FilterVerdict.Match : FilterVerdict.NoMatch;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Number comparison. Equal allows half a hundredth either way: percents come from floats
|
||||
/// (1.15 -> 14.999...) and are typed to two places at most.
|
||||
/// </summary>
|
||||
public static bool CompareNumber(double value, FilterOp op, double target)
|
||||
{
|
||||
const double Eps = 1e-6, EqTol = 0.005;
|
||||
return op switch
|
||||
{
|
||||
FilterOp.AtLeast => value >= target - Eps,
|
||||
FilterOp.AtMost => value <= target + Eps,
|
||||
FilterOp.Equal => Math.Abs(value - target) < EqTol,
|
||||
FilterOp.NotEqual => Math.Abs(value - target) >= EqTol,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A raw appraised float as the rule shows it.</summary>
|
||||
public static double Scale(FilterSource source, double raw) => source switch
|
||||
{
|
||||
FilterSource.FloatModPercent => raw == 0 ? 0 : (raw - 1.0) * 100.0,
|
||||
FilterSource.FloatPercent => raw * 100.0,
|
||||
_ => raw,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The level needed to wield: WieldRequirements (158) or WieldRequirements2 (270) = 7
|
||||
/// (Level) gives WieldDifficulty (160) or WieldDifficulty2 (271). 0 when neither is a level.
|
||||
/// </summary>
|
||||
public static int WieldLevel(int req1, int diff1, int req2, int diff2) =>
|
||||
req1 == WieldRequirementLevel ? diff1 : req2 == WieldRequirementLevel ? diff2 : 0;
|
||||
|
||||
public const int WieldRequirementLevel = 7;
|
||||
public const uint StypeWieldRequirements = 158, StypeWieldDifficulty = 160,
|
||||
StypeWieldRequirements2 = 270, StypeWieldDifficulty2 = 271;
|
||||
|
||||
// ── Slots ───────────────────────────────────────────────────────────
|
||||
|
||||
public static readonly string[] SlotNames =
|
||||
{
|
||||
"Head", "Chest", "Abdomen", "Upper arms", "Lower arms", "Hands", "Upper legs", "Lower legs", "Feet",
|
||||
"Neck", "Wrist", "Finger", "Melee weapon", "Shield", "Missile weapon", "Ammunition", "Held (wand, orb)",
|
||||
"Two-handed weapon", "Trinket", "Cloak", "Aetheria",
|
||||
};
|
||||
|
||||
/// <summary>EquipMask bits per <see cref="SlotNames"/> entry (armor and underclothes share a body part).</summary>
|
||||
public static readonly uint[] SlotMasks =
|
||||
{
|
||||
0x00000001, 0x00000002 | 0x00000200, 0x00000004 | 0x00000400, 0x00000008 | 0x00000800,
|
||||
0x00000010 | 0x00001000, 0x00000020, 0x00000040 | 0x00002000, 0x00000080 | 0x00004000, 0x00000100,
|
||||
0x00008000, 0x00030000, 0x000C0000, 0x00100000, 0x00200000, 0x00400000, 0x00800000, 0x01000000,
|
||||
0x02000000, 0x04000000, 0x08000000, 0x70000000,
|
||||
};
|
||||
|
||||
public static bool FitsSlot(uint validLocations, int choice) =>
|
||||
choice >= 0 && choice < SlotMasks.Length && (validLocations & SlotMasks[choice]) != 0;
|
||||
|
||||
// ── Names (material, armor set) ─────────────────────────────────────
|
||||
|
||||
// MaterialType 1..77 (ACE.Entity.Enum.MaterialType), in id order.
|
||||
private const string MaterialIds =
|
||||
"Ceramic,Porcelain,Cloth,Linen,Satin,Silk,Velvet,Wool,Gem,Agate,Amber,Amethyst,Aquamarine,Azurite,"
|
||||
+ "BlackGarnet,BlackOpal,Bloodstone,Carnelian,Citrine,Diamond,Emerald,FireOpal,GreenGarnet,GreenJade,"
|
||||
+ "Hematite,ImperialTopaz,Jet,LapisLazuli,LavenderJade,Malachite,Moonstone,Onyx,Opal,Peridot,RedGarnet,"
|
||||
+ "RedJade,RoseQuartz,Ruby,Sapphire,SmokeyQuartz,Sunstone,TigerEye,Tourmaline,Turquoise,WhiteJade,"
|
||||
+ "WhiteQuartz,WhiteSapphire,YellowGarnet,YellowTopaz,Zircon,Ivory,Leather,ArmoredilloHide,GromnieHide,"
|
||||
+ "ReedSharkHide,Metal,Brass,Bronze,Copper,Gold,Iron,Pyreal,Silver,Steel,Stone,Alabaster,Granite,Marble,"
|
||||
+ "Obsidian,Sandstone,Serpentine,Wood,Ebony,Mahogany,Oak,Pine,Teak";
|
||||
|
||||
// EquipmentSet 0..140 (ACECustom ACE.Entity.Enum.EquipmentSet), in id order.
|
||||
private const string SetIds =
|
||||
"Invalid,Test,Test2,Unknown3,CarraidasBenediction,NobleRelic,AncientRelic,AlduressaRelic,Ninja,EmpyreanRings,"
|
||||
+ "ArmMindHeart,ArmorPerfectLight,ArmorPerfectLight2,Soldiers,Adepts,Archers,Defenders,Tinkers,Crafters,Hearty,"
|
||||
+ "Dexterous,Wise,Swift,Hardened,Reinforced,Interlocking,Flameproof,Acidproof,Coldproof,Lightningproof,"
|
||||
+ "SocietyArmor,ColosseumClothing,GraveyardClothing,OlthoiClothing,NoobieArmor,AetheriaDefense,"
|
||||
+ "AetheriaDestruction,AetheriaFury,AetheriaGrowth,AetheriaVigor,RareDamageResistance,RareDamageBoost,"
|
||||
+ "OlthoiArmorDRed,OlthoiArmorCRat,OlthoiArmorCRed,OlthoiArmorDRat,AlduressaRelicUpgrade,AncientRelicUpgrade,"
|
||||
+ "NobleRelicUpgrade,CloakAlchemy,CloakArcaneLore,CloakArmorTinkering,CloakAssessPerson,CloakLightWeapons,"
|
||||
+ "CloakMissileWeapons,CloakCooking,CloakCreatureEnchantment,CloakCrossbow,CloakFinesseWeapons,CloakDeception,"
|
||||
+ "CloakFletching,CloakHealing,CloakItemEnchantment,CloakItemTinkering,CloakLeadership,CloakLifeMagic,"
|
||||
+ "CloakLoyalty,CloakMace,CloakMagicDefense,CloakMagicItemTinkering,CloakManaConversion,CloakMeleeDefense,"
|
||||
+ "CloakMissileDefense,CloakSalvaging,CloakSpear,CloakStaff,CloakHeavyWeapons,CloakThrownWeapon,"
|
||||
+ "CloakTwoHandedCombat,CloakUnarmedCombat,CloakVoidMagic,CloakWarMagic,CloakWeaponTinkering,"
|
||||
+ "CloakAssessCreature,CloakDirtyFighting,CloakDualWield,CloakRecklessness,CloakShield,CloakSneakAttack,"
|
||||
+ "Ninja_New,CloakSummoning,ShroudedSoul,DarkenedMind,CloudedSpirit,MinorStingingShroudedSoul,"
|
||||
+ "MinorSparkingShroudedSoul,MinorSmolderingShroudedSoul,MinorShiveringShroudedSoul,MinorStingingDarkenedMind,"
|
||||
+ "MinorSparkingDarkenedMind,MinorSmolderingDarkenedMind,MinorShiveringDarkenedMind,MinorStingingCloudedSpirit,"
|
||||
+ "MinorSparkingCloudedSpirit,MinorSmolderingCloudedSpirit,MinorShiveringCloudedSpirit,"
|
||||
+ "MajorStingingShroudedSoul,MajorSparkingShroudedSoul,MajorSmolderingShroudedSoul,MajorShiveringShroudedSoul,"
|
||||
+ "MajorStingingDarkenedMind,MajorSparkingDarkenedMind,MajorSmolderingDarkenedMind,MajorShiveringDarkenedMind,"
|
||||
+ "MajorStingingCloudedSpirit,MajorSparkingCloudedSpirit,MajorSmolderingCloudedSpirit,"
|
||||
+ "MajorShiveringCloudedSpirit,BlackfireStingingShroudedSoul,BlackfireSparkingShroudedSoul,"
|
||||
+ "BlackfireSmolderingShroudedSoul,BlackfireShiveringShroudedSoul,BlackfireStingingDarkenedMind,"
|
||||
+ "BlackfireSparkingDarkenedMind,BlackfireSmolderingDarkenedMind,BlackfireShiveringDarkenedMind,"
|
||||
+ "BlackfireStingingCloudedSpirit,BlackfireSparkingCloudedSpirit,BlackfireSmolderingCloudedSpirit,"
|
||||
+ "BlackfireShiveringCloudedSpirit,ShimmeringShadowsSet,BrownSocietyLocket,YellowSocietyLocket,"
|
||||
+ "RedSocietyBand,GreenSocietyBand,PurpleSocietyBand,BlueSocietyBand,GauntletGarb,ParagonMissile,"
|
||||
+ "ParagonCaster,ParagonMelee";
|
||||
|
||||
private static readonly string[] Materials = SplitNames(MaterialIds);
|
||||
private static readonly string[] Sets = SplitNames(SetIds);
|
||||
|
||||
/// <summary>"Black Garnet" for MaterialType 15; "" for 0 and ids past the list.</summary>
|
||||
public static string MaterialName(int materialType) =>
|
||||
materialType >= 1 && materialType <= Materials.Length ? Materials[materialType - 1] : string.Empty;
|
||||
|
||||
/// <summary>"Cloak War Magic" for EquipmentSet 81; "Set 200" for an id past the list; "" for none.</summary>
|
||||
public static string SetName(int setId) =>
|
||||
setId <= 0 ? string.Empty
|
||||
: setId < Sets.Length ? Sets[setId]
|
||||
: "Set " + setId.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
private static string[] SplitNames(string ids)
|
||||
{
|
||||
string[] parts = ids.Split(',');
|
||||
for (int i = 0; i < parts.Length; i++) parts[i] = Words(parts[i]);
|
||||
return parts;
|
||||
}
|
||||
|
||||
/// <summary>"CloakWarMagic" -> "Cloak War Magic"; underscores become spaces.</summary>
|
||||
public static string Words(string id)
|
||||
{
|
||||
var sb = new StringBuilder(id.Length + 6);
|
||||
for (int i = 0; i < id.Length; i++)
|
||||
{
|
||||
char c = id[i];
|
||||
if (c == '_') { sb.Append(' '); continue; }
|
||||
// A capital starts a word after a lower-case letter or digit, or ends a run of
|
||||
// capitals when a lower-case letter follows ("ArmorDRed" -> "Armor D Red").
|
||||
if (i > 0 && char.IsUpper(c))
|
||||
{
|
||||
char prev = id[i - 1];
|
||||
bool nextLower = i + 1 < id.Length && char.IsLower(id[i + 1]);
|
||||
if (char.IsLower(prev) || char.IsDigit(prev) || (char.IsUpper(prev) && nextLower)) sb.Append(' ');
|
||||
}
|
||||
sb.Append(c);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
// ── Description ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>"Armor level >= 300", "Spells contains Legendary", "Fits slot is Neck".</summary>
|
||||
public static string Describe(InventoryFilterRule rule)
|
||||
{
|
||||
FilterAttrInfo info = Info(rule.Attr);
|
||||
string what = info.Kind switch
|
||||
{
|
||||
FilterAttrKind.Number => " " + rule.Number.ToString("0.##", CultureInfo.InvariantCulture),
|
||||
FilterAttrKind.Text => " \"" + rule.Text + "\"",
|
||||
FilterAttrKind.Choice => " " + (rule.Choice >= 0 && rule.Choice < SlotNames.Length ? SlotNames[rule.Choice] : "?"),
|
||||
_ => string.Empty,
|
||||
};
|
||||
return info.Label + " " + OpLabel(rule.Op) + what;
|
||||
}
|
||||
|
||||
/// <summary>The rules joined with " and " / " or ", for the panel's tooltip.</summary>
|
||||
public string Summary()
|
||||
{
|
||||
if (Rules.Count == 0) return "No rules.";
|
||||
var sb = new StringBuilder();
|
||||
for (int i = 0; i < Rules.Count; i++)
|
||||
{
|
||||
if (i > 0) sb.Append(MatchAny ? " or " : " and ");
|
||||
sb.Append(Describe(Rules[i]));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
// ── Persistence ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// One line: "v1;on|off;all|any;" then rules split by ';', each "key,op,number,choice,text"
|
||||
/// (text URL-escaped so ',' and ';' can't break it).
|
||||
/// </summary>
|
||||
public string Serialize()
|
||||
{
|
||||
var sb = new StringBuilder("v1;");
|
||||
sb.Append(Enabled ? "on" : "off").Append(';').Append(MatchAny ? "any" : "all");
|
||||
foreach (InventoryFilterRule r in Rules)
|
||||
{
|
||||
sb.Append(';').Append(Info(r.Attr).Key).Append(',').Append(OpKey(r.Op)).Append(',')
|
||||
.Append(r.Number.ToString("R", CultureInfo.InvariantCulture)).Append(',')
|
||||
.Append(r.Choice.ToString(CultureInfo.InvariantCulture)).Append(',')
|
||||
.Append(Uri.EscapeDataString(r.Text));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads <see cref="Serialize"/>'s line. Unknown attributes and broken rules are skipped,
|
||||
/// so an older engine's or a hand-edited line still loads what it can.
|
||||
/// </summary>
|
||||
public static InventoryAttributeFilter Parse(string? line)
|
||||
{
|
||||
var f = new InventoryAttributeFilter();
|
||||
if (string.IsNullOrWhiteSpace(line)) return f;
|
||||
string[] parts = line.Trim().Split(';');
|
||||
if (parts.Length < 3 || parts[0] != "v1") return f;
|
||||
f.Enabled = parts[1] == "on";
|
||||
f.MatchAny = parts[2] == "any";
|
||||
for (int i = 3; i < parts.Length && f.Rules.Count < MaxRules; i++)
|
||||
{
|
||||
string[] r = parts[i].Split(',');
|
||||
if (r.Length < 5) continue;
|
||||
FilterAttrInfo? info = InfoByKey(r[0]);
|
||||
if (info == null || !TryOpFromKey(r[1], out FilterOp op)) continue;
|
||||
if (Array.IndexOf(OpsFor(info.Kind), op) < 0) continue;
|
||||
if (!double.TryParse(r[2], NumberStyles.Float, CultureInfo.InvariantCulture, out double num) || !double.IsFinite(num)) num = 0;
|
||||
if (!int.TryParse(r[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out int choice)) choice = 0;
|
||||
string text;
|
||||
try { text = Uri.UnescapeDataString(r[4]); }
|
||||
catch (UriFormatException) { text = string.Empty; }
|
||||
f.Rules.Add(new InventoryFilterRule
|
||||
{
|
||||
Attr = info.Id,
|
||||
Op = op,
|
||||
Number = num,
|
||||
Choice = info.Kind == FilterAttrKind.Choice ? Math.Clamp(choice, 0, SlotNames.Length - 1) : choice,
|
||||
Text = text,
|
||||
});
|
||||
}
|
||||
return f;
|
||||
}
|
||||
}
|
||||
112
src/RynthCore.Engine/Compatibility/InventoryFilterFacts.cs
Normal file
112
src/RynthCore.Engine/Compatibility/InventoryFilterFacts.cs
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/InventoryFilterFacts.cs
|
||||
// One item's values for the Inventory panel's attribute filter
|
||||
// (InventoryAttributeFilter): public ones from the panel's InventoryItem,
|
||||
// appraised ones from AppraisalHooks' cache (filled by an identify).
|
||||
//
|
||||
// Threads: the panel's (render) thread. AppraisalHooks' getters lock their
|
||||
// cache and PortalSpellTable's lookups read an immutable table, so neither
|
||||
// touches AC. One instance is re-bound per item (no allocation per item
|
||||
// except a spells string, built only when a rule asks for it).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Text;
|
||||
using RynthCore.Engine.ImGuiBackend.Hud;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal sealed class InventoryFilterFacts : IInventoryFilterFacts
|
||||
{
|
||||
private InventoryItem _item = null!;
|
||||
private bool _identified;
|
||||
private string? _spells;
|
||||
private readonly uint[] _spellBuf = new uint[64];
|
||||
private readonly StringBuilder _sb = new(256);
|
||||
|
||||
/// <summary>Points the facts at <paramref name="item"/>; cheap.</summary>
|
||||
public void Bind(InventoryItem item)
|
||||
{
|
||||
_item = item;
|
||||
_identified = AppraisalHooks.HasAppraisalData(item.Id);
|
||||
_spells = null;
|
||||
}
|
||||
|
||||
public bool Identified => _identified;
|
||||
public uint SlotMask => _item.ValidLocations;
|
||||
|
||||
public double Number(FilterAttrInfo attr)
|
||||
{
|
||||
uint id = _item.Id;
|
||||
switch (attr.Source)
|
||||
{
|
||||
case FilterSource.Public:
|
||||
return attr.Id switch
|
||||
{
|
||||
FilterAttr.Value => _item.Value,
|
||||
FilterAttr.Burden => _item.Burden,
|
||||
FilterAttr.Workmanship => _item.Workmanship,
|
||||
FilterAttr.Stack => Math.Max(1, _item.Stack),
|
||||
_ => 0,
|
||||
};
|
||||
case FilterSource.Int:
|
||||
return AppraisalHooks.TryGetCachedIntProperty(id, attr.Stype, out int i) ? i : 0;
|
||||
case FilterSource.Float:
|
||||
case FilterSource.FloatModPercent:
|
||||
case FilterSource.FloatPercent:
|
||||
return AppraisalHooks.TryGetCachedDoubleProperty(id, attr.Stype, out double d)
|
||||
? InventoryAttributeFilter.Scale(attr.Source, d) : 0;
|
||||
case FilterSource.Special when attr.Id == FilterAttr.WieldLevel:
|
||||
return InventoryAttributeFilter.WieldLevel(
|
||||
IntOr0(id, InventoryAttributeFilter.StypeWieldRequirements),
|
||||
IntOr0(id, InventoryAttributeFilter.StypeWieldDifficulty),
|
||||
IntOr0(id, InventoryAttributeFilter.StypeWieldRequirements2),
|
||||
IntOr0(id, InventoryAttributeFilter.StypeWieldDifficulty2));
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Flag(FilterAttrInfo attr) => attr.Source switch
|
||||
{
|
||||
FilterSource.Public => attr.Id switch
|
||||
{
|
||||
FilterAttr.Equipped => _item.Wielder != 0,
|
||||
FilterAttr.CastsSpell => _item.SpellId != 0,
|
||||
_ => false,
|
||||
},
|
||||
FilterSource.IntNonZero => IntOr0(_item.Id, attr.Stype) != 0,
|
||||
FilterSource.Bool => AppraisalHooks.TryGetCachedBoolProperty(_item.Id, attr.Stype, out bool b) && b,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
public string Text(FilterAttrInfo attr) => attr.Id switch
|
||||
{
|
||||
FilterAttr.Name => _item.Name,
|
||||
FilterAttr.Material => InventoryAttributeFilter.MaterialName(_item.MaterialType),
|
||||
FilterAttr.SetName => InventoryAttributeFilter.SetName(IntOr0(_item.Id, attr.Stype)),
|
||||
FilterAttr.Spells => _spells ??= SpellNames(),
|
||||
_ => string.Empty,
|
||||
};
|
||||
|
||||
private static int IntOr0(uint id, uint stype) =>
|
||||
AppraisalHooks.TryGetCachedIntProperty(id, stype, out int v) ? v : 0;
|
||||
|
||||
/// <summary>The appraised spells' names, newline-separated (a rule's text can't span two).</summary>
|
||||
private string SpellNames()
|
||||
{
|
||||
int n = AppraisalHooks.GetObjectSpellIds(_item.Id, _spellBuf, _spellBuf.Length);
|
||||
if (n <= 0) return string.Empty;
|
||||
if (!PortalSpellTable.Ready) PortalSpellTable.EnsureLoadQueued();
|
||||
_sb.Clear();
|
||||
int shown = Math.Min(n, _spellBuf.Length);
|
||||
for (int k = 0; k < shown; k++)
|
||||
{
|
||||
// Spell ids in an appraisal can carry the layer in the high word.
|
||||
uint sid = _spellBuf[k] & 0xFFFF;
|
||||
if (k > 0) _sb.Append('\n');
|
||||
_sb.Append(PortalSpellTable.TryGetName(sid, out string name) ? name : "spell " + sid);
|
||||
}
|
||||
return _sb.ToString();
|
||||
}
|
||||
}
|
||||
259
src/RynthCore.Engine/Compatibility/InventoryModel.Batch.cs
Normal file
259
src/RynthCore.Engine/Compatibility/InventoryModel.Batch.cs
Normal file
|
|
@ -0,0 +1,259 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/InventoryModel.Batch.cs
|
||||
// Several items in one go (the Inventory panel's multi-selection): Drop,
|
||||
// Give to the selected creature, or Move into a pack.
|
||||
//
|
||||
// Still one item action at a time (AC refuses a second while one waits): the
|
||||
// batch hands the next item to the normal request path only after the one
|
||||
// before it has ended (done, refused, gone or timed out), with a short gap,
|
||||
// so each item is checked and watched exactly like a single click.
|
||||
//
|
||||
// Threads: RequestBatch / CancelBatch / Batch / BatchRunning any thread;
|
||||
// everything else on AC's main thread (BatchTick, from MainThreadTick). The
|
||||
// batch keeps running with the panel closed and ends by itself.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>A running or finished batch, for the status row. Immutable.</summary>
|
||||
internal sealed class InventoryBatchStatus
|
||||
{
|
||||
public InventoryActionKind Kind;
|
||||
public int Total, Done, Failed;
|
||||
public string TargetName = string.Empty;
|
||||
public bool Running;
|
||||
/// <summary>Stop was pressed: it ends after the item in flight.</summary>
|
||||
public bool Stopping;
|
||||
/// <summary>"Giving 3 of 12 to Bob" while running, else the summary.</summary>
|
||||
public string Text = string.Empty;
|
||||
}
|
||||
|
||||
internal static partial class InventoryModel
|
||||
{
|
||||
// Between items: lets the server's answer to one settle before the next is sent.
|
||||
private static readonly long BatchGapTicks = Freq / 4;
|
||||
/// <summary>The most items one batch takes (a full main pack and its side packs).</summary>
|
||||
public const int MaxBatch = 400;
|
||||
|
||||
// ── Published / inputs (any thread) ─────────────────────────────────
|
||||
private static InventoryBatchStatus? _batchStatus;
|
||||
private static InventoryRequest[]? _batchRequested;
|
||||
private static int _batchActive, _batchCancel;
|
||||
|
||||
public static InventoryBatchStatus? Batch => Volatile.Read(ref _batchStatus);
|
||||
public static bool BatchRunning => Volatile.Read(ref _batchActive) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Starts acting on <paramref name="items"/> one after another (all of one kind; Drop, Give
|
||||
/// or Move). Refused while another action or batch is waiting. Any thread.
|
||||
/// </summary>
|
||||
public static bool RequestBatch(IReadOnlyList<InventoryRequest> items, out string why)
|
||||
{
|
||||
if (items.Count == 0) { why = "Nothing to do."; return false; }
|
||||
if (items.Count > MaxBatch) { why = $"At most {MaxBatch} items at once."; return false; }
|
||||
InventoryActionKind kind = items[0].Kind;
|
||||
if (kind is not (InventoryActionKind.Drop or InventoryActionKind.Give or InventoryActionKind.Move))
|
||||
{
|
||||
why = "Only Drop, Give and Move work on several items.";
|
||||
return false;
|
||||
}
|
||||
for (int i = 1; i < items.Count; i++)
|
||||
{
|
||||
if (items[i].Kind != kind) { why = "A batch is one kind of action."; return false; }
|
||||
}
|
||||
InventoryPending? busy = Pending;
|
||||
if (busy != null)
|
||||
{
|
||||
why = (busy.WaitingForGame ? "Still waiting for the game: " : "Still waiting for the server: ") + busy.Label;
|
||||
return false;
|
||||
}
|
||||
if (Volatile.Read(ref _requested) != null) { why = "Another item action is about to be sent."; return false; }
|
||||
if (Interlocked.CompareExchange(ref _batchActive, 1, 0) != 0) { why = "Several items are already being sent."; return false; }
|
||||
|
||||
var copy = new InventoryRequest[items.Count];
|
||||
for (int i = 0; i < copy.Length; i++) copy[i] = items[i];
|
||||
Volatile.Write(ref _batchCancel, 0);
|
||||
Volatile.Write(ref _batchRequested, copy);
|
||||
why = string.Empty;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Stop: no more items are sent; the one in flight still ends normally. Any thread.</summary>
|
||||
public static void CancelBatch()
|
||||
{
|
||||
if (!BatchRunning) return;
|
||||
Volatile.Write(ref _batchCancel, 1);
|
||||
InventoryBatchStatus? s = Batch;
|
||||
if (s is { Running: true, Stopping: false })
|
||||
Volatile.Write(ref _batchStatus, new InventoryBatchStatus
|
||||
{
|
||||
Kind = s.Kind, Total = s.Total, Done = s.Done, Failed = s.Failed, TargetName = s.TargetName,
|
||||
Running = true, Stopping = true, Text = s.Text + " (stopping)",
|
||||
});
|
||||
}
|
||||
|
||||
// ── Main thread ─────────────────────────────────────────────────────
|
||||
private static readonly Queue<InventoryRequest> _batchQueue = new();
|
||||
private static InventoryActionKind _batchKind;
|
||||
private static int _batchTotal, _batchDone, _batchFailed;
|
||||
private static string _batchTarget = string.Empty, _batchFirstError = string.Empty;
|
||||
// The item handed to the request path, until it has ended.
|
||||
private static InventoryRequest? _batchWaiting;
|
||||
private static InventoryResult? _batchResultBefore;
|
||||
private static long _batchNextAt;
|
||||
|
||||
/// <summary>Starts a requested batch, counts the item that ended, sends the next one. Main thread.</summary>
|
||||
private static void BatchTick(long now)
|
||||
{
|
||||
InventoryRequest[]? incoming = Interlocked.Exchange(ref _batchRequested, null);
|
||||
if (incoming != null) StartBatch(incoming, now);
|
||||
// RequestBatch sets the flag a moment before it hands over the items: they come next tick.
|
||||
if (_batchTotal == 0) return;
|
||||
|
||||
// The item handed over last tick: wait until it has ended, then count it.
|
||||
if (_batchWaiting != null)
|
||||
{
|
||||
if (Busy()) return;
|
||||
InventoryResult? r = LastResult;
|
||||
bool ended = r != null && !ReferenceEquals(r, _batchResultBefore);
|
||||
if (ended && r!.Ok) _batchDone++;
|
||||
else
|
||||
{
|
||||
_batchFailed++;
|
||||
if (_batchFirstError.Length == 0) _batchFirstError = ended ? r!.Text : "no answer";
|
||||
}
|
||||
_batchWaiting = null;
|
||||
_batchNextAt = now + BatchGapTicks;
|
||||
PublishBatch(running: true);
|
||||
}
|
||||
|
||||
if (Volatile.Read(ref _batchCancel) != 0) { EndBatch(now, "stopped"); return; }
|
||||
if (_batchQueue.Count == 0) { EndBatch(now, string.Empty); return; }
|
||||
if (now < _batchNextAt || Busy()) return;
|
||||
|
||||
uint player = ClientHelperHooks.GetPlayerId();
|
||||
if (player == 0) { FailRest("not in the world"); EndBatch(now, string.Empty); return; }
|
||||
|
||||
InventoryRequest next = _batchQueue.Peek();
|
||||
if (next.Kind == InventoryActionKind.Give
|
||||
&& (next.TargetId == 0 || next.TargetId == player || !ClientObjectHooks.TryGetItemType(next.TargetId, out _)))
|
||||
{
|
||||
FailRest(next.TargetName + " is gone");
|
||||
EndBatch(now, string.Empty);
|
||||
return;
|
||||
}
|
||||
|
||||
_batchQueue.Dequeue();
|
||||
_batchResultBefore = LastResult;
|
||||
if (Interlocked.CompareExchange(ref _requested, next, null) != null)
|
||||
{
|
||||
// Something else got in first (shouldn't happen: Request refuses during a batch).
|
||||
_batchFailed++;
|
||||
if (_batchFirstError.Length == 0) _batchFirstError = "another action was in the way";
|
||||
_batchNextAt = now + BatchGapTicks;
|
||||
PublishBatch(running: true);
|
||||
return;
|
||||
}
|
||||
_batchWaiting = next;
|
||||
PublishBatch(running: true);
|
||||
}
|
||||
|
||||
/// <summary>An item action requested, held or in flight (ours or not). Main thread.</summary>
|
||||
private static bool Busy() => _inFlight != null || _held != null || Volatile.Read(ref _requested) != null;
|
||||
|
||||
private static void StartBatch(InventoryRequest[] items, long now)
|
||||
{
|
||||
_batchQueue.Clear();
|
||||
foreach (InventoryRequest r in items) _batchQueue.Enqueue(r);
|
||||
_batchKind = items[0].Kind;
|
||||
_batchTotal = items.Length;
|
||||
_batchDone = _batchFailed = 0;
|
||||
_batchTarget = items[0].TargetName;
|
||||
_batchFirstError = string.Empty;
|
||||
_batchWaiting = null;
|
||||
_batchResultBefore = null;
|
||||
_batchNextAt = now;
|
||||
PublishBatch(running: true);
|
||||
RynthLog.Compat($"InventoryModel: batch {_batchKind} of {_batchTotal} item(s){(_batchTarget.Length > 0 ? " to " + _batchTarget : "")}.");
|
||||
}
|
||||
|
||||
private static void FailRest(string why)
|
||||
{
|
||||
_batchFailed += _batchQueue.Count;
|
||||
_batchQueue.Clear();
|
||||
if (_batchFirstError.Length == 0) _batchFirstError = why;
|
||||
}
|
||||
|
||||
/// <summary>Ends the batch: the summary goes to the status row (LastResult) and the log. Main thread.</summary>
|
||||
private static void EndBatch(long now, string how)
|
||||
{
|
||||
bool started = _batchTotal > 0;
|
||||
int skipped = _batchQueue.Count;
|
||||
_batchQueue.Clear();
|
||||
_batchWaiting = null;
|
||||
if (started)
|
||||
{
|
||||
InventoryBatchStatus s = PublishBatch(running: false, how, skipped);
|
||||
Finish(s.Text, _batchFailed == 0 && skipped == 0, now);
|
||||
RynthLog.Compat("InventoryModel: " + s.Text);
|
||||
}
|
||||
_batchTotal = 0;
|
||||
Volatile.Write(ref _batchCancel, 0);
|
||||
Volatile.Write(ref _batchActive, 0);
|
||||
}
|
||||
|
||||
private static InventoryBatchStatus PublishBatch(bool running, string how = "", int skipped = 0)
|
||||
{
|
||||
var s = new InventoryBatchStatus
|
||||
{
|
||||
Kind = _batchKind, Total = _batchTotal, Done = _batchDone, Failed = _batchFailed,
|
||||
TargetName = _batchTarget, Running = running,
|
||||
Stopping = running && Volatile.Read(ref _batchCancel) != 0,
|
||||
};
|
||||
s.Text = running
|
||||
? BatchProgressText(_batchKind, Math.Min(_batchTotal, _batchDone + _batchFailed + 1), _batchTotal, _batchTarget)
|
||||
+ (s.Stopping ? " (stopping)" : string.Empty)
|
||||
: BatchSummaryText(_batchKind, _batchDone, _batchFailed, skipped, _batchTotal, _batchTarget, how, _batchFirstError);
|
||||
Volatile.Write(ref _batchStatus, s);
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>"Giving 3 of 12 to Bob", "Dropping 3 of 12", "Moving 3 of 12 to Pack".</summary>
|
||||
internal static string BatchProgressText(InventoryActionKind kind, int n, int total, string target) => kind switch
|
||||
{
|
||||
InventoryActionKind.Give => $"Giving {n} of {total} to {target}",
|
||||
InventoryActionKind.Move => $"Moving {n} of {total} to {target}",
|
||||
_ => $"Dropping {n} of {total}",
|
||||
};
|
||||
|
||||
/// <summary>"Gave 10 of 12 items to Bob; 2 failed (first: ...)", "Dropped 12 items.", "Stopped: moved 3 of 12...".</summary>
|
||||
internal static string BatchSummaryText(InventoryActionKind kind, int done, int failed, int skipped, int total,
|
||||
string target, string how, string firstError)
|
||||
{
|
||||
string verb = kind switch
|
||||
{
|
||||
InventoryActionKind.Give => "gave",
|
||||
InventoryActionKind.Move => "moved",
|
||||
_ => "dropped",
|
||||
};
|
||||
string where = kind switch
|
||||
{
|
||||
InventoryActionKind.Give => " to " + target,
|
||||
InventoryActionKind.Move => " to " + target,
|
||||
_ => string.Empty,
|
||||
};
|
||||
string count = done == total ? $"{total} item{(total == 1 ? "" : "s")}" : $"{done} of {total} items";
|
||||
string text = how.Length > 0
|
||||
? $"{char.ToUpperInvariant(how[0])}{how[1..]}: {verb} {count}{where}"
|
||||
: $"{char.ToUpperInvariant(verb[0])}{verb[1..]} {count}{where}";
|
||||
if (failed > 0) text += $"; {failed} failed";
|
||||
if (skipped > 0) text += $"; {skipped} not sent";
|
||||
if (failed > 0 && firstError.Length > 0) text += $" (first: {firstError.TrimEnd('.')})";
|
||||
return text + ".";
|
||||
}
|
||||
}
|
||||
|
|
@ -17,6 +17,9 @@
|
|||
// One item action at a time: AC keeps one pending inventory request and refuses
|
||||
// a second ("You can only move or use one item at a time"; ClientActionGates).
|
||||
// Request() refuses while an action is waiting; nothing is ever queued behind it.
|
||||
// Several items (the panel's multi-selection) go through RequestBatch
|
||||
// (InventoryModel.Batch.cs), which feeds them to this same path one at a time,
|
||||
// each only after the one before it has ended.
|
||||
//
|
||||
// The client's own gate (ClientActionGates, read on the main thread here):
|
||||
// Before the send while AC's pending-request slot holds anyone's request (the
|
||||
|
|
@ -212,7 +215,7 @@ internal sealed class InventoryResult
|
|||
public long AtTicks;
|
||||
}
|
||||
|
||||
internal static class InventoryModel
|
||||
internal static partial class InventoryModel
|
||||
{
|
||||
// ── Cadence ─────────────────────────────────────────────────────────
|
||||
private static readonly long Freq = Stopwatch.Frequency;
|
||||
|
|
@ -295,6 +298,11 @@ internal static class InventoryModel
|
|||
/// </summary>
|
||||
public static bool Request(InventoryRequest request, out string why)
|
||||
{
|
||||
if (BatchRunning)
|
||||
{
|
||||
why = "Several items are being sent; wait, or press Stop.";
|
||||
return false;
|
||||
}
|
||||
InventoryPending? busy = Pending;
|
||||
if (busy != null)
|
||||
{
|
||||
|
|
@ -357,7 +365,8 @@ internal static class InventoryModel
|
|||
public static void MainThreadTick()
|
||||
{
|
||||
bool open = Volatile.Read(ref _subscribers) > 0;
|
||||
if (!open && _inFlight == null && _held == null && Volatile.Read(ref _requested) == null)
|
||||
if (!open && _inFlight == null && _held == null && Volatile.Read(ref _requested) == null
|
||||
&& Volatile.Read(ref _batchActive) == 0)
|
||||
return;
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return;
|
||||
|
|
@ -375,6 +384,8 @@ internal static class InventoryModel
|
|||
_lastWatch = now;
|
||||
Watch(now);
|
||||
}
|
||||
// After the watch, so an item that just ended is counted before the next is sent.
|
||||
if (Volatile.Read(ref _batchActive) != 0) BatchTick(now);
|
||||
if (!open) return;
|
||||
|
||||
bool dirty = Volatile.Read(ref _dirty) != 0;
|
||||
|
|
@ -392,6 +403,7 @@ internal static class InventoryModel
|
|||
SampleTarget();
|
||||
}
|
||||
HoverTick(now);
|
||||
IdentifyQueueTick(now);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -420,6 +432,7 @@ internal static class InventoryModel
|
|||
{
|
||||
_items.Clear(); // another character: nothing carries over
|
||||
_identified.Clear();
|
||||
ClearIdentifyQueue();
|
||||
_lastPlayer = player;
|
||||
_lastSignature = 0;
|
||||
_playerName = string.Empty;
|
||||
|
|
@ -1118,7 +1131,8 @@ internal static class InventoryModel
|
|||
_identified[id] = now;
|
||||
_lastIdentify = now;
|
||||
sentRecently = true;
|
||||
ClientActionHooks.RequestId(id); // main thread: the 0xC8 is sent now
|
||||
using (Net.EngineSendMarker.Enter(Net.IdRequester.Ui))
|
||||
ClientActionHooks.RequestId(id); // main thread: the 0xC8 is sent now
|
||||
tip = null; // rebuild below with "identifying"
|
||||
}
|
||||
|
||||
|
|
@ -1127,6 +1141,70 @@ internal static class InventoryModel
|
|||
Volatile.Write(ref _tooltip, BuildTooltip(id, appraised, !appraised && sentRecently));
|
||||
}
|
||||
|
||||
// ── Identify queue (the attribute filter's "Identify N") ────────────
|
||||
|
||||
private static readonly long QueuedIdentifyGapTicks = Freq / 4; // 4 a second
|
||||
private const int MaxQueuedIdentifies = 1024;
|
||||
private static readonly object IdQueueSync = new();
|
||||
private static readonly Queue<uint> _idQueue = new(); // guarded by IdQueueSync
|
||||
private static readonly HashSet<uint> _idQueued = new(); // guarded by IdQueueSync
|
||||
private static long _lastQueuedIdentify;
|
||||
|
||||
/// <summary>Items still waiting in the identify queue. Any thread.</summary>
|
||||
public static int IdentifyQueueCount
|
||||
{
|
||||
get { lock (IdQueueSync) return _idQueue.Count; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asks the server to identify <paramref name="ids"/>, a few a second on AC's main thread
|
||||
/// while the panel is open. Items already appraised, sent in the last minute, already
|
||||
/// queued or no longer carried are skipped. Any thread.
|
||||
/// </summary>
|
||||
public static void QueueIdentify(IReadOnlyList<uint> ids)
|
||||
{
|
||||
lock (IdQueueSync)
|
||||
{
|
||||
foreach (uint id in ids)
|
||||
{
|
||||
if (id == 0 || _idQueue.Count >= MaxQueuedIdentifies) continue;
|
||||
if (_idQueued.Add(id)) _idQueue.Enqueue(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drops every queued identify. Any thread.</summary>
|
||||
public static void ClearIdentifyQueue()
|
||||
{
|
||||
lock (IdQueueSync)
|
||||
{
|
||||
_idQueue.Clear();
|
||||
_idQueued.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Main thread: sends the next queued identify that still needs sending.</summary>
|
||||
private static void IdentifyQueueTick(long now)
|
||||
{
|
||||
if (now - _lastQueuedIdentify < QueuedIdentifyGapTicks) return;
|
||||
while (true)
|
||||
{
|
||||
uint id;
|
||||
lock (IdQueueSync)
|
||||
{
|
||||
if (!_idQueue.TryDequeue(out id)) return;
|
||||
_idQueued.Remove(id);
|
||||
}
|
||||
if (AppraisalHooks.HasAppraisalData(id) || !_items.ContainsKey(id)) continue;
|
||||
if (_identified.TryGetValue(id, out long sentAt) && now - sentAt < IdentifyRepeatTicks) continue;
|
||||
if (_identified.Count > 2048) _identified.Clear();
|
||||
_identified[id] = now;
|
||||
_lastQueuedIdentify = now;
|
||||
ClientActionHooks.RequestId(id); // main thread: the 0xC8 is sent now
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private static InventoryTooltip BuildTooltip(uint id, bool appraised, bool identifying)
|
||||
{
|
||||
var lines = new List<string>(8);
|
||||
|
|
|
|||
|
|
@ -30,6 +30,11 @@ internal static class LoginLifecycleHooks
|
|||
|
||||
public static bool IsInstalled { get; private set; }
|
||||
public static bool HasObservedLoginComplete { get; private set; }
|
||||
|
||||
/// <summary>When login completed (TickCount64), or 0 before it / after a logout. A hot reload
|
||||
/// marks it at the reload. AutoId defers its background appraisals 30 s past it.</summary>
|
||||
public static long LoginCompleteAtMs => System.Threading.Interlocked.Read(ref _loginCompleteAtMs);
|
||||
private static long _loginCompleteAtMs;
|
||||
public static string StatusMessage => _statusMessage;
|
||||
|
||||
public static event Action? LoginComplete;
|
||||
|
|
@ -100,6 +105,7 @@ internal static class LoginLifecycleHooks
|
|||
public static void ResetObservation()
|
||||
{
|
||||
HasObservedLoginComplete = false;
|
||||
System.Threading.Interlocked.Exchange(ref _loginCompleteAtMs, 0);
|
||||
// Queued engine work (appraisals, health queries, chat, actions) from this login is stale
|
||||
// for the next one (2026-10-06, AcMainThreadQueue).
|
||||
try { AcMainThreadQueue.NewLoginEpoch(); } catch { }
|
||||
|
|
@ -137,6 +143,7 @@ internal static class LoginLifecycleHooks
|
|||
return;
|
||||
|
||||
HasObservedLoginComplete = true;
|
||||
System.Threading.Interlocked.Exchange(ref _loginCompleteAtMs, Environment.TickCount64);
|
||||
_statusMessage = $"Login complete observed via {source}.";
|
||||
RynthLog.Verbose($"Compat: login complete observed via {source}.");
|
||||
LoginComplete?.Invoke();
|
||||
|
|
|
|||
|
|
@ -343,7 +343,18 @@ internal static unsafe class LogoffOriginProbe
|
|||
bool inWorld = false;
|
||||
try { inWorld = LoginLifecycleHooks.HasObservedLoginComplete; } catch { }
|
||||
if (!inWorld)
|
||||
{
|
||||
// Before LoginComplete too (2026-10-13): a relaunched client that never had any
|
||||
// input carries an idle time of years (last input 0), and AC logged Drakkon off
|
||||
// 0.7 s after he entered the world, before LoginComplete arrived, so the
|
||||
// in-world refresh below never ran. Keep the clock fresh at char-select as well.
|
||||
if (Plugins.EngineSettings.PreventIdleLogoff && idle > IdleRefreshAfterSec && TryRefreshLastInput() && !_preWorldRefreshLogged)
|
||||
{
|
||||
_preWorldRefreshLogged = true;
|
||||
RynthLog.Info($"LogoffProbe: reset the client's idle clock before entering the world ({idle:0}s idle) so the idle auto-logoff can't fire on arrival (PreventIdleLogoff; logged once).");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (double.IsNaN(limit) || double.IsInfinity(limit) || limit <= 60)
|
||||
{
|
||||
|
|
@ -387,6 +398,7 @@ internal static unsafe class LogoffOriginProbe
|
|||
}
|
||||
|
||||
private const double IdleRefreshAfterSec = 120;
|
||||
private static bool _preWorldRefreshLogged;
|
||||
private static long _lastIdleRefreshLogMs = -600_000;
|
||||
|
||||
/// <summary>Sets the input manager's last-input time to Timer::cur_time, as real input
|
||||
|
|
|
|||
|
|
@ -105,17 +105,27 @@ internal static class MainThreadSnapshots
|
|||
try { EnchantmentHooks.PrefetchWatchedObjectEnchantments(); } catch { }
|
||||
// Inventory panel: sends the one requested item action, watches it, and
|
||||
// captures the packs (throttled; returns at once while the panel is closed
|
||||
// and nothing is in flight). Only while the player object is live.
|
||||
try { InventoryModel.MainThreadTick(); } catch { }
|
||||
// and nothing is in flight). Only while the player object is live, and held
|
||||
// through a world transition (dead / portal / landblock jump): it SENDS item
|
||||
// actions, and those wait like the AcMainThreadQueue's (WorldTransitionState).
|
||||
if (!PlayerLifecycleLog.InWorldTransition)
|
||||
{
|
||||
try { InventoryModel.MainThreadTick(); } catch { }
|
||||
}
|
||||
// Skills panel: ranks, XP spent and buffs (500 ms, only while the panel is open).
|
||||
// After the enchantment snapshot so its buffs are this tick's.
|
||||
try { PlayerProgressHooks.Prefetch(); } catch { }
|
||||
}
|
||||
|
||||
// Aelrynth skill mastery: the /mastery-data request after login, on panel open
|
||||
// and after a raise (only on Aelrynth; a few compares when nothing is wanted).
|
||||
try { MasteryFeed.MainThreadTick(playerLive); } catch { }
|
||||
// Aelrynth account vault (the Inventory panel's Vault view): reads on request only.
|
||||
try { VaultFeed.MainThreadTick(playerLive); } catch { }
|
||||
// Both send server commands (a mastery raise, a vault withdraw), so like the
|
||||
// Inventory panel they wait out a world transition; their requests stay pending.
|
||||
if (!PlayerLifecycleLog.InWorldTransition)
|
||||
{
|
||||
// Aelrynth skill mastery: the /mastery-data request after login, on panel open
|
||||
// and after a raise (only on Aelrynth; a few compares when nothing is wanted).
|
||||
try { MasteryFeed.MainThreadTick(playerLive); } catch { }
|
||||
// Aelrynth account vault (the Inventory panel's Vault view): reads on request only.
|
||||
try { VaultFeed.MainThreadTick(playerLive); } catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
77
src/RynthCore.Engine/Compatibility/MergeStackResults.cs
Normal file
77
src/RynthCore.Engine/Compatibility/MergeStackResults.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Outcome of the most recent <see cref="ClientHelperHooks.MergeStackInternal"/> request per
|
||||
/// (source, target) pair, so a plugin can learn what happened on AC's main thread instead of
|
||||
/// only "queued". Before this, a merge the engine skipped (target already full) or that AC
|
||||
/// rejected looked identical to one in flight, and RynthAi's AutoStack waited 10 s per pair
|
||||
/// and logged a "confirmed failure". Thread-safe; bounded.
|
||||
/// </summary>
|
||||
internal static class MergeStackResults
|
||||
{
|
||||
// ABI status codes (GetMergeStackResult return value). Never renumber.
|
||||
public const int None = 0; // no request recorded for this pair (or it aged out)
|
||||
public const int Queued = 1; // accepted onto the main-thread queue, not executed yet
|
||||
public const int Sent = 2; // Event_StackableMerge sent for 'amount' units
|
||||
public const int TargetFull = 3; // skipped: target stack already at max stack size
|
||||
public const int Failed = 4; // invalid ids, merge API unavailable, AC returned 0, or threw
|
||||
public const int QueueFull = 5; // main-thread queue full; request dropped before execution
|
||||
|
||||
private struct Entry { public int Status; public int Amount; public long TickMs; }
|
||||
|
||||
private const int MaxEntries = 512; // prune threshold
|
||||
private const long PruneAgeMs = 120_000; // results older than this are dropped on prune
|
||||
|
||||
private static readonly object _lock = new();
|
||||
private static readonly Dictionary<ulong, Entry> _results = new();
|
||||
|
||||
private static ulong Key(uint source, uint target) => ((ulong)source << 32) | target;
|
||||
|
||||
/// <summary>Records the latest outcome for a pair (replaces any earlier one).</summary>
|
||||
public static void Record(uint source, uint target, int status, int amount = 0)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_results.Count >= MaxEntries)
|
||||
Prune(now);
|
||||
_results[Key(source, target)] = new Entry { Status = status, Amount = amount, TickMs = now };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Latest outcome for the pair, or <see cref="None"/>. <paramref name="amount"/>
|
||||
/// is the unit count sent (Sent only) and <paramref name="ageMs"/> how long ago it was recorded.</summary>
|
||||
public static int Get(uint source, uint target, out int amount, out int ageMs)
|
||||
{
|
||||
amount = 0;
|
||||
ageMs = 0;
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_results.TryGetValue(Key(source, target), out Entry e))
|
||||
return None;
|
||||
amount = e.Amount;
|
||||
long age = Environment.TickCount64 - e.TickMs;
|
||||
ageMs = age > int.MaxValue ? int.MaxValue : (int)age;
|
||||
return e.Status;
|
||||
}
|
||||
}
|
||||
|
||||
// Drops aged results; if everything is recent, clears the map (callers re-request anyway).
|
||||
private static void Prune(long now)
|
||||
{
|
||||
List<ulong>? old = null;
|
||||
foreach (var kv in _results)
|
||||
if (now - kv.Value.TickMs > PruneAgeMs)
|
||||
(old ??= new List<ulong>()).Add(kv.Key);
|
||||
if (old == null)
|
||||
{
|
||||
_results.Clear();
|
||||
return;
|
||||
}
|
||||
foreach (ulong k in old)
|
||||
_results.Remove(k);
|
||||
}
|
||||
}
|
||||
|
|
@ -12,15 +12,22 @@
|
|||
// Now the text is in the log, and the watchdog names the open dialog in its
|
||||
// hang report (see Describe).
|
||||
//
|
||||
// The detour only observes: it always calls the original and returns its
|
||||
// result. Installed per engine generation; EngineLifecycle's
|
||||
// MH_DisableHook(ALL) removes it on reload.
|
||||
// The detour only observes, with one exception (2026-10-12): AC's "Failed to
|
||||
// establish connection to the server" box (a relaunch that logged in too soon
|
||||
// after a crash, or the server down). AC's game loop waits on it, so the
|
||||
// Close on server disconnect check never ran and the client sat there for
|
||||
// 10 minutes. With that setting on, the box is answered OK without being
|
||||
// shown (AC then exits, as when the button is clicked), and if the client is
|
||||
// still open 20 s later the window is sent WM_CLOSE (again at 40 s).
|
||||
// Installed per engine generation; EngineLifecycle's MH_DisableHook(ALL)
|
||||
// removes it on reload.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
|
|
@ -52,6 +59,13 @@ internal static class MessageBoxHooks
|
|||
private static volatile string? _openDescription;
|
||||
private static long _openedAtTicks;
|
||||
private static int _openCount;
|
||||
// Boxes open on AC's MAIN thread: the main thread is inside a modal loop, so the plugin
|
||||
// pump's freeze gate (MainThreadFreeze) pauses plugin ticks at once.
|
||||
private static int _mainThreadOpenCount;
|
||||
|
||||
/// <summary>Message boxes open right now on AC's main thread. Any thread.</summary>
|
||||
public static int MainThreadOpenCount => Volatile.Read(ref _mainThreadOpenCount);
|
||||
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
|
|
@ -114,34 +128,94 @@ internal static class MessageBoxHooks
|
|||
{
|
||||
MessageBoxDelegate? original = wide ? _originalW : _originalA;
|
||||
string? description = null;
|
||||
bool counted = false;
|
||||
long opened = Environment.TickCount64;
|
||||
int result = 0;
|
||||
try
|
||||
{
|
||||
description = Opened(text, caption, type, wide);
|
||||
}
|
||||
catch { /* observation only: never block the dialog */ }
|
||||
|
||||
int result = original != null ? original(hWnd, text, caption, type) : 0;
|
||||
|
||||
try
|
||||
{
|
||||
long secs = (Environment.TickCount64 - opened) / 1000;
|
||||
RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}");
|
||||
if (Interlocked.Decrement(ref _openCount) <= 0)
|
||||
try
|
||||
{
|
||||
Interlocked.Exchange(ref _openCount, 0);
|
||||
_openDescription = null;
|
||||
// Counted first: the freeze gate must see the box even if the rest throws.
|
||||
bool mainThread = MainThreadGuard.IsOnMainThread();
|
||||
if (mainThread)
|
||||
{
|
||||
Interlocked.Increment(ref _mainThreadOpenCount);
|
||||
counted = true;
|
||||
}
|
||||
string body = Read(text, wide);
|
||||
// AC's OUT OF MEMORY box is modal: the process never crashes, so Windows never
|
||||
// writes a dump, and the launcher later kills the client as wedged. Decide and
|
||||
// write ONE full-memory dump now, before anything here allocates more (the stack
|
||||
// walk and the description below), and before the box shows (this thread waits:
|
||||
// the box would hold it anyway, and the user's OK must not let AC run on and
|
||||
// exit mid-dump).
|
||||
if (OutOfMemoryBoxRule.IsOutOfMemoryBox(body, mainThread))
|
||||
CrashDump.WriteOutOfMemoryDumpOnce(Flatten(body));
|
||||
description = Opened(body, caption, type, wide, mainThread);
|
||||
}
|
||||
catch { /* observation only: never block the dialog */ }
|
||||
|
||||
// The one box answered without showing it (Close on server disconnect, 2026-10-12).
|
||||
result = AnswerConnectionFailure(text, wide)
|
||||
? IDOK
|
||||
: original != null ? original(hWnd, text, caption, type) : 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// First, and whatever happened above: a leaked count would pause plugin ticks for good.
|
||||
if (counted && Interlocked.Decrement(ref _mainThreadOpenCount) < 0)
|
||||
Interlocked.Exchange(ref _mainThreadOpenCount, 0);
|
||||
try
|
||||
{
|
||||
long secs = (Environment.TickCount64 - opened) / 1000;
|
||||
if (Interlocked.Decrement(ref _openCount) <= 0)
|
||||
{
|
||||
Interlocked.Exchange(ref _openCount, 0);
|
||||
_openDescription = null;
|
||||
}
|
||||
RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}");
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
catch { }
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string Opened(IntPtr text, IntPtr caption, uint type, bool wide)
|
||||
private const int IDOK = 1;
|
||||
private static int _connectionFailureAnswered;
|
||||
|
||||
/// <summary>
|
||||
/// True for AC's connection-failure box while Close on server disconnect is on: answered
|
||||
/// OK unseen, with a WM_CLOSE fallback if AC doesn't exit by itself. Never throws.
|
||||
/// </summary>
|
||||
private static bool AnswerConnectionFailure(IntPtr text, bool wide)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!EngineSettings.CloseOnServerDisconnect) return false;
|
||||
if (!Read(text, wide).StartsWith("Failed to establish connection to the server", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
RynthLog.Warn("MessageBoxHooks: the connection failed - answering AC's box (OK) unseen so the client exits " +
|
||||
"and a launcher can relaunch it (Close on server disconnect, Settings > Misc).");
|
||||
if (Interlocked.Exchange(ref _connectionFailureAnswered, 1) == 0)
|
||||
{
|
||||
var fallback = new Thread(() =>
|
||||
{
|
||||
for (int i = 1; i <= 2; i++)
|
||||
{
|
||||
Thread.Sleep(20_000);
|
||||
ServerDisconnectClose.CloseClientNow($"the client is still open {i * 20}s after the connection-failure box");
|
||||
}
|
||||
}) { IsBackground = true, Name = "RynthCore connection-failure close" };
|
||||
fallback.Start();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
private static string Opened(string body, IntPtr caption, uint type, bool wide, bool mainThread)
|
||||
{
|
||||
string body = Read(text, wide);
|
||||
string title = Read(caption, wide);
|
||||
bool mainThread = MainThreadGuard.IsOnMainThread();
|
||||
|
||||
// The first frame outside user32 and this file: who asked for the dialog.
|
||||
string caller = "?";
|
||||
|
|
@ -165,6 +239,63 @@ internal static class MessageBoxHooks
|
|||
return description;
|
||||
}
|
||||
|
||||
// -- Stale main-thread count (safety net) ------------------------------------
|
||||
// The count is decremented in Show's finally, so it should never leak; if it ever reads
|
||||
// non-zero while AC's main thread owns no dialog window for 30 s, it is reset (and
|
||||
// logged), so a leak can never pause plugin ticks for good. Heartbeat thread, 1 Hz.
|
||||
private const long StaleCountResetMs = 30_000;
|
||||
private static long _countWithoutBoxSinceMs;
|
||||
|
||||
private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool EnumThreadWindows(uint threadId, EnumThreadWndProc callback, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern int GetClassNameW(IntPtr hWnd, System.Text.StringBuilder name, int max);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
private static bool MainThreadOwnsDialog()
|
||||
{
|
||||
uint tid = MainThreadGuard.MainThreadId;
|
||||
if (tid == 0) return false;
|
||||
bool found = false;
|
||||
var name = new System.Text.StringBuilder(64);
|
||||
EnumThreadWindows(tid, (h, _) =>
|
||||
{
|
||||
name.Clear();
|
||||
if (GetClassNameW(h, name, name.Capacity) > 0 && name.ToString() == "#32770" && IsWindowVisible(h))
|
||||
{
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}, IntPtr.Zero);
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>Heartbeat thread, about once a second. Never throws.</summary>
|
||||
public static void ReconcileStaleMainThreadCount()
|
||||
{
|
||||
try
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
// The OOM dump runs before the box window exists: counted, no dialog yet, legitimately.
|
||||
if (MainThreadOpenCount <= 0 || CrashDump.FullDumpInProgress || MainThreadOwnsDialog())
|
||||
{
|
||||
_countWithoutBoxSinceMs = 0;
|
||||
return;
|
||||
}
|
||||
if (_countWithoutBoxSinceMs == 0) { _countWithoutBoxSinceMs = now; return; }
|
||||
if (now - _countWithoutBoxSinceMs < StaleCountResetMs) return;
|
||||
int was = Interlocked.Exchange(ref _mainThreadOpenCount, 0);
|
||||
_countWithoutBoxSinceMs = 0;
|
||||
RynthLog.Warn($"MessageBoxHooks: main-thread box count was {was} with no dialog open on AC's main thread for {StaleCountResetMs / 1000}s - reset to 0.");
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
private static string Read(IntPtr p, bool wide)
|
||||
{
|
||||
if (p == IntPtr.Zero) return "";
|
||||
|
|
|
|||
|
|
@ -151,7 +151,7 @@ internal static class MovementActionHooks
|
|||
|
||||
public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = HoldKeyRun)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueDoMovement(motion, speed, holdKey);
|
||||
|
||||
int n = System.Threading.Interlocked.Increment(ref _doMovementCalls);
|
||||
|
|
@ -179,7 +179,7 @@ internal static class MovementActionHooks
|
|||
|
||||
public static bool StopMovement(uint motion, int holdKey = HoldKeyRun)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: true))
|
||||
return AcMainThreadQueue.EnqueueStopMovement(motion, holdKey);
|
||||
|
||||
int n = System.Threading.Interlocked.Increment(ref _stopMovementCalls);
|
||||
|
|
@ -207,7 +207,7 @@ internal static class MovementActionHooks
|
|||
|
||||
public static bool JumpNonAutonomous(float extent)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueJump(extent);
|
||||
|
||||
if (_jumpNonAutonomous == null)
|
||||
|
|
@ -231,7 +231,7 @@ internal static class MovementActionHooks
|
|||
if (_autonomyLevel == null)
|
||||
return false;
|
||||
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueSetAutonomyLevel(level);
|
||||
|
||||
try
|
||||
|
|
|
|||
28
src/RynthCore.Engine/Compatibility/MutatorGate.cs
Normal file
28
src/RynthCore.Engine/Compatibility/MutatorGate.cs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/MutatorGate.cs
|
||||
//
|
||||
// The decision behind AcMainThreadQueue.MustQueue, the one line every AC-mutating helper
|
||||
// opens with: call AC now, or queue the call?
|
||||
// - off AC's main thread: queue (AC is single-threaded);
|
||||
// - on it, called BY a queue drain: call now (the drain already applied the gate);
|
||||
// - on it, a stop or cancel (teardown): call now, even in a world transition;
|
||||
// - on it otherwise: queue while a world transition holds the drains (render-thread host
|
||||
// actions used to run straight into a world AC was tearing down), else call now.
|
||||
// holding is asked last and only when it matters (it is main-thread state).
|
||||
//
|
||||
// Pure. Compiled into tools\EngineRobustnessTests.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class MutatorGate
|
||||
{
|
||||
public static bool MustQueue(bool onMainThread, bool teardown, bool draining, Func<bool> holding)
|
||||
{
|
||||
if (!onMainThread) return true;
|
||||
if (draining || teardown) return false;
|
||||
return holding();
|
||||
}
|
||||
}
|
||||
74
src/RynthCore.Engine/Compatibility/ObjectFreshness.cs
Normal file
74
src/RynthCore.Engine/Compatibility/ObjectFreshness.cs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/ObjectFreshness.cs
|
||||
// When the server last sent anything about each object (2026-10-12, "ghost"
|
||||
// monsters: objects the client still draws but the server no longer has for
|
||||
// this player - no swing at them ever animates, they never move or die).
|
||||
//
|
||||
// Fed by SmartBoxHooks.DispatchSmartBoxEventDetour with every object-addressed
|
||||
// message (create, position, motion, vector, state, parent, pickup, effects,
|
||||
// object description, update object); a delete forgets the id. Read by the
|
||||
// plugin API's RemoveClientObject (v83) as a safety check: an object the server
|
||||
// talked about in the last few seconds is real and is never removed.
|
||||
// AC's main thread writes; any thread reads (lock). Bounded: a full table is
|
||||
// cleared wholesale (advisory data).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal static class ObjectFreshness
|
||||
{
|
||||
private static readonly object Sync = new();
|
||||
private static readonly Dictionary<uint, long> LastMessage = new(1024);
|
||||
private const int MaxEntries = 16384;
|
||||
|
||||
/// <summary>True for server messages whose u32 after the opcode is the object they are about.</summary>
|
||||
public static bool IsObjectMessage(uint opcode) => opcode switch
|
||||
{
|
||||
0xF745 => true, // CreateObject
|
||||
0xF748 => true, // UpdatePosition
|
||||
0xF749 => true, // ParentEvent
|
||||
0xF74A => true, // PickupEvent
|
||||
0xF74B => true, // SetState
|
||||
0xF74C => true, // UpdateMotion
|
||||
0xF74E => true, // VectorUpdate
|
||||
0xF754 => true, // PlayScriptId
|
||||
0xF755 => true, // PlayEffect
|
||||
0xF625 => true, // ObjDescEvent
|
||||
0xF7DB => true, // UpdateObject
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>A server message <paramref name="opcode"/> about <paramref name="objectId"/> arrived at <paramref name="nowMs"/>.</summary>
|
||||
public static void Note(uint opcode, uint objectId, long nowMs)
|
||||
{
|
||||
if (objectId == 0) return;
|
||||
if (opcode == 0xF747) { Forget(objectId); return; } // DeleteObject
|
||||
if (!IsObjectMessage(opcode)) return;
|
||||
lock (Sync)
|
||||
{
|
||||
if (LastMessage.Count >= MaxEntries && !LastMessage.ContainsKey(objectId)) LastMessage.Clear();
|
||||
LastMessage[objectId] = nowMs;
|
||||
}
|
||||
}
|
||||
|
||||
public static void Forget(uint objectId)
|
||||
{
|
||||
lock (Sync) LastMessage.Remove(objectId);
|
||||
}
|
||||
|
||||
/// <summary>Milliseconds since the server last sent a message about <paramref name="objectId"/>,
|
||||
/// or -1 when it sent none since the engine started watching (or the table was cleared).</summary>
|
||||
public static long AgeMs(uint objectId, long nowMs)
|
||||
{
|
||||
lock (Sync)
|
||||
return LastMessage.TryGetValue(objectId, out long t) ? Math.Max(0, nowMs - t) : -1;
|
||||
}
|
||||
|
||||
public static void Clear()
|
||||
{
|
||||
lock (Sync) LastMessage.Clear();
|
||||
}
|
||||
}
|
||||
115
src/RynthCore.Engine/Compatibility/PendingIdQueue.cs
Normal file
115
src/RynthCore.Engine/Compatibility/PendingIdQueue.cs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/PendingIdQueue.cs
|
||||
//
|
||||
// The pending queue behind AcMainThreadQueue's RequestId (0xC8 appraisal) slot.
|
||||
// A bounded FIFO of (object id, enqueue time, login epoch) that MERGES a request
|
||||
// for an object already waiting, the way the QueryHealth slot does: one appraisal
|
||||
// reply answers every caller that asked for it. Before this, AutoId's priority
|
||||
// appraisal, its create backlog and the plugins' RequestIdFn each queued their own
|
||||
// copy; one dump had 437 of 3211 identifies repeat an object within 125 ms.
|
||||
//
|
||||
// A pending entry only absorbs a new request while it is from the same login and
|
||||
// young enough that the drain will still send it (MergeMaxAgeMs). An entry the drain
|
||||
// would drop as stale, or one from an earlier login, takes no merges: the new
|
||||
// request is queued on its own so it is not lost with the old one.
|
||||
//
|
||||
// Pure data structure: no engine state, no locking (the caller holds its lock), and
|
||||
// no allocation after construction (a fixed ring). Compiled into
|
||||
// tools\EngineRobustnessTests.
|
||||
// ============================================================================
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal sealed class PendingIdQueue
|
||||
{
|
||||
public enum Result
|
||||
{
|
||||
/// <summary>Added as a new pending request.</summary>
|
||||
Queued,
|
||||
/// <summary>The object already had a pending request; nothing added.</summary>
|
||||
Merged,
|
||||
/// <summary>The queue is full; the request was not taken.</summary>
|
||||
Full,
|
||||
}
|
||||
|
||||
public readonly struct Item
|
||||
{
|
||||
public readonly uint Id;
|
||||
public readonly long At;
|
||||
public readonly int Epoch;
|
||||
/// <summary>Who asked (Net.IdRequester as a byte): the first request's, a merge keeps it.</summary>
|
||||
public readonly byte Source;
|
||||
|
||||
public Item(uint id, long at, int epoch, byte source = 0)
|
||||
{
|
||||
Id = id;
|
||||
At = at;
|
||||
Epoch = epoch;
|
||||
Source = source;
|
||||
}
|
||||
}
|
||||
|
||||
private readonly Item[] _ring;
|
||||
private int _head; // index of the oldest item
|
||||
private int _count;
|
||||
|
||||
public PendingIdQueue(int capacity)
|
||||
{
|
||||
if (capacity <= 0) throw new System.ArgumentOutOfRangeException(nameof(capacity));
|
||||
_ring = new Item[capacity];
|
||||
}
|
||||
|
||||
public int Count => _count;
|
||||
public int Capacity => _ring.Length;
|
||||
|
||||
/// <summary>Requests absorbed by an already-pending entry since construction.</summary>
|
||||
public long MergedTotal { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Queue a request for <paramref name="id"/>, or merge it into a pending one for the
|
||||
/// same object from the same <paramref name="epoch"/> that is at most
|
||||
/// <paramref name="mergeMaxAgeMs"/> old at <paramref name="nowMs"/> and was queued AFTER
|
||||
/// <paramref name="mergeOnlyAfterMs"/> (the last moment a world transition held the
|
||||
/// drains: an entry from before then is dropped when the drain reaches it, and a request
|
||||
/// merged into it would be lost with it).
|
||||
/// </summary>
|
||||
public Result Enqueue(uint id, long nowMs, int epoch, long mergeMaxAgeMs, long mergeOnlyAfterMs = 0, byte source = 0)
|
||||
{
|
||||
for (int i = 0; i < _count; i++)
|
||||
{
|
||||
ref readonly Item q = ref _ring[(_head + i) % _ring.Length];
|
||||
if (q.Id == id && q.Epoch == epoch && nowMs - q.At <= mergeMaxAgeMs
|
||||
&& (mergeOnlyAfterMs <= 0 || q.At > mergeOnlyAfterMs)) // 0 = no transition: no floor
|
||||
{
|
||||
MergedTotal++;
|
||||
return Result.Merged;
|
||||
}
|
||||
}
|
||||
if (_count >= _ring.Length)
|
||||
return Result.Full;
|
||||
_ring[(_head + _count) % _ring.Length] = new Item(id, nowMs, epoch, source);
|
||||
_count++;
|
||||
return Result.Queued;
|
||||
}
|
||||
|
||||
public bool TryDequeue(out Item item)
|
||||
{
|
||||
if (_count == 0)
|
||||
{
|
||||
item = default;
|
||||
return false;
|
||||
}
|
||||
item = _ring[_head];
|
||||
_ring[_head] = default;
|
||||
_head = (_head + 1) % _ring.Length;
|
||||
_count--;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
System.Array.Clear(_ring);
|
||||
_head = 0;
|
||||
_count = 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -10,8 +10,14 @@
|
|||
// teleport. With these lines a crash can be lined up with what the character
|
||||
// was doing.
|
||||
//
|
||||
// Also the world-transition gate (WorldTransitionState): while the player is dead,
|
||||
// portaling, or settling after either or after a landblock jump, AcMainThreadQueue
|
||||
// holds every queued game-mutating call instead of running it into a world AC is
|
||||
// tearing down (a client died right after a death recall's landblock jump).
|
||||
//
|
||||
// Sampled from GameTickHooks.UseTimeDetour on AC's main thread, before AC's
|
||||
// tick, so the reads see a consistent world. Alloc-free except on an edge.
|
||||
// tick and before the cast drain, so the reads see a consistent world and the gate
|
||||
// knows about a death in the same tick. Alloc-free except on an edge.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -21,20 +27,53 @@ namespace RynthCore.Engine.Compatibility;
|
|||
|
||||
internal static class PlayerLifecycleLog
|
||||
{
|
||||
private static bool _init;
|
||||
// Main thread only (the UseTime sample and both main-thread drains).
|
||||
private static readonly WorldTransitionState _state = new();
|
||||
private static long _settleUntil; // published copy for other threads
|
||||
private static volatile bool _portaling, _dead;
|
||||
private static long _transitionUntil;
|
||||
private const long TransitionSettleMs = 5_000;
|
||||
private static long _portalEnteredAt, _diedAt;
|
||||
|
||||
/// <summary>
|
||||
/// Dead, in portal space, or within 5 s after either: AC is tearing down and
|
||||
/// loading the world, so nothing should poke at its state (BusyCountHooks'
|
||||
/// force-clear). As of the last game tick; any thread.
|
||||
/// Dead, in portal space, or within 5 s after either or after a landblock jump: AC is
|
||||
/// tearing down and loading the world, so nothing should poke at its state
|
||||
/// (BusyCountHooks' force-clear). As of the last game tick; any thread.
|
||||
/// </summary>
|
||||
public static bool InWorldTransition =>
|
||||
_dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _transitionUntil);
|
||||
private static uint _landblock;
|
||||
private static long _portalEnteredAt, _diedAt;
|
||||
_dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _settleUntil);
|
||||
|
||||
/// <summary>
|
||||
/// When the last settle window ends (TickCount64; 0 = no transition yet), as of the last
|
||||
/// game tick; any thread. Moves only on a death, a portal, a teleport or a landblock jump,
|
||||
/// never on a walk into the next landblock (AutoIdPolicy's post-transition defer).
|
||||
/// </summary>
|
||||
public static long SettleUntilMs => Interlocked.Read(ref _settleUntil);
|
||||
|
||||
/// <summary>
|
||||
/// AC main thread only (the queue drains): true = hold everything queued now (see
|
||||
/// WorldTransitionState for the rule).
|
||||
/// </summary>
|
||||
public static bool HoldQueuedWork(long nowMs)
|
||||
{
|
||||
bool hold = _state.CheckHolding(nowMs);
|
||||
if (hold) Interlocked.Exchange(ref _lastBlockedPublished, nowMs);
|
||||
return hold;
|
||||
}
|
||||
|
||||
/// <summary>AC main thread only: what a drain does with one queued item (WorldTransitionState.Decide).</summary>
|
||||
public static WorldTransitionState.Verdict DecideQueued(long nowMs, long queuedAtMs, bool teardown)
|
||||
{
|
||||
WorldTransitionState.Verdict v = _state.Decide(nowMs, queuedAtMs, teardown);
|
||||
if (v == WorldTransitionState.Verdict.Hold) Interlocked.Exchange(ref _lastBlockedPublished, nowMs);
|
||||
return v;
|
||||
}
|
||||
|
||||
private static long _lastBlockedPublished;
|
||||
|
||||
/// <summary>
|
||||
/// The last moment a drain was held by a world transition (0 = never), for other threads:
|
||||
/// queued work from at or before it is dropped when the drains reach it.
|
||||
/// </summary>
|
||||
public static long LastBlockedMs => Interlocked.Read(ref _lastBlockedPublished);
|
||||
|
||||
/// <summary>AC main thread, once per game tick.</summary>
|
||||
public static void SampleOnGameThread(bool portaling)
|
||||
|
|
@ -52,51 +91,44 @@ internal static class PlayerLifecycleLog
|
|||
cell = c;
|
||||
uint landblock = cell >> 16;
|
||||
|
||||
if (!_init)
|
||||
{
|
||||
_init = true;
|
||||
_portaling = portaling;
|
||||
_dead = dead;
|
||||
_landblock = landblock;
|
||||
return;
|
||||
}
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
if (dead || portaling || _dead || _portaling)
|
||||
Interlocked.Exchange(ref _transitionUntil, now + TransitionSettleMs);
|
||||
if (dead != _dead)
|
||||
{
|
||||
if (dead)
|
||||
{
|
||||
_diedAt = now;
|
||||
RynthLog.Info($"[Lifecycle] player DIED (health 0/{maxHealth}) in landblock 0x{landblock:X4} (cell 0x{cell:X8}).");
|
||||
}
|
||||
else
|
||||
RynthLog.Info($"[Lifecycle] player alive again (health {health}/{maxHealth}) {Ago(_diedAt, now)} after death, landblock 0x{landblock:X4}.");
|
||||
_dead = dead;
|
||||
}
|
||||
WorldTransitionState.Edge edges = _state.Sample(now, dead, portaling, landblock);
|
||||
_dead = _state.Dead;
|
||||
_portaling = _state.Portaling;
|
||||
Interlocked.Exchange(ref _settleUntil, _state.SettleUntilMs);
|
||||
if (edges == WorldTransitionState.Edge.None)
|
||||
return;
|
||||
|
||||
if (portaling != _portaling)
|
||||
if ((edges & WorldTransitionState.Edge.Died) != 0)
|
||||
{
|
||||
if (portaling)
|
||||
{
|
||||
_portalEnteredAt = now;
|
||||
string why = _diedAt != 0 && now - _diedAt < 30_000 ? " (death portal)" : "";
|
||||
RynthLog.Info($"[Lifecycle] portal space ENTERED{why} from landblock 0x{landblock:X4} (cell 0x{cell:X8}).");
|
||||
}
|
||||
else
|
||||
RynthLog.Info($"[Lifecycle] portal space EXITED into landblock 0x{landblock:X4} (cell 0x{cell:X8}) after {Ago(_portalEnteredAt, now)}.");
|
||||
_portaling = portaling;
|
||||
_diedAt = now;
|
||||
RynthLog.Info($"[Lifecycle] player DIED (health 0/{maxHealth}) in landblock 0x{landblock:X4} (cell 0x{cell:X8}).");
|
||||
}
|
||||
if ((edges & WorldTransitionState.Edge.Revived) != 0)
|
||||
RynthLog.Info($"[Lifecycle] player alive again (health {health}/{maxHealth}) {Ago(_diedAt, now)} after death, landblock 0x{landblock:X4}.");
|
||||
if ((edges & WorldTransitionState.Edge.PortalEntered) != 0)
|
||||
{
|
||||
_portalEnteredAt = now;
|
||||
string why = _diedAt != 0 && now - _diedAt < 30_000 ? " (death portal)" : "";
|
||||
RynthLog.Info($"[Lifecycle] portal space ENTERED{why} from landblock 0x{landblock:X4} (cell 0x{cell:X8}).");
|
||||
}
|
||||
if ((edges & WorldTransitionState.Edge.PortalExited) != 0)
|
||||
RynthLog.Info($"[Lifecycle] portal space EXITED into landblock 0x{landblock:X4} (cell 0x{cell:X8}) after {Ago(_portalEnteredAt, now)}.");
|
||||
if ((edges & WorldTransitionState.Edge.LandblockJump) != 0)
|
||||
RynthLog.Info($"[Lifecycle] landblock jump 0x{_state.PreviousLandblock:X4} -> 0x{landblock:X4}{(portaling ? " (in portal space)" : "")}; queued game actions held off for {WorldTransitionState.SettleMs / 1000} s.");
|
||||
}
|
||||
|
||||
if (landblock != 0 && _landblock != 0 && landblock != _landblock)
|
||||
{
|
||||
int dx = (int)((landblock >> 8) & 0xFF) - (int)((_landblock >> 8) & 0xFF);
|
||||
int dy = (int)(landblock & 0xFF) - (int)(_landblock & 0xFF);
|
||||
if (Math.Abs(dx) > 1 || Math.Abs(dy) > 1)
|
||||
RynthLog.Info($"[Lifecycle] landblock jump 0x{_landblock:X4} -> 0x{landblock:X4}{(portaling ? " (in portal space)" : "")}.");
|
||||
}
|
||||
if (landblock != 0) _landblock = landblock;
|
||||
/// <summary>
|
||||
/// AC main thread (SmartBoxHooks, after AC handled 0xF751 PlayerTeleport): a teleport starts
|
||||
/// now. The settle window runs from here, published at once for the enqueue side.
|
||||
/// </summary>
|
||||
public static void OnTeleportMessage()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
bool started = _state.OnTeleportMessage(now);
|
||||
Interlocked.Exchange(ref _settleUntil, _state.SettleUntilMs);
|
||||
if (started)
|
||||
RynthLog.Info($"[Lifecycle] PlayerTeleport (0xF751) received in landblock 0x{_state.Landblock:X4}; queued game actions held off for {WorldTransitionState.SettleMs / 1000} s.");
|
||||
}
|
||||
|
||||
private static string Ago(long since, long now) =>
|
||||
|
|
|
|||
|
|
@ -385,7 +385,7 @@ internal static class PlayerPhysicsHooks
|
|||
// Park the heading in the coalesced slot instead; AcMainThreadQueue.Drain
|
||||
// calls back in here on the main thread (and falls back to the
|
||||
// CommandInterpreter turn there when there is no player, as before).
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueDirectHeading(decalHeadingDeg);
|
||||
|
||||
int n = System.Threading.Interlocked.Increment(ref _setHeadingCalls);
|
||||
|
|
@ -457,7 +457,7 @@ internal static class PlayerPhysicsHooks
|
|||
// raw write racing AC's own motion-graph tick is a guaranteed torn
|
||||
// write, not just an AV risk. Reachable off-thread via Jumper.cs's
|
||||
// ReleaseJump on the Decal-coexistence pump thread.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueLaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC);
|
||||
|
||||
if (!TryGetCMotionInterp(out IntPtr cmi))
|
||||
|
|
|
|||
|
|
@ -141,7 +141,7 @@ internal static unsafe class PlayerTrade
|
|||
/// <summary>Ask <paramref name="targetId"/> to trade (0x01F6 OpenTradeNegotiations).</summary>
|
||||
public static bool Open(uint targetId)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return _eventOpenTradeNegotiations != null && targetId != 0
|
||||
&& AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Open, targetId, 0);
|
||||
if (_eventOpenTradeNegotiations == null || targetId == 0) return false;
|
||||
|
|
@ -153,7 +153,7 @@ internal static unsafe class PlayerTrade
|
|||
/// <summary>Put one of your items in the trade window (0x01F8 AddToTrade). slot 0 = next free.</summary>
|
||||
public static bool Add(uint itemId, uint slot)
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return _eventAddToTrade != null && itemId != 0
|
||||
&& AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Add, itemId, slot);
|
||||
if (_eventAddToTrade == null || itemId == 0) return false;
|
||||
|
|
@ -165,7 +165,7 @@ internal static unsafe class PlayerTrade
|
|||
/// <summary>Empty both sides of the window (0x0204 ResetTrade).</summary>
|
||||
public static bool Reset()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return _eventResetTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Reset, 0, 0);
|
||||
if (_eventResetTrade == null) return false;
|
||||
byte rv = _eventResetTrade();
|
||||
|
|
@ -176,7 +176,7 @@ internal static unsafe class PlayerTrade
|
|||
/// <summary>Close the trade (0x01F7 CloseTradeNegotiations).</summary>
|
||||
public static bool Close()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return _eventCloseTradeNegotiations != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Close, 0, 0);
|
||||
if (_eventCloseTradeNegotiations == null) return false;
|
||||
byte rv = _eventCloseTradeNegotiations();
|
||||
|
|
@ -187,7 +187,7 @@ internal static unsafe class PlayerTrade
|
|||
/// <summary>Accept the trade as it stands (the window's Accept button, 0x01FA AcceptTrade).</summary>
|
||||
public static bool Accept()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return _tradeSystemAcceptTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Accept, 0, 0);
|
||||
if (_tradeSystemAcceptTrade == null) return false;
|
||||
IntPtr system = TradeSystemWithTrade();
|
||||
|
|
@ -200,7 +200,7 @@ internal static unsafe class PlayerTrade
|
|||
/// <summary>Withdraw your acceptance (the window's Decline button, 0x01FB DeclineTrade).</summary>
|
||||
public static bool Decline()
|
||||
{
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
if (AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return _tradeSystemDeclineTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Decline, 0, 0);
|
||||
if (_tradeSystemDeclineTrade == null) return false;
|
||||
IntPtr system = TradeSystemWithTrade();
|
||||
|
|
|
|||
|
|
@ -121,7 +121,7 @@ internal static unsafe class PlayerTraining
|
|||
RynthLog.Compat($"PlayerTraining: {kind} {stype} not sent - not in the world");
|
||||
return false;
|
||||
}
|
||||
if (defer || !MainThreadGuard.IsOnMainThread())
|
||||
if (defer || AcMainThreadQueue.MustQueue(teardown: false))
|
||||
return AcMainThreadQueue.EnqueueTrain((uint)kind, stype, xp);
|
||||
|
||||
byte rv = kind switch
|
||||
|
|
|
|||
|
|
@ -47,28 +47,6 @@ internal static class ProcessExitHooks
|
|||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint NtTerminateProcessDelegate(IntPtr processHandle, uint exitStatus);
|
||||
|
||||
// kernel32!RaiseFailFastException — what __fastfail() / abort() / FailFast
|
||||
// route through. Doesn't take an exit code; takes EXCEPTION_RECORD + CONTEXT.
|
||||
// We don't need the params, just the call-site capture.
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate void RaiseFailFastExceptionDelegate(IntPtr pExceptionRecord, IntPtr pContext, uint dwFlags);
|
||||
|
||||
// ntdll!RtlFailFast(NTSTATUS) — internally executes `int 0x29` (the
|
||||
// __fastfail intrinsic). The kernel handles 0x29 directly and terminates
|
||||
// the process WITHOUT re-entering user mode through ExitProcess /
|
||||
// TerminateProcess / RaiseFailFastException. Hooking RtlFailFast itself
|
||||
// is the only way to capture this path before the kernel takes over.
|
||||
// Used by: stack-cookie failures (/GS), heap corruption checks, CRT
|
||||
// abort paths on newer toolchains, NTDLL's own internal asserts.
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate void RtlFailFastDelegate(uint code);
|
||||
|
||||
// ntdll!RtlFailFast2(NTSTATUS, EXCEPTION_RECORD*) — newer variant that
|
||||
// also passes an exception record. Same semantics: the kernel terminates
|
||||
// the process via int 0x29 without revisiting user mode.
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate void RtlFailFast2Delegate(uint code, IntPtr pExceptionRecord);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
|
||||
|
||||
|
|
@ -103,43 +81,9 @@ internal static class ProcessExitHooks
|
|||
private static RtlExitUserProcessDelegate? _rtlExitOriginal;
|
||||
private static NtTerminateProcessDelegate? _ntTermDetour;
|
||||
private static NtTerminateProcessDelegate? _ntTermOriginal;
|
||||
private static RaiseFailFastExceptionDelegate? _failFastDetour;
|
||||
private static RaiseFailFastExceptionDelegate? _failFastOriginal;
|
||||
private static RtlFailFastDelegate? _rtlFailFastDetour;
|
||||
private static RtlFailFastDelegate? _rtlFailFastOriginal;
|
||||
private static RtlFailFast2Delegate? _rtlFailFast2Detour;
|
||||
private static RtlFailFast2Delegate? _rtlFailFast2Original;
|
||||
|
||||
private static int _installed;
|
||||
private static int _logged; // ensure we log at most once even if both fire
|
||||
|
||||
// Re-entrancy latch for the fail-fast family (RaiseFailFastException,
|
||||
// RtlFailFast, RtlFailFast2). In the NativeAOT-inside-acclient environment
|
||||
// a fail-fast does NOT terminate the way it does in a normal process: the
|
||||
// runtime/AC exception machinery swallows or continues the fail-fast
|
||||
// exception, so kernel32!RaiseFailFastException RETURNS instead of killing
|
||||
// the process. Its caller then re-invokes it, hitting our MinHook again →
|
||||
// detour re-enters → calls the original again → ~190K-deep recursion that
|
||||
// exhausts the 8 MB stack and AVs in ntdll (the recursing code is this
|
||||
// exit logger itself, so nothing downstream can ever log it). Latch is
|
||||
// process-wide and never reset — a fail-fast is terminal by contract;
|
||||
// there is no "recovery", we only need to die cleanly and once.
|
||||
private static int _inFailFast;
|
||||
|
||||
/// <summary>
|
||||
/// Terminate without any possibility of re-entering a ProcessExitHooks
|
||||
/// detour. Each call target is a MinHook *trampoline* (relocated original
|
||||
/// prologue + jump PAST our hook), so none of them route back through our
|
||||
/// detours. Used to break the fail-fast bounce.
|
||||
/// </summary>
|
||||
private static void HardTerminateNoReentry(uint code)
|
||||
{
|
||||
try { _ntTermOriginal?.Invoke(new IntPtr(-1), code); } catch { }
|
||||
try { _rtlExitOriginal?.Invoke(code); } catch { }
|
||||
try { _exitOriginal?.Invoke(code); } catch { }
|
||||
try { Environment.Exit(unchecked((int)code)); } catch { }
|
||||
}
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
|
||||
|
|
@ -178,23 +122,13 @@ internal static class ProcessExitHooks
|
|||
RynthLog.Info($"ProcessExitHooks: hooked kernel32!TerminateProcess @ 0x{terminateTarget.ToInt32():X8}.");
|
||||
}
|
||||
|
||||
// ── DO NOT HOOK RaiseFailFastException (proven fatal 2026-05-16) ──
|
||||
// Dump analysis of the every-few-minutes silent crash showed a
|
||||
// 190K-deep stack overflow whose repeating frame pair is
|
||||
// <ReverseOpenStaticDelegateStub>...RaiseFailFastExceptionDelegate
|
||||
// ↔ RhpReversePInvokeAttachOrTrapThread2. The NativeAOT reverse-
|
||||
// P/Invoke transition that enters a managed detour for this export
|
||||
// itself re-triggers RaiseFailFastException, so the detour recurses
|
||||
// through the transition shim BEFORE any managed code (incl. any
|
||||
// re-entrancy guard) can run. Unfixable from the managed side — the
|
||||
// only correct action is to not hook it. A real fail-fast then
|
||||
// terminates cleanly (as designed) instead of our hook converting
|
||||
// it into the guaranteed stack-overflow crash. Same applies to
|
||||
// ntdll!RtlFailFast / RtlFailFast2 below. The other exit hooks
|
||||
// (ExitProcess/TerminateProcess/RtlExitUserProcess/NtTerminate) are
|
||||
// safe — exiting the process does not re-enter those from within
|
||||
// the transition, and they log clean interceptions.
|
||||
|
||||
// DO NOT HOOK RaiseFailFastException, RtlFailFast or RtlFailFast2 (proven fatal
|
||||
// in practice): the reverse-P/Invoke transition into a managed detour for those
|
||||
// exports re-triggered the fail-fast itself (190K-deep recursion through the
|
||||
// transition shim, before any managed guard could run). Their detour bodies were
|
||||
// dead code and are gone, so nothing can switch them back on by
|
||||
// accident: a managed body on the fail-fast path turns a crash that would leave
|
||||
// a dump into a silent one.
|
||||
// ntdll-level hooks — catch paths that bypass kernel32 entirely.
|
||||
IntPtr ntdll = GetModuleHandleW("ntdll.dll");
|
||||
if (ntdll != IntPtr.Zero)
|
||||
|
|
@ -223,38 +157,6 @@ internal static class ProcessExitHooks
|
|||
RynthLog.Info($"ProcessExitHooks: hooked ntdll!NtTerminateProcess @ 0x{ntTermTarget.ToInt32():X8}.");
|
||||
}
|
||||
|
||||
// RtlFailFast / RtlFailFast2 — NOT HOOKED. Same NativeAOT
|
||||
// reverse-P/Invoke re-entry recursion as RaiseFailFastException
|
||||
// (see the block above). Hooking these with a managed detour
|
||||
// is the every-few-minutes crash. Leave them alone; a genuine
|
||||
// fail-fast terminates cleanly. (On this Windows build the
|
||||
// GetProcAddress for these also failed historically anyway.)
|
||||
if (false && ntdll != IntPtr.Zero)
|
||||
{
|
||||
HookExport(ntdll, "RtlFailFast", out IntPtr rtlFailFastTarget);
|
||||
if (rtlFailFastTarget != IntPtr.Zero)
|
||||
{
|
||||
_rtlFailFastDetour = RtlFailFastDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_rtlFailFastDetour);
|
||||
IntPtr trampoline = MinHook.HookCreate(rtlFailFastTarget, detourPtr);
|
||||
_rtlFailFastOriginal = Marshal.GetDelegateForFunctionPointer<RtlFailFastDelegate>(trampoline);
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(rtlFailFastTarget);
|
||||
RynthLog.Info($"ProcessExitHooks: hooked ntdll!RtlFailFast @ 0x{rtlFailFastTarget.ToInt32():X8}.");
|
||||
}
|
||||
|
||||
HookExport(ntdll, "RtlFailFast2", out IntPtr rtlFailFast2Target);
|
||||
if (rtlFailFast2Target != IntPtr.Zero)
|
||||
{
|
||||
_rtlFailFast2Detour = RtlFailFast2Detour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_rtlFailFast2Detour);
|
||||
IntPtr trampoline = MinHook.HookCreate(rtlFailFast2Target, detourPtr);
|
||||
_rtlFailFast2Original = Marshal.GetDelegateForFunctionPointer<RtlFailFast2Delegate>(trampoline);
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(rtlFailFast2Target);
|
||||
RynthLog.Info($"ProcessExitHooks: hooked ntdll!RtlFailFast2 @ 0x{rtlFailFast2Target.ToInt32():X8}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
|
@ -272,6 +174,15 @@ internal static class ProcessExitHooks
|
|||
|
||||
private static void ExitProcessDetour(uint exitCode)
|
||||
{
|
||||
// A crash exit goes straight to the original, before any managed work (IsCrashExit).
|
||||
// The reverse-P/Invoke transition into this detour is the only managed step left; a
|
||||
// native pass-through would remove that too; it is possible but not done here.
|
||||
if (IsCrashExit(exitCode))
|
||||
{
|
||||
SehTrampoline.FlushCrashLog(exitCode); // native, allocation-free
|
||||
_exitOriginal!(exitCode);
|
||||
return;
|
||||
}
|
||||
LogTermination("ExitProcess", IntPtr.Zero, exitCode);
|
||||
// Run our orderly shutdown BEFORE AC's CRT atexit chain. Without this,
|
||||
// hooks stay installed, our threads (TickPump, Avalonia STA) keep
|
||||
|
|
@ -283,44 +194,45 @@ internal static class ProcessExitHooks
|
|||
catch { /* original never returns; swallow if it somehow does */ }
|
||||
}
|
||||
|
||||
// A crash exit: an NTSTATUS error or exception code (0xC0000000 and up: 0xC0000005 an
|
||||
// access violation, 0xE0434352 a CLR exception). The process is dying of a fault, often
|
||||
// from inside the runtime's own fatal-error path; managed work here (logging, a
|
||||
// MiniDumpWriteDump) can deadlock or fault again there and leave nothing at all. So a crash
|
||||
// exit is passed straight to the original. The evidence comes from places that do not
|
||||
// need managed code on the way out: the native crash logger (SehTrampoline.c, its vectored
|
||||
// handler sees the fault first) and CoreCLR's own createdump (native\Loader\Loader.c, ConfigureCrashDumps). This
|
||||
// replaces the managed crash dump written here before, which left nothing for real crashes.
|
||||
// The one call made first, SehTrampoline.FlushCrashLog, is a raw native call: it writes
|
||||
// the crash logger's recent first-chance records that were not written one by one (the
|
||||
// fatal hit of an address seen before is usually among them; a terminate from a handler
|
||||
// never reaches the last-chance filter). Which codes count: CrashExitRule.
|
||||
private static bool IsCrashExit(uint code) => CrashExitRule.IsCrashExit(code);
|
||||
|
||||
private static bool TerminateProcessDetour(IntPtr hProcess, uint exitCode)
|
||||
{
|
||||
// Only log when terminating ourselves — TerminateProcess on other
|
||||
// process handles is a normal Process.Kill and not what we're hunting.
|
||||
// hProcess == -1 (pseudo-handle for current process) or == GetCurrentProcess() handle.
|
||||
// Only log when terminating ourselves: TerminateProcess on other process handles is a
|
||||
// normal Process.Kill and not what we're hunting. hProcess == -1 is the pseudo-handle.
|
||||
bool selfKill = hProcess == new IntPtr(-1) || hProcess == GetCurrentProcessHandle();
|
||||
if (selfKill)
|
||||
{
|
||||
LogTermination("TerminateProcess", hProcess, exitCode);
|
||||
DumpCrashOnce("TerminateProcess", exitCode);
|
||||
if (IsCrashExit(exitCode)) SehTrampoline.FlushCrashLog(exitCode);
|
||||
else LogTermination("TerminateProcess", hProcess, exitCode);
|
||||
}
|
||||
try { return _terminateOriginal!(hProcess, exitCode); }
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
// A crash exit (an NTSTATUS error code, 0xC0000000 and up: 0xC0000005 is an access
|
||||
// violation) on the way out: write a minidump once, while the faulting frames are still on
|
||||
// the stack. The runtime ends the process with TerminateProcess after a native AV under one
|
||||
// of our detours, so no unhandled exception ever reaches a crash watcher (procdump -e saw
|
||||
// nothing for Lucy's Town Network crashes, 10-01 19:46 and 10-02 15:55).
|
||||
private static int _crashDumped;
|
||||
private static void DumpCrashOnce(string via, uint code)
|
||||
{
|
||||
if (code < 0xC0000000u || System.Threading.Interlocked.Exchange(ref _crashDumped, 1) != 0) return;
|
||||
try
|
||||
{
|
||||
if (CrashDump.WriteSelfDump($"{via} 0x{code:X8}", out string path, "crash"))
|
||||
RynthLog.Info($"ProcessExit: crash dump written {path} ({via} 0x{code:X8})");
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern IntPtr GetCurrentProcess();
|
||||
private static IntPtr GetCurrentProcessHandle() => GetCurrentProcess();
|
||||
|
||||
private static void RtlExitUserProcessDetour(uint exitStatus)
|
||||
{
|
||||
if (IsCrashExit(exitStatus)) // see ExitProcessDetour
|
||||
{
|
||||
SehTrampoline.FlushCrashLog(exitStatus);
|
||||
_rtlExitOriginal!(exitStatus);
|
||||
return;
|
||||
}
|
||||
LogTermination("RtlExitUserProcess", IntPtr.Zero, exitStatus);
|
||||
try { EngineLifecycle.Shutdown(); }
|
||||
catch (Exception ex) { RynthLog.Info($"ProcessExit: EngineLifecycle.Shutdown threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
|
|
@ -333,57 +245,14 @@ internal static class ProcessExitHooks
|
|||
bool selfKill = processHandle == new IntPtr(-1) || processHandle == GetCurrentProcessHandle();
|
||||
if (selfKill)
|
||||
{
|
||||
LogTermination("NtTerminateProcess", processHandle, exitStatus);
|
||||
DumpCrashOnce("NtTerminateProcess", exitStatus);
|
||||
// A second flush (TerminateProcess calls this) writes nothing: records are written once.
|
||||
if (IsCrashExit(exitStatus)) SehTrampoline.FlushCrashLog(exitStatus);
|
||||
else LogTermination("NtTerminateProcess", processHandle, exitStatus);
|
||||
}
|
||||
try { return _ntTermOriginal!(processHandle, exitStatus); }
|
||||
catch { return 0xC0000001; /* STATUS_UNSUCCESSFUL */ }
|
||||
}
|
||||
|
||||
private static void RaiseFailFastExceptionDetour(IntPtr pExceptionRecord, IntPtr pContext, uint dwFlags)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _inFailFast, 1) != 0)
|
||||
{
|
||||
// Re-entered: the original bounced back through our hook instead
|
||||
// of terminating. Forwarding again is the 190K-deep stack-overflow
|
||||
// recursion. Break it — die now, non-recursively.
|
||||
HardTerminateNoReentry(dwFlags);
|
||||
return;
|
||||
}
|
||||
LogTermination("RaiseFailFastException", IntPtr.Zero, dwFlags);
|
||||
try { _failFastOriginal!(pExceptionRecord, pContext, dwFlags); }
|
||||
catch { }
|
||||
// A real fail-fast never returns. In this environment it can — don't
|
||||
// let the caller spin re-raising it; terminate deterministically.
|
||||
HardTerminateNoReentry(dwFlags);
|
||||
}
|
||||
|
||||
private static void RtlFailFastDetour(uint code)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _inFailFast, 1) != 0)
|
||||
{
|
||||
HardTerminateNoReentry(code);
|
||||
return;
|
||||
}
|
||||
LogTermination("RtlFailFast", IntPtr.Zero, code);
|
||||
try { _rtlFailFastOriginal!(code); }
|
||||
catch { /* original never returns */ }
|
||||
HardTerminateNoReentry(code);
|
||||
}
|
||||
|
||||
private static void RtlFailFast2Detour(uint code, IntPtr pExceptionRecord)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _inFailFast, 1) != 0)
|
||||
{
|
||||
HardTerminateNoReentry(code);
|
||||
return;
|
||||
}
|
||||
LogTermination("RtlFailFast2", IntPtr.Zero, code);
|
||||
try { _rtlFailFast2Original!(code, pExceptionRecord); }
|
||||
catch { /* original never returns */ }
|
||||
HardTerminateNoReentry(code);
|
||||
}
|
||||
|
||||
/// <summary>ExitProcess/TerminateProcess was called: the process is closing.</summary>
|
||||
public static bool TerminationIntercepted => Volatile.Read(ref _logged) != 0;
|
||||
|
||||
|
|
|
|||
|
|
@ -456,7 +456,9 @@ internal static class PropertyUpdateHooks
|
|||
if (objectId != 0)
|
||||
{
|
||||
EvictObject(objectId);
|
||||
AppraisalHooks.EvictObject(objectId);
|
||||
// A client release keeps the identify data a while (a server delete,
|
||||
// 0xF747, evicts it): see ReleasedObjectRetention.
|
||||
AppraisalHooks.OnClientRelease(objectId, Environment.TickCount64);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,77 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/ReleasedObjectRetention.cs
|
||||
//
|
||||
// How long AppraisalHooks keeps an object's identify data after the CLIENT released it
|
||||
// (AC's BeingDeleted, which fires for every object leaving the client's view).
|
||||
//
|
||||
// Before: the data was evicted on every client release, so when the
|
||||
// object came back into view AutoId found nothing cached and appraised it again: the
|
||||
// 10-minute re-appraisal window (AutoIdEligibility) almost never applied. Now the data is
|
||||
// kept for RetainMs after a client release and dropped:
|
||||
// - when RetainMs has passed (Expire, from AutoIdService's timer);
|
||||
// - when the SERVER deleted the object (0xF747; AppraisalHooks.EvictObject);
|
||||
// - at a session clear (logout), and under AppraisalHooks' object cap.
|
||||
// A re-create (OnLive) makes the object current again.
|
||||
//
|
||||
// Pure bookkeeping (released ids and when); no locking (AppraisalHooks holds its lock).
|
||||
// Compiled into tools\EngineRobustnessTests.
|
||||
// ============================================================================
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal sealed class ReleasedObjectRetention
|
||||
{
|
||||
public const long DefaultRetainMs = 10L * 60 * 1000;
|
||||
public const int DefaultMaxReleased = 4096;
|
||||
|
||||
private readonly Dictionary<uint, long> _releasedAt;
|
||||
private readonly long _retainMs;
|
||||
private readonly int _max;
|
||||
|
||||
public ReleasedObjectRetention(long retainMs = DefaultRetainMs, int maxReleased = DefaultMaxReleased)
|
||||
{
|
||||
_retainMs = retainMs;
|
||||
_max = maxReleased;
|
||||
_releasedAt = new Dictionary<uint, long>(maxReleased + 1);
|
||||
}
|
||||
|
||||
public int Count => _releasedAt.Count;
|
||||
public long RetainMs => _retainMs;
|
||||
|
||||
/// <summary>
|
||||
/// The client released <paramref name="id"/> (which has cached data). Returns true when the
|
||||
/// data is kept for now; false when it must be dropped at once (the bound is reached and
|
||||
/// nothing has expired to make room).
|
||||
/// </summary>
|
||||
public bool OnRelease(uint id, long nowMs)
|
||||
{
|
||||
if (_releasedAt.ContainsKey(id)) { _releasedAt[id] = nowMs; return true; }
|
||||
if (_releasedAt.Count >= _max) return false;
|
||||
_releasedAt[id] = nowMs == 0 ? 1 : nowMs;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The object is current again (re-created), or its data was dropped for another reason.</summary>
|
||||
public void Forget(uint id) => _releasedAt.Remove(id);
|
||||
|
||||
public bool IsReleased(uint id) => _releasedAt.ContainsKey(id);
|
||||
|
||||
/// <summary>Released ids whose data has outlived RetainMs: removed here and added to <paramref name="expired"/>.</summary>
|
||||
public int Expire(long nowMs, List<uint> expired)
|
||||
{
|
||||
int n = 0;
|
||||
foreach (KeyValuePair<uint, long> kv in _releasedAt)
|
||||
{
|
||||
if (nowMs - kv.Value < _retainMs) continue;
|
||||
expired.Add(kv.Key);
|
||||
n++;
|
||||
}
|
||||
for (int i = expired.Count - n; i < expired.Count; i++)
|
||||
_releasedAt.Remove(expired[i]);
|
||||
return n;
|
||||
}
|
||||
|
||||
public void Clear() => _releasedAt.Clear();
|
||||
}
|
||||
|
|
@ -81,6 +81,12 @@ namespace RynthCore.Engine.Compatibility;
|
|||
/// <item><c>/rc report [text]</c> - "Report a problem" (<see cref="Report.ProblemReport"/>): alone it
|
||||
/// opens the panel; with text it sends that report now, with the recent log attached
|
||||
/// (the panel is where the log can be left out). One report a minute.</item>
|
||||
/// <item><c>/rc autoid [all|limited|off]</c> - which background appraisals the engine's AutoId
|
||||
/// sends (<see cref="AutoIdService"/>, <see cref="AutoIdPolicy"/>; saved in engine.json);
|
||||
/// alone it reports the mode and the identify counts by who asked.</item>
|
||||
/// <item><c>/rc hotkeys</c> - opens Settings > Hotkeys. <c>/rc hotkey list | add <combo> <action or
|
||||
/// /command> | remove <combo> | enable|disable <combo> | actions | status | on|off</c> - the user
|
||||
/// hotkeys (<see cref="Hotkeys.HotkeyService"/>; saved for the PC in hotkeys.txt).</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
internal static class RynthCoreChatCommands
|
||||
|
|
@ -288,6 +294,18 @@ internal static class RynthCoreChatCommands
|
|||
return true;
|
||||
}
|
||||
|
||||
// /rc autoid [all|limited|off] : which background appraisals AutoId sends (alone: status)
|
||||
if (IsVerb(sub, "autoid", out string autoIdArgs))
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (string l in AutoIdService.HandleCommand(autoIdArgs))
|
||||
Reply(l);
|
||||
}
|
||||
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc autoid failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||
return true;
|
||||
}
|
||||
|
||||
// /rc netmsg [status|on|off|log on|off|capture on|off] : the v78 server message stream
|
||||
if (IsVerb(sub, "netmsg", out string netArgs))
|
||||
{
|
||||
|
|
@ -310,6 +328,97 @@ internal static class RynthCoreChatCommands
|
|||
return true;
|
||||
}
|
||||
|
||||
// /rc bounties|guardian [show|hide|toggle] : the ILT section's panels, like the bar's
|
||||
// ILT button (Bounties: the RynthILT plugin's tracker; Guardian: RynthAi's Temple
|
||||
// guardian tools). Only on Infinite Leaftide with the plugin installed.
|
||||
if (IsVerb(sub, "bounties", out string panelArgs) || IsVerb(sub, "bounty", out panelArgs) || IsVerb(sub, "bountys", out panelArgs))
|
||||
{
|
||||
IltPanel(ImGuiBackend.Panels.BountiesFace.Title, "Bounties", "RynthILT", panelArgs);
|
||||
return true;
|
||||
}
|
||||
if (IsVerb(sub, "guardian", out panelArgs) || IsVerb(sub, "guardians", out panelArgs))
|
||||
{
|
||||
IltPanel(ImGuiBackend.Panels.GuardianFace.Title, "Guardian", "RynthAi", panelArgs);
|
||||
return true;
|
||||
}
|
||||
|
||||
// /rc miniremote [show|hide|toggle|tab <tab>] : the ImGui Mini Remote panel, like its bar
|
||||
// button (RynthAi's dashboard and "/ra hub" use show / hide). "tab" opens it on one of
|
||||
// RynthAi's tabs (character, quests, pets, banking, gear, games; none = the remote).
|
||||
if (IsVerb(sub, "miniremote", out string remoteArgs) || IsVerb(sub, "remote", out remoteArgs))
|
||||
{
|
||||
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.MiniRemoteFace.Title))
|
||||
Reply("The Mini Remote panel isn't available (the ImGui layer is off?).");
|
||||
else if (IsVerb(remoteArgs, "tab", out string tab))
|
||||
{
|
||||
ImGuiBackend.ImGuiPanelHost.Open(ImGuiBackend.Panels.MiniRemoteFace.Title);
|
||||
UI.Data.RynthAiCommands.ApplyRemoteCommand("hub", tab.Length > 0 ? "tab " + tab : "tab");
|
||||
}
|
||||
else if (!TryPanelMode(remoteArgs, out bool? show))
|
||||
Reply("Usage: /rc miniremote [show|hide|toggle|tab <tab>]");
|
||||
else
|
||||
SetPanelOpen(ImGuiBackend.Panels.MiniRemoteFace.Title, show);
|
||||
return true;
|
||||
}
|
||||
|
||||
// /rc skills [show|hide|toggle] : the ImGui Skills panel; /rc progression opens it on its
|
||||
// Progression tab (ILT worlds; the tab shows once RynthAi reports ILT features).
|
||||
if (IsVerb(sub, "skills", out string skillsArgs))
|
||||
{
|
||||
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SkillsFace.Title))
|
||||
Reply("The Skills panel isn't available (the ImGui layer is off?).");
|
||||
else if (!TryPanelMode(skillsArgs, out bool? show))
|
||||
Reply("Usage: /rc skills [show|hide|toggle]");
|
||||
else
|
||||
SetPanelOpen(ImGuiBackend.Panels.SkillsFace.Title, show);
|
||||
return true;
|
||||
}
|
||||
if (sub.Equals("progression", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SkillsFace.Title))
|
||||
Reply("The Skills panel isn't available (the ImGui layer is off?).");
|
||||
else
|
||||
ImGuiBackend.Panels.SkillsFace.ShowProgression();
|
||||
return true;
|
||||
}
|
||||
|
||||
// /rc spells [show|hide|toggle] : RynthAi's Spells window (spell catalog, buff profiles).
|
||||
if (IsVerb(sub, "spells", out string spellsArgs))
|
||||
{
|
||||
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.RynthAiFace.Title))
|
||||
Reply("The Spells window comes with RynthAi; it isn't installed.");
|
||||
else if (!TryPanelMode(spellsArgs, out bool? show))
|
||||
Reply("Usage: /rc spells [show|hide|toggle]");
|
||||
else
|
||||
UI.Data.RynthAiCommands.ApplyRemoteCommand("spells", show == null ? "toggle" : show.Value ? "show" : "hide");
|
||||
return true;
|
||||
}
|
||||
|
||||
// /rc hotkeys : Settings > Hotkeys. /rc hotkey list|add|remove|enable|disable|actions|status|on|off
|
||||
// (Hotkeys/HotkeyService.cs; "/rc hotkeys <verb>" works too).
|
||||
if (IsVerb(sub, "hotkeys", out string hotkeyArgs) && hotkeyArgs.Length == 0)
|
||||
{
|
||||
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SettingsFace.Title))
|
||||
Reply("The Settings panel isn't available (the ImGui layer is off?). /rc hotkey list|add|remove work here in chat.");
|
||||
else
|
||||
{
|
||||
ImGuiBackend.Panels.SettingsFace.RequestTab(ImGuiBackend.Panels.HotkeysSettingsUi.TabName);
|
||||
if (!ImGuiBackend.ImGuiPanelHost.IsOpen(ImGuiBackend.Panels.SettingsFace.Title))
|
||||
UI.PanelRouter.Toggle(ImGuiBackend.Panels.SettingsFace.Title);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (IsVerb(sub, "hotkey", out hotkeyArgs) || IsVerb(sub, "hotkeys", out hotkeyArgs))
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (string l in Hotkeys.HotkeyService.HandleCommand(hotkeyArgs))
|
||||
Reply(l);
|
||||
}
|
||||
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc hotkey failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||
return true;
|
||||
}
|
||||
|
||||
switch (sub.ToLowerInvariant())
|
||||
{
|
||||
case "rl":
|
||||
|
|
@ -318,6 +427,7 @@ internal static class RynthCoreChatCommands
|
|||
// loader's reload shuts this engine down, and this handler runs
|
||||
// inside AC's outgoing-chat hook.
|
||||
RynthLog.Compat("RynthCoreChatCommands: /rc rl — engine reload requested.");
|
||||
EntryPoint.NoteManualReload(); // by hand: not held for combat (EntryPoint.DeferReloadWhilePluginsObject)
|
||||
System.Threading.ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null);
|
||||
return true;
|
||||
|
||||
|
|
@ -338,6 +448,15 @@ internal static class RynthCoreChatCommands
|
|||
UI.PanelRouter.Toggle(ImGuiBackend.Panels.SenseFace.Title);
|
||||
return true;
|
||||
|
||||
case "characters":
|
||||
case "chars":
|
||||
// The ImGui Characters panel (your other RynthCore clients, through RynthNet).
|
||||
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.CharactersFace.Title))
|
||||
Reply("The Characters panel needs the RynthNet plugin (add it in the launcher's Plugins tab).");
|
||||
else
|
||||
UI.PanelRouter.Toggle(ImGuiBackend.Panels.CharactersFace.Title);
|
||||
return true;
|
||||
|
||||
case "itemcount":
|
||||
case "itemhud":
|
||||
// The ImGui Item Count panel (open/close), like its bar button.
|
||||
|
|
@ -347,28 +466,6 @@ internal static class RynthCoreChatCommands
|
|||
UI.PanelRouter.Toggle(ImGuiBackend.Panels.ItemCountFace.Title);
|
||||
return true;
|
||||
|
||||
case "bounties":
|
||||
case "bounty":
|
||||
case "bountys":
|
||||
// The ImGui Bounties panel (ILT section: ACECustom bounties, the RynthILT plugin's
|
||||
// tracker), like the ILT bar button. Only on Infinite Leaftide with RynthILT installed.
|
||||
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.BountiesFace.Title))
|
||||
Reply("The Bounties panel isn't available (the RynthILT plugin isn't installed, or the ImGui layer is off).");
|
||||
else if (!IltInfo.IsIlt && !ImGuiBackend.ImGuiPanelHost.IsOpen(ImGuiBackend.Panels.BountiesFace.Title))
|
||||
Reply("Bounties are an Infinite Leaftide feature, and this isn't Infinite Leaftide (/rc ilt for why).");
|
||||
else
|
||||
UI.PanelRouter.Toggle(ImGuiBackend.Panels.BountiesFace.Title);
|
||||
return true;
|
||||
|
||||
case "remote":
|
||||
case "miniremote":
|
||||
// The ImGui Mini Remote panel (open/close), like its bar button.
|
||||
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.MiniRemoteFace.Title))
|
||||
Reply("The Mini Remote panel isn't available (the ImGui layer is off?).");
|
||||
else
|
||||
UI.PanelRouter.Toggle(ImGuiBackend.Panels.MiniRemoteFace.Title);
|
||||
return true;
|
||||
|
||||
case "resetbar":
|
||||
case "barreset":
|
||||
RynthLog.Compat("RynthCoreChatCommands: /rc resetbar — resetting overlay bar position.");
|
||||
|
|
@ -624,9 +721,12 @@ internal static class RynthCoreChatCommands
|
|||
Reply($"ILT: {(v.IsIlt ? "Infinite Leaftide" : "not Infinite Leaftide")} - {v.Reason}.");
|
||||
Reply($"Signals: host {ServerInfo.HostDescription}; world name {AccountHooks.AnnouncedWorldName ?? "(not announced)"}; "
|
||||
+ $"override {IltInfo.Override}. Lists: {IltInfo.ListsDescription}.");
|
||||
Reply(ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.BountiesFace.Title)
|
||||
? "RynthILT: installed (Bounties: the ILT bar button or /rc bounties)."
|
||||
: "RynthILT: not installed, so there is no ILT section.");
|
||||
bool bounties = ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.BountiesFace.Title);
|
||||
bool guardian = ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.GuardianFace.Title);
|
||||
Reply(bounties ? "RynthILT: installed (Bounties: the ILT bar button or /rc bounties)."
|
||||
: "RynthILT: not installed (no Bounties panel).");
|
||||
Reply(guardian ? "RynthAi: installed (Guardian: the ILT bar button or /rc guardian; the ILT tabs: the Mini Remote)."
|
||||
: "RynthAi: not installed (no Guardian panel or ILT tabs).");
|
||||
}
|
||||
|
||||
private static void HandleMasteryCommand()
|
||||
|
|
@ -670,6 +770,42 @@ internal static class RynthCoreChatCommands
|
|||
Reply(ImGuiBackend.UnderUiLayer.Describe());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "" / "toggle" → null (flip), "show" / "on" / "open" → true, "hide" / "off" / "close" →
|
||||
/// false. False for anything else.
|
||||
/// </summary>
|
||||
private static bool TryPanelMode(string args, out bool? show)
|
||||
{
|
||||
show = null;
|
||||
switch (args.Trim().ToLowerInvariant())
|
||||
{
|
||||
case "": case "toggle": return true;
|
||||
case "show": case "on": case "open": show = true; return true;
|
||||
case "hide": case "off": case "close": show = false; return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Opens (true), closes (false) or toggles (null) an ImGui panel, like its bar button.</summary>
|
||||
private static void SetPanelOpen(string title, bool? show)
|
||||
{
|
||||
if (show == null || show.Value != ImGuiBackend.ImGuiPanelHost.IsOpen(title))
|
||||
UI.PanelRouter.Toggle(title);
|
||||
}
|
||||
|
||||
/// <summary>"/rc bounties|guardian [show|hide|toggle]": one of the ILT section's panels.</summary>
|
||||
private static void IltPanel(string title, string label, string plugin, string args)
|
||||
{
|
||||
if (!ImGuiBackend.ImGuiPanelHost.HasFace(title))
|
||||
Reply($"The {label} panel isn't available (the {plugin} plugin isn't installed, or the ImGui layer is off).");
|
||||
else if (!TryPanelMode(args, out bool? show))
|
||||
Reply($"Usage: /rc {label.ToLowerInvariant()} [show|hide|toggle]");
|
||||
else if (show != false && !IltInfo.IsIlt && !ImGuiBackend.ImGuiPanelHost.IsOpen(title))
|
||||
Reply($"{label} is an Infinite Leaftide feature, and this isn't Infinite Leaftide (/rc ilt for why).");
|
||||
else
|
||||
SetPanelOpen(title, show);
|
||||
}
|
||||
|
||||
private static bool IsVerb(string sub, string verb, out string args)
|
||||
{
|
||||
args = string.Empty;
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@
|
|||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
|
|
@ -43,15 +44,114 @@ internal static class SehTrampoline
|
|||
/// no managed callback / reverse-P/Invoke transition — so unlike the removed
|
||||
/// managed CrashLogger VEH it cannot itself re-trigger a NativeAOT fail-fast on an
|
||||
/// AC-owned thread. Writes the faulting 32-bit context + a module-resolved stack
|
||||
/// sweep to <paramref name="logPath"/> for the 0xC0000005 (AV/CSE) and 0xC0000602
|
||||
/// (RaiseFailFast) classes that bypass managed handlers. Observes only.
|
||||
/// sweep to <paramref name="logPath"/>. v6 (PR #8): each faulting address once, repeats
|
||||
/// at power-of-two counts or after 30 s, .NET/CoreCLR noise not charged to the cap, the
|
||||
/// unhandled-exception entry always; a 16-record ring of the rest is flushed on a crash
|
||||
/// exit (RC_FlushCrashLog), from the last-chance filter, and at process exit (last 30 s).
|
||||
/// AVs caught by the SEH_* wrappers only go to that ring. Observes only.
|
||||
/// Caveat: "pure native" held only while nothing it calls had a managed detour. Before v5
|
||||
/// it called CreateFileW from the handlers, and DatFileShareHooks detours CreateFileW in
|
||||
/// managed code, so older DLLs are not installed while that hook is on (see below).
|
||||
/// </summary>
|
||||
public static void InstallCrashLogger(string logPath)
|
||||
{
|
||||
try { _InstallCrashLogger(logPath); }
|
||||
try
|
||||
{
|
||||
// v2+ logs fatal crashes only (unhandled-exception filter + NativeAOT-module AVs);
|
||||
// v1 (no version export) logged every first-chance AV.
|
||||
uint version = NativeVersion;
|
||||
if (version < SafeCrashLoggerVersion && DatFileShareHooks.IsInstalled)
|
||||
{
|
||||
// v1-v4 open native-crash.log with CreateFileW from inside the VEH, which runs
|
||||
// first, on the faulting thread. DatFileShareHooks detours CreateFileW with a
|
||||
// managed delegate, so for a fault in managed code (any NullReferenceException:
|
||||
// the thread is still in cooperative mode) that is a reverse P/Invoke from
|
||||
// cooperative mode, and CoreCLR ends the process: ReversePInvokeBadTransition,
|
||||
// event 1023 "internal error in the .NET Runtime at IP coreclr.dll+0x256E19",
|
||||
// exit 0x80131506. Seven client deaths 2026-09-29..10-12 were this. v5 opens the
|
||||
// file here instead (a normal P/Invoke), so the handlers never call CreateFileW.
|
||||
RynthLog.Warn($"SehTrampoline: native crash logger NOT installed - the loaded RynthCore.SehTrampoline.dll is v{version}, " +
|
||||
$"whose logger calls CreateFileW inside exception handling; with the DAT share hook's managed CreateFileW detour " +
|
||||
$"that turns any NullReferenceException into a fatal CLR error. Needs v{SafeCrashLoggerVersion}+ " +
|
||||
"(rebuild native\\SehTrampoline, then restart the client). A logger an earlier engine generation installed in " +
|
||||
"this client stays active until the client restarts.");
|
||||
return;
|
||||
}
|
||||
|
||||
_InstallCrashLogger(logPath);
|
||||
string mode = version >= 6 ? "once per address + repeats, flush ring"
|
||||
: version >= 2 ? "fatal-only" : "logs every first-chance AV";
|
||||
RynthLog.Compat($"SehTrampoline: native crash logger installed (v{version}, {mode}) -> {logPath}");
|
||||
}
|
||||
catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||
ResolveFlushCrashLog();
|
||||
}
|
||||
|
||||
// RC_FlushCrashLog, resolved once here (0 = a DLL older than the export). Called through a
|
||||
// raw unmanaged function pointer, so the crash path binds and compiles nothing: the call
|
||||
// is primed below with code 0, which the native side ignores.
|
||||
private static nint _flushCrashLog;
|
||||
|
||||
private static unsafe void ResolveFlushCrashLog()
|
||||
{
|
||||
try
|
||||
{
|
||||
nint module = GetModuleHandleW("RynthCore.SehTrampoline.dll");
|
||||
nint fn = module == 0 ? 0 : GetProcAddress(module, "RC_FlushCrashLog");
|
||||
if (fn == 0)
|
||||
{
|
||||
RynthLog.Compat("SehTrampoline: RC_FlushCrashLog not exported (older DLL); crash exits will not flush the crash log's recent records.");
|
||||
return;
|
||||
}
|
||||
((delegate* unmanaged[Cdecl]<uint, void>)fn)(0); // prime: code 0 is a no-op
|
||||
_flushCrashLog = fn;
|
||||
}
|
||||
catch (Exception ex) { RynthLog.Compat($"SehTrampoline: RC_FlushCrashLog unavailable - {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A crash exit is under way (ProcessExitHooks): write the crash logger's recent first-chance
|
||||
/// records that were not written one by one, such as the fatal repeat of an address seen
|
||||
/// before. Native and allocation-free; writes each record once, so a second call (one exit
|
||||
/// path calling another) writes nothing.
|
||||
/// </summary>
|
||||
public static unsafe void FlushCrashLog(uint exitCode)
|
||||
{
|
||||
nint fn = _flushCrashLog;
|
||||
if (fn == 0 || exitCode == 0) return;
|
||||
((delegate* unmanaged[Cdecl]<uint, void>)fn)(exitCode);
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetModuleHandleW")]
|
||||
private static extern nint GetModuleHandleW(string name);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, EntryPoint = "GetProcAddress", ExactSpelling = true)]
|
||||
private static extern nint GetProcAddress(nint module, string name);
|
||||
|
||||
private static int _moduleRefreshUnavailable;
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the crash logger's module cache (module names at exception time come from it,
|
||||
/// so the handler never calls the loader). Heartbeat thread, every few seconds. A DLL
|
||||
/// older than the export is tolerated: the first failure stops the calls.
|
||||
/// </summary>
|
||||
public static void RefreshCrashLoggerModules()
|
||||
{
|
||||
if (!_available || Volatile.Read(ref _moduleRefreshUnavailable) != 0) return;
|
||||
try { _RefreshCrashLoggerModules(); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Interlocked.Exchange(ref _moduleRefreshUnavailable, 1);
|
||||
RynthLog.Compat($"SehTrampoline: crash-logger module refresh unavailable - {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// First native version whose crash logger opens its file at install time and never calls
|
||||
/// CreateFileW while an exception is being dispatched (see SehTrampoline.c, cl_append_file).
|
||||
/// </summary>
|
||||
public const uint SafeCrashLoggerVersion = 5;
|
||||
|
||||
// ── Tag-parser guard (native detour) ───────────────────────────────────
|
||||
/// <summary>Address of the native tag-parser null-guard detour (RC_TagParserGuard),
|
||||
/// for the engine to pass to MinHook as the detour target.</summary>
|
||||
|
|
@ -70,6 +170,32 @@ internal static class SehTrampoline
|
|||
/// </summary>
|
||||
public static bool IsAvailable => _available;
|
||||
|
||||
private static int _nativeVersion = -1;
|
||||
|
||||
/// <summary>
|
||||
/// Version of the loaded native DLL (0 when unavailable, 1 when it predates the version
|
||||
/// export). A running client keeps the DLL it started with, so a newer engine can meet
|
||||
/// an older trampoline; gate newer exports on this.
|
||||
/// </summary>
|
||||
public static uint NativeVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
int cached = System.Threading.Volatile.Read(ref _nativeVersion);
|
||||
if (cached >= 0)
|
||||
return (uint)cached;
|
||||
uint version = 0;
|
||||
if (_available)
|
||||
{
|
||||
try { version = _SehTrampolineVersion(); }
|
||||
catch (EntryPointNotFoundException) { version = 1; }
|
||||
catch { version = 0; }
|
||||
}
|
||||
System.Threading.Volatile.Write(ref _nativeVersion, (int)version);
|
||||
return version;
|
||||
}
|
||||
}
|
||||
|
||||
// ── P/Invoke declarations ──────────────────────────────────────────────
|
||||
|
||||
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_CdeclPtrUint",
|
||||
|
|
@ -100,10 +226,23 @@ internal static class SehTrampoline
|
|||
CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern unsafe int _ThiscallIntUintPtr(IntPtr fn, IntPtr thisPtr, uint arg1, void* arg2, int* outResult);
|
||||
|
||||
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_GameTickThiscall",
|
||||
CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern unsafe int _GameTickThiscall(IntPtr fn, IntPtr thisPtr, int* outResult,
|
||||
uint* outExAddr, uint* outDataAddr, byte* module, int moduleCap);
|
||||
|
||||
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_InstallCrashLogger",
|
||||
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
|
||||
private static extern void _InstallCrashLogger([MarshalAs(UnmanagedType.LPWStr)] string logPath);
|
||||
|
||||
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_SehTrampolineVersion",
|
||||
CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern uint _SehTrampolineVersion();
|
||||
|
||||
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_RefreshCrashLoggerModules",
|
||||
CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern void _RefreshCrashLoggerModules();
|
||||
|
||||
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_GetTagParserGuardAddress",
|
||||
CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern IntPtr _GetTagParserGuardAddress();
|
||||
|
|
@ -191,4 +330,24 @@ internal static class SehTrampoline
|
|||
avCaught = _ThiscallIntUintPtr(fn, thisPtr, arg1, outStruct, &result) == 0;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// int __thiscall fn(this) — Client::UseTime. Requires <see cref="NativeVersion"/> >= 4.
|
||||
/// On a caught AV: avCaught=true, result 0, and the fault location; <paramref name="exAddr"/>
|
||||
/// is relative to <paramref name="module"/> when that is non-empty, else absolute.
|
||||
/// The native side also writes the full record to native-crash.log.
|
||||
/// </summary>
|
||||
public static unsafe int GameTickThiscall(IntPtr fn, IntPtr thisPtr, out bool avCaught,
|
||||
out uint exAddr, out uint dataAddr, out string module)
|
||||
{
|
||||
const int ModuleCap = 64;
|
||||
byte* name = stackalloc byte[ModuleCap];
|
||||
int result;
|
||||
uint ex, data;
|
||||
avCaught = _GameTickThiscall(fn, thisPtr, &result, &ex, &data, name, ModuleCap) == 0;
|
||||
exAddr = ex;
|
||||
dataAddr = data;
|
||||
module = avCaught ? (Marshal.PtrToStringAnsi((IntPtr)name) ?? string.Empty) : string.Empty;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@ internal static class SmartBoxHooks
|
|||
private const uint PlayerPositionUpdateOpcode = 0x0000F74B;
|
||||
private const uint VectorUpdateOpcode = 0x0000F74E;
|
||||
private const uint UpdateObjectOpcode = 0x0000F7DB;
|
||||
private const uint ServerObjectDeleteOpcode = 0x0000F747;
|
||||
private const uint PlayerTeleportOpcode = 0x0000F751;
|
||||
|
||||
// ACSmartBox::DispatchSmartBoxEvent
|
||||
// 83 EC 08 53 8B 5C 24 10 8B 53 30 83 FA 04 8B 43 2C 56 8B F1 89 44 24 14 89 54 24 08 72 ?? 8B 08
|
||||
|
|
@ -131,11 +133,23 @@ internal static class SmartBoxHooks
|
|||
|
||||
try
|
||||
{
|
||||
ObjectFreshness.Note(info.Opcode, info.RawObjectId, Environment.TickCount64); // ghost check (RemoveClientObject)
|
||||
if (info.Opcode == PositionUpdateOpcode && info.RawObjectId != 0)
|
||||
NotePlayerMotionEcho(blob, info);
|
||||
TryQueueHealthUpdate(blob, info);
|
||||
TryQueueDamageEvent(blob, info);
|
||||
|
||||
// Always on (no server-message capture needed), after AC handled the message:
|
||||
// 0xF747 ObjectDelete [opcode][objectId]: the SERVER deleted it (AutoId re-arms it
|
||||
// and its kept identify data goes), unlike the client's own view releases;
|
||||
// 0xF751 PlayerTeleport: a teleport starts, so queued game actions hold for the
|
||||
// settle window from this moment (WorldTransitionState), whatever the per-tick
|
||||
// teleport_in_progress sample catches.
|
||||
if (info.Opcode == ServerObjectDeleteOpcode && info.RawObjectId != 0)
|
||||
AutoIdService.OnServerDelete(info.RawObjectId);
|
||||
else if (info.Opcode == PlayerTeleportOpcode)
|
||||
PlayerLifecycleLog.OnTeleportMessage();
|
||||
|
||||
if (info.RawObjectId != 0 &&
|
||||
(info.Opcode == PositionUpdateOpcode ||
|
||||
info.Opcode == PlayerPositionUpdateOpcode ||
|
||||
|
|
@ -379,6 +393,15 @@ internal static class SmartBoxHooks
|
|||
RecordWeenieError(eventType, unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))), 0);
|
||||
break;
|
||||
|
||||
case 0x0022: // InventoryPutObjInContainer: [item u32][container u32][placement][type].
|
||||
// AutoId (Limited): an item that landed in the player's inventory with
|
||||
// nothing cached is a candidate. Here, not on the server message stream,
|
||||
// so it works with that stream off (engine.json / /rc netmsg off).
|
||||
if (size >= 12)
|
||||
AutoIdService.OnPutInContainer(
|
||||
unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))),
|
||||
unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 8))));
|
||||
break;
|
||||
case 0x00A0: // InventoryServerSaveFailed: [objectId u32][errorType u32] —
|
||||
// the server refused an inventory change (wield, move, ...).
|
||||
// Layout from UIQueueManager::ProcessNetBlobData's inline case
|
||||
|
|
@ -632,6 +655,7 @@ internal static class SmartBoxHooks
|
|||
if (critOff + 4 > size) return;
|
||||
|
||||
uint damageType = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, off)));
|
||||
double share = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(IntPtr.Add(data, off + 4))); // damage / the monster's max health
|
||||
uint damage = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, off + 12)));
|
||||
uint crit = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, critOff)));
|
||||
if (damage == 0 || damage > 1_000_000) return;
|
||||
|
|
@ -642,8 +666,8 @@ internal static class SmartBoxHooks
|
|||
RynthLog.Compat($"Combat: damage evt 0x{eventType:X3} dmg={damage} crit={crit} atk={attacker} len={size}");
|
||||
}
|
||||
PluginManager.QueueCombatDamage(damage, damageType, crit != 0, attacker);
|
||||
// RynthVision combat text: the attacker event names the monster hit.
|
||||
ImGuiBackend.Hud.HudFeed.OnDamageEvent(attacker, attacker ? ReadString16Latin1(data, 4, size) : null, damage, crit != 0);
|
||||
// RynthVision combat text (and the plate of a monster with no health feed): the attacker event names the monster hit.
|
||||
ImGuiBackend.Hud.HudFeed.OnDamageEvent(attacker, attacker ? ReadString16Latin1(data, 4, size) : null, damage, crit != 0, attacker ? share : 0);
|
||||
}
|
||||
|
||||
private static SmartBoxEventInfo ReadSmartBoxEventInfo(IntPtr blob)
|
||||
|
|
@ -767,6 +791,7 @@ internal static class SmartBoxHooks
|
|||
return;
|
||||
|
||||
uint damageType = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, off)));
|
||||
double share = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(IntPtr.Add(payloadPtr, off + 4))); // damage / the monster's max health
|
||||
uint damage = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, off + 12)));
|
||||
uint crit = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, critOff)));
|
||||
if (damage == 0 || damage > 1_000_000)
|
||||
|
|
@ -779,7 +804,7 @@ internal static class SmartBoxHooks
|
|||
}
|
||||
|
||||
PluginManager.QueueCombatDamage(damage, damageType, crit != 0, attacker);
|
||||
ImGuiBackend.Hud.HudFeed.OnDamageEvent(attacker, attacker ? ReadString16Latin1(payloadPtr, nameOff, info.BlobSize) : null, damage, crit != 0);
|
||||
ImGuiBackend.Hud.HudFeed.OnDamageEvent(attacker, attacker ? ReadString16Latin1(payloadPtr, nameOff, info.BlobSize) : null, damage, crit != 0, attacker ? share : 0);
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
|
|
|||
146
src/RynthCore.Engine/Compatibility/WorldTransitionState.cs
Normal file
146
src/RynthCore.Engine/Compatibility/WorldTransitionState.cs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Compatibility/WorldTransitionState.cs
|
||||
//
|
||||
// Is the player in a world transition: dead, in portal space (teleporting), or
|
||||
// within SettleMs after either, or after a landblock JUMP (a teleport, not walking
|
||||
// into the next landblock)? AC is then tearing objects down and loading new ones,
|
||||
// and nothing the engine queued for the main thread may run against it.
|
||||
//
|
||||
// Seen in a real crash: a client died right after a death recall's landblock
|
||||
// jump (0x00AE -> 0xA9B4), under GameTickHooks.UseTimeDetour, which runs queued casts
|
||||
// before AC's tick; a queued SetAutoRun(off) had run 1047 ms late a moment before.
|
||||
// The engine's own queued work runs inside those ticks, so it is the first
|
||||
// suspect.
|
||||
//
|
||||
// Gate rule for queued game-mutating work (AcMainThreadQueue, at its drains):
|
||||
// - while in transition, everything is HELD: nothing queued runs;
|
||||
// - once it ends, work queued at or before the last moment a drain saw the
|
||||
// transition is DROPPED (casts, selects, uses, moves, appraisals: the plugins
|
||||
// re-send what they still want), EXCEPT teardown work: stops and cancels (autorun
|
||||
// off, a motion off, StopMovement, StopCompletely, CancelAttack, a container close),
|
||||
// which still run, in queue order, as one group. A dropped stop can leave the
|
||||
// character running or turning, and AcMainThreadQueue never drops stops.
|
||||
//
|
||||
// Walking across a landblock boundary is not a transition: it happens constantly in a
|
||||
// fight, AC streams the neighbour in without tearing the player's world down, and a 5 s
|
||||
// hold there would stall every border fight.
|
||||
//
|
||||
// Pure: AC main thread only (single writer and reader: the UseTime sample and both
|
||||
// main-thread drains). Compiled into tools\EngineRobustnessTests.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
internal sealed class WorldTransitionState
|
||||
{
|
||||
public const long SettleMs = 5_000;
|
||||
|
||||
[Flags]
|
||||
public enum Edge
|
||||
{
|
||||
None = 0,
|
||||
Died = 1,
|
||||
Revived = 2,
|
||||
PortalEntered = 4,
|
||||
PortalExited = 8,
|
||||
LandblockJump = 16,
|
||||
}
|
||||
|
||||
private bool _init;
|
||||
public bool Dead { get; private set; }
|
||||
public bool Portaling { get; private set; }
|
||||
public uint Landblock { get; private set; }
|
||||
public uint PreviousLandblock { get; private set; }
|
||||
/// <summary>The settle window runs until this TickCount64.</summary>
|
||||
public long SettleUntilMs { get; private set; }
|
||||
/// <summary>Last time a gate check saw the transition (0 = never).</summary>
|
||||
public long LastBlockedMs { get; private set; }
|
||||
|
||||
/// <summary>One game-tick sample. Returns the edges crossed (for the lifecycle log).</summary>
|
||||
public Edge Sample(long nowMs, bool dead, bool portaling, uint landblock)
|
||||
{
|
||||
if (!_init)
|
||||
{
|
||||
_init = true;
|
||||
Dead = dead;
|
||||
Portaling = portaling;
|
||||
Landblock = landblock;
|
||||
if (dead || portaling) SettleUntilMs = nowMs + SettleMs;
|
||||
return Edge.None;
|
||||
}
|
||||
|
||||
Edge edges = Edge.None;
|
||||
if (dead || portaling || Dead || Portaling)
|
||||
SettleUntilMs = nowMs + SettleMs;
|
||||
if (dead != Dead) { edges |= dead ? Edge.Died : Edge.Revived; Dead = dead; }
|
||||
if (portaling != Portaling) { edges |= portaling ? Edge.PortalEntered : Edge.PortalExited; Portaling = portaling; }
|
||||
|
||||
if (landblock != 0 && Landblock != 0 && landblock != Landblock)
|
||||
{
|
||||
if (IsJump(Landblock, landblock))
|
||||
{
|
||||
edges |= Edge.LandblockJump;
|
||||
SettleUntilMs = Math.Max(SettleUntilMs, nowMs + SettleMs);
|
||||
}
|
||||
}
|
||||
if (landblock != 0 && landblock != Landblock)
|
||||
{
|
||||
PreviousLandblock = Landblock;
|
||||
Landblock = landblock;
|
||||
}
|
||||
return edges;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The server's PlayerTeleport message (0xF751) arrived: a teleport begins now, whether or not
|
||||
/// a tick sample ever sees teleport_in_progress or a landblock jump (a recall into the next
|
||||
/// landblock shows neither). Starts (or extends) the settle window. Returns false when the
|
||||
/// window was already running past it.
|
||||
/// </summary>
|
||||
public bool OnTeleportMessage(long nowMs)
|
||||
{
|
||||
long until = nowMs + SettleMs;
|
||||
if (until <= SettleUntilMs) return false;
|
||||
SettleUntilMs = until;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Two landblocks more than one apart on either axis: a teleport, not a walk.</summary>
|
||||
public static bool IsJump(uint from, uint to)
|
||||
{
|
||||
int dx = (int)((to >> 8) & 0xFF) - (int)((from >> 8) & 0xFF);
|
||||
int dy = (int)(to & 0xFF) - (int)(from & 0xFF);
|
||||
return Math.Abs(dx) > 1 || Math.Abs(dy) > 1;
|
||||
}
|
||||
|
||||
/// <summary>Dead, portaling, or inside the settle window.</summary>
|
||||
public bool InTransition(long nowMs) => Dead || Portaling || nowMs < SettleUntilMs;
|
||||
|
||||
public enum Verdict { Run, Hold, Drop }
|
||||
|
||||
/// <summary>
|
||||
/// A drain's check for the head of a queue: true = hold everything queued now. Records the
|
||||
/// moment, so work queued up to here is judged by <see cref="Decide"/> once it ends.
|
||||
/// </summary>
|
||||
public bool CheckHolding(long nowMs)
|
||||
{
|
||||
if (!InTransition(nowMs)) return false;
|
||||
LastBlockedMs = nowMs;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a drain does with one queued item: Hold while in transition; afterwards Drop it
|
||||
/// if it was queued during the transition (at or before the last held drain) unless it is
|
||||
/// <paramref name="teardown"/> work, which Runs; anything queued after the transition Runs.
|
||||
/// </summary>
|
||||
public Verdict Decide(long nowMs, long queuedAtMs, bool teardown)
|
||||
{
|
||||
if (CheckHolding(nowMs)) return Verdict.Hold;
|
||||
if (LastBlockedMs != 0 && queuedAtMs <= LastBlockedMs)
|
||||
return teardown ? Verdict.Run : Verdict.Drop;
|
||||
return Verdict.Run;
|
||||
}
|
||||
}
|
||||
|
|
@ -6,6 +6,12 @@
|
|||
// always-on procdump (which also dumped on every clean exit and every handled
|
||||
// first-chance AV, so a .dmp's existence never meant a real crash).
|
||||
//
|
||||
// Also writes ONE full-memory dump when AC shows its OUT OF MEMORY box
|
||||
// (MessageBoxHooks): that box is modal, so the process never crashes and Windows
|
||||
// never writes a dump; the launcher later kills the client as wedged
|
||||
// (AutoRestartWedgedClients, kept as it is). The hang dump is a small type and
|
||||
// holds no heap, which is what an out-of-memory needs.
|
||||
//
|
||||
// Safe to call from a background thread: MiniDumpWriteDump suspends all other
|
||||
// threads internally while it snapshots them, which is exactly what we want for
|
||||
// a hang. The dbghelp.dll P/Invoke is lazy-bound (no cost unless we ever fire).
|
||||
|
|
@ -14,6 +20,7 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine;
|
||||
|
||||
|
|
@ -46,6 +53,14 @@ internal static class CrashDump
|
|||
private const uint DumpTypePreferred = 0x00000000 | 0x00000004; // Normal + WithHandleData
|
||||
private const uint DumpTypeFallback = 0x00000000; // Normal only (universally supported)
|
||||
|
||||
// MiniDumpWithFullMemory (0x2) is as old as MiniDumpNormal, so dbghelp 6.1 takes it.
|
||||
private const uint DumpTypeFull = 0x00000002 | 0x00000004; // FullMemory + WithHandleData
|
||||
private const uint DumpTypeFullFallback = 0x00000002; // FullMemory only
|
||||
|
||||
// dbghelp is single-threaded: every MiniDumpWriteDump in this process goes through this
|
||||
// lock, so the hang watchdog's small dump can never run alongside the OOM full dump.
|
||||
private static readonly object DumpLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Write a minidump of the current process to Logs\dumps\. Best-effort;
|
||||
/// never throws. Returns true on success and sets <paramref name="dumpPath"/>.
|
||||
|
|
@ -60,40 +75,7 @@ internal static class CrashDump
|
|||
|
||||
string stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
|
||||
dumpPath = Path.Combine(dir, $"{prefix}_{Environment.ProcessId}_{stamp}.dmp");
|
||||
|
||||
using var fs = new FileStream(dumpPath, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||
bool ok = MiniDumpWriteDump(
|
||||
GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
|
||||
DumpTypePreferred, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
|
||||
int err = ok ? 0 : Marshal.GetLastWin32Error();
|
||||
|
||||
// ERROR_INVALID_PARAMETER (87) ⇒ AC's ancient dbghelp 6.1 rejected a flag.
|
||||
// Retry with bare MiniDumpNormal (universally supported, still has every
|
||||
// thread stack — what we need to read the deadlock's lock holder).
|
||||
if (!ok && err == 87)
|
||||
{
|
||||
fs.SetLength(0);
|
||||
ok = MiniDumpWriteDump(
|
||||
GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
|
||||
DumpTypeFallback, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
|
||||
err = ok ? 0 : Marshal.GetLastWin32Error();
|
||||
if (ok) RynthLog.Error($"CrashDump: rich flags rejected by AC's old dbghelp 6.1 — wrote bare Normal dump, reason={reason}");
|
||||
}
|
||||
|
||||
if (!ok)
|
||||
{
|
||||
RynthLog.Error($"CrashDump: MiniDumpWriteDump failed err={err} reason={reason}");
|
||||
// Don't leave a 0-byte .dmp behind — it reads as a crash marker
|
||||
// during triage (observed: hang_17692_20260611_114430.dmp, 0
|
||||
// bytes, main thread suspended mid-exception-dispatch).
|
||||
try { fs.Close(); File.Delete(dumpPath); } catch { }
|
||||
return false;
|
||||
}
|
||||
|
||||
long size = 0;
|
||||
try { size = new FileInfo(dumpPath).Length; } catch { }
|
||||
RynthLog.Error($"CrashDump: wrote {dumpPath} ({size / 1024}KB) reason={reason}");
|
||||
return true;
|
||||
return WriteDumpFile(dumpPath, DumpTypePreferred, DumpTypeFallback, reason);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -101,4 +83,215 @@ internal static class CrashDump
|
|||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Writes one dump to <paramref name="path"/>. On ERROR_INVALID_PARAMETER (87: AC's ancient
|
||||
// dbghelp 6.1 rejected a flag) retries with <paramref name="fallbackType"/>. Never leaves a
|
||||
// 0-byte or partial .dmp behind (it reads as a crash marker during triage; observed:
|
||||
// hang_17692_20260611_114430.dmp, 0 bytes, main thread suspended mid-exception-dispatch).
|
||||
private static bool WriteDumpFile(string path, uint type, uint fallbackType, string reason)
|
||||
{
|
||||
lock (DumpLock)
|
||||
{
|
||||
bool ok;
|
||||
int err;
|
||||
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
|
||||
type, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
|
||||
err = ok ? 0 : Marshal.GetLastWin32Error();
|
||||
if (!ok && err == 87 && fallbackType != type)
|
||||
{
|
||||
fs.SetLength(0);
|
||||
ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
|
||||
fallbackType, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
|
||||
err = ok ? 0 : Marshal.GetLastWin32Error();
|
||||
if (ok) RynthLog.Error($"CrashDump: flags 0x{type:X} rejected by AC's old dbghelp 6.1 - wrote type 0x{fallbackType:X}, reason={reason}");
|
||||
}
|
||||
}
|
||||
|
||||
if (!ok)
|
||||
{
|
||||
RynthLog.Error($"CrashDump: MiniDumpWriteDump failed err={err} type=0x{type:X} reason={reason}");
|
||||
try { File.Delete(path); } catch { }
|
||||
return false;
|
||||
}
|
||||
|
||||
long size = 0;
|
||||
try { size = new FileInfo(path).Length; } catch { }
|
||||
RynthLog.Error($"CrashDump: wrote {path} ({size / 1024}KB) reason={reason}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// -- OUT OF MEMORY full-memory dump --------------------------------------
|
||||
|
||||
/// <summary>Full dumps kept in the Dumps folder (a full dump is about the size of the process).</summary>
|
||||
internal const int OutOfMemoryDumpsKept = 3;
|
||||
internal const string OutOfMemoryDumpPrefix = "acclient_oom_";
|
||||
|
||||
// Longest the showing thread waits for the dump writer before letting the box open anyway.
|
||||
private const int FullDumpWaitMs = 300_000;
|
||||
|
||||
private static int _oomDumpLatch;
|
||||
private static volatile bool _fullDumpInProgress;
|
||||
private static volatile string? _fullDumpWrittenPath;
|
||||
|
||||
/// <summary>True while the OUT OF MEMORY full dump is being written (the watchdog holds off).</summary>
|
||||
internal static bool FullDumpInProgress => _fullDumpInProgress;
|
||||
|
||||
/// <summary>The OUT OF MEMORY full dump written this session, or null.</summary>
|
||||
internal static string? FullDumpWrittenPath => _fullDumpWrittenPath;
|
||||
|
||||
/// <summary>C:\Games\RynthCore\Dumps by default (beside Logs, under the install folder).</summary>
|
||||
internal static string OutOfMemoryDumpDirectory => Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "Dumps");
|
||||
|
||||
/// <summary>
|
||||
/// Once per process: write a full-memory dump to <see cref="OutOfMemoryDumpDirectory"/>, log
|
||||
/// its path, and keep only the newest <see cref="OutOfMemoryDumpsKept"/> of these dumps.
|
||||
/// Called on the thread about to show AC's OUT OF MEMORY box, which waits here until the
|
||||
/// dump is written (on its own thread, so the showing thread's stack is captured at rest).
|
||||
/// Never throws.
|
||||
/// </summary>
|
||||
internal static void WriteOutOfMemoryDumpOnce(string? reason)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _oomDumpLatch, 1) != 0) return;
|
||||
string why = "AC OUT OF MEMORY box: " + (reason ?? "?");
|
||||
_fullDumpInProgress = true;
|
||||
// The launcher reads this marker (DumpInProgressRule): MiniDumpWriteDump suspends every
|
||||
// thread, so the log goes silent for the whole dump, which would otherwise read as a dead
|
||||
// engine and get the client killed mid-dump.
|
||||
try { RynthLog.Error($"{DumpMarkerStarted} pid={Environment.ProcessId} - AC OUT OF MEMORY box; writing one full-memory dump before it shows."); }
|
||||
catch { }
|
||||
Thread? writer = null;
|
||||
try
|
||||
{
|
||||
writer = new Thread(() =>
|
||||
{
|
||||
// The flag stays up until the writer itself is done, even past a timed-out Join.
|
||||
try { WriteOutOfMemoryDumpCore(why); }
|
||||
finally { FinishFullDump(); }
|
||||
}) { IsBackground = true, Name = "RynthCore.OomDump" };
|
||||
writer.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// No thread to be had (out of memory, after all): write it from this one.
|
||||
try { RynthLog.Error($"CrashDump: dump thread failed to start ({ex.GetType().Name}) - writing on the calling thread."); } catch { }
|
||||
writer = null;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (writer == null)
|
||||
{
|
||||
try { WriteOutOfMemoryDumpCore(why); }
|
||||
finally { FinishFullDump(); }
|
||||
}
|
||||
else if (!writer.Join(FullDumpWaitMs))
|
||||
{
|
||||
RynthLog.Error($"CrashDump: full dump still writing after {FullDumpWaitMs / 1000}s - letting the box open (the writer keeps going).");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.Error($"CrashDump: OOM dump failed {ex.GetType().Name}: {ex.Message}"); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Log line written before the OUT OF MEMORY full dump starts (read by the launcher).</summary>
|
||||
internal const string DumpMarkerStarted = RynthCore.Install.DumpInProgressRule.MarkerStarted;
|
||||
/// <summary>Log line written once the writer has finished, whatever the outcome.</summary>
|
||||
internal const string DumpMarkerEnded = RynthCore.Install.DumpInProgressRule.MarkerEnded;
|
||||
|
||||
private static void FinishFullDump()
|
||||
{
|
||||
_fullDumpInProgress = false;
|
||||
try { RynthLog.Error($"{DumpMarkerEnded} pid={Environment.ProcessId}."); } catch { }
|
||||
}
|
||||
|
||||
private static void WriteOutOfMemoryDumpCore(string reason)
|
||||
{
|
||||
try
|
||||
{
|
||||
string dir = OutOfMemoryDumpDirectory;
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
string path = Path.Combine(dir, $"{OutOfMemoryDumpPrefix}{Environment.ProcessId}_{DateTime.Now:yyyyMMdd_HHmmss}.dmp");
|
||||
if (WriteDumpFile(path, DumpTypeFull, DumpTypeFullFallback, reason))
|
||||
{
|
||||
_fullDumpWrittenPath = path;
|
||||
RynthLog.Error($"CrashDump: OUT OF MEMORY full-memory dump: {path}");
|
||||
// Only after the new dump succeeded: a failed write never costs an older one.
|
||||
PruneDumps(dir, OutOfMemoryDumpPrefix, OutOfMemoryDumpsKept);
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.Error("CrashDump: OUT OF MEMORY full-memory dump FAILED; writing the small hang-type dump instead.");
|
||||
WriteSelfDump(reason, out _, "oom-small");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Error($"CrashDump: OOM dump writer failed {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes all but the newest <paramref name="keep"/> <paramref name="prefix"/>*.dmp files in
|
||||
/// <paramref name="dir"/>. The folder is shared by every client: a dump whose name carries
|
||||
/// the pid of ANOTHER process that is still running is never deleted (it may still be
|
||||
/// writing it, or about to report it), and is not counted against <paramref name="keep"/>.
|
||||
/// Never throws.
|
||||
/// </summary>
|
||||
internal static int PruneDumps(string dir, string prefix, int keep)
|
||||
{
|
||||
int deleted = 0;
|
||||
try
|
||||
{
|
||||
FileInfo[] files = new DirectoryInfo(dir).GetFiles(prefix + "*.dmp");
|
||||
Array.Sort(files, (a, b) => b.LastWriteTimeUtc.CompareTo(a.LastWriteTimeUtc));
|
||||
int kept = 0;
|
||||
int self = Environment.ProcessId;
|
||||
foreach (FileInfo f in files)
|
||||
{
|
||||
int pid = DumpPid(f.Name, prefix);
|
||||
if (pid > 0 && pid != self && IsProcessAlive(pid))
|
||||
continue; // another live client's dump: not ours to delete
|
||||
if (kept < Math.Max(0, keep)) { kept++; continue; }
|
||||
string name = f.Name;
|
||||
long length = 0;
|
||||
try { length = f.Length; } catch { }
|
||||
try
|
||||
{
|
||||
f.Delete();
|
||||
deleted++;
|
||||
RynthLog.Info($"CrashDump: pruned old dump {name} ({length / (1024 * 1024)}MB).");
|
||||
}
|
||||
catch { /* in use by a debugger, or already gone */ }
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return deleted;
|
||||
}
|
||||
|
||||
/// <summary>The pid in "prefix<pid>_...dmp", or 0.</summary>
|
||||
internal static int DumpPid(string fileName, string prefix)
|
||||
{
|
||||
if (!fileName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return 0;
|
||||
int start = prefix.Length, end = start;
|
||||
while (end < fileName.Length && char.IsDigit(fileName[end])) end++;
|
||||
return end > start && int.TryParse(fileName.AsSpan(start, end - start), out int pid) ? pid : 0;
|
||||
}
|
||||
|
||||
private static bool IsProcessAlive(int pid)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var p = System.Diagnostics.Process.GetProcessById(pid);
|
||||
return !p.HasExited;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -458,6 +458,11 @@ internal static class EndSceneHook
|
|||
if (_uiFrameCount < 30)
|
||||
RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}");
|
||||
}
|
||||
|
||||
// ImGui draw data (in-client panels, plugin overlay windows such as the ILT Hub)
|
||||
// is submitted LAST so it sits on top of the Avalonia layer. Built in OnEndScene;
|
||||
// guarded internally, so an ImGui draw failure can't skip the original EndScene.
|
||||
EngineFrameController.RenderDeferredImGui();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -164,11 +164,13 @@ internal static class EngineLifecycle
|
|||
// → AC chat box stops receiving input after a reload). Idempotent —
|
||||
// no-ops if Init never ran or the ImGui path already tore it down.
|
||||
Step("Win32Backend.Shutdown (input subclass)", () => ImGuiBackend.Win32Backend.Shutdown());
|
||||
Step("HotkeyService.Shutdown", () => Hotkeys.HotkeyService.Shutdown());
|
||||
|
||||
// Stop the dispatch-file watcher and the auto-ID drain timer before the
|
||||
// tick pump and plugins go away — both otherwise keep firing in the old
|
||||
// generation's (intentionally still-mapped) module across hot-reloads.
|
||||
Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop());
|
||||
Step("LogSettings.StopWatcher", () => LogSettings.StopWatcher());
|
||||
Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop());
|
||||
|
||||
// Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary.
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ using System.Runtime.InteropServices;
|
|||
using System.Threading;
|
||||
using System.Collections.Generic;
|
||||
using ImGuiNET;
|
||||
using RynthCore;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.D3D9;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
|
@ -45,7 +46,21 @@ public static class EntryPoint
|
|||
private static readonly Queue<string> RecentLogLines = new();
|
||||
private static long _recentLogSeq;
|
||||
|
||||
/// <summary>Set true to enable verbose startup logging (hook ready messages, plugin lifecycle, etc.).</summary>
|
||||
internal enum EngineLogLevel
|
||||
{
|
||||
/// <summary>As a global threshold: nothing but errors. As a category level: never written.</summary>
|
||||
Off = -1,
|
||||
Error = 0,
|
||||
Warning = 1,
|
||||
Info = 2,
|
||||
Debug = 3,
|
||||
Trace = 4
|
||||
}
|
||||
|
||||
/// <summary>Active engine logging threshold loaded from engine settings.</summary>
|
||||
internal static EngineLogLevel LoggingLevel = EngineLogLevel.Info;
|
||||
|
||||
/// <summary>Legacy convenience flag used by existing verbose call sites.</summary>
|
||||
internal static bool VerboseLogging = false;
|
||||
|
||||
/// <summary>Set by EngineFrameController once the game window is confirmed. Read by AvaloniaOverlay.</summary>
|
||||
|
|
@ -190,8 +205,14 @@ public static class EntryPoint
|
|||
}
|
||||
catch { }
|
||||
|
||||
// engine.json "LoggingLevel" + "LogCategories" (launcher Logging card) set the threshold
|
||||
// and per-category levels first so every line written below honours them. The watcher
|
||||
// started later re-reads them whenever the launcher edits the file.
|
||||
string logSummary = LogSettings.Reload();
|
||||
|
||||
// Set up the unified log sink BEFORE anything else so all
|
||||
// subsequent failures are captured in C:\Games\RynthCore\Logs.
|
||||
// subsequent failures are captured in <CoreDir>\Logs (installer-chosen;
|
||||
// resolved here on the init worker, never under the loader lock).
|
||||
LogPaths.EnsureLogDirectory();
|
||||
if (_initCount <= 1)
|
||||
{
|
||||
|
|
@ -206,10 +227,18 @@ public static class EntryPoint
|
|||
|
||||
InstallManagedExceptionHandlers();
|
||||
|
||||
RynthLog.Info("================================================================");
|
||||
RynthLog.Info($"RynthCore.Engine init build={BuildStamp} initCount={_initCount} pid={Environment.ProcessId}");
|
||||
RynthLog.Info($" os={Environment.OSVersion} clr={Environment.Version} cwd={Environment.CurrentDirectory}");
|
||||
RynthLog.Info("================================================================");
|
||||
// The banner bypasses the category levels: it must be in every log, whatever engine.json says.
|
||||
LogTagged("engine", "================================================================", "INF");
|
||||
LogTagged("engine", $"RynthCore.Engine init build={BuildStamp} initCount={_initCount} pid={Environment.ProcessId}", "INF");
|
||||
LogTagged("engine", $" os={Environment.OSVersion} clr={Environment.Version} cwd={Environment.CurrentDirectory}", "INF");
|
||||
LogTagged("engine", $" logging {logSummary}", "INF");
|
||||
LogTagged("engine", "================================================================", "INF");
|
||||
string hiddenCategories = LogSettings.HiddenCategoriesWarning();
|
||||
if (hiddenCategories.Length > 0) RynthLog.Warn(hiddenCategories);
|
||||
|
||||
// Live logging config: launcher edits to engine.json apply without a client restart.
|
||||
// Stopped in EngineLifecycle.Shutdown before the module can be unloaded.
|
||||
LogSettings.StartWatcher();
|
||||
|
||||
CrashLogger.Install();
|
||||
|
||||
|
|
@ -217,18 +246,10 @@ public static class EntryPoint
|
|||
// logging AC's main-thread native stack when its EndScene beat stalls.
|
||||
MainThreadHangWatchdog.Start();
|
||||
|
||||
// MultiClientHooks.Initialize installs MinHook detours synchronously
|
||||
// here, BEFORE InitWorker spawns and runs the main PreloadNativeDll
|
||||
// pass. If we don't preload minhook.x86.dll first, the P/Invoke
|
||||
// into minhook fails with DllNotFoundException and the multi-
|
||||
// client hook silently skips — which means AC's
|
||||
// Client::IsAlreadyRunning check fires unpatched on the second-
|
||||
// and-later concurrent acclient.exe processes.
|
||||
string? earlyEngineDir = GetEngineDirectory();
|
||||
if (!string.IsNullOrEmpty(earlyEngineDir))
|
||||
PreloadNativeDll(earlyEngineDir, "minhook.x86.dll");
|
||||
else
|
||||
RynthLog.Info("Early-init: could not resolve engine directory — minhook may not be preloaded before MultiClientHooks.");
|
||||
// MultiClientHooks installs MinHook-based detours immediately. P/Invoke resolves
|
||||
// minhook.x86.dll before InitWorker runs, so preload it from the engine directory;
|
||||
// otherwise Client::IsAlreadyRunning fires unpatched on second-and-later clients.
|
||||
TryPreloadMinHookForEarlyInit();
|
||||
|
||||
RunInitStep("early multi-client hooks", MultiClientHooks.Initialize);
|
||||
// Before AC's main thread resumes, so no dat or network unpack runs the stock
|
||||
|
|
@ -339,6 +360,33 @@ public static class EntryPoint
|
|||
return new string(buffer, 0, (int)length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads MinHook on the RynthCoreInit thread so <see cref="MultiClientHooks.Initialize"/> can
|
||||
/// call <see cref="Hooking.MinHook"/> P/Invokes without relying on the default DLL search path
|
||||
/// (which often resolves against the AC client directory, not <c>Runtime\</c>).
|
||||
/// </summary>
|
||||
private static void TryPreloadMinHookForEarlyInit()
|
||||
{
|
||||
try
|
||||
{
|
||||
string? engineDir = GetEngineDirectory();
|
||||
if (string.IsNullOrEmpty(engineDir))
|
||||
{
|
||||
RynthLog.Info("Early MinHook preload skipped: could not resolve engine directory.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (PreloadNativeDll(engineDir, "minhook.x86.dll"))
|
||||
RynthLog.Verbose($"Early MinHook preload OK (engine dir: {engineDir})");
|
||||
else
|
||||
RynthLog.Info($"Early MinHook preload failed: minhook.x86.dll not found beside engine ({engineDir}).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Info($"Early MinHook preload exception: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// No-op anchor whose address is taken via `&EngineDirAnchor` to give us a
|
||||
/// stable pointer inside the engine's own module image — used by
|
||||
|
|
@ -518,6 +566,44 @@ public static class EntryPoint
|
|||
/// (RynthAi/RynthChat/RynthVision) on the user's launcher selection.
|
||||
/// Filename match (not full-path) so users can keep the DLL anywhere.
|
||||
/// </summary>
|
||||
private static bool _serverMenusRegistered;
|
||||
|
||||
/// <summary>
|
||||
/// The server sections of the Char and Mini Remote menus (UI.ServerMenus): each server once,
|
||||
/// then the items of the installed plugins that have windows for it. A server whose plugins
|
||||
/// are all missing gets no items, so its section never shows.
|
||||
/// </summary>
|
||||
private static void RegisterServerMenus(bool rynthAi, bool rynthIlt)
|
||||
{
|
||||
if (_serverMenusRegistered) return;
|
||||
_serverMenusRegistered = true;
|
||||
|
||||
// Infinite Leaftide: IltInfo (host / world name lists, or "/rc ilt on" for the session).
|
||||
UI.ServerMenus.DefineServer("ilt", "Infinite Leaftide", static () => IltInfo.IsIlt, "/rc ilt on");
|
||||
if (rynthAi)
|
||||
{
|
||||
// RynthAi's ILT features: the Mini Remote's ILT tabs (shown once the server reports each
|
||||
// on). Its Quests and Pets tabs are universal: the Character half of the menus.
|
||||
foreach ((string label, string tab) in new[]
|
||||
{
|
||||
("Character", "character"), ("Banking", "banking"), ("Gear", "gear"), ("Charms", "charms"), ("Games", "games"),
|
||||
})
|
||||
{
|
||||
UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem(label, "/rc miniremote tab " + tab,
|
||||
$"The Mini Remote's {label} tab (RynthAi).", "tab:" + tab));
|
||||
}
|
||||
UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem("Guardian", "/rc guardian toggle",
|
||||
"Temple of Enlightenment guardians: riddle answers and Give (RynthAi)."));
|
||||
}
|
||||
if (rynthIlt)
|
||||
UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem("Bounties", "/rc bounties toggle",
|
||||
"ACECustom bounties and your progress on each (RynthILT)."));
|
||||
if (rynthAi)
|
||||
UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem("Progression", "/rc progression",
|
||||
"XP planner, augmentations and enlightenment (the Skills panel's Progression tab)."));
|
||||
UI.ServerMenus.PushToRynthAi = rynthAi;
|
||||
}
|
||||
|
||||
private static bool HasPluginDll(string dllFileName)
|
||||
{
|
||||
var paths = Plugins.EngineSettings.PluginPaths;
|
||||
|
|
@ -695,6 +781,8 @@ public static class EntryPoint
|
|||
Step("account hooks", AccountHooks.Initialize);
|
||||
Step("client combat hooks", () => ClientCombatHooks.Probe());
|
||||
Step("selected-target hooks", SelectedTargetHooks.Initialize);
|
||||
// Which item AC is dragging (AC keeps the old selection during a drag).
|
||||
Step("drag-start hook", DragDropHooks.Initialize);
|
||||
Step("smartbox hooks", SmartBoxHooks.Initialize);
|
||||
Step("player vitals hooks", PlayerVitalsHooks.Initialize);
|
||||
Step("enchantment hooks", () => EnchantmentHooks.Initialize());
|
||||
|
|
@ -993,10 +1081,16 @@ public static class EntryPoint
|
|||
ImGuiBackend.Panels.VisionFace.Register();
|
||||
if (HasPluginDll("RynthCore.Plugin.RynthNav.dll"))
|
||||
ImGuiBackend.Panels.RynthNavFace.Register();
|
||||
// The ILT section (Infinite Leaftide): its faces exist only with RynthILT
|
||||
// installed, and the bar's ILT button shows them only on ILT (IltInfo).
|
||||
// Characters (your other RynthCore clients, through RynthNet): only with RynthNet installed.
|
||||
if (HasPluginDll("RynthCore.Plugin.RynthNet.dll"))
|
||||
ImGuiBackend.Panels.CharactersFace.Register();
|
||||
// The ILT section (Infinite Leaftide): each face exists only with its plugin
|
||||
// installed (Bounties: RynthILT, Guardian: RynthAi), and the bar's ILT button
|
||||
// shows them only on ILT (IltInfo).
|
||||
if (HasPluginDll("RynthCore.Plugin.RynthILT.dll"))
|
||||
ImGuiBackend.Panels.BountiesFace.Register();
|
||||
if (HasPluginDll("RynthCore.Plugin.RynthAi.dll"))
|
||||
ImGuiBackend.Panels.GuardianFace.Register();
|
||||
if (HasPluginDll("RynthCore.Plugin.RynthChat.dll"))
|
||||
{
|
||||
ImGuiBackend.Panels.ChatFace.Register();
|
||||
|
|
@ -1021,6 +1115,7 @@ public static class EntryPoint
|
|||
// RynthAiPanel: see the dispatcher invariant above ChatModel.EnsureSettingsLoaded.
|
||||
RynthAiDashboardState.EnsureLoaded();
|
||||
}
|
||||
RegisterServerMenus(HasPluginDll("RynthCore.Plugin.RynthAi.dll"), HasPluginDll("RynthCore.Plugin.RynthILT.dll"));
|
||||
if (trackerPresent)
|
||||
TrackerSettings.EnsureLoaded();
|
||||
// Hide the docked Avalonia bar before it is built if the ImGui bar stands in.
|
||||
|
|
@ -1686,10 +1781,34 @@ public static class EntryPoint
|
|||
|
||||
internal static void LogVerbose(string message)
|
||||
{
|
||||
if (VerboseLogging)
|
||||
if (ShouldLog(EngineLogLevel.Debug))
|
||||
Log(message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when a line at <paramref name="level"/> passes the global threshold. Off-level lines
|
||||
/// never pass; an Off threshold blocks everything (errors bypass this gate).
|
||||
/// </summary>
|
||||
internal static bool ShouldLog(EngineLogLevel level)
|
||||
=> level != EngineLogLevel.Off && level <= LoggingLevel;
|
||||
|
||||
/// <summary>Parses the global level: Off, Error, Warning/Warn, Info, Debug/Verbose, Trace. Unknown → Info.</summary>
|
||||
internal static EngineLogLevel ParseLoggingLevel(string? configuredLevel)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(configuredLevel))
|
||||
return EngineLogLevel.Info;
|
||||
|
||||
string normalized = configuredLevel.Trim();
|
||||
if (string.Equals(normalized, "Verbose", StringComparison.OrdinalIgnoreCase))
|
||||
return EngineLogLevel.Debug;
|
||||
if (string.Equals(normalized, "Warn", StringComparison.OrdinalIgnoreCase))
|
||||
return EngineLogLevel.Warning;
|
||||
|
||||
return Enum.TryParse(normalized, ignoreCase: true, out EngineLogLevel parsed) && Enum.IsDefined(parsed)
|
||||
? parsed
|
||||
: EngineLogLevel.Info;
|
||||
}
|
||||
|
||||
internal static string[] GetRecentLogLines()
|
||||
{
|
||||
lock (LogLock)
|
||||
|
|
|
|||
709
src/RynthCore.Engine/Hotkeys/HotkeyModel.cs
Normal file
709
src/RynthCore.Engine/Hotkeys/HotkeyModel.cs
Normal file
|
|
@ -0,0 +1,709 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Hotkeys/HotkeyModel.cs
|
||||
//
|
||||
// User hotkeys (Settings > Hotkeys, /rc hotkey): a key with Ctrl/Alt/Shift runs
|
||||
// a built-in action (start/stop the macro, toggle Combat, open a panel...) or any
|
||||
// chat command ("/ra start", "/rn bc /ra stop", "/lua myscript go").
|
||||
//
|
||||
// This file is the pure part, with no engine dependencies, so tools/HotkeyTests
|
||||
// compiles it as is: key names and combo parsing/formatting, the built-in action
|
||||
// list, matching a key press against the bindings (exact modifiers, key-down edge
|
||||
// only), the "is the player typing" rule, conflict warnings, the /rc hotkey
|
||||
// argument parser and the per-PC file (%LOCALAPPDATA%\RynthCore\hotkeys.txt).
|
||||
// The engine side (key messages, running actions, the Settings section) is
|
||||
// Hotkeys/HotkeyService.cs and ImGui/Panels/HotkeysSettingsUi.cs.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Engine.Hotkeys;
|
||||
|
||||
[Flags]
|
||||
internal enum HotkeyMods
|
||||
{
|
||||
None = 0,
|
||||
Ctrl = 1,
|
||||
Alt = 2,
|
||||
Shift = 4,
|
||||
}
|
||||
|
||||
/// <summary>A key (Win32 virtual-key code) and the modifiers held with it.</summary>
|
||||
internal readonly record struct KeyCombo(int Vk, HotkeyMods Mods)
|
||||
{
|
||||
public bool IsEmpty => Vk == 0;
|
||||
public override string ToString() => HotkeyKeys.Format(this);
|
||||
}
|
||||
|
||||
/// <summary>Key names, and combo text ("Ctrl+Shift+F1") both ways.</summary>
|
||||
internal static class HotkeyKeys
|
||||
{
|
||||
public const int VK_BACK = 0x08, VK_TAB = 0x09, VK_RETURN = 0x0D, VK_SHIFT = 0x10, VK_CONTROL = 0x11,
|
||||
VK_MENU = 0x12, VK_PAUSE = 0x13, VK_ESCAPE = 0x1B, VK_SPACE = 0x20, VK_PRIOR = 0x21, VK_NEXT = 0x22,
|
||||
VK_END = 0x23, VK_HOME = 0x24, VK_LEFT = 0x25, VK_UP = 0x26, VK_RIGHT = 0x27, VK_DOWN = 0x28,
|
||||
VK_INSERT = 0x2D, VK_DELETE = 0x2E, VK_LWIN = 0x5B, VK_RWIN = 0x5C, VK_APPS = 0x5D,
|
||||
VK_NUMPAD0 = 0x60, VK_MULTIPLY = 0x6A, VK_ADD = 0x6B, VK_SUBTRACT = 0x6D, VK_DECIMAL = 0x6E,
|
||||
VK_DIVIDE = 0x6F, VK_F1 = 0x70, VK_F12 = 0x7B, VK_F24 = 0x87, VK_SCROLL = 0x91,
|
||||
VK_LSHIFT = 0xA0, VK_RSHIFT = 0xA1, VK_LCONTROL = 0xA2, VK_RCONTROL = 0xA3, VK_LMENU = 0xA4, VK_RMENU = 0xA5,
|
||||
VK_OEM_3 = 0xC0;
|
||||
|
||||
private static readonly Dictionary<int, string> NameByVk = BuildNames();
|
||||
private static readonly Dictionary<string, int> VkByName = BuildLookup();
|
||||
|
||||
private static Dictionary<int, string> BuildNames()
|
||||
{
|
||||
var n = new Dictionary<int, string>();
|
||||
for (int c = 'A'; c <= 'Z'; c++) n[c] = ((char)c).ToString();
|
||||
for (int c = '0'; c <= '9'; c++) n[c] = ((char)c).ToString();
|
||||
for (int i = 0; i < 24; i++) n[VK_F1 + i] = "F" + (i + 1);
|
||||
for (int i = 0; i < 10; i++) n[VK_NUMPAD0 + i] = "Num" + i;
|
||||
n[VK_MULTIPLY] = "Num*"; n[VK_ADD] = "Num+"; n[VK_SUBTRACT] = "Num-"; n[VK_DECIMAL] = "Num."; n[VK_DIVIDE] = "Num/";
|
||||
n[VK_BACK] = "Backspace"; n[VK_TAB] = "Tab"; n[VK_RETURN] = "Enter"; n[VK_PAUSE] = "Pause";
|
||||
n[VK_ESCAPE] = "Esc"; n[VK_SPACE] = "Space";
|
||||
n[VK_PRIOR] = "PageUp"; n[VK_NEXT] = "PageDown"; n[VK_END] = "End"; n[VK_HOME] = "Home";
|
||||
n[VK_LEFT] = "Left"; n[VK_UP] = "Up"; n[VK_RIGHT] = "Right"; n[VK_DOWN] = "Down";
|
||||
n[VK_INSERT] = "Insert"; n[VK_DELETE] = "Delete"; n[VK_SCROLL] = "ScrollLock";
|
||||
// US-layout punctuation (the OEM keys keep their codes on other layouts; the name is the US one).
|
||||
n[0xBA] = ";"; n[0xBB] = "="; n[0xBC] = ","; n[0xBD] = "-"; n[0xBE] = "."; n[0xBF] = "/";
|
||||
n[VK_OEM_3] = "`"; n[0xDB] = "["; n[0xDC] = "\\"; n[0xDD] = "]"; n[0xDE] = "'";
|
||||
return n;
|
||||
}
|
||||
|
||||
private static Dictionary<string, int> BuildLookup()
|
||||
{
|
||||
var d = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var kv in NameByVk) d[kv.Value] = kv.Key;
|
||||
void Alias(string name, int vk) => d[name] = vk;
|
||||
Alias("PgUp", VK_PRIOR); Alias("PgDn", VK_NEXT); Alias("PageDn", VK_NEXT);
|
||||
Alias("Ins", VK_INSERT); Alias("Del", VK_DELETE); Alias("Escape", VK_ESCAPE);
|
||||
Alias("Return", VK_RETURN); Alias("Spacebar", VK_SPACE); Alias("Back", VK_BACK);
|
||||
Alias("Plus", 0xBB); Alias("Equals", 0xBB); Alias("Minus", 0xBD); Alias("Comma", 0xBC);
|
||||
Alias("Period", 0xBE); Alias("Slash", 0xBF); Alias("Backslash", 0xDC); Alias("Semicolon", 0xBA);
|
||||
Alias("Quote", 0xDE); Alias("Apostrophe", 0xDE); Alias("Backtick", VK_OEM_3); Alias("Grave", VK_OEM_3);
|
||||
Alias("Tilde", VK_OEM_3); Alias("LBracket", 0xDB); Alias("RBracket", 0xDD);
|
||||
Alias("NumMultiply", VK_MULTIPLY); Alias("NumAdd", VK_ADD); Alias("NumPlus", VK_ADD);
|
||||
Alias("NumSubtract", VK_SUBTRACT); Alias("NumMinus", VK_SUBTRACT); Alias("NumDecimal", VK_DECIMAL);
|
||||
Alias("NumDivide", VK_DIVIDE); Alias("Scroll", VK_SCROLL);
|
||||
for (int i = 0; i < 10; i++) { Alias("Numpad" + i, VK_NUMPAD0 + i); Alias("Kp" + i, VK_NUMPAD0 + i); }
|
||||
return d;
|
||||
}
|
||||
|
||||
/// <summary>The key's name ("F1", "Num5", "PageUp", ";"), or "Key 0x.." for one without a name.</summary>
|
||||
public static string KeyName(int vk) => NameByVk.TryGetValue(vk, out string? n) ? n : $"Key 0x{vk:X2}";
|
||||
|
||||
/// <summary>Shift, Ctrl, Alt (either side) and the Windows keys: held with a key, never bound alone.</summary>
|
||||
public static bool IsModifierKey(int vk) =>
|
||||
vk is VK_SHIFT or VK_CONTROL or VK_MENU or VK_LSHIFT or VK_RSHIFT or VK_LCONTROL or VK_RCONTROL
|
||||
or VK_LMENU or VK_RMENU or VK_LWIN or VK_RWIN or VK_APPS;
|
||||
|
||||
/// <summary>A key a hotkey may use: any named key except Esc (it cancels and closes things).</summary>
|
||||
public static bool IsBindable(int vk) => vk != VK_ESCAPE && NameByVk.ContainsKey(vk);
|
||||
|
||||
public static bool IsFunctionKey(int vk) => vk >= VK_F1 && vk <= VK_F24;
|
||||
|
||||
public static string Format(KeyCombo c)
|
||||
{
|
||||
if (c.IsEmpty) return "(none)";
|
||||
var sb = new StringBuilder();
|
||||
if ((c.Mods & HotkeyMods.Ctrl) != 0) sb.Append("Ctrl+");
|
||||
if ((c.Mods & HotkeyMods.Alt) != 0) sb.Append("Alt+");
|
||||
if ((c.Mods & HotkeyMods.Shift) != 0) sb.Append("Shift+");
|
||||
sb.Append(KeyName(c.Vk));
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Ctrl+Shift+F1", "alt+num+", "Shift + PgDn" (spaces and case don't matter). Modifiers come
|
||||
/// first, each followed by '+'; what's left is the key's name.
|
||||
/// </summary>
|
||||
public static bool TryParse(string? text, out KeyCombo combo, out string error)
|
||||
{
|
||||
combo = default;
|
||||
error = string.Empty;
|
||||
string s = (text ?? string.Empty).Replace(" ", string.Empty).Replace("\t", string.Empty);
|
||||
if (s.Length == 0) { error = "No key given."; return false; }
|
||||
|
||||
HotkeyMods mods = HotkeyMods.None;
|
||||
while (true)
|
||||
{
|
||||
int plus = s.IndexOf('+');
|
||||
if (plus <= 0 || plus == s.Length - 1) break; // no modifier left ("+" alone or at the end is a key)
|
||||
HotkeyMods m = s[..plus].ToLowerInvariant() switch
|
||||
{
|
||||
"ctrl" or "control" or "ctl" => HotkeyMods.Ctrl,
|
||||
"alt" => HotkeyMods.Alt,
|
||||
"shift" => HotkeyMods.Shift,
|
||||
_ => HotkeyMods.None,
|
||||
};
|
||||
if (m == HotkeyMods.None) break;
|
||||
mods |= m;
|
||||
s = s[(plus + 1)..];
|
||||
}
|
||||
|
||||
if (s.ToLowerInvariant() is "ctrl" or "control" or "alt" or "shift")
|
||||
{
|
||||
error = "A modifier alone can't be a hotkey; add a key (e.g. Ctrl+F1).";
|
||||
return false;
|
||||
}
|
||||
if (!VkByName.TryGetValue(s, out int vk))
|
||||
{
|
||||
error = $"Unknown key '{s}'. Keys: A-Z, 0-9, F1-F24, Num0-Num9, Num* Num+ Num- Num. Num/, " +
|
||||
"Home End PageUp PageDown Insert Delete, Up Down Left Right, Space Tab Enter Backspace, ; = , - . / ` [ \\ ] '.";
|
||||
return false;
|
||||
}
|
||||
if (vk == VK_ESCAPE)
|
||||
{
|
||||
error = "Esc can't be a hotkey (it cancels and closes things).";
|
||||
return false;
|
||||
}
|
||||
combo = new KeyCombo(vk, mods);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A built-in action. <see cref="Panel"/>: the panel title it opens/closes, for panel actions.
|
||||
/// <see cref="Chat"/>: the chat command it runs ("/ra targetlock"); "{0}" is the binding's parameter
|
||||
/// (<see cref="HotkeyBinding.Command"/>), for an action with a <see cref="Param"/> (e.g. the meta state).
|
||||
/// <see cref="Group"/>: the dropdown section ("" = the RynthCore built-ins). <see cref="Tip"/>: a plain tooltip.
|
||||
/// </summary>
|
||||
internal sealed record HotkeyAction(string Id, string Name, string? Panel = null, string? Chat = null,
|
||||
string Group = "", string Tip = "", string? Param = null)
|
||||
{
|
||||
public bool HasParam => Param != null;
|
||||
}
|
||||
|
||||
internal static class HotkeyActions
|
||||
{
|
||||
/// <summary>The action id of a binding that runs <see cref="HotkeyBinding.Command"/> as a chat command.</summary>
|
||||
public const string Command = "command";
|
||||
public const string PanelPrefix = "panel:";
|
||||
public const string VTankPrefix = "vt:";
|
||||
public const string VTankGroup = "VTank-style";
|
||||
/// <summary>The parameterized "Meta: set state" action (its binding's Command is the state name).</summary>
|
||||
public const string MetaStateId = VTankPrefix + "metastate";
|
||||
|
||||
private static HotkeyAction V(string id, string name, string tip, string? chat = null, string? param = null) =>
|
||||
new(VTankPrefix + id, name, Chat: chat, Group: VTankGroup, Tip: tip, Param: param);
|
||||
|
||||
private static HotkeyAction P(string title, string? name = null) =>
|
||||
new(PanelPrefix + title, "Open/close " + (name ?? title), title);
|
||||
|
||||
/// <summary>Built-ins, in the order the Settings dropdown shows them.</summary>
|
||||
public static readonly HotkeyAction[] BuiltIns =
|
||||
{
|
||||
new("macro", "Start/stop the macro"),
|
||||
new("combat", "Toggle Combat"),
|
||||
new("buffing", "Toggle Buffing"),
|
||||
new("navigation", "Toggle Navigation"),
|
||||
new("looting", "Toggle Looting"),
|
||||
new("meta", "Toggle Meta"),
|
||||
new("forcerebuff", "Force rebuff"),
|
||||
new("patrol", "Start dungeon patrol"),
|
||||
new("autosort", "Toggle auto-sort (RynthSort)"),
|
||||
new("reload", "Reload the engine"),
|
||||
P("RynthAi", "the RynthAi dashboard"),
|
||||
P("Radar"),
|
||||
P("Dungeon Map"),
|
||||
P("Inventory"),
|
||||
P("Items"),
|
||||
P("Settings"),
|
||||
P("Characters"),
|
||||
P("Chat"),
|
||||
P("Meta", "the Meta editor"),
|
||||
P("Nav", "the Nav editor"),
|
||||
P("Lua"),
|
||||
P("Damage"),
|
||||
P("Mini Remote"),
|
||||
P("Skills"),
|
||||
P("Vision"),
|
||||
P("Sense"),
|
||||
P("Item Count"),
|
||||
P("Loot Editor"),
|
||||
P("RynthNav"),
|
||||
|
||||
// VTank's hotkey actions, by VTank's names. Those RynthCore already had run the same code
|
||||
// as the built-ins above; the rest run a RynthAi /ra command (also usable as a chat command).
|
||||
V("metastate", "Meta: set state...", "Switches the meta to the state you pick (/ra setmetastate <state>).",
|
||||
"/ra setmetastate {0}", param: "State"),
|
||||
V("startstop", "Start/Stop", "Starts or stops the macro."),
|
||||
V("targetlock", "Target lock", "Makes the macro attack the monster you have selected, ahead of everything else. " +
|
||||
"Press it again on the same monster to let go (/ra targetlock).", "/ra targetlock"),
|
||||
V("navigation", "Navigation", "Turns Navigation on or off."),
|
||||
V("looting", "Looting", "Turns Looting on or off."),
|
||||
V("combat", "Combat", "Turns Combat on or off."),
|
||||
V("buffing", "Buffing", "Turns Buffing on or off."),
|
||||
V("forcebuff", "Force buff", "Recasts every buff now, whatever time is left."),
|
||||
V("cancelforcebuff", "Cancel force buff", "Stops a force buff in progress."),
|
||||
V("meleelow", "MeleeLow", "Melee attacks go low (/ra meleelow).", "/ra meleelow"),
|
||||
V("meleemid", "MeleeMid", "Melee attacks go to the middle (/ra meleemid).", "/ra meleemid"),
|
||||
V("meleehigh", "MeleeHigh", "Melee attacks go high (/ra meleehigh).", "/ra meleehigh"),
|
||||
V("navaddpt", "NavAddPt", "Adds a waypoint where you stand to the loaded route (/ra navaddpt).", "/ra navaddpt"),
|
||||
V("testitem", "TestItem", "Checks the selected item against your loot profile and says what it would do (/ra testitem).", "/ra testitem"),
|
||||
V("propertydump", "PropertyDump", "Lists every property of the selected object in chat (/ra propertydump).", "/ra propertydump"),
|
||||
V("recharge", "Recharge", "One heal, stamina or mana top-off now, using your Top Off settings, " +
|
||||
"even with the macro stopped (/ra recharge).", "/ra recharge"),
|
||||
V("navprio", "NavPrio", "Turns Boost Nav Priority on or off (/ra navprio).", "/ra navprio"),
|
||||
V("lootprio", "LootPrio", "Turns Boost Loot Priority on or off (/ra lootprio).", "/ra lootprio"),
|
||||
V("navlootprio", "NavLootPrio", "Turns Boost Nav Priority and Boost Loot Priority on together, or both off " +
|
||||
"when both are on (/ra navlootprio).", "/ra navlootprio"),
|
||||
V("lootthiscont", "LootThisCont", "Loots the corpse or chest you have open now, even one the macro would skip. " +
|
||||
"Never house storage or your own packs (/ra lootthis).", "/ra lootthis"),
|
||||
};
|
||||
|
||||
/// <summary>The chat command a <see cref="HotkeyAction.Chat"/> action runs for this binding (its parameter filled in).</summary>
|
||||
public static string ChatFor(HotkeyAction a, HotkeyBinding b) =>
|
||||
a.Chat == null ? string.Empty : a.Chat.Replace("{0}", b.Command.Trim()).Trim();
|
||||
|
||||
private static string Norm(string s)
|
||||
{
|
||||
var sb = new StringBuilder(s.Length);
|
||||
foreach (char c in s)
|
||||
if (!char.IsWhiteSpace(c) && c != '-' && c != '_') sb.Append(char.ToLowerInvariant(c));
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>A built-in by id ("combat", "panel:Dungeon Map"), loosely ("panel dungeonmap", "dungeon map",
|
||||
/// "Toggle Combat"); null if none.</summary>
|
||||
public static HotkeyAction? Resolve(string? text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return null;
|
||||
string t = text.Trim();
|
||||
if (t.StartsWith("panel ", StringComparison.OrdinalIgnoreCase)) t = PanelPrefix + t[6..];
|
||||
string n = Norm(t);
|
||||
foreach (HotkeyAction a in BuiltIns)
|
||||
if (Norm(a.Id) == n || Norm(a.Name) == n) return a;
|
||||
foreach (HotkeyAction a in BuiltIns) // a panel's title alone
|
||||
if (a.Panel != null && Norm(a.Panel) == n) return a;
|
||||
foreach (HotkeyAction a in BuiltIns) // a VTank-style id without "vt:" ("startstop", "targetlock")
|
||||
if (a.Group == VTankGroup && Norm(a.Id) == VTankPrefix + n) return a;
|
||||
return null;
|
||||
}
|
||||
|
||||
public static HotkeyAction? Find(string id)
|
||||
{
|
||||
foreach (HotkeyAction a in BuiltIns)
|
||||
if (string.Equals(a.Id, id, StringComparison.OrdinalIgnoreCase)) return a;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>What the binding does, for lists ("Toggle Combat", "Chat: /ra start", "Meta: Hunting").</summary>
|
||||
public static string Describe(HotkeyBinding b)
|
||||
{
|
||||
if (string.Equals(b.Action, Command, StringComparison.OrdinalIgnoreCase))
|
||||
return b.Command.Length > 0 ? "Chat: " + b.Command : "Chat: (no command)";
|
||||
HotkeyAction? a = Find(b.Action);
|
||||
if (a == null) return $"Unknown action '{b.Action}'";
|
||||
string param = b.Command.Trim();
|
||||
if (string.Equals(a.Id, MetaStateId, StringComparison.OrdinalIgnoreCase))
|
||||
return param.Length > 0 ? "Meta: " + param : "Meta: (no state)";
|
||||
if (a.HasParam) return param.Length > 0 ? $"{a.Name} {param}" : $"{a.Name} (no {a.Param!.ToLowerInvariant()})";
|
||||
return a.Group.Length > 0 ? $"{a.Name} ({a.Group})" : a.Name;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An action that takes a parameter, and the text after it: "metastate Hunting" or "vt:metastate
|
||||
/// Hunting" -> (Meta: set state, "Hunting"). Null if the text doesn't start with one.
|
||||
/// </summary>
|
||||
public static (HotkeyAction Action, string Param)? ResolveWithParam(string? text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return null;
|
||||
string t = text.Trim();
|
||||
for (int sp = t.IndexOf(' '); sp > 0; sp = t.IndexOf(' ', sp + 1))
|
||||
{
|
||||
string head = t[..sp];
|
||||
if (Resolve(head) is { HasParam: true } a) return (a, t[(sp + 1)..].Trim());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One hotkey: the combo, a built-in action id or <see cref="HotkeyActions.Command"/>, and its chat command.</summary>
|
||||
internal sealed record HotkeyBinding(KeyCombo Combo, string Action, string Command = "", bool Enabled = true)
|
||||
{
|
||||
public bool IsCommand => string.Equals(Action, HotkeyActions.Command, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>Turning a key message into a combo and finding its binding.</summary>
|
||||
internal static class HotkeyMatch
|
||||
{
|
||||
/// <summary>
|
||||
/// WM_KEYDOWN / WM_SYSKEYDOWN lParam bit 30 is the key's previous state: set on auto-repeat.
|
||||
/// A hotkey fires on the first key-down only, never on repeats.
|
||||
/// </summary>
|
||||
public static bool IsFreshPress(long lParam) => (lParam & 0x40000000) == 0;
|
||||
|
||||
/// <summary>lParam bit 24: an extended key (numpad Enter, the arrow/navigation block).</summary>
|
||||
public static bool IsExtended(long lParam) => (lParam & 0x01000000) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// The virtual key a binding is matched on: left/right modifiers fold into Shift/Ctrl/Alt, and
|
||||
/// numpad Enter (extended Return) gives 0: AC keeps it for its own functions, as the chat code does.
|
||||
/// </summary>
|
||||
public static int NormalizeVk(int vk, bool extended)
|
||||
{
|
||||
if (vk == HotkeyKeys.VK_RETURN && extended) return 0;
|
||||
return vk switch
|
||||
{
|
||||
HotkeyKeys.VK_LSHIFT or HotkeyKeys.VK_RSHIFT => HotkeyKeys.VK_SHIFT,
|
||||
HotkeyKeys.VK_LCONTROL or HotkeyKeys.VK_RCONTROL => HotkeyKeys.VK_CONTROL,
|
||||
HotkeyKeys.VK_LMENU or HotkeyKeys.VK_RMENU => HotkeyKeys.VK_MENU,
|
||||
_ => vk,
|
||||
};
|
||||
}
|
||||
|
||||
public static HotkeyMods Mods(bool ctrl, bool alt, bool shift) =>
|
||||
(ctrl ? HotkeyMods.Ctrl : 0) | (alt ? HotkeyMods.Alt : 0) | (shift ? HotkeyMods.Shift : 0);
|
||||
|
||||
/// <summary>The first enabled binding for exactly this key and these modifiers (Ctrl+F1 doesn't fire on Ctrl+Shift+F1).</summary>
|
||||
public static HotkeyBinding? Find(IReadOnlyList<HotkeyBinding> bindings, KeyCombo pressed)
|
||||
{
|
||||
if (pressed.IsEmpty) return null;
|
||||
foreach (HotkeyBinding b in bindings)
|
||||
if (b.Enabled && b.Combo == pressed) return b;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the engine knows when a key goes down.</summary>
|
||||
/// <param name="InWorld">A character is in the world (not at character select).</param>
|
||||
/// <param name="GameFocused">The foreground window is this client's (the game or one of our windows).</param>
|
||||
/// <param name="RynthTextFocus">A RynthCore text box has the keyboard: RynthChat's input, an ImGui text
|
||||
/// field (io.WantTextInput), a popped-out panel's text box, an Avalonia text box.</param>
|
||||
/// <param name="AcTextFocus">AC's own UI has a keyboard focus element (its chat entry being typed in, a
|
||||
/// quantity box...): true / false, or null when AC's UI manager isn't readable.</param>
|
||||
internal readonly record struct TypingState(bool InWorld, bool GameFocused, bool RynthTextFocus, bool? AcTextFocus);
|
||||
|
||||
internal enum HotkeyGate
|
||||
{
|
||||
Fire,
|
||||
NotInWorld,
|
||||
NotFocused,
|
||||
RynthTyping,
|
||||
AcTyping,
|
||||
/// <summary>AC's focus is unknown and the key could be typing (no Ctrl/Alt, not an F key).</summary>
|
||||
AcUnknownTextKey,
|
||||
}
|
||||
|
||||
internal static class HotkeyRules
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether a bound key may fire. Never while the player is typing: in a RynthCore text box or in
|
||||
/// AC's own chat entry. When AC's focus can't be read, only keys that can't be typing fire.
|
||||
/// </summary>
|
||||
public static HotkeyGate Check(in TypingState s, KeyCombo combo)
|
||||
{
|
||||
if (!s.InWorld) return HotkeyGate.NotInWorld;
|
||||
if (!s.GameFocused) return HotkeyGate.NotFocused;
|
||||
if (s.RynthTextFocus) return HotkeyGate.RynthTyping;
|
||||
if (s.AcTextFocus == true) return HotkeyGate.AcTyping;
|
||||
if (s.AcTextFocus == null && !CantBeTyping(combo)) return HotkeyGate.AcUnknownTextKey;
|
||||
return HotkeyGate.Fire;
|
||||
}
|
||||
|
||||
/// <summary>Ctrl or Alt held, or an F key: a combo no text box takes as typing.</summary>
|
||||
public static bool CantBeTyping(KeyCombo c) =>
|
||||
(c.Mods & (HotkeyMods.Ctrl | HotkeyMods.Alt)) != 0 || HotkeyKeys.IsFunctionKey(c.Vk);
|
||||
|
||||
public static string Describe(HotkeyGate g) => g switch
|
||||
{
|
||||
HotkeyGate.Fire => "hotkeys fire",
|
||||
HotkeyGate.NotInWorld => "not in the world",
|
||||
HotkeyGate.NotFocused => "the game window isn't focused",
|
||||
HotkeyGate.RynthTyping => "typing in a RynthCore text box",
|
||||
HotkeyGate.AcTyping => "typing in AC's chat (or another AC text box)",
|
||||
HotkeyGate.AcUnknownTextKey => "AC's typing state is unknown; only Ctrl/Alt/F-key hotkeys fire",
|
||||
_ => g.ToString(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Warnings for a combo: bound twice, or one AC itself uses. Warnings only; the binding is allowed.</summary>
|
||||
internal static class HotkeyConflicts
|
||||
{
|
||||
/// <summary>Why AC may want this key itself (null if it's not a common AC key).</summary>
|
||||
public static string? CommonAcKey(KeyCombo c)
|
||||
{
|
||||
bool ctrlAlt = (c.Mods & (HotkeyMods.Ctrl | HotkeyMods.Alt)) != 0;
|
||||
if (ctrlAlt) return null;
|
||||
bool shift = (c.Mods & HotkeyMods.Shift) != 0;
|
||||
int vk = c.Vk;
|
||||
// Movement: with or without Shift (Shift switches walk/run while held).
|
||||
if (vk is 'W' or 'A' or 'S' or 'D' or 'Q' or 'E' or 'Z' or 'X' or 'C'
|
||||
or HotkeyKeys.VK_UP or HotkeyKeys.VK_DOWN or HotkeyKeys.VK_LEFT or HotkeyKeys.VK_RIGHT)
|
||||
return "AC moves your character with it";
|
||||
if (shift) return null;
|
||||
if (vk == HotkeyKeys.VK_SPACE) return "AC jumps with it";
|
||||
if (vk == HotkeyKeys.VK_RETURN) return "AC opens its chat with it";
|
||||
if (vk is >= '0' and <= '9') return "AC's shortcut bar uses the number keys";
|
||||
if (vk is HotkeyKeys.VK_TAB or HotkeyKeys.VK_BACK or HotkeyKeys.VK_OEM_3 or HotkeyKeys.VK_HOME
|
||||
or HotkeyKeys.VK_END or HotkeyKeys.VK_PRIOR or HotkeyKeys.VK_NEXT or HotkeyKeys.VK_INSERT or HotkeyKeys.VK_DELETE)
|
||||
return "AC's default keymap uses it";
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every warning for giving <paramref name="combo"/> to a binding. <paramref name="ignoreIndex"/>: the
|
||||
/// binding being edited (it doesn't conflict with itself).
|
||||
/// </summary>
|
||||
public static List<string> Warnings(IReadOnlyList<HotkeyBinding> bindings, KeyCombo combo, int ignoreIndex = -1)
|
||||
{
|
||||
var list = new List<string>();
|
||||
if (combo.IsEmpty) return list;
|
||||
for (int i = 0; i < bindings.Count; i++)
|
||||
{
|
||||
if (i == ignoreIndex || bindings[i].Combo != combo) continue;
|
||||
bool firstWins = ignoreIndex < 0 ? true : i < ignoreIndex;
|
||||
list.Add($"{combo} is also bound to \"{HotkeyActions.Describe(bindings[i])}\"" +
|
||||
(bindings[i].Enabled ? (firstWins ? " (that one fires, it's higher in the list)." : " (this one fires, it's higher in the list).")
|
||||
: " (switched off)."));
|
||||
}
|
||||
if (CommonAcKey(combo) is { } why)
|
||||
list.Add($"{combo}: {why}. While the hotkey is on, AC won't get that key.");
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Indexes of enabled bindings that share their combo with an earlier enabled one (they never fire).</summary>
|
||||
public static List<int> Shadowed(IReadOnlyList<HotkeyBinding> bindings)
|
||||
{
|
||||
var seen = new HashSet<KeyCombo>();
|
||||
var shadowed = new List<int>();
|
||||
for (int i = 0; i < bindings.Count; i++)
|
||||
{
|
||||
if (!bindings[i].Enabled) continue;
|
||||
if (!seen.Add(bindings[i].Combo)) shadowed.Add(i);
|
||||
}
|
||||
return shadowed;
|
||||
}
|
||||
}
|
||||
|
||||
internal enum HotkeyVerb { Help, List, Actions, Status, Add, Remove, Enable, Disable, On, Off, Error }
|
||||
|
||||
/// <summary>A parsed "/rc hotkey ..." line.</summary>
|
||||
internal sealed record HotkeyCommand(HotkeyVerb Verb, KeyCombo Combo = default, string Action = "", string ChatCommand = "",
|
||||
string Error = "");
|
||||
|
||||
internal static class HotkeyCommandParser
|
||||
{
|
||||
public const string Usage =
|
||||
"Usage: /rc hotkey list | add <combo> <action or /command> | remove <combo> | enable|disable <combo> | " +
|
||||
"actions | status | on|off. Combo e.g. F5, Ctrl+1, Alt+Shift+Num3. /rc hotkeys opens Settings > Hotkeys.";
|
||||
|
||||
/// <summary>Parses the arguments after "/rc hotkey".</summary>
|
||||
public static HotkeyCommand Parse(string? args)
|
||||
{
|
||||
string a = (args ?? string.Empty).Trim();
|
||||
if (a.Length == 0) return new HotkeyCommand(HotkeyVerb.Help);
|
||||
int sp = a.IndexOf(' ');
|
||||
string verb = (sp < 0 ? a : a[..sp]).ToLowerInvariant();
|
||||
string rest = sp < 0 ? string.Empty : a[(sp + 1)..].Trim();
|
||||
|
||||
switch (verb)
|
||||
{
|
||||
case "help": case "?": return new HotkeyCommand(HotkeyVerb.Help);
|
||||
case "list": case "ls": return new HotkeyCommand(HotkeyVerb.List);
|
||||
case "actions": return new HotkeyCommand(HotkeyVerb.Actions);
|
||||
case "status": return new HotkeyCommand(HotkeyVerb.Status);
|
||||
case "on": return rest.Length == 0 ? new HotkeyCommand(HotkeyVerb.On) : WithCombo(HotkeyVerb.Enable, rest);
|
||||
case "off": return rest.Length == 0 ? new HotkeyCommand(HotkeyVerb.Off) : WithCombo(HotkeyVerb.Disable, rest);
|
||||
case "remove": case "rm": case "del": case "delete": return WithCombo(HotkeyVerb.Remove, rest);
|
||||
case "enable": return WithCombo(HotkeyVerb.Enable, rest);
|
||||
case "disable": return WithCombo(HotkeyVerb.Disable, rest);
|
||||
case "add": case "bind": case "set": return ParseAdd(rest);
|
||||
default: return Fail($"Unknown '/rc hotkey {verb}'. {Usage}");
|
||||
}
|
||||
}
|
||||
|
||||
private static HotkeyCommand WithCombo(HotkeyVerb verb, string rest)
|
||||
{
|
||||
if (rest.Length == 0) return Fail($"Which key? e.g. /rc hotkey {verb.ToString().ToLowerInvariant()} Ctrl+F1");
|
||||
return HotkeyKeys.TryParse(rest, out KeyCombo combo, out string err) ? new HotkeyCommand(verb, combo) : Fail(err);
|
||||
}
|
||||
|
||||
private static HotkeyCommand ParseAdd(string rest)
|
||||
{
|
||||
// The combo is one word (no spaces inside: "Ctrl+Shift+F1"); the rest is the action.
|
||||
int sp = rest.IndexOf(' ');
|
||||
if (rest.Length == 0 || sp < 0)
|
||||
return Fail("Usage: /rc hotkey add <combo> <action or /command>, e.g. /rc hotkey add F5 macro or /rc hotkey add Ctrl+F1 /ra start");
|
||||
string comboText = rest[..sp];
|
||||
string what = rest[(sp + 1)..].Trim();
|
||||
if (!HotkeyKeys.TryParse(comboText, out KeyCombo combo, out string err)) return Fail(err);
|
||||
if (what.StartsWith('/'))
|
||||
return new HotkeyCommand(HotkeyVerb.Add, combo, HotkeyActions.Command, what);
|
||||
HotkeyAction? action = HotkeyActions.Resolve(what);
|
||||
if (action == null && HotkeyActions.ResolveWithParam(what) is { } withParam)
|
||||
{
|
||||
if (withParam.Param.Length == 0)
|
||||
return Fail($"'{withParam.Action.Name}' needs a {withParam.Action.Param!.ToLowerInvariant()}.");
|
||||
return new HotkeyCommand(HotkeyVerb.Add, combo, withParam.Action.Id, withParam.Param);
|
||||
}
|
||||
if (action is { HasParam: true })
|
||||
return Fail($"'{action.Name}' needs a {action.Param!.ToLowerInvariant()}: /rc hotkey add {comboText} {action.Id} <{action.Param.ToLowerInvariant()}>");
|
||||
if (action == null)
|
||||
return Fail($"Unknown action '{what}'. Use a chat command starting with / or a built-in (/rc hotkey actions).");
|
||||
return new HotkeyCommand(HotkeyVerb.Add, combo, action.Id);
|
||||
}
|
||||
|
||||
private static HotkeyCommand Fail(string error) => new(HotkeyVerb.Error, Error: error);
|
||||
}
|
||||
|
||||
/// <summary>The bindings and the master switch, as saved.</summary>
|
||||
internal sealed record HotkeyFile(bool Enabled, List<HotkeyBinding> Bindings);
|
||||
|
||||
/// <summary>
|
||||
/// %LOCALAPPDATA%\RynthCore\hotkeys.txt, for every client on this PC. Text, one binding a line:
|
||||
/// "on|off <TAB> combo <TAB> action <TAB> chat command". RYNTHCORE_HOTKEYS_FILE points a test at its own file.
|
||||
/// </summary>
|
||||
internal static class HotkeyStore
|
||||
{
|
||||
public const string EnvOverride = "RYNTHCORE_HOTKEYS_FILE";
|
||||
|
||||
public static string FilePath
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Environment.GetEnvironmentVariable(EnvOverride) is { Length: > 0 } p) return p;
|
||||
string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
return Path.Combine(root, "RynthCore", "hotkeys.txt");
|
||||
}
|
||||
}
|
||||
|
||||
public static string Serialize(HotkeyFile file)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("# RynthCore hotkeys (Settings > Hotkeys, /rc hotkey). Shared by every client on this PC.\n");
|
||||
sb.Append("# One per line: on|off <TAB> combo <TAB> action <TAB> chat command (action \"command\").\n");
|
||||
sb.Append("enabled=").Append(file.Enabled ? '1' : '0').Append('\n');
|
||||
foreach (HotkeyBinding b in file.Bindings)
|
||||
{
|
||||
if (b.Combo.IsEmpty) continue;
|
||||
bool keepsText = b.IsCommand || HotkeyActions.Find(b.Action)?.HasParam == true; // a chat command, or a parameter
|
||||
string cmd = keepsText ? b.Command.Replace('\t', ' ').Replace('\r', ' ').Replace('\n', ' ').Trim() : string.Empty;
|
||||
sb.Append(b.Enabled ? "on" : "off").Append('\t').Append(HotkeyKeys.Format(b.Combo)).Append('\t')
|
||||
.Append(b.Action).Append('\t').Append(cmd).Append('\n');
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Reads the file's text; bad lines are skipped (never throws).</summary>
|
||||
public static HotkeyFile Parse(string? text)
|
||||
{
|
||||
var file = new HotkeyFile(true, new List<HotkeyBinding>());
|
||||
bool enabled = true;
|
||||
if (string.IsNullOrEmpty(text)) return file;
|
||||
foreach (string raw in text.Split('\n'))
|
||||
{
|
||||
string line = raw.TrimEnd('\r');
|
||||
if (line.Trim().Length == 0 || line.TrimStart().StartsWith('#')) continue;
|
||||
if (line.StartsWith("enabled=", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
enabled = line.Substring(8).Trim() != "0";
|
||||
continue;
|
||||
}
|
||||
string[] f = line.Split('\t', 4);
|
||||
if (f.Length < 3) continue;
|
||||
if (!HotkeyKeys.TryParse(f[1], out KeyCombo combo, out _)) continue;
|
||||
string action = f[2].Trim();
|
||||
if (action.Length == 0) continue;
|
||||
string cmd = f.Length > 3 ? f[3].Trim() : string.Empty;
|
||||
bool on = !f[0].Trim().Equals("off", StringComparison.OrdinalIgnoreCase);
|
||||
file.Bindings.Add(new HotkeyBinding(combo, action, cmd, on));
|
||||
}
|
||||
return file with { Enabled = enabled };
|
||||
}
|
||||
|
||||
public static HotkeyFile Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = FilePath;
|
||||
return File.Exists(path) ? Parse(File.ReadAllText(path)) : new HotkeyFile(true, new List<HotkeyBinding>());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return new HotkeyFile(true, new List<HotkeyBinding>());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes the file (temp file, then replace). Returns false on an I/O error.</summary>
|
||||
public static bool Save(HotkeyFile file)
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = FilePath;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
string tmp = path + ".tmp";
|
||||
File.WriteAllText(tmp, Serialize(file));
|
||||
File.Move(tmp, path, overwrite: true);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The file's last write time (UTC), or MinValue if it doesn't exist.</summary>
|
||||
public static DateTime LastWriteUtc()
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = FilePath;
|
||||
return File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return DateTime.MinValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which key-ups and chars belong to a key a hotkey took. A hotkey's key-down is eaten, so are its
|
||||
/// auto-repeats, the char Windows makes from it and its key-up: AC sees none of that keystroke.
|
||||
/// Any other key passes untouched. Pure state, driven by HotkeyService on AC's thread.
|
||||
/// </summary>
|
||||
internal sealed class HotkeyKeyTracker
|
||||
{
|
||||
private readonly bool[] _eaten = new bool[256];
|
||||
private bool _eatNextChar;
|
||||
|
||||
/// <summary>A hotkey took this key-down: eat the rest of the keystroke.</summary>
|
||||
public void Took(int vk)
|
||||
{
|
||||
if ((uint)vk < 256) _eaten[vk] = true;
|
||||
_eatNextChar = true;
|
||||
}
|
||||
|
||||
/// <summary>True if this key's keystroke is being eaten (a repeat of a key a hotkey took).</summary>
|
||||
public bool IsEaten(int vk) => (uint)vk < 256 && _eaten[vk];
|
||||
|
||||
/// <summary>Key-down of another key: a char after it is that key's, not ours.</summary>
|
||||
public void OtherKeyDown() => _eatNextChar = false;
|
||||
|
||||
/// <summary>A WM_CHAR / WM_SYSCHAR: eat it when it's the one our key-down made.</summary>
|
||||
public bool TakeChar()
|
||||
{
|
||||
bool eat = _eatNextChar;
|
||||
_eatNextChar = false;
|
||||
return eat;
|
||||
}
|
||||
|
||||
/// <summary>A key-up: true (eat it) when its key-down was a hotkey's.</summary>
|
||||
public bool KeyUp(int vk)
|
||||
{
|
||||
_eatNextChar = false;
|
||||
if ((uint)vk >= 256 || !_eaten[vk]) return false;
|
||||
_eaten[vk] = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Focus lost: Windows sends no key-ups for keys still down; forget them.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
Array.Clear(_eaten);
|
||||
_eatNextChar = false;
|
||||
}
|
||||
}
|
||||
487
src/RynthCore.Engine/Hotkeys/HotkeyService.cs
Normal file
487
src/RynthCore.Engine/Hotkeys/HotkeyService.cs
Normal file
|
|
@ -0,0 +1,487 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Hotkeys/HotkeyService.cs
|
||||
//
|
||||
// The engine side of the user hotkeys (model and rules: HotkeyModel.cs).
|
||||
//
|
||||
// Keys: Win32Backend's WndProc subclass hands every key message here on AC's
|
||||
// main thread (after RynthChat's own input capture, before AC and ImGui see
|
||||
// it). A bound combo fires on its first key-down only (never on auto-repeat),
|
||||
// in the world, with the client in the foreground and nobody typing: not in a
|
||||
// RynthCore text box (RynthChat, an ImGui field, a pop-out's box) and not in
|
||||
// AC's own chat entry (AcKeyboardFocus: AC's UI focus element). The keystroke
|
||||
// that fires is eaten (down, repeats, its char and its up); unbound keys pass
|
||||
// through untouched.
|
||||
//
|
||||
// Actions run the way the panels run them: RynthAi/RynthSort exports through
|
||||
// the UI hub's pump (RynthAiCommands, RynthSortCommands), panels through
|
||||
// PanelRouter.Toggle, chat commands through AcMainThreadQueue (the next
|
||||
// main-thread drain, outside this keystroke's WndProc frame, so AC's chat bar
|
||||
// is never driven re-entrantly: see Win32Backend's WM_RYNTHCORE_CHAT note).
|
||||
//
|
||||
// Storage: %LOCALAPPDATA%\RynthCore\hotkeys.txt for every client on the PC
|
||||
// (HotkeyStore). Each client looks at the file's time at most every 2 s, so a
|
||||
// change made in one client reaches the others without a restart.
|
||||
//
|
||||
// Settings capture ("press a key"): the Settings section asks for the next
|
||||
// combo (BeginCapture); the next non-modifier key-down is taken for it (Esc
|
||||
// cancels) and AC never sees it.
|
||||
//
|
||||
// Hot reload: no event subscriptions, no threads; everything here is this
|
||||
// generation's statics. Shutdown cancels a capture.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace RynthCore.Engine.Hotkeys;
|
||||
|
||||
internal static class HotkeyService
|
||||
{
|
||||
private const uint WM_KILLFOCUS = 0x0008, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102,
|
||||
WM_DEADCHAR = 0x0103, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_SYSCHAR = 0x0106, WM_SYSDEADCHAR = 0x0107;
|
||||
|
||||
private const long FileCheckMs = 2000;
|
||||
private const long CaptureTimeoutMs = 15000;
|
||||
|
||||
[DllImport("user32.dll")] private static extern short GetKeyState(int nVirtKey);
|
||||
[DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
|
||||
|
||||
private static readonly object Sync = new();
|
||||
private static HotkeyFile _file = new(true, new List<HotkeyBinding>()); // replaced, never edited in place
|
||||
private static bool _loaded;
|
||||
private static DateTime _seenWriteUtc = DateTime.MinValue;
|
||||
private static long _nextFileCheckMs;
|
||||
private static int _pendingSaves;
|
||||
|
||||
private static readonly HotkeyKeyTracker Tracker = new(); // AC's main thread only
|
||||
|
||||
// Capture for the Settings section (main thread: the WndProc and ImGui both run there).
|
||||
private static bool _capturing;
|
||||
private static long _captureStartedMs;
|
||||
private static KeyCombo? _captured;
|
||||
private static bool _captureCancelled;
|
||||
private static string _captureNote = string.Empty;
|
||||
|
||||
private static HotkeyGate _lastGate = HotkeyGate.Fire;
|
||||
private static readonly uint OurPid = (uint)Environment.ProcessId;
|
||||
|
||||
// ── Bindings ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The bindings and master switch now (reloaded when another client changed the file). Any thread.</summary>
|
||||
public static HotkeyFile Current
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureFresh();
|
||||
return Volatile.Read(ref _file);
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureFresh()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (_loaded && now < Volatile.Read(ref _nextFileCheckMs)) return;
|
||||
lock (Sync)
|
||||
{
|
||||
if (_loaded && now < _nextFileCheckMs) return;
|
||||
_nextFileCheckMs = now + FileCheckMs;
|
||||
if (Volatile.Read(ref _pendingSaves) > 0) return; // our own write is on its way; don't read a half-old file
|
||||
DateTime w = HotkeyStore.LastWriteUtc();
|
||||
if (_loaded && w == _seenWriteUtc) return;
|
||||
HotkeyFile loaded = HotkeyStore.Load();
|
||||
bool first = !_loaded;
|
||||
_loaded = true;
|
||||
_seenWriteUtc = w;
|
||||
Volatile.Write(ref _file, loaded);
|
||||
if (first || loaded.Bindings.Count > 0)
|
||||
RynthLog.UI($"Hotkeys: {(first ? "loaded" : "reloaded")} {loaded.Bindings.Count} binding(s) from {HotkeyStore.FilePath} (hotkeys {(loaded.Enabled ? "on" : "off")}).");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Commit(HotkeyFile next)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
_loaded = true;
|
||||
Volatile.Write(ref _file, next);
|
||||
Interlocked.Increment(ref _pendingSaves);
|
||||
}
|
||||
UI.UiBackgroundWriter.Enqueue("hotkeys", () =>
|
||||
{
|
||||
bool ok = HotkeyStore.Save(next);
|
||||
lock (Sync)
|
||||
{
|
||||
if (ok) _seenWriteUtc = HotkeyStore.LastWriteUtc();
|
||||
Interlocked.Decrement(ref _pendingSaves);
|
||||
}
|
||||
if (!ok) RynthLog.UI($"Hotkeys: could not write {HotkeyStore.FilePath}.");
|
||||
});
|
||||
}
|
||||
|
||||
private static List<HotkeyBinding> Copy() => new(Current.Bindings);
|
||||
|
||||
public static void SetMasterEnabled(bool on)
|
||||
{
|
||||
HotkeyFile f = Current;
|
||||
if (f.Enabled != on) Commit(f with { Enabled = on, Bindings = new List<HotkeyBinding>(f.Bindings) });
|
||||
}
|
||||
|
||||
public static void Add(HotkeyBinding b)
|
||||
{
|
||||
List<HotkeyBinding> list = Copy();
|
||||
list.Add(b);
|
||||
Commit(Current with { Bindings = list });
|
||||
}
|
||||
|
||||
/// <summary>Replaces binding <paramref name="index"/> (from <see cref="Current"/>); false if it's gone.</summary>
|
||||
public static bool Replace(int index, HotkeyBinding b)
|
||||
{
|
||||
List<HotkeyBinding> list = Copy();
|
||||
if ((uint)index >= (uint)list.Count) return false;
|
||||
list[index] = b;
|
||||
Commit(Current with { Bindings = list });
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool RemoveAt(int index)
|
||||
{
|
||||
List<HotkeyBinding> list = Copy();
|
||||
if ((uint)index >= (uint)list.Count) return false;
|
||||
list.RemoveAt(index);
|
||||
Commit(Current with { Bindings = list });
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Moves binding <paramref name="index"/> up (-1) or down (+1): the higher of two with one key fires.</summary>
|
||||
public static bool Move(int index, int delta)
|
||||
{
|
||||
List<HotkeyBinding> list = Copy();
|
||||
int to = index + delta;
|
||||
if ((uint)index >= (uint)list.Count || (uint)to >= (uint)list.Count) return false;
|
||||
(list[index], list[to]) = (list[to], list[index]);
|
||||
Commit(Current with { Bindings = list });
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int RemoveCombo(KeyCombo combo)
|
||||
{
|
||||
List<HotkeyBinding> list = Copy();
|
||||
int n = list.RemoveAll(b => b.Combo == combo);
|
||||
if (n > 0) Commit(Current with { Bindings = list });
|
||||
return n;
|
||||
}
|
||||
|
||||
private static int SetComboEnabled(KeyCombo combo, bool on)
|
||||
{
|
||||
List<HotkeyBinding> list = Copy();
|
||||
int n = 0;
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
if (list[i].Combo == combo && list[i].Enabled != on) { list[i] = list[i] with { Enabled = on }; n++; }
|
||||
if (n > 0) Commit(Current with { Bindings = list });
|
||||
return n;
|
||||
}
|
||||
|
||||
// ── Capture (Settings: "press a key") ──────────────────────────────────
|
||||
|
||||
public static bool Capturing => _capturing;
|
||||
|
||||
public static void BeginCapture()
|
||||
{
|
||||
_capturing = true;
|
||||
_captured = null;
|
||||
_captureCancelled = false;
|
||||
_captureNote = string.Empty;
|
||||
_captureStartedMs = Environment.TickCount64;
|
||||
}
|
||||
|
||||
public static void CancelCapture()
|
||||
{
|
||||
if (!_capturing) return;
|
||||
_capturing = false;
|
||||
_captureCancelled = true;
|
||||
}
|
||||
|
||||
/// <summary>A key that couldn't be taken during the capture ("Numpad Enter can't be a hotkey").</summary>
|
||||
public static string CaptureNote => _captureNote;
|
||||
|
||||
/// <summary>
|
||||
/// The Settings section, each frame while it waits: true once the capture ended, with the combo, or
|
||||
/// null when it was cancelled (Esc, timeout).
|
||||
/// </summary>
|
||||
public static bool TryTakeCapture(out KeyCombo? combo)
|
||||
{
|
||||
combo = null;
|
||||
if (_capturing && Environment.TickCount64 - _captureStartedMs > CaptureTimeoutMs)
|
||||
{
|
||||
_capturing = false;
|
||||
_captureCancelled = true;
|
||||
}
|
||||
if (_capturing) return false;
|
||||
if (_captured is { } c) { _captured = null; combo = c; return true; }
|
||||
if (_captureCancelled) { _captureCancelled = false; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
// ── Keys (Win32Backend.WndProcHook, AC's main thread) ──────────────────
|
||||
|
||||
/// <summary>
|
||||
/// One key message. True: it belongs to a hotkey (or to a Settings capture) and must not reach AC
|
||||
/// or ImGui. <paramref name="rynthTextFocus"/>: a RynthCore text box has the keyboard.
|
||||
/// </summary>
|
||||
public static bool HandleKeyMessage(uint msg, IntPtr wParam, IntPtr lParam, bool rynthTextFocus)
|
||||
{
|
||||
try
|
||||
{
|
||||
switch (msg)
|
||||
{
|
||||
case WM_KILLFOCUS:
|
||||
Tracker.Reset();
|
||||
return false;
|
||||
case WM_CHAR:
|
||||
case WM_SYSCHAR:
|
||||
case WM_DEADCHAR:
|
||||
case WM_SYSDEADCHAR:
|
||||
return Tracker.TakeChar();
|
||||
case WM_KEYUP:
|
||||
case WM_SYSKEYUP:
|
||||
return Tracker.KeyUp(HotkeyMatch.NormalizeVk((int)wParam, HotkeyMatch.IsExtended(lParam.ToInt64())));
|
||||
case WM_KEYDOWN:
|
||||
case WM_SYSKEYDOWN:
|
||||
return KeyDown((int)wParam, lParam.ToInt64(), rynthTextFocus);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.UI($"Hotkeys: key message threw {ex.GetType().Name}: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Down(int vk) => (GetKeyState(vk) & 0x8000) != 0;
|
||||
|
||||
private static HotkeyMods HeldMods() =>
|
||||
HotkeyMatch.Mods(Down(HotkeyKeys.VK_CONTROL), Down(HotkeyKeys.VK_MENU), Down(HotkeyKeys.VK_SHIFT));
|
||||
|
||||
private static bool KeyDown(int rawVk, long lParam, bool rynthTextFocus)
|
||||
{
|
||||
int vk = HotkeyMatch.NormalizeVk(rawVk, HotkeyMatch.IsExtended(lParam));
|
||||
|
||||
if (_capturing)
|
||||
{
|
||||
if (HotkeyKeys.IsModifierKey(vk)) return false; // held for the combo; let it through
|
||||
Tracker.Took(vk);
|
||||
if (vk == HotkeyKeys.VK_ESCAPE) { CancelCapture(); return true; }
|
||||
if (vk == 0 || !HotkeyKeys.IsBindable(vk))
|
||||
{
|
||||
_captureNote = vk == 0 ? "Numpad Enter can't be a hotkey (AC keeps it)." : $"{HotkeyKeys.KeyName(vk)} can't be a hotkey.";
|
||||
return true; // keep waiting
|
||||
}
|
||||
_captured = new KeyCombo(vk, HeldMods());
|
||||
_capturing = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Tracker.IsEaten(vk))
|
||||
{
|
||||
Tracker.Took(vk); // auto-repeat of a key a hotkey took: eat it and its char too
|
||||
return true;
|
||||
}
|
||||
Tracker.OtherKeyDown();
|
||||
if (vk == 0 || HotkeyKeys.IsModifierKey(vk) || !HotkeyMatch.IsFreshPress(lParam)) return false;
|
||||
|
||||
HotkeyFile file = Current;
|
||||
if (!file.Enabled || file.Bindings.Count == 0) return false;
|
||||
var combo = new KeyCombo(vk, HeldMods());
|
||||
HotkeyBinding? b = HotkeyMatch.Find(file.Bindings, combo);
|
||||
if (b == null) return false;
|
||||
|
||||
HotkeyGate gate = HotkeyRules.Check(ReadTypingState(rynthTextFocus), combo);
|
||||
if (gate != _lastGate)
|
||||
{
|
||||
_lastGate = gate;
|
||||
if (gate != HotkeyGate.Fire) RynthLog.UI($"Hotkeys: {combo} held back - {HotkeyRules.Describe(gate)}.");
|
||||
}
|
||||
if (gate != HotkeyGate.Fire) return false;
|
||||
|
||||
Tracker.Took(vk);
|
||||
RynthLog.UI($"Hotkeys: {combo} -> {HotkeyActions.Describe(b)}.");
|
||||
Run(b);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static TypingState ReadTypingState(bool rynthTextFocus) => new(
|
||||
InWorld: LoginLifecycleHooks.HasObservedLoginComplete,
|
||||
GameFocused: ForegroundIsOurs(),
|
||||
RynthTextFocus: rynthTextFocus,
|
||||
AcTextFocus: AcKeyboardFocus.HasTextFocus());
|
||||
|
||||
private static bool ForegroundIsOurs()
|
||||
{
|
||||
IntPtr fg = GetForegroundWindow();
|
||||
if (fg == IntPtr.Zero) return false;
|
||||
GetWindowThreadProcessId(fg, out uint pid);
|
||||
return pid == OurPid;
|
||||
}
|
||||
|
||||
// ── Actions ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Runs a binding's action. Main thread (from the key); plugin work is posted to the pump.</summary>
|
||||
public static void Run(HotkeyBinding b)
|
||||
{
|
||||
if (b.IsCommand)
|
||||
{
|
||||
if (b.Command.Trim().Length == 0) return;
|
||||
if (!AcMainThreadQueue.EnqueueChatCommand(b.Command.Trim()))
|
||||
Reply("Hotkey: the chat command queue is full; try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
HotkeyAction? a = HotkeyActions.Find(b.Action);
|
||||
if (a == null)
|
||||
{
|
||||
Reply($"Hotkey {b.Combo}: unknown action '{b.Action}' (edit it in Settings > Hotkeys).");
|
||||
return;
|
||||
}
|
||||
if (a.Panel != null)
|
||||
{
|
||||
string title = UI.PanelRouter.Canonical(a.Panel);
|
||||
if (!ImGuiBackend.ImGuiPanelHost.HasFace(title))
|
||||
Reply($"Hotkey {b.Combo}: the {a.Panel} panel isn't available (its plugin isn't loaded, or the ImGui layer is off).");
|
||||
else
|
||||
UI.PanelRouter.Toggle(title);
|
||||
return;
|
||||
}
|
||||
|
||||
if (a.Chat != null)
|
||||
{
|
||||
// VTank-style actions that are RynthAi /ra commands (the same as typing them).
|
||||
if (a.HasParam && b.Command.Trim().Length == 0)
|
||||
{
|
||||
Reply($"Hotkey {b.Combo}: '{a.Name}' has no {a.Param!.ToLowerInvariant()} (edit it in Settings > Hotkeys).");
|
||||
return;
|
||||
}
|
||||
if (!AcMainThreadQueue.EnqueueChatCommand(HotkeyActions.ChatFor(a, b)))
|
||||
Reply("Hotkey: the chat command queue is full; try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (a.Id)
|
||||
{
|
||||
case "macro": case "vt:startstop": UI.Data.RynthAiCommands.ToggleMacro(); break;
|
||||
case "combat": case "vt:combat": UI.Data.RynthAiCommands.ToggleSubsystem(0); break;
|
||||
case "buffing": case "vt:buffing": UI.Data.RynthAiCommands.ToggleSubsystem(1); break;
|
||||
case "navigation": case "vt:navigation": UI.Data.RynthAiCommands.ToggleSubsystem(2); break;
|
||||
case "looting": case "vt:looting": UI.Data.RynthAiCommands.ToggleSubsystem(3); break;
|
||||
case "meta": UI.Data.RynthAiCommands.ToggleSubsystem(4); break;
|
||||
case "forcerebuff": case "vt:forcebuff": UI.Data.RynthAiCommands.ForceRebuff(); break;
|
||||
case "vt:cancelforcebuff": UI.Data.RynthAiCommands.CancelForceRebuff(); break;
|
||||
case "patrol": UI.Data.RynthAiCommands.SendNavCommand("{\"Cmd\":\"dunPatrol\"}", refreshPatrol: true); break;
|
||||
case "autosort": UI.Data.RynthSortCommands.ToggleAuto(); break;
|
||||
case "reload":
|
||||
// As /rc rl and the bar's RL: signalled from a pool thread (the reload shuts this engine down).
|
||||
RynthLog.Compat("Hotkeys: engine reload requested.");
|
||||
EntryPoint.NoteManualReload();
|
||||
ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null);
|
||||
break;
|
||||
default:
|
||||
Reply($"Hotkey {b.Combo}: '{a.Name}' isn't wired up in this engine.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Reply(string text) => AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, 1);
|
||||
|
||||
// ── /rc hotkey ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>"/rc hotkey ..." (args after "hotkey"): the reply lines.</summary>
|
||||
public static List<string> HandleCommand(string args)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
HotkeyCommand c = HotkeyCommandParser.Parse(args);
|
||||
HotkeyFile f = Current;
|
||||
switch (c.Verb)
|
||||
{
|
||||
case HotkeyVerb.Help:
|
||||
lines.Add(HotkeyCommandParser.Usage);
|
||||
break;
|
||||
case HotkeyVerb.Error:
|
||||
lines.Add(c.Error);
|
||||
break;
|
||||
case HotkeyVerb.List:
|
||||
if (f.Bindings.Count == 0) { lines.Add("No hotkeys. Add one in Settings > Hotkeys (/rc hotkeys) or with /rc hotkey add <combo> <action or /command>."); break; }
|
||||
lines.Add($"Hotkeys ({(f.Enabled ? "on" : "OFF: /rc hotkey on")}):");
|
||||
List<int> shadowed = HotkeyConflicts.Shadowed(f.Bindings);
|
||||
for (int i = 0; i < f.Bindings.Count; i++)
|
||||
{
|
||||
HotkeyBinding b = f.Bindings[i];
|
||||
lines.Add($" {b.Combo} - {HotkeyActions.Describe(b)}{(b.Enabled ? "" : " (off)")}{(shadowed.Contains(i) ? " (never fires: an earlier hotkey has this key)" : "")}");
|
||||
}
|
||||
break;
|
||||
case HotkeyVerb.Actions:
|
||||
lines.Add("Built-in actions (or any chat command starting with /):");
|
||||
foreach (string group in new[] { "", HotkeyActions.VTankGroup })
|
||||
{
|
||||
var sb = new System.Text.StringBuilder(group.Length > 0 ? " " + group + ": " : " ");
|
||||
foreach (HotkeyAction a in HotkeyActions.BuiltIns)
|
||||
{
|
||||
if (a.Group != group) continue;
|
||||
if (sb.Length > 150) { lines.Add(sb.ToString().TrimEnd(',', ' ')); sb.Clear().Append(" "); }
|
||||
sb.Append(a.Id);
|
||||
if (a.HasParam) sb.Append(" <").Append(a.Param!.ToLowerInvariant()).Append('>');
|
||||
sb.Append(", ");
|
||||
}
|
||||
lines.Add(sb.ToString().TrimEnd(',', ' '));
|
||||
}
|
||||
break;
|
||||
case HotkeyVerb.Status:
|
||||
lines.Add($"Hotkeys {(f.Enabled ? "on" : "off")}, {f.Bindings.Count} bound, file {HotkeyStore.FilePath}.");
|
||||
lines.Add("Last held back: " + (_lastGate == HotkeyGate.Fire ? "nothing" : HotkeyRules.Describe(_lastGate)) + ".");
|
||||
lines.Add(AcKeyboardFocus.Describe());
|
||||
break;
|
||||
case HotkeyVerb.On:
|
||||
case HotkeyVerb.Off:
|
||||
SetMasterEnabled(c.Verb == HotkeyVerb.On);
|
||||
lines.Add(c.Verb == HotkeyVerb.On ? "Hotkeys on." : "Hotkeys off (bindings kept; /rc hotkey on turns them back on).");
|
||||
break;
|
||||
case HotkeyVerb.Add:
|
||||
{
|
||||
var b = new HotkeyBinding(c.Combo, c.Action, c.ChatCommand);
|
||||
List<string> warn = HotkeyConflicts.Warnings(f.Bindings, c.Combo);
|
||||
Add(b);
|
||||
lines.Add($"Hotkey added: {c.Combo} - {HotkeyActions.Describe(b)}.");
|
||||
foreach (string w in warn) lines.Add("Note: " + w);
|
||||
if (!f.Enabled) lines.Add("Hotkeys are off; /rc hotkey on turns them on.");
|
||||
break;
|
||||
}
|
||||
case HotkeyVerb.Remove:
|
||||
{
|
||||
int n = RemoveCombo(c.Combo);
|
||||
lines.Add(n == 0 ? $"No hotkey on {c.Combo}." : $"Removed {n} hotkey(s) on {c.Combo}.");
|
||||
break;
|
||||
}
|
||||
case HotkeyVerb.Enable:
|
||||
case HotkeyVerb.Disable:
|
||||
{
|
||||
bool on = c.Verb == HotkeyVerb.Enable;
|
||||
int n = SetComboEnabled(c.Combo, on);
|
||||
lines.Add(n == 0 ? $"No hotkey on {c.Combo} to switch {(on ? "on" : "off")}." : $"{c.Combo}: {(on ? "on" : "off")}.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/// <summary>Engine shutdown: a capture in progress ends (the next generation starts clean).</summary>
|
||||
public static void Shutdown()
|
||||
{
|
||||
_capturing = false;
|
||||
_captured = null;
|
||||
Tracker.Reset();
|
||||
}
|
||||
}
|
||||
|
|
@ -23,6 +23,7 @@ using System.Runtime.InteropServices;
|
|||
using ImGuiNET;
|
||||
using RynthCore.Engine.D3D9;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Install;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
|
|
@ -48,6 +49,9 @@ internal static class EngineFrameController
|
|||
private static bool _imguiInitFailed;
|
||||
private static bool _coreResolved;
|
||||
private static bool _pluginsInitialized;
|
||||
// Pump frames plugin init has waited for the ImGui context (PumpPluginFrame; ~16 ms each).
|
||||
private static int _pluginInitContextWaits;
|
||||
private const int PluginInitContextMaxWaits = 300;
|
||||
private static IntPtr _context;
|
||||
private static IntPtr _gameHwnd;
|
||||
|
||||
|
|
@ -61,6 +65,26 @@ internal static class EngineFrameController
|
|||
/// </summary>
|
||||
internal static volatile IntPtr CachedDevice;
|
||||
private static int _pluginPumpInFrame; // re-entrancy guard for the pump
|
||||
private static int _pumpFrameFaults; // PumpPluginFrame throws caught (pump thread only)
|
||||
|
||||
// ImGui pipeline diagnostics (render thread only): one-time lines plus a 30 s heartbeat so a
|
||||
// log shows whether frames start, which branch runs and whether draw data is submitted.
|
||||
private const long HeartbeatIntervalMs = 30_000;
|
||||
private static long _engineErrorCount;
|
||||
private static long _nextEngineErrorLogAt;
|
||||
private static bool _loggedFirstSubmit;
|
||||
private static int _loggedBranch = -1;
|
||||
private static string _initFailStep = "unknown";
|
||||
private static long _drawSubmits;
|
||||
private static long _nextHeartbeatAt;
|
||||
|
||||
// Device for this frame's built ImGui draw data, submitted by RenderDeferredImGui after the
|
||||
// Avalonia blit. Render thread only; Zero = nothing pending. The draw data stays valid until
|
||||
// the next NewFrame on the main context.
|
||||
private static IntPtr _deferredSubmitDevice;
|
||||
// Build + pop-out time of the frame waiting in _deferredSubmitDevice (UiFrameStats adds the submit).
|
||||
private static long _deferredUiTicks;
|
||||
|
||||
private static long _lastFrameTicks;
|
||||
private static int _frameCount;
|
||||
|
||||
|
|
@ -103,7 +127,10 @@ internal static class EngineFrameController
|
|||
return true;
|
||||
|
||||
if (!EnsureCore(pDevice))
|
||||
{
|
||||
_initFailStep = "EnsureCore (game window not found)";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Before any context exists: the loaded cimgui.dll must be the exact
|
||||
// build ImGui.NET wraps, or every struct read below is at wrong offsets.
|
||||
|
|
@ -131,7 +158,7 @@ internal static class EngineFrameController
|
|||
System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir);
|
||||
IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath);
|
||||
unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; }
|
||||
RynthLog.Render($"EngineFrameController: imgui.ini pinned to {iniPath}");
|
||||
RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -155,10 +182,16 @@ internal static class EngineFrameController
|
|||
ImGuiFonts.Build(io, _uiScale);
|
||||
|
||||
if (!Win32Backend.Init(_gameHwnd))
|
||||
{
|
||||
_initFailStep = "Win32Backend.Init";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!DX9Backend.InitImGui(pDevice))
|
||||
{
|
||||
_initFailStep = "DX9Backend.InitImGui";
|
||||
return false;
|
||||
}
|
||||
|
||||
_lastFrameTicks = Stopwatch.GetTimestamp();
|
||||
_imguiInitialized = true;
|
||||
|
|
@ -229,6 +262,8 @@ internal static class EngineFrameController
|
|||
// EngineSettings.EnableImGuiBackend, so world→screen capture, nav-
|
||||
// marker rendering, and plugin lifecycle stay alive when the ImGui
|
||||
// surface is disabled.
|
||||
// A frame that throws before its build must not resubmit last frame's draw data.
|
||||
_deferredSubmitDevice = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
// Resolve game HWND and seed EntryPoint.GameHwnd. Required even
|
||||
|
|
@ -344,10 +379,10 @@ internal static class EngineFrameController
|
|||
// calls it at all.
|
||||
|
||||
// ── ImGui-gated work ─────────────────────────────────────────
|
||||
// The frame is BUILT here and SUBMITTED after the Nav3D fallback and
|
||||
// the vital HUD, so ImGui windows sit above both. The Avalonia quad
|
||||
// (EndSceneHook, after this returns) stays topmost while both stacks
|
||||
// run, matching input order: Avalonia gets the first hit test.
|
||||
// The frame is BUILT here and SUBMITTED by RenderDeferredImGui, which
|
||||
// EndSceneHook calls after the Avalonia quad, so ImGui windows sit above
|
||||
// the Nav3D fallback, the vital HUD and the Avalonia panels. Input order
|
||||
// matches: Win32Backend gives ImGui the mouse while it wants it.
|
||||
bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend;
|
||||
bool imguiBuilt = false;
|
||||
long uiTicks = 0;
|
||||
|
|
@ -370,17 +405,33 @@ internal static class EngineFrameController
|
|||
if (imguiEnabled)
|
||||
{
|
||||
long t0 = Stopwatch.GetTimestamp();
|
||||
if (imguiBuilt)
|
||||
SubmitImGuiFrame(pDevice);
|
||||
// Popped-out panels: their own contexts, windows and render targets.
|
||||
if (_imguiInitialized)
|
||||
ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive);
|
||||
UiFrameStats.Record(uiTicks + (Stopwatch.GetTimestamp() - t0));
|
||||
long ticks = uiTicks + (Stopwatch.GetTimestamp() - t0);
|
||||
if (imguiBuilt)
|
||||
{
|
||||
_deferredUiTicks = ticks;
|
||||
_deferredSubmitDevice = pDevice;
|
||||
}
|
||||
else
|
||||
{
|
||||
UiFrameStats.Record(ticks);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Info($"EngineFrameController: frame {_frameCount} engine error: {ex.GetType().Name}: {ex.Message}");
|
||||
// An exception here skips everything after it this frame (including RunImGuiFrame), so
|
||||
// the first one gets a stack trace; repeats are summarised every 30 s instead of per frame.
|
||||
_engineErrorCount++;
|
||||
long errNow = Environment.TickCount64;
|
||||
if (_engineErrorCount == 1)
|
||||
RynthLog.Error($"EngineFrameController: engine frame error (rest of this frame skipped): {ex}");
|
||||
else if (errNow >= _nextEngineErrorLogAt)
|
||||
RynthLog.Error($"EngineFrameController: engine frame errors so far={_engineErrorCount}, latest {ex.GetType().Name}: {ex.Message}");
|
||||
if (errNow >= _nextEngineErrorLogAt)
|
||||
_nextEngineErrorLogAt = errNow + HeartbeatIntervalMs;
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -442,14 +493,26 @@ internal static class EngineFrameController
|
|||
return; // never re-enter PluginManager from two stacks
|
||||
try
|
||||
{
|
||||
// Plugins only get the ImGui context when they may draw with it
|
||||
// (EnableImGuiShell, FORCE-gated). The engine's own ImGui panels
|
||||
// don't need plugins to see it, and handing it over switched
|
||||
// RynthAi into its legacy-ImGui setup (first ImGui-on test,
|
||||
// 2026-09-28) - plugins must behave exactly as in Avalonia-only mode.
|
||||
IntPtr pluginContext = Plugins.EngineSettings.EnableImGuiShell ? _context : IntPtr.Zero;
|
||||
// Plugins only get the ImGui context when they may draw with it: the
|
||||
// ImGui shell (EnableImGuiShell, FORCE-gated) or their own overlay
|
||||
// windows (EnablePluginOverlayWindows: RynthAi's ILT Hub, HUDs, Item
|
||||
// Info; RynthPluginRenderOverlay). RynthAi only reads the context for
|
||||
// those windows, so this does not switch it into a legacy-ImGui setup.
|
||||
bool pluginsDraw = Plugins.EngineSettings.EnableImGuiShell
|
||||
|| (Plugins.EngineSettings.EnablePluginOverlayWindows && Plugins.EngineSettings.EnableImGuiBackend);
|
||||
// _context is written by the render thread (Init); this is the pump thread.
|
||||
IntPtr pluginContext = pluginsDraw ? System.Threading.Volatile.Read(ref _context) : IntPtr.Zero;
|
||||
if (!_pluginsInitialized)
|
||||
{
|
||||
// The plugin host copies the context once at init, so wait for the
|
||||
// render path's ImGui init (first ImGui frame) rather than hand over
|
||||
// zero for the whole session. Bounded: a failed or stalled ImGui init
|
||||
// must not hold plugins (and the bot) back.
|
||||
if (pluginsDraw && pluginContext == IntPtr.Zero && !_imguiInitFailed
|
||||
&& ++_pluginInitContextWaits <= PluginInitContextMaxWaits)
|
||||
return;
|
||||
if (pluginsDraw && pluginContext == IntPtr.Zero)
|
||||
RynthLog.Warn($"EngineFrameController: plugins initialised without an ImGui context (imguiInitFailed={_imguiInitFailed}, waits={_pluginInitContextWaits}) - plugin overlay windows will not draw this session.");
|
||||
_pluginsInitialized = true;
|
||||
PluginManager.InitPlugins(pluginContext, device, _gameHwnd);
|
||||
}
|
||||
|
|
@ -471,7 +534,13 @@ internal static class EngineFrameController
|
|||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Plugin($"EngineFrameController.PumpPluginFrame: {ex.GetType().Name}: {ex.Message}");
|
||||
// The first one with its stack, then counted (a step throwing every frame
|
||||
// would otherwise write a line per pump tick).
|
||||
int n = ++_pumpFrameFaults;
|
||||
if (n == 1)
|
||||
RynthLog.Plugin($"EngineFrameController.PumpPluginFrame: {ex.GetType().Name}: {ex.Message} (caught; repeats are counted){Environment.NewLine}{ex}");
|
||||
else if (n % StepFaultLog.RepeatEvery == 0)
|
||||
RynthLog.Plugin($"EngineFrameController.PumpPluginFrame: {ex.GetType().Name}: {ex.Message} - {n} times so far, still caught.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -501,9 +570,16 @@ internal static class EngineFrameController
|
|||
if (!PanelsLive) return false;
|
||||
ImGuiPanelHost.RestoreOnce();
|
||||
return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame
|
||||
|| D3D9.VideoPatch.WantsBanner;
|
||||
|| D3D9.VideoPatch.WantsBanner || PluginOverlayWindowsLive;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// In the world, with the shell off, and some loaded plugin exports
|
||||
/// RynthPluginRenderOverlay: its windows need a frame every frame.
|
||||
/// </summary>
|
||||
private static bool PluginOverlayWindowsLive =>
|
||||
PanelsLive && Plugins.EngineSettings.EnablePluginOverlayWindows && PluginManager.HasOverlayPlugins;
|
||||
|
||||
/// <summary>
|
||||
/// Panel faces show only in the world, like the Avalonia overlay (hidden
|
||||
/// between characters, not closed). Also off as soon as AC leaves the world screen
|
||||
|
|
@ -544,7 +620,8 @@ internal static class EngineFrameController
|
|||
}
|
||||
|
||||
private static bool HasImGuiContentNoRestore() =>
|
||||
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner));
|
||||
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner))
|
||||
|| PluginOverlayWindowsLive;
|
||||
|
||||
// Keyboard owner between the stacks (plan §3.2 d): whichever side started
|
||||
// text entry most recently keeps the keyboard.
|
||||
|
|
@ -573,6 +650,7 @@ internal static class EngineFrameController
|
|||
if (!Init(pDevice))
|
||||
{
|
||||
_imguiInitFailed = true;
|
||||
RynthLog.Error($"EngineFrameController: ImGui init FAILED at step '{_initFailStep}' - ImGui frames disabled for this session.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -596,7 +674,6 @@ internal static class EngineFrameController
|
|||
ImGuiNET.ImGui.SetCurrentContext(_context);
|
||||
bool frameStarted = false;
|
||||
bool frameEnded = false;
|
||||
|
||||
try
|
||||
{
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
|
|
@ -644,6 +721,9 @@ internal static class EngineFrameController
|
|||
|
||||
ImGuiNET.ImGui.NewFrame();
|
||||
frameStarted = true;
|
||||
// Before any window: a drag from a popped-out Inventory or AC's inventory becomes
|
||||
// a payload the client's drop targets (Mini Remote slots) see this frame.
|
||||
ItemDragBridge.SubmitMainFrame(io);
|
||||
ImGuiTextFocus.BeginFrame();
|
||||
if (_dropImGuiTextFocus)
|
||||
{
|
||||
|
|
@ -653,11 +733,29 @@ internal static class EngineFrameController
|
|||
}
|
||||
// EnableImGuiShell gates the old diagnostic shell and plugin-drawn
|
||||
// ImGui windows (plugin code on AC's thread: FORCE-gated, stays off).
|
||||
int branch;
|
||||
if (Plugins.EngineSettings.EnableImGuiShell)
|
||||
{
|
||||
branch = 1;
|
||||
RynthCoreShell.Render(_frameCount);
|
||||
PluginManager.RenderAll();
|
||||
}
|
||||
else if (PluginOverlayWindowsLive)
|
||||
{
|
||||
branch = 2;
|
||||
// Only the opt-in extra windows (RynthPluginRenderOverlay), never the
|
||||
// plugins' full ImGui UIs.
|
||||
PluginManager.RenderOverlayAll();
|
||||
}
|
||||
else
|
||||
{
|
||||
branch = 0;
|
||||
}
|
||||
if (branch != _loggedBranch)
|
||||
{
|
||||
_loggedBranch = branch;
|
||||
RynthLog.Info($"EngineFrameController: ImGui plugin branch = {(branch == 1 ? "shell (RenderAll)" : branch == 2 ? "overlay windows (RenderOverlayAll)" : "none")}.");
|
||||
}
|
||||
if (PanelsLive)
|
||||
{
|
||||
// World overlays: built into UnderUiLayer's list, drawn next frame at
|
||||
|
|
@ -744,6 +842,24 @@ internal static class EngineFrameController
|
|||
_prevAvaloniaText = avaloniaText;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Submits this frame's ImGui draw data. EndSceneHook calls it after
|
||||
/// OverlayTextureRenderer.Render so ImGui windows draw on top of the Avalonia layer.
|
||||
/// Runs whether or not the Avalonia blit ran (character select, Avalonia off), and is
|
||||
/// a no-op when <see cref="OnEndScene"/> built nothing this frame. Never throws.
|
||||
/// </summary>
|
||||
public static void RenderDeferredImGui()
|
||||
{
|
||||
IntPtr device = _deferredSubmitDevice;
|
||||
if (device == IntPtr.Zero)
|
||||
return;
|
||||
_deferredSubmitDevice = IntPtr.Zero; // one submission per frame, even if it throws
|
||||
|
||||
long t0 = Stopwatch.GetTimestamp();
|
||||
SubmitImGuiFrame(device);
|
||||
UiFrameStats.Record(_deferredUiTicks + (Stopwatch.GetTimestamp() - t0));
|
||||
}
|
||||
|
||||
/// <summary>Draws the frame <see cref="BuildImGuiFrame"/> produced.</summary>
|
||||
private static void SubmitImGuiFrame(IntPtr pDevice)
|
||||
{
|
||||
|
|
@ -751,7 +867,15 @@ internal static class EngineFrameController
|
|||
ImGuiNET.ImGui.SetCurrentContext(_context);
|
||||
try
|
||||
{
|
||||
DX9Backend.RenderDrawData(ImGuiNET.ImGui.GetDrawData(), pDevice);
|
||||
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
|
||||
DX9Backend.RenderDrawData(drawData, pDevice);
|
||||
_drawSubmits++;
|
||||
if (!_loggedFirstSubmit)
|
||||
{
|
||||
_loggedFirstSubmit = true;
|
||||
RynthLog.Info("EngineFrameController: first ImGui draw submitted.");
|
||||
}
|
||||
LogHeartbeatIfDue(drawData);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -763,6 +887,29 @@ internal static class EngineFrameController
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every 30 s: built ImGui frames, submits, draw list / vertex counts of the
|
||||
/// latest frame and the overlay-window stats from PluginManager. Zero draw lists means no
|
||||
/// ImGui window was drawn that frame. One string per interval; no per-frame allocation.
|
||||
/// </summary>
|
||||
private static void LogHeartbeatIfDue(ImDrawDataPtr drawData)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (now < _nextHeartbeatAt) return;
|
||||
bool first = _nextHeartbeatAt == 0;
|
||||
_nextHeartbeatAt = now + HeartbeatIntervalMs;
|
||||
if (first) return; // first interval starts now; the first-frame line already covers t=0
|
||||
|
||||
int lists = 0, vertices = 0;
|
||||
unsafe
|
||||
{
|
||||
// ImDrawData: +4 CmdListsCount, +8 TotalIdxCount, +12 TotalVtxCount (see CLAUDE.md offsets).
|
||||
byte* p = (byte*)drawData.NativePtr;
|
||||
if (p != null) { lists = *(int*)(p + 4); vertices = *(int*)(p + 12); }
|
||||
}
|
||||
RynthLog.Info($"EngineFrameController: ImGui heartbeat frames={_framesBuilt} submits={_drawSubmits} lastFrame drawLists={lists} vertices={vertices} {PluginManager.DescribeOverlayState()}.");
|
||||
}
|
||||
|
||||
internal static IntPtr FindGameWindow()
|
||||
{
|
||||
uint pid = GetCurrentProcessId();
|
||||
|
|
|
|||
|
|
@ -57,12 +57,14 @@ internal static class ImGuiBar
|
|||
|
||||
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
|
||||
private static readonly string[] ImGuiOnlyBarPanels =
|
||||
{ Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.ItemCountFace.Title, Panels.MiniRemoteFace.Title };
|
||||
{ Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.ItemCountFace.Title, Panels.MiniRemoteFace.Title,
|
||||
Panels.CharactersFace.Title };
|
||||
|
||||
// The ILT section: the RynthILT plugin's ImGui-only panels. They never get buttons of their
|
||||
// own; one ILT button stands for them, shown only on Infinite Leaftide (IltInfo.IsIlt) and
|
||||
// only for the ones registered (EntryPoint registers them when RynthILT is installed).
|
||||
private static readonly string[] IltPanels = { Panels.BountiesFace.Title };
|
||||
// The ILT section: ImGui-only Infinite Leaftide panels (Bounties from RynthILT, Guardian from
|
||||
// RynthAi). They never get buttons of their own; one ILT button stands for them, shown only
|
||||
// on Infinite Leaftide (IltInfo.IsIlt) and only for the ones registered (EntryPoint registers
|
||||
// each when its plugin is installed).
|
||||
private static readonly string[] IltPanels = { Panels.BountiesFace.Title, Panels.GuardianFace.Title };
|
||||
|
||||
// Known panels' icons (DrakBot's where the same window exists); others show their first letter.
|
||||
private static readonly Dictionary<string, string> PanelIcons = new(StringComparer.OrdinalIgnoreCase)
|
||||
|
|
@ -88,6 +90,7 @@ internal static class ImGuiBar
|
|||
["Log"] = PhosphorIcons.TerminalWindow,
|
||||
["Item Count"] = PhosphorIcons.Bag,
|
||||
["Mini Remote"] = PhosphorIcons.SquaresFour,
|
||||
["Characters"] = PhosphorIcons.UsersThree,
|
||||
// Plugin windows with a bar button of their own (script windows, by title).
|
||||
["RynthSort"] = PhosphorIcons.SortAscending,
|
||||
["Oracle"] = PhosphorIcons.Sparkle,
|
||||
|
|
@ -261,6 +264,8 @@ internal static class ImGuiBar
|
|||
|
||||
public static void Draw(float s)
|
||||
{
|
||||
// The bar draws every frame the ImGui shell is up: keep RynthAi's server menu current.
|
||||
RynthCore.Engine.UI.ServerMenus.Tick();
|
||||
EnsureButtons();
|
||||
int step = ChromeStep(out float factor);
|
||||
s *= factor;
|
||||
|
|
@ -389,8 +394,8 @@ internal static class ImGuiBar
|
|||
FacePopup(b.PopupId, b.Title, ImGuiPanelHost.HasFace(b.Title));
|
||||
}
|
||||
|
||||
// The ILT section: one button, only on Infinite Leaftide with RynthILT's panels
|
||||
// registered. With one panel it toggles that panel; with more it opens a menu.
|
||||
// The ILT section: one button, only on Infinite Leaftide with ILT panels registered
|
||||
// (Bounties, Guardian). With one panel it toggles that panel; with more it opens a menu.
|
||||
int iltCount = IltPanelCount();
|
||||
if (iltCount > 0)
|
||||
{
|
||||
|
|
@ -418,7 +423,11 @@ internal static class ImGuiBar
|
|||
|
||||
ImGuiNET.ImGui.SameLine(0, 6 * s);
|
||||
if (IconButton("##reload", iconFont, PhosphorIcons.ArrowsClockwise, square, RynthTheme.ReloadLabel))
|
||||
{
|
||||
// By hand: not held while a plugin objects (combat, looting); the player chose the moment.
|
||||
EntryPoint.NoteManualReload();
|
||||
ThreadPool.UnsafeQueueUserWorkItem(static _ => EngineLifecycle.SignalReload(), null);
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Engine reload (RL) — shut down, FreeLibrary, reload from disk, re-init.");
|
||||
|
||||
if (ResolveFace() == PanelFace.ImGui)
|
||||
|
|
|
|||
|
|
@ -67,6 +67,10 @@ internal sealed record PanelSpec(
|
|||
// Where the panel first opens (logical units) when nothing is saved for its
|
||||
// key; null = the cascade. (Script windows: a FirstUseEver position.)
|
||||
Vector2? DefaultPos = null,
|
||||
// With nothing saved and no DefaultPos: open centred in the game view rather
|
||||
// than in the top-left cascade, where popped-out panels (separate windows
|
||||
// above the game frame) usually sit and would hide it.
|
||||
bool OpenCentered = false,
|
||||
// No resize grip, docked or popped out: the face sizes itself (the RynthNav arrow
|
||||
// fits its height to what it shows). Chromeless and GripInBody panels only.
|
||||
bool NoResize = false);
|
||||
|
|
@ -651,6 +655,10 @@ internal static class ImGuiPanelHost
|
|||
{
|
||||
pos = defaultPos; // the face's own first spot (a script window's FirstUseEver position)
|
||||
}
|
||||
else if (entry.Spec.OpenCentered && CenteredLogicalPos(size, placeScale) is Vector2 centered)
|
||||
{
|
||||
pos = centered;
|
||||
}
|
||||
else
|
||||
{
|
||||
int shown = 0;
|
||||
|
|
@ -670,6 +678,104 @@ internal static class ImGuiPanelHost
|
|||
entry.NeedsPlacement = true;
|
||||
entry.DesiredPos = entry.Pos != pos * placeScale ? pos * placeScale : null;
|
||||
entry.DesiredForDisplay = ImGuiNET.ImGui.GetIO().DisplaySize;
|
||||
|
||||
// Popped-out windows sit above the game frame, so a docked panel opening under
|
||||
// one would be invisible. The new spot is saved by the open's Persist, so the
|
||||
// panel comes back where it could be seen.
|
||||
if (ClearOfPopOuts(entry.Pos, entry.Size) is Vector2 clear)
|
||||
{
|
||||
RynthLog.UI($"ImGuiPanelHost: {entry.Title} would open under a popped-out window; " +
|
||||
$"moved from ({entry.Pos.X:0},{entry.Pos.Y:0}) to ({clear.X:0},{clear.Y:0}).");
|
||||
entry.Pos = clear;
|
||||
entry.PersistedPos = clear;
|
||||
entry.DesiredPos = null; // don't pull it back under the pop-out as the display grows
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Above this share of a docked panel hidden by popped-out windows, it opens elsewhere.</summary>
|
||||
private const float MaxCoveredFraction = 0.5f;
|
||||
/// <summary>Candidate spots per axis when looking for a clear place (a grid over the game view).</summary>
|
||||
private const int ClearSpotSteps = 8;
|
||||
|
||||
/// <summary>
|
||||
/// A spot (client px) for a docked window of <paramref name="size"/> at <paramref name="pos"/>
|
||||
/// that popped-out windows hide less, nearest the original among the least-covered; null when
|
||||
/// at most half of it is covered or no spot is better.
|
||||
/// </summary>
|
||||
private static Vector2? ClearOfPopOuts(Vector2 pos, Vector2 size)
|
||||
{
|
||||
float area = size.X * size.Y;
|
||||
if (area <= 0) return null;
|
||||
List<(Vector2 Min, Vector2 Max)> covers = PopOutRectsInClient();
|
||||
if (covers.Count == 0) return null;
|
||||
float covered = CoveredArea(pos, size, covers);
|
||||
if (covered <= area * MaxCoveredFraction) return null;
|
||||
|
||||
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
|
||||
if (display.X <= 1 || display.Y <= 1) return null;
|
||||
Vector2 room = Vector2.Max(Vector2.Zero, display - size);
|
||||
|
||||
// Pass 1: the least coverage any grid spot reaches. Pass 2: the nearest spot within
|
||||
// 2% of the panel's area of that, so a nearly-as-clear nearby spot beats a far one.
|
||||
float least = float.MaxValue;
|
||||
for (int i = 0; i <= ClearSpotSteps; i++)
|
||||
for (int j = 0; j <= ClearSpotSteps; j++)
|
||||
least = Math.Min(least, CoveredArea(GridSpot(room, i, j), size, covers));
|
||||
if (least >= covered) return null;
|
||||
|
||||
float tolerance = least + area * 0.02f;
|
||||
Vector2? best = null;
|
||||
float bestDist = float.MaxValue;
|
||||
for (int i = 0; i <= ClearSpotSteps; i++)
|
||||
for (int j = 0; j <= ClearSpotSteps; j++)
|
||||
{
|
||||
Vector2 spot = GridSpot(room, i, j);
|
||||
if (CoveredArea(spot, size, covers) > tolerance) continue;
|
||||
float dist = Vector2.DistanceSquared(spot, pos);
|
||||
if (dist < bestDist) { bestDist = dist; best = spot; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static Vector2 GridSpot(Vector2 room, int i, int j) =>
|
||||
new(MathF.Round(room.X * i / ClearSpotSteps), MathF.Round(room.Y * j / ClearSpotSteps));
|
||||
|
||||
/// <summary>Visible popped-out windows' rects in the game window's client px (ImGui coordinates).</summary>
|
||||
private static List<(Vector2 Min, Vector2 Max)> PopOutRectsInClient()
|
||||
{
|
||||
Vector2 origin = ImGuiPopOuts.ClientOriginOnScreen();
|
||||
var rects = new List<(Vector2, Vector2)>();
|
||||
foreach (var (left, top, width, height) in UI.LayeredWindow.VisibleContentRects())
|
||||
{
|
||||
var min = new Vector2(left, top) - origin;
|
||||
rects.Add((min, min + new Vector2(width, height)));
|
||||
}
|
||||
return rects;
|
||||
}
|
||||
|
||||
/// <summary>Area of the window hidden by <paramref name="covers"/> (overlaps between covers count twice).</summary>
|
||||
private static float CoveredArea(Vector2 pos, Vector2 size, List<(Vector2 Min, Vector2 Max)> covers)
|
||||
{
|
||||
Vector2 max = pos + size;
|
||||
float total = 0;
|
||||
foreach (var (cMin, cMax) in covers)
|
||||
{
|
||||
float w = MathF.Min(max.X, cMax.X) - MathF.Max(pos.X, cMin.X);
|
||||
float h = MathF.Min(max.Y, cMax.Y) - MathF.Max(pos.Y, cMin.Y);
|
||||
if (w > 0 && h > 0) total += w * h;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Top-left (logical units) that centres a window of logical <paramref name="size"/> in the
|
||||
/// game view; null while the display size isn't known yet.
|
||||
/// </summary>
|
||||
private static Vector2? CenteredLogicalPos(Vector2 size, float placeScale)
|
||||
{
|
||||
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
|
||||
if (display.X <= 1 || display.Y <= 1 || placeScale <= 0) return null;
|
||||
return Vector2.Max(Vector2.Zero, (display / placeScale - size) * 0.5f);
|
||||
}
|
||||
|
||||
private static Vector2 ClampToDisplay(Vector2 pos, Vector2 size)
|
||||
|
|
@ -1093,43 +1199,7 @@ internal static class ImGuiPanelHost
|
|||
if (!ImGuiNET.ImGui.BeginPopup(TextSizePopupId)) return;
|
||||
try
|
||||
{
|
||||
int step = PanelTextScale.Get(title);
|
||||
int max = PanelTextScale.SizeNames.Length - 1;
|
||||
int all = PanelTextScale.GetAll();
|
||||
float btn = 20f * s;
|
||||
|
||||
ImGuiNET.ImGui.TextUnformatted("Text size");
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero);
|
||||
ImGuiNET.ImGui.BeginDisabled(step <= 0);
|
||||
if (HeaderIconButton("##ts_smaller", PhosphorIcons.Minus, btn))
|
||||
PanelTextScale.SetForWindow(title, step - 1);
|
||||
ImGuiNET.ImGui.EndDisabled();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Smaller");
|
||||
ImGuiNET.ImGui.SameLine(0, 4 * s);
|
||||
ImGuiNET.ImGui.BeginDisabled(step >= max);
|
||||
if (HeaderIconButton("##ts_bigger", PhosphorIcons.Plus, btn))
|
||||
PanelTextScale.SetForWindow(title, step + 1);
|
||||
ImGuiNET.ImGui.EndDisabled();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Bigger");
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.SameLine(0, 8 * s);
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextUnformatted(PanelTextScale.Describe(step));
|
||||
|
||||
int pick = step;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(btn * 2 + 4 * s + 8 * s + 110 * s);
|
||||
if (ImGuiNET.ImGui.SliderInt("##ts_step", ref pick, 0, max, "%d", ImGuiSliderFlags.AlwaysClamp) && pick != step)
|
||||
PanelTextScale.SetForWindow(title, pick);
|
||||
|
||||
ImGuiNET.ImGui.BeginDisabled(step == all);
|
||||
if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + " Reset"))
|
||||
PanelTextScale.ResetWindow(title);
|
||||
ImGuiNET.ImGui.EndDisabled();
|
||||
ImGuiNET.ImGui.SetItemTooltip(all == 0 ? "Back to normal size" : "Back to the All Panels size (Settings > Display)");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.Button("Use for all windows"))
|
||||
PanelTextScale.UseForAll(step);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Every in-game window at this size (Settings > Display > All Panels)");
|
||||
TextSizeRows(title, s);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -1137,6 +1207,53 @@ internal static class ImGuiPanelHost
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The text size popup's rows for <paramref name="title"/> at the cursor: smaller / bigger and the
|
||||
/// size, a slider over the steps, reset, use for all windows. The title bar's popup, and a chromeless
|
||||
/// panel's own popup (the RynthAi dashboard's title row). <paramref name="s"/> scales the buttons.
|
||||
/// AC thread, inside a popup.
|
||||
/// </summary>
|
||||
public static void TextSizeRows(string title, float s, string heading = "Text size")
|
||||
{
|
||||
int step = PanelTextScale.Get(title);
|
||||
int max = PanelTextScale.SizeNames.Length - 1;
|
||||
int all = PanelTextScale.GetAll();
|
||||
float btn = 20f * s;
|
||||
|
||||
ImGuiNET.ImGui.TextUnformatted(heading);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero);
|
||||
ImGuiNET.ImGui.BeginDisabled(step <= 0);
|
||||
if (HeaderIconButton("##ts_smaller", PhosphorIcons.Minus, btn))
|
||||
PanelTextScale.SetForWindow(title, step - 1);
|
||||
ImGuiNET.ImGui.EndDisabled();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Smaller");
|
||||
ImGuiNET.ImGui.SameLine(0, 4 * s);
|
||||
ImGuiNET.ImGui.BeginDisabled(step >= max);
|
||||
if (HeaderIconButton("##ts_bigger", PhosphorIcons.Plus, btn))
|
||||
PanelTextScale.SetForWindow(title, step + 1);
|
||||
ImGuiNET.ImGui.EndDisabled();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Bigger");
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.SameLine(0, 8 * s);
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextUnformatted(PanelTextScale.Describe(step));
|
||||
|
||||
int pick = step;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(btn * 2 + 4 * s + 8 * s + 110 * s);
|
||||
if (ImGuiNET.ImGui.SliderInt("##ts_step", ref pick, 0, max, "%d", ImGuiSliderFlags.AlwaysClamp) && pick != step)
|
||||
PanelTextScale.SetForWindow(title, pick);
|
||||
|
||||
ImGuiNET.ImGui.BeginDisabled(step == all);
|
||||
if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + " Reset"))
|
||||
PanelTextScale.ResetWindow(title);
|
||||
ImGuiNET.ImGui.EndDisabled();
|
||||
ImGuiNET.ImGui.SetItemTooltip(all == 0 ? "Back to normal size" : "Back to the All Panels size (Settings > Display)");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.Button("Use for all windows"))
|
||||
PanelTextScale.UseForAll(step);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Every in-game window at this size (Settings > Display > All Panels)");
|
||||
}
|
||||
|
||||
private const string DragLabel = PhosphorIcons.DotsSixVertical + "DRAG";
|
||||
|
||||
/// <summary>A header button (the theme's button look) with an icon centred on it.</summary>
|
||||
|
|
|
|||
251
src/RynthCore.Engine/ImGui/ItemDragBridge.cs
Normal file
251
src/RynthCore.Engine/ImGui/ItemDragBridge.cs
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/ItemDragBridge.cs
|
||||
// Carries an item drag into the MAIN ImGui context when it didn't start there,
|
||||
// so drop targets in the client (RynthAi's Mini Remote slots) can take it:
|
||||
//
|
||||
// • A popped-out Inventory: the pop-out has its own ImGui context and holds
|
||||
// mouse capture for the whole drag, so the main context never sees it.
|
||||
// The pop-out face reports the dragged item (NotePopOutDrag); the main
|
||||
// frame republishes it as an extern payload. The main context sees no
|
||||
// button press, so the payload uses PayloadAutoExpire: it is delivered to
|
||||
// the hovered target on the first frame it is no longer submitted.
|
||||
// • AC's own inventory: a press that began on the game belongs to the game,
|
||||
// and ImGui ignores hovering for it. DragDropHooks reports the item AC
|
||||
// starts dragging (OnNativeDragStart); a carried one is republished the
|
||||
// same way, under PayloadType, and delivered when ImGui sees the button go
|
||||
// up. AC does not select the dragged item, so without that hook the bridge
|
||||
// can only guess from the selection: the guess goes out under
|
||||
// NativePayloadType, which targets treat as unreliable.
|
||||
//
|
||||
// A native drag released over an ImGui window would otherwise complete in AC
|
||||
// as a drop on the 3D view (the item lands on the ground). TryRedirectNativeDrop
|
||||
// moves that button-up back to where the drag began, which AC treats as
|
||||
// putting the item back.
|
||||
//
|
||||
// Threads: AC's main thread only (game WndProc, EndScene, pop-out frames).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static unsafe class ItemDragBridge
|
||||
{
|
||||
/// <summary>Payload type for one item (uint object id). Must match RynthAi's MiniRemoteHud.ItemPayloadType.</summary>
|
||||
public const string PayloadType = "RYNTH_INV_ITEM";
|
||||
|
||||
/// <summary>
|
||||
/// Payload type for a game drag whose item was guessed from the selection (DragDropHooks not
|
||||
/// installed). Any game left-drag with a carried item selected looks like this (moving an AC
|
||||
/// panel too), so targets should take it only where a wrong item does no harm (RynthAi: empty
|
||||
/// slots). Must match MiniRemoteHud.GameItemPayloadType.
|
||||
/// </summary>
|
||||
public const string NativePayloadType = "RYNTH_GAME_ITEM";
|
||||
|
||||
private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202;
|
||||
private const int MK_LBUTTON = 0x0001, MK_OTHER = 0x0002 | 0x0010 | 0x0020 | 0x0040;
|
||||
/// <summary>Movement (px, squared) before a game press counts as a drag.</summary>
|
||||
private const int DragThresholdSq = 5 * 5;
|
||||
/// <summary>AC may select the pressed item a few messages after the press: keep re-reading it this long.</summary>
|
||||
private static readonly long SelectionSettleTicks = Stopwatch.Frequency / 2;
|
||||
/// <summary>A pop-out drag with no report for this long is over (the pop-out closed mid-drag).</summary>
|
||||
private static readonly long PopOutStaleTicks = Stopwatch.Frequency;
|
||||
|
||||
// Popped-out Inventory drag.
|
||||
private static uint _popOutItem;
|
||||
private static long _popOutSeenAt;
|
||||
|
||||
// Native (AC inventory) drag.
|
||||
private static bool _pressPending;
|
||||
private static IntPtr _pressLParam;
|
||||
private static int _pressX, _pressY;
|
||||
private static long _pressAt;
|
||||
private static uint _nativeItem;
|
||||
/// <summary>_nativeItem came from AC's drag start (DragDropHooks), not from the selection.</summary>
|
||||
private static bool _nativeFromHook;
|
||||
/// <summary>The left button is down on a press that belongs to the game.</summary>
|
||||
private static bool _gamePressHeld;
|
||||
private static bool _nativeReleased;
|
||||
/// <summary>The cursor was over an ImGui window in the last main frame (only tracked during a native drag).</summary>
|
||||
private static bool _overImGui;
|
||||
|
||||
// ── Popped-out Inventory ────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A popped-out Inventory is dragging <paramref name="itemId"/> (call every pop-out frame of the drag).</summary>
|
||||
public static void NotePopOutDrag(uint itemId)
|
||||
{
|
||||
if (itemId == 0) return;
|
||||
if (_popOutItem != itemId)
|
||||
RynthLog.UI($"ItemDragBridge: pop-out drag 0x{itemId:X8} published to the client.");
|
||||
_popOutItem = itemId;
|
||||
_popOutSeenAt = Stopwatch.GetTimestamp();
|
||||
}
|
||||
|
||||
/// <summary>The popped-out Inventory's drag ended (dropped or cancelled).</summary>
|
||||
public static void EndPopOutDrag() => _popOutItem = 0;
|
||||
|
||||
// ── Native drag (game WndProc) ──────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Every game-window mouse message, after the backend decided who owns the held buttons.
|
||||
/// <paramref name="gameOwned"/>: the current press began on the game, not on ImGui.
|
||||
/// </summary>
|
||||
public static void OnGameMouse(uint msg, IntPtr wParam, IntPtr lParam, bool gameOwned)
|
||||
{
|
||||
int keys = (int)((long)wParam & 0xFFFF);
|
||||
switch (msg)
|
||||
{
|
||||
case WM_LBUTTONDOWN:
|
||||
// Only a plain left press that belongs to the game can be an inventory drag.
|
||||
_pressPending = gameOwned && (keys & MK_OTHER) == 0;
|
||||
_pressLParam = lParam;
|
||||
_pressX = LoWord(lParam);
|
||||
_pressY = HiWord(lParam);
|
||||
_pressAt = Stopwatch.GetTimestamp();
|
||||
_gamePressHeld = _pressPending;
|
||||
if (_pressPending) { _nativeItem = 0; _nativeFromHook = false; _nativeReleased = false; }
|
||||
break;
|
||||
|
||||
case WM_MOUSEMOVE:
|
||||
if ((keys & MK_LBUTTON) == 0)
|
||||
{
|
||||
// A release we never saw (outside the window): finish the drag.
|
||||
_pressPending = false;
|
||||
_gamePressHeld = false;
|
||||
if (_nativeItem != 0) _nativeReleased = true;
|
||||
break;
|
||||
}
|
||||
if (_pressPending)
|
||||
{
|
||||
int dx = LoWord(lParam) - _pressX, dy = HiWord(lParam) - _pressY;
|
||||
if (dx * dx + dy * dy >= DragThresholdSq)
|
||||
{
|
||||
_pressPending = false;
|
||||
// With the drag-start hook the real item arrives through OnNativeDragStart.
|
||||
if (_nativeItem == 0 && !DragDropHooks.IsInstalled)
|
||||
{
|
||||
_nativeItem = CarriedSelection();
|
||||
if (_nativeItem != 0)
|
||||
RynthLog.UI($"ItemDragBridge: native inventory drag 0x{_nativeItem:X8} (from the selection) published to ImGui.");
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (_nativeItem != 0 && !_nativeFromHook && !_nativeReleased && Stopwatch.GetTimestamp() - _pressAt < SelectionSettleTicks)
|
||||
{
|
||||
// The selection can trail the press by a few messages: follow it while it settles.
|
||||
uint sel = CarriedSelection();
|
||||
if (sel != 0) _nativeItem = sel;
|
||||
}
|
||||
break;
|
||||
|
||||
case WM_LBUTTONUP:
|
||||
_pressPending = false;
|
||||
_gamePressHeld = false;
|
||||
if (_nativeItem != 0) _nativeReleased = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AC started dragging <paramref name="itemId"/> (DragDropHooks, AC's main thread). Taken while
|
||||
/// a game-owned left press is held and only for items the player carries.
|
||||
/// </summary>
|
||||
public static void OnNativeDragStart(uint itemId)
|
||||
{
|
||||
if (!_gamePressHeld || itemId == 0 || !IsCarried(itemId)) return;
|
||||
_pressPending = false;
|
||||
_nativeItem = itemId;
|
||||
_nativeFromHook = true;
|
||||
_nativeReleased = false;
|
||||
RynthLog.UI($"ItemDragBridge: native inventory drag 0x{itemId:X8} published to ImGui.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A native item drag is being released over an ImGui window: returns the press position
|
||||
/// to send AC instead, so AC puts the item back rather than dropping it on the ground.
|
||||
/// </summary>
|
||||
public static bool TryRedirectNativeDrop(uint msg, out IntPtr pressLParam)
|
||||
{
|
||||
pressLParam = _pressLParam;
|
||||
if (msg != WM_LBUTTONUP || _nativeItem == 0 || !_overImGui) return false;
|
||||
RynthLog.UI($"ItemDragBridge: native drag 0x{_nativeItem:X8} released over an ImGui window; AC gets the drop back at its start ({_pressX},{_pressY}).");
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Main frame (after ImGui.NewFrame, before any window) ────────────────
|
||||
|
||||
/// <summary>Republishes a pop-out or native drag in the main context for this frame.</summary>
|
||||
public static void SubmitMainFrame(ImGuiIOPtr io)
|
||||
{
|
||||
uint id = 0;
|
||||
string type = PayloadType;
|
||||
if (_popOutItem != 0)
|
||||
{
|
||||
if (Stopwatch.GetTimestamp() - _popOutSeenAt > PopOutStaleTicks) _popOutItem = 0;
|
||||
else id = _popOutItem;
|
||||
}
|
||||
|
||||
if (id == 0 && _nativeItem != 0)
|
||||
{
|
||||
type = _nativeFromHook ? PayloadType : NativePayloadType;
|
||||
// After the button-up, stop once ImGui itself sees the button up: that frame
|
||||
// delivers the drop (the payload outlives its last submission by one frame).
|
||||
if (_nativeReleased && !io.MouseDown[0])
|
||||
{
|
||||
_nativeItem = 0;
|
||||
_nativeFromHook = false;
|
||||
_nativeReleased = false;
|
||||
_overImGui = false;
|
||||
return;
|
||||
}
|
||||
id = _nativeItem;
|
||||
_overImGui = ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow | ImGuiHoveredFlags.AllowWhenBlockedByActiveItem);
|
||||
}
|
||||
|
||||
if (id == 0) return;
|
||||
const ImGuiDragDropFlags flags = ImGuiDragDropFlags.SourceExtern | ImGuiDragDropFlags.SourceNoPreviewTooltip
|
||||
| ImGuiDragDropFlags.PayloadAutoExpire;
|
||||
if (ImGuiNET.ImGui.BeginDragDropSource(flags))
|
||||
{
|
||||
ImGuiNET.ImGui.SetDragDropPayload(type, (IntPtr)(&id), sizeof(uint));
|
||||
ImGuiNET.ImGui.EndDragDropSource();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forget every drag (focus lost, logout, engine shutdown).</summary>
|
||||
public static void Reset()
|
||||
{
|
||||
_popOutItem = 0;
|
||||
_pressPending = false;
|
||||
_gamePressHeld = false;
|
||||
_nativeItem = 0;
|
||||
_nativeFromHook = false;
|
||||
_nativeReleased = false;
|
||||
_overImGui = false;
|
||||
}
|
||||
|
||||
/// <summary>The game's selected object when the player carries it, else 0.</summary>
|
||||
private static uint CarriedSelection()
|
||||
{
|
||||
uint id = ClientHelperHooks.GetSelectedItemId();
|
||||
return IsCarried(id) ? id : 0;
|
||||
}
|
||||
|
||||
/// <summary><paramref name="id"/> is in the player's pack, a side pack, or worn.</summary>
|
||||
private static bool IsCarried(uint id)
|
||||
{
|
||||
if (id == 0 || !ClientHelperHooks.HasGetPlayerId) return false;
|
||||
uint player = ClientHelperHooks.GetPlayerId();
|
||||
if (player == 0 || id == player) return false;
|
||||
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _)) return false;
|
||||
if (wielder == player || container == player) return true;
|
||||
// Side pack in the main pack.
|
||||
return container != 0 && ClientObjectHooks.TryGetObjectOwnershipInfo(container, out uint outer, out _, out _) && outer == player;
|
||||
}
|
||||
|
||||
private static int LoWord(IntPtr l) => unchecked((short)((long)l & 0xFFFF));
|
||||
private static int HiWord(IntPtr l) => unchecked((short)(((long)l >> 16) & 0xFFFF));
|
||||
}
|
||||
76
src/RynthCore.Engine/ImGui/MonsterHud/CleaveHealth.cs
Normal file
76
src/RynthCore.Engine/ImGui/MonsterHud/CleaveHealth.cs
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/MonsterHud/CleaveHealth.cs
|
||||
// Health for monsters the player hits but the server doesn't stream health
|
||||
// for (2026-10-12, Drakkon with a Tetsubo: "the HUD health for monsters only
|
||||
// changes if they are targeted. It doesn't change for AoE monsters").
|
||||
//
|
||||
// ACE pushes UpdateHealth (0x01C0) only for the object a player has selected
|
||||
// or queried (RynthAi queries its combat target), so the second and third mob
|
||||
// a cleave hits kept their old bar. Every hit does send an AttackerNotification
|
||||
// (0x01B1) naming the monster - no id - with the damage and its share of the
|
||||
// monster's max health (damage / max: 204 on an Olthoi Slasher's 2300 reads
|
||||
// 0.089). This turns that share into a bar estimate on the plate it belongs
|
||||
// to. Pure: no engine state; MonsterHud passes the candidates in.
|
||||
//
|
||||
// Rules, for the plates carrying the hit's name:
|
||||
// * one whose real (server) health dropped by this share around the hit
|
||||
// already got it from 0x01C0: nothing to do;
|
||||
// * a plate with a live server feed (a real update in the last
|
||||
// LiveFeedSec) is left to the server;
|
||||
// * otherwise the nearest one takes the share off its last ratio (full when
|
||||
// never seen), never below MinRatio - a kill comes from the kill message
|
||||
// and the object's deletion, not from an estimate.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Hud;
|
||||
|
||||
internal static class CleaveHealth
|
||||
{
|
||||
/// <summary>A real update this close to the hit (s) with the same drop is the same hit.</summary>
|
||||
public const double SameHitSec = 0.6;
|
||||
/// <summary>Drop-vs-share tolerance for "the same hit".</summary>
|
||||
public const float MatchTolerance = 0.006f; // both sides are the server's exact numbers; a different hit is rarely this close
|
||||
/// <summary>A real update this recent (s) means the server is feeding this plate.</summary>
|
||||
public const double LiveFeedSec = 1.5;
|
||||
/// <summary>An estimate never takes a bar lower than this.</summary>
|
||||
public const float MinRatio = 0.01f;
|
||||
|
||||
/// <summary>One plate with the hit's name. <paramref name="ObsAgeSec"/>: seconds between its
|
||||
/// last health observation and the hit (negative = the observation came after it).</summary>
|
||||
public readonly record struct Candidate(uint Id, float Distance, bool HasObs, float Ratio, float Prev, bool Estimated, double ObsAgeSec);
|
||||
|
||||
/// <summary>
|
||||
/// The plate a hit of <paramref name="share"/> (damage / max health) belongs to and its new
|
||||
/// ratio, or 0 when no plate should change.
|
||||
/// </summary>
|
||||
public static uint Pick(ReadOnlySpan<Candidate> candidates, float share, out float newRatio)
|
||||
{
|
||||
newRatio = 0f;
|
||||
if (candidates.Length == 0 || !(share > 0f) || share > 1.5f) return 0;
|
||||
|
||||
foreach (Candidate c in candidates)
|
||||
{
|
||||
if (!c.HasObs || c.Estimated || c.Prev < 0f) continue;
|
||||
if (Math.Abs(c.ObsAgeSec) <= SameHitSec && Math.Abs((c.Prev - c.Ratio) - share) <= MatchTolerance)
|
||||
return 0; // the server reported this hit itself
|
||||
}
|
||||
|
||||
uint best = 0;
|
||||
float bestD = float.MaxValue, bestRatio = 1f;
|
||||
foreach (Candidate c in candidates)
|
||||
{
|
||||
if (c.HasObs && !c.Estimated && c.ObsAgeSec >= -SameHitSec && c.ObsAgeSec <= LiveFeedSec) continue; // server-fed
|
||||
if (c.Distance < bestD)
|
||||
{
|
||||
best = c.Id;
|
||||
bestD = c.Distance;
|
||||
bestRatio = c.HasObs ? c.Ratio : 1f;
|
||||
}
|
||||
}
|
||||
if (best == 0) return 0;
|
||||
newRatio = Math.Max(MinRatio, bestRatio - share);
|
||||
return best;
|
||||
}
|
||||
}
|
||||
|
|
@ -102,10 +102,16 @@ internal static class HudFeed
|
|||
catch (Exception ex) { Log("delete", ex); }
|
||||
}
|
||||
|
||||
public static void OnDamageEvent(bool attacker, string? name, uint damage, bool crit)
|
||||
/// <summary><paramref name="share"/>: the hit's damage / the monster's max health (AttackerNotification), 0 = unknown.</summary>
|
||||
public static void OnDamageEvent(bool attacker, string? name, uint damage, bool crit, double share = 0)
|
||||
{
|
||||
if (!On) return;
|
||||
try { CombatText.OnDamageEvent(attacker, name, damage, crit); }
|
||||
try
|
||||
{
|
||||
CombatText.OnDamageEvent(attacker, name, damage, crit);
|
||||
if (attacker && share > 0 && MonsterHudSettings.Enabled && !string.IsNullOrEmpty(name))
|
||||
MonsterHud.NoteDealtHit(name, damage, share);
|
||||
}
|
||||
catch (Exception ex) { Log("damage", ex); }
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -298,6 +298,7 @@ internal static class MonsterHud
|
|||
CombatText.PollGains(_playerId);
|
||||
if (track) Snapshot(now, trackMonsters);
|
||||
}
|
||||
if (monsters) ApplyDealtHits(now);
|
||||
|
||||
_hasContent = Plates.Count > 0 || MonsterHudSettings.SelfPlate || CombatText.HasContent;
|
||||
}
|
||||
|
|
@ -1564,6 +1565,66 @@ internal static class MonsterHud
|
|||
/// The plate whose monster has <paramref name="name"/>: the selected one first,
|
||||
/// then the one the player hit most recently, then the nearest. 0 if none.
|
||||
/// </summary>
|
||||
// ── Hits on monsters with no health feed (CleaveHealth) ─────────────
|
||||
private readonly record struct DealtHit(string Name, float Share, long Ticks);
|
||||
private static readonly object HitSync = new();
|
||||
private static readonly List<DealtHit> PendingHits = new();
|
||||
private static readonly List<DealtHit> HitWork = new();
|
||||
private static string? _lastHitName;
|
||||
private static uint _lastHitDamage;
|
||||
private static long _lastHitTicks;
|
||||
private const int MaxPendingHits = 64;
|
||||
/// <summary>A hit waits this long (s) so the server's own UpdateHealth for it (the queried
|
||||
/// target's) is in before the plates are matched.</summary>
|
||||
private const double HitSettleSec = 0.25;
|
||||
|
||||
/// <summary>AttackerNotification: the player hit <paramref name="name"/> for
|
||||
/// <paramref name="share"/> of its max health. AC's main thread (SmartBoxHooks, two paths per
|
||||
/// event - the same hit inside 50 ms counts once).</summary>
|
||||
internal static void NoteDealtHit(string name, uint damage, double share)
|
||||
{
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
lock (HitSync)
|
||||
{
|
||||
if (damage == _lastHitDamage && name == _lastHitName && now - _lastHitTicks < Stopwatch.Frequency / 20) return;
|
||||
_lastHitName = name; _lastHitDamage = damage; _lastHitTicks = now;
|
||||
if (PendingHits.Count >= MaxPendingHits) PendingHits.RemoveAt(0);
|
||||
PendingHits.Add(new DealtHit(name, (float)share, now));
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly List<CleaveHealth.Candidate> HitCandidates = new();
|
||||
|
||||
/// <summary>Settled hits onto the plates of monsters the server isn't feeding health for.</summary>
|
||||
private static void ApplyDealtHits(long now)
|
||||
{
|
||||
HitWork.Clear();
|
||||
lock (HitSync)
|
||||
{
|
||||
if (PendingHits.Count == 0) return;
|
||||
long settle = (long)(HitSettleSec * Stopwatch.Frequency);
|
||||
int n = 0;
|
||||
while (n < PendingHits.Count && now - PendingHits[n].Ticks >= settle) n++;
|
||||
if (n == 0) return;
|
||||
HitWork.AddRange(PendingHits.GetRange(0, n));
|
||||
PendingHits.RemoveRange(0, n);
|
||||
}
|
||||
double freq = Stopwatch.Frequency;
|
||||
foreach (DealtHit hit in HitWork)
|
||||
{
|
||||
HitCandidates.Clear();
|
||||
foreach (Plate p in Plates.Values)
|
||||
{
|
||||
if (p.Gone || p.IsLabel || !p.Name.Equals(hit.Name, StringComparison.Ordinal)) continue;
|
||||
bool has = MonsterHudData.TryGetHealth(p.Id, out HealthObservation h);
|
||||
HitCandidates.Add(new CleaveHealth.Candidate(p.Id, p.Distance, has, has ? h.Ratio : 1f, has ? h.Prev : -1f,
|
||||
has && h.Estimated, has ? (hit.Ticks - h.Ticks) / freq : 0));
|
||||
}
|
||||
uint id = CleaveHealth.Pick(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(HitCandidates), hit.Share, out float ratio);
|
||||
if (id != 0) MonsterHudData.RecordHealth(id, ratio, 0, 0, estimated: true);
|
||||
}
|
||||
}
|
||||
|
||||
internal static uint FindPlateByName(string name)
|
||||
{
|
||||
uint target = ClientHelperHooks.GetSelectedItemId();
|
||||
|
|
|
|||
|
|
@ -22,8 +22,9 @@ using System.Diagnostics;
|
|||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Hud;
|
||||
|
||||
/// <summary>Last health observation for one object.</summary>
|
||||
internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks);
|
||||
/// <summary>Last health observation for one object. <paramref name="Prev"/>: the ratio before it
|
||||
/// (-1 = first). <paramref name="Estimated"/>: worked out from a hit (CleaveHealth), not sent by the server.</summary>
|
||||
internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks, float Prev = -1f, bool Estimated = false);
|
||||
|
||||
internal static class MonsterHudData
|
||||
{
|
||||
|
|
@ -36,17 +37,20 @@ internal static class MonsterHudData
|
|||
/// <summary>
|
||||
/// A health update for <paramref name="id"/>. A max of 0 (ratio-only update)
|
||||
/// keeps the last known max. Any thread; never blocks for long.
|
||||
/// <paramref name="estimated"/>: from a hit's share of max health (CleaveHealth), not the server.
|
||||
/// </summary>
|
||||
public static void RecordHealth(uint id, float ratio, uint current, uint max)
|
||||
public static void RecordHealth(uint id, float ratio, uint current, uint max, bool estimated = false)
|
||||
{
|
||||
if (id == 0 || float.IsNaN(ratio)) return;
|
||||
ratio = Math.Clamp(ratio, 0f, 1f);
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
float before = -1f;
|
||||
bool prevWasEstimate = false;
|
||||
lock (Sync)
|
||||
{
|
||||
bool had = Health.TryGetValue(id, out HealthObservation prev);
|
||||
if (had) before = prev.Ratio;
|
||||
prevWasEstimate = had && prev.Estimated;
|
||||
if (max == 0 && had && prev.Max > 0)
|
||||
{
|
||||
max = prev.Max;
|
||||
|
|
@ -54,10 +58,13 @@ internal static class MonsterHudData
|
|||
}
|
||||
if (Health.Count >= MaxHealthEntries && !Health.ContainsKey(id))
|
||||
Health.Clear();
|
||||
Health[id] = new HealthObservation(ratio, current, max, now);
|
||||
Health[id] = new HealthObservation(ratio, current, max, now, before, estimated);
|
||||
}
|
||||
// An estimate never kills (CleaveHealth keeps it above 0) and the server correcting one
|
||||
// isn't a heal: the combat text sees an estimate's successor as a first observation.
|
||||
if (estimated) return;
|
||||
// Kills and heals for the combat text; a death also drops the monster's debuffs.
|
||||
HudFeed.OnHealth(id, before, ratio, max);
|
||||
HudFeed.OnHealth(id, prevWasEstimate ? -1f : before, ratio, max);
|
||||
}
|
||||
|
||||
public static bool TryGetHealth(uint id, out HealthObservation h)
|
||||
|
|
|
|||
401
src/RynthCore.Engine/ImGui/Panels/CharactersFace.cs
Normal file
401
src/RynthCore.Engine/ImGui/Panels/CharactersFace.cs
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/CharactersFace.cs
|
||||
// The Characters panel: your other characters (the other RynthCore clients on
|
||||
// this PC, through the RynthNet plugin), like UtilityBelt's networked
|
||||
// character window. Engine only, ImGui only.
|
||||
//
|
||||
// top how many, or why none (RynthNet missing / offline); "all
|
||||
// follow me"; the help mark
|
||||
// rows this client first (dimmed), then the others alphabetically (a
|
||||
// stable order: characters standing together would reshuffle
|
||||
// several times a second if sorted by distance). Each row:
|
||||
// line 1 direction arrow (relative to where you face), name
|
||||
// (+ server when it isn't yours), state (botting / idle /
|
||||
// dead / portal space / combat stance), a stale marker,
|
||||
// distance and compass point
|
||||
// line 2 health / stamina / mana bars with current/max, and
|
||||
// where they are (map coordinates or dungeon name)
|
||||
// click selects the character in game when this client can see it;
|
||||
// right follow me / stop following / start or stop the macro on that
|
||||
// client (sent as /rn tell; its RynthNet command policy decides)
|
||||
//
|
||||
// Data: UiSources.Characters (UI/Data/CharactersData.cs, 2 Hz while open).
|
||||
// Follows the panel text size (PanelTextScale): layout scales with the font.
|
||||
// AC's render thread; no AC calls, no per-frame allocation except a hovered
|
||||
// row's tooltip and the popup's labels.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.UI;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class CharactersFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Characters";
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(420, 260), new Vector2(280, 140), EdgeToEdge: true, GripInBody: true),
|
||||
() => new CharactersFace());
|
||||
}
|
||||
|
||||
// ── Palette (the RynthAi dashboard's vitals colours) ─────────────────
|
||||
private static uint C(uint argb) => RynthTheme.Argb(argb);
|
||||
private static readonly uint HpCol = C(0xFFD93333), StCol = C(0xFF40D973), MpCol = C(0xFF268CF2),
|
||||
BarBg = C(0xFF0D161F), Purple = C(0xFFBF4DFF), White = C(0xFFFFFFFF);
|
||||
|
||||
private const string HelpText =
|
||||
"Your other characters: every RynthCore client on this PC running the RynthNet plugin.\n\n" +
|
||||
"Each row shows health, stamina and mana, what the character is doing, and where it is. " +
|
||||
"The distance and direction show when you are both outdoors (or in surface buildings), or in the same dungeon; " +
|
||||
"otherwise the row says elsewhere and names the dungeon or gives map coordinates. Characters on another server " +
|
||||
"only show their server.\n\n" +
|
||||
"Rows stay in alphabetical order. A row that stops updating says so (its client may be frozen).\n\n" +
|
||||
"Click a row to select that character in game (when this client can see it). Right-click for commands: " +
|
||||
"follow me, stop following, start or stop the macro. They go through RynthNet, so the other client's " +
|
||||
"remote command setting (/rn remote) decides whether they run.\n\n" +
|
||||
"/rc characters opens and closes this panel.";
|
||||
|
||||
private float _k = 1f;
|
||||
private float Px(float v) => v * _k;
|
||||
|
||||
// The right-clicked row (copied: the snapshot can change while the popup is open).
|
||||
private string _menuName = "";
|
||||
private uint _menuId;
|
||||
private bool _menuInView, _menuOtherWorld, _menuSelf, _menuLoggedOut;
|
||||
private bool _openMenu;
|
||||
|
||||
public int PopOutIdleHz => 10; // the arrows turn with you
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.Characters.Subscribe();
|
||||
UiSources.Characters.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden() => UiSources.Characters.Unsubscribe();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
_k = PanelTextScale.Factor(ImGuiFonts.CurrentStep);
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
CharactersView view = UiSources.Characters.Current?.Value ?? CharactersView.Empty;
|
||||
DrawTop(view, w);
|
||||
|
||||
float bodyH = Math.Max(Px(30), Remaining(origin, size) - GripOverlap());
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
|
||||
ImGuiNET.ImGui.BeginChild("##chars_rows", new Vector2(w, bodyH));
|
||||
DrawRows(view);
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
End(origin, size);
|
||||
|
||||
DrawMenu(view);
|
||||
}
|
||||
|
||||
// ── Top line ────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawTop(CharactersView view, float w)
|
||||
{
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float h = Px(20), iconW = Px(22);
|
||||
float fontH = ImGuiNET.ImGui.GetFontSize();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float textW = Math.Max(10, w - 2 * iconW - Px(8));
|
||||
dl.PushClipRect(start, start + new Vector2(textW, h), true);
|
||||
dl.AddText(new Vector2(start.X, start.Y + (h - fontH) * 0.5f), view.NetLoaded ? Mute : Amber,
|
||||
view.Status.Length > 0 ? view.Status : "Waiting for RynthNet...");
|
||||
dl.PopClipRect();
|
||||
|
||||
float bx = start.X + w - 2 * iconW - Px(4);
|
||||
bool canFollow = view.NetLoaded && view.MyName.Length > 0;
|
||||
if (IconButton("##chars_followall", PhosphorIcons.Footprints, new Vector2(bx, start.Y), new Vector2(iconW, h), Text, BtnFill,
|
||||
enabled: canFollow, font: UiFont.Ui11))
|
||||
CharactersCommands.FollowMeAll();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Everyone follow me (/rn followme): every other client runs /ra follow <you>.");
|
||||
IconButton("##chars_help", PhosphorIcons.Info, new Vector2(bx + iconW + Px(4), start.Y), new Vector2(iconW, h), Mute, BtnFill,
|
||||
font: UiFont.Ui11);
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
{
|
||||
ImGuiNET.ImGui.BeginTooltip();
|
||||
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetFontSize() * 30);
|
||||
ImGuiNET.ImGui.TextUnformatted(HelpText);
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
ImGuiNET.ImGui.EndTooltip();
|
||||
}
|
||||
NextLine(start, h + Px(4));
|
||||
}
|
||||
|
||||
// ── Rows ────────────────────────────────────────────────────────────
|
||||
|
||||
private float RowH => Px(38);
|
||||
|
||||
private void DrawRows(CharactersView view)
|
||||
{
|
||||
CharacterRow[] rows = view.Rows;
|
||||
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
if (rows.Length == 0)
|
||||
{
|
||||
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(Px(6), Px(6));
|
||||
dl.AddText(at, Faded(Mute), view.NetLoaded ? "Not in the world." : "");
|
||||
return;
|
||||
}
|
||||
|
||||
uint selected = ClientHelperHooks.GetSelectedItemId();
|
||||
float heading = PlayerHeading(out bool haveHeading);
|
||||
float rowH = RowH;
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
int hovered = -1;
|
||||
|
||||
for (int i = 0; i < rows.Length; i++)
|
||||
{
|
||||
CharacterRow r = rows[i];
|
||||
var p = new Vector2(start.X, start.Y + i * rowH);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(bw, rowH),
|
||||
ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
bool right = clicked && ImGuiNET.ImGui.IsMouseReleased(ImGuiMouseButton.Right);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
if (hot) hovered = i;
|
||||
if (clicked && !right && r.InView && r.Id != 0 && !r.IsSelf)
|
||||
AcMainThreadQueue.EnqueueOverlaySelect(r.Id);
|
||||
if (right) OpenMenu(r);
|
||||
|
||||
DrawRow(dl, r, p, bw, rowH, i, hot, r.Id != 0 && r.Id == selected, heading, haveHeading);
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(start);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(bw, rows.Length * rowH));
|
||||
|
||||
if (hovered >= 0 && rows[hovered].Tooltip.Length > 0 && !ImGuiNET.ImGui.IsPopupOpen("##chars_menu"))
|
||||
{
|
||||
ImGuiNET.ImGui.BeginTooltip();
|
||||
ImGuiNET.ImGui.TextUnformatted(rows[hovered].Tooltip);
|
||||
ImGuiNET.ImGui.EndTooltip();
|
||||
}
|
||||
}
|
||||
|
||||
private void DrawRow(ImDrawListPtr dl, CharacterRow r, Vector2 p, float bw, float rowH, int index, bool hot, bool isSel,
|
||||
float heading, bool haveHeading)
|
||||
{
|
||||
uint bg = isSel ? Selected : hot ? Lighten(PanelBg) : (index & 1) == 1 ? RowAlt : 0;
|
||||
if (bg != 0) dl.AddRectFilled(p, p + new Vector2(bw, rowH), bg);
|
||||
if (isSel) dl.AddRect(p, p + new Vector2(bw, rowH), Teal);
|
||||
// This client's row is dimmed: it's here for comparison.
|
||||
float dim = r.IsSelf || r.LoggedOut ? 0.55f : 1f;
|
||||
|
||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11), f10 = ImGuiFonts.Get(UiFont.Ui10);
|
||||
float arrowW = Px(20), pad = Px(4);
|
||||
float line1 = p.Y + Px(3);
|
||||
float x = p.X + arrowW;
|
||||
float right = p.X + bw - pad;
|
||||
|
||||
// Arrow / dot / ring.
|
||||
var mid = new Vector2(p.X + arrowW * 0.5f, line1 + bold.FontSize * 0.5f + Px(1));
|
||||
uint arrowCol = Fade(StateColor(r), dim);
|
||||
if (!r.IsSelf && r.Measured && haveHeading && !float.IsNaN(r.Bearing))
|
||||
DrawArrow(dl, mid, r.Bearing - heading, arrowCol, _k);
|
||||
else if (r.IsSelf || r.Measured)
|
||||
dl.AddCircleFilled(mid, Px(2.5f), arrowCol);
|
||||
else
|
||||
dl.AddCircle(mid, Px(3.5f), Faded(Mute), 12, Px(1.2f));
|
||||
|
||||
// Right side of line 1: distance + compass (or "elsewhere").
|
||||
string dist = r.IsSelf ? "" : r.Measured ? r.DistanceText + (r.Compass.Length > 0 ? " " + r.Compass : "") : r.DistanceText;
|
||||
float distW = dist.Length > 0 ? ImGuiNET.ImGui.CalcTextSize(dist).X : 0;
|
||||
if (dist.Length > 0)
|
||||
dl.AddText(new Vector2(right - distW, line1 + (bold.FontSize - ImGuiNET.ImGui.GetFontSize()) * 0.5f),
|
||||
Fade(r.Measured ? Text : Faded(Mute), dim), dist);
|
||||
float limit = right - distW - (distW > 0 ? Px(8) : 0);
|
||||
|
||||
// Name (+ server), then state and the stale marker.
|
||||
float nameW = Math.Min(CalcW(bold, r.Name), Math.Max(Px(40), (limit - x) * 0.55f));
|
||||
Clip(dl, bold, r.Name, x, line1, nameW, Fade(r.IsSelf ? Mute : Text, dim));
|
||||
float sx = x + nameW + Px(6);
|
||||
if (r.OtherWorld.Length > 0)
|
||||
{
|
||||
string wtext = "[" + r.OtherWorld + "]";
|
||||
float ww = Math.Min(CalcW(f10, wtext), Math.Max(0, limit - sx));
|
||||
Clip(dl, f10, wtext, sx, line1 + Px(1), ww, Fade(Amber, dim));
|
||||
sx += ww + Px(6);
|
||||
}
|
||||
if (r.StateText.Length > 0 && sx < limit)
|
||||
{
|
||||
float tw = Math.Min(CalcW(f10, r.StateText), limit - sx);
|
||||
Clip(dl, f10, r.StateText, sx, line1 + Px(1), tw, Fade(StateColor(r), dim));
|
||||
sx += tw + Px(6);
|
||||
}
|
||||
if (r.Stale && sx < limit)
|
||||
{
|
||||
string st = PhosphorIcons.Warning + " " + r.StaleText;
|
||||
Clip(dl, f10, st, sx, line1 + Px(1), limit - sx, Amber);
|
||||
}
|
||||
|
||||
// Line 2: bars, then the location.
|
||||
float line2 = line1 + bold.FontSize + Px(4);
|
||||
float barH = Px(13);
|
||||
float locW = r.Location.Length > 0 ? Math.Min(CalcW(f10, r.Location), Math.Max(Px(70), bw * 0.32f)) : 0;
|
||||
float barsW = right - x - (locW > 0 ? locW + Px(8) : 0);
|
||||
if (barsW < Px(150)) { barsW = right - x; locW = 0; } // narrow: bars first, the tooltip has the place
|
||||
if (r.HasVitals)
|
||||
{
|
||||
float gap = Px(3);
|
||||
float one = (barsW - 2 * gap) / 3f;
|
||||
Bar(dl, x, line2, one, barH, r.Hp, HpCol, f10, dim);
|
||||
Bar(dl, x + one + gap, line2, one, barH, r.St, StCol, f10, dim);
|
||||
Bar(dl, x + 2 * (one + gap), line2, one, barH, r.Mp, MpCol, f10, dim);
|
||||
}
|
||||
else if (!r.LoggedOut)
|
||||
{
|
||||
Clip(dl, f10, "no vitals yet", x, line2, barsW, Faded(Mute));
|
||||
}
|
||||
if (locW > 0)
|
||||
Clip(dl, f10, r.Location, right - locW, line2 + (barH - f10.FontSize) * 0.5f, locW, Fade(Mute, dim));
|
||||
}
|
||||
|
||||
private void Bar(ImDrawListPtr dl, float x, float y, float w, float h, CharVital v, uint color, ImFontPtr font, float dim)
|
||||
{
|
||||
if (w <= 2) return;
|
||||
var a = new Vector2(x, y);
|
||||
var b = new Vector2(x + w, y + h);
|
||||
float round = Px(3);
|
||||
dl.AddRectFilled(a, b, BarBg, round);
|
||||
if (v.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * v.Fraction, b.Y), Fade(color, dim), round);
|
||||
float tw = CalcW(font, v.Text);
|
||||
float tx = x + Math.Max(Px(3), (w - tw) * 0.5f);
|
||||
dl.PushClipRect(a, b, true);
|
||||
dl.AddText(font, font.FontSize, new Vector2(tx, y + (h - font.FontSize) * 0.5f), Fade(White, dim), v.Text);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
|
||||
private static uint StateColor(CharacterRow r) => r.StateKind switch
|
||||
{
|
||||
_ when r.IsSelf => Mute,
|
||||
CharStateKind.Dead => Red,
|
||||
CharStateKind.Fighting => Amber,
|
||||
CharStateKind.Botting => Green,
|
||||
CharStateKind.Portal => Purple,
|
||||
CharStateKind.CombatMode => Teal,
|
||||
CharStateKind.NoStatus or CharStateKind.LoggedOut => Faded(Mute),
|
||||
_ => Mute,
|
||||
};
|
||||
|
||||
private static float CalcW(ImFontPtr font, string text) =>
|
||||
text.Length == 0 ? 0 : font.CalcTextSizeA(font.FontSize, float.MaxValue, 0f, text).X;
|
||||
|
||||
private static void Clip(ImDrawListPtr dl, ImFontPtr font, string text, float x, float y, float width, uint color)
|
||||
{
|
||||
if (text.Length == 0 || width <= 0) return;
|
||||
dl.PushClipRect(new Vector2(x, y - 2), new Vector2(x + width, y + font.FontSize + 4), true);
|
||||
dl.AddText(font, font.FontSize, new Vector2(x, y), color, text);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
|
||||
private static uint Fade(uint abgr, float k)
|
||||
{
|
||||
if (k >= 1f) return abgr;
|
||||
uint a = (uint)Math.Clamp((int)(((abgr >> 24) & 0xFF) * k), 0, 255);
|
||||
return (abgr & 0x00FFFFFF) | (a << 24);
|
||||
}
|
||||
|
||||
/// <summary>An arrow pointing <paramref name="degrees"/> clockwise from straight up (up = the way you face).</summary>
|
||||
private static void DrawArrow(ImDrawListPtr dl, Vector2 c, float degrees, uint color, float k)
|
||||
{
|
||||
float rad = degrees * (MathF.PI / 180f);
|
||||
float s = MathF.Sin(rad), co = MathF.Cos(rad);
|
||||
Vector2 tip = Rot(c, 0, -6.5f * k, s, co), left = Rot(c, -4.5f * k, 5f * k, s, co),
|
||||
notch = Rot(c, 0, 2.5f * k, s, co), rgt = Rot(c, 4.5f * k, 5f * k, s, co);
|
||||
dl.AddTriangleFilled(tip, left, notch, color);
|
||||
dl.AddTriangleFilled(tip, notch, rgt, color);
|
||||
}
|
||||
|
||||
private static Vector2 Rot(Vector2 c, float x, float y, float s, float co) =>
|
||||
new(c.X + x * co - y * s, c.Y + x * s + y * co);
|
||||
|
||||
/// <summary>Your heading this frame (compass degrees) from the pose snapshot; no AC call (SenseFace's way).</summary>
|
||||
private static float PlayerHeading(out bool ok)
|
||||
{
|
||||
ok = PlayerPhysicsHooks.TryGetPlayerPoseSnapshot(out _, out _, out _, out _, out float qw, out float qz,
|
||||
out bool headingValid, out float heading);
|
||||
if (!ok) return 0;
|
||||
if (headingValid) return heading;
|
||||
double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
|
||||
return (float)((-yaw % 360.0 + 720.0) % 360.0);
|
||||
}
|
||||
|
||||
// ── Right-click menu ────────────────────────────────────────────────
|
||||
|
||||
private void OpenMenu(CharacterRow r)
|
||||
{
|
||||
_menuName = r.Name;
|
||||
_menuId = r.Id;
|
||||
_menuInView = r.InView;
|
||||
_menuOtherWorld = r.OtherWorld.Length > 0;
|
||||
_menuSelf = r.IsSelf;
|
||||
_menuLoggedOut = r.LoggedOut;
|
||||
_openMenu = true;
|
||||
}
|
||||
|
||||
private void DrawMenu(CharactersView view)
|
||||
{
|
||||
if (_openMenu)
|
||||
{
|
||||
_openMenu = false;
|
||||
ImGuiNET.ImGui.OpenPopup("##chars_menu");
|
||||
}
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(6)));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup("##chars_menu");
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(3);
|
||||
if (!open) return;
|
||||
try
|
||||
{
|
||||
string me = view.MyName;
|
||||
bool canFollow = me.Length > 0;
|
||||
if (!_menuSelf && !_menuLoggedOut)
|
||||
{
|
||||
ImGuiNET.ImGui.TextDisabled(_menuName);
|
||||
if (ImGuiNET.ImGui.MenuItem("Select", "", false, _menuInView && _menuId != 0))
|
||||
AcMainThreadQueue.EnqueueOverlaySelect(_menuId);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem("Follow me", "", false, canFollow && !_menuOtherWorld))
|
||||
CharactersCommands.Tell(_menuName, "/ra follow " + me);
|
||||
ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow {me}");
|
||||
if (ImGuiNET.ImGui.MenuItem("Stop following"))
|
||||
CharactersCommands.Tell(_menuName, "/ra follow off");
|
||||
ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow off");
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem("Start macro"))
|
||||
CharactersCommands.Tell(_menuName, "/ra start");
|
||||
ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra start");
|
||||
if (ImGuiNET.ImGui.MenuItem("Stop macro"))
|
||||
CharactersCommands.Tell(_menuName, "/ra stop");
|
||||
ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra stop");
|
||||
ImGuiNET.ImGui.Separator();
|
||||
}
|
||||
if (ImGuiNET.ImGui.MenuItem("Everyone: follow me", "", false, canFollow))
|
||||
CharactersCommands.FollowMeAll();
|
||||
ImGuiNET.ImGui.SetItemTooltip("/rn followme");
|
||||
ImGuiNET.ImGui.TextDisabled("The other client's /rn remote setting decides.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -138,6 +138,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
Label("No rules yet. Click \"Add rule\", or right-click a line in the chat", Mute);
|
||||
Label("and pick \"Move them to\", \"Hide them\" or \"Colour them\".", Mute);
|
||||
}
|
||||
DrawStandardFilters(rowW);
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
|
||||
|
|
@ -181,6 +182,58 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
edit?.Invoke(); // after drawing: the rows above drew from the old list
|
||||
}
|
||||
|
||||
// ── Standard filters (RynthChatPresets) ──────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The canned filters, by group: tick to hide, or pick a tab to move the lines there.
|
||||
/// The router checks them after the rules, for lines no rule moved or hid.
|
||||
/// </summary>
|
||||
private void DrawStandardFilters(float rowW)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
|
||||
if (!ImGuiNET.ImGui.CollapsingHeader("Standard filters##std")) return;
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||
Label("Checked after the rules above, only for lines no rule moved or hid.", Mute);
|
||||
Label("Tick to hide the lines; pick a tab to move them there instead.", Mute);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
foreach (string group in UI.Panels.RynthChatPresets.Groups)
|
||||
{
|
||||
int on = 0, total = 0;
|
||||
foreach (var p in UI.Panels.RynthChatPresets.All)
|
||||
if (p.Group == group) { total++; if (p.Enabled) on++; }
|
||||
if (!ImGuiNET.ImGui.TreeNode($"{group} ({on}/{total})###grp_{group}")) continue;
|
||||
foreach (var p in UI.Panels.RynthChatPresets.All)
|
||||
{
|
||||
if (p.Group != group) continue;
|
||||
ImGuiNET.ImGui.PushID(p.Id);
|
||||
bool enabled = p.Enabled;
|
||||
if (ImGuiNET.ImGui.Checkbox(p.Label, ref enabled)) { p.Enabled = enabled; ChatModel.FiltersChanged(); }
|
||||
ImGuiNET.ImGui.SetItemTooltip(p.Description + "\nExample: " + p.Example);
|
||||
ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, rowW * 0.6f));
|
||||
string tabText = (p.Tab.Length == 0 ? "hide" : "to " + p.Tab) + Caret;
|
||||
if (ImGuiNET.ImGui.SmallButton(tabText))
|
||||
OpenPresetTabPicker(p, new Vector2(ImGuiNET.ImGui.GetItemRectMin().X, ImGuiNET.ImGui.GetItemRectMax().Y + 2));
|
||||
ImGuiNET.ImGui.SetItemTooltip("Where its lines go: hidden, or moved to a tab");
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
ImGuiNET.ImGui.TreePop();
|
||||
}
|
||||
}
|
||||
|
||||
private void OpenPresetTabPicker(UI.Panels.RynthChatPresets.Preset preset, Vector2 below)
|
||||
{
|
||||
string[] tabs = ChatModel.TargetTabs();
|
||||
var items = new string[tabs.Length + 1];
|
||||
items[0] = "Hide";
|
||||
Array.Copy(tabs, 0, items, 1, tabs.Length);
|
||||
int selected = preset.Tab.Length == 0 ? 0 : Math.Max(0, Array.FindIndex(tabs, t => string.Equals(t, preset.Tab, StringComparison.OrdinalIgnoreCase)) + 1);
|
||||
_picker.Open(below, items, selected, k =>
|
||||
{
|
||||
preset.Tab = k <= 0 ? "" : items[k];
|
||||
ChatModel.FiltersChanged();
|
||||
}, 160);
|
||||
}
|
||||
|
||||
private void Flash(string message)
|
||||
{
|
||||
_flash = message;
|
||||
|
|
@ -548,7 +601,12 @@ internal sealed class ChatFiltersFace : IImGuiPanel
|
|||
var trace = new List<ChatRouter.Step>();
|
||||
ChatRoute route = ChatModel.TestRouter().Evaluate(text, channel, type, trace);
|
||||
foreach (ChatRouter.Step step in trace)
|
||||
_testResult.Add(((step.Rule < 0 ? "Your name" : $"Rule {step.Rule + 1}") + ": " + step.What, Text));
|
||||
_testResult.Add((step.Rule switch
|
||||
{
|
||||
ChatRouter.StandardFilterStep => "Standard",
|
||||
< 0 => "Your name",
|
||||
_ => $"Rule {step.Rule + 1}",
|
||||
} + ": " + step.What, Text));
|
||||
if (trace.Count == 0) _testResult.Add(("No rule matches.", Faded(Mute)));
|
||||
|
||||
string where;
|
||||
|
|
|
|||
|
|
@ -10,8 +10,8 @@
|
|||
//
|
||||
// The mechanics live here (tabs, slide, side, placement, the one window);
|
||||
// each drawer only draws its panel (DashboardDrawer.DrawPanel) and says how
|
||||
// big it is. Drawers today: Ranges (RangesSlideOut.cs), Loaded files and
|
||||
// Patrol (RynthAiFace.Drawers.cs).
|
||||
// big it is. Drawers today: Ranges (RangesSlideOut.cs), Loaded files,
|
||||
// Patrol and Mini Remote (RynthAiFace.Drawers.cs).
|
||||
//
|
||||
// A top-level ImGui window of its own, begun from inside the dashboard's Draw
|
||||
// and placed against the dashboard's window every frame, so it follows the
|
||||
|
|
|
|||
|
|
@ -23,6 +23,28 @@
|
|||
// Settings are the engine's (dungeon_map_settings.txt beside radar_settings.txt),
|
||||
// not RynthAi's per-character Map* fields. Zoom, pan and floor picks last for the
|
||||
// session, as they did.
|
||||
//
|
||||
// RynthAi's nav route (2026-10-12; UiSources.Nav, subscribed only while the map is
|
||||
// open and its Route box is on): legs between the points (closed for Circular,
|
||||
// dashed after a Recall / Portal step, which jumps), points as dots and the other
|
||||
// step types as icon badges, the next waypoint ringed, numbers when zoomed in, a
|
||||
// tooltip on hover. A point's floor is the layer nearest its Z (nav Z * 240); points
|
||||
// on floors the map isn't showing are hidden, on shown other floors dimmed, like the
|
||||
// walls. Points outside this dungeon's floor area aren't drawn.
|
||||
//
|
||||
// "Edit route" (off by default; needs RynthAi with MapEdit >= 1):
|
||||
// - click (no drag) on a floor: add a point there (after the selected point, else
|
||||
// at the end; Z from that floor: the player's floor first, then the other shown
|
||||
// floors nearest it). Off every shown floor: refused with a status line;
|
||||
// - click a point: select / deselect it; Esc deselects;
|
||||
// - drag a point: move it (it follows the cursor; one move on release; Esc or
|
||||
// right-click cancels; a drop off every floor leaves it where it was);
|
||||
// - drag empty space: pans as always; the wheel zooms;
|
||||
// - right-click a point: Delete / Insert after / Set as next target.
|
||||
// Every edit is a RynthAi nav command (addPointAt, movePointTo, deletePoint,
|
||||
// setActive); the route file stays RynthAi's and the map shows the next poll.
|
||||
// Coordinates: DungeonMapMath (screen <-> world through pan and rotation, world <->
|
||||
// nav).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -44,7 +66,7 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
{
|
||||
DungeonMapSettingsStore.Load(); // engine init thread: the file read stays off AC's thread
|
||||
ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true),
|
||||
new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true, OpenCentered: true),
|
||||
() => new DungeonMapFace());
|
||||
}
|
||||
|
||||
|
|
@ -57,6 +79,10 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
CreatureLabel = C(0xFFFFE6E6), Hint = C(0xFF8FA3B8), ButtonBg = C(0xC0141F29), ButtonBorder = C(0xFF34587A),
|
||||
FloorOn = C(0xFF2673B3), FloorHere = C(0xFF1AA64D);
|
||||
private const uint FillFlat = 0x662E8C38, FillUp = 0x668C1F14, FillDown = 0x661A8026, FillVisited = 0xB84D6B94;
|
||||
// Route (ARGB, alpha scaled per floor).
|
||||
private const uint RouteLegArgb = 0xD9FFA733, RoutePointArgb = 0xFFFFC266, RouteActiveArgb = 0xFFFFF04D,
|
||||
RouteSelectedArgb = 0xFFFFFFFF, RouteBadgeBgArgb = 0xE00A121F, RouteNumberArgb = 0xFFFFE6B3,
|
||||
RouteBadArgb = 0xFFFF4D4D, StatusArgb = 0xFFFFD27A;
|
||||
private static uint C(uint argb) => RynthTheme.Argb(argb);
|
||||
|
||||
/// <summary>ARGB colour with its alpha scaled, as an ImGui colour.</summary>
|
||||
|
|
@ -76,6 +102,37 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
private uint _landblock;
|
||||
private int[] _drawOrder = Array.Empty<int>();
|
||||
|
||||
// ── Route state (per open) ───────────────────────────────────────────
|
||||
private const float NumberZoom = 6f; // point numbers from this zoom up
|
||||
private const float PickRadius = 8f; // px: a press this close to a point grabs it
|
||||
private const long StatusMs = 4000;
|
||||
private bool _navSubscribed;
|
||||
private bool _editRoute;
|
||||
private int _selected = -1; // route index the next added point goes after
|
||||
private int _hoverPt = -1;
|
||||
private readonly List<(int Idx, Vector2 At)> _drawn = new(); // this frame's drawn points, for picking
|
||||
private Vector2[] _ptScreen = Array.Empty<Vector2>();
|
||||
private float[] _ptAlpha = Array.Empty<float>();
|
||||
private int[] _ptLayer = Array.Empty<int>();
|
||||
private bool _pressing; // left button went down on the canvas
|
||||
private int _pressPt = -1; // the point under that press (Edit route)
|
||||
private bool _pressMoved; // the press turned into a drag
|
||||
private int _dragPt = -1; // the point being dragged
|
||||
private Vector2 _dragWorld;
|
||||
private bool _dragOnFloor;
|
||||
private int _pendingMoveIdx = -1; // a sent move, drawn there until the route updates
|
||||
private Vector2 _pendingMoveWorld;
|
||||
private object? _pendingMoveFrom;
|
||||
private long _pendingMoveUntil;
|
||||
private bool _openPtMenu;
|
||||
private int _menuPt = -1;
|
||||
private string _status = string.Empty;
|
||||
private long _statusUntil;
|
||||
private object? _boundsFor;
|
||||
private bool _haveBounds;
|
||||
private Vector4 _bounds;
|
||||
private int[] _layerOrder = new int[16];
|
||||
|
||||
public int PopOutIdleHz => 20; // markers move
|
||||
|
||||
public bool HiddenWhileDocked
|
||||
|
|
@ -94,22 +151,42 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
UiSources.Radar.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden() => UiSources.Radar.Unsubscribe();
|
||||
public void OnHidden()
|
||||
{
|
||||
UiSources.Radar.Unsubscribe();
|
||||
SyncNavSubscription(false);
|
||||
CancelPress();
|
||||
}
|
||||
|
||||
/// <summary>The route source is polled only while the map is open with Route on.</summary>
|
||||
private void SyncNavSubscription(bool want)
|
||||
{
|
||||
if (want == _navSubscribed) return;
|
||||
_navSubscribed = want;
|
||||
if (want)
|
||||
{
|
||||
UiSources.Nav.Subscribe();
|
||||
UiSources.Nav.RequestRefresh();
|
||||
}
|
||||
else UiSources.Nav.Unsubscribe();
|
||||
}
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
SyncNavSubscription(DungeonMapSettingsStore.ShowRoute);
|
||||
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
|
||||
if (size.X < 16 || size.Y < 16) return;
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
RadarView? view = UiSources.Radar.Current?.Value;
|
||||
NavPayload? nav = DungeonMapSettingsStore.ShowRoute ? UiSources.Nav.Current?.Value : null;
|
||||
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
try
|
||||
{
|
||||
if (view == null) { Message(dl, origin, size, "Waiting for map data from RynthAi..."); return; }
|
||||
if (view == null) { CancelPress(); Message(dl, origin, size, "Waiting for map data from RynthAi..."); return; }
|
||||
RadarSnapshot live = view.Live;
|
||||
if (!live.IsIndoor) { Message(dl, origin, size, "Outdoors: the map shows while you're in a dungeon."); return; }
|
||||
if (!live.IsIndoor) { CancelPress(); Message(dl, origin, size, "Outdoors: the map shows while you're in a dungeon."); return; }
|
||||
|
||||
int layers = live.LayerZs.Count;
|
||||
TrackLayers(view, live.Player.Landblock, layers);
|
||||
|
|
@ -132,6 +209,9 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
if (_follow) _pan = Vector2.Zero;
|
||||
Vector2 centre = (canvasMin + canvasMax) * 0.5f + _pan;
|
||||
|
||||
DungeonMapProjection? proj = null;
|
||||
bool routeDrawn = false;
|
||||
_drawn.Clear();
|
||||
if (layers == 0)
|
||||
DrawCentredText(dl, (canvasMin + canvasMax) * 0.5f, Hint,
|
||||
$"Loading dungeon geometry for {live.Player.Landblock:X4}...");
|
||||
|
|
@ -140,11 +220,15 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
ImDrawListFlags saved = dl.Flags;
|
||||
dl.Flags = saved & ~(ImDrawListFlags.AntiAliasedLines | ImDrawListFlags.AntiAliasedLinesUseTex | ImDrawListFlags.AntiAliasedFill);
|
||||
dl.PushClipRect(canvasMin, canvasMax, true);
|
||||
var proj = new Projection(centre, live.Player, DungeonMapSettingsStore.RotateWithPlayer, _zoom);
|
||||
DrawFloors(dl, view, proj, canvasMin, canvasMax);
|
||||
var p = new DungeonMapProjection(centre, live.Player.WorldX, live.Player.WorldY, live.Player.Heading,
|
||||
DungeonMapSettingsStore.RotateWithPlayer, _zoom);
|
||||
proj = p;
|
||||
DrawFloors(dl, view, p, canvasMin, canvasMax);
|
||||
dl.Flags = saved;
|
||||
DrawMarkers(dl, live, proj, canvasMin, canvasMax);
|
||||
DrawPlayer(dl, centre, proj);
|
||||
if (nav != null) routeDrawn = DrawRoute(dl, view, nav, p, canvasMin, canvasMax);
|
||||
DrawMarkers(dl, live, p, canvasMin, canvasMax);
|
||||
DrawPlayer(dl, centre, p);
|
||||
DrawRouteStatus(dl, canvasMin, canvasMax, nav, routeDrawn);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
|
||||
|
|
@ -159,7 +243,8 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.SetItemTooltip("Show the map settings");
|
||||
}
|
||||
|
||||
CanvasInput(canvasMin, canvasMax);
|
||||
CanvasInput(canvasMin, canvasMax, view, nav, proj);
|
||||
DrawPointMenu(nav);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -195,7 +280,7 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
if (_autoLayer < layers - 1) _visible.Add(_autoLayer + 1);
|
||||
}
|
||||
|
||||
private void DrawFloors(ImDrawListPtr dl, RadarView view, in Projection proj, Vector2 clipMin, Vector2 clipMax)
|
||||
private void DrawFloors(ImDrawListPtr dl, RadarView view, in DungeonMapProjection proj, Vector2 clipMin, Vector2 clipMax)
|
||||
{
|
||||
int layers = view.Live.LayerZs.Count;
|
||||
int cur = view.CurrentLayer;
|
||||
|
|
@ -248,7 +333,7 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
}
|
||||
}
|
||||
|
||||
private static void FillRect(ImDrawListPtr dl, in Projection proj, float x0, float y0, float x1, float y1,
|
||||
private static void FillRect(ImDrawListPtr dl, in DungeonMapProjection proj, float x0, float y0, float x1, float y1,
|
||||
uint col, Vector2 clipMin, Vector2 clipMax)
|
||||
{
|
||||
Vector2 p00 = proj.P(x0, y0), p11 = proj.P(x1, y1);
|
||||
|
|
@ -273,14 +358,15 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
|
||||
// ── Markers and player ────────────────────────────────────────────────
|
||||
|
||||
private static void DrawMarkers(ImDrawListPtr dl, RadarSnapshot live, in Projection proj, Vector2 clipMin, Vector2 clipMax)
|
||||
private static void DrawMarkers(ImDrawListPtr dl, RadarSnapshot live, in DungeonMapProjection proj, Vector2 clipMin, Vector2 clipMax)
|
||||
{
|
||||
const float Margin = 20f;
|
||||
bool doors = DungeonMapSettingsStore.ShowDoors, creatures = DungeonMapSettingsStore.ShowCreatures;
|
||||
bool doors = DungeonMapSettingsStore.ShowDoors, creatures = DungeonMapSettingsStore.ShowCreatures,
|
||||
corpses = DungeonMapSettingsStore.ShowCorpses;
|
||||
RadarMarkerStyle.FillColors(KindCols);
|
||||
foreach (RadarMarker m in live.Markers)
|
||||
{
|
||||
if (!ShowOnMap(m.Kind, doors, creatures)) continue;
|
||||
if (!ShowOnMap(m.Kind, doors, creatures, corpses)) continue;
|
||||
Vector2 p = proj.P(m.X, m.Y);
|
||||
if (p.X < clipMin.X - Margin || p.X > clipMax.X + Margin || p.Y < clipMin.Y - Margin || p.Y > clipMax.Y + Margin) continue;
|
||||
switch (m.Kind)
|
||||
|
|
@ -322,15 +408,17 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
/// Portals always; doors with the map's Doors box; monsters and NPCs with its Creatures box.
|
||||
/// The kinds added 2026-10-04 also follow the radar's show box for that kind (so items on the
|
||||
/// ground stay off unless turned on there): players, fellows, pets and vendors with Creatures,
|
||||
/// corpses, lifestones and ground items on the radar's box alone. Unknown kinds: hidden.
|
||||
/// corpses (both kinds) with the map's Corpses box too (2026-10-12: off hides them here whatever
|
||||
/// the radar says), lifestones and ground items on the radar's box alone. Unknown kinds: hidden.
|
||||
/// </summary>
|
||||
private static bool ShowOnMap(byte kind, bool doors, bool creatures) => kind switch
|
||||
private static bool ShowOnMap(byte kind, bool doors, bool creatures, bool corpses) => kind switch
|
||||
{
|
||||
RadarKind.Portal => true,
|
||||
RadarKind.Door => doors,
|
||||
RadarKind.Monster or RadarKind.Npc => creatures,
|
||||
RadarKind.Player or RadarKind.Fellow or RadarKind.Pet or RadarKind.Vendor =>
|
||||
creatures && UI.Panels.RadarSettingsStore.ShowKind(kind),
|
||||
RadarKind.Corpse or RadarKind.OwnCorpse => corpses && UI.Panels.RadarSettingsStore.ShowKind(kind),
|
||||
_ => UI.Panels.RadarSettingsStore.ShowKind(kind),
|
||||
};
|
||||
|
||||
|
|
@ -341,7 +429,7 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
dl.AddText(pos, col, text);
|
||||
}
|
||||
|
||||
private static void DrawPlayer(ImDrawListPtr dl, Vector2 at, in Projection proj)
|
||||
private static void DrawPlayer(ImDrawListPtr dl, Vector2 at, in DungeonMapProjection proj)
|
||||
{
|
||||
dl.AddCircleFilled(at, 4f, PlayerCol, 10);
|
||||
// Rotating: facing is always up. North-up: AC heading 0 = east, 90 = north.
|
||||
|
|
@ -349,57 +437,473 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
dl.AddLine(at, tip, PlayerCol, 1.5f);
|
||||
}
|
||||
|
||||
/// <summary>World (AC x east, y north) to screen around the player, north-up or rotated so facing is up.</summary>
|
||||
private readonly struct Projection
|
||||
// ── Route ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Draws the route's legs and points over the floors. Fills <see cref="_drawn"/> with the
|
||||
/// points drawn (for hover and clicks). Returns true when at least one point was drawn.
|
||||
/// </summary>
|
||||
private bool DrawRoute(ImDrawListPtr dl, RadarView view, NavPayload nav, in DungeonMapProjection proj, Vector2 clipMin, Vector2 clipMax)
|
||||
{
|
||||
private readonly float _cx, _cy, _pwx, _pwy, _sin, _cos, _zoom;
|
||||
public readonly bool Rotated;
|
||||
|
||||
public Projection(Vector2 playerAt, RadarPlayer p, bool rotate, float zoom)
|
||||
List<NavPoint> pts = nav.Points;
|
||||
int n = pts.Count;
|
||||
if (n == 0) return false;
|
||||
if (_ptScreen.Length < n)
|
||||
{
|
||||
_cx = playerAt.X; _cy = playerAt.Y; _pwx = p.WorldX; _pwy = p.WorldY;
|
||||
float h = p.Heading * MathF.PI / 180f;
|
||||
_sin = MathF.Sin(h); _cos = MathF.Cos(h);
|
||||
Rotated = rotate; _zoom = zoom;
|
||||
int cap = Math.Max(n, _ptScreen.Length * 2);
|
||||
_ptScreen = new Vector2[cap];
|
||||
_ptAlpha = new float[cap];
|
||||
_ptLayer = new int[cap];
|
||||
}
|
||||
UpdateBounds(view);
|
||||
List<float> layerZs = view.Live.LayerZs;
|
||||
int cur = view.CurrentLayer;
|
||||
bool pending = _pendingMoveIdx >= 0 && ReferenceEquals(nav, _pendingMoveFrom) && Environment.TickCount64 < _pendingMoveUntil;
|
||||
if (!pending) _pendingMoveIdx = -1;
|
||||
const float BoundsMargin = 24f;
|
||||
|
||||
public float Sin => _sin;
|
||||
public float Cos => _cos;
|
||||
|
||||
public Vector2 P(float wx, float wy)
|
||||
// Where each point is and how strongly it's drawn (0 = not at all).
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float dx = wx - _pwx, dy = wy - _pwy;
|
||||
if (Rotated)
|
||||
NavPoint p = pts[i];
|
||||
Vector2 w;
|
||||
bool dragged = i == _dragPt && _pressMoved;
|
||||
if (dragged) w = _dragWorld;
|
||||
else if (pending && i == _pendingMoveIdx) w = _pendingMoveWorld;
|
||||
else w = DungeonMapMath.NavToWorld(p.NS, p.EW);
|
||||
_ptScreen[i] = proj.P(w.X, w.Y);
|
||||
|
||||
float a = 0f;
|
||||
int layer = -1;
|
||||
bool inside = _haveBounds && w.X >= _bounds.X - BoundsMargin && w.X <= _bounds.Z + BoundsMargin
|
||||
&& w.Y >= _bounds.Y - BoundsMargin && w.Y <= _bounds.W + BoundsMargin;
|
||||
if (inside)
|
||||
{
|
||||
float right = _sin * dx - _cos * dy;
|
||||
float forward = _cos * dx + _sin * dy;
|
||||
return new Vector2(_cx + right * _zoom, _cy - forward * _zoom);
|
||||
layer = DungeonMapMath.NearestLayer(layerZs, DungeonMapMath.NavZToWorld(p.Z));
|
||||
if (layer >= 0 && _visible.Contains(layer)) a = layer == cur ? 1f : DimOtherFloors;
|
||||
}
|
||||
return new Vector2(_cx + dx * _zoom, _cy - dy * _zoom);
|
||||
if (dragged) a = 1f;
|
||||
_ptAlpha[i] = a;
|
||||
_ptLayer[i] = layer;
|
||||
}
|
||||
|
||||
// Legs: point to point, back to the start on a Circular route.
|
||||
bool closed = nav.RouteType == 1 && n > 2;
|
||||
int legs = closed ? n : n - 1;
|
||||
for (int k = 0; k < legs; k++)
|
||||
{
|
||||
int ia = k, ib = (k + 1) % n;
|
||||
float a = MathF.Min(_ptAlpha[ia], _ptAlpha[ib]);
|
||||
if (a <= 0f) continue;
|
||||
Vector2 pa = _ptScreen[ia], pb = _ptScreen[ib];
|
||||
if (MathF.Max(pa.X, pb.X) < clipMin.X || MathF.Min(pa.X, pb.X) > clipMax.X ||
|
||||
MathF.Max(pa.Y, pb.Y) < clipMin.Y || MathF.Min(pa.Y, pb.Y) > clipMax.Y) continue;
|
||||
uint col = MulAlpha(RouteLegArgb, a);
|
||||
float thick = ib == nav.ActiveNavIndex ? 2.5f : 1.5f;
|
||||
if (IsJumpStep(pts[ia].Type)) DashedLine(dl, pa, pb, col, thick); // a recall / portal: no walk
|
||||
else dl.AddLine(pa, pb, col, thick);
|
||||
LegArrow(dl, pa, pb, col);
|
||||
}
|
||||
|
||||
// Points, the dragged one last (on top).
|
||||
ImFontPtr font = ImGuiNET.ImGui.GetFont();
|
||||
bool numbers = _zoom >= NumberZoom;
|
||||
int drawnCount = 0;
|
||||
for (int pass = 0; pass < 2; pass++)
|
||||
{
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
bool top = i == _dragPt && _pressMoved;
|
||||
if ((pass == 1) != top) continue;
|
||||
float a = _ptAlpha[i];
|
||||
if (a <= 0f) continue;
|
||||
Vector2 at = _ptScreen[i];
|
||||
if (at.X < clipMin.X - 12 || at.X > clipMax.X + 12 || at.Y < clipMin.Y - 12 || at.Y > clipMax.Y + 12) continue;
|
||||
DrawRoutePoint(dl, font, pts[i].Type, at, a, i == nav.ActiveNavIndex, i == _selected, i == _hoverPt);
|
||||
if (top && !_dragOnFloor) dl.AddCircle(at, 9f, RynthTheme.Argb(RouteBadArgb), 16, 2f);
|
||||
if (numbers) dl.AddText(at + new Vector2(7, -15), MulAlpha(RouteNumberArgb, a), NumberLabel(i));
|
||||
_drawn.Add((i, at));
|
||||
drawnCount++;
|
||||
}
|
||||
}
|
||||
return drawnCount > 0;
|
||||
}
|
||||
|
||||
/// <summary>A Recall or Portal step: the leg after it is a jump, not a walk (drawn dashed).</summary>
|
||||
private static bool IsJumpStep(string type) => type is "Recall" or "PortalNPC";
|
||||
|
||||
private static void DrawRoutePoint(ImDrawListPtr dl, ImFontPtr font, string type, Vector2 at, float a,
|
||||
bool active, bool selected, bool hovered)
|
||||
{
|
||||
if (active) dl.AddCircle(at, 9.5f, MulAlpha(RouteActiveArgb, a), 18, 2f);
|
||||
if (selected) dl.AddCircle(at, 12.5f, MulAlpha(RouteSelectedArgb, a), 20, 1.5f);
|
||||
string? glyph = TypeGlyph(type);
|
||||
if (glyph == null)
|
||||
{
|
||||
// Point / Checkpoint (walked to).
|
||||
dl.AddCircleFilled(at, hovered ? 4.5f : 3.5f, MulAlpha(RoutePointArgb, a), 10);
|
||||
if (type == "Checkpoint") dl.AddCircle(at, 6f, MulAlpha(RoutePointArgb, a), 12, 1.2f);
|
||||
return;
|
||||
}
|
||||
const float r = 7f;
|
||||
uint col = MulAlpha(TypeColour(type), a);
|
||||
dl.AddCircleFilled(at, hovered ? r + 1 : r, MulAlpha(RouteBadgeBgArgb, a), 14);
|
||||
dl.AddCircle(at, hovered ? r + 1 : r, col, 14, 1.3f);
|
||||
PhosphorIcons.DrawCentered(dl, font, 10f, glyph, at - new Vector2(r, r), new Vector2(2 * r, 2 * r), col);
|
||||
}
|
||||
|
||||
/// <summary>The badge icon for a step type that isn't simply walked to (RynthAi's NavPointType names).</summary>
|
||||
private static string? TypeGlyph(string type) => type switch
|
||||
{
|
||||
"Point" or "Checkpoint" or "" => null,
|
||||
"Recall" => PhosphorIcons.ArrowCounterClockwise,
|
||||
"Pause" => PhosphorIcons.HourglassMedium,
|
||||
"Chat" => PhosphorIcons.ChatCircleText,
|
||||
"PortalNPC" => PhosphorIcons.Spiral,
|
||||
"Npc" => PhosphorIcons.User,
|
||||
"OpenVendor" => PhosphorIcons.Storefront,
|
||||
"Jump" => PhosphorIcons.ArrowCircleUp,
|
||||
_ => PhosphorIcons.Info,
|
||||
};
|
||||
|
||||
private static uint TypeColour(string type) => type switch
|
||||
{
|
||||
"Recall" => 0xFF8CB3FF,
|
||||
"Pause" => 0xFFE6E6E6,
|
||||
"Chat" => 0xFF8CFFB3,
|
||||
"PortalNPC" => 0xFFE673FF,
|
||||
"Npc" => 0xFFFFD933,
|
||||
"OpenVendor" => 0xFFFFB366,
|
||||
"Jump" => 0xFF66E6FF,
|
||||
_ => 0xFFB0B0B0,
|
||||
};
|
||||
|
||||
/// <summary>"Portal" for PortalNPC and so on, for the tooltip.</summary>
|
||||
private static string TypeName(string type) => type switch
|
||||
{
|
||||
"PortalNPC" => "Portal",
|
||||
"Npc" => "NPC",
|
||||
"OpenVendor" => "Vendor",
|
||||
"" => "Point",
|
||||
_ => type,
|
||||
};
|
||||
|
||||
private static void DashedLine(ImDrawListPtr dl, Vector2 a, Vector2 b, uint col, float thick)
|
||||
{
|
||||
float len = Vector2.Distance(a, b);
|
||||
if (len < 1f) return;
|
||||
if (len > 4000f) { dl.AddLine(a, b, col, thick); return; }
|
||||
Vector2 d = (b - a) / len;
|
||||
const float On = 5f, Off = 4f;
|
||||
for (float t = 0; t < len; t += On + Off)
|
||||
dl.AddLine(a + d * t, a + d * MathF.Min(t + On, len), col, thick);
|
||||
}
|
||||
|
||||
/// <summary>A small arrowhead at the middle of a leg that's long enough, pointing the way the route goes.</summary>
|
||||
private static void LegArrow(ImDrawListPtr dl, Vector2 a, Vector2 b, uint col)
|
||||
{
|
||||
float len = Vector2.Distance(a, b);
|
||||
if (len < 48f || len > 8000f) return;
|
||||
Vector2 d = (b - a) / len, nrm = new(-d.Y, d.X);
|
||||
Vector2 tip = (a + b) * 0.5f + d * 4f;
|
||||
dl.AddTriangleFilled(tip, tip - d * 7f + nrm * 4f, tip - d * 7f - nrm * 4f, col);
|
||||
}
|
||||
|
||||
private static readonly List<string> NumberLabels = new();
|
||||
|
||||
private static string NumberLabel(int i)
|
||||
{
|
||||
while (NumberLabels.Count <= i) NumberLabels.Add(NumberLabels.Count.ToString(CultureInfo.InvariantCulture));
|
||||
return NumberLabels[i];
|
||||
}
|
||||
|
||||
/// <summary>The floors' bounding box (cached per geometry): route points outside it aren't in this dungeon.</summary>
|
||||
private void UpdateBounds(RadarView view)
|
||||
{
|
||||
if (ReferenceEquals(_boundsFor, view.Fills)) return;
|
||||
_boundsFor = view.Fills;
|
||||
_haveBounds = DungeonMapMath.FillBounds(view.FillsByLayer, out _bounds);
|
||||
}
|
||||
|
||||
/// <summary>The floor (layer index) under a world spot, among the floors shown: the player's first.</summary>
|
||||
private int FloorUnder(RadarView view, Vector2 world)
|
||||
{
|
||||
int layers = view.Live.LayerZs.Count;
|
||||
if (_layerOrder.Length < layers) _layerOrder = new int[layers];
|
||||
int n = DungeonMapMath.LayerOrder(view.CurrentLayer, _visible, layers, _layerOrder);
|
||||
return DungeonMapMath.FloorAt(world.X, world.Y, view.FillsByLayer, _layerOrder.AsSpan(0, n));
|
||||
}
|
||||
|
||||
/// <summary>Status line (bottom left of the canvas): the last edit's result, and in Edit route the controls.</summary>
|
||||
private void DrawRouteStatus(ImDrawListPtr dl, Vector2 canvasMin, Vector2 canvasMax, NavPayload? nav, bool routeDrawn)
|
||||
{
|
||||
float y = canvasMax.Y - 18f;
|
||||
float x = canvasMin.X + 6f;
|
||||
if (_editRoute)
|
||||
{
|
||||
string hint = _selected >= 0
|
||||
? $"Edit route: click a floor to add after {_selected} | drag a point to move | right-click a point | Esc deselects"
|
||||
: "Edit route: click a floor to add at the end | click a point to select | drag to move | right-click a point";
|
||||
dl.AddText(new Vector2(x, y), Hint, hint);
|
||||
y -= 16f;
|
||||
}
|
||||
else if (DungeonMapSettingsStore.ShowRoute && nav != null && nav.Points.Count > 0 && !routeDrawn)
|
||||
{
|
||||
dl.AddText(new Vector2(x, y), Hint, $"Route ({nav.Points.Count} points): none on the floors shown");
|
||||
y -= 16f;
|
||||
}
|
||||
if (_status.Length > 0 && Environment.TickCount64 < _statusUntil)
|
||||
dl.AddText(new Vector2(x, y), RynthTheme.Argb(StatusArgb), _status);
|
||||
}
|
||||
|
||||
private void SetStatus(string text)
|
||||
{
|
||||
_status = text;
|
||||
_statusUntil = Environment.TickCount64 + StatusMs;
|
||||
}
|
||||
|
||||
/// <summary>Edit route can be turned on: RynthAi has the map commands (or hasn't answered yet).</summary>
|
||||
private bool TryStartEditing()
|
||||
{
|
||||
NavPayload? nav = UiSources.Nav.Current?.Value;
|
||||
if (nav != null && nav.MapEdit < 1)
|
||||
{
|
||||
SetStatus("Editing the route on the map needs a newer RynthAi.");
|
||||
return false;
|
||||
}
|
||||
_editRoute = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void StopEditing()
|
||||
{
|
||||
_editRoute = false;
|
||||
_selected = -1;
|
||||
CancelPress();
|
||||
}
|
||||
|
||||
private void CancelPress()
|
||||
{
|
||||
_pressing = false;
|
||||
_pressPt = -1;
|
||||
_pressMoved = false;
|
||||
_dragPt = -1;
|
||||
}
|
||||
|
||||
// ── Canvas input ──────────────────────────────────────────────────────
|
||||
|
||||
private void CanvasInput(Vector2 canvasMin, Vector2 canvasMax)
|
||||
/// <summary>
|
||||
/// Drag pans (and turns Follow off), the wheel zooms. Edit route: a press on a point and a drag
|
||||
/// moves it; a click on a point selects it; a click on a floor adds a point; a drag from empty
|
||||
/// space still pans; right-click a point for its menu.
|
||||
/// </summary>
|
||||
private void CanvasInput(Vector2 canvasMin, Vector2 canvasMax, RadarView view, NavPayload? nav, DungeonMapProjection? proj)
|
||||
{
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(canvasMin);
|
||||
ImGuiNET.ImGui.InvisibleButton("##dmap_canvas", Vector2.Max(canvasMax - canvasMin, new Vector2(1, 1)));
|
||||
if (ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left))
|
||||
ImGuiNET.ImGui.InvisibleButton("##dmap_canvas", Vector2.Max(canvasMax - canvasMin, new Vector2(1, 1)),
|
||||
ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight);
|
||||
bool hovered = ImGuiNET.ImGui.IsItemHovered();
|
||||
Vector2 mouse = io.MousePos;
|
||||
bool canEdit = _editRoute && nav != null && nav.MapEdit >= 1 && proj.HasValue;
|
||||
int count = nav?.Points.Count ?? 0;
|
||||
if (_selected >= count) _selected = -1;
|
||||
|
||||
_hoverPt = (hovered || _pressing) && _drawn.Count > 0 ? DungeonMapMath.Pick(mouse, _drawn, PickRadius) : -1;
|
||||
|
||||
// Press.
|
||||
if (hovered && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
|
||||
{
|
||||
Vector2 delta = ImGuiNET.ImGui.GetIO().MouseDelta;
|
||||
if (float.IsFinite(delta.X) && float.IsFinite(delta.Y) && delta != Vector2.Zero)
|
||||
_pressing = true;
|
||||
_pressMoved = false;
|
||||
_pressPt = canEdit ? _hoverPt : -1;
|
||||
_dragPt = -1;
|
||||
}
|
||||
|
||||
// Drag: a point (Edit route, press on a point) or the map.
|
||||
if (_pressing && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left))
|
||||
{
|
||||
_pressMoved = true;
|
||||
if (_pressPt >= 0)
|
||||
{
|
||||
_follow = false;
|
||||
_pan += delta;
|
||||
if (canEdit && _pressPt < count)
|
||||
{
|
||||
_dragPt = _pressPt;
|
||||
_dragWorld = proj!.Value.World(mouse);
|
||||
_dragOnFloor = FloorUnder(view, _dragWorld) >= 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Vector2 delta = io.MouseDelta;
|
||||
if (float.IsFinite(delta.X) && float.IsFinite(delta.Y) && delta != Vector2.Zero)
|
||||
{
|
||||
_follow = false;
|
||||
_pan += delta;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
|
||||
// Cancel a point drag: Esc or the right button. Esc with nothing dragged deselects.
|
||||
bool rightClicked = hovered && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right);
|
||||
bool esc = ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape, false);
|
||||
if (_pressing && _pressPt >= 0 && (esc || rightClicked))
|
||||
{
|
||||
float wheel = ImGuiNET.ImGui.GetIO().MouseWheel;
|
||||
if (_dragPt >= 0) SetStatus("Move cancelled.");
|
||||
CancelPress();
|
||||
rightClicked = false;
|
||||
}
|
||||
else if (esc && canEdit && _selected >= 0 && ImGuiNET.ImGui.IsWindowFocused(ImGuiFocusedFlags.RootAndChildWindows))
|
||||
_selected = -1;
|
||||
|
||||
// Release.
|
||||
if (_pressing && ImGuiNET.ImGui.IsMouseReleased(ImGuiMouseButton.Left))
|
||||
{
|
||||
if (canEdit)
|
||||
{
|
||||
if (_pressMoved)
|
||||
{
|
||||
if (_dragPt >= 0) CommitMove(view, nav!, _dragPt, _dragWorld);
|
||||
}
|
||||
else if (_pressPt >= 0) _selected = _selected == _pressPt ? -1 : _pressPt;
|
||||
else if (hovered) AddPointAt(view, nav!, proj!.Value.World(mouse));
|
||||
}
|
||||
else if (_editRoute && !_pressMoved && hovered)
|
||||
SetStatus(nav == null ? "Waiting for the route from RynthAi..." : "Editing the route on the map needs a newer RynthAi.");
|
||||
CancelPress();
|
||||
}
|
||||
if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && _pressing) CancelPress(); // released elsewhere
|
||||
|
||||
// Right-click a point: its menu.
|
||||
if (rightClicked && canEdit && _hoverPt >= 0)
|
||||
{
|
||||
_menuPt = _hoverPt;
|
||||
_openPtMenu = true;
|
||||
}
|
||||
|
||||
if (hovered)
|
||||
{
|
||||
float wheel = io.MouseWheel;
|
||||
if (float.IsFinite(wheel) && wheel != 0f)
|
||||
_zoom = Math.Clamp(_zoom + wheel * 0.5f, MinZoom, MaxZoom);
|
||||
}
|
||||
|
||||
if (hovered && _hoverPt >= 0 && _dragPt < 0 && nav != null && _hoverPt < count && !ImGuiNET.ImGui.IsPopupOpen("##dmap_ptmenu"))
|
||||
PointTooltip(nav, _hoverPt, view);
|
||||
}
|
||||
|
||||
private void AddPointAt(RadarView view, NavPayload nav, Vector2 world)
|
||||
{
|
||||
int layer = FloorUnder(view, world);
|
||||
if (layer < 0)
|
||||
{
|
||||
SetStatus("Not on a floor: click inside a room or corridor (on a floor that's shown).");
|
||||
return;
|
||||
}
|
||||
float z = view.Live.LayerZs[layer];
|
||||
int after = _selected;
|
||||
NavCommands.Send(new NavCmd
|
||||
{
|
||||
Cmd = "addPointAt",
|
||||
NS = DungeonMapMath.WorldToNav(world.Y),
|
||||
EW = DungeonMapMath.WorldToNav(world.X),
|
||||
Z = DungeonMapMath.WorldZToNav(z),
|
||||
AddMode = after >= 0 ? 2 : 0,
|
||||
InsertAt = after,
|
||||
});
|
||||
if (after >= 0)
|
||||
{
|
||||
SetStatus($"Added point {after + 1} after {after} ({FloorName(layer)}).");
|
||||
_selected = after + 1; // the next click goes after the new one
|
||||
}
|
||||
else SetStatus($"Added point {nav.Points.Count} at the end ({FloorName(layer)}).");
|
||||
}
|
||||
|
||||
private void CommitMove(RadarView view, NavPayload nav, int idx, Vector2 world)
|
||||
{
|
||||
if (idx < 0 || idx >= nav.Points.Count) return;
|
||||
int layer = FloorUnder(view, world);
|
||||
if (layer < 0)
|
||||
{
|
||||
SetStatus($"Dropped off the floor: point {idx} not moved.");
|
||||
return;
|
||||
}
|
||||
NavCommands.Send(new NavCmd
|
||||
{
|
||||
Cmd = "movePointTo",
|
||||
Index = idx,
|
||||
NS = DungeonMapMath.WorldToNav(world.Y),
|
||||
EW = DungeonMapMath.WorldToNav(world.X),
|
||||
Z = DungeonMapMath.WorldZToNav(view.Live.LayerZs[layer]),
|
||||
});
|
||||
// Keep it where it was dropped until the route comes back (or 3 s, if RynthAi refused).
|
||||
_pendingMoveIdx = idx;
|
||||
_pendingMoveWorld = world;
|
||||
_pendingMoveFrom = nav;
|
||||
_pendingMoveUntil = Environment.TickCount64 + 3000;
|
||||
SetStatus($"Moved point {idx} ({FloorName(layer)}).");
|
||||
}
|
||||
|
||||
private static string FloorName(int layer) => "F" + (layer + 1).ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
private void PointTooltip(NavPayload nav, int i, RadarView view)
|
||||
{
|
||||
NavPoint p = nav.Points[i];
|
||||
int layer = i < _ptLayer.Length ? _ptLayer[i] : -1;
|
||||
ImGuiNET.ImGui.BeginTooltip();
|
||||
ImGuiNET.ImGui.TextUnformatted($"{i} {TypeName(p.Type)}{(i == nav.ActiveNavIndex ? " (next waypoint)" : "")}");
|
||||
if (!string.IsNullOrEmpty(p.Desc) && TypeGlyph(p.Type) != null) ImGuiNET.ImGui.TextUnformatted(p.Desc); // a Point's is just its coordinates
|
||||
ImGuiNET.ImGui.TextUnformatted(string.Format(CultureInfo.InvariantCulture, "{0:0.000}{1} {2:0.000}{3} Z {4:0.0}{5}",
|
||||
Math.Abs(p.NS), p.NS >= 0 ? "N" : "S", Math.Abs(p.EW), p.EW >= 0 ? "E" : "W",
|
||||
DungeonMapMath.NavZToWorld(p.Z), layer >= 0 ? " " + FloorName(layer) : ""));
|
||||
if (_editRoute)
|
||||
ImGuiNET.ImGui.TextDisabled("Drag to move; click to select; right-click for more");
|
||||
ImGuiNET.ImGui.EndTooltip();
|
||||
}
|
||||
|
||||
/// <summary>Right-click menu on a route point (Edit route): Delete / Insert after / Set as next target.</summary>
|
||||
private void DrawPointMenu(NavPayload? nav)
|
||||
{
|
||||
if (_openPtMenu)
|
||||
{
|
||||
_openPtMenu = false;
|
||||
ImGuiNET.ImGui.OpenPopup("##dmap_ptmenu");
|
||||
}
|
||||
if (!ImGuiNET.ImGui.BeginPopup("##dmap_ptmenu")) return;
|
||||
try
|
||||
{
|
||||
if (nav == null || _menuPt < 0 || _menuPt >= nav.Points.Count || !_editRoute)
|
||||
{
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
return;
|
||||
}
|
||||
int i = _menuPt;
|
||||
ImGuiNET.ImGui.TextDisabled($"Point {i} {TypeName(nav.Points[i].Type)}");
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem("Delete"))
|
||||
{
|
||||
NavCommands.Send(new NavCmd { Cmd = "deletePoint", Index = i });
|
||||
if (_selected == i) _selected = -1;
|
||||
else if (_selected > i) _selected--;
|
||||
SetStatus($"Deleted point {i}.");
|
||||
}
|
||||
if (ImGuiNET.ImGui.MenuItem("Insert after"))
|
||||
{
|
||||
_selected = i;
|
||||
SetStatus($"Click a floor to add a point after {i}.");
|
||||
}
|
||||
if (ImGuiNET.ImGui.MenuItem("Set as next target", null, i == nav.ActiveNavIndex))
|
||||
{
|
||||
NavCommands.Send(new NavCmd { Cmd = "setActive", Index = i });
|
||||
SetStatus($"Next waypoint: {i}.");
|
||||
}
|
||||
if (_selected >= 0 && ImGuiNET.ImGui.MenuItem("Clear selection"))
|
||||
_selected = -1;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Toolbar ───────────────────────────────────────────────────────────
|
||||
|
|
@ -490,12 +994,34 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
SetOneUpOneDown(layers);
|
||||
}
|
||||
|
||||
// Doors / Creatures.
|
||||
SameLineIfFits(160, limit, 12);
|
||||
// Doors / Creatures / Corpses.
|
||||
SameLineIfFits(230, limit, 12);
|
||||
changed |= ImGuiNET.ImGui.Checkbox("Doors##dmap_doors", ref DungeonMapSettingsStore.ShowDoors);
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
changed |= ImGuiNET.ImGui.Checkbox("Creatures##dmap_creatures", ref DungeonMapSettingsStore.ShowCreatures);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Monsters, NPCs, players, fellows, your pet and vendors. Players, fellows, pets, vendors, corpses, lifestones and ground items also follow their box in the Radar's settings.");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Monsters, NPCs, players, fellows, your pet and vendors. Players, fellows, pets and vendors also follow their box in the Radar's settings; lifestones and items on the ground follow the Radar's settings alone.");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
changed |= ImGuiNET.ImGui.Checkbox("Corpses##dmap_corpses", ref DungeonMapSettingsStore.ShowCorpses);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Corpses on the map. Off hides them here whatever the Radar shows; on, they also follow the Radar's corpse boxes.");
|
||||
|
||||
// Route / Edit route.
|
||||
SameLineIfFits(160, limit, 12);
|
||||
if (ImGuiNET.ImGui.Checkbox("Route##dmap_route", ref DungeonMapSettingsStore.ShowRoute))
|
||||
{
|
||||
changed = true;
|
||||
if (!DungeonMapSettingsStore.ShowRoute) StopEditing();
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("RynthAi's nav route: legs (dashed after a recall or portal), points (numbered when zoomed in), the next waypoint ringed. Hover a point for its details.");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.BeginDisabled(!DungeonMapSettingsStore.ShowRoute);
|
||||
bool edit = _editRoute;
|
||||
if (ImGuiNET.ImGui.Checkbox("Edit route##dmap_editroute", ref edit))
|
||||
{
|
||||
if (edit) TryStartEditing();
|
||||
else StopEditing();
|
||||
}
|
||||
ImGuiNET.ImGui.EndDisabled();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Click a floor to add a point (after the selected point, else at the end). Click a point to select it; drag a point to move it (Esc cancels); right-click a point to delete it, insert after it or make it the next waypoint. Dragging empty space still pans.");
|
||||
|
||||
// Opacity (of the map's background).
|
||||
SameLineIfFits(130, limit, 12);
|
||||
|
|
@ -573,7 +1099,8 @@ internal sealed class DungeonMapFace : IImGuiPanel
|
|||
|
||||
/// <summary>
|
||||
/// The Dungeon Map's settings (the plugin map's MapShowDoors / MapShowCreatures /
|
||||
/// MapShowToolbar / MapBgOpacity / MapRotateWithPlayer, same defaults). Engine-wide,
|
||||
/// MapShowToolbar / MapBgOpacity / MapRotateWithPlayer, same defaults; showCorpses and
|
||||
/// showRoute added 2026-10-12, both on by default). Engine-wide,
|
||||
/// in %LOCALAPPDATA%\RynthCore\dungeon_map_settings.txt, like radar_settings.txt.
|
||||
/// </summary>
|
||||
internal static class DungeonMapSettingsStore
|
||||
|
|
@ -583,6 +1110,8 @@ internal static class DungeonMapSettingsStore
|
|||
|
||||
public static bool ShowDoors = true;
|
||||
public static bool ShowCreatures = true;
|
||||
public static bool ShowCorpses = true;
|
||||
public static bool ShowRoute = true;
|
||||
public static bool ShowToolbar = true;
|
||||
public static float BgOpacity = 1.0f;
|
||||
public static bool RotateWithPlayer;
|
||||
|
|
@ -618,6 +1147,8 @@ internal static class DungeonMapSettingsStore
|
|||
{
|
||||
case "showDoors": ShowDoors = val == "1"; break;
|
||||
case "showCreatures": ShowCreatures = val == "1"; break;
|
||||
case "showCorpses": ShowCorpses = val == "1"; break;
|
||||
case "showRoute": ShowRoute = val == "1"; break;
|
||||
case "showToolbar": ShowToolbar = val == "1"; break;
|
||||
case "rotate": RotateWithPlayer = val == "1"; break;
|
||||
case "opacity":
|
||||
|
|
@ -638,6 +1169,8 @@ internal static class DungeonMapSettingsStore
|
|||
string text = "# RynthCore dungeon map settings - auto-generated, hand-edits OK.\n"
|
||||
+ $"showDoors={(ShowDoors ? "1" : "0")}\n"
|
||||
+ $"showCreatures={(ShowCreatures ? "1" : "0")}\n"
|
||||
+ $"showCorpses={(ShowCorpses ? "1" : "0")}\n"
|
||||
+ $"showRoute={(ShowRoute ? "1" : "0")}\n"
|
||||
+ $"showToolbar={(ShowToolbar ? "1" : "0")}\n"
|
||||
+ $"rotate={(RotateWithPlayer ? "1" : "0")}\n"
|
||||
+ FormattableString.Invariant($"opacity={BgOpacity:0.##}\n");
|
||||
|
|
|
|||
78
src/RynthCore.Engine/ImGui/Panels/GuardianFace.cs
Normal file
78
src/RynthCore.Engine/ImGui/Panels/GuardianFace.cs
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/GuardianFace.cs
|
||||
// Temple of Enlightenment guardians (riddle answers, Give, the phrasebook),
|
||||
// drawn by RynthAi through RynthPluginRenderEmbed ("guardian"). Part of the
|
||||
// ILT section: registered when RynthAi is installed, opened from the bar's ILT
|
||||
// button or "/rc guardian" on Infinite Leaftide only. ImGui-only.
|
||||
//
|
||||
// The panel is user-sized: the plugin fills the body it is given. Until
|
||||
// RynthAi can draw it (not logged in, too old for the surface, or its embed
|
||||
// failed) the body says why.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class GuardianFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Guardian";
|
||||
|
||||
public static void Register() => ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(540, 520), new Vector2(320, 220), EdgeToEdge: true, GripInBody: true),
|
||||
() => new GuardianFace());
|
||||
|
||||
/// <summary>The RynthAi surface for this panel (NUL-terminated for the export).</summary>
|
||||
private static ReadOnlySpan<byte> Surface => "guardian\0"u8;
|
||||
|
||||
// Its export failed this session: say so instead of calling it every frame.
|
||||
private bool _embedOff;
|
||||
|
||||
public void OnShown() { }
|
||||
|
||||
public void OnHidden() { }
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
float h = Math.Max(60f, Remaining(origin, size) - GripOverlap());
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
int result = PluginManager.EmbedFailed;
|
||||
if (!_embedOff)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(6, 4));
|
||||
bool open = ImGuiNET.ImGui.BeginChild("##guardian_rynthai", new Vector2(w, h), ImGuiChildFlags.AlwaysUseWindowPadding,
|
||||
ImGuiWindowFlags.NoBackground);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
try
|
||||
{
|
||||
if (open)
|
||||
{
|
||||
// The plugin's widgets use the default UI font, as in its own windows.
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
try { result = PluginManager.RenderEmbed("RynthAi", Surface, ImGuiNET.ImGui.GetContentRegionAvail(), out _); }
|
||||
finally { ImGuiNET.ImGui.PopFont(); }
|
||||
}
|
||||
else result = PluginManager.EmbedDrawn; // clipped: nothing to draw, nothing wrong
|
||||
}
|
||||
finally { ImGuiNET.ImGui.EndChild(); }
|
||||
if (result == PluginManager.EmbedFailed) _embedOff = true;
|
||||
}
|
||||
|
||||
if (result != PluginManager.EmbedDrawn)
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(start + new Vector2(0, 4));
|
||||
Label(result switch
|
||||
{
|
||||
PluginManager.EmbedNoPlugin => "The Guardian tools come with RynthAi; it isn't loaded.",
|
||||
PluginManager.EmbedFailed => "RynthAi couldn't draw the Guardian tools (this build may be too old). See the log.",
|
||||
_ => "Waiting for RynthAi (log in; ILT features turn on once the server reports them).",
|
||||
}, Mute);
|
||||
}
|
||||
End(origin, size);
|
||||
}
|
||||
}
|
||||
452
src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs
Normal file
452
src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs
Normal file
|
|
@ -0,0 +1,452 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/HotkeysSettingsUi.cs
|
||||
// Settings > Hotkeys: the user hotkeys editor (Hotkeys/HotkeyService.cs).
|
||||
//
|
||||
// A master switch, the list of bindings (key, what it does, on/off; edit,
|
||||
// remove, move up/down), Add hotkey, and an editor under the list: Key is
|
||||
// captured ("press a key... Esc cancels": the next combo pressed, which never
|
||||
// reaches AC), Action is a dropdown of the built-ins or "Chat command" with a
|
||||
// text box. The VTank-style actions follow the built-ins under their own header;
|
||||
// "Meta: set state..." asks for the state (the loaded meta's states are offered,
|
||||
// from UiSources.Meta while the editor shows that action). Duplicate keys and
|
||||
// keys AC uses are warned about, never refused.
|
||||
// Drawn by SettingsFace for the Hotkeys tab's one row, in its look.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Hotkeys;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class HotkeysSettingsUi
|
||||
{
|
||||
public const string TabName = "Hotkeys";
|
||||
|
||||
private static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Mute = C(0xFFB8C8D8),
|
||||
TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14), PanelBg = C(0xFF141F29), BtnFill = C(0xFF16283A),
|
||||
BtnBord = C(0xFF34587A), ToggleOn = C(0xFF33FF33), ToggleOff = C(0xFF334455), TabActive = C(0xFF1A2E42),
|
||||
Warn = C(0xFFFFB347);
|
||||
private static uint C(uint argb) => RynthTheme.Argb(argb);
|
||||
|
||||
private const string ChatCommandItem = "Chat command...";
|
||||
|
||||
// The editor: open while adding (EditIndex -1) or editing a binding.
|
||||
private bool _editorOpen;
|
||||
private int _editIndex = -1;
|
||||
private KeyCombo _editCombo;
|
||||
private string _editAction = "macro";
|
||||
private string _editCommand = string.Empty;
|
||||
private string _editParam = string.Empty; // an action's parameter (the meta state)
|
||||
private bool _editEnabled = true;
|
||||
private bool _waitingForKey;
|
||||
private bool _metaSubscribed; // UiSources.Meta, for the meta state list
|
||||
|
||||
/// <summary>The section is no longer shown (Settings closed, another tab): a key capture stops.</summary>
|
||||
public void Leave()
|
||||
{
|
||||
if (_waitingForKey) HotkeyService.CancelCapture();
|
||||
_waitingForKey = false;
|
||||
WatchMetaStates(false);
|
||||
}
|
||||
|
||||
/// <summary>Subscribes to the meta snapshot while "Meta: set state..." is being edited (its state list).</summary>
|
||||
private void WatchMetaStates(bool on)
|
||||
{
|
||||
if (on == _metaSubscribed) return;
|
||||
_metaSubscribed = on;
|
||||
if (on) { UiSources.Meta.Subscribe(); UiSources.Meta.RequestRefresh(); }
|
||||
else UiSources.Meta.Unsubscribe();
|
||||
}
|
||||
|
||||
/// <summary>Draws the section. True while a text box here has the keyboard.</summary>
|
||||
public bool Draw(float w)
|
||||
{
|
||||
bool typing = false;
|
||||
HotkeyFile file = HotkeyService.Current;
|
||||
IReadOnlyList<HotkeyBinding> list = file.Bindings;
|
||||
|
||||
PollCapture();
|
||||
|
||||
MasterSwitch(file.Enabled, w);
|
||||
Note("A hotkey works in game while you aren't typing (AC's chat or any text box). The key goes to the hotkey, " +
|
||||
"not to AC. Saved for this PC: every client uses the same hotkeys. Also: /rc hotkey.", w);
|
||||
|
||||
Section("Your Hotkeys", w);
|
||||
if (list.Count == 0)
|
||||
Note("(No hotkeys yet. Add hotkey picks a key and what it does.)", w);
|
||||
List<int> shadowed = HotkeyConflicts.Shadowed(list);
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
BindingRow(list, i, shadowed.Contains(i), w);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
if (!_editorOpen)
|
||||
{
|
||||
if (ImGuiNET.ImGui.Button(PhosphorIcons.Plus + " Add hotkey"))
|
||||
OpenEditor(-1, null);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Bind a key to a built-in action or a chat command.");
|
||||
}
|
||||
else
|
||||
{
|
||||
typing = Editor(list, w);
|
||||
}
|
||||
return typing;
|
||||
}
|
||||
|
||||
// ── Rows ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static void MasterSwitch(bool on, float w)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const string label = "Hotkeys On";
|
||||
float labelW = ImGuiNET.ImGui.CalcTextSize(label).X;
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##hk_master", new Vector2(Math.Min(w, 18 + labelW), 16)))
|
||||
HotkeyService.SetMasterEnabled(!on);
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Off: no hotkey fires (they're kept). Also: /rc hotkey on|off.");
|
||||
dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2);
|
||||
dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
}
|
||||
|
||||
// [dot] Ctrl+F1 [^][v][edit][x]
|
||||
// Toggle Combat
|
||||
private void BindingRow(IReadOnlyList<HotkeyBinding> list, int i, bool shadowed, float w)
|
||||
{
|
||||
HotkeyBinding b = list[i];
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11), small = ImGuiFonts.Get(UiFont.Ui10);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
bool editingThis = _editorOpen && _editIndex == i;
|
||||
float rowH = bold.FontSize + small.FontSize + 6;
|
||||
if (editingThis) dl.AddRectFilled(p - new Vector2(2, 1), p + new Vector2(w, rowH), TabActive);
|
||||
|
||||
// Enabled dot: click to switch this hotkey on or off.
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##on", new Vector2(14, 16)))
|
||||
HotkeyService.Replace(i, b with { Enabled = !b.Enabled });
|
||||
ImGuiNET.ImGui.SetItemTooltip(b.Enabled ? "On. Click to switch this hotkey off." : "Off. Click to switch this hotkey on.");
|
||||
dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), b.Enabled ? ToggleOn : ToggleOff, 2);
|
||||
|
||||
dl.AddText(bold, bold.FontSize, p + new Vector2(18, 1), b.Enabled ? Amber : Mute, b.Combo.ToString());
|
||||
string what = HotkeyActions.Describe(b);
|
||||
float textRight = p.X + w - 4 * 20 - 4;
|
||||
dl.PushClipRect(p + new Vector2(18, 0), new Vector2(textRight, p.Y + rowH), true);
|
||||
dl.AddText(small, small.FontSize, p + new Vector2(18, bold.FontSize + 3), b.Enabled ? TextDim : Mute, what);
|
||||
dl.PopClipRect();
|
||||
// The full text on hover (a long chat command is clipped).
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p + new Vector2(18, 0));
|
||||
ImGuiNET.ImGui.InvisibleButton("##what", new Vector2(Math.Max(1, textRight - p.X - 18), rowH));
|
||||
ImGuiNET.ImGui.SetItemTooltip(b.Combo + ": " + what + (b.Enabled ? "" : " (off)"));
|
||||
|
||||
float x = p.X + w - 4 * 20;
|
||||
if (IconButton("##up", new Vector2(x, p.Y), PhosphorIcons.CaretUp, i > 0))
|
||||
HotkeyService.Move(i, -1);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Move up. Of two hotkeys on the same key, the higher one fires.");
|
||||
if (IconButton("##down", new Vector2(x + 20, p.Y), PhosphorIcons.CaretDown, i < list.Count - 1))
|
||||
HotkeyService.Move(i, +1);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Move down.");
|
||||
if (IconButton("##edit", new Vector2(x + 40, p.Y), PhosphorIcons.PencilSimple, true))
|
||||
OpenEditor(i, b);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Edit: change the key or what it does.");
|
||||
if (IconButton("##del", new Vector2(x + 60, p.Y), PhosphorIcons.Trash, true))
|
||||
{
|
||||
HotkeyService.RemoveAt(i);
|
||||
if (_editorOpen && _editIndex == i) CloseEditor();
|
||||
else if (_editorOpen && _editIndex > i) _editIndex--;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Remove this hotkey.");
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + rowH));
|
||||
if (shadowed && b.Enabled)
|
||||
Warning($"Never fires: a hotkey higher in the list has {b.Combo}.", w);
|
||||
else if (b.IsCommand && b.Command.Trim().Length == 0)
|
||||
Warning("No chat command: edit it to add one.", w);
|
||||
else if (HotkeyActions.Find(b.Action) is { HasParam: true } pa && b.Command.Trim().Length == 0)
|
||||
Warning($"No {pa.Param!.ToLowerInvariant()}: edit it to pick one.", w);
|
||||
else if (!b.IsCommand && HotkeyActions.Find(b.Action) == null)
|
||||
Warning($"This engine doesn't know the action '{b.Action}'.", w);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
}
|
||||
|
||||
// ── Editor ─────────────────────────────────────────────────────────────
|
||||
|
||||
private void OpenEditor(int index, HotkeyBinding? b)
|
||||
{
|
||||
if (_waitingForKey) HotkeyService.CancelCapture();
|
||||
_editorOpen = true;
|
||||
_editIndex = index;
|
||||
_editCombo = b?.Combo ?? default;
|
||||
_editAction = b?.Action ?? "macro";
|
||||
bool hasParam = b != null && HotkeyActions.Find(b.Action)?.HasParam == true;
|
||||
_editCommand = b != null && !hasParam ? b.Command : string.Empty;
|
||||
_editParam = hasParam ? b!.Command : string.Empty;
|
||||
_editEnabled = b?.Enabled ?? true;
|
||||
_waitingForKey = b == null; // a new hotkey starts by asking for its key
|
||||
if (_waitingForKey) HotkeyService.BeginCapture();
|
||||
}
|
||||
|
||||
private void CloseEditor()
|
||||
{
|
||||
if (_waitingForKey) HotkeyService.CancelCapture();
|
||||
_waitingForKey = false;
|
||||
_editorOpen = false;
|
||||
_editIndex = -1;
|
||||
WatchMetaStates(false);
|
||||
}
|
||||
|
||||
private void PollCapture()
|
||||
{
|
||||
if (!_waitingForKey) return;
|
||||
if (HotkeyService.TryTakeCapture(out KeyCombo? combo))
|
||||
{
|
||||
_waitingForKey = false;
|
||||
if (combo is { } c) _editCombo = c;
|
||||
}
|
||||
}
|
||||
|
||||
private bool Editor(IReadOnlyList<HotkeyBinding> list, float w)
|
||||
{
|
||||
bool typing = false;
|
||||
Section(_editIndex < 0 ? "New Hotkey" : "Edit Hotkey", w);
|
||||
|
||||
// Key: [Ctrl+F1] (click, then press the combo).
|
||||
Label("Key", "Click, then press the key with any of Ctrl, Alt and Shift. Esc cancels.");
|
||||
ImGuiNET.ImGui.SameLine(70);
|
||||
string keyText = _waitingForKey ? "Press a key... (Esc cancels)" : _editCombo.IsEmpty ? "Click to set" : _editCombo.ToString();
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, _waitingForKey ? Teal : Amber);
|
||||
if (ImGuiNET.ImGui.Button(keyText + "##key", new Vector2(Math.Max(80, w - 74), 0)))
|
||||
{
|
||||
if (_waitingForKey) { HotkeyService.CancelCapture(); _waitingForKey = false; }
|
||||
else { HotkeyService.BeginCapture(); _waitingForKey = true; }
|
||||
}
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.SetItemTooltip(_waitingForKey ? "Waiting for a key. Click again or press Esc to stop." : "Click, then press the key combination.");
|
||||
if (_waitingForKey && HotkeyService.CaptureNote.Length > 0)
|
||||
Warning(HotkeyService.CaptureNote, w);
|
||||
|
||||
// Action: dropdown of the built-ins and "Chat command...".
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 3));
|
||||
Label("Action", "What the key does: a built-in, or any chat command (e.g. /ra start, /rn bc /ra stop).");
|
||||
ImGuiNET.ImGui.SameLine(70);
|
||||
bool isCommand = string.Equals(_editAction, HotkeyActions.Command, StringComparison.OrdinalIgnoreCase);
|
||||
HotkeyAction? picked = isCommand ? null : HotkeyActions.Find(_editAction);
|
||||
string current = isCommand ? ChatCommandItem
|
||||
: picked == null ? _editAction
|
||||
: picked.Group.Length > 0 ? $"{picked.Name} ({picked.Group})" : picked.Name;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 74));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
|
||||
bool open = ImGuiNET.ImGui.BeginCombo("##action", current, ImGuiComboFlags.HeightLarge);
|
||||
ImGuiNET.ImGui.PopStyleColor(3);
|
||||
if (!open && picked is { Tip.Length: > 0 }) ImGuiNET.ImGui.SetItemTooltip(picked.Tip);
|
||||
if (open)
|
||||
{
|
||||
if (ImGuiNET.ImGui.Selectable(ChatCommandItem, isCommand)) _editAction = HotkeyActions.Command;
|
||||
ImGuiNET.ImGui.SetItemTooltip("Run a chat command, as if typed: /ra ..., /rc ..., /lua ..., /rn bc ...");
|
||||
string group = string.Empty;
|
||||
foreach (HotkeyAction a in HotkeyActions.BuiltIns)
|
||||
{
|
||||
if (a.Group != group || group.Length == 0 && a == HotkeyActions.BuiltIns[0])
|
||||
{
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (a.Group.Length > 0)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.TextUnformatted(a.Group);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
if (a.Group == HotkeyActions.VTankGroup)
|
||||
ImGuiNET.ImGui.SetItemTooltip("VirindiTank's hotkey actions, by VTank's names.");
|
||||
}
|
||||
group = a.Group;
|
||||
}
|
||||
if (ImGuiNET.ImGui.Selectable((a.Group.Length > 0 ? " " : "") + a.Name + "##" + a.Id,
|
||||
string.Equals(a.Id, _editAction, StringComparison.OrdinalIgnoreCase)))
|
||||
_editAction = a.Id;
|
||||
if (a.Tip.Length > 0) ImGuiNET.ImGui.SetItemTooltip(a.Tip);
|
||||
}
|
||||
ImGuiNET.ImGui.EndCombo();
|
||||
}
|
||||
|
||||
bool hasParam = picked is { HasParam: true };
|
||||
WatchMetaStates(hasParam && string.Equals(picked!.Id, HotkeyActions.MetaStateId, StringComparison.OrdinalIgnoreCase));
|
||||
if (hasParam)
|
||||
typing |= ParamRow(picked!, w);
|
||||
|
||||
if (isCommand)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 3));
|
||||
Label("Command", "The chat line to run, starting with /.");
|
||||
ImGuiNET.ImGui.SameLine(70);
|
||||
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 74));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
|
||||
ImGuiNET.ImGui.InputTextWithHint("##cmd", "/ra start", ref _editCommand, 400u);
|
||||
typing = ImGuiNET.ImGui.IsItemActive();
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(3);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Any chat command: /ra start, /rc reload, /lua myscript go, /rn bc /ra stop.");
|
||||
}
|
||||
|
||||
// Warnings for this key (allowed anyway).
|
||||
foreach (string warning in HotkeyConflicts.Warnings(list, _editCombo, _editIndex))
|
||||
Warning(warning, w);
|
||||
|
||||
string cmd = _editCommand.Trim();
|
||||
string param = _editParam.Trim();
|
||||
bool commandOk = !isCommand || cmd.StartsWith('/');
|
||||
bool paramOk = !hasParam || param.Length > 0;
|
||||
bool canSave = !_editCombo.IsEmpty && !_waitingForKey && commandOk && paramOk;
|
||||
if (isCommand && cmd.Length > 0 && !cmd.StartsWith('/'))
|
||||
Warning("A chat command starts with / (e.g. /ra start).", w);
|
||||
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
ImGuiNET.ImGui.BeginDisabled(!canSave);
|
||||
if (ImGuiNET.ImGui.Button(PhosphorIcons.FloppyDisk + " Save"))
|
||||
{
|
||||
var b = new HotkeyBinding(_editCombo, isCommand ? HotkeyActions.Command : _editAction,
|
||||
isCommand ? cmd : hasParam ? param : string.Empty, _editEnabled);
|
||||
if (_editIndex < 0 || !HotkeyService.Replace(_editIndex, b))
|
||||
HotkeyService.Add(b);
|
||||
CloseEditor();
|
||||
}
|
||||
ImGuiNET.ImGui.EndDisabled();
|
||||
if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
|
||||
ImGuiNET.ImGui.SetTooltip(!canSave
|
||||
? (_editCombo.IsEmpty || _waitingForKey ? "Pick a key first."
|
||||
: !paramOk ? $"Pick the {picked?.Param?.ToLowerInvariant() ?? "value"} first."
|
||||
: "Type the chat command (starting with /).")
|
||||
: "Save this hotkey (it works right away, in every client on this PC).");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.Button("Cancel"))
|
||||
CloseEditor();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Close without saving.");
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
return typing;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The parameter row (the meta state): a text box, and a list of the loaded meta's states when
|
||||
/// they are known. True while the text box has the keyboard.
|
||||
/// </summary>
|
||||
private bool ParamRow(HotkeyAction a, float w)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 3));
|
||||
bool meta = string.Equals(a.Id, HotkeyActions.MetaStateId, StringComparison.OrdinalIgnoreCase);
|
||||
Label(a.Param!, meta ? "The meta state to switch to. Pick one of the loaded meta's states, or type a name." : a.Tip);
|
||||
ImGuiNET.ImGui.SameLine(70);
|
||||
|
||||
List<string> states = meta ? UiSources.Meta.Current?.Value.States ?? new List<string>() : new List<string>();
|
||||
float listW = states.Count > 0 ? 26 : 0;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 74 - listW));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
|
||||
ImGuiNET.ImGui.InputTextWithHint("##param", meta ? "state name" : a.Param!.ToLowerInvariant(), ref _editParam, 200u);
|
||||
bool typing = ImGuiNET.ImGui.IsItemActive();
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(3);
|
||||
ImGuiNET.ImGui.SetItemTooltip(meta ? "The state's name, as in the meta (the case doesn't matter)." : a.Tip);
|
||||
|
||||
if (states.Count > 0)
|
||||
{
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
|
||||
ImGuiNET.ImGui.SetNextItemWidth(22);
|
||||
bool open = ImGuiNET.ImGui.BeginCombo("##states", string.Empty, ImGuiComboFlags.NoPreview | ImGuiComboFlags.HeightLarge);
|
||||
ImGuiNET.ImGui.PopStyleColor(3);
|
||||
if (open)
|
||||
{
|
||||
foreach (string st in states)
|
||||
if (ImGuiNET.ImGui.Selectable(st + "##st", string.Equals(st, _editParam.Trim(), StringComparison.OrdinalIgnoreCase)))
|
||||
_editParam = st;
|
||||
ImGuiNET.ImGui.EndCombo();
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("The loaded meta's states.");
|
||||
}
|
||||
else if (meta)
|
||||
Note("(No meta loaded, or RynthAi isn't running: type the state's name.)", w);
|
||||
|
||||
if (meta && states.Count > 0 && _editParam.Trim().Length > 0
|
||||
&& !states.Exists(st => string.Equals(st, _editParam.Trim(), StringComparison.OrdinalIgnoreCase)))
|
||||
Warning($"The loaded meta has no state '{_editParam.Trim()}' (it may be in another meta).", w);
|
||||
return typing;
|
||||
}
|
||||
|
||||
// ── Pieces in Settings' look ───────────────────────────────────────────
|
||||
|
||||
private static void Label(string text, string tip)
|
||||
{
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
|
||||
ImGuiNET.ImGui.TextUnformatted(text);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.SetItemTooltip(tip);
|
||||
}
|
||||
|
||||
private static void Section(string text, float w)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
|
||||
float h = bold.FontSize + 4;
|
||||
dl.AddRectFilled(p, p + new Vector2(w, h), TabActive);
|
||||
dl.AddText(bold, bold.FontSize, p + new Vector2(4, 2), Amber, text);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(w, h));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
}
|
||||
|
||||
private static void Note(string text, float w) => Wrapped(text, w, Mute);
|
||||
|
||||
private static void Warning(string text, float w) => Wrapped(PhosphorIcons.Warning + " " + text, w, Warn);
|
||||
|
||||
private static void Wrapped(string text, float w, uint color)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color);
|
||||
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
|
||||
ImGuiNET.ImGui.TextUnformatted(text);
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
|
||||
private static bool IconButton(string id, Vector2 pos, string glyph, bool enabled)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, new Vector2(18, 18)) && enabled;
|
||||
bool hot = enabled && ImGuiNET.ImGui.IsItemHovered();
|
||||
dl.AddRectFilled(pos, pos + new Vector2(18, 18), hot ? Lighten(BtnFill) : BtnFill);
|
||||
dl.AddRect(pos, pos + new Vector2(18, 18), BtnBord);
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), glyph, pos, new Vector2(18, 18), enabled ? TextDim : ToggleOff);
|
||||
return clicked;
|
||||
}
|
||||
|
||||
private static uint Lighten(uint abgr)
|
||||
{
|
||||
uint a = abgr & 0xFF000000;
|
||||
uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * 1.25f) + 12);
|
||||
uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * 1.25f) + 12);
|
||||
uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * 1.25f) + 12);
|
||||
return a | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
}
|
||||
403
src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs
Normal file
403
src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs
Normal file
|
|
@ -0,0 +1,403 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/InventoryFace.AttrFilter.cs
|
||||
// The Inventory panel's attribute filter: the funnel-list button in the tools
|
||||
// row, its rule editor popup, and the per-item check in the filtered list.
|
||||
// Rules and matching: Compatibility/InventoryAttributeFilter.cs; values:
|
||||
// Compatibility/InventoryFilterFacts.cs.
|
||||
//
|
||||
// Rules on appraised attributes (armor level, ratings, spells...) can't judge
|
||||
// an item the server hasn't identified yet: those items are hidden and
|
||||
// counted, and "Identify N" queues them (InventoryModel.QueueIdentify, a few a
|
||||
// second on AC's main thread). While such a rule is on, the list is rebuilt
|
||||
// once a second so new identifies show up.
|
||||
//
|
||||
// Classic: the filter applies only while the tools row is open (closing the
|
||||
// row turns it off, like the search), so nothing hides items unseen.
|
||||
// Threads: the panel's (render) thread only.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using System.Text;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed partial class InventoryFace
|
||||
{
|
||||
private const string AttrPopupId = "##inv_attrfilter";
|
||||
private static readonly long AttrRefreshTicks = Stopwatch.Frequency; // rebuild while appraisal rules are on
|
||||
|
||||
private InventoryAttributeFilter _attr = new();
|
||||
private bool _attrLoaded;
|
||||
private readonly InventoryFilterFacts _facts = new();
|
||||
// Items the last rebuild hid because they need an identify.
|
||||
private readonly List<uint> _unidentified = new();
|
||||
private int _builtAttrKey = int.MinValue;
|
||||
private long _attrRefreshAt;
|
||||
private bool _attrPass;
|
||||
private bool _openAttr, _attrPopupOpen, _attrSavePending;
|
||||
private string _attrSummary = string.Empty;
|
||||
private int _attrSummaryVersion = -1;
|
||||
// The text rules' edit buffers, by rule.
|
||||
private readonly Dictionary<InventoryFilterRule, byte[]> _attrText = new();
|
||||
|
||||
/// <summary>The attribute filter hides items now (on, has rules and, in Classic, the tools row is open).</summary>
|
||||
private bool AttrOn => _attr.Active && (!InventorySettingsStore.Classic || InventorySettingsStore.ShowTools);
|
||||
|
||||
private void LoadAttrFilter()
|
||||
{
|
||||
if (_attrLoaded) return;
|
||||
_attrLoaded = true;
|
||||
_attr = InventoryAttributeFilter.Parse(InventorySettingsStore.AttrFilter);
|
||||
}
|
||||
|
||||
/// <summary>An appraisal rule is on and a second has passed: rebuild to pick up new identifies.</summary>
|
||||
private bool AttrRefreshDue(bool attrOn) =>
|
||||
attrOn && _attr.NeedsIdentify && Stopwatch.GetTimestamp() >= _attrRefreshAt;
|
||||
|
||||
/// <summary>Start of a list rebuild.</summary>
|
||||
private void BeginAttrPass(bool attrOn)
|
||||
{
|
||||
_attrPass = attrOn;
|
||||
_unidentified.Clear();
|
||||
_attrRefreshAt = Stopwatch.GetTimestamp() + AttrRefreshTicks;
|
||||
}
|
||||
|
||||
/// <summary>Does the attribute filter keep <paramref name="item"/>? An unknown one is hidden and counted.</summary>
|
||||
private bool AttrKeeps(InventoryItem item)
|
||||
{
|
||||
_facts.Bind(item);
|
||||
switch (_attr.Evaluate(_facts))
|
||||
{
|
||||
case FilterVerdict.Match:
|
||||
return true;
|
||||
case FilterVerdict.Unknown:
|
||||
_unidentified.Add(item.Id);
|
||||
return false;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Records an edit: the list rebuilds now; the rules are saved when the editor closes.</summary>
|
||||
private void AttrChanged()
|
||||
{
|
||||
_attr.Touch();
|
||||
_attrSavePending = true;
|
||||
}
|
||||
|
||||
private void SetAttrEnabled(bool on)
|
||||
{
|
||||
if (_attr.Enabled == on) return;
|
||||
_attr.Enabled = on;
|
||||
_attr.Touch();
|
||||
InventorySettingsStore.SetAttrFilter(_attr.Serialize());
|
||||
}
|
||||
|
||||
private void SaveAttrIfPending()
|
||||
{
|
||||
if (!_attrSavePending) return;
|
||||
_attrSavePending = false;
|
||||
InventorySettingsStore.SetAttrFilter(_attr.Serialize());
|
||||
}
|
||||
|
||||
// ── The tools-row button ────────────────────────────────────────────
|
||||
|
||||
private void AttrFilterButton(Vector2 pos)
|
||||
{
|
||||
bool on = AttrOn;
|
||||
if (IconButton("##inv_attr", PhosphorIcons.ListChecks, pos, new Vector2(22, 22), on ? Teal : Mute,
|
||||
on ? Selected : BtnFill, border: on ? Teal : 0u, font: UiFont.Ui11))
|
||||
_openAttr = true;
|
||||
if (!ImGuiNET.ImGui.IsItemHovered()) return;
|
||||
if (_attrSummaryVersion != _attr.Version)
|
||||
{
|
||||
_attrSummaryVersion = _attr.Version;
|
||||
_attrSummary = _attr.Rules.Count == 0 ? string.Empty : _attr.Summary();
|
||||
}
|
||||
string tip = on ? "Attribute filter on: " + _attrSummary
|
||||
: _attr.Rules.Count > 0 ? "Attribute filter off (" + _attrSummary + ")"
|
||||
: "Filter by item attributes (armor level, ratings, spells, slot...)";
|
||||
if (on && _unidentified.Count > 0)
|
||||
tip += "\n" + _unidentified.Count.ToString(CultureInfo.InvariantCulture) + " hidden until identified.";
|
||||
ImGuiNET.ImGui.SetTooltip(tip);
|
||||
}
|
||||
|
||||
// ── The editor popup ────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Once per frame, outside any child.</summary>
|
||||
private void AttrFilterDialog()
|
||||
{
|
||||
if (_openAttr)
|
||||
{
|
||||
_openAttr = false;
|
||||
_attrPopupOpen = true;
|
||||
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetMousePos(), ImGuiCond.Always);
|
||||
ImGuiNET.ImGui.OpenPopup(AttrPopupId);
|
||||
}
|
||||
if (!_attrPopupOpen) return;
|
||||
|
||||
PushAttrStyle();
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8));
|
||||
bool visible = ImGuiNET.ImGui.BeginPopup(AttrPopupId, ImGuiWindowFlags.AlwaysAutoResize);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
if (!visible)
|
||||
{
|
||||
PopAttrStyle();
|
||||
_attrPopupOpen = false; // clicked outside, or Esc
|
||||
SaveAttrIfPending();
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (AttrBody())
|
||||
{
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
_attrPopupOpen = false;
|
||||
SaveAttrIfPending();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
PopAttrStyle();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The popup's contents; true when it should close.</summary>
|
||||
private bool AttrBody()
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.TextUnformatted(PhosphorIcons.ListChecks + " Filter by attributes");
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
|
||||
bool on = _attr.Enabled;
|
||||
if (ImGuiNET.ImGui.Checkbox("Filter on", ref on))
|
||||
{
|
||||
_attr.Enabled = on;
|
||||
AttrChanged();
|
||||
}
|
||||
ImGuiNET.ImGui.SameLine(0, 16);
|
||||
ImGuiNET.ImGui.TextUnformatted("Keep items matching");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.RadioButton("all rules", !_attr.MatchAny)) { _attr.MatchAny = false; AttrChanged(); }
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.RadioButton("any rule", _attr.MatchAny)) { _attr.MatchAny = true; AttrChanged(); }
|
||||
ImGuiNET.ImGui.Separator();
|
||||
|
||||
int remove = -1;
|
||||
for (int i = 0; i < _attr.Rules.Count; i++)
|
||||
{
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
if (RuleRow(_attr.Rules[i])) remove = i;
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
if (remove >= 0)
|
||||
{
|
||||
_attrText.Remove(_attr.Rules[remove]);
|
||||
_attr.Rules.RemoveAt(remove);
|
||||
AttrChanged();
|
||||
}
|
||||
if (_attr.Rules.Count == 0)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
|
||||
ImGuiNET.ImGui.TextUnformatted("No rules yet. Add one, e.g. Armor level >= 300.");
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
if (_attr.Rules.Count < InventoryAttributeFilter.MaxRules
|
||||
&& ImGuiNET.ImGui.Button(PhosphorIcons.Plus + " Add rule"))
|
||||
{
|
||||
_attr.Rules.Add(InventoryAttributeFilter.NewRule(FilterAttr.ArmorLevel));
|
||||
if (_attr.Rules.Count == 1) _attr.Enabled = true; // the first rule turns the filter on
|
||||
AttrChanged();
|
||||
}
|
||||
|
||||
IdentifySection();
|
||||
|
||||
ImGuiNET.ImGui.Separator();
|
||||
bool close = false;
|
||||
if (ImGuiNET.ImGui.Button("Clear rules") && _attr.Rules.Count > 0)
|
||||
{
|
||||
_attr.Rules.Clear();
|
||||
_attrText.Clear();
|
||||
AttrChanged();
|
||||
}
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.Button("Close")) close = true;
|
||||
return close;
|
||||
}
|
||||
|
||||
/// <summary>One rule: attribute, operator, value, remove. True when its remove button was pressed.</summary>
|
||||
private bool RuleRow(InventoryFilterRule rule)
|
||||
{
|
||||
FilterAttrInfo info = InventoryAttributeFilter.Info(rule.Attr);
|
||||
|
||||
ImGuiNET.ImGui.SetNextItemWidth(180);
|
||||
if (ImGuiNET.ImGui.BeginCombo("##attr", AttrLabel(info)))
|
||||
{
|
||||
bool first = true;
|
||||
foreach (FilterAttrInfo a in InventoryAttributeFilter.Attributes)
|
||||
{
|
||||
if (a.NeedsId && first)
|
||||
{
|
||||
first = false;
|
||||
ImGuiNET.ImGui.Separator();
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
|
||||
ImGuiNET.ImGui.TextUnformatted("Needs an identify (*)");
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
if (ImGuiNET.ImGui.Selectable(AttrLabel(a), a.Id == rule.Attr) && a.Id != rule.Attr)
|
||||
{
|
||||
InventoryAttributeFilter.SetAttr(rule, a.Id);
|
||||
AttrChanged();
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(a.Tip);
|
||||
}
|
||||
ImGuiNET.ImGui.EndCombo();
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip(info.Tip);
|
||||
info = InventoryAttributeFilter.Info(rule.Attr);
|
||||
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.SetNextItemWidth(info.Kind == FilterAttrKind.Text ? 120 : 60);
|
||||
if (ImGuiNET.ImGui.BeginCombo("##op", InventoryAttributeFilter.OpLabel(rule.Op)))
|
||||
{
|
||||
foreach (FilterOp op in InventoryAttributeFilter.OpsFor(info.Kind))
|
||||
{
|
||||
if (ImGuiNET.ImGui.Selectable(InventoryAttributeFilter.OpLabel(op), op == rule.Op) && op != rule.Op)
|
||||
{
|
||||
rule.Op = op;
|
||||
AttrChanged();
|
||||
}
|
||||
}
|
||||
ImGuiNET.ImGui.EndCombo();
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
switch (info.Kind)
|
||||
{
|
||||
case FilterAttrKind.Number:
|
||||
{
|
||||
ImGuiNET.ImGui.SetNextItemWidth(90);
|
||||
double v = rule.Number;
|
||||
if (ImGuiNET.ImGui.InputDouble("##num", ref v, 0, 0, "%g") && double.IsFinite(v) && v != rule.Number)
|
||||
{
|
||||
rule.Number = v;
|
||||
AttrChanged();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case FilterAttrKind.Text:
|
||||
{
|
||||
if (!_attrText.TryGetValue(rule, out byte[]? buf))
|
||||
{
|
||||
buf = new byte[64];
|
||||
byte[] src = Encoding.UTF8.GetBytes(rule.Text);
|
||||
Array.Copy(src, buf, Math.Min(src.Length, buf.Length - 1)); // the last byte stays the terminator
|
||||
_attrText[rule] = buf;
|
||||
}
|
||||
ImGuiNET.ImGui.SetNextItemWidth(150);
|
||||
if (ImGuiNET.ImGui.InputText("##text", buf, (uint)buf.Length))
|
||||
{
|
||||
rule.Text = Utf8(buf).Trim();
|
||||
AttrChanged();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case FilterAttrKind.Choice:
|
||||
{
|
||||
ImGuiNET.ImGui.SetNextItemWidth(150);
|
||||
int c = Math.Clamp(rule.Choice, 0, InventoryAttributeFilter.SlotNames.Length - 1);
|
||||
if (ImGuiNET.ImGui.BeginCombo("##choice", InventoryAttributeFilter.SlotNames[c]))
|
||||
{
|
||||
for (int k = 0; k < InventoryAttributeFilter.SlotNames.Length; k++)
|
||||
{
|
||||
if (ImGuiNET.ImGui.Selectable(InventoryAttributeFilter.SlotNames[k], k == c) && k != rule.Choice)
|
||||
{
|
||||
rule.Choice = k;
|
||||
AttrChanged();
|
||||
}
|
||||
}
|
||||
ImGuiNET.ImGui.EndCombo();
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(150, 0)); // a flag has no value; keeps the remove buttons lined up
|
||||
break;
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
bool removeIt = ImGuiNET.ImGui.SmallButton(PhosphorIcons.X);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Remove this rule");
|
||||
return removeIt;
|
||||
}
|
||||
|
||||
private static string AttrLabel(FilterAttrInfo a) => a.NeedsId ? a.Label + " *" : a.Label;
|
||||
|
||||
/// <summary>How many items wait for an identify, and the button that asks for them.</summary>
|
||||
private void IdentifySection()
|
||||
{
|
||||
if (!_attr.NeedsIdentify) return;
|
||||
ImGuiNET.ImGui.Separator();
|
||||
int queued = InventoryModel.IdentifyQueueCount;
|
||||
if (!AttrOn)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
|
||||
ImGuiNET.ImGui.TextUnformatted(InventorySettingsStore.Classic && !InventorySettingsStore.ShowTools
|
||||
? "Open the tools row to use the filter." : "Turn the filter on to see which items need an identify.");
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
else if (_unidentified.Count == 0)
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Green);
|
||||
ImGuiNET.ImGui.TextUnformatted("Every item the rules need is identified.");
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
else
|
||||
{
|
||||
string n = _unidentified.Count.ToString(CultureInfo.InvariantCulture);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.TextUnformatted(n + (_unidentified.Count == 1 ? " item is" : " items are") + " hidden until identified.");
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
if (ImGuiNET.ImGui.Button("Identify " + n)) InventoryModel.QueueIdentify(_unidentified);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Asks the server about them, 4 a second while this panel is open.");
|
||||
}
|
||||
if (queued > 0)
|
||||
{
|
||||
if (AttrOn && _unidentified.Count > 0) ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.TextUnformatted(queued.ToString(CultureInfo.InvariantCulture) + " waiting");
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.SmallButton("Stop")) InventoryModel.ClearIdentifyQueue();
|
||||
}
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute);
|
||||
ImGuiNET.ImGui.TextUnformatted("* needs an identify. Hovering an item also identifies it.");
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
|
||||
private static void PushAttrStyle()
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, Lighten(BtnFill));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.CheckMark, Teal);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Separator, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, BtnFill);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, Lighten(BtnFill));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
|
||||
}
|
||||
|
||||
private static void PopAttrStyle()
|
||||
{
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(9);
|
||||
}
|
||||
}
|
||||
|
|
@ -160,7 +160,7 @@ internal sealed partial class InventoryFace
|
|||
// The open pack: a real pack (Classic has no "All" or "Worn" entry; the paperdoll is Worn).
|
||||
if (_pack == AllPacks || _pack == WornPacks || view.PackOf(_pack) == null)
|
||||
_pack = view.Packs.Length > 0 ? view.Packs[0].Id : AllPacks;
|
||||
bool filtered = _category != 0 || _searchText.Length > 0;
|
||||
bool filtered = FiltersOn;
|
||||
RebuildIfNeeded(view, filtered ? AllPacks : _pack);
|
||||
|
||||
Backdrop(dl, o, w, bottom - o.Y, s);
|
||||
|
|
@ -774,12 +774,13 @@ internal sealed partial class InventoryFace
|
|||
dl.AddLine(p, p + new Vector2(w, 0), Faded(Gold));
|
||||
InventoryTarget? target = InventoryModel.Target;
|
||||
InventoryItem? sel = SelectedItem(view);
|
||||
RefreshSelectionLabels(target);
|
||||
float zh = h - 4, giveW = Math.Min(128 * s, w * 0.42f), dropW = 62 * s;
|
||||
var give = new Vector2(p.X + w - giveW - 2, p.Y + 2);
|
||||
var drop = new Vector2(give.X - dropW - 3, p.Y + 2);
|
||||
Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, "Drop", drop, new Vector2(dropW, zh), 0, "",
|
||||
InventoryModel.DropAvailable, sel, "Drop on the ground: drag an item here, or click to drop the selected item.");
|
||||
Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, target?.ZoneLabel ?? "Give", give, new Vector2(giveW, zh),
|
||||
Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, _dropLabel, drop, new Vector2(dropW, zh), 0, "",
|
||||
InventoryModel.DropAvailable, sel, DropTip);
|
||||
Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, _giveLabel, give, new Vector2(giveW, zh),
|
||||
target?.Id ?? 0, target?.Name ?? "", InventoryModel.GiveAvailable && target != null, sel,
|
||||
target?.ZoneTip ?? "Select a creature, NPC or player in the game to give to.");
|
||||
StatusLine(new Vector2(p.X + 3, p.Y), Math.Max(10, drop.X - p.X - 6), h, view);
|
||||
|
|
@ -803,7 +804,7 @@ internal sealed partial class InventoryFace
|
|||
dl.AddText(tp, StackCol, it.StackText);
|
||||
}
|
||||
if (it.Id == pendingId) Overlay(dl, Art.Waiting, min, cell, Amber);
|
||||
if (it.Id == _selected) Overlay(dl, Art.Selected, min, cell, SelYellow);
|
||||
if (IsPicked(it)) Overlay(dl, Art.Selected, min, cell, SelYellow);
|
||||
}
|
||||
|
||||
/// <summary>Hover, click (select, and a press that may become a drag), double-click (use), right-click (menu).</summary>
|
||||
|
|
@ -813,7 +814,7 @@ internal sealed partial class InventoryFace
|
|||
_hover = it;
|
||||
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
|
||||
{
|
||||
_selected = it.Id;
|
||||
ClickItem(it);
|
||||
_pressItem = it;
|
||||
_pressAt = ImGuiNET.ImGui.GetMousePos();
|
||||
}
|
||||
|
|
@ -823,11 +824,7 @@ internal sealed partial class InventoryFace
|
|||
Act(InventoryActionKind.Use, it, 0, "", 0);
|
||||
}
|
||||
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right))
|
||||
{
|
||||
_selected = it.Id;
|
||||
_ctxItem = it;
|
||||
_openCtx = true;
|
||||
}
|
||||
RightClickItem(it);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -967,8 +964,9 @@ internal sealed partial class InventoryFace
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Inventory panel's remembered choices: Classic or Modern look, and whether the
|
||||
/// Classic view shows its tools row. %LOCALAPPDATA%\RynthCore\inventory_settings.txt,
|
||||
/// The Inventory panel's remembered choices: Classic or Modern look, whether the
|
||||
/// Classic view shows its tools row, its size, and the attribute filter's rules.
|
||||
/// %LOCALAPPDATA%\RynthCore\inventory_settings.txt,
|
||||
/// read once when the panel opens, written in the background when a choice changes.
|
||||
/// </summary>
|
||||
internal static class InventorySettingsStore
|
||||
|
|
@ -983,6 +981,8 @@ internal static class InventorySettingsStore
|
|||
/// <summary>The panel's size in percent of the UI scale (50-150, steps of 5); text follows it.</summary>
|
||||
public static int SizePct { get; private set; } = 80;
|
||||
public static float SizeFactor => SizePct / 100f;
|
||||
/// <summary>The attribute filter's rules (InventoryAttributeFilter.Serialize); "" = none.</summary>
|
||||
public static string AttrFilter { get; private set; } = string.Empty;
|
||||
|
||||
private static string FilePath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "inventory_settings.txt");
|
||||
|
|
@ -1006,6 +1006,7 @@ internal static class InventorySettingsStore
|
|||
if (key == "classic") Classic = val == "1";
|
||||
else if (key == "tools") ShowTools = val == "1";
|
||||
else if (key == "size" && int.TryParse(val, out int pct)) SizePct = Math.Clamp(pct, 50, 150);
|
||||
else if (key == "attrfilter") AttrFilter = val;
|
||||
}
|
||||
}
|
||||
catch { /* defaults stay */ }
|
||||
|
|
@ -1034,13 +1035,22 @@ internal static class InventorySettingsStore
|
|||
Save();
|
||||
}
|
||||
|
||||
public static void SetAttrFilter(string line)
|
||||
{
|
||||
line ??= string.Empty;
|
||||
if (AttrFilter == line) return;
|
||||
AttrFilter = line;
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>Writes the settings in the background (the caller is AC's render thread).</summary>
|
||||
private static void Save()
|
||||
{
|
||||
string text = "# RynthCore inventory panel settings - auto-generated, hand-edits OK.\n"
|
||||
+ "classic=" + (Classic ? "1" : "0") + "\n"
|
||||
+ "tools=" + (ShowTools ? "1" : "0") + "\n"
|
||||
+ "size=" + SizePct + "\n";
|
||||
+ "size=" + SizePct + "\n"
|
||||
+ "attrfilter=" + AttrFilter + "\n";
|
||||
UiBackgroundWriter.Enqueue("inventory settings", () =>
|
||||
{
|
||||
lock (Sync)
|
||||
|
|
|
|||
373
src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs
Normal file
373
src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/InventoryFace.MultiSelect.cs
|
||||
// Several items at once, in both looks:
|
||||
// pick click = one item; Ctrl+click adds / removes one; Shift+click
|
||||
// the run from the last clicked item (Ctrl+Shift adds the run);
|
||||
// right-click menu: Select all shown
|
||||
// act with more than one picked, Drop, Give and a drop on a pack act
|
||||
// on all of them (drag any picked item, or click the zone); the
|
||||
// right-click menu has Drop / Give / Move to for the group
|
||||
// confirm Drop and Give of several ask first (given items don't come
|
||||
// back); Move doesn't
|
||||
// run InventoryModel.RequestBatch sends them one at a time; the status
|
||||
// row shows "Giving 3 of 12 to Bob" with a Stop button
|
||||
// Worn items, and items that can't go where they're sent, are left out (and
|
||||
// counted in the confirm / refusal text).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed partial class InventoryFace
|
||||
{
|
||||
private const int ConfirmNameLines = 10;
|
||||
private static readonly Func<InventoryItem, uint> IdOfItem = static it => it.Id;
|
||||
|
||||
private readonly InventorySelection _multi = new();
|
||||
// A plain press on an item that is part of the group: the group stays for a drag;
|
||||
// released without dragging, the selection narrows to that item (Explorer's rule).
|
||||
private bool _pressNarrow;
|
||||
|
||||
// Drop / Give confirmation (opened at the end of Draw, like the split dialog).
|
||||
private bool _openConfirm;
|
||||
private InventoryRequest[] _confirmItems = Array.Empty<InventoryRequest>();
|
||||
private string _confirmTitle = string.Empty, _confirmOk = string.Empty, _confirmNote = string.Empty;
|
||||
private string[] _confirmNames = Array.Empty<string>();
|
||||
|
||||
// Labels that carry the selection's size, rebuilt only when it or the give target changes.
|
||||
private int _labelsFor = -1;
|
||||
private InventoryTarget? _labelsTarget;
|
||||
private string _dropLabel = "Drop", _giveLabel = "Give", _countBadge = string.Empty, _selHint = string.Empty;
|
||||
private string _menuCount = string.Empty, _menuDrop = string.Empty, _menuGive = string.Empty, _menuMove = string.Empty;
|
||||
private string _selectAllLabel = "Select all shown";
|
||||
|
||||
// Status row cache for a running batch.
|
||||
private InventoryBatchStatus? _batchShown;
|
||||
|
||||
/// <summary>A left click on an item: one item, or Ctrl / Shift to pick several.</summary>
|
||||
private void ClickItem(InventoryItem it)
|
||||
{
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
_pressNarrow = false;
|
||||
if (io.KeyShift)
|
||||
{
|
||||
_multi.Range(_shown, IdOfItem, it.Id, additive: io.KeyCtrl);
|
||||
SelectItem(it);
|
||||
return;
|
||||
}
|
||||
if (io.KeyCtrl)
|
||||
{
|
||||
// Ctrl+click right after a right-click selection keeps that item too.
|
||||
if (_multi.Count == 0 && _selected != 0 && _selected != it.Id) _multi.Single(_selected);
|
||||
if (_multi.Toggle(it.Id)) SelectItem(it);
|
||||
else _selected = _multi.Count > 0 ? _multi.Ids[_multi.Count - 1] : 0;
|
||||
return;
|
||||
}
|
||||
if (_multi.IsMulti && _multi.Contains(it.Id)) _pressNarrow = true;
|
||||
else _multi.Single(it.Id);
|
||||
SelectItem(it);
|
||||
}
|
||||
|
||||
/// <summary>A right click: on a picked item the menu acts on the group, else on that one item.</summary>
|
||||
private void RightClickItem(InventoryItem it)
|
||||
{
|
||||
if (!_multi.Contains(it.Id)) _multi.Single(it.Id);
|
||||
_selected = it.Id;
|
||||
_ctxItem = it;
|
||||
_openCtx = true;
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="it"/> is drawn as selected (the one clicked, or part of the group).</summary>
|
||||
private bool IsPicked(InventoryItem it) => it.Id == _selected || _multi.Contains(it.Id);
|
||||
|
||||
/// <summary>True when an action on <paramref name="it"/> means the whole group.</summary>
|
||||
private bool IsGroup(InventoryItem? it) => _multi.IsMulti && (it == null || _multi.Contains(it.Id));
|
||||
|
||||
/// <summary>
|
||||
/// A zone click or a drop: on the group (Drop, Give, or a pack) when several are picked
|
||||
/// and <paramref name="item"/> is one of them; otherwise the single-item action.
|
||||
/// <paramref name="slot"/> is the pack cell a single item was dropped on (-1: none);
|
||||
/// a group goes to the end of the pack.
|
||||
/// </summary>
|
||||
private void DropOnSelection(DropKind kind, uint targetId, string targetName, InventoryItem? item, int slot = -1)
|
||||
{
|
||||
if (IsGroup(item) && kind is DropKind.Drop or DropKind.Give or DropKind.Pack)
|
||||
{
|
||||
GroupAction(kind, targetId, targetName);
|
||||
return;
|
||||
}
|
||||
if (item != null) DropOn(kind, targetId, targetName, item, slot);
|
||||
}
|
||||
|
||||
/// <summary>Builds the group's requests; Drop and Give ask first, Move starts at once.</summary>
|
||||
private void GroupAction(DropKind kind, uint targetId, string targetName)
|
||||
{
|
||||
InventoryView view = InventoryModel.Current;
|
||||
InventoryActionKind action = kind switch
|
||||
{
|
||||
DropKind.Drop => InventoryActionKind.Drop,
|
||||
DropKind.Give => InventoryActionKind.Give,
|
||||
_ => InventoryActionKind.Move,
|
||||
};
|
||||
if (action == InventoryActionKind.Give && targetId == 0) { Refuse("Select someone in the game to give to."); return; }
|
||||
|
||||
var list = new List<InventoryRequest>(_multi.Count);
|
||||
int worn = 0, gone = 0, cant = 0;
|
||||
foreach (uint id in _multi.Ids)
|
||||
{
|
||||
InventoryItem? it = FindAny(view, id);
|
||||
if (it == null) { gone++; continue; }
|
||||
if (it.Wielder != 0) { worn++; continue; }
|
||||
if (action == InventoryActionKind.Move)
|
||||
{
|
||||
// Already there (or the pack itself): skipped quietly, like a single item's drop.
|
||||
if (it.Id == targetId || it.Container == targetId) continue;
|
||||
// Foci and packs go only in the main pack (a side pack has no pack slots).
|
||||
if ((it.RequiresPackSlot || it.IsPack) && targetId != view.PlayerId) { cant++; continue; }
|
||||
}
|
||||
list.Add(new InventoryRequest
|
||||
{
|
||||
Kind = action, ItemId = it.Id, TargetId = action == InventoryActionKind.Drop ? 0 : targetId,
|
||||
TargetName = action == InventoryActionKind.Drop ? string.Empty : targetName, ItemName = it.Name,
|
||||
});
|
||||
}
|
||||
if (list.Count > InventoryModel.MaxBatch)
|
||||
{
|
||||
Refuse($"{list.Count} items: at most {InventoryModel.MaxBatch} at once.");
|
||||
return;
|
||||
}
|
||||
|
||||
string note = LeftOutText(worn, gone, cant);
|
||||
if (list.Count == 0)
|
||||
{
|
||||
// All already in that pack: nothing to do, nothing to say.
|
||||
if (action == InventoryActionKind.Move && note.Length == 0) return;
|
||||
Refuse(note.Length > 0 ? "Nothing to send: " + note : "Nothing to send.");
|
||||
return;
|
||||
}
|
||||
if (action == InventoryActionKind.Move)
|
||||
{
|
||||
StartBatch(list);
|
||||
if (note.Length > 0 && _refusal.Length == 0) Refuse("Left out: " + note);
|
||||
return;
|
||||
}
|
||||
OpenConfirm(action, list, targetName, note);
|
||||
}
|
||||
|
||||
/// <summary>"2 worn, 1 gone" for the items a group action leaves out ("" when none).</summary>
|
||||
private static string LeftOutText(int worn, int gone, int cant)
|
||||
{
|
||||
var parts = new List<string>(3);
|
||||
if (worn > 0) parts.Add($"{worn} worn");
|
||||
if (cant > 0) parts.Add($"{cant} can only go in the main pack");
|
||||
if (gone > 0) parts.Add($"{gone} gone");
|
||||
return string.Join(", ", parts);
|
||||
}
|
||||
|
||||
private void StartBatch(IReadOnlyList<InventoryRequest> list)
|
||||
{
|
||||
if (!InventoryModel.RequestBatch(list, out string why)) Refuse(why);
|
||||
else _refusal = string.Empty;
|
||||
}
|
||||
|
||||
// ── Confirmation ────────────────────────────────────────────────────
|
||||
|
||||
private void OpenConfirm(InventoryActionKind action, List<InventoryRequest> list, string targetName, string note)
|
||||
{
|
||||
string n = list.Count.ToString(CultureInfo.InvariantCulture);
|
||||
_confirmItems = list.ToArray();
|
||||
_confirmTitle = action == InventoryActionKind.Give
|
||||
? $"Give {n} item{(list.Count == 1 ? "" : "s")} to {targetName}?"
|
||||
: $"Drop {n} item{(list.Count == 1 ? "" : "s")} on the ground?";
|
||||
_confirmOk = (action == InventoryActionKind.Give ? PhosphorIcons.Gift + " Give " : PhosphorIcons.ArrowFatDown + " Drop ") + n;
|
||||
_confirmNote = note.Length > 0 ? "Left out: " + note + "." : string.Empty;
|
||||
_confirmNames = ConfirmNames(list);
|
||||
_openConfirm = true;
|
||||
}
|
||||
|
||||
/// <summary>The items by name ("Pyreal x3"), in picked order, at most ConfirmNameLines lines.</summary>
|
||||
private static string[] ConfirmNames(List<InventoryRequest> list)
|
||||
{
|
||||
var order = new List<string>();
|
||||
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
foreach (InventoryRequest r in list)
|
||||
{
|
||||
if (counts.TryGetValue(r.ItemName, out int c)) counts[r.ItemName] = c + 1;
|
||||
else { counts[r.ItemName] = 1; order.Add(r.ItemName); }
|
||||
}
|
||||
var lines = new List<string>(Math.Min(order.Count, ConfirmNameLines) + 1);
|
||||
for (int i = 0; i < order.Count && i < ConfirmNameLines; i++)
|
||||
lines.Add(counts[order[i]] > 1 ? $"{order[i]} x{counts[order[i]]}" : order[i]);
|
||||
if (order.Count > ConfirmNameLines)
|
||||
lines.Add($"...and {order.Count - ConfirmNameLines} more kind{(order.Count - ConfirmNameLines == 1 ? "" : "s")}");
|
||||
return lines.ToArray();
|
||||
}
|
||||
|
||||
private void ConfirmDialog()
|
||||
{
|
||||
if (_openConfirm)
|
||||
{
|
||||
_openConfirm = false;
|
||||
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetMousePos(), ImGuiCond.Always);
|
||||
ImGuiNET.ImGui.OpenPopup("##inv_batch_confirm");
|
||||
}
|
||||
PushMenuStyle();
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup("##inv_batch_confirm");
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
if (!open) { PopMenuStyle(); return; }
|
||||
try
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.TextUnformatted(_confirmTitle);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
foreach (string line in _confirmNames) ImGuiNET.ImGui.BulletText(line);
|
||||
if (_confirmNote.Length > 0) ImGuiNET.ImGui.TextDisabled(_confirmNote);
|
||||
if (_confirmItems.Length > 0 && _confirmItems[0].Kind == InventoryActionKind.Give)
|
||||
ImGuiNET.ImGui.TextDisabled("Given items can't be taken back.");
|
||||
|
||||
bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning;
|
||||
Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4);
|
||||
if (Button("##bc_ok", _confirmOk, bp, new Vector2(110, 24), Teal, BtnFill, enabled: idle && _confirmItems.Length > 0))
|
||||
{
|
||||
StartBatch(_confirmItems);
|
||||
_confirmItems = Array.Empty<InventoryRequest>();
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
}
|
||||
if (!idle) ImGuiNET.ImGui.SetItemTooltip("An item action is still waiting.");
|
||||
if (Button("##bc_cancel", "Cancel", bp + new Vector2(116, 0), new Vector2(80, 24), Text, BtnFill))
|
||||
{
|
||||
_confirmItems = Array.Empty<InventoryRequest>();
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
}
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(bp + new Vector2(0, 28));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(200, 0));
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
PopMenuStyle();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Labels ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Zone labels, menu entries and hints that show the group's size. Rebuilt only on change.</summary>
|
||||
private void RefreshSelectionLabels(InventoryTarget? target)
|
||||
{
|
||||
int n = _multi.IsMulti ? _multi.Count : 0;
|
||||
if (n == _labelsFor && ReferenceEquals(target, _labelsTarget)) return;
|
||||
_labelsFor = n;
|
||||
_labelsTarget = target;
|
||||
string count = n.ToString(CultureInfo.InvariantCulture);
|
||||
_dropLabel = n > 0 ? "Drop " + count : "Drop";
|
||||
_giveLabel = target == null ? "Give" : n > 0 ? "Give " + count + ": " + target.Name : target.ZoneLabel;
|
||||
_countBadge = n > 0 ? count : string.Empty;
|
||||
_selHint = n > 0
|
||||
? count + " selected: Drop, Give, drag to a pack, or right-click. Ctrl+click adds or removes; Shift+click picks a run."
|
||||
: string.Empty;
|
||||
_menuCount = count + " items selected";
|
||||
_menuDrop = "Drop " + count + " items";
|
||||
_menuGive = target == null ? string.Empty : "Give " + count + " items to " + target.Name;
|
||||
_menuMove = "Move " + count + " items to";
|
||||
}
|
||||
|
||||
// ── Group menu ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The right-click menu when the clicked item is part of a group.</summary>
|
||||
private void GroupMenu(InventoryView view, InventoryItem clicked)
|
||||
{
|
||||
bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning;
|
||||
InventoryTarget? target = InventoryModel.Target;
|
||||
RefreshSelectionLabels(target);
|
||||
ImGuiNET.ImGui.TextDisabled(_menuCount);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem(_menuDrop, "", false, idle && InventoryModel.DropAvailable))
|
||||
GroupAction(DropKind.Drop, 0, string.Empty);
|
||||
if (target != null && ImGuiNET.ImGui.MenuItem(_menuGive, "", false, idle && InventoryModel.GiveAvailable))
|
||||
GroupAction(DropKind.Give, target.Id, target.Name);
|
||||
if (ImGuiNET.ImGui.BeginMenu(_menuMove, idle))
|
||||
{
|
||||
foreach (InventoryPack p in view.Packs)
|
||||
if (ImGuiNET.ImGui.MenuItem(p.Name, p.FillText, false, true))
|
||||
GroupAction(DropKind.Pack, p.Id, p.Name);
|
||||
ImGuiNET.ImGui.EndMenu();
|
||||
}
|
||||
ImGuiNET.ImGui.Separator();
|
||||
SelectionMenuItems(clicked);
|
||||
if (!idle) ImGuiNET.ImGui.TextDisabled("(an item action is waiting)");
|
||||
}
|
||||
|
||||
/// <summary>Select all shown / select only this one (both menus).</summary>
|
||||
private void SelectionMenuItems(InventoryItem clicked)
|
||||
{
|
||||
if (ImGuiNET.ImGui.MenuItem(_selectAllLabel, "", false, _shown.Count > 1))
|
||||
_multi.SelectAll(_shown, IdOfItem);
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
ImGuiNET.ImGui.SetTooltip("Pick every item the grid shows (this pack, or the search's matches). Ctrl+click and Shift+click also pick several.");
|
||||
if (_multi.IsMulti && ImGuiNET.ImGui.MenuItem("Select only this item"))
|
||||
{
|
||||
_multi.Single(clicked.Id);
|
||||
_selected = clicked.Id;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Status and pieces ───────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// A running batch in the status row: progress and a Stop button at the row's right end.
|
||||
/// False when no batch is running.
|
||||
/// </summary>
|
||||
private bool BatchStatus(ImDrawListPtr dl, Vector2 p, float w, float statusH, float ty)
|
||||
{
|
||||
InventoryBatchStatus? batch = InventoryModel.Batch;
|
||||
if (batch == null || !batch.Running) { _batchShown = null; return false; }
|
||||
_batchShown = batch;
|
||||
float stop = Math.Min(statusH - 2, 20);
|
||||
var stopPos = new Vector2(p.X + w - stop - 1, p.Y + (statusH - stop) * 0.5f);
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.HourglassMedium, p, new Vector2(16, statusH), Amber);
|
||||
dl.PushClipRect(p, new Vector2(stopPos.X - 2, p.Y + statusH), true);
|
||||
dl.AddText(new Vector2(p.X + 18, ty), Amber, batch.Text);
|
||||
dl.PopClipRect();
|
||||
if (IconButton("##inv_batch_stop", PhosphorIcons.Stop, stopPos, new Vector2(stop, stop), Red, BtnFill,
|
||||
enabled: !batch.Stopping, font: UiFont.Ui11))
|
||||
InventoryModel.CancelBatch();
|
||||
ImGuiNET.ImGui.SetItemTooltip("Stop: no more items are sent (the one in flight still finishes).");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The group's size on the drag ghost.</summary>
|
||||
private void DragBadge(ImDrawListPtr fg, Vector2 ghostMin)
|
||||
{
|
||||
if (!IsGroup(_dragItem) || _countBadge.Length == 0) return;
|
||||
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_countBadge);
|
||||
var tp = ghostMin + new Vector2(Icon - ts.X + 4, Icon - ts.Y + 4);
|
||||
fg.AddRectFilled(tp - new Vector2(3, 1), tp + ts + new Vector2(3, 1), Faded(Black), 4);
|
||||
fg.AddText(tp, Amber, _countBadge);
|
||||
}
|
||||
|
||||
/// <summary>Forgets picked items that left the inventory (given, dropped, merged). On a new view only.</summary>
|
||||
private void PruneSelection(InventoryView view)
|
||||
{
|
||||
if (_multi.Count == 0) return;
|
||||
_multi.Prune(id => FindAny(view, id) != null);
|
||||
}
|
||||
|
||||
/// <summary>An item in the packs or worn, by id.</summary>
|
||||
private static InventoryItem? FindAny(InventoryView view, uint id)
|
||||
{
|
||||
foreach (InventoryPack p in view.Packs)
|
||||
foreach (InventoryItem it in p.Items)
|
||||
if (it.Id == id) return it;
|
||||
foreach (InventoryItem it in view.Worn)
|
||||
if (it.Id == id) return it;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -7,20 +7,24 @@
|
|||
// Modern the Phase 1 layout, below
|
||||
//
|
||||
// header burden (percent of capacity) and pyreals; item count
|
||||
// tools search box, sort picker; category chips
|
||||
// tools search box, attribute filter (InventoryFace.AttrFilter.cs), sort
|
||||
// picker; category chips
|
||||
// packs All, Main pack, each side pack (its icon and fill), Worn
|
||||
// grid the chosen pack's items as icons with stack counts; hover for a
|
||||
// tooltip (asks the server to identify an unknown item, throttled);
|
||||
// double-click uses; right-click for Use / Equip / Split / Move to /
|
||||
// Drop / Give; drag onto a pack to move, onto Equip / Drop / Give
|
||||
// zones Equip, Drop, Give-to-<selected creature>: drop targets for a drag,
|
||||
// or buttons for the selected item
|
||||
// or buttons for the selected item(s)
|
||||
// status the one action waiting for the server (with a timer), or how the
|
||||
// last one ended
|
||||
// last one ended; a several-item run's progress and Stop
|
||||
// several Ctrl+click / Shift+click / Select all pick several items for Drop,
|
||||
// Give or Move (InventoryFace.MultiSelect.cs)
|
||||
//
|
||||
// Data: InventoryModel (Compatibility), captured and acted on on AC's main
|
||||
// thread. This face only reads its published objects and posts requests; one
|
||||
// item action at a time (a click while one waits is refused, never queued).
|
||||
// Several items go as a batch the model sends one after another.
|
||||
// Per frame: no allocation except the tooltip of a newly hovered item and the
|
||||
// filtered list when the view, pack, filter, search or sort change.
|
||||
// ============================================================================
|
||||
|
|
@ -122,6 +126,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
public void OnShown()
|
||||
{
|
||||
InventorySettingsStore.Load();
|
||||
LoadAttrFilter();
|
||||
InventoryModel.Subscribe();
|
||||
}
|
||||
|
||||
|
|
@ -130,6 +135,8 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
InventoryModel.Hover(0);
|
||||
InventoryModel.Unsubscribe();
|
||||
_dragItem = _pressItem = null;
|
||||
_pressNarrow = false;
|
||||
ItemDragBridge.EndPopOutDrag();
|
||||
UiDropTargets.EngineDragObject = 0;
|
||||
_lootAdd.Cancel();
|
||||
}
|
||||
|
|
@ -168,6 +175,8 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
DrawDragGhost();
|
||||
ContextMenu(view);
|
||||
SplitDialog(view);
|
||||
ConfirmDialog();
|
||||
AttrFilterDialog();
|
||||
_lootAdd.Draw();
|
||||
_picker.Draw();
|
||||
}
|
||||
|
|
@ -254,7 +263,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float sortW = 118;
|
||||
float boxW = Math.Max(80, w - sortW - 26 - 8);
|
||||
float boxW = Math.Max(80, w - sortW - 26 - 26 - 8);
|
||||
if (TextBox("##inv_search", _search, p, boxW, PhosphorIcons.MagnifyingGlass + " Search names", out _))
|
||||
_searchText = Utf8(_search).Trim().ToLowerInvariant();
|
||||
if (IconButton("##inv_clear", PhosphorIcons.X, new Vector2(p.X + boxW + 2, p.Y), new Vector2(22, 22), Mute, BtnFill,
|
||||
|
|
@ -264,6 +273,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
_searchText = string.Empty;
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Clear the search");
|
||||
AttrFilterButton(new Vector2(p.X + boxW + 26, p.Y));
|
||||
Vector2 sp = new(p.X + w - sortW, p.Y);
|
||||
if (Button("##inv_sortbtn", SortLabels[_sort], sp, new Vector2(sortW, 22), Text, BtnFill,
|
||||
leftAlign: true))
|
||||
|
|
@ -316,12 +326,17 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
private void RebuildIfNeeded(InventoryView view, uint pack)
|
||||
{
|
||||
bool classic = InventorySettingsStore.Classic;
|
||||
bool attrOn = AttrOn;
|
||||
int attrKey = attrOn ? _attr.Version : -1;
|
||||
if (ReferenceEquals(view, _builtFor) && _builtPack == pack && _builtSort == _sort
|
||||
&& _builtCategory == _category && ReferenceEquals(_builtSearch, _searchText) && _builtClassic == classic
|
||||
&& _builtOrderVersion == Net.InventoryOrder.Version)
|
||||
&& _builtOrderVersion == Net.InventoryOrder.Version && _builtAttrKey == attrKey && !AttrRefreshDue(attrOn))
|
||||
return;
|
||||
if (_builtPack != pack || !ReferenceEquals(_builtSearch, _searchText) || _builtCategory != _category)
|
||||
if (_builtPack != pack || !ReferenceEquals(_builtSearch, _searchText) || _builtCategory != _category || _builtAttrKey != attrKey)
|
||||
_gridFirstRow = 0; // another pack or filter: back to the top (Classic grid)
|
||||
_builtAttrKey = attrKey;
|
||||
BeginAttrPass(attrOn);
|
||||
if (!ReferenceEquals(view, _builtFor)) PruneSelection(view);
|
||||
_builtFor = view;
|
||||
_builtPack = pack;
|
||||
_builtSort = _sort;
|
||||
|
|
@ -356,6 +371,9 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
_countText = _shown.Count == total
|
||||
? total.ToString(CultureInfo.InvariantCulture) + " items"
|
||||
: _shown.Count.ToString(CultureInfo.InvariantCulture) + " of " + total.ToString(CultureInfo.InvariantCulture);
|
||||
if (_unidentified.Count > 0)
|
||||
_countText += ", " + _unidentified.Count.ToString(CultureInfo.InvariantCulture) + " not ID'd";
|
||||
_selectAllLabel = "Select all shown (" + _shown.Count.ToString(CultureInfo.InvariantCulture) + ")";
|
||||
// The Classic grid's caption, retail's "Contents of <pack>".
|
||||
_captionText = pack == WornPacks ? "Worn"
|
||||
: one == null ? (_shown.Count == total ? "All packs" : "Matches in all packs: " + _countText)
|
||||
|
|
@ -388,7 +406,10 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
|
||||
/// <summary>A grid cell is a slot only while the list is the server's, whole and in pack order, and the item is an ordinary one.</summary>
|
||||
private bool CellsAreSlots(InventoryItem item) =>
|
||||
_orderKnown && _sort == 0 && _category == 0 && _searchText.Length == 0 && !item.RequiresPackSlot && !item.IsPack;
|
||||
_orderKnown && _sort == 0 && !FiltersOn && !item.RequiresPackSlot && !item.IsPack;
|
||||
|
||||
/// <summary>Some filter hides items: a category, search text or the attribute filter.</summary>
|
||||
private bool FiltersOn => _category != 0 || _searchText.Length > 0 || AttrOn;
|
||||
|
||||
/// <summary>The slot an item holds now among its pack's ordinary items, or -1 when unknown.</summary>
|
||||
private static int SlotOf(InventoryItem item)
|
||||
|
|
@ -411,6 +432,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
if (_skipSlotItems && it.RequiresPackSlot) continue;
|
||||
if (_category != 0 && it.Category != cat) continue;
|
||||
if (_searchText.Length > 0 && !it.SearchName.Contains(_searchText, StringComparison.Ordinal)) continue;
|
||||
if (_attrPass && !AttrKeeps(it)) continue;
|
||||
_shown.Add(it);
|
||||
}
|
||||
}
|
||||
|
|
@ -513,7 +535,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
|
||||
if (_shown.Count == 0)
|
||||
{
|
||||
dl.AddText(o + new Vector2(4, 4), Mute, _searchText.Length > 0 || _category != 0 ? "Nothing matches." : "Empty.");
|
||||
dl.AddText(o + new Vector2(4, 4), Mute, FiltersOn ? "Nothing matches." : "Empty.");
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(avail, 20));
|
||||
}
|
||||
else
|
||||
|
|
@ -538,7 +560,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
|
||||
if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
|
||||
{
|
||||
_selected = hot.Id;
|
||||
ClickItem(hot);
|
||||
_pressItem = hot;
|
||||
_pressAt = mouse;
|
||||
}
|
||||
|
|
@ -548,11 +570,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
Act(InventoryActionKind.Use, hot, 0, "", 0);
|
||||
}
|
||||
if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right))
|
||||
{
|
||||
_selected = hot.Id;
|
||||
_ctxItem = hot;
|
||||
_openCtx = true;
|
||||
}
|
||||
RightClickItem(hot);
|
||||
if (_pressItem != null && _dragItem == null && ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)
|
||||
&& Vector2.DistanceSquared(mouse, _pressAt) > 25)
|
||||
_dragItem = _pressItem;
|
||||
|
|
@ -571,7 +589,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
InventoryItem it = _shown[i];
|
||||
var cmin = new Vector2(o.X + c * Cell, o.Y + r * Cell);
|
||||
var cmax = cmin + new Vector2(Cell - 2, Cell - 2);
|
||||
bool sel = it.Id == _selected;
|
||||
bool sel = IsPicked(it);
|
||||
dl.AddRectFilled(cmin, cmax, i == hoverIdx ? CellHot : CellBg, 3);
|
||||
DrawItemIcon(dl, it.Id, cmin + new Vector2(2, 2), Icon, ReferenceEquals(it, _dragItem) ? 0x60FFFFFFu : 0xFFFFFFFFu);
|
||||
if (it.StackText.Length > 0)
|
||||
|
|
@ -612,21 +630,24 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
InventoryTarget? target = InventoryModel.Target;
|
||||
InventoryItem? sel = SelectedItem(view);
|
||||
RefreshSelectionLabels(target);
|
||||
float zw = (w - 8) / 3f;
|
||||
var sz = new Vector2(zw, ZoneH);
|
||||
|
||||
Zone("##z_equip", DropKind.Equip, PhosphorIcons.Shield, "Equip", new Vector2(p.X, p.Y), sz, 0, "",
|
||||
InventoryModel.WieldAvailable, sel,
|
||||
"Equip: drag an item here, or click to equip the selected item.");
|
||||
Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, "Drop", new Vector2(p.X + zw + 4, p.Y), sz, 0, "",
|
||||
InventoryModel.DropAvailable, sel,
|
||||
"Drop on the ground: drag an item here, or click to drop the selected item.");
|
||||
Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, target?.ZoneLabel ?? "Give", new Vector2(p.X + 2 * (zw + 4), p.Y), sz,
|
||||
Zone("##z_drop", DropKind.Drop, PhosphorIcons.ArrowFatDown, _dropLabel, new Vector2(p.X + zw + 4, p.Y), sz, 0, "",
|
||||
InventoryModel.DropAvailable, sel, DropTip);
|
||||
Zone("##z_give", DropKind.Give, PhosphorIcons.Gift, _giveLabel, new Vector2(p.X + 2 * (zw + 4), p.Y), sz,
|
||||
target?.Id ?? 0, target?.Name ?? "", InventoryModel.GiveAvailable && target != null, sel,
|
||||
target?.ZoneTip ?? "Select a creature, NPC or player in the game to give to.");
|
||||
NextLine(p, ZoneH + 4);
|
||||
}
|
||||
|
||||
private const string DropTip = "Drop on the ground: drag an item here, or click to drop the selected item(s).\n"
|
||||
+ "Ctrl+click or Shift+click items to drop several.";
|
||||
|
||||
private void Zone(string id, DropKind kind, string glyph, string label, Vector2 pos, Vector2 size, uint targetId,
|
||||
string targetName, bool enabled, InventoryItem? selected, string tip)
|
||||
{
|
||||
|
|
@ -646,20 +667,14 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
dl.PopClipRect();
|
||||
if (enabled)
|
||||
_targets.Add(new Target { Min = pos, Max = pos + size, Kind = kind, Id = targetId, Name = targetName });
|
||||
if (clicked && enabled && selected != null)
|
||||
DropOn(kind, targetId, targetName, selected); // refused with a message while one waits
|
||||
// Refused with a message while one waits. Equip is always the one selected item.
|
||||
if (clicked && enabled && kind != DropKind.Equip && _multi.IsMulti)
|
||||
DropOnSelection(kind, targetId, targetName, null);
|
||||
else if (clicked && enabled && selected != null)
|
||||
DropOn(kind, targetId, targetName, selected);
|
||||
}
|
||||
|
||||
private InventoryItem? SelectedItem(InventoryView view)
|
||||
{
|
||||
if (_selected == 0) return null;
|
||||
foreach (InventoryPack p in view.Packs)
|
||||
foreach (InventoryItem it in p.Items)
|
||||
if (it.Id == _selected) return it;
|
||||
foreach (InventoryItem it in view.Worn)
|
||||
if (it.Id == _selected) return it;
|
||||
return null;
|
||||
}
|
||||
private InventoryItem? SelectedItem(InventoryView view) => _selected == 0 ? null : FindAny(view, _selected);
|
||||
|
||||
// ── Status row ──────────────────────────────────────────────────────
|
||||
|
||||
|
|
@ -681,6 +696,8 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
InventoryPending? pending = InventoryModel.Pending;
|
||||
InventoryResult? result = InventoryModel.LastResult;
|
||||
float ty = p.Y + (statusH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||
// A several-item run: its progress and Stop (a button, so outside the clip below).
|
||||
if (BatchStatus(dl, p, w, statusH, ty)) return;
|
||||
dl.PushClipRect(p, p + new Vector2(w, statusH), true);
|
||||
if (pending != null)
|
||||
{
|
||||
|
|
@ -710,6 +727,11 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
p, new Vector2(16, statusH), result.Ok ? Green : Red);
|
||||
dl.AddText(new Vector2(p.X + 18, ty), result.Ok ? Green : Red, result.Text);
|
||||
}
|
||||
else if (_selHint.Length > 0)
|
||||
{
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CheckSquare, p, new Vector2(16, statusH), Teal);
|
||||
dl.AddText(new Vector2(p.X + 18, ty), Text, _selHint);
|
||||
}
|
||||
else if (idleView != null)
|
||||
{
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Coins, p, new Vector2(16, statusH), Amber);
|
||||
|
|
@ -750,7 +772,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
case DropKind.Pack:
|
||||
if (slot == -2)
|
||||
{
|
||||
Refuse(_sort != 0 || _category != 0 || _searchText.Length > 0
|
||||
Refuse(_sort != 0 || FiltersOn
|
||||
? "To reorder, set Sort to Pack order and clear the search and filter."
|
||||
: "The pack's order isn't known yet: log in again so the panel can learn it.");
|
||||
return;
|
||||
|
|
@ -802,12 +824,13 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>Back to everything: no search text, no category.</summary>
|
||||
/// <summary>Back to everything: no search text, no category, the attribute filter off (its rules kept).</summary>
|
||||
private void ClearFilters()
|
||||
{
|
||||
Array.Clear(_search);
|
||||
_searchText = string.Empty;
|
||||
_category = 0;
|
||||
SetAttrEnabled(false);
|
||||
}
|
||||
|
||||
private void Refuse(string why)
|
||||
|
|
@ -834,15 +857,23 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
{
|
||||
if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left))
|
||||
{
|
||||
InventoryItem? item = _dragItem;
|
||||
InventoryItem? item = _dragItem, pressed = _pressItem;
|
||||
bool narrow = _pressNarrow;
|
||||
_dragItem = null;
|
||||
_pressItem = null;
|
||||
if (item == null) return;
|
||||
_pressNarrow = false;
|
||||
if (item == null)
|
||||
{
|
||||
// A plain click on one of a group, not dragged: just that item now.
|
||||
if (narrow && pressed != null) _multi.Single(pressed.Id);
|
||||
return;
|
||||
}
|
||||
ItemDragBridge.EndPopOutDrag();
|
||||
Vector2 m = ImGuiNET.ImGui.GetMousePos();
|
||||
foreach (Target t in _targets)
|
||||
{
|
||||
if (m.X < t.Min.X || m.Y < t.Min.Y || m.X >= t.Max.X || m.Y >= t.Max.Y) continue;
|
||||
DropOn(t.Kind, t.Id, t.Name, item, t.Slot);
|
||||
DropOnSelection(t.Kind, t.Id, t.Name, item, t.Slot);
|
||||
return;
|
||||
}
|
||||
// Let go outside this panel: another engine panel that takes items (Item Count,
|
||||
|
|
@ -852,13 +883,51 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
}
|
||||
}
|
||||
|
||||
private void DrawDragGhost()
|
||||
/// <summary>
|
||||
/// ImGui drag-and-drop payload type for one item (uint object id), published while an item is
|
||||
/// dragged so other ImGui windows (RynthAi's Mini Remote slots) can accept the drop. Must
|
||||
/// match MiniRemoteHud.ItemPayloadType in RynthAi.
|
||||
/// </summary>
|
||||
public const string ItemPayloadType = "RYNTH_INV_ITEM";
|
||||
|
||||
/// <summary>
|
||||
/// Selects <paramref name="it"/> here and in the game, like a click in the retail inventory, so
|
||||
/// "selected item" features (Mini Remote slots, item info, loot rules) see it too.
|
||||
/// </summary>
|
||||
private void SelectItem(InventoryItem it)
|
||||
{
|
||||
_selected = it.Id;
|
||||
// Queued, not called inline: Draw runs inside EndScene, and AC's SetSelectedObject rebuilds
|
||||
// UI elements, so it runs at the main-thread queue's drain point instead.
|
||||
if (ClientHelperHooks.GetSelectedItemId() != it.Id)
|
||||
AcMainThreadQueue.EnqueueSetSelectedObject(it.Id);
|
||||
}
|
||||
|
||||
private unsafe void DrawDragGhost()
|
||||
{
|
||||
if (_dragItem == null) return;
|
||||
var fg = ImGuiNET.ImGui.GetForegroundDrawList();
|
||||
Vector2 m = ImGuiNET.ImGui.GetMousePos() - new Vector2(Icon * 0.5f, Icon * 0.5f);
|
||||
DrawItemIcon(fg, _dragItem.Id, m, Icon, 0xD0FFFFFF);
|
||||
DragBadge(fg, m);
|
||||
ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
|
||||
|
||||
// A popped-out Inventory draws in its own ImGui context: the client's drop targets
|
||||
// only see the drag through the bridge, which republishes it in the main context.
|
||||
if (ImGuiPopOuts.InPopOutFrame)
|
||||
{
|
||||
ItemDragBridge.NotePopOutDrag(_dragItem.Id);
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-submitted every frame of the drag (an extern source expires when it isn't); the
|
||||
// ghost above is the preview, so no ImGui tooltip.
|
||||
if (ImGuiNET.ImGui.BeginDragDropSource(ImGuiDragDropFlags.SourceExtern | ImGuiDragDropFlags.SourceNoPreviewTooltip))
|
||||
{
|
||||
uint id = _dragItem.Id;
|
||||
ImGuiNET.ImGui.SetDragDropPayload(ItemPayloadType, (IntPtr)(&id), sizeof(uint));
|
||||
ImGuiNET.ImGui.EndDragDropSource();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Tooltip ─────────────────────────────────────────────────────────
|
||||
|
|
@ -948,7 +1017,8 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
{
|
||||
InventoryItem? it = _ctxItem;
|
||||
if (it == null) { ImGuiNET.ImGui.CloseCurrentPopup(); return; }
|
||||
bool idle = InventoryModel.Pending == null;
|
||||
if (IsGroup(it)) { GroupMenu(view, it); return; }
|
||||
bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning;
|
||||
ImGuiNET.ImGui.TextDisabled(it.Name);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.MenuItem("Use", "double-click", false, idle))
|
||||
|
|
@ -985,6 +1055,13 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
_lootAdd.Open(it.Id, it.Name, toOpenProfile: false);
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
ImGuiNET.ImGui.SetTooltip("Make a RynthAi loot rule for this item (preview first)");
|
||||
if (!it.IsPack && ImGuiNET.ImGui.MenuItem("Add to item count HUD"))
|
||||
UI.Data.RynthAiCommands.ApplyRemoteCommand("itemhudadd", it.Name);
|
||||
if (ImGuiNET.ImGui.IsItemHovered())
|
||||
ImGuiNET.ImGui.SetTooltip("Track how many of these you carry on RynthAi's floating item count HUD (/ra itemhud add)");
|
||||
if (!it.IsPack) MiniRemoteMenu(it);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
SelectionMenuItems(it);
|
||||
if (!idle)
|
||||
ImGuiNET.ImGui.TextDisabled("(an item action is waiting)");
|
||||
}
|
||||
|
|
@ -995,6 +1072,36 @@ internal sealed partial class InventoryFace : IImGuiPanel
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>RynthAi Mini Remote quick-use grid size (HudState.MiniRemoteSlotCount, 6 rows of 5).</summary>
|
||||
private const int MiniRemoteSlots = 30, MiniRemoteColumns = 5;
|
||||
|
||||
/// <summary>
|
||||
/// "Add to Mini Remote" submenu: first empty slot, or a numbered grid laid out like the
|
||||
/// remote's own slots. RynthAi validates the item and reports the result in chat.
|
||||
/// </summary>
|
||||
private static void MiniRemoteMenu(InventoryItem it)
|
||||
{
|
||||
if (!ImGuiNET.ImGui.BeginMenu("Add to Mini Remote")) return;
|
||||
if (ImGuiNET.ImGui.MenuItem("First empty slot"))
|
||||
UI.Data.RynthAiCommands.ApplyRemoteCommand("remoteslot", "first " + it.Id.ToString(CultureInfo.InvariantCulture));
|
||||
ImGuiNET.ImGui.Separator();
|
||||
ImGuiNET.ImGui.TextDisabled("Or pick a slot (replaces what's there):");
|
||||
for (int i = 0; i < MiniRemoteSlots; i++)
|
||||
{
|
||||
if (i % MiniRemoteColumns != 0) ImGuiNET.ImGui.SameLine();
|
||||
string label = (i + 1).ToString("00", CultureInfo.InvariantCulture);
|
||||
if (ImGuiNET.ImGui.Button(label, new Vector2(28, 0)))
|
||||
{
|
||||
UI.Data.RynthAiCommands.ApplyRemoteCommand("remoteslot",
|
||||
(i + 1).ToString(CultureInfo.InvariantCulture) + " " + it.Id.ToString(CultureInfo.InvariantCulture));
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
}
|
||||
}
|
||||
ImGuiNET.ImGui.Separator();
|
||||
ImGuiNET.ImGui.TextDisabled("Tip: you can also drag the item onto a slot.");
|
||||
ImGuiNET.ImGui.EndMenu();
|
||||
}
|
||||
|
||||
// ── Split dialog ────────────────────────────────────────────────────
|
||||
|
||||
private void SplitDialog(InventoryView view)
|
||||
|
|
|
|||
129
src/RynthCore.Engine/ImGui/Panels/InventorySelection.cs
Normal file
129
src/RynthCore.Engine/ImGui/Panels/InventorySelection.cs
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/InventorySelection.cs
|
||||
// The Inventory panel's multi-selection: which items are picked for a
|
||||
// Drop / Give / Move of several at once. Windows-style: click picks one,
|
||||
// Ctrl+click adds or removes one, Shift+click picks the run from the last
|
||||
// clicked item (the anchor) in the order the grid shows them, Ctrl+Shift+click
|
||||
// adds that run.
|
||||
//
|
||||
// Ids only (object ids), no engine state, so tools/InventorySelectionTests can
|
||||
// run it. AC's render thread only (the panel's Draw); not thread-safe.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class InventorySelection
|
||||
{
|
||||
private readonly HashSet<uint> _set = new();
|
||||
// Picked order: a batch acts on the items in the order the player picked them.
|
||||
private readonly List<uint> _order = new();
|
||||
|
||||
/// <summary>Where a Shift+click run starts: the last item clicked or Ctrl+clicked (0 = none).</summary>
|
||||
public uint Anchor { get; private set; }
|
||||
|
||||
public int Count => _order.Count;
|
||||
|
||||
/// <summary>The picked ids, in picked order.</summary>
|
||||
public IReadOnlyList<uint> Ids => _order;
|
||||
|
||||
/// <summary>More than one item picked: the zones and the menu act on all of them.</summary>
|
||||
public bool IsMulti => _order.Count > 1;
|
||||
|
||||
public bool Contains(uint id) => _set.Contains(id);
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_set.Clear();
|
||||
_order.Clear();
|
||||
Anchor = 0;
|
||||
}
|
||||
|
||||
/// <summary>A plain click: just <paramref name="id"/>.</summary>
|
||||
public void Single(uint id)
|
||||
{
|
||||
Clear();
|
||||
if (id == 0) return;
|
||||
Add(id);
|
||||
Anchor = id;
|
||||
}
|
||||
|
||||
/// <summary>Ctrl+click: adds <paramref name="id"/>, or removes it if picked. Returns true when it is now picked.</summary>
|
||||
public bool Toggle(uint id)
|
||||
{
|
||||
if (id == 0) return false;
|
||||
Anchor = id;
|
||||
if (_set.Remove(id))
|
||||
{
|
||||
_order.Remove(id);
|
||||
return false;
|
||||
}
|
||||
Add(id);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shift+click: the items from the anchor to <paramref name="id"/>, both included, in the
|
||||
/// order of <paramref name="shown"/>. <paramref name="additive"/> (Ctrl+Shift) keeps what is
|
||||
/// already picked. With no anchor on show (another pack, a new search) it picks just
|
||||
/// <paramref name="id"/>. The anchor stays where it was, so the run can be changed.
|
||||
/// </summary>
|
||||
public void Range<T>(IReadOnlyList<T> shown, Func<T, uint> idOf, uint id, bool additive)
|
||||
{
|
||||
int to = IndexOf(shown, idOf, id);
|
||||
int from = Anchor == 0 ? -1 : IndexOf(shown, idOf, Anchor);
|
||||
if (to < 0 || from < 0)
|
||||
{
|
||||
if (additive) { Add(id); Anchor = id; }
|
||||
else Single(id);
|
||||
return;
|
||||
}
|
||||
uint anchor = Anchor;
|
||||
if (!additive)
|
||||
{
|
||||
_set.Clear();
|
||||
_order.Clear();
|
||||
}
|
||||
int step = to >= from ? 1 : -1;
|
||||
for (int i = from; ; i += step)
|
||||
{
|
||||
Add(idOf(shown[i]));
|
||||
if (i == to) break;
|
||||
}
|
||||
Anchor = anchor;
|
||||
}
|
||||
|
||||
/// <summary>Everything in <paramref name="shown"/> (the grid's current list), in its order.</summary>
|
||||
public void SelectAll<T>(IReadOnlyList<T> shown, Func<T, uint> idOf)
|
||||
{
|
||||
Clear();
|
||||
for (int i = 0; i < shown.Count; i++) Add(idOf(shown[i]));
|
||||
if (_order.Count > 0) Anchor = _order[0];
|
||||
}
|
||||
|
||||
/// <summary>Drops ids that <paramref name="exists"/> no longer finds (given, dropped, merged). True if any went.</summary>
|
||||
public bool Prune(Func<uint, bool> exists)
|
||||
{
|
||||
int before = _order.Count;
|
||||
_order.RemoveAll(id => !exists(id));
|
||||
if (_order.Count == before) return false;
|
||||
_set.Clear();
|
||||
foreach (uint id in _order) _set.Add(id);
|
||||
if (Anchor != 0 && !_set.Contains(Anchor)) Anchor = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Add(uint id)
|
||||
{
|
||||
if (id != 0 && _set.Add(id)) _order.Add(id);
|
||||
}
|
||||
|
||||
private static int IndexOf<T>(IReadOnlyList<T> shown, Func<T, uint> idOf, uint id)
|
||||
{
|
||||
for (int i = 0; i < shown.Count; i++)
|
||||
if (idOf(shown[i]) == id) return i;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
|
@ -54,6 +54,13 @@ internal sealed class ItemsFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.BeginChild("##items_body", new Vector2(w, Math.Max(60, Remaining(origin, size))));
|
||||
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
|
||||
// Above the lists, which can run long: drops entries for items sold, dropped, used up or traded.
|
||||
AddSelected("##clean_missing", PhosphorIcons.Eraser + " Remove Missing", "(weapons and consumables no longer in your inventory)", ItemsCommands.CleanMissing,
|
||||
"Removes listed weapons and consumables that are no longer in your inventory.\n" +
|
||||
"An entry whose item is gone but with an unlisted item of the same name in your pack\n" +
|
||||
"(a new stack of kits, a replacement weapon) is pointed at that item instead.\n" +
|
||||
"Does nothing while your inventory is still loading. Also: /ra items clean.");
|
||||
|
||||
// Weapons
|
||||
Section("Weapons", bw);
|
||||
if (_data.Weapons.Count == 0) Empty("No weapons configured", bw);
|
||||
|
|
@ -242,11 +249,12 @@ internal sealed class ItemsFace : IImGuiPanel
|
|||
return result;
|
||||
}
|
||||
|
||||
private static void AddSelected(string id, string label, string hint, Action onClick)
|
||||
private static void AddSelected(string id, string label, string hint, Action onClick, string? tooltip = null)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 4);
|
||||
float bw = ButtonWidth(label) + 4;
|
||||
if (Button(id, label, p, new Vector2(bw, 24), Teal, BtnFill)) onClick();
|
||||
if (tooltip != null) ImGuiNET.ImGui.SetItemTooltip(tooltip);
|
||||
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9);
|
||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(f9, f9.FontSize, new Vector2(p.X + bw + 8, p.Y + (24 - f9.FontSize) * 0.5f), Mute, hint);
|
||||
NextLine(new Vector2(p.X - 4, p.Y - 4), 32);
|
||||
|
|
|
|||
|
|
@ -1,14 +1,28 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/MiniRemoteFace.cs
|
||||
// The Mini Remote: a small grid of slots the player fills with items; a click
|
||||
// uses that item. Engine only, ImGui only. (An idea from Silentkelpie's rynth
|
||||
// PR #1, done as an engine face.)
|
||||
// The Mini Remote: one window for the quick-use item slots, whoever draws them.
|
||||
//
|
||||
// With RynthAi loaded it hosts RynthAi's Mini Remote (session rates, target,
|
||||
// summon, item slots, toggles, bank, rebuff, Translate, Guardian and its
|
||||
// Options menu, plus on ILT worlds the tabs Character, Quests, Pets, Banking,
|
||||
// Gear and Games that were the ILT Hub), drawn by the plugin through
|
||||
// RynthPluginRenderEmbed ("miniremote-window"). The window fits itself to what
|
||||
// the plugin asks for whenever that changes (another tab, a section shown or
|
||||
// hidden, bigger or smaller boxes);
|
||||
// a resize by hand holds until then. While this window shows it, RynthAi keeps
|
||||
// its own floating copy hidden, so there is one Mini Remote, not two.
|
||||
//
|
||||
// Without RynthAi (not loaded, too old for the surface, not logged in yet,
|
||||
// popped out with a RynthAi older than 0.5.38, which can't draw in a pop-out's
|
||||
// context, or its embed failed) it is the engine's own grid (an idea from Silentkelpie's
|
||||
// rynth PR #1, done as an engine face):
|
||||
// slots the item's icon and carried count; an empty slot shows +
|
||||
// click uses the slot's item (the same object if still carried, else a
|
||||
// stack with its name); on an empty slot, puts the selected
|
||||
// inventory item there
|
||||
// right Set to the selected item, Clear, More / Fewer slots
|
||||
// right Set to the selected item, Clear, More / Fewer slots,
|
||||
// Bigger / Smaller boxes
|
||||
// ctrl+wheel over the slots: bigger / smaller boxes
|
||||
// drop drag an item from the game's inventory (or the Inventory panel)
|
||||
// onto a slot to put it there (UiDropTargets, one target a slot)
|
||||
// status the use waiting for the server, or how the last one ended
|
||||
|
|
@ -16,7 +30,8 @@
|
|||
// A click never calls AC from the render thread: it posts an InventoryModel
|
||||
// Use request, which AC's main thread sends at its next tick behind the
|
||||
// client's own item gate (one item action at a time; a click while one waits
|
||||
// is refused, not queued). Slots are saved per character (ItemHudStore).
|
||||
// is refused, not queued). Slots and box size are saved per character
|
||||
// (ItemHudStore).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
|
@ -24,6 +39,7 @@ using System.Globalization;
|
|||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using RynthCore.Engine.UI.ScriptWindows;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
|
@ -42,7 +58,12 @@ internal sealed class MiniRemoteFace : IImGuiPanel
|
|||
ItemHudStore.EnsureLoadQueued();
|
||||
}
|
||||
|
||||
private const float Slot = 36f, Gap = 4f, IconSize = 32f, StatusH = 18f;
|
||||
/// <summary>The RynthAi surface for this window (NUL-terminated for the export).</summary>
|
||||
private static ReadOnlySpan<byte> Surface => "miniremote-window\0"u8;
|
||||
|
||||
private const float Gap = 4f, StatusH = 18f;
|
||||
/// <summary>Pixels a Ctrl+wheel notch or a Bigger / Smaller menu click changes the box edge by.</summary>
|
||||
private const int SlotSizeStep = 4;
|
||||
private const string MenuId = "##miniremote_menu";
|
||||
private static readonly string[] DropKeys = BuildDropKeys();
|
||||
|
||||
|
|
@ -66,34 +87,144 @@ internal sealed class MiniRemoteFace : IImGuiPanel
|
|||
private uint[] _slotItem = Array.Empty<uint>();
|
||||
private string[] _slotCount = Array.Empty<string>();
|
||||
|
||||
// RynthAi hosting: it drew last frame; its export failed this session; the size it last asked for.
|
||||
private bool _hosted;
|
||||
private bool _embedOff;
|
||||
private Vector2 _lastWant;
|
||||
// The engine grid: the box size it last fitted the window to (0 = fit on the next frame).
|
||||
private int _fittedSlotSize;
|
||||
// The window size last requested (logical units), so the same request isn't repeated.
|
||||
private Vector2 _requested;
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
ItemHudStore.EnsureLoadQueued();
|
||||
InventoryModel.Subscribe();
|
||||
_lastWant = Vector2.Zero;
|
||||
_fittedSlotSize = 0;
|
||||
_requested = Vector2.Zero;
|
||||
}
|
||||
|
||||
public void OnHidden()
|
||||
{
|
||||
InventoryModel.Unsubscribe();
|
||||
_menuSlot = -1;
|
||||
_hosted = false;
|
||||
}
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
if (DrawRynthAi(w, origin, size))
|
||||
{
|
||||
End(origin, size);
|
||||
return;
|
||||
}
|
||||
|
||||
InventoryView view = InventoryModel.Current;
|
||||
HudItem[] items = _items.Get(view);
|
||||
ItemHudCharacter data = ItemHudStore.Current;
|
||||
bool ready = ItemHudStore.Loaded && ItemHudStore.HasCharacter && view.PlayerId != 0;
|
||||
Resolve(data, items);
|
||||
|
||||
float gridH = Math.Max(Slot, Remaining(origin, size) - StatusH - GripOverlap());
|
||||
float haveH = Remaining(origin, size);
|
||||
float gridH = Math.Max(data.SlotSize, haveH - StatusH - GripOverlap());
|
||||
DrawGrid(data, items, w, gridH, ready);
|
||||
DrawStatus(ready);
|
||||
FitGrid(data, w, haveH);
|
||||
End(origin, size);
|
||||
DrawMenu(data, items);
|
||||
}
|
||||
|
||||
// ── RynthAi's Mini Remote ───────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Lets RynthAi draw its Mini Remote here. True when it did (or is mid-layout after
|
||||
/// drawing last frame); false means the engine grid draws instead. The plugin draws
|
||||
/// nothing when it declines, and the auto-height child it would have filled stays
|
||||
/// empty, so the grid can take the space the same frame.
|
||||
/// </summary>
|
||||
private bool DrawRynthAi(float w, Vector2 origin, Vector2 size)
|
||||
{
|
||||
if (_embedOff) return false;
|
||||
float haveH = Remaining(origin, size);
|
||||
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
|
||||
bool open = ImGuiNET.ImGui.BeginChild("##mr_rynthai", new Vector2(w, 0), ImGuiChildFlags.AutoResizeY,
|
||||
ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoScrollbar);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
int result = PluginManager.EmbedNotReady;
|
||||
Vector2 want = Vector2.Zero;
|
||||
try
|
||||
{
|
||||
if (open)
|
||||
{
|
||||
// The plugin's widgets use the default UI font, as in its floating Mini Remote.
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
try { result = PluginManager.RenderEmbed("RynthAi", Surface, new Vector2(w, Math.Max(1f, haveH)), out want); }
|
||||
finally { ImGuiNET.ImGui.PopFont(); }
|
||||
}
|
||||
}
|
||||
finally { ImGuiNET.ImGui.EndChild(); }
|
||||
|
||||
if (result == PluginManager.EmbedFailed) _embedOff = true;
|
||||
// A clipped child (open == false) draws nothing; keep the last frame's answer so the
|
||||
// window doesn't flick to the engine grid for that frame.
|
||||
_hosted = open ? result == PluginManager.EmbedDrawn : _hosted && !_embedOff;
|
||||
if (!_hosted) { _lastWant = Vector2.Zero; return false; }
|
||||
|
||||
if (result == PluginManager.EmbedDrawn && want.X > 0 && want.Y > 0
|
||||
&& Vector2.DistanceSquared(want, _lastWant) > 1f)
|
||||
{
|
||||
_lastWant = want;
|
||||
// + the grip's reach, so the plugin's last row isn't under the resize grip.
|
||||
FitWindow(new Vector2(want.X, want.Y + GripOverlap()), w, haveH);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Window fit ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Sizes the window so the body area (<paramref name="haveW"/> × <paramref name="haveH"/>
|
||||
/// now) becomes <paramref name="wantPx"/>; never taller than the screen. Docked only:
|
||||
/// popped out the OS window keeps its size, as other faces do (RynthNavArrowFace).
|
||||
/// </summary>
|
||||
private void FitWindow(Vector2 wantPx, float haveW, float haveH)
|
||||
{
|
||||
if (ImGuiPopOuts.InPopOutFrame) return;
|
||||
float place = ImGuiPanelHost.PlacementScale();
|
||||
float extraW = ImGuiNET.ImGui.GetWindowWidth() - haveW; // anything around the body
|
||||
float extraH = ImGuiNET.ImGui.GetWindowHeight() - haveH;
|
||||
var want = new Vector2(MathF.Ceiling((wantPx.X + extraW) / place), MathF.Ceiling((wantPx.Y + extraH) / place));
|
||||
float screenH = ImGuiNET.ImGui.GetIO().DisplaySize.Y / place;
|
||||
if (screenH > 1) want.Y = MathF.Min(want.Y, screenH - 8);
|
||||
if (Vector2.DistanceSquared(want, _requested) < 1f) return;
|
||||
_requested = want;
|
||||
ImGuiPanelHost.RequestSize(Title, want);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The engine grid: after the box size changes (and on the first frame shown), fits the
|
||||
/// window to the slots at the same number of columns, plus the status line.
|
||||
/// </summary>
|
||||
private void FitGrid(ItemHudCharacter data, float w, float haveH)
|
||||
{
|
||||
if (_fittedSlotSize == data.SlotSize || !ItemHudStore.Loaded) return;
|
||||
bool first = _fittedSlotSize == 0;
|
||||
int oldSlot = first ? data.SlotSize : _fittedSlotSize;
|
||||
_fittedSlotSize = data.SlotSize;
|
||||
// First show: keep the window the player left (only a box-size change refits it).
|
||||
if (first) return;
|
||||
int cols = Math.Max(1, (int)((w + Gap) / (oldSlot + Gap)));
|
||||
int rows = (data.Slots.Length + cols - 1) / cols;
|
||||
float slot = data.SlotSize;
|
||||
var body = new Vector2(cols * (slot + Gap) - Gap, rows * (slot + Gap) - Gap + StatusH + GripOverlap());
|
||||
FitWindow(body, w, haveH);
|
||||
}
|
||||
|
||||
// ── Engine grid ─────────────────────────────────────────────────────
|
||||
|
||||
private void Resolve(ItemHudCharacter data, HudItem[] items)
|
||||
{
|
||||
if (ReferenceEquals(data, _resolvedFor) && _resolvedItemsVersion == _items.Version) return;
|
||||
|
|
@ -112,20 +243,20 @@ internal sealed class MiniRemoteFace : IImGuiPanel
|
|||
}
|
||||
}
|
||||
|
||||
// ── Grid ────────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawGrid(ItemHudCharacter data, HudItem[] items, float w, float h, bool ready)
|
||||
{
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
int cols = Math.Max(1, (int)((w + Gap) / (Slot + Gap)));
|
||||
float slot = data.SlotSize;
|
||||
float iconSize = slot - 4f;
|
||||
int cols = Math.Max(1, (int)((w + Gap) / (slot + Gap)));
|
||||
bool dragging = ready && UiDropTargets.AnyDragInProgress;
|
||||
int clicked = -1;
|
||||
|
||||
for (int i = 0; i < data.Slots.Length; i++)
|
||||
{
|
||||
var p = new Vector2(start.X + (i % cols) * (Slot + Gap), start.Y + (i / cols) * (Slot + Gap));
|
||||
var max = p + new Vector2(Slot, Slot);
|
||||
var p = new Vector2(start.X + (i % cols) * (slot + Gap), start.Y + (i / cols) * (slot + Gap));
|
||||
var max = p + new Vector2(slot, slot);
|
||||
RemoteSlot? s = data.Slots[i];
|
||||
|
||||
// One drop target a slot, so the item lands where it was let go.
|
||||
|
|
@ -135,7 +266,7 @@ internal sealed class MiniRemoteFace : IImGuiPanel
|
|||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##slot", new Vector2(Slot, Slot))) clicked = i;
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##slot", new Vector2(slot, slot))) clicked = i;
|
||||
bool hot = ImGuiNET.ImGui.IsItemHovered();
|
||||
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _menuSlot = i; _openMenu = true; }
|
||||
ImGuiNET.ImGui.PopID();
|
||||
|
|
@ -145,20 +276,20 @@ internal sealed class MiniRemoteFace : IImGuiPanel
|
|||
dl.AddRect(p, max, dropHot || dragging ? Teal : BtnBord, 3);
|
||||
|
||||
uint id = s != null && i < _slotItem.Length ? _slotItem[i] : 0;
|
||||
Vector2 ip = p + new Vector2((Slot - IconSize) * 0.5f, (Slot - IconSize) * 0.5f);
|
||||
Vector2 ip = p + new Vector2((slot - iconSize) * 0.5f, (slot - iconSize) * 0.5f);
|
||||
if (s == null)
|
||||
{
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.Plus, p, new Vector2(Slot, Slot), Faded(Mute));
|
||||
if (hot) ImGuiNET.ImGui.SetItemTooltip("Empty slot: click to put the selected inventory item here, or drag an item onto it.");
|
||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui14), PhosphorIcons.Plus, p, new Vector2(slot, slot), Faded(Mute));
|
||||
if (hot) ImGuiNET.ImGui.SetItemTooltip("Empty slot: click to put the selected inventory item here, or drag an item onto it.\nCtrl+wheel: bigger / smaller boxes.");
|
||||
continue;
|
||||
}
|
||||
if (id != 0 && ScriptIcons.TryGet(ScriptIconKind.Object, id, out IntPtr tex))
|
||||
dl.AddImage(tex, ip, ip + new Vector2(IconSize, IconSize));
|
||||
dl.AddImage(tex, ip, ip + new Vector2(iconSize, iconSize));
|
||||
else
|
||||
{
|
||||
string initial = s.Name.Length > 0 ? s.Name[..1].ToUpperInvariant() : "?";
|
||||
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(initial);
|
||||
dl.AddText(p + (new Vector2(Slot, Slot) - ts) * 0.5f, Faded(Text), initial);
|
||||
dl.AddText(p + (new Vector2(slot, slot) - ts) * 0.5f, Faded(Text), initial);
|
||||
}
|
||||
string count = _slotCount[i];
|
||||
if (count.Length > 0)
|
||||
|
|
@ -174,13 +305,30 @@ internal sealed class MiniRemoteFace : IImGuiPanel
|
|||
: $"{s.Name} ({count switch { "" => "1", _ => count }} carried)\nClick to use. Right-click for options.");
|
||||
}
|
||||
int rows = (data.Slots.Length + cols - 1) / cols;
|
||||
float shownH = Math.Min(h, rows * (slot + Gap));
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(start);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(w, Math.Min(h, rows * (Slot + Gap))));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(w, shownH));
|
||||
|
||||
// Ctrl+wheel over the slots: bigger / smaller boxes (saved per character).
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
if (ready && io.KeyCtrl && io.MouseWheel != 0
|
||||
&& ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows)
|
||||
&& ImGuiNET.ImGui.IsMouseHoveringRect(start, start + new Vector2(w, shownH)))
|
||||
ResizeSlots(io.MouseWheel > 0 ? SlotSizeStep : -SlotSizeStep);
|
||||
|
||||
if (clicked >= 0 && ready) Click(data, items, clicked);
|
||||
else if (clicked >= 0) ShowMessage(ItemHudStore.Loaded ? "Waiting for your character..." : "Loading...", Amber);
|
||||
}
|
||||
|
||||
/// <summary>Grows (+) or shrinks (-) the boxes by <paramref name="delta"/> pixels, within the saved range.</summary>
|
||||
private void ResizeSlots(int delta)
|
||||
{
|
||||
if (!ItemHudStore.Update(d => d.WithSlotSize(d.SlotSize + delta), out string why))
|
||||
ShowMessage(why, Amber);
|
||||
else
|
||||
ShowMessage($"Box size {ItemHudStore.Current.SlotSize} px.", Mute);
|
||||
}
|
||||
|
||||
private void Click(ItemHudCharacter data, HudItem[] items, int i)
|
||||
{
|
||||
RemoteSlot? s = data.Slots[i];
|
||||
|
|
@ -228,7 +376,7 @@ internal sealed class MiniRemoteFace : IImGuiPanel
|
|||
else if (pending != null) { text = pending.WaitingForGame ? "Waiting for the game: " + pending.Label : pending.Label + "..."; color = Teal; }
|
||||
else if (last != null && nowTicks - last.AtTicks < System.Diagnostics.Stopwatch.Frequency * 4) { text = last.Text; color = last.Ok ? Green : Amber; }
|
||||
else if (!ready) { text = ItemHudStore.Loaded ? "Waiting for your character..." : "Loading..."; color = Mute; }
|
||||
else { text = "Click: use. Right-click: options."; color = Faded(Mute); }
|
||||
else { text = "Click: use. Right-click: options. Ctrl+wheel: box size."; color = Faded(Mute); }
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float w = ImGuiNET.ImGui.GetContentRegionAvail().X - BodyGripRoom();
|
||||
|
|
@ -273,6 +421,14 @@ internal sealed class MiniRemoteFace : IImGuiPanel
|
|||
ItemHudStore.Update(d => d.WithSlotCount(d.Slots.Length + 4), out _);
|
||||
if (ImGuiNET.ImGui.MenuItem("Fewer slots (drops the last 4)", "", false, n > ItemHudCharacter.MinSlots))
|
||||
ItemHudStore.Update(d => d.WithSlotCount(d.Slots.Length - 4), out _);
|
||||
ImGuiNET.ImGui.Separator();
|
||||
int px = data.SlotSize;
|
||||
if (ImGuiNET.ImGui.MenuItem($"Bigger boxes ({px} px now)", "Ctrl+wheel up", false, px < ItemHudCharacter.MaxSlotSize))
|
||||
ResizeSlots(SlotSizeStep);
|
||||
if (ImGuiNET.ImGui.MenuItem("Smaller boxes", "Ctrl+wheel down", false, px > ItemHudCharacter.MinSlotSize))
|
||||
ResizeSlots(-SlotSizeStep);
|
||||
if (ImGuiNET.ImGui.MenuItem("Default box size", "", false, px != ItemHudCharacter.DefaultSlotSize))
|
||||
ResizeSlots(ItemHudCharacter.DefaultSlotSize - px);
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,21 +1,28 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/NavFace.cs
|
||||
// ImGui face of the Nav panel (UI/Panels/NavPanel.cs): active nav + status,
|
||||
// Start/Stop, route type and insert mode, Add Waypoint / Portal (not yet) /
|
||||
// Recall / Clear / Save / Dungeon Patrol, a chat waypoint, Save As, the nav
|
||||
// file picker, the nav point reach (RynthAi's FollowNavMin, the same row as
|
||||
// Settings > Navigation), and the waypoint list (click selects the insert
|
||||
// point, X deletes, => marks the active one).
|
||||
// Start/Stop, route type and insert mode, the Breadcrumbs and Route overlay
|
||||
// toggles, Add Waypoint / Portal (selected object) /
|
||||
// Recall / Clear / Save / Dungeon Patrol, the route editor (move / duplicate /
|
||||
// delete / set active / move here on the selection; nearest, reverse, snap to
|
||||
// path, point at selection, pause, simplify; recording and trail -> route),
|
||||
// a chat waypoint, Save As, the nav file picker, the nav point reach
|
||||
// (RynthAi's FollowNavMin, the same row as Settings > Navigation), and the
|
||||
// waypoint list (click selects, Ctrl/Shift-click multi-selects, double-click
|
||||
// sets active, right-click edits, X or Delete deletes, => marks the active one).
|
||||
//
|
||||
// Data: UiSources.Nav (hub) and NavCommands. Button actions change a private
|
||||
// copy at once; the plugin applies commands immediately, so the next
|
||||
// snapshot (requested right after) replaces the copy. The reach row reads
|
||||
// UiSources.Settings and saves through SettingsCommands, like the Settings face.
|
||||
// snapshot (requested right after) replaces the copy. Edits send indices into
|
||||
// the route this face shows, so the selection is remapped locally as the copy
|
||||
// changes. The reach row reads UiSources.Settings and saves through
|
||||
// SettingsCommands, like the Settings face.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
|
@ -28,7 +35,7 @@ internal sealed class NavFace : IImGuiPanel
|
|||
public const string Title = "Nav";
|
||||
|
||||
public static void Register() => ImGuiPanelHost.Register(Title,
|
||||
new PanelSpec(new Vector2(400, 560), new Vector2(360, 380), EdgeToEdge: true),
|
||||
new PanelSpec(new Vector2(400, 680), new Vector2(360, 440), EdgeToEdge: true),
|
||||
() => new NavFace());
|
||||
|
||||
private static readonly string[] Actions =
|
||||
|
|
@ -38,12 +45,30 @@ internal sealed class NavFace : IImGuiPanel
|
|||
};
|
||||
private const string StartNav = PhosphorIcons.Play + " Start Navigation", StopNav = PhosphorIcons.Stop + " Stop Navigation";
|
||||
private const string AddChat = PhosphorIcons.Plus + " Add Chat", SaveAs = PhosphorIcons.FloppyDisk + " Save As";
|
||||
private static readonly bool[] ActionsEnabled = { true, false, true, true, true, true };
|
||||
|
||||
// Route editor rows. Edit acts on the selected waypoints; Tools on the route.
|
||||
private static readonly string[] EditActions =
|
||||
{
|
||||
PhosphorIcons.ArrowUp + " Up", PhosphorIcons.ArrowDown + " Down", PhosphorIcons.Copy + " Duplicate",
|
||||
PhosphorIcons.Trash + " Delete", PhosphorIcons.Target + " Set Active", PhosphorIcons.Crosshair + " Move Here",
|
||||
};
|
||||
private static readonly string[] ToolActions =
|
||||
{
|
||||
PhosphorIcons.NavigationArrow + " Nearest", PhosphorIcons.ArrowsClockwise + " Reverse", PhosphorIcons.Path + " Snap to Path",
|
||||
PhosphorIcons.MapPin + " Point at Selected", PhosphorIcons.Hourglass + " Add Pause", PhosphorIcons.Scissors + " Simplify",
|
||||
};
|
||||
private static readonly string[] RowMenu =
|
||||
{ "Set Active", "Move Here", "Move Up", "Move Down", "Duplicate", "Delete" };
|
||||
private const string FromTrail = PhosphorIcons.Footprints + " Route from Trail...";
|
||||
private readonly bool[] _editEnabled = new bool[6];
|
||||
|
||||
private NavPayload _data = new();
|
||||
private long _seenVersion = -1;
|
||||
private readonly List<string> _pointText = new();
|
||||
private int _selected = -1, _addMode;
|
||||
// _selected is the focus row (insert point, chat editing); _multi is every selected row,
|
||||
// always containing _selected when it is set. _anchor starts Shift-click ranges.
|
||||
private int _selected = -1, _anchor = -1, _addMode;
|
||||
private readonly HashSet<int> _multi = new();
|
||||
private bool _typing;
|
||||
private string _routeLabel = "Route: Once", _insertLabel = "Insert: End", _activeLabel = "Active Nav: None (Unsaved)";
|
||||
private string _fileLabel = "Select nav file...";
|
||||
|
|
@ -130,13 +155,32 @@ internal sealed class NavFace : IImGuiPanel
|
|||
});
|
||||
NextLine(p, 26);
|
||||
|
||||
// Breadcrumbs | Route overlay (RynthAi's NavOverlaySettings; saved per character)
|
||||
p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (OverlayToggle("##crumbs", "Breadcrumbs", _data.TrackBreadcrumbs, p, half,
|
||||
"Record the trail you walk and draw it on the ground (/ra navtrail on|off).\nTurning it off hides the trail; /ra navtrail clear wipes it."))
|
||||
{
|
||||
bool on = !_data.TrackBreadcrumbs;
|
||||
NavCommands.Send(new NavCmd { Cmd = "setBreadcrumbs", On = on });
|
||||
_data.TrackBreadcrumbs = on;
|
||||
}
|
||||
if (OverlayToggle("##routeovl", "Route overlay", _data.ShowRouteOverlay, new Vector2(p.X + half + 4, p.Y), half,
|
||||
"Draw the route in the world: waypoint rings and lines, waypoint labels and the guide line\nto the active waypoint (/ra navoverlay on|off). The waypoint HUD window is separate."))
|
||||
{
|
||||
bool on = !_data.ShowRouteOverlay;
|
||||
NavCommands.Send(new NavCmd { Cmd = "setRouteOverlay", On = on });
|
||||
_data.ShowRouteOverlay = on;
|
||||
}
|
||||
NextLine(p, 26);
|
||||
|
||||
typing |= ReachRow(w);
|
||||
|
||||
// Actions
|
||||
int action = WrapButtons("nav_act", Actions, w, 24, ActionsEnabled);
|
||||
int action = WrapButtons("nav_act", Actions, w, 24);
|
||||
switch (action)
|
||||
{
|
||||
case 0: NavCommands.Send(new NavCmd { Cmd = "addWaypoint", AddMode = _addMode, InsertAt = _selected }); break;
|
||||
case 1: NavCommands.Send(new NavCmd { Cmd = "addPortal", AddMode = _addMode, InsertAt = _selected }); break;
|
||||
case 2:
|
||||
_picker.Open(ImGuiNET.ImGui.GetIO().MousePos, NavCommands.RecallLabels, -1, i =>
|
||||
NavCommands.Send(new NavCmd { Cmd = "addRecall", SpellId = NavCommands.RecallIds[i], AddMode = _addMode, InsertAt = _selected }));
|
||||
|
|
@ -144,13 +188,15 @@ internal sealed class NavFace : IImGuiPanel
|
|||
case 3:
|
||||
NavCommands.Send(new NavCmd { Cmd = "clearRoute" });
|
||||
_data.Points.Clear();
|
||||
_selected = -1;
|
||||
ClearSelection();
|
||||
RebuildPointText();
|
||||
break;
|
||||
case 4: NavCommands.Send(new NavCmd { Cmd = "saveRoute" }); break;
|
||||
case 5: NavCommands.Send(new NavCmd { Cmd = "dunPatrol" }); break;
|
||||
}
|
||||
|
||||
RouteEditor(w);
|
||||
|
||||
// Chat waypoint: sent as if typed when the route reaches it. Selecting an
|
||||
// existing chat waypoint loads its command here; Update saves the edit.
|
||||
bool chatSelected = _selected >= 0 && _selected < _data.Points.Count
|
||||
|
|
@ -230,6 +276,9 @@ internal sealed class NavFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1));
|
||||
ImGuiNET.ImGui.BeginChild("##nav_points", new Vector2(w, listH));
|
||||
Waypoints(ImGuiNET.ImGui.GetContentRegionAvail().X);
|
||||
if (!typing && _multi.Count > 0 && ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Delete, false)
|
||||
&& (ImGuiNET.ImGui.IsWindowHovered() || ImGuiNET.ImGui.IsWindowFocused()))
|
||||
DeleteSelected();
|
||||
ImGuiNET.ImGui.EndChild();
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
|
|
@ -239,6 +288,18 @@ internal sealed class NavFace : IImGuiPanel
|
|||
_picker.Draw();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A checkbox-style toggle button: ticked box and teal text when on, empty box and muted
|
||||
/// text when off. Returns true when clicked (the caller flips the value).
|
||||
/// </summary>
|
||||
private static bool OverlayToggle(string id, string label, bool on, Vector2 pos, float width, string tooltip)
|
||||
{
|
||||
string text = (on ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " " + label;
|
||||
bool clicked = Button(id, text, pos, new Vector2(width, 22), on ? Teal : Mute, BtnFill, leftAlign: true);
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tooltip);
|
||||
return clicked;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Nav point reach (yd): how close nav gets to each nav point before moving on. Label,
|
||||
/// [-] value [+]; the typed value commits on Enter or when the box loses focus. Saves the
|
||||
|
|
@ -303,20 +364,24 @@ internal sealed class NavFace : IImGuiPanel
|
|||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
const float h = 22;
|
||||
if (p.Y + h < clipMin.Y || p.Y > clipMax.Y) { ImGuiNET.ImGui.Dummy(new Vector2(w, h)); continue; }
|
||||
bool active = i == _data.ActiveNavIndex, selected = i == _selected;
|
||||
bool active = i == _data.ActiveNavIndex, selected = _multi.Contains(i);
|
||||
ImGuiNET.ImGui.PushID(i);
|
||||
// Row click selects (drawn first so the X button on top wins).
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
ImGuiNET.ImGui.SetNextItemAllowOverlap(); // the X button on top gets its clicks
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) _selected = i;
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) ClickRow(i);
|
||||
if (ImGuiNET.ImGui.IsItemHovered() && ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left))
|
||||
SetActive(i);
|
||||
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
|
||||
{
|
||||
if (!selected) SelectOnly(i);
|
||||
_picker.Open(ImGuiNET.ImGui.GetIO().MousePos, RowMenu, -1, RowMenuPick, width: 140);
|
||||
}
|
||||
dl.AddRectFilled(p, p + new Vector2(w, h), selected ? Selected : i % 2 == 0 ? PanelBg : RowAlt);
|
||||
if (IconButton("##del", PhosphorIcons.X, new Vector2(p.X + 2, p.Y + 2), new Vector2(18, 18), Text, DeleteBg, font: UiFont.Ui11))
|
||||
{
|
||||
NavCommands.Send(new NavCmd { Cmd = "deletePoint", Index = i });
|
||||
if (_selected == i) _selected = -1;
|
||||
else if (_selected > i) _selected--;
|
||||
_data.Points.RemoveAt(i);
|
||||
RebuildPointText();
|
||||
RemoveLocal(new HashSet<int> { i });
|
||||
ImGuiNET.ImGui.PopID();
|
||||
return;
|
||||
}
|
||||
|
|
@ -331,6 +396,216 @@ internal sealed class NavFace : IImGuiPanel
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Route editor: Edit row (on the selection), Tools row (on the route), the Record toggle
|
||||
/// with "Route from Trail...", and the last edit's result. Picker-backed buttons (pause,
|
||||
/// simplify, trail) double as the confirmation for edits that can't be undone.
|
||||
/// </summary>
|
||||
private void RouteEditor(float w)
|
||||
{
|
||||
int n = _multi.Count, count = _data.Points.Count;
|
||||
bool one = n == 1 && _selected >= 0;
|
||||
_editEnabled[0] = n > 0 && _multi.Min() > 0;
|
||||
_editEnabled[1] = n > 0 && _multi.Max() < count - 1;
|
||||
_editEnabled[2] = _editEnabled[3] = n > 0;
|
||||
_editEnabled[4] = _editEnabled[5] = one;
|
||||
Label(n > 1 ? $"Edit ({n} selected)" : "Edit", Mute);
|
||||
switch (WrapButtons("nav_edit", EditActions, w, 22, _editEnabled))
|
||||
{
|
||||
case 0: MoveSelected(-1); break;
|
||||
case 1: MoveSelected(+1); break;
|
||||
case 2: DuplicateSelected(); break;
|
||||
case 3: DeleteSelected(); break;
|
||||
case 4: SetActive(_selected); break;
|
||||
case 5: NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break;
|
||||
}
|
||||
|
||||
Vector2 at = ImGuiNET.ImGui.GetIO().MousePos;
|
||||
switch (WrapButtons("nav_tools", ToolActions, w, 22))
|
||||
{
|
||||
case 0: NavCommands.Send(new NavCmd { Cmd = "nearestActive" }); break;
|
||||
case 1:
|
||||
if (count < 2) break;
|
||||
NavCommands.Send(new NavCmd { Cmd = "reverseRoute" });
|
||||
ReverseLocal();
|
||||
break;
|
||||
case 2: NavCommands.Send(new NavCmd { Cmd = "snapToPath" }); break;
|
||||
case 3: NavCommands.Send(new NavCmd { Cmd = "addPointAtSelected", AddMode = _addMode, InsertAt = _selected }); break;
|
||||
case 4:
|
||||
_picker.Open(at, NavCommands.PauseLabels, -1, i => NavCommands.Send(new NavCmd
|
||||
{ Cmd = "addPause", Seconds = NavCommands.PauseSeconds[i], AddMode = _addMode, InsertAt = _selected }), width: 140);
|
||||
break;
|
||||
case 5:
|
||||
_picker.Open(at, NavCommands.SimplifyLabels, -1, i =>
|
||||
NavCommands.Send(new NavCmd { Cmd = "simplifyRoute", Yards = NavCommands.SimplifyYards[i] }), width: 300);
|
||||
break;
|
||||
}
|
||||
|
||||
// Record | Route from Trail...
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float half = (w - 4) / 2;
|
||||
if (OverlayToggle("##record", "Record route", _data.IsRecording, p, half,
|
||||
"Add a point every few yards as you walk, and portal steps as you use portals\n(/ra navrec on|off). Points go into the current route."))
|
||||
{
|
||||
bool on = !_data.IsRecording;
|
||||
NavCommands.Send(new NavCmd { Cmd = "setRecording", On = on });
|
||||
_data.IsRecording = on;
|
||||
}
|
||||
Vector2 tp = new(p.X + half + 4, p.Y);
|
||||
if (Button("##fromtrail", FromTrail, tp, new Vector2(half, 22), Text, BtnFill, enabled: _data.TrailPoints >= 2))
|
||||
_picker.Open(new Vector2(tp.X, tp.Y + 22), NavCommands.TrailChoices, -1, i =>
|
||||
NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }), width: 300);
|
||||
if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
|
||||
ImGuiNET.ImGui.SetTooltip(_data.TrailPoints >= 2
|
||||
? $"Breadcrumb trail: {_data.TrailPoints} crumbs, {_data.TrailYards:0} yd.\nThe new route is unsaved; the loaded nav file is not changed."
|
||||
: "Turn on Breadcrumbs and walk a while to build a trail.");
|
||||
NextLine(p, 26);
|
||||
|
||||
if (_data.EditStatus.Length > 0) Label(_data.EditStatus, Amber);
|
||||
}
|
||||
|
||||
/// <summary>Plain click selects one row, Ctrl toggles a row, Shift selects from the anchor.</summary>
|
||||
private void ClickRow(int i)
|
||||
{
|
||||
var io = ImGuiNET.ImGui.GetIO();
|
||||
if (io.KeyShift && _anchor >= 0)
|
||||
{
|
||||
if (!io.KeyCtrl) _multi.Clear();
|
||||
for (int k = Math.Min(_anchor, i); k <= Math.Max(_anchor, i); k++) _multi.Add(k);
|
||||
_selected = i;
|
||||
}
|
||||
else if (io.KeyCtrl)
|
||||
{
|
||||
if (!_multi.Remove(i)) { _multi.Add(i); _selected = i; }
|
||||
else if (_selected == i) _selected = _multi.Count > 0 ? _multi.Min() : -1;
|
||||
_anchor = i;
|
||||
}
|
||||
else SelectOnly(i);
|
||||
}
|
||||
|
||||
private void SelectOnly(int i)
|
||||
{
|
||||
_multi.Clear();
|
||||
_multi.Add(i);
|
||||
_selected = _anchor = i;
|
||||
}
|
||||
|
||||
private void ClearSelection()
|
||||
{
|
||||
_multi.Clear();
|
||||
_selected = _anchor = -1;
|
||||
}
|
||||
|
||||
private List<int> SelectedIndices()
|
||||
{
|
||||
var list = new List<int>(_multi);
|
||||
list.Sort();
|
||||
return list;
|
||||
}
|
||||
|
||||
private void RowMenuPick(int item)
|
||||
{
|
||||
switch (item)
|
||||
{
|
||||
case 0: if (_selected >= 0) SetActive(_selected); break;
|
||||
case 1: if (_selected >= 0) NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break;
|
||||
case 2: MoveSelected(-1); break;
|
||||
case 3: MoveSelected(+1); break;
|
||||
case 4: DuplicateSelected(); break;
|
||||
case 5: DeleteSelected(); break;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetActive(int i)
|
||||
{
|
||||
if (i < 0 || i >= _data.Points.Count) return;
|
||||
NavCommands.Send(new NavCmd { Cmd = "setActive", Index = i });
|
||||
_data.ActiveNavIndex = i;
|
||||
}
|
||||
|
||||
/// <summary>Moves the selected rows one slot, the way the plugin does (NavRouteEditing.Move).</summary>
|
||||
private void MoveSelected(int delta)
|
||||
{
|
||||
if (_multi.Count == 0) return;
|
||||
NavCommands.Send(new NavCmd { Cmd = "movePoints", Indices = SelectedIndices(), Delta = delta });
|
||||
var pts = _data.Points;
|
||||
var sel = new HashSet<NavPoint>();
|
||||
foreach (int i in _multi) sel.Add(pts[i]);
|
||||
NavPoint? focus = _selected >= 0 ? pts[_selected] : null, anchor = _anchor >= 0 && _anchor < pts.Count ? pts[_anchor] : null;
|
||||
if (delta < 0)
|
||||
{
|
||||
for (int i = 1; i < pts.Count; i++)
|
||||
if (sel.Contains(pts[i]) && !sel.Contains(pts[i - 1])) (pts[i - 1], pts[i]) = (pts[i], pts[i - 1]);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = pts.Count - 2; i >= 0; i--)
|
||||
if (sel.Contains(pts[i]) && !sel.Contains(pts[i + 1])) (pts[i + 1], pts[i]) = (pts[i], pts[i + 1]);
|
||||
}
|
||||
_multi.Clear();
|
||||
for (int i = 0; i < pts.Count; i++) if (sel.Contains(pts[i])) _multi.Add(i);
|
||||
_selected = focus != null ? pts.IndexOf(focus) : -1;
|
||||
_anchor = anchor != null ? pts.IndexOf(anchor) : _selected;
|
||||
RebuildPointText();
|
||||
}
|
||||
|
||||
/// <summary>Each selected row gets a copy right after it (as the plugin does); the copies end up selected.</summary>
|
||||
private void DuplicateSelected()
|
||||
{
|
||||
if (_multi.Count == 0) return;
|
||||
NavCommands.Send(new NavCmd { Cmd = "duplicatePoints", Indices = SelectedIndices() });
|
||||
var result = new List<NavPoint>(_data.Points.Count + _multi.Count);
|
||||
var copies = new HashSet<int>();
|
||||
for (int i = 0; i < _data.Points.Count; i++)
|
||||
{
|
||||
NavPoint pt = _data.Points[i];
|
||||
result.Add(pt);
|
||||
if (!_multi.Contains(i)) continue;
|
||||
copies.Add(result.Count);
|
||||
result.Add(new NavPoint { Type = pt.Type, Desc = pt.Desc, Text = pt.Text, NS = pt.NS, EW = pt.EW, Z = pt.Z });
|
||||
}
|
||||
_data.Points = result;
|
||||
_multi.Clear();
|
||||
_multi.UnionWith(copies);
|
||||
_selected = _anchor = _multi.Count > 0 ? _multi.Min() : -1;
|
||||
RebuildPointText();
|
||||
}
|
||||
|
||||
private void DeleteSelected()
|
||||
{
|
||||
if (_multi.Count == 0) return;
|
||||
NavCommands.Send(new NavCmd { Cmd = "deletePoints", Indices = SelectedIndices() });
|
||||
RemoveLocal(new HashSet<int>(_multi));
|
||||
}
|
||||
|
||||
/// <summary>Drops rows from the local copy and shifts the selection past them.</summary>
|
||||
private void RemoveLocal(HashSet<int> removed)
|
||||
{
|
||||
int Shift(int i) { int s = 0; foreach (int r in removed) if (r < i) s++; return i - s; }
|
||||
var keep = new List<int>();
|
||||
foreach (int i in _multi) if (!removed.Contains(i)) keep.Add(Shift(i));
|
||||
_selected = _selected >= 0 && !removed.Contains(_selected) ? Shift(_selected) : -1;
|
||||
_anchor = _anchor >= 0 && !removed.Contains(_anchor) ? Shift(_anchor) : _selected;
|
||||
_multi.Clear();
|
||||
_multi.UnionWith(keep);
|
||||
if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min();
|
||||
for (int i = _data.Points.Count - 1; i >= 0; i--) if (removed.Contains(i)) _data.Points.RemoveAt(i);
|
||||
RebuildPointText();
|
||||
}
|
||||
|
||||
private void ReverseLocal()
|
||||
{
|
||||
int last = _data.Points.Count - 1;
|
||||
_data.Points.Reverse();
|
||||
var flipped = new List<int>();
|
||||
foreach (int i in _multi) flipped.Add(last - i);
|
||||
_multi.Clear();
|
||||
_multi.UnionWith(flipped);
|
||||
if (_selected >= 0) _selected = last - _selected;
|
||||
if (_anchor >= 0) _anchor = last - _anchor;
|
||||
RebuildPointText();
|
||||
}
|
||||
|
||||
private void TakeSnapshot()
|
||||
{
|
||||
var snap = UiSources.Nav.Current;
|
||||
|
|
@ -338,7 +613,11 @@ internal sealed class NavFace : IImGuiPanel
|
|||
_seenVersion = snap.Version;
|
||||
_data = snap.Value.Clone();
|
||||
_navFiles = _data.NavFiles.ToArray();
|
||||
if (_selected >= _data.Points.Count) _selected = -1;
|
||||
int count = _data.Points.Count;
|
||||
_multi.RemoveWhere(i => i >= count);
|
||||
if (_selected >= count) _selected = -1;
|
||||
if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min();
|
||||
if (_anchor >= count) _anchor = _selected;
|
||||
RebuildPointText();
|
||||
UpdateLabels();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -210,7 +210,7 @@ internal sealed unsafe class LogFace : IImGuiPanel
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>Tracker: nine session-stat rows over an adjustable-opacity background.</summary>
|
||||
/// <summary>Tracker: the session-stat rows (TrackerSource) over an adjustable-opacity background.</summary>
|
||||
internal sealed class TrackerFace : IImGuiPanel
|
||||
{
|
||||
private static readonly Vector4 TitleColor = RynthTheme.Vec(0xFFE6B450);
|
||||
|
|
@ -275,6 +275,10 @@ internal sealed class TrackerFace : IImGuiPanel
|
|||
float rowRight = ImGuiNET.ImGui.GetCursorPosX() + ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
if (ImGuiNET.ImGui.GetCursorScreenPos().Y + rowH > gripTop) rowRight -= grip;
|
||||
ImGuiNET.ImGui.TextColored(LabelColor, labels[i]);
|
||||
if (labels[i].StartsWith("Pass", StringComparison.Ordinal))
|
||||
ImGuiNET.ImGui.SetItemTooltip("Luminance that reached your bank without a \"You've banked\" line: your vassals' pass-up.\nFellowship and Zone Share splits arrive the same silent way and are included.");
|
||||
else if (labels[i] == "Lum/5m")
|
||||
ImGuiNET.ImGui.SetItemTooltip("Luminance earned in the last five minutes.");
|
||||
string value = values != null && i < values.Length ? values[i] : "—";
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono9));
|
||||
float w = ImGuiNET.ImGui.CalcTextSize(value).X;
|
||||
|
|
|
|||
|
|
@ -460,11 +460,10 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
_tipLabel = m.Label;
|
||||
_tipDistance = d;
|
||||
_tipPct = pct;
|
||||
// A label is the object's name; the kinds a name alone doesn't tell apart say what they are.
|
||||
// A label is the object's name; the kind always follows it, so a dot says which show box
|
||||
// in the settings hides it (a fellow is not a "Player", your kill's corpse not a "Corpse").
|
||||
string name = string.IsNullOrEmpty(m.Label) ? RadarKind.Name(m.Kind)
|
||||
: m.Kind is RadarKind.Fellow or RadarKind.Pet or RadarKind.Vendor or RadarKind.OwnCorpse or RadarKind.Player
|
||||
? m.Label + " (" + RadarKind.Name(m.Kind) + ")"
|
||||
: m.Label!;
|
||||
: m.Label + " (" + RadarKind.Name(m.Kind) + ")";
|
||||
var inv = System.Globalization.CultureInfo.InvariantCulture;
|
||||
_tipText = name + "\n" + d.ToString(inv) + " yd"
|
||||
+ (pct >= 0 ? " " + pct.ToString(inv) + "%" : "");
|
||||
|
|
@ -572,6 +571,9 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
AvaloniaOverlay.RadarCtrlGatedClickThrough = RadarSettingsStore.CtrlGatedClickThrough;
|
||||
RadarSettingsStore.Save();
|
||||
}
|
||||
// The gear toggles this window too; Close is the obvious way out (changes are already saved).
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (ImGuiNET.ImGui.Button("Close")) _settingsOpen = false;
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
ImGuiNET.ImGui.End();
|
||||
|
|
@ -590,16 +592,16 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
|
||||
private static readonly string[] KindTips =
|
||||
{
|
||||
"Creatures you can attack.",
|
||||
"Creatures you can't attack (townsfolk, quest givers).",
|
||||
"Creatures you can attack.\nHover a dot on the radar: its tooltip names the box that shows it.",
|
||||
"Creatures you can't attack (townsfolk, quest givers).\nShopkeepers have their own box (Vendors).",
|
||||
"Portals, with their destination.",
|
||||
"Doors, gates and hatches.",
|
||||
"Other players.",
|
||||
"Other players, outside your fellowship.\nPlayers in your fellowship have their own box (Fellows).",
|
||||
"Players in your fellowship.",
|
||||
"Your own combat pet.",
|
||||
"Shopkeepers.",
|
||||
"Corpses you can't loot (or not identified yet: selecting one tells).",
|
||||
"Corpses you may loot: your kills, your fellows' kills and your own corpse. Known once the corpse has been identified (looting or selecting it does that).",
|
||||
"Corpses. Off hides every corpse, the ones you may loot too.\nOn: corpses you can't loot (or not identified yet: selecting one tells) show in this colour.",
|
||||
"Corpses you may loot: your kills, your fellows' kills and your own corpse, in their own colour. Known once the corpse has been identified (looting or selecting it does that).\nOnly while Corpses is on.",
|
||||
"Lifestones.",
|
||||
"Items lying on the ground. Off by default: there can be a lot of them.",
|
||||
};
|
||||
|
|
@ -623,14 +625,21 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
foreach (var (kind, label) in KindRowsOrder)
|
||||
{
|
||||
ImGuiNET.ImGui.PushID(kind);
|
||||
// "Your corpses" sits under Corpses: Corpses off hides them too (RadarSettingsStore.ShowKind).
|
||||
bool sub = kind == RadarKind.OwnCorpse;
|
||||
if (sub) { ImGuiNET.ImGui.Indent(14 * scale); ImGuiNET.ImGui.BeginDisabled(!RadarSettingsStore.ShowCorpses); }
|
||||
changed |= ImGuiNET.ImGui.Checkbox("##show", ref RadarSettingsStore.ShowFlag(kind));
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(KindTips[kind]);
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
// The marker exactly as the radar draws it.
|
||||
// The marker exactly as the radar draws it; faded while the kind is hidden, so the
|
||||
// legend doesn't look like the box did nothing.
|
||||
float box = ImGuiNET.ImGui.GetFrameHeight();
|
||||
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(box, box));
|
||||
RadarMarkerStyle.Draw(dl, kind, at + new Vector2(box, box) * 0.5f, KindCols[kind], 1.3f * scale);
|
||||
uint glyph = KindCols[kind];
|
||||
if (!RadarSettingsStore.ShowKind(kind))
|
||||
glyph = (glyph & 0x00FFFFFFu) | ((uint)((glyph >> 24) * 0.3f) << 24);
|
||||
RadarMarkerStyle.Draw(dl, kind, at + new Vector2(box, box) * 0.5f, glyph, 1.3f * scale);
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextUnformatted(label);
|
||||
|
|
@ -642,6 +651,7 @@ internal sealed class RadarFace : IImGuiPanel
|
|||
RadarSettingsStore.KindColors[kind] = ToArgb(v);
|
||||
_colorDirty = true;
|
||||
}
|
||||
if (sub) { ImGuiNET.ImGui.EndDisabled(); ImGuiNET.ImGui.Unindent(14 * scale); }
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
|
|
|
|||
|
|
@ -12,12 +12,19 @@
|
|||
// recorded hazards and the saved routes. Was the Patrol
|
||||
// launcher's right-click popup; right-click now opens this
|
||||
// drawer (popped out: still the popup).
|
||||
// Mini Remote RynthAi's Mini Remote (session rates, target, summon,
|
||||
// item slots, toggles, bank, rebuff, Translate, Guardian)
|
||||
// with its Options menu. The plugin draws it here through
|
||||
// RynthPluginRenderEmbed("miniremote") and says how big it
|
||||
// wants the panel; the Hub launcher's right-click opens it
|
||||
// (popped out: the floating Mini Remote instead).
|
||||
// AC thread only (inside the dashboard's Draw).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.Engine.UI;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
|
|
@ -25,7 +32,7 @@ namespace RynthCore.Engine.ImGuiBackend.Panels;
|
|||
|
||||
internal sealed partial class RynthAiFace
|
||||
{
|
||||
/// <summary>Meta state, bot activity and the four file pickers.</summary>
|
||||
/// <summary>Meta state, bot activity and the five file pickers.</summary>
|
||||
private sealed class FilesDrawer : DashboardDrawer
|
||||
{
|
||||
private readonly RynthAiFace _face;
|
||||
|
|
@ -40,17 +47,20 @@ internal sealed partial class RynthAiFace
|
|||
public override string TabTooltip(bool right)
|
||||
{
|
||||
RynthAiView? v = _face._view;
|
||||
return "Loaded files: the Profile, Nav, Loot and Meta pickers, meta state and bot activity.\n" +
|
||||
return "Loaded files: the Profile, Nav, Loot, Meta and Buffs pickers, meta state and bot activity.\n" +
|
||||
"Profile: " + (v?.ProfileText ?? "Default") + "\nNav: " + (v?.NavText ?? "None") +
|
||||
"\nLoot: " + (v?.LootText ?? "None") + "\nMeta: " + (v?.MetaText ?? "None") +
|
||||
"\nBuffs: " + (v?.BuffText ?? "Built-in") +
|
||||
(right ? "\n\nClick to slide them out (to the right: there's no room on the left)." : "\n\nClick to slide them out.");
|
||||
}
|
||||
|
||||
// The picker rows are the dashboard's own (Selector), so they take its size factor (_k);
|
||||
// the frame and the info lines take the drawers' k.
|
||||
private const float LineH = 15, SelRow = 16, SelGap = 3;
|
||||
|
||||
public override float Width(float k) => 230 * k;
|
||||
public override float Height(float k) =>
|
||||
(Pad + TitleH + 4 + 2 * LineH + 6) * k + 4 * SelRow + 3 * SelGap + Pad * k;
|
||||
(Pad + TitleH + 4 + 2 * LineH + 6) * k + (5 * SelRow + 4 * SelGap) * _k + Pad * k;
|
||||
|
||||
public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k)
|
||||
{
|
||||
|
|
@ -70,12 +80,14 @@ internal sealed partial class RynthAiFace
|
|||
y += lh + 6 * k;
|
||||
|
||||
_face.Selector(0, "Profile:", view?.ProfileText ?? "Default", raw.Profiles, raw.SelectedProfileIdx, 3, x, y, w, null);
|
||||
y += SelRow + SelGap;
|
||||
y += (SelRow + SelGap) * _k;
|
||||
_face.Selector(1, "Nav:", view?.NavText ?? "None", raw.NavProfiles, raw.SelectedNavIdx, 0, x, y, w, null);
|
||||
y += SelRow + SelGap;
|
||||
y += (SelRow + SelGap) * _k;
|
||||
_face.Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, x, y, w, raw);
|
||||
y += SelRow + SelGap;
|
||||
y += (SelRow + SelGap) * _k;
|
||||
_face.Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, x, y, w, null);
|
||||
y += (SelRow + SelGap) * _k;
|
||||
_face.Selector(4, "Buffs:", view?.BuffText ?? "Built-in", raw.BuffProfiles, raw.SelectedBuffIdx, 4, x, y, w, null, spellsButton: true);
|
||||
}
|
||||
|
||||
private static void InfoLine(ImDrawListPtr dl, ImFontPtr f, float x, float y, float w, float lh, float labelW, string label, string value)
|
||||
|
|
@ -136,4 +148,81 @@ internal sealed partial class RynthAiFace
|
|||
finally { ImGuiNET.ImGui.EndChild(); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>RynthAi's Mini Remote, drawn by the plugin into this drawer (the Hub launcher's right-click).</summary>
|
||||
private sealed class RemoteDrawer : DashboardDrawer
|
||||
{
|
||||
/// <summary>The plugin surface name, NUL-terminated for the export.</summary>
|
||||
private static ReadOnlySpan<byte> Surface => "miniremote\0"u8;
|
||||
|
||||
// Content bounds in unscaled pixels; the plugin's wish is clamped to them.
|
||||
private const float MinW = 200, MaxW = 760, MinH = 60, DefaultH = 120;
|
||||
|
||||
/// <summary>The content size the plugin last asked for (pixels); zero until it has drawn here.</summary>
|
||||
private Vector2 _want;
|
||||
|
||||
public override string Key => "remote";
|
||||
public override string Icon => PhosphorIcons.SquaresFour;
|
||||
public override string Name => "Mini Remote drawer";
|
||||
public override bool SavedOpen => RynthAiDashboardState.RemoteOpen;
|
||||
public override void SaveOpen(bool open) => RynthAiDashboardState.SetRemoteOpen(open);
|
||||
|
||||
public override string TabTooltip(bool right) =>
|
||||
"Mini Remote: session rates, attack target, summon, item slots, toggles, bank, rebuff, Translate.\n" +
|
||||
"Its Options button picks the sections (also: right-click Hub). The ILT tabs are in the Mini Remote window.\n" +
|
||||
(right ? "Click to slide it out (to the right: there's no room on the left)." : "Click to slide it out.");
|
||||
|
||||
public override float Width(float k) =>
|
||||
Math.Clamp(_want.X > 0 ? _want.X : MinW * k, MinW * k, MaxW * k) + 2 * Pad * k;
|
||||
|
||||
public override float Height(float k)
|
||||
{
|
||||
float frame = (Pad + TitleH + 4 + Pad) * k;
|
||||
// Never taller than the screen: the body scrolls instead.
|
||||
float screen = ImGuiNET.ImGui.GetIO().DisplaySize.Y;
|
||||
float maxBody = screen > 1 ? MathF.Max(MinH * k, screen - frame - 8 * k) : 900 * k;
|
||||
return frame + Math.Clamp(_want.Y > 0 ? _want.Y : DefaultH * k, MinH * k, maxBody);
|
||||
}
|
||||
|
||||
public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k)
|
||||
{
|
||||
float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.SquaresFour, "MINI REMOTE", null, "Hide the Mini Remote drawer");
|
||||
float x = origin.X + Pad * k;
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y));
|
||||
Vector2 size = new(panelW - 2 * Pad * k, MathF.Max(1, origin.Y + panelH - Pad * k - y));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
|
||||
bool open = ImGuiNET.ImGui.BeginChild("##remote_body", size, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
try
|
||||
{
|
||||
if (!open) return;
|
||||
// The plugin's widgets use the default UI font, as in its floating Mini Remote.
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
try
|
||||
{
|
||||
int result = PluginManager.RenderEmbed("RynthAi", Surface, size, out Vector2 want);
|
||||
if (result == PluginManager.EmbedDrawn)
|
||||
{
|
||||
if (want.X > 0 && want.Y > 0) _want = want;
|
||||
}
|
||||
else
|
||||
{
|
||||
_want = Vector2.Zero;
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, DMute);
|
||||
ImGuiNET.ImGui.TextWrapped(result switch
|
||||
{
|
||||
PluginManager.EmbedNoPlugin =>
|
||||
"This RynthAi can't draw its Mini Remote here (it needs RynthAi 0.5.27 or later). Left-click Hub for the floating Mini Remote.",
|
||||
PluginManager.EmbedFailed =>
|
||||
"The Mini Remote failed to draw here (see the log). Left-click Hub for the floating Mini Remote.",
|
||||
_ => "The Mini Remote shows here once RynthAi is ready: in the world, with plugin windows on (engine.json EnablePluginOverlayWindows).",
|
||||
});
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
}
|
||||
finally { ImGuiNET.ImGui.PopFont(); }
|
||||
}
|
||||
finally { ImGuiNET.ImGui.EndChild(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@
|
|||
// the buttons above it.
|
||||
// drawers tabs on the left edge (DashboardDrawers.cs), one open at a
|
||||
// time, a window of their own beside the dashboard: Ranges
|
||||
// (RangesSlideOut.cs), Loaded files and Patrol
|
||||
// (RangesSlideOut.cs), Loaded files, Patrol and Mini Remote
|
||||
// (RynthAiFace.Drawers.cs). Everything that slides out goes
|
||||
// left; only the bars stay at the bottom (Tom 2026-10-05).
|
||||
// Minimized keeps the title row, the control row and the bars. The window's
|
||||
|
|
@ -27,6 +27,17 @@
|
|||
// string preformatted); clicks: RynthAiCommands.
|
||||
//
|
||||
// Chromeless (like the Avalonia face): the title row is the drag surface.
|
||||
//
|
||||
// Size: the dashboard's panel text size (PanelTextScale.Get(Title): its own
|
||||
// row in Settings > Display, else All Panels). The host draws the face with
|
||||
// the fonts baked for that step (ImGuiFonts.CurrentStep, the nearest baked
|
||||
// one until a re-bake lands) and every box here is multiplied by that same
|
||||
// step's factor (Px), so text, icons and boxes grow together; size 0 is the
|
||||
// plain pixel layout. The title row has no host title bar, so it carries the
|
||||
// control: Ctrl+wheel over it steps the size, right-click opens the size
|
||||
// popup (ImGuiPanelHost.TextSizeRows). A size change scales the window's
|
||||
// width with it and fits the height to the content (MeasureAndFit).
|
||||
//
|
||||
// AC thread only; no per-frame string building except the FPS/uptime footer,
|
||||
// which is cached until its value changes.
|
||||
// ============================================================================
|
||||
|
|
@ -76,31 +87,54 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
// The drawers on the dashboard's left edge (their own window, placed against this one).
|
||||
private readonly DashboardDrawers _drawers;
|
||||
private readonly PatrolDrawer _patrol = new();
|
||||
private readonly RemoteDrawer _remote = new();
|
||||
// This frame's data, for the drawers.
|
||||
private RynthAiView? _view;
|
||||
private RynthAiSnapshot _raw = Empty;
|
||||
// Picker toggle: ImGui closes a popup on the press outside it, so remember
|
||||
// whether it was showing when the selector press began (a second click closes).
|
||||
private readonly int[] _pickerShownFrame = { -10, -10, -10, -10 };
|
||||
private readonly bool[] _pressedWhileOpen = new bool[4];
|
||||
private readonly int[] _pickerShownFrame = { -10, -10, -10, -10, -10 };
|
||||
private readonly bool[] _pressedWhileOpen = new bool[5];
|
||||
// The content's height (logical units, body padding included), measured each
|
||||
// frame: the window's minimum height. _fit: resize the window to it once.
|
||||
private float _contentHeight;
|
||||
private bool _fit;
|
||||
// The host's resize grip, which keeps its own size (it is not the panel's text).
|
||||
private const float GripRoom = 12;
|
||||
|
||||
// This frame's size factor (PanelTextScale.Factor of the step the fonts are drawn at); 1 at size 0.
|
||||
// Static: the popups' and drawers' static helpers read it too. AC thread.
|
||||
private static float _k = 1f;
|
||||
/// <summary>A layout length (pixels at size 0) at the dashboard's size.</summary>
|
||||
private static float Px(float v) => v * _k;
|
||||
// The size factor the docked window was last fitted at and its width then (logical units):
|
||||
// a size change scales the width from there (not from a width the new minimum already grew).
|
||||
private float _fitK, _fitWidth;
|
||||
private const string SizePopupId = "##dash_size";
|
||||
|
||||
/// <summary>The factor of the step the host draws this panel's fonts at (ImGuiPanelHost.DrawPanel sets the same step).</summary>
|
||||
private static float SizeFactor() => PanelTextScale.Factor(ImGuiFonts.BakedStepNear(PanelTextScale.Get(Title)));
|
||||
|
||||
public RynthAiFace()
|
||||
{
|
||||
// Tab order top to bottom; the first one saved open wins at load.
|
||||
_drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol);
|
||||
_drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol, _remote);
|
||||
}
|
||||
|
||||
public Vector2? MinSize => new Vector2(MinWidth, _contentHeight > 0 ? _contentHeight
|
||||
: RynthAiDashboardState.Minimized ? 54 : 180);
|
||||
public Vector2? MinSize
|
||||
{
|
||||
get
|
||||
{
|
||||
float k = SizeFactor();
|
||||
return new Vector2(MinWidth * k, _contentHeight > 0 ? _contentHeight
|
||||
: (RynthAiDashboardState.Minimized ? 54 : 180) * k);
|
||||
}
|
||||
}
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
UiSources.RynthAi.Subscribe();
|
||||
UiSources.RynthSortWatch.Subscribe(); // the Sort toggle, while RynthSort is loaded
|
||||
UiSources.RynthAi.RequestRefresh();
|
||||
_fit = true; // drop the empty space a taller saved size leaves under the content
|
||||
}
|
||||
|
|
@ -108,6 +142,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
public void OnHidden()
|
||||
{
|
||||
UiSources.RynthAi.Unsubscribe();
|
||||
UiSources.RynthSortWatch.Unsubscribe();
|
||||
if (_patrolOpen) { UiSources.Patrol.Unsubscribe(); _patrolOpen = false; }
|
||||
_drawers.Detach();
|
||||
}
|
||||
|
|
@ -121,31 +156,45 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
_view = view;
|
||||
_raw = raw;
|
||||
uint boxBg = (C(0xFF0A121A) & 0x00FFFFFF) | ((uint)(view?.PanelAlpha ?? 242) << 24);
|
||||
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float x0 = start.X;
|
||||
float width = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
|
||||
TitleRow(raw, x0, width, minimized);
|
||||
Gap(4);
|
||||
// Popped out (no drawers there): the Profile/Nav/Loot/Meta pickers inline while expanded
|
||||
// (the caret on the control row). Docked they are the Loaded files drawer.
|
||||
if (popped && !minimized && RynthAiDashboardState.FilesOpen)
|
||||
// The host set the step these fonts are drawn at; the boxes take the same step's factor.
|
||||
_k = PanelTextScale.Factor(ImGuiFonts.CurrentStep);
|
||||
// Enlarged: tooltips and menus opened from the dashboard at its size too. (At size 0 the
|
||||
// default font already is Ui11: nothing is pushed, so nothing changes.)
|
||||
bool pushFont = ImGuiFonts.CurrentStep > 0;
|
||||
if (pushFont) ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
|
||||
try
|
||||
{
|
||||
HeaderGrid(view, raw, x0, width);
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float x0 = start.X;
|
||||
float width = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
|
||||
TitleRow(raw, x0, width, minimized);
|
||||
Gap(4);
|
||||
// Popped out (no drawers there): the Profile/Nav/Loot/Meta pickers inline while expanded
|
||||
// (the caret on the control row). Docked they are the Loaded files drawer.
|
||||
if (popped && !minimized && RynthAiDashboardState.FilesOpen)
|
||||
{
|
||||
HeaderGrid(view, raw, x0, width);
|
||||
Gap(4);
|
||||
}
|
||||
ControlRow(view, raw, x0, width, minimized, popped, boxBg);
|
||||
if (!minimized)
|
||||
{
|
||||
Gap(4);
|
||||
Launchers(x0, width);
|
||||
Gap(6);
|
||||
Footer(view, x0, width);
|
||||
}
|
||||
Bars(view, raw, x0, width, boxBg);
|
||||
PatrolPopup();
|
||||
CharMenu();
|
||||
SizePopup();
|
||||
MeasureAndFit(start.Y);
|
||||
}
|
||||
ControlRow(view, raw, x0, width, minimized, popped, boxBg);
|
||||
if (!minimized)
|
||||
finally
|
||||
{
|
||||
Gap(4);
|
||||
Launchers(x0, width);
|
||||
Gap(6);
|
||||
Footer(view, x0, width);
|
||||
if (pushFont) ImGuiNET.ImGui.PopFont();
|
||||
}
|
||||
Bars(view, raw, x0, width, boxBg);
|
||||
PatrolPopup();
|
||||
MeasureAndFit(start.Y);
|
||||
// Last: a window of its own, placed against this one's rect (hidden popped out).
|
||||
_drawers.Draw();
|
||||
}
|
||||
|
|
@ -153,6 +202,9 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
/// <summary>
|
||||
/// Records the content height as the window's minimum (so the bars at the
|
||||
/// bottom are never cut off) and, after a toggle, fits the window to it.
|
||||
/// After a size change the width scales with the size (from the width it had
|
||||
/// at the old size), never wider than the screen, and the window is kept on
|
||||
/// the screen.
|
||||
/// </summary>
|
||||
private void MeasureAndFit(float startY)
|
||||
{
|
||||
|
|
@ -161,11 +213,30 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
float place = ImGuiPanelHost.PlacementScale();
|
||||
// + room for the host's resize grip, which is painted over the body's bottom-right corner.
|
||||
_contentHeight = MathF.Ceiling(px / place) + GripRoom;
|
||||
if (_fit && !ImGuiPopOuts.InPopOutFrame)
|
||||
// Popped out the window is the OS window's (sized by the player); a size change made
|
||||
// meanwhile is fitted when it docks back (_fitK still holds the docked size).
|
||||
if (ImGuiPopOuts.InPopOutFrame) return;
|
||||
|
||||
float width = ImGuiNET.ImGui.GetWindowWidth() / place;
|
||||
if (_fitK > 0 && _k != _fitK)
|
||||
{
|
||||
_fit = false;
|
||||
ImGuiPanelHost.RequestSize(Title, new Vector2(ImGuiNET.ImGui.GetWindowWidth() / place, _contentHeight));
|
||||
width = _fitWidth * (_k / _fitK);
|
||||
float screenW = ImGuiNET.ImGui.GetIO().DisplaySize.X / place;
|
||||
if (screenW > 1) width = MathF.Min(width, screenW);
|
||||
width = MathF.Max(width, MinWidth * _k);
|
||||
ImGuiPanelHost.RequestSize(Title, new Vector2(width, _contentHeight));
|
||||
// Applied after the size, clamped to the screen at it: a bigger dashboard near the right or
|
||||
// bottom edge moves in rather than running off (saved with the new size, like the bar's clamp).
|
||||
ImGuiPanelHost.RequestPos(Title, ImGuiNET.ImGui.GetWindowPos() / place);
|
||||
}
|
||||
else if (_fit)
|
||||
{
|
||||
_fit = false;
|
||||
ImGuiPanelHost.RequestSize(Title, new Vector2(width, _contentHeight));
|
||||
}
|
||||
_fitK = _k;
|
||||
_fitWidth = width;
|
||||
}
|
||||
|
||||
// ── Title row: "R" + "YNTH" | chips (drag surface) ──────
|
||||
|
|
@ -175,18 +246,19 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
const int chips = 7;
|
||||
const float chipW = 18, chipH = 16, chipGap = 2;
|
||||
float chipW = Px(18), chipH = Px(16), chipGap = Px(2), chipRound = Px(2);
|
||||
float chipsW = chips * chipW + (chips - 1) * chipGap;
|
||||
float rowH = 20;
|
||||
float rowH = Px(20);
|
||||
|
||||
// Drag surface: everything left of the chips.
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y));
|
||||
ImGuiNET.ImGui.InvisibleButton("##dash_drag", new Vector2(Math.Max(1, width - chipsW), rowH));
|
||||
ImGuiPanelHost.DragWindowWithLastItem();
|
||||
ImGuiNET.ImGui.SetItemTooltip(DragTip);
|
||||
|
||||
ImFontPtr title = ImGuiFonts.Get(UiFont.Dash14);
|
||||
float ty = y + (rowH - title.FontSize) * 0.5f;
|
||||
dl.PushClipRect(new Vector2(x0, y), new Vector2(x0 + Math.Max(1, width - chipsW - 4), y + rowH), true);
|
||||
dl.PushClipRect(new Vector2(x0, y), new Vector2(x0 + Math.Max(1, width - chipsW - Px(4)), y + rowH), true);
|
||||
dl.AddText(title, title.FontSize, new Vector2(x0, ty), Teal, "R");
|
||||
float rw = CalcWidth(title, "R");
|
||||
dl.AddText(title, title.FontSize, new Vector2(x0 + rw, ty), White, "YNTH");
|
||||
|
|
@ -198,7 +270,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
const UiFont chipFont = UiFont.Dash11;
|
||||
|
||||
bool target = RynthAiDashboardState.ShowTargetBar;
|
||||
if (IconButton("##chip_target", new Vector2(cx, cy), chip, PhosphorIcons.Crosshair, chipFont, BtnFill, target ? Teal : Mute, BtnBord, 2))
|
||||
if (IconButton("##chip_target", new Vector2(cx, cy), chip, PhosphorIcons.Crosshair, chipFont, BtnFill, target ? Teal : Mute, BtnBord, chipRound))
|
||||
{
|
||||
RynthAiDashboardState.SetShowTargetBar(!target);
|
||||
_fit = true;
|
||||
|
|
@ -208,7 +280,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
: "Target bar off. Click to show the target's name and health at the bottom.");
|
||||
cx += chipW + chipGap;
|
||||
bool vitals = RynthAiDashboardState.ShowVitals;
|
||||
if (IconButton("##chip_vitals", new Vector2(cx, cy), chip, PhosphorIcons.Heartbeat, chipFont, BtnFill, vitals ? Teal : Mute, BtnBord, 2))
|
||||
if (IconButton("##chip_vitals", new Vector2(cx, cy), chip, PhosphorIcons.Heartbeat, chipFont, BtnFill, vitals ? Teal : Mute, BtnBord, chipRound))
|
||||
{
|
||||
RynthAiDashboardState.SetShowVitals(!vitals);
|
||||
_fit = true;
|
||||
|
|
@ -218,20 +290,20 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
: "Player vitals off. Click to show your health, stamina and mana at the bottom.");
|
||||
cx += chipW + chipGap;
|
||||
if (IconButton("##chip_lock", new Vector2(cx, cy), chip, raw.IsLocked ? PhosphorIcons.Lock : PhosphorIcons.LockOpen,
|
||||
chipFont, BtnFill, raw.IsLocked ? Amber : Mute, BtnBord, 2))
|
||||
chipFont, BtnFill, raw.IsLocked ? Amber : Mute, BtnBord, chipRound))
|
||||
RynthAiCommands.TogglePanelLock();
|
||||
ImGuiNET.ImGui.SetItemTooltip(raw.IsLocked ? "Locked. Click to unlock the dashboard." : "Click to lock the dashboard in place.");
|
||||
cx += chipW + chipGap;
|
||||
if (IconButton("##chip_minus", new Vector2(cx, cy), chip, PhosphorIcons.Minus, chipFont, BtnFill, Mute, BtnBord, 2))
|
||||
if (IconButton("##chip_minus", new Vector2(cx, cy), chip, PhosphorIcons.Minus, chipFont, BtnFill, Mute, BtnBord, chipRound))
|
||||
RynthAiCommands.AdjustOpacity(-0.1f);
|
||||
ImGuiNET.ImGui.SetItemTooltip("More transparent");
|
||||
cx += chipW + chipGap;
|
||||
if (IconButton("##chip_plus", new Vector2(cx, cy), chip, PhosphorIcons.Plus, chipFont, BtnFill, Mute, BtnBord, 2))
|
||||
if (IconButton("##chip_plus", new Vector2(cx, cy), chip, PhosphorIcons.Plus, chipFont, BtnFill, Mute, BtnBord, chipRound))
|
||||
RynthAiCommands.AdjustOpacity(0.1f);
|
||||
ImGuiNET.ImGui.SetItemTooltip("More opaque");
|
||||
cx += chipW + chipGap;
|
||||
if (IconButton("##chip_min", new Vector2(cx, cy), chip,
|
||||
minimized ? PhosphorIcons.ArrowsOutLineVertical : PhosphorIcons.ArrowsInLineVertical, chipFont, BtnFill, Mute, BtnBord, 2))
|
||||
minimized ? PhosphorIcons.ArrowsOutLineVertical : PhosphorIcons.ArrowsInLineVertical, chipFont, BtnFill, Mute, BtnBord, chipRound))
|
||||
{
|
||||
RynthAiDashboardState.SetMinimized(!minimized);
|
||||
_fit = true; // the window fits the other mode's content next frame
|
||||
|
|
@ -240,68 +312,122 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
cx += chipW + chipGap;
|
||||
if (PanelRouter.CanPopOut)
|
||||
{
|
||||
if (IconButton("##chip_dock", new Vector2(cx, cy), chip, ImGuiPanelHost.PopOutGlyph, chipFont, BtnFill, Mute, BtnBord, 2))
|
||||
if (IconButton("##chip_dock", new Vector2(cx, cy), chip, ImGuiPanelHost.PopOutGlyph, chipFont, BtnFill, Mute, BtnBord, chipRound))
|
||||
ImGuiPanelHost.TogglePopOut(Title);
|
||||
ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip);
|
||||
}
|
||||
|
||||
// The size, from the title row (no host title bar here): Ctrl+wheel steps it, right-click
|
||||
// opens the size popup. The whole row, chips included; the body below keeps its wheel.
|
||||
if (ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem)
|
||||
&& ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x0, y), new Vector2(x0 + width, y + rowH), false))
|
||||
{
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
if (io.KeyCtrl && io.MouseWheel != 0f)
|
||||
PanelTextScale.SetForWindow(Title, PanelTextScale.Get(Title) + (io.MouseWheel > 0f ? 1 : -1));
|
||||
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right))
|
||||
ImGuiNET.ImGui.OpenPopup(SizePopupId);
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + rowH));
|
||||
}
|
||||
|
||||
// ── Header: macro + state (40%) | Profile/Nav/Loot/Meta pickers (60%) ──
|
||||
private const string DragTip = "Drag to move the dashboard.\nRight-click: dashboard size. Ctrl+wheel here: bigger or smaller.";
|
||||
|
||||
/// <summary>
|
||||
/// The title row's right-click popup: the dashboard's size (its panel text size, the same
|
||||
/// setting as Settings > Display > RynthAi Dashboard, or All Panels until it is set on its own).
|
||||
/// </summary>
|
||||
private static void SizePopup()
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(8)));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup(SizePopupId);
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
if (!open) return;
|
||||
try
|
||||
{
|
||||
ImGuiPanelHost.TextSizeRows(Title, _k, "Dashboard size");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Header: macro + state (40%) | Profile/Nav/Loot/Meta/Buffs pickers (60%) ──
|
||||
|
||||
private void HeaderGrid(RynthAiView? view, RynthAiSnapshot raw, float x0, float width)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float y0 = ImGuiNET.ImGui.GetCursorScreenPos().Y + 2;
|
||||
float y0 = ImGuiNET.ImGui.GetCursorScreenPos().Y + Px(2);
|
||||
float leftW = width * 0.4f;
|
||||
|
||||
// Left: Meta State / Bot Activity (the macro start/stop is the control row's first square).
|
||||
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10);
|
||||
float ly = y0;
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly), Mute, "Meta State:");
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.MetaStateText ?? "Default");
|
||||
ly += 2 * (f10.FontSize + 1) + 4;
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + Px(1)), Amber, view?.MetaStateText ?? "Default");
|
||||
ly += 2 * (f10.FontSize + Px(1)) + Px(4);
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly), Mute, "Bot Activity:");
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.BotActivityText ?? "Idle");
|
||||
float leftBottom = ly + 2 * (f10.FontSize + 1);
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + Px(1)), Amber, view?.BotActivityText ?? "Idle");
|
||||
float leftBottom = ly + 2 * (f10.FontSize + Px(1));
|
||||
|
||||
// Right: four selector rows (label 36 px, picker fills, spacing 3).
|
||||
// Right: five selector rows (label 36 px, picker fills, spacing 3; x the size).
|
||||
float rx = x0 + leftW, rw = width - leftW, ry = y0;
|
||||
// The fold arrow sits at the end of the Profile row, where it always fits.
|
||||
const float foldW = 18f;
|
||||
Selector(0, "Profile:", view?.ProfileText ?? "Default", raw.Profiles, raw.SelectedProfileIdx, 3, rx, ry, rw - foldW - 2, null);
|
||||
if (IconButton("##files_fold", new Vector2(rx + rw - foldW, ry), new Vector2(foldW, 16), PhosphorIcons.CaretUp, UiFont.Dash11, BtnFill, Mute, BtnBord, 2))
|
||||
float foldW = Px(18f), selH = Px(16), selStep = Px(16 + 3);
|
||||
Selector(0, "Profile:", view?.ProfileText ?? "Default", raw.Profiles, raw.SelectedProfileIdx, 3, rx, ry, rw - foldW - Px(2), null);
|
||||
if (IconButton("##files_fold", new Vector2(rx + rw - foldW, ry), new Vector2(foldW, selH), PhosphorIcons.CaretUp, UiFont.Dash11, BtnFill, Mute, BtnBord, Px(2)))
|
||||
RynthAiDashboardState.SetFilesOpen(false);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Fold the loaded files into one line");
|
||||
ry += 16 + 3;
|
||||
ry += selStep;
|
||||
Selector(1, "Nav:", view?.NavText ?? "None", raw.NavProfiles, raw.SelectedNavIdx, 0, rx, ry, rw, null);
|
||||
ry += 16 + 3;
|
||||
ry += selStep;
|
||||
Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, rx, ry, rw, raw);
|
||||
ry += 16 + 3;
|
||||
ry += selStep;
|
||||
Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, rx, ry, rw, null);
|
||||
ry += 16;
|
||||
ry += selStep;
|
||||
Selector(4, "Buffs:", view?.BuffText ?? "Built-in", raw.BuffProfiles, raw.SelectedBuffIdx, 4, rx, ry, rw, null, spellsButton: true);
|
||||
ry += selH;
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, Math.Max(leftBottom, ry) + 4));
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, Math.Max(leftBottom, ry) + Px(4)));
|
||||
}
|
||||
|
||||
private static readonly string[] SelectorIds = { "##sel_profile", "##sel_nav", "##sel_loot", "##sel_meta" };
|
||||
private static readonly string[] PickerIds = { "##pick_profile", "##pick_nav", "##pick_loot", "##pick_meta" };
|
||||
private static readonly string[] SelectorIds = { "##sel_profile", "##sel_nav", "##sel_loot", "##sel_meta", "##sel_buff" };
|
||||
private static readonly string[] PickerIds = { "##pick_profile", "##pick_nav", "##pick_loot", "##pick_meta", "##pick_buff" };
|
||||
private static readonly string[] NoneItems = { "None" };
|
||||
|
||||
/// <summary>
|
||||
/// One file picker row. <paramref name="kind"/> is RynthPluginSelectProfile's list (0 nav,
|
||||
/// 1 loot, 2 meta, 3 settings profile, 4 buff profile). <paramref name="lootEdit"/> adds the
|
||||
/// Loot Editor button, <paramref name="spellsButton"/> the RynthAi Spells window button.
|
||||
/// </summary>
|
||||
private void Selector(int slot, string label, string text, string[] items, int selected, int kind,
|
||||
float x, float y, float w, RynthAiSnapshot? lootEdit)
|
||||
float x, float y, float w, RynthAiSnapshot? lootEdit, bool spellsButton = false)
|
||||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10), f9 = ImGuiFonts.Get(UiFont.Dash9);
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x, y + (16 - f10.FontSize) * 0.5f), Mute, label);
|
||||
float rowH = Px(16), round = Px(2);
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(x, y + (rowH - f10.FontSize) * 0.5f), Mute, label);
|
||||
|
||||
float editW = 0;
|
||||
if (spellsButton)
|
||||
{
|
||||
editW = Px(18);
|
||||
var ep = new Vector2(x + w - editW, y);
|
||||
if (IconButton("##buff_spells", ep, new Vector2(editW, rowH), PhosphorIcons.Sparkle, UiFont.Dash11, SelectorBg, Mute, 0, round))
|
||||
RynthAiCommands.ApplyRemoteCommand("spells", "toggle");
|
||||
ImGuiNET.ImGui.SetItemTooltip("RynthAi Spells: browse the spell list and build buff profiles.");
|
||||
editW += Px(3);
|
||||
}
|
||||
if (lootEdit != null)
|
||||
{
|
||||
editW = 18;
|
||||
editW = Px(18);
|
||||
var ep = new Vector2(x + w - editW, y);
|
||||
if (IconButton("##loot_edit", ep, new Vector2(editW, 16), PhosphorIcons.TreasureChest, UiFont.Dash11, SelectorBg, Mute, 0, 2))
|
||||
if (IconButton("##loot_edit", ep, new Vector2(editW, rowH), PhosphorIcons.TreasureChest, UiFont.Dash11, SelectorBg, Mute, 0, round))
|
||||
{
|
||||
string path = !string.IsNullOrEmpty(lootEdit.VendorProfilePath) ? lootEdit.VendorProfilePath : lootEdit.CurrentLootPath;
|
||||
// The in-game Loot Editor panel. The external editor is one click away on the
|
||||
|
|
@ -309,29 +435,29 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
LootEditorFace.ToggleFor(path);
|
||||
}
|
||||
ImGuiNET.ImGui.SetItemTooltip("Loot Editor: the loot profile in use, or the open vendor's AutoVendor profile.");
|
||||
editW += 3;
|
||||
editW += Px(3);
|
||||
}
|
||||
|
||||
var pos = new Vector2(x + 36, y);
|
||||
var size = new Vector2(Math.Max(20, w - 36 - editW), 16);
|
||||
var pos = new Vector2(x + Px(36), y);
|
||||
var size = new Vector2(Math.Max(Px(20), w - Px(36) - editW), rowH);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(SelectorIds[slot], size);
|
||||
bool hovered = ImGuiNET.ImGui.IsItemHovered();
|
||||
if (ImGuiNET.ImGui.IsItemActivated())
|
||||
_pressedWhileOpen[slot] = ImGuiNET.ImGui.GetFrameCount() - _pickerShownFrame[slot] <= 1;
|
||||
bool open = ImGuiNET.ImGui.IsPopupOpen(PickerIds[slot]);
|
||||
dl.AddRectFilled(pos, pos + size, hovered ? Lighten(SelectorBg) : SelectorBg, 2);
|
||||
dl.AddRect(pos, pos + size, BtnBord, 2);
|
||||
const float arrowW = 12;
|
||||
dl.PushClipRect(pos, pos + size - new Vector2(arrowW + 4, 0), true);
|
||||
dl.AddText(f9, f9.FontSize, pos + new Vector2(5, (16 - f9.FontSize) * 0.5f), White, text);
|
||||
dl.AddRectFilled(pos, pos + size, hovered ? Lighten(SelectorBg) : SelectorBg, round);
|
||||
dl.AddRect(pos, pos + size, BtnBord, round);
|
||||
float arrowW = Px(12);
|
||||
dl.PushClipRect(pos, pos + size - new Vector2(arrowW + Px(4), 0), true);
|
||||
dl.AddText(f9, f9.FontSize, pos + new Vector2(Px(5), (rowH - f9.FontSize) * 0.5f), White, text);
|
||||
dl.PopClipRect();
|
||||
PhosphorIcons.DrawCentered(dl, f10, open ? PhosphorIcons.CaretUp : PhosphorIcons.CaretDown,
|
||||
new Vector2(pos.X + size.X - arrowW - 3, y), new Vector2(arrowW, 16), Mute);
|
||||
new Vector2(pos.X + size.X - arrowW - Px(3), y), new Vector2(arrowW, rowH), Mute);
|
||||
|
||||
if (clicked && !_pressedWhileOpen[slot] && !open)
|
||||
{
|
||||
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(pos.X, pos.Y + size.Y + 2));
|
||||
ImGuiNET.ImGui.SetNextWindowPos(new Vector2(pos.X, pos.Y + size.Y + Px(2)));
|
||||
ImGuiNET.ImGui.OpenPopup(PickerIds[slot]);
|
||||
}
|
||||
Picker(slot, items.Length == 0 ? NoneItems : items, Math.Clamp(selected, 0, Math.Max(0, items.Length - 1)), kind, items.Length > 0);
|
||||
|
|
@ -339,16 +465,16 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
|
||||
private void Picker(int slot, string[] items, int selected, int kind, bool real)
|
||||
{
|
||||
// Same look as the Avalonia picker: 200 wide, teal border, radius 6.
|
||||
float maxH = Math.Min(items.Length * 26 + 12, Math.Max(60,
|
||||
ImGuiNET.ImGui.GetIO().DisplaySize.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - 20));
|
||||
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(200, maxH));
|
||||
// Same look as the Avalonia picker: 200 wide, teal border, radius 6 (x the size).
|
||||
float maxH = Math.Min(items.Length * Px(26) + Px(12), Math.Max(Px(60),
|
||||
ImGuiNET.ImGui.GetIO().DisplaySize.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - Px(20)));
|
||||
ImGuiNET.ImGui.SetNextWindowSize(new Vector2(Px(200), maxH));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 6f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(6f));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupBorderSize, 1f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 4));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(2, 2));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(4), Px(4)));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(Px(2), Px(2)));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup(PickerIds[slot]);
|
||||
ImGuiNET.ImGui.PopStyleVar(4);
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
|
|
@ -361,7 +487,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.PushID(i);
|
||||
bool isSel = i == selected;
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (ItemButton("##item", p, new Vector2(w, 24), items[i], isSel ? TealSoft : BtnFill, isSel ? Teal : White))
|
||||
if (ItemButton("##item", p, new Vector2(w, Px(24)), items[i], isSel ? TealSoft : BtnFill, isSel ? Teal : White))
|
||||
{
|
||||
if (real) RynthAiCommands.SelectProfile(kind, i);
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
|
|
@ -377,16 +503,16 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
|
||||
uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(bg) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(bg) : bg;
|
||||
dl.AddRectFilled(pos, pos + size, fill, 3);
|
||||
dl.AddRect(pos, pos + size, BtnBord, 3);
|
||||
dl.AddRectFilled(pos, pos + size, fill, Px(3));
|
||||
dl.AddRect(pos, pos + size, BtnBord, Px(3));
|
||||
ImFontPtr f = ImGuiFonts.Get(UiFont.Dash11);
|
||||
dl.PushClipRect(pos, pos + size, true);
|
||||
dl.AddText(f, f.FontSize, pos + new Vector2(8, (size.Y - f.FontSize) * 0.5f), fg, text);
|
||||
dl.AddText(f, f.FontSize, pos + new Vector2(Px(8), (size.Y - f.FontSize) * 0.5f), fg, text);
|
||||
dl.PopClipRect();
|
||||
return clicked;
|
||||
}
|
||||
|
||||
// ── Control row: (ON/OFF) combat, buffing, nav, looting, meta ... force rebuff ──
|
||||
// ── Control row: (ON/OFF) combat, buffing, nav, looting, meta, [sort] ... force rebuff ──
|
||||
|
||||
private const float Square = 24, SquareStep = 27, RowPad = 3;
|
||||
|
||||
|
|
@ -394,66 +520,80 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
{
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float top = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
float bottom = top + Square + 2 * RowPad;
|
||||
dl.AddRectFilled(new Vector2(x0, top), new Vector2(x0 + width, bottom), boxBg, 3);
|
||||
dl.AddRect(new Vector2(x0, top), new Vector2(x0 + width, bottom), BtnBord, 3);
|
||||
float sq = Px(Square), sqStep = Px(SquareStep), round = Px(3);
|
||||
var square = new Vector2(sq, sq);
|
||||
float bottom = top + sq + 2 * Px(RowPad);
|
||||
dl.AddRectFilled(new Vector2(x0, top), new Vector2(x0 + width, bottom), boxBg, round);
|
||||
dl.AddRect(new Vector2(x0, top), new Vector2(x0 + width, bottom), BtnBord, round);
|
||||
|
||||
float x = x0 + 5, y = top + RowPad;
|
||||
float x = x0 + Px(5), y = top + Px(RowPad);
|
||||
// Macro start/stop: a square like the toggles, green with a Stop glyph while running.
|
||||
{
|
||||
bool on = raw.MacroRunning;
|
||||
if (IconButton("##macro", new Vector2(x, y), new Vector2(Square, Square), on ? PhosphorIcons.Stop : PhosphorIcons.Play,
|
||||
UiFont.Dash14, on ? MacroRun : BarBg, on ? White : Mute, on ? Green : BtnBord, 3))
|
||||
if (IconButton("##macro", new Vector2(x, y), square, on ? PhosphorIcons.Stop : PhosphorIcons.Play,
|
||||
UiFont.Dash14, on ? MacroRun : BarBg, on ? White : Mute, on ? Green : BtnBord, round))
|
||||
RynthAiCommands.ToggleMacro();
|
||||
ImGuiNET.ImGui.SetItemTooltip(on ? "Macro running. Click to stop it." : "Macro stopped. Click to start it.");
|
||||
x += SquareStep + 6;
|
||||
x += sqStep + Px(6);
|
||||
}
|
||||
Toggle("##t_combat", PhosphorIcons.Sword, raw.CombatEnabled, 0, new Vector2(x, y), "Combat");
|
||||
x += SquareStep;
|
||||
x += sqStep;
|
||||
Toggle("##t_buff", PhosphorIcons.Sparkle, raw.BuffingEnabled, 1, new Vector2(x, y), "Buffing");
|
||||
x += SquareStep;
|
||||
x += sqStep;
|
||||
Toggle("##t_nav", PhosphorIcons.SneakerMove, raw.NavigationEnabled, 2, new Vector2(x, y), "Navigation");
|
||||
x += SquareStep;
|
||||
x += sqStep;
|
||||
Toggle("##t_loot", PhosphorIcons.Bag, raw.LootingEnabled, 3, new Vector2(x, y), "Looting");
|
||||
x += SquareStep;
|
||||
x += sqStep;
|
||||
Toggle("##t_meta", PhosphorIcons.Code, raw.MetaEnabled, 4, new Vector2(x, y), "Meta (the macro rules)");
|
||||
x += SquareStep;
|
||||
x += sqStep;
|
||||
// RynthSort's auto-sort, when RynthSort is loaded and knows the character.
|
||||
int sort = RynthSortWatch.State;
|
||||
if (sort >= 0)
|
||||
{
|
||||
bool on = sort == 1;
|
||||
if (IconButton("##t_sort", new Vector2(x, y), square, PhosphorIcons.SortAscending, UiFont.Dash14,
|
||||
on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, round))
|
||||
RynthSortCommands.SetAuto(!on);
|
||||
ImGuiNET.ImGui.SetItemTooltip(on ? "Auto-sort (RynthSort) on. Click to turn it off." : "Auto-sort (RynthSort) off. Click to turn it on.");
|
||||
x += sqStep;
|
||||
}
|
||||
|
||||
// Popped out: the pickers fold out from a caret left of FR (expanded mode, while folded away).
|
||||
// Docked they are the Loaded files drawer on the left edge.
|
||||
const float caretW = 16f;
|
||||
float caretW = Px(16f);
|
||||
bool caret = popped && !minimized && !RynthAiDashboardState.FilesOpen;
|
||||
float frX = x0 + width - 5 - Square;
|
||||
float frX = x0 + width - Px(5) - sq;
|
||||
if (caret)
|
||||
{
|
||||
if (IconButton("##files_open", new Vector2(frX - 4 - caretW, y), new Vector2(caretW, Square), PhosphorIcons.CaretDown,
|
||||
UiFont.Dash11, BtnFill, Teal, BtnBord, 2))
|
||||
if (IconButton("##files_open", new Vector2(frX - Px(4) - caretW, y), new Vector2(caretW, sq), PhosphorIcons.CaretDown,
|
||||
UiFont.Dash11, BtnFill, Teal, BtnBord, Px(2)))
|
||||
RynthAiDashboardState.SetFilesOpen(true);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") +
|
||||
"\nLoot: " + (view?.LootText ?? "None") + "\nMeta: " + (view?.MetaText ?? "None") +
|
||||
"\n\nClick to show the Profile, Nav, Loot and Meta pickers.");
|
||||
"\nBuffs: " + (view?.BuffText ?? "Built-in") +
|
||||
"\n\nClick to show the Profile, Nav, Loot, Meta and Buffs pickers.");
|
||||
}
|
||||
|
||||
// What the bot is doing, always in view (every mode, minimized too): between the toggles and FR.
|
||||
{
|
||||
ImFontPtr af = ImGuiFonts.Get(UiFont.Dash10);
|
||||
float ax = x + 2, aRight = (caret ? frX - 4 - caretW : frX) - 6;
|
||||
if (aRight - ax > 20)
|
||||
float ax = x + Px(2), aRight = (caret ? frX - Px(4) - caretW : frX) - Px(6);
|
||||
if (aRight - ax > Px(20))
|
||||
{
|
||||
string activity = view?.BotActivityText ?? "Idle";
|
||||
float ay = y + (Square - af.FontSize) * 0.5f;
|
||||
dl.PushClipRect(new Vector2(ax, y), new Vector2(aRight, y + Square), true);
|
||||
float ay = y + (sq - af.FontSize) * 0.5f;
|
||||
dl.PushClipRect(new Vector2(ax, y), new Vector2(aRight, y + sq), true);
|
||||
dl.AddText(af, af.FontSize, new Vector2(ax, ay), Amber, activity);
|
||||
dl.PopClipRect();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(ax, y));
|
||||
ImGuiNET.ImGui.InvisibleButton("##activity", new Vector2(aRight - ax, Square));
|
||||
ImGuiNET.ImGui.InvisibleButton("##activity", new Vector2(aRight - ax, sq));
|
||||
ImGuiNET.ImGui.SetItemTooltip("Bot activity: " + activity + "\nMeta state: " + (view?.MetaStateText ?? "Default"));
|
||||
}
|
||||
}
|
||||
|
||||
// Force rebuff, set apart at the right (DrakBot's place for it).
|
||||
if (IconButton("##fr", new Vector2(x0 + width - 5 - Square, y), new Vector2(Square, Square), PhosphorIcons.ArrowsClockwise,
|
||||
UiFont.Dash14, FrFill, Amber, BtnBord, 3))
|
||||
if (IconButton("##fr", new Vector2(frX, y), square, PhosphorIcons.ArrowsClockwise,
|
||||
UiFont.Dash14, FrFill, Amber, BtnBord, round))
|
||||
RynthAiCommands.ForceRebuff();
|
||||
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
|
||||
RynthAiCommands.CancelForceRebuff();
|
||||
|
|
@ -465,7 +605,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
|
||||
private void Toggle(string id, string icon, bool on, int subsystem, Vector2 pos, string name)
|
||||
{
|
||||
if (IconButton(id, pos, new Vector2(Square, Square), icon, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, 3))
|
||||
if (IconButton(id, pos, new Vector2(Px(Square), Px(Square)), icon, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, Px(3)))
|
||||
RynthAiCommands.SetSubsystemEnabled(subsystem, !on);
|
||||
ImGuiNET.ImGui.SetItemTooltip(on ? name + " on. Click to turn it off." : name + " off. Click to turn it on.");
|
||||
}
|
||||
|
|
@ -477,30 +617,31 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
private void Launchers(float x0, float width)
|
||||
{
|
||||
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
const int buttons = 8;
|
||||
float bw = MathF.Floor((width - buttons * LauncherGap) / buttons);
|
||||
const int buttons = 10;
|
||||
float gap = Px(LauncherGap);
|
||||
float bw = MathF.Floor((width - buttons * gap) / buttons);
|
||||
// Short labels only when every button has room for its icon and label.
|
||||
bool labels = bw >= 68;
|
||||
bool labels = bw >= Px(68);
|
||||
float x = x0;
|
||||
|
||||
Launcher("##l_meta", PhosphorIcons.ListChecks, "Meta", "Meta: the macro rules", x, y, bw, labels, () => PanelRouter.Toggle("Meta"));
|
||||
x += bw + LauncherGap;
|
||||
x += bw + gap;
|
||||
Launcher("##l_lua", PhosphorIcons.FileCode, "Lua", "Lua scripts", x, y, bw, labels, () => PanelRouter.Toggle("Lua"));
|
||||
x += bw + LauncherGap;
|
||||
x += bw + gap;
|
||||
// Monsters opens the Damage panel (the basic Monsters panel and its
|
||||
// Simple/Advanced chip were retired 2026-10-01).
|
||||
Launcher("##l_mon", PhosphorIcons.Skull, "Monsters", "Monsters: weapons, spells and rules per monster (the Damage panel)",
|
||||
x, y, bw, labels, PanelRouter.ToggleMonsters);
|
||||
x += bw + LauncherGap;
|
||||
x += bw + gap;
|
||||
Launcher("##l_set", PhosphorIcons.Gear, "Settings", "Settings", x, y, bw, labels, () => PanelRouter.Toggle("Settings"));
|
||||
x += bw + LauncherGap;
|
||||
x += bw + gap;
|
||||
Launcher("##l_nav", PhosphorIcons.MapTrifold, "Nav", "Nav: routes", x, y, bw, labels, () => PanelRouter.Toggle("Nav"));
|
||||
x += bw + LauncherGap;
|
||||
x += bw + gap;
|
||||
Launcher("##l_map", PhosphorIcons.MapPin, "Map", "Dungeon Map (shows while you're in a dungeon)", x, y, bw, labels,
|
||||
() => PanelRouter.Toggle(DungeonMapFace.Title));
|
||||
x += bw + LauncherGap;
|
||||
x += bw + gap;
|
||||
Launcher("##l_items", PhosphorIcons.Backpack, "Items", "Items", x, y, bw, labels, () => PanelRouter.Toggle("Items"));
|
||||
x += bw + LauncherGap;
|
||||
x += bw + gap;
|
||||
bool popped = ImGuiPopOuts.InPopOutFrame;
|
||||
Launcher("##l_patrol", PhosphorIcons.Footprints, "Patrol",
|
||||
popped ? "Patrol. Left-click: start dungeon patrol. Right-click: routes & recorded hazards."
|
||||
|
|
@ -516,30 +657,57 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
}
|
||||
else _drawers.Toggle(_patrol);
|
||||
}
|
||||
x += bw + gap;
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + LauncherH));
|
||||
// Char and Hub open the Mini Remote window (MiniRemoteFace, hosting RynthAi's remote): Char
|
||||
// on its Character tab (an ILT tab; elsewhere the remote shows), Hub as it was left.
|
||||
Launcher("##l_char", PhosphorIcons.User, "Char",
|
||||
"Char. Left-click: the Mini Remote on its Character tab (ILT worlds). Right-click: Character windows (Spells, Quests, Pets, Skills, Inventory...), then Server: this server's plugin windows.",
|
||||
x, y, bw, labels, () => ShowMiniRemoteTab("character"));
|
||||
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
|
||||
{
|
||||
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1));
|
||||
ImGuiNET.ImGui.OpenPopup("##charmenu");
|
||||
}
|
||||
x += bw + gap;
|
||||
// Left-click is the Mini Remote window (MiniRemoteFace, which hosts RynthAi's remote, the
|
||||
// same window as the bar button). Right-click is the Mini Remote drawer, as Patrol's is
|
||||
// its drawer; popped out there are no drawers, so it opens the window. Inventory HUDs
|
||||
// setup is in the Mini Remote's Options menu.
|
||||
Launcher("##l_hub", PhosphorIcons.SquaresFour, "Hub",
|
||||
popped ? "Hub. Left-click: the Mini Remote window (/rc miniremote). Right-click: open the Mini Remote window."
|
||||
: "Hub. Left-click: the Mini Remote window (/rc miniremote). Right-click: the Mini Remote drawer (left), with its Options.",
|
||||
x, y, bw, labels, () => PanelRouter.Toggle(MiniRemoteFace.Title));
|
||||
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
|
||||
{
|
||||
if (popped) ImGuiPanelHost.Open(MiniRemoteFace.Title);
|
||||
else _drawers.Toggle(_remote);
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + Px(LauncherH)));
|
||||
}
|
||||
|
||||
private void Launcher(string id, string icon, string label, string tooltip, float x, float y, float w, bool showLabel, Action? onClick)
|
||||
{
|
||||
var pos = new Vector2(x, y);
|
||||
var size = new Vector2(Math.Max(10, w), LauncherH);
|
||||
float lh = Px(LauncherH);
|
||||
var size = new Vector2(Math.Max(Px(10), w), lh);
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||
bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size);
|
||||
ImGuiNET.ImGui.SetItemTooltip(tooltip);
|
||||
uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(BtnFill) : BtnFill;
|
||||
dl.AddRectFilled(pos, pos + size, fill, 3);
|
||||
dl.AddRect(pos, pos + size, BtnBord, 3);
|
||||
dl.AddRectFilled(pos, pos + size, fill, Px(3));
|
||||
dl.AddRect(pos, pos + size, BtnBord, Px(3));
|
||||
|
||||
ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Dash14);
|
||||
if (showLabel)
|
||||
{
|
||||
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Dash9);
|
||||
const float iconBox = 16;
|
||||
PhosphorIcons.DrawCentered(dl, iconFont, icon, pos + new Vector2(4, 0), new Vector2(iconBox, LauncherH), Mute);
|
||||
float iconBox = Px(16);
|
||||
PhosphorIcons.DrawCentered(dl, iconFont, icon, pos + new Vector2(Px(4), 0), new Vector2(iconBox, lh), Mute);
|
||||
dl.PushClipRect(pos, pos + size, true);
|
||||
dl.AddText(f9, f9.FontSize, new Vector2(pos.X + 4 + iconBox + 4, pos.Y + (LauncherH - f9.FontSize) * 0.5f), Mute, label);
|
||||
dl.AddText(f9, f9.FontSize, new Vector2(pos.X + Px(4) + iconBox + Px(4), pos.Y + (lh - f9.FontSize) * 0.5f), Mute, label);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
else
|
||||
|
|
@ -606,24 +774,25 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
string version = view?.Version ?? string.Empty;
|
||||
if (version.Length > 0)
|
||||
{
|
||||
float left = x0 + fpsW + 8, right = x0 + width - upW - 8;
|
||||
float left = x0 + fpsW + Px(8), right = x0 + width - upW - Px(8);
|
||||
if (right > left)
|
||||
{
|
||||
float vw = CalcWidth(f10, version);
|
||||
float vx = x0 + (width - vw) * 0.5f;
|
||||
if (vx < left || vx + vw > right) vx = left;
|
||||
dl.PushClipRect(new Vector2(left, y), new Vector2(right, y + f10.FontSize + 2), true);
|
||||
dl.PushClipRect(new Vector2(left, y), new Vector2(right, y + f10.FontSize + Px(2)), true);
|
||||
dl.AddText(f10, f10.FontSize, new Vector2(vx, y), Mute, version);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
}
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + f10.FontSize + 2));
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + f10.FontSize + Px(2)));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(width, 0));
|
||||
}
|
||||
|
||||
// ── Bars (bottom): player vitals, then the target ──────────────────────
|
||||
|
||||
private const float VitalsH = 14 + 3 + 14 + 3 + 14;
|
||||
// A vital bar's row and the gap under it; three rows.
|
||||
private const float VitalH = 14, VitalGap = 3;
|
||||
|
||||
private void Bars(RynthAiView? view, RynthAiSnapshot raw, float x0, float width, uint boxBg)
|
||||
{
|
||||
|
|
@ -636,21 +805,23 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
// The target's stamina/mana rows are held while that option is on, so they
|
||||
// don't grow the box (and the window) as targets come and go.
|
||||
bool subRows = raw.ShowTargetStaminaMana;
|
||||
float targetH = f11.FontSize + 2 + 3 + 12 + (subRows ? 2 * (13 + 3) - 3 : 0);
|
||||
float targetH = f11.FontSize + Px(2) + Px(3) + Px(12) + (subRows ? 2 * (Px(13) + Px(3)) - Px(3) : 0);
|
||||
float vh = Px(VitalH), vgap = Px(VitalGap);
|
||||
float vitalsH = vh + vgap + vh + vgap + vh;
|
||||
float top = ImGuiNET.ImGui.GetCursorScreenPos().Y;
|
||||
float height = 5 + (vitals ? VitalsH : 0) + (vitals && target ? 6 : 0) + (target ? targetH : 0) + 4;
|
||||
float height = Px(5) + (vitals ? vitalsH : 0) + (vitals && target ? Px(6) : 0) + (target ? targetH : 0) + Px(4);
|
||||
var tl = new Vector2(x0, top);
|
||||
var br = new Vector2(x0 + width, top + height);
|
||||
dl.AddRectFilled(tl, br, boxBg, 3);
|
||||
dl.AddRect(tl, br, BtnBord, 3);
|
||||
dl.AddRectFilled(tl, br, boxBg, Px(3));
|
||||
dl.AddRect(tl, br, BtnBord, Px(3));
|
||||
|
||||
float rx = x0 + 5, rw = width - 10, ry = top + 5;
|
||||
float rx = x0 + Px(5), rw = width - Px(10), ry = top + Px(5);
|
||||
if (vitals)
|
||||
{
|
||||
VitalRow(dl, rx, ry, rw, PhosphorIcons.Heart, view?.Health ?? default, Hp, f10); ry += 14 + 3;
|
||||
VitalRow(dl, rx, ry, rw, PhosphorIcons.Lightning, view?.Stamina ?? default, Green, f10); ry += 14 + 3;
|
||||
VitalRow(dl, rx, ry, rw, PhosphorIcons.Drop, view?.Mana ?? default, Mana, f10); ry += 14;
|
||||
if (target) ry += 6;
|
||||
VitalRow(dl, rx, ry, rw, PhosphorIcons.Heart, view?.Health ?? default, Hp, f10); ry += vh + vgap;
|
||||
VitalRow(dl, rx, ry, rw, PhosphorIcons.Lightning, view?.Stamina ?? default, Green, f10); ry += vh + vgap;
|
||||
VitalRow(dl, rx, ry, rw, PhosphorIcons.Drop, view?.Mana ?? default, Mana, f10); ry += vh;
|
||||
if (target) ry += Px(6);
|
||||
}
|
||||
if (target)
|
||||
{
|
||||
|
|
@ -659,27 +830,28 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
float hpW = CalcWidth(f11, hpText);
|
||||
float iconW = CalcWidth(f11, PhosphorIcons.Crosshair);
|
||||
dl.AddText(f11, f11.FontSize, new Vector2(rx, ry), Mute, PhosphorIcons.Crosshair);
|
||||
dl.PushClipRect(new Vector2(rx, ry), new Vector2(rx + rw - hpW - 4, ry + f11.FontSize + 2), true);
|
||||
dl.AddText(f11, f11.FontSize, new Vector2(rx + iconW + 3, ry), TextDim, view?.TargetHeadline ?? "NO TARGET");
|
||||
dl.PushClipRect(new Vector2(rx, ry), new Vector2(rx + rw - hpW - Px(4), ry + f11.FontSize + Px(2)), true);
|
||||
dl.AddText(f11, f11.FontSize, new Vector2(rx + iconW + Px(3), ry), TextDim, view?.TargetHeadline ?? "NO TARGET");
|
||||
dl.PopClipRect();
|
||||
dl.AddText(f11, f11.FontSize, new Vector2(rx + rw - hpW, ry), White, hpText);
|
||||
ry += f11.FontSize + 2 + 3;
|
||||
ry += f11.FontSize + Px(2) + Px(3);
|
||||
|
||||
// 15-segment gradient bar, 10 high, 2 px between segments.
|
||||
// 15-segment gradient bar, 10 high, 2 px between segments (x the size).
|
||||
int lit = view?.TargetSegmentsLit ?? 0;
|
||||
float segW = (rw - 2 * (RynthAiView.Segments - 1)) / RynthAiView.Segments;
|
||||
float segGap = Px(2);
|
||||
float segW = (rw - segGap * (RynthAiView.Segments - 1)) / RynthAiView.Segments;
|
||||
for (int i = 0; i < RynthAiView.Segments; i++)
|
||||
{
|
||||
float sx = rx + i * (segW + 2);
|
||||
dl.AddRectFilled(new Vector2(sx, ry + 1), new Vector2(sx + segW, ry + 11), i < lit ? SegmentColors[i] : BarBg, 1);
|
||||
float sx = rx + i * (segW + segGap);
|
||||
dl.AddRectFilled(new Vector2(sx, ry + Px(1)), new Vector2(sx + segW, ry + Px(11)), i < lit ? SegmentColors[i] : BarBg, Px(1));
|
||||
}
|
||||
ry += 12;
|
||||
ry += Px(12);
|
||||
|
||||
if (subRows)
|
||||
{
|
||||
bool shown = view != null && view.ShowTargetSubBars;
|
||||
ry += 3;
|
||||
CompactBar(dl, rx, ry, rw, shown ? view!.TargetStamina : default, Green, f10); ry += 13 + 3;
|
||||
ry += Px(3);
|
||||
CompactBar(dl, rx, ry, rw, shown ? view!.TargetStamina : default, Green, f10); ry += Px(13) + Px(3);
|
||||
CompactBar(dl, rx, ry, rw, shown ? view!.TargetMana : default, Mana, f10);
|
||||
}
|
||||
}
|
||||
|
|
@ -690,22 +862,80 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
|
||||
private static void CompactBar(ImDrawListPtr dl, float x, float y, float w, VitalView bar, uint color, ImFontPtr font)
|
||||
{
|
||||
var a = new Vector2(x, y + 1);
|
||||
var b = new Vector2(x + w, y + 12);
|
||||
dl.AddRectFilled(a, b, BarBg, 2);
|
||||
if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, 2);
|
||||
dl.AddText(font, font.FontSize, new Vector2(x + 4, y + 1 + (11 - font.FontSize) * 0.5f), White, bar.Text ?? "");
|
||||
var a = new Vector2(x, y + Px(1));
|
||||
var b = new Vector2(x + w, y + Px(12));
|
||||
dl.AddRectFilled(a, b, BarBg, Px(2));
|
||||
if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, Px(2));
|
||||
dl.AddText(font, font.FontSize, new Vector2(x + Px(4), y + Px(1) + (Px(11) - font.FontSize) * 0.5f), White, bar.Text ?? "");
|
||||
}
|
||||
|
||||
private static void VitalRow(ImDrawListPtr dl, float x, float y, float w, string icon, VitalView bar, uint color, ImFontPtr font)
|
||||
{
|
||||
var a = new Vector2(x, y + 1);
|
||||
var b = new Vector2(x + w, y + 14);
|
||||
dl.AddRectFilled(a, b, BarBg, 6);
|
||||
if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, 6);
|
||||
float ty = y + 1 + (13 - font.FontSize) * 0.5f;
|
||||
dl.AddText(font, font.FontSize, new Vector2(x + 4, ty), Mute, icon);
|
||||
dl.AddText(font, font.FontSize, new Vector2(x + 4 + CalcWidth(font, icon) + 3, ty), White, bar.Text ?? "");
|
||||
var a = new Vector2(x, y + Px(1));
|
||||
var b = new Vector2(x + w, y + Px(14));
|
||||
dl.AddRectFilled(a, b, BarBg, Px(6));
|
||||
if (bar.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * bar.Fraction, b.Y), color, Px(6));
|
||||
float ty = y + Px(1) + (Px(13) - font.FontSize) * 0.5f;
|
||||
dl.AddText(font, font.FontSize, new Vector2(x + Px(4), ty), Mute, icon);
|
||||
dl.AddText(font, font.FontSize, new Vector2(x + Px(4) + CalcWidth(font, icon) + Px(3), ty), White, bar.Text ?? "");
|
||||
}
|
||||
|
||||
// ── Char menu (right-click Char) ───────────────────────────────────
|
||||
// Top: "Character", the windows every server has. Bottom: the server section
|
||||
// (UI.ServerMenus): the installed server plugins' windows for the world you're on.
|
||||
|
||||
/// <summary>
|
||||
/// Opens the Mini Remote window on one of its tabs ("" = the remote). Quests and Pets show on
|
||||
/// every server; RynthAi shows an ILT tab once the server reports that feature on, and until
|
||||
/// then the window shows the remote.
|
||||
/// </summary>
|
||||
private static void ShowMiniRemoteTab(string section)
|
||||
{
|
||||
ImGuiPanelHost.Open(MiniRemoteFace.Title);
|
||||
RynthAiCommands.ApplyRemoteCommand("hub", section.Length > 0 ? "tab " + section : "tab");
|
||||
}
|
||||
|
||||
/// <summary>A Char menu item that toggles a registered ImGui panel (checked while open).</summary>
|
||||
private static void PanelMenuItem(string title, string command)
|
||||
{
|
||||
if (!ImGuiPanelHost.HasFace(title)) return;
|
||||
if (ImGuiNET.ImGui.MenuItem(title, command, ImGuiPanelHost.IsOpen(title)))
|
||||
PanelRouter.Toggle(title);
|
||||
}
|
||||
|
||||
private static void CharMenu()
|
||||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(8)));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup("##charmenu");
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
if (!open) return;
|
||||
try
|
||||
{
|
||||
ImGuiNET.ImGui.TextDisabled("Character");
|
||||
if (ImGuiNET.ImGui.MenuItem("Mini Remote", "/rc miniremote", ImGuiPanelHost.IsOpen(MiniRemoteFace.Title)))
|
||||
ShowMiniRemoteTab("");
|
||||
if (ImGuiNET.ImGui.MenuItem("Spells", "/rc spells"))
|
||||
RynthAiCommands.ApplyRemoteCommand("spells", "toggle");
|
||||
ImGuiNET.ImGui.SetItemTooltip("RynthAi Spells: the spell catalog and buff profiles.");
|
||||
// The Mini Remote's universal tabs (every server); its ILT tabs are in the server half.
|
||||
if (ImGuiNET.ImGui.MenuItem("Quests", "/rc miniremote tab quests")) ShowMiniRemoteTab("quests");
|
||||
ImGuiNET.ImGui.SetItemTooltip("The Mini Remote's Quests tab: /myquests timers and favorites (RynthAi).");
|
||||
if (ImGuiNET.ImGui.MenuItem("Pets", "/rc miniremote tab pets")) ShowMiniRemoteTab("pets");
|
||||
ImGuiNET.ImGui.SetItemTooltip("The Mini Remote's Pets tab: summoning essences, priorities and the healing pet (RynthAi).");
|
||||
PanelMenuItem(SkillsFace.Title, "/rc skills");
|
||||
PanelMenuItem(InventoryFace.Title, "/rc inventory");
|
||||
PanelMenuItem(ItemCountFace.Title, "/rc itemcount");
|
||||
PanelMenuItem(CharactersFace.Title, "/rc characters");
|
||||
|
||||
UI.ServerMenus.DrawImGuiMenu(separatorFirst: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Patrol popup (right-click Patrol, popped out; docked it's the Patrol drawer) ──
|
||||
|
|
@ -714,8 +944,8 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
{
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));
|
||||
ImGuiNET.ImGui.SetNextWindowSizeConstraints(new Vector2(260, 0), new Vector2(260, 376));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(8)));
|
||||
ImGuiNET.ImGui.SetNextWindowSizeConstraints(new Vector2(Px(260), 0), new Vector2(Px(260), Px(376)));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup("##patrol");
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
|
|
@ -801,7 +1031,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
|
||||
private static void Section(string text)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, Px(4)));
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9));
|
||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), text);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
|
|
@ -816,8 +1046,8 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 2f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(6, 1));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, Px(2f));
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(Px(6), Px(1)));
|
||||
bool clicked = ImGuiNET.ImGui.Button(label);
|
||||
ImGuiNET.ImGui.PopStyleVar(3);
|
||||
ImGuiNET.ImGui.PopStyleColor(5);
|
||||
|
|
@ -880,7 +1110,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
|
|||
return a | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
|
||||
private static void Gap(float h) => ImGuiNET.ImGui.Dummy(new Vector2(0, h));
|
||||
private static void Gap(float h) => ImGuiNET.ImGui.Dummy(new Vector2(0, Px(h)));
|
||||
|
||||
private static uint[] BuildSegmentColors()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -53,6 +53,16 @@ internal sealed class SettingsFace : IImGuiPanel
|
|||
public bool Active; // the box had keyboard focus last frame
|
||||
}
|
||||
private readonly Dictionary<SettingRow, NumberEdit> _edits = new();
|
||||
// Text rows being typed in (the saved value shows again once the box loses focus).
|
||||
private readonly Dictionary<SettingRow, string> _textEdits = new();
|
||||
// The Hotkeys tab (engine-side; not part of RynthAi's settings).
|
||||
private readonly HotkeysSettingsUi _hotkeys = new();
|
||||
|
||||
// A tab asked for from outside (/rc hotkeys), taken on the next draw.
|
||||
private static volatile string? _requestedTab;
|
||||
|
||||
/// <summary>Shows tab <paramref name="name"/> (a SettingsSchema tab name) the next time Settings draws. Any thread.</summary>
|
||||
public static void RequestTab(string name) => _requestedTab = name;
|
||||
|
||||
public void OnShown()
|
||||
{
|
||||
|
|
@ -60,7 +70,11 @@ internal sealed class SettingsFace : IImGuiPanel
|
|||
UiSources.Settings.RequestRefresh();
|
||||
}
|
||||
|
||||
public void OnHidden() => UiSources.Settings.Unsubscribe();
|
||||
public void OnHidden()
|
||||
{
|
||||
UiSources.Settings.Unsubscribe();
|
||||
_hotkeys.Leave();
|
||||
}
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
|
|
@ -73,6 +87,13 @@ internal sealed class SettingsFace : IImGuiPanel
|
|||
}
|
||||
_editing = false;
|
||||
|
||||
if (_requestedTab is { } wanted)
|
||||
{
|
||||
_requestedTab = null;
|
||||
int idx = Array.FindIndex(SettingsSchema.Tabs, t => t.Name.Equals(wanted, StringComparison.OrdinalIgnoreCase));
|
||||
if (idx >= 0) _tab = idx;
|
||||
}
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail();
|
||||
|
|
@ -163,6 +184,7 @@ internal sealed class SettingsFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
|
||||
|
||||
SettingRow[] rows = SettingsSchema.Tabs[_tab].Rows;
|
||||
if (SettingsSchema.Tabs[_tab].Name != HotkeysSettingsUi.TabName) _hotkeys.Leave();
|
||||
for (int i = 0; i < rows.Length; i++)
|
||||
{
|
||||
SettingRow row = rows[i];
|
||||
|
|
@ -189,9 +211,133 @@ internal sealed class SettingsFace : IImGuiPanel
|
|||
case SettingKind.Spacer: ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); break;
|
||||
case SettingKind.Note: Note(row.Label, w); break;
|
||||
case SettingKind.CraftingStatus: CraftingStatus(row); break;
|
||||
case SettingKind.Button: ButtonRow(row, w); break;
|
||||
case SettingKind.TraceCategories: TraceCategoriesRow(row, w); break;
|
||||
case SettingKind.Text: TextRow(row, w); break;
|
||||
case SettingKind.Status: StatusRow(row, w); break;
|
||||
case SettingKind.Hotkeys: _editing |= _hotkeys.Draw(w); break;
|
||||
}
|
||||
}
|
||||
|
||||
// [All on] [All off] [ILT on], then a 3-column grid of square toggles, one per
|
||||
// RynthAi trace category. Edits the copy's DiagCategories and saves like any other row.
|
||||
private void TraceCategoriesRow(SettingRow row, float w)
|
||||
{
|
||||
var cats = TraceCategoryLevels.Parse(_data.DiagCategories);
|
||||
if (cats.Count == 0)
|
||||
{
|
||||
Note("Waiting for RynthAi...", w);
|
||||
return;
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
if (ImGuiNET.ImGui.Button("All on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true));
|
||||
ImGuiNET.ImGui.SameLine(0, 6);
|
||||
if (ImGuiNET.ImGui.Button("All off")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", false));
|
||||
ImGuiNET.ImGui.SameLine(0, 6);
|
||||
if (ImGuiNET.ImGui.Button("ILT on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true, "Ilt"));
|
||||
Tooltip(row);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
|
||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||
float colW = Math.Max(80f, w / 3f);
|
||||
int perRow = Math.Max(1, (int)(w / colW));
|
||||
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
for (int i = 0; i < cats.Count; i++)
|
||||
{
|
||||
var (name, level) = cats[i];
|
||||
bool on = level != TraceCategoryLevels.Off;
|
||||
string label = TraceCategoryLevels.Label(name, level);
|
||||
var p = start + new Vector2(i % perRow * colW, i / perRow * 18f);
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(p);
|
||||
ImGuiNET.ImGui.PushID(name);
|
||||
if (ImGuiNET.ImGui.InvisibleButton("##cat", new Vector2(colW - 4, 16)))
|
||||
SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, name, !on));
|
||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
|
||||
ImGuiNET.ImGui.PopID();
|
||||
dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2);
|
||||
dl.PushClipRect(p, p + new Vector2(colW - 4, 16), true);
|
||||
dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
int rowsUsed = (cats.Count + perRow - 1) / perRow;
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(start + new Vector2(0, rowsUsed * 18f));
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
||||
}
|
||||
|
||||
private void SaveCategories(string levels)
|
||||
{
|
||||
_data.DiagCategories = levels;
|
||||
SettingsCommands.Save(_data.Clone());
|
||||
}
|
||||
|
||||
// Label, then a full-width box; the value commits on Enter or focus loss (like the number boxes).
|
||||
private void TextRow(SettingRow row, float w)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
|
||||
ImGuiNET.ImGui.TextUnformatted(row.Label);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
Tooltip(row);
|
||||
|
||||
string saved = row.GetText?.Invoke(_data) ?? string.Empty;
|
||||
string text = _textEdits.TryGetValue(row, out string? typing) ? typing : saved;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 4));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0f);
|
||||
bool enter = ImGuiNET.ImGui.InputTextWithHint("##text", row.Hint ?? string.Empty, ref text, 512u,
|
||||
ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
bool active = ImGuiNET.ImGui.IsItemActive();
|
||||
bool committed = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
|
||||
ImGuiNET.ImGui.PopStyleVar(2);
|
||||
ImGuiNET.ImGui.PopStyleColor(3);
|
||||
Tooltip(row);
|
||||
_editing |= active;
|
||||
|
||||
if (committed)
|
||||
{
|
||||
_textEdits.Remove(row);
|
||||
if (!string.Equals(text, saved, StringComparison.Ordinal))
|
||||
{
|
||||
row.SetText?.Invoke(_data, text);
|
||||
SettingsCommands.Save(_data.Clone());
|
||||
}
|
||||
}
|
||||
else if (active) _textEdits[row] = text;
|
||||
else _textEdits.Remove(row);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
}
|
||||
|
||||
// RynthAi's one-line status (teal), wrapped to the column.
|
||||
private void StatusRow(SettingRow row, float w)
|
||||
{
|
||||
string text = row.GetText?.Invoke(_data) ?? string.Empty;
|
||||
if (text.Length == 0) return;
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Teal);
|
||||
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
|
||||
ImGuiNET.ImGui.TextUnformatted(text);
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
}
|
||||
|
||||
// Label | [caption]; Click posts its own work (never runs plugin code on AC's thread).
|
||||
private static void ButtonRow(SettingRow row, float w)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
|
||||
ImGuiNET.ImGui.AlignTextToFramePadding();
|
||||
ImGuiNET.ImGui.TextUnformatted(row.Label);
|
||||
ImGuiNET.ImGui.PopStyleColor();
|
||||
ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f));
|
||||
if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label))
|
||||
row.Click?.Invoke();
|
||||
Tooltip(row);
|
||||
}
|
||||
|
||||
private void Changed(SettingRow row, double value)
|
||||
{
|
||||
row.Set!(_data, value);
|
||||
|
|
@ -420,6 +566,7 @@ internal sealed class SettingsFace : IImGuiPanel
|
|||
{
|
||||
["Display"] = PhosphorIcons.Monitor,
|
||||
["UI"] = PhosphorIcons.AppWindow,
|
||||
["Hotkeys"] = PhosphorIcons.Keyboard,
|
||||
["Misc"] = PhosphorIcons.DotsThree,
|
||||
["Recharge"] = PhosphorIcons.BatteryCharging,
|
||||
["Melee Combat"] = PhosphorIcons.Sword,
|
||||
|
|
@ -430,6 +577,7 @@ internal sealed class SettingsFace : IImGuiPanel
|
|||
["Crafting"] = PhosphorIcons.Hammer,
|
||||
["Looting"] = PhosphorIcons.Bag,
|
||||
["Vendoring"] = PhosphorIcons.Storefront,
|
||||
["Diagnostics"] = PhosphorIcons.Wrench,
|
||||
};
|
||||
private static readonly System.Collections.Generic.Dictionary<string, string> TabLabels = new();
|
||||
|
||||
|
|
|
|||
693
src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs
Normal file
693
src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs
Normal file
|
|
@ -0,0 +1,693 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/Panels/SkillsFace.Progression.cs
|
||||
// The Skills panel's Progression tab, shown on ILT-like worlds only:
|
||||
// - XP planner: exact XP for the next N raises of every attribute and vital,
|
||||
// from the client's XP tables (raising stays on the Attributes & Vitals tab).
|
||||
// - Attribute raiser: infinite attributes past the retail cap. RynthAi reads the
|
||||
// server's costs ("/xp all") and raises with "/attr", by hand or on a timer from
|
||||
// unassigned XP, in the order and mode set here. Laid out like UB's Leaftide XP
|
||||
// tab: "+1 Level" / "+10 Levels" buttons labelled with their (projected) cost.
|
||||
// - Augmentations: UB's Augs tab - Refresh current (/aug), Current / Target / Inc /
|
||||
// Luminance / Coins with a totals row, Reset targets, Copy Discord / In-Game.
|
||||
// - Augmentations / Enlightenment: RynthAi's ILT Hub planners. RynthAi owns the
|
||||
// math and the saved inputs (UiSources.Progression snapshot); edits and
|
||||
// actions go back as "prog ..." remote commands. /enl and arming
|
||||
// auto-enlighten ask here first; the server still shows its own dialog.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.UI;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed partial class SkillsFace
|
||||
{
|
||||
private const string ProgConfirmId = "##skills_prog_confirm";
|
||||
|
||||
private int _planLevels = 10; // XP planner: raises to price per row
|
||||
private bool _progSubscribed;
|
||||
|
||||
// The confirm the Progression tab asked for; the command is sent only on its Yes button.
|
||||
private string _progConfirmTitle = "", _progConfirmText = "", _progConfirmYes = "", _progConfirmCommand = "";
|
||||
private bool _progConfirmOpenRequested;
|
||||
|
||||
// Set by ShowProgression (any panel, AC thread); the tab is selected once RynthAi's snapshot
|
||||
// says it exists (the first poll lands a step after the panel opens).
|
||||
private static bool _progressionRequested;
|
||||
|
||||
/// <summary>RynthAi reports an ILT-like world (its ILT Hub exists and the server has ILT features).</summary>
|
||||
private static bool ProgressionTabVisible => UiSources.Progression.Current?.Value.Available == true;
|
||||
|
||||
/// <summary>Opens the Skills panel (if closed) on the Progression tab. AC thread.</summary>
|
||||
public static void ShowProgression()
|
||||
{
|
||||
_progressionRequested = true;
|
||||
if (!ImGuiPanelHost.IsOpen(Title)) PanelRouter.Toggle(Title);
|
||||
}
|
||||
|
||||
/// <summary>Draw: applies a pending ShowProgression once the tab exists.</summary>
|
||||
private void ApplyProgressionRequest()
|
||||
{
|
||||
if (!_progressionRequested || !ProgressionTabVisible) return;
|
||||
_progressionRequested = false;
|
||||
_tab = 2;
|
||||
}
|
||||
|
||||
private void ProgressionShown()
|
||||
{
|
||||
if (_progSubscribed) return;
|
||||
_progSubscribed = true;
|
||||
UiSources.Progression.Subscribe();
|
||||
UiSources.Progression.RequestRefresh();
|
||||
}
|
||||
|
||||
private void ProgressionHidden()
|
||||
{
|
||||
_progressionRequested = false;
|
||||
if (!_progSubscribed) return;
|
||||
_progSubscribed = false;
|
||||
UiSources.Progression.Unsubscribe();
|
||||
}
|
||||
|
||||
/// <summary>Sends "prog <value>" to RynthAi; the snapshot re-polls after its next tick applies it.</summary>
|
||||
private static void SendProg(string value)
|
||||
{
|
||||
RynthAiCommands.ApplyRemoteCommand("prog", value);
|
||||
UiSources.Progression.RequestRefreshAfterPluginTick();
|
||||
}
|
||||
|
||||
private void AskProgConfirm(string title, string text, string yes, string command)
|
||||
{
|
||||
_progConfirmTitle = title;
|
||||
_progConfirmText = text;
|
||||
_progConfirmYes = yes;
|
||||
_progConfirmCommand = command;
|
||||
_progConfirmOpenRequested = true;
|
||||
}
|
||||
|
||||
// ── Body ────────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawProgression(float w)
|
||||
{
|
||||
ProgressionInfo? info = UiSources.Progression.Current?.Value;
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4));
|
||||
try
|
||||
{
|
||||
DrawXpPlanner(w);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
|
||||
if (info == null || !info.Available)
|
||||
{
|
||||
Message("Augmentations and Enlightenment need RynthAi's ILT features on an ILT world.", w);
|
||||
return;
|
||||
}
|
||||
DrawAttrRaiser(info.Attr, w);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
|
||||
DrawAugPlanner(info.Aug, w);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
|
||||
DrawEnlPlanner(info.Enl, w);
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 8));
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.PopStyleVar();
|
||||
}
|
||||
}
|
||||
|
||||
private void DrawXpPlanner(float w)
|
||||
{
|
||||
Section("XP planner", w);
|
||||
if (_snap == null || _dat == null || _attributes.Count == 0)
|
||||
{
|
||||
Message("Waiting for your character's data...", w);
|
||||
return;
|
||||
}
|
||||
ImGuiNET.ImGui.Indent(8);
|
||||
long have = _snap.UnassignedXp;
|
||||
Label($"Unassigned XP: {have:N0}", have > 0 ? Teal : Mute);
|
||||
ImGuiNET.ImGui.SetNextItemWidth(160);
|
||||
ImGuiNET.ImGui.SliderInt("Raises to plan##prog_lv", ref _planLevels, 1, 100);
|
||||
|
||||
if (ImGuiNET.ImGui.BeginTable("##prog_xp", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
|
||||
new Vector2(w - 16, 0)))
|
||||
{
|
||||
ImGuiNET.ImGui.TableSetupColumn("Stat");
|
||||
ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 50);
|
||||
ImGuiNET.ImGui.TableSetupColumn("Next raise", ImGuiTableColumnFlags.WidthFixed, 100);
|
||||
ImGuiNET.ImGui.TableSetupColumn($"Next {_planLevels}", ImGuiTableColumnFlags.WidthFixed, 120);
|
||||
ImGuiNET.ImGui.TableHeadersRow();
|
||||
foreach (Row r in _attributes) PlannerRow(r, have);
|
||||
foreach (Row r in _vitals) PlannerRow(r, have);
|
||||
ImGuiNET.ImGui.EndTable();
|
||||
}
|
||||
Label("Exact costs from the client's XP tables. Raise on the Attributes & Vitals tab"
|
||||
+ (ProgressionTabVisible ? ", or past the cap with the Attribute raiser below." : "."), Dim);
|
||||
ImGuiNET.ImGui.Unindent(8);
|
||||
}
|
||||
|
||||
private void PlannerRow(Row r, long have)
|
||||
{
|
||||
ImGuiNET.ImGui.TableNextRow();
|
||||
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Name);
|
||||
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Base.ToString(CultureInfo.InvariantCulture));
|
||||
uint[]? table = r.Table;
|
||||
int left = table == null ? 0 : Math.Max(0, table.Length - 1 - (int)Math.Min(r.Ranks, (uint)int.MaxValue));
|
||||
ImGuiNET.ImGui.TableNextColumn();
|
||||
if (table == null || left == 0) { Label(table == null ? "-" : "max", Dim); ImGuiNET.ImGui.TableNextColumn(); Label("-", Dim); return; }
|
||||
long one = SkillDat.CostOf(table, r.Ranks, r.Spent, 1);
|
||||
Label(one >= 0 ? one.ToString("N0", CultureInfo.InvariantCulture) : "-", one >= 0 && one <= have ? Teal : Dim);
|
||||
ImGuiNET.ImGui.TableNextColumn();
|
||||
int n = Math.Min(_planLevels, left);
|
||||
long many = SkillDat.CostOf(table, r.Ranks, r.Spent, n);
|
||||
string text = many >= 0 ? many.ToString("N0", CultureInfo.InvariantCulture) : "-";
|
||||
if (n < _planLevels) text += $" ({n} to max)";
|
||||
Label(text, many >= 0 && many <= have ? Teal : Dim);
|
||||
}
|
||||
|
||||
private static readonly string[] AttrModes =
|
||||
{
|
||||
"Priority - top of the order first",
|
||||
"Round robin - one level each, in order",
|
||||
"Cheapest next level first",
|
||||
};
|
||||
|
||||
private string? _attrKeepEdit; // reserve box being typed in (null = show RynthAi's value)
|
||||
private int? _attrEveryEdit; // interval box being typed in
|
||||
|
||||
private void DrawAttrRaiser(AttrRaiser? a, float w)
|
||||
{
|
||||
Section("Attribute raiser (infinite attributes)", w);
|
||||
ImGuiNET.ImGui.Indent(8);
|
||||
float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24;
|
||||
ImGuiNET.ImGui.PushTextWrapPos(wrap);
|
||||
try
|
||||
{
|
||||
if (a == null) { Label("Update RynthAi to use the attribute raiser.", Mute); return; }
|
||||
if (a.Off) { Label(a.Reason, Mute); return; }
|
||||
|
||||
Label(a.XpHeader.Length > 0 ? a.XpHeader : a.Unassigned, Teal);
|
||||
if (a.XpHeader.Length > 0 && a.Unassigned.Contains("spendable", StringComparison.Ordinal)) Label(a.Unassigned, Dim);
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (a.Running)
|
||||
{
|
||||
if (Button("##attr_stop", "Stop", p, new Vector2(90, 24), Text, StopBg)) SendProg("attrstop");
|
||||
}
|
||||
else if (Button("##attr_run", "Raise now", p, new Vector2(110, 24), Text, StartBg, border: Teal))
|
||||
SendProg("attrrun");
|
||||
if (Button("##attr_costs", "Refresh XP", new Vector2(p.X + 116, p.Y), new Vector2(100, 24), Text, BtnFill, enabled: !a.Running))
|
||||
SendProg("attrcosts");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Re-reads every next-level cost with /xp all.");
|
||||
if (a.Updated.Length > 0)
|
||||
{
|
||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 224, p.Y + 4));
|
||||
Label("Last updated: " + a.Updated, Dim);
|
||||
}
|
||||
NextLine(p, 28);
|
||||
if (a.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(a.Status);
|
||||
if (a.LastRun.Length > 0) Label("Last run: " + a.LastRun, Dim);
|
||||
|
||||
ImGuiNET.ImGui.Separator();
|
||||
bool auto = a.Auto;
|
||||
if (ImGuiNET.ImGui.Checkbox("Auto-raise from unassigned XP##attr_auto", ref auto))
|
||||
SendProg("attrauto " + (auto ? "on" : "off"));
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
// Commit on Enter, the +/- buttons or focus loss (not on every keystroke: each send
|
||||
// restarts the auto-raise timer).
|
||||
int every = _attrEveryEdit ?? a.Every;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(90);
|
||||
bool everyCommit = ImGuiNET.ImGui.InputInt("every (min)##attr_every", ref every, 1, 10, ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
bool everyActive = ImGuiNET.ImGui.IsItemActive();
|
||||
if (everyCommit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
|
||||
{
|
||||
_attrEveryEdit = null;
|
||||
if (every != a.Every) SendProg("attrevery " + Math.Clamp(every, 1, 1440).ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
else _attrEveryEdit = everyActive ? every : null;
|
||||
if (a.Auto && a.Next.Length > 0) Label($"Next auto-raise: {a.Next}", Dim);
|
||||
|
||||
int mode = Math.Clamp(a.Mode, 0, AttrModes.Length - 1);
|
||||
ImGuiNET.ImGui.SetNextItemWidth(260);
|
||||
if (ImGuiNET.ImGui.Combo("Raise order##attr_mode", ref mode, AttrModes, AttrModes.Length))
|
||||
SendProg("attrmode " + mode.ToString(CultureInfo.InvariantCulture));
|
||||
|
||||
// The box holds the exact reserve (KeepFull); it is sent only when the text changed, so an
|
||||
// Enter on an untouched box can't round the reserve.
|
||||
string shownKeep = a.KeepFull.Length > 0 ? a.KeepFull : a.Keep;
|
||||
string keep = _attrKeepEdit ?? shownKeep;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(140);
|
||||
bool enter = ImGuiNET.ImGui.InputTextWithHint("Keep in reserve (XP)##attr_keep", "0, 500m, 2b", ref keep, 32u,
|
||||
ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
bool keepActive = ImGuiNET.ImGui.IsItemActive();
|
||||
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
|
||||
{
|
||||
_attrKeepEdit = null;
|
||||
if (!string.Equals(keep.Trim(), shownKeep, StringComparison.Ordinal))
|
||||
SendProg("attrkeep " + keep.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal));
|
||||
}
|
||||
else _attrKeepEdit = keepActive ? keep : null;
|
||||
ImGuiNET.ImGui.SetItemTooltip("Unassigned XP the raiser never spends. Accepts k / m / b / t suffixes.");
|
||||
|
||||
DrawAttrTable(a, w);
|
||||
Label("Auto: the stats Raise now / auto-raise may spend on; arrows set the order. "
|
||||
+ "+1 / +10 raise by hand (red = not enough unassigned XP). "
|
||||
+ "+10 is an estimate (7.7% dearer per level); the server charges the real cost. " + a.CostsAge + ".", Dim);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
ImGuiNET.ImGui.Unindent(8);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UB Leaftide XP tab layout: Auto tick, stat, base, then "+1 Level" / "+10 Levels" buttons
|
||||
/// labelled with what they cost, then the priority arrows.
|
||||
/// </summary>
|
||||
private void DrawAttrTable(AttrRaiser a, float w)
|
||||
{
|
||||
if (!ImGuiNET.ImGui.BeginTable("##prog_attr", 6, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
|
||||
new Vector2(w - 16, 0)))
|
||||
return;
|
||||
ImGuiNET.ImGui.TableSetupColumn("Auto", ImGuiTableColumnFlags.WidthFixed, 34);
|
||||
ImGuiNET.ImGui.TableSetupColumn("Stat");
|
||||
ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 56);
|
||||
ImGuiNET.ImGui.TableSetupColumn("+1 Level", ImGuiTableColumnFlags.WidthFixed, 84);
|
||||
ImGuiNET.ImGui.TableSetupColumn("+10 Levels", ImGuiTableColumnFlags.WidthFixed, 84);
|
||||
ImGuiNET.ImGui.TableSetupColumn("Order", ImGuiTableColumnFlags.WidthFixed, 48);
|
||||
ImGuiNET.ImGui.TableHeadersRow();
|
||||
for (int i = 0; i < a.Rows.Length; i++)
|
||||
{
|
||||
AttrRow r = a.Rows[i];
|
||||
ImGuiNET.ImGui.PushID("attr_" + r.Key);
|
||||
ImGuiNET.ImGui.TableNextRow();
|
||||
|
||||
ImGuiNET.ImGui.TableNextColumn();
|
||||
bool on = r.On;
|
||||
if (ImGuiNET.ImGui.Checkbox("##on", ref on)) SendProg($"attron {r.Key} {(on ? "on" : "off")}");
|
||||
|
||||
ImGuiNET.ImGui.TableNextColumn();
|
||||
Label($"{i + 1}. {r.Label}", r.On ? Text : Mute);
|
||||
|
||||
ImGuiNET.ImGui.TableNextColumn();
|
||||
int clientBase = ClientBase(r);
|
||||
Label(clientBase > 0 ? clientBase.ToString("N0", CultureInfo.InvariantCulture)
|
||||
: r.Base >= 0 ? r.Base.ToString("N0", CultureInfo.InvariantCulture) : "-", Text);
|
||||
|
||||
// Older RynthAi sends no cost10 / afford1: plain buttons, the server decides.
|
||||
bool rich = r.Cost10.Length > 0;
|
||||
ImGuiNET.ImGui.TableNextColumn();
|
||||
RaiseButton(a, r, 1, rich ? r.Cost : "+1", rich ? r.Afford1 : true, r.CostFull, rich);
|
||||
ImGuiNET.ImGui.TableNextColumn();
|
||||
RaiseButton(a, r, 10, rich ? r.Cost10 : "+10", rich ? r.Afford10 : true, r.Cost10Full, rich);
|
||||
|
||||
ImGuiNET.ImGui.TableNextColumn();
|
||||
ImGuiNET.ImGui.BeginDisabled(i == 0);
|
||||
if (ImGuiNET.ImGui.ArrowButton("##up", ImGuiDir.Up)) SendProg($"attrmove {r.Key} up");
|
||||
ImGuiNET.ImGui.EndDisabled();
|
||||
ImGuiNET.ImGui.SameLine(0, 2);
|
||||
ImGuiNET.ImGui.BeginDisabled(i == a.Rows.Length - 1);
|
||||
if (ImGuiNET.ImGui.ArrowButton("##down", ImGuiDir.Down)) SendProg($"attrmove {r.Key} down");
|
||||
ImGuiNET.ImGui.EndDisabled();
|
||||
ImGuiNET.ImGui.PopID();
|
||||
}
|
||||
ImGuiNET.ImGui.EndTable();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One by-hand raise button filling its cell. Unknown cost ("?") stays clickable (the server
|
||||
/// checks); a known cost over the unassigned XP is red and disabled.
|
||||
/// </summary>
|
||||
private static void RaiseButton(AttrRaiser a, AttrRow r, int levels, string label, bool afford, string exact, bool rich)
|
||||
{
|
||||
bool known = rich && r.Known;
|
||||
bool enabled = !a.Running && (!known || afford);
|
||||
uint fg = !known ? Text : afford ? Teal : Red;
|
||||
Vector2 pos = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float width = Math.Max(40f, ImGuiNET.ImGui.GetContentRegionAvail().X);
|
||||
if (Button("##raise" + levels, label, pos, new Vector2(width, 20), fg, BtnFill, enabled, border: known && afford ? Teal : 0))
|
||||
SendProg($"attrraise {r.Key} {levels}");
|
||||
string what = $"{r.Label} +{levels} level{(levels > 1 ? "s" : "")}";
|
||||
string tip = !known ? $"{what}: cost not read yet (Refresh XP)."
|
||||
: levels > 1 ? $"{what}: about {exact} XP (estimate)."
|
||||
: $"{what}: {exact} XP.";
|
||||
if (known && !afford) tip += " Not enough unassigned XP.";
|
||||
if (a.Running) tip += " Wait for the raise run to finish.";
|
||||
ImGuiNET.ImGui.SetItemTooltip(tip);
|
||||
}
|
||||
|
||||
/// <summary>The client's own base value for a raiser row (0 when the snapshot has none).</summary>
|
||||
private int ClientBase(AttrRow r)
|
||||
{
|
||||
List<Row> rows = r.Vital ? _vitals : _attributes;
|
||||
foreach (Row row in rows)
|
||||
if (row.Name.Equals(r.Label, StringComparison.OrdinalIgnoreCase)) return row.Base;
|
||||
return 0;
|
||||
}
|
||||
|
||||
private void DrawAugPlanner(AugPlanner a, float w)
|
||||
{
|
||||
Section("Augmentations", w);
|
||||
ImGuiNET.ImGui.Indent(8);
|
||||
try
|
||||
{
|
||||
if (a.Off) { Label("/aug is not available on this server.", Mute); return; }
|
||||
|
||||
// UB Augs tab buttons: Refresh Current, Reset Target, Copy Discord, Copy In-Game.
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float x = p.X;
|
||||
if (Button("##aug_refresh", "Refresh current", new Vector2(x, p.Y), new Vector2(120, 22), Text, StartBg, border: Teal))
|
||||
SendProg("augload");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Reads your augmentation levels with /aug (also done once when this tab first opens).");
|
||||
x += 124;
|
||||
if (Button("##aug_reset", "Reset targets", new Vector2(x, p.Y), new Vector2(104, 22), Text, BtnFill))
|
||||
SendProg("augreset");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Sets every target back to the current level.");
|
||||
x += 108;
|
||||
if (Button("##aug_discord", "Copy Discord", new Vector2(x, p.Y), new Vector2(100, 22), Text, BtnFill, enabled: a.CopyDiscord.Length > 0))
|
||||
ImGuiNET.ImGui.SetClipboardText(a.CopyDiscord);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Copies the plan as a Discord code-block table.");
|
||||
x += 104;
|
||||
if (Button("##aug_ingame", "Copy in-game", new Vector2(x, p.Y), new Vector2(100, 22), Text, BtnFill, enabled: a.CopyIngame.Length > 0))
|
||||
ImGuiNET.ImGui.SetClipboardText(a.CopyIngame);
|
||||
ImGuiNET.ImGui.SetItemTooltip("Copies your current levels as one chat line.");
|
||||
NextLine(p, 26);
|
||||
Label("Status: " + a.Status, Dim);
|
||||
|
||||
if (ImGuiNET.ImGui.BeginTable("##prog_augs", 6, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
|
||||
new Vector2(w - 16, 0)))
|
||||
{
|
||||
ImGuiNET.ImGui.TableSetupColumn("Aug");
|
||||
ImGuiNET.ImGui.TableSetupColumn("Current", ImGuiTableColumnFlags.WidthFixed, 56);
|
||||
ImGuiNET.ImGui.TableSetupColumn("Target", ImGuiTableColumnFlags.WidthFixed, 124);
|
||||
ImGuiNET.ImGui.TableSetupColumn("Inc", ImGuiTableColumnFlags.WidthFixed, 44);
|
||||
ImGuiNET.ImGui.TableSetupColumn("Luminance", ImGuiTableColumnFlags.WidthFixed, 76);
|
||||
ImGuiNET.ImGui.TableSetupColumn("Coins", ImGuiTableColumnFlags.WidthFixed, 56);
|
||||
ImGuiNET.ImGui.TableHeadersRow();
|
||||
foreach (AugRow row in a.Rows)
|
||||
{
|
||||
ImGuiNET.ImGui.TableNextRow();
|
||||
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Label);
|
||||
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Current.ToString("N0", CultureInfo.InvariantCulture));
|
||||
ImGuiNET.ImGui.TableNextColumn();
|
||||
DrawAugTarget(row);
|
||||
int inc = row.Increase > 0 ? row.Increase : Math.Max(0, row.Target - row.Current);
|
||||
ImGuiNET.ImGui.TableNextColumn(); Label(inc > 0 ? inc.ToString("N0", CultureInfo.InvariantCulture) : "-", inc > 0 ? Teal : Dim);
|
||||
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Lum);
|
||||
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Coins > 0 ? row.Coins.ToString("N0", CultureInfo.InvariantCulture) : "-");
|
||||
}
|
||||
if (a.TotalLum.Length > 0)
|
||||
{
|
||||
ImGuiNET.ImGui.TableNextRow();
|
||||
ImGuiNET.ImGui.TableNextColumn(); Label("TOTALS", Amber);
|
||||
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalCurrent.ToString("N0", CultureInfo.InvariantCulture), Amber);
|
||||
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalTarget.ToString("N0", CultureInfo.InvariantCulture), Amber);
|
||||
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalIncrease.ToString("N0", CultureInfo.InvariantCulture), Amber);
|
||||
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalLum, Amber);
|
||||
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalCoins.ToString("N0", CultureInfo.InvariantCulture), Amber);
|
||||
}
|
||||
ImGuiNET.ImGui.EndTable();
|
||||
}
|
||||
|
||||
// Lum per coin commits on Enter / focus loss, not per keystroke.
|
||||
string shownLpc = a.LumPerCoin.ToString(CultureInfo.InvariantCulture);
|
||||
string lpc = _augLpcEdit ?? shownLpc;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(140);
|
||||
bool lpcEnter = ImGuiNET.ImGui.InputTextWithHint("Lum per e-coin##prog_lpc", "0 = don't price coins", ref lpc, 24u,
|
||||
ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
bool lpcActive = ImGuiNET.ImGui.IsItemActive();
|
||||
if (lpcEnter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
|
||||
{
|
||||
_augLpcEdit = null;
|
||||
string clean = lpc.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal);
|
||||
if (!string.Equals(clean, shownLpc, StringComparison.Ordinal)) SendProg("lumpercoin " + clean);
|
||||
}
|
||||
else _augLpcEdit = lpcActive ? lpc : null;
|
||||
ImGuiNET.ImGui.SetItemTooltip("Luminance one Enlightened Coin costs you. Accepts k / m / b / t suffixes.");
|
||||
|
||||
if (a.CoinsLine.Length > 0)
|
||||
{
|
||||
Label(a.CoinsLine, Text);
|
||||
Label(a.LumToBuy, Text);
|
||||
}
|
||||
else
|
||||
{
|
||||
Label(a.Total, Amber);
|
||||
if (a.Short.Length > 0) Label(a.Short, Text);
|
||||
}
|
||||
Label(a.Banked, Dim);
|
||||
if (a.Config != null) DrawAugCostSettings(a.Config, w);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.Unindent(8);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly string[] AugTierNames = { "Below S1", "From S1", "From S2", "From S3", "From S4" };
|
||||
|
||||
// Cost-settings boxes being typed in, by box id (committed on Enter / focus loss).
|
||||
private readonly Dictionary<string, int> _augCfgIntEdit = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, double> _augCfgDblEdit = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// Collapsible editor for this world's aug cost rules (RynthAi saves them per world). The
|
||||
/// defaults are UB's InfiniteLeaftide model; Reset puts a changed world back on them.
|
||||
/// </summary>
|
||||
private void DrawAugCostSettings(AugCostConfig cfg, float w)
|
||||
{
|
||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
||||
string head = $"Cost settings for {cfg.World}" + (cfg.Custom ? " (custom)" : " (InfiniteLeaftide defaults)");
|
||||
if (!ImGuiNET.ImGui.CollapsingHeader(head + "##aug_cfg")) return;
|
||||
|
||||
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w - 24);
|
||||
Label("Level i costs (Base + (i - 1) x Base x Growth% / 100) x the multiplier of its tier. "
|
||||
+ "A tier starts at its S level (UB's InfiniteLeaftide model). Changes apply to this world only.", Dim);
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
|
||||
// Tier multipliers, one box each.
|
||||
Label("Tier multipliers", Text);
|
||||
for (int t = 0; t < AugTierNames.Length && t < cfg.Multipliers.Length; t++)
|
||||
{
|
||||
if (t > 0) ImGuiNET.ImGui.SameLine();
|
||||
ImGuiNET.ImGui.BeginGroup();
|
||||
Label(AugTierNames[t], Mute);
|
||||
ImGuiNET.ImGui.SetNextItemWidth(62);
|
||||
CfgDouble($"mult{t}", cfg.Multipliers[t], v => $"augmult {t} {v.ToString("R", CultureInfo.InvariantCulture)}");
|
||||
ImGuiNET.ImGui.EndGroup();
|
||||
}
|
||||
|
||||
// Per-aug rules.
|
||||
if (ImGuiNET.ImGui.BeginTable("##aug_cfg_rows", 9, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
|
||||
new Vector2(w - 16, 0)))
|
||||
{
|
||||
ImGuiNET.ImGui.TableSetupColumn("Aug");
|
||||
ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 74);
|
||||
ImGuiNET.ImGui.TableSetupColumn("Growth%", ImGuiTableColumnFlags.WidthFixed, 54);
|
||||
ImGuiNET.ImGui.TableSetupColumn("S1", ImGuiTableColumnFlags.WidthFixed, 46);
|
||||
ImGuiNET.ImGui.TableSetupColumn("S2", ImGuiTableColumnFlags.WidthFixed, 46);
|
||||
ImGuiNET.ImGui.TableSetupColumn("S3", ImGuiTableColumnFlags.WidthFixed, 46);
|
||||
ImGuiNET.ImGui.TableSetupColumn("S4", ImGuiTableColumnFlags.WidthFixed, 46);
|
||||
ImGuiNET.ImGui.TableSetupColumn("Cap", ImGuiTableColumnFlags.WidthFixed, 50);
|
||||
ImGuiNET.ImGui.TableSetupColumn("Coins", ImGuiTableColumnFlags.WidthFixed, 42);
|
||||
ImGuiNET.ImGui.TableHeadersRow();
|
||||
foreach (AugCostRule r in cfg.Rows)
|
||||
{
|
||||
ImGuiNET.ImGui.TableNextRow();
|
||||
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Label);
|
||||
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.base", (int)Math.Min(r.Base, int.MaxValue), $"augcfg {r.Key} base");
|
||||
ImGuiNET.ImGui.TableNextColumn(); CfgDouble($"{r.Key}.pct", r.Percent, v => $"augcfg {r.Key} pct {v.ToString("R", CultureInfo.InvariantCulture)}");
|
||||
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s1", r.S1, $"augcfg {r.Key} s1");
|
||||
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s2", r.S2, $"augcfg {r.Key} s2");
|
||||
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s3", r.S3, $"augcfg {r.Key} s3");
|
||||
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s4", r.S4, $"augcfg {r.Key} s4");
|
||||
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.cap", r.Cap, $"augcfg {r.Key} cap");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Highest target level; 0 = no limit.");
|
||||
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.coins", r.Coins, $"augcfg {r.Key} coins");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Enlightened Coins per level.");
|
||||
}
|
||||
ImGuiNET.ImGui.EndTable();
|
||||
}
|
||||
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (Button("##aug_cfg_reset", "Reset to InfiniteLeaftide defaults", p, new Vector2(230, 22), Text, BtnFill, enabled: cfg.Custom))
|
||||
SendProg("augcfgreset");
|
||||
ImGuiNET.ImGui.SetItemTooltip("Drops this world's changes; it goes back to UB's InfiniteLeaftide rules.");
|
||||
NextLine(p, 26);
|
||||
}
|
||||
|
||||
/// <summary>Integer box that sends "<paramref name="verb"/> value" on Enter or focus loss.</summary>
|
||||
private void CfgInt(string id, int value, string verb)
|
||||
{
|
||||
int v = _augCfgIntEdit.TryGetValue(id, out int typing) ? typing : value;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(-1);
|
||||
bool enter = ImGuiNET.ImGui.InputInt("##cfg_" + id, ref v, 0, 0, ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
bool active = ImGuiNET.ImGui.IsItemActive();
|
||||
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
|
||||
{
|
||||
_augCfgIntEdit.Remove(id);
|
||||
if (v != value) SendProg($"{verb} {Math.Max(0, v).ToString(CultureInfo.InvariantCulture)}");
|
||||
}
|
||||
else if (active) _augCfgIntEdit[id] = v;
|
||||
else _augCfgIntEdit.Remove(id);
|
||||
}
|
||||
|
||||
/// <summary>Decimal box (the caller sets its width) that sends <paramref name="command"/>(value) on Enter or focus loss.</summary>
|
||||
private void CfgDouble(string id, double value, Func<double, string> command)
|
||||
{
|
||||
double v = _augCfgDblEdit.TryGetValue(id, out double typing) ? typing : value;
|
||||
if (!id.StartsWith("mult", StringComparison.Ordinal)) ImGuiNET.ImGui.SetNextItemWidth(-1);
|
||||
bool enter = ImGuiNET.ImGui.InputDouble("##cfg_" + id, ref v, 0, 0, "%.6g", ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
bool active = ImGuiNET.ImGui.IsItemActive();
|
||||
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
|
||||
{
|
||||
_augCfgDblEdit.Remove(id);
|
||||
if (Math.Abs(v - value) > 1e-9 && double.IsFinite(v)) SendProg(command(Math.Max(0, v)));
|
||||
}
|
||||
else if (active) _augCfgDblEdit[id] = v;
|
||||
else _augCfgDblEdit.Remove(id);
|
||||
}
|
||||
|
||||
private string? _augLpcEdit; // Lum per coin box being typed in
|
||||
private readonly Dictionary<string, int> _augTargetEdit = new(StringComparer.Ordinal); // target boxes being typed in
|
||||
|
||||
/// <summary>
|
||||
/// Target cell: -/+ step one level (Ctrl: 100), typing commits on Enter or focus loss so a
|
||||
/// half-typed number never reaches RynthAi. RynthAi clamps to current..cap.
|
||||
/// </summary>
|
||||
private void DrawAugTarget(AugRow row)
|
||||
{
|
||||
int tgt = _augTargetEdit.TryGetValue(row.Key, out int typing) ? typing : row.Target;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(-1);
|
||||
bool commit = ImGuiNET.ImGui.InputInt("##prog_tgt_" + row.Key, ref tgt, 1, 100, ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
bool active = ImGuiNET.ImGui.IsItemActive();
|
||||
if (commit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
|
||||
{
|
||||
_augTargetEdit.Remove(row.Key);
|
||||
int clamped = Math.Clamp(tgt, row.Current, Math.Max(row.Cap, row.Current));
|
||||
if (clamped != row.Target) SendProg($"augtarget {row.Key} {clamped.ToString(CultureInfo.InvariantCulture)}");
|
||||
}
|
||||
else if (active) _augTargetEdit[row.Key] = tgt;
|
||||
else _augTargetEdit.Remove(row.Key);
|
||||
ImGuiNET.ImGui.SetItemTooltip($"Target {row.Label} level (up to {row.Cap.ToString("N0", CultureInfo.InvariantCulture)}).");
|
||||
}
|
||||
|
||||
private void DrawEnlPlanner(EnlPlanner e, float w)
|
||||
{
|
||||
Section("Enlightenment", w);
|
||||
ImGuiNET.ImGui.Indent(8);
|
||||
float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24; // window-local x
|
||||
ImGuiNET.ImGui.PushTextWrapPos(wrap);
|
||||
try
|
||||
{
|
||||
if (e.Off) { Label("/enl is not available on this server.", Mute); return; }
|
||||
Label(e.Header, Text);
|
||||
Label(e.Next, Teal);
|
||||
|
||||
int target = e.Target;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(100);
|
||||
if (ImGuiNET.ImGui.InputInt("Plan to level##prog_enlt", ref target))
|
||||
SendProg("enltarget " + Math.Max(e.Level + 1, target).ToString(CultureInfo.InvariantCulture));
|
||||
foreach (string line in e.Plan) ImGuiNET.ImGui.BulletText(line);
|
||||
|
||||
int coinsPerToken = e.CoinsPerToken;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(100);
|
||||
if (ImGuiNET.ImGui.InputInt("Coins per token (shop price)##prog_cpt", ref coinsPerToken))
|
||||
SendProg("coinspertoken " + Math.Max(0, coinsPerToken).ToString(CultureInfo.InvariantCulture));
|
||||
if (e.TokensShort.Length > 0) Label(e.TokensShort, Dim);
|
||||
|
||||
ImGuiNET.ImGui.Separator();
|
||||
if (e.Blockers.Length == 0) Label("Client-side checks pass.", Green);
|
||||
foreach (string b in e.Blockers) Label(b, Amber);
|
||||
Label(e.ServerChecks, Dim);
|
||||
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
if (Button("##prog_enl", "Enlighten now...", p, new Vector2(150, 24), Text, BtnFill, border: Teal))
|
||||
AskProgConfirm("Enlighten",
|
||||
"Send /enl now?\n\nEnlightening resets your level and wipes unassigned XP.\n"
|
||||
+ "The server will show its own Yes/No dialog - you must click Yes there.",
|
||||
"Send /enl", "enlighten");
|
||||
NextLine(p, 28);
|
||||
|
||||
ImGuiNET.ImGui.Separator();
|
||||
bool auto = e.Auto;
|
||||
if (ImGuiNET.ImGui.Checkbox("Auto-enlighten when ready##prog_auto", ref auto))
|
||||
{
|
||||
if (auto)
|
||||
AskProgConfirm("Arm auto-enlighten",
|
||||
"Auto-enlighten will send /enl whenever the checks pass (peace mode, level, materials).\n"
|
||||
+ "You still have to click Yes in the AC dialog each time.\n\nArm it for this session?",
|
||||
"Arm", "autoenl on");
|
||||
else
|
||||
SendProg("autoenl off");
|
||||
}
|
||||
if (e.Auto && !e.Armed)
|
||||
{
|
||||
ImGuiNET.ImGui.SameLine();
|
||||
if (ImGuiNET.ImGui.SmallButton("Arm for this session...##prog_arm"))
|
||||
AskProgConfirm("Arm auto-enlighten", "Arm auto-enlighten for this session?", "Arm", "autoenl arm");
|
||||
}
|
||||
bool spend = e.SpendFirst;
|
||||
if (ImGuiNET.ImGui.Checkbox("Spend unassigned XP on attributes first##prog_spend", ref spend))
|
||||
SendProg("spendfirst " + (spend ? "on" : "off"));
|
||||
int every = e.CheckEvery;
|
||||
ImGuiNET.ImGui.SetNextItemWidth(100);
|
||||
if (ImGuiNET.ImGui.InputInt("Check every (s)##prog_every", ref every))
|
||||
SendProg("checkevery " + Math.Max(10, every).ToString(CultureInfo.InvariantCulture));
|
||||
Label(e.Armed ? "Armed." : "Disarmed.", e.Armed ? Amber : Dim);
|
||||
if (e.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(e.Status);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
ImGuiNET.ImGui.Unindent(8);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Confirm ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The Progression tab's Yes/No popup (outside the body child, like DrawConfirm).</summary>
|
||||
private void DrawProgressionConfirm()
|
||||
{
|
||||
if (_progConfirmOpenRequested)
|
||||
{
|
||||
_progConfirmOpenRequested = false;
|
||||
ImGuiNET.ImGui.OpenPopup(ProgConfirmId);
|
||||
}
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
|
||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8));
|
||||
bool open = ImGuiNET.ImGui.BeginPopup(ProgConfirmId);
|
||||
ImGuiNET.ImGui.PopStyleVar(2);
|
||||
ImGuiNET.ImGui.PopStyleColor(2);
|
||||
if (!open) return;
|
||||
try
|
||||
{
|
||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
|
||||
Label(_progConfirmTitle, Amber);
|
||||
ImGuiNET.ImGui.PopFont();
|
||||
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 320);
|
||||
Label(_progConfirmText, Text);
|
||||
ImGuiNET.ImGui.PopTextWrapPos();
|
||||
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4);
|
||||
if (Button("##prog_yes", _progConfirmYes, p, new Vector2(120, 24), Text, StartBg))
|
||||
{
|
||||
SendProg(_progConfirmCommand);
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
}
|
||||
if (Button("##prog_no", "Cancel", new Vector2(p.X + 126, p.Y), new Vector2(90, 24), Text, BtnFill))
|
||||
ImGuiNET.ImGui.CloseCurrentPopup();
|
||||
NextLine(p, 28);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.EndPopup();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -45,7 +45,7 @@ using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
|
|||
|
||||
namespace RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
internal sealed class SkillsFace : IImGuiPanel
|
||||
internal sealed partial class SkillsFace : IImGuiPanel
|
||||
{
|
||||
public const string Title = "Skills";
|
||||
|
||||
|
|
@ -127,7 +127,7 @@ internal sealed class SkillsFace : IImGuiPanel
|
|||
}
|
||||
|
||||
// ── State ───────────────────────────────────────────────────────────
|
||||
private int _tab; // 0 skills, 1 attributes & vitals
|
||||
private int _tab; // 0 skills, 1 attributes & vitals, 2 progression (ILT worlds)
|
||||
private SortKey _sort = SortKey.Name;
|
||||
private bool _descending;
|
||||
private readonly bool[] _collapsed = { false, false, false, true };
|
||||
|
|
@ -193,18 +193,23 @@ internal sealed class SkillsFace : IImGuiPanel
|
|||
SkillDat.EnsureLoadQueued();
|
||||
PortalSpellTable.EnsureLoadQueued();
|
||||
MasteryFeed.PanelOpened(); // asks only on Aelrynth, and only if the last reply is stale
|
||||
ProgressionShown();
|
||||
}
|
||||
|
||||
public void OnHidden() => ProgressionHidden();
|
||||
|
||||
public void Draw()
|
||||
{
|
||||
PlayerProgressHooks.Want();
|
||||
Refresh();
|
||||
ApplyProgressionRequest();
|
||||
if (_tab == 2 && !ProgressionTabVisible) _tab = 0;
|
||||
|
||||
float w = Begin(out Vector2 origin, out Vector2 size);
|
||||
DrawSummary(w);
|
||||
DrawTabs(w);
|
||||
if (_tab == 0) DrawToolbar(w);
|
||||
DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute");
|
||||
if (_tab != 2) DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute");
|
||||
|
||||
float bodyH = Math.Max(60, Remaining(origin, size) - GripOverlap());
|
||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
|
||||
|
|
@ -212,7 +217,9 @@ internal sealed class SkillsFace : IImGuiPanel
|
|||
ImGuiNET.ImGui.BeginChild("##skills_body", new Vector2(w, bodyH));
|
||||
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
|
||||
EnsureWidths();
|
||||
if (_snap == null || !_snap.SkillTableRead && !_snap.AttributeCacheRead)
|
||||
if (_tab == 2)
|
||||
DrawProgression(bw);
|
||||
else if (_snap == null || !_snap.SkillTableRead && !_snap.AttributeCacheRead)
|
||||
Message("Waiting for your character's data...", bw);
|
||||
else if (_dat == null)
|
||||
Message("Loading skill names from the client's portal.dat: " + SkillDat.Status, bw);
|
||||
|
|
@ -228,6 +235,7 @@ internal sealed class SkillsFace : IImGuiPanel
|
|||
_picker.Draw();
|
||||
DrawMulti();
|
||||
DrawConfirm();
|
||||
DrawProgressionConfirm();
|
||||
}
|
||||
|
||||
// ── Data ────────────────────────────────────────────────────────────
|
||||
|
|
@ -691,13 +699,18 @@ internal sealed class SkillsFace : IImGuiPanel
|
|||
private void DrawTabs(float w)
|
||||
{
|
||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||
float half = (w - 4) * 0.5f;
|
||||
if (Button("##tab_skills", "Skills", p, new Vector2(half, 22), _tab == 0 ? Teal : Text, _tab == 0 ? Selected : BtnFill,
|
||||
// The Progression tab only exists on ILT-like worlds (RynthAi's snapshot says so).
|
||||
int count = ProgressionTabVisible ? 3 : 2;
|
||||
float tabW = (w - 4 * (count - 1)) / count;
|
||||
if (Button("##tab_skills", "Skills", p, new Vector2(tabW, 22), _tab == 0 ? Teal : Text, _tab == 0 ? Selected : BtnFill,
|
||||
border: _tab == 0 ? Teal : 0))
|
||||
_tab = 0;
|
||||
if (Button("##tab_attrs", "Attributes & Vitals", new Vector2(p.X + half + 4, p.Y), new Vector2(half, 22),
|
||||
if (Button("##tab_attrs", "Attributes & Vitals", new Vector2(p.X + tabW + 4, p.Y), new Vector2(tabW, 22),
|
||||
_tab == 1 ? Teal : Text, _tab == 1 ? Selected : BtnFill, border: _tab == 1 ? Teal : 0))
|
||||
_tab = 1;
|
||||
if (count == 3 && Button("##tab_prog", "Progression", new Vector2(p.X + 2 * (tabW + 4), p.Y), new Vector2(tabW, 22),
|
||||
_tab == 2 ? Teal : Text, _tab == 2 ? Selected : BtnFill, border: _tab == 2 ? Teal : 0))
|
||||
_tab = 2;
|
||||
NextLine(p, 26);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -90,6 +90,7 @@ internal static unsafe class PhosphorIcons
|
|||
public const string HourglassMedium = "\uE2B8";
|
||||
public const string Hourglass = "\uE2B2";
|
||||
public const string Info = "\uE2CE";
|
||||
public const string Keyboard = "\uE2D8";
|
||||
public const string Knife = "\uE636";
|
||||
public const string Lightning = "\uE2DE";
|
||||
public const string Leaf = "\uE2DA";
|
||||
|
|
@ -168,7 +169,7 @@ internal static unsafe class PhosphorIcons
|
|||
+ ArrowCircleUp + Barbell + Brain + GraduationCap + Hourglass + SortDescending + Package
|
||||
+ Binoculars + Crown + Sun
|
||||
+ CastleTurret + ClockCounterClockwise + GlobeHemisphereWest + Path + Star + Target + User
|
||||
+ TextAa + Leaf;
|
||||
+ TextAa + Leaf + Keyboard;
|
||||
|
||||
/// <summary>
|
||||
/// Draws <paramref name="glyph"/> (one icon) centred in the box at
|
||||
|
|
|
|||
|
|
@ -392,6 +392,14 @@ internal static unsafe class Win32Backend
|
|||
RunOnGameThread<bool>(() => { action(); return true; });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True once the game window is known AND its WndProc is subclassed, i.e.
|
||||
/// <see cref="RunOnGameThread{T}"/> can actually deliver work to AC's main
|
||||
/// thread. Knowing the HWND alone is not enough: without the subclass,
|
||||
/// WM_RYNTH_RUN_ACTION reaches AC's own WndProc, which ignores it.
|
||||
/// </summary>
|
||||
public static bool CanRunOnGameThread => _initialized && _gameHwnd != IntPtr.Zero;
|
||||
|
||||
/// <summary>Deactivates chat capture. The game HWND retains focus throughout so no
|
||||
/// Win32 focus transfer is needed.</summary>
|
||||
public static void ReturnFocusToGame() => ChatCaptureActive = false;
|
||||
|
|
@ -572,10 +580,11 @@ internal static unsafe class Win32Backend
|
|||
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).
|
||||
// thread. LayeredWindow.Dispose posts its destroy to the panel itself
|
||||
// (handled by the panel's own WndProc, which survives this unhook), but
|
||||
// any panel never disposed would outlive this engine load, frozen and
|
||||
// unclickable (duplicate RynthAi dashboard after RL) — this sweep is the
|
||||
// synchronous backstop for those.
|
||||
IntPtr swept = SendMessageTimeout(_gameHwnd, WM_RYNTH_SWEEP_PANELS, new IntPtr(1), IntPtr.Zero,
|
||||
SMTO_NORMAL, 2000, out _);
|
||||
if (swept == IntPtr.Zero)
|
||||
|
|
@ -956,6 +965,17 @@ internal static unsafe class Win32Backend
|
|||
// which used to be unusable whenever RynthChat was installed, even closed.
|
||||
// !ImGuiTextInputActive: the same rule for an ImGui text box.
|
||||
ExpireStaleCaptureFlags();
|
||||
|
||||
// ── User hotkeys (Settings > Hotkeys, Hotkeys/HotkeyService.cs) ──
|
||||
// A bound combo's keystroke is eaten here, before AC, ImGui and the Enter-opens-chat
|
||||
// branch below; every other key passes on. RynthChat's capture returned above, and
|
||||
// the service holds hotkeys back while any text box (ours or AC's chat) is typed in.
|
||||
if ((IsKeyMessage(msg) || IsExtraCharMessage(msg) || msg == WM_KILLFOCUS)
|
||||
&& Hotkeys.HotkeyService.HandleKeyMessage(msg, wParam, lParam,
|
||||
rynthTextFocus: ChatCaptureActive || AvaloniaTextInputActive || ImGuiTextInputActive
|
||||
|| _wantCaptureKeyboard || ImGuiPopOuts.HasTextFocus))
|
||||
return IntPtr.Zero;
|
||||
|
||||
if (msg == WM_KEYDOWN && (int)wParam == VK_RETURN && !IsExtendedKey(lParam) && !ChatCaptureActive && !AvaloniaTextInputActive
|
||||
&& !ImGuiTextInputActive && !ImGuiPopOuts.HasTextFocus
|
||||
&& RynthCore.Engine.Compatibility.ChatHooks.RynthChatOwnsChat)
|
||||
|
|
@ -991,11 +1011,15 @@ internal static unsafe class Win32Backend
|
|||
// HUD drag (keeps our SetCapture from fighting NewFrame's). No-op
|
||||
// unless the HUD is drawn.
|
||||
if (IsMouseMessage(msg))
|
||||
{
|
||||
TrackMouseButtons(msg, wParam);
|
||||
ItemDragBridge.OnGameMouse(msg, wParam, lParam, _heldButtonsBelongToGame);
|
||||
}
|
||||
else if (msg == WM_KILLFOCUS)
|
||||
{
|
||||
_heldMouseButtons = 0;
|
||||
_heldButtonsBelongToGame = false;
|
||||
ItemDragBridge.Reset();
|
||||
}
|
||||
|
||||
// ── Avalonia panel hit-test & input forwarding ────────────────
|
||||
|
|
@ -1006,7 +1030,7 @@ internal static unsafe class Win32Backend
|
|||
{
|
||||
// fall through: AC gets the message
|
||||
}
|
||||
else if (IsMouseMessage(msg))
|
||||
else if (IsMouseMessage(msg) && !ImGuiOwnsMouseOverAvalonia())
|
||||
{
|
||||
bool handled = TryForwardToAvalonia(msg, wParam, lParam);
|
||||
if (handled)
|
||||
|
|
@ -1097,6 +1121,14 @@ internal static unsafe class Win32Backend
|
|||
}
|
||||
}
|
||||
|
||||
// An AC inventory item dragged onto an ImGui window: AC must not drop it on the
|
||||
// ground behind the window. It gets the release where the drag began instead.
|
||||
if (ItemDragBridge.TryRedirectNativeDrop(msg, out IntPtr pressLParam))
|
||||
{
|
||||
CallWindowProcA(_originalWndProc, hWnd, WM_MOUSEMOVE, (IntPtr)MK_LBUTTON, pressLParam);
|
||||
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, pressLParam);
|
||||
}
|
||||
|
||||
// Pass through to original WndProc
|
||||
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
|
||||
}
|
||||
|
|
@ -1107,6 +1139,17 @@ internal static unsafe class Win32Backend
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ImGui windows are drawn on top of the Avalonia layer, so when the cursor is over
|
||||
/// an ImGui window (or an ImGui widget is active) mouse input must go to ImGui
|
||||
/// instead of the Avalonia panel underneath. An Avalonia drag/resize that is already
|
||||
/// in progress keeps its capture so the release is never lost.
|
||||
/// </summary>
|
||||
private static bool ImGuiOwnsMouseOverAvalonia()
|
||||
{
|
||||
return _wantCaptureMouse && !AvaloniaOverlay.HasPointerCapture;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// If the cursor is over the Avalonia shell panel, PostMessage the mouse event to
|
||||
/// the off-screen Avalonia HWND and return true (caller should suppress game delivery).
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@
|
|||
|
||||
using System;
|
||||
using System.IO;
|
||||
using RynthCore.Install;
|
||||
|
||||
namespace RynthCore.Engine;
|
||||
|
||||
|
|
|
|||
245
src/RynthCore.Engine/LogSettings.cs
Normal file
245
src/RynthCore.Engine/LogSettings.cs
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// Engine log categories. Each one has a configurable emit level (see <see cref="LogSettings"/>).
|
||||
/// Names are the keys of engine.json "LogCategories" and must stay stable.
|
||||
/// </summary>
|
||||
internal enum LogCategory
|
||||
{
|
||||
/// <summary>Uncategorised RynthLog.Info lines.</summary>
|
||||
General = 0,
|
||||
/// <summary>D3D9: vtable, EndScene, bootstrapper, matrix capture, nav3D.</summary>
|
||||
D3D9,
|
||||
/// <summary>Compatibility hooks: client objects, combat, movement, vitals, chat, ...</summary>
|
||||
Compat,
|
||||
/// <summary>ImGui rendering: context, DX9 backend, Win32 input, shell.</summary>
|
||||
Render,
|
||||
/// <summary>Plugin system, including every line plugins write through the host Log API.</summary>
|
||||
Plugin,
|
||||
/// <summary>UI / Avalonia overlay.</summary>
|
||||
UI,
|
||||
/// <summary>Verbose detail lines (RynthLog.Verbose / RynthLog.Debug).</summary>
|
||||
Verbose,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Live engine logging configuration, read from %APPDATA%\RynthCore\engine.json:
|
||||
/// <list type="bullet">
|
||||
/// <item><c>"LoggingLevel"</c> — global threshold: Off, Error, Warning, Info, Debug, Trace.</item>
|
||||
/// <item><c>"LogCategories"</c> — per-category emit level: <c>{ "Compat": "Info", "Verbose": "Debug", ... }</c>.
|
||||
/// The emit level is the level a category's lines are written AT, so a line shows when
|
||||
/// its emit level is within the global threshold. Setting a Trace/Debug category to
|
||||
/// Info puts it in the normal (Info) log; Off silences the category entirely.</item>
|
||||
/// </list>
|
||||
/// A background thread polls the file's timestamp once a second, so launcher edits apply to a
|
||||
/// running client without a restart. Errors are always written, even when the level is Off.
|
||||
/// </summary>
|
||||
internal static class LogSettings
|
||||
{
|
||||
/// <summary>engine.json property holding the per-category levels.</summary>
|
||||
internal const string CategoriesProperty = "LogCategories";
|
||||
|
||||
private const int PollIntervalMs = 1000;
|
||||
|
||||
// Default emit level per LogCategory (index = enum value): categories at Info,
|
||||
// Render off, verbose lines at Debug.
|
||||
private static readonly EntryPoint.EngineLogLevel[] Defaults =
|
||||
{
|
||||
EntryPoint.EngineLogLevel.Info, // General
|
||||
EntryPoint.EngineLogLevel.Info, // D3D9
|
||||
EntryPoint.EngineLogLevel.Info, // Compat
|
||||
EntryPoint.EngineLogLevel.Off, // Render
|
||||
EntryPoint.EngineLogLevel.Info, // Plugin
|
||||
EntryPoint.EngineLogLevel.Info, // UI
|
||||
EntryPoint.EngineLogLevel.Debug, // Verbose
|
||||
};
|
||||
|
||||
// Replaced wholesale on reload (never mutated after publish) so hot-path readers on any
|
||||
// thread can index it without a lock.
|
||||
private static EntryPoint.EngineLogLevel[] _levels = (EntryPoint.EngineLogLevel[])Defaults.Clone();
|
||||
|
||||
private static readonly object WatcherLock = new();
|
||||
private static Thread? _watcherThread;
|
||||
private static ManualResetEventSlim? _stopSignal;
|
||||
private static DateTime _stampUtc = DateTime.MinValue;
|
||||
|
||||
private static string SettingsPath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "engine.json");
|
||||
|
||||
/// <summary>Current emit level for a category (cheap; safe on hot paths).</summary>
|
||||
internal static EntryPoint.EngineLogLevel LevelFor(LogCategory category)
|
||||
{
|
||||
EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels);
|
||||
int i = (int)category;
|
||||
return (uint)i < (uint)levels.Length ? levels[i] : EntryPoint.EngineLogLevel.Info;
|
||||
}
|
||||
|
||||
/// <summary>True when a line in this category would be written right now.</summary>
|
||||
internal static bool IsEnabled(LogCategory category) => EntryPoint.ShouldLog(LevelFor(category));
|
||||
|
||||
/// <summary>3-char severity tag written into each log line.</summary>
|
||||
internal static string Tag(EntryPoint.EngineLogLevel level) => level switch
|
||||
{
|
||||
EntryPoint.EngineLogLevel.Error => "ERR",
|
||||
EntryPoint.EngineLogLevel.Warning => "WRN",
|
||||
EntryPoint.EngineLogLevel.Debug => "DBG",
|
||||
EntryPoint.EngineLogLevel.Trace => "TRC",
|
||||
_ => "INF",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Reads the global level and category levels from engine.json and publishes them.
|
||||
/// Called once at init (before the first log line) and again by the watcher on change.
|
||||
/// Missing or unreadable values fall back to their defaults. Returns a one-line summary.
|
||||
/// </summary>
|
||||
internal static string Reload()
|
||||
{
|
||||
string? globalText = null;
|
||||
var levels = (EntryPoint.EngineLogLevel[])Defaults.Clone();
|
||||
|
||||
try
|
||||
{
|
||||
string path = SettingsPath;
|
||||
if (File.Exists(path))
|
||||
{
|
||||
_stampUtc = File.GetLastWriteTimeUtc(path);
|
||||
// ReadAllText strips a UTF-8/UTF-16 BOM that JsonDocument would choke on.
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(path));
|
||||
JsonElement root = doc.RootElement;
|
||||
|
||||
if (root.TryGetProperty("LoggingLevel", out JsonElement levelEl) && levelEl.ValueKind == JsonValueKind.String)
|
||||
globalText = levelEl.GetString();
|
||||
|
||||
if (root.TryGetProperty(CategoriesProperty, out JsonElement catsEl) && catsEl.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (JsonProperty p in catsEl.EnumerateObject())
|
||||
{
|
||||
if (p.Value.ValueKind != JsonValueKind.String) continue;
|
||||
if (!Enum.TryParse(p.Name, ignoreCase: true, out LogCategory cat) || !Enum.IsDefined(cat)) continue;
|
||||
if (TryParseCategoryLevel(p.Value.GetString(), out EntryPoint.EngineLogLevel lvl))
|
||||
levels[(int)cat] = lvl;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Half-written / corrupt file: keep defaults for this pass; the next timestamp change retries.
|
||||
globalText ??= EngineSettings.LoggingLevel;
|
||||
}
|
||||
|
||||
EntryPoint.LoggingLevel = EntryPoint.ParseLoggingLevel(globalText);
|
||||
Volatile.Write(ref _levels, levels);
|
||||
EntryPoint.VerboseLogging = IsEnabled(LogCategory.Verbose);
|
||||
return Describe();
|
||||
}
|
||||
|
||||
/// <summary>Human-readable "level=Info D3D9=Info Compat=Info ..." summary for the log.</summary>
|
||||
internal static string Describe()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("level=").Append(EntryPoint.LoggingLevel);
|
||||
EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels);
|
||||
for (int i = 0; i < levels.Length; i++)
|
||||
sb.Append(' ').Append((LogCategory)i).Append('=').Append(levels[i]);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Categories whose emit level is more verbose than the global level, so none of their lines
|
||||
/// are written (e.g. every category at Trace with LoggingLevel Info: an almost empty log).
|
||||
/// Empty when nothing is hidden.
|
||||
/// </summary>
|
||||
internal static string HiddenCategoriesWarning()
|
||||
{
|
||||
EntryPoint.EngineLogLevel global = EntryPoint.LoggingLevel;
|
||||
EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels);
|
||||
var hidden = new StringBuilder();
|
||||
for (int i = 0; i < levels.Length; i++)
|
||||
{
|
||||
if (levels[i] == EntryPoint.EngineLogLevel.Off || levels[i] <= global) continue;
|
||||
if (hidden.Length > 0) hidden.Append(", ");
|
||||
hidden.Append((LogCategory)i).Append('=').Append(levels[i]);
|
||||
}
|
||||
return hidden.Length == 0 ? ""
|
||||
: $"LogSettings: {hidden} write above the global LoggingLevel ({global}), so those lines are NOT logged. " +
|
||||
"Raise LoggingLevel to the most verbose category level, or set the categories to Info.";
|
||||
}
|
||||
|
||||
/// <summary>Starts the once-a-second engine.json poll. Idempotent.</summary>
|
||||
internal static void StartWatcher()
|
||||
{
|
||||
lock (WatcherLock)
|
||||
{
|
||||
if (_watcherThread != null) return;
|
||||
_stopSignal = new ManualResetEventSlim(false);
|
||||
ManualResetEventSlim stop = _stopSignal;
|
||||
_watcherThread = new Thread(() => WatchLoop(stop))
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "RynthCore.LogSettingsWatcher",
|
||||
};
|
||||
_watcherThread.Start();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops and joins the poll thread. Called from EngineLifecycle.Shutdown so the thread never
|
||||
/// runs inside an old engine generation after a hot reload.
|
||||
/// </summary>
|
||||
internal static void StopWatcher()
|
||||
{
|
||||
Thread? thread;
|
||||
lock (WatcherLock)
|
||||
{
|
||||
thread = _watcherThread;
|
||||
_stopSignal?.Set();
|
||||
_watcherThread = null;
|
||||
}
|
||||
thread?.Join(2000);
|
||||
}
|
||||
|
||||
private static void WatchLoop(ManualResetEventSlim stop)
|
||||
{
|
||||
while (!stop.Wait(PollIntervalMs))
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = SettingsPath;
|
||||
if (!File.Exists(path) || File.GetLastWriteTimeUtc(path) == _stampUtc)
|
||||
continue;
|
||||
|
||||
string summary = Reload();
|
||||
// Bypasses the category levels so a change is visible whenever Info is in range.
|
||||
if (EntryPoint.ShouldLog(EntryPoint.EngineLogLevel.Info))
|
||||
EntryPoint.LogTagged("engine", $"LogSettings: engine.json changed - logging reloaded ({summary}).", "INF");
|
||||
string hidden = HiddenCategoriesWarning();
|
||||
if (hidden.Length > 0) RynthLog.Warn(hidden);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Logging configuration must never take the client down; retry next poll.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a category emit level: Off, Trace, Debug (or Verbose), Info, Warning (or Warn), Error.
|
||||
/// </summary>
|
||||
private static bool TryParseCategoryLevel(string? text, out EntryPoint.EngineLogLevel level)
|
||||
{
|
||||
level = EntryPoint.EngineLogLevel.Info;
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
string t = text.Trim();
|
||||
if (t.Equals("Verbose", StringComparison.OrdinalIgnoreCase)) { level = EntryPoint.EngineLogLevel.Debug; return true; }
|
||||
if (t.Equals("Warn", StringComparison.OrdinalIgnoreCase)) { level = EntryPoint.EngineLogLevel.Warning; return true; }
|
||||
return Enum.TryParse(t, ignoreCase: true, out level) && Enum.IsDefined(level);
|
||||
}
|
||||
}
|
||||
87
src/RynthCore.Engine/MainThreadFreeze.cs
Normal file
87
src/RynthCore.Engine/MainThreadFreeze.cs
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - MainThreadFreeze.cs
|
||||
// The plugin pump's freeze gate (rule and reasons: MainThreadFreezeRule.cs).
|
||||
// PluginManager.TickAll asks ShouldPausePluginTick once per pump tick; while it
|
||||
// says yes, no plugin Tick runs (no decisions, no actions), while event delivery
|
||||
// (ProcessPendingActions: observing) carries on.
|
||||
//
|
||||
// Plugins can read the state through GetEngineStatusJson (additive fields, no API
|
||||
// version change): mainThreadFrozen, mainThreadStallMs, pluginTicksPausedMs (a running
|
||||
// total, so a stall detector can subtract the paused time from what it measured).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine;
|
||||
|
||||
internal static class MainThreadFreeze
|
||||
{
|
||||
private static readonly PumpPauseTracker Tracker = new(); // pump thread only
|
||||
private static int _pausedFlag; // published copies, any thread
|
||||
private static long _pausedTotalMs, _pausedSinceMs;
|
||||
|
||||
/// <summary>Plugin ticks are paused right now. Any thread.</summary>
|
||||
public static bool Paused => Volatile.Read(ref _pausedFlag) != 0;
|
||||
|
||||
/// <summary>Total time plugin ticks have been paused, a pause in progress included. Any thread.</summary>
|
||||
public static long PausedTotalMs
|
||||
{
|
||||
get
|
||||
{
|
||||
long total = Interlocked.Read(ref _pausedTotalMs);
|
||||
long since = Interlocked.Read(ref _pausedSinceMs);
|
||||
return Paused && since != 0 ? total + Math.Max(0, Environment.TickCount64 - since) : total;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>How long AC's main thread has gone without a beat (0 before the first one). Any thread.</summary>
|
||||
public static long MainThreadStallMs =>
|
||||
MainThreadHangWatchdog.HasBeaten ? Math.Max(0, Environment.TickCount64 - MainThreadHangWatchdog.LastBeatTick) : 0;
|
||||
|
||||
/// <summary>Frozen right now by the rule (main-thread message box, or a stale beat). Any thread.</summary>
|
||||
public static bool IsFrozenNow(out int mainThreadBoxes, out long staleMs)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
mainThreadBoxes = Compatibility.MessageBoxHooks.MainThreadOpenCount;
|
||||
bool beaten = MainThreadHangWatchdog.HasBeaten;
|
||||
long last = MainThreadHangWatchdog.LastBeatTick;
|
||||
staleMs = beaten ? now - last : 0;
|
||||
return MainThreadFreezeRule.IsFrozen(now, last, beaten, mainThreadBoxes, MainThreadHangWatchdog.HangThresholdMs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pump thread, once per TickAll. True = skip this tick's plugin Ticks. Logs the pause and
|
||||
/// the resume. Never throws.
|
||||
/// </summary>
|
||||
public static bool ShouldPausePluginTick()
|
||||
{
|
||||
try
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
bool frozen = IsFrozenNow(out int boxes, out long staleMs);
|
||||
PumpPauseTracker.Transition t = Tracker.Update(frozen, now);
|
||||
if (t == PumpPauseTracker.Transition.Paused)
|
||||
{
|
||||
Interlocked.Exchange(ref _pausedSinceMs, now);
|
||||
Volatile.Write(ref _pausedFlag, 1);
|
||||
string why = boxes > 0
|
||||
? $"a message box is open on its main thread ({Compatibility.MessageBoxHooks.Describe() ?? "?"})"
|
||||
: $"no main-thread beat for {staleMs} ms";
|
||||
RynthLog.Warn($"PluginManager: AC's main thread is frozen ({why}) - plugin ticks PAUSED (events still delivered).");
|
||||
}
|
||||
else if (t == PumpPauseTracker.Transition.Resumed)
|
||||
{
|
||||
Interlocked.Exchange(ref _pausedTotalMs, Tracker.FinishedPausedMs);
|
||||
Volatile.Write(ref _pausedFlag, 0);
|
||||
long lasted = now - Tracker.PausedSinceMs;
|
||||
RynthLog.Info($"PluginManager: AC's main thread is back - plugin ticks resumed after {lasted} ms ({Tracker.TicksSkippedThisPause} tick(s) skipped, pause #{Tracker.Pauses}).");
|
||||
}
|
||||
return Tracker.Paused;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
96
src/RynthCore.Engine/MainThreadFreezeRule.cs
Normal file
96
src/RynthCore.Engine/MainThreadFreezeRule.cs
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - MainThreadFreezeRule.cs
|
||||
//
|
||||
// When AC's main thread is frozen, plugin ticks (where plugins decide and act) are
|
||||
// paused; event delivery (observing) goes on. In one real case AC's
|
||||
// OUT OF MEMORY box held the main thread for 12 s while the plugin pump kept
|
||||
// ticking; the bot jumped and asked for Peace mode to break a "stuck cast", and
|
||||
// blamed the server, while nothing could reach the server at all.
|
||||
//
|
||||
// Frozen means either of:
|
||||
// - a message box is open ON AC'S MAIN THREAD (MessageBoxHooks): modal, the main
|
||||
// thread is inside it from the first instant; or
|
||||
// - the main-thread heartbeat (EndScene / Client::UseTime beats) is at least the
|
||||
// hang watchdog's threshold old: the same signal MainThreadHangWatchdog uses.
|
||||
// Before the first beat nothing is frozen (the main thread is not known yet).
|
||||
//
|
||||
// PumpPauseTracker keeps the pause transitions and how long plugin ticks have been
|
||||
// paused in total, which plugins can read (GetEngineStatusJson) to discount frozen
|
||||
// time from their own stall detectors.
|
||||
//
|
||||
// Pure: no engine state. Compiled into tools\EngineRobustnessTests.
|
||||
// ============================================================================
|
||||
|
||||
namespace RynthCore.Engine;
|
||||
|
||||
internal static class MainThreadFreezeRule
|
||||
{
|
||||
public static bool IsFrozen(long nowMs, long lastBeatMs, bool beatSeen, int mainThreadMessageBoxes, long thresholdMs)
|
||||
{
|
||||
if (mainThreadMessageBoxes > 0)
|
||||
return true;
|
||||
return beatSeen && nowMs - lastBeatMs >= thresholdMs;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Is a message box AC's OUT OF MEMORY box (the one that gets a full-memory dump)? Only on
|
||||
/// AC's main thread, and only AC's own text, matched exactly at the start (ordinal): a plugin
|
||||
/// box or a chat line that merely mentions memory must never cost a multi-gigabyte dump.
|
||||
/// </summary>
|
||||
internal static class OutOfMemoryBoxRule
|
||||
{
|
||||
public const string Prefix = "OUT OF MEMORY: Failed to allocate";
|
||||
|
||||
public static bool IsOutOfMemoryBox(string? body, bool onMainThread) =>
|
||||
onMainThread && body != null && body.StartsWith(Prefix, System.StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Single-writer (the plugin pump). Not thread-safe; the engine glue publishes copies.</summary>
|
||||
internal sealed class PumpPauseTracker
|
||||
{
|
||||
public enum Transition { None, Paused, Resumed }
|
||||
|
||||
public bool Paused { get; private set; }
|
||||
public long PausedSinceMs { get; private set; }
|
||||
/// <summary>Paused time of finished pauses (the current one is added by <see cref="TotalPausedMs"/>).</summary>
|
||||
public long FinishedPausedMs { get; private set; }
|
||||
public int Pauses { get; private set; }
|
||||
public long TicksSkippedThisPause { get; private set; }
|
||||
public long TicksSkippedTotal { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Feed one pump tick. Returns the transition, if any. While paused the tick is to be
|
||||
/// skipped (and is counted as skipped).
|
||||
/// </summary>
|
||||
public Transition Update(bool frozen, long nowMs)
|
||||
{
|
||||
if (frozen)
|
||||
{
|
||||
Transition t = Transition.None;
|
||||
if (!Paused)
|
||||
{
|
||||
Paused = true;
|
||||
PausedSinceMs = nowMs;
|
||||
Pauses++;
|
||||
TicksSkippedThisPause = 0;
|
||||
t = Transition.Paused;
|
||||
}
|
||||
TicksSkippedThisPause++;
|
||||
TicksSkippedTotal++;
|
||||
return t;
|
||||
}
|
||||
if (Paused)
|
||||
{
|
||||
Paused = false;
|
||||
long d = nowMs - PausedSinceMs;
|
||||
if (d > 0) FinishedPausedMs += d;
|
||||
return Transition.Resumed;
|
||||
}
|
||||
return Transition.None;
|
||||
}
|
||||
|
||||
/// <summary>Total time plugin ticks have been paused, including a pause in progress.</summary>
|
||||
public long TotalPausedMs(long nowMs) =>
|
||||
FinishedPausedMs + (Paused && nowMs > PausedSinceMs ? nowMs - PausedSinceMs : 0);
|
||||
}
|
||||
|
|
@ -63,7 +63,8 @@ internal static class MainThreadHangWatchdog
|
|||
internal static volatile string? CrashCause;
|
||||
|
||||
// Stalls longer than this with no EndScene beat = main thread wedged.
|
||||
private const long HangThresholdMs = 4000;
|
||||
// Also the plugin pump's freeze gate (MainThreadFreeze): one signal for both.
|
||||
internal const long HangThresholdMs = 4000;
|
||||
// Max stack samples to take during a single hang (1/sec). A permanent freeze
|
||||
// shows a stable eip across these = the true wedge; a transient stall logs
|
||||
// RECOVERED. Capped to keep the log readable.
|
||||
|
|
@ -82,6 +83,12 @@ internal static class MainThreadHangWatchdog
|
|||
/// <summary>Monotonic EndScene frame count since engine init.</summary>
|
||||
internal static int FrameCount => _frameCount;
|
||||
|
||||
/// <summary>True once the main thread has beaten (its id is known). Any thread.</summary>
|
||||
internal static bool HasBeaten => _mainThreadId != 0;
|
||||
|
||||
/// <summary>Environment.TickCount64 of the last main-thread beat. Any thread.</summary>
|
||||
internal static long LastBeatTick => Volatile.Read(ref _lastBeatTick);
|
||||
|
||||
/// <summary>
|
||||
/// Called from EndSceneDetour on AC's main thread, every frame. Must be
|
||||
/// cheap and never throw.
|
||||
|
|
@ -155,6 +162,13 @@ internal static class MainThreadHangWatchdog
|
|||
uint tid = _mainThreadId;
|
||||
if (tid == 0) continue; // EndScene hasn't beaten yet
|
||||
|
||||
// The main thread is writing the OUT OF MEMORY full-memory dump (CrashDump,
|
||||
// from MessageBoxHooks). Neither suspend it nor report the wedge yet: the
|
||||
// launcher kills the client on "still hung after", which would cut the dump
|
||||
// short. The hang is detected and reported as usual once the dump is done.
|
||||
if (CrashDump.FullDumpInProgress)
|
||||
continue;
|
||||
|
||||
long lastBeat = Volatile.Read(ref _lastBeatTick);
|
||||
long stale = Environment.TickCount64 - lastBeat;
|
||||
|
||||
|
|
@ -170,6 +184,12 @@ internal static class MainThreadHangWatchdog
|
|||
// A modal dialog (AC's error MessageBox) holds the main thread: say which.
|
||||
string? box = Compatibility.MessageBoxHooks.Describe();
|
||||
if (box != null) RynthLog.Error($" hang cause: {box}");
|
||||
// The plugin pump stuck in (or crashed inside) a plugin call: say which. A
|
||||
// native fault in a managed plugin's export is fatal and leaves only
|
||||
// "TickAll" in the event log; this line is written during the ~12 s the
|
||||
// crash dump takes (2026-10-13: RynthAi's Tick).
|
||||
string? pump = Plugins.PluginManager.DescribePumpDispatch();
|
||||
if (pump != null) RynthLog.Error($" plugin pump: {pump}");
|
||||
CrashCause = null;
|
||||
}
|
||||
|
||||
|
|
@ -230,6 +250,11 @@ internal static class MainThreadHangWatchdog
|
|||
RynthLog.Info(" (hang minidump disabled via EngineSettings.EnableHangMinidump)");
|
||||
return;
|
||||
}
|
||||
if (CrashDump.FullDumpWrittenPath is { } full)
|
||||
{
|
||||
RynthLog.Info($" (hang minidump skipped: the full-memory dump {full} already covers this hang)");
|
||||
return;
|
||||
}
|
||||
CrashDump.WriteSelfDump(
|
||||
$"main-thread hang tid={tid} stale={staleMs}ms build={EntryPoint.BuildStamp}", out _);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -348,8 +348,14 @@ internal sealed unsafe class FlightCapture
|
|||
NoteTarget(arg1, now);
|
||||
}
|
||||
|
||||
f |= MatchEngineCall(action, arg0, arg1, now) ? FlightFlags.Engine : FlightFlags.Client;
|
||||
Keep(_out, now, FlightDir.Out, f, msg, len, fullLen, seq, 0);
|
||||
// An IdentifyObject is the engine's when an engine send for that object was
|
||||
// registered just before (EngineSend, with who asked); otherwise AC or Decal sent it.
|
||||
byte idWho = action == FlightOp.AcIdentifyObject ? MatchEngineSend(arg0, now) : (byte)0;
|
||||
bool engine = idWho != 0 || MatchEngineCall(action, arg0, arg1, now);
|
||||
if (action == FlightOp.AcIdentifyObject && !engine)
|
||||
Interlocked.Increment(ref _identifyForeign);
|
||||
f |= engine ? FlightFlags.Engine : FlightFlags.Client;
|
||||
Keep(_out, now, FlightDir.Out, f, msg, len, fullLen, seq, 0, idWho);
|
||||
|
||||
if (action == FlightOp.AcUse || action == FlightOp.AcUseWithTarget)
|
||||
DetectUseSent(action == FlightOp.AcUse ? arg0 : arg1, counted: action == FlightOp.AcUse, now);
|
||||
|
|
@ -431,10 +437,10 @@ internal sealed unsafe class FlightCapture
|
|||
}
|
||||
}
|
||||
|
||||
private void Keep(Side side, long now, FlightDir dir, FlightFlags f, byte* msg, int len, int fullLen, uint seq, uint suppressed)
|
||||
private void Keep(Side side, long now, FlightDir dir, FlightFlags f, byte* msg, int len, int fullLen, uint seq, uint suppressed, uint requester = 0)
|
||||
{
|
||||
side.Kept++;
|
||||
Ring.WriteMessage(now, dir, f, msg, len, fullLen, seq, suppressed);
|
||||
Ring.WriteMessage(now, dir, f, msg, len, fullLen, seq, suppressed, requester);
|
||||
}
|
||||
|
||||
// ── positions ──────────────────────────────────────────────────────────
|
||||
|
|
@ -589,6 +595,72 @@ internal sealed unsafe class FlightCapture
|
|||
}
|
||||
}
|
||||
|
||||
// -- engine IdentifyObject (0xC8) sends --
|
||||
// Kept apart from _pending: AutoId alone can send 30 a second, which would push every
|
||||
// other engine call out of that 16-entry table. No marker line per send: the tag on the
|
||||
// 0xC8 itself ([eng:<who>]) says who asked. 256 entries = AcMainThreadQueue's
|
||||
// MaxRequestIdQueue: one drain can send a whole full queue before any of it reaches sendto.
|
||||
private struct IdPending { public uint Id; public byte Who; public long Stamp; public bool Used; }
|
||||
private readonly IdPending[] _idPending = new IdPending[256];
|
||||
private int _idPendingNext;
|
||||
private long _identifyForeign;
|
||||
|
||||
/// <summary>IdentifyObject (0xC8) messages sent with no engine send to match: AC itself or Decal.</summary>
|
||||
public long IdentifyForeignTotal => Interlocked.Read(ref _identifyForeign);
|
||||
|
||||
/// <summary>
|
||||
/// The engine is about to send an IdentifyObject for <paramref name="id"/> on behalf of
|
||||
/// <paramref name="who"/> (an IdRequester, non-zero). The next 0xC8 for that id within
|
||||
/// EngineMatchMs is tagged [eng:<who>]. Called BEFORE the send, so a 0xC8 that AC puts
|
||||
/// on the wire inside the call is still matched. Returns a token for EngineSendFailed, or -1.
|
||||
/// </summary>
|
||||
public int EngineSend(byte who, uint id)
|
||||
{
|
||||
if (who == 0) return -1;
|
||||
long now = _clock();
|
||||
lock (_engineLock)
|
||||
{
|
||||
int slot = _idPendingNext;
|
||||
ref IdPending p = ref _idPending[slot];
|
||||
_idPendingNext = (_idPendingNext + 1) & (_idPending.Length - 1);
|
||||
p.Id = id; p.Who = who; p.Stamp = now; p.Used = false;
|
||||
return slot;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The send registered as <paramref name="token"/> did not happen (the call returned false or
|
||||
/// threw): retire its entry so it cannot tag a later 0xC8 for the same id. A no-op when the
|
||||
/// entry was already matched or the slot has since been reused for another id.
|
||||
/// </summary>
|
||||
public void EngineSendFailed(int token, uint id)
|
||||
{
|
||||
if (token < 0 || token >= _idPending.Length) return;
|
||||
lock (_engineLock)
|
||||
{
|
||||
ref IdPending p = ref _idPending[token];
|
||||
if (p.Id == id && !p.Used) p.Used = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The requester of the oldest unmatched engine send for <paramref name="id"/>, or 0.</summary>
|
||||
private byte MatchEngineSend(uint id, long now)
|
||||
{
|
||||
lock (_engineLock)
|
||||
{
|
||||
int best = -1;
|
||||
for (int i = 0; i < _idPending.Length; i++)
|
||||
{
|
||||
ref IdPending p = ref _idPending[i];
|
||||
if (p.Who == 0 || p.Used || p.Id != id || now < p.Stamp || Ms(now - p.Stamp) > EngineMatchMs) continue;
|
||||
if (best < 0 || p.Stamp < _idPending[best].Stamp) best = i;
|
||||
}
|
||||
if (best < 0) return 0;
|
||||
_idPending[best].Used = true;
|
||||
return _idPending[best].Who;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Engine calls that send something to the server.</summary>
|
||||
private static bool Expects(string name) => name switch
|
||||
{
|
||||
|
|
|
|||
|
|
@ -344,7 +344,9 @@ internal static class FlightFormat
|
|||
|
||||
uint seq = rd.U32();
|
||||
uint action = rd.U32();
|
||||
string tag = (e.Flags & FlightFlags.Engine) != 0 ? "[eng] " : (e.Flags & FlightFlags.Client) != 0 ? "[cli] " : "";
|
||||
string who = IdRequesters.Label(e.C);
|
||||
string tag = (e.Flags & FlightFlags.Engine) != 0 ? (who.Length > 0 ? $"[eng:{who}] " : "[eng] ")
|
||||
: (e.Flags & FlightFlags.Client) != 0 ? "[cli] " : "";
|
||||
string body = action switch
|
||||
{
|
||||
FlightOp.AcUse => $"{Id(rd.U32())}",
|
||||
|
|
@ -539,12 +541,12 @@ internal static class FlightFormat
|
|||
case FlightOp.EvAttackerNotification:
|
||||
{
|
||||
string who = rd.Str(40); rd.U32(); double pct = rd.F64(); uint dmg = rd.U32(); uint crit = rd.U32();
|
||||
return $"hit '{who}' for {dmg}{(crit != 0 ? " (crit)" : "")}, {pct * 100:0}% left";
|
||||
return $"hit '{who}' for {dmg}{(crit != 0 ? " (crit)" : "")} ({pct * 100:0}% of its max health)"; // the share is damage / max, not what is left
|
||||
}
|
||||
case FlightOp.EvDefenderNotification:
|
||||
{
|
||||
string who = rd.Str(40); rd.U32(); double pct = rd.F64(); uint dmg = rd.U32();
|
||||
return $"'{who}' hit you for {dmg}, {pct * 100:0}% left";
|
||||
return $"'{who}' hit you for {dmg} ({pct * 100:0}% of your max health)";
|
||||
}
|
||||
case FlightOp.EvEvasionAttacker: return $"'{rd.Str(40)}' evaded";
|
||||
case FlightOp.EvEvasionDefender: return $"evaded '{rd.Str(40)}'";
|
||||
|
|
@ -794,6 +796,8 @@ internal static class FlightFormat
|
|||
" -> client to server (what this client sent). [eng] = matches an engine direct-action call just before",
|
||||
" (the 'engine ...' marker above it); [cli] = no engine call to match: the client's own path",
|
||||
" (keyboard/mouse, or a plugin calling AC some other way). Movement matches are by time only.",
|
||||
" IdentifyObject: [eng:autoid-target|autoid-container|autoid-inventory|autoid-world|plugin|self|ui]",
|
||||
" = an engine appraisal and who asked for it; [cli] = AC itself or Decal.",
|
||||
" <- server to client: game events (UseDone, ViewContents, errors, magic, combat), the player's own",
|
||||
" motion/position/teleport, system text, and messages about objects the character just used.",
|
||||
" ** engine markers: engine calls, m_cBusy changes and resets, action-gate clears, a per-second link",
|
||||
|
|
|
|||
|
|
@ -125,6 +125,35 @@ internal static unsafe class FlightRecorder
|
|||
try { c.EngineCall(name, a, b); } catch { }
|
||||
}
|
||||
|
||||
/// <summary>An engine IdentifyObject send for <paramref name="id"/>, asked for by <paramref name="who"/>
|
||||
/// (IdRequester): the 0xC8 it produces is tagged [eng:<who>]. Call it before the send; the
|
||||
/// token goes to EngineSendFailed when the send does not happen. -1 while the recorder is off.</summary>
|
||||
public static int EngineSend(byte who, uint id)
|
||||
{
|
||||
FlightCapture? c = _cap;
|
||||
if (c == null || _paused) return -1;
|
||||
try { return c.EngineSend(who, id); } catch { return -1; }
|
||||
}
|
||||
|
||||
/// <summary>The send registered as <paramref name="token"/> did not happen: retire its entry.</summary>
|
||||
public static void EngineSendFailed(int token, uint id)
|
||||
{
|
||||
if (token < 0) return;
|
||||
FlightCapture? c = _cap;
|
||||
if (c == null) return;
|
||||
try { c.EngineSendFailed(token, id); } catch { }
|
||||
}
|
||||
|
||||
/// <summary>IdentifyObject messages sent with no engine send to match (AC or Decal); -1 while the recorder is off.</summary>
|
||||
public static long ForeignIdentifyTotal
|
||||
{
|
||||
get
|
||||
{
|
||||
FlightCapture? c = _cap;
|
||||
return c == null ? -1 : c.IdentifyForeignTotal;
|
||||
}
|
||||
}
|
||||
|
||||
public static void Mark(FlightMark kind, uint a = 0, uint b = 0, uint c = 0, string? text = null)
|
||||
{
|
||||
FlightCapture? cap = _cap;
|
||||
|
|
|
|||
|
|
@ -93,7 +93,7 @@ internal unsafe struct FlightEntry
|
|||
public uint A;
|
||||
/// <summary>Messages: rate-limited copies dropped before this one. Markers: second number.</summary>
|
||||
public uint B;
|
||||
/// <summary>Messages: unused. Markers: third number.</summary>
|
||||
/// <summary>Messages: an engine 0xC8's requester (IdRequester), else 0. Markers: third number.</summary>
|
||||
public uint C;
|
||||
public fixed byte Data[DataCap];
|
||||
}
|
||||
|
|
@ -153,7 +153,8 @@ internal sealed unsafe class FlightRing
|
|||
}
|
||||
|
||||
/// <summary>A message: its first DataCap bytes.</summary>
|
||||
public void WriteMessage(long stamp, FlightDir dir, FlightFlags flags, byte* msg, int len, int fullLen, uint fragSeq, uint suppressed)
|
||||
/// <param name="requester">Messages' C: for an engine 0xC8, who asked (IdRequester); else 0.</param>
|
||||
public void WriteMessage(long stamp, FlightDir dir, FlightFlags flags, byte* msg, int len, int fullLen, uint fragSeq, uint suppressed, uint requester = 0)
|
||||
{
|
||||
if (!Own(out int i, out int serial)) return;
|
||||
ref FlightEntry e = ref _slots[i];
|
||||
|
|
@ -167,7 +168,7 @@ internal sealed unsafe class FlightRing
|
|||
e.FullLen = (ushort)Math.Clamp(fullLen, 0, ushort.MaxValue);
|
||||
e.A = fragSeq;
|
||||
e.B = suppressed;
|
||||
e.C = 0;
|
||||
e.C = requester;
|
||||
fixed (byte* d = e.Data)
|
||||
{
|
||||
if (keep > 0) Buffer.MemoryCopy(msg, d, FlightEntry.DataCap, keep);
|
||||
|
|
|
|||
116
src/RynthCore.Engine/Net/IdRequester.cs
Normal file
116
src/RynthCore.Engine/Net/IdRequester.cs
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Net/IdRequester.cs
|
||||
//
|
||||
// Who asked for an IdentifyObject (0xC8) the engine sends, so the flight recorder and
|
||||
// the per-minute counters can tell the engine's appraisals apart from AC's and Decal's.
|
||||
//
|
||||
// Before: the recorder tagged every 0xC8 [cli] (FlightCapture had no case for it), so
|
||||
// 3211 identifies in one session's dump could not be split between AutoId, the plugins
|
||||
// and the client itself.
|
||||
//
|
||||
// The marker is call-scoped and thread-local: whoever calls CombatActionHooks.RequestId
|
||||
// wraps the call in EngineSendMarker.Enter(who). When the call is queued for AC's main
|
||||
// thread, the requester rides with the queued entry (PendingIdQueue) and the drain
|
||||
// re-enters the marker around the real send. Only a send made under a marker is
|
||||
// registered with the recorder (FlightCapture.EngineSend), so a 0xC8 nobody marked stays
|
||||
// [cli]: AC itself or Decal.
|
||||
//
|
||||
// Pure: no engine state. Compiled into tools\EngineRobustnessTests and
|
||||
// tools\FlightRecorderTests.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Net;
|
||||
|
||||
/// <summary>Who asked for an engine 0xC8. The byte value is what the flight ring stores.</summary>
|
||||
internal enum IdRequester : byte
|
||||
{
|
||||
/// <summary>No marker: not an engine send (AC itself, Decal), or an unmarked engine path.</summary>
|
||||
None = 0,
|
||||
AutoIdTarget = 1,
|
||||
AutoIdContainer = 2,
|
||||
AutoIdInventory = 3,
|
||||
/// <summary>AutoIdMode All only: an object that is not the target, in an open container or in the pack.</summary>
|
||||
AutoIdWorld = 4,
|
||||
/// <summary>A plugin through the host RequestId (plugin API).</summary>
|
||||
Plugin = 5,
|
||||
/// <summary>The engine's delayed login self-identify (max vitals).</summary>
|
||||
Self = 6,
|
||||
/// <summary>The engine's Inventory panel identifying the item under the cursor.</summary>
|
||||
Ui = 7,
|
||||
}
|
||||
|
||||
internal static class IdRequesters
|
||||
{
|
||||
public const int Count = 8;
|
||||
|
||||
/// <summary>The flight-recorder label after "eng:" ("" for None or an unknown code).</summary>
|
||||
public static string Label(uint code) => code switch
|
||||
{
|
||||
1 => "autoid-target",
|
||||
2 => "autoid-container",
|
||||
3 => "autoid-inventory",
|
||||
4 => "autoid-world",
|
||||
5 => "plugin",
|
||||
6 => "self",
|
||||
7 => "ui",
|
||||
_ => "",
|
||||
};
|
||||
|
||||
/// <summary>Short heartbeat field names (none contains fps=, plug=, login= or qd=).</summary>
|
||||
public static string Short(IdRequester who) => who switch
|
||||
{
|
||||
IdRequester.AutoIdTarget => "tgt",
|
||||
IdRequester.AutoIdContainer => "ctr",
|
||||
IdRequester.AutoIdInventory => "inv",
|
||||
IdRequester.AutoIdWorld => "wld",
|
||||
IdRequester.Plugin => "plg",
|
||||
IdRequester.Self => "slf",
|
||||
IdRequester.Ui => "ui",
|
||||
_ => "unm",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The thread-local "this 0xC8 is the engine's" marker around a RequestId call.</summary>
|
||||
internal static class EngineSendMarker
|
||||
{
|
||||
[ThreadStatic] private static IdRequester t_current;
|
||||
|
||||
/// <summary>The requester marked on this thread (None outside any scope).</summary>
|
||||
public static IdRequester Current => t_current;
|
||||
|
||||
/// <summary>Marks this thread until the returned scope is disposed (scopes nest).</summary>
|
||||
public static Scope Enter(IdRequester who)
|
||||
{
|
||||
IdRequester previous = t_current;
|
||||
t_current = who;
|
||||
return new Scope(previous);
|
||||
}
|
||||
|
||||
public readonly struct Scope : IDisposable
|
||||
{
|
||||
private readonly IdRequester _previous;
|
||||
internal Scope(IdRequester previous) { _previous = previous; }
|
||||
public void Dispose() => t_current = _previous;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Engine 0xC8 sends that really went out, per requester (running totals; any thread).</summary>
|
||||
internal static class IdSendStats
|
||||
{
|
||||
private static readonly long[] _sent = new long[IdRequesters.Count];
|
||||
|
||||
public static void CountSent(IdRequester who)
|
||||
{
|
||||
int i = (int)who;
|
||||
if ((uint)i < (uint)_sent.Length) Interlocked.Increment(ref _sent[i]);
|
||||
}
|
||||
|
||||
public static long Sent(IdRequester who)
|
||||
{
|
||||
int i = (int)who;
|
||||
return (uint)i < (uint)_sent.Length ? Interlocked.Read(ref _sent[i]) : 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -218,6 +218,14 @@ internal static unsafe class ServerMessageStream
|
|||
{
|
||||
try { InventoryOrder.Observe(new ReadOnlySpan<byte>(message, length)); }
|
||||
catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: inventory order failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||
// The SERVER deleted an object (0xF747 ObjectDelete, its id after the opcode). AutoId
|
||||
// tells this apart from the client's own releases: only this one makes a re-create
|
||||
// under the same id due an appraisal again (AutoIdEligibility).
|
||||
if (opcode == InventoryOrder.DeleteObjectOpcode && length >= 8)
|
||||
{
|
||||
try { Compatibility.AutoIdService.OnServerDelete(AcPacketWire.ReadU32(message + 4)); }
|
||||
catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: server delete failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
if (_pluginsWant)
|
||||
_dispatchedToPlugins += PluginManager.DispatchServerMessage(opcode, eventType, message + 4, length - 4);
|
||||
|
|
|
|||
|
|
@ -28,9 +28,11 @@ internal static class EngineSettings
|
|||
private static bool _enableEngine = true;
|
||||
private static int _engineHookCount = int.MaxValue;
|
||||
private static bool _enableImGuiBackend = true;
|
||||
private static bool _enablePluginOverlayWindows = true;
|
||||
private static bool _enableHangMinidump = true;
|
||||
private static bool _preventIdleLogoff = true;
|
||||
private static bool _closeOnServerDisconnect = true;
|
||||
private static string _loggingLevel = "Info";
|
||||
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
|
||||
private static bool _decalInGameImGui = true;
|
||||
private static bool _decalStandDown = true;
|
||||
|
|
@ -48,6 +50,7 @@ internal static class EngineSettings
|
|||
// "ReportEndpoint": where "Report a problem" posts (Report/ProblemReport.cs); null = the built-in URL.
|
||||
// For testing only (https, or http to this PC); read only, like MaxHotReloads.
|
||||
private static string? _reportEndpoint;
|
||||
private static Compatibility.AutoIdMode _autoIdMode = Compatibility.AutoIdPolicy.DefaultMode;
|
||||
private static bool _loaded;
|
||||
|
||||
public static IReadOnlyList<string> PluginPaths
|
||||
|
|
@ -205,6 +208,19 @@ internal static class EngineSettings
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>When true (default) and the ImGui shell is off, plugins that export
|
||||
/// RynthPluginRenderOverlay draw their extra ImGui windows (RynthAi: ILT Hub, Item Info)
|
||||
/// beside the Avalonia UI. engine.json "EnablePluginOverlayWindows": false hides them.
|
||||
/// Needs <see cref="EnableImGuiBackend"/>.</summary>
|
||||
public static bool EnablePluginOverlayWindows
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _enablePluginOverlayWindows;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>When true, MainThreadHangWatchdog writes a minidump to
|
||||
/// Logs\dumps\ the first time AC's main thread is confirmed permanently
|
||||
/// wedged — a targeted post-mortem to replace always-on procdump (which
|
||||
|
|
@ -253,6 +269,18 @@ internal static class EngineSettings
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>Engine log threshold from engine.json "LoggingLevel", written by the launcher's
|
||||
/// Logging level box: Error, Warning, Info (default), Debug/Verbose or Trace. Parsed by
|
||||
/// EntryPoint.ParseLoggingLevel at init; unknown values fall back to Info.</summary>
|
||||
public static string LoggingLevel
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _loggingLevel;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"DecalBridge" in engine.json: Auto (default), On or Off. Only matters when
|
||||
/// Decal is loaded in the same client (docs/DECAL_BRIDGE_PLAN.md):
|
||||
/// Auto - bridge mode when the RynthCore Decal bridge is registered and says hello
|
||||
|
|
@ -418,6 +446,25 @@ internal static class EngineSettings
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>"AutoIdMode" in engine.json: "All", "Limited" (default) or "Off".
|
||||
/// Which background appraisals the engine's AutoId sends (Compatibility/AutoIdPolicy.cs);
|
||||
/// plugins' own RequestId calls are never limited by it. Set live with /rc autoid.</summary>
|
||||
public static Compatibility.AutoIdMode AutoIdMode
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _autoIdMode;
|
||||
}
|
||||
set
|
||||
{
|
||||
EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file
|
||||
if (_autoIdMode == value) return;
|
||||
_autoIdMode = value;
|
||||
Save();
|
||||
}
|
||||
}
|
||||
|
||||
public static void AddPluginPath(string path)
|
||||
{
|
||||
EnsureLoaded();
|
||||
|
|
@ -522,6 +569,12 @@ internal static class EngineSettings
|
|||
_enableImGuiBackend = ibEl.GetBoolean();
|
||||
}
|
||||
|
||||
if (doc.RootElement.TryGetProperty("EnablePluginOverlayWindows", out var powEl) &&
|
||||
(powEl.ValueKind == JsonValueKind.True || powEl.ValueKind == JsonValueKind.False))
|
||||
{
|
||||
_enablePluginOverlayWindows = powEl.GetBoolean();
|
||||
}
|
||||
|
||||
if (doc.RootElement.TryGetProperty("EnableHangMinidump", out var hmEl) &&
|
||||
(hmEl.ValueKind == JsonValueKind.True || hmEl.ValueKind == JsonValueKind.False))
|
||||
{
|
||||
|
|
@ -568,6 +621,11 @@ internal static class EngineSettings
|
|||
repEl.GetString() is { Length: > 0 } rep)
|
||||
_reportEndpoint = rep.Trim();
|
||||
|
||||
if (doc.RootElement.TryGetProperty("AutoIdMode", out var aimEl) &&
|
||||
aimEl.ValueKind == JsonValueKind.String &&
|
||||
Compatibility.AutoIdPolicy.TryParseMode(aimEl.GetString(), out Compatibility.AutoIdMode aim))
|
||||
_autoIdMode = aim;
|
||||
|
||||
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
|
||||
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
|
||||
{
|
||||
|
|
@ -595,6 +653,14 @@ internal static class EngineSettings
|
|||
_disabledUiHooks.Add(hookName.Trim());
|
||||
}
|
||||
}
|
||||
|
||||
if (doc.RootElement.TryGetProperty("LoggingLevel", out var logLevelEl) &&
|
||||
logLevelEl.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
string? configuredLevel = logLevelEl.GetString();
|
||||
if (!string.IsNullOrWhiteSpace(configuredLevel))
|
||||
_loggingLevel = configuredLevel;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -627,7 +693,7 @@ internal static class EngineSettings
|
|||
"EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge",
|
||||
"DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream",
|
||||
"FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix",
|
||||
"MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect",
|
||||
"MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "AutoIdMode", "EnablePluginOverlayWindows", "LoggingLevel",
|
||||
};
|
||||
|
||||
private static void Save()
|
||||
|
|
@ -653,8 +719,11 @@ internal static class EngineSettings
|
|||
w.WriteBoolean("EnableEngine", _enableEngine);
|
||||
w.WriteNumber("EngineHookCount", _engineHookCount);
|
||||
w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend);
|
||||
w.WriteBoolean("EnablePluginOverlayWindows", _enablePluginOverlayWindows);
|
||||
w.WriteBoolean("EnableHangMinidump", _enableHangMinidump);
|
||||
w.WriteBoolean("PreventIdleLogoff", _preventIdleLogoff);
|
||||
// Preserve the launcher-chosen level; dropping it here would reset logging to Info.
|
||||
w.WriteString("LoggingLevel", _loggingLevel);
|
||||
if (_decalBridgeMode != DecalBridgeMode.Auto) // default: leave the file as it was
|
||||
w.WriteString("DecalBridge", _decalBridgeMode.ToString());
|
||||
if (!_decalInGameImGui) // default true: leave the file as it was
|
||||
|
|
@ -684,6 +753,8 @@ internal static class EngineSettings
|
|||
w.WriteString("ReportEndpoint", _reportEndpoint);
|
||||
WriteStringList(w, "IltServerNames", _iltServerNames); // null (not in the file): left out
|
||||
WriteStringList(w, "IltHosts", _iltHosts);
|
||||
if (_autoIdMode != Compatibility.AutoIdPolicy.DefaultMode) // default: leave the file as it was
|
||||
w.WriteString("AutoIdMode", _autoIdMode.ToString());
|
||||
w.WriteEndObject();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -54,6 +54,18 @@ internal sealed class LoadedPlugin
|
|||
public PluginOnEnchantmentRemovedDelegate? OnEnchantmentRemoved { get; set; }
|
||||
public PluginTickDelegate? Tick { get; set; }
|
||||
public PluginRenderDelegate? Render { get; set; }
|
||||
/// <summary>Optional RynthPluginRenderOverlay: ImGui windows drawn while the ImGui shell is off.</summary>
|
||||
public PluginRenderDelegate? RenderOverlay { get; set; }
|
||||
|
||||
/// <summary>Set after the first RenderOverlay call has been logged (render thread only).</summary>
|
||||
public bool RenderOverlayLogged { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Optional <c>int RynthPluginRenderEmbed(const char* surface, float width, float height,
|
||||
/// float* wantWidth, float* wantHeight)</c>, Cdecl: the plugin draws a named surface into the
|
||||
/// engine's current ImGui window (PluginManager.RenderEmbed). Zeroed after it throws.
|
||||
/// </summary>
|
||||
public IntPtr RenderEmbedPtr { get; set; }
|
||||
|
||||
// ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ───
|
||||
public bool UiExportsResolved { get; set; }
|
||||
|
|
@ -85,4 +97,45 @@ internal sealed class LoadedPlugin
|
|||
public RynthCore.PluginSdk.Manifest.RynthPluginManifest? Manifest { get; set; }
|
||||
/// <summary>Why the plugin was not started (a required plugin missing or failed); empty otherwise.</summary>
|
||||
public string NotStartedReason { get; set; } = "";
|
||||
|
||||
/// <summary>
|
||||
/// Drops managed delegates wrapping exports so the native module can fully unload after
|
||||
/// the host calls FreeLibrary (hot-reload / rescan).
|
||||
/// </summary>
|
||||
internal void ClearResolvedDelegates()
|
||||
{
|
||||
Init = null;
|
||||
Shutdown = null;
|
||||
GetName = null;
|
||||
GetVersion = null;
|
||||
OnLoginComplete = null;
|
||||
OnUIInitialized = null;
|
||||
OnBusyCountIncremented = null;
|
||||
OnBusyCountDecremented = null;
|
||||
OnSelectedTargetChange = null;
|
||||
OnCombatModeChange = null;
|
||||
OnSmartBoxEventPtr = IntPtr.Zero;
|
||||
OnSmartBoxEvent = null;
|
||||
OnDeleteObject = null;
|
||||
OnCreateObject = null;
|
||||
OnUpdateObjectPtr = IntPtr.Zero;
|
||||
OnUpdateObject = null;
|
||||
OnUpdateObjectInventory = null;
|
||||
OnViewObjectContents = null;
|
||||
OnStopViewingObjectContents = null;
|
||||
OnVendorOpen = null;
|
||||
OnVendorClose = null;
|
||||
OnUpdateHealthPtr = IntPtr.Zero;
|
||||
OnUpdateHealth = null;
|
||||
OnChatWindowTextPtr = IntPtr.Zero;
|
||||
OnChatWindowText = null;
|
||||
OnChatBarEnter = null;
|
||||
OnBarAction = null;
|
||||
OnEnchantmentAdded = null;
|
||||
OnEnchantmentRemoved = null;
|
||||
Tick = null;
|
||||
Render = null;
|
||||
RenderOverlay = null;
|
||||
RenderEmbedPtr = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -146,10 +146,13 @@ internal static class ManagedPlugins
|
|||
if (retired.Contains(kv.Value)) Loaded.Remove(kv.Key);
|
||||
}
|
||||
#if ENGINE_CORECLR
|
||||
string vaBefore = retired.Count > 0 ? Compatibility.AddressSpace.Describe() : "";
|
||||
foreach (Entry e in retired)
|
||||
e.Context.Unload();
|
||||
// Context.Unload only starts the collection; "after" is right after the request, so the
|
||||
// NEXT reload's "va before" is where a context that never collects shows up.
|
||||
if (retired.Count > 0)
|
||||
RynthLog.Plugin($"ManagedPlugins: {retired.Count} plugin context(s) unloading: {string.Join(", ", retired.ConvertAll(e => e.Name))}.");
|
||||
RynthLog.Plugin($"ManagedPlugins: {retired.Count} plugin context(s) unloading: {string.Join(", ", retired.ConvertAll(e => e.Name))} (va before: {vaBefore}, after: {Compatibility.AddressSpace.Describe()}).");
|
||||
#endif
|
||||
}
|
||||
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue