Snapshot for release 2026.10.12.1 (internal ef4d41d)
This commit is contained in:
parent
08b80eed86
commit
b0f9d74b21
54 changed files with 5062 additions and 935 deletions
|
|
@ -984,11 +984,46 @@ internal static class AcMainThreadQueue
|
||||||
_castTargetId = targetId;
|
_castTargetId = targetId;
|
||||||
_castSpellId = spellId;
|
_castSpellId = spellId;
|
||||||
_castQueuedAt = NowMs;
|
_castQueuedAt = NowMs;
|
||||||
|
_castStopWaitNoted = false;
|
||||||
_castPending = 1;
|
_castPending = 1;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Casts that waited for a movement stop queued ahead of them (counted once per 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);
|
||||||
|
|
||||||
|
/// <summary>A movement stop (autorun off, a motion off, StopMovement, StopCompletely).</summary>
|
||||||
|
private static bool IsMovementStop(in Entry e) => e.Kind switch
|
||||||
|
{
|
||||||
|
ActionKind.SetAutoRun => e.A == 0,
|
||||||
|
ActionKind.SetMotion => e.B == 0,
|
||||||
|
ActionKind.StopMovement or ActionKind.StopCompletely => true,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <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.
|
||||||
|
/// </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;
|
||||||
|
}
|
||||||
|
|
||||||
// Drained on AC's MAIN thread from the Client::UseTime detour (game-logic tick).
|
// 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
|
// Re-invokes CombatActionHooks.CastSpell, which on the main thread executes the
|
||||||
// cast directly (SelectItem + ClientMagicSystem::CastSpell via the SEH trampoline).
|
// cast directly (SelectItem + ClientMagicSystem::CastSpell via the SEH trampoline).
|
||||||
|
|
@ -1028,6 +1063,62 @@ internal static class AcMainThreadQueue
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── A stop queued before the cast goes first (2026-10-12) ─────────────
|
||||||
|
// Casts drain here (Client::UseTime, before the tick), the action ring at EndScene,
|
||||||
|
// so an autorun-off or a motion-off the bot queued BEFORE its cast used to run AFTER
|
||||||
|
// it: the cast's FreeHandsAndCastSpell -> MaybeStopCompletely sent its stop with AC's
|
||||||
|
// 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 (castAge <= CastDeferMaxMs)
|
||||||
|
{
|
||||||
|
if (!_castStopWaitNoted)
|
||||||
|
{
|
||||||
|
_castStopWaitNoted = true;
|
||||||
|
Interlocked.Increment(ref _castStopWaits);
|
||||||
|
try { Net.FlightRecorder.Mark(Net.FlightMark.Note, text: "cast waits for a movement stop queued before it"); } catch { }
|
||||||
|
}
|
||||||
|
return; // retry next tick, after the ring drains
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── The stop goes a server answer ahead of the cast (2026-10-12, PreCastStopRules) ──
|
||||||
|
long castStamp = Volatile.Read(ref _castQueuedAt);
|
||||||
|
if (_preStopFor != castStamp) { _preStopFor = castStamp; _preStopSent = false; }
|
||||||
|
long nowMs = NowMs;
|
||||||
|
PreCastStep step = PreCastStopRules.Decide(
|
||||||
|
_preStopSent ? 0 : CommandInterpreterHooks.ReadControlledByServer(),
|
||||||
|
_preStopSent,
|
||||||
|
Interlocked.Read(ref _playerMotionEchoes) - _preStopEchoBase,
|
||||||
|
nowMs - _preStopAt);
|
||||||
|
if (step == PreCastStep.SendStop)
|
||||||
|
{
|
||||||
|
if (castAge <= CastDeferMaxMs)
|
||||||
|
{
|
||||||
|
_preStopEchoBase = Interlocked.Read(ref _playerMotionEchoes);
|
||||||
|
if (CommandInterpreterHooks.StopCompletely())
|
||||||
|
{
|
||||||
|
_preStopSent = true;
|
||||||
|
_preStopAt = nowMs;
|
||||||
|
Interlocked.Increment(ref _preCastStops);
|
||||||
|
try { Net.FlightRecorder.Mark(Net.FlightMark.Note, text: "pre-cast stop sent; the cast waits for the server's answer"); } catch { }
|
||||||
|
return; // cast on a later tick, after the answer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
step = PreCastStep.CastNow; // couldn't send it: cast as before
|
||||||
|
}
|
||||||
|
else if (step == PreCastStep.Wait)
|
||||||
|
{
|
||||||
|
if (castAge <= CastDeferMaxMs + PreCastStopRules.EchoMaxMs)
|
||||||
|
return;
|
||||||
|
step = PreCastStep.CastWithoutStop;
|
||||||
|
}
|
||||||
|
bool withoutStop = step == PreCastStep.CastWithoutStop;
|
||||||
|
if (withoutStop && Interlocked.Read(ref _playerMotionEchoes) == _preStopEchoBase)
|
||||||
|
Interlocked.Increment(ref _preCastEchoTimeouts);
|
||||||
|
|
||||||
uint target, spell;
|
uint target, spell;
|
||||||
lock (_castLock)
|
lock (_castLock)
|
||||||
{
|
{
|
||||||
|
|
@ -1038,6 +1129,23 @@ internal static class AcMainThreadQueue
|
||||||
}
|
}
|
||||||
if (castAge > LateActionLogMs)
|
if (castAge > LateActionLogMs)
|
||||||
NoteStale($"CastSpell({spell})", castAge, dropped: false);
|
NoteStale($"CastSpell({spell})", castAge, dropped: false);
|
||||||
CombatActionHooks.CastSpell(target, unchecked((int)spell));
|
CombatActionHooks.CastSpell(target, unchecked((int)spell), suppressMoveStop: withoutStop);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pre-cast stop state (main thread only).
|
||||||
|
private static long _preStopFor = long.MinValue;
|
||||||
|
private static bool _preStopSent;
|
||||||
|
private static long _preStopAt;
|
||||||
|
private static long _preStopEchoBase;
|
||||||
|
private static long _playerMotionEchoes;
|
||||||
|
private static long _preCastStops;
|
||||||
|
private static long _preCastEchoTimeouts;
|
||||||
|
|
||||||
|
/// <summary>Casts whose stop the engine sent ahead of them.</summary>
|
||||||
|
public static long PreCastStopCount => Interlocked.Read(ref _preCastStops);
|
||||||
|
/// <summary>Of those, casts that went without seeing the server's answer (EchoMaxMs ran out).</summary>
|
||||||
|
public static long PreCastEchoTimeoutCount => Interlocked.Read(ref _preCastEchoTimeouts);
|
||||||
|
|
||||||
|
/// <summary>An autonomous UpdateMotion for the player arrived (SmartBoxHooks, main thread).</summary>
|
||||||
|
public static void NotePlayerMotionEcho() => Interlocked.Increment(ref _playerMotionEchoes);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -928,6 +928,9 @@ internal static class ClientHelperHooks
|
||||||
// refreshed every EndScene by EngineFrameController, 0 = no player / not ready.
|
// refreshed every EndScene by EngineFrameController, 0 = no player / not ready.
|
||||||
private static int _cachedPlayerId;
|
private static int _cachedPlayerId;
|
||||||
|
|
||||||
|
/// <summary>The player id last read on the main thread (0 = none yet); no native call.</summary>
|
||||||
|
public static uint CachedPlayerId => unchecked((uint)Volatile.Read(ref _cachedPlayerId));
|
||||||
|
|
||||||
public static uint GetPlayerId()
|
public static uint GetPlayerId()
|
||||||
{
|
{
|
||||||
if (_getPlayerId == null)
|
if (_getPlayerId == null)
|
||||||
|
|
|
||||||
|
|
@ -474,7 +474,14 @@ internal static class CombatActionHooks
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool CastSpell(uint targetId, int spellId)
|
public static bool CastSpell(uint targetId, int spellId) => CastSpell(targetId, spellId, suppressMoveStop: false);
|
||||||
|
|
||||||
|
/// <param name="suppressMoveStop">
|
||||||
|
/// The engine already sent this cast's stop and the server answered it (AcMainThreadQueue
|
||||||
|
/// DrainCasts, PreCastStopRules): FreeHandsAndCastSpell's MaybeStopCompletely is made to send
|
||||||
|
/// nothing for the length of the call, so no stop rides in the cast's frame.
|
||||||
|
/// </param>
|
||||||
|
internal static bool CastSpell(uint targetId, int spellId, bool suppressMoveStop)
|
||||||
{
|
{
|
||||||
if (spellId <= 0) return false;
|
if (spellId <= 0) return false;
|
||||||
if (_castSpellClient == null) return false;
|
if (_castSpellClient == null) return false;
|
||||||
|
|
@ -543,7 +550,11 @@ internal static class CombatActionHooks
|
||||||
// busy leak. BusyCountHooks reconciles the delta once the cast
|
// busy leak. BusyCountHooks reconciles the delta once the cast
|
||||||
// gesture completes.
|
// gesture completes.
|
||||||
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
|
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
|
||||||
bool okCast = SehTrampoline.FreeHandsCast(_freeHandsCastPtr, mgr, (uint)spellId, targetId);
|
int savedCtl = 0;
|
||||||
|
IntPtr suppressed = suppressMoveStop ? CommandInterpreterHooks.BeginCastStopSuppression(out savedCtl) : IntPtr.Zero;
|
||||||
|
bool okCast;
|
||||||
|
try { okCast = SehTrampoline.FreeHandsCast(_freeHandsCastPtr, mgr, (uint)spellId, targetId); }
|
||||||
|
finally { if (suppressed != IntPtr.Zero) CommandInterpreterHooks.EndCastStopSuppression(suppressed, savedCtl); }
|
||||||
BusyCountHooks.NoteDirectCastIssued(busyBefore);
|
BusyCountHooks.NoteDirectCastIssued(busyBefore);
|
||||||
if (!okCast && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
|
if (!okCast && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
|
||||||
RynthLog.Compat($"[SEH] AV in FreeHandsAndCastSpell spell={spellId} target=0x{targetId:X8} — caught");
|
RynthLog.Compat($"[SEH] AV in FreeHandsAndCastSpell spell={spellId} target=0x{targetId:X8} — caught");
|
||||||
|
|
@ -560,7 +571,11 @@ internal static class CombatActionHooks
|
||||||
// buff self-casts were the dominant leak source (4322 plugin
|
// buff self-casts were the dominant leak source (4322 plugin
|
||||||
// clears / 10h soak, nearly all on buffs).
|
// clears / 10h soak, nearly all on buffs).
|
||||||
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
|
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
|
||||||
bool ok = SehTrampoline.CdeclVoidUintByte(_castSpellClientPtr, (uint)spellId, 0);
|
int savedCtl = 0;
|
||||||
|
IntPtr suppressed = suppressMoveStop ? CommandInterpreterHooks.BeginCastStopSuppression(out savedCtl) : IntPtr.Zero;
|
||||||
|
bool ok;
|
||||||
|
try { ok = SehTrampoline.CdeclVoidUintByte(_castSpellClientPtr, (uint)spellId, 0); }
|
||||||
|
finally { if (suppressed != IntPtr.Zero) CommandInterpreterHooks.EndCastStopSuppression(suppressed, savedCtl); }
|
||||||
BusyCountHooks.NoteDirectCastIssued(busyBefore);
|
BusyCountHooks.NoteDirectCastIssued(busyBefore);
|
||||||
if (!ok && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
|
if (!ok && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
|
||||||
RynthLog.Compat($"[SEH] AV in self-CastSpell spell={spellId} — caught");
|
RynthLog.Compat($"[SEH] AV in self-CastSpell spell={spellId} — caught");
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,19 @@ internal static class CommandInterpreterHooks
|
||||||
private const int TakeControlOffsetFromSetAutoRun = ReferenceCommandInterpreterTakeControlFromServer - ReferenceCommandInterpreterSetAutoRun;
|
private const int TakeControlOffsetFromSetAutoRun = ReferenceCommandInterpreterTakeControlFromServer - ReferenceCommandInterpreterSetAutoRun;
|
||||||
private const int ClearAllCommandsOffsetFromSetAutoRun = ReferenceCommandInterpreterClearAllCommands - ReferenceCommandInterpreterSetAutoRun;
|
private const int ClearAllCommandsOffsetFromSetAutoRun = ReferenceCommandInterpreterClearAllCommands - ReferenceCommandInterpreterSetAutoRun;
|
||||||
|
|
||||||
|
// CommandInterpreter::SendMovementEvent (vtable slot 19 = +0x4C, VA 0x006B55C0, thiscall,
|
||||||
|
// no args, plain ret): sends the current raw motion state to the server as a MoveToState
|
||||||
|
// (0xF61C). Bound from the live vtable and accepted only when it sits at the reference
|
||||||
|
// distance from SetAutoRun (same binary layout); otherwise it stays null and SetAutoRun
|
||||||
|
// behaves as before (no send).
|
||||||
|
private const int VtblSendMovementEventIndex = 19;
|
||||||
|
private const int ReferenceCommandInterpreterSendMovementEvent = 0x006B55C0;
|
||||||
|
private const int SendMovementEventOffsetFromSetAutoRun = ReferenceCommandInterpreterSendMovementEvent - ReferenceCommandInterpreterSetAutoRun;
|
||||||
|
|
||||||
|
// CommandInterpreter.autoRun (int): SetAutoRun(val, ...) compares and writes [this+0x48];
|
||||||
|
// ToggleAutoRun reads it (acclient 0x006B5790 / 0x006B4C00).
|
||||||
|
internal const int CmdInterpAutoRunOffset = 0x48;
|
||||||
|
|
||||||
// Verified unique + lands at the Reference VA offline (tools/pe_pattern.py).
|
// Verified unique + lands at the Reference VA offline (tools/pe_pattern.py).
|
||||||
// Primary resolution; the *Offset deltas below remain as fallback only.
|
// Primary resolution; the *Offset deltas below remain as fallback only.
|
||||||
private static readonly byte?[] SetMotionPattern = [ 0x8B, 0x41, 0x08, 0x81, 0xEC, 0x0C, 0x01, 0x00 ];
|
private static readonly byte?[] SetMotionPattern = [ 0x8B, 0x41, 0x08, 0x81, 0xEC, 0x0C, 0x01, 0x00 ];
|
||||||
|
|
@ -61,6 +74,9 @@ internal static class CommandInterpreterHooks
|
||||||
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||||
private delegate void ClearAllCommandsDelegate(IntPtr thisPtr);
|
private delegate void ClearAllCommandsDelegate(IntPtr thisPtr);
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
|
||||||
|
private delegate void SendMovementEventDelegate(IntPtr thisPtr);
|
||||||
|
|
||||||
private static IntPtr _smartboxStaticAddr;
|
private static IntPtr _smartboxStaticAddr;
|
||||||
private static IntPtr _boundCmdInterp;
|
private static IntPtr _boundCmdInterp;
|
||||||
private static bool _absResolved;
|
private static bool _absResolved;
|
||||||
|
|
@ -74,8 +90,15 @@ internal static class CommandInterpreterHooks
|
||||||
private static PlayerTeleportedDelegate? _playerTeleported;
|
private static PlayerTeleportedDelegate? _playerTeleported;
|
||||||
private static TakeControlFromServerDelegate? _takeControlFromServer;
|
private static TakeControlFromServerDelegate? _takeControlFromServer;
|
||||||
private static ClearAllCommandsDelegate? _clearAllCommands;
|
private static ClearAllCommandsDelegate? _clearAllCommands;
|
||||||
|
private static SendMovementEventDelegate? _sendMovementEvent;
|
||||||
|
private static bool _sendMovementEventMissLogged;
|
||||||
|
private static long _autoRunMovementSends;
|
||||||
private static string _statusMessage = "Not probed yet.";
|
private static string _statusMessage = "Not probed yet.";
|
||||||
|
|
||||||
|
/// <summary>MoveToStates sent after an autorun change (diagnostics).</summary>
|
||||||
|
public static long AutoRunMovementSends => System.Threading.Interlocked.Read(ref _autoRunMovementSends);
|
||||||
|
public static bool HasSendMovementEvent => _sendMovementEvent != null;
|
||||||
|
|
||||||
public static bool IsInitialized { get; private set; }
|
public static bool IsInitialized { get; private set; }
|
||||||
public static bool HasTapJump => _commenceJump != null && _doJump != null;
|
public static bool HasTapJump => _commenceJump != null && _doJump != null;
|
||||||
public static bool HasSetAutoRun => _setAutoRun != null;
|
public static bool HasSetAutoRun => _setAutoRun != null;
|
||||||
|
|
@ -152,9 +175,39 @@ internal static class CommandInterpreterHooks
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
// Tell the server, like AC's own autorun key and Decal's SetAutorun (2026-10-12).
|
||||||
|
// CommandInterpreter::SetAutoRun(val, applyMovement) only changes the LOCAL motion
|
||||||
|
// (MovePlayer -> DoMotion/StopMotion); it never sends a MoveToState. AC's autorun key
|
||||||
|
// (HandleKeyboardCommand 0x090000C7) is ToggleAutoRun + SendMovementEvent, and
|
||||||
|
// Decal's IACHooks::SetAutorun (Decal.dll 0x18025C10) is SetAutoRun(on, 1) followed by
|
||||||
|
// one more no-arg cmdinterp call. Without the send the server never learned that the
|
||||||
|
// bot started or stopped running: the client ran on AutonomousPositions alone, and the
|
||||||
|
// next SendMovementEvent - a SetMotion turn-off, or the cast's own
|
||||||
|
// FreeHandsAndCastSpell -> MaybeStopCompletely -> StopCompletely - delivered a burst
|
||||||
|
// of stops for a run the server had never seen (flight 63260, 12:27:44 / 12:35:55 /
|
||||||
|
// 12:38:56: every bad burst had no forward command; the harmless ones began with
|
||||||
|
// WalkForward). Sent only when AC's flag really changed: nav re-sends autorun every
|
||||||
|
// tick and AC ignores an unchanged value, so a send each time would spam the server.
|
||||||
|
int before = TryReadAutoRunFlag(_boundCmdInterp);
|
||||||
_setAutoRun!(_boundCmdInterp, enabled ? 1 : 0, 1);
|
_setAutoRun!(_boundCmdInterp, enabled ? 1 : 0, 1);
|
||||||
|
int after = TryReadAutoRunFlag(_boundCmdInterp);
|
||||||
|
bool sent = false;
|
||||||
|
if (before >= 0 && after >= 0 && before != after)
|
||||||
|
{
|
||||||
|
if (_sendMovementEvent != null)
|
||||||
|
{
|
||||||
|
_sendMovementEvent(_boundCmdInterp);
|
||||||
|
System.Threading.Interlocked.Increment(ref _autoRunMovementSends);
|
||||||
|
sent = true;
|
||||||
|
}
|
||||||
|
else if (!_sendMovementEventMissLogged)
|
||||||
|
{
|
||||||
|
_sendMovementEventMissLogged = true;
|
||||||
|
RynthLog.Compat("Move: SetAutoRun changed AC's autorun but SendMovementEvent is not bound - the server is not told (old behavior).");
|
||||||
|
}
|
||||||
|
}
|
||||||
if (ShouldLogMove(n))
|
if (ShouldLogMove(n))
|
||||||
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} -> ok (cmdInterp=0x{_boundCmdInterp.ToInt32():X8})");
|
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} -> ok (cmdInterp=0x{_boundCmdInterp.ToInt32():X8}, autorun {before}->{after}{(sent ? ", MoveToState sent" : "")})");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
|
|
@ -165,6 +218,55 @@ internal static class CommandInterpreterHooks
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CommandInterpreter.controlled_by_server (int, +0x34): LoseControlToServer sets it to 1,
|
||||||
|
// TakeControlFromServer to 0. MaybeStopCompletely (vtable +0xC0, 0x006B4AD0) - the first thing
|
||||||
|
// ClientMagicSystem::FreeHandsAndCastSpell (0x00567C90) does - calls StopCompletely (and so
|
||||||
|
// sends a MoveToState) only while it is 0, i.e. while the player has control.
|
||||||
|
internal const int CmdInterpControlledByServerOffset = 0x34;
|
||||||
|
|
||||||
|
/// <summary>1 the server has control (a cast sends no stop), 0 the player has (a cast sends one), -1 unknown. Main thread.</summary>
|
||||||
|
public static int ReadControlledByServer()
|
||||||
|
{
|
||||||
|
if (!MainThreadGuard.IsOnMainThread() || !TryBindDelegates()) return -1;
|
||||||
|
try { return Marshal.ReadInt32(_boundCmdInterp + CmdInterpControlledByServerOffset) != 0 ? 1 : 0; }
|
||||||
|
catch { return -1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// For the length of one cast call: makes MaybeStopCompletely see "server has control", so
|
||||||
|
/// FreeHandsAndCastSpell sends no stop in the cast's frame. Only for a cast whose stop the
|
||||||
|
/// engine already sent a server answer ahead (PreCastStop). Returns the command interpreter to
|
||||||
|
/// pass to <see cref="EndCastStopSuppression"/>, or Zero when nothing was changed.
|
||||||
|
/// </summary>
|
||||||
|
public static IntPtr BeginCastStopSuppression(out int saved)
|
||||||
|
{
|
||||||
|
saved = 0;
|
||||||
|
if (!MainThreadGuard.IsOnMainThread() || !TryBindDelegates()) return IntPtr.Zero;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
IntPtr ci = _boundCmdInterp;
|
||||||
|
saved = Marshal.ReadInt32(ci + CmdInterpControlledByServerOffset);
|
||||||
|
if (saved != 0) return IntPtr.Zero; // already no stop: nothing to do
|
||||||
|
Marshal.WriteInt32(ci + CmdInterpControlledByServerOffset, 1);
|
||||||
|
return ci;
|
||||||
|
}
|
||||||
|
catch { return IntPtr.Zero; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void EndCastStopSuppression(IntPtr cmdInterp, int saved)
|
||||||
|
{
|
||||||
|
if (cmdInterp == IntPtr.Zero || !MainThreadGuard.IsOnMainThread()) return;
|
||||||
|
try { Marshal.WriteInt32(cmdInterp + CmdInterpControlledByServerOffset, saved); } catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>AC's autorun flag (0/1), or -1 when it can't be read.</summary>
|
||||||
|
private static int TryReadAutoRunFlag(IntPtr cmdInterp)
|
||||||
|
{
|
||||||
|
if (cmdInterp == IntPtr.Zero) return -1;
|
||||||
|
try { return Marshal.ReadInt32(cmdInterp + CmdInterpAutoRunOffset) != 0 ? 1 : 0; }
|
||||||
|
catch { return -1; }
|
||||||
|
}
|
||||||
|
|
||||||
public static bool SetMotion(uint motion, bool enabled)
|
public static bool SetMotion(uint motion, bool enabled)
|
||||||
{
|
{
|
||||||
if (!MainThreadGuard.IsOnMainThread())
|
if (!MainThreadGuard.IsOnMainThread())
|
||||||
|
|
@ -461,6 +563,21 @@ internal static class CommandInterpreterHooks
|
||||||
_takeControlFromServer = Marshal.GetDelegateForFunctionPointer<TakeControlFromServerDelegate>(takeControlPtr);
|
_takeControlFromServer = Marshal.GetDelegateForFunctionPointer<TakeControlFromServerDelegate>(takeControlPtr);
|
||||||
_clearAllCommands = Marshal.GetDelegateForFunctionPointer<ClearAllCommandsDelegate>(clearAllCommandsPtr);
|
_clearAllCommands = Marshal.GetDelegateForFunctionPointer<ClearAllCommandsDelegate>(clearAllCommandsPtr);
|
||||||
|
|
||||||
|
// Optional: SendMovementEvent from the vtable, only at the reference distance from
|
||||||
|
// SetAutoRun. A miss leaves it null (SetAutoRun then sends nothing, as before) and never
|
||||||
|
// fails the binding of the others.
|
||||||
|
IntPtr sendMovementPtr = Marshal.ReadIntPtr(vtable, VtblSendMovementEventIndex * IntPtr.Size);
|
||||||
|
if (sendMovementPtr == AddOffset(setAutoRunPtr, SendMovementEventOffsetFromSetAutoRun)
|
||||||
|
&& SmartBoxLocator.IsPointerInModule(sendMovementPtr))
|
||||||
|
{
|
||||||
|
_sendMovementEvent = Marshal.GetDelegateForFunctionPointer<SendMovementEventDelegate>(sendMovementPtr);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_sendMovementEvent = null;
|
||||||
|
RynthLog.Compat($"Compat: CommandInterpreter::SendMovementEvent not bound (vtable slot {VtblSendMovementEventIndex} = 0x{sendMovementPtr.ToInt32():X8}, expected SetAutoRun{SendMovementEventOffsetFromSetAutoRun:+0;-0}) - autorun changes are not sent to the server.");
|
||||||
|
}
|
||||||
|
|
||||||
_smartboxStaticAddr = selectedStaticAddr;
|
_smartboxStaticAddr = selectedStaticAddr;
|
||||||
_boundCmdInterp = cmdInterp;
|
_boundCmdInterp = cmdInterp;
|
||||||
IsInitialized = true;
|
IsInitialized = true;
|
||||||
|
|
@ -496,6 +613,7 @@ internal static class CommandInterpreterHooks
|
||||||
_playerTeleported = null;
|
_playerTeleported = null;
|
||||||
_takeControlFromServer = null;
|
_takeControlFromServer = null;
|
||||||
_clearAllCommands = null;
|
_clearAllCommands = null;
|
||||||
|
_sendMovementEvent = null;
|
||||||
IsInitialized = false;
|
IsInitialized = false;
|
||||||
_statusMessage = "Not probed yet.";
|
_statusMessage = "Not probed yet.";
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -59,6 +59,9 @@ internal static class GameTickHooks
|
||||||
|
|
||||||
public static bool IsInstalled => Volatile.Read(ref _installed) != 0;
|
public static bool IsInstalled => Volatile.Read(ref _installed) != 0;
|
||||||
|
|
||||||
|
/// <summary>Client::UseTime returned 0: AC's game loop is exiting (any exit path).</summary>
|
||||||
|
public static bool GameLoopExiting => Volatile.Read(ref _exitLatch) != 0;
|
||||||
|
|
||||||
public static void Initialize()
|
public static void Initialize()
|
||||||
{
|
{
|
||||||
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
|
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
|
||||||
|
|
@ -203,6 +206,10 @@ internal static class GameTickHooks
|
||||||
// Flight recorder: per-second summary, stall detectors, scheduled automatic dump.
|
// Flight recorder: per-second summary, stall detectors, scheduled automatic dump.
|
||||||
try { Net.FlightRecorder.MainTick(); }
|
try { Net.FlightRecorder.MainTick(); }
|
||||||
catch { }
|
catch { }
|
||||||
|
// AC's "server has disconnected" screen: close the client after a short wait so a
|
||||||
|
// launcher can relaunch it (EngineSettings.CloseOnServerDisconnect).
|
||||||
|
try { ServerDisconnectClose.MainTick(); }
|
||||||
|
catch { }
|
||||||
|
|
||||||
// MUST return Client::UseTime's own bool — AC loops do/while on it.
|
// MUST return Client::UseTime's own bool — AC loops do/while on it.
|
||||||
return result;
|
return result;
|
||||||
|
|
|
||||||
51
src/RynthCore.Engine/Compatibility/PreCastStopRules.cs
Normal file
51
src/RynthCore.Engine/Compatibility/PreCastStopRules.cs
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
namespace RynthCore.Engine.Compatibility;
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// The stop before a cast goes a server answer ahead of the cast (2026-10-12).
|
||||||
|
//
|
||||||
|
// ClientMagicSystem::FreeHandsAndCastSpell (every cast path: ours, the UI's, Decal's
|
||||||
|
// ClientMagicSystem::CastSpell) starts with cmdinterp->MaybeStopCompletely(): while the player
|
||||||
|
// has control of the character (controlled_by_server == 0) that is StopCompletely, and so a
|
||||||
|
// MoveToState stop in the SAME frame as the CastTargetedSpell. Flight 63260: every run of
|
||||||
|
// projectile casts that never landed began with a stop burst in a cast's frame; ACE launches
|
||||||
|
// projectiles from its own physics copy of the caster, which such a frame can leave wrong.
|
||||||
|
//
|
||||||
|
// So, for a queued cast while the player has control, AcMainThreadQueue.DrainCasts:
|
||||||
|
// 1. sends the stop itself (CommandInterpreterHooks.StopCompletely) and does not cast;
|
||||||
|
// 2. waits for the server's answer to it - the next UpdateMotion for the player
|
||||||
|
// (SmartBoxHooks counts them) - or EchoMaxMs;
|
||||||
|
// 3. then casts with MaybeStopCompletely's stop suppressed (the state it would send is the
|
||||||
|
// one just sent and answered).
|
||||||
|
// With the server in control (after a cast's server turn: the usual case between casts) the
|
||||||
|
// cast sends no stop anyway and goes at once. Pure decision code (no AC access), so the tests
|
||||||
|
// in tools/PreCastStopTests compile it on its own.
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
internal enum PreCastStep
|
||||||
|
{
|
||||||
|
/// <summary>Cast now, as before (no stop would ride with it, or the state can't be read).</summary>
|
||||||
|
CastNow,
|
||||||
|
/// <summary>Send the pre-cast stop now; don't cast this tick.</summary>
|
||||||
|
SendStop,
|
||||||
|
/// <summary>The stop went out; wait for the server's answer.</summary>
|
||||||
|
Wait,
|
||||||
|
/// <summary>The stop was answered (or the wait ran out): cast, without the cast's own stop.</summary>
|
||||||
|
CastWithoutStop,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class PreCastStopRules
|
||||||
|
{
|
||||||
|
/// <summary>The longest a cast waits for the server's answer to its stop.</summary>
|
||||||
|
public const long EchoMaxMs = 750;
|
||||||
|
|
||||||
|
/// <param name="controlledByServer">1 server has control, 0 the player has, -1 unknown.</param>
|
||||||
|
/// <param name="stopSent">The pre-cast stop for this cast already went out.</param>
|
||||||
|
/// <param name="echoesSinceStop">Player UpdateMotions counted since the stop went out.</param>
|
||||||
|
/// <param name="msSinceStop">Milliseconds since the stop went out.</param>
|
||||||
|
public static PreCastStep Decide(int controlledByServer, bool stopSent, long echoesSinceStop, long msSinceStop)
|
||||||
|
{
|
||||||
|
if (stopSent)
|
||||||
|
return echoesSinceStop > 0 || msSinceStop >= EchoMaxMs ? PreCastStep.CastWithoutStop : PreCastStep.Wait;
|
||||||
|
return controlledByServer == 0 ? PreCastStep.SendStop : PreCastStep.CastNow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -77,6 +77,7 @@ namespace RynthCore.Engine.Compatibility;
|
||||||
/// the last minutes of client/server messages and engine markers) to
|
/// the last minutes of client/server messages and engine markers) to
|
||||||
/// Logs\flight-<pid>-<time>.txt; <c>/rc flightdump auto <reason></c> is the rate-limited
|
/// Logs\flight-<pid>-<time>.txt; <c>/rc flightdump auto <reason></c> is the rate-limited
|
||||||
/// automatic form. <c>/rc flight [status|mark <text>|on|off|auto on|off]</c>.</item>
|
/// automatic form. <c>/rc flight [status|mark <text>|on|off|auto on|off]</c>.</item>
|
||||||
|
/// <item><c>/rc quit</c> / <c>/rc exit</c> - closes the client cleanly, as its close button does.</item>
|
||||||
/// <item><c>/rc report [text]</c> - "Report a problem" (<see cref="Report.ProblemReport"/>): alone it
|
/// <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
|
/// 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>
|
/// (the panel is where the log can be left out). One report a minute.</item>
|
||||||
|
|
@ -254,6 +255,15 @@ internal static class RynthCoreChatCommands
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// /rc quit | /rc exit : close the client cleanly (as its close button; the character logs off)
|
||||||
|
if (IsVerb(sub, "quit", out _) || IsVerb(sub, "exit", out _))
|
||||||
|
{
|
||||||
|
Reply("Closing the client.");
|
||||||
|
try { ServerDisconnectClose.CloseClientNow("/rc quit"); }
|
||||||
|
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc quit failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
// /rc report [text] : Report a problem - alone it opens the panel; with text it sends now (with the log)
|
// /rc report [text] : Report a problem - alone it opens the panel; with text it sends now (with the log)
|
||||||
if (IsVerb(sub, "report", out string reportArgs))
|
if (IsVerb(sub, "report", out string reportArgs))
|
||||||
{
|
{
|
||||||
|
|
|
||||||
131
src/RynthCore.Engine/Compatibility/ServerDisconnectClose.cs
Normal file
131
src/RynthCore.Engine/Compatibility/ServerDisconnectClose.cs
Normal file
|
|
@ -0,0 +1,131 @@
|
||||||
|
// ============================================================================
|
||||||
|
// RynthCore.Engine - Compatibility/ServerDisconnectClose.cs
|
||||||
|
//
|
||||||
|
// Closes the client when AC lost the server (2026-10-11). AC then shows "The server
|
||||||
|
// has disconnected. Please try again in a few minutes." with only a Quit Game button,
|
||||||
|
// and the client sat there until someone clicked it, so no launcher relaunched it.
|
||||||
|
//
|
||||||
|
// Signal: UIFlow mode Disconnected (0x10000002, UiFlowHooks), which AC switches to only
|
||||||
|
// when the connection is gone. In the logs of 2026-10-05..11 it appears exactly at the
|
||||||
|
// eight drops (World -> Disconnected seven times, CharacterSelect -> Disconnected once)
|
||||||
|
// and never on a logout (World -> CharacterSelect) or a quit (no screen change). The
|
||||||
|
// other candidates were weaker: ClientNet::LogOffServer also runs on every quit (twice,
|
||||||
|
// from Client::Disconnect and Client::CleanupNet) and came up to 142 s after the screen;
|
||||||
|
// the logoff request AC sends (gmGamePlayUI::EndSession -> LogOffCharacter) looks like
|
||||||
|
// any other logoff.
|
||||||
|
//
|
||||||
|
// What it does (AC's main thread, GameTickHooks post-tick, so the mode poll just ran):
|
||||||
|
// - first tick on the screen: logs it and asks the flight recorder for a dump (the
|
||||||
|
// last minutes of traffic say whether the server went quiet or sent a disconnect);
|
||||||
|
// - after ServerDisconnectClosePolicy.DefaultDelayMs (5 s; longer while that dump is
|
||||||
|
// being written): posts WM_CLOSE to the game window, the same as its close button.
|
||||||
|
// That runs the normal shutdown: Win32Backend stops the plugin pump and starts
|
||||||
|
// EngineLifecycle.Shutdown, AC's UseTime returns 0 and the client exits with 0;
|
||||||
|
// - still open 20 s later: posts WM_CLOSE once more; 60 s later: says so and stops.
|
||||||
|
// Off (engine.json CloseOnServerDisconnect false, Settings > Misc): only the log line.
|
||||||
|
// Polled rather than evented, so a hot reload on the screen still closes the client.
|
||||||
|
// ============================================================================
|
||||||
|
using System;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using RynthCore.Engine.Plugins;
|
||||||
|
|
||||||
|
namespace RynthCore.Engine.Compatibility;
|
||||||
|
|
||||||
|
internal static class ServerDisconnectClose
|
||||||
|
{
|
||||||
|
private const uint WM_CLOSE = 0x0010;
|
||||||
|
|
||||||
|
[DllImport("user32.dll", SetLastError = true)]
|
||||||
|
private static extern bool PostMessageW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||||
|
|
||||||
|
[DllImport("user32.dll")]
|
||||||
|
private static extern bool IsWindow(IntPtr hWnd);
|
||||||
|
|
||||||
|
private static readonly ServerDisconnectClosePolicy Policy = new();
|
||||||
|
private static int _fromMode;
|
||||||
|
|
||||||
|
/// <summary>AC's main thread, every game tick (GameTickHooks, after the queue drain).</summary>
|
||||||
|
public static void MainTick()
|
||||||
|
{
|
||||||
|
int mode = UiFlowHooks.CurrentMode;
|
||||||
|
bool disconnected = mode == UiFlowHooks.ModeDisconnected;
|
||||||
|
if (!disconnected && !Policy.OnScreen)
|
||||||
|
return; // the common case: two reads and out
|
||||||
|
|
||||||
|
long now = Environment.TickCount64;
|
||||||
|
bool exiting = GameTickHooks.GameLoopExiting || UiFlowHooks.ClientCleanupStarted || EngineThreads.Stopping;
|
||||||
|
bool enabled = EngineSettings.CloseOnServerDisconnect;
|
||||||
|
bool dumpBusy = false;
|
||||||
|
try { dumpBusy = Net.FlightRecorder.DumpPendingOrRunning; } catch { }
|
||||||
|
|
||||||
|
long onScreenMs = Policy.OnScreenMs(now);
|
||||||
|
switch (Policy.Update(now, disconnected, enabled, exiting, dumpBusy))
|
||||||
|
{
|
||||||
|
case ServerDisconnectClosePolicy.Verdict.Detected:
|
||||||
|
OnDetected(enabled);
|
||||||
|
break;
|
||||||
|
case ServerDisconnectClosePolicy.Verdict.Close:
|
||||||
|
PostClose($"closing the client after {onScreenMs / 1000.0:0.0}s on the Disconnected screen{(dumpBusy ? " (waited for the flight dump)" : "")}");
|
||||||
|
break;
|
||||||
|
case ServerDisconnectClosePolicy.Verdict.Retry:
|
||||||
|
PostClose($"the client is still open {ServerDisconnectClosePolicy.RetryAfterMs / 1000}s after WM_CLOSE - sending it again");
|
||||||
|
break;
|
||||||
|
case ServerDisconnectClosePolicy.Verdict.GiveUp:
|
||||||
|
RynthLog.Error($"ServerDisconnect: the client is still open {ServerDisconnectClosePolicy.GiveUpAfterMs / 1000}s after WM_CLOSE (sent twice) - not trying again. Click Quit Game.");
|
||||||
|
break;
|
||||||
|
case ServerDisconnectClosePolicy.Verdict.Left:
|
||||||
|
RynthLog.Warn($"ServerDisconnect: the Disconnected screen went away after {onScreenMs / 1000.0:0.0}s (now {UiFlowHooks.ModeName(mode)}) before the client closed.");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void OnDetected(bool enabled)
|
||||||
|
{
|
||||||
|
_fromMode = UiFlowHooks.PreviousMode;
|
||||||
|
string who = DescribeSession();
|
||||||
|
string action = enabled
|
||||||
|
? $"closing the client in {Policy.DelayMs / 1000}s so a launcher can relaunch it (Close on server disconnect, Settings > Misc)"
|
||||||
|
: "Close on server disconnect is off (Settings > Misc) - the client stays on this screen";
|
||||||
|
RynthLog.Warn($"ServerDisconnect: AC lost the server and shows its 'server has disconnected' screen ({UiFlowHooks.ModeName(_fromMode)} -> Disconnected){who}; {action}.");
|
||||||
|
try { Net.FlightRecorder.RequestAuto("server disconnect (the Disconnected screen)", "engine"); }
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string DescribeSession()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string ch = SessionStateRegistry.LastCharacterName;
|
||||||
|
string acct = SessionStateRegistry.LastAccountName;
|
||||||
|
string world = AccountHooks.AnnouncedWorldName ?? SessionStateRegistry.LastServerName;
|
||||||
|
if (string.IsNullOrEmpty(ch) && string.IsNullOrEmpty(acct) && string.IsNullOrEmpty(world))
|
||||||
|
return "";
|
||||||
|
return $" - {(string.IsNullOrEmpty(ch) ? "?" : ch)} ({(string.IsNullOrEmpty(acct) ? "?" : acct)}) on {(string.IsNullOrEmpty(world) ? "?" : world)}";
|
||||||
|
}
|
||||||
|
catch { return ""; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Closes the client now, the way its close button does (WM_CLOSE: AC logs the character
|
||||||
|
/// off and the engine shuts down normally). /rc quit, and RynthAi's /ra, /mt and /ub quit.
|
||||||
|
/// </summary>
|
||||||
|
public static void CloseClientNow(string why) => PostClose(why);
|
||||||
|
|
||||||
|
private static void PostClose(string why)
|
||||||
|
{
|
||||||
|
IntPtr hwnd = ImGuiBackend.Win32Backend.GameHwnd;
|
||||||
|
if (hwnd == IntPtr.Zero || !IsWindow(hwnd))
|
||||||
|
{
|
||||||
|
try { hwnd = Process.GetCurrentProcess().MainWindowHandle; } catch { hwnd = IntPtr.Zero; }
|
||||||
|
}
|
||||||
|
if (hwnd == IntPtr.Zero)
|
||||||
|
{
|
||||||
|
RynthLog.Error($"ServerDisconnect: {why}, but the game window isn't known - can't close the client.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bool ok = PostMessageW(hwnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
|
||||||
|
int err = ok ? 0 : Marshal.GetLastWin32Error();
|
||||||
|
RynthLog.Warn($"ServerDisconnect: {why} - WM_CLOSE to 0x{hwnd.ToInt64():X} {(ok ? "posted" : $"FAILED (Win32 error {err})")}.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,112 @@
|
||||||
|
// ============================================================================
|
||||||
|
// RynthCore.Engine - Compatibility/ServerDisconnectClosePolicy.cs
|
||||||
|
//
|
||||||
|
// When to close the client after AC lost the server (ServerDisconnectClose.cs does
|
||||||
|
// the closing). No engine dependencies: tools/DisconnectCloseTests compiles this file.
|
||||||
|
//
|
||||||
|
// Fed once per game tick with the clock and what the engine sees:
|
||||||
|
// - disconnected: AC's UIFlow mode is Disconnected (0x10000002), the screen that says
|
||||||
|
// "The server has disconnected. Please try again in a few minutes." with only a
|
||||||
|
// Quit Game button. AC switches to it only when the connection is gone; a logout
|
||||||
|
// goes to character select and a quit never changes the screen.
|
||||||
|
// - enabled: engine.json CloseOnServerDisconnect.
|
||||||
|
// - exiting: the client is already closing (UseTime returned 0 / Client::Cleanup).
|
||||||
|
// - dumpBusy: the flight recorder is writing (or about to write) its dump of the
|
||||||
|
// disconnect; the close waits for it, up to DumpGraceMs more.
|
||||||
|
//
|
||||||
|
// Answers, at most once each per visit to the screen:
|
||||||
|
// Detected - first tick on the screen (log it, ask for a flight dump);
|
||||||
|
// Close - DelayMs on the screen: close the client (WM_CLOSE);
|
||||||
|
// Retry - RetryAfterMs after Close and still here: close again;
|
||||||
|
// GiveUp - GiveUpAfterMs after Close and still here: say so, stop trying;
|
||||||
|
// Left - the screen went away before the client closed (start over next time).
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
namespace RynthCore.Engine.Compatibility;
|
||||||
|
|
||||||
|
internal sealed class ServerDisconnectClosePolicy
|
||||||
|
{
|
||||||
|
public const long DefaultDelayMs = 5000;
|
||||||
|
public const long DumpGraceMs = 10000;
|
||||||
|
public const long RetryAfterMs = 20000;
|
||||||
|
public const long GiveUpAfterMs = 60000;
|
||||||
|
|
||||||
|
public enum Verdict { None, Detected, Close, Retry, GiveUp, Left }
|
||||||
|
|
||||||
|
private readonly long _delayMs;
|
||||||
|
private long _sinceMs; // when the screen was first seen; 0 = not on it
|
||||||
|
private long _closedAtMs; // when Close was answered; 0 = not yet
|
||||||
|
private int _attempts; // Close + Retry answers this visit
|
||||||
|
private bool _gaveUp;
|
||||||
|
|
||||||
|
public ServerDisconnectClosePolicy(long delayMs = DefaultDelayMs)
|
||||||
|
{
|
||||||
|
_delayMs = delayMs < 0 ? 0 : delayMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long DelayMs => _delayMs;
|
||||||
|
|
||||||
|
/// <summary>On the Disconnected screen (as of the last Update).</summary>
|
||||||
|
public bool OnScreen => _sinceMs != 0;
|
||||||
|
|
||||||
|
/// <summary>Milliseconds on the screen as of <paramref name="nowMs"/>, 0 when not on it.</summary>
|
||||||
|
public long OnScreenMs(long nowMs) => _sinceMs == 0 ? 0 : nowMs - _sinceMs;
|
||||||
|
|
||||||
|
public int Attempts => _attempts;
|
||||||
|
|
||||||
|
public Verdict Update(long nowMs, bool disconnected, bool enabled, bool exiting, bool dumpBusy)
|
||||||
|
{
|
||||||
|
if (exiting)
|
||||||
|
return Verdict.None;
|
||||||
|
|
||||||
|
if (!disconnected)
|
||||||
|
{
|
||||||
|
if (_sinceMs == 0)
|
||||||
|
return Verdict.None;
|
||||||
|
Reset();
|
||||||
|
return Verdict.Left;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_sinceMs == 0)
|
||||||
|
{
|
||||||
|
_sinceMs = nowMs == 0 ? 1 : nowMs;
|
||||||
|
return Verdict.Detected;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!enabled)
|
||||||
|
return Verdict.None;
|
||||||
|
|
||||||
|
long onScreen = nowMs - _sinceMs;
|
||||||
|
if (_attempts == 0)
|
||||||
|
{
|
||||||
|
if (onScreen < _delayMs)
|
||||||
|
return Verdict.None;
|
||||||
|
if (dumpBusy && onScreen < _delayMs + DumpGraceMs)
|
||||||
|
return Verdict.None;
|
||||||
|
_attempts = 1;
|
||||||
|
_closedAtMs = nowMs;
|
||||||
|
return Verdict.Close;
|
||||||
|
}
|
||||||
|
|
||||||
|
long sinceClose = nowMs - _closedAtMs;
|
||||||
|
if (_attempts == 1 && sinceClose >= RetryAfterMs)
|
||||||
|
{
|
||||||
|
_attempts = 2;
|
||||||
|
return Verdict.Retry;
|
||||||
|
}
|
||||||
|
if (!_gaveUp && sinceClose >= GiveUpAfterMs)
|
||||||
|
{
|
||||||
|
_gaveUp = true;
|
||||||
|
return Verdict.GiveUp;
|
||||||
|
}
|
||||||
|
return Verdict.None;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Reset()
|
||||||
|
{
|
||||||
|
_sinceMs = 0;
|
||||||
|
_closedAtMs = 0;
|
||||||
|
_attempts = 0;
|
||||||
|
_gaveUp = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -131,6 +131,8 @@ internal static class SmartBoxHooks
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
if (info.Opcode == PositionUpdateOpcode && info.RawObjectId != 0)
|
||||||
|
NotePlayerMotionEcho(blob, info);
|
||||||
TryQueueHealthUpdate(blob, info);
|
TryQueueHealthUpdate(blob, info);
|
||||||
TryQueueDamageEvent(blob, info);
|
TryQueueDamageEvent(blob, info);
|
||||||
|
|
||||||
|
|
@ -671,6 +673,24 @@ internal static class SmartBoxHooks
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateMotion (0xF74C) for the player with the autonomous flag set: the server's answer to a
|
||||||
|
// MoveToState from this client (layout: opcode, guid, u16 instance, u16 movement seq, u16
|
||||||
|
// server-control seq, u8 autonomous at +14). Counted for the pre-cast stop (PreCastStopRules).
|
||||||
|
private static void NotePlayerMotionEcho(IntPtr blob, SmartBoxEventInfo info)
|
||||||
|
{
|
||||||
|
if (info.BlobSize < 16) return;
|
||||||
|
uint player = ClientHelperHooks.CachedPlayerId;
|
||||||
|
if (player == 0 || info.RawObjectId != player) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
|
||||||
|
if (payloadPtr == IntPtr.Zero) return;
|
||||||
|
if (Marshal.ReadByte(IntPtr.Add(payloadPtr, 14)) != 0)
|
||||||
|
AcMainThreadQueue.NotePlayerMotionEcho();
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
private static void TryQueueHealthUpdate(IntPtr blob, SmartBoxEventInfo info)
|
private static void TryQueueHealthUpdate(IntPtr blob, SmartBoxEventInfo info)
|
||||||
{
|
{
|
||||||
if (info.Opcode != 0x01C0 || info.BlobSize < 12 || blob == IntPtr.Zero)
|
if (info.Opcode != 0x01C0 || info.BlobSize < 12 || blob == IntPtr.Zero)
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,9 @@
|
||||||
// Same content as the Avalonia bar, as square Phosphor icon buttons with
|
// Same content as the Avalonia bar, as square Phosphor icon buttons with
|
||||||
// the names in tooltips: the grip (RC: build stamp tooltip), one button per
|
// the names in tooltips: the grip (RC: build stamp tooltip), one button per
|
||||||
// registered panel except the ones the RynthAi launcher opens (PanelIcons;
|
// registered panel except the ones the RynthAi launcher opens (PanelIcons;
|
||||||
// an unknown panel shows its first letter), reload (RL) and pop out.
|
// an unknown panel shows its first letter), one per plugin script window that
|
||||||
|
// asked for a button (WindowFlags.BarButton: RynthSort, Oracle, ...; tooltip =
|
||||||
|
// its title; the set is rebuilt as plugins come and go), reload (RL) and pop out.
|
||||||
// Dragging the grip moves the bar; the position is the shared bar= row in
|
// Dragging the grip moves the bar; the position is the shared bar= row in
|
||||||
// panel_state.txt. Right-click a panel button (or the grip for the bar
|
// panel_state.txt. Right-click a panel button (or the grip for the bar
|
||||||
// itself) to choose which face shows it docked; the grip's menu also has the
|
// itself) to choose which face shows it docked; the grip's menu also has the
|
||||||
|
|
@ -48,8 +50,10 @@ internal static class ImGuiBar
|
||||||
private static readonly PanelFace[] Faces = { PanelFace.Avalonia, PanelFace.ImGui, PanelFace.Both };
|
private static readonly PanelFace[] Faces = { PanelFace.Avalonia, PanelFace.ImGui, PanelFace.Both };
|
||||||
private static readonly string[] FaceNames = { "Avalonia", "ImGui", "Both (side by side)" };
|
private static readonly string[] FaceNames = { "Avalonia", "ImGui", "Both (side by side)" };
|
||||||
|
|
||||||
|
// Window: a plugin's script window with a bar button of its own (WindowFlags.BarButton);
|
||||||
|
// the button toggles it through ScriptWindowRegistry, like the Scripts menu does.
|
||||||
private sealed record ButtonInfo(string Title, string Id, string PopupId, string Icon, bool Letter, string Tooltip,
|
private sealed record ButtonInfo(string Title, string Id, string PopupId, string Icon, bool Letter, string Tooltip,
|
||||||
bool ImGuiOnly = false);
|
bool ImGuiOnly = false, ScriptWindow? Window = null);
|
||||||
|
|
||||||
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
|
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
|
||||||
private static readonly string[] ImGuiOnlyBarPanels =
|
private static readonly string[] ImGuiOnlyBarPanels =
|
||||||
|
|
@ -84,6 +88,10 @@ internal static class ImGuiBar
|
||||||
["Log"] = PhosphorIcons.TerminalWindow,
|
["Log"] = PhosphorIcons.TerminalWindow,
|
||||||
["Item Count"] = PhosphorIcons.Bag,
|
["Item Count"] = PhosphorIcons.Bag,
|
||||||
["Mini Remote"] = PhosphorIcons.SquaresFour,
|
["Mini Remote"] = PhosphorIcons.SquaresFour,
|
||||||
|
// Plugin windows with a bar button of their own (script windows, by title).
|
||||||
|
["RynthSort"] = PhosphorIcons.SortAscending,
|
||||||
|
["Oracle"] = PhosphorIcons.Sparkle,
|
||||||
|
["Global Inventory"] = PhosphorIcons.GlobeHemisphereWest,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>A panel's bar icon: its Phosphor icon, else its first letter (letter = true).</summary>
|
/// <summary>A panel's bar icon: its Phosphor icon, else its first letter (letter = true).</summary>
|
||||||
|
|
@ -111,6 +119,10 @@ internal static class ImGuiBar
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ButtonInfo[]? _buttons;
|
private static ButtonInfo[]? _buttons;
|
||||||
|
// What _buttons was built from: the plugin windows' snapshot (a new array on every change)
|
||||||
|
// and which ImGui-only panels had a face. Either changing rebuilds the buttons.
|
||||||
|
private static ScriptBarItem[]? _builtScriptButtons;
|
||||||
|
private static int _builtImGuiOnlyMask;
|
||||||
private static string _tooltip = "";
|
private static string _tooltip = "";
|
||||||
private static bool _placed;
|
private static bool _placed;
|
||||||
private static Vector2 _pos, _persistedPos;
|
private static Vector2 _pos, _persistedPos;
|
||||||
|
|
@ -366,8 +378,11 @@ internal static class ImGuiBar
|
||||||
{
|
{
|
||||||
ImGuiNET.ImGui.SameLine();
|
ImGuiNET.ImGui.SameLine();
|
||||||
if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText))
|
if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText))
|
||||||
PanelRouter.Toggle(b.Title);
|
{
|
||||||
ImGuiNET.ImGui.SetItemTooltip(b.Tooltip);
|
if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !ImGuiPanelHost.IsOpen(b.Window.PanelKey));
|
||||||
|
else PanelRouter.Toggle(b.Title);
|
||||||
|
}
|
||||||
|
ImGuiNET.ImGui.SetItemTooltip(b.Tooltip); // a plugin window's title arrives with '%' doubled (EnsureButtons)
|
||||||
if (b.ImGuiOnly) continue; // no Avalonia face: no face to choose
|
if (b.ImGuiOnly) continue; // no Avalonia face: no face to choose
|
||||||
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
|
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
|
||||||
ImGuiNET.ImGui.OpenPopup(b.PopupId);
|
ImGuiNET.ImGui.OpenPopup(b.PopupId);
|
||||||
|
|
@ -390,8 +405,8 @@ internal static class ImGuiBar
|
||||||
}
|
}
|
||||||
|
|
||||||
// Script windows (decision 2): one button with a menu, only while a ShowInBar
|
// Script windows (decision 2): one button with a menu, only while a ShowInBar
|
||||||
// script window exists. They never get buttons of their own (EnsureButtons
|
// script window exists. A window that also sets BarButton (plugin windows such as
|
||||||
// lists OverlayHost's engine panels only; script windows are dynamic entries).
|
// RynthSort's) has a button of its own instead (EnsureButtons) and isn't listed here.
|
||||||
ScriptBarItem[] scripts = ScriptWindowRegistry.BarItems;
|
ScriptBarItem[] scripts = ScriptWindowRegistry.BarItems;
|
||||||
if (scripts.Length > 0)
|
if (scripts.Length > 0)
|
||||||
{
|
{
|
||||||
|
|
@ -591,9 +606,27 @@ internal static class ImGuiBar
|
||||||
ImGuiNET.ImGui.PopStyleVar(3);
|
ImGuiNET.ImGui.PopStyleVar(3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Bit i set: ImGuiOnlyBarPanels[i] has a face now.</summary>
|
||||||
|
private static int ImGuiOnlyMask()
|
||||||
|
{
|
||||||
|
int mask = 0;
|
||||||
|
for (int i = 0; i < ImGuiOnlyBarPanels.Length; i++)
|
||||||
|
if (ImGuiPanelHost.HasFace(ImGuiOnlyBarPanels[i])) mask |= 1 << i;
|
||||||
|
return mask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The bar's buttons, rebuilt when the set changes: a plugin window with a bar button
|
||||||
|
/// appeared, went (plugin unloaded, window dropped) or was renamed, or an ImGui-only
|
||||||
|
/// panel's face was registered or removed. AC thread, every frame (two cheap checks).
|
||||||
|
/// </summary>
|
||||||
private static void EnsureButtons()
|
private static void EnsureButtons()
|
||||||
{
|
{
|
||||||
if (_buttons != null) return;
|
ScriptBarItem[] scriptButtons = ScriptWindowRegistry.BarButtons;
|
||||||
|
int mask = ImGuiOnlyMask();
|
||||||
|
if (_buttons != null && ReferenceEquals(scriptButtons, _builtScriptButtons) && mask == _builtImGuiOnlyMask) return;
|
||||||
|
_builtScriptButtons = scriptButtons;
|
||||||
|
_builtImGuiOnlyMask = mask;
|
||||||
var list = new List<ButtonInfo>();
|
var list = new List<ButtonInfo>();
|
||||||
foreach (var (title, _) in OverlayHost.GetPanels())
|
foreach (var (title, _) in OverlayHost.GetPanels())
|
||||||
if (!LauncherOnly.Contains(title))
|
if (!LauncherOnly.Contains(title))
|
||||||
|
|
@ -608,6 +641,17 @@ internal static class ImGuiBar
|
||||||
string icon = IconFor(title, out bool letter);
|
string icon = IconFor(title, out bool letter);
|
||||||
list.Add(new ButtonInfo(title, "##bar_" + title, "##face_" + title, icon, letter, title, ImGuiOnly: true));
|
list.Add(new ButtonInfo(title, "##bar_" + title, "##face_" + title, icon, letter, title, ImGuiOnly: true));
|
||||||
}
|
}
|
||||||
|
// Plugin script windows that asked for a button (RynthSort, Oracle, ...): after the
|
||||||
|
// engine's own. Only while the plugin is loaded and has submitted the window.
|
||||||
|
foreach (ScriptBarItem item in scriptButtons)
|
||||||
|
{
|
||||||
|
ScriptWindow w = item.Window;
|
||||||
|
string title = w.Title.Length > 0 ? w.Title : w.Key;
|
||||||
|
string icon = IconFor(title, out bool letter);
|
||||||
|
string id = "##bar_sw" + w.Hash.ToString("X8");
|
||||||
|
// The tooltip goes through SetItemTooltip, a format function: the plugin's text with '%' doubled.
|
||||||
|
list.Add(new ButtonInfo(title, id, id + "_face", icon, letter, title.Replace("%", "%%"), ImGuiOnly: true, Window: w));
|
||||||
|
}
|
||||||
_buttons = list.ToArray();
|
_buttons = list.ToArray();
|
||||||
_tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar face and size. Ctrl+wheel over the bar: size.";
|
_tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar face and size. Ctrl+wheel over the bar: size.";
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -65,6 +65,7 @@ internal static unsafe class ImGuiFonts
|
||||||
// dashes are in MainRanges.
|
// dashes are in MainRanges.
|
||||||
private static readonly ushort[] SymbolCodepoints =
|
private static readonly ushort[] SymbolCodepoints =
|
||||||
{
|
{
|
||||||
|
0x2264, 0x2265, // ≤ ≥ (Meta rule list: "Prismatic Taper ≤ 50")
|
||||||
0x25CF, // ● (Meta source: unapplied edits)
|
0x25CF, // ● (Meta source: unapplied edits)
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,11 @@
|
||||||
// from it: move / copy lines like it to a tab, hide them, colour them. A line
|
// from it: move / copy lines like it to a tab, hide them, colour them. A line
|
||||||
// with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go
|
// with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go
|
||||||
// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them).
|
// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them).
|
||||||
// Follows the newest line until you scroll up.
|
// Follows the newest line until you scroll up; the scroll for new lines is set
|
||||||
|
// in the same frame they're drawn (DrawLines; until 2026-10-11 it landed a frame
|
||||||
|
// late and the text bounced). Scrolled up, the view holds still. The history is
|
||||||
|
// as long as the "Chat history" setting (ChatHistory, up to 10,000 lines): no
|
||||||
|
// per-frame work walks all of it, and re-measuring after a resize is time-sliced.
|
||||||
//
|
//
|
||||||
// The input line belongs to ChatModel (UI/Data/ChatData.cs): Win32Backend
|
// The input line belongs to ChatModel (UI/Data/ChatData.cs): Win32Backend
|
||||||
// turns the chat keys into ChatModel edits on AC's thread, which is also
|
// turns the chat keys into ChatModel edits on AC's thread, which is also
|
||||||
|
|
@ -74,7 +78,11 @@ internal sealed class ChatFace : IImGuiPanel
|
||||||
private readonly List<float> _h = new(512);
|
private readonly List<float> _h = new(512);
|
||||||
private readonly List<SpanLayout?> _lay = new(512);
|
private readonly List<SpanLayout?> _lay = new(512);
|
||||||
private float[] _tops = new float[1];
|
private float[] _tops = new float[1];
|
||||||
private int _heightsFrom; // first line whose height needs measuring
|
private int _heightsFrom; // first new line: not measured at all yet
|
||||||
|
// Lines below this index were measured for another width or font, or not at all (a
|
||||||
|
// rebuild gives them one row each until then): MeasureLines catches up a few ms a frame.
|
||||||
|
private int _measuredFrom;
|
||||||
|
private float _rowH = 13f; // one row of the chat font: an unmeasured line's height
|
||||||
private bool _topsDirty = true;
|
private bool _topsDirty = true;
|
||||||
private long _seenLinesVersion = -1, _seenRoutes = -1, _lastId;
|
private long _seenLinesVersion = -1, _seenRoutes = -1, _lastId;
|
||||||
private string _seenTab = "", _seenSearch = "";
|
private string _seenTab = "", _seenSearch = "";
|
||||||
|
|
@ -88,6 +96,13 @@ internal sealed class ChatFace : IImGuiPanel
|
||||||
// tail: the view is moved up by as much, so the lines being read stay put instead of
|
// tail: the view is moved up by as much, so the lines being read stay put instead of
|
||||||
// sliding away.
|
// sliding away.
|
||||||
private float _droppedAbove;
|
private float _droppedAbove;
|
||||||
|
// The part of a dropped-lines move ImGui's whole-pixel scroll couldn't take, carried
|
||||||
|
// into the next one (heights can be fractional at some DPI scales).
|
||||||
|
private float _scrollCarry;
|
||||||
|
// The list's scrollbar width (always shown), and a correction to the list width
|
||||||
|
// DrawLines works out before its BeginChild, should the child ever report another.
|
||||||
|
private const float ListScrollbarW = 10f;
|
||||||
|
private float _wrapFix;
|
||||||
private float _inputScroll;
|
private float _inputScroll;
|
||||||
|
|
||||||
// Selection: indices into _vis.
|
// Selection: indices into _vis.
|
||||||
|
|
@ -100,12 +115,14 @@ internal sealed class ChatFace : IImGuiPanel
|
||||||
// Unread lines per tab since it was last on screen (Id of the newest line seen there).
|
// Unread lines per tab since it was last on screen (Id of the newest line seen there).
|
||||||
private readonly Dictionary<string, long> _seenId = new(StringComparer.OrdinalIgnoreCase);
|
private readonly Dictionary<string, long> _seenId = new(StringComparer.OrdinalIgnoreCase);
|
||||||
private readonly Dictionary<string, (int Count, bool Mention)> _unread = new(StringComparer.OrdinalIgnoreCase);
|
private readonly Dictionary<string, (int Count, bool Mention)> _unread = new(StringComparer.OrdinalIgnoreCase);
|
||||||
private long _unreadLines = -1, _unreadRoutes = -1, _unreadTabsVersion = -1;
|
private long _unreadLines = -1, _unreadRoutes = -1, _unreadTabsVersion = -1, _unreadCountedTo;
|
||||||
private string _unreadTab = "";
|
private string _unreadTab = "";
|
||||||
|
|
||||||
private bool _openSettings, _openNewTab, _focusNewTab, _openTabMenu, _openLineMenu, _openRename;
|
private bool _openSettings, _openNewTab, _focusNewTab, _openTabMenu, _openLineMenu, _openRename;
|
||||||
/// <summary>A line colour changed and isn't saved yet (saved once the picker is let go).</summary>
|
/// <summary>A line colour changed and isn't saved yet (saved once the picker is let go).</summary>
|
||||||
private bool _coloursDirty;
|
private bool _coloursDirty;
|
||||||
|
/// <summary>The Chat history slider's value while it's held (0: not held).</summary>
|
||||||
|
private int _historyEdit;
|
||||||
private string? _ctxTab, _renameFrom;
|
private string? _ctxTab, _renameFrom;
|
||||||
private ChatLine? _ctxLine;
|
private ChatLine? _ctxLine;
|
||||||
private string _ctxPattern = "";
|
private string _ctxPattern = "";
|
||||||
|
|
@ -129,7 +146,7 @@ internal sealed class ChatFace : IImGuiPanel
|
||||||
_stick = true;
|
_stick = true;
|
||||||
_seenRoutes = -1; // full rebuild on the first frame
|
_seenRoutes = -1; // full rebuild on the first frame
|
||||||
_seenId.Clear(); // every tab starts read
|
_seenId.Clear(); // every tab starts read
|
||||||
_unreadLines = -1;
|
_unreadLines = _unreadRoutes = -1; // a full recount
|
||||||
}
|
}
|
||||||
|
|
||||||
public void OnHidden()
|
public void OnHidden()
|
||||||
|
|
@ -351,22 +368,30 @@ internal sealed class ChatFace : IImGuiPanel
|
||||||
long newest = lines.Length > 0 ? lines[^1].Id : 0;
|
long newest = lines.Length > 0 ? lines[^1].Id : 0;
|
||||||
_seenId[current] = newest;
|
_seenId[current] = newest;
|
||||||
long routes = ChatModel.RoutesVersion, tabsVersion = ChatModel.FiltersVersion;
|
long routes = ChatModel.RoutesVersion, tabsVersion = ChatModel.FiltersVersion;
|
||||||
if (linesVersion == _unreadLines && routes == _unreadRoutes && tabsVersion == _unreadTabsVersion
|
bool recount = routes != _unreadRoutes || tabsVersion != _unreadTabsVersion
|
||||||
&& string.Equals(current, _unreadTab, StringComparison.Ordinal)) return;
|
|| !string.Equals(current, _unreadTab, StringComparison.Ordinal);
|
||||||
|
if (!recount && linesVersion == _unreadLines) return;
|
||||||
_unreadLines = linesVersion;
|
_unreadLines = linesVersion;
|
||||||
_unreadRoutes = routes;
|
_unreadRoutes = routes;
|
||||||
_unreadTabsVersion = tabsVersion;
|
_unreadTabsVersion = tabsVersion;
|
||||||
_unreadTab = current;
|
_unreadTab = current;
|
||||||
_unread.Clear();
|
// Only new lines arrived: count just those (lines past _unreadCountedTo). A full recount
|
||||||
|
// walks every unread line of every tab - up to the whole history per tab (3.7 ms at
|
||||||
|
// 10,000 lines, tools/ChatHistoryBench), which used to run on every new batch.
|
||||||
|
if (recount) _unread.Clear();
|
||||||
foreach (string tab in ChatModel.AllTabs())
|
foreach (string tab in ChatModel.AllTabs())
|
||||||
{
|
{
|
||||||
if (!_seenId.TryGetValue(tab, out long seen)) { _seenId[tab] = newest; continue; } // a new tab starts read
|
if (!_seenId.TryGetValue(tab, out long seen)) { _seenId[tab] = newest; continue; } // a new tab starts read
|
||||||
|
long from = recount ? seen : Math.Max(seen, _unreadCountedTo);
|
||||||
int count = 0;
|
int count = 0;
|
||||||
bool mention = false;
|
bool mention = false;
|
||||||
for (int i = lines.Length - 1; i >= 0 && lines[i].Id > seen; i--)
|
for (int i = lines.Length - 1; i >= 0 && lines[i].Id > from; i--)
|
||||||
if (ChatModel.LineInTab(lines[i], tab)) { count++; mention |= lines[i].Route.Mention; }
|
if (ChatModel.LineInTab(lines[i], tab)) { count++; mention |= lines[i].Route.Mention; }
|
||||||
if (count > 0) _unread[tab] = (count, mention);
|
if (count == 0) continue;
|
||||||
|
_unread.TryGetValue(tab, out var had);
|
||||||
|
_unread[tab] = (had.Count + count, had.Mention || mention);
|
||||||
}
|
}
|
||||||
|
_unreadCountedTo = newest;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void DrawSearch(Vector2 p, float w)
|
private void DrawSearch(Vector2 p, float w)
|
||||||
|
|
@ -399,9 +424,9 @@ internal sealed class ChatFace : IImGuiPanel
|
||||||
_h.Clear();
|
_h.Clear();
|
||||||
_lay.Clear();
|
_lay.Clear();
|
||||||
foreach (ChatLine line in lines)
|
foreach (ChatLine line in lines)
|
||||||
if (ChatModel.LineVisible(line, tab, search)) { _vis.Add(line); _h.Add(0); _lay.Add(null); }
|
if (ChatModel.LineVisible(line, tab, search)) { _vis.Add(line); _h.Add(_rowH); _lay.Add(null); }
|
||||||
_lastId = lines.Length > 0 ? lines[^1].Id : _lastId;
|
_lastId = lines.Length > 0 ? lines[^1].Id : _lastId;
|
||||||
_heightsFrom = 0;
|
_heightsFrom = _measuredFrom = _vis.Count; // all unmeasured: MeasureLines, newest first
|
||||||
_topsDirty = true;
|
_topsDirty = true;
|
||||||
ClearSelection();
|
ClearSelection();
|
||||||
_stick = true; // a rebuild re-pins to the newest line
|
_stick = true; // a rebuild re-pins to the newest line
|
||||||
|
|
@ -423,6 +448,7 @@ internal sealed class ChatFace : IImGuiPanel
|
||||||
_h.RemoveRange(0, drop);
|
_h.RemoveRange(0, drop);
|
||||||
_lay.RemoveRange(0, drop);
|
_lay.RemoveRange(0, drop);
|
||||||
_heightsFrom = Math.Max(0, _heightsFrom - drop);
|
_heightsFrom = Math.Max(0, _heightsFrom - drop);
|
||||||
|
_measuredFrom = Math.Max(0, _measuredFrom - drop);
|
||||||
if (_selAnchor >= 0) { _selAnchor -= drop; _selEnd -= drop; if (_selAnchor < 0 || _selEnd < 0) ClearSelection(); }
|
if (_selAnchor >= 0) { _selAnchor -= drop; _selEnd -= drop; if (_selAnchor < 0 || _selEnd < 0) ClearSelection(); }
|
||||||
_topsDirty = true;
|
_topsDirty = true;
|
||||||
}
|
}
|
||||||
|
|
@ -433,7 +459,7 @@ internal sealed class ChatFace : IImGuiPanel
|
||||||
if (!ChatModel.LineVisible(line, tab, search)) continue;
|
if (!ChatModel.LineVisible(line, tab, search)) continue;
|
||||||
if (_heightsFrom > _vis.Count) _heightsFrom = _vis.Count;
|
if (_heightsFrom > _vis.Count) _heightsFrom = _vis.Count;
|
||||||
_vis.Add(line);
|
_vis.Add(line);
|
||||||
_h.Add(0);
|
_h.Add(_rowH);
|
||||||
_lay.Add(null);
|
_lay.Add(null);
|
||||||
_topsDirty = true;
|
_topsDirty = true;
|
||||||
}
|
}
|
||||||
|
|
@ -444,81 +470,85 @@ internal sealed class ChatFace : IImGuiPanel
|
||||||
|
|
||||||
private void DrawLines(Vector2 size)
|
private void DrawLines(Vector2 size)
|
||||||
{
|
{
|
||||||
// Lines left the top of a full buffer while not following: scroll up by as much
|
|
||||||
// in THIS frame's BeginChild. (SetScrollY only lands in the next frame's Begin,
|
|
||||||
// after this frame has drawn the shortened list at the old scroll - the text
|
|
||||||
// jumped up for a frame and a strip at the bottom went blank, several times a
|
|
||||||
// second in busy chat.) A frame with wheel input waits a frame: this would
|
|
||||||
// override the wheel's own scroll.
|
|
||||||
bool compensated = false;
|
|
||||||
if (_droppedAbove > 0f)
|
|
||||||
{
|
|
||||||
if (Following) _droppedAbove = 0f;
|
|
||||||
else if (ImGuiNET.ImGui.GetIO().MouseWheel == 0f)
|
|
||||||
{
|
|
||||||
ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, Math.Max(0f, _lastScrollY - _droppedAbove)));
|
|
||||||
_droppedAbove = 0f;
|
|
||||||
compensated = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u);
|
|
||||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ScrollbarBg, 0u);
|
|
||||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0, 0));
|
|
||||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, 10f);
|
|
||||||
bool open = ImGuiNET.ImGui.BeginChild("##chat_lines", size, ImGuiChildFlags.None, ImGuiWindowFlags.AlwaysVerticalScrollbar);
|
|
||||||
ImGuiNET.ImGui.PopStyleVar(2);
|
|
||||||
ImGuiNET.ImGui.PopStyleColor(2);
|
|
||||||
if (!open) { ImGuiNET.ImGui.EndChild(); return; }
|
|
||||||
|
|
||||||
float fontSize = ChatModel.FontSize;
|
float fontSize = ChatModel.FontSize;
|
||||||
ImFontPtr font = ImGuiFonts.Chat(fontSize);
|
ImFontPtr font = ImGuiFonts.Chat(fontSize);
|
||||||
ImGuiNET.ImGui.PushFont(font);
|
ImGuiNET.ImGui.PushFont(font);
|
||||||
bool showTs = ChatModel.ShowTimestamps;
|
bool showTs = ChatModel.ShowTimestamps;
|
||||||
float wrapW = Math.Max(20, ImGuiNET.ImGui.GetContentRegionAvail().X - 6);
|
|
||||||
// The text starts after the timestamp and wraps under itself.
|
// The lines are measured BEFORE the list's BeginChild, so this frame's scroll can be
|
||||||
|
// set for this frame's lines (see "Where the view goes" below). The width they wrap
|
||||||
|
// to is the child's: its width less its scrollbar (always shown) and a margin;
|
||||||
|
// _wrapFix corrects that guess if the child ever reports otherwise.
|
||||||
|
float wrapW = Math.Max(20, MathF.Floor(size.X) - ListScrollbarW - 6 + _wrapFix);
|
||||||
float tsW = showTs ? ImGuiNET.ImGui.CalcTextSize("00:00:00 ").X : 0;
|
float tsW = showTs ? ImGuiNET.ImGui.CalcTextSize("00:00:00 ").X : 0;
|
||||||
|
MeasureLines(font, wrapW, tsW, fontSize, showTs, MathF.Floor(size.Y));
|
||||||
|
float total = _tops[_vis.Count];
|
||||||
|
|
||||||
|
// Where the view goes this frame. (2026-10-11, the chat "bouncing": until now the
|
||||||
|
// view followed the newest line with SetScrollHereY at the end of the frame, which
|
||||||
|
// only lands in the NEXT frame's Begin. So every batch of new lines was first drawn
|
||||||
|
// at the old scroll: with the buffer full, lines leave the top as others arrive,
|
||||||
|
// and the text jumped by the difference - up and back down when a long line left
|
||||||
|
// and a short one came - then snapped into place a frame later. A popped-out chat
|
||||||
|
// redraws at 5 Hz while idle, so the wrong frame stayed up for 200 ms.) Now the
|
||||||
|
// content height and the scroll are both handed to this frame's BeginChild:
|
||||||
|
// • the content size, so ImGui's scroll limit is this frame's and not last frame's
|
||||||
|
// (it clamps any scroll set before Begin to the limit it knows);
|
||||||
|
// • following: the bottom (the limit clamps 'total' to exactly the bottom);
|
||||||
|
// • not following: only the lines dropped off a full buffer's top, so what is
|
||||||
|
// being read stays put (fractions carried, so rounding can't creep the view).
|
||||||
|
// A frame with wheel input over the list leaves the scroll to the wheel (this would
|
||||||
|
// override it); a drag-select scrolls the list itself.
|
||||||
|
Vector2 listPos = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||||
|
bool wheelHere = ImGuiNET.ImGui.GetIO().MouseWheel != 0f
|
||||||
|
&& ImGuiNET.ImGui.IsMouseHoveringRect(listPos, listPos + size, false);
|
||||||
|
ImGuiNET.ImGui.SetNextWindowContentSize(new Vector2(0f, total));
|
||||||
|
bool compensated = false;
|
||||||
|
if (Following)
|
||||||
|
{
|
||||||
|
_droppedAbove = 0f;
|
||||||
|
_scrollCarry = 0f;
|
||||||
|
// Not counted as "our move": a scrollbar drag in this Begin overrides it, and the
|
||||||
|
// check below must see that to stop following.
|
||||||
|
if (!wheelHere && !_selDragging)
|
||||||
|
ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, total));
|
||||||
|
}
|
||||||
|
else if (_droppedAbove != 0f && !wheelHere)
|
||||||
|
{
|
||||||
|
float target = _lastScrollY + _scrollCarry - _droppedAbove;
|
||||||
|
float applied = MathF.Round(Math.Max(0f, target)); // ImGui rounds scroll to whole pixels
|
||||||
|
_scrollCarry = target > 0f ? target - applied : 0f;
|
||||||
|
ImGuiNET.ImGui.SetNextWindowScroll(new Vector2(-1f, applied));
|
||||||
|
_droppedAbove = 0f;
|
||||||
|
compensated = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u);
|
||||||
|
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ScrollbarBg, 0u);
|
||||||
|
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(0, 0));
|
||||||
|
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, ListScrollbarW);
|
||||||
|
bool open = ImGuiNET.ImGui.BeginChild("##chat_lines", size, ImGuiChildFlags.None, ImGuiWindowFlags.AlwaysVerticalScrollbar);
|
||||||
|
ImGuiNET.ImGui.PopStyleVar(2);
|
||||||
|
ImGuiNET.ImGui.PopStyleColor(2);
|
||||||
|
if (!open) { ImGuiNET.ImGui.EndChild(); ImGuiNET.ImGui.PopFont(); return; }
|
||||||
|
|
||||||
|
// The child's real width, should the guess above ever be off (a style change):
|
||||||
|
// measured again now, and the guess corrected from the next frame on.
|
||||||
|
float realWrapW = Math.Max(20, ImGuiNET.ImGui.GetContentRegionAvail().X - 6);
|
||||||
|
if (Math.Abs(realWrapW - wrapW) > 0.5f)
|
||||||
|
{
|
||||||
|
_wrapFix += realWrapW - wrapW;
|
||||||
|
wrapW = realWrapW;
|
||||||
|
MeasureLines(font, wrapW, tsW, fontSize, showTs, MathF.Floor(size.Y));
|
||||||
|
total = _tops[_vis.Count];
|
||||||
|
}
|
||||||
float textW = Math.Max(20, wrapW - tsW);
|
float textW = Math.Max(20, wrapW - tsW);
|
||||||
if (wrapW != _seenWrap || fontSize != _seenFont || showTs != _seenTs)
|
|
||||||
{
|
|
||||||
_seenWrap = wrapW;
|
|
||||||
_seenFont = fontSize;
|
|
||||||
_seenTs = showTs;
|
|
||||||
_heightsFrom = 0;
|
|
||||||
}
|
|
||||||
if (_heightsFrom < _vis.Count)
|
|
||||||
{
|
|
||||||
for (int i = _heightsFrom; i < _vis.Count; i++)
|
|
||||||
{
|
|
||||||
ChatLine line = _vis[i];
|
|
||||||
ChatSpan[]? spans = line.Route.Spans;
|
|
||||||
if (spans != null)
|
|
||||||
{
|
|
||||||
SpanLayout lay = LayoutSpans(font, line.Text, spans, textW);
|
|
||||||
_lay[i] = lay;
|
|
||||||
_h[i] = lay.Height;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_lay[i] = null;
|
|
||||||
_h[i] = ImGuiNET.ImGui.CalcTextSize(line.Text, false, textW).Y;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_heightsFrom = _vis.Count;
|
|
||||||
_topsDirty = true;
|
|
||||||
}
|
|
||||||
if (_topsDirty)
|
|
||||||
{
|
|
||||||
if (_tops.Length < _vis.Count + 1) _tops = new float[Math.Max(_vis.Count + 1, _tops.Length * 2)];
|
|
||||||
_tops[0] = 0;
|
|
||||||
for (int i = 0; i < _vis.Count; i++) _tops[i + 1] = _tops[i] + _h[i];
|
|
||||||
_topsDirty = false;
|
|
||||||
}
|
|
||||||
int n = _vis.Count;
|
int n = _vis.Count;
|
||||||
float total = _tops[n];
|
|
||||||
|
|
||||||
// Following the tail until the user scrolls away from it.
|
// Following the tail until the user scrolls away from it.
|
||||||
float scrollY = ImGuiNET.ImGui.GetScrollY(), maxY = ImGuiNET.ImGui.GetScrollMaxY();
|
float scrollY = ImGuiNET.ImGui.GetScrollY(), maxY = ImGuiNET.ImGui.GetScrollMaxY();
|
||||||
if (compensated) _lastScrollY = scrollY; // our move, not the user's
|
if (compensated) _lastScrollY = scrollY; // our move, not the user's
|
||||||
|
else if (Math.Abs(scrollY - _lastScrollY) > 0.5f) _scrollCarry = 0f; // the user's: start afresh
|
||||||
// Wheel up over the chat stops following at once; reaching the bottom again resumes it.
|
// Wheel up over the chat stops following at once; reaching the bottom again resumes it.
|
||||||
// Not while it has nothing to scroll: no scroll change would ever turn following back on.
|
// Not while it has nothing to scroll: no scroll change would ever turn following back on.
|
||||||
if (maxY > 0f && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.GetIO().MouseWheel > 0f)
|
if (maxY > 0f && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.GetIO().MouseWheel > 0f)
|
||||||
|
|
@ -555,8 +585,6 @@ internal sealed class ChatFace : IImGuiPanel
|
||||||
HandleLineMenu(basePos, wrapW, n);
|
HandleLineMenu(basePos, wrapW, n);
|
||||||
|
|
||||||
_lastScrollY = scrollY;
|
_lastScrollY = scrollY;
|
||||||
if (ChatModel.AutoScroll && _stick && !_selDragging && total > viewH)
|
|
||||||
ImGuiNET.ImGui.SetScrollHereY(1f);
|
|
||||||
|
|
||||||
// "Copied N lines" / "Rule added", top-right, for a moment.
|
// "Copied N lines" / "Rule added", top-right, for a moment.
|
||||||
if (_flash != null)
|
if (_flash != null)
|
||||||
|
|
@ -574,8 +602,93 @@ internal sealed class ChatFace : IImGuiPanel
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ImGuiNET.ImGui.PopFont();
|
|
||||||
ImGuiNET.ImGui.EndChild();
|
ImGuiNET.ImGui.EndChild();
|
||||||
|
ImGuiNET.ImGui.PopFont(); // pushed before the child, for MeasureLines
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Time MeasureLines may spend a frame catching up on lines measured for another width.</summary>
|
||||||
|
private const double MeasureBudgetMs = 2.0;
|
||||||
|
private static readonly long MeasureBudgetTicks = (long)(System.Diagnostics.Stopwatch.Frequency * MeasureBudgetMs / 1000);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Brings the line heights and tops up to date for this wrap width, font and timestamp
|
||||||
|
/// setting. Chat font pushed. New lines are measured at once. When the width, font or
|
||||||
|
/// timestamps change (or after a rebuild) every line needs measuring again: 16 ms at
|
||||||
|
/// 10,000 lines (tools/ChatHistoryBench), every frame of a resize drag. So that is done
|
||||||
|
/// a slice at a time: the lines in view first, then from the newest line up, for
|
||||||
|
/// MeasureBudgetMs a frame; the others keep their old height meanwhile. Scrolled up,
|
||||||
|
/// the view is moved by however much the lines above it grew or shrank, so what's being
|
||||||
|
/// read stays put (the same way as lines dropping off the top).
|
||||||
|
/// </summary>
|
||||||
|
private void MeasureLines(ImFontPtr font, float wrapW, float tsW, float fontSize, bool showTs, float viewH)
|
||||||
|
{
|
||||||
|
// The text starts after the timestamp and wraps under itself.
|
||||||
|
float textW = Math.Max(20, wrapW - tsW);
|
||||||
|
_rowH = font.FontSize;
|
||||||
|
if (wrapW != _seenWrap || fontSize != _seenFont || showTs != _seenTs)
|
||||||
|
{
|
||||||
|
_seenWrap = wrapW;
|
||||||
|
_seenFont = fontSize;
|
||||||
|
_seenTs = showTs;
|
||||||
|
_measuredFrom = Math.Min(_heightsFrom, _vis.Count); // all measured so far is stale
|
||||||
|
}
|
||||||
|
bool changed = false;
|
||||||
|
for (int i = _heightsFrom; i < _vis.Count; i++) { MeasureLine(font, i, textW); changed = true; }
|
||||||
|
_heightsFrom = _vis.Count;
|
||||||
|
|
||||||
|
if (_measuredFrom > 0)
|
||||||
|
{
|
||||||
|
UpdateTops();
|
||||||
|
int n = _vis.Count;
|
||||||
|
bool following = Following;
|
||||||
|
// Where the view will be (last frame's scroll, less any move still to come).
|
||||||
|
float viewTop = _lastScrollY + _scrollCarry - _droppedAbove;
|
||||||
|
int firstVisible = following || n == 0 ? int.MaxValue : FirstAtOrBelow(Math.Max(0f, viewTop), n);
|
||||||
|
if (!following)
|
||||||
|
for (int i = firstVisible; i < Math.Min(n, _measuredFrom) && _tops[i] < viewTop + viewH; i++)
|
||||||
|
MeasureLine(font, i, textW);
|
||||||
|
float grewAbove = 0f;
|
||||||
|
long t0 = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||||
|
int count = 0;
|
||||||
|
while (_measuredFrom > 0)
|
||||||
|
{
|
||||||
|
int i = --_measuredFrom;
|
||||||
|
float old = _h[i];
|
||||||
|
MeasureLine(font, i, textW);
|
||||||
|
if (i < firstVisible) grewAbove += _h[i] - old;
|
||||||
|
if ((++count & 15) == 0 && System.Diagnostics.Stopwatch.GetTimestamp() - t0 > MeasureBudgetTicks) break;
|
||||||
|
}
|
||||||
|
if (!following) _droppedAbove -= grewAbove;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (changed) _topsDirty = true;
|
||||||
|
UpdateTops();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void MeasureLine(ImFontPtr font, int i, float textW)
|
||||||
|
{
|
||||||
|
ChatLine line = _vis[i];
|
||||||
|
ChatSpan[]? spans = line.Route.Spans;
|
||||||
|
if (spans != null)
|
||||||
|
{
|
||||||
|
SpanLayout lay = LayoutSpans(font, line.Text, spans, textW);
|
||||||
|
_lay[i] = lay;
|
||||||
|
_h[i] = lay.Height;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_lay[i] = null;
|
||||||
|
_h[i] = ImGuiNET.ImGui.CalcTextSize(line.Text, false, textW).Y;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateTops()
|
||||||
|
{
|
||||||
|
if (!_topsDirty && _tops.Length > _vis.Count) return;
|
||||||
|
if (_tops.Length < _vis.Count + 1) _tops = new float[Math.Max(_vis.Count + 1, _tops.Length * 2)];
|
||||||
|
_tops[0] = 0;
|
||||||
|
for (int i = 0; i < _vis.Count; i++) _tops[i + 1] = _tops[i] + _h[i];
|
||||||
|
_topsDirty = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void Flash(string message, double seconds = 2.0)
|
private void Flash(string message, double seconds = 2.0)
|
||||||
|
|
@ -871,6 +984,18 @@ internal sealed class ChatFace : IImGuiPanel
|
||||||
if (ImGuiNET.ImGui.SliderInt("Background", ref pct, 0, 100, "%d%%"))
|
if (ImGuiNET.ImGui.SliderInt("Background", ref pct, 0, 100, "%d%%"))
|
||||||
ChatModel.BackgroundAlpha = (int)MathF.Round(pct * 2.55f);
|
ChatModel.BackgroundAlpha = (int)MathF.Round(pct * 2.55f);
|
||||||
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatModel.SaveSettings();
|
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatModel.SaveSettings();
|
||||||
|
// How many lines the chat keeps (ChatHistory): applied when the slider is let go, so
|
||||||
|
// dragging it down doesn't cut the history at every step on the way.
|
||||||
|
int history = _historyEdit > 0 ? _historyEdit : ChatModel.HistoryLines;
|
||||||
|
if (ImGuiNET.ImGui.SliderInt("Chat history", ref history, ChatHistory.MinLines, ChatHistory.MaxLines, "%d lines"))
|
||||||
|
_historyEdit = ChatHistory.Clamp(history);
|
||||||
|
if (ImGuiNET.ImGui.IsItemDeactivated() && _historyEdit > 0)
|
||||||
|
{
|
||||||
|
ChatModel.SetHistoryLines(_historyEdit);
|
||||||
|
_historyEdit = 0;
|
||||||
|
}
|
||||||
|
ImGuiNET.ImGui.SetItemTooltip("How many lines the chat keeps, all tabs together (default 2000).\n" +
|
||||||
|
"About 2 MB of memory per 1000 lines. Lowering it drops the oldest lines.");
|
||||||
ImGuiNET.ImGui.PopItemWidth();
|
ImGuiNET.ImGui.PopItemWidth();
|
||||||
|
|
||||||
bool ts = ChatModel.ShowTimestamps;
|
bool ts = ChatModel.ShowTimestamps;
|
||||||
|
|
|
||||||
|
|
@ -87,6 +87,8 @@ internal sealed class DamageFace : IImGuiPanel
|
||||||
private sealed class RowText
|
private sealed class RowText
|
||||||
{
|
{
|
||||||
public string Wcid = "", Tier = "", Crit = "", NonCrit = "", Casts = "", Kills = "";
|
public string Wcid = "", Tier = "", Crit = "", NonCrit = "", Casts = "", Kills = "";
|
||||||
|
/// <summary>The name as shown: "Rampager (2 kinds)" for a row of several wcids.</summary>
|
||||||
|
public string NameShown = "", NameTip = "";
|
||||||
public string Weapon = "", Offhand = "", Pet = "", WeakTop = "", Sec = "", SecTip = "";
|
public string Weapon = "", Offhand = "", Pet = "", WeakTop = "", Sec = "", SecTip = "";
|
||||||
public bool CritSet, NonCritSet, WeaponGold, OffhandGold, PetGold;
|
public bool CritSet, NonCritSet, WeaponGold, OffhandGold, PetGold;
|
||||||
public string[] TierLines = Array.Empty<string>();
|
public string[] TierLines = Array.Empty<string>();
|
||||||
|
|
@ -250,7 +252,8 @@ internal sealed class DamageFace : IImGuiPanel
|
||||||
if (_filterWid != 0 && r.Wid != _filterWid) continue;
|
if (_filterWid != 0 && r.Wid != _filterWid) continue;
|
||||||
if (_searchText.Length > 0
|
if (_searchText.Length > 0
|
||||||
&& r.Name.IndexOf(_searchText, StringComparison.OrdinalIgnoreCase) < 0
|
&& r.Name.IndexOf(_searchText, StringComparison.OrdinalIgnoreCase) < 0
|
||||||
&& !r.Wcid.ToString(CultureInfo.InvariantCulture).Contains(_searchText, StringComparison.Ordinal))
|
&& !r.Wcid.ToString(CultureInfo.InvariantCulture).Contains(_searchText, StringComparison.Ordinal)
|
||||||
|
&& !Array.Exists(r.Wcids, w => w.ToString(CultureInfo.InvariantCulture).Contains(_searchText, StringComparison.Ordinal)))
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
_shown.Add(r);
|
_shown.Add(r);
|
||||||
|
|
@ -306,6 +309,20 @@ internal sealed class DamageFace : IImGuiPanel
|
||||||
}
|
}
|
||||||
BuildPrio(r.Name, t);
|
BuildPrio(r.Name, t);
|
||||||
t.Wcid = r.Wcid.ToString(inv);
|
t.Wcid = r.Wcid.ToString(inv);
|
||||||
|
const string DetailTip = "Details: weaknesses, accuracy, damage, summons, damage taken and spell settings (wcid ";
|
||||||
|
if (r.Wcids.Length > 1)
|
||||||
|
{
|
||||||
|
// Monsters of one name with several weenies (retail has five Rampagers): one row.
|
||||||
|
t.NameShown = r.Name + " (" + r.Wcids.Length.ToString(inv) + " kinds)";
|
||||||
|
t.NameTip = r.Wcids.Length.ToString(inv) + " kinds of " + r.Name + ": wcids " + string.Join(", ", r.Wcids) + ".\n"
|
||||||
|
+ "Kills and fights are added up; a weapon, offhand, pet or HP set here applies to all of them.\n"
|
||||||
|
+ DetailTip + t.Wcid + ", the one with the most kills).";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
t.NameShown = r.Name;
|
||||||
|
t.NameTip = DetailTip + t.Wcid + ").";
|
||||||
|
}
|
||||||
t.Tier = DamageSource.FormatTier(r.Tier);
|
t.Tier = DamageSource.FormatTier(r.Tier);
|
||||||
t.CritSet = r.CritN > 0;
|
t.CritSet = r.CritN > 0;
|
||||||
t.Crit = t.CritSet ? r.Crit.ToString("0", inv) : "—";
|
t.Crit = t.CritSet ? r.Crit.ToString("0", inv) : "—";
|
||||||
|
|
@ -762,10 +779,10 @@ internal sealed class DamageFace : IImGuiPanel
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ImGuiNET.ImGui.SetItemTooltip("Follow the Default config (spells, weapon). Uncheck to customize this monster.");
|
ImGuiNET.ImGui.SetItemTooltip("Follow the Default config (spells, weapon). Uncheck to customize this monster.");
|
||||||
if (NameLink("##name", r.Name, new Vector2(p.X + ColX[ColMonster] + 22, p.Y), ColW[ColMonster] - 24, custom ? Gold : White,
|
if (NameLink("##name", t.NameShown, new Vector2(p.X + ColX[ColMonster] + 22, p.Y), ColW[ColMonster] - 24, custom ? Gold : White,
|
||||||
ImGuiFonts.Get(UiFont.Ui11)))
|
ImGuiFonts.Get(UiFont.Ui11)))
|
||||||
DamageDetailFace.Show(r.Wcid, r.Name);
|
DamageDetailFace.Show(r.Wcid, r.Name);
|
||||||
ImGuiNET.ImGui.SetItemTooltip("Details: weaknesses, accuracy, damage, summons, damage taken and spell settings (wcid " + t.Wcid + ").");
|
ImGuiNET.ImGui.SetItemTooltip(t.NameTip);
|
||||||
|
|
||||||
PrioCell(r.Key, r.Name, t.PrioCopyFrom, t, p);
|
PrioCell(r.Key, r.Name, t.PrioCopyFrom, t, p);
|
||||||
HpCell(r, p);
|
HpCell(r, p);
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,9 @@
|
||||||
// RynthCore.Engine - ImGui/Panels/ItemsFace.cs
|
// RynthCore.Engine - ImGui/Panels/ItemsFace.cs
|
||||||
// ImGui face of the Items panel (UI/Panels/ItemsPanel.cs): weapons (name,
|
// ImGui face of the Items panel (UI/Panels/ItemsPanel.cs): weapons (name,
|
||||||
// element, Del), consumables (name, type, Del), each with "Add Selected",
|
// element, Del), consumables (name, type, Del), each with "Add Selected",
|
||||||
// and mana stone tapping (on/off, keep count, min max-mana to tap).
|
// and mana stone tapping (on/off, keep count, min max-mana to tap). A listed
|
||||||
|
// weapon the character no longer carries (RynthAi's missingIds) shows in amber
|
||||||
|
// with a warning icon and "(missing)", and says what to do in its tooltip.
|
||||||
//
|
//
|
||||||
// Edits change a private copy and save the whole payload (ItemsCommands,
|
// Edits change a private copy and save the whole payload (ItemsCommands,
|
||||||
// pump thread). A newer snapshot replaces the copy; snapshots from before
|
// pump thread). A newer snapshot replaces the copy; snapshots from before
|
||||||
|
|
@ -62,7 +64,7 @@ internal sealed class ItemsFace : IImGuiPanel
|
||||||
{
|
{
|
||||||
ItemsPanel.WeaponEntry wpn = _data.Weapons[i];
|
ItemsPanel.WeaponEntry wpn = _data.Weapons[i];
|
||||||
ImGuiNET.ImGui.PushID("w" + i);
|
ImGuiNET.ImGui.PushID("w" + i);
|
||||||
int r = Row(wpn.Name, wpn.Element, i, bw);
|
int r = Row(wpn.Name, wpn.Element, i, bw, _data.MissingIds.Contains(wpn.Id));
|
||||||
ImGuiNET.ImGui.PopID();
|
ImGuiNET.ImGui.PopID();
|
||||||
if (r == 1)
|
if (r == 1)
|
||||||
{
|
{
|
||||||
|
|
@ -94,7 +96,7 @@ internal sealed class ItemsFace : IImGuiPanel
|
||||||
{
|
{
|
||||||
ItemsPanel.ConsumableEntry c = _data.Consumables[i];
|
ItemsPanel.ConsumableEntry c = _data.Consumables[i];
|
||||||
ImGuiNET.ImGui.PushID("c" + i);
|
ImGuiNET.ImGui.PushID("c" + i);
|
||||||
int r = Row(c.Name, c.Type, i, bw);
|
int r = Row(c.Name, c.Type, i, bw, missing: false);
|
||||||
ImGuiNET.ImGui.PopID();
|
ImGuiNET.ImGui.PopID();
|
||||||
if (r == 1)
|
if (r == 1)
|
||||||
{
|
{
|
||||||
|
|
@ -200,16 +202,38 @@ internal sealed class ItemsFace : IImGuiPanel
|
||||||
ImGuiNET.ImGui.Dummy(new Vector2(w, 22));
|
ImGuiNET.ImGui.Dummy(new Vector2(w, 22));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Name | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, else 0.</summary>
|
private const string MissingSuffix = " (missing)";
|
||||||
private static int Row(string name, string value, int index, float w)
|
|
||||||
|
/// <summary>
|
||||||
|
/// Name | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, else 0.
|
||||||
|
/// <paramref name="missing"/>: the item isn't carried any more (amber, a warning icon,
|
||||||
|
/// "(missing)" and a tooltip saying what to do).
|
||||||
|
/// </summary>
|
||||||
|
private static int Row(string name, string value, int index, float w, bool missing)
|
||||||
{
|
{
|
||||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||||
dl.AddRectFilled(p, p + new Vector2(w, 24), index % 2 == 0 ? RowAlt : PanelBg);
|
dl.AddRectFilled(p, p + new Vector2(w, 24), index % 2 == 0 ? RowAlt : PanelBg);
|
||||||
float nameW = w - 146;
|
float nameW = w - 146;
|
||||||
|
float ty = p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
||||||
dl.PushClipRect(p, p + new Vector2(nameW, 24), true);
|
dl.PushClipRect(p, p + new Vector2(nameW, 24), true);
|
||||||
dl.AddText(new Vector2(p.X + 6, p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, name);
|
if (missing)
|
||||||
|
{
|
||||||
|
float x = p.X + 6;
|
||||||
|
dl.AddText(new Vector2(x, ty), Amber, PhosphorIcons.Warning);
|
||||||
|
x += ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.Warning).X + 4;
|
||||||
|
dl.AddText(new Vector2(x, ty), Amber, name);
|
||||||
|
x += ImGuiNET.ImGui.CalcTextSize(name).X;
|
||||||
|
dl.AddText(new Vector2(x, ty), Amber, MissingSuffix);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
dl.AddText(new Vector2(p.X + 6, ty), Text, name);
|
||||||
|
}
|
||||||
dl.PopClipRect();
|
dl.PopClipRect();
|
||||||
|
if (missing && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.IsMouseHoveringRect(p, p + new Vector2(nameW, 24)))
|
||||||
|
ImGuiNET.ImGui.SetTooltip("Not in your pack any more - select the item in your inventory and click\n"
|
||||||
|
+ "Add Selected Weapon again, or remove this entry.");
|
||||||
int result = 0;
|
int result = 0;
|
||||||
if (Button("##pick", value, new Vector2(p.X + nameW + 2, p.Y + 2), new Vector2(96, 20), Text, BtnFill)) result = 1;
|
if (Button("##pick", value, new Vector2(p.X + nameW + 2, p.Y + 2), new Vector2(96, 20), Text, BtnFill)) result = 1;
|
||||||
if (IconButton("##del", PhosphorIcons.Trash, new Vector2(p.X + nameW + 102, p.Y + 2), new Vector2(42, 20), Red, BtnFill)) result = 2;
|
if (IconButton("##del", PhosphorIcons.Trash, new Vector2(p.X + nameW + 102, p.Y + 2), new Vector2(42, 20), Red, BtnFill)) result = 2;
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@
|
||||||
//
|
//
|
||||||
// [<- Back] Edit rule Saved
|
// [<- Back] Edit rule Saved
|
||||||
// State: [Combat v]
|
// State: [Combat v]
|
||||||
|
// Name: [Optional: a name to find this rule by ]
|
||||||
// +- Conditions ------ [+ Add] -+ +- Actions --------- [+ Add] -+
|
// +- Conditions ------ [+ Add] -+ +- Actions --------- [+ Add] -+
|
||||||
// | [Landblock == v] | | [Chat Command v] |
|
// | [Landblock == v] | | [Chat Command v] |
|
||||||
// | [A9B40000 ][Set current] | | [/say hello ] |
|
// | [A9B40000 ][Set current] | | [/say hello ] |
|
||||||
|
|
@ -15,6 +16,13 @@
|
||||||
// first of an All (a single action into the first of a DoAll), or adds one
|
// first of an All (a single action into the first of a DoAll), or adds one
|
||||||
// more to an All / Any / DoAll.
|
// more to an All / Any / DoAll.
|
||||||
//
|
//
|
||||||
|
// Groups (2026-10-11): an All / Any / Not, nested or the column's own, and a
|
||||||
|
// DoAll is a box (tint, border and left bar in its colour: All teal, Any
|
||||||
|
// amber, Not rose) around its picker and everything in it, so a box inside
|
||||||
|
// a box shows what belongs where; a nested group's line says what it means
|
||||||
|
// ("any of the conditions inside"). Rows alternate a light shade; a DoAll's
|
||||||
|
// actions are numbered in the order they run.
|
||||||
|
//
|
||||||
// Saving: every change marks the rule dirty (MetaAutosave); 0.75 s after the
|
// Saving: every change marks the rule dirty (MetaAutosave); 0.75 s after the
|
||||||
// last change, and never while a text box is being typed in, the rule goes
|
// last change, and never while a text box is being typed in, the rule goes
|
||||||
// to RynthAi as add_rule (a new rule, the first time, and only once its
|
// to RynthAi as add_rule (a new rule, the first time, and only once its
|
||||||
|
|
@ -68,6 +76,11 @@ internal sealed partial class MetaFace
|
||||||
private string? _nameProblem;
|
private string? _nameProblem;
|
||||||
private const string NewStateEntry = PhosphorIcons.Plus + " New state...";
|
private const string NewStateEntry = PhosphorIcons.Plus + " New state...";
|
||||||
|
|
||||||
|
// The rule's Name box (MetaRuleDto.Name; one line, MaxNameLength bytes of UTF-8).
|
||||||
|
private readonly byte[] _ruleNameBytes = new byte[MetaRuleEdit.MaxNameLength + 1];
|
||||||
|
private string? _ruleNameShown; // the name the box was last filled from
|
||||||
|
private bool _ruleNameActive, _focusRuleName;
|
||||||
|
|
||||||
private const string BackLabel = PhosphorIcons.ArrowLeft + " Back";
|
private const string BackLabel = PhosphorIcons.ArrowLeft + " Back";
|
||||||
private const string AddLabel = PhosphorIcons.Plus + " Add";
|
private const string AddLabel = PhosphorIcons.Plus + " Add";
|
||||||
private const string SetCurrentLabel = PhosphorIcons.MapPin + " Set current";
|
private const string SetCurrentLabel = PhosphorIcons.MapPin + " Set current";
|
||||||
|
|
@ -86,6 +99,7 @@ internal sealed partial class MetaFace
|
||||||
_lastSaved = index >= 0 ? rule.Clone() : null;
|
_lastSaved = index >= 0 ? rule.Clone() : null;
|
||||||
_autosave.Clear();
|
_autosave.Clear();
|
||||||
_fields.Clear();
|
_fields.Clear();
|
||||||
|
_ruleNameShown = null;
|
||||||
_editConfirmDelete = false;
|
_editConfirmDelete = false;
|
||||||
_editTyping = false;
|
_editTyping = false;
|
||||||
CancelNaming();
|
CancelNaming();
|
||||||
|
|
@ -136,6 +150,7 @@ internal sealed partial class MetaFace
|
||||||
}
|
}
|
||||||
if (!_autosave.Take()) return;
|
if (!_autosave.Take()) return;
|
||||||
MetaRuleDto send = _editRule.Clone();
|
MetaRuleDto send = _editRule.Clone();
|
||||||
|
send.Name = send.Name.Trim(); // the box keeps a space you just typed; the rule doesn't
|
||||||
if (_editIndex < 0)
|
if (_editIndex < 0)
|
||||||
{
|
{
|
||||||
_editIndex = _data.Rules.Count; // add_rule appends
|
_editIndex = _data.Rules.Count; // add_rule appends
|
||||||
|
|
@ -163,7 +178,6 @@ internal sealed partial class MetaFace
|
||||||
{
|
{
|
||||||
SendEdit(new MetaCmd { Op = "delete_rule", Index = index });
|
SendEdit(new MetaCmd { Op = "delete_rule", Index = index });
|
||||||
_data.Rules.RemoveAt(index);
|
_data.Rules.RemoveAt(index);
|
||||||
_expanded.Clear();
|
|
||||||
RebuildCaches();
|
RebuildCaches();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -195,7 +209,7 @@ internal sealed partial class MetaFace
|
||||||
float indW = SaveIndicatorWidth(editor: true);
|
float indW = SaveIndicatorWidth(editor: true);
|
||||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
|
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
|
||||||
float tx = top.X + backW + 8;
|
float tx = top.X + backW + 8;
|
||||||
string title = _editIndex < 0 ? "New rule" : "Edit rule";
|
string title = _editIndex < 0 ? "New rule" : r.Name.Trim().Length > 0 ? r.Name.Trim() : "Edit rule";
|
||||||
ImGuiNET.ImGui.PushFont(bold);
|
ImGuiNET.ImGui.PushFont(bold);
|
||||||
dl.AddText(new Vector2(tx, top.Y + (22 - bold.FontSize) * 0.5f), Teal, Fit(title, Math.Max(10, top.X + w - indW - 8 - tx)));
|
dl.AddText(new Vector2(tx, top.Y + (22 - bold.FontSize) * 0.5f), Teal, Fit(title, Math.Max(10, top.X + w - indW - 8 - tx)));
|
||||||
ImGuiNET.ImGui.PopFont();
|
ImGuiNET.ImGui.PopFont();
|
||||||
|
|
@ -203,7 +217,7 @@ internal sealed partial class MetaFace
|
||||||
|
|
||||||
// State: [picker]
|
// State: [picker]
|
||||||
float y = top.Y + 26;
|
float y = top.Y + 26;
|
||||||
float lw = ImGuiNET.ImGui.CalcTextSize("State:").X + 6;
|
float lw = Math.Max(ImGuiNET.ImGui.CalcTextSize("State:").X, ImGuiNET.ImGui.CalcTextSize("Name:").X) + 6;
|
||||||
dl.AddText(new Vector2(top.X, y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "State:");
|
dl.AddText(new Vector2(top.X, y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "State:");
|
||||||
string? state = StatePicker("##ed_state", r.State, _statePicks, IndexOf(_statePicks, r.State),
|
string? state = StatePicker("##ed_state", r.State, _statePicks, IndexOf(_statePicks, r.State),
|
||||||
new Vector2(top.X + lw, y), w - lw, out _);
|
new Vector2(top.X + lw, y), w - lw, out _);
|
||||||
|
|
@ -212,7 +226,12 @@ internal sealed partial class MetaFace
|
||||||
r.State = state; // a new state is made by moving this rule into it
|
r.State = state; // a new state is made by moving this rule into it
|
||||||
_editChanged = true;
|
_editChanged = true;
|
||||||
}
|
}
|
||||||
y += 22 + ProblemLine("##ed_state", new Vector2(top.X + lw, y + 22), w - lw) + 6;
|
y += 22 + ProblemLine("##ed_state", new Vector2(top.X + lw, y + 22), w - lw) + 4;
|
||||||
|
|
||||||
|
// Name: [optional]
|
||||||
|
dl.AddText(new Vector2(top.X, y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "Name:");
|
||||||
|
NameBox(new Vector2(top.X + lw, y), w - lw);
|
||||||
|
y += 22 + 6;
|
||||||
|
|
||||||
// Conditions | Actions
|
// Conditions | Actions
|
||||||
const float footerH = 24;
|
const float footerH = 24;
|
||||||
|
|
@ -279,44 +298,191 @@ internal sealed partial class MetaFace
|
||||||
|
|
||||||
private void ConditionsBody(MetaRuleDto r, float w)
|
private void ConditionsBody(MetaRuleDto r, float w)
|
||||||
{
|
{
|
||||||
int picked = FlowPicker("##ed_cond", MetaVocabulary.ConditionName(r.Condition), MetaVocabulary.ConditionNames, r.Condition, w);
|
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||||
if (picked >= 0 && picked != r.Condition)
|
BeginBacks(dl);
|
||||||
|
try
|
||||||
{
|
{
|
||||||
SetCondition(r, picked);
|
// An All / Any / Not is a box around its picker and everything in it.
|
||||||
_editChanged = true;
|
bool card = MetaVocabulary.IsCompositeCondition(r.Condition);
|
||||||
|
Vector2 top = CardOpen(card);
|
||||||
|
float iw = card ? w - CardInset - CardPadR : w;
|
||||||
|
int picked = FlowPicker("##ed_cond", MetaVocabulary.ConditionName(r.Condition), MetaVocabulary.ConditionNames, r.Condition, iw);
|
||||||
|
if (picked >= 0 && picked != r.Condition)
|
||||||
|
{
|
||||||
|
SetCondition(r, picked);
|
||||||
|
_editChanged = true;
|
||||||
|
}
|
||||||
|
if (!card || !MetaVocabulary.IsCompositeCondition(r.Condition))
|
||||||
|
{
|
||||||
|
if (!MetaVocabulary.IsCompositeCondition(r.Condition)) ConditionField("##ed_cdata", r, iw, 22);
|
||||||
|
CardClose(card, top, w, GroupColor(r.Condition, false), GroupTint(r.Condition, false), 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
GroupLabel(r.Condition switch
|
||||||
|
{
|
||||||
|
MetaRuleEdit.Not => "Not: true while the condition inside is false",
|
||||||
|
MetaRuleEdit.All => "All of these:",
|
||||||
|
_ => "Any of these:",
|
||||||
|
}, GroupColor(r.Condition, false));
|
||||||
|
if (r.Children.Count == 0) Note("None yet: + Add (top right).");
|
||||||
|
SubRules(r.Children, action: false, 0, r.Condition == MetaRuleEdit.Not ? 1 : int.MaxValue, iw);
|
||||||
|
CardClose(card, top, w, GroupColor(r.Condition, false), GroupTint(r.Condition, false), 0);
|
||||||
}
|
}
|
||||||
if (!MetaVocabulary.IsCompositeCondition(r.Condition))
|
finally
|
||||||
{
|
{
|
||||||
ConditionField("##ed_cdata", r, w, 22);
|
EndBacks(dl);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
SmallLabel(r.Condition switch
|
|
||||||
{
|
|
||||||
MetaRuleEdit.Not => "Not: true while this one is false",
|
|
||||||
MetaRuleEdit.All => "All of these:",
|
|
||||||
_ => "Any of these:",
|
|
||||||
});
|
|
||||||
if (r.Children.Count == 0) Note("None yet: + Add (top right).");
|
|
||||||
SubRules(r.Children, action: false, 0, r.Condition == MetaRuleEdit.Not ? 1 : int.MaxValue, w);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ActionsBody(MetaRuleDto r, float w)
|
private void ActionsBody(MetaRuleDto r, float w)
|
||||||
{
|
{
|
||||||
int picked = FlowPicker("##ed_act", MetaVocabulary.ActionName(r.Action), MetaVocabulary.ActionNames, r.Action, w);
|
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||||
if (picked >= 0 && picked != r.Action)
|
BeginBacks(dl);
|
||||||
|
try
|
||||||
{
|
{
|
||||||
r.Action = picked;
|
bool card = MetaVocabulary.IsAllAction(r.Action); // a DoAll is a box around its actions
|
||||||
if (!MetaVocabulary.IsAllAction(picked)) r.ActionChildren.Clear();
|
Vector2 top = CardOpen(card);
|
||||||
|
float iw = card ? w - CardInset - CardPadR : w;
|
||||||
|
int picked = FlowPicker("##ed_act", MetaVocabulary.ActionName(r.Action), MetaVocabulary.ActionNames, r.Action, iw);
|
||||||
|
if (picked >= 0 && picked != r.Action)
|
||||||
|
{
|
||||||
|
r.Action = picked;
|
||||||
|
if (!MetaVocabulary.IsAllAction(picked)) r.ActionChildren.Clear();
|
||||||
|
_editChanged = true;
|
||||||
|
}
|
||||||
|
if (!card || !MetaVocabulary.IsAllAction(r.Action))
|
||||||
|
{
|
||||||
|
if (!MetaVocabulary.IsAllAction(r.Action)) ActionField("##ed_adata", r, iw, 22, problemLine: true);
|
||||||
|
CardClose(card, top, w, GroupColor(MetaRuleEdit.DoAll, true), GroupTint(MetaRuleEdit.DoAll, true), 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
GroupLabel("All of these, in order:", GroupColor(MetaRuleEdit.DoAll, true));
|
||||||
|
if (r.ActionChildren.Count == 0) Note("None yet: + Add (top right).");
|
||||||
|
SubRules(r.ActionChildren, action: true, 0, int.MaxValue, iw);
|
||||||
|
CardClose(card, top, w, GroupColor(MetaRuleEdit.DoAll, true), GroupTint(MetaRuleEdit.DoAll, true), 0);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
EndBacks(dl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// =====================================================================
|
||||||
|
// Group boxes and row stripes (2026-10-11: "hard to see what's what in All and Any")
|
||||||
|
// =====================================================================
|
||||||
|
//
|
||||||
|
// An All / Any / Not (and a DoAll) is a box: a tint and a border in the group's colour (All
|
||||||
|
// teal, Any amber, Not rose), an accent bar down its left, around its picker and everything in
|
||||||
|
// it; a box inside a box is another, so what belongs where shows at a glance. Rows of a list
|
||||||
|
// alternate a light shade. A box's height is known only after its contents are laid out, so
|
||||||
|
// boxes and stripes are recorded while the rows are placed and drawn at the end on a channel
|
||||||
|
// under them (outer boxes first, each list's stripes over its box).
|
||||||
|
|
||||||
|
private const float CardInset = 9, CardPadR = 5, CardPadT = 5, CardPadB = 4;
|
||||||
|
private static readonly uint Rose = C(0xFFE07A9A), StripeOver = C(0x12FFFFFF);
|
||||||
|
private readonly List<(Vector2 Min, Vector2 Max, uint Fill, uint Border, uint Accent, int Order)> _backs = new();
|
||||||
|
|
||||||
|
private void BeginBacks(ImDrawListPtr dl)
|
||||||
|
{
|
||||||
|
_backs.Clear();
|
||||||
|
dl.ChannelsSplit(2);
|
||||||
|
dl.ChannelsSetCurrent(1); // widgets over the boxes
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EndBacks(ImDrawListPtr dl)
|
||||||
|
{
|
||||||
|
dl.ChannelsSetCurrent(0);
|
||||||
|
// Outer before inner (Order = 2 x depth for a box, + 1 for its list's stripes).
|
||||||
|
_backs.Sort((x, y) => x.Order.CompareTo(y.Order));
|
||||||
|
foreach (var b in _backs)
|
||||||
|
{
|
||||||
|
if (b.Fill != 0) dl.AddRectFilled(b.Min, b.Max, b.Fill, b.Border != 0 ? 4f : 0f);
|
||||||
|
if (b.Accent != 0) dl.AddRectFilled(b.Min, new Vector2(b.Min.X + 3, b.Max.Y), b.Accent, 2f);
|
||||||
|
if (b.Border != 0) dl.AddRect(b.Min, b.Max, b.Border, 4f);
|
||||||
|
}
|
||||||
|
_backs.Clear();
|
||||||
|
dl.ChannelsMerge();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Starts a box at the cursor when <paramref name="card"/> (its contents indented); returns its top-left.</summary>
|
||||||
|
private static Vector2 CardOpen(bool card)
|
||||||
|
{
|
||||||
|
Vector2 top = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||||
|
if (!card) return top;
|
||||||
|
ImGuiNET.ImGui.Indent(CardInset); // moves the cursor in; the box's rows keep to it
|
||||||
|
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(ImGuiNET.ImGui.GetCursorScreenPos().X, top.Y + CardPadT));
|
||||||
|
return top;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Ends a box opened at <paramref name="top"/>, <paramref name="w"/> wide, and records it.</summary>
|
||||||
|
private void CardClose(bool card, Vector2 top, float w, uint color, uint tint, int depth)
|
||||||
|
{
|
||||||
|
if (!card) return;
|
||||||
|
float endY = ImGuiNET.ImGui.GetCursorScreenPos().Y - ImGuiNET.ImGui.GetStyle().ItemSpacing.Y + CardPadB;
|
||||||
|
ImGuiNET.ImGui.Unindent(CardInset);
|
||||||
|
_backs.Add((top, new Vector2(top.X + w, endY), tint, (color & 0x00FFFFFF) | 0x80000000u, color, depth * 2));
|
||||||
|
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(top.X, endY + 3));
|
||||||
|
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A group's colour: All (and DoAll) teal, Any amber, Not rose.</summary>
|
||||||
|
private static uint GroupColor(int kind, bool action) => action ? Teal : kind switch
|
||||||
|
{
|
||||||
|
MetaRuleEdit.Any => Amber,
|
||||||
|
MetaRuleEdit.Not => Rose,
|
||||||
|
_ => Teal,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>A group box's fill: its colour, faint, over the column.</summary>
|
||||||
|
private static uint GroupTint(int kind, bool action) => action ? C(0xFF10262E) : kind switch
|
||||||
|
{
|
||||||
|
MetaRuleEdit.Any => C(0xFF2A2412),
|
||||||
|
MetaRuleEdit.Not => C(0xFF2C1622),
|
||||||
|
_ => C(0xFF10262E),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>What a nested group's line says after its picker.</summary>
|
||||||
|
private static string GroupWords(int kind) => kind switch
|
||||||
|
{
|
||||||
|
MetaRuleEdit.All => "all of the conditions inside",
|
||||||
|
MetaRuleEdit.Any => "any of the conditions inside",
|
||||||
|
_ => "true while the condition inside is false",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static void GroupLabel(string text, uint color)
|
||||||
|
{
|
||||||
|
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
||||||
|
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color);
|
||||||
|
ImGuiNET.ImGui.TextUnformatted(text);
|
||||||
|
ImGuiNET.ImGui.PopStyleColor();
|
||||||
|
ImGuiNET.ImGui.PopFont();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The rule's name: optional, one line; saves like every other change.</summary>
|
||||||
|
private void NameBox(Vector2 pos, float width)
|
||||||
|
{
|
||||||
|
if (!_ruleNameActive && !ReferenceEquals(_ruleNameShown, _editRule.Name))
|
||||||
|
{
|
||||||
|
WriteUtf8(_ruleNameBytes, _editRule.Name);
|
||||||
|
_ruleNameShown = _editRule.Name;
|
||||||
|
}
|
||||||
|
ImGuiNET.ImGui.SetCursorScreenPos(pos);
|
||||||
|
if (_focusRuleName)
|
||||||
|
{
|
||||||
|
ImGuiNET.ImGui.SetKeyboardFocusHere();
|
||||||
|
_focusRuleName = false;
|
||||||
|
}
|
||||||
|
bool edited = TextBox("##ed_name", _ruleNameBytes, width, "Optional: a name to find this rule by",
|
||||||
|
ImGuiInputTextFlags.None, out _ruleNameActive);
|
||||||
|
ImGuiNET.ImGui.SetItemTooltip("Shown in bold over the rule in the list (and instead of its condition in Compact).");
|
||||||
|
_typingNow |= _ruleNameActive; // autosave waits until the box is left
|
||||||
|
if (edited)
|
||||||
|
{
|
||||||
|
string typed = MetaRuleEdit.CleanName(Utf8(_ruleNameBytes));
|
||||||
|
_editRule.Name = typed;
|
||||||
|
_ruleNameShown = typed;
|
||||||
_editChanged = true;
|
_editChanged = true;
|
||||||
}
|
}
|
||||||
if (!MetaVocabulary.IsAllAction(r.Action))
|
|
||||||
{
|
|
||||||
ActionField("##ed_adata", r, w, 22, problemLine: true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
SmallLabel("All of these, in order:");
|
|
||||||
if (r.ActionChildren.Count == 0) Note("None yet: + Add (top right).");
|
|
||||||
SubRules(r.ActionChildren, action: true, 0, int.MaxValue, w);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void SetCondition(MetaRuleDto c, int picked)
|
private static void SetCondition(MetaRuleDto c, int picked)
|
||||||
|
|
@ -385,15 +551,21 @@ internal sealed partial class MetaFace
|
||||||
}
|
}
|
||||||
if (problemLine) extra = ProblemLine(id, new Vector2(p.X, p.Y + height), width);
|
if (problemLine) extra = ProblemLine(id, new Vector2(p.X, p.Y + height), width);
|
||||||
}
|
}
|
||||||
else if (a.Action == 3) // Embedded Nav Route
|
else if (a.Action == 3) // Embedded Nav Route: Patrol, nav files, the meta's routes
|
||||||
{
|
{
|
||||||
int picked = Picker(id, a.ActionData.Length == 0 ? "Select route..." : a.ActionData, _routePicks,
|
int sel = IndexOf(_routeValues, a.ActionData);
|
||||||
Array.IndexOf(_routePicks, a.ActionData), p, width, height);
|
string shown = a.ActionData.Length == 0 ? "Select route..." : sel >= 0 ? _routeLabels[sel] : a.ActionData;
|
||||||
if (picked >= 0 && _routePicks[picked] != a.ActionData)
|
int picked = Picker(id, shown, _routeLabels, sel, p, width, height);
|
||||||
|
if (picked >= 0 && _routeValues[picked] != a.ActionData)
|
||||||
{
|
{
|
||||||
a.ActionData = _routePicks[picked];
|
a.ActionData = _routeValues[picked]; // the name RynthAi looks up, not the list's label
|
||||||
_editChanged = true;
|
_editChanged = true;
|
||||||
}
|
}
|
||||||
|
// (The picker's last item is a spacer, so the hover is checked on its rectangle.)
|
||||||
|
if (MetaVocabulary.PatrolRoute.Equals(a.ActionData, StringComparison.OrdinalIgnoreCase)
|
||||||
|
&& !MetaVocabulary.HasRoute(_data, a.ActionData)
|
||||||
|
&& ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.IsMouseHoveringRect(p, p + new Vector2(width, height)))
|
||||||
|
ImGuiNET.ImGui.SetTooltip("RynthAi's dungeon patrol (/ra dunnav-patrol): a circular hunt through every room of the dungeon you're in. Needs no nav file; only works inside a dungeon.");
|
||||||
}
|
}
|
||||||
else if (!MetaRuleEdit.ActionTakesData(a.Action) && a.ActionData.Length == 0)
|
else if (!MetaRuleEdit.ActionTakesData(a.Action) && a.ActionData.Length == 0)
|
||||||
NoteAt(p, "Nothing to set.", height);
|
NoteAt(p, "Nothing to set.", height);
|
||||||
|
|
@ -407,58 +579,87 @@ internal sealed partial class MetaFace
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sub-conditions nest (All/Any/Not under All/Any/Not, MaxSubConditionDepth levels; a Not takes
|
// Sub-conditions nest (All/Any/Not under All/Any/Not, MaxSubConditionDepth levels; a Not takes
|
||||||
// one); DoAll's sub-actions are a flat list. Each row: [type][value][x]; in a narrow column the
|
// one); DoAll's sub-actions are a flat list that runs in order, so each is numbered and has up /
|
||||||
// value goes on a second line. The top level's "+ Add" is in the column header.
|
// down. A row: [type][value]([up][down])[x]; every other row a light shade; in a narrow column the
|
||||||
|
// value goes on a second line. A nested All / Any / Not is a box (its picker, what it means, then
|
||||||
|
// its conditions inside, indented). The top level's "+ Add" is in the column header.
|
||||||
private void SubRules(List<MetaRuleDto> subs, bool action, int depth, int maxCount, float w)
|
private void SubRules(List<MetaRuleDto> subs, bool action, int depth, int maxCount, float w)
|
||||||
{
|
{
|
||||||
string[] names = action ? MetaVocabulary.ActionNames : MetaVocabulary.ConditionNames;
|
string[] names = action ? MetaVocabulary.ActionNames : MetaVocabulary.ConditionNames;
|
||||||
bool narrow = w < 300;
|
bool narrow = w < 300;
|
||||||
const float rh = 20, xw = 20;
|
const float rh = 20, xw = 20, aw = 16, childIndent = 10;
|
||||||
for (int i = 0; i < subs.Count; i++)
|
for (int i = 0; i < subs.Count; i++)
|
||||||
{
|
{
|
||||||
MetaRuleDto sub = subs[i];
|
MetaRuleDto sub = subs[i];
|
||||||
ImGuiNET.ImGui.PushID(i);
|
ImGuiNET.ImGui.PushID(i);
|
||||||
|
bool nests = !action && MetaVocabulary.IsCompositeCondition(sub.Condition) && depth < MetaVocabulary.MaxSubConditionDepth;
|
||||||
|
Vector2 cardTop = CardOpen(nests);
|
||||||
|
float rw = nests ? w - CardInset - CardPadR : w; // the row's width (inside its box)
|
||||||
|
float tools = xw + (action ? 2 * (aw + 2) : 0); // [up][down][x] or [x]
|
||||||
|
float lead = action ? 16 : 0; // a DoAll's step number
|
||||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||||
float pickW = narrow ? w - xw - 4 : (w - xw - 8) * 0.45f;
|
float pickW = narrow ? rw - tools - lead - 4 : (rw - tools - lead - 8) * 0.45f;
|
||||||
|
|
||||||
|
if (action)
|
||||||
|
{
|
||||||
|
string step = (i + 1).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
ImGuiNET.ImGui.GetWindowDrawList().AddText(
|
||||||
|
new Vector2(p.X + lead - 4 - ImGuiNET.ImGui.CalcTextSize(step).X, p.Y + (rh - ImGuiNET.ImGui.GetFontSize()) * 0.5f),
|
||||||
|
Faded(Mute), step);
|
||||||
|
}
|
||||||
int current = action ? sub.Action : sub.Condition;
|
int current = action ? sub.Action : sub.Condition;
|
||||||
string shown = action ? MetaVocabulary.ActionName(sub.Action) : MetaVocabulary.ConditionName(sub.Condition);
|
string shown = action ? MetaVocabulary.ActionName(sub.Action) : MetaVocabulary.ConditionName(sub.Condition);
|
||||||
int picked = Picker("##type", shown, names, current, p, pickW, rh);
|
int picked = Picker("##type", shown, names, current, new Vector2(p.X + lead, p.Y), pickW, rh);
|
||||||
if (picked >= 0 && picked != current)
|
if (picked >= 0 && picked != current)
|
||||||
{
|
{
|
||||||
if (action) sub.Action = picked; else SetCondition(sub, picked);
|
if (action) sub.Action = picked; else SetCondition(sub, picked);
|
||||||
_editChanged = true;
|
_editChanged = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool nests = !action && MetaVocabulary.IsCompositeCondition(sub.Condition) && depth < MetaVocabulary.MaxSubConditionDepth;
|
bool removed = IconButton("##rm", PhosphorIcons.X, new Vector2(p.X + rw - xw, p.Y), new Vector2(xw, rh), TextDim, DelFill, BtnBord);
|
||||||
bool removed = IconButton("##rm", PhosphorIcons.X, new Vector2(p.X + w - xw, p.Y), new Vector2(xw, rh), TextDim, DelFill, BtnBord);
|
ImGuiNET.ImGui.SetItemTooltip(action ? "Remove this action" : nests ? "Remove this group and what is in it" : "Remove this condition");
|
||||||
ImGuiNET.ImGui.SetItemTooltip(action ? "Remove this action" : "Remove this condition");
|
int moveTo = -1;
|
||||||
|
if (action)
|
||||||
|
{
|
||||||
|
float ax = p.X + rw - xw - 2 - 2 * (aw + 2);
|
||||||
|
if (IconButton("##sub_up", PhosphorIcons.ArrowUp, new Vector2(ax, p.Y), new Vector2(aw, rh), Mute, BtnFill, BtnBord, enabled: i > 0))
|
||||||
|
moveTo = i - 1;
|
||||||
|
ImGuiNET.ImGui.SetItemTooltip("Run this action earlier");
|
||||||
|
if (IconButton("##sub_dn", PhosphorIcons.ArrowDown, new Vector2(ax + aw + 2, p.Y), new Vector2(aw, rh), Mute, BtnFill, BtnBord,
|
||||||
|
enabled: i < subs.Count - 1))
|
||||||
|
moveTo = i + 1;
|
||||||
|
ImGuiNET.ImGui.SetItemTooltip("Run this action later");
|
||||||
|
}
|
||||||
|
|
||||||
float rowH = rh;
|
float rowH = rh;
|
||||||
if (nests)
|
if (nests)
|
||||||
{
|
{
|
||||||
if (!narrow)
|
if (!narrow)
|
||||||
NoteAt(new Vector2(p.X + pickW + 6, p.Y), sub.Condition == MetaRuleEdit.Not ? "(the condition below)" : "(the conditions below)", rh);
|
NoteAt(new Vector2(p.X + pickW + 6, p.Y), GroupWords(sub.Condition), rh, GroupColor(sub.Condition, false));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Vector2 vp = narrow ? new Vector2(p.X + 12, p.Y + rh + 2) : new Vector2(p.X + pickW + 4, p.Y);
|
Vector2 vp = narrow ? new Vector2(p.X + lead + 12, p.Y + rh + 2) : new Vector2(p.X + lead + pickW + 4, p.Y);
|
||||||
float vw = narrow ? w - 12 : w - pickW - 4 - xw - 4;
|
float vw = narrow ? rw - lead - 12 : rw - lead - pickW - 4 - tools - 4;
|
||||||
ImGuiNET.ImGui.SetCursorScreenPos(vp);
|
ImGuiNET.ImGui.SetCursorScreenPos(vp);
|
||||||
if (action) ActionField("##data", sub, vw, rh, problemLine: false);
|
if (action) ActionField("##data", sub, vw, rh, problemLine: false);
|
||||||
else ConditionField("##data", sub, vw, rh);
|
else ConditionField("##data", sub, vw, rh);
|
||||||
if (narrow) rowH = rh * 2 + 2;
|
if (narrow) rowH = rh * 2 + 2;
|
||||||
|
// Every other row a light shade, reaching halfway into the gaps so the shades meet.
|
||||||
|
if (i % 2 == 1)
|
||||||
|
_backs.Add((new Vector2(p.X - 4, p.Y - 4.5f), new Vector2(p.X + rw + 3, p.Y + rowH + 4.5f), StripeOver, 0, 0, depth * 2 + 1));
|
||||||
}
|
}
|
||||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + rowH + 2));
|
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + rowH + 5));
|
||||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
||||||
|
|
||||||
if (!removed && nests)
|
if (!removed && nests)
|
||||||
{
|
{
|
||||||
ImGuiNET.ImGui.Indent(14);
|
ImGuiNET.ImGui.Indent(childIndent);
|
||||||
SmallLabel(sub.Condition switch { MetaRuleEdit.Not => "Not:", MetaRuleEdit.All => "All of:", _ => "Any of:" });
|
if (sub.Children.Count == 0) Note("None yet: + Add below.");
|
||||||
SubRules(sub.Children, action: false, depth + 1, sub.Condition == MetaRuleEdit.Not ? 1 : int.MaxValue, w - 14);
|
SubRules(sub.Children, action: false, depth + 1, sub.Condition == MetaRuleEdit.Not ? 1 : int.MaxValue, rw - childIndent);
|
||||||
ImGuiNET.ImGui.Unindent(14);
|
ImGuiNET.ImGui.Unindent(childIndent);
|
||||||
}
|
}
|
||||||
|
CardClose(nests, cardTop, w, GroupColor(sub.Condition, false), GroupTint(sub.Condition, false), depth + 1);
|
||||||
ImGuiNET.ImGui.PopID();
|
ImGuiNET.ImGui.PopID();
|
||||||
if (removed)
|
if (removed)
|
||||||
{
|
{
|
||||||
|
|
@ -466,6 +667,12 @@ internal sealed partial class MetaFace
|
||||||
_editChanged = true;
|
_editChanged = true;
|
||||||
break; // indices shifted: the rest draws next frame
|
break; // indices shifted: the rest draws next frame
|
||||||
}
|
}
|
||||||
|
if (moveTo >= 0)
|
||||||
|
{
|
||||||
|
(subs[i], subs[moveTo]) = (subs[moveTo], subs[i]);
|
||||||
|
_editChanged = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Nested groups get their own Add; the top level's is in the column header.
|
// Nested groups get their own Add; the top level's is in the column header.
|
||||||
|
|
@ -539,12 +746,12 @@ internal sealed partial class MetaFace
|
||||||
/// (<paramref name="isNew"/> true) once its name box is confirmed; else null.
|
/// (<paramref name="isNew"/> true) once its name box is confirmed; else null.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private string? StatePicker(string id, string shown, string[] items, int selected, Vector2 pos, float width, out bool isNew,
|
private string? StatePicker(string id, string shown, string[] items, int selected, Vector2 pos, float width, out bool isNew,
|
||||||
float height = 22)
|
float height = 22, string? badge = null)
|
||||||
{
|
{
|
||||||
isNew = false;
|
isNew = false;
|
||||||
uint key = ImGuiNET.ImGui.GetID(id);
|
uint key = ImGuiNET.ImGui.GetID(id);
|
||||||
if (_namingKey == key) return NamingBox(id, pos, width, height, out isNew);
|
if (_namingKey == key) return NamingBox(id, pos, width, height, out isNew);
|
||||||
int picked = Picker(id, shown, items, selected, pos, width, height, NewStateEntry);
|
int picked = Picker(id, shown, items, selected, pos, width, height, NewStateEntry, badge);
|
||||||
if (picked == items.Length)
|
if (picked == items.Length)
|
||||||
{
|
{
|
||||||
_namingKey = key;
|
_namingKey = key;
|
||||||
|
|
@ -650,12 +857,6 @@ internal sealed partial class MetaFace
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void SmallLabel(string text)
|
|
||||||
{
|
|
||||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
|
||||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), text);
|
|
||||||
ImGuiNET.ImGui.PopFont();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void Note(string text)
|
private static void Note(string text)
|
||||||
{
|
{
|
||||||
|
|
@ -664,8 +865,9 @@ internal sealed partial class MetaFace
|
||||||
ImGuiNET.ImGui.PopFont();
|
ImGuiNET.ImGui.PopFont();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void NoteAt(Vector2 p, string text, float height)
|
private static void NoteAt(Vector2 p, string text, float height, uint color = 0)
|
||||||
{
|
{
|
||||||
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + 4, p.Y + (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute), text);
|
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + 4, p.Y + (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f),
|
||||||
|
color != 0 ? color : Faded(Mute), text);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
1069
src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs
Normal file
1069
src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -207,7 +207,7 @@ internal sealed partial class MetaFace
|
||||||
ScheduleRuleDto r = sc.Rules[i];
|
ScheduleRuleDto r = sc.Rules[i];
|
||||||
bool first = i == sc.FirstMatch && sc.Enabled;
|
bool first = i == sc.FirstMatch && sc.Enabled;
|
||||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
||||||
dl.AddRectFilled(p, p + new Vector2(w, h), i % 2 == 0 ? PanelBg : RowAlt);
|
dl.AddRectFilled(p, p + new Vector2(w, h), i % 2 == 0 ? StripeA : StripeB);
|
||||||
ImGuiNET.ImGui.PushID(1000 + i);
|
ImGuiNET.ImGui.PushID(1000 + i);
|
||||||
bool changed = false;
|
bool changed = false;
|
||||||
float x = p.X + 1;
|
float x = p.X + 1;
|
||||||
|
|
|
||||||
|
|
@ -3,11 +3,13 @@
|
||||||
// ImGui face of the Meta panel (docs/IMGUI_PARITY_PLAN.md §2.13), with the
|
// ImGui face of the Meta panel (docs/IMGUI_PARITY_PLAN.md §2.13), with the
|
||||||
// Avalonia face's look and three views:
|
// Avalonia face's look and three views:
|
||||||
//
|
//
|
||||||
// List file picker / refresh / Save As / "Saved" indicator; Visual|Source;
|
// List (MetaFace.List.cs) file picker / refresh / Save As / "Saved"
|
||||||
// Meta, Debug; rules grouped by state (collapsible, red while
|
// indicator; Visual|Source; Meta, Debug; a filter; rules grouped
|
||||||
// firing), rows with enable, expand, up/down within the state,
|
// by state, each rule in full (every condition and action on its
|
||||||
// duplicate, and delete on the far right (click twice); click a row
|
// own line, or one line in Compact) with lines between rules and
|
||||||
// to edit it; State picker and New Rule at the bottom.
|
// columns; move / duplicate / delete on the hovered row and on
|
||||||
|
// right-click; click a row to edit it; State picker and New Rule
|
||||||
|
// at the bottom.
|
||||||
// Editor (MetaFace.Editor.cs) state; Conditions and Actions side by side
|
// Editor (MetaFace.Editor.cs) state; Conditions and Actions side by side
|
||||||
// (stacked when the panel is narrow), each with "+ Add"; Set current
|
// (stacked when the panel is narrow), each with "+ Add"; Set current
|
||||||
// for landblock / landcell; every change saves on its own.
|
// for landblock / landcell; every change saves on its own.
|
||||||
|
|
@ -55,7 +57,7 @@ internal sealed partial class MetaFace : IImGuiPanel
|
||||||
private static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Green = C(0xFF33CC66),
|
private static readonly uint Teal = C(0xFF26D9E6), Amber = C(0xFFE8B333), Green = C(0xFF33CC66),
|
||||||
Red = C(0xFFE04848), Mute = C(0xFFC8D6E4), TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14),
|
Red = C(0xFFE04848), Mute = C(0xFFC8D6E4), TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14),
|
||||||
PanelBg = C(0xFF141F29), RowAlt = C(0xFF101822), BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A),
|
PanelBg = C(0xFF141F29), RowAlt = C(0xFF101822), BtnFill = C(0xFF16283A), BtnBord = C(0xFF34587A),
|
||||||
Fired = C(0xFF3A1212), BtnOn = C(0xFF0E2E3A), StateHdrA = C(0xFF0E1E30), StateHdrB = C(0xFF162A40),
|
Fired = C(0xFF3A1212), BtnOn = C(0xFF0E2E3A), StateHdrA = C(0xFF0E1E30),
|
||||||
DelFill = C(0xFF7A1414), NewFill = C(0xFF0E2E1A), PickSel = C(0xFF1A2E42);
|
DelFill = C(0xFF7A1414), NewFill = C(0xFF0E2E1A), PickSel = C(0xFF1A2E42);
|
||||||
private static uint C(uint argb) => RynthTheme.Argb(argb);
|
private static uint C(uint argb) => RynthTheme.Argb(argb);
|
||||||
private static uint Faded(uint abgr) => (abgr & 0x00FFFFFF) | ((abgr >> 25) << 24); // half alpha
|
private static uint Faded(uint abgr) => (abgr & 0x00FFFFFF) | ((abgr >> 25) << 24); // half alpha
|
||||||
|
|
@ -66,11 +68,9 @@ internal sealed partial class MetaFace : IImGuiPanel
|
||||||
private MetaPayload _data = new();
|
private MetaPayload _data = new();
|
||||||
private long _seenVersion = -1;
|
private long _seenVersion = -1;
|
||||||
private List<(string State, List<int> Rules)> _groups = new();
|
private List<(string State, List<int> Rules)> _groups = new();
|
||||||
private string[] _condText = Array.Empty<string>(), _actText = Array.Empty<string>();
|
|
||||||
private string[] _groupLabel = Array.Empty<string>();
|
|
||||||
private bool[] _groupFiring = Array.Empty<bool>();
|
private bool[] _groupFiring = Array.Empty<bool>();
|
||||||
private string[] _statePicks = Array.Empty<string>(), _statesOnly = Array.Empty<string>();
|
private string[] _statePicks = Array.Empty<string>(), _statesOnly = Array.Empty<string>();
|
||||||
private string[] _routePicks = Array.Empty<string>(), _fileDisplays = Array.Empty<string>();
|
private string[] _routeLabels = Array.Empty<string>(), _routeValues = Array.Empty<string>(), _fileDisplays = Array.Empty<string>();
|
||||||
private string _fileDisplay = "-- None --", _sourceFileLabel = "File: Unsaved";
|
private string _fileDisplay = "-- None --", _sourceFileLabel = "File: Unsaved";
|
||||||
private IReadOnlyList<string> _completionNavs = Array.Empty<string>();
|
private IReadOnlyList<string> _completionNavs = Array.Empty<string>();
|
||||||
|
|
||||||
|
|
@ -78,8 +78,8 @@ internal sealed partial class MetaFace : IImGuiPanel
|
||||||
private readonly Dictionary<(string Text, int Width), string> _fit = new();
|
private readonly Dictionary<(string Text, int Width), string> _fit = new();
|
||||||
|
|
||||||
private View _view = View.List;
|
private View _view = View.List;
|
||||||
|
private readonly MetaStateClock _stateClock = new();
|
||||||
private readonly HashSet<string> _collapsed = new();
|
private readonly HashSet<string> _collapsed = new();
|
||||||
private readonly HashSet<int> _expanded = new();
|
|
||||||
private bool _saveAs, _saveAsFocus;
|
private bool _saveAs, _saveAsFocus;
|
||||||
private readonly byte[] _saveName = new byte[128];
|
private readonly byte[] _saveName = new byte[128];
|
||||||
|
|
||||||
|
|
@ -195,6 +195,7 @@ internal sealed partial class MetaFace : IImGuiPanel
|
||||||
if (snap == null || snap.Version == _seenVersion) return;
|
if (snap == null || snap.Version == _seenVersion) return;
|
||||||
_seenVersion = snap.Version;
|
_seenVersion = snap.Version;
|
||||||
MetaPayload fresh = snap.Value;
|
MetaPayload fresh = snap.Value;
|
||||||
|
_stateClock.Snapshot(fresh.Snapshot, NowMs);
|
||||||
CheckApplyResult(fresh);
|
CheckApplyResult(fresh);
|
||||||
_data = fresh.Clone();
|
_data = fresh.Clone();
|
||||||
RebuildCaches();
|
RebuildCaches();
|
||||||
|
|
@ -211,21 +212,12 @@ internal sealed partial class MetaFace : IImGuiPanel
|
||||||
{
|
{
|
||||||
List<MetaRuleDto> rules = _data.Rules;
|
List<MetaRuleDto> rules = _data.Rules;
|
||||||
_groups = MetaVocabulary.GroupByState(rules);
|
_groups = MetaVocabulary.GroupByState(rules);
|
||||||
_condText = new string[rules.Count];
|
|
||||||
_actText = new string[rules.Count];
|
|
||||||
for (int i = 0; i < rules.Count; i++)
|
|
||||||
{
|
|
||||||
_condText[i] = MetaVocabulary.RowConditionText(rules[i]);
|
|
||||||
_actText[i] = MetaVocabulary.RowActionText(rules[i]);
|
|
||||||
}
|
|
||||||
_groupLabel = new string[_groups.Count];
|
|
||||||
_groupFiring = new bool[_groups.Count];
|
_groupFiring = new bool[_groups.Count];
|
||||||
for (int g = 0; g < _groups.Count; g++)
|
for (int g = 0; g < _groups.Count; g++)
|
||||||
{
|
{
|
||||||
bool firing = false;
|
bool firing = false;
|
||||||
foreach (int i in _groups[g].Rules) firing |= rules[i].LastFiredMs < 1500;
|
foreach (int i in _groups[g].Rules) firing |= rules[i].LastFiredMs < 1500;
|
||||||
_groupFiring[g] = firing;
|
_groupFiring[g] = firing;
|
||||||
_groupLabel[g] = firing ? $"{_groups[g].State} ({_groups[g].Rules.Count}) — firing" : $"{_groups[g].State} ({_groups[g].Rules.Count})";
|
|
||||||
}
|
}
|
||||||
// States made here that the snapshot doesn't list yet (dropped once it does, or on a meta switch).
|
// States made here that the snapshot doesn't list yet (dropped once it does, or on a meta switch).
|
||||||
if (!string.Equals(_statesPath, _data.CurrentMetaPath, StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(_statesPath, _data.CurrentMetaPath, StringComparison.OrdinalIgnoreCase))
|
||||||
|
|
@ -241,47 +233,20 @@ internal sealed partial class MetaFace : IImGuiPanel
|
||||||
_statePicks = With(_statePicks, s);
|
_statePicks = With(_statePicks, s);
|
||||||
_statesOnly = With(_statesOnly, s);
|
_statesOnly = With(_statesOnly, s);
|
||||||
}
|
}
|
||||||
_routePicks = MetaVocabulary.RoutePicks(_data);
|
(_routeLabels, _routeValues) = MetaVocabulary.RoutePicks(_data);
|
||||||
_fileDisplays = new string[_data.Files.Count];
|
_fileDisplays = new string[_data.Files.Count];
|
||||||
for (int i = 0; i < _fileDisplays.Length; i++) _fileDisplays[i] = _data.Files[i].Display;
|
for (int i = 0; i < _fileDisplays.Length; i++) _fileDisplays[i] = _data.Files[i].Display;
|
||||||
_fileDisplay = MetaVocabulary.CurrentFileDisplay(_data);
|
_fileDisplay = MetaVocabulary.CurrentFileDisplay(_data);
|
||||||
_sourceFileLabel = "File: " + (string.IsNullOrEmpty(_data.CurrentMetaPath) ? "Unsaved" : System.IO.Path.GetFileName(_data.CurrentMetaPath));
|
_sourceFileLabel = "File: " + (string.IsNullOrEmpty(_data.CurrentMetaPath) ? "Unsaved" : System.IO.Path.GetFileName(_data.CurrentMetaPath));
|
||||||
_completionNavs = MetaVocabulary.CompletionNavs(_data);
|
_completionNavs = MetaVocabulary.CompletionNavs(_data);
|
||||||
_fit.Clear();
|
_fit.Clear();
|
||||||
|
RebuildListText(rules); // after the states: a Set State to a missing state shows in red
|
||||||
}
|
}
|
||||||
|
|
||||||
// =====================================================================
|
// =====================================================================
|
||||||
// List view
|
// File bar and mode row (the list itself: MetaFace.List.cs)
|
||||||
// =====================================================================
|
// =====================================================================
|
||||||
|
|
||||||
private void ListView(Vector2 origin, Vector2 size)
|
|
||||||
{
|
|
||||||
float w = size.X;
|
|
||||||
LoadSaveBar(w);
|
|
||||||
Separator(w);
|
|
||||||
ModeRow(w, source: false);
|
|
||||||
Separator(w);
|
|
||||||
if (_listNote.Length > 0 && NowMs - _listNoteAt < 8000)
|
|
||||||
{
|
|
||||||
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
|
|
||||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), Fit(_listNote, w));
|
|
||||||
ImGuiNET.ImGui.PopFont();
|
|
||||||
}
|
|
||||||
|
|
||||||
const float bottomH = 24;
|
|
||||||
float listH = Math.Max(40, origin.Y + size.Y - ImGuiNET.ImGui.GetCursorScreenPos().Y - bottomH - 9);
|
|
||||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, 0);
|
|
||||||
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
|
|
||||||
ImGuiNET.ImGui.BeginChild("##meta_rules", new Vector2(w, listH));
|
|
||||||
RuleList(ImGuiNET.ImGui.GetContentRegionAvail().X);
|
|
||||||
ImGuiNET.ImGui.EndChild();
|
|
||||||
ImGuiNET.ImGui.PopStyleVar();
|
|
||||||
ImGuiNET.ImGui.PopStyleColor();
|
|
||||||
|
|
||||||
Separator(w);
|
|
||||||
BottomBar(w);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void LoadSaveBar(float w)
|
private void LoadSaveBar(float w)
|
||||||
{
|
{
|
||||||
if (_saveAs)
|
if (_saveAs)
|
||||||
|
|
@ -458,255 +423,8 @@ internal sealed partial class MetaFace : IImGuiPanel
|
||||||
_editor.RequestFocus();
|
_editor.RequestFocus();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Condition/action split of the rule list (dragged in its header) and where
|
// Condition/action split of the rule list (dragged in its header; saved per PC).
|
||||||
// the text starts within a row (from the last row drawn).
|
|
||||||
private static float _condFrac = Math.Clamp(RynthCore.Engine.UI.PanelColumnStore.Get("Meta.condFrac", 0.5f), 0.15f, 0.85f);
|
private static float _condFrac = Math.Clamp(RynthCore.Engine.UI.PanelColumnStore.Get("Meta.condFrac", 0.5f), 0.15f, 0.85f);
|
||||||
private float _textStartOff;
|
|
||||||
/// <summary>The far-right delete button and the gap before it: the row text ends this far from the edge.</summary>
|
|
||||||
private const float DeleteColumnW = 30;
|
|
||||||
|
|
||||||
private void RuleList(float w)
|
|
||||||
{
|
|
||||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
|
||||||
if (_groups.Count == 0)
|
|
||||||
{
|
|
||||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
|
|
||||||
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), " No rules. Click New Rule to add one.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
|
|
||||||
List<MetaRuleDto> rules = _data.Rules;
|
|
||||||
|
|
||||||
// Condition | Action header; drag the divider to move the split (saved per PC).
|
|
||||||
if (_textStartOff > 0)
|
|
||||||
{
|
|
||||||
Vector2 hp = ImGuiNET.ImGui.GetCursorScreenPos();
|
|
||||||
const float hh = 16;
|
|
||||||
float tx = hp.X + _textStartOff, tw = Math.Max(1, hp.X + w - DeleteColumnW - tx);
|
|
||||||
float split = tw * _condFrac;
|
|
||||||
float hy = hp.Y + (hh - bold.FontSize) * 0.5f;
|
|
||||||
dl.AddText(bold, bold.FontSize, new Vector2(tx + 3, hy), C(0xFFC8D6E4), "Condition");
|
|
||||||
dl.AddText(bold, bold.FontSize, new Vector2(tx + split + 4, hy), C(0xFFC8D6E4), "Action");
|
|
||||||
if (FaceKit.ColumnDivider("##meta_split", tx + split, hp.Y, hh, ref split, 40,
|
|
||||||
_ => RynthCore.Engine.UI.PanelColumnStore.Set("Meta.condFrac", _condFrac)))
|
|
||||||
_condFrac = Math.Clamp(split / tw, 0.15f, 0.85f);
|
|
||||||
ImGuiNET.ImGui.Dummy(new Vector2(w, hh));
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int g = 0; g < _groups.Count; g++)
|
|
||||||
{
|
|
||||||
(string state, List<int> members) = _groups[g];
|
|
||||||
bool collapsed = _collapsed.Contains(state);
|
|
||||||
bool firing = _groupFiring[g];
|
|
||||||
|
|
||||||
// Header: caret, State (n) [— firing]; click toggles.
|
|
||||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
|
|
||||||
Vector2 hp = ImGuiNET.ImGui.GetCursorScreenPos();
|
|
||||||
float hh = bold.FontSize + 6;
|
|
||||||
ImGuiNET.ImGui.PushID(g);
|
|
||||||
if (ImGuiNET.ImGui.InvisibleButton("##hdr", new Vector2(w, hh)))
|
|
||||||
{
|
|
||||||
if (collapsed) _collapsed.Remove(state); else _collapsed.Add(state);
|
|
||||||
}
|
|
||||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
|
|
||||||
ImGuiNET.ImGui.PopID();
|
|
||||||
uint hc = firing ? Red : Amber;
|
|
||||||
dl.AddRectFilled(hp, hp + new Vector2(w, hh), g % 2 == 0 ? StateHdrA : StateHdrB);
|
|
||||||
dl.AddText(bold, bold.FontSize, hp + new Vector2(3, 3), hc, collapsed ? PhosphorIcons.CaretRight : PhosphorIcons.CaretDown);
|
|
||||||
dl.AddText(bold, bold.FontSize, hp + new Vector2(18, 3), hc, _groupLabel[g]);
|
|
||||||
if (collapsed) continue;
|
|
||||||
|
|
||||||
for (int gi = 0; gi < members.Count; gi++)
|
|
||||||
{
|
|
||||||
int index = members[gi];
|
|
||||||
if (index >= rules.Count) break;
|
|
||||||
if (RuleRow(rules[index], index, gi, members.Count, w)) return; // the list changed: redraw next frame
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>One rule row plus its expanded children. True when a click changed the list.</summary>
|
|
||||||
private bool RuleRow(MetaRuleDto rule, int index, int gi, int groupCount, float w)
|
|
||||||
{
|
|
||||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
|
||||||
bool firing = rule.LastFiredMs < 1500;
|
|
||||||
bool hasChildren = (MetaVocabulary.IsCompositeCondition(rule.Condition) && rule.Children.Count > 0)
|
|
||||||
|| (MetaVocabulary.IsAllAction(rule.Action) && rule.ActionChildren.Count > 0);
|
|
||||||
bool expanded = _expanded.Contains(index);
|
|
||||||
|
|
||||||
const float h = 20;
|
|
||||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
|
||||||
dl.AddRectFilled(p, p + new Vector2(w, h), firing ? Fired : gi % 2 == 0 ? PanelBg : RowAlt);
|
|
||||||
ImGuiNET.ImGui.PushID(index);
|
|
||||||
bool changed = false;
|
|
||||||
|
|
||||||
// Enable
|
|
||||||
float x = p.X + 1;
|
|
||||||
if (IconButton("##en", rule.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square, new Vector2(x, p.Y + 2), new Vector2(14, 16),
|
|
||||||
rule.Enabled ? Green : Mute, BtnFill, BtnBord))
|
|
||||||
{
|
|
||||||
rule.Enabled = !rule.Enabled;
|
|
||||||
SendEdit(new MetaCmd { Op = "set_rule_enabled", Index = index, Value = rule.Enabled ? "true" : "false" });
|
|
||||||
}
|
|
||||||
ImGuiNET.ImGui.SetItemTooltip(rule.Enabled ? "Enabled — click to disable" : "Disabled — click to enable");
|
|
||||||
x += 16;
|
|
||||||
|
|
||||||
// Expand (only with children)
|
|
||||||
if (hasChildren && IconButton("##exp", expanded ? PhosphorIcons.Minus : PhosphorIcons.Plus, new Vector2(x + 2, p.Y + 3), new Vector2(14, 14),
|
|
||||||
Teal, BtnFill, BtnBord))
|
|
||||||
{
|
|
||||||
if (expanded) _expanded.Remove(index); else _expanded.Add(index);
|
|
||||||
}
|
|
||||||
x += 18;
|
|
||||||
|
|
||||||
// Up / down within the state (Appendix A3: the plugin now swaps within the state too)
|
|
||||||
if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord, enabled: gi > 0))
|
|
||||||
changed |= Move(index, -1);
|
|
||||||
ImGuiNET.ImGui.SetItemTooltip("Move up");
|
|
||||||
x += 18;
|
|
||||||
if (IconButton("##dn", PhosphorIcons.ArrowDown, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord,
|
|
||||||
enabled: gi < groupCount - 1))
|
|
||||||
changed |= Move(index, +1);
|
|
||||||
ImGuiNET.ImGui.SetItemTooltip("Move down");
|
|
||||||
x += 18;
|
|
||||||
|
|
||||||
// Duplicate
|
|
||||||
if (IconButton("##dup", PhosphorIcons.Copy, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord))
|
|
||||||
{
|
|
||||||
SendEdit(new MetaCmd { Op = "duplicate_rule", Index = index, Rule = rule.Clone() });
|
|
||||||
_data.Rules.Insert(Math.Min(index + 1, _data.Rules.Count), rule.Clone());
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
ImGuiNET.ImGui.SetItemTooltip("Duplicate rule");
|
|
||||||
x += 20;
|
|
||||||
|
|
||||||
// Delete: on its own at the far right, away from the other buttons (2026-10-05). A rule
|
|
||||||
// with anything in it takes a second click within 3 s; an empty Never -> None one goes at once.
|
|
||||||
bool arming = _confirmDeleteIndex == index && _confirmDelete != null && NowMs < _confirmDeleteUntil
|
|
||||||
&& MetaRuleEdit.SameContent(_confirmDelete, rule);
|
|
||||||
float delW = arming ? BtnW("Delete?", 50) : 20;
|
|
||||||
float delX = p.X + w - delW - 2;
|
|
||||||
if (arming
|
|
||||||
? Button("Delete?##del", new Vector2(delX, p.Y + 2), new Vector2(delW, 16), TextDim, DelFill, Red)
|
|
||||||
: IconButton("##del", PhosphorIcons.Trash, new Vector2(delX, p.Y + 2), new Vector2(delW, 16), TextDim, DelFill, BtnBord))
|
|
||||||
{
|
|
||||||
if (arming || MetaRuleEdit.IsPlaceholder(rule))
|
|
||||||
{
|
|
||||||
SendEdit(new MetaCmd { Op = "delete_rule", Index = index });
|
|
||||||
_data.Rules.RemoveAt(index);
|
|
||||||
_expanded.Clear();
|
|
||||||
_confirmDelete = null;
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_confirmDelete = rule.Clone();
|
|
||||||
_confirmDeleteIndex = index;
|
|
||||||
_confirmDeleteUntil = NowMs + 3000;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ImGuiNET.ImGui.SetItemTooltip(arming ? "Click again to delete this rule" : "Delete rule");
|
|
||||||
|
|
||||||
// Condition | action text; clicking it edits the rule.
|
|
||||||
float textW = Math.Max(1, p.X + w - DeleteColumnW - x);
|
|
||||||
_textStartOff = x - p.X;
|
|
||||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y));
|
|
||||||
if (ImGuiNET.ImGui.InvisibleButton("##edit", new Vector2(textW, h)))
|
|
||||||
OpenEditor(index, rule);
|
|
||||||
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
|
|
||||||
ImGuiNET.ImGui.PopID();
|
|
||||||
|
|
||||||
if (!changed)
|
|
||||||
{
|
|
||||||
float col = textW * _condFrac;
|
|
||||||
float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
|
|
||||||
uint condCol = firing ? Red : TextDim, actCol = firing ? Amber : C(0xFFC8D8E8);
|
|
||||||
if (!rule.Enabled) { condCol = Faded(condCol); actCol = Faded(actCol); }
|
|
||||||
dl.AddText(new Vector2(x + 3, ty), condCol, Fit(_condText[index], col - 5));
|
|
||||||
// The armed "Delete?" button is wider than the column gap: the action text stops short of it.
|
|
||||||
float actW = Math.Min(textW - col - 4, delX - 6 - (x + col + 2));
|
|
||||||
dl.AddText(new Vector2(x + col + 2, ty), actCol, Fit(_actText[index], actW));
|
|
||||||
}
|
|
||||||
|
|
||||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h));
|
|
||||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
|
||||||
|
|
||||||
if (changed)
|
|
||||||
{
|
|
||||||
RebuildCaches();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasChildren && expanded) ExpandedChildren(rule);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ExpandedChildren(MetaRuleDto rule)
|
|
||||||
{
|
|
||||||
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9);
|
|
||||||
ImGuiNET.ImGui.PushFont(f9);
|
|
||||||
Vector4 amber = RynthTheme.Vec(0xFFE8B333), mute = RynthTheme.Vec(0xFFC8D6E4);
|
|
||||||
ImGuiNET.ImGui.Indent(22);
|
|
||||||
if (MetaVocabulary.IsCompositeCondition(rule.Condition) && rule.Children.Count > 0)
|
|
||||||
{
|
|
||||||
ImGuiNET.ImGui.TextColored(amber, " " + MetaVocabulary.ConditionName(rule.Condition) + ":");
|
|
||||||
foreach (MetaRuleDto child in rule.Children)
|
|
||||||
ImGuiNET.ImGui.TextColored(mute, " • " + MetaVocabulary.CondText(child));
|
|
||||||
}
|
|
||||||
if (MetaVocabulary.IsAllAction(rule.Action) && rule.ActionChildren.Count > 0)
|
|
||||||
{
|
|
||||||
ImGuiNET.ImGui.TextColored(amber, " All (actions):");
|
|
||||||
foreach (MetaRuleDto child in rule.ActionChildren)
|
|
||||||
ImGuiNET.ImGui.TextColored(mute, " • " + MetaVocabulary.ActText(child));
|
|
||||||
}
|
|
||||||
ImGuiNET.ImGui.Unindent(22);
|
|
||||||
ImGuiNET.ImGui.PopFont();
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool Move(int index, int direction)
|
|
||||||
{
|
|
||||||
int other = MetaVocabulary.SwapPartner(_data.Rules, index, direction);
|
|
||||||
if (other < 0) return false;
|
|
||||||
SendEdit(new MetaCmd { Op = direction < 0 ? "move_up" : "move_down", Index = index });
|
|
||||||
(_data.Rules[index], _data.Rules[other]) = (_data.Rules[other], _data.Rules[index]);
|
|
||||||
_expanded.Clear();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void BottomBar(float w)
|
|
||||||
{
|
|
||||||
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
|
|
||||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
|
||||||
float labelW = ImGuiNET.ImGui.CalcTextSize("State:").X;
|
|
||||||
dl.AddText(new Vector2(p.X, p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "State:");
|
|
||||||
// Buttons sized from their text, so a larger panel text size can't overflow them
|
|
||||||
// (2026-10-05: "+ New Rule" spilled past its fixed 72 px button).
|
|
||||||
string ruleLabel = PhosphorIcons.Plus + " New Rule";
|
|
||||||
float newW = ImGuiNET.ImGui.CalcTextSize(ruleLabel).X + 18;
|
|
||||||
// The bar sits on the body's bottom edge: it stops short of the resize grip (GripInBody).
|
|
||||||
float grip = ImGuiPanelHost.BodyGripReserve;
|
|
||||||
float ruleX = p.X + w - grip - newW;
|
|
||||||
float pickX = p.X + labelW + 4;
|
|
||||||
float pickW = Math.Max(40, ruleX - 4 - pickX);
|
|
||||||
|
|
||||||
// The meta's current state. "+ New state..." at the end of the list makes one: it starts
|
|
||||||
// with an empty Never -> None rule (that rule is what keeps it), becomes the current state
|
|
||||||
// like any state picked here, and that rule opens in the editor.
|
|
||||||
string? chosen = StatePicker("##cur_state", _data.CurrentState, _statePicks, Array.IndexOf(_statePicks, _data.CurrentState),
|
|
||||||
new Vector2(pickX, p.Y + 1), pickW, out bool isNew);
|
|
||||||
if (chosen != null)
|
|
||||||
{
|
|
||||||
if (isNew) CreateState(chosen, openIt: true);
|
|
||||||
_data.CurrentState = chosen;
|
|
||||||
MetaCommands.Simple("set_state", value: chosen);
|
|
||||||
}
|
|
||||||
if (Button(ruleLabel + "##new", new Vector2(ruleX, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green))
|
|
||||||
OpenEditor(-1, new MetaRuleDto { State = _data.CurrentState, Action = 1 });
|
|
||||||
ImGuiNET.ImGui.SetItemTooltip("A new rule in the current state (added once its condition and action are filled in)");
|
|
||||||
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 24));
|
|
||||||
ImGuiNET.ImGui.Dummy(new Vector2(0, 0));
|
|
||||||
}
|
|
||||||
|
|
||||||
// =====================================================================
|
// =====================================================================
|
||||||
// Source view
|
// Source view
|
||||||
|
|
@ -1125,7 +843,7 @@ internal sealed partial class MetaFace : IImGuiPanel
|
||||||
/// picked index or -1.
|
/// picked index or -1.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private int Picker(string id, string shown, string[] items, int selected, Vector2 pos, float width, float height = 22,
|
private int Picker(string id, string shown, string[] items, int selected, Vector2 pos, float width, float height = 22,
|
||||||
string? extra = null)
|
string? extra = null, string? badge = null)
|
||||||
{
|
{
|
||||||
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
var dl = ImGuiNET.ImGui.GetWindowDrawList();
|
||||||
ImGuiNET.ImGui.PushID(id);
|
ImGuiNET.ImGui.PushID(id);
|
||||||
|
|
@ -1146,7 +864,16 @@ internal sealed partial class MetaFace : IImGuiPanel
|
||||||
const float caretW = 14;
|
const float caretW = 14;
|
||||||
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretDown,
|
PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretDown,
|
||||||
new Vector2(pos.X + width - caretW - 3, pos.Y), new Vector2(caretW, height), Mute);
|
new Vector2(pos.X + width - caretW - 3, pos.Y), new Vector2(caretW, height), Mute);
|
||||||
dl.AddText(pos + new Vector2(6, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, Fit(shown, width - 6 - caretW - 6));
|
// A badge (seconds in state) sits right-aligned before the arrow; the text is cut before it.
|
||||||
|
float badgeW = 0;
|
||||||
|
if (!string.IsNullOrEmpty(badge))
|
||||||
|
{
|
||||||
|
badgeW = ImGuiNET.ImGui.CalcTextSize(badge).X + 8;
|
||||||
|
if (badgeW > width * 0.5f) badgeW = 0;
|
||||||
|
else dl.AddText(new Vector2(pos.X + width - caretW - 3 - badgeW + 2, pos.Y + (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f),
|
||||||
|
Faded(Teal), badge);
|
||||||
|
}
|
||||||
|
dl.AddText(pos + new Vector2(6, (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, Fit(shown, width - 6 - caretW - 6 - badgeW));
|
||||||
|
|
||||||
int picked = -1;
|
int picked = -1;
|
||||||
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
|
||||||
|
|
@ -1278,9 +1005,15 @@ internal sealed partial class MetaFace : IImGuiPanel
|
||||||
string shown = text;
|
string shown = text;
|
||||||
if (ImGuiNET.ImGui.CalcTextSize(text).X > width)
|
if (ImGuiNET.ImGui.CalcTextSize(text).X > width)
|
||||||
{
|
{
|
||||||
int n = text.Length;
|
// The longest start that fits with "…" (binary search: long expressions are cut often,
|
||||||
while (n > 0 && ImGuiNET.ImGui.CalcTextSize(text.AsSpan(0, n).ToString() + "…").X > width) n--;
|
// and the cache empties with every snapshot while rules fire).
|
||||||
shown = text.Substring(0, n) + "…";
|
int lo = 0, hi = text.Length - 1;
|
||||||
|
while (lo < hi)
|
||||||
|
{
|
||||||
|
int mid = (lo + hi + 1) / 2;
|
||||||
|
if (ImGuiNET.ImGui.CalcTextSize(text.Substring(0, mid) + "…").X <= width) lo = mid; else hi = mid - 1;
|
||||||
|
}
|
||||||
|
shown = text.Substring(0, lo) + "…";
|
||||||
}
|
}
|
||||||
if (_fit.Count > 4000) _fit.Clear(); // widths change while a panel is resized
|
if (_fit.Count > 4000) _fit.Clear(); // widths change while a panel is resized
|
||||||
_fit[key] = shown;
|
_fit[key] = shown;
|
||||||
|
|
|
||||||
|
|
@ -63,6 +63,16 @@ internal static unsafe class FlightRecorder
|
||||||
|
|
||||||
public static bool Enabled => _cap != null && !_paused;
|
public static bool Enabled => _cap != null && !_paused;
|
||||||
|
|
||||||
|
/// <summary>An automatic dump is scheduled or a dump is being written right now.</summary>
|
||||||
|
public static bool DumpPendingOrRunning
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (Volatile.Read(ref _dumping) != 0) return true;
|
||||||
|
lock (ScheduleLock) return _scheduledReason != null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ── setup ──────────────────────────────────────────────────────────────
|
// ── setup ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
public static void Initialize()
|
public static void Initialize()
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,7 @@ internal static class EngineSettings
|
||||||
private static bool _enableImGuiBackend = true;
|
private static bool _enableImGuiBackend = true;
|
||||||
private static bool _enableHangMinidump = true;
|
private static bool _enableHangMinidump = true;
|
||||||
private static bool _preventIdleLogoff = true;
|
private static bool _preventIdleLogoff = true;
|
||||||
|
private static bool _closeOnServerDisconnect = true;
|
||||||
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
|
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
|
||||||
private static bool _decalInGameImGui = true;
|
private static bool _decalInGameImGui = true;
|
||||||
private static bool _decalStandDown = true;
|
private static bool _decalStandDown = true;
|
||||||
|
|
@ -231,6 +232,27 @@ internal static class EngineSettings
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>"CloseOnServerDisconnect" in engine.json (default true, 2026-10-11): when AC shows
|
||||||
|
/// its "The server has disconnected" screen (UIFlow mode Disconnected, only a Quit Game
|
||||||
|
/// button), the engine closes the client a few seconds later the way the window's close
|
||||||
|
/// button does (Compatibility/ServerDisconnectClose.cs), so a launcher's auto-relaunch can
|
||||||
|
/// bring it back. Off: the client stays on that screen. Set in game in Settings > Misc.</summary>
|
||||||
|
public static bool CloseOnServerDisconnect
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
EnsureLoaded();
|
||||||
|
return _closeOnServerDisconnect;
|
||||||
|
}
|
||||||
|
set
|
||||||
|
{
|
||||||
|
EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file
|
||||||
|
if (_closeOnServerDisconnect == value) return;
|
||||||
|
_closeOnServerDisconnect = value;
|
||||||
|
Save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>"DecalBridge" in engine.json: Auto (default), On or Off. Only matters when
|
/// <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):
|
/// 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
|
/// Auto - bridge mode when the RynthCore Decal bridge is registered and says hello
|
||||||
|
|
@ -552,6 +574,10 @@ internal static class EngineSettings
|
||||||
_preventIdleLogoff = pilEl.GetBoolean();
|
_preventIdleLogoff = pilEl.GetBoolean();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (doc.RootElement.TryGetProperty("CloseOnServerDisconnect", out var cosdEl) &&
|
||||||
|
(cosdEl.ValueKind == JsonValueKind.True || cosdEl.ValueKind == JsonValueKind.False))
|
||||||
|
_closeOnServerDisconnect = cosdEl.GetBoolean();
|
||||||
|
|
||||||
if (doc.RootElement.TryGetProperty("IltServerNames", out var ilnEl) &&
|
if (doc.RootElement.TryGetProperty("IltServerNames", out var ilnEl) &&
|
||||||
ilnEl.ValueKind == JsonValueKind.Array)
|
ilnEl.ValueKind == JsonValueKind.Array)
|
||||||
_iltServerNames = ReadStringList(ilnEl);
|
_iltServerNames = ReadStringList(ilnEl);
|
||||||
|
|
@ -601,7 +627,7 @@ internal static class EngineSettings
|
||||||
"EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge",
|
"EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge",
|
||||||
"DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream",
|
"DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream",
|
||||||
"FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix",
|
"FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix",
|
||||||
"MaxHotReloads", "ReportEndpoint",
|
"MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect",
|
||||||
};
|
};
|
||||||
|
|
||||||
private static void Save()
|
private static void Save()
|
||||||
|
|
@ -650,6 +676,8 @@ internal static class EngineSettings
|
||||||
w.WriteBoolean("EnableLargeAddressAlignmentFix", false);
|
w.WriteBoolean("EnableLargeAddressAlignmentFix", false);
|
||||||
if (_insertReleasesUi) // default false: leave the file as it was
|
if (_insertReleasesUi) // default false: leave the file as it was
|
||||||
w.WriteBoolean("InsertReleasesUi", true);
|
w.WriteBoolean("InsertReleasesUi", true);
|
||||||
|
if (!_closeOnServerDisconnect) // default true: leave the file as it was
|
||||||
|
w.WriteBoolean("CloseOnServerDisconnect", false);
|
||||||
if (_maxHotReloads != ReloadCapNotice.DefaultMaxHotReloads) // only a hand-set value is written
|
if (_maxHotReloads != ReloadCapNotice.DefaultMaxHotReloads) // only a hand-set value is written
|
||||||
w.WriteNumber("MaxHotReloads", _maxHotReloads);
|
w.WriteNumber("MaxHotReloads", _maxHotReloads);
|
||||||
if (_reportEndpoint != null) // only a hand-set value is written
|
if (_reportEndpoint != null) // only a hand-set value is written
|
||||||
|
|
|
||||||
|
|
@ -844,6 +844,26 @@ internal struct RynthCoreAPI
|
||||||
/// must equal that price; 0 skips the comparison. Same results and threading as Raise.
|
/// must equal that price; 0 skips the comparison. Same results and threading as Raise.
|
||||||
/// Requires API v79+.</summary>
|
/// Requires API v79+.</summary>
|
||||||
public IntPtr TrainSkillFn;
|
public IntPtr TrainSkillFn;
|
||||||
|
|
||||||
|
/// <summary>v80: <c>int GetContainerOrder(uint containerId, int slotKind, uint* ids, int maxIds)</c>:
|
||||||
|
/// the items in one of the player's containers in their real slot order, as the server keeps it
|
||||||
|
/// (Net/InventoryOrder: the login message, a pack's contents list and every item move), where
|
||||||
|
/// GetContainerContents is in object-id order. slotKind 0 = the ordinary items (slot 0 first);
|
||||||
|
/// 1 = the side packs and foci in the main pack (the pack column, top first). Writes at most
|
||||||
|
/// maxIds ids (ids may be null with maxIds 0 to ask the count) and returns how many there are,
|
||||||
|
/// or -1 when no full list for that container has been seen (a side pack the server hasn't
|
||||||
|
/// listed yet): then the order is unknown, never guessed. Any thread. Requires API v80+.</summary>
|
||||||
|
public IntPtr GetContainerOrderFn;
|
||||||
|
|
||||||
|
/// <summary>v80: <c>int PutItemInContainer(uint itemId, uint containerId, int placement)</c>: move an
|
||||||
|
/// item into a container at a slot (the 0x19 PutItemInContainer game action, the packet only:
|
||||||
|
/// CM_Inventory::Event_PutItemInContainer), as a drop on a cell of the pack grid does. Within one
|
||||||
|
/// container it reorders: placement is the index the item should end at, counted without it.
|
||||||
|
/// MoveItemInternal ignores its slot argument (first empty slot); this doesn't. The server decides
|
||||||
|
/// (full pack, busy) and answers as for any move. Queued to AC's main thread when called off it.
|
||||||
|
/// Returns 1 sent or queued, 0 refused before sending (bad ids, negative placement), -1 the
|
||||||
|
/// sender isn't bound on this client. Requires API v80+.</summary>
|
||||||
|
public IntPtr PutItemInContainerFn;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary>
|
/// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary>
|
||||||
|
|
@ -1664,3 +1684,9 @@ internal unsafe delegate int RaiseCallbackDelegate(uint kind, uint stype, uint r
|
||||||
|
|
||||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||||
internal delegate int TrainSkillCallbackDelegate(uint stype, int expectedCredits);
|
internal delegate int TrainSkillCallbackDelegate(uint stype, int expectedCredits);
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||||
|
internal unsafe delegate int GetContainerOrderCallbackDelegate(uint containerId, int slotKind, uint* ids, int maxIds);
|
||||||
|
|
||||||
|
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||||
|
internal delegate int PutItemInContainerCallbackDelegate(uint itemId, uint containerId, int placement);
|
||||||
|
|
|
||||||
|
|
@ -15,5 +15,5 @@ namespace RynthCore.Engine.Plugins;
|
||||||
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI (and the SDK's RynthCoreApiNative).</summary>
|
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI (and the SDK's RynthCoreApiNative).</summary>
|
||||||
internal static class PluginContractVersion
|
internal static class PluginContractVersion
|
||||||
{
|
{
|
||||||
public const uint Current = 79;
|
public const uint Current = 80;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -264,6 +264,8 @@ internal static partial class PluginManager
|
||||||
private static GetTrainingInfoCallbackDelegate? _getTrainingInfoCallback; // v79
|
private static GetTrainingInfoCallbackDelegate? _getTrainingInfoCallback; // v79
|
||||||
private static RaiseCallbackDelegate? _raiseCallback; // v79
|
private static RaiseCallbackDelegate? _raiseCallback; // v79
|
||||||
private static TrainSkillCallbackDelegate? _trainSkillCallback; // v79
|
private static TrainSkillCallbackDelegate? _trainSkillCallback; // v79
|
||||||
|
private static GetContainerOrderCallbackDelegate? _getContainerOrderCallback; // v80
|
||||||
|
private static PutItemInContainerCallbackDelegate? _putItemInContainerCallback; // v80
|
||||||
private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback;
|
private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback;
|
||||||
private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback;
|
private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback;
|
||||||
private static VendorBuyCallbackDelegate? _vendorBuyCallback;
|
private static VendorBuyCallbackDelegate? _vendorBuyCallback;
|
||||||
|
|
@ -2787,6 +2789,8 @@ internal static partial class PluginManager
|
||||||
unsafe { _getTrainingInfoCallback ??= GetTrainingInfoAction; } // v79
|
unsafe { _getTrainingInfoCallback ??= GetTrainingInfoAction; } // v79
|
||||||
unsafe { _raiseCallback ??= RaiseAction; }
|
unsafe { _raiseCallback ??= RaiseAction; }
|
||||||
_trainSkillCallback ??= TrainSkillAction;
|
_trainSkillCallback ??= TrainSkillAction;
|
||||||
|
unsafe { _getContainerOrderCallback ??= GetContainerOrderAction; } // v80
|
||||||
|
_putItemInContainerCallback ??= PutItemInContainerAction;
|
||||||
_getVendorInfoCallback ??= GetVendorInfoAction;
|
_getVendorInfoCallback ??= GetVendorInfoAction;
|
||||||
_getVendorItemsCallback ??= GetVendorItemsAction;
|
_getVendorItemsCallback ??= GetVendorItemsAction;
|
||||||
_vendorBuyCallback ??= VendorBuyAction;
|
_vendorBuyCallback ??= VendorBuyAction;
|
||||||
|
|
@ -2930,6 +2934,8 @@ internal static partial class PluginManager
|
||||||
_api.GetTrainingInfoFn = Marshal.GetFunctionPointerForDelegate(_getTrainingInfoCallback);
|
_api.GetTrainingInfoFn = Marshal.GetFunctionPointerForDelegate(_getTrainingInfoCallback);
|
||||||
_api.RaiseFn = Marshal.GetFunctionPointerForDelegate(_raiseCallback);
|
_api.RaiseFn = Marshal.GetFunctionPointerForDelegate(_raiseCallback);
|
||||||
_api.TrainSkillFn = Marshal.GetFunctionPointerForDelegate(_trainSkillCallback);
|
_api.TrainSkillFn = Marshal.GetFunctionPointerForDelegate(_trainSkillCallback);
|
||||||
|
_api.GetContainerOrderFn = Marshal.GetFunctionPointerForDelegate(_getContainerOrderCallback);
|
||||||
|
_api.PutItemInContainerFn = Marshal.GetFunctionPointerForDelegate(_putItemInContainerCallback);
|
||||||
_api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback);
|
_api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback);
|
||||||
_api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback);
|
_api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback);
|
||||||
_api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback);
|
_api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback);
|
||||||
|
|
@ -4041,6 +4047,41 @@ internal static partial class PluginManager
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── v80: slot order and placed moves (Net/InventoryOrder, ClientHelperHooks) ──
|
||||||
|
|
||||||
|
/// <summary>v80: see PluginContract.GetContainerOrderFn.</summary>
|
||||||
|
private static unsafe int GetContainerOrderAction(uint containerId, int slotKind, uint* ids, int maxIds)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (containerId == 0 || slotKind is < 0 or > 1 || maxIds < 0 || (ids == null && maxIds > 0)) return -1;
|
||||||
|
if (!Net.InventoryOrder.TryGetOrder(containerId, slotKind == 1, out uint[] order)) return -1;
|
||||||
|
int n = Math.Min(order.Length, maxIds);
|
||||||
|
for (int i = 0; i < n; i++) ids[i] = order[i];
|
||||||
|
return order.Length;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>v80: see PluginContract.PutItemInContainerFn.</summary>
|
||||||
|
private static int PutItemInContainerAction(uint itemId, uint containerId, int placement)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!ClientHelperHooks.HasPutItemInContainer) return -1;
|
||||||
|
Compatibility.AcActionTrace.Record("PutItemInContainer", itemId, containerId);
|
||||||
|
return ToAbiBool(ClientHelperHooks.PutItemInContainerAt(itemId, containerId, placement));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
RynthLog.Compat($"PutItemInContainer failed - {ex.GetType().Name}: {ex.Message}");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>v78: see PluginContract.SetServerMessageInterestFn.</summary>
|
/// <summary>v78: see PluginContract.SetServerMessageInterestFn.</summary>
|
||||||
private static unsafe int SetServerMessageInterestAction(uint* opcodes, int opcodeCount, uint* gameEvents, int eventCount)
|
private static unsafe int SetServerMessageInterestAction(uint* opcodes, int opcodeCount, uint* gameEvents, int eventCount)
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,9 @@
|
||||||
// the Avalonia UI/Panels/RynthChatPanel.cs) and both filter editors:
|
// the Avalonia UI/Panels/RynthChatPanel.cs) and both filter editors:
|
||||||
//
|
//
|
||||||
// • ChatSource (hub, 100 ms) pulls new lines from RynthChatGetScrollbackJson
|
// • ChatSource (hub, 100 ms) pulls new lines from RynthChatGetScrollbackJson
|
||||||
// on the pump thread, keeps the newest 500, routes and colours them with
|
// on the pump thread, keeps the newest ChatModel.HistoryLines ("Chat
|
||||||
// the rules, and writes the chat log. It also hands each new line to the
|
// history", 2,000 by default; 500 before 2026-10-11, see ChatHistory.cs),
|
||||||
|
// routes and colours them with the rules, and writes the chat log. It also hands each new line to the
|
||||||
// Discord relay and ticks it (UI/Data/Discord/ChatDiscord.cs), which keeps
|
// Discord relay and ticks it (UI/Data/Discord/ChatDiscord.cs), which keeps
|
||||||
// this source subscribed while it is on.
|
// this source subscribed while it is on.
|
||||||
// • ChatModel holds the settings (rynthchat_settings.json), the regex
|
// • ChatModel holds the settings (rynthchat_settings.json), the regex
|
||||||
|
|
@ -25,13 +26,14 @@
|
||||||
// colours add up, a higher rule winning where two overlap.
|
// colours add up, a higher rule winning where two overlap.
|
||||||
//
|
//
|
||||||
// Threads: rules are evaluated ONLY on the pump (ChatSource) - each new line
|
// Threads: rules are evaluated ONLY on the pump (ChatSource) - each new line
|
||||||
// once, and every kept line again when the rules change - and the result is
|
// once, and every kept line again when the rules change (in 8 ms slices, newest
|
||||||
|
// first, since the history can be 10,000 lines) - and the result is
|
||||||
// stored on the line (ChatLine.Route). The faces just read routes; no regex
|
// stored on the line (ChatLine.Route). The faces just read routes; no regex
|
||||||
// runs per frame. The one UI-thread evaluation is the rule editor's test box,
|
// runs per frame. The one UI-thread evaluation is the rule editor's test box,
|
||||||
// on a keystroke. Every regex has a 15 ms match timeout; a rule that times
|
// on a keystroke. Every regex has a 15 ms match timeout; a rule that times
|
||||||
// out is marked Slow and skipped until it is edited, so a pathological
|
// out is marked Slow and skipped until it is edited, so a pathological
|
||||||
// pattern costs one timeout, not one per line. A rule that never times out
|
// pattern costs one timeout, not one per line. A rule that never times out
|
||||||
// but spends over 100 ms re-routing the kept lines is marked Slow too: the
|
// but spends over 100 ms (per 500 lines) re-routing the kept lines is marked Slow too: the
|
||||||
// pump is the plugin tick thread, and a slow re-route holds every plugin's
|
// pump is the plugin tick thread, and a slow re-route holds every plugin's
|
||||||
// tick (ChatRouter.Charge).
|
// tick (ChatRouter.Charge).
|
||||||
//
|
//
|
||||||
|
|
@ -63,205 +65,28 @@ using RynthCore.Engine.Plugins;
|
||||||
|
|
||||||
namespace RynthCore.Engine.UI.Data;
|
namespace RynthCore.Engine.UI.Data;
|
||||||
|
|
||||||
/// <summary>One scrollback line. Immutable except its Route, which the pump replaces.</summary>
|
|
||||||
internal sealed class ChatLine
|
|
||||||
{
|
|
||||||
public ChatLine(long id, string ts, string chan, int chatType, string? sender, string text)
|
|
||||||
{
|
|
||||||
Id = id;
|
|
||||||
Timestamp = ts;
|
|
||||||
Channel = chan;
|
|
||||||
ChatType = chatType;
|
|
||||||
Sender = sender;
|
|
||||||
Text = text;
|
|
||||||
ColorKind = ChatLineColors.KindOf(chatType, chan, text);
|
|
||||||
ChatLineColors.NoteKind(ColorKind);
|
|
||||||
// The text already names the speaker ("Bob says, ..."); until 2026-09-29
|
|
||||||
// the sender was printed in front of it as well ("Bob: Bob says, ...").
|
|
||||||
FormattedText = $"{ts} {text}";
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Engine-assigned, increasing for the whole session (the plugin's own
|
|
||||||
/// seq restarts after RL).</summary>
|
|
||||||
public long Id { get; }
|
|
||||||
/// <summary>RynthChat's own number for the line (restarts when its plugin reloads); 0 when not
|
|
||||||
/// from RynthChat. The Discord relay tells news from scrollback by it.</summary>
|
|
||||||
public ulong Seq { get; init; }
|
|
||||||
public string Timestamp { get; }
|
|
||||||
/// <summary>The channel tab it belongs to (ChatClassifier in the plugin).</summary>
|
|
||||||
public string Channel { get; }
|
|
||||||
/// <summary>AC's ChatMessageType; -1 from RynthChat before 0.2.0.</summary>
|
|
||||||
public int ChatType { get; }
|
|
||||||
/// <summary>Who spoke, for player speech; metadata only (mentions, rules from a line).</summary>
|
|
||||||
public string? Sender { get; }
|
|
||||||
/// <summary>The line as AC printed it. Rules match this.</summary>
|
|
||||||
public string Text { get; }
|
|
||||||
/// <summary>Which line colour setting applies ("say", "chan:General", ...), or null:
|
|
||||||
/// its tab's colour (ChatLineColors.KindOf, worked out once here).</summary>
|
|
||||||
public string? ColorKind { get; }
|
|
||||||
/// <summary>"HH:mm:ss text": copy, log and the Avalonia face.</summary>
|
|
||||||
public string FormattedText { get; }
|
|
||||||
|
|
||||||
private ChatRoute _route = ChatRoute.Default;
|
|
||||||
|
|
||||||
/// <summary>Where the rules put this line and how it's coloured. Written by the
|
|
||||||
/// pump (before the line is published, and again when the rules change); any thread reads.</summary>
|
|
||||||
public ChatRoute Route
|
|
||||||
{
|
|
||||||
get => Volatile.Read(ref _route);
|
|
||||||
internal set => Volatile.Write(ref _route, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>A run of the line's Text drawn in its own colour (0xAARRGGBB).</summary>
|
|
||||||
internal readonly record struct ChatSpan(int Start, int Length, uint Argb);
|
|
||||||
|
|
||||||
/// <summary>The rules' verdict for one line. Immutable.</summary>
|
|
||||||
internal sealed class ChatRoute
|
|
||||||
{
|
|
||||||
public static readonly ChatRoute Default = new(false, true, null, null, null, false);
|
|
||||||
|
|
||||||
public ChatRoute(bool hidden, bool inHome, string[]? tabs, uint? lineArgb, ChatSpan[]? spans, bool mention)
|
|
||||||
{
|
|
||||||
Hidden = hidden;
|
|
||||||
InHome = inHome;
|
|
||||||
Tabs = tabs;
|
|
||||||
LineArgb = lineArgb;
|
|
||||||
Spans = spans;
|
|
||||||
Mention = mention;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>A Hide rule matched: shown nowhere.</summary>
|
|
||||||
public bool Hidden { get; }
|
|
||||||
/// <summary>Shown under All and its channel tab (false once a Move rule took it away).</summary>
|
|
||||||
public bool InHome { get; }
|
|
||||||
/// <summary>Tabs a Move or Copy rule sent it to.</summary>
|
|
||||||
public string[]? Tabs { get; }
|
|
||||||
/// <summary>Whole-line colour from a rule; null = the channel colour.</summary>
|
|
||||||
public uint? LineArgb { get; }
|
|
||||||
/// <summary>Matched-text colours: offsets into Text, sorted, not overlapping.</summary>
|
|
||||||
public ChatSpan[]? Spans { get; }
|
|
||||||
/// <summary>Someone said your name (or a mention word).</summary>
|
|
||||||
public bool Mention { get; }
|
|
||||||
|
|
||||||
public bool ShowsIn(string tab, string channel)
|
|
||||||
{
|
|
||||||
if (Hidden) return false;
|
|
||||||
if (InHome && (tab == "All" || string.Equals(tab, channel, StringComparison.OrdinalIgnoreCase))) return true;
|
|
||||||
if (Tabs != null)
|
|
||||||
foreach (string t in Tabs)
|
|
||||||
if (string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)) return true;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal enum ChatRuleAction
|
|
||||||
{
|
|
||||||
/// <summary>Only in the rule's tab: leaves All and its channel tab.</summary>
|
|
||||||
Move,
|
|
||||||
/// <summary>Also in the rule's tab.</summary>
|
|
||||||
Copy,
|
|
||||||
/// <summary>Nowhere.</summary>
|
|
||||||
Hide,
|
|
||||||
/// <summary>No routing: the rule only colours.</summary>
|
|
||||||
Color,
|
|
||||||
}
|
|
||||||
|
|
||||||
internal enum ChatColorMode { None, Line, Match }
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// One rule. Its fields are edited in place by a rule editor (then
|
/// New RynthChat lines while a chat face or the Discord relay holds it (100 ms). Publishes
|
||||||
/// ChatModel.FiltersChanged); the pump reads each field once per line, and a
|
/// the newest ChatModel.HistoryLines (the "Chat history" setting; 500 until 2026-10-11),
|
||||||
/// half-applied edit is re-routed by the version bump that follows it.
|
/// routed, and keeps RynthChat's own ring the same length (RynthChatSetCapacity).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed class ChatFilterRule
|
|
||||||
{
|
|
||||||
public const int TimeoutMs = 15;
|
|
||||||
|
|
||||||
public volatile bool Enabled = true;
|
|
||||||
public volatile string Pattern = "";
|
|
||||||
/// <summary>The Move / Copy target. Empty: a Move or Copy rule routes nowhere (it can still colour).</summary>
|
|
||||||
public volatile string Tab = "";
|
|
||||||
public volatile ChatRuleAction Action = ChatRuleAction.Move;
|
|
||||||
public volatile ChatColorMode ColorMode = ChatColorMode.None;
|
|
||||||
/// <summary>How Pattern is read: a regex (the default, and every rule saved before
|
|
||||||
/// 2026-10-05) or plain text. Recompile after changing it.</summary>
|
|
||||||
public volatile ChatMatchMode Mode = ChatMatchMode.Regex;
|
|
||||||
/// <summary>A new rule's colour (amber).</summary>
|
|
||||||
public const uint DefaultColor = 0xFFFFD27A;
|
|
||||||
/// <summary>0xAARRGGBB.</summary>
|
|
||||||
public volatile uint ColorArgb = DefaultColor;
|
|
||||||
|
|
||||||
private volatile WhenSpec _when = WhenSpec.Any;
|
|
||||||
/// <summary>"" any line; "chan:Combat" one channel tab; "type:3" one ChatMessageType (see ChatModel.Conditions).</summary>
|
|
||||||
public string When
|
|
||||||
{
|
|
||||||
get => _when.Raw;
|
|
||||||
set => _when = WhenSpec.Parse(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Kept lines this rule matched (recounted when the rules change, then
|
|
||||||
/// counted up as lines arrive). Written by the pump; the editor shows it.</summary>
|
|
||||||
public int Hits;
|
|
||||||
|
|
||||||
public volatile Regex? Compiled;
|
|
||||||
/// <summary>The pattern doesn't compile (or is empty).</summary>
|
|
||||||
public volatile bool Invalid;
|
|
||||||
/// <summary>Why it doesn't compile; null when it does or is just empty.</summary>
|
|
||||||
public volatile string? Error;
|
|
||||||
/// <summary>A match timed out: skipped until the pattern is edited.</summary>
|
|
||||||
public volatile bool Slow;
|
|
||||||
|
|
||||||
/// <summary>Compiles the pattern once (after every pattern edit). Any thread.</summary>
|
|
||||||
public void Recompile()
|
|
||||||
{
|
|
||||||
Slow = false;
|
|
||||||
// A Regex rule compiles exactly as before; plain text is escaped (ChatRuleMatching).
|
|
||||||
Regex? rx = ChatRuleMatching.Compile(Mode, Pattern, TimeoutMs, out string? error);
|
|
||||||
Compiled = rx;
|
|
||||||
Error = error;
|
|
||||||
Invalid = rx == null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Does the rule route (Move / Copy with a tab, or Hide)?</summary>
|
|
||||||
public bool Routes => Action == ChatRuleAction.Hide
|
|
||||||
|| (Action is ChatRuleAction.Move or ChatRuleAction.Copy && Tab.Length > 0);
|
|
||||||
|
|
||||||
internal bool WhenMatches(string channel, int chatType)
|
|
||||||
{
|
|
||||||
WhenSpec w = _when;
|
|
||||||
if (w.Channel != null) return string.Equals(w.Channel, channel, StringComparison.OrdinalIgnoreCase);
|
|
||||||
if (w.Type >= 0) return w.Type == chatType;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class WhenSpec
|
|
||||||
{
|
|
||||||
public static readonly WhenSpec Any = new("", null, -1);
|
|
||||||
public readonly string Raw;
|
|
||||||
public readonly string? Channel;
|
|
||||||
public readonly int Type;
|
|
||||||
private WhenSpec(string raw, string? channel, int type) { Raw = raw; Channel = channel; Type = type; }
|
|
||||||
|
|
||||||
public static WhenSpec Parse(string? raw)
|
|
||||||
{
|
|
||||||
raw = (raw ?? "").Trim();
|
|
||||||
(string? channel, int type) = ChatRuleMatching.ParseWhen(raw);
|
|
||||||
return channel == null && type < 0 ? Any : new WhenSpec(raw, channel, type);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>New RynthChat lines while a chat face or the Discord relay holds it (100 ms). Publishes the newest 500, routed.</summary>
|
|
||||||
internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
|
internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
|
||||||
{
|
{
|
||||||
private const int MaxLines = 500;
|
|
||||||
private delegate* unmanaged[Cdecl]<ulong, IntPtr> _get;
|
private delegate* unmanaged[Cdecl]<ulong, IntPtr> _get;
|
||||||
|
// RynthChat 0.3.0+: how many lines its ring keeps. Null for an older plugin (it keeps 500).
|
||||||
|
private delegate* unmanaged[Cdecl]<int, int> _setCapacity;
|
||||||
|
private int _sentCapacity;
|
||||||
private ulong _sinceSeq;
|
private ulong _sinceSeq;
|
||||||
private long _nextId = 1;
|
private long _nextId = 1;
|
||||||
private bool _boundLogged;
|
private bool _boundLogged;
|
||||||
private long _routedVersion = -1;
|
private long _routedVersion = -1;
|
||||||
private string _routedName = "";
|
private string _routedName = "";
|
||||||
|
// A re-route pass in progress (the rules changed): its router, and the Id below which the
|
||||||
|
// kept lines still carry the old routes. It runs newest first, RerouteSliceMs per poll.
|
||||||
|
private ChatRouter? _passRouter;
|
||||||
|
private long _passBelowId;
|
||||||
|
private const double RerouteSliceMs = 8;
|
||||||
|
private static readonly long RerouteSliceTicks = (long)(Stopwatch.Frequency * RerouteSliceMs / 1000);
|
||||||
|
|
||||||
public ChatSource() : base("Chat", periodMs: 100) { }
|
public ChatSource() : base("Chat", periodMs: 100) { }
|
||||||
|
|
||||||
|
|
@ -290,26 +115,25 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
|
||||||
if (ChatModel.SendLinePtr == IntPtr.Zero)
|
if (ChatModel.SendLinePtr == IntPtr.Zero)
|
||||||
ChatModel.SendLinePtr = PluginExportBinder.Resolve("RynthChat", "RynthChatSendLine");
|
ChatModel.SendLinePtr = PluginExportBinder.Resolve("RynthChat", "RynthChatSendLine");
|
||||||
ChatModel.PluginBound = _get != null;
|
ChatModel.PluginBound = _get != null;
|
||||||
|
int maxLines = ChatModel.HistoryLines;
|
||||||
|
if (_get != null) SyncPluginCapacity(maxLines);
|
||||||
ChatModel.PumpLog(null);
|
ChatModel.PumpLog(null);
|
||||||
|
|
||||||
// The rules (or the name mentions look for) changed: route the kept lines again.
|
// The rules (or the name mentions look for) changed: route the kept lines again.
|
||||||
long version = ChatModel.FiltersVersion;
|
long version = ChatModel.FiltersVersion;
|
||||||
string name = ChatModel.PumpCharacterName();
|
string name = ChatModel.PumpCharacterName();
|
||||||
ChatRouter router = ChatModel.PumpRouter(name);
|
ChatRouter router = ChatModel.PumpRouter(name);
|
||||||
|
TrimToLength(maxLines);
|
||||||
if (version != _routedVersion || name != _routedName)
|
if (version != _routedVersion || name != _routedName)
|
||||||
{
|
{
|
||||||
_routedVersion = version;
|
_routedVersion = version;
|
||||||
_routedName = name;
|
_routedName = name;
|
||||||
ChatLine[]? kept = Current?.Value;
|
_passRouter = router;
|
||||||
router.BeginPass();
|
_passBelowId = long.MaxValue;
|
||||||
try
|
router.BeginPass(Current?.Value.Length ?? 0);
|
||||||
{
|
router.EndPass(); // paused until its slice below
|
||||||
if (kept != null)
|
|
||||||
foreach (ChatLine line in kept) line.Route = router.Evaluate(line, null);
|
|
||||||
}
|
|
||||||
finally { router.EndPass(); }
|
|
||||||
ChatModel.BumpRoutes();
|
|
||||||
}
|
}
|
||||||
|
if (_passRouter != null) ContinueReroute(_passRouter);
|
||||||
|
|
||||||
if (_get == null) return;
|
if (_get == null) return;
|
||||||
|
|
||||||
|
|
@ -353,16 +177,74 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
|
||||||
}
|
}
|
||||||
|
|
||||||
ChatLine[] old = Current?.Value ?? Array.Empty<ChatLine>();
|
ChatLine[] old = Current?.Value ?? Array.Empty<ChatLine>();
|
||||||
int keepOld = Math.Max(0, Math.Min(old.Length, MaxLines - added.Count));
|
Publish(ChatHistory.Merge(old, added, maxLines));
|
||||||
int skipAdded = Math.Max(0, added.Count - MaxLines);
|
|
||||||
var lines = new ChatLine[keepOld + added.Count - skipAdded];
|
|
||||||
Array.Copy(old, old.Length - keepOld, lines, 0, keepOld);
|
|
||||||
added.CopyTo(skipAdded, lines, keepOld, added.Count - skipAdded);
|
|
||||||
Publish(lines);
|
|
||||||
ChatModel.PumpLog(added);
|
ChatModel.PumpLog(added);
|
||||||
RelayRead(added);
|
RelayRead(added);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One time slice of re-routing the kept lines with <paramref name="router"/>, newest
|
||||||
|
/// first. Up to 2,000 lines take one slice (5 ms, tools/ChatHistoryBench), as the whole
|
||||||
|
/// pass did before; 10,000 take about four polls. Lines that arrive meanwhile are routed
|
||||||
|
/// with the same router as they come in. The faces rebuild once, when the pass is done.
|
||||||
|
/// </summary>
|
||||||
|
private void ContinueReroute(ChatRouter router)
|
||||||
|
{
|
||||||
|
ChatLine[] kept = Current?.Value ?? Array.Empty<ChatLine>();
|
||||||
|
int i = LastIndexBelow(kept, _passBelowId);
|
||||||
|
long t0 = Stopwatch.GetTimestamp();
|
||||||
|
int n = 0;
|
||||||
|
router.ResumePass();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (i >= 0)
|
||||||
|
{
|
||||||
|
ChatLine line = kept[i--];
|
||||||
|
line.Route = router.Evaluate(line, null);
|
||||||
|
_passBelowId = line.Id;
|
||||||
|
if ((++n & 31) == 0 && Stopwatch.GetTimestamp() - t0 > RerouteSliceTicks) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally { router.EndPass(); }
|
||||||
|
if (i >= 0) return; // more next poll
|
||||||
|
_passRouter = null;
|
||||||
|
ChatModel.BumpRoutes();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The index of the newest line whose Id is below <paramref name="id"/> (Ids increase), or -1.</summary>
|
||||||
|
private static int LastIndexBelow(ChatLine[] lines, long id)
|
||||||
|
{
|
||||||
|
int lo = 0, hi = lines.Length; // first index with Id >= id
|
||||||
|
while (lo < hi)
|
||||||
|
{
|
||||||
|
int mid = (lo + hi) >> 1;
|
||||||
|
if (lines[mid].Id < id) lo = mid + 1; else hi = mid;
|
||||||
|
}
|
||||||
|
return lo - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The setting was lowered: drop the oldest kept lines now, not only when new ones arrive.</summary>
|
||||||
|
private void TrimToLength(int maxLines)
|
||||||
|
{
|
||||||
|
ChatLine[]? kept = Current?.Value;
|
||||||
|
if (kept != null && ChatHistory.Trim(kept, maxLines) is { } trimmed) Publish(trimmed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Tells RynthChat (0.3.0+) the history length once it's bound and whenever the setting moves.</summary>
|
||||||
|
private void SyncPluginCapacity(int maxLines)
|
||||||
|
{
|
||||||
|
if (_setCapacity == null)
|
||||||
|
{
|
||||||
|
_setCapacity = (delegate* unmanaged[Cdecl]<int, int>)PluginExportBinder.Resolve("RynthChat", "RynthChatSetCapacity");
|
||||||
|
if (_setCapacity == null) return; // an older RynthChat: its ring stays at 500
|
||||||
|
}
|
||||||
|
if (_sentCapacity == maxLines) return;
|
||||||
|
int applied = _setCapacity(maxLines);
|
||||||
|
if (applied <= 0) return; // the plugin isn't up yet: try again next poll
|
||||||
|
_sentCapacity = maxLines;
|
||||||
|
RynthLog.UI($"ChatSource: RynthChat keeps {applied} lines (chat history {maxLines}).");
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Every scrollback read goes to the Discord relay, empty or not (its first read is a baseline).</summary>
|
/// <summary>Every scrollback read goes to the Discord relay, empty or not (its first read is a baseline).</summary>
|
||||||
private static void RelayRead(IReadOnlyList<ChatLine> added)
|
private static void RelayRead(IReadOnlyList<ChatLine> added)
|
||||||
{
|
{
|
||||||
|
|
@ -451,6 +333,8 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
|
||||||
// RL loads a fresh plugin copy whose scrollback numbers from 1 again.
|
// RL loads a fresh plugin copy whose scrollback numbers from 1 again.
|
||||||
// The lines already shown stay.
|
// The lines already shown stay.
|
||||||
_get = null;
|
_get = null;
|
||||||
|
_setCapacity = null;
|
||||||
|
_sentCapacity = 0;
|
||||||
_sinceSeq = 0;
|
_sinceSeq = 0;
|
||||||
Discord.ChatDiscord.PumpSourceReset();
|
Discord.ChatDiscord.PumpSourceReset();
|
||||||
ChatModel.SendLinePtr = IntPtr.Zero;
|
ChatModel.SendLinePtr = IntPtr.Zero;
|
||||||
|
|
@ -458,236 +342,6 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Evaluates the rules for one line: a snapshot of the rule list plus the
|
|
||||||
/// mention regex. Built by ChatModel.PumpRouter (pump) or for the editor's
|
|
||||||
/// test box (UI thread). One thread per router: each one's cost counters are
|
|
||||||
/// its own (the pump's lives on the pump; the test box builds a fresh one).
|
|
||||||
/// </summary>
|
|
||||||
internal sealed class ChatRouter
|
|
||||||
{
|
|
||||||
/// <summary>Mentions colour the name like this (amber).</summary>
|
|
||||||
public const uint MentionArgb = 0xFFFFC857;
|
|
||||||
|
|
||||||
// The 15 ms timeout only catches a pattern that is slow on one line. One that
|
|
||||||
// costs a millisecond or two per line never times out, yet re-routing the 500
|
|
||||||
// kept lines (on every keystroke in the rule editor) then holds the pump -
|
|
||||||
// which is the plugin tick thread - for a second or more. So during a
|
|
||||||
// re-route pass each rule's matching time is added up, and a rule that uses
|
|
||||||
// more than PassBudgetMs is marked Slow like a timed-out one. An ordinary
|
|
||||||
// rule takes a few microseconds a line, a few ms for the pass. One reading
|
|
||||||
// counts at most MaxChargeMs, so a GC pause or a descheduled thread in the
|
|
||||||
// middle of a match doesn't condemn the rule on its own.
|
|
||||||
private const double PassBudgetMs = 100, MaxChargeMs = 30;
|
|
||||||
private static readonly long PassBudgetTicks = (long)(Stopwatch.Frequency * PassBudgetMs / 1000);
|
|
||||||
private static readonly long MaxChargeTicks = (long)(Stopwatch.Frequency * MaxChargeMs / 1000);
|
|
||||||
|
|
||||||
/// <summary>ChatMessageType Emote (0x0C).</summary>
|
|
||||||
private const int EmoteType = 0x0C;
|
|
||||||
|
|
||||||
private readonly ChatFilterRule[] _rules;
|
|
||||||
private readonly Regex? _mention;
|
|
||||||
private readonly string _self;
|
|
||||||
private readonly bool _countHits;
|
|
||||||
private readonly long[] _passTicks;
|
|
||||||
private bool _inPass;
|
|
||||||
|
|
||||||
/// <param name="self">Your character's name ("" unknown): your own emotes don't mention you.</param>
|
|
||||||
/// <param name="countHits">Count matches into ChatFilterRule.Hits (the pump's router; not the test box's).</param>
|
|
||||||
public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits)
|
|
||||||
{
|
|
||||||
_rules = rules;
|
|
||||||
_mention = mention;
|
|
||||||
_self = self.Trim();
|
|
||||||
_countHits = countHits;
|
|
||||||
_passTicks = new long[rules.Length];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Before routing every kept line again: hit counts restart, and each rule's time is watched.</summary>
|
|
||||||
public void BeginPass()
|
|
||||||
{
|
|
||||||
ResetHits();
|
|
||||||
Array.Clear(_passTicks);
|
|
||||||
_inPass = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void EndPass() => _inPass = false;
|
|
||||||
|
|
||||||
/// <summary>Adds a rule's matching time during a pass; marks it Slow past the budget. False once it's Slow.</summary>
|
|
||||||
private bool Charge(int i, long ticks, List<Step>? trace)
|
|
||||||
{
|
|
||||||
if (!_inPass) return true;
|
|
||||||
_passTicks[i] += Math.Min(ticks, MaxChargeTicks);
|
|
||||||
if (_passTicks[i] <= PassBudgetTicks) return true;
|
|
||||||
MarkSlow(_rules[i], trace, i, $"over {PassBudgetMs:0} ms to re-route the kept lines");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Before routing every kept line again.</summary>
|
|
||||||
public void ResetHits()
|
|
||||||
{
|
|
||||||
foreach (ChatFilterRule rule in _rules) Volatile.Write(ref rule.Hits, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>One step of the editor's test: rule index (-1 = mention) and what it did.</summary>
|
|
||||||
public readonly record struct Step(int Rule, string What);
|
|
||||||
|
|
||||||
public ChatRoute Evaluate(ChatLine line, List<Step>? trace) =>
|
|
||||||
Evaluate(line.Text, line.Channel, line.ChatType, trace);
|
|
||||||
|
|
||||||
public ChatRoute Evaluate(string text, string channel, int chatType, List<Step>? trace)
|
|
||||||
{
|
|
||||||
bool hidden = false, inHome = true, routed = false;
|
|
||||||
List<string>? tabs = null;
|
|
||||||
uint? lineArgb = null;
|
|
||||||
List<(int Start, int Length, uint Argb)>? spans = null;
|
|
||||||
|
|
||||||
for (int i = 0; i < _rules.Length; i++)
|
|
||||||
{
|
|
||||||
ChatFilterRule rule = _rules[i];
|
|
||||||
if (!rule.Enabled || rule.Slow) continue;
|
|
||||||
Regex? rx = rule.Compiled;
|
|
||||||
if (rx == null) continue;
|
|
||||||
ChatRuleAction action = rule.Action;
|
|
||||||
ChatColorMode mode = rule.ColorMode;
|
|
||||||
string tab = rule.Tab;
|
|
||||||
bool routes = action == ChatRuleAction.Hide
|
|
||||||
|| (action is ChatRuleAction.Move or ChatRuleAction.Copy && tab.Length > 0);
|
|
||||||
bool wantsRoute = routes && !routed;
|
|
||||||
bool wantsLine = mode == ChatColorMode.Line && lineArgb == null;
|
|
||||||
bool wantsMatch = mode == ChatColorMode.Match;
|
|
||||||
// Nothing left for it to decide (the test box still shows that it matches).
|
|
||||||
if (!wantsRoute && !wantsLine && !wantsMatch && trace == null) continue;
|
|
||||||
if (!rule.WhenMatches(channel, chatType)) continue;
|
|
||||||
|
|
||||||
Match m;
|
|
||||||
long t0 = Stopwatch.GetTimestamp();
|
|
||||||
try { m = rx.Match(text); }
|
|
||||||
catch (RegexMatchTimeoutException) { MarkSlow(rule, trace, i, $"a match took over {ChatFilterRule.TimeoutMs} ms"); continue; }
|
|
||||||
if (!Charge(i, Stopwatch.GetTimestamp() - t0, trace)) continue;
|
|
||||||
if (!m.Success) continue;
|
|
||||||
if (_countHits) Interlocked.Increment(ref rule.Hits);
|
|
||||||
|
|
||||||
var what = trace != null ? new StringBuilder() : null;
|
|
||||||
if (wantsRoute)
|
|
||||||
{
|
|
||||||
switch (action)
|
|
||||||
{
|
|
||||||
case ChatRuleAction.Hide:
|
|
||||||
hidden = routed = true;
|
|
||||||
what?.Append("hides it");
|
|
||||||
break;
|
|
||||||
case ChatRuleAction.Move:
|
|
||||||
inHome = false;
|
|
||||||
routed = true;
|
|
||||||
AddTab(ref tabs, tab);
|
|
||||||
what?.Append("moves it to ").Append(tab);
|
|
||||||
break;
|
|
||||||
case ChatRuleAction.Copy:
|
|
||||||
AddTab(ref tabs, tab);
|
|
||||||
what?.Append("copies it to ").Append(tab);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (routes && trace != null)
|
|
||||||
what!.Append("(a Move/Hide above already decided the tab)");
|
|
||||||
if (hidden)
|
|
||||||
{
|
|
||||||
trace?.Add(new Step(i, what!.ToString()));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (wantsLine)
|
|
||||||
{
|
|
||||||
lineArgb = rule.ColorArgb;
|
|
||||||
what?.Append(what.Length > 0 ? ", " : "").Append("colours the line");
|
|
||||||
}
|
|
||||||
else if (mode == ChatColorMode.Line && trace != null)
|
|
||||||
what!.Append(what.Length > 0 ? ", " : "").Append("(line colour already set above)");
|
|
||||||
if (wantsMatch)
|
|
||||||
{
|
|
||||||
int n = 0;
|
|
||||||
long t1 = Stopwatch.GetTimestamp();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
for (; m.Success && n < 16; m = m.NextMatch())
|
|
||||||
if (m.Length > 0) { (spans ??= new()).Add((m.Index, m.Length, rule.ColorArgb)); n++; }
|
|
||||||
}
|
|
||||||
catch (RegexMatchTimeoutException) { MarkSlow(rule, trace, i, $"a match took over {ChatFilterRule.TimeoutMs} ms"); }
|
|
||||||
if (!rule.Slow) Charge(i, Stopwatch.GetTimestamp() - t1, trace);
|
|
||||||
what?.Append(what.Length > 0 ? ", " : "").Append(n == 1 ? "colours the match" : $"colours {n} matches");
|
|
||||||
}
|
|
||||||
if (what is { Length: 0 }) what.Append("matches, but has nothing to do yet (no tab, no colour)");
|
|
||||||
trace?.Add(new Step(i, what!.ToString()));
|
|
||||||
}
|
|
||||||
|
|
||||||
bool mention = false;
|
|
||||||
if (!hidden && _mention != null && ChatModel.MentionEligible(channel, chatType))
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Match m = _mention.Match(text);
|
|
||||||
for (int n = 0; m.Success && n < 8; m = m.NextMatch(), n++)
|
|
||||||
{
|
|
||||||
// Your own emote prints as "Tom waves." (type Emote, your name first): that's you, not a mention.
|
|
||||||
if (m.Index == 0 && chatType == EmoteType && _self.Length > 0
|
|
||||||
&& string.Equals(m.Value, _self, StringComparison.OrdinalIgnoreCase)) continue;
|
|
||||||
mention = true;
|
|
||||||
(spans ??= new()).Add((m.Index, m.Length, MentionArgb));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (RegexMatchTimeoutException) { }
|
|
||||||
if (mention) trace?.Add(new Step(-1, "mentions you (highlighted)"));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!hidden && inHome && tabs == null && lineArgb == null && spans == null && !mention)
|
|
||||||
return ChatRoute.Default;
|
|
||||||
return new ChatRoute(hidden, inHome, tabs?.ToArray(), lineArgb, Resolve(spans, text.Length), mention);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void AddTab(ref List<string>? tabs, string tab)
|
|
||||||
{
|
|
||||||
tabs ??= new List<string>(2);
|
|
||||||
foreach (string t in tabs) if (string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)) return;
|
|
||||||
tabs.Add(tab);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void MarkSlow(ChatFilterRule rule, List<Step>? trace, int index, string why)
|
|
||||||
{
|
|
||||||
if (!rule.Slow)
|
|
||||||
{
|
|
||||||
rule.Slow = true;
|
|
||||||
RynthLog.UI($"ChatModel: rule \"{rule.Pattern}\" is too slow ({why}) and is skipped until edited.");
|
|
||||||
// Lines already routed with it are routed again without it.
|
|
||||||
ChatModel.BumpFiltersVersion();
|
|
||||||
}
|
|
||||||
trace?.Add(new Step(index, "too slow - now skipped until edited"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Overlapping spans: the earlier one (a higher rule) keeps its characters.</summary>
|
|
||||||
private static ChatSpan[]? Resolve(List<(int Start, int Length, uint Argb)>? spans, int textLength)
|
|
||||||
{
|
|
||||||
if (spans == null || spans.Count == 0) return null;
|
|
||||||
if (spans.Count == 1)
|
|
||||||
return new[] { new ChatSpan(spans[0].Start, spans[0].Length, spans[0].Argb) };
|
|
||||||
var owner = new int[textLength]; // 0 = free, else span index + 1
|
|
||||||
for (int s = 0; s < spans.Count; s++)
|
|
||||||
{
|
|
||||||
int end = Math.Min(textLength, spans[s].Start + spans[s].Length);
|
|
||||||
for (int c = spans[s].Start; c < end; c++)
|
|
||||||
if (owner[c] == 0) owner[c] = s + 1;
|
|
||||||
}
|
|
||||||
var result = new List<ChatSpan>();
|
|
||||||
for (int c = 0; c < textLength;)
|
|
||||||
{
|
|
||||||
int o = owner[c];
|
|
||||||
int start = c;
|
|
||||||
while (c < textLength && owner[c] == o) c++;
|
|
||||||
if (o != 0) result.Add(new ChatSpan(start, c - start, spans[o - 1].Argb));
|
|
||||||
}
|
|
||||||
return result.ToArray();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static class ChatModel
|
internal static class ChatModel
|
||||||
{
|
{
|
||||||
/// <summary>Channel tabs; must match ChatClassifier in the plugin.</summary>
|
/// <summary>Channel tabs; must match ChatClassifier in the plugin.</summary>
|
||||||
|
|
@ -771,6 +425,16 @@ internal static class ChatModel
|
||||||
public static volatile bool MentionSound;
|
public static volatile bool MentionSound;
|
||||||
/// <summary>Extra words to highlight, comma-separated.</summary>
|
/// <summary>Extra words to highlight, comma-separated.</summary>
|
||||||
public static volatile string MentionWords = "";
|
public static volatile string MentionWords = "";
|
||||||
|
/// <summary>How many lines the scrollback keeps, all tabs together (ChatHistory; "Chat history" in the gear menu).</summary>
|
||||||
|
public static volatile int HistoryLines = ChatHistory.DefaultLines;
|
||||||
|
|
||||||
|
public static void SetHistoryLines(int lines)
|
||||||
|
{
|
||||||
|
lines = ChatHistory.Clamp(lines);
|
||||||
|
if (lines == HistoryLines) return;
|
||||||
|
HistoryLines = lines;
|
||||||
|
SaveSettings();
|
||||||
|
}
|
||||||
|
|
||||||
public static void SetCtrlGatedClickThrough(bool on)
|
public static void SetCtrlGatedClickThrough(bool on)
|
||||||
{
|
{
|
||||||
|
|
@ -1668,6 +1332,7 @@ internal static class ChatModel
|
||||||
MentionHighlight = dto.MentionHighlight;
|
MentionHighlight = dto.MentionHighlight;
|
||||||
MentionSound = dto.MentionSound;
|
MentionSound = dto.MentionSound;
|
||||||
MentionWords = dto.MentionWords ?? "";
|
MentionWords = dto.MentionWords ?? "";
|
||||||
|
HistoryLines = ChatHistory.Clamp(dto.HistoryLines ?? 0); // absent before 2026-10-11: the default
|
||||||
ChatLineColors.Load(dto.LineColors); // absent before 2026-10-08: nothing set
|
ChatLineColors.Load(dto.LineColors); // absent before 2026-10-08: nothing set
|
||||||
|
|
||||||
var tabs = new List<string>();
|
var tabs = new List<string>();
|
||||||
|
|
@ -1734,6 +1399,8 @@ internal static class ChatModel
|
||||||
MentionHighlight = MentionHighlight,
|
MentionHighlight = MentionHighlight,
|
||||||
MentionSound = MentionSound,
|
MentionSound = MentionSound,
|
||||||
MentionWords = MentionWords,
|
MentionWords = MentionWords,
|
||||||
|
// Left out at the default, so a file follows the default if it ever changes.
|
||||||
|
HistoryLines = HistoryLines == ChatHistory.DefaultLines ? null : HistoryLines,
|
||||||
LineColors = ChatLineColors.ToJson(), // null (left out) until a colour is set
|
LineColors = ChatLineColors.ToJson(), // null (left out) until a colour is set
|
||||||
CustomTabs = Volatile.Read(ref _customTabs),
|
CustomTabs = Volatile.Read(ref _customTabs),
|
||||||
Filters = Filters.Select(ToDto).ToArray(),
|
Filters = Filters.Select(ToDto).ToArray(),
|
||||||
|
|
|
||||||
70
src/RynthCore.Engine/UI/Data/ChatHistory.cs
Normal file
70
src/RynthCore.Engine/UI/Data/ChatHistory.cs
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
// ============================================================================
|
||||||
|
// RynthCore.Engine - UI/Data/ChatHistory.cs
|
||||||
|
// How long RynthChat's scrollback is (the chat setting "Chat history",
|
||||||
|
// 2026-10-11; a fixed 500 lines before) and the newest-N bookkeeping that
|
||||||
|
// goes with it. No engine state: tools/ChatHistoryBench compiles it in.
|
||||||
|
//
|
||||||
|
// The length applies to both copies of the scrollback: the engine's
|
||||||
|
// (ChatSource's published ChatLine[]) and RynthChat's own ring, which the
|
||||||
|
// engine resizes through the plugin's RynthChatSetCapacity export (RynthChat
|
||||||
|
// 0.3.0; an older plugin keeps its 500). Lines are numbered by the plugin and
|
||||||
|
// the engine either way, so the Discord relay's seq bookkeeping is untouched.
|
||||||
|
//
|
||||||
|
// Cost, measured by tools/ChatHistoryBench (x86, like acclient): about 1.8 MB
|
||||||
|
// of managed memory per 1,000 lines (engine 1.2, plugin ring 0.6, the face's
|
||||||
|
// lists 0.04), so 18 MB at 10,000 against the 1.3-2.3 GB of address space a
|
||||||
|
// client has free. Per poll the work grows with the new lines, not the length
|
||||||
|
// (one array copy: 11 us at 10,000). What grows with it: the first read after
|
||||||
|
// a bind or reload (15 ms at 2,000, 59 ms at 10,000, once), re-routing after
|
||||||
|
// a rule edit (7 / 27 ms, done in 8 ms slices) and re-measuring after a resize
|
||||||
|
// (4 / 15 ms, done in 2 ms slices a frame). The table is in that tool's header.
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace RynthCore.Engine.UI.Data;
|
||||||
|
|
||||||
|
internal static class ChatHistory
|
||||||
|
{
|
||||||
|
public const int DefaultLines = 2000;
|
||||||
|
public const int MinLines = 500;
|
||||||
|
public const int MaxLines = 10000;
|
||||||
|
/// <summary>The setting moves in steps of this many lines.</summary>
|
||||||
|
public const int StepLines = 500;
|
||||||
|
|
||||||
|
/// <summary>A stored or typed length made valid: 0 or less (absent) is the default.</summary>
|
||||||
|
public static int Clamp(int lines)
|
||||||
|
{
|
||||||
|
if (lines <= 0) return DefaultLines;
|
||||||
|
lines = (int)Math.Round(lines / (double)StepLines) * StepLines;
|
||||||
|
return Math.Clamp(lines, MinLines, MaxLines);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The newest <paramref name="max"/> of <paramref name="old"/> followed by
|
||||||
|
/// <paramref name="added"/>, as a new array (the published one is never changed:
|
||||||
|
/// faces on other threads read it). Cost: one copy of the kept references.
|
||||||
|
/// </summary>
|
||||||
|
public static T[] Merge<T>(T[] old, IReadOnlyList<T> added, int max)
|
||||||
|
{
|
||||||
|
max = Math.Max(1, max);
|
||||||
|
int skipAdded = Math.Max(0, added.Count - max);
|
||||||
|
int takeAdded = added.Count - skipAdded;
|
||||||
|
int keepOld = Math.Max(0, Math.Min(old.Length, max - takeAdded));
|
||||||
|
var lines = new T[keepOld + takeAdded];
|
||||||
|
Array.Copy(old, old.Length - keepOld, lines, 0, keepOld);
|
||||||
|
for (int i = 0; i < takeAdded; i++) lines[keepOld + i] = added[skipAdded + i];
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The newest <paramref name="max"/> lines, or null when there are no more than that.</summary>
|
||||||
|
public static T[]? Trim<T>(T[] lines, int max)
|
||||||
|
{
|
||||||
|
max = Math.Max(1, max);
|
||||||
|
if (lines.Length <= max) return null;
|
||||||
|
var kept = new T[max];
|
||||||
|
Array.Copy(lines, lines.Length - max, kept, 0, max);
|
||||||
|
return kept;
|
||||||
|
}
|
||||||
|
}
|
||||||
452
src/RynthCore.Engine/UI/Data/ChatRouting.cs
Normal file
452
src/RynthCore.Engine/UI/Data/ChatRouting.cs
Normal file
|
|
@ -0,0 +1,452 @@
|
||||||
|
// ============================================================================
|
||||||
|
// RynthCore.Engine - UI/Data/ChatRouting.cs
|
||||||
|
// RynthChat's lines and rules: ChatLine (one scrollback line), ChatRoute (the
|
||||||
|
// rules' verdict for it), ChatFilterRule and ChatRouter (which evaluates the
|
||||||
|
// rules). Moved out of ChatData.cs (2026-10-11) unchanged, so tools can run
|
||||||
|
// the real classes without the engine (tools/ChatHistoryBench). How the rules
|
||||||
|
// work and on which thread: see the header of ChatData.cs.
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using System.Threading;
|
||||||
|
using RynthCore.Engine.Compatibility;
|
||||||
|
|
||||||
|
namespace RynthCore.Engine.UI.Data;
|
||||||
|
|
||||||
|
/// <summary>One scrollback line. Immutable except its Route, which the pump replaces.</summary>
|
||||||
|
internal sealed class ChatLine
|
||||||
|
{
|
||||||
|
public ChatLine(long id, string ts, string chan, int chatType, string? sender, string text)
|
||||||
|
{
|
||||||
|
Id = id;
|
||||||
|
Timestamp = ts;
|
||||||
|
Channel = chan;
|
||||||
|
ChatType = chatType;
|
||||||
|
Sender = sender;
|
||||||
|
Text = text;
|
||||||
|
ColorKind = ChatLineColors.KindOf(chatType, chan, text);
|
||||||
|
ChatLineColors.NoteKind(ColorKind);
|
||||||
|
// The text already names the speaker ("Bob says, ..."); until 2026-09-29
|
||||||
|
// the sender was printed in front of it as well ("Bob: Bob says, ...").
|
||||||
|
FormattedText = $"{ts} {text}";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Engine-assigned, increasing for the whole session (the plugin's own
|
||||||
|
/// seq restarts after RL).</summary>
|
||||||
|
public long Id { get; }
|
||||||
|
/// <summary>RynthChat's own number for the line (restarts when its plugin reloads); 0 when not
|
||||||
|
/// from RynthChat. The Discord relay tells news from scrollback by it.</summary>
|
||||||
|
public ulong Seq { get; init; }
|
||||||
|
public string Timestamp { get; }
|
||||||
|
/// <summary>The channel tab it belongs to (ChatClassifier in the plugin).</summary>
|
||||||
|
public string Channel { get; }
|
||||||
|
/// <summary>AC's ChatMessageType; -1 from RynthChat before 0.2.0.</summary>
|
||||||
|
public int ChatType { get; }
|
||||||
|
/// <summary>Who spoke, for player speech; metadata only (mentions, rules from a line).</summary>
|
||||||
|
public string? Sender { get; }
|
||||||
|
/// <summary>The line as AC printed it. Rules match this.</summary>
|
||||||
|
public string Text { get; }
|
||||||
|
/// <summary>Which line colour setting applies ("say", "chan:General", ...), or null:
|
||||||
|
/// its tab's colour (ChatLineColors.KindOf, worked out once here).</summary>
|
||||||
|
public string? ColorKind { get; }
|
||||||
|
/// <summary>"HH:mm:ss text": copy, log and the Avalonia face.</summary>
|
||||||
|
public string FormattedText { get; }
|
||||||
|
|
||||||
|
private ChatRoute _route = ChatRoute.Default;
|
||||||
|
|
||||||
|
/// <summary>Where the rules put this line and how it's coloured. Written by the
|
||||||
|
/// pump (before the line is published, and again when the rules change); any thread reads.</summary>
|
||||||
|
public ChatRoute Route
|
||||||
|
{
|
||||||
|
get => Volatile.Read(ref _route);
|
||||||
|
internal set => Volatile.Write(ref _route, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A run of the line's Text drawn in its own colour (0xAARRGGBB).</summary>
|
||||||
|
internal readonly record struct ChatSpan(int Start, int Length, uint Argb);
|
||||||
|
|
||||||
|
/// <summary>The rules' verdict for one line. Immutable.</summary>
|
||||||
|
internal sealed class ChatRoute
|
||||||
|
{
|
||||||
|
public static readonly ChatRoute Default = new(false, true, null, null, null, false);
|
||||||
|
|
||||||
|
public ChatRoute(bool hidden, bool inHome, string[]? tabs, uint? lineArgb, ChatSpan[]? spans, bool mention)
|
||||||
|
{
|
||||||
|
Hidden = hidden;
|
||||||
|
InHome = inHome;
|
||||||
|
Tabs = tabs;
|
||||||
|
LineArgb = lineArgb;
|
||||||
|
Spans = spans;
|
||||||
|
Mention = mention;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A Hide rule matched: shown nowhere.</summary>
|
||||||
|
public bool Hidden { get; }
|
||||||
|
/// <summary>Shown under All and its channel tab (false once a Move rule took it away).</summary>
|
||||||
|
public bool InHome { get; }
|
||||||
|
/// <summary>Tabs a Move or Copy rule sent it to.</summary>
|
||||||
|
public string[]? Tabs { get; }
|
||||||
|
/// <summary>Whole-line colour from a rule; null = the channel colour.</summary>
|
||||||
|
public uint? LineArgb { get; }
|
||||||
|
/// <summary>Matched-text colours: offsets into Text, sorted, not overlapping.</summary>
|
||||||
|
public ChatSpan[]? Spans { get; }
|
||||||
|
/// <summary>Someone said your name (or a mention word).</summary>
|
||||||
|
public bool Mention { get; }
|
||||||
|
|
||||||
|
public bool ShowsIn(string tab, string channel)
|
||||||
|
{
|
||||||
|
if (Hidden) return false;
|
||||||
|
if (InHome && (tab == "All" || string.Equals(tab, channel, StringComparison.OrdinalIgnoreCase))) return true;
|
||||||
|
if (Tabs != null)
|
||||||
|
foreach (string t in Tabs)
|
||||||
|
if (string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum ChatRuleAction
|
||||||
|
{
|
||||||
|
/// <summary>Only in the rule's tab: leaves All and its channel tab.</summary>
|
||||||
|
Move,
|
||||||
|
/// <summary>Also in the rule's tab.</summary>
|
||||||
|
Copy,
|
||||||
|
/// <summary>Nowhere.</summary>
|
||||||
|
Hide,
|
||||||
|
/// <summary>No routing: the rule only colours.</summary>
|
||||||
|
Color,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum ChatColorMode { None, Line, Match }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One rule. Its fields are edited in place by a rule editor (then
|
||||||
|
/// ChatModel.FiltersChanged); the pump reads each field once per line, and a
|
||||||
|
/// half-applied edit is re-routed by the version bump that follows it.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class ChatFilterRule
|
||||||
|
{
|
||||||
|
public const int TimeoutMs = 15;
|
||||||
|
|
||||||
|
public volatile bool Enabled = true;
|
||||||
|
public volatile string Pattern = "";
|
||||||
|
/// <summary>The Move / Copy target. Empty: a Move or Copy rule routes nowhere (it can still colour).</summary>
|
||||||
|
public volatile string Tab = "";
|
||||||
|
public volatile ChatRuleAction Action = ChatRuleAction.Move;
|
||||||
|
public volatile ChatColorMode ColorMode = ChatColorMode.None;
|
||||||
|
/// <summary>How Pattern is read: a regex (the default, and every rule saved before
|
||||||
|
/// 2026-10-05) or plain text. Recompile after changing it.</summary>
|
||||||
|
public volatile ChatMatchMode Mode = ChatMatchMode.Regex;
|
||||||
|
/// <summary>A new rule's colour (amber).</summary>
|
||||||
|
public const uint DefaultColor = 0xFFFFD27A;
|
||||||
|
/// <summary>0xAARRGGBB.</summary>
|
||||||
|
public volatile uint ColorArgb = DefaultColor;
|
||||||
|
|
||||||
|
private volatile WhenSpec _when = WhenSpec.Any;
|
||||||
|
/// <summary>"" any line; "chan:Combat" one channel tab; "type:3" one ChatMessageType (see ChatModel.Conditions).</summary>
|
||||||
|
public string When
|
||||||
|
{
|
||||||
|
get => _when.Raw;
|
||||||
|
set => _when = WhenSpec.Parse(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Kept lines this rule matched (recounted when the rules change, then
|
||||||
|
/// counted up as lines arrive). Written by the pump; the editor shows it.</summary>
|
||||||
|
public int Hits;
|
||||||
|
|
||||||
|
public volatile Regex? Compiled;
|
||||||
|
/// <summary>The pattern doesn't compile (or is empty).</summary>
|
||||||
|
public volatile bool Invalid;
|
||||||
|
/// <summary>Why it doesn't compile; null when it does or is just empty.</summary>
|
||||||
|
public volatile string? Error;
|
||||||
|
/// <summary>A match timed out: skipped until the pattern is edited.</summary>
|
||||||
|
public volatile bool Slow;
|
||||||
|
|
||||||
|
/// <summary>Compiles the pattern once (after every pattern edit). Any thread.</summary>
|
||||||
|
public void Recompile()
|
||||||
|
{
|
||||||
|
Slow = false;
|
||||||
|
// A Regex rule compiles exactly as before; plain text is escaped (ChatRuleMatching).
|
||||||
|
Regex? rx = ChatRuleMatching.Compile(Mode, Pattern, TimeoutMs, out string? error);
|
||||||
|
Compiled = rx;
|
||||||
|
Error = error;
|
||||||
|
Invalid = rx == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Does the rule route (Move / Copy with a tab, or Hide)?</summary>
|
||||||
|
public bool Routes => Action == ChatRuleAction.Hide
|
||||||
|
|| (Action is ChatRuleAction.Move or ChatRuleAction.Copy && Tab.Length > 0);
|
||||||
|
|
||||||
|
internal bool WhenMatches(string channel, int chatType)
|
||||||
|
{
|
||||||
|
WhenSpec w = _when;
|
||||||
|
if (w.Channel != null) return string.Equals(w.Channel, channel, StringComparison.OrdinalIgnoreCase);
|
||||||
|
if (w.Type >= 0) return w.Type == chatType;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class WhenSpec
|
||||||
|
{
|
||||||
|
public static readonly WhenSpec Any = new("", null, -1);
|
||||||
|
public readonly string Raw;
|
||||||
|
public readonly string? Channel;
|
||||||
|
public readonly int Type;
|
||||||
|
private WhenSpec(string raw, string? channel, int type) { Raw = raw; Channel = channel; Type = type; }
|
||||||
|
|
||||||
|
public static WhenSpec Parse(string? raw)
|
||||||
|
{
|
||||||
|
raw = (raw ?? "").Trim();
|
||||||
|
(string? channel, int type) = ChatRuleMatching.ParseWhen(raw);
|
||||||
|
return channel == null && type < 0 ? Any : new WhenSpec(raw, channel, type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Evaluates the rules for one line: a snapshot of the rule list plus the
|
||||||
|
/// mention regex. Built by ChatModel.PumpRouter (pump) or for the editor's
|
||||||
|
/// test box (UI thread). One thread per router: each one's cost counters are
|
||||||
|
/// its own (the pump's lives on the pump; the test box builds a fresh one).
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class ChatRouter
|
||||||
|
{
|
||||||
|
/// <summary>Mentions colour the name like this (amber).</summary>
|
||||||
|
public const uint MentionArgb = 0xFFFFC857;
|
||||||
|
|
||||||
|
// The 15 ms timeout only catches a pattern that is slow on one line. One that
|
||||||
|
// costs a millisecond or two per line never times out, yet re-routing the 500
|
||||||
|
// kept lines (on every keystroke in the rule editor) then holds the pump -
|
||||||
|
// which is the plugin tick thread - for a second or more. So during a
|
||||||
|
// re-route pass each rule's matching time is added up, and a rule that uses
|
||||||
|
// more than PassBudgetMs is marked Slow like a timed-out one. An ordinary
|
||||||
|
// rule takes a few microseconds a line, a few ms for the pass. One reading
|
||||||
|
// counts at most MaxChargeMs, so a GC pause or a descheduled thread in the
|
||||||
|
// middle of a match doesn't condemn the rule on its own.
|
||||||
|
// Since the history length became a setting (2026-10-11, up to 10,000 lines) the
|
||||||
|
// budget is PassBudgetMs per 500 kept lines, so a longer history doesn't condemn a
|
||||||
|
// rule sooner; the pump re-routes in time slices (ChatSource), so a pass no longer
|
||||||
|
// holds the tick thread for its whole length either.
|
||||||
|
private const double PassBudgetMs = 100, MaxChargeMs = 30;
|
||||||
|
private const int PassBudgetLines = 500;
|
||||||
|
private static readonly long PassBudgetTicks = (long)(Stopwatch.Frequency * PassBudgetMs / 1000);
|
||||||
|
private static readonly long MaxChargeTicks = (long)(Stopwatch.Frequency * MaxChargeMs / 1000);
|
||||||
|
|
||||||
|
/// <summary>ChatMessageType Emote (0x0C).</summary>
|
||||||
|
private const int EmoteType = 0x0C;
|
||||||
|
|
||||||
|
private readonly ChatFilterRule[] _rules;
|
||||||
|
private readonly Regex? _mention;
|
||||||
|
private readonly string _self;
|
||||||
|
private readonly bool _countHits;
|
||||||
|
private readonly long[] _passTicks;
|
||||||
|
private long _passBudgetTicks = PassBudgetTicks;
|
||||||
|
private bool _inPass;
|
||||||
|
|
||||||
|
/// <param name="self">Your character's name ("" unknown): your own emotes don't mention you.</param>
|
||||||
|
/// <param name="countHits">Count matches into ChatFilterRule.Hits (the pump's router; not the test box's).</param>
|
||||||
|
public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits)
|
||||||
|
{
|
||||||
|
_rules = rules;
|
||||||
|
_mention = mention;
|
||||||
|
_self = self.Trim();
|
||||||
|
_countHits = countHits;
|
||||||
|
_passTicks = new long[rules.Length];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Before routing the <paramref name="lines"/> kept lines again: hit counts restart, and
|
||||||
|
/// each rule's time is watched (PassBudgetMs per PassBudgetLines lines, never less than
|
||||||
|
/// PassBudgetMs).
|
||||||
|
/// </summary>
|
||||||
|
public void BeginPass(int lines = PassBudgetLines)
|
||||||
|
{
|
||||||
|
ResetHits();
|
||||||
|
Array.Clear(_passTicks);
|
||||||
|
_passBudgetTicks = PassBudgetTicks * Math.Max(PassBudgetLines, lines) / PassBudgetLines;
|
||||||
|
_inPass = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The pass is over, or paused between two time slices (lines routed meanwhile aren't charged).</summary>
|
||||||
|
public void EndPass() => _inPass = false;
|
||||||
|
|
||||||
|
/// <summary>The next time slice of a pass begun with BeginPass.</summary>
|
||||||
|
public void ResumePass() => _inPass = true;
|
||||||
|
|
||||||
|
/// <summary>Adds a rule's matching time during a pass; marks it Slow past the budget. False once it's Slow.</summary>
|
||||||
|
private bool Charge(int i, long ticks, List<Step>? trace)
|
||||||
|
{
|
||||||
|
if (!_inPass) return true;
|
||||||
|
_passTicks[i] += Math.Min(ticks, MaxChargeTicks);
|
||||||
|
if (_passTicks[i] <= _passBudgetTicks) return true;
|
||||||
|
MarkSlow(_rules[i], trace, i, $"over {PassBudgetMs:0} ms per {PassBudgetLines} lines to re-route the kept lines");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Before routing every kept line again.</summary>
|
||||||
|
public void ResetHits()
|
||||||
|
{
|
||||||
|
foreach (ChatFilterRule rule in _rules) Volatile.Write(ref rule.Hits, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One step of the editor's test: rule index (-1 = mention) and what it did.</summary>
|
||||||
|
public readonly record struct Step(int Rule, string What);
|
||||||
|
|
||||||
|
public ChatRoute Evaluate(ChatLine line, List<Step>? trace) =>
|
||||||
|
Evaluate(line.Text, line.Channel, line.ChatType, trace);
|
||||||
|
|
||||||
|
public ChatRoute Evaluate(string text, string channel, int chatType, List<Step>? trace)
|
||||||
|
{
|
||||||
|
bool hidden = false, inHome = true, routed = false;
|
||||||
|
List<string>? tabs = null;
|
||||||
|
uint? lineArgb = null;
|
||||||
|
List<(int Start, int Length, uint Argb)>? spans = null;
|
||||||
|
|
||||||
|
for (int i = 0; i < _rules.Length; i++)
|
||||||
|
{
|
||||||
|
ChatFilterRule rule = _rules[i];
|
||||||
|
if (!rule.Enabled || rule.Slow) continue;
|
||||||
|
Regex? rx = rule.Compiled;
|
||||||
|
if (rx == null) continue;
|
||||||
|
ChatRuleAction action = rule.Action;
|
||||||
|
ChatColorMode mode = rule.ColorMode;
|
||||||
|
string tab = rule.Tab;
|
||||||
|
bool routes = action == ChatRuleAction.Hide
|
||||||
|
|| (action is ChatRuleAction.Move or ChatRuleAction.Copy && tab.Length > 0);
|
||||||
|
bool wantsRoute = routes && !routed;
|
||||||
|
bool wantsLine = mode == ChatColorMode.Line && lineArgb == null;
|
||||||
|
bool wantsMatch = mode == ChatColorMode.Match;
|
||||||
|
// Nothing left for it to decide (the test box still shows that it matches).
|
||||||
|
if (!wantsRoute && !wantsLine && !wantsMatch && trace == null) continue;
|
||||||
|
if (!rule.WhenMatches(channel, chatType)) continue;
|
||||||
|
|
||||||
|
Match m;
|
||||||
|
long t0 = Stopwatch.GetTimestamp();
|
||||||
|
try { m = rx.Match(text); }
|
||||||
|
catch (RegexMatchTimeoutException) { MarkSlow(rule, trace, i, $"a match took over {ChatFilterRule.TimeoutMs} ms"); continue; }
|
||||||
|
if (!Charge(i, Stopwatch.GetTimestamp() - t0, trace)) continue;
|
||||||
|
if (!m.Success) continue;
|
||||||
|
if (_countHits) Interlocked.Increment(ref rule.Hits);
|
||||||
|
|
||||||
|
var what = trace != null ? new StringBuilder() : null;
|
||||||
|
if (wantsRoute)
|
||||||
|
{
|
||||||
|
switch (action)
|
||||||
|
{
|
||||||
|
case ChatRuleAction.Hide:
|
||||||
|
hidden = routed = true;
|
||||||
|
what?.Append("hides it");
|
||||||
|
break;
|
||||||
|
case ChatRuleAction.Move:
|
||||||
|
inHome = false;
|
||||||
|
routed = true;
|
||||||
|
AddTab(ref tabs, tab);
|
||||||
|
what?.Append("moves it to ").Append(tab);
|
||||||
|
break;
|
||||||
|
case ChatRuleAction.Copy:
|
||||||
|
AddTab(ref tabs, tab);
|
||||||
|
what?.Append("copies it to ").Append(tab);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (routes && trace != null)
|
||||||
|
what!.Append("(a Move/Hide above already decided the tab)");
|
||||||
|
if (hidden)
|
||||||
|
{
|
||||||
|
trace?.Add(new Step(i, what!.ToString()));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (wantsLine)
|
||||||
|
{
|
||||||
|
lineArgb = rule.ColorArgb;
|
||||||
|
what?.Append(what.Length > 0 ? ", " : "").Append("colours the line");
|
||||||
|
}
|
||||||
|
else if (mode == ChatColorMode.Line && trace != null)
|
||||||
|
what!.Append(what.Length > 0 ? ", " : "").Append("(line colour already set above)");
|
||||||
|
if (wantsMatch)
|
||||||
|
{
|
||||||
|
int n = 0;
|
||||||
|
long t1 = Stopwatch.GetTimestamp();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
for (; m.Success && n < 16; m = m.NextMatch())
|
||||||
|
if (m.Length > 0) { (spans ??= new()).Add((m.Index, m.Length, rule.ColorArgb)); n++; }
|
||||||
|
}
|
||||||
|
catch (RegexMatchTimeoutException) { MarkSlow(rule, trace, i, $"a match took over {ChatFilterRule.TimeoutMs} ms"); }
|
||||||
|
if (!rule.Slow) Charge(i, Stopwatch.GetTimestamp() - t1, trace);
|
||||||
|
what?.Append(what.Length > 0 ? ", " : "").Append(n == 1 ? "colours the match" : $"colours {n} matches");
|
||||||
|
}
|
||||||
|
if (what is { Length: 0 }) what.Append("matches, but has nothing to do yet (no tab, no colour)");
|
||||||
|
trace?.Add(new Step(i, what!.ToString()));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool mention = false;
|
||||||
|
if (!hidden && _mention != null && ChatModel.MentionEligible(channel, chatType))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Match m = _mention.Match(text);
|
||||||
|
for (int n = 0; m.Success && n < 8; m = m.NextMatch(), n++)
|
||||||
|
{
|
||||||
|
// Your own emote prints as "Tom waves." (type Emote, your name first): that's you, not a mention.
|
||||||
|
if (m.Index == 0 && chatType == EmoteType && _self.Length > 0
|
||||||
|
&& string.Equals(m.Value, _self, StringComparison.OrdinalIgnoreCase)) continue;
|
||||||
|
mention = true;
|
||||||
|
(spans ??= new()).Add((m.Index, m.Length, MentionArgb));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (RegexMatchTimeoutException) { }
|
||||||
|
if (mention) trace?.Add(new Step(-1, "mentions you (highlighted)"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hidden && inHome && tabs == null && lineArgb == null && spans == null && !mention)
|
||||||
|
return ChatRoute.Default;
|
||||||
|
return new ChatRoute(hidden, inHome, tabs?.ToArray(), lineArgb, Resolve(spans, text.Length), mention);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AddTab(ref List<string>? tabs, string tab)
|
||||||
|
{
|
||||||
|
tabs ??= new List<string>(2);
|
||||||
|
foreach (string t in tabs) if (string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)) return;
|
||||||
|
tabs.Add(tab);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void MarkSlow(ChatFilterRule rule, List<Step>? trace, int index, string why)
|
||||||
|
{
|
||||||
|
if (!rule.Slow)
|
||||||
|
{
|
||||||
|
rule.Slow = true;
|
||||||
|
RynthLog.UI($"ChatModel: rule \"{rule.Pattern}\" is too slow ({why}) and is skipped until edited.");
|
||||||
|
// Lines already routed with it are routed again without it.
|
||||||
|
ChatModel.BumpFiltersVersion();
|
||||||
|
}
|
||||||
|
trace?.Add(new Step(index, "too slow - now skipped until edited"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Overlapping spans: the earlier one (a higher rule) keeps its characters.</summary>
|
||||||
|
private static ChatSpan[]? Resolve(List<(int Start, int Length, uint Argb)>? spans, int textLength)
|
||||||
|
{
|
||||||
|
if (spans == null || spans.Count == 0) return null;
|
||||||
|
if (spans.Count == 1)
|
||||||
|
return new[] { new ChatSpan(spans[0].Start, spans[0].Length, spans[0].Argb) };
|
||||||
|
var owner = new int[textLength]; // 0 = free, else span index + 1
|
||||||
|
for (int s = 0; s < spans.Count; s++)
|
||||||
|
{
|
||||||
|
int end = Math.Min(textLength, spans[s].Start + spans[s].Length);
|
||||||
|
for (int c = spans[s].Start; c < end; c++)
|
||||||
|
if (owner[c] == 0) owner[c] = s + 1;
|
||||||
|
}
|
||||||
|
var result = new List<ChatSpan>();
|
||||||
|
for (int c = 0; c < textLength;)
|
||||||
|
{
|
||||||
|
int o = owner[c];
|
||||||
|
int start = c;
|
||||||
|
while (c < textLength && owner[c] == o) c++;
|
||||||
|
if (o != 0) result.Add(new ChatSpan(start, c - start, spans[o - 1].Argb));
|
||||||
|
}
|
||||||
|
return result.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -62,6 +62,8 @@ internal sealed class RynthChatSettingsDto
|
||||||
// 2026-10-08: per-kind line colours (ChatLineColors), { "say": "#RRGGBB", "chan:General": ..., "tab:Chat": ... };
|
// 2026-10-08: per-kind line colours (ChatLineColors), { "say": "#RRGGBB", "chan:General": ..., "tab:Chat": ... };
|
||||||
// only the colours the user set, and absent while none is.
|
// only the colours the user set, and absent while none is.
|
||||||
[JsonPropertyName("lineColors")] public Dictionary<string, string>? LineColors { get; set; }
|
[JsonPropertyName("lineColors")] public Dictionary<string, string>? LineColors { get; set; }
|
||||||
|
// 2026-10-11: how many lines the scrollback keeps (ChatHistory); absent at the default (2000).
|
||||||
|
[JsonPropertyName("historyLines")] public int? HistoryLines { get; set; }
|
||||||
[JsonPropertyName("customTabs")] public string[]? CustomTabs { get; set; }
|
[JsonPropertyName("customTabs")] public string[]? CustomTabs { get; set; }
|
||||||
[JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; }
|
[JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -40,6 +40,10 @@ internal sealed class DamageRow
|
||||||
public bool HpEst;
|
public bool HpEst;
|
||||||
public double Crit; public int CritN; public double NonCrit; public int NonCritN;
|
public double Crit; public int CritN; public double NonCrit; public int NonCritN;
|
||||||
public double Casts; public int Kills; public string Key = "";
|
public double Casts; public int Kills; public string Key = "";
|
||||||
|
/// <summary>Every wcid of a row of several kinds (monsters of one name, e.g. retail's five
|
||||||
|
/// Rampagers), ascending; empty for one kind. Wcid is the one edits and details go to; the
|
||||||
|
/// plugin applies an edit to all of them.</summary>
|
||||||
|
public uint[] Wcids = Array.Empty<uint>();
|
||||||
/// <summary>Per-monster (wcid) weapon state, the same on every row of a wcid.</summary>
|
/// <summary>Per-monster (wcid) weapon state, the same on every row of a wcid.</summary>
|
||||||
public uint AssignedWid; public string AssignedWeapon = "";
|
public uint AssignedWid; public string AssignedWeapon = "";
|
||||||
public uint BestWid; public string BestWeapon = "";
|
public uint BestWid; public string BestWeapon = "";
|
||||||
|
|
@ -288,6 +292,12 @@ internal sealed unsafe class DamageSource : UiSource<DamageView>
|
||||||
if (e.TryGetProperty("assignedOffName", out var aon)) row.AssignedOffName = aon.GetString() ?? "";
|
if (e.TryGetProperty("assignedOffName", out var aon)) row.AssignedOffName = aon.GetString() ?? "";
|
||||||
if (e.TryGetProperty("isDefault", out var idf)) row.IsDefault = idf.GetBoolean();
|
if (e.TryGetProperty("isDefault", out var idf)) row.IsDefault = idf.GetBoolean();
|
||||||
if (e.TryGetProperty("hpEst", out var he)) row.HpEst = he.ValueKind == JsonValueKind.True;
|
if (e.TryGetProperty("hpEst", out var he)) row.HpEst = he.ValueKind == JsonValueKind.True;
|
||||||
|
if (e.TryGetProperty("wcids", out var wa) && wa.ValueKind == JsonValueKind.Array)
|
||||||
|
{
|
||||||
|
var kinds = new List<uint>();
|
||||||
|
foreach (var w in wa.EnumerateArray()) if (w.TryGetInt64(out long wl)) kinds.Add((uint)wl);
|
||||||
|
if (kinds.Count > 1) row.Wcids = kinds.ToArray();
|
||||||
|
}
|
||||||
if (e.TryGetProperty("pet", out var pc)) row.Pet = pc.GetString() ?? "";
|
if (e.TryGetProperty("pet", out var pc)) row.Pet = pc.GetString() ?? "";
|
||||||
if (e.TryGetProperty("petLabel", out var pl)) row.PetLabel = pl.GetString() ?? "Auto";
|
if (e.TryGetProperty("petLabel", out var pl)) row.PetLabel = pl.GetString() ?? "Auto";
|
||||||
if (e.TryGetProperty("weak", out var wk)) row.Weak = wk.GetString() ?? "";
|
if (e.TryGetProperty("weak", out var wk)) row.Weak = wk.GetString() ?? "";
|
||||||
|
|
|
||||||
|
|
@ -115,6 +115,8 @@ internal sealed class MetaPayload
|
||||||
public MetaApplyResult? ApplyResult { get; set; }
|
public MetaApplyResult? ApplyResult { get; set; }
|
||||||
/// <summary>The Meta Manager; null from a RynthAi without it.</summary>
|
/// <summary>The Meta Manager; null from a RynthAi without it.</summary>
|
||||||
public SchedulePayload? Schedule { get; set; }
|
public SchedulePayload? Schedule { get; set; }
|
||||||
|
/// <summary>Seconds in state and the Watchdog; null from a RynthAi without it.</summary>
|
||||||
|
public MetaStateSnapshot? Snapshot { get; set; }
|
||||||
|
|
||||||
/// <summary>Deep copy of the rules; the rest is shared (faces never change it).</summary>
|
/// <summary>Deep copy of the rules; the rest is shared (faces never change it).</summary>
|
||||||
public MetaPayload Clone()
|
public MetaPayload Clone()
|
||||||
|
|
@ -381,19 +383,53 @@ internal static class MetaVocabulary
|
||||||
return states.ToArray();
|
return states.ToArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Embedded Nav's route picker: nav files, then "[emb] key" for embedded routes.</summary>
|
/// <summary>Embedded Nav Route's "Patrol": RynthAi's dungeon patrol (/ra dunnav-patrol) when the
|
||||||
public static string[] RoutePicks(MetaPayload d)
|
/// meta and NavProfiles have no route by that name (RynthAi MetaManager.IsPatrolRoute).</summary>
|
||||||
|
public const string PatrolRoute = "Patrol";
|
||||||
|
|
||||||
|
/// <summary>A route of the meta or NavProfiles called <paramref name="name"/> (any case).</summary>
|
||||||
|
public static bool HasRoute(MetaPayload d, string name)
|
||||||
{
|
{
|
||||||
var routes = new List<string>();
|
foreach (string n in d.NavFiles) if (string.Equals(n, name, StringComparison.OrdinalIgnoreCase)) return true;
|
||||||
foreach (string n in d.NavFiles) if (n != "None") routes.Add(n);
|
foreach (string k in d.EmbeddedNavKeys) if (string.Equals(k, name, StringComparison.OrdinalIgnoreCase)) return true;
|
||||||
foreach (string k in d.EmbeddedNavKeys) if (!routes.Contains(k)) routes.Add($"[emb] {k}");
|
return false;
|
||||||
return routes.ToArray();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Nav names for source completion (nav files and embedded keys, no duplicates).</summary>
|
/// <summary>
|
||||||
|
/// Embedded Nav Route's picker: Patrol (the dungeon patrol) first, nav files, then the meta's own
|
||||||
|
/// routes. Labels are what the list shows ("[emb] key" for embedded routes); values are what the
|
||||||
|
/// rule stores, the name RynthAi looks up (2026-10-11: the label was stored, so an embedded route
|
||||||
|
/// picked here was "Route missing").
|
||||||
|
/// </summary>
|
||||||
|
public static (string[] Labels, string[] Values) RoutePicks(MetaPayload d)
|
||||||
|
{
|
||||||
|
var labels = new List<string>();
|
||||||
|
var values = new List<string>();
|
||||||
|
if (!HasRoute(d, PatrolRoute))
|
||||||
|
{
|
||||||
|
labels.Add(PatrolRoute + " (dungeon patrol, no nav file)");
|
||||||
|
values.Add(PatrolRoute);
|
||||||
|
}
|
||||||
|
foreach (string n in d.NavFiles)
|
||||||
|
{
|
||||||
|
if (n == "None") continue;
|
||||||
|
labels.Add(n);
|
||||||
|
values.Add(n);
|
||||||
|
}
|
||||||
|
foreach (string k in d.EmbeddedNavKeys)
|
||||||
|
{
|
||||||
|
if (values.Contains(k)) continue;
|
||||||
|
labels.Add($"[emb] {k}");
|
||||||
|
values.Add(k);
|
||||||
|
}
|
||||||
|
return (labels.ToArray(), values.ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Nav names for source completion (Patrol, nav files and embedded keys, no duplicates).</summary>
|
||||||
public static IReadOnlyList<string> CompletionNavs(MetaPayload d)
|
public static IReadOnlyList<string> CompletionNavs(MetaPayload d)
|
||||||
{
|
{
|
||||||
var combined = new List<string>(d.NavFiles.Count + d.EmbeddedNavKeys.Count);
|
var combined = new List<string>(d.NavFiles.Count + d.EmbeddedNavKeys.Count + 1);
|
||||||
|
if (!HasRoute(d, PatrolRoute)) combined.Add(PatrolRoute);
|
||||||
combined.AddRange(d.NavFiles);
|
combined.AddRange(d.NavFiles);
|
||||||
foreach (string n in d.EmbeddedNavKeys) if (!combined.Contains(n)) combined.Add(n);
|
foreach (string n in d.EmbeddedNavKeys) if (!combined.Contains(n)) combined.Add(n);
|
||||||
return combined;
|
return combined;
|
||||||
|
|
|
||||||
|
|
@ -141,9 +141,21 @@ internal static class MetaRuleEdit
|
||||||
/// STATE: block per state that has rules), so this rule is what keeps an empty state.</summary>
|
/// STATE: block per state that has rules), so this rule is what keeps an empty state.</summary>
|
||||||
public static MetaRuleDto Placeholder(string state) => new() { State = state, Condition = Never, Action = NoAction };
|
public static MetaRuleDto Placeholder(string state) => new() { State = state, Condition = Never, Action = NoAction };
|
||||||
|
|
||||||
|
/// <summary>The longest rule name the editor takes.</summary>
|
||||||
|
public const int MaxNameLength = 80;
|
||||||
|
|
||||||
|
/// <summary>A typed rule name: one line (RynthAi writes it as a "~~ @name" comment line), no longer
|
||||||
|
/// than <see cref="MaxNameLength"/>. The editor trims the ends when it sends the rule.</summary>
|
||||||
|
public static string CleanName(string? typed)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(typed)) return string.Empty;
|
||||||
|
string s = typed.Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' ');
|
||||||
|
return s.Length > MaxNameLength ? s.Substring(0, MaxNameLength) : s;
|
||||||
|
}
|
||||||
|
|
||||||
public static bool IsPlaceholder(MetaRuleDto r) =>
|
public static bool IsPlaceholder(MetaRuleDto r) =>
|
||||||
r.Condition == Never && r.Action == NoAction && r.ConditionData.Length == 0 && r.ActionData.Length == 0
|
r.Condition == Never && r.Action == NoAction && r.ConditionData.Length == 0 && r.ActionData.Length == 0
|
||||||
&& r.Children.Count == 0 && r.ActionChildren.Count == 0;
|
&& r.Children.Count == 0 && r.ActionChildren.Count == 0 && r.Name.Length == 0;
|
||||||
|
|
||||||
/// <summary>False for conditions with nothing to type: Never, Always, Character Death, Any Vendor Open,
|
/// <summary>False for conditions with nothing to type: Never, Always, Character Death, Any Vendor Open,
|
||||||
/// Vendor Closed, Need To Buff, Portalspace Entered / Exited, Navroute Empty (and the composites).</summary>
|
/// Vendor Closed, Need To Buff, Portalspace Entered / Exited, Navroute Empty (and the composites).</summary>
|
||||||
|
|
@ -227,11 +239,11 @@ internal static class MetaRuleEdit
|
||||||
r.ActionChildren.Add(new MetaRuleDto { State = r.State, Action = NoAction });
|
r.ActionChildren.Add(new MetaRuleDto { State = r.State, Action = NoAction });
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Same state, condition, action, data, enabled flag and children (not LastFiredMs).</summary>
|
/// <summary>Same state, name, condition, action, data, enabled flag and children (not LastFiredMs).</summary>
|
||||||
public static bool SameContent(MetaRuleDto a, MetaRuleDto b)
|
public static bool SameContent(MetaRuleDto a, MetaRuleDto b)
|
||||||
{
|
{
|
||||||
if (!string.Equals(a.State, b.State, StringComparison.Ordinal) || a.Condition != b.Condition || a.Action != b.Action
|
if (!string.Equals(a.State, b.State, StringComparison.Ordinal) || a.Condition != b.Condition || a.Action != b.Action
|
||||||
|| a.Enabled != b.Enabled
|
|| a.Enabled != b.Enabled || !string.Equals(a.Name, b.Name, StringComparison.Ordinal)
|
||||||
|| !string.Equals(a.ConditionData, b.ConditionData, StringComparison.Ordinal)
|
|| !string.Equals(a.ConditionData, b.ConditionData, StringComparison.Ordinal)
|
||||||
|| !string.Equals(a.ActionData, b.ActionData, StringComparison.Ordinal)
|
|| !string.Equals(a.ActionData, b.ActionData, StringComparison.Ordinal)
|
||||||
|| a.Children.Count != b.Children.Count || a.ActionChildren.Count != b.ActionChildren.Count)
|
|| a.Children.Count != b.Children.Count || a.ActionChildren.Count != b.ActionChildren.Count)
|
||||||
|
|
|
||||||
486
src/RynthCore.Engine/UI/Data/MetaRowText.cs
Normal file
486
src/RynthCore.Engine/UI/Data/MetaRowText.cs
Normal file
|
|
@ -0,0 +1,486 @@
|
||||||
|
// ============================================================================
|
||||||
|
// RynthCore.Engine - UI/Data/MetaRowText.cs
|
||||||
|
// How the Meta panel's rule list reads a rule (2026-10-11 readability pass):
|
||||||
|
// words in one colour, the values you typed in another, state names in the
|
||||||
|
// state headers' amber, and a problem (an empty chat command, a Set State to
|
||||||
|
// a state that doesn't exist) in red.
|
||||||
|
//
|
||||||
|
// Count Prismatic Taper ≤ 50 (was "Inventory Item Count <=: Prismatic Taper, 50")
|
||||||
|
// Expr getcharintprop[25]<30
|
||||||
|
// and not Spell 512 ≥ 305 s left (an All of two: one line each, joined by "and")
|
||||||
|
// /vt opt set enablecombat true (a DoAll: one line per action, in order)
|
||||||
|
// → ReBuff
|
||||||
|
//
|
||||||
|
// Full form: a list of lines (nested All / Any indent under an "and any of"
|
||||||
|
// line). Compact form: one line ("a and (b or c)", actions joined by " · ").
|
||||||
|
// An All or Any of one condition is just that condition, as RynthAi runs it.
|
||||||
|
//
|
||||||
|
// No ImGui here (tools/MetaEditTests compiles this file): MetaFace turns
|
||||||
|
// tones into colours and draws the lines.
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace RynthCore.Engine.UI.Data;
|
||||||
|
|
||||||
|
/// <summary>What a piece of rule text is, for its colour.</summary>
|
||||||
|
internal enum MetaTone : byte
|
||||||
|
{
|
||||||
|
/// <summary>Words: "Count", "Spell", "s left".</summary>
|
||||||
|
Label,
|
||||||
|
/// <summary>What was typed: an item name, a number, a chat command.</summary>
|
||||||
|
Value,
|
||||||
|
/// <summary>A state name (Set / Call Meta State, Watchdog).</summary>
|
||||||
|
State,
|
||||||
|
/// <summary>An expression or regex.</summary>
|
||||||
|
Code,
|
||||||
|
/// <summary>"and" / "or" / "not".</summary>
|
||||||
|
Join,
|
||||||
|
/// <summary>Never, None, "(nothing)".</summary>
|
||||||
|
Dim,
|
||||||
|
/// <summary>Something that won't work as written: "(empty)", a missing state.</summary>
|
||||||
|
Warn,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal readonly struct MetaSeg
|
||||||
|
{
|
||||||
|
public readonly string Text;
|
||||||
|
public readonly MetaTone Tone;
|
||||||
|
public MetaSeg(string text, MetaTone tone) { Text = text; Tone = tone; }
|
||||||
|
public override string ToString() => Text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One line of a rule's condition or action column (full form).</summary>
|
||||||
|
internal sealed class MetaLine
|
||||||
|
{
|
||||||
|
/// <summary>Nesting: the line starts this many slots in (a guide line is drawn in each).</summary>
|
||||||
|
public int Depth;
|
||||||
|
/// <summary>The line is an item of an and / or list: <see cref="Join"/> sits in a slot before it,
|
||||||
|
/// so the items' text lines up whether or not they have a join word.</summary>
|
||||||
|
public bool Slot;
|
||||||
|
/// <summary>"and" / "or" on a list's second and later items; "" otherwise.</summary>
|
||||||
|
public string Join = string.Empty;
|
||||||
|
public MetaSeg[] Segs = Array.Empty<MetaSeg>();
|
||||||
|
|
||||||
|
public string Plain()
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
if (Join.Length > 0) sb.Append(Join).Append(' ');
|
||||||
|
foreach (MetaSeg s in Segs) sb.Append(s.Text);
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What the text needs from outside: spell names, which states exist.</summary>
|
||||||
|
internal sealed class MetaTextContext
|
||||||
|
{
|
||||||
|
/// <summary>A spell's name, or null when unknown (the spell table may still be loading).</summary>
|
||||||
|
public Func<uint, string?>? SpellName;
|
||||||
|
/// <summary>The meta's states (any case); null skips the missing-state check.</summary>
|
||||||
|
public ICollection<string>? States;
|
||||||
|
/// <summary>True when the meta or NavProfiles has a route of this name (then "Patrol" is that
|
||||||
|
/// route, not the dungeon patrol); null: no route is called Patrol.</summary>
|
||||||
|
public Func<string, bool>? RouteExists;
|
||||||
|
/// <summary>Set when a spell id was shown as a number for want of a name.</summary>
|
||||||
|
public bool MissedSpellName;
|
||||||
|
|
||||||
|
public bool StateExists(string s)
|
||||||
|
{
|
||||||
|
if (States == null) return true;
|
||||||
|
foreach (string x in States)
|
||||||
|
if (string.Equals(x, s, StringComparison.OrdinalIgnoreCase)) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class MetaRowText
|
||||||
|
{
|
||||||
|
public const int All = 2, Any = 3, Not = 20, DoAll = 4;
|
||||||
|
private const int MaxLevels = 8; // the editor nests 4; a hand-written file could go deeper
|
||||||
|
|
||||||
|
public const string Le = "≤", Ge = "≥", Arrow = "→", Dot = "·";
|
||||||
|
|
||||||
|
// =====================================================================
|
||||||
|
// Conditions
|
||||||
|
// =====================================================================
|
||||||
|
|
||||||
|
/// <summary>The condition column's lines. An All / Any of two or more at the top lists its
|
||||||
|
/// conditions one per line, the second and later ones starting "and" / "or".</summary>
|
||||||
|
public static MetaLine[] ConditionLines(MetaRuleDto rule, MetaTextContext ctx)
|
||||||
|
{
|
||||||
|
var lines = new List<MetaLine>();
|
||||||
|
Cond(rule, 0, slot: false, join: "", lead: null, lines, ctx, 0);
|
||||||
|
return lines.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
// c's lines. depth/slot/join place its first line (an item of the parent's list gets the slot);
|
||||||
|
// lead goes before its text on that line ("not ").
|
||||||
|
private static void Cond(MetaRuleDto c, int depth, bool slot, string join, List<MetaSeg>? lead,
|
||||||
|
List<MetaLine> lines, MetaTextContext ctx, int level)
|
||||||
|
{
|
||||||
|
if (level > MaxLevels)
|
||||||
|
{
|
||||||
|
lines.Add(Line(depth, slot, join, lead, new MetaSeg("…", MetaTone.Dim)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (c.Condition is All or Any)
|
||||||
|
{
|
||||||
|
List<MetaRuleDto> kids = c.Children;
|
||||||
|
string what = c.Condition == All ? "all of" : "any of";
|
||||||
|
if (kids.Count == 0)
|
||||||
|
{
|
||||||
|
lines.Add(Line(depth, slot, join, lead, new MetaSeg(what, MetaTone.Label), new MetaSeg(" (nothing)", MetaTone.Warn)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (kids.Count == 1)
|
||||||
|
{
|
||||||
|
Cond(kids[0], depth, slot, join, lead, lines, ctx, level + 1); // the same as the one condition
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
string word = c.Condition == All ? "and" : "or";
|
||||||
|
int kidDepth = depth;
|
||||||
|
if (slot || lead != null)
|
||||||
|
{
|
||||||
|
// An item of a list, or after "not": an "all of" / "any of" line, the conditions under it.
|
||||||
|
lines.Add(Line(depth, slot, join, lead, new MetaSeg(what, MetaTone.Label)));
|
||||||
|
kidDepth = depth + 1;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < kids.Count; i++)
|
||||||
|
Cond(kids[i], kidDepth, slot: true, join: i == 0 ? "" : word, lead: null, lines, ctx, level + 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (c.Condition == Not)
|
||||||
|
{
|
||||||
|
var notLead = new List<MetaSeg>();
|
||||||
|
if (lead != null) notLead.AddRange(lead);
|
||||||
|
notLead.Add(new MetaSeg("not ", MetaTone.Join));
|
||||||
|
if (c.Children.Count == 0)
|
||||||
|
{
|
||||||
|
notLead.Add(new MetaSeg("(nothing)", MetaTone.Warn));
|
||||||
|
lines.Add(Line(depth, slot, join, notLead));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Cond(c.Children[0], depth, slot, join, notLead, lines, ctx, level + 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
lines.Add(Line(depth, slot, join, lead, Leaf(c, ctx)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The condition on one line: "a and (b or c)", "not (a and b)".</summary>
|
||||||
|
public static MetaSeg[] ConditionCompact(MetaRuleDto rule, MetaTextContext ctx)
|
||||||
|
{
|
||||||
|
var segs = new List<MetaSeg>();
|
||||||
|
CondCompact(rule, segs, nested: false, ctx, 0);
|
||||||
|
return segs.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CondCompact(MetaRuleDto c, List<MetaSeg> o, bool nested, MetaTextContext ctx, int level)
|
||||||
|
{
|
||||||
|
if (level > MaxLevels) { o.Add(new MetaSeg("…", MetaTone.Dim)); return; }
|
||||||
|
if (c.Condition is All or Any)
|
||||||
|
{
|
||||||
|
List<MetaRuleDto> kids = c.Children;
|
||||||
|
if (kids.Count == 0)
|
||||||
|
{
|
||||||
|
o.Add(new MetaSeg(c.Condition == All ? "all of" : "any of", MetaTone.Label));
|
||||||
|
o.Add(new MetaSeg(" (nothing)", MetaTone.Warn));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (kids.Count == 1) { CondCompact(kids[0], o, nested, ctx, level + 1); return; }
|
||||||
|
string word = c.Condition == All ? " and " : " or ";
|
||||||
|
if (nested) o.Add(new MetaSeg("(", MetaTone.Join));
|
||||||
|
for (int i = 0; i < kids.Count; i++)
|
||||||
|
{
|
||||||
|
if (i > 0) o.Add(new MetaSeg(word, MetaTone.Join));
|
||||||
|
CondCompact(kids[i], o, nested: true, ctx, level + 1);
|
||||||
|
}
|
||||||
|
if (nested) o.Add(new MetaSeg(")", MetaTone.Join));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (c.Condition == Not)
|
||||||
|
{
|
||||||
|
o.Add(new MetaSeg("not ", MetaTone.Join));
|
||||||
|
if (c.Children.Count == 0) o.Add(new MetaSeg("(nothing)", MetaTone.Warn));
|
||||||
|
else CondCompact(c.Children[0], o, nested: true, ctx, level + 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
o.AddRange(Leaf(c, ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One plain condition (not All / Any / Not).</summary>
|
||||||
|
public static MetaSeg[] Leaf(MetaRuleDto c, MetaTextContext ctx)
|
||||||
|
{
|
||||||
|
string d = (c.ConditionData ?? string.Empty).Trim();
|
||||||
|
switch (c.Condition)
|
||||||
|
{
|
||||||
|
case 0: return One("Never", MetaTone.Dim);
|
||||||
|
case 1: return One("Always", MetaTone.Label);
|
||||||
|
case 4: return Typed("Chat matches ", d, MetaTone.Code);
|
||||||
|
case 27: return Typed("Chat captures ", d, MetaTone.Code);
|
||||||
|
case 26: return Typed("Expr ", d, MetaTone.Code);
|
||||||
|
case 5: return Typed("Free pack slots " + Le + " ", d, MetaTone.Value);
|
||||||
|
case 6: return Seconds("In state " + Ge + " ", d);
|
||||||
|
case 21: return Seconds("In state (P) " + Ge + " ", d);
|
||||||
|
case 7: return One("Character death", MetaTone.Label);
|
||||||
|
case 8: return One("Vendor open", MetaTone.Label);
|
||||||
|
case 9: return One("Vendor closed", MetaTone.Label);
|
||||||
|
case 10: return ItemCount(d, Le);
|
||||||
|
case 11: return ItemCount(d, Ge);
|
||||||
|
case 12: return MobsNamed(d);
|
||||||
|
case 13: return PriorityMobs(d);
|
||||||
|
case 14: return One("Need to buff", MetaTone.Label);
|
||||||
|
case 15:
|
||||||
|
return d.Length == 0
|
||||||
|
? new[] { new MetaSeg("No mobs within ", MetaTone.Label), new MetaSeg("20", MetaTone.Value), new MetaSeg(" (default)", MetaTone.Dim) }
|
||||||
|
: new[] { new MetaSeg("No mobs within ", MetaTone.Label), new MetaSeg(d, MetaTone.Value) };
|
||||||
|
case 16: return Typed("Landblock ", d.ToUpperInvariant(), MetaTone.Value);
|
||||||
|
case 17: return Typed("Landcell ", d.ToUpperInvariant(), MetaTone.Value);
|
||||||
|
case 18: return One("Entered portal space", MetaTone.Label);
|
||||||
|
case 19: return One("Left portal space", MetaTone.Label);
|
||||||
|
case 22: return SpellLeft(d, Ge, ctx);
|
||||||
|
case 23: return SpellLeft(d, Le, ctx);
|
||||||
|
case 24: return Unit("Burden " + Ge + " ", d, "%");
|
||||||
|
case 25: return Typed("Off route " + Ge + " ", d, MetaTone.Value);
|
||||||
|
case 28: return One("Nav route empty", MetaTone.Label);
|
||||||
|
case 29: return Typed("Health " + Le + " ", d, MetaTone.Value);
|
||||||
|
case 30: return Unit("Health " + Ge + " ", d, "%");
|
||||||
|
case 31: return Typed("Mana " + Le + " ", d, MetaTone.Value);
|
||||||
|
case 32: return Unit("Mana " + Ge + " ", d, "%");
|
||||||
|
case 33: return Typed("Stamina " + Le + " ", d, MetaTone.Value);
|
||||||
|
case 34: return Unit("Vitae " + Ge + " ", d, "%");
|
||||||
|
case 35: return Unit("No kill for ", d, " min");
|
||||||
|
default:
|
||||||
|
// A condition this engine doesn't know yet (a newer RynthAi): its number and data.
|
||||||
|
string name = "Condition " + c.Condition.ToString(CultureInfo.InvariantCulture);
|
||||||
|
return d.Length == 0 ? One(name, MetaTone.Label)
|
||||||
|
: new[] { new MetaSeg(name + " ", MetaTone.Label), new MetaSeg(d, MetaTone.Value) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// "Count Prismatic Taper ≤ 50" from "Prismatic Taper,50" (the count after the last comma).
|
||||||
|
private static MetaSeg[] ItemCount(string d, string op)
|
||||||
|
{
|
||||||
|
int comma = d.LastIndexOf(',');
|
||||||
|
if (comma < 0) return Typed("Count ", d, MetaTone.Value);
|
||||||
|
string name = d.Substring(0, comma).Trim(), count = d.Substring(comma + 1).Trim();
|
||||||
|
return new[]
|
||||||
|
{
|
||||||
|
new MetaSeg("Count ", MetaTone.Label), Val(name), new MetaSeg(" " + op + " ", MetaTone.Label), Val(count),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// "Mobs Drudge ≥ 3 within 20" from "Drudge,20,3" (name regex, distance, count; the regex may hold commas).
|
||||||
|
private static MetaSeg[] MobsNamed(string d)
|
||||||
|
{
|
||||||
|
int c2 = d.LastIndexOf(',');
|
||||||
|
int c1 = c2 > 0 ? d.LastIndexOf(',', c2 - 1) : -1;
|
||||||
|
if (c1 < 0) return Typed("Mobs named ", d, MetaTone.Code);
|
||||||
|
string name = d.Substring(0, c1).Trim(), dist = d.Substring(c1 + 1, c2 - c1 - 1).Trim(), count = d.Substring(c2 + 1).Trim();
|
||||||
|
return new[]
|
||||||
|
{
|
||||||
|
new MetaSeg("Mobs ", MetaTone.Label), new MetaSeg(name.Length == 0 ? "(any name)" : name, name.Length == 0 ? MetaTone.Warn : MetaTone.Code),
|
||||||
|
new MetaSeg(" " + Ge + " ", MetaTone.Label), Val(count), new MetaSeg(" within ", MetaTone.Label), Val(dist),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// "Priority mobs ≥ 1 within 20" from "1,20" (count, distance).
|
||||||
|
private static MetaSeg[] PriorityMobs(string d)
|
||||||
|
{
|
||||||
|
int comma = d.IndexOf(',');
|
||||||
|
if (comma < 0) return Typed("Priority mobs ", d, MetaTone.Value);
|
||||||
|
return new[]
|
||||||
|
{
|
||||||
|
new MetaSeg("Priority mobs " + Ge + " ", MetaTone.Label), Val(d.Substring(0, comma).Trim()),
|
||||||
|
new MetaSeg(" within ", MetaTone.Label), Val(d.Substring(comma + 1).Trim()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// "Spell Strength Other VI ≥ 300 s left" from "2293,300" (spell id, seconds).
|
||||||
|
private static MetaSeg[] SpellLeft(string d, string op, MetaTextContext ctx)
|
||||||
|
{
|
||||||
|
int comma = d.IndexOf(',');
|
||||||
|
string id = (comma < 0 ? d : d.Substring(0, comma)).Trim();
|
||||||
|
string secs = comma < 0 ? "" : d.Substring(comma + 1).Trim();
|
||||||
|
string shown = id;
|
||||||
|
if (uint.TryParse(id, NumberStyles.None, CultureInfo.InvariantCulture, out uint sid))
|
||||||
|
{
|
||||||
|
string? name = ctx.SpellName?.Invoke(sid);
|
||||||
|
if (!string.IsNullOrEmpty(name)) shown = name;
|
||||||
|
else ctx.MissedSpellName = true;
|
||||||
|
}
|
||||||
|
return new[]
|
||||||
|
{
|
||||||
|
new MetaSeg("Spell ", MetaTone.Label), id.Length == 0 ? new MetaSeg("(not set)", MetaTone.Warn) : Val(shown),
|
||||||
|
new MetaSeg(" " + op + " ", MetaTone.Label), Val(secs), new MetaSeg(" s left", MetaTone.Label),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MetaSeg[] Seconds(string label, string d) => Unit(label, d, " s");
|
||||||
|
|
||||||
|
private static MetaSeg[] Unit(string label, string d, string unit) =>
|
||||||
|
d.Length == 0
|
||||||
|
? new[] { new MetaSeg(label, MetaTone.Label), new MetaSeg("(not set)", MetaTone.Warn) }
|
||||||
|
: new[] { new MetaSeg(label, MetaTone.Label), Val(d), new MetaSeg(unit, MetaTone.Label) };
|
||||||
|
|
||||||
|
// =====================================================================
|
||||||
|
// Actions
|
||||||
|
// =====================================================================
|
||||||
|
|
||||||
|
/// <summary>The action column's lines: one per action, a DoAll's in order.</summary>
|
||||||
|
public static MetaLine[] ActionLines(MetaRuleDto rule, MetaTextContext ctx)
|
||||||
|
{
|
||||||
|
var lines = new List<MetaLine>();
|
||||||
|
Act(rule, lines, ctx, 0);
|
||||||
|
return lines.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Act(MetaRuleDto a, List<MetaLine> lines, MetaTextContext ctx, int level)
|
||||||
|
{
|
||||||
|
if (a.Action == DoAll && level <= MaxLevels)
|
||||||
|
{
|
||||||
|
if (a.ActionChildren.Count == 0)
|
||||||
|
{
|
||||||
|
lines.Add(Line(0, false, "", null, new MetaSeg("do all", MetaTone.Label), new MetaSeg(" (nothing)", MetaTone.Warn)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
foreach (MetaRuleDto kid in a.ActionChildren) Act(kid, lines, ctx, level + 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
lines.Add(Line(0, false, "", null, ActionLeaf(a, ctx)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The actions on one line, joined by " · ".</summary>
|
||||||
|
public static MetaSeg[] ActionCompact(MetaRuleDto rule, MetaTextContext ctx)
|
||||||
|
{
|
||||||
|
var segs = new List<MetaSeg>();
|
||||||
|
foreach (MetaLine line in ActionLines(rule, ctx))
|
||||||
|
{
|
||||||
|
if (segs.Count > 0) segs.Add(new MetaSeg(" " + Dot + " ", MetaTone.Dim));
|
||||||
|
segs.AddRange(line.Segs);
|
||||||
|
}
|
||||||
|
return segs.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One action (not DoAll).</summary>
|
||||||
|
public static MetaSeg[] ActionLeaf(MetaRuleDto a, MetaTextContext ctx)
|
||||||
|
{
|
||||||
|
string d = (a.ActionData ?? string.Empty).Trim();
|
||||||
|
switch (a.Action)
|
||||||
|
{
|
||||||
|
case 0: return d.Length == 0 ? One("None", MetaTone.Dim) : Typed("None ", d, MetaTone.Value);
|
||||||
|
case 1:
|
||||||
|
// A command reads as itself ("/vt opt set ..."); plain text is said in chat.
|
||||||
|
if (d.Length == 0) return new[] { new MetaSeg("Chat ", MetaTone.Label), new MetaSeg("(empty)", MetaTone.Warn) };
|
||||||
|
return d.StartsWith('/') ? new[] { Val(d) } : new[] { new MetaSeg("Chat ", MetaTone.Label), Val(d) };
|
||||||
|
case 2: return StateRef(Arrow + " ", d, ctx);
|
||||||
|
case 5: return StateRef("Call " + Arrow + " ", d, ctx);
|
||||||
|
case 6: return One("Return from call", MetaTone.Label);
|
||||||
|
case 3:
|
||||||
|
{
|
||||||
|
int semi = d.IndexOf(';');
|
||||||
|
string route = semi >= 0 ? d.Substring(0, semi).Trim() : d;
|
||||||
|
// "Patrol" with no route of that name: RynthAi's dungeon patrol (/ra dunnav-patrol).
|
||||||
|
if (string.Equals(route, "Patrol", StringComparison.OrdinalIgnoreCase) && ctx.RouteExists?.Invoke(route) != true)
|
||||||
|
return new[] { new MetaSeg("Nav ", MetaTone.Label), new MetaSeg(route, MetaTone.Value), new MetaSeg(" (dungeon patrol)", MetaTone.Dim) };
|
||||||
|
return Typed("Nav ", route, MetaTone.Value);
|
||||||
|
}
|
||||||
|
case 7: return Typed("Expr ", d, MetaTone.Code);
|
||||||
|
case 8: return Typed("Chat expr ", d, MetaTone.Code);
|
||||||
|
case 9: return Watchdog(d, ctx);
|
||||||
|
case 10: return One("Clear watchdog", MetaTone.Label);
|
||||||
|
case 11:
|
||||||
|
{
|
||||||
|
// "variable;option" (RynthAi keeps metaf's GetOpt {Option} {Variable} as variable;option).
|
||||||
|
int semi = d.IndexOf(';');
|
||||||
|
if (semi < 0) return Typed("Get option ", d, MetaTone.Value);
|
||||||
|
return new[]
|
||||||
|
{
|
||||||
|
new MetaSeg("Get option ", MetaTone.Label), Val(d.Substring(semi + 1).Trim()),
|
||||||
|
new MetaSeg(" " + Arrow + " ", MetaTone.Label), new MetaSeg(d.Substring(0, semi).Trim(), MetaTone.Code),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 12:
|
||||||
|
{
|
||||||
|
int semi = d.IndexOf(';');
|
||||||
|
if (semi < 0) return Typed("Set option ", d, MetaTone.Value);
|
||||||
|
return new[]
|
||||||
|
{
|
||||||
|
new MetaSeg("Set ", MetaTone.Label), Val(d.Substring(0, semi).Trim()),
|
||||||
|
new MetaSeg(" = ", MetaTone.Label), Val(d.Substring(semi + 1).Trim()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case 13:
|
||||||
|
{
|
||||||
|
int semi = d.IndexOf(';');
|
||||||
|
return Typed("Create view ", semi >= 0 ? d.Substring(0, semi).Trim() : d, MetaTone.Value);
|
||||||
|
}
|
||||||
|
case 14: return Typed("Destroy view ", d, MetaTone.Value);
|
||||||
|
case 15: return One("Destroy all views", MetaTone.Label);
|
||||||
|
default:
|
||||||
|
string name = "Action " + a.Action.ToString(CultureInfo.InvariantCulture);
|
||||||
|
return d.Length == 0 ? One(name, MetaTone.Label)
|
||||||
|
: new[] { new MetaSeg(name + " ", MetaTone.Label), new MetaSeg(d, MetaTone.Value) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MetaSeg[] StateRef(string label, string state, MetaTextContext ctx)
|
||||||
|
{
|
||||||
|
if (state.Length == 0) return new[] { new MetaSeg(label, MetaTone.Label), new MetaSeg("(no state)", MetaTone.Warn) };
|
||||||
|
if (!ctx.StateExists(state))
|
||||||
|
return new[] { new MetaSeg(label, MetaTone.Label), new MetaSeg(state, MetaTone.Warn), new MetaSeg(" (no such state)", MetaTone.Warn) };
|
||||||
|
return new[] { new MetaSeg(label, MetaTone.Label), new MetaSeg(state, MetaTone.State) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// "Watchdog 5 m in 30 s → Default" from "Default;5;30" (state; meters; seconds): if you haven't
|
||||||
|
// moved that far in that long, the meta goes to the state.
|
||||||
|
private static MetaSeg[] Watchdog(string d, MetaTextContext ctx)
|
||||||
|
{
|
||||||
|
string[] p = d.Split(';');
|
||||||
|
if (p.Length < 3) return Typed("Watchdog ", d, MetaTone.Value);
|
||||||
|
var segs = new List<MetaSeg>
|
||||||
|
{
|
||||||
|
new("Watchdog ", MetaTone.Label), Val(p[1].Trim()), new(" m in ", MetaTone.Label), Val(p[2].Trim()), new(" s ", MetaTone.Label),
|
||||||
|
};
|
||||||
|
segs.AddRange(StateRef(Arrow + " ", p[0].Trim(), ctx));
|
||||||
|
return segs.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
// =====================================================================
|
||||||
|
// Helpers
|
||||||
|
// =====================================================================
|
||||||
|
|
||||||
|
/// <summary>The text of segments, for search and tooltips.</summary>
|
||||||
|
public static string Plain(MetaSeg[] segs)
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
foreach (MetaSeg s in segs) sb.Append(s.Text);
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MetaSeg Val(string text) =>
|
||||||
|
text.Length == 0 ? new MetaSeg("(not set)", MetaTone.Warn) : new MetaSeg(text, MetaTone.Value);
|
||||||
|
|
||||||
|
private static MetaSeg[] One(string text, MetaTone tone) => new[] { new MetaSeg(text, tone) };
|
||||||
|
|
||||||
|
// "Label value"; an empty value shows "(not set)".
|
||||||
|
private static MetaSeg[] Typed(string label, string value, MetaTone tone) =>
|
||||||
|
new[] { new MetaSeg(label, MetaTone.Label), value.Length == 0 ? new MetaSeg("(not set)", MetaTone.Warn) : new MetaSeg(value, tone) };
|
||||||
|
|
||||||
|
private static MetaLine Line(int depth, bool slot, string join, List<MetaSeg>? lead, params MetaSeg[] segs)
|
||||||
|
{
|
||||||
|
MetaSeg[] all = segs;
|
||||||
|
if (lead != null && lead.Count > 0)
|
||||||
|
{
|
||||||
|
all = new MetaSeg[lead.Count + segs.Length];
|
||||||
|
lead.CopyTo(all, 0);
|
||||||
|
segs.CopyTo(all, lead.Count);
|
||||||
|
}
|
||||||
|
return new MetaLine { Depth = depth, Slot = slot, Join = join, Segs = all };
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MetaLine Line(int depth, bool slot, string join, List<MetaSeg> lead) =>
|
||||||
|
new() { Depth = depth, Slot = slot, Join = join, Segs = lead.ToArray() };
|
||||||
|
}
|
||||||
|
|
@ -20,6 +20,10 @@ internal sealed class MetaRuleDto
|
||||||
public List<MetaRuleDto> Children { get; set; } = new();
|
public List<MetaRuleDto> Children { get; set; } = new();
|
||||||
public List<MetaRuleDto> ActionChildren { get; set; } = new();
|
public List<MetaRuleDto> ActionChildren { get; set; } = new();
|
||||||
public bool Enabled { get; set; } = true;
|
public bool Enabled { get; set; } = true;
|
||||||
|
/// <summary>A name to find the rule by (top-level rules; "" = none). RynthAi saves it in .af as a
|
||||||
|
/// "~~ @name ..." line; one without rule names leaves it out of the snapshot ("").</summary>
|
||||||
|
public string Name { get => _name; set => _name = value ?? string.Empty; } // a JSON null is ""
|
||||||
|
private string _name = string.Empty;
|
||||||
public long LastFiredMs { get; set; } = 99999;
|
public long LastFiredMs { get; set; } = 99999;
|
||||||
|
|
||||||
public MetaRuleDto Clone()
|
public MetaRuleDto Clone()
|
||||||
|
|
@ -27,7 +31,7 @@ internal sealed class MetaRuleDto
|
||||||
var r = new MetaRuleDto
|
var r = new MetaRuleDto
|
||||||
{
|
{
|
||||||
State = State, Condition = Condition, ConditionData = ConditionData,
|
State = State, Condition = Condition, ConditionData = ConditionData,
|
||||||
Action = Action, ActionData = ActionData, Enabled = Enabled, LastFiredMs = LastFiredMs,
|
Action = Action, ActionData = ActionData, Enabled = Enabled, Name = Name, LastFiredMs = LastFiredMs,
|
||||||
};
|
};
|
||||||
foreach (MetaRuleDto c in Children) r.Children.Add(c.Clone());
|
foreach (MetaRuleDto c in Children) r.Children.Add(c.Clone());
|
||||||
foreach (MetaRuleDto a in ActionChildren) r.ActionChildren.Add(a.Clone());
|
foreach (MetaRuleDto a in ActionChildren) r.ActionChildren.Add(a.Clone());
|
||||||
|
|
|
||||||
67
src/RynthCore.Engine/UI/Data/MetaStateClock.cs
Normal file
67
src/RynthCore.Engine/UI/Data/MetaStateClock.cs
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
// ============================================================================
|
||||||
|
// RynthCore.Engine - UI/Data/MetaStateClock.cs
|
||||||
|
// The Meta panel's timers (2026-10-11): how long the meta has been in its
|
||||||
|
// current state, and the Watchdog's countdown, from RynthAi's state-machine
|
||||||
|
// snapshot ("snapshot" in RynthPluginGetMetaJson), counted on between
|
||||||
|
// snapshots. No ImGui: tools/MetaEditTests compiles this file.
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace RynthCore.Engine.UI.Data;
|
||||||
|
|
||||||
|
/// <summary>RynthAi's meta state machine as of the snapshot ("snapshot"): how long the current state
|
||||||
|
/// has run, and the Watchdog. Read-only for the faces.</summary>
|
||||||
|
internal sealed class MetaStateSnapshot
|
||||||
|
{
|
||||||
|
public double SecondsInState { get; set; }
|
||||||
|
public bool WatchdogActive { get; set; }
|
||||||
|
public string WatchdogState { get; set; } = string.Empty;
|
||||||
|
public double WatchdogSecondsRemaining { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Seconds in the current state and the Watchdog's countdown between snapshots (they come every
|
||||||
|
/// couple of seconds): counted on from the last one, so the Meta panel's timers tick each second.
|
||||||
|
/// A state picked in the panel starts at 0 until the next snapshot says otherwise.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class MetaStateClock
|
||||||
|
{
|
||||||
|
private MetaStateSnapshot? _last;
|
||||||
|
private long _atMs;
|
||||||
|
|
||||||
|
public bool Known => _last != null;
|
||||||
|
|
||||||
|
public void Snapshot(MetaStateSnapshot? snap, long nowMs)
|
||||||
|
{
|
||||||
|
_last = snap;
|
||||||
|
_atMs = nowMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The panel set the state: its clock starts again.</summary>
|
||||||
|
public void StateSet(long nowMs)
|
||||||
|
{
|
||||||
|
if (_last == null) return;
|
||||||
|
_last = new MetaStateSnapshot { SecondsInState = 0 };
|
||||||
|
_atMs = nowMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double SecondsInState(long nowMs) =>
|
||||||
|
_last == null ? 0 : _last.SecondsInState + Math.Max(0, nowMs - _atMs) / 1000.0;
|
||||||
|
|
||||||
|
/// <summary>Seconds until the Watchdog fires (its state in <paramref name="state"/>); -1 when none is set.</summary>
|
||||||
|
public double WatchdogLeft(long nowMs, out string state)
|
||||||
|
{
|
||||||
|
state = _last?.WatchdogState ?? string.Empty;
|
||||||
|
if (_last == null || !_last.WatchdogActive) return -1;
|
||||||
|
return Math.Max(0, _last.WatchdogSecondsRemaining - Math.Max(0, nowMs - _atMs) / 1000.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>"42 s" under an hour (rules count seconds: "In state >= 300 s"), else "1:02:03".</summary>
|
||||||
|
public static string Format(double seconds)
|
||||||
|
{
|
||||||
|
long s = (long)Math.Max(0, seconds);
|
||||||
|
if (s < 3600) return s.ToString(System.Globalization.CultureInfo.InvariantCulture) + " s";
|
||||||
|
return string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{s / 3600}:{s / 60 % 60:00}:{s % 60:00}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -526,6 +526,12 @@ internal static class SettingsSchema
|
||||||
"While the 3D world isn't drawn the client runs at most this many frames a second, so the\n" +
|
"While the 3D world isn't drawn the client runs at most this many frames a second, so the\n" +
|
||||||
"saved time is slept (0 = no extra cap). Saved for this PC. Also: /rc video fps <n>.",
|
"saved time is slept (0 = no extra cap). Saved for this PC. Also: /rc video fps <n>.",
|
||||||
when: _ => D3D9.VideoPatch.Mode != D3D9.VideoPatchMode.Off),
|
when: _ => D3D9.VideoPatch.Mode != D3D9.VideoPatchMode.Off),
|
||||||
|
// Stored in engine.json for every client (EngineSettings), not in the RynthAi profile.
|
||||||
|
Bool("Close Client on Server Disconnect", _ => Plugins.EngineSettings.CloseOnServerDisconnect,
|
||||||
|
(_, v) => Plugins.EngineSettings.CloseOnServerDisconnect = v,
|
||||||
|
"On (default): when the game shows \"The server has disconnected\" (only a Quit Game button),\n" +
|
||||||
|
"the client closes itself 5 seconds later, so the launcher's auto-relaunch can start it again.\n" +
|
||||||
|
"A logout or a quit never shows that screen. Applies to all your clients; others pick it up when they start."),
|
||||||
Spacer(),
|
Spacer(),
|
||||||
Bool("Auto Cram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v,
|
Bool("Auto Cram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v,
|
||||||
"Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack."),
|
"Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack."),
|
||||||
|
|
|
||||||
|
|
@ -61,6 +61,12 @@ internal static class ItemsPanel
|
||||||
[JsonPropertyName("manaTapMinMana")] public int ManaTapMinMana { get; set; } = 2500;
|
[JsonPropertyName("manaTapMinMana")] public int ManaTapMinMana { get; set; } = 2500;
|
||||||
[JsonPropertyName("manaStoneKeepCount")]public int ManaStoneKeepCount{ get; set; } = 5;
|
[JsonPropertyName("manaStoneKeepCount")]public int ManaStoneKeepCount{ get; set; } = 5;
|
||||||
[JsonPropertyName("currentTargetName")] public string CurrentTargetName { get; set; } = string.Empty;
|
[JsonPropertyName("currentTargetName")] public string CurrentTargetName { get; set; } = string.Empty;
|
||||||
|
/// <summary>
|
||||||
|
/// Listed weapons the character no longer carries (not in the pack, not wielded), by id
|
||||||
|
/// (RynthAi from 2026-10-11; empty from older plugins). Display only: RynthAi ignores
|
||||||
|
/// it when the payload is saved back.
|
||||||
|
/// </summary>
|
||||||
|
[JsonPropertyName("missingIds")] public List<int> MissingIds { get; set; } = new();
|
||||||
}
|
}
|
||||||
|
|
||||||
internal sealed class WeaponEntry
|
internal sealed class WeaponEntry
|
||||||
|
|
|
||||||
|
|
@ -409,11 +409,17 @@ internal static class RynthChatPanel
|
||||||
{
|
{
|
||||||
ClearSelectionState();
|
ClearSelectionState();
|
||||||
chatStack.Children.Clear();
|
chatStack.Children.Clear();
|
||||||
foreach (var line in CurrentLines())
|
// The newest 500 shown lines, as AppendLine trims to: the history can be 10,000
|
||||||
|
// lines since 2026-10-11 (ChatHistory), far too many TextBlocks. ImGui's face shows all.
|
||||||
|
var lines = CurrentLines();
|
||||||
|
int from = lines.Length;
|
||||||
|
for (int shown = 0; from > 0 && shown < 500; )
|
||||||
|
if (ChatModel.LineVisible(lines[--from], activeTab, searchFilter)) shown++;
|
||||||
|
if (lines.Length > 0) lastShownId = lines[^1].Id;
|
||||||
|
for (int i = from; i < lines.Length; i++)
|
||||||
{
|
{
|
||||||
lastShownId = line.Id;
|
if (!ChatModel.LineVisible(lines[i], activeTab, searchFilter)) continue;
|
||||||
if (!ChatModel.LineVisible(line, activeTab, searchFilter)) continue;
|
chatStack.Children.Add(MakeTextBlock(lines[i]));
|
||||||
chatStack.Children.Add(MakeTextBlock(line));
|
|
||||||
}
|
}
|
||||||
// A full rebuild (tab/filter/font change) re-pins to the newest line.
|
// A full rebuild (tab/filter/font change) re-pins to the newest line.
|
||||||
if (autoScrollCheck.IsChecked == true)
|
if (autoScrollCheck.IsChecked == true)
|
||||||
|
|
|
||||||
|
|
@ -196,7 +196,13 @@ internal static class WindowFlags
|
||||||
public const uint HasError = 1u << 9;
|
public const uint HasError = 1u << 9;
|
||||||
/// <summary>RequestPos is a FirstUseEver default position (used only when nothing is saved).</summary>
|
/// <summary>RequestPos is a FirstUseEver default position (used only when nothing is saved).</summary>
|
||||||
public const uint PosIsDefault = 1u << 10;
|
public const uint PosIsDefault = 1u << 10;
|
||||||
public const uint Known = (1u << 11) - 1;
|
/// <summary>
|
||||||
|
/// With ShowInBar: the window gets a button of its own on the bar (icon, tooltip = title)
|
||||||
|
/// instead of a line in the Scripts menu. For plugin windows; engines before 2026-10-11
|
||||||
|
/// mask it off and list the window in the Scripts menu as before.
|
||||||
|
/// </summary>
|
||||||
|
public const uint BarButton = 1u << 11;
|
||||||
|
public const uint Known = (1u << 12) - 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static class DisplayListParser
|
internal static class DisplayListParser
|
||||||
|
|
|
||||||
|
|
@ -460,15 +460,27 @@ internal static class ScriptWindowRegistry
|
||||||
private static readonly Dictionary<string, ScriptWindow> ByPanelKey = new(StringComparer.OrdinalIgnoreCase);
|
private static readonly Dictionary<string, ScriptWindow> ByPanelKey = new(StringComparer.OrdinalIgnoreCase);
|
||||||
private static long _lastRejectLogTicks;
|
private static long _lastRejectLogTicks;
|
||||||
|
|
||||||
// The bar's Scripts menu: a copy-on-write snapshot of the ShowInBar windows, republished
|
// The bar's Scripts menu and the windows with a bar button of their own: copy-on-write
|
||||||
// (under Sync) when the window set, a title or a ShowInBar flag changed. AC's thread
|
// snapshots of the ShowInBar windows, republished (under Sync) when the window set, a
|
||||||
// reads it without taking Sync.
|
// title or a ShowInBar/BarButton flag changed. AC's thread reads them without taking Sync.
|
||||||
private static ScriptBarItem[] _barItems = Array.Empty<ScriptBarItem>();
|
private static ScriptBarItem[] _barItems = Array.Empty<ScriptBarItem>();
|
||||||
|
private static ScriptBarItem[] _barButtons = Array.Empty<ScriptBarItem>();
|
||||||
private static bool _barDirty;
|
private static bool _barDirty;
|
||||||
|
|
||||||
/// <summary>The Scripts menu's items, grouped (empty = no Scripts button). Any thread.</summary>
|
/// <summary>The Scripts menu's items, grouped (empty = no Scripts button). Any thread.</summary>
|
||||||
public static ScriptBarItem[] BarItems => Volatile.Read(ref _barItems);
|
public static ScriptBarItem[] BarItems => Volatile.Read(ref _barItems);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The windows that asked for a bar button of their own (ShowInBar + BarButton), sorted
|
||||||
|
/// like the menu. A new array whenever the set or a title changes, so the bar can compare
|
||||||
|
/// references to know when to rebuild its buttons. Any thread.
|
||||||
|
/// </summary>
|
||||||
|
public static ScriptBarItem[] BarButtons => Volatile.Read(ref _barButtons);
|
||||||
|
|
||||||
|
/// <summary>True when a window with these flags gets a bar button of its own (not a Scripts menu line).</summary>
|
||||||
|
public static bool HasOwnBarButton(uint flags) =>
|
||||||
|
(flags & (WindowFlags.ShowInBar | WindowFlags.BarButton)) == (WindowFlags.ShowInBar | WindowFlags.BarButton);
|
||||||
|
|
||||||
// ── Host functions ───────────────────────────────────────────────────
|
// ── Host functions ───────────────────────────────────────────────────
|
||||||
|
|
||||||
/// <summary>UiSubmit: the owner's complete window set. Pump thread, inside the owner's dispatch.</summary>
|
/// <summary>UiSubmit: the owner's complete window set. Pump thread, inside the owner's dispatch.</summary>
|
||||||
|
|
@ -629,28 +641,36 @@ internal static class ScriptWindowRegistry
|
||||||
ByPanelKey.Clear();
|
ByPanelKey.Clear();
|
||||||
_barDirty = false;
|
_barDirty = false;
|
||||||
Volatile.Write(ref _barItems, Array.Empty<ScriptBarItem>());
|
Volatile.Write(ref _barItems, Array.Empty<ScriptBarItem>());
|
||||||
|
Volatile.Write(ref _barButtons, Array.Empty<ScriptBarItem>());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Rebuilds the Scripts menu snapshot when something it shows changed. Caller holds Sync.</summary>
|
/// <summary>
|
||||||
|
/// Rebuilds the Scripts menu and bar button snapshots when something they show changed.
|
||||||
|
/// A ShowInBar window goes in the menu, or on a button of its own with BarButton set.
|
||||||
|
/// Caller holds Sync.
|
||||||
|
/// </summary>
|
||||||
private static void PublishBarLocked()
|
private static void PublishBarLocked()
|
||||||
{
|
{
|
||||||
if (!_barDirty) return;
|
if (!_barDirty) return;
|
||||||
_barDirty = false;
|
_barDirty = false;
|
||||||
var rows = new List<(string Group, ScriptWindow W)>();
|
var menu = new List<(string Group, ScriptWindow W)>();
|
||||||
|
var buttons = new List<(string Group, ScriptWindow W)>();
|
||||||
foreach (ScriptWindowOwner o in Owners.Values)
|
foreach (ScriptWindowOwner o in Owners.Values)
|
||||||
foreach (ScriptWindow w in o.Windows.Values)
|
foreach (ScriptWindow w in o.Windows.Values)
|
||||||
{
|
{
|
||||||
if ((w.Flags & WindowFlags.ShowInBar) == 0) continue;
|
if ((w.Flags & WindowFlags.ShowInBar) == 0) continue;
|
||||||
int slash = w.Key.LastIndexOf('/');
|
int slash = w.Key.LastIndexOf('/');
|
||||||
string group = slash > 0 ? w.Key[..slash] : o.Plugin.DisplayName;
|
string group = slash > 0 ? w.Key[..slash] : o.Plugin.DisplayName;
|
||||||
rows.Add((group, w));
|
(HasOwnBarButton(w.Flags) ? buttons : menu).Add((group, w));
|
||||||
}
|
}
|
||||||
if (rows.Count == 0)
|
Volatile.Write(ref _barItems, Snapshot(menu));
|
||||||
{
|
Volatile.Write(ref _barButtons, Snapshot(buttons));
|
||||||
Volatile.Write(ref _barItems, Array.Empty<ScriptBarItem>());
|
}
|
||||||
return;
|
|
||||||
}
|
private static ScriptBarItem[] Snapshot(List<(string Group, ScriptWindow W)> rows)
|
||||||
|
{
|
||||||
|
if (rows.Count == 0) return Array.Empty<ScriptBarItem>();
|
||||||
rows.Sort(static (a, b) =>
|
rows.Sort(static (a, b) =>
|
||||||
{
|
{
|
||||||
int c = string.Compare(a.Group, b.Group, StringComparison.OrdinalIgnoreCase);
|
int c = string.Compare(a.Group, b.Group, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
@ -662,7 +682,7 @@ internal static class ScriptWindowRegistry
|
||||||
for (int i = 0; i < rows.Count; i++)
|
for (int i = 0; i < rows.Count; i++)
|
||||||
items[i] = new ScriptBarItem(rows[i].W, rows[i].Group,
|
items[i] = new ScriptBarItem(rows[i].W, rows[i].Group,
|
||||||
groupStart: i == 0 || !string.Equals(rows[i].Group, rows[i - 1].Group, StringComparison.Ordinal));
|
groupStart: i == 0 || !string.Equals(rows[i].Group, rows[i - 1].Group, StringComparison.Ordinal));
|
||||||
Volatile.Write(ref _barItems, items);
|
return items;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Windows ──────────────────────────────────────────────────────────
|
// ── Windows ──────────────────────────────────────────────────────────
|
||||||
|
|
@ -677,7 +697,7 @@ internal static class ScriptWindowRegistry
|
||||||
bool specChanged = isNew || ((w.Flags ^ pw.Flags) & SpecFlags) != 0
|
bool specChanged = isNew || ((w.Flags ^ pw.Flags) & SpecFlags) != 0
|
||||||
|| w.DefaultSize != pw.DefaultSize || w.MinSize != pw.MinSize || w.DefaultPos != defaultPos;
|
|| w.DefaultSize != pw.DefaultSize || w.MinSize != pw.MinSize || w.DefaultPos != defaultPos;
|
||||||
bool titleChanged = w.Title != pw.Title;
|
bool titleChanged = w.Title != pw.Title;
|
||||||
if (isNew || titleChanged || ((w.Flags ^ pw.Flags) & WindowFlags.ShowInBar) != 0)
|
if (isNew || titleChanged || ((w.Flags ^ pw.Flags) & (WindowFlags.ShowInBar | WindowFlags.BarButton)) != 0)
|
||||||
_barDirty = true;
|
_barDirty = true;
|
||||||
w.Flags = pw.Flags;
|
w.Flags = pw.Flags;
|
||||||
w.Title = pw.Title;
|
w.Title = pw.Title;
|
||||||
|
|
@ -862,7 +882,7 @@ internal static class ScriptWindowRegistry
|
||||||
+ $" flags=0x{w.Flags:X3}({DescribeFlags(w.Flags)}) error={(w.ErrorUtf8 != null ? "shown" : "none")}"
|
+ $" flags=0x{w.Flags:X3}({DescribeFlags(w.Flags)}) error={(w.ErrorUtf8 != null ? "shown" : "none")}"
|
||||||
+ $" ops={w.List.OpCount} listSeq={w.List.ListSeq} playerSeq={w.PlayerVisibilitySeq}");
|
+ $" ops={w.List.OpCount} listSeq={w.List.ListSeq} playerSeq={w.PlayerVisibilitySeq}");
|
||||||
}
|
}
|
||||||
lines.Add($"script windows: {BarItems.Length} in the bar's Scripts menu");
|
lines.Add($"script windows: {BarItems.Length} in the bar's Scripts menu, {BarButtons.Length} with a bar button");
|
||||||
return lines;
|
return lines;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -881,6 +901,7 @@ internal static class ScriptWindowRegistry
|
||||||
Add(WindowFlags.NoPopOut, "NoPopOut");
|
Add(WindowFlags.NoPopOut, "NoPopOut");
|
||||||
Add(WindowFlags.HasError, "HasError");
|
Add(WindowFlags.HasError, "HasError");
|
||||||
Add(WindowFlags.PosIsDefault, "PosIsDefault");
|
Add(WindowFlags.PosIsDefault, "PosIsDefault");
|
||||||
|
Add(WindowFlags.BarButton, "BarButton");
|
||||||
return sb.Length > 0 ? sb.ToString() : "none";
|
return sb.Length > 0 ? sb.ToString() : "none";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -162,6 +162,9 @@ public struct RynthCoreApiNative
|
||||||
public IntPtr GetTrainingInfoFn; // int GetTrainingInfo(TrainingInfoNative* info, TrainingEntryNative* entries, int max) -> entries there are
|
public IntPtr GetTrainingInfoFn; // int GetTrainingInfo(TrainingInfoNative* info, TrainingEntryNative* entries, int max) -> entries there are
|
||||||
public IntPtr RaiseFn; // int Raise(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent) -> RaiseResult
|
public IntPtr RaiseFn; // int Raise(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent) -> RaiseResult
|
||||||
public IntPtr TrainSkillFn; // int TrainSkill(uint stype, int expectedCredits) -> RaiseResult
|
public IntPtr TrainSkillFn; // int TrainSkill(uint stype, int expectedCredits) -> RaiseResult
|
||||||
|
// v80: real slot order of a container's items, and moves that land at a slot
|
||||||
|
public IntPtr GetContainerOrderFn; // int GetContainerOrder(uint container, int slotKind, uint* ids, int max) -> count, -1 unknown
|
||||||
|
public IntPtr PutItemInContainerFn; // int PutItemInContainer(uint item, uint container, int placement) -> 1 sent, 0 refused, -1 unbound
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|
|
||||||
|
|
@ -155,6 +155,14 @@ public readonly unsafe struct RynthCoreHost
|
||||||
/// (spend unassigned XP and skill credits like the character window).</summary>
|
/// (spend unassigned XP and skill credits like the character window).</summary>
|
||||||
public bool HasTraining => _api.Version >= 79 && _api.GetTrainingInfoFn != IntPtr.Zero
|
public bool HasTraining => _api.Version >= 79 && _api.GetTrainingInfoFn != IntPtr.Zero
|
||||||
&& _api.RaiseFn != IntPtr.Zero && _api.TrainSkillFn != IntPtr.Zero;
|
&& _api.RaiseFn != IntPtr.Zero && _api.TrainSkillFn != IntPtr.Zero;
|
||||||
|
|
||||||
|
/// <summary>v80: <see cref="TryGetContainerOrder"/> (a container's items in real slot order, and the
|
||||||
|
/// side packs' order in the pack column).</summary>
|
||||||
|
public bool HasContainerOrder => _api.Version >= 80 && _api.GetContainerOrderFn != IntPtr.Zero;
|
||||||
|
|
||||||
|
/// <summary>v80: <see cref="PutItemInContainer"/> (a move that lands at a slot; a reorder within a
|
||||||
|
/// pack). The sender can still be unbound on an odd client: the call then answers -1.</summary>
|
||||||
|
public bool HasPutItemInContainer => _api.Version >= 80 && _api.PutItemInContainerFn != IntPtr.Zero;
|
||||||
public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero;
|
public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero;
|
||||||
public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero;
|
public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero;
|
||||||
public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero;
|
public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero;
|
||||||
|
|
@ -1784,6 +1792,47 @@ public readonly unsafe struct RynthCoreHost
|
||||||
? (RaiseResult)((delegate* unmanaged[Cdecl]<uint, int, int>)_api.TrainSkillFn)(stype, expectedCredits)
|
? (RaiseResult)((delegate* unmanaged[Cdecl]<uint, int, int>)_api.TrainSkillFn)(stype, expectedCredits)
|
||||||
: RaiseResult.EngineTooOld;
|
: RaiseResult.EngineTooOld;
|
||||||
|
|
||||||
|
// ─── Slot order and placed moves (API v80) ─────────────────────────────
|
||||||
|
// The server keeps every container's items in an order (the pack grid on screen); the engine
|
||||||
|
// follows it from the login message, a pack's contents list and every item move. A container
|
||||||
|
// is only known once a full list for it was seen: then and only then is there an order.
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// v80: the items in <paramref name="containerId"/> in real slot order (slot 0 first), or with
|
||||||
|
/// <paramref name="slotKind"/> the side packs and foci in the main pack (the pack column, top
|
||||||
|
/// first). <paramref name="count"/> = how many there are; the buffer grows to fit. False on an
|
||||||
|
/// engine before v80 or when the order isn't known (no full list for that container yet).
|
||||||
|
/// Any thread.
|
||||||
|
/// </summary>
|
||||||
|
public bool TryGetContainerOrder(uint containerId, bool slotKind, ref uint[] buffer, out int count)
|
||||||
|
{
|
||||||
|
count = 0;
|
||||||
|
if (!HasContainerOrder || containerId == 0) return false;
|
||||||
|
buffer ??= new uint[64];
|
||||||
|
var fn = (delegate* unmanaged[Cdecl]<uint, int, uint*, int, int>)_api.GetContainerOrderFn;
|
||||||
|
for (int attempt = 0; attempt < 3; attempt++)
|
||||||
|
{
|
||||||
|
int n;
|
||||||
|
fixed (uint* p = buffer) n = fn(containerId, slotKind ? 1 : 0, buffer.Length > 0 ? p : null, buffer.Length);
|
||||||
|
if (n < 0) return false;
|
||||||
|
if (n <= buffer.Length) { count = n; return true; }
|
||||||
|
buffer = new uint[Math.Max(n, buffer.Length * 2)];
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// v80: moves <paramref name="itemId"/> into <paramref name="containerId"/> at slot
|
||||||
|
/// <paramref name="placement"/> (the index it should end at, counted without it), like a drop on
|
||||||
|
/// a cell of the pack grid; within one container it reorders. The server decides and answers as
|
||||||
|
/// for any move. 1 sent or queued, 0 refused before sending, -1 the sender isn't bound on this
|
||||||
|
/// client, -2 an engine before v80. Any thread (queued to AC's main thread).
|
||||||
|
/// </summary>
|
||||||
|
public int PutItemInContainer(uint itemId, uint containerId, int placement)
|
||||||
|
=> HasPutItemInContainer
|
||||||
|
? ((delegate* unmanaged[Cdecl]<uint, uint, int, int>)_api.PutItemInContainerFn)(itemId, containerId, placement)
|
||||||
|
: -2;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// v78: which reassembled server messages this plugin wants on its
|
/// v78: which reassembled server messages this plugin wants on its
|
||||||
/// <c>RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c> export (Cdecl;
|
/// <c>RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c> export (Cdecl;
|
||||||
|
|
|
||||||
|
|
@ -33,7 +33,7 @@
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. -->
|
<!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. -->
|
||||||
<RynthCoreSdkApiVersion>79</RynthCoreSdkApiVersion>
|
<RynthCoreSdkApiVersion>80</RynthCoreSdkApiVersion>
|
||||||
<_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn>
|
<_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
|
|
||||||
79
tools/ChatHistoryBench/ChatHistoryBench.csproj
Normal file
79
tools/ChatHistoryBench/ChatHistoryBench.csproj
Normal file
|
|
@ -0,0 +1,79 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!--
|
||||||
|
How much a longer RynthChat history costs (2026-10-11, the "Chat history" setting), and
|
||||||
|
a check of the ImGui scroll behaviour the chat's follow-the-newest-line fix relies on.
|
||||||
|
Measures, with the real classes compiled in:
|
||||||
|
- managed memory per 1,000 lines: the engine's ChatLine (+ its route) and RynthChat's
|
||||||
|
ring (the plugin's ChatBuffer), filled with realistic AC lines;
|
||||||
|
- per poll: the plugin's BuildJson for a few new lines (0.3.0 vs the 0.2.1 copy in
|
||||||
|
OldChatBuffer.cs) and the engine's merge into a new published array;
|
||||||
|
- the first read after a bind or reload (the whole ring as JSON, parsed and routed);
|
||||||
|
- re-routing every kept line when a rule changes, on the pump;
|
||||||
|
- the chat face's work: a tab or search rebuild, unread counts, the tops, and
|
||||||
|
measuring wrapped heights with the engine's own cimgui.dll;
|
||||||
|
at 500, 2,000, 5,000 and 10,000 lines.
|
||||||
|
|
||||||
|
x86 on purpose, like acclient (object sizes, the 32-bit address space). Needs the x86
|
||||||
|
.NET runtime (C:\Program Files (x86)\dotnet). RynthChat's files come from the sibling
|
||||||
|
RynthSuite checkout (..\..\..\RynthSuite, or -p:RynthSuiteDir=...); without it the
|
||||||
|
plugin-side numbers are skipped.
|
||||||
|
Run: dotnet run -c Release (exit 0 = every check passed, 1 = one failed)
|
||||||
|
|
||||||
|
2026-10-11 (Tom's PC, x86, 8 cores; medians, run-to-run noise ~20%):
|
||||||
|
lines 500 2,000 5,000 10,000
|
||||||
|
memory, engine + plugin + face 0.9 MB 3.7 MB 9.1 MB 18 MB
|
||||||
|
plugin BuildJson, 3 new 0.2.1 / 0.3.0 19/4 us 50/6 us 82/5 us 136/4 us
|
||||||
|
engine merge per poll 0.3 us 1.2 us 3.4 us 11 us
|
||||||
|
first read (bind / reload, once) 3.2 ms 14.6 ms 29.8 ms 58.5 ms
|
||||||
|
re-route all lines (rule edit) 2.4 ms 6.6 ms 17.1 ms 27.2 ms
|
||||||
|
face: tab rebuild / search rebuild 11/177 us 45/716 us 0.1/1.8 ms 0.7/3.6 ms
|
||||||
|
face: unread, full (was) / incremental 100/0.5 us 396/0.5 us 1.1ms/0.7us 4.1ms/0.5us
|
||||||
|
face: measure every wrapped line 0.6 ms 3.7 ms 6.7 ms 14.8 ms
|
||||||
|
-->
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net10.0-windows</TargetFramework>
|
||||||
|
<PlatformTarget>x86</PlatformTarget>
|
||||||
|
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
|
||||||
|
<SelfContained>false</SelfContained>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
|
<InvariantGlobalization>true</InvariantGlobalization>
|
||||||
|
<ServerGarbageCollector>false</ServerGarbageCollector>
|
||||||
|
<ConcurrentGarbageCollection>false</ConcurrentGarbageCollection>
|
||||||
|
<TieredPGO>true</TieredPGO>
|
||||||
|
<RootNamespace>ChatHistoryBench</RootNamespace>
|
||||||
|
<RynthSuiteDir Condition="'$(RynthSuiteDir)' == ''">$(MSBuildThisFileDirectory)..\..\..\RynthSuite</RynthSuiteDir>
|
||||||
|
<RynthChatDir>$(RynthSuiteDir)\Plugins\RynthCore.Plugin.RynthChat</RynthChatDir>
|
||||||
|
<DefineConstants Condition="Exists('$(RynthChatDir)\ChatBuffer.cs')">$(DefineConstants);HAVE_RYNTHCHAT</DefineConstants>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatRouting.cs" Link="Engine\ChatRouting.cs" />
|
||||||
|
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatHistory.cs" Link="Engine\ChatHistory.cs" />
|
||||||
|
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatLineColors.cs" Link="Engine\ChatLineColors.cs" />
|
||||||
|
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatRuleMatching.cs" Link="Engine\ChatRuleMatching.cs" />
|
||||||
|
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatSettingsDto.cs" Link="Engine\ChatSettingsDto.cs" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup Condition="Exists('$(RynthChatDir)\ChatBuffer.cs')">
|
||||||
|
<Compile Include="$(RynthChatDir)\ChatBuffer.cs" Link="RynthChat\ChatBuffer.cs" />
|
||||||
|
<Compile Include="$(RynthChatDir)\ChatClassifier.cs" Link="RynthChat\ChatClassifier.cs" />
|
||||||
|
<Compile Include="$(RynthChatDir)\ChatLine.cs" Link="RynthChat\ChatLine.cs" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup Condition="!Exists('$(RynthChatDir)\ChatBuffer.cs')">
|
||||||
|
<Compile Remove="OldChatBuffer.cs" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<!-- The engine's own cimgui.dll (x86, obsolete APIs compiled out), over the package's. -->
|
||||||
|
<Target Name="CopyEngineCimgui" AfterTargets="Build">
|
||||||
|
<Copy SourceFiles="..\..\src\RynthCore.Engine\Native\cimgui.dll" DestinationFolder="$(OutputPath)" />
|
||||||
|
</Target>
|
||||||
|
|
||||||
|
</Project>
|
||||||
159
tools/ChatHistoryBench/OldChatBuffer.cs
Normal file
159
tools/ChatHistoryBench/OldChatBuffer.cs
Normal file
|
|
@ -0,0 +1,159 @@
|
||||||
|
// RynthChat 0.2.1's ChatBuffer as the per-poll baseline for ChatHistoryBench: unchanged
|
||||||
|
// but for its name and its capacity (a const 500 there). It cloned and walked the whole
|
||||||
|
// ring on every poll.
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
using RynthCore.Plugin.RynthChat;
|
||||||
|
|
||||||
|
namespace ChatHistoryBench;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The newest 500 chat lines, exported to the engine as JSON
|
||||||
|
/// (RynthChatGetScrollbackJson). Add runs on the game thread (chat dispatch),
|
||||||
|
/// BuildJson on the engine's pump thread; the lock covers both.
|
||||||
|
///
|
||||||
|
/// JSON per line: {"seq":N,"ts":"HH:mm:ss","chan":"Chat","type":3,"sender":"Bob"|null,"text":"..."}.
|
||||||
|
/// "type" (AC's ChatMessageType) was added in 0.2.0; engines before it ignore it.
|
||||||
|
/// Every non-ASCII character is written as a \uXXXX escape, so the export is
|
||||||
|
/// pure ASCII and survives the ANSI marshalling on both sides (before 0.2.0 an
|
||||||
|
/// accented name or the "→" of an outgoing tell arrived as "?").
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class OldChatBuffer
|
||||||
|
{
|
||||||
|
private readonly int Capacity; // bench: a const 500 in 0.2.1
|
||||||
|
|
||||||
|
private readonly ChatLine[] _ring;
|
||||||
|
|
||||||
|
public OldChatBuffer(int capacity) { Capacity = capacity; _ring = new ChatLine[capacity]; }
|
||||||
|
private readonly object _lock = new();
|
||||||
|
private int _head; // next write index (mod Capacity)
|
||||||
|
private int _count; // total items stored (≤ Capacity)
|
||||||
|
private ulong _nextSeq = 1;
|
||||||
|
|
||||||
|
internal void Add(string? text, int chatType)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(text)) return;
|
||||||
|
string channel = ChatClassifier.IsItemInfo(text) ? ChatClassifier.Items
|
||||||
|
: ChatClassifier.IsRynthOutput(text) ? ChatClassifier.Rynth
|
||||||
|
: ChatClassifier.ChannelFor(chatType);
|
||||||
|
string? sender = ChatClassifier.SenderFor(text, chatType);
|
||||||
|
string ts = DateTime.Now.ToString("HH:mm:ss");
|
||||||
|
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
// Numbered under the lock, so the ring is always in seq order (the
|
||||||
|
// engine skips anything at or below the last seq it has seen).
|
||||||
|
_ring[_head % Capacity] = new ChatLine
|
||||||
|
{
|
||||||
|
Seq = _nextSeq++,
|
||||||
|
Timestamp = ts,
|
||||||
|
Channel = channel,
|
||||||
|
ChatType = chatType,
|
||||||
|
Sender = sender,
|
||||||
|
Text = text,
|
||||||
|
};
|
||||||
|
_head = (_head + 1) % Capacity;
|
||||||
|
if (_count < Capacity) _count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns JSON array of lines with Seq > sinceSeq, oldest-first.
|
||||||
|
internal string BuildJson(ulong sinceSeq)
|
||||||
|
{
|
||||||
|
ChatLine[] snapshot;
|
||||||
|
int count;
|
||||||
|
int head;
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
snapshot = (ChatLine[])_ring.Clone();
|
||||||
|
count = _count;
|
||||||
|
head = _head;
|
||||||
|
}
|
||||||
|
|
||||||
|
var sb = new StringBuilder(256);
|
||||||
|
sb.Append('[');
|
||||||
|
bool first = true;
|
||||||
|
|
||||||
|
// Iterate oldest→newest. Oldest entry is at (head - count + Capacity) % Capacity.
|
||||||
|
int start = (head - count + Capacity) % Capacity;
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
var line = snapshot[(start + i) % Capacity];
|
||||||
|
if (line == null || line.Seq <= sinceSeq) continue;
|
||||||
|
|
||||||
|
if (!first) sb.Append(',');
|
||||||
|
first = false;
|
||||||
|
sb.Append("{\"seq\":");
|
||||||
|
sb.Append(line.Seq);
|
||||||
|
sb.Append(",\"ts\":\"");
|
||||||
|
AppendEscaped(sb, line.Timestamp);
|
||||||
|
sb.Append("\",\"chan\":\"");
|
||||||
|
AppendEscaped(sb, line.Channel);
|
||||||
|
sb.Append("\",\"type\":");
|
||||||
|
sb.Append(line.ChatType);
|
||||||
|
sb.Append(",\"sender\":");
|
||||||
|
if (line.Sender != null)
|
||||||
|
{
|
||||||
|
sb.Append('"');
|
||||||
|
AppendEscaped(sb, line.Sender);
|
||||||
|
sb.Append('"');
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
sb.Append("null");
|
||||||
|
}
|
||||||
|
sb.Append(",\"text\":\"");
|
||||||
|
AppendEscaped(sb, line.Text);
|
||||||
|
sb.Append("\"}");
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.Append(']');
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AppendEscaped(StringBuilder sb, string s)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < s.Length; i++)
|
||||||
|
{
|
||||||
|
char c = s[i];
|
||||||
|
// A surrogate pair is escaped as two \uXXXX; a lone half becomes U+FFFD.
|
||||||
|
// System.Text.Json refuses a lone surrogate, and before 0.2.1 one such line
|
||||||
|
// failed the engine's whole batch (and every poll after it).
|
||||||
|
if (char.IsSurrogate(c))
|
||||||
|
{
|
||||||
|
if (char.IsHighSurrogate(c) && i + 1 < s.Length && char.IsLowSurrogate(s[i + 1]))
|
||||||
|
{
|
||||||
|
AppendUnicodeEscape(sb, c);
|
||||||
|
AppendUnicodeEscape(sb, s[++i]);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
sb.Append("\\uFFFD");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
switch (c)
|
||||||
|
{
|
||||||
|
case '"': sb.Append("\\\""); break;
|
||||||
|
case '\\': sb.Append("\\\\"); break;
|
||||||
|
case '\n': sb.Append("\\n"); break;
|
||||||
|
case '\r': sb.Append("\\r"); break;
|
||||||
|
case '\t': sb.Append("\\t"); break;
|
||||||
|
default:
|
||||||
|
// Control characters and everything outside ASCII: the string is
|
||||||
|
// marshalled as ANSI, which would turn those into '?'.
|
||||||
|
if (c < 0x20 || c > 0x7E)
|
||||||
|
AppendUnicodeEscape(sb, c);
|
||||||
|
else
|
||||||
|
sb.Append(c);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AppendUnicodeEscape(StringBuilder sb, char c)
|
||||||
|
{
|
||||||
|
sb.Append("\\u");
|
||||||
|
sb.Append(((int)c).ToString("X4"));
|
||||||
|
}
|
||||||
|
}
|
||||||
584
tools/ChatHistoryBench/Program.cs
Normal file
584
tools/ChatHistoryBench/Program.cs
Normal file
|
|
@ -0,0 +1,584 @@
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Numerics;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using ImGuiNET;
|
||||||
|
using RynthCore.Engine.UI.Data;
|
||||||
|
|
||||||
|
namespace ChatHistoryBench;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What a longer chat history costs, and whether ImGui scrolls the way ChatFace's
|
||||||
|
/// follow fix needs (see the csproj header). Prints tables; exit 1 if a scroll check fails.
|
||||||
|
/// </summary>
|
||||||
|
internal static unsafe class Program
|
||||||
|
{
|
||||||
|
private static readonly int[] Sizes = { 500, 2000, 5000, 10000 };
|
||||||
|
private static int _checks, _failed;
|
||||||
|
|
||||||
|
private static int Main(string[] args)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"ChatHistoryBench: {(Environment.Is64BitProcess ? "x64" : "x86")} process, .NET {Environment.Version}, {Environment.ProcessorCount} cores");
|
||||||
|
#if !HAVE_RYNTHCHAT
|
||||||
|
Console.WriteLine("RynthSuite checkout not found: plugin-side numbers skipped.");
|
||||||
|
#endif
|
||||||
|
InitImGui();
|
||||||
|
ScrollChecks();
|
||||||
|
HistoryChecks();
|
||||||
|
Memory();
|
||||||
|
Cpu();
|
||||||
|
Console.WriteLine();
|
||||||
|
Console.WriteLine($"Checks: {_checks - _failed}/{_checks} passed.");
|
||||||
|
return _failed == 0 ? 0 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Realistic lines ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static readonly string[] Names = { "Drakkon", "Aja", "Bob Smith", "Lucy", "Malar Zhavik", "Tusker Slayer", "Kel of the Vale" };
|
||||||
|
private static readonly string[] Monsters = { "Tusker Guard", "Olthoi Swarm Nymph", "Mattekar", "Banderling Raider", "Shadow Child", "Drudge Ravener" };
|
||||||
|
private static readonly string[] Spells = { "Incantation of Strength Self", "Aura of Defender", "Focus Self VII", "Incantation of Blade Protection Self" };
|
||||||
|
private static readonly string[] Words = (
|
||||||
|
"anyone selling mana stones need buffs at the portal north of town lfg for the olthoi dungeon " +
|
||||||
|
"key drop rate is terrible tonight wts pyreal motes lol thanks for the fellow invite where is " +
|
||||||
|
"the lifestone heading to the hub in a minute who has a legendary key ok see you there").Split(' ');
|
||||||
|
|
||||||
|
/// <summary>One AC chat line: (text as AC prints it, ChatMessageType), 60-150 characters.</summary>
|
||||||
|
private static (string Text, int Type) MakeLine(Random r)
|
||||||
|
{
|
||||||
|
int target = r.Next(60, 151);
|
||||||
|
string name = Names[r.Next(Names.Length)], mob = Monsters[r.Next(Monsters.Length)];
|
||||||
|
int k = r.Next(100);
|
||||||
|
(string head, int type, bool speech) = k switch
|
||||||
|
{
|
||||||
|
< 20 => ($"You hit {mob} for {r.Next(5, 400)} points of slashing damage!", 0x16, false),
|
||||||
|
< 35 => ($"{mob} grazes your foot for {r.Next(1, 90)} points of bludgeoning damage!", 0x15, false),
|
||||||
|
< 45 => ($"You cast {Spells[r.Next(Spells.Length)]} on yourself, refreshing {Spells[r.Next(Spells.Length)]}", 0x07, false),
|
||||||
|
< 50 => ("The spell consumed the following components: Prismatic Taper", 0x07, false),
|
||||||
|
< 62 => ($"[{(r.Next(2) == 0 ? "General" : "Trade")}] {name} says, \"", 0x08, true),
|
||||||
|
< 72 => ($"{name} says, \"", 0x02, true),
|
||||||
|
< 77 => ($"{name} tells you, \"", 0x03, true),
|
||||||
|
< 82 => ($"[Fellowship] {name} says, \"", 0x13, true),
|
||||||
|
< 88 => ($"[RynthAi] Meta state Combat -> Loot ({r.Next(1, 30)} corpses)", 0x00, false),
|
||||||
|
< 92 => ("You're too busy!", 0x1A, false),
|
||||||
|
_ => ($"You've earned {r.Next(1000, 900000)} experience.", 0x0D, false),
|
||||||
|
};
|
||||||
|
var sb = new System.Text.StringBuilder(head, 160);
|
||||||
|
if (speech)
|
||||||
|
{
|
||||||
|
if (r.Next(12) == 0) sb.Append("Drakkon "); // someone mentions you now and then
|
||||||
|
while (sb.Length < target - 1) sb.Append(Words[r.Next(Words.Length)]).Append(' ');
|
||||||
|
sb.Length = Math.Min(sb.Length, target - 1);
|
||||||
|
sb.Append('"');
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
while (sb.Length < target) sb.Append(sb.Length == head.Length ? " (" : " ").Append(Words[r.Next(Words.Length)]);
|
||||||
|
if (sb.Length > target) sb.Length = target;
|
||||||
|
}
|
||||||
|
return (sb.ToString(), type);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── The engine side, as ChatSource does it ───────────────────────────
|
||||||
|
|
||||||
|
private static ChatRouter MakeRouter()
|
||||||
|
{
|
||||||
|
ChatFilterRule Rule(ChatMatchMode mode, string pattern, ChatRuleAction action, string tab = "", string when = "",
|
||||||
|
ChatColorMode color = ChatColorMode.None)
|
||||||
|
{
|
||||||
|
var r = new ChatFilterRule { Mode = mode, Pattern = pattern, Action = action, Tab = tab, When = when, ColorMode = color };
|
||||||
|
r.Recompile();
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
// A rule set like a player's: hide spam, sort, copy tells, colour.
|
||||||
|
ChatFilterRule[] rules =
|
||||||
|
{
|
||||||
|
Rule(ChatMatchMode.Contains, "You're too busy!", ChatRuleAction.Hide),
|
||||||
|
Rule(ChatMatchMode.StartsWith, "The spell consumed the following components", ChatRuleAction.Hide),
|
||||||
|
Rule(ChatMatchMode.Regex, @"^\[RynthAi\]", ChatRuleAction.Move, "Bot"),
|
||||||
|
Rule(ChatMatchMode.Regex, @"tells you, """, ChatRuleAction.Copy, "Tells", color: ChatColorMode.Line),
|
||||||
|
Rule(ChatMatchMode.Regex, @"^\[(Trade|LFG)\]", ChatRuleAction.Move, "Trade"),
|
||||||
|
Rule(ChatMatchMode.Regex, @"^You cast .* on yourself", ChatRuleAction.Move, "Buffs", "type:7"),
|
||||||
|
Rule(ChatMatchMode.Regex, @"\b(Olthoi|Tusker)\b", ChatRuleAction.Color, color: ChatColorMode.Match),
|
||||||
|
Rule(ChatMatchMode.Contains, "Critical hit", ChatRuleAction.Color, color: ChatColorMode.Line),
|
||||||
|
};
|
||||||
|
var mention = new Regex(@"(?<![\w'])(?:Drakkon)(?![\w])", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant,
|
||||||
|
TimeSpan.FromMilliseconds(ChatFilterRule.TimeoutMs));
|
||||||
|
return new ChatRouter(rules, mention, "Drakkon", countHits: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long _nextId = 1;
|
||||||
|
|
||||||
|
/// <summary>ChatSource.PollLines' parse + construct + route for one read (no AC-link stripping: no links here).</summary>
|
||||||
|
private static List<ChatLine> ReadLines(string json, ChatRouter router)
|
||||||
|
{
|
||||||
|
RynthChatLineDto[]? dtos = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatLineDtoArray);
|
||||||
|
var added = new List<ChatLine>(dtos?.Length ?? 0);
|
||||||
|
foreach (RynthChatLineDto dto in dtos ?? Array.Empty<RynthChatLineDto>())
|
||||||
|
{
|
||||||
|
var line = new ChatLine(_nextId++, dto.Ts ?? "", dto.Chan ?? "Other", dto.Type, dto.Sender, dto.Text ?? "") { Seq = dto.Seq };
|
||||||
|
line.Route = router.Evaluate(line, null);
|
||||||
|
added.Add(line);
|
||||||
|
}
|
||||||
|
return added;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if HAVE_RYNTHCHAT
|
||||||
|
private static RynthCore.Plugin.RynthChat.ChatBuffer FilledPlugin(int n, Random r)
|
||||||
|
{
|
||||||
|
var b = new RynthCore.Plugin.RynthChat.ChatBuffer(n);
|
||||||
|
for (int i = 0; i < n; i++) { var (t, ty) = MakeLine(r); b.Add(t, ty); }
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/// <summary>N engine lines, routed, built the way ChatSource builds them (from the plugin's JSON when it's here).</summary>
|
||||||
|
private static ChatLine[] EngineLines(int n, Random r, ChatRouter router)
|
||||||
|
{
|
||||||
|
#if HAVE_RYNTHCHAT
|
||||||
|
string json = FilledPlugin(n, r).BuildJson(0);
|
||||||
|
#else
|
||||||
|
var dtos = new RynthChatLineDto[n];
|
||||||
|
for (int i = 0; i < n; i++) { var (t, ty) = MakeLine(r); dtos[i] = new RynthChatLineDto { Seq = (ulong)i + 1, Ts = "12:34:56", Chan = "Combat", Type = ty, Text = t }; }
|
||||||
|
string json = JsonSerializer.Serialize(dtos, RynthChatJsonContext.Default.RynthChatLineDtoArray);
|
||||||
|
#endif
|
||||||
|
return ReadLines(json, router).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Memory ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static long Heap()
|
||||||
|
{
|
||||||
|
for (int i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); }
|
||||||
|
return GC.GetTotalMemory(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Bytes held by what <paramref name="make"/> returns.</summary>
|
||||||
|
private static long Held(Func<object> make)
|
||||||
|
{
|
||||||
|
make(); // once first, so lazy statics (regex caches, colour tables) aren't counted
|
||||||
|
long before = Heap();
|
||||||
|
object o = Make(make);
|
||||||
|
long after = Heap();
|
||||||
|
GC.KeepAlive(o);
|
||||||
|
return after - before;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not inlined: the temporaries of make() (JSON, DTOs, the plugin ring the engine lines
|
||||||
|
// were read from) must be unreachable when Held measures.
|
||||||
|
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
|
||||||
|
private static object Make(Func<object> make) => make();
|
||||||
|
|
||||||
|
private static void Memory()
|
||||||
|
{
|
||||||
|
Console.WriteLine();
|
||||||
|
Console.WriteLine("Managed memory (x86 object sizes), measured with GC.GetTotalMemory:");
|
||||||
|
Console.WriteLine($"{"lines",8} | {"engine lines",13} | {"plugin ring",12} | {"face lists",11} | {"total",9} | {"per 1,000",10}");
|
||||||
|
var router = MakeRouter();
|
||||||
|
foreach (int n in Sizes)
|
||||||
|
{
|
||||||
|
long engine = Held(() => EngineLines(n, new Random(n), router));
|
||||||
|
#if HAVE_RYNTHCHAT
|
||||||
|
long plugin = Held(() => FilledPlugin(n, new Random(n + 1)));
|
||||||
|
#else
|
||||||
|
long plugin = 0;
|
||||||
|
#endif
|
||||||
|
ChatLine[] lines = EngineLines(n, new Random(n), router);
|
||||||
|
long face = Held(() =>
|
||||||
|
{
|
||||||
|
// ChatFace's per-line lists (_vis, _h, _lay, _tops), sized like List growth leaves them.
|
||||||
|
var vis = new List<ChatLine>(lines);
|
||||||
|
var h = new List<float>(new float[n]);
|
||||||
|
var lay = new List<object?>(new object?[n]);
|
||||||
|
var tops = new float[n + 1];
|
||||||
|
return new object[] { vis, h, lay, tops };
|
||||||
|
});
|
||||||
|
long total = engine + plugin + face;
|
||||||
|
Console.WriteLine($"{n,8:N0} | {Mb(engine),13} | {Mb(plugin),12} | {Mb(face),11} | {Mb(total),9} | {Mb(total * 1000 / n),10}");
|
||||||
|
}
|
||||||
|
Console.WriteLine("(The face's highlighted lines also keep a hand layout; first read of the whole ring is transient: see 'first read'.)");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Mb(long bytes) => $"{bytes / 1048576.0:0.00} MB";
|
||||||
|
|
||||||
|
// ── CPU ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// <summary>Median milliseconds per call of <paramref name="body"/> (setup outside the timing).</summary>
|
||||||
|
private static double Time(Action body, int iters = 50, int rounds = 7)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < Math.Min(iters, 10); i++) body(); // warm up
|
||||||
|
var samples = new double[rounds];
|
||||||
|
for (int s = 0; s < rounds; s++)
|
||||||
|
{
|
||||||
|
long t0 = Stopwatch.GetTimestamp();
|
||||||
|
for (int i = 0; i < iters; i++) body();
|
||||||
|
samples[s] = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency / iters;
|
||||||
|
}
|
||||||
|
Array.Sort(samples);
|
||||||
|
return samples[rounds / 2];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Ms(double ms) => ms < 0.01 ? $"{ms * 1000:0.0} us" : ms < 1 ? $"{ms * 1000:0} us" : $"{ms:0.0} ms";
|
||||||
|
|
||||||
|
private static readonly string[] Tabs = { "All", "Chat", "Channels", "System", "Combat", "Rynth", "Items", "Other", "Bot", "Tells", "Trade", "Buffs" };
|
||||||
|
|
||||||
|
private static void Cpu()
|
||||||
|
{
|
||||||
|
Console.WriteLine();
|
||||||
|
Console.WriteLine("CPU, median per call (one batch = 3 new lines, the buffer full):");
|
||||||
|
var rows = new List<(string Name, string Where, string[] Cells)>();
|
||||||
|
void Row(string name, string where, Func<int, double> run)
|
||||||
|
{
|
||||||
|
var cells = new string[Sizes.Length];
|
||||||
|
for (int i = 0; i < Sizes.Length; i++) cells[i] = Ms(run(Sizes[i]));
|
||||||
|
rows.Add((name, where, cells));
|
||||||
|
}
|
||||||
|
|
||||||
|
#if HAVE_RYNTHCHAT
|
||||||
|
Row("plugin BuildJson, 3 new (0.2.1)", "pump, per poll", n =>
|
||||||
|
{
|
||||||
|
var r = new Random(n);
|
||||||
|
var b = new OldChatBuffer(n);
|
||||||
|
for (int i = 0; i < n; i++) { var (t, ty) = MakeLine(r); b.Add(t, ty); }
|
||||||
|
ulong seq = (ulong)n;
|
||||||
|
var adds = Enumerable.Range(0, 64).Select(_ => MakeLine(r)).ToArray();
|
||||||
|
int a = 0;
|
||||||
|
return Time(() =>
|
||||||
|
{
|
||||||
|
for (int i = 0; i < 3; i++) { var (t, ty) = adds[a++ & 63]; b.Add(t, ty); }
|
||||||
|
string json = b.BuildJson(seq);
|
||||||
|
seq += 3;
|
||||||
|
GC.KeepAlive(json);
|
||||||
|
}, 200);
|
||||||
|
});
|
||||||
|
Row("plugin BuildJson, 3 new (0.3.0)", "pump, per poll", n =>
|
||||||
|
{
|
||||||
|
var r = new Random(n);
|
||||||
|
var b = FilledPlugin(n, r);
|
||||||
|
ulong seq = (ulong)n;
|
||||||
|
var adds = Enumerable.Range(0, 64).Select(_ => MakeLine(r)).ToArray();
|
||||||
|
int a = 0;
|
||||||
|
return Time(() =>
|
||||||
|
{
|
||||||
|
for (int i = 0; i < 3; i++) { var (t, ty) = adds[a++ & 63]; b.Add(t, ty); }
|
||||||
|
string json = b.BuildJson(seq);
|
||||||
|
seq += 3;
|
||||||
|
GC.KeepAlive(json);
|
||||||
|
}, 200);
|
||||||
|
});
|
||||||
|
Row("plugin BuildJson, nothing new (0.2.1)", "pump, per poll", n =>
|
||||||
|
{
|
||||||
|
var r = new Random(n);
|
||||||
|
var b = new OldChatBuffer(n);
|
||||||
|
for (int i = 0; i < n; i++) { var (t, ty) = MakeLine(r); b.Add(t, ty); }
|
||||||
|
return Time(() => GC.KeepAlive(b.BuildJson((ulong)n)), 200);
|
||||||
|
});
|
||||||
|
Row("plugin BuildJson, nothing new (0.3.0)", "pump, per poll", n =>
|
||||||
|
{
|
||||||
|
var b = FilledPlugin(n, new Random(n));
|
||||||
|
return Time(() => GC.KeepAlive(b.BuildJson((ulong)n)), 200);
|
||||||
|
});
|
||||||
|
#endif
|
||||||
|
Row("engine read: parse+route 3 lines", "pump, per poll", n =>
|
||||||
|
{
|
||||||
|
var router = MakeRouter();
|
||||||
|
var r = new Random(n);
|
||||||
|
var dtos = Enumerable.Range(0, 3).Select(i => { var (t, ty) = MakeLine(r); return new RynthChatLineDto { Seq = (ulong)i + 1, Ts = "12:34:56", Chan = "Combat", Type = ty, Text = t }; }).ToArray();
|
||||||
|
string json = JsonSerializer.Serialize(dtos, RynthChatJsonContext.Default.RynthChatLineDtoArray);
|
||||||
|
return Time(() => GC.KeepAlive(ReadLines(json, router)), 200);
|
||||||
|
});
|
||||||
|
Row("engine merge into new array", "pump, per poll", n =>
|
||||||
|
{
|
||||||
|
var router = MakeRouter();
|
||||||
|
ChatLine[] kept = EngineLines(n, new Random(n), router);
|
||||||
|
var added = EngineLines(3, new Random(1), router).ToList();
|
||||||
|
return Time(() => { kept = ChatHistory.Merge(kept, added, n); }, 200);
|
||||||
|
});
|
||||||
|
Row("first read: whole ring, JSON+parse+route", "pump, once per bind/reload", n =>
|
||||||
|
{
|
||||||
|
var router = MakeRouter();
|
||||||
|
#if HAVE_RYNTHCHAT
|
||||||
|
var b = FilledPlugin(n, new Random(n));
|
||||||
|
return Time(() =>
|
||||||
|
{
|
||||||
|
string json = b.BuildJson(0);
|
||||||
|
IntPtr p = Marshal.StringToHGlobalAnsi(json); // RynthChatGetScrollbackJson
|
||||||
|
string got = Marshal.PtrToStringAnsi(p)!; // ChatSource
|
||||||
|
Marshal.FreeHGlobal(p);
|
||||||
|
GC.KeepAlive(ReadLines(got, router));
|
||||||
|
}, 3, 5);
|
||||||
|
#else
|
||||||
|
return double.NaN;
|
||||||
|
#endif
|
||||||
|
});
|
||||||
|
Row("re-route every kept line (rule edit)", "pump, per rule change", n =>
|
||||||
|
{
|
||||||
|
var router = MakeRouter();
|
||||||
|
ChatLine[] kept = EngineLines(n, new Random(n), router);
|
||||||
|
return Time(() =>
|
||||||
|
{
|
||||||
|
router.BeginPass();
|
||||||
|
try { foreach (ChatLine line in kept) line.Route = router.Evaluate(line, null); }
|
||||||
|
finally { router.EndPass(); }
|
||||||
|
}, 3, 5);
|
||||||
|
});
|
||||||
|
Row("face rebuild: tab Combat", "AC thread, tab switch", n =>
|
||||||
|
{
|
||||||
|
ChatLine[] kept = EngineLines(n, new Random(n), MakeRouter());
|
||||||
|
var vis = new List<ChatLine>(n);
|
||||||
|
return Time(() => { vis.Clear(); foreach (var l in kept) if (ChatModel.LineVisible(l, "Combat", "")) vis.Add(l); }, 20);
|
||||||
|
});
|
||||||
|
Row("face rebuild: All + search \"tusker\"", "AC thread, search keystroke", n =>
|
||||||
|
{
|
||||||
|
ChatLine[] kept = EngineLines(n, new Random(n), MakeRouter());
|
||||||
|
var vis = new List<ChatLine>(n);
|
||||||
|
return Time(() => { vis.Clear(); foreach (var l in kept) if (ChatModel.LineVisible(l, "All", "tusker")) vis.Add(l); }, 20);
|
||||||
|
});
|
||||||
|
Row("face new lines: filter 3 + drop 3 + tops", "AC thread, per batch", n =>
|
||||||
|
{
|
||||||
|
ChatLine[] kept = EngineLines(n, new Random(n), MakeRouter());
|
||||||
|
var vis = new List<ChatLine>(kept); var h = new List<float>(new float[n]); var lay = new List<object?>(new object?[n]);
|
||||||
|
var tops = new float[n + 1];
|
||||||
|
var added = EngineLines(3, new Random(2), MakeRouter());
|
||||||
|
return Time(() =>
|
||||||
|
{
|
||||||
|
vis.RemoveRange(0, 3); h.RemoveRange(0, 3); lay.RemoveRange(0, 3);
|
||||||
|
foreach (var l in added) if (ChatModel.LineVisible(l, "All", "")) { vis.Add(l); h.Add(13f); lay.Add(null); }
|
||||||
|
for (int i = 0; i < vis.Count; i++) tops[i + 1] = tops[i] + h[i];
|
||||||
|
}, 200);
|
||||||
|
});
|
||||||
|
Row("unread counts, full recount (before)", "AC thread, per batch (was)", n =>
|
||||||
|
{
|
||||||
|
ChatLine[] kept = EngineLines(n, new Random(n), MakeRouter());
|
||||||
|
var seen = Tabs.ToDictionary(t => t, _ => 0L); // worst case: no tab visited since the start
|
||||||
|
return Time(() => UnreadFull(kept, seen), 10);
|
||||||
|
});
|
||||||
|
Row("unread counts, incremental (now)", "AC thread, per batch", n =>
|
||||||
|
{
|
||||||
|
ChatLine[] kept = EngineLines(n, new Random(n), MakeRouter());
|
||||||
|
var seen = Tabs.ToDictionary(t => t, _ => 0L);
|
||||||
|
long countedTo = kept[^4].Id; // all but the newest 3 already counted
|
||||||
|
return Time(() => UnreadIncremental(kept, seen, countedTo), 200);
|
||||||
|
});
|
||||||
|
Row("measure wrapped heights, every line", "AC thread, resize/font/rebuild", n =>
|
||||||
|
{
|
||||||
|
ChatLine[] kept = EngineLines(n, new Random(n), MakeRouter());
|
||||||
|
double ms = 0;
|
||||||
|
InFrame(() => ms = Time(() => { foreach (var l in kept) GC.KeepAlive(ImGui.CalcTextSize(l.Text, false, 380f).Y); }, 3, 5));
|
||||||
|
return ms;
|
||||||
|
});
|
||||||
|
|
||||||
|
int nameW = rows.Max(r => r.Name.Length), whereW = rows.Max(r => r.Where.Length);
|
||||||
|
Console.WriteLine($"{"".PadRight(nameW)} | {"thread / when".PadRight(whereW)} | " + string.Join(" | ", Sizes.Select(s => $"{s,9:N0}")));
|
||||||
|
foreach (var (name, where, cells) in rows)
|
||||||
|
Console.WriteLine($"{name.PadRight(nameW)} | {where.PadRight(whereW)} | " + string.Join(" | ", cells.Select(c => $"{c,9}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int UnreadFull(ChatLine[] lines, Dictionary<string, long> seen)
|
||||||
|
{
|
||||||
|
int total = 0;
|
||||||
|
foreach (string tab in Tabs)
|
||||||
|
{
|
||||||
|
long s = seen[tab];
|
||||||
|
for (int i = lines.Length - 1; i >= 0 && lines[i].Id > s; i--)
|
||||||
|
if (ChatModel.LineInTab(lines[i], tab)) total++;
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int UnreadIncremental(ChatLine[] lines, Dictionary<string, long> seen, long countedTo)
|
||||||
|
{
|
||||||
|
int total = 0;
|
||||||
|
foreach (string tab in Tabs)
|
||||||
|
{
|
||||||
|
long floor = Math.Max(seen[tab], countedTo);
|
||||||
|
for (int i = lines.Length - 1; i >= 0 && lines[i].Id > floor; i--)
|
||||||
|
if (ChatModel.LineInTab(lines[i], tab)) total++;
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── ImGui ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static void InitImGui()
|
||||||
|
{
|
||||||
|
IntPtr ctx = ImGui.CreateContext();
|
||||||
|
ImGui.SetCurrentContext(ctx);
|
||||||
|
ImGuiIOPtr io = ImGui.GetIO();
|
||||||
|
io.NativePtr->IniFilename = null;
|
||||||
|
io.DisplaySize = new Vector2(1280, 800);
|
||||||
|
io.DeltaTime = 1f / 60f;
|
||||||
|
string fonts = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
|
||||||
|
string font = new[] { "CascadiaMono.ttf", "consola.ttf" }.Select(f => Path.Combine(fonts, f)).FirstOrDefault(File.Exists) ?? "";
|
||||||
|
if (font.Length > 0) io.Fonts.AddFontFromFileTTF(font, 13f);
|
||||||
|
else io.Fonts.AddFontDefault();
|
||||||
|
io.Fonts.GetTexDataAsRGBA32(out IntPtr _, out int _, out int _, out int _);
|
||||||
|
io.Fonts.SetTexID((IntPtr)1);
|
||||||
|
Console.WriteLine($"ImGui {ImGui.GetVersion()} (the engine's cimgui.dll), font {(font.Length > 0 ? Path.GetFileName(font) : "default")} 13 px");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void InFrame(Action body)
|
||||||
|
{
|
||||||
|
ImGui.GetIO().DeltaTime = 1f / 60f;
|
||||||
|
ImGui.NewFrame();
|
||||||
|
ImGui.SetNextWindowPos(Vector2.Zero);
|
||||||
|
ImGui.SetNextWindowSize(new Vector2(600, 500));
|
||||||
|
ImGui.Begin("host", ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoSavedSettings);
|
||||||
|
body();
|
||||||
|
ImGui.End();
|
||||||
|
ImGui.EndFrame();
|
||||||
|
}
|
||||||
|
|
||||||
|
private const float ViewH = 200f;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One frame of a chat-like list: content <paramref name="total"/> high. "before" is
|
||||||
|
/// ChatFace until 2026-10-11 (SetScrollHereY at the end of the frame); "now" hands the
|
||||||
|
/// content size and the scroll to this frame's BeginChild. <paramref name="setScroll"/>
|
||||||
|
/// (now only): the scroll to ask for, or null. Returns (scroll, max) as seen inside the child.
|
||||||
|
/// </summary>
|
||||||
|
private static (float Scroll, float Max) ListFrame(string id, float total, bool now, float? setScroll, bool follow)
|
||||||
|
{
|
||||||
|
(float, float) seen = default;
|
||||||
|
InFrame(() =>
|
||||||
|
{
|
||||||
|
if (now)
|
||||||
|
{
|
||||||
|
ImGui.SetNextWindowContentSize(new Vector2(0, total));
|
||||||
|
if (setScroll is float s) ImGui.SetNextWindowScroll(new Vector2(-1, s));
|
||||||
|
}
|
||||||
|
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
|
||||||
|
ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, 10f);
|
||||||
|
ImGui.BeginChild(id, new Vector2(300, ViewH), ImGuiChildFlags.None, ImGuiWindowFlags.AlwaysVerticalScrollbar);
|
||||||
|
ImGui.PopStyleVar(2);
|
||||||
|
seen = (ImGui.GetScrollY(), ImGui.GetScrollMaxY());
|
||||||
|
ImGui.Dummy(new Vector2(280, total));
|
||||||
|
if (!now && follow && total > ViewH) ImGui.SetScrollHereY(1f);
|
||||||
|
ImGui.EndChild();
|
||||||
|
});
|
||||||
|
return seen;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Check(string what, bool ok, string detail)
|
||||||
|
{
|
||||||
|
_checks++;
|
||||||
|
if (!ok) _failed++;
|
||||||
|
Console.WriteLine($" {(ok ? "ok " : "FAIL")} {what}: {detail}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>ChatHistory's arithmetic and RynthChat's resizable ring (newest kept, seq untouched).</summary>
|
||||||
|
private static void HistoryChecks()
|
||||||
|
{
|
||||||
|
Console.WriteLine();
|
||||||
|
Console.WriteLine("History checks:");
|
||||||
|
Check("Clamp: absent is the default, steps of 500, 500..10000",
|
||||||
|
ChatHistory.Clamp(0) == 2000 && ChatHistory.Clamp(-5) == 2000 && ChatHistory.Clamp(1) == 500
|
||||||
|
&& ChatHistory.Clamp(2240) == 2000 && ChatHistory.Clamp(2260) == 2500 && ChatHistory.Clamp(99999) == 10000,
|
||||||
|
$"0->{ChatHistory.Clamp(0)}, 1->{ChatHistory.Clamp(1)}, 2260->{ChatHistory.Clamp(2260)}, 99999->{ChatHistory.Clamp(99999)}");
|
||||||
|
int[] old = Enumerable.Range(1, 10).ToArray();
|
||||||
|
int[] m1 = ChatHistory.Merge(old, new[] { 11, 12, 13 }, 10);
|
||||||
|
int[] m2 = ChatHistory.Merge(old, new[] { 11, 12 }, 20);
|
||||||
|
int[] m3 = ChatHistory.Merge(old, Enumerable.Range(11, 30).ToArray(), 10);
|
||||||
|
Check("Merge keeps the newest, in order", m1.SequenceEqual(Enumerable.Range(4, 10)) && m2.SequenceEqual(Enumerable.Range(1, 12))
|
||||||
|
&& m3.SequenceEqual(Enumerable.Range(31, 10)), $"[{m1[0]}..{m1[^1]}], [{m2[0]}..{m2[^1]}], [{m3[0]}..{m3[^1]}]");
|
||||||
|
int[]? t1 = ChatHistory.Trim(old, 4);
|
||||||
|
Check("Trim drops the oldest, or nothing", t1 != null && t1.SequenceEqual(new[] { 7, 8, 9, 10 }) && ChatHistory.Trim(old, 10) == null, "");
|
||||||
|
#if HAVE_RYNTHCHAT
|
||||||
|
var r = new Random(5);
|
||||||
|
var b = new RynthCore.Plugin.RynthChat.ChatBuffer(500);
|
||||||
|
for (int i = 0; i < 700; i++) { var (t, ty) = MakeLine(r); b.Add(t, ty); }
|
||||||
|
ulong[] Seqs(string json) => JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatLineDtoArray)!.Select(d => d.Seq).ToArray();
|
||||||
|
ulong[] all = Seqs(b.BuildJson(0));
|
||||||
|
Check("ring of 500 after 700 lines: seq 201..700", all.Length == 500 && all[0] == 201 && all[^1] == 700, $"{all.Length} lines, {all[0]}..{all[^1]}");
|
||||||
|
b.SetCapacity(2000);
|
||||||
|
for (int i = 0; i < 100; i++) { var (t, ty) = MakeLine(r); b.Add(t, ty); }
|
||||||
|
all = Seqs(b.BuildJson(0));
|
||||||
|
Check("grown to 2000: keeps all 500, then grows; seq carries on", all.Length == 600 && all[0] == 201 && all[^1] == 800
|
||||||
|
&& all.Zip(all.Skip(1)).All(p => p.Second == p.First + 1), $"{all.Length} lines, {all[0]}..{all[^1]}");
|
||||||
|
b.SetCapacity(100);
|
||||||
|
all = Seqs(b.BuildJson(0));
|
||||||
|
ulong[] since = Seqs(b.BuildJson(790));
|
||||||
|
Check("shrunk to 100: the newest 100; 'since' still works", all.Length == 100 && all[0] == 701 && all[^1] == 800
|
||||||
|
&& since.SequenceEqual(Enumerable.Range(791, 10).Select(x => (ulong)x)) && b.BuildJson(800) == "[]" && b.BuildJson(5000) == "[]",
|
||||||
|
$"{all.Length} lines, {all[0]}..{all[^1]}; since 790: {since.Length}");
|
||||||
|
Check("capacity clamped to 100..10000", b.SetCapacity(5) == 100 && b.SetCapacity(50000) == 10000 && b.Capacity == 10000, "");
|
||||||
|
var old500 = new OldChatBuffer(500);
|
||||||
|
var new500 = new RynthCore.Plugin.RynthChat.ChatBuffer(500);
|
||||||
|
var r1 = new Random(9);
|
||||||
|
bool same = true;
|
||||||
|
for (int i = 0; i < 1200; i++)
|
||||||
|
{
|
||||||
|
var (t, ty) = MakeLine(r1);
|
||||||
|
old500.Add(t, ty);
|
||||||
|
new500.Add(t, ty);
|
||||||
|
if (i % 37 == 0)
|
||||||
|
foreach (ulong s in new ulong[] { 0, (ulong)Math.Max(0, i - 3), (ulong)i, (ulong)(i + 1), (ulong)(i + 5) })
|
||||||
|
{
|
||||||
|
string a = old500.BuildJson(s), c = new500.BuildJson(s);
|
||||||
|
// Same lines; only the timestamp may differ (each buffer stamps its own Add).
|
||||||
|
if (!Seqs(a).SequenceEqual(Seqs(c))) same = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Check("0.3.0 returns the same lines as 0.2.1 for any 'since'", same, "");
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ScrollChecks()
|
||||||
|
{
|
||||||
|
Console.WriteLine();
|
||||||
|
Console.WriteLine("Scroll checks (a 200 px list; 'gap' = how far the newest line's bottom is from the list's bottom in that frame):");
|
||||||
|
|
||||||
|
// Before: following with SetScrollHereY. New lines (40 px) arrive with nothing dropped,
|
||||||
|
// then a full buffer drops 60 px off the top while 20 px arrive.
|
||||||
|
for (int f = 0; f < 4; f++) ListFrame("before", 1000, false, null, true);
|
||||||
|
var a = ListFrame("before", 1040, false, null, true);
|
||||||
|
float gapGrow = 1040 - (a.Scroll + ViewH);
|
||||||
|
var b = ListFrame("before", 1040, false, null, true);
|
||||||
|
var c = ListFrame("before", 1000, false, null, true);
|
||||||
|
float gapShrink = 1000 - (c.Scroll + ViewH);
|
||||||
|
var d = ListFrame("before", 1000, false, null, true);
|
||||||
|
Console.WriteLine($" before: 40 px arrive -> gap {gapGrow:0} px that frame, {1040 - (b.Scroll + ViewH):0} the next; " +
|
||||||
|
$"60 px leave the top as 20 arrive -> gap {gapShrink:0} px (blank under the text), {1000 - (d.Scroll + ViewH):0} the next");
|
||||||
|
Check("the old follow lags a frame (the bounce)", gapGrow > 0.5f && Math.Abs(gapShrink) > 0.5f,
|
||||||
|
"reproduced: each batch is first drawn at the old scroll");
|
||||||
|
|
||||||
|
// Now: the content size and the scroll go into this frame's BeginChild.
|
||||||
|
for (int f = 0; f < 4; f++) ListFrame("now", 1000, true, 1000, true);
|
||||||
|
var e = ListFrame("now", 1040, true, 1040, true);
|
||||||
|
var g = ListFrame("now", 1000, true, 1000, true);
|
||||||
|
var h = ListFrame("now", 1000.4f, true, 1000.4f, true);
|
||||||
|
Check("following: newest line at the bottom in the same frame (grow)", Math.Abs(1040 - (e.Scroll + ViewH)) <= 0.5f && Math.Abs(e.Scroll - e.Max) < 0.01f,
|
||||||
|
$"scroll {e.Scroll:0.#} of max {e.Max:0.#}");
|
||||||
|
Check("following: newest line at the bottom in the same frame (shrink)", Math.Abs(1000 - (g.Scroll + ViewH)) <= 0.5f && Math.Abs(g.Scroll - g.Max) < 0.01f,
|
||||||
|
$"scroll {g.Scroll:0.#} of max {g.Max:0.#}");
|
||||||
|
Check("following: still pinned with a fractional height", h.Scroll >= h.Max - 24f && Math.Abs(1000.4f - (h.Scroll + ViewH)) < 1f,
|
||||||
|
$"scroll {h.Scroll:0.##} of max {h.Max:0.##} (stays within the 24 px stick threshold)");
|
||||||
|
|
||||||
|
// Scrolled up: lines of a fractional height (13.3 px) leave the top of a full buffer as
|
||||||
|
// as many arrive, 60 batches. The view moves up by exactly what left, fractions carried.
|
||||||
|
float total = 5000, start = 3000, scroll = start, carry = 0, worst = 0, worstNoCarry = 0, noCarry = start;
|
||||||
|
ListFrame("up", total, true, start, false);
|
||||||
|
for (int i = 1; i <= 60; i++)
|
||||||
|
{
|
||||||
|
const float dropped = 13.3f;
|
||||||
|
float target = scroll + carry - dropped;
|
||||||
|
float applied = MathF.Round(Math.Max(0, target));
|
||||||
|
carry = target > 0 ? target - applied : 0;
|
||||||
|
var s = ListFrame("up", total, true, applied, false);
|
||||||
|
scroll = s.Scroll;
|
||||||
|
float exact = start - i * dropped;
|
||||||
|
worst = Math.Max(worst, Math.Abs(scroll - exact));
|
||||||
|
noCarry = MathF.Round(noCarry - dropped);
|
||||||
|
worstNoCarry = Math.Max(worstNoCarry, Math.Abs(noCarry - exact));
|
||||||
|
}
|
||||||
|
Check("scrolled up: the view holds still across 60 batches (no creep)", worst <= 0.51f,
|
||||||
|
$"off by at most {worst:0.00} px (without carrying fractions: {worstNoCarry:0.00} px)");
|
||||||
|
|
||||||
|
// Scrolled up, nothing dropped (buffer not full yet): no scroll is set, nothing moves.
|
||||||
|
var u0 = ListFrame("up2", 3000, true, 1200, false);
|
||||||
|
var u1 = ListFrame("up2", 3040, true, null, false);
|
||||||
|
var u2 = ListFrame("up2", 3080, true, null, false);
|
||||||
|
Check("scrolled up: new lines below leave the view where it is", u1.Scroll == u0.Scroll && u2.Scroll == u0.Scroll,
|
||||||
|
$"scroll {u0.Scroll:0} -> {u1.Scroll:0} -> {u2.Scroll:0}");
|
||||||
|
}
|
||||||
|
}
|
||||||
31
tools/ChatHistoryBench/Stubs.cs
Normal file
31
tools/ChatHistoryBench/Stubs.cs
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
// The two engine pieces ChatRouting.cs calls, without the engine. ChatModel's are copies
|
||||||
|
// of the real ones in src/RynthCore.Engine/UI/Data/ChatData.cs (MentionEligible, and
|
||||||
|
// LineInTab / LineVisible, which the chat face filters with).
|
||||||
|
|
||||||
|
namespace RynthCore.Engine.Compatibility
|
||||||
|
{
|
||||||
|
internal static class RynthLog
|
||||||
|
{
|
||||||
|
public static int Lines;
|
||||||
|
public static void UI(string message) { Lines++; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace RynthCore.Engine.UI.Data
|
||||||
|
{
|
||||||
|
internal static class ChatModel
|
||||||
|
{
|
||||||
|
public static int FilterBumps;
|
||||||
|
|
||||||
|
internal static bool MentionEligible(string channel, int chatType) =>
|
||||||
|
(channel == "Chat" || channel == "Channels") && chatType is not (4 or 9 or 11);
|
||||||
|
|
||||||
|
internal static void BumpFiltersVersion() => FilterBumps++;
|
||||||
|
|
||||||
|
public static bool LineInTab(ChatLine line, string tab) => line.Route.ShowsIn(tab, line.Channel);
|
||||||
|
|
||||||
|
public static bool LineVisible(ChatLine line, string tab, string search) =>
|
||||||
|
LineInTab(line, tab)
|
||||||
|
&& (search.Length == 0 || line.FormattedText.Contains(search, StringComparison.OrdinalIgnoreCase));
|
||||||
|
}
|
||||||
|
}
|
||||||
25
tools/DisconnectCloseTests/DisconnectCloseTests.csproj
Normal file
25
tools/DisconnectCloseTests/DisconnectCloseTests.csproj
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Offline checks for closing the client on a server disconnect (2026-10-11):
|
||||||
|
src\RynthCore.Engine\Compatibility\ServerDisconnectClosePolicy.cs, compiled in. On AC's
|
||||||
|
Disconnected screen ("The server has disconnected", only Quit Game) the engine closes the
|
||||||
|
client 5 s later (longer while the flight dump is written, at most 10 s more), tries once more
|
||||||
|
20 s after that and gives up at 60 s; it does nothing while the client is already exiting,
|
||||||
|
nothing but the first log line when the setting is off, and starts over if the screen goes.
|
||||||
|
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||||
|
-->
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<InvariantGlobalization>true</InvariantGlobalization>
|
||||||
|
<RootNamespace>DisconnectCloseTests</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ServerDisconnectClosePolicy.cs" Link="Engine\ServerDisconnectClosePolicy.cs" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
164
tools/DisconnectCloseTests/Program.cs
Normal file
164
tools/DisconnectCloseTests/Program.cs
Normal file
|
|
@ -0,0 +1,164 @@
|
||||||
|
using RynthCore.Engine.Compatibility;
|
||||||
|
using V = RynthCore.Engine.Compatibility.ServerDisconnectClosePolicy.Verdict;
|
||||||
|
|
||||||
|
namespace DisconnectCloseTests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// When the engine closes the client after AC lost the server (ServerDisconnectClosePolicy.cs).
|
||||||
|
/// Clients sat on "The server has disconnected" until someone clicked Quit Game, so no launcher
|
||||||
|
/// relaunched them (Drakkon and Aryze on DreamWeave, 2026-10-11 14:52, for 71+ minutes).
|
||||||
|
/// </summary>
|
||||||
|
internal static class Program
|
||||||
|
{
|
||||||
|
private static int _checks, _failed;
|
||||||
|
private static string _case = "";
|
||||||
|
|
||||||
|
private static int Main()
|
||||||
|
{
|
||||||
|
NothingOffTheScreen();
|
||||||
|
ClosesAfterTheDelay();
|
||||||
|
WaitsForTheFlightDumpButNotForever();
|
||||||
|
RetriesThenGivesUp();
|
||||||
|
SettingOffOnlyDetects();
|
||||||
|
TurnedOnWhileOnTheScreen();
|
||||||
|
NothingWhileExiting();
|
||||||
|
LeavingTheScreenStartsOver();
|
||||||
|
ZeroClockStillCounts();
|
||||||
|
|
||||||
|
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
|
||||||
|
return _failed == 0 ? 0 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Check(bool ok, string what)
|
||||||
|
{
|
||||||
|
_checks++;
|
||||||
|
if (ok) return;
|
||||||
|
_failed++;
|
||||||
|
Console.WriteLine($"[FAIL] {_case}: {what}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Eq(V actual, V expected, string what) =>
|
||||||
|
Check(actual == expected, $"{what}: expected {expected}, got {actual}");
|
||||||
|
|
||||||
|
/// <summary>Ticks every 16 ms from <paramref name="from"/> to <paramref name="to"/> (exclusive);
|
||||||
|
/// returns the verdicts other than None with the time they came.</summary>
|
||||||
|
private static List<(long At, V Verdict)> Run(ServerDisconnectClosePolicy p, long from, long to,
|
||||||
|
bool disconnected = true, bool enabled = true, bool exiting = false, Func<long, bool>? dumpBusy = null)
|
||||||
|
{
|
||||||
|
var seen = new List<(long, V)>();
|
||||||
|
for (long t = from; t < to; t += 16)
|
||||||
|
{
|
||||||
|
V v = p.Update(t, disconnected, enabled, exiting, dumpBusy?.Invoke(t) ?? false);
|
||||||
|
if (v != V.None) seen.Add((t, v));
|
||||||
|
}
|
||||||
|
return seen;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void NothingOffTheScreen()
|
||||||
|
{
|
||||||
|
_case = nameof(NothingOffTheScreen);
|
||||||
|
var p = new ServerDisconnectClosePolicy();
|
||||||
|
Check(Run(p, 1000, 120_000, disconnected: false).Count == 0, "no verdicts in the world / at character select");
|
||||||
|
Check(!p.OnScreen, "not on the screen");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ClosesAfterTheDelay()
|
||||||
|
{
|
||||||
|
_case = nameof(ClosesAfterTheDelay);
|
||||||
|
var p = new ServerDisconnectClosePolicy();
|
||||||
|
Eq(p.Update(10_000, true, true, false, false), V.Detected, "first tick on the screen");
|
||||||
|
Check(p.OnScreen, "on the screen");
|
||||||
|
var seen = Run(p, 10_016, 15_100);
|
||||||
|
Check(seen.Count == 1 && seen[0].Verdict == V.Close, $"one Close in the first 5.1 s ({seen.Count} verdicts)");
|
||||||
|
Check(seen.Count == 1 && seen[0].At >= 15_000 && seen[0].At < 15_016, $"Close 5 s after the screen came (at {(seen.Count > 0 ? seen[0].At : -1)})");
|
||||||
|
Eq(p.Update(15_200, true, true, false, false), V.None, "no second Close right after");
|
||||||
|
Check(p.Attempts == 1, "one attempt");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WaitsForTheFlightDumpButNotForever()
|
||||||
|
{
|
||||||
|
_case = nameof(WaitsForTheFlightDumpButNotForever);
|
||||||
|
// Dump written from +3 s to +8 s: the close waits for it.
|
||||||
|
var p = new ServerDisconnectClosePolicy();
|
||||||
|
Eq(p.Update(0 + 100, true, true, false, true), V.Detected, "detected while the dump is scheduled");
|
||||||
|
var seen = Run(p, 116, 30_000, dumpBusy: t => t < 8_100);
|
||||||
|
Check(seen.Count >= 1 && seen[0].Verdict == V.Close && seen[0].At >= 8_100 && seen[0].At < 8_120, $"Close as soon as the dump is done (at {(seen.Count > 0 ? seen[0].At : -1)})");
|
||||||
|
|
||||||
|
// A dump that never finishes: the close waits at most DumpGraceMs more.
|
||||||
|
p = new ServerDisconnectClosePolicy();
|
||||||
|
p.Update(100, true, true, false, true);
|
||||||
|
seen = Run(p, 116, 30_000, dumpBusy: _ => true);
|
||||||
|
long expected = 100 + ServerDisconnectClosePolicy.DefaultDelayMs + ServerDisconnectClosePolicy.DumpGraceMs;
|
||||||
|
Check(seen.Count >= 1 && seen[0].Verdict == V.Close && seen[0].At >= expected && seen[0].At < expected + 16, $"Close at the 15 s cap (at {(seen.Count > 0 ? seen[0].At : -1)}, cap {expected})");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RetriesThenGivesUp()
|
||||||
|
{
|
||||||
|
_case = nameof(RetriesThenGivesUp);
|
||||||
|
var p = new ServerDisconnectClosePolicy();
|
||||||
|
p.Update(1, true, true, false, false);
|
||||||
|
var seen = Run(p, 17, 300_000);
|
||||||
|
Check(seen.Count == 3, $"Close, Retry, GiveUp and nothing more ({string.Join(", ", seen)})");
|
||||||
|
if (seen.Count != 3) return;
|
||||||
|
Eq(seen[0].Verdict, V.Close, "first");
|
||||||
|
Eq(seen[1].Verdict, V.Retry, "second");
|
||||||
|
Eq(seen[2].Verdict, V.GiveUp, "third");
|
||||||
|
long close = seen[0].At;
|
||||||
|
Check(seen[1].At - close >= ServerDisconnectClosePolicy.RetryAfterMs && seen[1].At - close < ServerDisconnectClosePolicy.RetryAfterMs + 16, "Retry 20 s after Close");
|
||||||
|
Check(seen[2].At - close >= ServerDisconnectClosePolicy.GiveUpAfterMs && seen[2].At - close < ServerDisconnectClosePolicy.GiveUpAfterMs + 16, "GiveUp 60 s after Close");
|
||||||
|
Check(p.Attempts == 2, "two close attempts");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SettingOffOnlyDetects()
|
||||||
|
{
|
||||||
|
_case = nameof(SettingOffOnlyDetects);
|
||||||
|
var p = new ServerDisconnectClosePolicy();
|
||||||
|
var seen = Run(p, 1, 600_000, enabled: false);
|
||||||
|
Check(seen.Count == 1 && seen[0].Verdict == V.Detected, $"only Detected with the setting off ({string.Join(", ", seen)})");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TurnedOnWhileOnTheScreen()
|
||||||
|
{
|
||||||
|
_case = nameof(TurnedOnWhileOnTheScreen);
|
||||||
|
var p = new ServerDisconnectClosePolicy();
|
||||||
|
Run(p, 1, 60_000, enabled: false);
|
||||||
|
Eq(p.Update(60_000, true, true, false, false), V.Close, "turning it on past the delay closes at once");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void NothingWhileExiting()
|
||||||
|
{
|
||||||
|
_case = nameof(NothingWhileExiting);
|
||||||
|
var p = new ServerDisconnectClosePolicy();
|
||||||
|
Check(Run(p, 1, 120_000, exiting: true).Count == 0, "no verdicts while the client is already closing");
|
||||||
|
|
||||||
|
// Quit Game clicked after the screen came, before the close: nothing more from us.
|
||||||
|
p = new ServerDisconnectClosePolicy();
|
||||||
|
p.Update(1, true, true, false, false);
|
||||||
|
Run(p, 17, 2_000);
|
||||||
|
Check(Run(p, 2_000, 120_000, exiting: true).Count == 0, "no Close once the client started exiting on its own");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void LeavingTheScreenStartsOver()
|
||||||
|
{
|
||||||
|
_case = nameof(LeavingTheScreenStartsOver);
|
||||||
|
var p = new ServerDisconnectClosePolicy();
|
||||||
|
p.Update(1, true, true, false, false);
|
||||||
|
Run(p, 17, 2_000);
|
||||||
|
Eq(p.Update(2_000, false, true, false, false), V.Left, "the screen went away before the close");
|
||||||
|
Check(!p.OnScreen && p.Attempts == 0, "reset");
|
||||||
|
Eq(p.Update(2_016, false, true, false, false), V.None, "Left only once");
|
||||||
|
Eq(p.Update(50_000, true, true, false, false), V.Detected, "a second visit is detected again");
|
||||||
|
var seen = Run(p, 50_016, 55_100);
|
||||||
|
Check(seen.Count == 1 && seen[0].Verdict == V.Close && seen[0].At >= 55_000, "and closes 5 s into the second visit");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ZeroClockStillCounts()
|
||||||
|
{
|
||||||
|
_case = nameof(ZeroClockStillCounts);
|
||||||
|
var p = new ServerDisconnectClosePolicy();
|
||||||
|
Eq(p.Update(0, true, true, false, false), V.Detected, "detected at clock 0");
|
||||||
|
Check(p.OnScreen, "a clock of 0 still marks the screen as seen");
|
||||||
|
var seen = Run(p, 16, 6_000);
|
||||||
|
Check(seen.Count == 1 && seen[0].Verdict == V.Close, "closes");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -50,6 +50,7 @@ namespace EngineSettingsTests
|
||||||
Run(nameof(SaveWithoutFileWritesOwnedKeys), SaveWithoutFileWritesOwnedKeys);
|
Run(nameof(SaveWithoutFileWritesOwnedKeys), SaveWithoutFileWritesOwnedKeys);
|
||||||
Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone);
|
Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone);
|
||||||
Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept);
|
Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept);
|
||||||
|
Run(nameof(CloseOnServerDisconnectDefaultOnAndSaved), CloseOnServerDisconnectDefaultOnAndSaved);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
|
|
@ -80,6 +81,8 @@ namespace EngineSettingsTests
|
||||||
case "hook-off": EngineSettings.SetUiHookEnabled(args[1], false); break;
|
case "hook-off": EngineSettings.SetUiHookEnabled(args[1], false); break;
|
||||||
case "add-plugin": EngineSettings.AddPluginPath(args[1]); break;
|
case "add-plugin": EngineSettings.AddPluginPath(args[1]); break;
|
||||||
case "imgui-off": EngineSettings.EnableImGuiBackend = false; break;
|
case "imgui-off": EngineSettings.EnableImGuiBackend = false; break;
|
||||||
|
case "dcclose-off": EngineSettings.CloseOnServerDisconnect = false; break;
|
||||||
|
case "dcclose-on": EngineSettings.CloseOnServerDisconnect = true; break;
|
||||||
case "dump":
|
case "dump":
|
||||||
Console.WriteLine("PluginPaths=" + string.Join("|", EngineSettings.PluginPaths));
|
Console.WriteLine("PluginPaths=" + string.Join("|", EngineSettings.PluginPaths));
|
||||||
Console.WriteLine("StartTooltip=" + EngineSettings.IsUiHookEnabled("StartTooltip"));
|
Console.WriteLine("StartTooltip=" + EngineSettings.IsUiHookEnabled("StartTooltip"));
|
||||||
|
|
@ -87,6 +90,7 @@ namespace EngineSettingsTests
|
||||||
Console.WriteLine("ImGuiBackend=" + EngineSettings.EnableImGuiBackend);
|
Console.WriteLine("ImGuiBackend=" + EngineSettings.EnableImGuiBackend);
|
||||||
Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream);
|
Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream);
|
||||||
Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads);
|
Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads);
|
||||||
|
Console.WriteLine("CloseOnServerDisconnect=" + EngineSettings.CloseOnServerDisconnect);
|
||||||
break;
|
break;
|
||||||
default: throw new ArgumentException(args[0]);
|
default: throw new ArgumentException(args[0]);
|
||||||
}
|
}
|
||||||
|
|
@ -289,6 +293,39 @@ namespace EngineSettingsTests
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// engine.json "CloseOnServerDisconnect" (close the client on AC's Disconnected screen):
|
||||||
|
// default on and not written while on; the Settings checkbox turning it off writes false,
|
||||||
|
// which a later start reads back; turning it on again drops it from the file; a value
|
||||||
|
// that isn't true/false is ignored.
|
||||||
|
private static void CloseOnServerDisconnectDefaultOnAndSaved()
|
||||||
|
{
|
||||||
|
string dir = NewDir("dcclose");
|
||||||
|
string path = Path.Combine(dir, "engine.json");
|
||||||
|
|
||||||
|
File.WriteAllText(path, LauncherFile);
|
||||||
|
Eq(DumpValue(RunChild(path, "dump").Out, "CloseOnServerDisconnect"), "True", "missing: on");
|
||||||
|
Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "save with the default");
|
||||||
|
Check(!ReadJson(path).TryGetProperty("CloseOnServerDisconnect", out _), "the default isn't written to the file");
|
||||||
|
|
||||||
|
var (exit, output) = RunChild(path, "dcclose-off");
|
||||||
|
Eq(exit, 0, "turn off (" + output.Trim() + ")");
|
||||||
|
Eq(ReadJson(path).GetProperty("CloseOnServerDisconnect").GetRawText(), "false", "off is saved");
|
||||||
|
Check(ReadJson(path).TryGetProperty("LauncherWindow", out _), "launcher keys kept");
|
||||||
|
Eq(DumpValue(RunChild(path, "dump").Out, "CloseOnServerDisconnect"), "False", "off read back at the next start");
|
||||||
|
Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, "another save");
|
||||||
|
Eq(ReadJson(path).GetProperty("CloseOnServerDisconnect").GetRawText(), "false", "off survives other saves");
|
||||||
|
|
||||||
|
Eq(RunChild(path, "dcclose-on").Exit, 0, "turn on");
|
||||||
|
Check(!ReadJson(path).TryGetProperty("CloseOnServerDisconnect", out _), "on again: dropped from the file");
|
||||||
|
Eq(DumpValue(RunChild(path, "dump").Out, "CloseOnServerDisconnect"), "True", "on read back");
|
||||||
|
|
||||||
|
foreach (string bad in new[] { "\"no\"", "0", "null" })
|
||||||
|
{
|
||||||
|
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"CloseOnServerDisconnect\": {bad}, \"LoggingLevel\""));
|
||||||
|
Eq(DumpValue(RunChild(path, "dump").Out, "CloseOnServerDisconnect"), "True", $"{bad}: ignored, on");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>The value of a "Name=value" line of the child's dump output ("" if none).</summary>
|
/// <summary>The value of a "Name=value" line of the child's dump output ("" if none).</summary>
|
||||||
private static string DumpValue(string output, string name)
|
private static string DumpValue(string output, string name)
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@
|
||||||
one .bak per session, placeholder rule, Add condition / action, finding a rule again by
|
one .bak per session, placeholder rule, Add condition / action, finding a rule again by
|
||||||
content), MetaLocation.cs ("Set current" text for landblock / landcell, against a copy of
|
content), MetaLocation.cs ("Set current" text for landblock / landcell, against a copy of
|
||||||
RynthAi's MetaManager reading; RynthSuite's RynthAiHostTests check the real one) and
|
RynthAi's MetaManager reading; RynthSuite's RynthAiHostTests check the real one) and
|
||||||
MetaRuleDto.cs. Nothing native: no AC, no ImGui, no files.
|
MetaRuleDto.cs, the rule list's text (MetaRowText.cs) and its timers (MetaStateClock.cs). Nothing native: no AC, no ImGui, no files.
|
||||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||||
-->
|
-->
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
|
|
@ -22,6 +22,8 @@
|
||||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaEditing.cs" Link="Engine\MetaEditing.cs" />
|
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaEditing.cs" Link="Engine\MetaEditing.cs" />
|
||||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaLocation.cs" Link="Engine\MetaLocation.cs" />
|
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaLocation.cs" Link="Engine\MetaLocation.cs" />
|
||||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaRuleDto.cs" Link="Engine\MetaRuleDto.cs" />
|
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaRuleDto.cs" Link="Engine\MetaRuleDto.cs" />
|
||||||
|
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaRowText.cs" Link="Engine\MetaRowText.cs" />
|
||||||
|
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaStateClock.cs" Link="Engine\MetaStateClock.cs" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,11 @@ internal static class Program
|
||||||
TakesData();
|
TakesData();
|
||||||
NoKillsMinutes();
|
NoKillsMinutes();
|
||||||
SameContentAndLocate();
|
SameContentAndLocate();
|
||||||
|
RuleNames();
|
||||||
|
StateClock();
|
||||||
|
RowTextLeaves();
|
||||||
|
RowTextLists();
|
||||||
|
RowTextActions();
|
||||||
|
|
||||||
Console.WriteLine();
|
Console.WriteLine();
|
||||||
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL: {_failed} of {_checks} checks");
|
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL: {_failed} of {_checks} checks");
|
||||||
|
|
@ -302,6 +307,168 @@ internal static class Program
|
||||||
|
|
||||||
// ── Checks ───────────────────────────────────────────────────────────
|
// ── Checks ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// ── Rule list text (MetaRowText) ─────────────────────────────────────
|
||||||
|
|
||||||
|
private static MetaRuleDto Cnd(int condition, string data = "", params MetaRuleDto[] kids)
|
||||||
|
{
|
||||||
|
var r = new MetaRuleDto { Condition = condition, ConditionData = data };
|
||||||
|
r.Children.AddRange(kids);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MetaRuleDto Act(int action, string data = "", params MetaRuleDto[] kids)
|
||||||
|
{
|
||||||
|
var r = new MetaRuleDto { Action = action, ActionData = data };
|
||||||
|
r.ActionChildren.AddRange(kids);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string CondLine(MetaRuleDto c, MetaTextContext? ctx = null) =>
|
||||||
|
MetaRowText.Plain(MetaRowText.ConditionCompact(c, ctx ?? new MetaTextContext()));
|
||||||
|
|
||||||
|
private static string ActLine(MetaRuleDto a, MetaTextContext? ctx = null) =>
|
||||||
|
MetaRowText.Plain(MetaRowText.ActionCompact(a, ctx ?? new MetaTextContext()));
|
||||||
|
|
||||||
|
private static string Lines(MetaLine[] lines)
|
||||||
|
{
|
||||||
|
var parts = new List<string>();
|
||||||
|
foreach (MetaLine l in lines)
|
||||||
|
parts.Add($"{l.Depth}{(l.Slot ? "s" : "")}:{l.Plain()}");
|
||||||
|
return string.Join(" | ", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RuleNames()
|
||||||
|
{
|
||||||
|
Case("rule names");
|
||||||
|
var a = new MetaRuleDto { State = "Hunt", Condition = 1, Action = 1, ActionData = "/x", Name = "Start" };
|
||||||
|
var b = a.Clone();
|
||||||
|
Eq(b.Name, "Start", "Clone keeps the name");
|
||||||
|
True(MetaRuleEdit.SameContent(a, b), "same name, same content");
|
||||||
|
b.Name = "Other";
|
||||||
|
False(MetaRuleEdit.SameContent(a, b), "a renamed rule is a different rule (Locate, delete confirm)");
|
||||||
|
|
||||||
|
var placeholder = MetaRuleEdit.Placeholder("Loot");
|
||||||
|
True(MetaRuleEdit.IsPlaceholder(placeholder), "an unnamed Never -> None is a placeholder");
|
||||||
|
placeholder.Name = "Parked";
|
||||||
|
False(MetaRuleEdit.IsPlaceholder(placeholder), "a named one isn't (delete asks first)");
|
||||||
|
|
||||||
|
Eq(MetaRuleEdit.CleanName("a\r\nb\tc"), "a b c", "one line");
|
||||||
|
Eq(MetaRuleEdit.CleanName(" keep the space "), " keep the space ", "ends kept while typing (trimmed when sent)");
|
||||||
|
Eq(MetaRuleEdit.CleanName(new string('x', 200)).Length, MetaRuleEdit.MaxNameLength, "cut to the longest name");
|
||||||
|
Eq(MetaRuleEdit.CleanName(null), "", "null");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void StateClock()
|
||||||
|
{
|
||||||
|
Case("seconds in state / watchdog clock");
|
||||||
|
var clock = new MetaStateClock();
|
||||||
|
False(clock.Known, "nothing before a snapshot");
|
||||||
|
Eq(clock.WatchdogLeft(0, out _), -1.0, "no watchdog before a snapshot");
|
||||||
|
clock.Snapshot(new MetaStateSnapshot { SecondsInState = 10, WatchdogActive = true, WatchdogState = "Default", WatchdogSecondsRemaining = 30 }, 1000);
|
||||||
|
True(clock.Known, "known");
|
||||||
|
Eq(clock.SecondsInState(1000), 10.0, "as snapshotted");
|
||||||
|
Eq(clock.SecondsInState(3500), 12.5, "counted on between snapshots");
|
||||||
|
Eq(clock.SecondsInState(500), 10.0, "a clock that went back doesn't count down");
|
||||||
|
Eq(clock.WatchdogLeft(3500, out string wdState), 27.5, "watchdog counts down");
|
||||||
|
Eq(wdState, "Default", "and says where it goes");
|
||||||
|
Eq(clock.WatchdogLeft(100_000, out _), 0.0, "never below 0");
|
||||||
|
clock.StateSet(4000);
|
||||||
|
Eq(clock.SecondsInState(4000), 0.0, "a state picked in the panel starts at 0");
|
||||||
|
Eq(clock.WatchdogLeft(4000, out _), -1.0, "...and drops the old state's watchdog");
|
||||||
|
clock.Snapshot(new MetaStateSnapshot { SecondsInState = 3 }, 5000);
|
||||||
|
Eq(clock.WatchdogLeft(5000, out _), -1.0, "no watchdog set");
|
||||||
|
clock.Snapshot(null, 6000);
|
||||||
|
False(clock.Known, "a RynthAi without the snapshot");
|
||||||
|
|
||||||
|
Eq(MetaStateClock.Format(42.9), "42 s", "whole seconds");
|
||||||
|
Eq(MetaStateClock.Format(3599), "3599 s", "seconds under an hour (rules count seconds)");
|
||||||
|
Eq(MetaStateClock.Format(3723), "1:02:03", "h:mm:ss from an hour");
|
||||||
|
Eq(MetaStateClock.Format(-5), "0 s", "never negative");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RowTextLeaves()
|
||||||
|
{
|
||||||
|
Case("row text: conditions");
|
||||||
|
Eq(CondLine(Cnd(10, "Prismatic Taper,50")), "Count Prismatic Taper ≤ 50", "item count <=");
|
||||||
|
Eq(CondLine(Cnd(11, "Prismatic Taper, 50")), "Count Prismatic Taper ≥ 50", "item count >=, spaces trimmed");
|
||||||
|
Eq(CondLine(Cnd(10, "Foo, Bar,3")), "Count Foo, Bar ≤ 3", "a comma in the item name: the count is after the last one");
|
||||||
|
Eq(CondLine(Cnd(16, "5c45")), "Landblock 5C45", "landblock upper-cased");
|
||||||
|
Eq(CondLine(Cnd(26, "getcharintprop[25]<30")), "Expr getcharintprop[25]<30", "expression");
|
||||||
|
Eq(CondLine(Cnd(4, "")), "Chat matches (not set)", "an empty pattern says so");
|
||||||
|
Eq(CondLine(Cnd(12, "Drudge|Mite{1,2},20,3")), "Mobs Drudge|Mite{1,2} ≥ 3 within 20", "mob name regex with a comma");
|
||||||
|
Eq(CondLine(Cnd(13, "1,20")), "Priority mobs ≥ 1 within 20", "priority mobs");
|
||||||
|
Eq(CondLine(Cnd(15, "")), "No mobs within 20 (default)", "no mobs: RynthAi's default distance");
|
||||||
|
Eq(CondLine(Cnd(24, "250")), "Burden ≥ 250%", "burden");
|
||||||
|
Eq(CondLine(Cnd(35, "2.5")), "No kill for 2.5 min", "no kills");
|
||||||
|
Eq(CondLine(Cnd(6, "10")), "In state ≥ 10 s", "seconds in state");
|
||||||
|
Eq(CondLine(Cnd(99, "x")), "Condition 99 x", "an unknown condition shows its number and data");
|
||||||
|
|
||||||
|
var ctx = new MetaTextContext { SpellName = id => id == 2293 ? "Strength Other VI" : null };
|
||||||
|
Eq(CondLine(Cnd(22, "2293,30"), ctx), "Spell Strength Other VI ≥ 30 s left", "spell by name");
|
||||||
|
False(ctx.MissedSpellName, "no name missed yet");
|
||||||
|
Eq(CondLine(Cnd(23, "512,305"), ctx), "Spell 512 ≤ 305 s left", "unknown spell: its id");
|
||||||
|
True(ctx.MissedSpellName, "a missed name is noted (rebuild once the spell table loads)");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RowTextLists()
|
||||||
|
{
|
||||||
|
Case("row text: all / any / not");
|
||||||
|
var ctx = new MetaTextContext();
|
||||||
|
MetaRuleDto one = Cnd(2, "", Cnd(16, "5C45"));
|
||||||
|
Eq(CondLine(one), "Landblock 5C45", "an All of one is that condition");
|
||||||
|
Eq(Lines(MetaRowText.ConditionLines(one, ctx)), "0:Landblock 5C45", "...on one line, no slot");
|
||||||
|
|
||||||
|
MetaRuleDto andNot = Cnd(2, "", Cnd(26, "a<1"), Cnd(20, "", Cnd(22, "512,305")));
|
||||||
|
Eq(CondLine(andNot), "Expr a<1 and not Spell 512 ≥ 305 s left", "compact: and, not");
|
||||||
|
Eq(Lines(MetaRowText.ConditionLines(andNot, ctx)), "0s:Expr a<1 | 0s:and not Spell 512 ≥ 305 s left",
|
||||||
|
"full: one line per condition, the second joined by and");
|
||||||
|
|
||||||
|
MetaRuleDto anyAll = Cnd(3, "", Cnd(1), Cnd(2, "", Cnd(8), Cnd(9)));
|
||||||
|
Eq(CondLine(anyAll), "Always or (Vendor open and Vendor closed)", "compact: nested list in brackets");
|
||||||
|
Eq(Lines(MetaRowText.ConditionLines(anyAll, ctx)),
|
||||||
|
"0s:Always | 0s:or all of | 1s:Vendor open | 1s:and Vendor closed", "full: nested list under an 'or all of' line");
|
||||||
|
|
||||||
|
MetaRuleDto notAll = Cnd(20, "", Cnd(2, "", Cnd(8), Cnd(9)));
|
||||||
|
Eq(CondLine(notAll), "not (Vendor open and Vendor closed)", "compact: not of a list");
|
||||||
|
Eq(Lines(MetaRowText.ConditionLines(notAll, ctx)), "0:not all of | 1s:Vendor open | 1s:and Vendor closed", "full: not all of");
|
||||||
|
|
||||||
|
Eq(CondLine(Cnd(3)), "any of (nothing)", "an empty Any says so");
|
||||||
|
Eq(CondLine(Cnd(20)), "not (nothing)", "an empty Not says so");
|
||||||
|
Eq(CondLine(Cnd(20, "", Cnd(20, "", Cnd(1)))), "not not Always", "not not");
|
||||||
|
|
||||||
|
MetaRuleDto deep = Cnd(1);
|
||||||
|
for (int i = 0; i < 20; i++) deep = Cnd(20, "", deep);
|
||||||
|
True(MetaRowText.ConditionLines(deep, ctx).Length == 1, "a very deep chain stops (no runaway recursion)");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RowTextActions()
|
||||||
|
{
|
||||||
|
Case("row text: actions");
|
||||||
|
var ctx = new MetaTextContext { States = new[] { "Default", "ReBuff" } };
|
||||||
|
Eq(ActLine(Act(1, "/vt opt set enablecombat true"), ctx), "/vt opt set enablecombat true", "a command reads as itself");
|
||||||
|
Eq(ActLine(Act(1, "hello"), ctx), "Chat hello", "plain chat text");
|
||||||
|
Eq(ActLine(Act(1, ""), ctx), "Chat (empty)", "an empty chat command says so");
|
||||||
|
Eq(ActLine(Act(2, "rebuff"), ctx), "→ rebuff", "set state (a state in any case exists)");
|
||||||
|
MetaSeg[] missing = MetaRowText.ActionLeaf(Act(2, "ReBuf"), ctx);
|
||||||
|
Eq(MetaRowText.Plain(missing), "→ ReBuf (no such state)", "set state to a missing state");
|
||||||
|
True(Array.Exists(missing, s => s.Tone == MetaTone.Warn), "...in the warning colour");
|
||||||
|
Eq(ActLine(Act(5, "ReBuff"), ctx), "Call → ReBuff", "call state");
|
||||||
|
Eq(ActLine(Act(9, "Default;5;30"), ctx), "Watchdog 5 m in 30 s → Default", "watchdog");
|
||||||
|
Eq(ActLine(Act(3, "Tusker_Abode;205"), ctx), "Nav Tusker_Abode", "embedded nav: the name before ';'");
|
||||||
|
Eq(ActLine(Act(3, "Patrol"), ctx), "Nav Patrol (dungeon patrol)", "Patrol: RynthAi's dungeon patrol");
|
||||||
|
var withPatrolRoute = new MetaTextContext { RouteExists = n => n.Equals("patrol", StringComparison.OrdinalIgnoreCase) };
|
||||||
|
Eq(ActLine(Act(3, "Patrol"), withPatrolRoute), "Nav Patrol", "...unless a route is called Patrol");
|
||||||
|
Eq(ActLine(Act(12, "EnableBuffing;False"), ctx), "Set EnableBuffing = False", "set option");
|
||||||
|
Eq(ActLine(Act(11, "doors;OpenDoors"), ctx), "Get option OpenDoors → doors", "get option (variable;option)");
|
||||||
|
Eq(ActLine(Act(0), ctx), "None", "none");
|
||||||
|
|
||||||
|
MetaRuleDto all = Act(4, "", Act(1, "/a"), Act(4, "", Act(2, "Default")), Act(6));
|
||||||
|
Eq(Lines(MetaRowText.ActionLines(all, ctx)), "0:/a | 0:→ Default | 0:Return from call", "DoAll: one line per action, nested DoAll flattened");
|
||||||
|
Eq(ActLine(all, ctx), "/a · → Default · Return from call", "compact: joined by a dot");
|
||||||
|
Eq(ActLine(Act(4), ctx), "do all (nothing)", "an empty DoAll says so");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
private static void Case(string name)
|
private static void Case(string name)
|
||||||
{
|
{
|
||||||
_case = name;
|
_case = name;
|
||||||
|
|
|
||||||
|
|
@ -52,6 +52,7 @@ internal static class Program
|
||||||
Run(nameof(GatePlanFromFiles), GatePlanFromFiles);
|
Run(nameof(GatePlanFromFiles), GatePlanFromFiles);
|
||||||
Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift);
|
Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift);
|
||||||
Run(nameof(TrainingStructsMirror), TrainingStructsMirror);
|
Run(nameof(TrainingStructsMirror), TrainingStructsMirror);
|
||||||
|
Run(nameof(ContainerOrderSlots), ContainerOrderSlots);
|
||||||
Run(nameof(ManifestAttributeDrivesRuntimeMinimum), ManifestAttributeDrivesRuntimeMinimum);
|
Run(nameof(ManifestAttributeDrivesRuntimeMinimum), ManifestAttributeDrivesRuntimeMinimum);
|
||||||
Run(nameof(DedupeSamePathTwice), DedupeSamePathTwice);
|
Run(nameof(DedupeSamePathTwice), DedupeSamePathTwice);
|
||||||
Run(nameof(DedupeCaseAndSlashes), DedupeCaseAndSlashes);
|
Run(nameof(DedupeCaseAndSlashes), DedupeCaseAndSlashes);
|
||||||
|
|
@ -473,13 +474,26 @@ internal static class Program
|
||||||
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.TrainingEntryNative>(f.Name), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.TrainingEntryNative>(f.Name), "TrainingEntryNative." + f.Name + " offset");
|
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.TrainingEntryNative>(f.Name), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.TrainingEntryNative>(f.Name), "TrainingEntryNative." + f.Name + " offset");
|
||||||
Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits");
|
Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits");
|
||||||
Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits");
|
Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits");
|
||||||
// The three v79 slots are the table's last three, in this order.
|
// The three v79 slots follow v78's and come right before v80's, in this order.
|
||||||
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).TakeLast(3).ToArray();
|
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(2).TakeLast(3).ToArray();
|
||||||
Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn" }), "v79 slots last: " + string.Join(",", names));
|
Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn" }), "v79 slots before v80's: " + string.Join(",", names));
|
||||||
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).TakeLast(3).ToArray();
|
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(2).TakeLast(3).ToArray();
|
||||||
Check(sdkNames.SequenceEqual(names), "SDK v79 slots in the same order");
|
Check(sdkNames.SequenceEqual(names), "SDK v79 slots in the same order");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// v80: GetContainerOrder and PutItemInContainer are the table's last two slots, engine and SDK alike,
|
||||||
|
// and the whole table has the same field names in the same order on both sides.
|
||||||
|
private static void ContainerOrderSlots()
|
||||||
|
{
|
||||||
|
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray();
|
||||||
|
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray();
|
||||||
|
Check(names.TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots last: " + string.Join(",", names.TakeLast(2)));
|
||||||
|
Check(sdkNames.TakeLast(2).SequenceEqual(names.TakeLast(2)), "SDK v80 slots in the same order");
|
||||||
|
Eq(Marshal.SizeOf<RynthCore.PluginSdk.RynthCoreApiNative>(), Marshal.SizeOf<RynthCore.Engine.Plugins.RynthCoreAPI>(), "SDK table size = engine table size");
|
||||||
|
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("PutItemInContainerFn"),
|
||||||
|
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("PutItemInContainerFn"), "PutItemInContainerFn offset");
|
||||||
|
}
|
||||||
|
|
||||||
private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { }
|
private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { }
|
||||||
private sealed class OverridingPlugin : RynthCore.PluginCore.RynthPluginBase { public override uint MinimumApiVersion => 70; }
|
private sealed class OverridingPlugin : RynthCore.PluginCore.RynthPluginBase { public override uint MinimumApiVersion => 70; }
|
||||||
|
|
||||||
|
|
|
||||||
24
tools/PreCastStopTests/PreCastStopTests.csproj
Normal file
24
tools/PreCastStopTests/PreCastStopTests.csproj
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Offline checks for the pre-cast stop (2026-10-12): src\RynthCore.Engine\Compatibility\
|
||||||
|
PreCastStopRules.cs, compiled in. While the player has control, a queued cast first sends
|
||||||
|
its stop and waits for the server's answer (or 750 ms), then casts without the stop that
|
||||||
|
FreeHandsAndCastSpell would otherwise send in the cast's frame. With the server in control
|
||||||
|
(or the state unreadable) the cast goes at once, as before. Pure code, nothing native.
|
||||||
|
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||||
|
-->
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<InvariantGlobalization>true</InvariantGlobalization>
|
||||||
|
<RootNamespace>PreCastStopTests</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\PreCastStopRules.cs" Link="Engine\PreCastStopRules.cs" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
43
tools/PreCastStopTests/Program.cs
Normal file
43
tools/PreCastStopTests/Program.cs
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
using RynthCore.Engine.Compatibility;
|
||||||
|
|
||||||
|
namespace PreCastStopTests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The pre-cast stop (PreCastStopRules.cs). Flight 63260: runs of projectile casts that never
|
||||||
|
/// landed each began with a stop burst in a cast's frame; FreeHandsAndCastSpell's own
|
||||||
|
/// MaybeStopCompletely is one of those stops whenever the player has control.
|
||||||
|
/// </summary>
|
||||||
|
internal static class Program
|
||||||
|
{
|
||||||
|
private static int _checks, _failed;
|
||||||
|
|
||||||
|
private static int Main()
|
||||||
|
{
|
||||||
|
// Server in control (after a cast's server turn): no stop would ride, cast at once.
|
||||||
|
Check(PreCastStopRules.Decide(1, false, 0, 0) == PreCastStep.CastNow, "server in control: cast now");
|
||||||
|
// Unknown state: as before.
|
||||||
|
Check(PreCastStopRules.Decide(-1, false, 0, 0) == PreCastStep.CastNow, "unreadable: cast now (old behavior)");
|
||||||
|
// Player in control: send the stop first, never the cast in the same tick.
|
||||||
|
Check(PreCastStopRules.Decide(0, false, 0, 0) == PreCastStep.SendStop, "player in control: the stop goes first");
|
||||||
|
// Stop sent: wait for the answer.
|
||||||
|
Check(PreCastStopRules.Decide(0, true, 0, 0) == PreCastStep.Wait, "stop sent, no answer: wait");
|
||||||
|
Check(PreCastStopRules.Decide(0, true, 0, PreCastStopRules.EchoMaxMs - 1) == PreCastStep.Wait, "still waiting 1 ms before the limit");
|
||||||
|
// Answered: cast without the cast's own stop.
|
||||||
|
Check(PreCastStopRules.Decide(0, true, 1, 120) == PreCastStep.CastWithoutStop, "answered: cast, no stop in its frame");
|
||||||
|
// Control state is not re-read once the stop is out (the answer may be a server motion).
|
||||||
|
Check(PreCastStopRules.Decide(1, true, 1, 120) == PreCastStep.CastWithoutStop, "answered, server took control meanwhile: still no stop");
|
||||||
|
// No answer in time: cast anyway (never park a cast), still without a second stop.
|
||||||
|
Check(PreCastStopRules.Decide(0, true, 0, PreCastStopRules.EchoMaxMs) == PreCastStep.CastWithoutStop, "no answer in 750 ms: cast anyway");
|
||||||
|
|
||||||
|
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
|
||||||
|
return _failed == 0 ? 0 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Check(bool ok, string what)
|
||||||
|
{
|
||||||
|
_checks++;
|
||||||
|
if (ok) return;
|
||||||
|
_failed++;
|
||||||
|
Console.WriteLine($"[FAIL] {what}");
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue