diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 8aba138..1544ef3 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -984,11 +984,46 @@ internal static class AcMainThreadQueue _castTargetId = targetId; _castSpellId = spellId; _castQueuedAt = NowMs; + _castStopWaitNoted = false; _castPending = 1; 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; + + /// Casts that waited one or more ticks for a stop queued ahead of them. + public static long CastStopWaitCount => Interlocked.Read(ref _castStopWaits); + + /// A movement stop (autorun off, a motion off, StopMovement, StopCompletely). + 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, + }; + + /// + /// True when the action ring holds a movement stop queued at or before . + /// 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. + /// + 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). // Re-invokes CombatActionHooks.CastSpell, which on the main thread executes the // cast directly (SelectItem + ClientMagicSystem::CastSpell via the SEH trampoline). @@ -1028,6 +1063,62 @@ internal static class AcMainThreadQueue 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; lock (_castLock) { @@ -1038,6 +1129,23 @@ internal static class AcMainThreadQueue } if (castAge > LateActionLogMs) 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; + + /// Casts whose stop the engine sent ahead of them. + public static long PreCastStopCount => Interlocked.Read(ref _preCastStops); + /// Of those, casts that went without seeing the server's answer (EchoMaxMs ran out). + public static long PreCastEchoTimeoutCount => Interlocked.Read(ref _preCastEchoTimeouts); + + /// An autonomous UpdateMotion for the player arrived (SmartBoxHooks, main thread). + public static void NotePlayerMotionEcho() => Interlocked.Increment(ref _playerMotionEchoes); } diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index a0fa357..b706fb1 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -928,6 +928,9 @@ internal static class ClientHelperHooks // refreshed every EndScene by EngineFrameController, 0 = no player / not ready. private static int _cachedPlayerId; + /// The player id last read on the main thread (0 = none yet); no native call. + public static uint CachedPlayerId => unchecked((uint)Volatile.Read(ref _cachedPlayerId)); + public static uint GetPlayerId() { if (_getPlayerId == null) diff --git a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs index dcd1c07..7755d56 100644 --- a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs @@ -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); + + /// + /// 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. + /// + internal static bool CastSpell(uint targetId, int spellId, bool suppressMoveStop) { if (spellId <= 0) return false; if (_castSpellClient == null) return false; @@ -543,7 +550,11 @@ internal static class CombatActionHooks // busy leak. BusyCountHooks reconciles the delta once the cast // gesture completes. 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); if (!okCast && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20) 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 // clears / 10h soak, nearly all on buffs). 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); if (!ok && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20) RynthLog.Compat($"[SEH] AV in self-CastSpell spell={spellId} — caught"); diff --git a/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs b/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs index 68b9b28..80aa85e 100644 --- a/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs @@ -25,6 +25,19 @@ internal static class CommandInterpreterHooks private const int TakeControlOffsetFromSetAutoRun = ReferenceCommandInterpreterTakeControlFromServer - 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). // Primary resolution; the *Offset deltas below remain as fallback only. private static readonly byte?[] SetMotionPattern = [ 0x8B, 0x41, 0x08, 0x81, 0xEC, 0x0C, 0x01, 0x00 ]; @@ -61,6 +74,9 @@ internal static class CommandInterpreterHooks [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void ClearAllCommandsDelegate(IntPtr thisPtr); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void SendMovementEventDelegate(IntPtr thisPtr); + private static IntPtr _smartboxStaticAddr; private static IntPtr _boundCmdInterp; private static bool _absResolved; @@ -74,8 +90,15 @@ internal static class CommandInterpreterHooks private static PlayerTeleportedDelegate? _playerTeleported; private static TakeControlFromServerDelegate? _takeControlFromServer; private static ClearAllCommandsDelegate? _clearAllCommands; + private static SendMovementEventDelegate? _sendMovementEvent; + private static bool _sendMovementEventMissLogged; + private static long _autoRunMovementSends; private static string _statusMessage = "Not probed yet."; + /// MoveToStates sent after an autorun change (diagnostics). + 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 HasTapJump => _commenceJump != null && _doJump != null; public static bool HasSetAutoRun => _setAutoRun != null; @@ -152,9 +175,39 @@ internal static class CommandInterpreterHooks 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); + 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)) - 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; } 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; + + /// 1 the server has control (a cast sends no stop), 0 the player has (a cast sends one), -1 unknown. Main thread. + public static int ReadControlledByServer() + { + if (!MainThreadGuard.IsOnMainThread() || !TryBindDelegates()) return -1; + try { return Marshal.ReadInt32(_boundCmdInterp + CmdInterpControlledByServerOffset) != 0 ? 1 : 0; } + catch { return -1; } + } + + /// + /// 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 , or Zero when nothing was changed. + /// + 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 { } + } + + /// AC's autorun flag (0/1), or -1 when it can't be read. + 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) { if (!MainThreadGuard.IsOnMainThread()) @@ -461,6 +563,21 @@ internal static class CommandInterpreterHooks _takeControlFromServer = Marshal.GetDelegateForFunctionPointer(takeControlPtr); _clearAllCommands = Marshal.GetDelegateForFunctionPointer(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(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; _boundCmdInterp = cmdInterp; IsInitialized = true; @@ -496,6 +613,7 @@ internal static class CommandInterpreterHooks _playerTeleported = null; _takeControlFromServer = null; _clearAllCommands = null; + _sendMovementEvent = null; IsInitialized = false; _statusMessage = "Not probed yet."; } diff --git a/src/RynthCore.Engine/Compatibility/GameTickHooks.cs b/src/RynthCore.Engine/Compatibility/GameTickHooks.cs index a0ab5ce..c3c78f9 100644 --- a/src/RynthCore.Engine/Compatibility/GameTickHooks.cs +++ b/src/RynthCore.Engine/Compatibility/GameTickHooks.cs @@ -59,6 +59,9 @@ internal static class GameTickHooks public static bool IsInstalled => Volatile.Read(ref _installed) != 0; + /// Client::UseTime returned 0: AC's game loop is exiting (any exit path). + public static bool GameLoopExiting => Volatile.Read(ref _exitLatch) != 0; + public static void Initialize() { 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. try { Net.FlightRecorder.MainTick(); } 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. return result; diff --git a/src/RynthCore.Engine/Compatibility/PreCastStopRules.cs b/src/RynthCore.Engine/Compatibility/PreCastStopRules.cs new file mode 100644 index 0000000..a035c10 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/PreCastStopRules.cs @@ -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 +{ + /// Cast now, as before (no stop would ride with it, or the state can't be read). + CastNow, + /// Send the pre-cast stop now; don't cast this tick. + SendStop, + /// The stop went out; wait for the server's answer. + Wait, + /// The stop was answered (or the wait ran out): cast, without the cast's own stop. + CastWithoutStop, +} + +internal static class PreCastStopRules +{ + /// The longest a cast waits for the server's answer to its stop. + public const long EchoMaxMs = 750; + + /// 1 server has control, 0 the player has, -1 unknown. + /// The pre-cast stop for this cast already went out. + /// Player UpdateMotions counted since the stop went out. + /// Milliseconds since the stop went out. + 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; + } +} diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 02b4020..7e517d4 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -77,6 +77,7 @@ namespace RynthCore.Engine.Compatibility; /// the last minutes of client/server messages and engine markers) to /// Logs\flight-<pid>-<time>.txt; /rc flightdump auto <reason> is the rate-limited /// automatic form. /rc flight [status|mark <text>|on|off|auto on|off]. +/// /rc quit / /rc exit - closes the client cleanly, as its close button does. /// /rc report [text] - "Report a problem" (): alone it /// opens the panel; with text it sends that report now, with the recent log attached /// (the panel is where the log can be left out). One report a minute. @@ -254,6 +255,15 @@ internal static class RynthCoreChatCommands 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) if (IsVerb(sub, "report", out string reportArgs)) { diff --git a/src/RynthCore.Engine/Compatibility/ServerDisconnectClose.cs b/src/RynthCore.Engine/Compatibility/ServerDisconnectClose.cs new file mode 100644 index 0000000..3785944 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ServerDisconnectClose.cs @@ -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; + + /// AC's main thread, every game tick (GameTickHooks, after the queue drain). + 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 ""; } + } + + /// + /// 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. + /// + 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})")}."); + } +} diff --git a/src/RynthCore.Engine/Compatibility/ServerDisconnectClosePolicy.cs b/src/RynthCore.Engine/Compatibility/ServerDisconnectClosePolicy.cs new file mode 100644 index 0000000..bb1d51b --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ServerDisconnectClosePolicy.cs @@ -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; + + /// On the Disconnected screen (as of the last Update). + public bool OnScreen => _sinceMs != 0; + + /// Milliseconds on the screen as of , 0 when not on it. + 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; + } +} diff --git a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs index afa46b3..85fe442 100644 --- a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs @@ -131,6 +131,8 @@ internal static class SmartBoxHooks try { + if (info.Opcode == PositionUpdateOpcode && info.RawObjectId != 0) + NotePlayerMotionEcho(blob, info); TryQueueHealthUpdate(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) { if (info.Opcode != 0x01C0 || info.BlobSize < 12 || blob == IntPtr.Zero) diff --git a/src/RynthCore.Engine/ImGui/ImGuiBar.cs b/src/RynthCore.Engine/ImGui/ImGuiBar.cs index e8bf5fa..f28e8fe 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiBar.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiBar.cs @@ -5,7 +5,9 @@ // 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 // 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 // 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 @@ -48,8 +50,10 @@ internal static class ImGuiBar private static readonly PanelFace[] Faces = { PanelFace.Avalonia, PanelFace.ImGui, PanelFace.Both }; 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, - bool ImGuiOnly = false); + bool ImGuiOnly = false, ScriptWindow? Window = null); // Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button. private static readonly string[] ImGuiOnlyBarPanels = @@ -84,6 +88,10 @@ internal static class ImGuiBar ["Log"] = PhosphorIcons.TerminalWindow, ["Item Count"] = PhosphorIcons.Bag, ["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, }; /// A panel's bar icon: its Phosphor icon, else its first letter (letter = true). @@ -111,6 +119,10 @@ internal static class ImGuiBar } 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 bool _placed; private static Vector2 _pos, _persistedPos; @@ -366,8 +378,11 @@ internal static class ImGuiBar { ImGuiNET.ImGui.SameLine(); 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 (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) 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 window exists. They never get buttons of their own (EnsureButtons - // lists OverlayHost's engine panels only; script windows are dynamic entries). + // script window exists. A window that also sets BarButton (plugin windows such as + // RynthSort's) has a button of its own instead (EnsureButtons) and isn't listed here. ScriptBarItem[] scripts = ScriptWindowRegistry.BarItems; if (scripts.Length > 0) { @@ -591,9 +606,27 @@ internal static class ImGuiBar ImGuiNET.ImGui.PopStyleVar(3); } + /// Bit i set: ImGuiOnlyBarPanels[i] has a face now. + 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; + } + + /// + /// 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). + /// 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(); foreach (var (title, _) in OverlayHost.GetPanels()) if (!LauncherOnly.Contains(title)) @@ -608,6 +641,17 @@ internal static class ImGuiBar string icon = IconFor(title, out bool letter); 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(); _tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar face and size. Ctrl+wheel over the bar: size."; } diff --git a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs index c75324c..2f09d46 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs @@ -65,6 +65,7 @@ internal static unsafe class ImGuiFonts // dashes are in MainRanges. private static readonly ushort[] SymbolCodepoints = { + 0x2264, 0x2265, // ≤ ≥ (Meta rule list: "Prismatic Taper ≤ 50") 0x25CF, // ● (Meta source: unapplied edits) }; diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index fe15706..4ddd41d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -17,7 +17,11 @@ // 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 // 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 // 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 _h = new(512); private readonly List _lay = new(512); 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 long _seenLinesVersion = -1, _seenRoutes = -1, _lastId; 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 // sliding away. 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; // 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). private readonly Dictionary _seenId = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary _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 bool _openSettings, _openNewTab, _focusNewTab, _openTabMenu, _openLineMenu, _openRename; /// A line colour changed and isn't saved yet (saved once the picker is let go). private bool _coloursDirty; + /// The Chat history slider's value while it's held (0: not held). + private int _historyEdit; private string? _ctxTab, _renameFrom; private ChatLine? _ctxLine; private string _ctxPattern = ""; @@ -129,7 +146,7 @@ internal sealed class ChatFace : IImGuiPanel _stick = true; _seenRoutes = -1; // full rebuild on the first frame _seenId.Clear(); // every tab starts read - _unreadLines = -1; + _unreadLines = _unreadRoutes = -1; // a full recount } public void OnHidden() @@ -351,22 +368,30 @@ internal sealed class ChatFace : IImGuiPanel long newest = lines.Length > 0 ? lines[^1].Id : 0; _seenId[current] = newest; long routes = ChatModel.RoutesVersion, tabsVersion = ChatModel.FiltersVersion; - if (linesVersion == _unreadLines && routes == _unreadRoutes && tabsVersion == _unreadTabsVersion - && string.Equals(current, _unreadTab, StringComparison.Ordinal)) return; + bool recount = routes != _unreadRoutes || tabsVersion != _unreadTabsVersion + || !string.Equals(current, _unreadTab, StringComparison.Ordinal); + if (!recount && linesVersion == _unreadLines) return; _unreadLines = linesVersion; _unreadRoutes = routes; _unreadTabsVersion = tabsVersion; _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()) { 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; 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 (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) @@ -399,9 +424,9 @@ internal sealed class ChatFace : IImGuiPanel _h.Clear(); _lay.Clear(); 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; - _heightsFrom = 0; + _heightsFrom = _measuredFrom = _vis.Count; // all unmeasured: MeasureLines, newest first _topsDirty = true; ClearSelection(); _stick = true; // a rebuild re-pins to the newest line @@ -423,6 +448,7 @@ internal sealed class ChatFace : IImGuiPanel _h.RemoveRange(0, drop); _lay.RemoveRange(0, 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(); } _topsDirty = true; } @@ -433,7 +459,7 @@ internal sealed class ChatFace : IImGuiPanel if (!ChatModel.LineVisible(line, tab, search)) continue; if (_heightsFrom > _vis.Count) _heightsFrom = _vis.Count; _vis.Add(line); - _h.Add(0); + _h.Add(_rowH); _lay.Add(null); _topsDirty = true; } @@ -444,81 +470,85 @@ internal sealed class ChatFace : IImGuiPanel 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; ImFontPtr font = ImGuiFonts.Chat(fontSize); ImGuiNET.ImGui.PushFont(font); 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; + 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); - 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; - float total = _tops[n]; // Following the tail until the user scrolls away from it. float scrollY = ImGuiNET.ImGui.GetScrollY(), maxY = ImGuiNET.ImGui.GetScrollMaxY(); 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. // 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) @@ -555,8 +585,6 @@ internal sealed class ChatFace : IImGuiPanel HandleLineMenu(basePos, wrapW, n); _lastScrollY = scrollY; - if (ChatModel.AutoScroll && _stick && !_selDragging && total > viewH) - ImGuiNET.ImGui.SetScrollHereY(1f); // "Copied N lines" / "Rule added", top-right, for a moment. if (_flash != null) @@ -574,8 +602,93 @@ internal sealed class ChatFace : IImGuiPanel } } - ImGuiNET.ImGui.PopFont(); ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopFont(); // pushed before the child, for MeasureLines + } + + /// Time MeasureLines may spend a frame catching up on lines measured for another width. + private const double MeasureBudgetMs = 2.0; + private static readonly long MeasureBudgetTicks = (long)(System.Diagnostics.Stopwatch.Frequency * MeasureBudgetMs / 1000); + + /// + /// 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). + /// + 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) @@ -871,6 +984,18 @@ internal sealed class ChatFace : IImGuiPanel if (ImGuiNET.ImGui.SliderInt("Background", ref pct, 0, 100, "%d%%")) ChatModel.BackgroundAlpha = (int)MathF.Round(pct * 2.55f); 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(); bool ts = ChatModel.ShowTimestamps; diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs index c6b0648..19e4110 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs @@ -87,6 +87,8 @@ internal sealed class DamageFace : IImGuiPanel private sealed class RowText { public string Wcid = "", Tier = "", Crit = "", NonCrit = "", Casts = "", Kills = ""; + /// The name as shown: "Rampager (2 kinds)" for a row of several wcids. + public string NameShown = "", NameTip = ""; public string Weapon = "", Offhand = "", Pet = "", WeakTop = "", Sec = "", SecTip = ""; public bool CritSet, NonCritSet, WeaponGold, OffhandGold, PetGold; public string[] TierLines = Array.Empty(); @@ -250,7 +252,8 @@ internal sealed class DamageFace : IImGuiPanel if (_filterWid != 0 && r.Wid != _filterWid) continue; if (_searchText.Length > 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; } _shown.Add(r); @@ -306,6 +309,20 @@ internal sealed class DamageFace : IImGuiPanel } BuildPrio(r.Name, t); 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.CritSet = r.CritN > 0; 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."); - 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))) 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); HpCell(r, p); diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs index cfa8195..432164a 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs @@ -2,7 +2,9 @@ // RynthCore.Engine - ImGui/Panels/ItemsFace.cs // ImGui face of the Items panel (UI/Panels/ItemsPanel.cs): weapons (name, // 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, // 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]; 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(); if (r == 1) { @@ -94,7 +96,7 @@ internal sealed class ItemsFace : IImGuiPanel { ItemsPanel.ConsumableEntry c = _data.Consumables[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(); if (r == 1) { @@ -200,16 +202,38 @@ internal sealed class ItemsFace : IImGuiPanel ImGuiNET.ImGui.Dummy(new Vector2(w, 22)); } - /// Name | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, else 0. - private static int Row(string name, string value, int index, float w) + private const string MissingSuffix = " (missing)"; + + /// + /// Name | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, else 0. + /// : the item isn't carried any more (amber, a warning icon, + /// "(missing)" and a tooltip saying what to do). + /// + private static int Row(string name, string value, int index, float w, bool missing) { Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); var dl = ImGuiNET.ImGui.GetWindowDrawList(); dl.AddRectFilled(p, p + new Vector2(w, 24), index % 2 == 0 ? RowAlt : PanelBg); float nameW = w - 146; + float ty = p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f; 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(); + 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; 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; diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs index a7115c7..547c199 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs @@ -4,6 +4,7 @@ // // [<- Back] Edit rule Saved // State: [Combat v] +// Name: [Optional: a name to find this rule by ] // +- Conditions ------ [+ Add] -+ +- Actions --------- [+ Add] -+ // | [Landblock == v] | | [Chat Command v] | // | [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 // 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 // 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 @@ -68,6 +76,11 @@ internal sealed partial class MetaFace private string? _nameProblem; 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 AddLabel = PhosphorIcons.Plus + " Add"; private const string SetCurrentLabel = PhosphorIcons.MapPin + " Set current"; @@ -86,6 +99,7 @@ internal sealed partial class MetaFace _lastSaved = index >= 0 ? rule.Clone() : null; _autosave.Clear(); _fields.Clear(); + _ruleNameShown = null; _editConfirmDelete = false; _editTyping = false; CancelNaming(); @@ -136,6 +150,7 @@ internal sealed partial class MetaFace } if (!_autosave.Take()) return; MetaRuleDto send = _editRule.Clone(); + send.Name = send.Name.Trim(); // the box keeps a space you just typed; the rule doesn't if (_editIndex < 0) { _editIndex = _data.Rules.Count; // add_rule appends @@ -163,7 +178,6 @@ internal sealed partial class MetaFace { SendEdit(new MetaCmd { Op = "delete_rule", Index = index }); _data.Rules.RemoveAt(index); - _expanded.Clear(); RebuildCaches(); } } @@ -195,7 +209,7 @@ internal sealed partial class MetaFace float indW = SaveIndicatorWidth(editor: true); ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); 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); 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(); @@ -203,7 +217,7 @@ internal sealed partial class MetaFace // State: [picker] 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:"); string? state = StatePicker("##ed_state", r.State, _statePicks, IndexOf(_statePicks, r.State), 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 _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 const float footerH = 24; @@ -279,44 +298,191 @@ internal sealed partial class MetaFace private void ConditionsBody(MetaRuleDto r, float w) { - int picked = FlowPicker("##ed_cond", MetaVocabulary.ConditionName(r.Condition), MetaVocabulary.ConditionNames, r.Condition, w); - if (picked >= 0 && picked != r.Condition) + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + BeginBacks(dl); + try { - SetCondition(r, picked); - _editChanged = true; + // An All / Any / Not is a box around its picker and everything in it. + 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); - return; + EndBacks(dl); } - 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) { - int picked = FlowPicker("##ed_act", MetaVocabulary.ActionName(r.Action), MetaVocabulary.ActionNames, r.Action, w); - if (picked >= 0 && picked != r.Action) + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + BeginBacks(dl); + try { - r.Action = picked; - if (!MetaVocabulary.IsAllAction(picked)) r.ActionChildren.Clear(); + bool card = MetaVocabulary.IsAllAction(r.Action); // a DoAll is a box around its actions + 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(); + } + + /// Starts a box at the cursor when (its contents indented); returns its top-left. + 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; + } + + /// Ends a box opened at , wide, and records it. + 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)); + } + + /// A group's colour: All (and DoAll) teal, Any amber, Not rose. + private static uint GroupColor(int kind, bool action) => action ? Teal : kind switch + { + MetaRuleEdit.Any => Amber, + MetaRuleEdit.Not => Rose, + _ => Teal, + }; + + /// A group box's fill: its colour, faint, over the column. + private static uint GroupTint(int kind, bool action) => action ? C(0xFF10262E) : kind switch + { + MetaRuleEdit.Any => C(0xFF2A2412), + MetaRuleEdit.Not => C(0xFF2C1622), + _ => C(0xFF10262E), + }; + + /// What a nested group's line says after its picker. + 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(); + } + + /// The rule's name: optional, one line; saves like every other change. + 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; } - 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) @@ -385,15 +551,21 @@ internal sealed partial class MetaFace } 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, - Array.IndexOf(_routePicks, a.ActionData), p, width, height); - if (picked >= 0 && _routePicks[picked] != a.ActionData) + int sel = IndexOf(_routeValues, a.ActionData); + string shown = a.ActionData.Length == 0 ? "Select route..." : sel >= 0 ? _routeLabels[sel] : 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; } + // (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) 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 - // one); DoAll's sub-actions are a flat list. Each row: [type][value][x]; in a narrow column the - // value goes on a second line. The top level's "+ Add" is in the column header. + // one); DoAll's sub-actions are a flat list that runs in order, so each is numbered and has up / + // 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 subs, bool action, int depth, int maxCount, float w) { string[] names = action ? MetaVocabulary.ActionNames : MetaVocabulary.ConditionNames; 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++) { MetaRuleDto sub = subs[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(); - 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; 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 (action) sub.Action = picked; else SetCondition(sub, picked); _editChanged = true; } - bool nests = !action && MetaVocabulary.IsCompositeCondition(sub.Condition) && depth < MetaVocabulary.MaxSubConditionDepth; - 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" : "Remove this condition"); + bool removed = IconButton("##rm", PhosphorIcons.X, new Vector2(p.X + rw - 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"); + 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; if (nests) { 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 { - Vector2 vp = narrow ? new Vector2(p.X + 12, p.Y + rh + 2) : new Vector2(p.X + pickW + 4, p.Y); - float vw = narrow ? w - 12 : w - pickW - 4 - xw - 4; + 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 ? rw - lead - 12 : rw - lead - pickW - 4 - tools - 4; ImGuiNET.ImGui.SetCursorScreenPos(vp); if (action) ActionField("##data", sub, vw, rh, problemLine: false); else ConditionField("##data", sub, vw, rh); 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)); if (!removed && nests) { - ImGuiNET.ImGui.Indent(14); - SmallLabel(sub.Condition switch { MetaRuleEdit.Not => "Not:", MetaRuleEdit.All => "All of:", _ => "Any of:" }); - SubRules(sub.Children, action: false, depth + 1, sub.Condition == MetaRuleEdit.Not ? 1 : int.MaxValue, w - 14); - ImGuiNET.ImGui.Unindent(14); + ImGuiNET.ImGui.Indent(childIndent); + if (sub.Children.Count == 0) Note("None yet: + Add below."); + SubRules(sub.Children, action: false, depth + 1, sub.Condition == MetaRuleEdit.Not ? 1 : int.MaxValue, rw - childIndent); + ImGuiNET.ImGui.Unindent(childIndent); } + CardClose(nests, cardTop, w, GroupColor(sub.Condition, false), GroupTint(sub.Condition, false), depth + 1); ImGuiNET.ImGui.PopID(); if (removed) { @@ -466,6 +667,12 @@ internal sealed partial class MetaFace _editChanged = true; 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. @@ -539,12 +746,12 @@ internal sealed partial class MetaFace /// ( true) once its name box is confirmed; else null. /// 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; uint key = ImGuiNET.ImGui.GetID(id); 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) { _namingKey = key; @@ -650,12 +857,6 @@ internal sealed partial class MetaFace 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) { @@ -664,8 +865,9 @@ internal sealed partial class MetaFace 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); } } diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs new file mode 100644 index 0000000..f42ba75 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs @@ -0,0 +1,1069 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/MetaFace.List.cs +// The Meta panel's rule list (readability pass, 2026-10-11): +// +// [file v][refresh][Save As] Saved +// [Visual][Source][Schedule] | [x Meta][x Debug] +// [Filter rules... ][Collapse rules][collapse states] +// Condition | Action +// v Hunting 7 rules current +// [x] 1 Always | None +// ---------------------------------------------------------------- +// v [x] 2 Landblock 5C45 | /vt opt set enablecombat true +// | Nav Tusker_Abode +// ---------------------------------------------------------------- +// > [x] 3 Expr getcharintprop[25]<30 and not Spell 512 >= 305... | -> ReBuff +// State: [Hunting v][target][+ New Rule] +// +// - A rule shows all of itself: every condition of an All / Any (joined by +// "and" / "or", nested lists indented under "and any of"), every action of +// a DoAll, one per line; words, values, states and problems in their own +// colours (MetaRowText). +// - Rules fold: a rule of more than one line has a caret in its gutter that +// folds it to one line (conditions joined by and / or, actions by " · "; +// hovering shows all of it). A state's right-click menu folds or opens its +// rules; "Collapse rules" / "Expand rules" in the toolbar does every rule. +// A rule's fold follows its content (state + text), so it keeps through +// snapshots and moves; editing a rule shows it as the toolbar has rules. +// - Lines between rules and down the Condition | Action split (drag it in +// the header); every other rule a different shade. The fold caret, the +// enable box and the rule's number (its place in the state: rules are +// checked in order) sit in a narrow gutter. +// - Move up / down, duplicate and delete appear on the row under the mouse +// (delete takes a second click), and on right-click with Edit and Enable. +// Click a rule to edit it; drag it to move it within its state (a teal +// line shows where it lands; the list scrolls at its edges; Esc cancels). +// A drop is the same move_up / move_down commands the arrows send. +// - A named rule (MetaRuleDto.Name, set in the editor) shows its name in +// bold on a line of its own over its condition and actions; folded, the +// name stands in for the condition. Unnamed rules show as before. +// - The current state's header is marked with how long the meta has been in +// it ("current · 42 s", RynthAi's seconds in state, counted on between +// snapshots) and, while one is set, the Watchdog's countdown; the state +// picker shows the seconds too. The target button scrolls to the state. +// A current state with no rules gets a note (the meta can't do anything). +// - The filter matches the rules' text and state names; moving rules waits +// until it is cleared (a hidden neighbour would make a move look like +// nothing happened). +// - Only rows on screen are drawn, so a meta of hundreds of rules scrolls +// as cheaply as a small one. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.ImGuiBackend.Hud; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class MetaFace +{ + // ── Rule text colours (MetaTone) and list lines ────────────────────── + private static readonly uint ToneLabel = C(0xFF8FA9C2), ToneCode = C(0xFF9CC8FF), ToneJoin = C(0xFF4FC3CF), + RowLine = C(0x7034587A), ColLine = C(0x5834587A), GuideLine = C(0x6034587A), CurrentHdr = C(0xFF0D2B36), + // Every other rule a clearly different shade (Tom, 2026-10-11: the old pair was hard to tell apart). + StripeA = C(0xFF121B25), StripeB = C(0xFF1C2B3A); + + private static uint ToneColor(MetaTone tone) => tone switch + { + MetaTone.Label => ToneLabel, + MetaTone.State => Amber, + MetaTone.Code => ToneCode, + MetaTone.Join => ToneJoin, + MetaTone.Dim => Faded(Mute), + MetaTone.Warn => Red, + _ => TextDim, + }; + + // ── Per-rule text, rebuilt with the snapshot (RebuildListText) ─────── + private MetaLine[][] _condLines = Array.Empty(), _actLines = Array.Empty(); + private MetaSeg[][] _condCompact = Array.Empty(), _actCompact = Array.Empty(); + private string[] _searchText = Array.Empty(); + private bool _spellNamesPending; // a spell showed as a number while the spell table loads + + // ── List state ─────────────────────────────────────────────────────── + // Folded rules: _compact is the toolbar's choice for every rule (saved per PC); _ruleFlip holds the + // rules folded the other way (a rule's caret, a state's menu), by _ruleKey (state + text). + private bool _compact = RynthCore.Engine.UI.PanelColumnStore.Get("Meta.compact", 0f) > 0.5f; + private readonly HashSet _ruleFlip = new(); + private string[] _ruleKey = Array.Empty(); + private int[] _fullLines = Array.Empty(); // a rule's lines unfolded (its name's line included) + private readonly byte[] _filterBuf = new byte[128]; + private string _filter = string.Empty; // lower case, trimmed + private bool[] _filterHit = Array.Empty(); + private string? _scrollToState; // the target button: scroll to this state's header + private int _ctxRule = -1; // right-clicked rule (its menu) + + // Dragging a rule within its state: the rule (index) and its place when picked up, the gap it + // would land in (0..count), and this frame's rows of that state (place, top, bottom on screen). + private int _dragIndex = -1, _dragFromGi, _dragGap = -1, _dragStartFrame; + private string _dragState = string.Empty; + private bool _dragSwallowClick; // the release that ends a drag isn't a click (no editor) + private readonly List<(int Gi, float Top, float Bottom)> _dragSlots = new(); + private string? _ctxState; // right-clicked state header (its menu) + private bool _openRuleMenu, _openStateMenu; + + // Layout of the frame's rows (LayoutRows), and the list's inner width last frame (less its + // scrollbar), which the column header above the list lines up with. + private float _lineH, _slotW, _gutterW, _numW, _listInnerW; + private const float RowPad = 3; + + private void RebuildListText(List rules) + { + var ctx = new MetaTextContext + { + SpellName = id => PortalSpellTable.TryGetName(id, out string n) ? n : null, + States = _statesOnly, + RouteExists = name => MetaVocabulary.HasRoute(_data, name), + }; + int n = rules.Count; + _condLines = new MetaLine[n][]; + _actLines = new MetaLine[n][]; + _condCompact = new MetaSeg[n][]; + _actCompact = new MetaSeg[n][]; + _searchText = new string[n]; + _ruleKey = new string[n]; + _fullLines = new int[n]; + for (int i = 0; i < n; i++) + { + MetaRuleDto r = rules[i]; + _condLines[i] = MetaRowText.ConditionLines(r, ctx); + _actLines[i] = MetaRowText.ActionLines(r, ctx); + _condCompact[i] = MetaRowText.ConditionCompact(r, ctx); + _actCompact[i] = MetaRowText.ActionCompact(r, ctx); + _searchText[i] = (r.Name + "\n" + MetaRowText.Plain(_condCompact[i]) + "\n" + MetaRowText.Plain(_actCompact[i])).ToLowerInvariant(); + _ruleKey[i] = r.State + "\u0001" + _searchText[i]; + _fullLines[i] = Math.Max(1, Math.Max(_condLines[i].Length, _actLines[i].Length)) + (r.Name.Length > 0 ? 1 : 0); + } + // Names appear once the client's spell table has been read (in the background). + _spellNamesPending = ctx.MissedSpellName && !PortalSpellTable.Ready; + if (_spellNamesPending) PortalSpellTable.EnsureLoadQueued(); + RefilterRules(); + } + + private void RefilterRules() + { + List rules = _data.Rules; + if (_filterHit.Length != rules.Count) _filterHit = new bool[rules.Count]; + for (int i = 0; i < rules.Count && i < _searchText.Length; i++) + _filterHit[i] = _filter.Length == 0 + || _searchText[i].Contains(_filter, StringComparison.Ordinal) + || rules[i].State.Contains(_filter, StringComparison.OrdinalIgnoreCase); + } + + private bool IsCurrent(string state) => string.Equals(state, _data.CurrentState, StringComparison.OrdinalIgnoreCase); + + // ── Folded rules ───────────────────────────────────────────────────── + + /// A rule of more than one line can fold to one. + private bool Folds(int i) => i >= 0 && i < _fullLines.Length && _fullLines[i] > 1; + + private bool IsFolded(int i) => Folds(i) && (_compact ^ _ruleFlip.Contains(_ruleKey[i])); + + private void SetFolded(int i, bool folded) + { + if (!Folds(i)) return; + if (folded == _compact) _ruleFlip.Remove(_ruleKey[i]); + else _ruleFlip.Add(_ruleKey[i]); + } + + /// The toolbar: every rule folded or every rule open. + private void SetAllFolded(bool folded) + { + _compact = folded; + _ruleFlip.Clear(); + RynthCore.Engine.UI.PanelColumnStore.Set("Meta.compact", folded ? 1f : 0f); + } + + private bool AnyRuleOpen() + { + for (int i = 0; i < _fullLines.Length; i++) + if (Folds(i) && !IsFolded(i)) return true; + return false; + } + + private void SetStateFolded(string state, bool folded) + { + foreach ((string s, List members) in _groups) + if (string.Equals(s, state, StringComparison.Ordinal)) + foreach (int i in members) SetFolded(i, folded); + } + + // ===================================================================== + // List view + // ===================================================================== + + private void ListView(Vector2 origin, Vector2 size) + { + if (_spellNamesPending && PortalSpellTable.Ready) RebuildCaches(); + float w = size.X; + LoadSaveBar(w); + Separator(w); + ModeRow(w, source: false); + Separator(w); + FilterRow(w); + + // A note over the list: the editor closed under a meta switch, or the meta can't do anything. + string note = string.Empty; + if (_listNote.Length > 0 && NowMs - _listNoteAt < 8000) note = _listNote; + else if (_data.Rules.Count > 0 && !HasRulesIn(_data.CurrentState)) + note = $"The current state, {_data.CurrentState}, has no rules: the meta does nothing until something changes the state."; + if (note.Length > 0) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.TextUnformatted(note); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopFont(); + } + + // The Condition | Action header stays put above the scrolling list. + LayoutRows(); + if (_groups.Count > 0) ColumnHeader(w, TextWidth(_listInnerW > 0 ? _listInnerW : w)); + + 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); + RuleMenus(); + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(); + + Separator(w); + BottomBar(w); + } + + private bool HasRulesIn(string state) + { + foreach ((string s, List _) in _groups) + if (string.Equals(s, state, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + // [Filter rules... x][Compact][collapse / expand all] + private void FilterRow(float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + bool anyRuleOpen = AnyRuleOpen(); + string compactLabel = (anyRuleOpen ? "Collapse rules" : "Expand rules") + "##meta_compact"; + float compactW = Math.Max(ImGuiNET.ImGui.CalcTextSize("Collapse rules").X, ImGuiNET.ImGui.CalcTextSize("Expand rules").X) + 16; + const float iconW = 26; + float boxW = Math.Max(60, w - compactW - iconW - 8); + + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.SetNextItemAllowOverlap(); // the clear button sits inside the box + if (TextBox("##meta_filter", _filterBuf, boxW, PhosphorIcons.MagnifyingGlass + " Filter rules...", + ImGuiInputTextFlags.EscapeClearsAll, out _)) + SetFilter(Utf8(_filterBuf)); + if (_filter.Length > 0) + { + if (GlyphButton("##filter_x", PhosphorIcons.X, new Vector2(p.X + boxW - 20, p.Y + 2), new Vector2(18, 18), Mute, TextDim)) + { + Array.Clear(_filterBuf); + SetFilter(string.Empty); + } + ImGuiNET.ImGui.SetItemTooltip("Clear the filter (Esc in the box)"); + } + + float x = p.X + boxW + 4; + float toggleX = x; + if (Toggle(compactLabel, ref x, p.Y, !anyRuleOpen)) SetAllFolded(anyRuleOpen); + x = toggleX + compactW + 4; // the button keeps one width whichever label it shows + ImGuiNET.ImGui.SetItemTooltip(anyRuleOpen + ? "Fold every rule to one line (hover one to see all of it; its caret opens it again)." + : "Show every rule in full: each condition and action on its own line."); + + bool anyOpen = false; + foreach ((string s, List _) in _groups) anyOpen |= !_collapsed.Contains(s); + if (IconButton("##collapse_all", anyOpen ? PhosphorIcons.ArrowsInLineVertical : PhosphorIcons.ArrowsOutLineVertical, + new Vector2(x, p.Y), new Vector2(iconW, 22), TextDim, BtnFill, BtnBord, font: UiFont.Ui14)) + { + if (anyOpen) foreach ((string s, List _) in _groups) _collapsed.Add(s); + else _collapsed.Clear(); + } + ImGuiNET.ImGui.SetItemTooltip(anyOpen ? "Collapse every state" : "Expand every state"); + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + } + + private void SetFilter(string text) + { + _filter = text.Trim().ToLowerInvariant(); + RefilterRules(); + } + + // ===================================================================== + // Rules + // ===================================================================== + + 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; + } + + List rules = _data.Rules; + bool filtering = _filter.Length > 0; + _dragSlots.Clear(); + // While a rule is dragged, nothing else in the list highlights or shows its tools. + bool listHot = ImGuiNET.ImGui.IsWindowHovered() && _dragIndex < 0; + _listInnerW = w; + float textW = TextWidth(w); + + bool first = true; + int shown = 0; + for (int g = 0; g < _groups.Count; g++) + { + (string state, List members) = _groups[g]; + int hits = members.Count; + if (filtering) + { + hits = 0; + foreach (int i in members) if (i < _filterHit.Length && _filterHit[i]) hits++; + if (hits == 0) continue; + } + if (_scrollToState != null && string.Equals(_scrollToState, state, StringComparison.OrdinalIgnoreCase)) + _collapsed.Remove(state); + bool collapsed = !filtering && _collapsed.Contains(state); + + if (!first) ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + first = false; + StateHeader(g, state, members.Count, hits, filtering, collapsed, w, listHot); + if (collapsed) continue; + + int stripe = 0; // counts the rows shown, so a filter never puts two of a shade together + for (int gi = 0; gi < members.Count; gi++) + { + int index = members[gi]; + if (index >= rules.Count) break; + if (filtering && !(index < _filterHit.Length && _filterHit[index])) continue; + shown++; + if (RuleRow(rules[index], index, gi, members.Count, stripe++ % 2 == 1, w, textW, listHot, filtering)) return; // the list changed: redraw next frame + } + } + _scrollToState = null; // its header wasn't drawn (filtered out): don't jump there later + DragUpdate(); + if (filtering && shown == 0 && first) + { + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGuiNET.ImGui.TextUnformatted($" No rule or state matches \"{Utf8(_filterBuf).Trim()}\"."); + ImGuiNET.ImGui.PopStyleColor(); + } + ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); + } + + /// This frame's row layout: line height, the and / or slot, the gutter (enable box + rule number). + private void LayoutRows() + { + _lineH = ImGuiNET.ImGui.GetTextLineHeight() + 2; + _slotW = ImGuiNET.ImGui.CalcTextSize("and ").X + 2; + int most = 1; + foreach ((string _, List m) in _groups) most = Math.Max(most, m.Count); + _numW = ImGuiNET.ImGui.CalcTextSize(most >= 100 ? "999" : most >= 10 ? "99" : "9").X; + _gutterW = 36 + _numW + 6; // fold caret, enable box, number + } + + /// The condition + action text width of a row wide. + private float TextWidth(float rowW) => Math.Max(40, rowW - _gutterW - 4); + + // Condition | Action, over the text columns; drag the line between them (saved per PC). + private void ColumnHeader(float w, float textW) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + Vector2 hp = ImGuiNET.ImGui.GetCursorScreenPos(); + const float hh = 18; + float tx = hp.X + _gutterW; + float split = textW * _condFrac; + float hy = hp.Y + (hh - bold.FontSize) * 0.5f; + dl.AddText(bold, bold.FontSize, new Vector2(tx + 4, hy), Mute, "Condition"); + dl.AddText(bold, bold.FontSize, new Vector2(tx + split + 6, hy), Mute, "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 / textW, 0.15f, 0.85f); + ImGuiNET.ImGui.Dummy(new Vector2(w, hh)); + dl.AddLine(new Vector2(hp.X, hp.Y + hh - 0.5f), new Vector2(hp.X + w, hp.Y + hh - 0.5f), BtnBord); + } + + /// A state's header band: caret, name, rule count; "current" when it is the meta's state; + /// red while one of its rules fires. Click folds it; right-click for its menu; + adds a rule. + private void StateHeader(int g, string state, int count, int hits, bool filtering, bool collapsed, float w, bool listHot) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + bool current = IsCurrent(state); + bool firing = _groupFiring[g]; + float hh = bold.FontSize + 9; + Vector2 hp = ImGuiNET.ImGui.GetCursorScreenPos(); + if (_scrollToState != null && string.Equals(_scrollToState, state, StringComparison.OrdinalIgnoreCase)) + { + ImGuiNET.ImGui.SetScrollHereY(0f); + _scrollToState = null; + } + + ImGuiNET.ImGui.PushID(-1 - g); // rows use their rule index + ImGuiNET.ImGui.SetNextItemAllowOverlap(); + if (ImGuiNET.ImGui.InvisibleButton("##hdr", new Vector2(w, hh)) && !filtering) + { + if (collapsed) _collapsed.Remove(state); else _collapsed.Add(state); + } + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) + { + _ctxState = state; + _openStateMenu = true; + } + bool hot = listHot && ImGuiNET.ImGui.IsMouseHoveringRect(hp, hp + new Vector2(w, hh)); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + + uint bg = current ? CurrentHdr : StateHdrA; + dl.AddRectFilled(hp, hp + new Vector2(w, hh), hot ? Lighten(bg) : bg, 3); + if (current) dl.AddRectFilled(hp, hp + new Vector2(3, hh), Teal, 1); + uint nameColor = firing ? Red : Amber; + float ty = hp.Y + (hh - bold.FontSize) * 0.5f; + dl.AddText(bold, bold.FontSize, new Vector2(hp.X + 7, ty), Faded(nameColor), + collapsed ? PhosphorIcons.CaretRight : PhosphorIcons.CaretDown); + float nx = hp.X + 22; + dl.AddText(bold, bold.FontSize, new Vector2(nx, ty), nameColor, state); + nx += bold.CalcTextSizeA(bold.FontSize, float.MaxValue, 0, state).X + 8; + string countText = filtering ? $"{hits} of {count}" : count == 1 ? "1 rule" : $"{count} rules"; + if (firing) countText += " • firing"; + float fy = hp.Y + (hh - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + dl.AddText(new Vector2(nx, fy), firing ? Red : Faded(Mute), countText); + + // Right: [watchdog] [current · 42 s] [+] + float rx = hp.X + w - 4; + if (hot) + { + const float pw = 20; + rx -= pw; + if (GlyphButton("##add", PhosphorIcons.Plus, new Vector2(rx, hp.Y + (hh - 18) * 0.5f), new Vector2(pw, 18), Green, Lighten(Green))) + OpenEditor(-1, new MetaRuleDto { State = state, Action = 1 }); + ImGuiNET.ImGui.SetItemTooltip($"New rule in {state}"); + rx -= 4; + } + if (current) + { + string tag = _stateClock.Known ? "current \u00B7 " + MetaStateClock.Format(_stateClock.SecondsInState(NowMs)) : "current"; + ImFontPtr small = ImGuiFonts.Get(UiFont.Ui9); + Vector2 ts = small.CalcTextSizeA(small.FontSize, float.MaxValue, 0, tag); + Vector2 a = new(rx - ts.X - 10, hp.Y + (hh - ts.Y - 4) * 0.5f), b = new(rx, a.Y + ts.Y + 4); + dl.AddRectFilled(a, b, BtnOn, 8); + dl.AddRect(a, b, Teal, 8); + dl.AddText(small, small.FontSize, new Vector2(a.X + 5, a.Y + 2), Teal, tag); + if (_stateClock.Known && ImGuiNET.ImGui.IsMouseHoveringRect(a, b)) + ImGuiNET.ImGui.SetTooltip("The meta's current state, and how long it has been in it (what \"In state >= N s\" rules count)."); + rx = a.X - 6; + + // The Watchdog, while one is set: it sends the meta to its state when the time runs out + // (unless you've moved far enough). + double wd = _stateClock.WatchdogLeft(NowMs, out string wdState); + if (wd >= 0) + { + string wtag = PhosphorIcons.Hourglass + " " + MetaStateClock.Format(wd) + (wdState.Length > 0 ? " \u2192 " + wdState : ""); + Vector2 ws = small.CalcTextSizeA(small.FontSize, float.MaxValue, 0, wtag); + Vector2 wa = new(rx - ws.X - 10, a.Y), wb = new(rx, b.Y); + if (wa.X > nx + ImGuiNET.ImGui.CalcTextSize(countText).X + 8) // only when it doesn't cover the count + { + dl.AddRectFilled(wa, wb, C(0xFF2A2210), 8); + dl.AddRect(wa, wb, Amber, 8); + dl.AddText(small, small.FontSize, new Vector2(wa.X + 5, wa.Y + 2), Amber, wtag); + if (ImGuiNET.ImGui.IsMouseHoveringRect(wa, wb)) + ImGuiNET.ImGui.SetTooltip("Watchdog: unless you move far enough, the meta goes to " + + (wdState.Length > 0 ? wdState.Replace("%", "%%") : "its state") + " when this runs out."); + } + } + } + ImGuiNET.ImGui.PopID(); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(hp.X, hp.Y + hh)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + } + + /// One rule. True when a click changed the list (the caller stops drawing this frame). + private bool RuleRow(MetaRuleDto rule, int index, int gi, int groupCount, bool odd, float w, float textW, bool listHot, bool filtering) + { + bool named = rule.Name.Length > 0; + bool folded = IsFolded(index); + int lineCount = folded ? 1 : index < _fullLines.Length ? _fullLines[index] : 1; // unfolded: the name has a line of its own + float h = RowPad * 2 + lineCount * _lineH; + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (_dragIndex >= 0 && string.Equals(rule.State, _dragState, StringComparison.Ordinal)) + _dragSlots.Add((gi, p.Y, p.Y + h)); // on screen or not: the drop gap needs every row of the state + bool dragged = _dragIndex == index; + bool arming = _confirmDeleteIndex == index && _confirmDelete != null && NowMs < _confirmDeleteUntil + && MetaRuleEdit.SameContent(_confirmDelete, rule); + if (!arming && !ImGuiNET.ImGui.IsRectVisible(p, p + new Vector2(w, h))) + { + ImGuiNET.ImGui.Dummy(new Vector2(w, h)); // off screen: keep its space, draw nothing + return false; + } + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + bool firing = rule.LastFiredMs < 1500; + bool hot = listHot && ImGuiNET.ImGui.IsMouseHoveringRect(p, p + new Vector2(w, h)); + uint bg = firing ? Fired : odd ? StripeB : StripeA; + if (hot) bg = Lighten(bg); + dl.AddRectFilled(p, p + new Vector2(w, h), bg); + if (firing) dl.AddRectFilled(p, p + new Vector2(3, h), Red); + + ImGuiNET.ImGui.PushID(index); + bool changed = false; + + // The whole row: click edits, right-click opens its menu. The buttons below sit on top of it. + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.SetNextItemAllowOverlap(); + bool edit = ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h)); + bool rowTip = ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip) && _dragIndex < 0; + // Pressed and pulled a few pixels: a drag (moves stay off while filtering, like the arrows). + if (_dragIndex < 0 && !filtering && ImGuiNET.ImGui.IsItemActive() && ImGuiNET.ImGui.IsMouseDragging(ImGuiMouseButton.Left, 6f)) + { + _dragIndex = index; + _dragState = rule.State; + _dragFromGi = gi; + _dragGap = gi; + _dragSwallowClick = true; + _dragStartFrame = ImGuiNET.ImGui.GetFrameCount(); // rows above it weren't recorded this frame + dragged = true; + } + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) + { + _ctxRule = index; + _openRuleMenu = true; + } + + // Gutter: the fold caret (rules of more than one line), the enable box, the rule's place in its state. + float firstLineY = p.Y + RowPad; + float textY = firstLineY + (_lineH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + bool caretHot = false; + if (Folds(index)) + { + if (GlyphButton("##fold", folded ? PhosphorIcons.CaretRight : PhosphorIcons.CaretDown, + new Vector2(p.X + 2, firstLineY + (_lineH - 16) * 0.5f), new Vector2(14, 16), Faded(TextDim), Teal)) + SetFolded(index, !folded); + caretHot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.SetItemTooltip(folded ? "Show all of this rule" : "Fold this rule to one line"); + } + if (GlyphButton("##en", rule.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square, + new Vector2(p.X + 16, firstLineY + (_lineH - 16) * 0.5f), new Vector2(16, 16), rule.Enabled ? Green : Mute, TextDim)) + { + 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"); + if ((hot && !filtering) || dragged) // on hover the number becomes a grip: the row drags + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.DotsSixVertical, + new Vector2(p.X + 34, firstLineY), new Vector2(_numW + 4, _lineH), dragged ? Teal : Mute); + else + { + string num = (gi + 1).ToString(System.Globalization.CultureInfo.InvariantCulture); + float numX = p.X + 36 + _numW - ImGuiNET.ImGui.CalcTextSize(num).X; + dl.AddText(new Vector2(numX, textY), Faded(Mute), num); + } + + // Name (its own line), condition | action text, and the line between them. + float tx = p.X + _gutterW; + float split = tx + textW * _condFrac; + bool fade = !rule.Enabled || dragged; + bool cut = false; + float condX = tx + 4, condMax = split - 6, actX = split + 6, actMax = p.X + w - 6; + float bodyY = textY; + if (named && !folded) + { + cut |= DrawName(dl, condX, firstLineY, actMax, rule.Name, fade); + bodyY += _lineH; + } + float lineTop = named && !folded ? p.Y + RowPad + _lineH : p.Y; + dl.AddLine(new Vector2(split, lineTop), new Vector2(split, p.Y + h), ColLine); + if (folded) + { + if (named) cut |= DrawName(dl, condX, firstLineY, condMax, rule.Name, fade); + else if (index < _condCompact.Length) cut |= DrawSegs(dl, condX, textY, condMax, _condCompact[index], fade); + if (index < _actCompact.Length) cut |= DrawSegs(dl, actX, textY, actMax, _actCompact[index], fade); + } + else + { + if (index < _condLines.Length) + for (int i = 0; i < _condLines[index].Length; i++) + cut |= DrawLine(dl, condX, bodyY + i * _lineH, condMax, _condLines[index][i], fade); + if (index < _actLines.Length) + for (int i = 0; i < _actLines[index].Length; i++) + cut |= DrawLine(dl, actX, bodyY + i * _lineH, actMax, _actLines[index][i], fade); + } + + // Row tools on the row under the mouse (and while delete waits for its second click). + bool toolHot = false; + if (hot || arming) + { + const float bs = 18, gap = 2; + float delW = arming ? BtnW("Delete?", 50) : bs; + float toolsW = bs * 3 + gap * 3 + delW; + float bx = p.X + w - 4 - toolsW; + float by = p.Y + Math.Max(1, RowPad + (_lineH - bs) * 0.5f); + dl.AddRectFilled(new Vector2(bx - 4, by - 1), new Vector2(p.X + w - 1, by + bs + 1), bg, 3); + bool canMove = !filtering; + if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(bx, by), new Vector2(bs, bs), Mute, BtnFill, BtnBord, enabled: canMove && gi > 0)) + changed |= Move(index, -1); + toolHot |= ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.SetItemTooltip(canMove ? "Move up" : "Clear the filter to move rules"); + bx += bs + gap; + if (IconButton("##dn", PhosphorIcons.ArrowDown, new Vector2(bx, by), new Vector2(bs, bs), Mute, BtnFill, BtnBord, + enabled: canMove && gi < groupCount - 1)) + changed |= Move(index, +1); + toolHot |= ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.SetItemTooltip(canMove ? "Move down" : "Clear the filter to move rules"); + bx += bs + gap; + if (IconButton("##dup", PhosphorIcons.Copy, new Vector2(bx, by), new Vector2(bs, bs), Mute, BtnFill, BtnBord)) + changed |= Duplicate(index, rule); + toolHot |= ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.SetItemTooltip("Duplicate rule"); + bx += bs + gap; + if (arming + ? Button("Delete?##del", new Vector2(bx, by), new Vector2(delW, bs), TextDim, DelFill, Red) + : IconButton("##del", PhosphorIcons.Trash, new Vector2(bx, by), new Vector2(bs, bs), TextDim, DelFill, BtnBord)) + { + // A rule with anything in it takes a second click within 3 s; an empty Never -> None one goes at once. + if (arming || MetaRuleEdit.IsPlaceholder(rule)) changed |= Delete(index); + else + { + _confirmDelete = rule.Clone(); + _confirmDeleteIndex = index; + _confirmDeleteUntil = NowMs + 3000; + } + } + toolHot |= ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.SetItemTooltip(arming ? "Click again to delete this rule" : "Delete rule"); + } + + dl.AddLine(new Vector2(p.X, p.Y + h - 0.5f), new Vector2(p.X + w, p.Y + h - 0.5f), RowLine); + if (dragged) dl.AddRect(p + new Vector2(1, 1), p + new Vector2(w - 1, h - 1), Teal, 2f, ImDrawFlags.None, 1.5f); + ImGuiNET.ImGui.PopID(); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); + + if (changed) + { + RebuildCaches(); + return true; + } + if (rowTip && !toolHot && !caretHot && (folded || cut)) RuleTooltip(rule, index, gi); + if (edit && !_dragSwallowClick) OpenEditor(index, rule); + return false; + } + + /// A rule's name in bold on the line at , cut with "…" at maxX. + /// True when it didn't fit. + private static bool DrawName(ImDrawListPtr dl, float x, float lineY, float maxX, string name, bool fade) + { + ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11); + float y = lineY + (ImGuiNET.ImGui.GetTextLineHeight() + 2 - bold.FontSize) * 0.5f; + uint col = fade ? Faded(TextDim) : TextDim; + float room = maxX - x; + if (room <= 10) return true; + if (bold.CalcTextSizeA(bold.FontSize, float.MaxValue, 0, name).X <= room) + { + dl.AddText(bold, bold.FontSize, new Vector2(x, y), col, name); + return false; + } + // Too long: the longest start that fits with "…" (names are short; only cut rows on screen get here). + int lo = 0, hi = name.Length - 1; + while (lo < hi) + { + int mid = (lo + hi + 1) / 2; + if (bold.CalcTextSizeA(bold.FontSize, float.MaxValue, 0, name.Substring(0, mid) + "…").X <= room) lo = mid; else hi = mid - 1; + } + dl.AddText(bold, bold.FontSize, new Vector2(x, y), col, name.Substring(0, lo) + "…"); + return true; + } + + /// Segments from x, cut with "…" at maxX. True when something didn't fit. + private bool DrawSegs(ImDrawListPtr dl, float x, float y, float maxX, MetaSeg[] segs, bool fade) + { + foreach (MetaSeg s in segs) + { + if (s.Text.Length == 0) continue; + uint col = ToneColor(s.Tone); + if (fade) col = Faded(col); + float tw = ImGuiNET.ImGui.CalcTextSize(s.Text).X; + if (x + tw > maxX) + { + if (maxX - x > 10) dl.AddText(new Vector2(x, y), col, Fit(s.Text, maxX - x)); + return true; + } + dl.AddText(new Vector2(x, y), col, s.Text); + x += tw; + } + return false; + } + + /// One full-form line: guides for its nesting, its and / or slot, its text. + private bool DrawLine(ImDrawListPtr dl, float colX, float y, float maxX, MetaLine line, bool fade) + { + for (int k = 0; k < line.Depth; k++) + { + float gx = colX + k * _slotW + 4; + dl.AddLine(new Vector2(gx, y - 1), new Vector2(gx, y + _lineH - 1), GuideLine); + } + float x = colX + line.Depth * _slotW; + if (line.Slot) + { + if (line.Join.Length > 0) + { + float jw = ImGuiNET.ImGui.CalcTextSize(line.Join).X; + dl.AddText(new Vector2(x + _slotW - 4 - jw, y), fade ? Faded(ToneJoin) : ToneJoin, line.Join); + } + x += _slotW; + } + return DrawSegs(dl, x, y, maxX, line.Segs, fade); + } + + /// All of a rule (it didn't fit, or the list is compact), as the full form draws it. + private void RuleTooltip(MetaRuleDto rule, int index, int gi) + { + if (!ImGuiNET.ImGui.BeginTooltip()) return; + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 1)); + if (rule.Name.Length > 0) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); + Colored(rule.Name, TextDim); + ImGuiNET.ImGui.PopFont(); + } + Colored($"{rule.State} · rule {gi + 1}{(rule.Enabled ? "" : " · disabled")}", Faded(Mute)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 3)); + Colored("If", Amber); + if (index < _condLines.Length) foreach (MetaLine l in _condLines[index]) TipLine(l); + ImGuiNET.ImGui.Dummy(new Vector2(0, 3)); + Colored("Do", Amber); + if (index < _actLines.Length) foreach (MetaLine l in _actLines[index]) TipLine(l); + ImGuiNET.ImGui.Dummy(new Vector2(0, 3)); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + Colored("Click to edit; drag to move; right-click for more.", Faded(Mute)); + ImGuiNET.ImGui.PopFont(); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.EndTooltip(); + } + + private void TipLine(MetaLine l) + { + float x0 = ImGuiNET.ImGui.GetCursorPosX() + 12 + l.Depth * _slotW; + if (l.Slot) + { + if (l.Join.Length > 0) + { + ImGuiNET.ImGui.SetCursorPosX(x0 + _slotW - 4 - ImGuiNET.ImGui.CalcTextSize(l.Join).X); + Colored(l.Join, ToneJoin); + ImGuiNET.ImGui.SameLine(0, 0); + } + ImGuiNET.ImGui.SetCursorPosX(x0 + _slotW); + } + else ImGuiNET.ImGui.SetCursorPosX(x0); + for (int i = 0; i < l.Segs.Length; i++) + { + if (i > 0) ImGuiNET.ImGui.SameLine(0, 0); + Colored(l.Segs[i].Text, ToneColor(l.Segs[i].Tone)); + } + if (l.Segs.Length == 0) ImGuiNET.ImGui.NewLine(); + } + + /// Unformatted text in a colour (rule text may hold '%'). + private static void Colored(string text, uint color) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color); + ImGuiNET.ImGui.TextUnformatted(text); + ImGuiNET.ImGui.PopStyleColor(); + } + + // ===================================================================== + // Dragging a rule + // ===================================================================== + + /// + /// After the rows are drawn: the gap under the mouse among the dragged rule's state, the teal + /// line there, a label by the mouse, scrolling at the list's edges; on release the move. + /// + private void DragUpdate() + { + if (_dragIndex < 0) + { + if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) _dragSwallowClick = false; + return; + } + if (ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Escape) || _dragIndex >= _data.Rules.Count || _filter.Length > 0) + { + _dragIndex = -1; // cancelled: the release still isn't a click + return; + } + ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.ResizeNS); + if (ImGuiNET.ImGui.GetFrameCount() == _dragStartFrame) return; // its state's rows are all in from next frame + float my = ImGuiNET.ImGui.GetIO().MousePos.Y; + int count = _dragSlots.Count; + if (count > 0) + { + int gap = count; + for (int k = 0; k < count; k++) + if (my < (_dragSlots[k].Top + _dragSlots[k].Bottom) * 0.5f) { gap = k; break; } + _dragGap = gap; + } + int to = _dragGap > _dragFromGi ? _dragGap - 1 : _dragGap; // its place once taken out of the list + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 wp = ImGuiNET.ImGui.GetWindowPos(); + float ww = ImGuiNET.ImGui.GetWindowWidth(); + if (count > 0 && to != _dragFromGi) + { + float y = _dragGap < count ? _dragSlots[_dragGap].Top : _dragSlots[count - 1].Bottom; + dl.AddLine(new Vector2(wp.X + 2, y), new Vector2(wp.X + ww - 2, y), Teal, 2.5f); + dl.AddCircleFilled(new Vector2(wp.X + 6, y), 4f, Teal); + } + + MetaRuleDto rule = _data.Rules[_dragIndex]; + if (ImGuiNET.ImGui.BeginTooltip()) + { + string what = rule.Name.Length > 0 ? rule.Name + : _dragIndex < _condCompact.Length ? MetaRowText.Plain(_condCompact[_dragIndex]) : "Rule"; + Colored(Fit(what, 320), TextDim); + Colored(count == 0 || to == _dragFromGi ? $"Drop to leave it at {_dragFromGi + 1}" + : $"Move to {to + 1} of {count} in {_dragState}", to == _dragFromGi ? Mute : Teal); + ImGuiNET.ImGui.EndTooltip(); + } + + // Near the top or bottom of the list: scroll, faster the closer to the edge. + float top = wp.Y, bottom = wp.Y + ImGuiNET.ImGui.GetWindowHeight(); + const float edge = 28; + if (my < top + edge) + ImGuiNET.ImGui.SetScrollY(Math.Max(0, ImGuiNET.ImGui.GetScrollY() - (top + edge - my) * 0.4f)); + else if (my > bottom - edge) + ImGuiNET.ImGui.SetScrollY(Math.Min(ImGuiNET.ImGui.GetScrollMaxY(), ImGuiNET.ImGui.GetScrollY() + (my - (bottom - edge)) * 0.4f)); + + if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) + { + int from = _dragIndex; + _dragIndex = -1; + _dragSwallowClick = false; // the rows have had this frame's release + if (count > 0 && to != _dragFromGi) MoveBy(from, to - _dragFromGi); + } + } + + /// Moves a rule places within its state (move_up / move_down, + /// one swap each, as the arrows do). + private void MoveBy(int index, int steps) + { + int dir = Math.Sign(steps); + for (int k = 0; k < Math.Abs(steps); k++) + { + int partner = MetaVocabulary.SwapPartner(_data.Rules, index, dir); + if (partner < 0 || !Move(index, dir)) break; + index = partner; + } + RebuildCaches(); + } + + // ===================================================================== + // Row and header menus (right-click) + // ===================================================================== + + private void RuleMenus() + { + if (_openRuleMenu) { ImGuiNET.ImGui.OpenPopup("##meta_rule_menu"); _openRuleMenu = false; } + if (_openStateMenu) { ImGuiNET.ImGui.OpenPopup("##meta_state_menu"); _openStateMenu = false; } + + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.HeaderHovered, PickSel); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(6, 6)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupBorderSize, 1f); + + if (ImGuiNET.ImGui.BeginPopup("##meta_rule_menu")) + { + int i = _ctxRule; + if (i < 0 || i >= _data.Rules.Count) ImGuiNET.ImGui.CloseCurrentPopup(); + else + { + MetaRuleDto rule = _data.Rules[i]; + bool canMove = _filter.Length == 0; + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.PencilSimple + " Edit rule")) OpenEditor(i, rule); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.TextAa + (rule.Name.Length > 0 ? " Rename..." : " Name..."))) + { + OpenEditor(i, rule); + _focusRuleName = true; + } + if (Folds(i) && ImGuiNET.ImGui.MenuItem(IsFolded(i) ? PhosphorIcons.CaretDown + " Show all of it" : PhosphorIcons.CaretRight + " Fold to one line")) + SetFolded(i, !IsFolded(i)); + if (ImGuiNET.ImGui.MenuItem((rule.Enabled ? PhosphorIcons.Square + " Disable" : PhosphorIcons.CheckSquare + " Enable"))) + { + rule.Enabled = !rule.Enabled; + SendEdit(new MetaCmd { Op = "set_rule_enabled", Index = i, Value = rule.Enabled ? "true" : "false" }); + } + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.ArrowUp + " Move up", "", false, + canMove && MetaVocabulary.SwapPartner(_data.Rules, i, -1) >= 0) && Move(i, -1)) + RebuildCaches(); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.ArrowDown + " Move down", "", false, + canMove && MetaVocabulary.SwapPartner(_data.Rules, i, +1) >= 0) && Move(i, +1)) + RebuildCaches(); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Copy + " Duplicate") && Duplicate(i, rule)) RebuildCaches(); + ImGuiNET.ImGui.Separator(); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Red); + bool del = ImGuiNET.ImGui.MenuItem(PhosphorIcons.Trash + " Delete rule"); + ImGuiNET.ImGui.PopStyleColor(); + if (del && Delete(i)) RebuildCaches(); + } + ImGuiNET.ImGui.EndPopup(); + } + + if (ImGuiNET.ImGui.BeginPopup("##meta_state_menu")) + { + string? s = _ctxState; + if (s == null) ImGuiNET.ImGui.CloseCurrentPopup(); + else + { + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Play + " Make current state", "", false, !IsCurrent(s))) + { + _data.CurrentState = s; + MetaCommands.Simple("set_state", value: s); + _stateClock.StateSet(NowMs); + } + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Plus + " New rule in " + s)) + OpenEditor(-1, new MetaRuleDto { State = s, Action = 1 }); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.CaretRight + " Fold its rules")) SetStateFolded(s, true); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.CaretDown + " Show its rules in full")) SetStateFolded(s, false); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.ArrowsInLineVertical + " Collapse the others")) + { + foreach ((string st, List _) in _groups) if (!string.Equals(st, s, StringComparison.Ordinal)) _collapsed.Add(st); + _collapsed.Remove(s); + } + if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.ArrowsOutLineVertical + " Expand all states")) _collapsed.Clear(); + } + ImGuiNET.ImGui.EndPopup(); + } + + ImGuiNET.ImGui.PopStyleVar(4); + ImGuiNET.ImGui.PopStyleColor(4); + } + + // ===================================================================== + // Rule commands + // ===================================================================== + + 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]); + return true; + } + + private bool Duplicate(int index, MetaRuleDto rule) + { + SendEdit(new MetaCmd { Op = "duplicate_rule", Index = index, Rule = rule.Clone() }); + _data.Rules.Insert(Math.Min(index + 1, _data.Rules.Count), rule.Clone()); + return true; + } + + private bool Delete(int index) + { + if (index < 0 || index >= _data.Rules.Count) return false; + SendEdit(new MetaCmd { Op = "delete_rule", Index = index }); + _data.Rules.RemoveAt(index); + _confirmDelete = null; + return true; + } + + // ===================================================================== + // Bottom bar + // ===================================================================== + + // State: [current state v][target][+ New Rule] + 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; + const float goW = 24; + float pickX = p.X + labelW + 4; + float pickW = Math.Max(40, ruleX - 4 - goW - 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? inState = _stateClock.Known ? MetaStateClock.Format(_stateClock.SecondsInState(NowMs)) : null; + string? chosen = StatePicker("##cur_state", _data.CurrentState, _statePicks, Array.IndexOf(_statePicks, _data.CurrentState), + new Vector2(pickX, p.Y + 1), pickW, out bool isNew, badge: inState); + if (chosen != null) + { + if (isNew) CreateState(chosen, openIt: true); + _data.CurrentState = chosen; + MetaCommands.Simple("set_state", value: chosen); + _stateClock.StateSet(NowMs); // picking a state enters it afresh (RynthAi resets its clock) + } + if (inState != null && ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(pickX, p.Y + 1), new Vector2(pickX + pickW, p.Y + 23))) + ImGuiNET.ImGui.SetTooltip($"The meta's current state; in it for {inState}."); + bool canGo = HasRulesIn(_data.CurrentState); + if (IconButton("##goto_current", PhosphorIcons.Crosshair, new Vector2(pickX + pickW + 4, p.Y + 1), new Vector2(goW, 22), + Teal, BtnFill, BtnBord, enabled: canGo, font: UiFont.Ui14)) + { + _scrollToState = _data.CurrentState; + if (_filter.Length > 0 && !StateHasHits(_data.CurrentState)) + { + Array.Clear(_filterBuf); + SetFilter(string.Empty); + } + } + ImGuiNET.ImGui.SetItemTooltip(canGo ? "Show the current state in the list" : "The current state has no rules"); + 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)); + } + + private bool StateHasHits(string state) + { + foreach ((string s, List members) in _groups) + { + if (!string.Equals(s, state, StringComparison.OrdinalIgnoreCase)) continue; + foreach (int i in members) if (i < _filterHit.Length && _filterHit[i]) return true; + } + return false; + } + + // ===================================================================== + // Widgets + // ===================================================================== + + /// An icon with no frame (the enable box, the header's +, the filter's clear): brighter on hover. + private static bool GlyphButton(string id, string icon, Vector2 pos, Vector2 size, uint color, uint hoverColor) + { + ImGuiNET.ImGui.SetCursorScreenPos(pos); + bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(UiFont.Ui14), icon, pos, size, hot ? hoverColor : color); + return clicked; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs index f6b51fa..07ec4f4 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs @@ -207,7 +207,7 @@ internal sealed partial class MetaFace ScheduleRuleDto r = sc.Rules[i]; bool first = i == sc.FirstMatch && sc.Enabled; 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); bool changed = false; float x = p.X + 1; diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs index aa3c6d2..9ac960b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs @@ -3,11 +3,13 @@ // ImGui face of the Meta panel (docs/IMGUI_PARITY_PLAN.md §2.13), with the // Avalonia face's look and three views: // -// List file picker / refresh / Save As / "Saved" indicator; Visual|Source; -// Meta, Debug; rules grouped by state (collapsible, red while -// firing), rows with enable, expand, up/down within the state, -// duplicate, and delete on the far right (click twice); click a row -// to edit it; State picker and New Rule at the bottom. +// List (MetaFace.List.cs) file picker / refresh / Save As / "Saved" +// indicator; Visual|Source; Meta, Debug; a filter; rules grouped +// by state, each rule in full (every condition and action on its +// own line, or one line in Compact) with lines between rules and +// 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 // (stacked when the panel is narrow), each with "+ Add"; Set current // 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), Red = C(0xFFE04848), Mute = C(0xFFC8D6E4), TextDim = C(0xFFF2F7FC), ShellBg = C(0xFF0A0F14), 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); private static uint C(uint argb) => RynthTheme.Argb(argb); 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 long _seenVersion = -1; private List<(string State, List Rules)> _groups = new(); - private string[] _condText = Array.Empty(), _actText = Array.Empty(); - private string[] _groupLabel = Array.Empty(); private bool[] _groupFiring = Array.Empty(); private string[] _statePicks = Array.Empty(), _statesOnly = Array.Empty(); - private string[] _routePicks = Array.Empty(), _fileDisplays = Array.Empty(); + private string[] _routeLabels = Array.Empty(), _routeValues = Array.Empty(), _fileDisplays = Array.Empty(); private string _fileDisplay = "-- None --", _sourceFileLabel = "File: Unsaved"; private IReadOnlyList _completionNavs = Array.Empty(); @@ -78,8 +78,8 @@ internal sealed partial class MetaFace : IImGuiPanel private readonly Dictionary<(string Text, int Width), string> _fit = new(); private View _view = View.List; + private readonly MetaStateClock _stateClock = new(); private readonly HashSet _collapsed = new(); - private readonly HashSet _expanded = new(); private bool _saveAs, _saveAsFocus; private readonly byte[] _saveName = new byte[128]; @@ -195,6 +195,7 @@ internal sealed partial class MetaFace : IImGuiPanel if (snap == null || snap.Version == _seenVersion) return; _seenVersion = snap.Version; MetaPayload fresh = snap.Value; + _stateClock.Snapshot(fresh.Snapshot, NowMs); CheckApplyResult(fresh); _data = fresh.Clone(); RebuildCaches(); @@ -211,21 +212,12 @@ internal sealed partial class MetaFace : IImGuiPanel { List rules = _data.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]; for (int g = 0; g < _groups.Count; g++) { bool firing = false; foreach (int i in _groups[g].Rules) firing |= rules[i].LastFiredMs < 1500; _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). if (!string.Equals(_statesPath, _data.CurrentMetaPath, StringComparison.OrdinalIgnoreCase)) @@ -241,47 +233,20 @@ internal sealed partial class MetaFace : IImGuiPanel _statePicks = With(_statePicks, s); _statesOnly = With(_statesOnly, s); } - _routePicks = MetaVocabulary.RoutePicks(_data); + (_routeLabels, _routeValues) = MetaVocabulary.RoutePicks(_data); _fileDisplays = new string[_data.Files.Count]; for (int i = 0; i < _fileDisplays.Length; i++) _fileDisplays[i] = _data.Files[i].Display; _fileDisplay = MetaVocabulary.CurrentFileDisplay(_data); _sourceFileLabel = "File: " + (string.IsNullOrEmpty(_data.CurrentMetaPath) ? "Unsaved" : System.IO.Path.GetFileName(_data.CurrentMetaPath)); _completionNavs = MetaVocabulary.CompletionNavs(_data); _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) { if (_saveAs) @@ -458,255 +423,8 @@ internal sealed partial class MetaFace : IImGuiPanel _editor.RequestFocus(); } - // Condition/action split of the rule list (dragged in its header) and where - // the text starts within a row (from the last row drawn). + // Condition/action split of the rule list (dragged in its header; saved per PC). private static float _condFrac = Math.Clamp(RynthCore.Engine.UI.PanelColumnStore.Get("Meta.condFrac", 0.5f), 0.15f, 0.85f); - private float _textStartOff; - /// The far-right delete button and the gap before it: the row text ends this far from the edge. - 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 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 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 - } - } - } - - /// One rule row plus its expanded children. True when a click changed the list. - 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 @@ -1125,7 +843,7 @@ internal sealed partial class MetaFace : IImGuiPanel /// picked index or -1. /// 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(); ImGuiNET.ImGui.PushID(id); @@ -1146,7 +864,16 @@ internal sealed partial class MetaFace : IImGuiPanel const float caretW = 14; PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretDown, 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; ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); @@ -1278,9 +1005,15 @@ internal sealed partial class MetaFace : IImGuiPanel string shown = text; if (ImGuiNET.ImGui.CalcTextSize(text).X > width) { - int n = text.Length; - while (n > 0 && ImGuiNET.ImGui.CalcTextSize(text.AsSpan(0, n).ToString() + "…").X > width) n--; - shown = text.Substring(0, n) + "…"; + // The longest start that fits with "…" (binary search: long expressions are cut often, + // and the cache empties with every snapshot while rules fire). + 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 _fit[key] = shown; diff --git a/src/RynthCore.Engine/Net/FlightRecorder.cs b/src/RynthCore.Engine/Net/FlightRecorder.cs index 33bba5b..6fa5963 100644 --- a/src/RynthCore.Engine/Net/FlightRecorder.cs +++ b/src/RynthCore.Engine/Net/FlightRecorder.cs @@ -63,6 +63,16 @@ internal static unsafe class FlightRecorder public static bool Enabled => _cap != null && !_paused; + /// An automatic dump is scheduled or a dump is being written right now. + public static bool DumpPendingOrRunning + { + get + { + if (Volatile.Read(ref _dumping) != 0) return true; + lock (ScheduleLock) return _scheduledReason != null; + } + } + // ── setup ────────────────────────────────────────────────────────────── public static void Initialize() diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index fd21e0e..992d743 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -30,6 +30,7 @@ internal static class EngineSettings private static bool _enableImGuiBackend = true; private static bool _enableHangMinidump = true; private static bool _preventIdleLogoff = true; + private static bool _closeOnServerDisconnect = true; private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto; private static bool _decalInGameImGui = true; private static bool _decalStandDown = true; @@ -231,6 +232,27 @@ internal static class EngineSettings } } + /// "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. + public static bool CloseOnServerDisconnect + { + get + { + EnsureLoaded(); + return _closeOnServerDisconnect; + } + set + { + EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file + if (_closeOnServerDisconnect == value) return; + _closeOnServerDisconnect = value; + Save(); + } + } + /// "DecalBridge" in engine.json: Auto (default), On or Off. Only matters when /// Decal is loaded in the same client (docs/DECAL_BRIDGE_PLAN.md): /// Auto - bridge mode when the RynthCore Decal bridge is registered and says hello @@ -552,6 +574,10 @@ internal static class EngineSettings _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) && ilnEl.ValueKind == JsonValueKind.Array) _iltServerNames = ReadStringList(ilnEl); @@ -601,7 +627,7 @@ internal static class EngineSettings "EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge", "DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream", "FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix", - "MaxHotReloads", "ReportEndpoint", + "MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", }; private static void Save() @@ -650,6 +676,8 @@ internal static class EngineSettings w.WriteBoolean("EnableLargeAddressAlignmentFix", false); if (_insertReleasesUi) // default false: leave the file as it was 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 w.WriteNumber("MaxHotReloads", _maxHotReloads); if (_reportEndpoint != null) // only a hand-set value is written diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index c2bdc06..c23ac07 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -844,6 +844,26 @@ internal struct RynthCoreAPI /// must equal that price; 0 skips the comparison. Same results and threading as Raise. /// Requires API v79+. public IntPtr TrainSkillFn; + + /// v80: int GetContainerOrder(uint containerId, int slotKind, uint* ids, int maxIds): + /// 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+. + public IntPtr GetContainerOrderFn; + + /// v80: int PutItemInContainer(uint itemId, uint containerId, int placement): 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+. + public IntPtr PutItemInContainerFn; } /// v79 bits. @@ -1664,3 +1684,9 @@ internal unsafe delegate int RaiseCallbackDelegate(uint kind, uint stype, uint r [UnmanagedFunctionPointer(CallingConvention.Cdecl)] 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); diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index 07f9bd6..e1a1ab1 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -15,5 +15,5 @@ namespace RynthCore.Engine.Plugins; /// Current API version. Bump when adding fields to RynthCoreAPI (and the SDK's RynthCoreApiNative). internal static class PluginContractVersion { - public const uint Current = 79; + public const uint Current = 80; } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 9537dd2..7d16441 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -264,6 +264,8 @@ internal static partial class PluginManager private static GetTrainingInfoCallbackDelegate? _getTrainingInfoCallback; // v79 private static RaiseCallbackDelegate? _raiseCallback; // v79 private static TrainSkillCallbackDelegate? _trainSkillCallback; // v79 + private static GetContainerOrderCallbackDelegate? _getContainerOrderCallback; // v80 + private static PutItemInContainerCallbackDelegate? _putItemInContainerCallback; // v80 private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback; private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback; private static VendorBuyCallbackDelegate? _vendorBuyCallback; @@ -2787,6 +2789,8 @@ internal static partial class PluginManager unsafe { _getTrainingInfoCallback ??= GetTrainingInfoAction; } // v79 unsafe { _raiseCallback ??= RaiseAction; } _trainSkillCallback ??= TrainSkillAction; + unsafe { _getContainerOrderCallback ??= GetContainerOrderAction; } // v80 + _putItemInContainerCallback ??= PutItemInContainerAction; _getVendorInfoCallback ??= GetVendorInfoAction; _getVendorItemsCallback ??= GetVendorItemsAction; _vendorBuyCallback ??= VendorBuyAction; @@ -2930,6 +2934,8 @@ internal static partial class PluginManager _api.GetTrainingInfoFn = Marshal.GetFunctionPointerForDelegate(_getTrainingInfoCallback); _api.RaiseFn = Marshal.GetFunctionPointerForDelegate(_raiseCallback); _api.TrainSkillFn = Marshal.GetFunctionPointerForDelegate(_trainSkillCallback); + _api.GetContainerOrderFn = Marshal.GetFunctionPointerForDelegate(_getContainerOrderCallback); + _api.PutItemInContainerFn = Marshal.GetFunctionPointerForDelegate(_putItemInContainerCallback); _api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback); _api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback); _api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback); @@ -4041,6 +4047,41 @@ internal static partial class PluginManager } } + // ── v80: slot order and placed moves (Net/InventoryOrder, ClientHelperHooks) ── + + /// v80: see PluginContract.GetContainerOrderFn. + 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; + } + } + + /// v80: see PluginContract.PutItemInContainerFn. + 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; + } + } + /// v78: see PluginContract.SetServerMessageInterestFn. private static unsafe int SetServerMessageInterestAction(uint* opcodes, int opcodeCount, uint* gameEvents, int eventCount) { diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index 06534c4..e2b85ce 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -4,8 +4,9 @@ // the Avalonia UI/Panels/RynthChatPanel.cs) and both filter editors: // // • ChatSource (hub, 100 ms) pulls new lines from RynthChatGetScrollbackJson -// on the pump thread, keeps the newest 500, routes and colours them with -// the rules, and writes the chat log. It also hands each new line to the +// on the pump thread, keeps the newest ChatModel.HistoryLines ("Chat +// 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 // this source subscribed while it is on. // • ChatModel holds the settings (rynthchat_settings.json), the regex @@ -25,13 +26,14 @@ // colours add up, a higher rule winning where two overlap. // // 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 // 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 // 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 -// 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 // tick (ChatRouter.Charge). // @@ -63,205 +65,28 @@ using RynthCore.Engine.Plugins; namespace RynthCore.Engine.UI.Data; -/// One scrollback line. Immutable except its Route, which the pump replaces. -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}"; - } - - /// Engine-assigned, increasing for the whole session (the plugin's own - /// seq restarts after RL). - public long Id { get; } - /// 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. - public ulong Seq { get; init; } - public string Timestamp { get; } - /// The channel tab it belongs to (ChatClassifier in the plugin). - public string Channel { get; } - /// AC's ChatMessageType; -1 from RynthChat before 0.2.0. - public int ChatType { get; } - /// Who spoke, for player speech; metadata only (mentions, rules from a line). - public string? Sender { get; } - /// The line as AC printed it. Rules match this. - public string Text { get; } - /// Which line colour setting applies ("say", "chan:General", ...), or null: - /// its tab's colour (ChatLineColors.KindOf, worked out once here). - public string? ColorKind { get; } - /// "HH:mm:ss text": copy, log and the Avalonia face. - public string FormattedText { get; } - - private ChatRoute _route = ChatRoute.Default; - - /// 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. - public ChatRoute Route - { - get => Volatile.Read(ref _route); - internal set => Volatile.Write(ref _route, value); - } -} - -/// A run of the line's Text drawn in its own colour (0xAARRGGBB). -internal readonly record struct ChatSpan(int Start, int Length, uint Argb); - -/// The rules' verdict for one line. Immutable. -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; - } - - /// A Hide rule matched: shown nowhere. - public bool Hidden { get; } - /// Shown under All and its channel tab (false once a Move rule took it away). - public bool InHome { get; } - /// Tabs a Move or Copy rule sent it to. - public string[]? Tabs { get; } - /// Whole-line colour from a rule; null = the channel colour. - public uint? LineArgb { get; } - /// Matched-text colours: offsets into Text, sorted, not overlapping. - public ChatSpan[]? Spans { get; } - /// Someone said your name (or a mention word). - 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 -{ - /// Only in the rule's tab: leaves All and its channel tab. - Move, - /// Also in the rule's tab. - Copy, - /// Nowhere. - Hide, - /// No routing: the rule only colours. - Color, -} - -internal enum ChatColorMode { None, Line, Match } - /// -/// 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. +/// New RynthChat lines while a chat face or the Discord relay holds it (100 ms). Publishes +/// the newest ChatModel.HistoryLines (the "Chat history" setting; 500 until 2026-10-11), +/// routed, and keeps RynthChat's own ring the same length (RynthChatSetCapacity). /// -internal sealed class ChatFilterRule -{ - public const int TimeoutMs = 15; - - public volatile bool Enabled = true; - public volatile string Pattern = ""; - /// The Move / Copy target. Empty: a Move or Copy rule routes nowhere (it can still colour). - public volatile string Tab = ""; - public volatile ChatRuleAction Action = ChatRuleAction.Move; - public volatile ChatColorMode ColorMode = ChatColorMode.None; - /// How Pattern is read: a regex (the default, and every rule saved before - /// 2026-10-05) or plain text. Recompile after changing it. - public volatile ChatMatchMode Mode = ChatMatchMode.Regex; - /// A new rule's colour (amber). - public const uint DefaultColor = 0xFFFFD27A; - /// 0xAARRGGBB. - public volatile uint ColorArgb = DefaultColor; - - private volatile WhenSpec _when = WhenSpec.Any; - /// "" any line; "chan:Combat" one channel tab; "type:3" one ChatMessageType (see ChatModel.Conditions). - public string When - { - get => _when.Raw; - set => _when = WhenSpec.Parse(value); - } - - /// Kept lines this rule matched (recounted when the rules change, then - /// counted up as lines arrive). Written by the pump; the editor shows it. - public int Hits; - - public volatile Regex? Compiled; - /// The pattern doesn't compile (or is empty). - public volatile bool Invalid; - /// Why it doesn't compile; null when it does or is just empty. - public volatile string? Error; - /// A match timed out: skipped until the pattern is edited. - public volatile bool Slow; - - /// Compiles the pattern once (after every pattern edit). Any thread. - 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; - } - - /// Does the rule route (Move / Copy with a tab, or Hide)? - 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); - } - } -} - -/// New RynthChat lines while a chat face or the Discord relay holds it (100 ms). Publishes the newest 500, routed. internal sealed unsafe class ChatSource : UiSource { - private const int MaxLines = 500; private delegate* unmanaged[Cdecl] _get; + // RynthChat 0.3.0+: how many lines its ring keeps. Null for an older plugin (it keeps 500). + private delegate* unmanaged[Cdecl] _setCapacity; + private int _sentCapacity; private ulong _sinceSeq; private long _nextId = 1; private bool _boundLogged; private long _routedVersion = -1; 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) { } @@ -290,26 +115,25 @@ internal sealed unsafe class ChatSource : UiSource if (ChatModel.SendLinePtr == IntPtr.Zero) ChatModel.SendLinePtr = PluginExportBinder.Resolve("RynthChat", "RynthChatSendLine"); ChatModel.PluginBound = _get != null; + int maxLines = ChatModel.HistoryLines; + if (_get != null) SyncPluginCapacity(maxLines); ChatModel.PumpLog(null); // The rules (or the name mentions look for) changed: route the kept lines again. long version = ChatModel.FiltersVersion; string name = ChatModel.PumpCharacterName(); ChatRouter router = ChatModel.PumpRouter(name); + TrimToLength(maxLines); if (version != _routedVersion || name != _routedName) { _routedVersion = version; _routedName = name; - ChatLine[]? kept = Current?.Value; - router.BeginPass(); - try - { - if (kept != null) - foreach (ChatLine line in kept) line.Route = router.Evaluate(line, null); - } - finally { router.EndPass(); } - ChatModel.BumpRoutes(); + _passRouter = router; + _passBelowId = long.MaxValue; + router.BeginPass(Current?.Value.Length ?? 0); + router.EndPass(); // paused until its slice below } + if (_passRouter != null) ContinueReroute(_passRouter); if (_get == null) return; @@ -353,16 +177,74 @@ internal sealed unsafe class ChatSource : UiSource } ChatLine[] old = Current?.Value ?? Array.Empty(); - int keepOld = Math.Max(0, Math.Min(old.Length, MaxLines - added.Count)); - 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); + Publish(ChatHistory.Merge(old, added, maxLines)); ChatModel.PumpLog(added); RelayRead(added); } + /// + /// One time slice of re-routing the kept lines with , 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. + /// + private void ContinueReroute(ChatRouter router) + { + ChatLine[] kept = Current?.Value ?? Array.Empty(); + 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(); + } + + /// The index of the newest line whose Id is below (Ids increase), or -1. + 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; + } + + /// The setting was lowered: drop the oldest kept lines now, not only when new ones arrive. + private void TrimToLength(int maxLines) + { + ChatLine[]? kept = Current?.Value; + if (kept != null && ChatHistory.Trim(kept, maxLines) is { } trimmed) Publish(trimmed); + } + + /// Tells RynthChat (0.3.0+) the history length once it's bound and whenever the setting moves. + private void SyncPluginCapacity(int maxLines) + { + if (_setCapacity == null) + { + _setCapacity = (delegate* unmanaged[Cdecl])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})."); + } + /// Every scrollback read goes to the Discord relay, empty or not (its first read is a baseline). private static void RelayRead(IReadOnlyList added) { @@ -451,6 +333,8 @@ internal sealed unsafe class ChatSource : UiSource // RL loads a fresh plugin copy whose scrollback numbers from 1 again. // The lines already shown stay. _get = null; + _setCapacity = null; + _sentCapacity = 0; _sinceSeq = 0; Discord.ChatDiscord.PumpSourceReset(); ChatModel.SendLinePtr = IntPtr.Zero; @@ -458,236 +342,6 @@ internal sealed unsafe class ChatSource : UiSource } } -/// -/// 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). -/// -internal sealed class ChatRouter -{ - /// Mentions colour the name like this (amber). - 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); - - /// ChatMessageType Emote (0x0C). - 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; - - /// Your character's name ("" unknown): your own emotes don't mention you. - /// Count matches into ChatFilterRule.Hits (the pump's router; not the test box's). - public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits) - { - _rules = rules; - _mention = mention; - _self = self.Trim(); - _countHits = countHits; - _passTicks = new long[rules.Length]; - } - - /// Before routing every kept line again: hit counts restart, and each rule's time is watched. - public void BeginPass() - { - ResetHits(); - Array.Clear(_passTicks); - _inPass = true; - } - - public void EndPass() => _inPass = false; - - /// Adds a rule's matching time during a pass; marks it Slow past the budget. False once it's Slow. - private bool Charge(int i, long ticks, List? 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; - } - - /// Before routing every kept line again. - public void ResetHits() - { - foreach (ChatFilterRule rule in _rules) Volatile.Write(ref rule.Hits, 0); - } - - /// One step of the editor's test: rule index (-1 = mention) and what it did. - public readonly record struct Step(int Rule, string What); - - public ChatRoute Evaluate(ChatLine line, List? trace) => - Evaluate(line.Text, line.Channel, line.ChatType, trace); - - public ChatRoute Evaluate(string text, string channel, int chatType, List? trace) - { - bool hidden = false, inHome = true, routed = false; - List? 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? tabs, string tab) - { - tabs ??= new List(2); - foreach (string t in tabs) if (string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)) return; - tabs.Add(tab); - } - - private static void MarkSlow(ChatFilterRule rule, List? 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")); - } - - /// Overlapping spans: the earlier one (a higher rule) keeps its characters. - 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(); - 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 { /// Channel tabs; must match ChatClassifier in the plugin. @@ -771,6 +425,16 @@ internal static class ChatModel public static volatile bool MentionSound; /// Extra words to highlight, comma-separated. public static volatile string MentionWords = ""; + /// How many lines the scrollback keeps, all tabs together (ChatHistory; "Chat history" in the gear menu). + 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) { @@ -1668,6 +1332,7 @@ internal static class ChatModel MentionHighlight = dto.MentionHighlight; MentionSound = dto.MentionSound; 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 var tabs = new List(); @@ -1734,6 +1399,8 @@ internal static class ChatModel MentionHighlight = MentionHighlight, MentionSound = MentionSound, 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 CustomTabs = Volatile.Read(ref _customTabs), Filters = Filters.Select(ToDto).ToArray(), diff --git a/src/RynthCore.Engine/UI/Data/ChatHistory.cs b/src/RynthCore.Engine/UI/Data/ChatHistory.cs new file mode 100644 index 0000000..59e8910 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatHistory.cs @@ -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; + /// The setting moves in steps of this many lines. + public const int StepLines = 500; + + /// A stored or typed length made valid: 0 or less (absent) is the default. + 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); + } + + /// + /// The newest of followed by + /// , as a new array (the published one is never changed: + /// faces on other threads read it). Cost: one copy of the kept references. + /// + public static T[] Merge(T[] old, IReadOnlyList 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; + } + + /// The newest lines, or null when there are no more than that. + public static T[]? Trim(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; + } +} diff --git a/src/RynthCore.Engine/UI/Data/ChatRouting.cs b/src/RynthCore.Engine/UI/Data/ChatRouting.cs new file mode 100644 index 0000000..9ac1192 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatRouting.cs @@ -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; + +/// One scrollback line. Immutable except its Route, which the pump replaces. +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}"; + } + + /// Engine-assigned, increasing for the whole session (the plugin's own + /// seq restarts after RL). + public long Id { get; } + /// 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. + public ulong Seq { get; init; } + public string Timestamp { get; } + /// The channel tab it belongs to (ChatClassifier in the plugin). + public string Channel { get; } + /// AC's ChatMessageType; -1 from RynthChat before 0.2.0. + public int ChatType { get; } + /// Who spoke, for player speech; metadata only (mentions, rules from a line). + public string? Sender { get; } + /// The line as AC printed it. Rules match this. + public string Text { get; } + /// Which line colour setting applies ("say", "chan:General", ...), or null: + /// its tab's colour (ChatLineColors.KindOf, worked out once here). + public string? ColorKind { get; } + /// "HH:mm:ss text": copy, log and the Avalonia face. + public string FormattedText { get; } + + private ChatRoute _route = ChatRoute.Default; + + /// 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. + public ChatRoute Route + { + get => Volatile.Read(ref _route); + internal set => Volatile.Write(ref _route, value); + } +} + +/// A run of the line's Text drawn in its own colour (0xAARRGGBB). +internal readonly record struct ChatSpan(int Start, int Length, uint Argb); + +/// The rules' verdict for one line. Immutable. +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; + } + + /// A Hide rule matched: shown nowhere. + public bool Hidden { get; } + /// Shown under All and its channel tab (false once a Move rule took it away). + public bool InHome { get; } + /// Tabs a Move or Copy rule sent it to. + public string[]? Tabs { get; } + /// Whole-line colour from a rule; null = the channel colour. + public uint? LineArgb { get; } + /// Matched-text colours: offsets into Text, sorted, not overlapping. + public ChatSpan[]? Spans { get; } + /// Someone said your name (or a mention word). + 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 +{ + /// Only in the rule's tab: leaves All and its channel tab. + Move, + /// Also in the rule's tab. + Copy, + /// Nowhere. + Hide, + /// No routing: the rule only colours. + Color, +} + +internal enum ChatColorMode { None, Line, Match } + +/// +/// 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. +/// +internal sealed class ChatFilterRule +{ + public const int TimeoutMs = 15; + + public volatile bool Enabled = true; + public volatile string Pattern = ""; + /// The Move / Copy target. Empty: a Move or Copy rule routes nowhere (it can still colour). + public volatile string Tab = ""; + public volatile ChatRuleAction Action = ChatRuleAction.Move; + public volatile ChatColorMode ColorMode = ChatColorMode.None; + /// How Pattern is read: a regex (the default, and every rule saved before + /// 2026-10-05) or plain text. Recompile after changing it. + public volatile ChatMatchMode Mode = ChatMatchMode.Regex; + /// A new rule's colour (amber). + public const uint DefaultColor = 0xFFFFD27A; + /// 0xAARRGGBB. + public volatile uint ColorArgb = DefaultColor; + + private volatile WhenSpec _when = WhenSpec.Any; + /// "" any line; "chan:Combat" one channel tab; "type:3" one ChatMessageType (see ChatModel.Conditions). + public string When + { + get => _when.Raw; + set => _when = WhenSpec.Parse(value); + } + + /// Kept lines this rule matched (recounted when the rules change, then + /// counted up as lines arrive). Written by the pump; the editor shows it. + public int Hits; + + public volatile Regex? Compiled; + /// The pattern doesn't compile (or is empty). + public volatile bool Invalid; + /// Why it doesn't compile; null when it does or is just empty. + public volatile string? Error; + /// A match timed out: skipped until the pattern is edited. + public volatile bool Slow; + + /// Compiles the pattern once (after every pattern edit). Any thread. + 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; + } + + /// Does the rule route (Move / Copy with a tab, or Hide)? + 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); + } + } +} + +/// +/// 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). +/// +internal sealed class ChatRouter +{ + /// Mentions colour the name like this (amber). + 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); + + /// ChatMessageType Emote (0x0C). + 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; + + /// Your character's name ("" unknown): your own emotes don't mention you. + /// Count matches into ChatFilterRule.Hits (the pump's router; not the test box's). + public ChatRouter(ChatFilterRule[] rules, Regex? mention, string self, bool countHits) + { + _rules = rules; + _mention = mention; + _self = self.Trim(); + _countHits = countHits; + _passTicks = new long[rules.Length]; + } + + /// + /// Before routing the kept lines again: hit counts restart, and + /// each rule's time is watched (PassBudgetMs per PassBudgetLines lines, never less than + /// PassBudgetMs). + /// + public void BeginPass(int lines = PassBudgetLines) + { + ResetHits(); + Array.Clear(_passTicks); + _passBudgetTicks = PassBudgetTicks * Math.Max(PassBudgetLines, lines) / PassBudgetLines; + _inPass = true; + } + + /// The pass is over, or paused between two time slices (lines routed meanwhile aren't charged). + public void EndPass() => _inPass = false; + + /// The next time slice of a pass begun with BeginPass. + public void ResumePass() => _inPass = true; + + /// Adds a rule's matching time during a pass; marks it Slow past the budget. False once it's Slow. + private bool Charge(int i, long ticks, List? 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; + } + + /// Before routing every kept line again. + public void ResetHits() + { + foreach (ChatFilterRule rule in _rules) Volatile.Write(ref rule.Hits, 0); + } + + /// One step of the editor's test: rule index (-1 = mention) and what it did. + public readonly record struct Step(int Rule, string What); + + public ChatRoute Evaluate(ChatLine line, List? trace) => + Evaluate(line.Text, line.Channel, line.ChatType, trace); + + public ChatRoute Evaluate(string text, string channel, int chatType, List? trace) + { + bool hidden = false, inHome = true, routed = false; + List? 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? tabs, string tab) + { + tabs ??= new List(2); + foreach (string t in tabs) if (string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)) return; + tabs.Add(tab); + } + + private static void MarkSlow(ChatFilterRule rule, List? 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")); + } + + /// Overlapping spans: the earlier one (a higher rule) keeps its characters. + 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(); + 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(); + } +} diff --git a/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs b/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs index f3259d1..d81f272 100644 --- a/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs +++ b/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs @@ -62,6 +62,8 @@ internal sealed class RynthChatSettingsDto // 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. [JsonPropertyName("lineColors")] public Dictionary? 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("filters")] public RynthChatFilterDto[]? Filters { get; set; } } diff --git a/src/RynthCore.Engine/UI/Data/DamageData.cs b/src/RynthCore.Engine/UI/Data/DamageData.cs index 812923c..de9a9c4 100644 --- a/src/RynthCore.Engine/UI/Data/DamageData.cs +++ b/src/RynthCore.Engine/UI/Data/DamageData.cs @@ -40,6 +40,10 @@ internal sealed class DamageRow public bool HpEst; public double Crit; public int CritN; public double NonCrit; public int NonCritN; public double Casts; public int Kills; public string Key = ""; + /// 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. + public uint[] Wcids = Array.Empty(); /// Per-monster (wcid) weapon state, the same on every row of a wcid. public uint AssignedWid; public string AssignedWeapon = ""; public uint BestWid; public string BestWeapon = ""; @@ -288,6 +292,12 @@ internal sealed unsafe class DamageSource : UiSource 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("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(); + 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("petLabel", out var pl)) row.PetLabel = pl.GetString() ?? "Auto"; if (e.TryGetProperty("weak", out var wk)) row.Weak = wk.GetString() ?? ""; diff --git a/src/RynthCore.Engine/UI/Data/MetaData.cs b/src/RynthCore.Engine/UI/Data/MetaData.cs index 5a5bd3b..362df73 100644 --- a/src/RynthCore.Engine/UI/Data/MetaData.cs +++ b/src/RynthCore.Engine/UI/Data/MetaData.cs @@ -115,6 +115,8 @@ internal sealed class MetaPayload public MetaApplyResult? ApplyResult { get; set; } /// The Meta Manager; null from a RynthAi without it. public SchedulePayload? Schedule { get; set; } + /// Seconds in state and the Watchdog; null from a RynthAi without it. + public MetaStateSnapshot? Snapshot { get; set; } /// Deep copy of the rules; the rest is shared (faces never change it). public MetaPayload Clone() @@ -381,19 +383,53 @@ internal static class MetaVocabulary return states.ToArray(); } - /// Embedded Nav's route picker: nav files, then "[emb] key" for embedded routes. - public static string[] RoutePicks(MetaPayload d) + /// Embedded Nav Route's "Patrol": RynthAi's dungeon patrol (/ra dunnav-patrol) when the + /// meta and NavProfiles have no route by that name (RynthAi MetaManager.IsPatrolRoute). + public const string PatrolRoute = "Patrol"; + + /// A route of the meta or NavProfiles called (any case). + public static bool HasRoute(MetaPayload d, string name) { - var routes = new List(); - foreach (string n in d.NavFiles) if (n != "None") routes.Add(n); - foreach (string k in d.EmbeddedNavKeys) if (!routes.Contains(k)) routes.Add($"[emb] {k}"); - return routes.ToArray(); + foreach (string n in d.NavFiles) if (string.Equals(n, name, StringComparison.OrdinalIgnoreCase)) return true; + foreach (string k in d.EmbeddedNavKeys) if (string.Equals(k, name, StringComparison.OrdinalIgnoreCase)) return true; + return false; } - /// Nav names for source completion (nav files and embedded keys, no duplicates). + /// + /// 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"). + /// + public static (string[] Labels, string[] Values) RoutePicks(MetaPayload d) + { + var labels = new List(); + var values = new List(); + 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()); + } + + /// Nav names for source completion (Patrol, nav files and embedded keys, no duplicates). public static IReadOnlyList CompletionNavs(MetaPayload d) { - var combined = new List(d.NavFiles.Count + d.EmbeddedNavKeys.Count); + var combined = new List(d.NavFiles.Count + d.EmbeddedNavKeys.Count + 1); + if (!HasRoute(d, PatrolRoute)) combined.Add(PatrolRoute); combined.AddRange(d.NavFiles); foreach (string n in d.EmbeddedNavKeys) if (!combined.Contains(n)) combined.Add(n); return combined; diff --git a/src/RynthCore.Engine/UI/Data/MetaEditing.cs b/src/RynthCore.Engine/UI/Data/MetaEditing.cs index 2102c3f..d07e71b 100644 --- a/src/RynthCore.Engine/UI/Data/MetaEditing.cs +++ b/src/RynthCore.Engine/UI/Data/MetaEditing.cs @@ -141,9 +141,21 @@ internal static class MetaRuleEdit /// STATE: block per state that has rules), so this rule is what keeps an empty state. public static MetaRuleDto Placeholder(string state) => new() { State = state, Condition = Never, Action = NoAction }; + /// The longest rule name the editor takes. + public const int MaxNameLength = 80; + + /// A typed rule name: one line (RynthAi writes it as a "~~ @name" comment line), no longer + /// than . The editor trims the ends when it sends the rule. + 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) => 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; /// 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). @@ -227,11 +239,11 @@ internal static class MetaRuleEdit r.ActionChildren.Add(new MetaRuleDto { State = r.State, Action = NoAction }); } - /// Same state, condition, action, data, enabled flag and children (not LastFiredMs). + /// Same state, name, condition, action, data, enabled flag and children (not LastFiredMs). 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 - || 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.ActionData, b.ActionData, StringComparison.Ordinal) || a.Children.Count != b.Children.Count || a.ActionChildren.Count != b.ActionChildren.Count) diff --git a/src/RynthCore.Engine/UI/Data/MetaRowText.cs b/src/RynthCore.Engine/UI/Data/MetaRowText.cs new file mode 100644 index 0000000..01a4830 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/MetaRowText.cs @@ -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; + +/// What a piece of rule text is, for its colour. +internal enum MetaTone : byte +{ + /// Words: "Count", "Spell", "s left". + Label, + /// What was typed: an item name, a number, a chat command. + Value, + /// A state name (Set / Call Meta State, Watchdog). + State, + /// An expression or regex. + Code, + /// "and" / "or" / "not". + Join, + /// Never, None, "(nothing)". + Dim, + /// Something that won't work as written: "(empty)", a missing state. + 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; +} + +/// One line of a rule's condition or action column (full form). +internal sealed class MetaLine +{ + /// Nesting: the line starts this many slots in (a guide line is drawn in each). + public int Depth; + /// The line is an item of an and / or list: sits in a slot before it, + /// so the items' text lines up whether or not they have a join word. + public bool Slot; + /// "and" / "or" on a list's second and later items; "" otherwise. + public string Join = string.Empty; + public MetaSeg[] Segs = Array.Empty(); + + 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(); + } +} + +/// What the text needs from outside: spell names, which states exist. +internal sealed class MetaTextContext +{ + /// A spell's name, or null when unknown (the spell table may still be loading). + public Func? SpellName; + /// The meta's states (any case); null skips the missing-state check. + public ICollection? States; + /// 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. + public Func? RouteExists; + /// Set when a spell id was shown as a number for want of a name. + 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 + // ===================================================================== + + /// 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". + public static MetaLine[] ConditionLines(MetaRuleDto rule, MetaTextContext ctx) + { + var lines = new List(); + 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? lead, + List 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 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(); + 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))); + } + + /// The condition on one line: "a and (b or c)", "not (a and b)". + public static MetaSeg[] ConditionCompact(MetaRuleDto rule, MetaTextContext ctx) + { + var segs = new List(); + CondCompact(rule, segs, nested: false, ctx, 0); + return segs.ToArray(); + } + + private static void CondCompact(MetaRuleDto c, List 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 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)); + } + + /// One plain condition (not All / Any / Not). + 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 + // ===================================================================== + + /// The action column's lines: one per action, a DoAll's in order. + public static MetaLine[] ActionLines(MetaRuleDto rule, MetaTextContext ctx) + { + var lines = new List(); + Act(rule, lines, ctx, 0); + return lines.ToArray(); + } + + private static void Act(MetaRuleDto a, List 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))); + } + + /// The actions on one line, joined by " · ". + public static MetaSeg[] ActionCompact(MetaRuleDto rule, MetaTextContext ctx) + { + var segs = new List(); + 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(); + } + + /// One action (not DoAll). + 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 + { + 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 + // ===================================================================== + + /// The text of segments, for search and tooltips. + 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? 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 lead) => + new() { Depth = depth, Slot = slot, Join = join, Segs = lead.ToArray() }; +} diff --git a/src/RynthCore.Engine/UI/Data/MetaRuleDto.cs b/src/RynthCore.Engine/UI/Data/MetaRuleDto.cs index 520d548..711e5dd 100644 --- a/src/RynthCore.Engine/UI/Data/MetaRuleDto.cs +++ b/src/RynthCore.Engine/UI/Data/MetaRuleDto.cs @@ -20,6 +20,10 @@ internal sealed class MetaRuleDto public List Children { get; set; } = new(); public List ActionChildren { get; set; } = new(); public bool Enabled { get; set; } = true; + /// 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 (""). + 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 MetaRuleDto Clone() @@ -27,7 +31,7 @@ internal sealed class MetaRuleDto var r = new MetaRuleDto { 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 a in ActionChildren) r.ActionChildren.Add(a.Clone()); diff --git a/src/RynthCore.Engine/UI/Data/MetaStateClock.cs b/src/RynthCore.Engine/UI/Data/MetaStateClock.cs new file mode 100644 index 0000000..69af5aa --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/MetaStateClock.cs @@ -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; + +/// 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. +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; } +} + +/// +/// 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. +/// +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; + } + + /// The panel set the state: its clock starts again. + 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; + + /// Seconds until the Watchdog fires (its state in ); -1 when none is set. + 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); + } + + /// "42 s" under an hour (rules count seconds: "In state >= 300 s"), else "1:02:03". + 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}"); + } +} diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index 679088b..75b9649 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -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" + "saved time is slept (0 = no extra cap). Saved for this PC. Also: /rc video fps .", 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(), 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."), diff --git a/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs b/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs index 533c2a2..5bc249a 100644 --- a/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/ItemsPanel.cs @@ -61,6 +61,12 @@ internal static class ItemsPanel [JsonPropertyName("manaTapMinMana")] public int ManaTapMinMana { get; set; } = 2500; [JsonPropertyName("manaStoneKeepCount")]public int ManaStoneKeepCount{ get; set; } = 5; [JsonPropertyName("currentTargetName")] public string CurrentTargetName { get; set; } = string.Empty; + /// + /// 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. + /// + [JsonPropertyName("missingIds")] public List MissingIds { get; set; } = new(); } internal sealed class WeaponEntry diff --git a/src/RynthCore.Engine/UI/Panels/RynthChatPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthChatPanel.cs index 2ada387..5931fe2 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthChatPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthChatPanel.cs @@ -409,11 +409,17 @@ internal static class RynthChatPanel { ClearSelectionState(); 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(line, activeTab, searchFilter)) continue; - chatStack.Children.Add(MakeTextBlock(line)); + if (!ChatModel.LineVisible(lines[i], activeTab, searchFilter)) continue; + chatStack.Children.Add(MakeTextBlock(lines[i])); } // A full rebuild (tab/filter/font change) re-pins to the newest line. if (autoScrollCheck.IsChecked == true) diff --git a/src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs b/src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs index 6152eb3..c69ca4c 100644 --- a/src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs +++ b/src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs @@ -196,7 +196,13 @@ internal static class WindowFlags public const uint HasError = 1u << 9; /// RequestPos is a FirstUseEver default position (used only when nothing is saved). public const uint PosIsDefault = 1u << 10; - public const uint Known = (1u << 11) - 1; + /// + /// 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. + /// + public const uint BarButton = 1u << 11; + public const uint Known = (1u << 12) - 1; } internal static class DisplayListParser diff --git a/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs b/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs index 36be8ff..26a3015 100644 --- a/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs +++ b/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs @@ -460,15 +460,27 @@ internal static class ScriptWindowRegistry private static readonly Dictionary ByPanelKey = new(StringComparer.OrdinalIgnoreCase); private static long _lastRejectLogTicks; - // The bar's Scripts menu: a copy-on-write snapshot of the ShowInBar windows, republished - // (under Sync) when the window set, a title or a ShowInBar flag changed. AC's thread - // reads it without taking Sync. + // The bar's Scripts menu and the windows with a bar button of their own: copy-on-write + // snapshots of the ShowInBar windows, republished (under Sync) when the window set, a + // title or a ShowInBar/BarButton flag changed. AC's thread reads them without taking Sync. private static ScriptBarItem[] _barItems = Array.Empty(); + private static ScriptBarItem[] _barButtons = Array.Empty(); private static bool _barDirty; /// The Scripts menu's items, grouped (empty = no Scripts button). Any thread. public static ScriptBarItem[] BarItems => Volatile.Read(ref _barItems); + /// + /// 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. + /// + public static ScriptBarItem[] BarButtons => Volatile.Read(ref _barButtons); + + /// True when a window with these flags gets a bar button of its own (not a Scripts menu line). + public static bool HasOwnBarButton(uint flags) => + (flags & (WindowFlags.ShowInBar | WindowFlags.BarButton)) == (WindowFlags.ShowInBar | WindowFlags.BarButton); + // ── Host functions ─────────────────────────────────────────────────── /// UiSubmit: the owner's complete window set. Pump thread, inside the owner's dispatch. @@ -629,28 +641,36 @@ internal static class ScriptWindowRegistry ByPanelKey.Clear(); _barDirty = false; Volatile.Write(ref _barItems, Array.Empty()); + Volatile.Write(ref _barButtons, Array.Empty()); } } - /// Rebuilds the Scripts menu snapshot when something it shows changed. Caller holds Sync. + /// + /// 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. + /// private static void PublishBarLocked() { if (!_barDirty) return; _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 (ScriptWindow w in o.Windows.Values) { if ((w.Flags & WindowFlags.ShowInBar) == 0) continue; int slash = w.Key.LastIndexOf('/'); 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, Array.Empty()); - return; - } + Volatile.Write(ref _barItems, Snapshot(menu)); + Volatile.Write(ref _barButtons, Snapshot(buttons)); + } + + private static ScriptBarItem[] Snapshot(List<(string Group, ScriptWindow W)> rows) + { + if (rows.Count == 0) return Array.Empty(); rows.Sort(static (a, b) => { 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++) items[i] = new ScriptBarItem(rows[i].W, rows[i].Group, groupStart: i == 0 || !string.Equals(rows[i].Group, rows[i - 1].Group, StringComparison.Ordinal)); - Volatile.Write(ref _barItems, items); + return items; } // ── Windows ────────────────────────────────────────────────────────── @@ -677,7 +697,7 @@ internal static class ScriptWindowRegistry bool specChanged = isNew || ((w.Flags ^ pw.Flags) & SpecFlags) != 0 || w.DefaultSize != pw.DefaultSize || w.MinSize != pw.MinSize || w.DefaultPos != defaultPos; 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; w.Flags = pw.Flags; 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")}" + $" 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; } @@ -881,6 +901,7 @@ internal static class ScriptWindowRegistry Add(WindowFlags.NoPopOut, "NoPopOut"); Add(WindowFlags.HasError, "HasError"); Add(WindowFlags.PosIsDefault, "PosIsDefault"); + Add(WindowFlags.BarButton, "BarButton"); return sb.Length > 0 ? sb.ToString() : "none"; } } diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 07920c2..310b5ae 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -162,6 +162,9 @@ public struct RynthCoreApiNative public IntPtr GetTrainingInfoFn; // int GetTrainingInfo(TrainingInfoNative* info, TrainingEntryNative* entries, int max) -> entries there are public IntPtr RaiseFn; // int Raise(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent) -> RaiseResult public IntPtr TrainSkillFn; // int TrainSkill(uint stype, int expectedCredits) -> RaiseResult + // 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 } /// diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 88010ac..633a0ea 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -155,6 +155,14 @@ public readonly unsafe struct RynthCoreHost /// (spend unassigned XP and skill credits like the character window). public bool HasTraining => _api.Version >= 79 && _api.GetTrainingInfoFn != IntPtr.Zero && _api.RaiseFn != IntPtr.Zero && _api.TrainSkillFn != IntPtr.Zero; + + /// v80: (a container's items in real slot order, and the + /// side packs' order in the pack column). + public bool HasContainerOrder => _api.Version >= 80 && _api.GetContainerOrderFn != IntPtr.Zero; + + /// v80: (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. + public bool HasPutItemInContainer => _api.Version >= 80 && _api.PutItemInContainerFn != IntPtr.Zero; public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero; public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero; public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero; @@ -1784,6 +1792,47 @@ public readonly unsafe struct RynthCoreHost ? (RaiseResult)((delegate* unmanaged[Cdecl])_api.TrainSkillFn)(stype, expectedCredits) : 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. + + /// + /// v80: the items in in real slot order (slot 0 first), or with + /// the side packs and foci in the main pack (the pack column, top + /// first). = 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. + /// + 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])_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; + } + + /// + /// v80: moves into at slot + /// (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). + /// + public int PutItemInContainer(uint itemId, uint containerId, int placement) + => HasPutItemInContainer + ? ((delegate* unmanaged[Cdecl])_api.PutItemInContainerFn)(itemId, containerId, placement) + : -2; + /// /// v78: which reassembled server messages this plugin wants on its /// RynthPluginOnServerMessage(uint opcode, byte* data, int length) export (Cdecl; diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets index 76cf396..b3336b7 100644 --- a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -33,7 +33,7 @@ - 79 + 80 <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true diff --git a/tools/ChatHistoryBench/ChatHistoryBench.csproj b/tools/ChatHistoryBench/ChatHistoryBench.csproj new file mode 100644 index 0000000..293e2a6 --- /dev/null +++ b/tools/ChatHistoryBench/ChatHistoryBench.csproj @@ -0,0 +1,79 @@ + + + + + Exe + net10.0-windows + x86 + win-x86 + false + enable + enable + true + true + false + false + true + ChatHistoryBench + $(MSBuildThisFileDirectory)..\..\..\RynthSuite + $(RynthSuiteDir)\Plugins\RynthCore.Plugin.RynthChat + $(DefineConstants);HAVE_RYNTHCHAT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/ChatHistoryBench/OldChatBuffer.cs b/tools/ChatHistoryBench/OldChatBuffer.cs new file mode 100644 index 0000000..48f5ea3 --- /dev/null +++ b/tools/ChatHistoryBench/OldChatBuffer.cs @@ -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; + +/// +/// 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 "?"). +/// +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")); + } +} diff --git a/tools/ChatHistoryBench/Program.cs b/tools/ChatHistoryBench/Program.cs new file mode 100644 index 0000000..4fc2bd7 --- /dev/null +++ b/tools/ChatHistoryBench/Program.cs @@ -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; + +/// +/// 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. +/// +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(' '); + + /// One AC chat line: (text as AC prints it, ChatMessageType), 60-150 characters. + 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(@"(?ChatSource.PollLines' parse + construct + route for one read (no AC-link stripping: no links here). + private static List ReadLines(string json, ChatRouter router) + { + RynthChatLineDto[]? dtos = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatLineDtoArray); + var added = new List(dtos?.Length ?? 0); + foreach (RynthChatLineDto dto in dtos ?? Array.Empty()) + { + 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 + + /// N engine lines, routed, built the way ChatSource builds them (from the plugin's JSON when it's here). + 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); + } + + /// Bytes held by what returns. + private static long Held(Func 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 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(lines); + var h = new List(new float[n]); + var lay = new List(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 ────────────────────────────────────────────────────────────── + + /// Median milliseconds per call of (setup outside the timing). + 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 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(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(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(kept); var h = new List(new float[n]); var lay = new List(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 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 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; + + /// + /// One frame of a chat-like list: content 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. + /// (now only): the scroll to ask for, or null. Returns (scroll, max) as seen inside the child. + /// + 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}"); + } + + /// ChatHistory's arithmetic and RynthChat's resizable ring (newest kept, seq untouched). + 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}"); + } +} diff --git a/tools/ChatHistoryBench/Stubs.cs b/tools/ChatHistoryBench/Stubs.cs new file mode 100644 index 0000000..85f7c4c --- /dev/null +++ b/tools/ChatHistoryBench/Stubs.cs @@ -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)); + } +} diff --git a/tools/DisconnectCloseTests/DisconnectCloseTests.csproj b/tools/DisconnectCloseTests/DisconnectCloseTests.csproj new file mode 100644 index 0000000..2b4942e --- /dev/null +++ b/tools/DisconnectCloseTests/DisconnectCloseTests.csproj @@ -0,0 +1,25 @@ + + + + + Exe + net10.0 + enable + enable + true + DisconnectCloseTests + + + + + + + diff --git a/tools/DisconnectCloseTests/Program.cs b/tools/DisconnectCloseTests/Program.cs new file mode 100644 index 0000000..53d2a90 --- /dev/null +++ b/tools/DisconnectCloseTests/Program.cs @@ -0,0 +1,164 @@ +using RynthCore.Engine.Compatibility; +using V = RynthCore.Engine.Compatibility.ServerDisconnectClosePolicy.Verdict; + +namespace DisconnectCloseTests; + +/// +/// 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). +/// +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}"); + + /// Ticks every 16 ms from to (exclusive); + /// returns the verdicts other than None with the time they came. + private static List<(long At, V Verdict)> Run(ServerDisconnectClosePolicy p, long from, long to, + bool disconnected = true, bool enabled = true, bool exiting = false, Func? 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"); + } +} diff --git a/tools/EngineSettingsTests/Program.cs b/tools/EngineSettingsTests/Program.cs index 407645a..2b8e8f7 100644 --- a/tools/EngineSettingsTests/Program.cs +++ b/tools/EngineSettingsTests/Program.cs @@ -50,6 +50,7 @@ namespace EngineSettingsTests Run(nameof(SaveWithoutFileWritesOwnedKeys), SaveWithoutFileWritesOwnedKeys); Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone); Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept); + Run(nameof(CloseOnServerDisconnectDefaultOnAndSaved), CloseOnServerDisconnectDefaultOnAndSaved); } finally { @@ -80,6 +81,8 @@ namespace EngineSettingsTests case "hook-off": EngineSettings.SetUiHookEnabled(args[1], false); break; case "add-plugin": EngineSettings.AddPluginPath(args[1]); break; case "imgui-off": EngineSettings.EnableImGuiBackend = false; break; + case "dcclose-off": EngineSettings.CloseOnServerDisconnect = false; break; + case "dcclose-on": EngineSettings.CloseOnServerDisconnect = true; break; case "dump": Console.WriteLine("PluginPaths=" + string.Join("|", EngineSettings.PluginPaths)); Console.WriteLine("StartTooltip=" + EngineSettings.IsUiHookEnabled("StartTooltip")); @@ -87,6 +90,7 @@ namespace EngineSettingsTests Console.WriteLine("ImGuiBackend=" + EngineSettings.EnableImGuiBackend); Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream); Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads); + Console.WriteLine("CloseOnServerDisconnect=" + EngineSettings.CloseOnServerDisconnect); break; 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"); + } + } + /// The value of a "Name=value" line of the child's dump output ("" if none). private static string DumpValue(string output, string name) { diff --git a/tools/MetaEditTests/MetaEditTests.csproj b/tools/MetaEditTests/MetaEditTests.csproj index 3f07b50..49e761e 100644 --- a/tools/MetaEditTests/MetaEditTests.csproj +++ b/tools/MetaEditTests/MetaEditTests.csproj @@ -6,7 +6,7 @@ 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 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) --> @@ -22,6 +22,8 @@ + + diff --git a/tools/MetaEditTests/Program.cs b/tools/MetaEditTests/Program.cs index 110fd0b..42afdd7 100644 --- a/tools/MetaEditTests/Program.cs +++ b/tools/MetaEditTests/Program.cs @@ -25,6 +25,11 @@ internal static class Program TakesData(); NoKillsMinutes(); SameContentAndLocate(); + RuleNames(); + StateClock(); + RowTextLeaves(); + RowTextLists(); + RowTextActions(); Console.WriteLine(); Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL: {_failed} of {_checks} checks"); @@ -302,6 +307,168 @@ internal static class Program // ── 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(); + 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) { _case = name; diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index c9a5e7c..c312635 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -52,6 +52,7 @@ internal static class Program Run(nameof(GatePlanFromFiles), GatePlanFromFiles); Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift); Run(nameof(TrainingStructsMirror), TrainingStructsMirror); + Run(nameof(ContainerOrderSlots), ContainerOrderSlots); Run(nameof(ManifestAttributeDrivesRuntimeMinimum), ManifestAttributeDrivesRuntimeMinimum); Run(nameof(DedupeSamePathTwice), DedupeSamePathTwice); Run(nameof(DedupeCaseAndSlashes), DedupeCaseAndSlashes); @@ -473,13 +474,26 @@ internal static class Program Eq((int)Marshal.OffsetOf(f.Name), (int)Marshal.OffsetOf(f.Name), "TrainingEntryNative." + f.Name + " offset"); Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); - // The three v79 slots are the table's last three, in this order. - var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).TakeLast(3).ToArray(); - Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn" }), "v79 slots last: " + string.Join(",", names)); - var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).TakeLast(3).ToArray(); + // 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).SkipLast(2).TakeLast(3).ToArray(); + 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).SkipLast(2).TakeLast(3).ToArray(); 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(), Marshal.SizeOf(), "SDK table size = engine table size"); + Eq((int)Marshal.OffsetOf("PutItemInContainerFn"), + (int)Marshal.OffsetOf("PutItemInContainerFn"), "PutItemInContainerFn offset"); + } + private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { } private sealed class OverridingPlugin : RynthCore.PluginCore.RynthPluginBase { public override uint MinimumApiVersion => 70; } diff --git a/tools/PreCastStopTests/PreCastStopTests.csproj b/tools/PreCastStopTests/PreCastStopTests.csproj new file mode 100644 index 0000000..bcd35bb --- /dev/null +++ b/tools/PreCastStopTests/PreCastStopTests.csproj @@ -0,0 +1,24 @@ + + + + + Exe + net10.0 + enable + enable + true + PreCastStopTests + + + + + + + diff --git a/tools/PreCastStopTests/Program.cs b/tools/PreCastStopTests/Program.cs new file mode 100644 index 0000000..8b655fd --- /dev/null +++ b/tools/PreCastStopTests/Program.cs @@ -0,0 +1,43 @@ +using RynthCore.Engine.Compatibility; + +namespace PreCastStopTests; + +/// +/// 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. +/// +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}"); + } +}