commit 6fe5630e8c1ea1de9d94dc99ff0a95e58bb04c5f Author: Tom Bohar Date: Wed Oct 21 09:35:08 2026 -0400 Snapshot for release 2026.10.21.1 (internal 32a418d) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..968f2f5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +# Build outputs +bin/ +obj/ +publish/ +artifacts/ +TestResults/ + +# IDE and local tooling +.vs/ +.vscode/ +.idea/ +.claude/ +*.user +*.pubxml.user +*.suo +*.userosscache +*.rsuser + +# Local app data +.appdata/ +.localappdata/ + +# Logs and transient files +*.log +*.tmp +*.temp +*.cache +Thumbs.db +Desktop.ini + +# Local secrets and machine-specific config +.env +.env.* +*.secrets.json +secrets.* +appsettings.Local.json +appsettings.*.local.json + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a4ae066 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# Contributing to RynthServers + +This repository holds the plugins for particular game servers. RynthCore is the hook layer and RynthSuite holds the shared plugins; a feature for one server lives here, in that server's plugin, and nowhere else. + +## Where a change goes + +| It is... | It goes in | +|---|---| +| A feature, page, command or data for one server | **That server's plugin here** (`Plugins/RynthCore.Plugin.Rynth`) | +| Something every server plugin needs (the card, pages, settings, chat replies) | **`Plugins/Shared/ServerPack`** | +| A place in a shared plugin for server plugins to fill (a tab slot, a data feed) | **RynthSuite**, as a generic hook that names no server | +| A hook into the client or a new plugin API function | **RynthCore** | + +## Pull requests + +- One purpose per pull request. A change that needs a new hook comes as a pull request to RynthCore or RynthSuite for the hook first, then one here for the feature. +- Plugin API numbers and plugin versions are assigned when a change is merged. +- Add or update tests (`Tools/`). +- Say in the description what you tested in game, on which server. diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..abeec8d --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,10 @@ + + + + $([MSBuild]::NormalizeDirectory('$(MSBuildThisFileDirectory)', '..', 'RynthSuite')) + + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..16bbf9c --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 tombohar + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Plugins/Directory.Build.props b/Plugins/Directory.Build.props new file mode 100644 index 0000000..997db2e --- /dev/null +++ b/Plugins/Directory.Build.props @@ -0,0 +1,5 @@ + + + + + diff --git a/Plugins/Directory.Build.targets b/Plugins/Directory.Build.targets new file mode 100644 index 0000000..681b561 --- /dev/null +++ b/Plugins/Directory.Build.targets @@ -0,0 +1,4 @@ + + + + diff --git a/Plugins/RynthCore.Plugin.RynthAChard/RynthCore.Plugin.RynthAChard.csproj b/Plugins/RynthCore.Plugin.RynthAChard/RynthCore.Plugin.RynthAChard.csproj new file mode 100644 index 0000000..589c30a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAChard/RynthCore.Plugin.RynthAChard.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthAChard + 0.1.0 + achard + AChard + a-chard.ddns.net + AChard|A-Chard + AChard only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthAChard/ServerData.cs b/Plugins/RynthCore.Plugin.RynthAChard/ServerData.cs new file mode 100644 index 0000000..d3ec8dd --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAChard/ServerData.cs @@ -0,0 +1,23 @@ +// ServerData.cs - What is known about AChard (RynthAChard). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvP", + Status = "Stable", + Summary = "ACE EOR PVP Server/Custom PK Content/PK Kill Rankings", + Facts = new[] + { + "PvP server: other players can attack you.", + "Custom PK content and PK kill rankings.", + }, + Discord = "https://discord.gg/gmHfqt2J2D", + Website = "http://a-chard.ddns.net/", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthBoards.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthBoards.cs new file mode 100644 index 0000000..a007686 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthBoards.cs @@ -0,0 +1,277 @@ +// Moved here from RynthOracle (Data/AelrynthBoards.cs) on 2026-10-20: Aelrynth-only features live in RynthAelrynth. +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using RynthCore.Plugin.ServerPack; + +namespace RynthCore.Plugin.RynthAelrynth; + +/// A row of a leaderboard. +internal sealed class BoardRow +{ + public int Rank; + public string Name = ""; + public string Value = ""; + public string Extra = ""; + public bool IsYou; +} + +/// A board in Aelrynth's /top overview. +internal sealed class AelrynthBoardSummary +{ + public string Key = "", Title = "", Leader = "", Value = ""; +} + +/// Your standing on one board ("/top me"). +internal sealed class AelrynthStanding +{ + public string Title = ""; + public int Rank; + public int Of; + public string Value = ""; +} + +/// A line of the "/trial" overview: a dungeon's record, yours and this week's best. +internal sealed class TrialDungeon +{ + public string Name = "", Landblock = "", Record = "", You = "", Week = ""; +} + +/// +/// Aelrynth's leaderboards, read from the replies of the server's own commands +/// (ACEPublic Mods: Aeshnidae.Leaderboard /top, Aeshnidae.Trials /trial; one Broadcast line +/// each, numbers with thousands separators). Formats (Commands.cs): +/// /top "Leaderboards - N characters, refreshed X. /top <board> ..." +/// then " key Title: Leader, value" (or ": nobody yet") +/// /top <board> "Title - top K of N[, counted since ...][, per account]:" +/// then " r. Name value[ extra][ <- you]", " ... you: #r with v", " nobody yet." +/// /top me "Name on the boards:" then " Title #r of N, value" or " Title -" +/// /trial a few intro lines, then " Dungeon (LLLL): records | you: ... | this week: ..." +/// /trial <dungeon> "Dungeon (LLLL) - top 10, best per character, any tier:" +/// then " r. m:ss Name (tier T, K kills, d MMM)" and " records per tier/you/this week" lines +/// Entry lines only count right after their header (within a few seconds), so ordinary chat +/// can't add rows. Conquest answers /top in a very different shape (RynthConquest's parser), which is +/// why each server plugin reads only its own server's replies. +/// +internal sealed class AelrynthBoards +{ + private const long BlockMs = 4000; + + private static readonly Regex OverviewHeader = new(@"^\s*Leaderboards - ([\d,]+) characters, refreshed (.+?)\.\s"); + private static readonly Regex OverviewEntry = new(@"^\s*(\S+)\s+(.+?): (?:(.+), ([\d,]+)|nobody yet)\s*$"); + private static readonly Regex BoardHeader = new(@"^\s*(.+?) - top (\d+) of (\d+)(.*):\s*$"); + private static readonly Regex BoardEntry = new(@"^\s*(\d+)\.\s+(.+?)\s+([\d,]+)(?:\s{2,}(?!<-)(.+?))?(\s{2,}<- you)?\s*$"); + private static readonly Regex BoardYouBelow = new(@"^\s*\.\.\.\s+you: #(\d+) with ([\d,]+)\s*$"); + private static readonly Regex MeHeader = new(@"^\s*(.+?) on the boards:\s*$"); + private static readonly Regex MeEntry = new(@"^\s*(.+?)\s+#(\d+) of (\d+), ([\d,]+)\s*$"); + private static readonly Regex MeNone = new(@"^\s*(.+?)\s+-\s*$"); + private static readonly Regex OneMe = new(@"^\s*(.+?): you are #(\d+) of (\d+) with ([\d,]+)"); + private static readonly Regex TopError = new(@"^\s*(?:No board called '|Leaderboards are unavailable|The boards are still being built)"); + private static readonly Regex TrialDungeonLine = new(@"^\s*(.+?) \(([0-9A-Fa-f]{4})\): (.+?) \| you: (.+?) \| this week: (.+?)\s*$"); + private static readonly Regex TrialBoardHeader = new(@"^\s*(.+?) \(([0-9A-Fa-f]{4})\) - top 10, best per character, any tier:\s*$"); + private static readonly Regex TrialEntry = new(@"^\s*(\d+)\.\s+(\d+:\d{2}(?::\d{2})?)\s+(.+?) \((.+)\)\s*$"); + private static readonly Regex TrialNote = new(@"^\s*(?:records per tier|you|this week \([^)]*\)):\s"); + private static readonly Regex TrialError = new(@"^\s*(?:No Trial matches '|The Trials are switched off|The Trials could not be read)"); + private static readonly Regex TrialIntro = new(@"^\s*Trials - a fresh personal copy of a listed dungeon"); + private static readonly Regex TrialExtra = new(@"^\s*(?:your next attempt here: in \d+ min|running now: .+|Trophy: the week's fastest clear .+)$"); + + private enum Block { None, Overview, Board, Me, TrialList, TrialBoard } + + public readonly List Overview = new(); + public string OverviewNote = ""; + public string BoardTitle = "", BoardNote = ""; + public readonly List BoardRows = new(); + public string BoardYou = ""; + public readonly List Standings = new(); + public readonly List Trials = new(); + public readonly List TrialLines = new(); + public string TrialBoardTitle = ""; + public readonly List TrialRows = new(); + public readonly List TrialNotes = new(); + public string LastError = ""; + public int Revision { get; private set; } + + private Block _block; + private long _blockMs; + private readonly ServerChatRequest _topReq = new(), _trialReq = new(); + + public void Clear() + { + Overview.Clear(); BoardRows.Clear(); Standings.Clear(); Trials.Clear(); TrialLines.Clear(); TrialRows.Clear(); TrialNotes.Clear(); + OverviewNote = BoardTitle = BoardNote = BoardYou = TrialBoardTitle = LastError = ""; + _block = Block.None; + Revision++; + } + + public string RequestTop(string arg, long now) + { + _topReq.Sent(now); + LastError = ""; + if (string.IsNullOrWhiteSpace(arg)) { BoardTitle = ""; BoardRows.Clear(); } + return string.IsNullOrWhiteSpace(arg) ? "/top" : "/top " + arg.Trim(); + } + + public string RequestTrial(string arg, long now) + { + _trialReq.Sent(now); + LastError = ""; + return string.IsNullOrWhiteSpace(arg) ? "/trial" : "/trial " + arg.Trim(); + } + + private bool InBlock(Block b, long now) => _block == b && now - _blockMs < BlockMs; + + private void Start(Block b, long now) { _block = b; _blockMs = now; } + + /// A chat line: true when it was a leaderboard reply; = it answers RynthAelrynth's request. + public bool OnChatLine(string text, long now, out bool ours) + { + ours = false; + Match m; + + if ((m = OverviewHeader.Match(text)).Success) + { + Overview.Clear(); + OverviewNote = $"{m.Groups[1].Value} characters, refreshed {m.Groups[2].Value}"; + Start(Block.Overview, now); + return Mine(_topReq, now, out ours); + } + if ((m = TrialBoardHeader.Match(text)).Success) + { + TrialBoardTitle = $"{m.Groups[1].Value} ({m.Groups[2].Value.ToUpperInvariant()})"; + TrialRows.Clear(); + TrialNotes.Clear(); + Start(Block.TrialBoard, now); + return Mine(_trialReq, now, out ours); + } + if ((m = BoardHeader.Match(text)).Success && !text.Contains(" on the boards", StringComparison.Ordinal)) + { + BoardTitle = m.Groups[1].Value.Trim(); + BoardNote = $"top {m.Groups[2].Value} of {m.Groups[3].Value}{m.Groups[4].Value}"; + BoardRows.Clear(); + BoardYou = ""; + Start(Block.Board, now); + return Mine(_topReq, now, out ours); + } + if ((m = MeHeader.Match(text)).Success) + { + Standings.Clear(); + Start(Block.Me, now); + return Mine(_topReq, now, out ours); + } + if ((m = OneMe.Match(text)).Success) + { + BoardYou = $"{m.Groups[1].Value}: #{m.Groups[2].Value} of {m.Groups[3].Value} with {m.Groups[4].Value}"; + return Mine(_topReq, now, out ours); + } + if (TopError.IsMatch(text)) + { + LastError = text.Trim(); + return Mine(_topReq, now, out ours); + } + if (TrialError.IsMatch(text)) + { + LastError = text.Trim(); + return Mine(_trialReq, now, out ours); + } + if ((m = TrialDungeonLine.Match(text)).Success) + { + if (!InBlock(Block.TrialList, now)) { Trials.Clear(); TrialLines.Clear(); } + Trials.Add(new TrialDungeon + { + Name = m.Groups[1].Value.Trim(), Landblock = m.Groups[2].Value.ToUpperInvariant(), + Record = m.Groups[3].Value.Trim(), You = m.Groups[4].Value.Trim(), Week = m.Groups[5].Value.Trim(), + }); + Start(Block.TrialList, now); + return Mine(_trialReq, now, out ours); + } + + if (InBlock(Block.Overview, now) && (m = OverviewEntry.Match(text)).Success) + { + Overview.Add(new AelrynthBoardSummary + { + Key = m.Groups[1].Value, Title = m.Groups[2].Value.Trim(), + Leader = m.Groups[3].Success ? m.Groups[3].Value.Trim() : "nobody yet", + Value = m.Groups[4].Success ? m.Groups[4].Value : "", + }); + _blockMs = now; + return Mine(_topReq, now, out ours); + } + if (InBlock(Block.Board, now)) + { + if ((m = BoardEntry.Match(text)).Success) + { + int.TryParse(m.Groups[1].Value, out int rank); + BoardRows.Add(new BoardRow + { + Rank = rank, Name = m.Groups[2].Value.Trim(), Value = m.Groups[3].Value, + Extra = m.Groups[4].Success ? m.Groups[4].Value.Trim() : "", IsYou = m.Groups[5].Success, + }); + _blockMs = now; + return Mine(_topReq, now, out ours); + } + if ((m = BoardYouBelow.Match(text)).Success) + { + BoardYou = $"you: #{m.Groups[1].Value} with {m.Groups[2].Value}"; + return Mine(_topReq, now, out ours); + } + if (text.Trim() == "nobody yet.") return Mine(_topReq, now, out ours); + } + if (InBlock(Block.Me, now)) + { + if ((m = MeEntry.Match(text)).Success) + { + int.TryParse(m.Groups[2].Value, out int r); + int.TryParse(m.Groups[3].Value, out int of); + Standings.Add(new AelrynthStanding { Title = m.Groups[1].Value.Trim(), Rank = r, Of = of, Value = m.Groups[4].Value }); + _blockMs = now; + return Mine(_topReq, now, out ours); + } + if ((m = MeNone.Match(text)).Success) + { + Standings.Add(new AelrynthStanding { Title = m.Groups[1].Value.Trim() }); + _blockMs = now; + return Mine(_topReq, now, out ours); + } + } + if (InBlock(Block.TrialBoard, now)) + { + if ((m = TrialEntry.Match(text)).Success) + { + int.TryParse(m.Groups[1].Value, out int rank); + TrialRows.Add(new BoardRow { Rank = rank, Value = m.Groups[2].Value, Name = m.Groups[3].Value.Trim(), Extra = m.Groups[4].Value.Trim() }); + _blockMs = now; + return Mine(_trialReq, now, out ours); + } + if (TrialNote.IsMatch(text) || text.Trim() == "no clear yet") + { + TrialNotes.Add(text.Trim()); + _blockMs = now; + return Mine(_trialReq, now, out ours); + } + } + // The rest of a /trial overview: the intro, "next attempt", "running now" and trophy lines. + if (TrialIntro.IsMatch(text)) + { + Trials.Clear(); + TrialLines.Clear(); + TrialLines.Add(text.Trim()); + Start(Block.TrialList, now); + return Mine(_trialReq, now, out ours); + } + if (InBlock(Block.TrialList, now) && TrialExtra.IsMatch(text)) + { + TrialLines.Add(text.Trim()); + _blockMs = now; + return Mine(_trialReq, now, out ours); + } + return false; + } + + private bool Mine(ServerChatRequest req, long now, out bool ours) + { + ours = req.Awaiting(now); + req.Extend(now); + Revision++; + return true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthDifficulty.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthDifficulty.cs new file mode 100644 index 0000000..7579b18 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthDifficulty.cs @@ -0,0 +1,74 @@ +// AelrynthDifficulty.cs - Aelrynth's difficulty tier where the player stands, published for other plugins +// (2026-10-21; until then RynthAi read it itself, CreatureData/AwakenedTier.cs, added 2026-10-03). +// +// Aelrynth's awakened worlds and scaled dungeon copies hold the same monsters as real Dereth - same +// names, same wcids - with health, skills and damage scaled 5% a tier (resistances and weaknesses are +// not). Every monster in one copy or world shares one tier. The server tells the player's own client +// that tier as PropertyInt 9051 on the player (Aeshnidae.AwakenedRewards TierFeed.cs): a private update +// on login, teleport and every change; 0 = real Dereth. +// +// RynthAelrynth puts it in its "RynthServer.Profile" values (RynthServerProfile.ValueDifficultyTier and +// ValueDifficultyHealthPercent, Plugins/Shared/RynthServerProfileApi.cs). RynthAi reads them from the +// active server's plugin without knowing the server: learned HP, casts to kill, accuracy and fight times +// are kept per tier, a monster's HP is scaled by the percent, and the Damage panel shows the tier picker. +// +// Nothing is published off Aelrynth, nor before the property has been seen this login (an older server +// build that doesn't send it changes nothing): RynthAi then stays at tier 0, as on any other server. +// Pure (the plugin hands in the property read): RynthServerPack.Tests covers it. +using System; +using RynthCore.Plugin.ServerPack; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAelrynth; + +internal sealed class AelrynthDifficulty +{ + /// PropertyInt 9051 on the player: the difficulty tier where they stand. + public const uint TierProperty = 9051; + + /// The server's scaling per tier (InstancesNoDat DifficultyPercentPerEnlightenment, 5.0). + public const double HealthPercentPerTier = 5.0; + + /// How often the tier is read while on Aelrynth. + public const long ReadMs = 500; + + private long _nextReadMs; + + /// The tier where the player stands; null until the server has sent it this login (or off Aelrynth). + public int? Tier { get; private set; } + + /// Login and logout: nothing carries over (the values themselves are cleared at logout). + public void Reset() + { + Tier = null; + _nextReadMs = 0; + } + + /// + /// The plugin tick. On Aelrynth () the tier is read at most every + /// (: the player's PropertyInt 9051, null when it isn't + /// there) and, once seen, published in with the health percent per tier. + /// Off Aelrynth both values are taken out. A read that fails after one succeeded keeps the last tier. + /// + public void Tick(long nowMs, bool active, Func readTier, ServerProfileValues values) + { + if (!active) + { + if (Tier != null) Reset(); + values.Remove(RynthServerProfile.ValueDifficultyTier); + values.Remove(RynthServerProfile.ValueDifficultyHealthPercent); + return; + } + if (nowMs < _nextReadMs) return; + _nextReadMs = nowMs + ReadMs; + if (readTier() is int tier) Tier = Math.Max(0, tier); + if (Tier is not int known) return; + values.Set(RynthServerProfile.ValueDifficultyTier, known); + values.Set(RynthServerProfile.ValueDifficultyHealthPercent, HealthPercentPerTier); + } + + /// One line for "/rserver info". + public string Describe() => Tier is int t + ? $"Difficulty tier here: {t} (+{HealthPercentPerTier:0.#}% monster health a tier), shared with RynthAi." + : "Difficulty tier: not sent by the server yet this login (RynthAi stays at tier 0)."; +} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthFeature.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthFeature.cs new file mode 100644 index 0000000..bc236dd --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthFeature.cs @@ -0,0 +1,106 @@ +// AelrynthFeature.cs - What RynthAelrynth does on Aelrynth, without the host (AelrynthPlugin.cs wires it +// to the engine, AelrynthPages.cs draws it). Moved out of RynthOracle on 2026-10-20 so that only players +// who installed RynthAelrynth carry Aelrynth's features: +// * reads the replies of Aelrynth's own commands (AelrynthBoards: /top, /top me, /trial) and hides +// the replies to its own requests when HideOwnReplies is on; +// * reads the account vault (VaultFeed: /mule-data, moved here from RynthInventory, which asked every +// server for it) a few seconds after login and every ten minutes, and hands it to RynthInventory +// through the generic storage feed (Plugins/Shared/StorageFeed.cs), so it shows in Global Inventory. +// Settings: rynthaelrynth.json (ServerPackSettings); "hide own replies" is taken over once from +// rynthoracle.json (it was RynthOracle's hideOwnQuestReplies). +// Threads: everything here runs under Gate (chat and tick from the pump, the pages on the render thread). +// Pure: RynthServerPack.Tests covers it. +using System; +using RynthCore.Plugin.ServerPack; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAelrynth; + +internal sealed class AelrynthFeature +{ + public const string SettingHideOwnReplies = "hideOwnReplies"; + /// Set once rynthoracle.json's setting was taken over (it's never read again). + public const string MigrationMarker = "migratedFromRynthOracle"; + + /// RynthAelrynth's pages (AelrynthPages draws them): id, label, tooltip. + public static readonly (string Id, string Label, string Tooltip)[] PageList = + { + ("boards", "Leaderboards", "Aelrynth's /top leaderboards and /trial dungeon records (RynthAelrynth)."), + }; + + /// Held for everything below (pump and render thread). + public readonly object Gate = new(); + public readonly AelrynthBoards Boards = new(); + + /// Hide the replies to RynthAelrynth's own requests (a command typed by hand always shows). + public bool HideOwnReplies = true; + + /// Sends a chat command as if typed (the vault's /mule-data); the plugin sets it (AelrynthPlugin). + public Func SendCommand = _ => false; + + /// The account vault reader. + public readonly VaultFeed Vault; + private long _nextVaultAskMs; + + /// What happened to the last vault read on its way to RynthInventory ("" before one). + public string VaultHandOff = string.Empty; + + public AelrynthFeature() => Vault = new VaultFeed(cmd => SendCommand(cmd)); + + /// Takes over RynthOracle's reply-hiding choice once (default: hidden, as it was there). + public static bool Migrate(ServerPackSettings settings, string oraclePath) => settings.MigrateOnce(MigrationMarker, s => + { + if (ServerPackSettings.ReadBoolFrom(oraclePath, "hideOwnQuestReplies") is bool hide) s.SetBool(SettingHideOwnReplies, hide); + }); + + public void LoadSettings(ServerPackSettings s) => HideOwnReplies = s.GetBool(SettingHideOwnReplies, true); + + public void SaveSettings(ServerPackSettings s) + { + if (s.SetBool(SettingHideOwnReplies, HideOwnReplies)) s.Save(); + } + + /// Login and logout: the boards and the vault are read fresh. + public void Reset() + { + Boards.Clear(); + Vault.Reset(); + _nextVaultAskMs = 0; + VaultHandOff = string.Empty; + } + + /// + /// An incoming chat line on Aelrynth: true when it should be hidden. The vault's data lines (and + /// the unknown-command reply to our own probe) always are; a leaderboard reply to our own request + /// is when HideOwnReplies is on. + /// + public bool OnChatLine(string text, int chatType, long nowMs) + { + if (Vault.ShouldEat(text, chatType)) return true; + return Boards.OnChatLine(text.TrimEnd('\r', '\n'), nowMs, out bool ours) && ours && HideOwnReplies; + } + + /// + /// The vault's timing (plugin tick, on Aelrynth): the first read + /// after login, then every unless the server has no vault. + /// Returns the record to hand to RynthInventory when a read just finished, else null. + /// + public StorageFeedRecord? VaultTick(long nowMs, string account) + { + if (_nextVaultAskMs == 0) _nextVaultAskMs = nowMs + VaultFeed.FirstAskMs; + else if (nowMs >= _nextVaultAskMs && Vault.Status != VaultFeed.State.Unsupported) + { + _nextVaultAskMs = nowMs + VaultFeed.RefreshMs; + Vault.Ask(nowMs); + } + Vault.Tick(nowMs, account); + return Vault.TakeChanged() ? Vault.Record : null; + } + + /// "/rserver vault": a read now (even on a server that said it has none); the next timed one in ten minutes. + public bool VaultAskNow(long nowMs) + { + _nextVaultAskMs = nowMs + VaultFeed.RefreshMs; + return Vault.Ask(nowMs, force: true); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthPages.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthPages.cs new file mode 100644 index 0000000..7745c0c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthPages.cs @@ -0,0 +1,252 @@ +// RynthOracle's Leaderboards tab, Aelrynth's half (Views/BoardsTab.cs), moved here on 2026-10-20 and +// redrawn with ImGui as RynthAelrynth's Leaderboards page: a sub-tab of the Mini Remote's Server +// section while on Aelrynth, and a tab of the /rserver window. +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.ServerPack; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAelrynth; + +/// +/// Aelrynth's /top boards (every board's leader, one board's top 10, your own standings) and the +/// /trial dungeon records. Render thread: draws holding the feature's lock, and queues what it sends. +/// +internal sealed class AelrynthPages +{ + private static readonly Vector4 Gold = new(1.00f, 0.84f, 0.30f, 1f); + private static readonly Vector4 Red = new(0.95f, 0.45f, 0.40f, 1f); + private static readonly Vector4 Selected = new(0.26f, 0.45f, 0.70f, 1f); + + private readonly AelrynthFeature _f; + private readonly Func _active; + private readonly Action _runOnTick; + private readonly Func _send; + private readonly Action _print; + private readonly Action _saveSettings; + private readonly ServerRefreshRow _refresh = new(); + + private int _view; // 0 boards, 1 me, 2 trials + private string _boardArg = ""; + private string _trialArg = ""; + + public AelrynthPages(AelrynthFeature feature, Func active, Action runOnTick, Func send, + Action print, Action saveSettings) + { + _f = feature; + _active = active; + _runOnTick = runOnTick; + _send = send; + _print = print; + _saveSettings = saveSettings; + } + + public ServerPage[] Pages() + { + var list = AelrynthFeature.PageList; + return new[] { new ServerPage(list[0].Id, list[0].Label, list[0].Tooltip, DrawBoards) }; + } + + /// Logout: the next character's status lines start empty. + public void Reset() => _refresh.Reset(); + + private void DrawBoards() + { + if (!_active()) + { + SafeImGui.TextWrapped("This page is for Aelrynth. RynthCore doesn't see this world as Aelrynth " + + "(check RynthCore Options > Diagnostics, or /rserver info)."); + return; + } + lock (_f.Gate) + { + AelrynthBoards a = _f.Boards; + if (Toggle("Boards##ab_v0", _view == 0)) _view = 0; + ImGui.SameLine(); + if (Toggle("Me##ab_v1", _view == 1)) _view = 1; + ImGui.SameLine(); + if (Toggle("Trials##ab_v2", _view == 2)) _view = 2; + _refresh.Draw("ab" + _view, BoardsHelp(), RefreshBoards); + ImGui.Separator(); + if (a.LastError.Length > 0) SafeImGui.TextColored(Red, a.LastError); + + if (_view == 1) DrawMe(a); + else if (_view == 2) DrawTrials(a); + else DrawOverview(a); + + ImGui.Spacing(); + bool hide = _f.HideOwnReplies; + if (ImGui.Checkbox("Hide the replies to RynthAelrynth's own requests##ab_hide", ref hide)) + { + _f.HideOwnReplies = hide; + _runOnTick(_saveSettings); + } + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("/top and /trial when RynthAelrynth sends them. A command you type yourself always shows its reply."); + } + } + + private void DrawMe(AelrynthBoards a) + { + if (ImGui.BeginChild("##ab_me", new Vector2(0f, 300f), ImGuiChildFlags.Borders)) + { + foreach (AelrynthStanding s in a.Standings) + { + SafeImGui.Text(Cut(s.Title, 34)); + ImGui.SameLine(260f); + SafeImGui.Text(s.Rank > 0 ? $"#{s.Rank} of {s.Of}" : "-"); + if (s.Value.Length > 0) { ImGui.SameLine(380f); SafeImGui.Text(s.Value); } + } + if (a.Standings.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); + } + ImGui.EndChild(); + } + + private void DrawTrials(AelrynthBoards a) + { + ImGui.SetNextItemWidth(220f); + ImGui.InputText("Dungeon##ab_trialarg", ref _trialArg, 48); + ImGui.SameLine(); + if (ImGui.SmallButton("Top 10##ab_trialtop") && _trialArg.Trim().Length > 0) Ask(a, isTrial: true, _trialArg); + if (ImGui.BeginChild("##ab_trials", new Vector2(0f, 300f), ImGuiChildFlags.Borders)) + { + int i = 0; + foreach (TrialDungeon d in a.Trials) + { + TrialDungeon row = d; + if (ImGui.Selectable($"{d.Name} ({d.Landblock})##ab_t{i++}")) + { + _trialArg = row.Name; + Ask(a, isTrial: true, row.Name); + } + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Click for this dungeon's top 10."); + ImGui.TextDisabled(" record:"); ImGui.SameLine(90f); SafeImGui.TextWrapped(d.Record); + ImGui.TextDisabled(" you:"); ImGui.SameLine(90f); SafeImGui.Text(d.You); + ImGui.TextDisabled(" this week:"); ImGui.SameLine(90f); SafeImGui.Text(d.Week); + } + foreach (string line in a.TrialLines) if (!line.StartsWith("Trials - ", StringComparison.Ordinal)) SafeImGui.TextWrapped(line); + if (a.TrialBoardTitle.Length > 0) + { + ImGui.SeparatorText(a.TrialBoardTitle); + foreach (BoardRow r in a.TrialRows) + { + SafeImGui.Text($"{r.Rank,2}. {r.Value}"); + ImGui.SameLine(90f); + SafeImGui.Text(Cut(r.Name, 28)); + ImGui.SameLine(300f); + SafeImGui.TextDisabled(Cut(r.Extra, 40)); + } + foreach (string n in a.TrialNotes) SafeImGui.TextWrapped(n); + } + if (a.Trials.Count == 0 && a.TrialBoardTitle.Length == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); + } + ImGui.EndChild(); + } + + private void DrawOverview(AelrynthBoards a) + { + if (ImGui.SmallButton("All boards##ab_all")) Ask(a, isTrial: false, ""); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Sends /top: every board's leader."); + ImGui.SameLine(); + ImGui.SetNextItemWidth(160f); + ImGui.InputText("Board##ab_arg", ref _boardArg, 32); + ImGui.SameLine(); + if (ImGui.SmallButton("Top 10##ab_board") && _boardArg.Trim().Length > 0) Ask(a, isTrial: false, _boardArg); + if (a.OverviewNote.Length > 0) SafeImGui.TextDisabled(a.OverviewNote); + + if (a.BoardTitle.Length > 0) + { + ImGui.SeparatorText($"{a.BoardTitle} ({a.BoardNote})"); + if (a.BoardYou.Length > 0) SafeImGui.TextColored(Gold, a.BoardYou); + if (ImGui.BeginChild("##ab_rows", new Vector2(0f, 300f), ImGuiChildFlags.Borders)) + { + ImGui.TextDisabled("Rank"); ImGui.SameLine(60f); ImGui.TextDisabled("Name"); ImGui.SameLine(280f); ImGui.TextDisabled("Value"); + foreach (BoardRow r in a.BoardRows) + { + SafeImGui.Text(r.Rank.ToString()); + ImGui.SameLine(60f); + if (r.IsYou) SafeImGui.TextColored(Gold, Cut(r.Name, 30)); + else SafeImGui.Text(Cut(r.Name, 30)); + ImGui.SameLine(280f); + SafeImGui.Text(r.Value); + if (r.Extra.Length > 0) { ImGui.SameLine(420f); SafeImGui.TextDisabled(Cut(r.Extra, 40)); } + } + if (a.BoardRows.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); + } + ImGui.EndChild(); + return; + } + if (ImGui.BeginChild("##ab_overview", new Vector2(0f, 300f), ImGuiChildFlags.Borders)) + { + int i = 0; + foreach (AelrynthBoardSummary s in a.Overview) + { + AelrynthBoardSummary row = s; + if (ImGui.Selectable(Cut(s.Title, 30) + "##ab_o" + i++, false, ImGuiSelectableFlags.None, new Vector2(230f, 0f))) + { + _boardArg = row.Key; + Ask(a, isTrial: false, row.Key); + } + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"/top {s.Key}"); + ImGui.SameLine(240f); + SafeImGui.Text(Cut(s.Leader, 24)); + if (s.Value.Length > 0) { ImGui.SameLine(430f); SafeImGui.Text(s.Value); } + } + if (a.Overview.Count == 0) ImGui.TextDisabled("Nothing read yet. Press All boards."); + } + ImGui.EndChild(); + } + + // ── Refresh (RynthOracle's RefreshBar, Aelrynth's part) ───────────── + + private ServerRefreshResult RefreshBoards() + { + AelrynthBoards a = _f.Boards; + string key = _view switch { 1 => "top me", 2 => "trial", _ => "top " + _boardArg }; + if (_refresh.CoolingDown(key, Environment.TickCount64)) return new ServerRefreshResult(ServerRefreshRow.TooSoon); + int before = a.Revision; + string cmd = _view switch + { + 1 => Ask(a, isTrial: false, "me"), + 2 => Ask(a, isTrial: true, ""), + _ => Ask(a, isTrial: false, a.BoardTitle.Length > 0 ? _boardArg : ""), + }; + return new ServerRefreshResult($"Sent {cmd}.", () => a.Revision != before); + } + + private string BoardsHelp() => _view switch + { + 1 => "Sends /top me and reads the reply.", + 2 => "Sends /trial and reads the dungeon list.", + _ => "Sends /top (every board's leader), or asks again for the board that is open.", + }; + + /// + /// "/top [arg]" or "/trial [arg]" on the next tick, marked as RynthAelrynth's own (its reply can + /// be hidden); returns the command. + /// + private string Ask(AelrynthBoards a, bool isTrial, string arg) + { + string cmd = string.IsNullOrWhiteSpace(arg) ? (isTrial ? "/trial" : "/top") : (isTrial ? "/trial " : "/top ") + arg.Trim(); + _runOnTick(() => + { + lock (_f.Gate) + { + if (isTrial) a.RequestTrial(arg, Environment.TickCount64); + else a.RequestTop(arg, Environment.TickCount64); + } + if (!_send(cmd)) _print($"Couldn't send {cmd} (not in the world)."); + }); + return cmd; + } + + private static bool Toggle(string label, bool selected) + { + if (selected) ImGui.PushStyleColor(ImGuiCol.Button, Selected); + bool clicked = ImGui.SmallButton(label); + if (selected) ImGui.PopStyleColor(); + return clicked; + } + + private static string Cut(string s, int max) => s.Length <= max ? s : s.Substring(0, Math.Max(0, max - 3)) + "..."; +} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/VaultFeed.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/VaultFeed.cs new file mode 100644 index 0000000..ea3732e --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/VaultFeed.cs @@ -0,0 +1,239 @@ +// Moved here from RynthInventory (Scanning/VaultFeed.cs) on 2026-10-20: RynthInventory asked every server +// for an Aelrynth vault; now only RynthAelrynth asks, on Aelrynth, and hands the vault to RynthInventory +// through the generic storage feed (Plugins/Shared/StorageFeed.cs). +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Globalization; +using System.Text.Json; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAelrynth; + +/// +/// The Aelrynth account vault (the Aeshnidae.Mule mod): item storage the retail client is never +/// shown, so the only way to see inside is to ask. RynthAelrynth types /mule-data, exactly as a +/// player could, and the server answers one chat line a page: +/// +/// ~ael1 {"t":"mule","ready":true,"page":1,"pages":3,"count":57,"max":1000,"items":[{...}]} +/// +/// (the same "~ael1" lines the Aelrynth Companion reads; only lines whose "t" is "mule" are ours). +/// The pages are collected into one StorageFeedRecord, which RynthAelrynth sends to RynthInventory +/// (StorageFeed): it is kept with the character's storage, so the vault is searched, shown with +/// icons and merged across characters like any other storage; the newest copy wins, and a vault +/// belongs to the account, so every character sees the same one. +/// +/// A server without the command (Aelrynth without the mod, or a world wrongly taken for Aelrynth) +/// is asked once after login; its "Unknown command" reply is eaten and the feed stays quiet. A +/// vault the server says is not ready yet is asked again a few times, and is never recorded as empty. +/// +/// Threads: only queues; everything else runs on the plugin tick. +/// Pure: RynthServerPack.Tests covers it. +/// +internal sealed class VaultFeed +{ + public const string Command = "/mule-data"; + public const string Prefix = "~ael1 "; + public const string Label = "Account vault"; + public const string VaultName = "Aelrynth vault"; + /// After login, before the first /mule-data; then every . + public const long FirstAskMs = 8_000, RefreshMs = 10 * 60_000; + + public enum State { Idle, Asking, Unsupported, Waiting } + + private const long AnswerWindowMs = 15_000, RetryReadyMs = 3_000; + private const int MaxReadyRetries = 6, MaxPages = 80; + private const string UnknownMarker = "\u0001unknown"; + + private readonly Func _send; + private readonly ConcurrentQueue _lines = new(); + + private long _sentAtMs; + private volatile bool _expecting; + private int _readyTries; + private long _retryAtMs; + private readonly List _pages = new(); + private bool _changed; + + public VaultFeed(Func send) => _send = send; + + public State Status { get; private set; } = State.Idle; + /// The vault once a full read finished (null until then). + public StorageFeedRecord? Record { get; private set; } + public int Max { get; private set; } + + /// For /rserver info. + public string Describe() => Status switch + { + State.Unsupported => "no vault on this server", + State.Asking => "reading the vault...", + State.Waiting => "the vault is still loading on the server", + _ => Record == null ? "vault not read yet" : $"vault: {Record.Items.Count} item(s)" + (Max > 0 ? $" of {Max}" : ""), + }; + + /// True once after was replaced. + public bool TakeChanged() { bool c = _changed; _changed = false; return c; } + + /// Login and logout: a fresh read (the record from before is forgotten). + public void Reset() + { + Status = State.Idle; + _expecting = false; + _pages.Clear(); + _readyTries = 0; + Record = null; + _changed = false; + Max = 0; + while (_lines.TryDequeue(out _)) { } + } + + /// Starts a read from page 1, unless one is under way or the server has no vault ( asks anyway). + public bool Ask(long nowMs, bool force = false) + { + if (Status == State.Asking || Status == State.Waiting) return false; + if (Status == State.Unsupported && !force) return false; + _readyTries = 0; + _pages.Clear(); + return SendPage(nowMs, 1); + } + + private bool SendPage(long nowMs, int page) + { + _sentAtMs = nowMs; + Status = State.Asking; + _expecting = true; + if (_send(page <= 1 ? Command : Command + " " + page.ToString(CultureInfo.InvariantCulture))) return true; + _expecting = false; + Status = State.Idle; + return false; + } + + /// + /// True for a line this feed answers, so the caller keeps it out of the chat window. Cheap; any thread. + /// is the line's eChatTypes (-1 = not known). Server lines only: a line + /// in a player's chat type, or one that doesn't start with the marker (a player's copy has their + /// name in front), is left alone, so nobody can feed the vault view or hide chat by typing "~ael1". + /// + public bool ShouldEat(string? text, int chatType = -1) + { + if (string.IsNullOrEmpty(text) || ChatSource.IsPlayerAuthored(chatType)) return false; + int at = ChatSource.ContentStart(text); + if (ChatSource.StartsWithMarker(text, Prefix)) + { + // Only our own kind: another plugin's ~ael1 line (the Companion's) stays visible to it. + if (text.IndexOf("\"t\":\"mule\"", at, StringComparison.Ordinal) < 0) return false; + _lines.Enqueue(text.Substring(at + Prefix.Length)); + return true; + } + // The reply of a server that has no such command: swallowed only while we wait for one. + if (_expecting && IsUnknownCommandReply(text)) + { + _lines.Enqueue(UnknownMarker); + return true; + } + return false; + } + + /// ACE's "Unknown command: mule-data" (GameActionTalk names the bare command; a leading / or @ is allowed). + private static bool IsUnknownCommandReply(string text) + { + const string marker = "Unknown command:"; + if (!ChatSource.StartsWithMarker(text, marker, StringComparison.OrdinalIgnoreCase)) return false; + string named = text.Substring(ChatSource.ContentStart(text) + marker.Length).Trim().TrimStart('/', '@'); + return string.Equals(named, "mule-data", StringComparison.OrdinalIgnoreCase); + } + + /// Applies what arrived and decides what to send next. Plugin tick. + public void Tick(long nowMs, string account) + { + while (_lines.TryDequeue(out string? line)) Apply(line, nowMs, account); + + if (Status == State.Waiting && nowMs >= _retryAtMs) SendPage(nowMs, 1); + else if (Status == State.Asking && nowMs - _sentAtMs > AnswerWindowMs) + { + // Nothing came back: a server without the mod, or a lost line. The next refresh retries. + _expecting = false; + Status = State.Idle; + _pages.Clear(); + } + } + + private void Apply(string line, long nowMs, string account) + { + if (line == UnknownMarker) + { + if (Status == State.Asking) { _expecting = false; Status = State.Unsupported; _pages.Clear(); } + return; + } + if (Status != State.Asking) return; // a line we did not ask for (typed by hand, say) + _expecting = false; + + try + { + using JsonDocument doc = JsonDocument.Parse(line); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) { Status = State.Idle; return; } + + if (!(root.TryGetProperty("ready", out JsonElement ready) && ready.ValueKind == JsonValueKind.True)) + { + string why = Str(root, "why"); + if (why == "loading" && ++_readyTries <= MaxReadyRetries) { Status = State.Waiting; _retryAtMs = nowMs + RetryReadyMs; } + else Status = State.Idle; // closed / fault / error: try again at the next refresh + _pages.Clear(); + return; + } + + int page = Int(root, "page", 1), pages = Math.Min(Math.Max(Int(root, "pages", 1), 1), MaxPages); + Max = Int(root, "max", Max); + int count = Int(root, "count", 0); + if (page == 1) _pages.Clear(); + if (root.TryGetProperty("items", out JsonElement items) && items.ValueKind == JsonValueKind.Array) + foreach (JsonElement e in items.EnumerateArray()) + if (e.ValueKind == JsonValueKind.Object) _pages.Add(Item(e)); + + if (page < pages) { SendPage(nowMs, page + 1); return; } + + // Last page. A total that disagrees with what was read means the vault changed under + // the read (a deposit between pages): keep the old copy and read again shortly. + if (count != _pages.Count && _readyTries++ < MaxReadyRetries) + { + Status = State.Waiting; _retryAtMs = nowMs + RetryReadyMs; _pages.Clear(); return; + } + Record = new StorageFeedRecord(VaultId(account), VaultName, Label, new List(_pages)); + _pages.Clear(); + _changed = true; + Status = State.Idle; + } + catch (JsonException) + { + Status = State.Idle; + _pages.Clear(); + } + } + + private static StorageFeedItem Item(JsonElement e) => new( + UInt(e, "o"), UInt(e, "w"), Str(e, "n"), UInt(e, "i"), UInt(e, "u"), UInt(e, "v"), + Math.Max(1, Int(e, "s", 1)), Int(e, "m", 0), UInt(e, "y")); + + /// + /// A stand-in container id for the account's vault. Storage is merged by (server, id) with the + /// newest copy winning, so the same id on every character of the account shows ONE vault. It is + /// in the top of the id space, where no object the client has seen lives (StorageFeed.IsStandInId). + /// The same formula as RynthInventory used, so vaults saved before the move are replaced, not doubled. + /// + public static uint VaultId(string account) + { + uint h = 2166136261u; + foreach (char c in (account ?? "").Trim().ToLowerInvariant()) { h ^= c; h *= 16777619u; } + return 0xFF000000u | (h & 0x00FFFFFFu); + } + + private static int Int(JsonElement e, string name, int fallback) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback; + + private static uint UInt(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetUInt32(out uint u) ? u : 0u; + + private static string Str(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; +} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/AelrynthPlugin.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/AelrynthPlugin.cs new file mode 100644 index 0000000..c824cd3 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/AelrynthPlugin.cs @@ -0,0 +1,143 @@ +// AelrynthPlugin.cs - RynthAelrynth's own features, through the shared server plugin's hooks +// (Plugins/Shared/ServerPack/ServerPackPlugin.cs). Aelrynth-specific code that RynthOracle and +// RynthInventory used to carry lives here since 2026-10-20 (Aelrynth/AelrynthFeature.cs says what), +// so a player without RynthAelrynth gets none of it, and no other server is asked for a vault. +// Since 2026-10-21 it also publishes the difficulty tier where the player stands (AelrynthDifficulty.cs), +// which RynthAi used to read itself (RynthAi reads the published values, knowing no server). +using System; +using System.IO; +using RynthCore.Plugin.RynthAelrynth; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.ServerPack; + +public sealed partial class ServerPackPlugin +{ + private readonly AelrynthFeature _aelrynth = new(); + private readonly AelrynthDifficulty _difficulty = new(); + private Func? _readDifficultyTier; + private AelrynthPages? _aelrynthPages; + // The last vault read, until RynthInventory took it (it may load after the read). + private StorageFeedRecord? _vaultToHandOff; + private long _nextVaultHandOffMs; + private const long VaultHandOffRetryMs = 30_000; + + /// Where RynthOracle kept the reply-hiding choice before it moved here (read once). + internal static string OracleSettingsPath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json"); + + partial void ServerPages(System.Collections.Generic.List pages) + { + _aelrynthPages = new AelrynthPages(_aelrynth, () => Active, RunOnTick, Send, + text => ChatLine($"[{RynthPluginInfo.Name}] {text}"), SaveAelrynthSettings); + pages.AddRange(_aelrynthPages.Pages()); + } + + partial void ServerCommandVerbs(System.Collections.Generic.List verbs) => verbs.Add("vault"); + + partial void ServerInitialize() + { + _aelrynth.SendCommand = Send; + if (AelrynthFeature.Migrate(Settings, OracleSettingsPath)) + LogTagged("Took over RynthOracle's reply-hiding choice from rynthoracle.json."); + lock (_aelrynth.Gate) _aelrynth.LoadSettings(Settings); + } + + private void SaveAelrynthSettings() + { + lock (_aelrynth.Gate) _aelrynth.SaveSettings(Settings); + } + + partial void ServerLoginComplete() + { + _difficulty.Reset(); + lock (_aelrynth.Gate) _aelrynth.Reset(); + _vaultToHandOff = null; + _aelrynthPages?.Reset(); + } + + partial void ServerLogout() + { + _difficulty.Reset(); + lock (_aelrynth.Gate) _aelrynth.Reset(); + _vaultToHandOff = null; + _aelrynthPages?.Reset(); + } + + partial void ServerShutdown() => SaveAelrynthSettings(); + + partial void ServerChatText(string text, int chatType, ref bool eat) + { + if (!Active) return; + bool hide; + lock (_aelrynth.Gate) hide = _aelrynth.OnChatLine(text, chatType, Environment.TickCount64); + if (hide) eat = true; + } + + partial void ServerTick(bool active) + { + long now = Environment.TickCount64; + _difficulty.Tick(now, active, _readDifficultyTier ??= ReadDifficultyTier, ProfileValues); + if (!active || !Host.HasInvokeChatParser) return; + uint player = Host.HasGetPlayerId ? Host.GetPlayerId() : 0; + if (player == 0) return; // the vault belongs to the account; wait for the character + string account = Host.TryGetAccountName(out string a) && a.Trim().Length > 0 ? a.Trim() : "unknown"; + StorageFeedRecord? read; + lock (_aelrynth.Gate) read = _aelrynth.VaultTick(now, account); + if (read != null) { _vaultToHandOff = read; _nextVaultHandOffMs = 0; } + if (_vaultToHandOff != null && now >= _nextVaultHandOffMs) HandOffVault(now); + } + + /// The player's PropertyInt 9051 (Aelrynth's difficulty tier where they stand), null when it isn't there. + private int? ReadDifficultyTier() + { + uint player = Host.HasGetPlayerId ? Host.GetPlayerId() : 0; + return player != 0 && Host.HasGetObjectIntProperty + && Host.TryGetObjectIntProperty(player, AelrynthDifficulty.TierProperty, out int tier) ? tier : null; + } + + /// + /// The vault to RynthInventory (StorageFeed), which files it with the character's storage. Kept and + /// offered again now and then while RynthInventory isn't there to take it. + /// + private void HandOffVault(long now) + { + StorageFeedRecord? vault = _vaultToHandOff; + if (vault == null) return; + bool taken = Host.HasSendPluginCommand + && Host.SendPluginCommand(StorageFeed.TargetPlugin, StorageFeed.Action, StorageFeed.ToJson(vault)); + string note = taken + ? $"{vault.Items.Count} item(s) handed to RynthInventory at {DateTime.Now:HH:mm}" + : "RynthInventory isn't loaded (or is too old), so the vault isn't in Global Inventory"; + lock (_aelrynth.Gate) _aelrynth.VaultHandOff = note; + if (taken) _vaultToHandOff = null; + else _nextVaultHandOffMs = now + VaultHandOffRetryMs; + } + + partial void ServerChatCommand(string[] parts, ref bool handled) + { + if (parts.Length < 2 || !parts[1].Equals("vault", StringComparison.OrdinalIgnoreCase)) return; + handled = true; + string tag = $"[{RynthPluginInfo.Name}] "; + if (!Active) { ChatLine(tag + "The account vault is Aelrynth's; RynthCore doesn't see this world as Aelrynth."); return; } + bool asked; + string state; + lock (_aelrynth.Gate) + { + asked = _aelrynth.VaultAskNow(Environment.TickCount64); + state = _aelrynth.Vault.Describe(); + } + ChatLine(tag + (asked ? "Reading the account vault (/mule-data)..." : "The vault is already being read: " + state)); + } + + partial void ServerInfoLines(Action line) + { + line(_difficulty.Describe()); + lock (_aelrynth.Gate) + { + string handOff = _aelrynth.VaultHandOff.Length > 0 ? "; " + _aelrynth.VaultHandOff : ""; + line("Account vault: " + _aelrynth.Vault.Describe() + handOff + " (/rserver vault reads it now)."); + line("Own replies (/top, /trial) " + (_aelrynth.HideOwnReplies ? "hidden" : "shown") + "."); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/Resources/quests.aelrynth.csv b/Plugins/RynthCore.Plugin.RynthAelrynth/Resources/quests.aelrynth.csv new file mode 100644 index 0000000..61bf90c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/Resources/quests.aelrynth.csv @@ -0,0 +1,4278 @@ +QuestFlag,Server,Quest,Url,Info,Hint,Repeatable,MinDelta,MaxSolves,Source,NotOnServer +30minattributes,Aelrynth,,,30 Minutes to pick up Attribute Gems,,TRUE,1800,-1,set by Chafulumisa, +50to11brokercontractsa,Aelrynth,,,Tracks which quests have been completed for Contract Brokers quest,,TRUE,0,2097151,, +50to11brokercontractsb,Aelrynth,,,Tracks which quests have been completed for Contract Brokers quest,,TRUE,0,1048575,, +50to11contractscomplete_0511,Aelrynth,,,Complete contracts from the Contract Brokers for extra rewards,,FALSE,0,1,"set by Abd-al-Matin Basshir, Gawain Cooper, Giancarlo De Luca and 1 more", +abandonednuhmudira,Aelrynth,,,Player left Nuhmudira to her fate.,,FALSE,0,1,set by Lever, +abayarresearchnotes,Aelrynth,,,Abayar's Research Notes (Fiun Spell Casting Gloves),,TRUE,72000,-1,, +abductedcompleted_0313,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Virindi Delegate, +abhorrenteaterjaw,Aelrynth,,,Abhorrent Eater Jaw,,TRUE,72000,-1,checked by Clemenza, +abyssaltotemgatewayflag,Aelrynth,,,Player has access to Abyssal Totem Gateway,,FALSE,0,1,set by Abyssal Totem Gateway, +academeyexittokengiven,Aelrynth,,,Recived the Acadmey Exit Token,,FALSE,0,1,set by Jonathan, +academytokengiven,Aelrynth,,,Turned over the Academy Token,,FALSE,0,1,"set by Guard, Training Master", +accessatlanslaboratory,Aelrynth,,,Access granted to the Atlan's Laboratory,,FALSE,0,1,"set by Ciandra, Arcanum Alchemist", +accessboss10x,Aelrynth,,,Win Colo 10 Times,,FALSE,0,1,set by Master Arbitrator, +accessboss18,Aelrynth,,,Player completed Colo,,FALSE,0,1,set by Return to the Hall of Champions, +accessboss3,Aelrynth,,,Player entered Arena 3,,FALSE,0,1,set by Arena 3, +accessboss5,Aelrynth,,,Player entered Arena 5,,FALSE,0,1,set by Arena 5, +accessboss7,Aelrynth,,,Player entered Arena 7,,FALSE,0,1,set by Arena 7, +accessboss8,Aelrynth,,,Player entered Arena 8,,FALSE,0,1,set by Arena 8, +accessempyreanworkshop,Aelrynth,,,Flagging for access to the Empyrean Workshop,,FALSE,0,1,"set by Ciandra, Arcanum Alchemist", +accessrossumortachapterhouse,Aelrynth,,,Access granted to the Rossu Morta Chapterhouse,,FALSE,0,1,set by Melaverre, +accessruschkburialmound,Aelrynth,,,Access granted to Ruschk Burial Mound,,FALSE,0,1,set by Lydda, +accesssclavusumbralforge,Aelrynth,,,Access granted to Sclavus Umbral Forge,,FALSE,0,1,set by Giordonni, +accesssilyunchapterhouse,Aelrynth,,,Access granted to the Silyun Chapterhouse,,FALSE,0,1,set by Hashina, +accesswhisperingbladechapterhouse,Aelrynth,,,Access granted to the Whispering Blade Chapterhouse,,FALSE,0,1,set by Harkwull the Discreet, +acidaxeturnedin,Aelrynth,,,Turned Acid Axe into Ivory Crafter.,,TRUE,72000,-1,"set by Ivory Crafter, Ulna bint-Fasha the Ivory Crafter", +acidzenithdead,Aelrynth,,,quest timer,,FALSE,0,1,set by Acid Zenith, +acolyteherrenskey_pickup,Aelrynth,,,Player has picked up Acolyte Herrens Key,,TRUE,72000,-1,, +aelrynthcitadelbelowcrestpickup,Aelrynth,,,You may take another of Kazrok's crests in %tqt.,,TRUE,86400,-1,, +aelrynthcitadelbelowwarlord,Aelrynth,,,Warlord Kazrok's helm crest handed to Ysolde Varn in the Hub of Awakening,,TRUE,86400,-1,set by Ysolde Varn, +aerbaxchestkey1pickup,Aelrynth,,,Picked up the first Aerbax Key.,,TRUE,432000,-1,, +aerbaxchestkey2pickup,Aelrynth,,,Picked up the second Aerbax Key.,,TRUE,432000,-1,, +aerbaxcitadelfellowstart,Aelrynth,,,Fellow has started Aerbax Citadel,,TRUE,3600,-1,set by Emissary of Asheron, +aerbaxcitadelrewards1,Aelrynth,,,Player has received the Empowered Helm of the Perfect Light,,FALSE,0,1,set by Emissary of Asheron, +aerbaxcitadelrewards2,Aelrynth,,,Player has received the Empowered Girth of the Perfect Light,,FALSE,0,1,set by Emissary of Asheron, +aerbaxcitadelrewards3,Aelrynth,,,Player has received the Empowered Greaves of the Perfect Light,,FALSE,0,1,set by Emissary of Asheron, +aerbaxcompletedwait,Aelrynth,,,Players wait time to receive rewards for Aerbax Citadel,,TRUE,72000,-1,set by Emissary of Asheron, +aerbaxmaskshardpickuptimer,Aelrynth,,,Picked up Aerbax Mask Shard,,TRUE,72000,-1,, +aerbaxplatformaccess,Aelrynth,,,Player has started Aerbax Citadel,,TRUE,3600,-1,set by Harmonic Transference Field, +aerbaxshadowdefeated,Aelrynth,,,Fellow has killed Aerbax,,FALSE,0,1,checked by Emissary of Asheron, +aerbaxshadowdefeatedrepeat,Aelrynth,,,Player has already killed Aerbax before,,FALSE,0,1,set by Emissary of Asheron, +aerbaxsprodigalbanderling_fellow,Aelrynth,,,Fellow flag for Aerbaxs Prodigal Banderling Quest,,FALSE,0,1,set by Chief Taraash, +aerbaxsprodigalbanderling_start,Aelrynth,,,Player has started Aerbaxs Prodigal Banderling Quest,,FALSE,0,1,set by Guard Winterborn, +aerbaxsprodigalbanderling_wait,Aelrynth,,,Player has completed Aerbaxs Prodigal Banderling Quest,,TRUE,72000,-1,set by Guard Winterborn, +aerbaxsprodigallugian_flag,Aelrynth,,,Player is flagged for Prodigal Lugian portion of lockbox,,FALSE,0,1,set by Lord Kresovus, +aerbaxsprodigallugian_repeat,Aelrynth,,,Player has completed Prodigal Lugian at least once,,FALSE,0,1,set by Lord Kresovus, +aerbaxsprodigallugian_start,Aelrynth,,,Player has started Aerbaxs Prodigal Lugian.,,FALSE,0,1,set by Oswent the Pale, +aerbaxsprodigallugian_wait,Aelrynth,,,Wait timer for Aerbaxs Prodigal Lugian,,TRUE,72000,-1,set by Lord Kresovus, +aerbaxsprodigalmosswartcompleted,Aelrynth,,,Player wait timer for Aerbaxs Prodigal Mosswart Quest.,,TRUE,72000,-1,set by Sergeant Brigitta, +aerbaxsprodigalmosswartrepeat,Aelrynth,,,Player has completed Aerbaxs Prodigal Mosswart Quest at least once.,,FALSE,0,1,set by Sergeant Brigitta, +aerbaxsprodigalmosswartstarted,Aelrynth,,,Player has started Aerbaxs Prodigal Mosswart Quest.,,FALSE,0,1,set by Sergeant Brigitta, +aerbaxsprodigaltumerokrepeat,Aelrynth,,,Repeating Aerbaxs Prodigal Tumerok quest,,FALSE,0,1,set by Nomea ibn Makar, +aerbaxsprodigaltumerokstart,Aelrynth,,,Started Aerbaxs Prodigal Tumerok quest,,FALSE,0,1,set by Nomea ibn Makar, +aerbaxsprodigaltumerokwait,Aelrynth,,,Finished Aerbaxs Prodigal Tumerok quest,,TRUE,1728000,-1,set by Nomea ibn Makar, +aercyno,Aelrynth,,,Aerlinthe Cynosure,,TRUE,72000,-1,, +aerfallecharmpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +aerfalleembossedtokenpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +aerfalleornatetokenpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +aerfallerewardgiverinprogress,Aelrynth,,,Ghost of Galaeral Spawned,,TRUE,300,-1,set by Ghost of Galaeral, +aerfallestaffobtained,Aelrynth,,,Staff of Aerfalle,,TRUE,72000,-1,, +aerfalletokenpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +aerlinthebellows,Aelrynth,,,Aerlinthe Bellows Found,,TRUE,72000,-1,set by Smithing Golem, +aerlinthesluice,Aelrynth,,,Aerlinthe Magma Sluice Found,,TRUE,72000,-1,"set by Construction Golem, Repair Golem", +aetheriumcorefragmentpickuptimer,Aelrynth,,,Pickup timer for Aetherium Core Fragment,,TRUE,72000,-1,, +aetheriumraidshighcompleted_0210,Aelrynth,,,Turned in a Bright Aetherium Ore Fragment,,TRUE,72000,-1,set by Sir Durnstad, +aetheriumraidshighstarted_0210,Aelrynth,,,Aetherium Raid High Started,,FALSE,0,1,set by Sir Durnstad, +aetheriumraidslowcompleted,Aelrynth,,,Turned in a Dull Aetherium Ore Fragment,,TRUE,72000,-1,set by Sir Oakley, +aetheriumraidslowstarted,Aelrynth,,,Aetherium Raid Low Started,,FALSE,0,1,set by Sir Oakley, +aggregateshardpickup,Aelrynth,,,Picked up Aggregate Crystalline Shard,,TRUE,72000,-1,, +allowbalorrobe,Aelrynth,,,Player is flagged to have Yi Yo-Jin create Balors robe,,FALSE,0,1,set by Lord Kresovus, +altarnest_flag,Aelrynth,,,Access granted to the Altar Nest portal,,FALSE,0,1,set by Varlanna, +altereddrudgekillcount,Aelrynth,,,Altered Drudge Kill Counter,,TRUE,0,40,, +altereddrudgekilltask,Aelrynth,,,Altered Drudge Kill Task,,TRUE,72000,-1,, +ameliatoysfound,Aelrynth,,,Toys Found Bitfield,,TRUE,0,63,, +ameliatoysinprogress,Aelrynth,,,Flags a player while they are active in the Amelia Toys quest,,TRUE,3600,-1,set by Amelia, +ameliatoysturnedincount,Aelrynth,,,Keeps track of how many toys a player has turned in to Amelia,,TRUE,0,63,, +ameliatoyswait,Aelrynth,,,Timer for repeating the Amelia Lost Toys quest,,TRUE,72000,-1,set by Amelia, +ancientbone_pickup,Aelrynth,,,Player has picked up the Ancient Bone.,,TRUE,72000,-1,, +ancientcrestpickup,Aelrynth,,,Picked up an Ancient Crest.,,TRUE,72000,-1,, +ancientdiscoveries,Aelrynth,,,Dericost Ruin Quest - Reward Item Pickup Timer,,TRUE,72000,-1,, +ancientemblemofmhoireturnin,Aelrynth,,,Player has turned in a Ancient Emblem of Mhoire to the Arcanum Mana-smith,,TRUE,1209600,-1,set by Arcanum Mana-smith, +ancientfalatacotsymbolpickup,Aelrynth,,,Picked up Ancient Falatacot Symbol in Foundry of Izexi.,,TRUE,72000,-1,, +ancientgobletcompleted,Aelrynth,,,You have turned in the correct Ancient Goblet.,,TRUE,72000,-1,set by Portal Servitor, +ancientgobletpickup,Aelrynth,,,You have picked up an Ancient Goblet.,,TRUE,1800,-1,, +ancientnecklacecompleted,Aelrynth,,,You have turned in the correct Ancient Necklace.,,TRUE,72000,-1,set by Portal Servitor, +ancientnecklacepickup,Aelrynth,,,You have picked up an Ancient Necklace.,,TRUE,1800,-1,, +ancientringcompleted,Aelrynth,,,You have turned in the correct Ancient Ring.,,TRUE,72000,-1,set by Portal Servitor, +ancientringpickup,Aelrynth,,,You have picked up an Ancient Ring.,,TRUE,1800,-1,, +andrilosaccused,Aelrynth,,,Andrilos shown sketch first time,,FALSE,0,1,set by Andrilos, +andriloslives,Aelrynth,,,Andrilos allowed to live,,FALSE,0,1,set by Andrilos, +andriloslivesextraxp,Aelrynth,,,Player let Andrilos Live,,FALSE,0,1,set by Fiun Layeel, +andriloslivesextraxpwait,Aelrynth,,,Extra XP for letting Andrilos Live Wait Timer,,TRUE,72000,-1,set by Fiun Layeel, +andrilosshownsketch,Aelrynth,,,Andrilos shown the sketch,,FALSE,0,1,set by Andrilos, +anekshaycrystalcollectionstart,Aelrynth,,,anekshay crystal collection start,,TRUE,0,20,, +anekshaycrystalcollectionwait,Aelrynth,,,anekshay crystal collection wait,,TRUE,72000,-1,, +anekshaygemofknowledgecollectedinamonth,Aelrynth,Amount of Anekshay Gem of Knowledges player has turned in within a 30 day period.,,Amount of A'nekshay Gem of Knowledges player has turned in within a 30 day period.,Amount of A'nekshay Gem of Knowledges player has turned in within a 30 day period.,TRUE,0,10,"set by Agent Dravos, Agent of the Arcanum", +anekshaygemofknowledgetimer_monthly,Aelrynth,Monthly timer for turning in up to 10 Anekshay Gem of Knowledges.,,Monthly timer for turning in up to 10 A'nekshay Gem of Knowledges.,Monthly timer for turning in up to 10 A'nekshay Gem of Knowledges.,TRUE,2592000,-1,"set by Agent Dravos, Agent of the Arcanum", +anekshaygemoflesserknowledgecollectedinamonth,Aelrynth,Amount of Anekshay Gems of Lesser Knowledge player has turned in within a 30 day period.,,Amount of A'nekshay Gems of Lesser Knowledge player has turned in within a 30 day period.,Amount of A'nekshay Gems of Lesser Knowledge player has turned in within a 30 day period.,TRUE,0,10,"set by Agent Dravos, Agent of the Arcanum", +anekshaygemoflesserknowledgetimer_monthly,Aelrynth,,,Monthly timer for turning in up to 10 A'nekshay Gems of Lesser Knowledge.,,TRUE,2592000,-1,"set by Agent Dravos, Agent of the Arcanum", +anekshayluminancecertificatecollectedinamonth,Aelrynth,Amount of Anekshay Luminance Certificates player has turned in within a 30 day period.,,Amount of A'nekshay Luminance Certificates player has turned in within a 30 day period.,Amount of A'nekshay Luminance Certificates player has turned in within a 30 day period.,TRUE,0,10,"set by Agent Dravos, Agent of the Arcanum", +anekshayluminancecertificatetimer_monthly,Aelrynth,Monthly timer for turning in up to 10 Anekshay Luminance Certificates.,,Monthly timer for turning in up to 10 A'nekshay Luminance Certificates.,Monthly timer for turning in up to 10 A'nekshay Luminance Certificates.,TRUE,2592000,-1,"set by Agent Dravos, Agent of the Arcanum", +angersplinterpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +antiqueplatterquest,Aelrynth,,,Retreive Worcer's Antique Platter,,TRUE,72000,-1,, +apostatebrokenmaskpickuptimer,Aelrynth,,,Timer for mask pick up,,TRUE,72000,-1,, +apostatefinalecompleted_0910,Aelrynth,,,Apostate Finale timer,,TRUE,72000,-1,set by Emissary of Asheron, +apostatefinalemaskshardpickup,Aelrynth,,,Picked up Apostate Grand Director mask shard,,TRUE,72000,-1,, +apostatefinalestarted_0910,Aelrynth,,,Apostate Finale Started,,FALSE,0,1,set by Emissary of Asheron, +apostatemessageshardpickedup,Aelrynth,,,You have obtained an Apostate Message Shard.,,TRUE,72000,-1,, +apostatenexusflag,Aelrynth,,,Player flagged to enter Apostate Nexus,,FALSE,0,1,set by Ned the Clever, +apostateoverseermaskpickedup,Aelrynth,,,You have obtained a Apostate Overseer Mask.,,TRUE,72000,-1,, +applicationgiven,Aelrynth,,,Turned over the Application Form,,FALSE,0,1,set by Greeter, +arantahboon1,Aelrynth,,,Give Hea Arantah CurseObject1,,TRUE,72000,-1,set by Hea Arantah, +arantahboon2,Aelrynth,,,Give Hea Arantah CurseObject2,,TRUE,72000,-1,set by Hea Arantah, +arantahboon3,Aelrynth,,,Give Hea Arantah CurseObject3,,TRUE,72000,-1,set by Hea Arantah, +arantahboon4,Aelrynth,,,Give Hea Arantah CurseObject4,,TRUE,72000,-1,set by Hea Arantah, +arantahboon5,Aelrynth,,,Give Hea Arantah CurseObject5,,TRUE,72000,-1,set by Hea Arantah, +arantahkill1,Aelrynth,Hunting Aun Ralirea,https://acportalstorm.com/wiki/Hunting_Aun_Ralirea,Give Clay Figurine to Hea Arantah.,PERMANENT - Give Hea Arantah FigurineRalirea,FALSE,0,1,set by Hea Arantah, +arbitratoregggivencomplete,Aelrynth,,,Flagged to locked door inside Colosseum,,FALSE,0,1,set by Master Arbitrator, +arbitratorpackcowgivencomplete,Aelrynth,,,Flagged to use Mad Cow Portal,,FALSE,0,1,set by Master Arbitrator, +arcanumalchemistspoken1,Aelrynth,,,Player has spoken to the Arcanum Alchemist the first time.,,FALSE,0,1,, +arcanumalchemistspoken2,Aelrynth,,,Player has spoken to the Arcanum Alchemist the second time.,,FALSE,0,1,, +arcanumalchemistspoken3,Aelrynth,,,Player has completed the Isparian Arms quest and is starting again.,,FALSE,0,1,, +arcanumfurniturepermission,Aelrynth,,,Writ Nov Quest 3,,TRUE,72000,-1,set by Arcanum Envoy, +arcanumresearchbypass,Aelrynth,,,Player may enter the research facility.,,FALSE,0,1,, +arcticmattekarkillcount,Aelrynth,,,Arctic Mattekar Kill Counter,,TRUE,0,25,set by Enzo Ilario, +arcticmattekarkilltask,Aelrynth,,,Arctic Mattekar Kill Task,,TRUE,72000,-1,set by Enzo Ilario, +areacacademycomplete,Aelrynth,,,Player has finished the last area of the Training Academy.,,FALSE,0,1,set by Sentry, +arikasspoken,Aelrynth,,,Spoken to Arikas,,FALSE,0,1,"set by Arikas, Warden of Knorr", +armoredillohuntingneftetkillcount,Aelrynth,,,Armoredillo Hunting Neftet Kill Counter,,TRUE,0,30,, +armoredillohuntingneftetkilltask,Aelrynth,,,Armoredillo Hunting Neftet Kill Task,,TRUE,72000,-1,, +armoredillokeypickedup,Aelrynth,,,Armoredillo Key Pick Up timer,,TRUE,72000,-1,, +armorofdarknesspickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +artscraftsalchemyhigh,Aelrynth,,,Player has turned in high alchemy item.,,TRUE,72000,-1,, +artscraftsalchemylow,Aelrynth,,,Player has turned in low alchemy item.,,TRUE,72000,-1,, +artscraftsalchemymid,Aelrynth,,,Player has turned in mid alchemy item.,,TRUE,72000,-1,, +artscraftsalchemyproportional,Aelrynth,,,Player has turned in extreme alchemy item.,,TRUE,72000,-1,, +artscraftscookinghigh,Aelrynth,,,Player has turned in high Cooking item.,,TRUE,72000,-1,, +artscraftscookinglow,Aelrynth,,,Player has turned in low Cooking item.,,TRUE,72000,-1,, +artscraftscookingmid,Aelrynth,,,Player has turned in mid Cooking item.,,TRUE,72000,-1,, +artscraftscookingproportional,Aelrynth,,,Player has turned in extreme Cooking item.,,TRUE,72000,-1,, +artscraftsfletchinghigh,Aelrynth,,,Player has turned in high Fletching item.,,TRUE,72000,-1,, +artscraftsfletchinglow,Aelrynth,,,Player has turned in low Fletching item.,,TRUE,72000,-1,, +artscraftsfletchingmid,Aelrynth,,,Player has turned in mid Fletching item.,,TRUE,72000,-1,, +artscraftsfletchingproportional,Aelrynth,,,Player has turned in extreme Fletching item.,,TRUE,72000,-1,, +ashbaneextremeturnedin,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Leikotha, +ashbaneturnedin,Aelrynth,,,Gave Ashbane to Leikotha.,,TRUE,72000,-1,set by Leikotha, +ashbaneuberturnedin,Aelrynth,,,Gave Superior Ashbane to Leikotha.,,TRUE,72000,-1,set by Leikotha, +asheronemissaryspoken1,Aelrynth,,,Player has visited and conversed with the Emissary after talking to the Arcanum Alchemist.,,FALSE,0,1,, +asheronemissaryspoken2,Aelrynth,,,Player has visited and conversed with the Emissary after talking to the Arcanum Alchemist a swcond time.,,FALSE,0,1,, +asheroninvasionspoken,Aelrynth,,,You have spoken to the Almighty Asheron!,,FALSE,0,1,set by Asheron, +asheronsdeparturejournal,Aelrynth,,,You have turned in Asheron's Depature Journal.,,TRUE,72000,-1,set by Shan Zhen, +askedlacarrafirst,Aelrynth,,,Spoke to Lacarra First,,FALSE,0,1,set by Lacarra Avanthi, +askedzhofirst,Aelrynth,,,Spoke to Zho First,,FALSE,0,1,set by Zho Heishan, +assassinshideout_flag,Aelrynth,,,Access granted to the Assassins Hideout,,FALSE,0,1,set by Barsinni, +assaultvaultaccessgranted0105,Aelrynth,,,You have obtained access to the Royal Sewers!,,TRUE,72000,-1,"set by Phantom, Poltergeist, Restless Spirit and 1 more", +asteliarygem,Aelrynth,,,Asteliary Gem,,TRUE,72000,-1,, +atamarrbronze,Aelrynth,,,Atamarr Bronze Knight flag,,FALSE,0,1,set by Atamarr, +atamarrbronzedone,Aelrynth,,,Atamarr Bronze Cog Knight flag complete,,FALSE,0,1,set by Bronze Gauntlet Knight-Commander, +atamarrcopper,Aelrynth,,,Atamarr Copper Cog Craftmaster flag,,FALSE,0,1,set by Atamarr, +atamarrcopperdone,Aelrynth,,,Atamarr Copper Cog Craftmaster flag complete,,FALSE,0,1,set by Copper Cog Craftsmaster, +atamarrdone,Aelrynth,,,Completed an Atamarr task,,TRUE,72000,-1,set by Atamarr, +atamarriron,Aelrynth,,,AtamarrIron flag,,FALSE,0,1,set by Atamarr, +atamarrirondone,Aelrynth,,,AtamarrIronDone flag complete,,FALSE,0,1,set by Iron Blade Warmaster, +atamarrquest,Aelrynth,,,AtamarrQuest flag,,FALSE,0,1,set by Atamarr, +atamarrsilver,Aelrynth,,,AtamarrSilver flag,,FALSE,0,1,set by Atamarr, +atamarrsilverdone,Aelrynth,,,AtamarrSilverDone flag complete,,FALSE,0,1,set by Silver Scope Spymaster, +atlatlstatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +attribute13days,Aelrynth,,,2 week attribute forgetfulness timer.,,TRUE,1123200,-1,"set by Warden of Lowering Coordination, Warden of Lowering Endurance, Warden of Lowering Focus and 3 more", +attribute6days,Aelrynth,,,1 week attribute forgetfulness timer.,,TRUE,518400,-1,"set by Warden of Lowering Coordination, Warden of Lowering Endurance, Warden of Lowering Focus and 3 more", +attributegems1,Aelrynth,Attribute and Skill Redistribution,https://acportalstorm.com/wiki/Attribute_and_Skill_Redistribution,Attribute gems received counter. See Warden of Lowering Endurance; Warden of Lowering Coordination; Warden of Lowering Strength (among others).,Attribute gems received counter,TRUE,0,7,"set by Warden of Lowering Coordination, Warden of Lowering Endurance, Warden of Lowering Focus and 3 more", +attributegems2,Aelrynth,,,Second attribute gems received counter,,TRUE,0,8,"set by Warden of Lowering Coordination, Warden of Lowering Endurance, Warden of Lowering Focus and 3 more", +attributegems3,Aelrynth,,,Third attribute gems received counter,,TRUE,0,9999999,"set by Warden of Lowering Coordination, Warden of Lowering Endurance, Warden of Lowering Focus and 3 more", +attributeloweringgempickedup,Aelrynth,,,Picked up an attribute lowering gem.,,TRUE,72000,-1,, +attributeraisinggempickedup,Aelrynth,,,Picked up an attribute raising gem.,,TRUE,72000,-1,, +attributereset30day,Aelrynth,,,Used your 30 day attribute reset at Asheron's Castle,,TRUE,2592000,-1,set by Chafulumisa, +audetaungagiven,Aelrynth,,,Aun Shimauri will give players permission to enter the Palenqual dungeon only once per month.,,TRUE,72000,-1,, +auggemflag,Aelrynth,,,Flagged to Enter Augmentation Realm,,TRUE,518400,-1,, +augmentationblankgemacquired,Aelrynth,,,Blank Aug Gem Pickup Timer,,TRUE,518400,-1,, +augmentationprovinggroundaccess,Aelrynth,,,Flagged to Enter Augmentation Realm,,TRUE,518400,-1,set by Fiun Rehlyun, +augmenteddrudgekillcount,Aelrynth,,,Augmented Drudge Kill Counter,,TRUE,0,40,, +augmenteddrudgekilltask,Aelrynth,,,Augmented Drudge Kill Task,,TRUE,72000,-1,, +augruncaptivefreed,Aelrynth,,,Aug Run Captive Freed,,FALSE,0,1,set by Captive, +aunkiller,Aelrynth,,,Timaru Collector will stamp players who bring him Aun Pendants and refuse to trade with them again.,,TRUE,72000,-1,set by Aun Mareura the Collector, +aunkillerbagsiraluun,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillerbagsiraluun1,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillerbagsiraluun2,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillerbagsiraluun3,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillerbagsiraluun4,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillerbagsiraluun5,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillercarenzipeltburrower,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillercarenzipeltpouchling,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillercarenzipeltrabid,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillercarenzipeltsentry,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillercarenzipeltstalker,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillerdrudgecharm,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillerfeatherssiraluun,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillergolemheartforest,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillergolemheartmud,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillergolemheartsand,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillergolemheartvapor,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillergolemheartwater,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillerolthoiclaw,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillerpendantaun,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillersiraluunclawlittoral,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillersiraluunclawmarsh,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillersiraluunclawstrand,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillersiraluunclawtidal,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillersiraluunclawtimber,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunkillerwatergolemheart,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +aunteriona_flag,Aelrynth,,,Player has spoke with Aun Teriona.,,FALSE,0,1,set by Aun Teriona, +aurutisitemupgrade_flag,Aelrynth,,,Player is flagged to have Aurutis upgrade an item from list,,FALSE,0,1,set by Lord Kresovus, +avaricerewarded_0813,Aelrynth,,,quest timer,,FALSE,0,1,set by Aspect of Avarice, +axebattlestatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +axebrogordquest,Aelrynth,,,Axe Brogord Quest,,TRUE,72000,-1,, +axecragstatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +axeofkorogaith,Aelrynth,,,Axe of Korogaith pickup timer,,TRUE,72000,-1,, +axesicklestatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +ayanbaqurmoarsmencomplete_0508,Aelrynth,,,Player has completed the Ayan Baqur portion of Moarsmen on the Shores,,TRUE,72000,-1,set by Guard Bey, +azaxiscritterskilled,Aelrynth,,,Player has killed a creature found in Azaxis,,TRUE,0,-1,set by Azaxis Event Watcher, +babythrungus1,Aelrynth,,,babythrungus1 flag,,FALSE,0,1,set by Baby Thrungus, +babythrungus2,Aelrynth,,,babythrungus2 flag,,FALSE,0,1,set by Baby Thrungus, +babythrungus3,Aelrynth,,,babythrungus3 flag,,FALSE,0,1,set by Baby Thrungus, +babythrungus4,Aelrynth,,,babythrungus4 flag,,FALSE,0,1,set by Baby Thrungus, +babythrungus5,Aelrynth,,,babythrungus5 flag,,FALSE,0,1,set by Baby Thrungus, +babythrungus6,Aelrynth,,,babythrungus6 flag,,FALSE,0,1,set by Baby Thrungus, +backtunnelsaccess,Aelrynth,,,Access to the Back Tunnels dungeon granted,,FALSE,0,1,set by Jedeth Eckhart, +bagpuzzleblackbagcorrect,Aelrynth,,,You picked the correct contents for the black bag.,,TRUE,72000,-1,"set by Bag labeled ""Black""", +bagpuzzlecangethintmarble,Aelrynth,,,You can get a hint marble.,,TRUE,72000,-1,set by Instructions, +bagpuzzlefailed,Aelrynth,,,You picked the wrong contents for one of the bags.,,TRUE,72000,-1,"set by Bag labeled ""Black"", Bag labeled ""Mixed"", Bag labeled ""White""", +bagpuzzlemixedbagcorrect,Aelrynth,,,You picked the correct contents for the mixed bag.,,TRUE,72000,-1,"set by Bag labeled ""Mixed""", +bagpuzzleperforming,Aelrynth,,,You are performing the three bag puzzle.,,TRUE,72000,-1,, +bagpuzzlepickbagvariant1,Aelrynth,,,You have varient 1 of the bag puzzle.,,TRUE,72000,-1,set by Instructions, +bagpuzzlepickbagvariant2,Aelrynth,,,You have varient 2 of the bag puzzle.,,TRUE,72000,-1,set by Instructions, +bagpuzzlesolved,Aelrynth,,,You've compleated the Clutch of Kings three bags puzzle.,,TRUE,72000,-1,"set by Bag labeled ""Black"", Bag labeled ""Mixed"", Bag labeled ""White""", +bagpuzzlewhitebagcorrect,Aelrynth,,,You picked the correct contents for the white bag.,,TRUE,72000,-1,"set by Bag labeled ""White""", +banderlinghauntemblemacquired0105,Aelrynth,,,Player has picked up Stone Emblem,,TRUE,72000,-1,, +banderlinghauntgemacquired0105,Aelrynth,,,Player has picked up Murky Gem,,TRUE,72000,-1,, +banderlinghauntoilystoneacquired0105,Aelrynth,,,Player has picked up the Oily Stone.,,TRUE,72000,-1,, +banderlinghauntringacquired0105,Aelrynth,,,Player has picked up Ring of Vines,,TRUE,72000,-1,, +banderlingmacehead,Aelrynth,,,Banderling Mace Head,,TRUE,72000,-1,, +banderlingmaceshaft,Aelrynth,,,Banderling Mace Shaft,,TRUE,72000,-1,, +banditblades,Aelrynth,,,Bandits' Blazing Blades,,TRUE,72000,-1,set by MacNiall the Unruled, +bandittranscription,Aelrynth,,,Bandit Frore Transcription,,TRUE,72000,-1,, +banishedcreaturekillcount,Aelrynth,,,Banished Creature Kill Counter,,TRUE,0,10,, +banishedcreaturekilltask,Aelrynth,,,Banished Creature Kill Task,,TRUE,72000,-1,, +barbaricmukkirlordhead_pickup,Aelrynth,,,Player has picked up Barbaric Mukkir Nest-lord's Head.,,TRUE,72000,-1,, +barbedfletchingtool,Aelrynth,,,Barbed Fletching Tool,,TRUE,72000,-1,, +barkoswaldtaken,Aelrynth,,,Took the bark,,TRUE,72000,-1,, +bartenderfound1111,Aelrynth,,,Player talked to bartender greeter,,FALSE,0,1,"set by A'shadieeyah, Benjirou, Buckminster and 1 more", +bdcquidityingotpurified,Aelrynth,,,Purified the BDC Quiddity Ingot,,TRUE,72000,-1,set by Vat of Olthoi Jelly, +beachfortmoarsmencomplete_0508,Aelrynth,,,Player has completed the Beach Fort portion of Moarsmen on the Shores,,TRUE,72000,-1,set by Guard Al'Zira, +beacongemobtained,Aelrynth,,,Cooldown for obtaining another beacon gem,,TRUE,72000,-1,set by Elena Du Furza, +belindakilltasksstart,Aelrynth,,,Player has started Belindas Kill Tasks,,FALSE,0,1,set by Belinda du Loc, +bellowsnewbiepickedup,Aelrynth,,,Player has found the Blacksmith's bellows.,,FALSE,0,1,, +bellowsnewbieturnedin,Aelrynth,,,Player has turned in the Blacksmith's bellows.,,FALSE,0,1,set by Academy Blacksmith, +benefactionnuhmudiragiven,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +benekniffiskillcount,Aelrynth,,,Benek Niffis Kill Counter,,TRUE,0,50,set by Colista Fluress, +benekniffiskilltask,Aelrynth,,,Benek Niffis Kill Task,,TRUE,72000,-1,set by Colista Fluress, +bestoweralchemy1,Aelrynth,,,Apothecary,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestoweralchemy2,Aelrynth,,,Alchemist,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestoweraxe1,Aelrynth,,,Axe Warrior,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestoweraxe2,Aelrynth,,,Skullsplitter,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerbasepiece,Aelrynth,,,The base piece for the Bestowers' Guild skill puzzle.,,TRUE,72000,-1,, +bestowerbow1,Aelrynth,,,Sharpshooter,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerbow2,Aelrynth,,,Deadeye,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowercooking1,Aelrynth,,,Chef,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowercooking2,Aelrynth,,,Iron Chef,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowercreature1,Aelrynth,,,Creature Enchantment Adept,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowercreature2,Aelrynth,,,Evoker,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerdagger1,Aelrynth,,,Dagger Fighter,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerdagger2,Aelrynth,,,Slicer,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerfletching1,Aelrynth,,,Fletcher,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerfletching2,Aelrynth,,,MasterFletcher,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestoweritem1,Aelrynth,,,Item Enchantment Adept,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestoweritem2,Aelrynth,,,Artifex,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerlife1,Aelrynth,,,Life Magic Adept,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerlife2,Aelrynth,,,Theurgist,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowermace1,Aelrynth,,,Mace Warrior,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowermace2,Aelrynth,,,Skullcrusher,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerspear1,Aelrynth,,,Spear Warrior,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerspear2,Aelrynth,,,Impaler,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerstaff1,Aelrynth,,,Staff Warrior,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerstaff2,Aelrynth,,,Master of Staves,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowersword1,Aelrynth,,,Swordfighter,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowersword2,Aelrynth,,,Duelist,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerthrownweapons1,Aelrynth,,,Ballisteer,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerthrownweapons2,Aelrynth,,,Projectilist,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerunarmed1,Aelrynth,,,Unarmed Brawler,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerunarmed2,Aelrynth,,,Pugilist,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerwar1,Aelrynth,,,War Magic Adept,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerwar2,Aelrynth,,,Warlock,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerxbow1,Aelrynth,,,Sniper,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowerxbow2,Aelrynth,,,Sureshot,,FALSE,0,1,"set by Darsida al-Qawa, Eluard the Namer, Jaizen Tan", +bestowmentnuhmudiragiven,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +bethelcompleted,Aelrynth,,,Bethel of Butterflies once players have brought the amulet to Aun Papileona he will stamp them so he will not send them on the quest again for one week.,,TRUE,72000,-1,set by Aun Papileona, +bethelcompleted02,Aelrynth,,,Bethel of Butterflies players may pick the key off the boss monster only once a week,,TRUE,72000,-1,, +blackboulder,Aelrynth,,,Picked up Black Boulder/Blackfire Atlan Stone,,TRUE,72000,-1,, +blackcoralgolemkillcount,Aelrynth,,,Black Coral Golem Kill Counter,,TRUE,0,20,, +blackcoralgolemkilltask,Aelrynth,,,Black Coral Golem Kill Task,,TRUE,72000,-1,, +blackdeathcatacombsquidditywait,Aelrynth,,,Completed Black Death Catacombs Quiddity Seed Quest,,TRUE,72000,-1,set by Emissary of Asheron, +blackferahsvault_start,Aelrynth,,,Player has access to Black Ferahs Vault,,FALSE,0,1,set by Varetha, +blackmarketadvancementwait,Aelrynth,,,Cooldown for Black Market Advancement Gem,,TRUE,72000,-1,set by Ilnorra Denasta, +blackmarketagedlegendarykeywait,Aelrynth,,,Cooldown for Black Market Legendary Key Purchase,,TRUE,72000,-1,"set by Consolata, Digby", +blackmarketblackcoralgolemkilltask,Aelrynth,,,Black Coral Golem Kill Task,,TRUE,0,20,set by Chiriko, +blackmarketblackcoralgolemkilltaskwait,Aelrynth,,,Black Coral Golem Kill Task Wait,,TRUE,72000,-1,set by Chiriko, +blackmarketblightedcoralgolemkilltask,Aelrynth,,,Blighted Coral Golem Kill Task,,TRUE,0,20,set by Hanzo, +blackmarketblightedcoralgolemkilltaskwait,Aelrynth,,,Blighted Coral Golem Kill Task Wait,,TRUE,72000,-1,set by Hanzo, +blackspearbufftimer,Aelrynth,,,Player has used on of the Black Spears,,TRUE,72000,-1,"set by Black Spear of Mukkir Strength, Black Spear of Ruschk Protection, Black Spear of Shadow Renewal", +blackspearicetotem_pickup,Aelrynth,,,Player has picked up the Black Spear Ice Totem,,TRUE,72000,-1,, +blackspearicetotemcompleted,Aelrynth,,,Player has completed the Black Spear Ice Totem Quest,,TRUE,72000,-1,"set by Arialle du Bellenesse, Kalakh", +blackspearicetotemstarted,Aelrynth,,,Player has started the Black Spear Ice Totem Quest,,FALSE,0,1,"set by Arialle du Bellenesse, Kalakh", +blackspeartemple_flag,Aelrynth,,,Access granted to the Black Spear Temple,,FALSE,0,1,set by Lord Pyrovor, +blackspeartempleupperlevel_flag,Aelrynth,,,Access granted to the Black Spear Temple Upper Levels,,FALSE,0,1,set by Melaverre, +blacktotemshard_pickup,Aelrynth,,,Player has picked up the Black Totem Shard,,TRUE,72000,-1,, +blacktotemtemple_flag,Aelrynth,,,Access granted to the Black Totem Temple,,FALSE,0,1,set by Black Totem Gateway, +blankaug,Aelrynth,,,Blank Aug Gem Pickup Timer,,TRUE,518400,-1,, +blankaugluminancetimer_0511,Aelrynth,,,Cooldown timer for Augmentation Gem turn-in,,TRUE,1209600,-1,set by Nalicana, +blessedcavecompleted_0912,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Shah-hi, +blessedcavereachedend,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Spirit of Bist'elle, +blessedcavestarted_0912,Aelrynth,,,quest timer,,FALSE,0,1,set by Shah-hi, +blessedmoarsmankillcount,Aelrynth,,,Blessed Moarsman Kill Counter,,TRUE,0,50,, +blessedmoarsmankilltask,Aelrynth,,,Blessed Moarsman Kill Task,,TRUE,72000,-1,, +blightedcoralgolemkillcount,Aelrynth,,,Blighted Coral Golem Kill Counter,,TRUE,0,20,, +blightedcoralgolemkilltask,Aelrynth,,,Blighted Coral Golem Kill Task,,TRUE,72000,-1,, +blightlordlairwait1008,Aelrynth,,,Player wait time for Blight Lord Lairs.,,TRUE,72000,-1,"set by A'mun Altar, Aerlinthe Altar, Esper Altar and 3 more", +bloodgemblueacquired0805,Aelrynth,,,Ricardo's Blood Gem - Blue,,TRUE,72000,-1,, +bloodgemquestcompleted0805,Aelrynth,,,Ricardo's Blood Gem Complete,,TRUE,72000,-1,set by Ricardo, +bloodjewelhighpickedup,Aelrynth,,,Player has collected the high Blood Jewel.,,TRUE,72000,-1,, +bloodjewellowpickedup,Aelrynth,,,Player has collected the low Blood Jewel.,,TRUE,72000,-1,, +bloodjewelmidpickedup,Aelrynth,,,Player has collected the mid Blood Jewel.,,TRUE,72000,-1,, +bloodmouthmawrepeat,Aelrynth,,,Player has turned in a Bloodmouth Maw at least once.,,FALSE,0,1,set by Merwart Pelagurg, +bloodpuzzlecompleted,Aelrynth,,,You've compleated the Clutch of Kings blood puzzle.,,TRUE,72000,-1,set by Sacrificial Statue, +bloodstonefactorycompleted_0211,Aelrynth,,,Completed Bloodstone Invesigation,,TRUE,72000,-1,set by Sir Donovan, +bloodstonefactorykeypickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +bloodstonefactorylargetomepickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +bloodstonefactorystarted_0211,Aelrynth,,,Started Bloodstone Investigation,,FALSE,0,1,set by Sir Donovan, +blueblanketgivencomplete,Aelrynth,,,Flagged to use Arena of Pumpkin King,,TRUE,72000,-1,set by Arena of the Pumpkin King, +bluefacepaintturnin,Aelrynth,,,Player turned in Blue Face Paint,,FALSE,0,1,, +bluefireinfusion,Aelrynth,,,Blue Fire SOLL Infusion,,TRUE,72000,-1,, +blueprintsburunfort,Aelrynth,,,You have picked up the Burun Ingress Fort Blueprints.,,TRUE,72000,-1,, +bonecrunchkeypickuptimer,Aelrynth,,,Player has picked up Bonecrunchs Key,,TRUE,72000,-1,, +boneylumpoffleshpickuptimer,Aelrynth,,,Picked up Boney Lump of Flesh,,TRUE,72000,-1,checked by Niccolo De Luca, +book100paths7quest,Aelrynth,,,Book 100 Paths Quest,,TRUE,518400,-1,, +bookcasenoir1,Aelrynth,,,You've moved the bookcase.,,TRUE,5400,-1,set by Bookcase, +bookercelquest,Aelrynth,,,Retreive Ercel's Book,,TRUE,72000,-1,, +bookfalatacotway,Aelrynth,,,Player has received a copy of the Falatacot Way.,,TRUE,72000,-1,set by Living Tome, +bookkouquest,Aelrynth,,,Book Kou Quest,,TRUE,72000,-1,, +booknoir1,Aelrynth,,,You've looked at Jake's journal.,,TRUE,5400,-1,set by Open Journal, +bookturnedin,Aelrynth,,,Turned in book to Olcris.,,FALSE,0,1,"set by Olcris, Nuhmudira's Student", +boshboshslayertokenpickuptimer,Aelrynth,,,Player has picked up Bosh Bosh Slayer Token,,TRUE,72000,-1,, +bosshelmacquired0205,Aelrynth,,,You looted the Salvaging Helm.,,TRUE,72000,-1,, +bosstokenacquired0205,Aelrynth,,,You acquired a token denoting you the Sezzherei Slayer!,,TRUE,72000,-1,, +bowstatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +boygrubcompletedquest,Aelrynth,,,Has the player completed the quest?,,TRUE,72000,-1,set by Putiputipuh, +boygrubfedwrongapple,Aelrynth,,,Has the player fed an apple to the grub without first being infested?,,TRUE,72000,-1,set by Putiputipuh, +boygrubfoundapple,Aelrynth,,,Has the player found an apple as far as Tekapuapuh knows?,,TRUE,72000,-1,"set by Putiputipuh, Tekapuapuh", +boygrubgaveahna,Aelrynth,,,Has the player given Tekapuapuh an Ahna?,,TRUE,72000,-1,set by Tekapuapuh, +boygrubgavepah,Aelrynth,,,Has the player given Tekapuapuh a Pan?,,TRUE,72000,-1,set by Tekapuapuh, +boygrubgotbow,Aelrynth,,,Has the player been given the Panaq bow?,,TRUE,72000,-1,set by Tekapuapuh, +boygrubinfested,Aelrynth,,,Has the player used the Infested cistern?,,TRUE,72000,-1,set by Olthoi Cistern, +boygrubstartedquest,Aelrynth,,,Has the player started the quest?,,TRUE,72000,-1,set by Tekapuapuh, +boygrubtookahna,Aelrynth,,,Has the player picked up an Ahna?,,TRUE,72000,-1,, +boygrubtooknaq,Aelrynth,,,Has the player picked up a Naq?,,TRUE,72000,-1,, +boygrubtookpah,Aelrynth,,,Has the player picked up a Pan?,,TRUE,72000,-1,, +braceletebuillantpickup,Aelrynth,Elemental Bracelets,,Player has picked up Ebuillant Bracelet,,TRUE,72000,-1,, +braceletfrigidpickup,Aelrynth,Elemental Bracelets,,Player has picked up Frigid Bracelet,,TRUE,72000,-1,, +braceletgalvanicpickup,Aelrynth,Elemental Bracelets,,Player has picked up Galvanic Bracelet,,TRUE,72000,-1,, +braceletincalescentpickup,Aelrynth,Elemental Bracelets,,Player has picked up Incalescent Bracelet,,TRUE,72000,-1,, +braceletloueiquest,Aelrynth,,,Bracelet Lou Ei Quest,,TRUE,72000,-1,, +braceletofpassage,Aelrynth,,,Wearing Bracelet Of Passage,,FALSE,0,1,set by Bracelet of Passage, +braidmansionruincompleted_1111,Aelrynth,,,Completed Braid Mansion Ruin (Lou Ka's Stolen Items),,TRUE,72000,-1,set by Lou Ka, +brewmasterback,Aelrynth,,,Brew Master Quest Pickup Timer Back,,TRUE,72000,-1,, +brewmastercover,Aelrynth,,,Brew Master Quest Pickup Timer Cover,,TRUE,72000,-1,, +brewmasterpages,Aelrynth,,,Brew Master Quest Pickup Timer Pages,,TRUE,72000,-1,, +brewmasterspine,Aelrynth,,,Brew Master Quest Pickup Timer Spine,,TRUE,72000,-1,, +brightaetheriumorefragmentpickedup,Aelrynth,,,You have obtained a Bright Aetherium Ore Fragment.,,TRUE,72000,-1,, +brilliantshardgiven,Aelrynth,,,Brilliant Shard given to Rhujun,,FALSE,0,1,set by Rhujun, +brokenkeyringmartine,Aelrynth,,,Player has picked up the Broken Singularity Keyring,,TRUE,72000,-1,, +brokenkeyteethmartine,Aelrynth,,,Player has been picked up the Broken Singularity Key Teeth,,TRUE,72000,-1,, +brokenoccultusseal,Aelrynth,,,Broken Occultus Seal,,FALSE,0,1,set by Balior, +brokenoccultussealgiven,Aelrynth,,,Broken Occultus Seal given,,FALSE,0,1,set by Roderick, +bronzegauntlettrooperkillcount,Aelrynth,,,kill count,,TRUE,0,25,set by Lieutenant Grenlin, +bronzegauntlettrooperkilltask,Aelrynth,,,kill task timer,,TRUE,72000,-1,set by Lieutenant Grenlin, +broodmatroncarapacepickedup,Aelrynth,,,You have obtained a Brood Matron Carapace.,,TRUE,72000,-1,, +broodmatronclawpickedup,Aelrynth,,,You have obtained a Brood Matron Claw.,,TRUE,72000,-1,, +broodmatroncrestpickedup,Aelrynth,,,You have obtained a Brood Matron Crest.,,TRUE,72000,-1,, +broodmatronpincerpickedup,Aelrynth,,,You have obtained a Brood Matron Pincer.,,TRUE,72000,-1,, +broodmotheronedead,Aelrynth,,,BroodMotherOneDead,,FALSE,0,1,set by Brood Mother, +broodmothersreckblue42,Aelrynth,,,Brood Mothers Riddle,,FALSE,0,1,set by Statue, +broodmothersreckgreen117,Aelrynth,,,Brood Mothers Riddle,,FALSE,0,1,set by Statue, +broodmothersreckred78,Aelrynth,,,Brood Mothers Riddle,,FALSE,0,1,set by Statue, +broodmotherthreedead,Aelrynth,,,BroodMotherThreeDead,,FALSE,0,1,set by Brood Mother, +broodmothertwodead,Aelrynth,,,BroodMotherTwoDead,,FALSE,0,1,set by Brood Mother, +broodmotherzerodead,Aelrynth,,,BroodMotherZeroDead,,FALSE,0,1,set by Brood Mother, +broodpincerpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +broodubeaten,Aelrynth,,,You've beaten Broodu.,,FALSE,0,1,checked by Guard Hamdyn, +brooducomplete,Aelrynth,,,You've completed the Broodu quest.,,TRUE,72000,-1,set by Guard Hamdyn, +broodukilled,Aelrynth,,,You killed Broodu.,,FALSE,0,1,set by Guard Hamdyn, +browerkbeaten,Aelrynth,,,You've beaten Browerk.,,FALSE,0,1,checked by Guard Haigh, +browerkcomplete,Aelrynth,,,You've completed the Browerk quest.,,TRUE,72000,-1,set by Guard Haigh, +browerkkilled,Aelrynth,,,You killed Browerk.,,FALSE,0,1,set by Guard Haigh, +btmcompleted_0513,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Virindi Delegate, +btmpickup_0513,Aelrynth,,,quest timer,,TRUE,72000,-1,, +btmstarted_0513,Aelrynth,,,quest timer,,FALSE,0,1,set by Virindi Delegate, +buadreninvokinggiven,Aelrynth,,,Player has received the magic Buadren from Tikakhe.,,FALSE,0,1,set by Aun Tikakhe, +bucketadja,Aelrynth,,,Adja Well Bucket,,TRUE,72000,-1,, +bucketsbalancedcomplete,Aelrynth,,,Bits for completed Buckets in Trial of Mind,,TRUE,0,31,checked by Pillar of the Mind, +bulbofharvests_flag,Aelrynth,,,Player has completed Harvesting the Bulb of Mornings quest.,,FALSE,0,1,set by Kaltus, +bulbofharvestsseedgiven,Aelrynth,,,Player has been given the Seed of Essence.,,FALSE,0,1,set by Bulb of Harvests, +bulbofmornings_flag,Aelrynth,,,Player has completed Releasing the Light quest.,,FALSE,0,1,set by Shah-hi, +bulbofmorningsseedgiven,Aelrynth,,,Player has been given the Seed of Essence.,,FALSE,0,1,set by Bulb of Mornings, +bulboftwilight_flag,Aelrynth,,,Player has completed Harvesting the Bulb of Harvests quest.,,FALSE,0,1,set by Adrenkus, +bunnygardenletter,Aelrynth,,,This quest flag is obsolete.,,TRUE,2400,-1,, +bunnygardensafeguard,Aelrynth,,,This quest flag is obsolete.,,TRUE,1200,-1,, +bunnymastercompletedquest,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +bunnymasterquest1,Aelrynth,,,This quest flag is obsolete.,,TRUE,1800,-1,, +bunnymasterquest2,Aelrynth,,,This quest flag is obsolete.,,TRUE,1800,-1,, +bunnymasterquest3,Aelrynth,,,This quest flag is obsolete.,,TRUE,1800,-1,, +bunnymasterquest4,Aelrynth,,,This quest flag is obsolete.,,TRUE,1800,-1,, +bunnyslippergiven,Aelrynth,,,CragstoneSlipperCrafter stamps players with this questflag after giving them SlipperBunny or SlipperBunnyWhite,,TRUE,72000,-1,set by William Witty, +burflagged(gem),Aelrynth,,,One of three flags for 1-79 Portal to Bur,,FALSE,0,1,set by Bretself the Translator, +burflagged(metal),Aelrynth,,,One of three flags for 1-79 Portal to Bur,,FALSE,0,1,set by Felscuda, +burflagged(motes),Aelrynth,Asheron's Trail,https://acportalstorm.com/wiki/Asheron's_Trail,One of three flags for 1-79 Portal to Bur. See Golem Warden of Metos.,One of three flags for 1-79 Portal to Bur,FALSE,0,1,set by Golem Warden of Metos, +burflagged(permanent),Aelrynth,,,You can take the portal to Bur.,,FALSE,0,1,set by Shan Zhen, +buriedalivecompleted1212,Aelrynth,,,Picked up Blazing Shard,,TRUE,72000,-1,, +buriedalivestarted1212,Aelrynth,,,Started Crystal Core Quest,,FALSE,0,1,set by David, +burnjasboardturninrepeat,Aelrynth,,,Player has already turned in 1 Burnjas Board with nails,,FALSE,0,1,set by Jarvis Hammerstone, +burrecall_repeat,Aelrynth,,,Player has completed Bur Recall at least once,,FALSE,0,1,set by Oswent the Pale, +burrecall_start,Aelrynth,,,Player is flagged for Bur Recall portion of lockbox,,FALSE,0,1,set by Oswent the Pale, +burrecall_wait,Aelrynth,,,Wait timer for Bur Recall,,TRUE,72000,-1,set by Oswent the Pale, +buruncontact,Aelrynth,,,You have learned that the Renegades mean to make contact with the Burun.,,FALSE,0,1,set by A Cluttered Table, +buruningressdirelands,Aelrynth,,,You can now enter the Burun temple in the Direlands.,,FALSE,0,1,set by Translator Aun Laokhe, +burunliberator_repeat,Aelrynth,,,Player has completed Burun Liberator Quest once,,FALSE,0,1,set by Scout Leader Tmauruk, +burunliberator_start,Aelrynth,,,Player has started Burun Liberator Quest,,FALSE,0,1,set by Scout Leader Tmauruk, +burunliberator_wait,Aelrynth,,,Player wait timer for Burun Liberator Quest,,TRUE,72000,-1,set by Scout Leader Tmauruk, +caligaegis,Aelrynth,,,Caliginous Aegis,,TRUE,518400,-1,, +caliginousbethelcomplete_0511,Aelrynth,,,Handed Refulgent Bracelet to Aurten Rhell,,TRUE,72000,-1,set by Aurten Rhell, +callingstonegiven,Aelrynth,,,Turned over the Calling Stone,,FALSE,0,1,"set by Greeter, Society Greeter", +cameraguardspoken1,Aelrynth,,,Camera Guard has spoken once,,FALSE,0,1,set by Guard, +cameraguardspoken2,Aelrynth,,,Camera Guard has spoken twice,,FALSE,0,1,set by Guard, +cameraguardspoken3,Aelrynth,,,CameraGuard has spoken thrice,,FALSE,0,1,set by Guard, +campentemarrecompleted,Aelrynth,,,Head of Baron Entemarre quest completed,,TRUE,1123200,-1,set by Hashina, +campentemarrestarted,Aelrynth,,,Head of Baron Entemarre quest started,,FALSE,0,1,set by Hashina, +canaccessqueenlairrot2,Aelrynth,,,wearing ring lets you go in lair,,FALSE,0,1,"set by Crystal Ring of Protection, Crystal Ring of Quickness, Scintillating Crystal Ring and 1 more", +candlerunfailwait,Aelrynth,,,Cooldown for Candle Run failed attempt,,TRUE,900,-1,set by Hoshino Kiri, +candlerunprogress,Aelrynth,,,Candle Run progress tracker and timer,,TRUE,30,5,"set by First Enchanted Candle, Hoshino Kiri, Second Enchanted Candle and 1 more", +candlerunwait,Aelrynth,,,Cooldown for Candle Run rewards,,TRUE,518400,-1,set by Hoshino Kiri, +canentergerainerefuge,Aelrynth,,,Flagged to enter Geraine's Hosts dungeons.,,FALSE,0,1,set by Mhoire Soldier, +canenterlordkastellarslab,Aelrynth,,,Flagged to enter Lord Kastellar's Lab,,FALSE,0,1,set by Sir Donovan, +canentersclavustempledoor,Aelrynth,,,Flagged to use Sclavus Temple Lord Test,,FALSE,0,1,set by Coral Hollow, +canpickupcorruptedmanashard,Aelrynth,,,Player can pick up Corrupted Mana Shard,,FALSE,0,1,"set by Arturus of the Eldrytch Web, Ayesha of the Radiant Blood, Kirina of the Celestial Hand", +canpickuplargecorruptedmanashard,Aelrynth,,,Player can pick up Large Corrupted Mana Shard for Deru Quest.,,FALSE,0,1,set by Aun Kimintari, +canpickupsilverantoken,Aelrynth,,,Player can pick up a Silveran Token,,FALSE,0,1,"set by Jathaq al-Nishadina, Varlanna", +caocaofirstspeak,Aelrynth,,,TBD,,FALSE,0,1,, +caocaoright,Aelrynth,,,Correct answer on Cao Cao,,FALSE,0,1,set by Cao Cao, +capacademypickup,Aelrynth,,,Player has picked up the Academy Cap,,FALSE,0,1,checked by Samuel, +capplewine,Aelrynth,,,Allowed to pickup Cove Apple Wine,,FALSE,0,1,set by Lubziklan al-Luq, +captive100gwi1205,Aelrynth,,,Started Glenden Wood Invasion Mid quest,,FALSE,0,1,set by Captain Sovano, +captive130gwi1205,Aelrynth,,,Started Glenden Wood Invasion High quest,,FALSE,0,1,set by Captain Anrayl, +captive80gwi1205,Aelrynth,,,Started Glenden Wood Invasion Low quest,,FALSE,0,1,set by Captain Nyino, +captivetalk100,Aelrynth,,,Started Glenden Wood Invasion Mid quest,,FALSE,0,1,set by Captive, +captivetalk180,Aelrynth,,,Started Glenden Wood Invasion High quest,,FALSE,0,1,set by Captive, +captivetalk80,Aelrynth,,,Started Glenden Wood Invasion Low quest,,FALSE,0,1,set by Captive, +carenziplaguestarted,Aelrynth,,,Player count down timer for Diseased Livers.,,TRUE,7200,-1,"set by Diseased Carenzi Stalker Liver, Diseased Carnivorous Carenzi Liver, Diseased Feral Carenzi Liver and 3 more", +carenzirace,Aelrynth,,,Started a Race,,TRUE,900,-1,set by Carenzi Race Bookie, +carenziracebetterr1,Aelrynth,,,Bet on Racer 1,,FALSE,0,1,set by Carenzi Racer, +carenziracebetterr2,Aelrynth,,,Bet on Racer 2,,FALSE,0,1,set by Carenzi Racer, +carenziracebetterr3,Aelrynth,,,Bet on Racer 3,,FALSE,0,1,set by Carenzi Racer, +carenziracebetterr4,Aelrynth,,,Bet on Racer 4,,FALSE,0,1,set by Carenzi Racer, +carenziracebetterr5,Aelrynth,,,Bet on Racer 5,,FALSE,0,1,set by Carenzi Racer, +carenziracebetterr6,Aelrynth,,,Bet on Racer 6,,FALSE,0,1,set by Carenzi Racer, +carenziracebetterr7,Aelrynth,,,Bet on Racer 7,,FALSE,0,1,set by Carenzi Racer, +carenziracebetterr8,Aelrynth,,,Bet on Racer 8,,FALSE,0,1,set by Carenzi Racer, +carenziracecup,Aelrynth,,,Won the Carenzi Cup,,FALSE,0,1,set by Carenzi Race Bookie, +carenziracermoves,Aelrynth,,,Total of moves for a racer to reach finish line in Carenzi Race,,TRUE,0,60,set by Carenzi Racer, +carenziracewins,Aelrynth,,,Total Carenzi Race Wins,,TRUE,0,-1,set by Carenzi Race Bookie, +carloloreviamontianmages001acquired0205,Aelrynth,,,You picked up page 1 of Carlo di Cenza's journal.,,TRUE,72000,-1,, +carloloreviamontianmages007acquired0205,Aelrynth,,,You picked up page 7 of Carlo di Cenza's journal.,,TRUE,72000,-1,, +carloloreviamontianmagesbindingacquired0205,Aelrynth,,,You picked up Carlo di Cenza's book binding.,,TRUE,72000,-1,, +carpwing,Aelrynth,,,Player has picked up a Carpenter Wasp wing in the Academy,,FALSE,0,1,, +cartilageofoldscratchy_pickup,Aelrynth,,,Player has picked up Cartilage of Old Scratchy,,TRUE,72000,-1,, +casinovipportalaccess,Aelrynth,,,Access Pass for Casino VIP Portals,,TRUE,300,-1,"set by Carenzi Race Bookie, Monster Fight Bookie", +caulnalaincrystal,Aelrynth,,,Caulnalain Crystal,,TRUE,72000,-1,, +cavepenguinegg,Aelrynth,,,Picked up Cave Penguin Egg,,TRUE,72000,-1,, +cavernenchantedmnemosynesfound,Aelrynth,,,Enchanted Mnemosynes Found Bits,,TRUE,0,15,checked by Menhir, +celestialhandmember,Aelrynth,,,Player is a member of Celestial Hand,,FALSE,0,1,set by Kirina of the Celestial Hand, +centralhiveportalok,Aelrynth,,,Kill special Eviscerator in Mt Elyrii Wastland Hive or N Dam to go through the portal to Royal Hive,,TRUE,5400,-1,set by Olthoi Eviscerator, +cestusstatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +championbullgarabet,Aelrynth,,,Player bet on Champion Bullgara,,FALSE,0,1,set by Champion Bulgara, +championkillquest1,Aelrynth,,,Kill Aun Ralirea,,TRUE,72000,-1,set by Aun Ralirea, +championkillquest2,Aelrynth,,,Kill Hea Temenua,,TRUE,72000,-1,set by Hea Temenua, +championquest01,Aelrynth,,,Pick up KeyKarenua - opens the Hea Raiders' chest,,TRUE,72000,-1,, +championquest02,Aelrynth,,,Pick up VirindiScalpelBlade,,TRUE,72000,-1,, +championquest03,Aelrynth,,,Pick up VirindiScalpelHilt,,TRUE,72000,-1,, +championquest04,Aelrynth,,,Pick up CropTuperea1,,TRUE,72000,-1,, +championquest05,Aelrynth,,,Pick up CropTuperea2,,TRUE,72000,-1,, +championquest06,Aelrynth,,,Pick up ExquisiteElariBowString,,TRUE,72000,-1,, +championquest07,Aelrynth,,,Pick up ExquisiteElariBowHaft,,TRUE,72000,-1,, +changedsurveyorsettings,Aelrynth,,,You played with the surveyor's equipment! Bad person!,,TRUE,72000,-1,set by Surveying Device, +changinggearscompleted_0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Ilte Krongal, +changinggearsstarted_0813,Aelrynth,,,quest timer,,FALSE,0,1,set by Ilte Krongal, +charmdolloct01,Aelrynth,,,Pyreal Doll Charm,,TRUE,72000,-1,, +chasingoswalddungeonflag,Aelrynth,,,Chasing Oswald dungeon flagged,,FALSE,0,1,set by Huntsman of Silyun, +chasingoswaldruschkicehold,Aelrynth,,,Chasing Oswald Ruschk Ice Hold flagged,,FALSE,0,1,set by Huntsman of Silyun, +chasingoswaldviamontprison,Aelrynth,,,Chasing Oswald Viamont Prison flagged,,FALSE,0,1,set by Huntsman of Silyun, +chdscompletedonce0608,Aelrynth,,,Player stamp for first completion of Harlunes Diplomacy.,,FALSE,0,1,set by Roderick, +chdsfalatacotcharm0608,Aelrynth,,,Player wait timer for Harlunes Diplomacy.,,TRUE,72000,-1,set by Roderick, +chdsrepeat0608,Aelrynth,,,Player stamp for repeat completions of Harlunes Diplomacy.,,FALSE,0,1,set by Roderick, +chdsstarted0608,Aelrynth,,,Player has started Harlunes Diplomacy.,,FALSE,0,1,set by Roderick, +chdsstatuecharged0608,Aelrynth,,,NPC stamp for Falatacot Warden Statues.,,FALSE,0,1,set by Falatacot Warden Statue, +chestblackmarrowburningtower0205,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestblackmarrowcaulcano0205,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestblackmarrowcauloasis0205,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestblackmarrowfloatingbridge0205,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestblackmarrowfloatingtower0205,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestblackmarrowgatewaydemesne0205,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestblackmarrowgatewaylurza0205,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestblackmarrowgatewayshemza0205,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestblackmarrownightmaregate0205,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestblackmarrowtunneloflove0205,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestburuppercatacomb1,Aelrynth,Upper Catacombs,,You have opened this chest already.,,TRUE,72000,-1,, +chestburuppercatacomb2,Aelrynth,Upper Catacombs,,You have opened this chest already.,,TRUE,72000,-1,, +chestburuppercatacomb3,Aelrynth,Upper Catacombs,,You have opened this chest already.,,TRUE,72000,-1,, +chestburuppercatacomb4,Aelrynth,Upper Catacombs,,You have opened this chest already.,,TRUE,72000,-1,, +chestburuppercatacomb5,Aelrynth,Upper Catacombs,,You have opened this chest already.,,TRUE,72000,-1,, +chestburuppercatacomb6,Aelrynth,Upper Catacombs,,You have opened this chest already.,,TRUE,72000,-1,, +chestchorizite48745,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestchorizite48757,Aelrynth,,,quest timer,,TRUE,72000,-1,, +chestchorizite48759,Aelrynth,,,quest timer,,TRUE,72000,-1,, +chestchorizite48760,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestchorizite48766,Aelrynth,,,quest timer,,TRUE,72000,-1,, +chestchorizite48767,Aelrynth,,,quest timer,,TRUE,72000,-1,, +chestchorizite48773,Aelrynth,,,Used Chorizite Chest in Count Phainors Tomb,,TRUE,72000,-1,, +chestchorizite48824,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestchorizite48913,Aelrynth,,,Used Chorizite Chest in Foundry of Izexi.,,TRUE,72000,-1,, +chestchorizite51280,Aelrynth,,,Used Chorizite Chest in Virindi Edifice,,TRUE,72000,-1,, +chestchorizite51327,Aelrynth,,,Used Chorizite Chest in Hive Warrior Mound,,TRUE,72000,-1,, +chestchorizite51427,Aelrynth,,,You have opened this chest already.,,TRUE,72000,-1,, +chestchorizite51643,Aelrynth,,,Used Chorizite Chest in Rynthid Access,,TRUE,72000,-1,, +chestchorizite51662,Aelrynth,,,Used Chorizite Chest in Rynthid Foundry,,TRUE,72000,-1,, +chestchorizite51687,Aelrynth,,,Used Chorizite Chest in Fear Factory,,TRUE,72000,-1,, +chestchorizite72060,Aelrynth,,,Used Chorizite Chest in Bah'Ktar Tower,,TRUE,72000,-1,, +chestchorizite72061,Aelrynth,,,Used Chorizite Chest in Rynthid Genesis,,TRUE,72000,-1,, +chestchorizite72137,Aelrynth,,,Used Chorizite Chest in Virindi Edifice,,TRUE,72000,-1,, +chestchorizite72153,Aelrynth,,,Used Chorizite Chest in Presk's Bunker,,TRUE,72000,-1,, +chestchorizite72171,Aelrynth,,,Used Chorizite Chest in Curator of Torment's Study,,TRUE,72000,-1,, +chestchorizite72172,Aelrynth,,,Used Chorizite Chest in Catacombs of Torment,,TRUE,72000,-1,, +chestchorizite72326,Aelrynth,,,quest timer,,TRUE,72000,-1,, +chestchorizite72526,Aelrynth,,,quest timer,,TRUE,72000,-1,, +chestchorizite72616,Aelrynth,,,quest timer,,TRUE,72000,-1,, +chestchorizite72698,Aelrynth,,,Used Chorizite Chest in Hive Eviscerator Burrow,,TRUE,72000,-1,, +chestchorizite73155,Aelrynth,,,quest timer,,TRUE,72000,-1,, +chestchorizite87509,Aelrynth,,,Used Chorizite Chest in Four Corners.,,TRUE,72000,-1,, +chestchorizite87566,Aelrynth,,,Used Chorizite Chest in Third Sister.,,TRUE,72000,-1,, +chestquestaubereanmap,Aelrynth,,,Opened a ChestQuest,,TRUE,72000,-1,, +chestquestcoinattachment,Aelrynth,,,Opened a ChestQuest,,TRUE,72000,-1,, +chestquestdarkmonolith,Aelrynth,,,Opened a ChestQuest,,TRUE,72000,-1,, +chestquestdarktowers,Aelrynth,,,Opened a ChestQuest,,TRUE,72000,-1,, +chestquestdeepcaverns,Aelrynth,,,Opened a ChestQuest,,TRUE,72000,-1,, +chestquestdrudgefight,Aelrynth,,,Opened a ChestQuest,,TRUE,72000,-1,, +chestquestgibbering,Aelrynth,,,Opened a ChestQuest,,TRUE,72000,-1,, +chestquestlairhomunculus,Aelrynth,,,Opened a ChestQuest,,TRUE,72000,-1,, +chestquestlittlestniffis1204,Aelrynth,,,You have opened the Littlest Niffis chest!,,TRUE,72000,-1,, +chestquestlockedextreme,Aelrynth,,,Opened a ChestQuestLockedExtreme.,,TRUE,72000,-1,, +chestquestlockedextremepoia,Aelrynth,,,Opened a ChestQuestLockedExtreme.,,TRUE,72000,-1,, +chestquestlockedextremepoib,Aelrynth,,,Opened a ChestQuestLockedExtreme.,,TRUE,72000,-1,, +chestquestlockedextremepoic,Aelrynth,,,Opened a ChestQuestLockedExtreme.,,TRUE,72000,-1,, +chestquestlockedextremepoid,Aelrynth,,,Opened a ChestQuestLockedExtreme.,,TRUE,72000,-1,, +chestquestlockedextremepoie,Aelrynth,,,Opened a ChestQuestLockedExtreme.,,TRUE,72000,-1,, +chestquestlockedextremepoif,Aelrynth,,,Opened a ChestQuestLockedExtreme.,,TRUE,72000,-1,, +chestquestlockedextremepoig,Aelrynth,,,Opened a ChestQuestLockedExtreme.,,TRUE,72000,-1,, +chestquestlockedhigh,Aelrynth,,,Opened a ChestQuestLockedHigh.,,TRUE,72000,-1,, +chestquestlockedhighpoia,Aelrynth,,,Opened a ChestQuestLockedHigh.,,TRUE,72000,-1,, +chestquestlockedhighpoib,Aelrynth,,,Opened a ChestQuestLockedHigh.,,TRUE,72000,-1,, +chestquestlockedhighpoic,Aelrynth,,,Opened a ChestQuestLockedHigh.,,TRUE,72000,-1,, +chestquestlockedhighpoid,Aelrynth,,,Opened a ChestQuestLockedHigh.,,TRUE,72000,-1,, +chestquestlockedhighpoie,Aelrynth,,,Opened a ChestQuestLockedHigh.,,TRUE,72000,-1,, +chestquestlockedhighpoif,Aelrynth,,,Opened a ChestQuestLockedHigh.,,TRUE,72000,-1,, +chestquestlockedhighpoig,Aelrynth,,,Opened a ChestQuestLockedHigh.,,TRUE,72000,-1,, +chestquestlockedlow,Aelrynth,,,Opened a ChestQuestLockedLow.,,TRUE,72000,-1,, +chestquestlockedlowgolemmound,Aelrynth,,,Opened a ChestQuestLockedLowGolemMound.,,TRUE,72000,-1,, +chestquestlockedlowlichhut,Aelrynth,,,Opened a ChestQuestLockedLowLichHut.,,TRUE,72000,-1,, +chestquestlockedlowpoia,Aelrynth,,,Opened a ChestQuestLockedLow.,,TRUE,72000,-1,, +chestquestlockedlowpoib,Aelrynth,,,Opened a ChestQuestLockedLow.,,TRUE,72000,-1,, +chestquestlockedlowpoic,Aelrynth,,,Opened a ChestQuestLockedLow.,,TRUE,72000,-1,, +chestquestlockedlowpoid,Aelrynth,,,Opened a ChestQuestLockedLow.,,TRUE,72000,-1,, +chestquestlockedlowpoie,Aelrynth,,,Opened a ChestQuestLockedLow.,,TRUE,72000,-1,, +chestquestlockedlowpoif,Aelrynth,,,Opened a ChestQuestLockedLow.,,TRUE,72000,-1,, +chestquestlockedlowpoig,Aelrynth,,,Opened a ChestQuestLockedLow.,,TRUE,72000,-1,, +chestquestlockedlowratnest,Aelrynth,,,Opened a ChestQuestLockedLowRatNest.,,TRUE,72000,-1,, +chestquestlockedmid,Aelrynth,,,Opened a ChestQuestLockedMid.,,TRUE,72000,-1,, +chestquestlockedmidbanderlingbandittower,Aelrynth,,,Opened a ChestQuestLockedMidBanderlingBanditTower.,,TRUE,72000,-1,, +chestquestlockedmiddaiklos,Aelrynth,,,Opened a ChestQuestLockedMidDaiklos.,,TRUE,72000,-1,, +chestquestlockedmidhilltopdrudgetower,Aelrynth,,,Opened a ChestQuestLockedMidHilltopDrudgeTower.,,TRUE,72000,-1,, +chestquestlockedmidholtburgruin,Aelrynth,,,Opened a ChestQuestLockedMidHoltburgRuin.,,TRUE,72000,-1,, +chestquestlockedmidmushroomaltar,Aelrynth,,,Opened a ChestQuestLockedMidMushroomAltar.,,TRUE,72000,-1,, +chestquestlockedmidpoia,Aelrynth,,,Opened a ChestQuestLockedMid.,,TRUE,72000,-1,, +chestquestlockedmidpoib,Aelrynth,,,Opened a ChestQuestLockedMid.,,TRUE,72000,-1,, +chestquestlockedmidpoic,Aelrynth,,,Opened a ChestQuestLockedMid.,,TRUE,72000,-1,, +chestquestlockedmidpoid,Aelrynth,,,Opened a ChestQuestLockedMid.,,TRUE,72000,-1,, +chestquestlockedmidpoie,Aelrynth,,,Opened a ChestQuestLockedMid.,,TRUE,72000,-1,, +chestquestlockedmidpoif,Aelrynth,,,Opened a ChestQuestLockedMid.,,TRUE,72000,-1,, +chestquestlockedmidpoig,Aelrynth,,,Opened a ChestQuestLockedMid.,,TRUE,72000,-1,, +chestquestlockednewbiepoia,Aelrynth,,,Opened a ChestQuestLockedNewbie.,,TRUE,72000,-1,, +chestquestlockednewbiepoib,Aelrynth,,,Opened a ChestQuestLockedNewbie.,,TRUE,72000,-1,, +chestquestlockednewbiepoic,Aelrynth,,,Opened a ChestQuestLockedNewbie.,,TRUE,72000,-1,, +chestquestlockednewbiepoid,Aelrynth,,,Opened a ChestQuestLockedNewbie.,,TRUE,72000,-1,, +chestquestlockednewbiepoie,Aelrynth,,,Opened a ChestQuestLockedNewbie.,,TRUE,72000,-1,, +chestquestlockednewbiepoif,Aelrynth,,,Opened a ChestQuestLockedNewbie.,,TRUE,72000,-1,, +chestquestlockednewbiepoig,Aelrynth,,,Opened a ChestQuestLockedNewbie.,,TRUE,72000,-1,, +chestquestrelic,Aelrynth,,,Opened a ChestQuest,,TRUE,72000,-1,, +chestquestrestingplace,Aelrynth,,,Opened a ChestQuest,,TRUE,72000,-1,, +chestquestunlockedhigh,Aelrynth,,,Opened a ChestQuestUnlockedHigh.,,TRUE,72000,-1,, +chestquestunlockedhighpoia,Aelrynth,,,Opened a ChestQuestUnlockedHigh.,,TRUE,72000,-1,, +chestquestunlockedhighpoib,Aelrynth,,,Opened a ChestQuestUnlockedHigh.,,TRUE,72000,-1,, +chestquestunlockedhighpoic,Aelrynth,,,Opened a ChestQuestUnlockedHigh.,,TRUE,72000,-1,, +chestquestunlockedhighpoid,Aelrynth,,,Opened a ChestQuestUnlockedHigh.,,TRUE,72000,-1,, +chestquestunlockedhighpoie,Aelrynth,,,Opened a ChestQuestUnlockedHigh.,,TRUE,72000,-1,, +chestquestunlockedhighpoif,Aelrynth,,,Opened a ChestQuestUnlockedHigh.,,TRUE,72000,-1,, +chestquestunlockedhighpoig,Aelrynth,,,Opened a ChestQuestUnlockedHigh.,,TRUE,72000,-1,, +chestquestunlockedlow,Aelrynth,,,Opened a ChestQuestUnlockedLow.,,TRUE,72000,-1,, +chestquestunlockedlowdaiklos,Aelrynth,,,Opened a ChestQuestUnlockedLowDaiklos.,,TRUE,72000,-1,, +chestquestunlockedlowdrudgehideout,Aelrynth,,,Opened a ChestQuestUnlockedLowDrudgeHideout.,,TRUE,72000,-1,, +chestquestunlockedlowdungeonfern,Aelrynth,,,Opened a ChestQuestUnlockedLowDungeonFern.,,TRUE,72000,-1,, +chestquestunlockedlowhedgedplatform,Aelrynth,,,Opened a ChestQuestUnlockedLowHedgedPlatform.,,TRUE,72000,-1,, +chestquestunlockedlowpoia,Aelrynth,,,Opened a ChestQuestUnlockedLow.,,TRUE,72000,-1,, +chestquestunlockedlowpoib,Aelrynth,,,Opened a ChestQuestUnlockedLow.,,TRUE,72000,-1,, +chestquestunlockedlowpoic,Aelrynth,,,Opened a ChestQuestUnlockedLow.,,TRUE,72000,-1,, +chestquestunlockedlowpoid,Aelrynth,,,Opened a ChestQuestUnlockedLow.,,TRUE,72000,-1,, +chestquestunlockedlowpoie,Aelrynth,,,Opened a ChestQuestUnlockedLow.,,TRUE,72000,-1,, +chestquestunlockedlowpoif,Aelrynth,,,Opened a ChestQuestUnlockedLow.,,TRUE,72000,-1,, +chestquestunlockedlowpoig,Aelrynth,,,Opened a ChestQuestUnlockedLow.,,TRUE,72000,-1,, +chestquestunlockedlowratnest,Aelrynth,,,Opened a ChestQuestUnlockedLowRatNest.,,TRUE,72000,-1,, +chestquestunlockedmid,Aelrynth,,,Opened a ChestQuestUnlockedMid.,,TRUE,72000,-1,, +chestquestunlockedmidpoia,Aelrynth,,,Opened a ChestQuestUnlockedMid.,,TRUE,72000,-1,, +chestquestunlockedmidpoib,Aelrynth,,,Opened a ChestQuestUnlockedMid.,,TRUE,72000,-1,, +chestquestunlockedmidpoic,Aelrynth,,,Opened a ChestQuestUnlockedMid.,,TRUE,72000,-1,, +chestquestunlockedmidpoid,Aelrynth,,,Opened a ChestQuestUnlockedMid.,,TRUE,72000,-1,, +chestquestunlockedmidpoie,Aelrynth,,,Opened a ChestQuestUnlockedMid.,,TRUE,72000,-1,, +chestquestunlockedmidpoif,Aelrynth,,,Opened a ChestQuestUnlockedMid.,,TRUE,72000,-1,, +chestquestunlockedmidpoig,Aelrynth,,,Opened a ChestQuestUnlockedMid.,,TRUE,72000,-1,, +chestquestunlockednewbiepoia,Aelrynth,,,Opened a ChestQuestUnlockedNewbie.,,TRUE,72000,-1,, +chestquestunlockednewbiepoib,Aelrynth,,,Opened a ChestQuestUnlockedNewbie.,,TRUE,72000,-1,, +chestquestunlockednewbiepoic,Aelrynth,,,Opened a ChestQuestUnlockedNewbie.,,TRUE,72000,-1,, +chestquestunlockednewbiepoid,Aelrynth,,,Opened a ChestQuestUnlockedNewbie.,,TRUE,72000,-1,, +chestquestunlockednewbiepoie,Aelrynth,,,Opened a ChestQuestUnlockedNewbie.,,TRUE,72000,-1,, +chestquestunlockednewbiepoif,Aelrynth,,,Opened a ChestQuestUnlockedNewbie.,,TRUE,72000,-1,, +chestquestunlockednewbiepoig,Aelrynth,,,Opened a ChestQuestUnlockedNewbie.,,TRUE,72000,-1,, +chestquestwizardsblade,Aelrynth,,,Opened a ChestQuest,,TRUE,72000,-1,, +chestsawatobanditfort,Aelrynth,,,Timer for the Old Runed Chest at Sawato Bandit Fort,,TRUE,72000,-1,, +chiefgrogbashbet,Aelrynth,,,Player bet on Chief Grogbash,,FALSE,0,1,set by Chief Grogbash, +chitinrot1,Aelrynth,,,Player picked up OlthoiChitin.,,TRUE,72000,-1,, +chorizitea,Aelrynth,,,Chorizite Refined A,,TRUE,57600,-1,set by Feruza ibn Salaq, +choriziteb,Aelrynth,,,Chorizite Refined B,,TRUE,57600,-1,set by Feruza ibn Salaq, +chorizitec,Aelrynth,,,Chorizite Refined C,,TRUE,57600,-1,set by Feruza ibn Salaq, +chunkyore_turnins,Aelrynth,,,Turn in amount for Chunky Ore Collection,,TRUE,0,5,set by Mine Foreman, +chunkyore_wait,Aelrynth,,,Wait timer for Chunky Ore Collection,,TRUE,72000,-1,set by Mine Foreman, +claudecount,Aelrynth,,,Player turned in a reflection in Claude's Mind.,,TRUE,0,-1,set by Claude the Archmage, +claudegotreflection,Aelrynth,,,Human got its reflection in Claude's Mind.,,FALSE,0,1,set by Human, +claudekillcount,Aelrynth,,,Player killed an Elite shadow in Claude's Mind.,,TRUE,0,-1,set by Claude Witnessing History Stopgap, +clawofthehopeslayerfirstrun,Aelrynth,,,Stamped on first turn in of Claw of the Hopeslayer,,FALSE,0,1,set by Aun Aemaua, +clawofthehopeslayerpickuptimer,Aelrynth,,,Picked up Claw of the Hopeslayer,,TRUE,72000,-1,, +cleansingthethronestart_1209,Aelrynth,,,quest timer,,FALSE,0,1,set by Shade of Antemy, +cleansingthethronewaiting_1209,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Shade of Antemy, +climbedviridianderu,Aelrynth,,,quest timer,,FALSE,0,1,set by Doriathazaar, +clonekillerextreme,Aelrynth,,,Player has killed a extreme replica statue and can enter the low statue dungeon.,,FALSE,0,1,, +clonekillerhigh,Aelrynth,,,Player has killed a high replica statue and can enter the low statue dungeon.,,FALSE,0,1,, +clonekillerlow,Aelrynth,,,Player has killed a low replica statue and can enter the low statue dungeon.,,FALSE,0,1,, +clonekillermid,Aelrynth,,,Player has killed a midreplica statue and can enter the low statue dungeon.,,FALSE,0,1,, +cluecardpickedup,Aelrynth,,,You have picked up the clue card.,,TRUE,72000,-1,, +clutchkingscomplete,Aelrynth,,,You've killed all six Burun Kings.,,TRUE,72000,-1,set by Guard Devon, +codedtanadascrollpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +coffinquestlockedlowholtburgdungeon,Aelrynth,,,Opened a CoffinQuestLockedLowHoltburgDungeon.,,TRUE,72000,-1,, +coilbanderling,Aelrynth,,,Player has picked up a banderling coil and cannot pick up another for 1 day.,,TRUE,72000,-1,, +coilbanderlinggiven,Aelrynth,,,Player has given this coil and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +coilbenten,Aelrynth,,,Player has picked up a Ben Ten coil and cannot pick up another for 1 day.,,TRUE,72000,-1,, +coilbentengiven,Aelrynth,,,Player has given this coil and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +coilsclavus,Aelrynth,,,Player has picked up a Sclavus coil and cannot pick up another for 1 day.,,TRUE,72000,-1,, +coilsclavusgiven,Aelrynth,,,Player has given this coil and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +coilskeleton,Aelrynth,,,Player has picked up a Skeleton coil and cannot pick up another for 1 day.,,TRUE,72000,-1,, +coilskeletongiven,Aelrynth,,,Player has given this coil and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +coilthorsten,Aelrynth,,,Player has picked up a Thorsten coil and cannot pick up another for 1 day.,,TRUE,72000,-1,, +coilthorstengiven,Aelrynth,,,Player has given this coil and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +coilzharalim,Aelrynth,,,Player has picked up a Zharalim coil and cannot pick up another for 1 day.,,TRUE,72000,-1,, +coilzharalimgiven,Aelrynth,,,Player has given this coil and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +coinattachmentpickup,Aelrynth,,,You've picked up the Coin of Attachment,,FALSE,0,1,, +colierminetreasurekey,Aelrynth,,,The Treasure Key for Colier Mine,,TRUE,72000,-1,, +collectoralchemyalulow,Aelrynth,,,You have turned in a Low alchemy arts&crafts item.,,TRUE,72000,-1,set by Apprentice Alchemist, +collectoralchemyalumid,Aelrynth,,,You have turned in a Mid alchemy arts&crafts item.,,TRUE,72000,-1,set by Journeyman Alchemist, +collectoralchemyalunewbie,Aelrynth,,,You have turned in a newbie alchemy arts&crafts item.,,TRUE,72000,-1,set by Apprentice Alchemist, +collectoralchemyghalow,Aelrynth,,,You have turned in a Low alchemy arts&crafts item.,,TRUE,72000,-1,set by Apprentice Alchemist, +collectoralchemyghamid,Aelrynth,,,You have turned in a Mid alchemy arts&crafts item.,,TRUE,72000,-1,set by Journeyman Alchemist, +collectoralchemyghanewbie,Aelrynth,,,You have turned in a newbie alchemy arts&crafts item.,,TRUE,72000,-1,set by Apprentice Alchemist, +collectoralchemysholow,Aelrynth,,,You have turned in a Low alchemy arts&crafts item.,,TRUE,72000,-1,set by Apprentice Alchemist, +collectoralchemyshomid,Aelrynth,,,You have turned in a Mid alchemy arts&crafts item.,,TRUE,72000,-1,set by Journeyman Alchemist, +collectoralchemyshonewbie,Aelrynth,,,You have turned in a newbie alchemy arts&crafts item.,,TRUE,72000,-1,set by Apprentice Alchemist, +collectorcookingalulow,Aelrynth,,,You have turned in a Low cooking arts&crafts item.,,TRUE,72000,-1,set by Apprentice Cook, +collectorcookingalumid,Aelrynth,,,You have turned in a Mid cooking arts&crafts item.,,TRUE,72000,-1,set by Journeyman Cook, +collectorcookingalunewbie,Aelrynth,,,You have turned in a newbie cooking arts&crafts item.,,TRUE,72000,-1,set by Apprentice Cook, +collectorcookingghalow,Aelrynth,,,You have turned in a Low cooking arts&crafts item.,,TRUE,72000,-1,set by Apprentice Cook, +collectorcookingghamid,Aelrynth,,,You have turned in a Mid cooking arts&crafts item.,,TRUE,72000,-1,set by Journeyman Cook, +collectorcookingghanewbie,Aelrynth,,,You have turned in a newbie cooking arts&crafts item.,,TRUE,72000,-1,set by Apprentice Cook, +collectorcookingsholow,Aelrynth,,,You have turned in a Low cooking arts&crafts item.,,TRUE,72000,-1,set by Apprentice Cook, +collectorcookingshomid,Aelrynth,,,You have turned in a Mid cooking arts&crafts item.,,TRUE,72000,-1,set by Journeyman Cook, +collectorcookingshonewbie,Aelrynth,,,You have turned in a newbie cooking arts&crafts item.,,TRUE,72000,-1,set by Apprentice Cook, +collectorfletchingalulow,Aelrynth,,,You have turned in a Low fletching arts&crafts item.,,TRUE,72000,-1,set by Apprentice Fletcher, +collectorfletchingalumid,Aelrynth,,,You have turned in a Mid fletching arts&crafts item.,,TRUE,72000,-1,set by Journeyman Fletcher, +collectorfletchingalunewbie,Aelrynth,,,You have turned in a newbie fletching arts&crafts item.,,TRUE,72000,-1,set by Apprentice Fletcher, +collectorfletchingghalow,Aelrynth,,,You have turned in a Low fletching arts&crafts item.,,TRUE,72000,-1,set by Apprentice Fletcher, +collectorfletchingghamid,Aelrynth,,,You have turned in a Mid fletching arts&crafts item.,,TRUE,72000,-1,set by Journeyman Fletcher, +collectorfletchingghanewbie,Aelrynth,,,You have turned in a newbie fletching arts&crafts item.,,TRUE,72000,-1,set by Apprentice Fletcher, +collectorfletchingsholow,Aelrynth,,,You have turned in a Low fletching arts&crafts item.,,TRUE,72000,-1,set by Apprentice Fletcher, +collectorfletchingshomid,Aelrynth,,,You have turned in a Mid fletching arts&crafts item.,,TRUE,72000,-1,set by Journeyman Fletcher, +collectorfletchingshonewbie,Aelrynth,,,You have turned in a newbie fletching arts&crafts item.,,TRUE,72000,-1,set by Apprentice Fletcher, +coloarenacooldownactive,Aelrynth,,,Cooldown Active for a Colo Arena,,FALSE,0,1,"set by Arena Five Statue, Arena Four Statue, Arena One Statue and 2 more", +coloarenafiveaccess,Aelrynth,,,Access to Colo Arena Five,,TRUE,3600,-1,"set by Advanced Colosseum Arena, Arena Five Statue, Colosseum Arena and 1 more", +coloarenafiveboot,Aelrynth,,,Boot Timer for Colo Arena Five,,TRUE,3588,-1,set by Arena Five Statue, +coloarenafivewait,Aelrynth,,,Cooldown for Colo Arena Five,,TRUE,10,-1,set by Master Arbitrator, +coloarenafouraccess,Aelrynth,,,Access to Colo Arena Four,,TRUE,3600,-1,"set by Advanced Colosseum Arena, Arena Four Statue, Colosseum Arena and 1 more", +coloarenafourboot,Aelrynth,,,Boot Timer for Colo Arena Four,,TRUE,3588,-1,set by Arena Four Statue, +coloarenafourwait,Aelrynth,,,Cooldown for Colo Arena Four,,TRUE,10,-1,set by Master Arbitrator, +coloarenaoneaccess,Aelrynth,,,Access to Colo Arena One,,TRUE,3600,-1,"set by Advanced Colosseum Arena, Arena One Statue, Colosseum Arena and 1 more", +coloarenaoneboot,Aelrynth,,,Boot Timer for Colo Arena One,,TRUE,3588,-1,set by Arena One Statue, +coloarenaonewait,Aelrynth,,,Cooldown for Colo Arena One,,TRUE,10,-1,set by Master Arbitrator, +coloarenaroomstarted,Aelrynth,,,Arena Bell has started the first wave in a Colo Arena,,FALSE,0,1,set by Arena Bell, +coloarenathreeaccess,Aelrynth,,,Access to Colo Arena Three,,TRUE,3600,-1,"set by Advanced Colosseum Arena, Arena Three Statue, Colosseum Arena and 1 more", +coloarenathreeboot,Aelrynth,,,Boot Timer for Colo Arena Three,,TRUE,3588,-1,set by Arena Three Statue, +coloarenathreewait,Aelrynth,,,Cooldown for Colo Arena Three,,TRUE,10,-1,set by Master Arbitrator, +coloarenatwoaccess,Aelrynth,,,Access to Colo Arena Two,,TRUE,3600,-1,"set by Advanced Colosseum Arena, Arena Two Statue, Colosseum Arena and 1 more", +coloarenatwoboot,Aelrynth,,,Boot Timer for Colo Arena Two,,TRUE,3588,-1,set by Arena Two Statue, +coloarenatwowait,Aelrynth,,,Cooldown for Colo Arena Two,,TRUE,10,-1,set by Master Arbitrator, +coloarenawait,Aelrynth,,,Cooldown for a Colo Arena,,TRUE,60,-1,"set by Arena Five Statue, Arena Four Statue, Arena One Statue and 2 more", +colocritterskilled,Aelrynth,,,Player has killed a creature found in a Colo Arena,,TRUE,0,-1,"set by Colo Final Room Coordinator, Colo Room Coordinator", +colofinalroomwavespassed,Aelrynth,,,Player has passed a wave in the final room of a Colo Arena,,TRUE,0,5,set by Colo Final Room Coordinator, +colonextwavearmed,Aelrynth,,,Arena Bell is preparing to start a new wave in a Colo Arena,,FALSE,0,1,"set by Colo Final Room Coordinator, Colo Room Coordinator", +color10completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 10,,FALSE,0,1,checked by Master Arbitrator, +color11completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 11,,FALSE,0,1,checked by Master Arbitrator, +color12completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 12,,FALSE,0,1,checked by Master Arbitrator, +color13completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 13,,FALSE,0,1,checked by Master Arbitrator, +color14completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 14,,FALSE,0,1,checked by Master Arbitrator, +color15completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 15,,FALSE,0,1,checked by Master Arbitrator, +color16completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 16,,FALSE,0,1,checked by Master Arbitrator, +color17completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 17,,FALSE,0,1,checked by Master Arbitrator, +color18completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 18,,FALSE,0,1,checked by Master Arbitrator, +color1completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 1,,FALSE,0,1,checked by Master Arbitrator, +color2completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 2,,FALSE,0,1,checked by Master Arbitrator, +color3completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 3,,FALSE,0,1,checked by Master Arbitrator, +color4completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 4,,FALSE,0,1,checked by Master Arbitrator, +color5completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 5,,FALSE,0,1,checked by Master Arbitrator, +color6completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 6,,FALSE,0,1,checked by Master Arbitrator, +color7completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 7,,FALSE,0,1,checked by Master Arbitrator, +color8completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 8,,FALSE,0,1,checked by Master Arbitrator, +color9completed,Aelrynth,,,Player Beat (and used exit portal) Colo Arena Room 9,,FALSE,0,1,checked by Master Arbitrator, +coloredportal,Aelrynth,,,Player counter for how many portals entered in Rynthid Assessment.,,TRUE,0,4,"set by Blue Portal, Green Portal, Orange Portal and 3 more", +coloredportal1blue,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Blue Portal, +coloredportal1green,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Green Portal, +coloredportal1orange,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Orange Portal, +coloredportal1red,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Red Portal, +coloredportal1white,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by White Portal, +coloredportal1yellow,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Yellow Portal, +coloredportal2blue,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Blue Portal, +coloredportal2green,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Green Portal, +coloredportal2orange,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Orange Portal, +coloredportal2red,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Red Portal, +coloredportal2white,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by White Portal, +coloredportal2yellow,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Yellow Portal, +coloredportal3blue,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Blue Portal, +coloredportal3green,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Green Portal, +coloredportal3orange,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Orange Portal, +coloredportal3red,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Red Portal, +coloredportal3white,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by White Portal, +coloredportal3yellow,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Yellow Portal, +coloredportal4blue,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Blue Portal, +coloredportal4green,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Green Portal, +coloredportal4orange,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Orange Portal, +coloredportal4red,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Red Portal, +coloredportal4white,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by White Portal, +coloredportal4yellow,Aelrynth,,,Player flag for colored portal in Rynthid Assessment.,,FALSE,0,1,set by Yellow Portal, +coloredportalleverpull,Aelrynth,,,Player counter for how many levers pulled in Rynthid Assessment.,,TRUE,0,5,"set by Blue Lever, Green Lever, Orange Lever and 3 more", +coloredportalleverpullcompleted,Aelrynth,,,Player flag for completing lever pull successfully in Rynthid Assessment.,,FALSE,0,1,"set by Blue Lever, Green Lever, Orange Lever and 3 more", +colorpuzzleballpickedup,Aelrynth,,,You have picked up a colored ball.,,TRUE,120,-1,, +colorpuzzleblueriddle,Aelrynth,,,You got a riddle from the clue card.,,TRUE,72000,-1,set by Clue Card, +colorpuzzlecompleted,Aelrynth,,,You've compleated the Clutch of Kings color puzzle.,,TRUE,72000,-1,set by Arbiter, +colorpuzzlegreenriddle,Aelrynth,,,You got a riddle from the clue card.,,TRUE,72000,-1,set by Clue Card, +colorpuzzleindigoriddle,Aelrynth,,,You got a riddle from the clue card.,,TRUE,72000,-1,set by Clue Card, +colorpuzzleorangeriddle,Aelrynth,,,You got a riddle from the clue card.,,TRUE,72000,-1,set by Clue Card, +colorpuzzleredriddle,Aelrynth,,,You got a riddle from the clue card.,,TRUE,72000,-1,set by Clue Card, +colorpuzzlevioletriddle,Aelrynth,,,You got a riddle from the clue card.,,TRUE,72000,-1,set by Clue Card, +colorpuzzleyellowriddle,Aelrynth,,,You got a riddle from the clue card.,,TRUE,72000,-1,set by Clue Card, +colosseumboss10xpass,Aelrynth,,,Access timer for Gladiator Diemos Pass,,TRUE,86400,-1,set by Gladiator Diemos, +colosseummedallionofhonorturnin,Aelrynth,,,Player has turned in a Colosseum Medallion of Honor to the Arcanum Mana-smith,,TRUE,1209600,-1,set by Arcanum Mana-smith, +coloticketpayment,Aelrynth,,,Payment Received In Full for Colo Ticket,,TRUE,0,4,set by Colosseum Ticket Vendor, +colowaveinprogress,Aelrynth,,,Arena Bell has started a wave in a Colo Arena,,FALSE,0,1,"set by Colo Final Room Coordinator, Colo Room Coordinator", +colowavespassed,Aelrynth,,,Player has passed a wave in a Colo Arena,,TRUE,0,4,set by Colo Room Coordinator, +completed_gwi100_1205,Aelrynth,,,Completed Glenden Wood Invasion Mid quest,,TRUE,72000,-1,set by Captain Sovano, +completed_gwi130_1205,Aelrynth,,,Completed Glenden Wood Invasion High quest,,TRUE,72000,-1,set by Captain Anrayl, +completed_gwi80_1205,Aelrynth,,,Completed Glenden Wood Invasion Low quest,,TRUE,72000,-1,set by Captain Nyino, +completedcolosseum,Aelrynth,,,Completed Colosseum,,TRUE,0,-1,set by Master Arbitrator, +completedtempleixirzi,Aelrynth,,,Player has defeated the Temple of Ixir Zi.,,TRUE,72000,-1,"set by Crimson Brace of Pain, Crown of Anointed Blood, Ensorcelled Falchion and 4 more", +completedtempleliazk,Aelrynth,,,Player has received a reward for Liazk Itzi's temple.,,TRUE,72000,-1,"set by Bladed Bow of Impaling, Fist of Massacre, Scroll of Acumen of the Conclave and 7 more", +contractquestcounter_0511,Aelrynth,,,Complete contracts from the Contract Brokers for extra rewards,,TRUE,0,35,"set by Alchemy Forge, Aurten Rhell, Camp Blacksmith and 30 more", +contractquestsolves,Aelrynth,,,QuestBits to Tracker Which Level of Broker Contract Quests have been solved,,TRUE,0,127,, +cookingvat1,Aelrynth,,,quest timer,,FALSE,0,1,set by Cooking Vat, +cookingvat2,Aelrynth,,,quest timer,,FALSE,0,1,set by Cooking Vat, +cookingvat3,Aelrynth,,,quest timer,,FALSE,0,1,set by Cooking Vat, +cookingvat4,Aelrynth,,,quest timer,,FALSE,0,1,set by Cooking Vat, +cookingvat5,Aelrynth,,,quest timer,,FALSE,0,1,set by Cooking Vat, +cookingvat6,Aelrynth,,,quest timer,,FALSE,0,1,set by Cooking Vat, +coppercogtrooperkillcount,Aelrynth,,,kill count,,TRUE,0,25,set by Lieutenant Zin, +coppercogtrooperkilltask,Aelrynth,,,kill task timer,,TRUE,72000,-1,set by Lieutenant Zin, +coppergolemkingpinkillcount,Aelrynth,,,Copper Golem Kingpin Kill Counter,,TRUE,0,5,, +coppergolemkingpinkilltask,Aelrynth,,,Copper Golem Kingpin Kill Task,,TRUE,72000,-1,, +copperinvaderlordhelm,Aelrynth,,,Timer for Copper Lord Helm,,TRUE,72000,-1,, +copperknightmedallion,Aelrynth,,,Defense of Zaikhal Medallion Pickup Timer Copper,,TRUE,72000,-1,set by Jun Sawashima, +copperlegionchestkey,Aelrynth,,,Pick Up Key for Copper Chest,,TRUE,72000,-1,, +copperlegiondoorkey,Aelrynth,,,Pick Up Key for Door to Copper Legion,,TRUE,72000,-1,, +coralgolemkillcount,Aelrynth,,,Coral Golem Hunting: Coral Shield,,TRUE,0,50,set by Malrin, +coralgolemviceroykillcount,Aelrynth,,,Coral Golem Viceroy Kill Counter,,TRUE,0,5,, +coralgolemviceroykilltask,Aelrynth,,,Coral Golem Viceroy Kill Task,,TRUE,72000,-1,, +coraltowerblackdead,Aelrynth,,,CoralTowerBlackDead,,FALSE,0,1,set by Coral Tower, +coraltowerbluedead,Aelrynth,,,CoralTowerBlueDead,,FALSE,0,1,set by Coral Tower, +coraltowergreendead,Aelrynth,,,CoralTowerGreenDead,,FALSE,0,1,set by Coral Tower, +coraltowerreddead,Aelrynth,,,CoralTowerRedDead,,FALSE,0,1,set by Coral Tower, +coraltowerwhitedead,Aelrynth,,,CoralTowerWhiteDead,,FALSE,0,1,set by Coral Tower, +corettotestament,Aelrynth,,,Pickup timer on Coretto Testament (Knights of Karlun),,TRUE,72000,-1,checked by Sir Ginazio, +corruptedessencecount,Aelrynth,,,Corrupted Essence Counter,,TRUE,0,100,"set by Francois di Terli, The Deep, Tyrina of Arwic", +corruptedessenceturnintimer,Aelrynth,,,Corrupted Essence Day Timer,,TRUE,86400,-1,"set by Francois di Terli, The Deep, Tyrina of Arwic", +corruptedgravestonekillcount,Aelrynth,,,Corrupted Gravestone Kill Counter,,TRUE,0,6,, +corruptedgravestonekilltask,Aelrynth,,,Corrupted Gravestone Kill Task,,TRUE,72000,-1,, +corruptedharbingerblood_pickup,Aelrynth,,,Player has picked up Corrupted Harbinger Blood.,,TRUE,72000,-1,, +countdardantesnotespickuptimer,Aelrynth,,,Count Dardante's Notes pickup timer,,TRUE,72000,-1,checked by Royal Guard Qumasha, +counterfeitwritcratefakepearls,Aelrynth,,,Counterfeit Writ Quest Crate of Fake Pearls Pickup,,TRUE,72000,-1,, +counterfeitwritstart,Aelrynth,,,Counterfeit Writ Quest On Use Shanrek,,TRUE,72000,-1,set by Shanrek the Forger, +coveapplewine,Aelrynth,,,Trade Alliance Quest Pickup Timer on Cove Apple Wine,,TRUE,72000,-1,, +coveoswaldtaken,Aelrynth,,,Took the poisoned cider,,TRUE,72000,-1,, +coveoswaldulgrim,Aelrynth,,,Ulgrim needs the cider,,TRUE,72000,-1,set by Lubziklan al-Luq, +cowtipcounter,Aelrynth,,,Counter for how many cows Player has tipped,,TRUE,0,300,"set by Cow, Dwennon", +cowtipwait,Aelrynth,,,Cow Tipping Quest cooldown timer,,TRUE,72000,-1,set by Dwennon, +craftershardpickup,Aelrynth,,,Asteliary Crafter's Message Shard pickup timer,,TRUE,72000,-1,, +craftingforgecompleted0710,Aelrynth,,,Completed one of the Crafting Forges,,TRUE,72000,-1,"set by Alchemy Forge, Cooking Forge, Fletching Forge and 2 more", +craftingforgeused1204,Aelrynth,,,you've used any crafting forge,,FALSE,0,1,"set by Alchemy Forge, Cooking Forge, Fletching Forge and 2 more", +crestlugian,Aelrynth,,,Lugian Commander Trophy,,TRUE,72000,-1,, +crimsonbrokenhaft,Aelrynth,,,Crimson Broken Haft,,TRUE,72000,-1,set by Leikotha, +crimsonbrokenhaft2,Aelrynth,,,Crimson Broken Haft 2,,TRUE,72000,-1,set by Kayna bint Iswas, +crimsonrepairedhaft,Aelrynth,,,Crimson Repaired Haft,,TRUE,72000,-1,, +crimsonruby1,Aelrynth,,,Crimson Ruby 1,,TRUE,72000,-1,, +crimsonruby2,Aelrynth,,,Crimson Ruby 2,,TRUE,72000,-1,, +crimsonruby3,Aelrynth,,,Crimson Ruby 3,,TRUE,72000,-1,, +crimsonruby4,Aelrynth,,,Crimson Ruby 4,,TRUE,72000,-1,, +crimsonruby5,Aelrynth,,,Crimson Ruby 5,,TRUE,72000,-1,, +crimsonscarabpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +crossedroad,Aelrynth,,,The Chicken has crossed the road.,,FALSE,0,1,"set by Blinded Apparition, Corrupt Gear Sentry, Paradox-touched Olthoi Sentinel and 1 more", +cruciblegivenhiro,Aelrynth,,,This quest flag is obsolete.,,FALSE,0,1,, +cryptcrimsonnightflagged,Aelrynth,,,Flagged to enter Crypt of Crimson Night,,FALSE,0,1,set by Maqudh al Nishadina, +crystalfinalpickup0509,Aelrynth,,,Picked up Crystalline Array Fragment,,TRUE,72000,-1,, +crystalidolneftetkillcount,Aelrynth,,,Crystal Idol Dungeon Kill Counter,,TRUE,0,20,set by Altar of the Black Crystal, +crystalidolneftetkilltask,Aelrynth,,,Crystal Idol Kill Task,,TRUE,72000,-1,set by Altar of the Black Crystal, +crystallineboundwisp,Aelrynth,,,Player has reached the Bound Wisp,,TRUE,72000,-1,, +crystallinekiller,Aelrynth,,,Crystalline Killer,,TRUE,72000,-1,, +crystallinemarker10x,Aelrynth,,,Found 10 Crystalline Markers,,FALSE,0,1,set by Jyotsana, +crystallinemarker15x,Aelrynth,,,Found 15 Crystalline Markers,,FALSE,0,1,set by Jyotsana, +crystallinemarker20x,Aelrynth,,,Found 20 Crystalline Markers,,FALSE,0,1,set by Jyotsana, +crystallinemarker25x,Aelrynth,,,Found 25 Crystalline Markers,,FALSE,0,1,set by Jyotsana, +crystallinemarker5x,Aelrynth,,,Found 5 Crystalline Markers,,FALSE,0,1,set by Jyotsana, +crystallinemarkercounter0109,Aelrynth,,,Crystalline Markers Counter,,TRUE,0,25,set by Crystal, +crystallinemarkersfound,Aelrynth,,,Crystalline Markers Found by Player,,TRUE,0,33554431,, +crystallinemarkerstart,Aelrynth,,,Started Crystalline Markers Quest,,FALSE,0,1,set by Jyotsana, +crystallineshardturnin,Aelrynth,,,Turned in Crystalline Shard,,TRUE,0,20,set by Tokashi Ando, +crystallineshardturninwait,Aelrynth,,,Turned in Crystalline Shard Wait timer,,TRUE,72000,-1,set by Tokashi Ando, +crystallineskilltest10109wait,Aelrynth,,,Found Crystalline Bound Wisp,,TRUE,72000,-1,set by Bound Wisp, +crystallordhuntercomplete,Aelrynth,,,You've received a key from Tahuirea.,,TRUE,172800,-1,set by Aun Tahuirea, +crystalofthedarkislecrystalshardpickuptimer,Aelrynth,,,Picked up Crystal Shard,,TRUE,72000,-1,, +daggerstatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +dainalive,Aelrynth,,,Lady Dain thinks Gareth Dain is dead.,,TRUE,72000,-1,set by Talira Dain, +daindead,Aelrynth,,,Lady Dain knows Gareth Dain is alive.,,TRUE,72000,-1,set by Dalius Kendmar, +damagedshadowstone,Aelrynth,,,Damaged Shadow Stone pickup timer,,TRUE,72000,-1,, +damagedyalainitomepickup,Aelrynth,,,Player has picked up a Damaged Yalaini Tome,,TRUE,72000,-1,, +damenoir1,Aelrynth,,,You've spoken to the dame responsible for the noir quest.,,TRUE,72000,-1,set by Dame Brinna O'Shea, +danbymoarsmencomplete_0508,Aelrynth,,,Player has completed the Danbys Outpost portion of Moarsmen on the Shores,,TRUE,72000,-1,set by Marcus Danby, +darcuschthebarbarianbet,Aelrynth,,,Player bet on Darcusch the Barbarian,,FALSE,0,1,set by Darcusch the Barbarian, +dardantesworkshop_flag,Aelrynth,,,Access granted to Dardantes Workshop,,FALSE,0,1,set by Harkwull the Discreet, +darkapostateshardpickuptimer,Aelrynth,,,Pickup timer for Dark Apostate Shard,,TRUE,3600,-1,, +darkidolscompleted,Aelrynth,,,You've completed the Dark Idols quest.,,TRUE,72000,-1,set by Lighthouse Hermit, +darkisledelivery,Aelrynth,,,Dark Isle Delivery,,TRUE,72000,-1,, +darkisleflagged,Aelrynth,,,Flagged to use Dark Isle portal,,FALSE,0,1,, +darkmonolithreceived,Aelrynth,,,Received a Dark Monolith,,TRUE,72000,-1,set by Dark Monolith, +darkrecordingsstart,Aelrynth,,,quest timer,,FALSE,0,1,set by Black Ferah, +darkspiralbookpickup,Aelrynth,,,Dark Spiral Book Pick Up timer,,TRUE,72000,-1,, +dazzlingshardgiven,Aelrynth,,,Dazzling Shard given to Dmesne,,FALSE,0,1,set by Dmesne, +dcaaccess,Aelrynth,,,Player has paid toll to access Derethian Combat Arena,,FALSE,0,1,set by Derethian Combat Arena Master, +dcadeathstatuecooldown,Aelrynth,,,Player has used the Statue of Death in Derethian Combat Arena,,TRUE,300,-1,set by Statue of Death, +dcadeathstatuetimeout,Aelrynth,,,Player has used the Statue of Death in Derethian Combat Arena,,TRUE,360,-1,set by Statue of Death, +dcalumstatuebitfield,Aelrynth,,,Player has used the Statue of Illuminating Death in Derethian Combat Arena,,TRUE,0,255,, +dcalumstatuecooldown,Aelrynth,,,Player has used the Statue of Illuminating Death in Derethian Combat Arena,,TRUE,30,-1,"set by Statue of Extreme Illumination, Statue of High Illumination, Statue of Illuminating Death", +dcalumstatuetimeout,Aelrynth,,,Player has used the Statue of Illuminating Death in Derethian Combat Arena,,TRUE,60,-1,"set by Statue of Extreme Illumination, Statue of High Illumination, Statue of Illuminating Death", +dcamarksturnedin,Aelrynth,,,Counter for Marks of a Kill turned in,,TRUE,0,-1,"set by Derethian Combat Arena Master, Statue of Death", +deathcap,Aelrynth,,,Deathcap Thrungus Kill Task,,TRUE,72000,-1,, +deathcapkillcount,Aelrynth,,,Deathcap Thrungus Kill Counter,,TRUE,0,25,, +deathcapthrunguskillcount,Aelrynth,,,Deathcap Thrungus Kill Counter,,TRUE,0,25,set by Jiang Li, +deathcapthrunguskilltask,Aelrynth,,,Deathcap Thrungus Kill Task,,TRUE,72000,-1,set by Jiang Li, +deathsallurequestfinished,Aelrynth,,,Death's Allure Timer Flag,,TRUE,72000,-1,set by Hermit, +deathtailfangpickuptimer,Aelrynth,,,Picked up DeathTail Fang,,TRUE,259200,-1,, +decanterofessencesgiven,Aelrynth,,,Need to give all four Essence Decanters to Talar,,TRUE,0,15,, +decanterscollected,Aelrynth,,,Player has collected an essence decanter.,,TRUE,0,10,, +deconstructioncompleted_0213,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Lieutenant Karul, +deconstructionstarted_0213,Aelrynth,,,quest timer,,FALSE,0,1,set by Lieutenant Roothe, +decoratedfalatacotmedallionpickuptimer,Aelrynth,,,Player has picked up Decorated Falatacot Medallion,,TRUE,72000,-1,, +decrepittowercomplete_0511,Aelrynth,,,Handed Refulgent Bracelet to Aurten Rhell,,TRUE,72000,-1,"set by Ufet, Prophet of Blades", +deepcorruptedessencearmorcount,Aelrynth,,,Corrupted Essence turn in counter for Armor Piece,,TRUE,0,-1,set by The Deep, +deepplaces1,Aelrynth,,,You've picked up the first note in Olthoi Tunnels.,,TRUE,72000,-1,, +deepplaces2,Aelrynth,,,You've picked up the second note in Olthoi Tunnels.,,TRUE,72000,-1,, +deepplaces3,Aelrynth,,,You've picked up the third note in Olthoi Tunnels.,,TRUE,72000,-1,, +deepplaces4,Aelrynth,,,You've picked up the fourth note in Olthoi Tunnels.,,TRUE,72000,-1,, +deepplaces5,Aelrynth,,,You've picked up the fifth note in Olthoi Tunnels.,,TRUE,72000,-1,, +deewainattacked_0411,Aelrynth,,,Player attacked Deewain.,,FALSE,0,1,, +deewainbossroomflag,Aelrynth,,,Player has entered Deewains Chamber,,FALSE,0,1,set by Deewain's Chamber, +deewaincompleted0211,Aelrynth,,,Player has turned in Energy Infused Rock,,TRUE,72000,-1,set by Fayza, +deewaingavenote_0411,Aelrynth,,,Player gave note to Deewain.,,FALSE,0,1,, +deewainlegkeypickuptimer,Aelrynth,,,Player has picked up Legendary Key at end of Deewains,,TRUE,72000,-1,, +deewainrocktrophy0211,Aelrynth,,,Player has picked up Energy Infused Rock,,TRUE,72000,-1,, +deewainstarted_0411,Aelrynth,,,Player spoke to Asheron and got note for Deewain .,,FALSE,0,1,, +defeatedbonecrunch,Aelrynth,,,Player has defeated Bonecrunch,,FALSE,0,1,set by Escape Portal, +defeatedibrexijikti,Aelrynth,,,Player has assisted in killing Ibrexi Jikti.,,FALSE,0,1,set by Guardian of the Matriarch's Gaze, +defeatedjexkiki,Aelrynth,,,Player has assisted in killing Jexki Ki.,,FALSE,0,1,set by Guardian of the Matriarch's Gaze, +defeatedkixktixri,Aelrynth,,,Player has assisted in killing Kixkti Xri.,,FALSE,0,1,set by Guardian of the Matriarch's Gaze, +defeatedprodigaldrudgewait,Aelrynth,,,Bonecrunch Wait Timer,,TRUE,72000,-1,set by Jarvis Hammerstone, +defeatedtthuunreward,Aelrynth,,,Summoning Tthuun wait timer.,,TRUE,72000,-1,set by Captain Tulmada, +defeathoshinokeicompleted_0113,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Spirit of Bist'elle, +defeathoshinokeistarted_0113,Aelrynth,,,quest timer,,FALSE,0,1,set by Lord Brem, +defeatingvaeshok,Aelrynth,,,Defeating Vaeshok,,TRUE,72000,-1,, +defenseofzaikhalplatinumshard,Aelrynth,,,Shard of Corcima Pickup Timer - Defense of Zaikhal Platinum,,TRUE,72000,-1,, +defenseofzaikhalroyalblood,Aelrynth,,,Royal Blood Pickup Timer - Defense of Zaikhal Platinum,,TRUE,72000,-1,, +deliveredchrysoberyl,Aelrynth,,,Delivered Chryoberyl,,TRUE,72000,-1,set by Aun Paritea, +deliveredcurebobo_0807,Aelrynth,,,Delivered Cure for Bobo,,TRUE,72000,-1,"set by Oolutanga, the Tusker King", +deliverediolitegem,Aelrynth,,,Delivered the Iolite gem.,,TRUE,72000,-1,set by Aun Paritea, +demonswarmmatroncritterskilled,Aelrynth,,,Player has killed a creature found in Demon Swarm Matron,,TRUE,0,-1,set by Demon Swarm Matron Event Watcher, +depletedaetheriumorecollection,Aelrynth,,,Turned in 10 Depleted Aetherium Ore in Inner Sea Invasion,,TRUE,72000,-1,set by Jin Ato, +dericostchestkey_pickup,Aelrynth,,,Player has picked up Dericost Chest Key,,TRUE,72000,-1,, +dericostlegkeypickuptimer,Aelrynth,,,Picked up Legendary Key in Hidden Treasury,,TRUE,72000,-1,, +dericostquestspawnkilled,Aelrynth,,,Player has killed a critter in Dericost,,TRUE,0,12,, +dericostruinpickup,Aelrynth,,,Dericost Tome Pickup Timer Dericost Ruins Quest,,TRUE,72000,-1,, +dericosttomesgiven,Aelrynth,,,Player has been given the dericost books,,TRUE,72000,-1,set by Bookshelf, +dericostvault_flag,Aelrynth,,,Access granted to the Dericost Vault,,FALSE,0,1,set by Lord Pyrovor, +dericostwave1complete,Aelrynth,,,Player has completed Wave 1,,FALSE,0,1,, +dericostwave2complete,Aelrynth,,,Player has completed Wave 2,,FALSE,0,1,, +dericostwave3complete,Aelrynth,,,Player has completed Wave 3,,FALSE,0,1,, +dericostwave4complete,Aelrynth,,,Player has completed Wave 4,,FALSE,0,1,, +desertareacollectionbracersstart_0511,Aelrynth,,,A'nekshay Bracer,,FALSE,0,1,set by T'ing Setsuko, +desertareacollectionbracerswait_0511,Aelrynth,,,A'nekshay Bracer,,TRUE,72000,-1,set by T'ing Setsuko, +desertareacollectionpayotestart_0511,Aelrynth,,,Prickly Pears,,FALSE,0,1,set by Hammah al Rundik, +desertareacollectionpayotewait_0511,Aelrynth,,,Prickly Pears,,TRUE,72000,-1,set by Hammah al Rundik, +desertareacollectiontabletstart_0511,Aelrynth,,,A'nekshay Bracer,,FALSE,0,1,set by Taylarn bint Tulani, +desertareacollectiontabletwait_0511,Aelrynth,,,A'nekshay Bracer,,TRUE,72000,-1,set by Taylarn bint Tulani, +desertcactuskillcount,Aelrynth,,,Desert Area Cactus Kill Counter,,TRUE,0,6,set by Sir Unell bin Rakke, +desertcactuskilltask,Aelrynth,,,Desert Area Cactus Kill Task,,TRUE,72000,-1,set by Sir Unell bin Rakke, +deservesdarktiderecompense,Aelrynth,,,You deserve the hook-up!,,FALSE,0,1,, +deserveshomecomingflag,Aelrynth,,,You deserve a Homecoming Flag!,,FALSE,0,1,checked by Jalina al-Hajj, +deservesnewyearsgift0105,Aelrynth,,,You deserve a New Year's gift!,,FALSE,0,1,, +deservesrealaidainraiment,Aelrynth,,,Player is able to receive the Realaidain Raiment.,,FALSE,0,1,checked by Adara al-Rajin, +deservesrollbackrecompense0704,Aelrynth,,,You deserve a free level of XP because you lost two days of gameplay on July 25,,FALSE,0,1,, +desolationseainvasionkey_pickup,Aelrynth,,,Pickup timer for Desolation Sea Invasion Key,,TRUE,72000,-1,, +detailmukkirorbnotespickup,Aelrynth,Timer for Gabilles Encoded Notes pickup,,Timer for Gabille's Encoded Notes pickup,Timer for Gabille's Encoded Notes pickup,TRUE,72000,-1,, +deterioratedaegispickup,Aelrynth,,,Picked up the Deteriorated Aegis,,TRUE,72000,-1,, +devastatedwatcherflagged,Aelrynth,,,Flagged to use Devastated Watcher,,FALSE,0,1,set by Devastated Watcher, +devastatedwatchertokengiven,Aelrynth,,,Token given to Devastated Watcher,,FALSE,0,1,set by Devastated Watcher, +deviceroomportalflag,Aelrynth,,,Player has been flagged to use Portal,,FALSE,0,1,, +devourermargulkillcount,Aelrynth,,,Devourer Margul Kill Counter,,TRUE,0,15,, +devourermargulkilltask,Aelrynth,,,Devourer Margul Kill Task,,TRUE,72000,-1,, +direbanderlingtitle,Aelrynth,,,Player has received Dire Champion Banderling Title.,,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +direchampbanderling,Aelrynth,,,Player has killed Dire Champion Banderling.,,FALSE,0,1,set by Dire Champion Banderling, +direchampdailytokencounter,Aelrynth,,,"Player counter for 100 tokens turned in to Aun Javhalrea, the Game Warden to start wait.",,TRUE,0,100,"set by Aun Javhalrea, the Game Warden", +direchampdirehunttitle,Aelrynth,,,Player has received the title Dire Huntsman.,,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +direchampdrudge,Aelrynth,,,Player has killed Dire Champion Drudge.,,FALSE,0,1,set by Dire Champion Drudge, +direchampgamewardentitle,Aelrynth,,,Player has received the title Game Warden.,,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +direchampgolem,Aelrynth,,,Player has killed Dire Champion Golem.,,FALSE,0,1,set by Dire Champion Golem, +direchamphonoraryreatitle,Aelrynth,,,Player has received the title Honorary Rea of the Aun.,,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +direchamplugian,Aelrynth,,,Player has killed Dire Champion Lugian.,,FALSE,0,1,set by Dire Champion Lugian, +direchampmonouga,Aelrynth,,,Player has killed Dire Champion Monouga.,,FALSE,0,1,set by Dire Champion Monouga, +direchampshadow,Aelrynth,,,Player has killed Dire Champion Shadow.,,FALSE,0,1,set by Dire Champion Shadow, +direchampskeleton,Aelrynth,,,Player has killed Dire Champion Skeleton.,,FALSE,0,1,set by Dire Champion Skeleton, +direchampstart,Aelrynth,,,"Player has spoke to Aun Javhalrea, the Game Warden.",,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +direchamptoken_first,Aelrynth,,,Player has turned in their first Token.,,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +direchamptokencounter,Aelrynth,,,"Player counter on tokens turned in to Aun Javhalrea, the Game Warden.",,TRUE,0,100,"set by Aun Javhalrea, the Game Warden", +direchamptokenwait,Aelrynth,,,"Player wait timer for tokens turn in to Aun Javhalrea, the Game Warden.",,TRUE,72000,-1,"set by Aun Javhalrea, the Game Warden", +direchampvirindi,Aelrynth,,,Player has killed Dire Champion Virindi.,,FALSE,0,1,set by Dire Champion Virindi, +diredrudgetitle,Aelrynth,,,Player has received Dire Champion Drudge Title.,,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +diregolemtitle,Aelrynth,,,Player has received Dire Champion Golem Title.,,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +direlandqueenkiller,Aelrynth,,,Player assisted in killing a newbie nest.,,FALSE,0,1,, +direlandsminecommandersgemgiven,Aelrynth,,,Given the Direlands Mine Commander's Gem to Qumasha,,FALSE,0,1,set by Royal Guard Qumasha, +direlandsminecommandersgempickuptimer,Aelrynth,,,Direlands Mine Commander's Gem pickup timer,,TRUE,72000,-1,checked by Royal Guard Qumasha, +direlandsnestkiller,Aelrynth,,,Player assisted in killing a newbie nest.,,FALSE,0,1,, +direlugiantitle,Aelrynth,,,Player has received Dire Champion Lugian Title.,,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +diremattekarkillcount,Aelrynth,,,Dire Mattekar Kill Counter,,TRUE,0,10,set by Fergal the Dire, +diremattekarkilltask,Aelrynth,,,Dire Mattekar Kill Task,,TRUE,72000,-1,set by Fergal the Dire, +diremonougatitle,Aelrynth,,,Player has received Dire Champion Monouga Title.,,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +direshadowtitle,Aelrynth,,,Player has received Dire Champion Shadow Title.,,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +direskeletontitle,Aelrynth,,,Player has received Dire Champion Skeleton Title.,,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +direvirindititle,Aelrynth,,,Player has received Dire Champion Virindi Title.,,FALSE,0,1,"set by Aun Javhalrea, the Game Warden", +diseasedcarnivorousliver_completed,Aelrynth,,,Player has found 15 Diseased Carnivorous Carenzi Livers.,,FALSE,0,1,set by Diseased Carnivorous Carenzi Liver, +diseasedcarnivorousliver_counter,Aelrynth,,,Player Diseased Carnivorous Carenzi Liver Counter.,,TRUE,0,15,set by Diseased Carnivorous Carenzi Liver, +diseasedferalliver_completed,Aelrynth,,,Player has found 30 Diseased Feral Carenzi Livers.,,FALSE,0,1,set by Diseased Feral Carenzi Liver, +diseasedferalliver_counter,Aelrynth,,,Player Diseased Feral Carenzi Liver Counter.,,TRUE,0,30,set by Diseased Feral Carenzi Liver, +diseasedmangyliver_completed,Aelrynth,,,Player has found 20 Diseased Mangy Carenzi Livers.,,FALSE,0,1,set by Diseased Mangy Carenzi Liver, +diseasedmangyliver_counter,Aelrynth,,,Player Diseased Mangy Carenzi Liver Counter.,,TRUE,0,20,set by Diseased Mangy Carenzi Liver, +diseasedpolarliver_completed,Aelrynth,,,Player has found 4 Diseased Polar Carenzi Livers.,,FALSE,0,1,set by Diseased Polar Carenzi Liver, +diseasedpolarliver_counter,Aelrynth,,,Player Diseased Polar Carenzi Liver Counter.,,TRUE,0,5,set by Diseased Polar Carenzi Liver, +diseasedstalkerliver_completed,Aelrynth,,,Player has found 35 Diseased Stalker Carenzi Livers.,,FALSE,0,1,set by Diseased Carenzi Stalker Liver, +diseasedstalkerliver_counter,Aelrynth,,,Player Diseased Stalker Carenzi Liver Counter.,,TRUE,0,35,set by Diseased Carenzi Stalker Liver, +diseasedtaintedliver_completed,Aelrynth,,,Player has found 13 Diseased Tainted Carenzi Livers.,,FALSE,0,1,set by Diseased Tainted Carenzi Liver, +diseasedtaintedliver_counter,Aelrynth,,,Player Diseased Tainted Carenzi Liver Counter.,,TRUE,0,13,set by Diseased Tainted Carenzi Liver, +disgustingseainvasionkey_pickup,Aelrynth,,,Pickup timer for Disgusting Sea Invasion Key,,TRUE,72000,-1,, +distilleryambrosiaquest,Aelrynth,,,Distillery Ambrosia Quest,,TRUE,518400,-1,, +distilleryambrosiaquest2,Aelrynth,,,Distillery Ambrosia Quest,,TRUE,518400,-1,, +distillerydewquest,Aelrynth,,,Distillery Dew Quest,,TRUE,72000,-1,, +distillerynectarquest,Aelrynth,,,Distillery Nectar Quest,,TRUE,518400,-1,, +divinerpheraionskey_pickup,Aelrynth,,,Player has picked up the Diviner Pheraions Key,,TRUE,72000,-1,, +dmesnepyrealbargiven,Aelrynth,,,Pyreal Bar given to Dmesne,,FALSE,0,1,set by Dmesne, +donewithhiypthetoad,Aelrynth,,,Done with Hiyp,,FALSE,0,1,set by Hiyp the Toad, +dravannessencepickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +drudgehideoutcompleted_1111,Aelrynth,,,Completed the Drudge Hideout Quest,,TRUE,72000,-1,set by Alfrin, +drudgekilltasks_start,Aelrynth,,,Player has started Drudge Kill Tasks,,FALSE,0,1,set by Jarvis Hammerstone, +drudgelurkerkillcount,Aelrynth,,,Drudge Lurker Kill Counter,,TRUE,0,100,, +drudgelurkerkilltask,Aelrynth,,,Drudge Lurker Kill Task,,TRUE,72000,-1,, +drudgeplan_start,Aelrynth,,,Player has started Drudge Plan Quest,,FALSE,0,1,set by Jarvis Hammerstone, +drudgeplan_wait,Aelrynth,,,Player has completed Drudge Plan Quest,,TRUE,72000,-1,set by Jarvis Hammerstone, +drudgepresentraidswait,Aelrynth,,,Player wait timer for Drudge Present Raids,,TRUE,72000,-1,set by Holiday Presents, +drudgeravenerkillcount,Aelrynth,,,Drudge Ravener Kill Counter,,TRUE,0,100,, +drudgeravenerkilltask,Aelrynth,,,Drudge Ravener Kill Task,,TRUE,72000,-1,, +drudgestalkerkillcount,Aelrynth,,,Drudge Stalker Kill Counter,,TRUE,0,100,, +drudgestalkerkilltask,Aelrynth,,,Drudge Stalker Kill Task,,TRUE,72000,-1,, +druggedmeat,Aelrynth,,,quest timer,,FALSE,0,1,"set by Bubba, Shady, Spot", +dryreachprisonbreakquest,Aelrynth,,,Dryreach Prison Break,,TRUE,72000,-1,set by Dansha-Ki, +dulecounter,Aelrynth,,,quest timer,,TRUE,0,6,"set by Black Ferah, Emissary of Asheron, Isin Dule", +duleengineerassassin,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +duleinformant,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +dulemiddleman,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +dullaetheriumcorefragment,Aelrynth,,,Fragment pickup timer,,TRUE,72000,-1,, +easternpedestalshard_pickup,Aelrynth,Player has picked up the Shard of the Eastern Pedestal.,,Player has picked up the Shard of the Eastern Pedestal.,Player has picked up the Shard of the Eastern Pedestal.,TRUE,72000,-1,, +easthamsewerswordpickup1110,Aelrynth,,,Player has picked up the Slimy Broad Sword from the Eastham Sewer,,TRUE,72000,-1,, +eastwatchmoarsmencomplete_0508,Aelrynth,,,Player has completed the Eastwatch portion of Moarsmen on the Shores,,TRUE,72000,-1,set by Francisco the Hunter, +eaterpit,Aelrynth,,,Eater pit flagged,,FALSE,0,1,set by Sir Ginazio, +ebongromniekills,Aelrynth,,,Ebon Gromnie Kill Counter,,TRUE,0,25,set by Afra bint Abbas, +ebongromnietask,Aelrynth,,,Ebon Gromnie Kill Task,,TRUE,72000,-1,set by Afra bint Abbas, +ecortochiseloct01,Aelrynth,,,Ecorto's Chisel,,TRUE,43200,-1,, +efllcentermanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Lower Level Center Aetheria Mana Field,,FALSE,0,1,set by Aetheria Mana Field, +eflleastmanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Lower Level East Aetheria Mana Field,,FALSE,0,1,set by Lower Level East Aetheria Mana Field, +efllnorthmanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Lower Level North Aetheria Mana Field,,FALSE,0,1,set by Lower Level North Aetheria Mana Field, +efllsouthmanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Lower Level South Aetheria Mana Field,,FALSE,0,1,set by Lower Level South Aetheria Mana Field, +efllwestmanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Lower Level West Aetheria Mana Field,,FALSE,0,1,set by Lower Level West Aetheria Mana Field, +efmlcentermanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Middle Level Center Aetheria Mana Field,,FALSE,0,1,set by Aetheria Mana Field, +efmleastmanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Middle Level East Aetheria Mana Field,,FALSE,0,1,set by Middle Level East Aetheria Mana Field, +efmlnorthmanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Middle Level North Aetheria Mana Field,,FALSE,0,1,set by Middle Level North Aetheria Mana Field, +efmlsouthmanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Middle Level South Aetheria Mana Field,,FALSE,0,1,set by Middle Level South Aetheria Mana Field, +efmlwestmanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Middle Level West Aetheria Mana Field,,FALSE,0,1,set by Middle Level West Aetheria Mana Field, +efulcentermanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Upper Level Center Aetheria Mana Field,,FALSE,0,1,set by Aetheria Mana Field, +efuleastmanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Upper Level East Aetheria Mana Field,,FALSE,0,1,set by Upper Level East Aetheria Mana Field, +efulnorthmanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Upper Level North Aetheria Mana Field,,FALSE,0,1,set by Upper Level North Aetheria Mana Field, +efulsouthmanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Upper Level South Aetheria Mana Field,,FALSE,0,1,set by Upper Level South Aetheria Mana Field, +efulwestmanafieldused,Aelrynth,,,Used Aligned Mana Stone in EF Upper Level West Aetheria Mana Field,,FALSE,0,1,set by Upper Level West Aetheria Mana Field, +eggretrievalprize,Aelrynth,,,Additional reward counter for Egg Retrieval,,TRUE,0,3,set by Game Coordinator, +eggretrievalprogress,Aelrynth,,,Questbit Tracker for Egg Retrieval,,TRUE,0,255,, +eggretrievalstarted,Aelrynth,,,Timer for Egg Retrieval,,TRUE,180,2,set by Game Coordinator, +eggretrievaltophatwait,Aelrynth,,,Cooldown for Egg Retrieval Top Hat reward,,TRUE,518400,-1,set by Game Coordinator, +eggretrievalwait,Aelrynth,,,Cooldown for Egg Retrieval additional rewards,,TRUE,518400,-1,set by Game Coordinator, +eldrytchwebmember,Aelrynth,,,Player is a member of Eldrytch Web,,FALSE,0,1,set by Arturus of the Eldrytch Web, +electriczenithdead,Aelrynth,,,quest timer,,FALSE,0,1,set by Electric Zenith, +elementalkillcount,Aelrynth,,,Elemental Kill Counter,,TRUE,0,25,, +elementalkilltask,Aelrynth,,,Elemental Kill Task,,TRUE,72000,-1,, +elenabeaconcomplete,Aelrynth,,,Beacon Quest Complete Timer,,TRUE,72000,-1,, +elenagemreceived,Aelrynth,,,Beacon gem received,,FALSE,0,1,, +eleonoranote,Aelrynth,,,Eleonora's Heart Quest - Note Pickup Timer,,TRUE,72000,-1,, +eleonorasheart,Aelrynth,,,Elanora's Heart Quest Pickup Timer,,TRUE,72000,-1,, +elysascouragepickuptimer,Aelrynth,,,Picked up Elysas Courage,,TRUE,72000,-1,, +elysasdeterminationpickuptimer,Aelrynth,,,Picked up Elysas Determination,,TRUE,72000,-1,, +elysashopepickuptimer,Aelrynth,,,Picked up Elysas Hope,,TRUE,72000,-1,, +elysasresolvepickuptimer,Aelrynth,,,Picked up Elysas Resolve,,TRUE,72000,-1,, +emberbrightgiven,Aelrynth,,,Player has received the Bright Ember from Aun Tanua,,FALSE,0,1,, +emberbrightgivennew,Aelrynth,,,Player has received the Bright Ember from Aun Tanua. Created for the March 2004 revision.,,FALSE,0,1,set by Aun Tanua, +emberbrightreceived,Aelrynth,,,Aulakhe has received the Bright Ember,,FALSE,0,1,, +emberbrightreceivednew,Aelrynth,,,Aulakhe has received the Bright Ember,,FALSE,0,1,set by Aun Aulakhe, +emberinvokingpickup,Aelrynth,,,Players can pick up EmberInvoking in 1 month. Added for the March 2004 revision.,,TRUE,72000,-1,, +embossedashenkeypickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +emotetestdrudgekillerquest,Aelrynth,,,Test Emote Drudge Quest,,TRUE,0,2,"set by Emote Test Drudge, WEventCoordinator", +emotetestnpcquest,Aelrynth,,,Test Emote NPC Quest,,TRUE,30,-1,set by WEventCoordinator, +emotetestportal,Aelrynth,,,Test Emote Portal Quest,,TRUE,30,3,set by Emote Test Portal, +emotetestswordquest,Aelrynth,,,Test Emote Sword Quest,,TRUE,75,3,"set by Test Emote NPC, WEventCoordinator", +empoweredwispskillcount,Aelrynth,,,Empowered Wisps Kill Counter,,TRUE,0,50,, +empoweredwispskilltask,Aelrynth,,,Empowered Wisps Kill Task,,TRUE,72000,-1,, +emptyskinpickedup,Aelrynth,,,You have obtained an empty skin.,,TRUE,72000,-1,, +emptysoul,Aelrynth,,,You've begun the Empty Soul quest.,,FALSE,0,1,"set by Han Rin-Jo, Jojii Adherent", +emptysoulcomplete,Aelrynth,,,You've complete the Empty Soul quest.,,TRUE,72000,-1,set by Honshu Takeda, +emptysoulcrystal,Aelrynth,,,You've received the Crystals for Empty Soul.,,TRUE,72000,-1,set by Crystal Formation, +emptysouldragon,Aelrynth,,,You've been allowed to enter the Dungeon for the Dragon part of Empty Soul.,,FALSE,0,1,"set by Miko Li, Jojii Adherent", +emptysoulfirebird,Aelrynth,,,You've been allowed to enter the Dungeon for the Firebird part of Empty Soul.,,FALSE,0,1,set by Jojii Shrine, +emptysoulorb,Aelrynth,,,You've received the Orb for Empty Soul.,,TRUE,72000,-1,set by Smooth Rocks, +emptysoulshield,Aelrynth,,,You've received the Shield for Empty Soul.,,TRUE,72000,-1,set by Smoldering Brazier, +emptysoulunicorn,Aelrynth,,,You've been allowed to enter the Dungeon for the Unicorn part of Empty Soul.,,FALSE,0,1,set by Jojii Shrine, +emptysoulzen,Aelrynth,,,You are allowed to use the buffing aspect of the Empy Soul reward.,,FALSE,0,1,set by Honshu Takeda, +empyreannotebookpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +empyreanportalspacestabilizerhigh_completed,Aelrynth,,,Player wait timer for the high level Empyrean Portalspace Stabilizer Quest.,,TRUE,518400,-1,set by Emissary of Asheron, +empyreanportalspacestabilizerhigh_start,Aelrynth,,,Player has started the high level Empyrean Portalspace Stabilizer Quest.,,FALSE,0,1,set by Emissary of Asheron, +empyreanportalspacestabilizerlow_completed,Aelrynth,,,Player wait timer for the low level Empyrean Portalspace Stabilizer Quest.,,TRUE,518400,-1,set by Emissary of Asheron, +empyreanportalspacestabilizerlow_start,Aelrynth,,,Player has started the low level Empyrean Portalspace Stabilizer Quest.,,FALSE,0,1,set by Emissary of Asheron, +empyreanportalspacestabilizermid_completed,Aelrynth,,,Player wait timer for the mid level Empyrean Portalspace Stabilizer Quest.,,TRUE,518400,-1,set by Emissary of Asheron, +empyreanportalspacestabilizermid_start,Aelrynth,,,Player has started the mid level Empyrean Portalspace Stabilizer Quest.,,FALSE,0,1,set by Emissary of Asheron, +empyreanrescuecompleted_1010,Aelrynth,,,Player has completed the Empyrean Rescue Quest,,TRUE,72000,-1,set by Emissary of Asheron, +empyreanrescuestarted_0910,Aelrynth,,,Player has started the Empyrean Rescue Quest,,FALSE,0,1,set by Emissary of Asheron, +empyreanscalemailshirt,Aelrynth,,,Empyrean Scalemail Shirt,,TRUE,72000,-1,, +empyreansunstone_pickup,Aelrynth,,,Player has picked up the Empyrean Sun Stone,,TRUE,72000,-1,, +enameledfalatacotmedallionpickuptimer,Aelrynth,,,Player has picked up Enameled Falatacot Medallion,,TRUE,72000,-1,, +enchantedmnemosynesfound,Aelrynth,,,Enchanted Mnemosynes Found Bits,,TRUE,0,1023,checked by Sir Learth, +endowmentnuhmudiragiven,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +engorgedbloodstoneshardpickuptimer,Aelrynth,,,Pickup timer for Engorged Bloodstone Shard,,TRUE,72000,-1,, +engorgedeaterjaw,Aelrynth,,,Engorged Eater Jaw,,TRUE,72000,-1,checked by Clemenza, +engravedashenkeypickuptimer,Aelrynth,,,Picked up Engraved Ashen Key,,TRUE,72000,-1,, +engravedfalatacotmedallionpickuptimer,Aelrynth,,,Player has picked up Engraved Falatacot Medallion,,TRUE,72000,-1,, +enhancingmucor_repeat,Aelrynth,,,Player has completed the Enhancing Mucor Quest before,,FALSE,0,1,set by Ley Line, +enhancingmucor_start,Aelrynth,,,Player has started the Enhancing Mucor Quest,,FALSE,0,1,"set by Torgluuk, High Shaman of Kor-Gursha", +enhancingmucor_wait,Aelrynth,,,Enhancing Mucor Quest Wait Timer,,TRUE,72000,-1,set by Ley Line, +enlightenedcelestialhandmaster,Aelrynth,,,Player is an enlightened former master of Celestial Hand,,FALSE,0,1,checked by Promotions Officer, +enlightenedeldrytchwebmaster,Aelrynth,,,Player is an enlightened former master of Eldrytch Web,,FALSE,0,1,checked by Promotions Officer, +enlightenedmastersmedallion_pickup,Aelrynth,,,Player has picked up Enlightened Masters Medallion,,TRUE,72000,-1,, +enlightenedradiantbloodmaster,Aelrynth,,,Player is an enlightened former master of Radiant Blood,,FALSE,0,1,checked by Promotions Officer, +enricoaugmentation,Aelrynth,,,Pickup timer for Augmentation Text,,TRUE,72000,-1,, +enricoaugmentationletterturnin,Aelrynth,,,Player has turned in Augmentation letter.,,FALSE,0,1,set by Enrico di Bellenesse, +enricosbetrayalcomplete_0511,Aelrynth,,,Contract Repeat Timer for Enricos Betrayal,,TRUE,72000,-1,set by Enrico di Bellenesse, +enricouncle,Aelrynth,,,Pickup timer for To My Dear Uncle,,TRUE,72000,-1,, +enricouncleletterturnin,Aelrynth,,,Player has turned in To My Dear Uncle letter.,,FALSE,0,1,set by Enrico di Bellenesse, +enricowarning,Aelrynth,,,Pickup timer for A Warning,,TRUE,72000,-1,, +enricowarningletterturnin,Aelrynth,,,Player has turned in A Warning letter.,,FALSE,0,1,set by Enrico di Bellenesse, +enterbattledungeon,Aelrynth,,,You've entered a battle dungeon.,,TRUE,1800,-1,set by Small Creepy Statue, +enterburuncatacombs,Aelrynth,,,You can now enter the Burun catacombs and fight Morgluuk.,,FALSE,0,1,set by Captain K'rank, +enterelementalcaverns,Aelrynth,,,HemmikTheSlyNPC grants access to the Elemental Caverns.,,FALSE,0,1,set by Hemmik the Sly, +enterharbingerissk,Aelrynth,,,Issk said you can enter the dungeon.,,FALSE,0,1,set by Issk, +enterharbingervincadi,Aelrynth,,,Vincadi said you can enter the dungeon.,,FALSE,0,1,set by Vincadi, +eodcompleted_1013,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Aun Ol'tra, +eodkeypickup_1013,Aelrynth,,,quest timer,,TRUE,72000,-1,, +eodstarted_1013,Aelrynth,,,quest timer,,FALSE,0,1,set by Aun Ol'tra, +erqlegkeypickuptimer,Aelrynth,,,Pickup timer for Legendary Key at the end of Empyrean Rescue Quest,,TRUE,72000,-1,, +escapecompleted_0213,Aelrynth,,,Escape Spirit of Janthef,,TRUE,72000,-1,set by Spirit of Janthef, +escapestarted_0213,Aelrynth,,,Escape Janthef Started,,FALSE,0,1,set by Nekshla, +esperminecommandersgemgiven,Aelrynth,,,Given the Esper Mine Commander's Gem to Qumasha,,FALSE,0,1,set by Royal Guard Qumasha, +esperminecommandersgempickuptimer,Aelrynth,,,Esper Mine Commander's Gem pickup timer,,TRUE,72000,-1,, +essencebraceletreceived,Aelrynth,,,Player has received the Bracelet of Dark Essence,,TRUE,72000,-1,set by Magically Sealed Dais, +essencelockused,Aelrynth,,,Used Essence Lock,,FALSE,0,1,set by Essence Lock, +essenceofartificepickup,Aelrynth,,,Essence of Artifice pickup timer,,TRUE,72000,-1,, +essenceofenchantmentpickup,Aelrynth,,,Essence of Enchantment pickup timer,,TRUE,72000,-1,, +essenceofstrifepickup,Aelrynth,,,Essence of Strife pickup timer,,TRUE,72000,-1,, +essenceofverdancypickup,Aelrynth,,,Essence of Verdancy pickup timer,,TRUE,72000,-1,, +essencerecovered,Aelrynth,,,Player has gotten essence from the essence font.,,FALSE,0,1,, +eventbanderlingkiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventbentenkiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventdrudgekiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventgolemkiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventgrievverkiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventgromniekiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventhighsclavuskiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventhighskeletonkiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventkiller,Aelrynth,,,Player has killed one of the Event Statues.,,FALSE,0,1,checked by Arcanum Researcher, +eventmidsclavuskiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventmidskeletonkiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventmosswartkiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventreedsharkkiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventshadowkiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventthorstenkiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventtumerokkiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventvirindikiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +eventzharalimkiller,Aelrynth,,,Player has killed this event boss,,FALSE,0,1,"checked by Bhab, Arcanum Tinkerer", +evilmazeparchment1,Aelrynth,,,Evil Maze Parchment 1 Quest,,TRUE,72000,-1,, +experimentalshadowstonepickuptimer,Aelrynth,,,Picked up Experimental Shadow Stone,,TRUE,72000,-1,, +explorationmarkerscratercrasherfound,Aelrynth,,,Amount of Crater Crasher Exploration Markers found.,,TRUE,0,5,set by Exploration Marker, +explorationmarkersdaredevilfound,Aelrynth,,,Amount of Daredevil Exploration Markers found.,,TRUE,0,5,set by Exploration Marker, +explorationmarkersfound,Aelrynth,,,Amount of Exploration Markers found.,,TRUE,0,100,set by Exploration Marker, +explorationmarkersfoundingroupa,Aelrynth,,,Amount of Group A Exploration Markers found.,,TRUE,0,1023,, +explorationmarkersfoundingroupb,Aelrynth,,,Amount of Group B Exploration Markers found.,,TRUE,0,1023,, +explorationmarkersfoundingroupc,Aelrynth,,,Amount of Group C Exploration Markers found.,,TRUE,0,1023,, +explorationmarkersfoundingroupd,Aelrynth,,,Amount of Group D Exploration Markers found.,,TRUE,0,1023,, +explorationmarkersfoundingroupe,Aelrynth,,,Amount of Group E Exploration Markers found.,,TRUE,0,1023,, +explorationmarkersfoundingroupf,Aelrynth,,,Amount of Group F Exploration Markers found.,,TRUE,0,1023,, +explorationmarkersfoundingroupg,Aelrynth,,,Amount of Group G Exploration Markers found.,,TRUE,0,1023,, +explorationmarkersfoundingrouph,Aelrynth,,,Amount of Group H Exploration Markers found.,,TRUE,0,1023,, +explorationmarkersfoundingroupi,Aelrynth,,,Amount of Group I Exploration Markers found.,,TRUE,0,1023,, +explorationmarkersfoundingroupj,Aelrynth,,,Amount of Group J Exploration Markers found.,,TRUE,0,1023,, +explorationmarkersgroups,Aelrynth,,,Group of Exploration Markers found.,,TRUE,0,1023,checked by Sean the Speedy, +explorationmarkersmountainclimberfound,Aelrynth,,,Amount of Mountain Climber Exploration Markers found.,,TRUE,0,5,set by Exploration Marker, +explorationmarkerspartygoerfound,Aelrynth,,,Amount of Party-Goer Exploration Markers found.,,TRUE,0,5,set by Exploration Marker, +explorationmarkersskydiverfound,Aelrynth,,,Amount of Sky Diver Exploration Markers found.,,TRUE,0,5,set by Exploration Marker, +explorationmarkersspelunkerfound,Aelrynth,,,Amount of Spelunker Exploration Markers found.,,TRUE,0,5,set by Exploration Marker, +explorationmarkersthemes,Aelrynth,,,Theme Group of Exploration Markers found.,,TRUE,0,63,, +extremeaerfallestaffobtained,Aelrynth,,,quest timer,,TRUE,72000,-1,, +eyekiviklirhaven1,Aelrynth,,,You've used the Eye.,,TRUE,60,-1,set by Eye of the Watcher, +eyekiviklirhaven2,Aelrynth,,,You've used the Eye.,,TRUE,60,-1,set by Eye of the Watcher, +eyekiviklirhaven3,Aelrynth,,,You've used the Eye.,,TRUE,60,-1,set by Eye of the Watcher, +eyekiviklirhaven4,Aelrynth,,,You've used the Eye.,,TRUE,60,-1,set by Eye of the Watcher, +eyekiviklirtrial1,Aelrynth,,,You've used the Eye.,,TRUE,30,-1,set by Eye of the Watcher, +eyekiviklirtrial2,Aelrynth,,,You've used the Eye.,,TRUE,30,-1,set by Eye of the Watcher, +eyekiviklirtrial3,Aelrynth,,,You've used the Eye.,,TRUE,30,-1,set by Eye of the Watcher, +eyekiviklirtrial4,Aelrynth,,,You've used the Eye.,,TRUE,30,-1,set by Eye of the Watcher, +eyekiviklirtrialarena,Aelrynth,,,You've completed the Kivik Lir Combat Trial.,,TRUE,900,-1,set by Guardian of the Arena, +eyekiviklirtrialjump,Aelrynth,,,You've completed the Kivik Lir Agility Trial.,,TRUE,900,-1,set by Eye of the Heights, +eyekiviklirtriallogic,Aelrynth,,,You've completed the Kivik Lir Logic Trial.,,TRUE,900,-1,set by Eye of the Watcher, +facesmukkircomplete1005,Aelrynth,,,Completed Faces of Mukkir quest,,TRUE,72000,-1,set by Qath al-Haddash, +facesmukkircontractcomplete,Aelrynth,Contract Completed for Faces of Mukkir quest,,Contract Completed for Faces of Mukkir quest,,FALSE,0,1,, +facesmukkirnotes1005,Aelrynth,,,Portal flagging for Faces of Mukkir dungeons,,FALSE,0,1,set by Qath al-Haddash, +fachubbanderlingcamp,Aelrynth,,,PERMANENT - FC Quarter Staff of Fire Quest,,FALSE,0,1,set by Warden, +fachubbanderlingcampportal_flag,Aelrynth,,,Player is flagged to use the Banderling Camp portal,,FALSE,0,1,set by Warden, +fachubbellig,Aelrynth,,,PERMANENT - FC Hammer of Lightning Quest,,FALSE,0,1,set by Warden, +fachubbelligportal_flag,Aelrynth,,,Player is flagged to use the Bellig portal,,FALSE,0,1,set by Warden, +fachubblackmire,Aelrynth,,,PERMANENT - FC Blackmire Lore Quest,,FALSE,0,1,set by Warden, +fachubblackmireportal_flag,Aelrynth,,,Player is flagged to use the Blackmire portal,,FALSE,0,1,set by Warden, +fachubcastle,Aelrynth,,,PERMANENT - FC Crown of Bone Quest,,FALSE,0,1,set by Warden, +fachubcastleportal_flag,Aelrynth,,,Player is flagged to use the Castle of Baron Nuvillus portal,,FALSE,0,1,set by Warden, +fachubcatacombs,Aelrynth,,,PERMANENT - FC Mi Krau-Li's Improved Jitte Quest,,FALSE,0,1,set by Warden, +fachubcatacombsportal_flag,Aelrynth,,,Player is flagged to use the Catacombs of the Forgotten portal,,FALSE,0,1,set by Warden, +fachubcolier,Aelrynth,,,PERMANENT - FC Colier Mines Quest,,FALSE,0,1,set by Warden, +fachubcolierportal_flag,Aelrynth,,,Player is flagged to use the Colier portal,,FALSE,0,1,set by Warden, +fachubdangerouscatacombs,Aelrynth,,,PERMANENT - FC Tibri's Fire Spear Quest,,FALSE,0,1,set by Mosswart Warden, +fachubdangerouscatacombsportal_flag,Aelrynth,,,Player is flagged to use the Dangerous Cave portal,,FALSE,0,1,set by Mosswart Warden, +fachubdryreach,Aelrynth,,,PERMANENT - FC Dryreach Resure Quest,,FALSE,0,1,set by Warden, +fachubdryreachportal_flag,Aelrynth,,,Player is flagged to use the Dyreach portal,,FALSE,0,1,set by Warden, +fachubeastham,Aelrynth,,,PERMANENT - FC Mace of the Explorer Quest,,FALSE,0,1,set by Warden, +fachubeasthamportals_flag,Aelrynth,,,Player is flagged to use the portals in the Eastham wing of Facility Hub,,FALSE,0,1,set by Warden, +fachubfledgemasterscamp,Aelrynth,,,PERMANENT - FC Fledgemaster's Tusk Quest,,FALSE,0,1,set by Warden, +fachubfledgemasterscampportal_flag,Aelrynth,,,Player is flagged to use the Fledgemasters Camp portal,,FALSE,0,1,set by Warden, +fachubfolthid,Aelrynth,,,PERMANENT - FC Dagger of Tikola Quest,,FALSE,0,1,set by Warden, +fachubfolthidportal_flag,Aelrynth,,,Player is flagged to use the Folthid Estate portal,,FALSE,0,1,set by Warden, +fachubglendenwood,Aelrynth,,,PERMANENT - FC Glenden Wood Dungeon Quest,,FALSE,0,1,set by Warden, +fachubglendenwoodportal_flag,Aelrynth,,,Player is flagged to use the Glenden Wood portal,,FALSE,0,1,set by Warden, +fachubgreenmiregrave,Aelrynth,,,PERMANENT - FC Green Mire Grave Quest,,FALSE,0,1,set by Warden, +fachubgreenmiregraveportal_flag,Aelrynth,,,Player is flagged to use the Green Mire Grave portal,,FALSE,0,1,set by Warden, +fachubhallsofhelm,Aelrynth,,,PERMANENT - FC Halls of the Helm Quest,,FALSE,0,1,set by Warden, +fachubhallsofhelmportal_flag,Aelrynth,,,Player is flagged to use the Halls of the Helm portal,,FALSE,0,1,set by Warden, +fachubhauntedmansion,Aelrynth,,,PERMANENT - FC Haunted Mansion Quest,,FALSE,0,1,set by Aun Warden, +fachubhauntedmansionportal_flag,Aelrynth,,,Player is flagged to use the Haunted Mansion portal,,FALSE,0,1,set by Aun Warden, +fachubhuntersleap,Aelrynth,,,PERMANENT - FC Hunter's Leap Quest,,FALSE,0,1,set by Warden, +fachubhuntersleapportal_flag,Aelrynth,,,Player is flagged to use the Hunters Leap portal,,FALSE,0,1,set by Warden, +fachubmitemaze,Aelrynth,,,PERMANENT - FC Branith's Stolen Possessions Quest,,FALSE,0,1,set by Warden, +fachubmitemazeportal_flag,Aelrynth,,,Player is flagged to use the Mite Maze portal,,FALSE,0,1,set by Warden, +fachubmosswartcamp,Aelrynth,,,PERMANENT - FC Mosswart Ice Tachi Quest,,FALSE,0,1,set by Warden, +fachubmosswartcampportal_flag,Aelrynth,,,Player is flagged to use Mosswart Camp portal,,FALSE,0,1,set by Warden, +fachubmountainsewer,Aelrynth,,,PERMANENT - FC Mountain Sewer Quest,,FALSE,0,1,set by Warden, +fachubmountainsewerportal_flag,Aelrynth,,,Player is flagged to use the Mountain Sewer portal,,FALSE,0,1,set by Warden, +fachubskeletonfort,Aelrynth,,,PERMANENT - FC Jacob's Axe Quest,,FALSE,0,1,set by Warden, +fachubskeletonfortportal_flag,Aelrynth,,,Player is flagged to use the Skeleton Fort portal,,FALSE,0,1,set by Warden, +fachubsuntik,Aelrynth,,,PERMANENT - FC Acid Axe Quest,,FALSE,0,1,set by Warden, +fachubsuntikportal_flag,Aelrynth,,,Player is flagged to use the Suntik portal,,FALSE,0,1,set by Warden, +fachubtrothyrsrest,Aelrynth,,,PERMANENT - FC Trothyr's Rest Quest,,FALSE,0,1,set by Warden, +fachubtrothyrsrestportal_flag,Aelrynth,,,Player is flagged to use the Trothyrs Rest portal,,FALSE,0,1,set by Warden, +faciltyhubfound_1111,Aelrynth,,,Facilty Hub found,,FALSE,0,1,set by Facility Hub Portal Gem, +falatacotchestkey_pickup,Aelrynth,,,Player has picked up Falatacot Chest Key,,TRUE,72000,-1,, +falatacotdepotquest_completed,Aelrynth,,,Player has completed the Falatacot Depot Quest,,TRUE,72000,-1,set by Neelic, +falatacotdepotquest_started,Aelrynth,,,Player has started the Falatacot Depot Quest,,FALSE,0,1,set by Neelic, +falatacotmagicresistance,Aelrynth,,,Teachings of the Falatacot,,FALSE,0,1,set by Fanzen San the Translator, +falatacotmedallion_start,Aelrynth,,,Player has started Falatacot Medallion Quest,,FALSE,0,1,set by Gruuk'lar, +falatacotmedallion_wait,Aelrynth,,,Player wait timer for turning in Falatacot Medallion,,TRUE,72000,-1,set by Gruuk'lar, +falatacotsoultrap_pickup,Aelrynth,,,Player has picked up Falatacot Soul Trap,,TRUE,72000,-1,, +falatacottome_pickup,Aelrynth,,,Player has picked up the Falatacot Tome,,TRUE,72000,-1,, +falatacotvault_flag,Aelrynth,,,Access granted to the Falatacot Vault,,FALSE,0,1,set by Abbess Zik'Lir, +falatcotreports,Aelrynth,,,Falatcot Reports Collected Adept Society,,TRUE,72000,-1,, +fallencreaturekillcount,Aelrynth,,,Fallen Creature Kill Counter,,TRUE,0,10,, +fallencreaturekilltask,Aelrynth,,,Fallen Creature Kill Task,,TRUE,72000,-1,, +fearfactorycache,Aelrynth,,,quest timer,,TRUE,72000,-1,, +fearfactorycompleted_0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Geilla, +fearfactoryreleased_0813,Aelrynth,,,quest counter,,TRUE,0,5,"set by Geilla, Shadow Captive", +fearfactorystarted_0813,Aelrynth,,,quest timer,,FALSE,0,1,set by Geilla, +feb01clquest1,Aelrynth,,,Unkindled Thaumaturgic Girth,,TRUE,72000,-1,set by Eaushi the Trainer, +feb01clquest10,Aelrynth,,,Right Mario Boot,,TRUE,72000,-1,, +feb01clquest11,Aelrynth,,,Sasalia's Key,,TRUE,72000,-1,, +feb01clquest2,Aelrynth,,,Unkindled Thaumaturgic Leggings,,TRUE,72000,-1,set by Eaushi the Trainer, +feb01clquest3,Aelrynth,,,Unkindled Thaumaturgic Coat,,TRUE,72000,-1,set by Eaushi the Trainer, +feb01clquest4,Aelrynth,,,Sunstone Geode,,TRUE,72000,-1,, +feb01clquest5,Aelrynth,,,Organic Acid Vial,,TRUE,72000,-1,, +feb01clquest6,Aelrynth,,,Lightweight Tome,,TRUE,72000,-1,, +feb01clquest7,Aelrynth,,,Left Mario Boot,,TRUE,72000,-1,, +feb01clquest8,Aelrynth,,,Globe of Auberean,,TRUE,72000,-1,set by Eaushi the Trainer, +feb01clquest9,Aelrynth,,,Titan Mana Charge,,TRUE,72000,-1,, +fellowmagicdefense4,Aelrynth,,,You found a fellowship magic defense spell.,,TRUE,72000,-1,, +fellowmagicdefense5,Aelrynth,,,You found a fellowship magic defense spell.,,TRUE,72000,-1,, +fellowmagicdefense6,Aelrynth,,,You found a fellowship magic defense spell.,,TRUE,72000,-1,, +fellowmagicdefense7,Aelrynth,,,You found a fellowship magic defense spell.,,TRUE,72000,-1,, +fellowmeleedefense4,Aelrynth,,,You found a fellowship melee defense spell.,,TRUE,72000,-1,, +fellowmeleedefense5,Aelrynth,,,You found a fellowship melee defense spell.,,TRUE,72000,-1,, +fellowmeleedefense6,Aelrynth,,,You found a fellowship melee defense spell.,,TRUE,72000,-1,, +fellowmeleedefense7,Aelrynth,,,You found a fellowship melee defense spell.,,TRUE,72000,-1,, +fellowmissiledefense4,Aelrynth,,,You found a fellowship melee defense spell.,,TRUE,72000,-1,, +fellowmissiledefense5,Aelrynth,,,You found a fellowship melee defense spell.,,TRUE,72000,-1,, +fellowmissiledefense6,Aelrynth,,,You found a fellowship melee defense spell.,,TRUE,72000,-1,, +fellowmissiledefense7,Aelrynth,,,You found a fellowship melee defense spell.,,TRUE,72000,-1,, +fellowshipcrystallordslayerquest,Aelrynth,,,Your fellowhsip has killed a Crystal Lord.,,TRUE,169200,-1,set by Crystal Lord, +fenmalaincrystal,Aelrynth,,,Fenmalain Crystal,,TRUE,72000,-1,, +findmumiyahdevicestart,Aelrynth,,,Flagged to Find Mumiyah Device,,FALSE,0,1,set by Mu-miyah Device, +findmumiyahdevicewait,Aelrynth,,,Mumiyah Device Wait,,TRUE,72000,-1,set by Nephthys, +finemetalscrapspickup,Aelrynth,,,FineMetalScraps Timer,,TRUE,72000,-1,, +finishednoir1,Aelrynth,,,You've completed the first noir quest.,,TRUE,72000,-1,set by Dame Brinna O'Shea, +fireworksused0105,Aelrynth,,,You've set off some New Years fireworks.,,TRUE,90,-1,"set by Fireworks, Wedding Fireworks Launcher", +firezenithdead,Aelrynth,,,quest timer,,FALSE,0,1,set by Fire Zenith, +firstcontact_firstcompletion,Aelrynth,First completion of the First Contact quest,,First completion of the First Contact quest,,FALSE,0,1,, +firstcontact_threedocumentsgiven,Aelrynth,,,Three documents given to Translator Aun Laokhe,,TRUE,0,3,set by Translator Aun Laokhe, +firstcontactcomplete_0511,Aelrynth,,,First Contact quest cooldown timer,,TRUE,72000,-1,set by Translator Aun Laokhe, +firstlieutenantinsigniapickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +firstsistercompleted_1012,Aelrynth,,,Player has completed Harvesting the Bulb of Mornings quest.,,TRUE,72000,-1,set by Kaltus, +firstsisterstarted_1012,Aelrynth,,,Player has started Harvesting the Bulb of Mornings quest.,,FALSE,0,1,set by Kaltus, +firstspawncomplete,Aelrynth,,,Player has killed first Spawn,,FALSE,0,1,, +firsttalkwithroderick,Aelrynth,,,Player stamp after first talk with Roderick.,,FALSE,0,1,set by Roderick, +firstyanshimatronkill,Aelrynth,,,First Completion of Yanshi Tunnels quest,,FALSE,0,1,set by Royal Guard Adrana, +fishcounter,Aelrynth,,,Number of Minnows turned in.,,TRUE,0,100,set by Fishing Hole, +fishingdelay,Aelrynth,,,Player must wait for fishing delay to expire before fishing again.,,TRUE,5,-1,set by Fishing Hole, +fishlargecounter,Aelrynth,,,Number of Minnows turned in.,,TRUE,0,300,set by Fishing Hole, +fiunhealingmachinecompleted_0511,Aelrynth,,,Assembled Healing Machine Turn-in to Scorus,,TRUE,72000,-1,set by Scorus, +fiunhealingmachinestarted_0511,Aelrynth,,,StartFiunHealingMachine flagged,,FALSE,0,1,set by Scorus, +flaggedcellsblackbook,Aelrynth,,,Flagging for entering the Cells of the Black Book dungeon,,FALSE,0,1,set by Hassha, +flaggedmoarsmancity,Aelrynth,,,FlaggedMoarsmanCity,,FALSE,0,1,"set by Gamri Nightshade, Istonia Charson, Philonius Porbandar", +fledgemastertusk,Aelrynth,,,Fledge Master's Tusk Quest,,TRUE,72000,-1,checked by Seneschal Dalmour, +fledgemastertuskrepeat,Aelrynth,,,Player has completed Fledgemaster Tusk once.,,FALSE,0,1,set by Seneschal Dalmour, +floesharkkillcount,Aelrynth,,,Floeshark Kill Counter,,TRUE,0,50,set by Ryuichi Tai, +floesharkkilltask,Aelrynth,,,Floeshark Kill Task,,TRUE,72000,-1,set by Ryuichi Tai, +flyingmachineplansacquired0105,Aelrynth,,,Player has picked up the Flying Machine Plans.,,TRUE,72000,-1,, +focusingstone,Aelrynth,,,Focusing Stone from Mines of Despair,,TRUE,72000,-1,, +focusingstoneimbued,Aelrynth,,,Imbued Focusing Stone from Mines of Despair,,TRUE,72000,-1,, +folthidshardpickup,Aelrynth,,,Ancient Shard of Metal picked up from a Large Chest.,,TRUE,72000,-1,, +forgeessencegiven1204,Aelrynth,,,You've given any forge essence to any crafting forge,,FALSE,0,1,"set by Alchemy Forge, Cooking Forge, Fletching Forge and 2 more", +forgeessencenorthacquired1204,Aelrynth,,,You have picked up the Northern Forge Essence,,TRUE,72000,-1,, +forgeessencesouthacquired1204,Aelrynth,,,You have picked up the Southern Forge Essence,,TRUE,72000,-1,, +forgeessencewestacquired1204,Aelrynth,,,You have picked up the Western Forge Essence,,TRUE,72000,-1,, +forgeessencexprewardreceived0105,Aelrynth,,,You handed a Western Forge Essence to an Agent of the Arcanum.,,FALSE,0,1,, +forger'shideoutportal,Aelrynth,,,Forger's Hideout Portal Flag - 1 week,,TRUE,518400,-1,set by Shanrek the Forger, +forgetfulness13days,Aelrynth,,,2 week skill forgetfulness timer.,,TRUE,1123200,-1,"set by Alchemy Warden of Forgetfulness, Arcane Lore Warden of Forgetfulness, Armor Tinkering Warden of Forgetfulness and 35 more", +forgetfulness20days,Aelrynth,,,3 week skill forgetfulness timer.,,TRUE,1728000,-1,"set by Alchemy Warden of Forgetfulness, Arcane Lore Warden of Forgetfulness, Armor Tinkering Warden of Forgetfulness and 35 more", +forgetfulness6days,Aelrynth,Attribute and Skill Redistribution,https://acportalstorm.com/wiki/Attribute_and_Skill_Redistribution,1 week skill forgetfulness timer. See Run Warden of Forgetfulness; Salvaging Warden of Forgetfulness; Heavy Weapons Warden of Forgetfulness (among others).,1 week skill forgetfulness timer.,TRUE,518400,-1,"set by Alchemy Warden of Forgetfulness, Arcane Lore Warden of Forgetfulness, Armor Tinkering Warden of Forgetfulness and 35 more", +forgetfulnessgems1,Aelrynth,Attribute and Skill Redistribution,https://acportalstorm.com/wiki/Attribute_and_Skill_Redistribution,First Forgetfulness gems received counter. See Summoning Warden of Forgetfulness; Alchemy Warden of Forgetfulness; Void Magic Warden of Forgetfulness (among others).,First Forgetfulness gems received counter,TRUE,0,3,"set by Alchemy Warden of Forgetfulness, Arcane Lore Warden of Forgetfulness, Armor Tinkering Warden of Forgetfulness and 35 more", +forgetfulnessgems2,Aelrynth,Attribute and Skill Redistribution,https://acportalstorm.com/wiki/Attribute_and_Skill_Redistribution,Second Forgetfulness gems received counter. See Dirty Fighting Warden of Forgetfulness; Dual Wield Warden of Forgetfulness; Recklessness Warden of Forgetfulness (among others).,Second Forgetfulness gems received counter,TRUE,0,3,"set by Alchemy Warden of Forgetfulness, Arcane Lore Warden of Forgetfulness, Armor Tinkering Warden of Forgetfulness and 35 more", +forgetfulnessgems3,Aelrynth,,,Third Forgetfulness gems received counter,,TRUE,0,7,"set by Alchemy Warden of Forgetfulness, Arcane Lore Warden of Forgetfulness, Armor Tinkering Warden of Forgetfulness and 35 more", +forgetfulnessgems4,Aelrynth,,,Fourth Forgetfulness gems received counter,,TRUE,0,9999999,"set by Alchemy Warden of Forgetfulness, Arcane Lore Warden of Forgetfulness, Armor Tinkering Warden of Forgetfulness and 35 more", +forgevaultkeypickuptimer,Aelrynth,,,Picked up Forge Vault Key,,TRUE,72000,-1,, +formacademypickup,Aelrynth,,,Player must wait 30 seconds to pick up another Academy Form,,TRUE,30,-1,, +fortunecounter,Aelrynth,,,How many Lucky Numbers did you get?,,TRUE,0,3,set by Jojii Shrine, +fossilizedbone_pickup,Aelrynth,,,Player has picked up the Fossilized Bone.,,TRUE,72000,-1,, +found9jestermarkers,Aelrynth,,,Found 9 Jester Markers,,TRUE,0,10,"set by Jester, Jester's Marker", +foundjestermarker1,Aelrynth,,,Found Jester Marker,,TRUE,72000,-1,set by Jester's Marker, +foundjestermarker10,Aelrynth,,,Found Jester Marker,,TRUE,72000,-1,set by Jester's Marker, +foundjestermarker2,Aelrynth,,,Found Jester Marker,,TRUE,72000,-1,set by Jester's Marker, +foundjestermarker3,Aelrynth,,,Found Jester Marker,,TRUE,72000,-1,set by Jester's Marker, +foundjestermarker4,Aelrynth,,,Found Jester Marker,,TRUE,72000,-1,set by Jester's Marker, +foundjestermarker5,Aelrynth,,,Found Jester Marker,,TRUE,72000,-1,set by Jester's Marker, +foundjestermarker6,Aelrynth,,,Found Jester Marker,,TRUE,72000,-1,set by Jester's Marker, +foundjestermarker7,Aelrynth,,,Found Jester Marker,,TRUE,72000,-1,set by Jester's Marker, +foundjestermarker8,Aelrynth,,,Found Jester Marker,,TRUE,72000,-1,set by Jester's Marker, +foundjestermarker9,Aelrynth,,,Found Jester Marker,,TRUE,72000,-1,set by Jester's Marker, +foundryofizexicompleted_1212,Aelrynth,,,Player wait timer for Foundry of Izexi.,,TRUE,72000,-1,set by Fahneph, +foundryofizexistarted_1212,Aelrynth,,,Player has started Foundry of Izexi Quest.,,FALSE,0,1,set by Fahneph, +foundseanthespeedy,Aelrynth,,,Sean the Speedy found.,,FALSE,0,1,set by Sean the Speedy, +fourcornerscompleted_1113,Aelrynth,,,Player has completed the Four Corners quest.,,TRUE,72000,-1,set by El'Yst Maggann, +fourcornersrecluseflag_1113,Aelrynth,,,Player flag for Sanctuary of the Recluse.,,FALSE,0,1,set by El'Yst Maggann, +fourcornersstarted_1113,Aelrynth,,,Player has started the Four Corners quest.,,TRUE,72000,-1,set by El'Yst Maggann, +fragofyajasarmpickuptimer,Aelrynth,,,Player has picked up Fragment of Yajas Arm,,TRUE,72000,-1,, +francoiscorruptedessencearmorcount,Aelrynth,,,Corrupted Essence turn in counter for Armor Piece,,TRUE,0,-1,set by Francois di Terli, +freebooteradvancementwait,Aelrynth,,,Cooldown for Freebooter Advancement Gem,,TRUE,72000,-1,set by Lormish Littlefinger, +freebooterkilltask0809,Aelrynth,,,Prison Moarsman Kill Task,,TRUE,0,20,set by Avarin, +freebooterkilltaskboss10809,Aelrynth,,,Large Ardant Moarsman Kill Task,,FALSE,0,1,set by Avarin, +freebooterkilltaskboss1wait0809,Aelrynth,,,Large Ardant Moarsman Kill Task,,TRUE,72000,-1,set by Avarin, +freebooterkilltaskboss20809,Aelrynth,,,Large Blessed Moarsman Kill Task,,FALSE,0,1,set by Avarin, +freebooterkilltaskboss2wait0809,Aelrynth,,,Large Blessed Moarsman Kill Task,,TRUE,72000,-1,set by Avarin, +freebooterkilltaskboss30809,Aelrynth,,,Large Verdant Moarsman Kill Task,,FALSE,0,1,set by Avarin, +freebooterkilltaskboss3wait0809,Aelrynth,,,Verdant Moarsman Kill Task,,TRUE,72000,-1,set by Avarin, +freebooterkilltaskwait0809,Aelrynth,,,Prison Moarsman Kill Task,,TRUE,72000,-1,set by Avarin, +freebooterluminancewait,Aelrynth,,,Cooldown for Freebooter Luminance Gem,,TRUE,72000,-1,set by Calhoun, +freedbrontynnthorstenarmor,Aelrynth,,,Player has freed Brontynn Marshad,,TRUE,72000,-1,set by Brontynn Marshad, +freedjester,Aelrynth,,,quest flag,,FALSE,0,1,set by Jester, +freedtempleexarch,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Freed Temple Exarch, +frostgolemkillcount,Aelrynth,,,Frost Golem Kill Counter,,TRUE,0,20,set by George, +frostgolemkilltask,Aelrynth,,,Frost Golem Kill Task,,TRUE,72000,-1,set by George, +frostzenithdead,Aelrynth,,,quest timer,,FALSE,0,1,set by Frost Zenith, +frozenblackcrystal_pickup,Aelrynth,,,Player has picked up the Frozen Black Crystal,,TRUE,72000,-1,, +frozencrystalkillcount,Aelrynth,,,Frozen Crystal Kill Counter,,TRUE,0,4,set by Boone, +frozencrystalkilltask,Aelrynth,,,Frozen Crystal Kill Task,,TRUE,72000,-1,set by Boone, +frozendreadkillcount,Aelrynth,,,Frozen Dread Kill Counter,,TRUE,0,10,set by Kumiko, +frozendreadkilltask,Aelrynth,,,Frost Dread Kill Task,,TRUE,72000,-1,set by Kumiko, +frozenfortresslabaccess_0513,Aelrynth,,,Flagged to enter Frozen Lab,,FALSE,0,1,set by Frozen Fortress Laboratory Attunement Shard (Level 180+), +frozenfortresslabcompleted_0513,Aelrynth,,,You have obtained a experimental bloodstone shadr.,,TRUE,72000,-1,, +frozenfortresstestinggroundsaccess_0513,Aelrynth,,,Flagged to enter Testing Grounds,,FALSE,0,1,set by Frozen Fortress Testing Grounds Attunement Shard (Level 180+), +frozenfortresstestinggroundscompleted_0513,Aelrynth,,,Frost Fortress Test Kill Task Timer,,TRUE,72000,-1,set by Prototype Bloodstone, +frozenfortresstestinggroundskilltask_0513,Aelrynth,,,Frozen Fortress Kill Counter,,TRUE,0,20,set by Prototype Bloodstone, +frozenpresentpickuptimer,Aelrynth,Picked up Frozen Present,,Picked up Frozen Present,,TRUE,72000,-1,, +frozenwightkillcount,Aelrynth,,,Frozen Wight Kill Count,,TRUE,0,20,set by Leilah, +frozenwightkilltask,Aelrynth,,,Frozen Wight Kill Task,,TRUE,72000,-1,set by Leilah, +frozenwightlaircomplete1111,Aelrynth,,,You have obtained a Wardley Reward.,,TRUE,72000,-1,set by Halvor, +frozenwightlairtrophy1111,Aelrynth,,,You have obtained a Wardley belonging.,,TRUE,72000,-1,, +furgalmushroomstarted,Aelrynth,,,Player has talked to Furgal,,FALSE,0,1,set by Furgal, +furgalmushroomturninmax,Aelrynth,,,Player handed in 200 Mushrooms to Furgal,,FALSE,0,1,set by Furgal, +furgalmushroomturnins,Aelrynth,,,Player stamp for handing in Mushrooms to Furgal,,TRUE,0,200,, +gaerlanatlatl,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlanbow,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlanbracelet,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlanbreastplate,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlancestus,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlancirclet,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlancrit,Aelrynth,,,Player has gone through the portal to the inner sanctum.,,TRUE,72000,-1,checked by Gaerlan's Phylacteric Prison, +gaerlancrossbow,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlandagger,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlandefeated,Aelrynth,,,Player has finished the Gaerlan quest and can receive a reward.,,TRUE,72000,-1,set by Gaerlan's Phylacteric Prison, +gaerlanfight,Aelrynth,,,Unused questflag,,TRUE,3600,-1,, +gaerlankiller,Aelrynth,,,Player has gone through the portal to the inner sanctum.,,TRUE,72000,-1,set by Gaerlan, +gaerlanlife,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlanmace,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlannecklace,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlanpreamble,Aelrynth,,,Player has given the ornate seal to the ornate pillar,,FALSE,0,1,set by Ornate Pillar, +gaerlanquest,Aelrynth,,,Player has started the Gaerlan Quest.,,FALSE,0,1,checked by Asheron's Platinum Golem, +gaerlanring,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlanshield,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlanspear,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlanstaff,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlanstave,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,, +gaerlansword,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlanswordturnin,Aelrynth,,,Player can only turn in the sword 1 time every 1 days,,TRUE,72000,-1,"set by Agent Dravos, Agent of the Arcanum", +gaerlanwar1,Aelrynth,,,Player has received the War reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +gaerlanwar2,Aelrynth,,,Player has received the War 2 reward.,,FALSE,0,1,, +gaerlanwar3,Aelrynth,,,Player has received the War 3 reward.,,FALSE,0,1,, +gaerlanwar4,Aelrynth,,,Player has received the War 4 reward.,,FALSE,0,1,, +gaerlanwarhammer,Aelrynth,,,Player has received the corresponding reward.,,FALSE,0,1,set by Gaerlan's Phylacteric Prison, +galaeraldagger,Aelrynth,,,Galaeral Dagger,,TRUE,72000,-1,, +garaktarsblood_pickup,Aelrynth,,,Player has picked up Garaktars Blood,,TRUE,72000,-1,, +gardensofmenileshflag,Aelrynth,,,Flag for Gardens of Menilesh,,FALSE,0,1,"set by Lacarra Avanthi, Zho Heishan", +gatekeepersflagcomplete,Aelrynth,,,Flagged to use GateKeepers portal,,FALSE,0,1,set by Shemza, +gatewatcherdefeated,Aelrynth,,,Defeated Gate Watcher,,FALSE,0,1,set by Gate Watcher, +gauntletarena1ch,Aelrynth,,,Player/fellow stamp for Arena 1 access in Gauntlet.,,TRUE,3600,-1,"set by Gauntlet Arena One Statue, Master of the Gauntlet", +gauntletarena1ew,Aelrynth,,,Player/fellow stamp for Arena 1 access in Gauntlet.,,TRUE,3600,-1,"set by Gauntlet Arena One Statue, Master of the Gauntlet", +gauntletarena1rb,Aelrynth,,,Player/fellow stamp for Arena 1 access in Gauntlet.,,TRUE,3600,-1,"set by Gauntlet Arena One Statue, Master of the Gauntlet", +gauntletarena2ch,Aelrynth,,,Player/fellow stamp for Arena 2 access in Gauntlet.,,TRUE,3600,-1,"set by Gauntlet Arena Two Statue, Master of the Gauntlet", +gauntletarena2ew,Aelrynth,,,Player/fellow stamp for Arena 2 access in Gauntlet.,,TRUE,3600,-1,"set by Gauntlet Arena Two Statue, Master of the Gauntlet", +gauntletarena2rb,Aelrynth,,,Player/fellow stamp for Arena 2 access in Gauntlet.,,TRUE,3600,-1,"set by Gauntlet Arena Two Statue, Master of the Gauntlet", +gauntletarenaboot,Aelrynth,,,NPC cooldown for Booter event.,,TRUE,3588,-1,"set by Gauntlet Arena One Statue, Gauntlet Arena Two Statue", +gauntletarenacooldownactive,Aelrynth,,,NPC flag for Gauntlet cooldown.,,FALSE,0,1,"set by Gauntlet Arena One Statue, Gauntlet Arena Two Statue", +gauntletarenawait,Aelrynth,,,NPC flag for Gauntlet wait.,,TRUE,10,-1,"set by Gauntlet Arena One Statue, Gauntlet Arena Two Statue", +gauntletbossgromnuschampion_flag,Aelrynth,,,Player flag for Gauntlet Boss Gromnus Champion.,,FALSE,0,1,set by Master of the Gauntlet, +gauntletbossholcha_flag,Aelrynth,,,Player flag for Gauntlet Boss Holcha.,,FALSE,0,1,set by Gauntlet Stage 11, +gauntletbosstremborh_flag,Aelrynth,,,Player flag for Gauntlet Boss Tremb Orh.,,FALSE,0,1,set by Gauntlet Stage 9, +gauntletrewardwait,Aelrynth,,,Player claimed rewards in Gauntlet.,,TRUE,72000,-1,set by Master of the Gauntlet, +gauntletsacademypickup,Aelrynth,,,Player has picked up the Academy Gauntlets,,FALSE,0,1,checked by Samuel, +gauntletstage0complete,Aelrynth,,,Player entered the Gauntlet.,,FALSE,0,1,set by Gauntlet Arena, +gauntletstage10complete,Aelrynth,,,Player completed Stage 10 in Gauntlet.,,FALSE,0,1,checked by Master of the Gauntlet, +gauntletstage11complete,Aelrynth,,,Player completed Stage 11 in Gauntlet.,,FALSE,0,1,checked by Master of the Gauntlet, +gauntletstage12complete,Aelrynth,,,Player completed Stage 12 in Gauntlet.,,FALSE,0,1,checked by Master of the Gauntlet, +gauntletstage1complete,Aelrynth,,,Player completed Stage 1 in Gauntlet.,,FALSE,0,1,checked by Master of the Gauntlet, +gauntletstage2complete,Aelrynth,,,Player completed Stage 2 in Gauntlet.,,FALSE,0,1,checked by Master of the Gauntlet, +gauntletstage3complete,Aelrynth,,,Player completed Stage 3 in Gauntlet.,,FALSE,0,1,checked by Master of the Gauntlet, +gauntletstage4complete,Aelrynth,,,Player completed Stage 4 in Gauntlet.,,FALSE,0,1,set by Gauntlet Stage 5, +gauntletstage5a_flag,Aelrynth,,,Player flag for Stage 5 A.,,FALSE,0,1,set by Gauntlet Stage 5, +gauntletstage5b_flag,Aelrynth,,,Player flag for Stage 5 B.,,FALSE,0,1,set by Gauntlet Stage 5, +gauntletstage5complete,Aelrynth,,,Player completed Stage 5 in Gauntlet.,,FALSE,0,1,checked by Master of the Gauntlet, +gauntletstage5myquest,Aelrynth,,,NPC quest for room dividing in 5..,,FALSE,0,1,set by Gauntlet Stage 5, +gauntletstage6complete,Aelrynth,,,Player completed Stage 6 in Gauntlet.,,FALSE,0,1,checked by Master of the Gauntlet, +gauntletstage7complete,Aelrynth,,,Player completed Stage 7 in Gauntlet.,,FALSE,0,1,checked by Master of the Gauntlet, +gauntletstage8complete,Aelrynth,,,Player completed Stage 8 in Gauntlet.,,FALSE,0,1,checked by Master of the Gauntlet, +gauntletstage9complete,Aelrynth,,,Player completed Stage 9 in Gauntlet.,,FALSE,0,1,checked by Master of the Gauntlet, +gauntletwinscounter,Aelrynth,,,Player stamp for wins in Gauntlet.,,TRUE,0,-1,set by Master of the Gauntlet, +gavecoloredstoneexcess,Aelrynth,,,Handed in too many Colored Stones in Trial of the Mind,,TRUE,0,3,"set by Bag of Stones, Bucket", +gavecresttonanoc,Aelrynth,,,Picked up note,,TRUE,72000,-1,"set by Nanoc, Basher of Bugs", +gavecresttonarg,Aelrynth,,,Picked up note,,TRUE,72000,-1,set by Narg, +gaveeastgateharmoniccrystal,Aelrynth,,,Player has turned in East Gate Harmonic Crystal,,FALSE,0,1,set by Emissary of Asheron, +gaveevilcouch,Aelrynth,Frest Greelving's Haunted Mansion,https://acportalstorm.com/wiki/Frest_Greelving's_Haunted_Mansion,Player was given the Evil Couch. See Frest Greelving.,Player was given the Evil Couch,TRUE,72000,-1,set by Frest Greelving, +gavefemurtodanta,Aelrynth,,,Picked up note,,TRUE,72000,-1,set by Pincer Danta, +gavegeraineheart1,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Mhoire Soldier, +gavegeraineheart2,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Mhoire Soldier, +gavegeraineheart3,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Mhoire Soldier, +gavegeraineheart4,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Mhoire Soldier, +gavegeraineheart5,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Mhoire Soldier, +gavegeraineheart6,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Mhoire Soldier, +gavegeraineheart7,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Mhoire Soldier, +gavehooganblueprints,Aelrynth,,,Player has gave Hoogan the Blueprints,,FALSE,0,1,set by Hoogan, +gavehooganshovel,Aelrynth,,,Player has gave Hoogan the Shovel,,FALSE,0,1,set by Hoogan, +gavejailerpyramid,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Jailer, +gavejesterletter,Aelrynth,,,quest timer,,FALSE,0,1,set by Wall, +gaveleathertonanoc,Aelrynth,,,Picked up note,,TRUE,72000,-1,"set by Nanoc, Basher of Bugs", +gaveletterthorstenarmor1,Aelrynth,,,Player has given this letter in exchange for xp,,TRUE,72000,-1,set by Glysander Cartoth, +gaveletterthorstenarmor2,Aelrynth,,,Player has given this letter in exchange for xp,,TRUE,72000,-1,set by Glysander Cartoth, +gaveletterthorstenarmor3,Aelrynth,,,Player has given this letter in exchange for xp,,TRUE,72000,-1,set by Glysander Cartoth, +gaveletterthorstenarmor4,Aelrynth,,,Player has given this letter in exchange for xp,,TRUE,72000,-1,set by Glysander Cartoth, +gaveletterthorstenarmor4copy,Aelrynth,,,Player has given this letter in exchange for xp,,TRUE,72000,-1,set by Glysander Cartoth, +gaveletterthorstenarmor5,Aelrynth,,,Player has given this letter in exchange for xp,,TRUE,72000,-1,set by Glysander Cartoth, +gavenbucketredstone,Aelrynth,,,Red Stone hand in Trial of the Mind,,TRUE,0,3,set by Bucket, +gavenbucketwhitestone,Aelrynth,,,White Stone hand in Trial of the Mind,,TRUE,0,4,set by Bucket, +gavenbucketyellowstone,Aelrynth,,,Yellow Stone hand in Trial of the Mind,,TRUE,0,3,set by Bucket, +gavenorthgateharmoniccrystal,Aelrynth,,,Player has turned in North Gate Harmonic Crystal,,FALSE,0,1,set by Emissary of Asheron, +gavenotethorstenarmor1,Aelrynth,,,Player has been given the note for Brontynn,,TRUE,72000,-1,set by Glysander Cartoth, +gaveolthoiscoutnote1,Aelrynth,,,Turned in a note,,TRUE,72000,-1,, +gaveolthoiscoutnote2,Aelrynth,,,Turned in a note,,TRUE,72000,-1,, +gaveolthoiscoutnote3,Aelrynth,,,Turned in a note,,TRUE,72000,-1,, +gaveolthoiscoutnote4,Aelrynth,,,Turned in a note,,TRUE,72000,-1,, +gaveolthoiscoutnote5,Aelrynth,,,Turned in a note,,TRUE,72000,-1,, +gaveolthoiscoutnote6,Aelrynth,,,Turned in a note,,TRUE,72000,-1,, +gaveolthoiscoutnote7,Aelrynth,,,Turned in a note,,TRUE,72000,-1,, +gaveolthoiscoutnote8,Aelrynth,,,Turned in a note,,TRUE,72000,-1,set by Scout Luzumin Abigwei, +gavepleadingletter,Aelrynth,,,quest timer,,FALSE,0,1,set by Lord Cynreft Mhoire, +gaveredstone,Aelrynth,,,Red Stone hand in Trial of the Mind,,TRUE,0,3,set by Bag of Stones, +gavesbucketredstone,Aelrynth,,,Red Stone hand in Trial of the Mind,,TRUE,0,3,set by Bucket, +gavesbucketwhitestone,Aelrynth,,,White Stone hand in Trial of the Mind,,TRUE,0,4,, +gavesbucketyellowstone,Aelrynth,,,Yellow Stone hand in Trial of the Mind,,TRUE,0,3,set by Bucket, +gavestabclawtodanta,Aelrynth,,,Picked up note,,TRUE,72000,-1,set by Pincer Danta, +gavetuningfork,Aelrynth,,,quest timer,,TRUE,72000,-1,"set by Aun Aanaua, Aun Gehaua, Aun Kahmaula and 2 more", +gaveunframedderethmap,Aelrynth,,,Player has given unframed Dereth Map to Gharu Furniture Master.,,FALSE,0,1,set by Jordan Ibn'Ikia, +gavewestgateharmoniccrystal,Aelrynth,,,Player has turned in West Gate Harmonic Crystal,,FALSE,0,1,set by Emissary of Asheron, +gavewhitestone,Aelrynth,,,White Stone hand in Trial of the Mind,,TRUE,0,4,set by Bag of Stones, +gavewoodtonarg,Aelrynth,,,Picked up note,,TRUE,72000,-1,set by Narg, +gaveyellowstone,Aelrynth,,,Yellow Stone hand in Trial of the Mind,,TRUE,0,3,set by Bag of Stones, +gayalily,Aelrynth,,,First Snow Lily turned in to Fiun Gaya,,FALSE,0,1,set by Fiun Gaya, +gearallcorepickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +geardrudge,Aelrynth,,,Player has picked up a Drudge Gear and cannot pick up another for 1 day.,,TRUE,72000,-1,, +geardrudgegiven,Aelrynth,,,Player has given this gear and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +geargromnie,Aelrynth,,,Player has picked up a Gromnie Gear and cannot pick up another for 1 day.,,TRUE,72000,-1,, +geargromniegiven,Aelrynth,,,Player has given this gear and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +gearknightconstructioncompletedkaytin,Aelrynth,,,Max gear knight parts handed to Kaytin,,FALSE,0,1,set by Kaytin, +gearknightconstructioncompletedtakahume,Aelrynth,,,Max gear knight parts handed to Takahume,,FALSE,0,1,set by Master Craftsman Takahume, +gearknightconstructionturninskaytin,Aelrynth,,,Number of gear knight parts handed to Kaytin,,TRUE,0,200,set by Kaytin, +gearknightconstructionturninstakahume,Aelrynth,,,Number of gear knight parts handed to Takahume,,TRUE,0,200,set by Master Craftsman Takahume, +gearknightexcavationcomplete0809,Aelrynth,,,Apostate Excavation Investigation wait timer,,TRUE,72000,-1,set by Felizio Calmasi, +gearknightexcavationstarted0809,Aelrynth,,,Started Apostate Excavation Investigation,,FALSE,0,1,set by Felizio Calmasi, +gearknightinvasionhighbosskill_1009,Aelrynth,,,Invading Iron Blade Commander kill task,,FALSE,0,1,set by Dame Trielle, +gearknightinvasionhighbosswait_1009,Aelrynth,,,Timer for Invading Iron Blade Commander kill task,,TRUE,72000,-1,set by Dame Trielle, +gearknightinvasionhighcorecollectwait_1009,Aelrynth,,,Turned in 10 Aetherium Power Cores in Direlands Invasion,,TRUE,72000,-1,set by T'ing Douzen, +gearknightinvasionhighkilltask_1009,Aelrynth,,,Direlands Invasion Gear Knight kill task,,TRUE,0,10,set by Sir Yanov, +gearknightinvasionhighkillwait_1009,Aelrynth,,,Direlands Invasion Gear Knight kill task timer,,TRUE,72000,-1,set by Sir Yanov, +gearknightinvasionhighorecollectwait_1009,Aelrynth,Turned in 10 Aetherium Ore in Direlands Invasion,,Turned in 10 Aetherium Ore in Direlands Invasion,Turned in 10 Aetherium Ore in Direlands Invasion,TRUE,72000,-1,set by T'ing Douzen, +gearknightinvasionhighsiphonstart_1009,Aelrynth,,,Mana Siphon Destruction Started,,FALSE,0,1,set by Mana Siphon, +gearknightinvasionhighsiphonwait_1009,Aelrynth,,,Turned in an Unstable Mana Stone,,TRUE,72000,-1,"set by Aldreda, Edweena, Kimberleigh", +gearknightinvasionphalanxkilltask_0513,Aelrynth,,,Gear Knight Phalanx Kill Task,,TRUE,0,10,"set by Aun Quanah, Ladice, Tressar", +gearknightinvasionphalanxkillwait_0513,Aelrynth,,,Gear Knight Phalanx Kill Task,,TRUE,72000,-1,"set by Aun Quanah, Ladice, Tressar", +gearknightinvasionsquirekilltask_0513,Aelrynth,,,Direlands Invasion Gear Squire kill task,,TRUE,0,10,set by Sir Yanov, +gearknightinvasionsquirekillwait_0513,Aelrynth,,,Direlands Invasion Gear Squire kill task timer,,TRUE,72000,-1,set by Sir Yanov, +gearknightkillcount,Aelrynth,,,Gear Knight Kill Counter,,TRUE,0,10,, +gearknightkilled,Aelrynth,,,Player has killed a Gearknight,,TRUE,0,-1,set by Frozen Cave Golem Watcher, +gearknightkilltask,Aelrynth,,,Gear Knight Kill Task,,TRUE,72000,-1,, +gearknightlesserlordkillcount,Aelrynth,,,Gearknight Lesser Lord kill count,,TRUE,0,6,set by Dame Alistra, +gearknightlesserlordkilltask,Aelrynth,,,Gearknight Lesser Lord kill timer,,TRUE,72000,-1,set by Dame Alistra, +gearknightparts,Aelrynth,,,Gear Knight Parts Collected Initiate Society,,TRUE,72000,-1,, +gearknightpartscollectionwait_0513,Aelrynth,,,Collect Gear Knight Parts,,TRUE,72000,-1,"set by Dark Reshan, Drocogst, Trathium", +gearknightphalanxkillcount,Aelrynth,,,Gear Knight Phalanx Kill Counter,,TRUE,0,10,, +gearknightphalanxkilltask,Aelrynth,,,Gear Knight Phalanx Kill Task,,TRUE,72000,-1,, +gearknightsquirekillcount,Aelrynth,,,Gear Knight Squire Kill Counter,,TRUE,0,10,, +gearknightsquirekilltask,Aelrynth,,,Gear Knight Squire Kill Task,,TRUE,72000,-1,, +gearmosswart,Aelrynth,,,Player has picked up a Mosswart Gear and cannot pick up another for 1 day.,,TRUE,72000,-1,, +gearmosswartgiven,Aelrynth,,,Player has given this gear and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +gearreedshark,Aelrynth,,,Player has picked up a Reedshark Gear and cannot pick up another for 1 day.,,TRUE,72000,-1,, +gearreedsharkgiven,Aelrynth,,,Player has given this gear and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +gearxbowwait,Aelrynth,,,Received Rewards for Gear Crossbow Quest,,TRUE,72000,-1,set by Ordas Myr, +gembaidenquest,Aelrynth,,,Retreive Bai Den's Flawed Gem,,TRUE,72000,-1,, +gemimpulse,Aelrynth,,,Xarabydun Impulse Gem,,TRUE,72000,-1,set by Aino Lunnan-Shin, +gemithaenccatacombs,Aelrynth,,,Ithaenc Catacombs Gem,,TRUE,600,-1,, +gemnewbiepickedup,Aelrynth,,,Player has picked up the portal gem (removed from game),,TRUE,0,3,, +genesiscompleted_0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Vision of Horror, +genesisstarted_0813,Aelrynth,,,quest timer,,FALSE,0,1,set by Vision of Horror, +geowulfjournal1,Aelrynth,,,Timer for Geowulf's Journal Logs 1-2,,TRUE,72000,-1,, +geowulfjournal2,Aelrynth,,,Timer for Geowulf's Journal Logs 3-4,,TRUE,72000,-1,, +geowulfjournal3,Aelrynth,,,Timer for Geowulf's Journal Logs 5-7,,TRUE,72000,-1,, +geowulfsring,Aelrynth,,,Pickup timer for Geowulf's Wedding Ring,,TRUE,72000,-1,, +geraineheart1,Aelrynth,,,quest timer,,TRUE,600,-1,set by Mhoire Soldier, +geraineheart2,Aelrynth,,,quest timer,,TRUE,600,-1,set by Mhoire Soldier, +geraineheart3,Aelrynth,,,quest timer,,TRUE,600,-1,set by Mhoire Soldier, +geraineheart4,Aelrynth,,,quest timer,,TRUE,600,-1,set by Mhoire Soldier, +geraineheart5,Aelrynth,,,quest timer,,TRUE,600,-1,set by Mhoire Soldier, +geraineheart6,Aelrynth,,,quest timer,,TRUE,600,-1,set by Mhoire Soldier, +geraineheart7,Aelrynth,,,quest timer,,TRUE,600,-1,set by Mhoire Soldier, +gerainesbodiesbookone0412,Aelrynth,,,quest timer,,TRUE,72000,-1,, +gerainesbodiescompleted0412,Aelrynth,,,quest timer,,TRUE,72000,-1,"set by Mhoire Lieutenant, Mhoire Soldier", +geraineslibrarybook0312,Aelrynth,,,quest timer,,FALSE,0,1,set by Mhoire Soldier, +geraineslibrarycompleted0312,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Mhoire Soldier, +gerainestudybookpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +gerainestudykeypickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +gerainetome2,Aelrynth,,,quest timer,,TRUE,72000,-1,, +gerainetome3,Aelrynth,,,quest timer,,TRUE,72000,-1,, +gerainetome4,Aelrynth,,,quest timer,,TRUE,72000,-1,, +gerainetome5,Aelrynth,,,quest timer,,TRUE,72000,-1,, +gerainetome6,Aelrynth,,,quest timer,,TRUE,72000,-1,, +gerainetome7,Aelrynth,,,quest timer,,TRUE,72000,-1,, +ghosthunterwait,Aelrynth,,,Completed Ghost Hunter quest,,TRUE,72000,-1,set by Sharia Blackmist, +giantaggregateshardpickup,Aelrynth,,,Picked up Giant Aggregate Crystalline Shard,,TRUE,72000,-1,, +giantmonougarib_pickup,Aelrynth,,,Player has picked up Giant Monouga Rib,,TRUE,72000,-1,, +giftboxesfound,Aelrynth,,,Gift Boxes Found Bits,,TRUE,0,4095,, +giftboxesfoundcounter,Aelrynth,,,Counter for gift boxes found,,TRUE,0,12,set by Gift Box, +giftboxeswait,Aelrynth,,,Cooldown for Hidden Presents,,TRUE,25920000,-1,set by Gift Box, +giftgopher_count,Aelrynth,,,Player count for Package Delivery.,,TRUE,0,15,"checked by Blair, Chrissy, Cindy and 10 more", +giftgopher_list,Aelrynth,,,Player has received a list.,,TRUE,0,3,set by Raymond, +giftgopher_listscomplete,Aelrynth,,,Player has completed all three lists.,,TRUE,0,15,checked by Raymond, +giftgopher_timer,Aelrynth,,,Player has started Package Delivery.,,TRUE,1800,-1,set by Raymond, +giftgopher_wait,Aelrynth,,,Player wait timer for Package Delivery.,,TRUE,72000,-1,set by Raymond, +ginsword,Aelrynth,,,Knights of Karlun - Sir Ginazio,,TRUE,72000,-1,set by Sir Ginazio, +givenblindsnowmanpeppermint,Aelrynth,,,Player has given the Blind Snowman Peppermint.,,TRUE,72000,-1,set by Blind Snowman, +giventibrispear,Aelrynth,,,Player has given Tibri back her fire spear.,,TRUE,72000,-1,set by Tibri the Cavedweller, +glacialgolemmargravekillcount,Aelrynth,,,Glacial Golem Margrave Kill Counter,,TRUE,0,5,, +glacialgolemmargravekilltask,Aelrynth,,,Glacial Golem Margrave Kill Task,,TRUE,72000,-1,, +glandcollected,Aelrynth,,,Player assisted in killing a newbie nest.,,FALSE,0,1,, +glendeninvaders,Aelrynth,,,Glenden Wood Invaders quest cooldown timer,,TRUE,72000,-1,set by Londigul Ellic the Armorer, +glendeninvadersblockadee,Aelrynth,,,Glenden Wood Invaders Blockade Guard East,,FALSE,0,1,set by Blockade Guard, +glendeninvadersblockadeguards,Aelrynth,,,Glenden Invaders Blockade Guard quest cooldown timer,,TRUE,72000,-1,set by Londigul Ellic the Armorer, +glendeninvadersblockadeguardstarted,Aelrynth,,,Started Glenden Wood Invaders Blockade Guards portion of quest,,FALSE,0,1,set by Londigul Ellic the Armorer, +glendeninvadersblockaden,Aelrynth,,,Glenden Wood Invaders Blockade Guard North,,FALSE,0,1,set by Blockade Guard, +glendeninvadersblockadew,Aelrynth,,,Glenden Wood Invaders Blockade Guard West,,FALSE,0,1,set by Blockade Guard, +glendeninvaderskills,Aelrynth,,,Glenden Woods Invaders kill counter,,TRUE,0,20,"set by Eater, Engorged Eater, Famished Eater and 3 more", +glendeninvadersstarted,Aelrynth,,,Started Glenden Wood Invaders quest,,FALSE,0,1,set by Londigul Ellic the Armorer, +glendenorbgiven,Aelrynth,,,Glenden Wood Recall Orb given,,FALSE,0,1,set by Londigul Ellic the Armorer, +glormigothbet,Aelrynth,,,Player bet on Glormigoth,,FALSE,0,1,set by Glormigoth, +glowingboxpickup,Aelrynth,,,Player has picked up Glowing Box,,TRUE,72000,-1,, +glowingstatueshardpickuptimer,Aelrynth,,,Pickup timer for Glowing Statue Shard,,TRUE,72000,-1,, +glyphkiviklirshardamber,Aelrynth,,,You've used the Eye.,,TRUE,900,-1,, +glyphkiviklirshardblood,Aelrynth,,,You've used the Eye.,,TRUE,900,-1,, +glyphkiviklirshardserpentine,Aelrynth,,,You've used the Eye.,,TRUE,900,-1,, +glyphkiviklirshardwood,Aelrynth,,,You've used the Eye.,,TRUE,900,-1,, +glyphofalterationpickup,Aelrynth,,,Glyph of Alteration pickup timer,,TRUE,72000,-1,, +goldenshuriken16count,Aelrynth,,,Player turned in a Golden Shuriken of Tanada,,TRUE,0,16,set by Master Liao Oazaka, +goldgeartrooperkillcount,Aelrynth,,,kill count,,TRUE,0,25,set by Sir Stavitor, +goldgeartrooperkilltask,Aelrynth,,,kill task timer,,TRUE,72000,-1,set by Sir Stavitor, +goldinvaderlordhelm,Aelrynth,,,Timer for Gold Lord Helm,,TRUE,72000,-1,, +goldknightmedallion,Aelrynth,,,Defense of Zaikhal Medallion Pickup Timer Gold,,TRUE,72000,-1,set by Jun Sawashima, +goldlegionchestkey,Aelrynth,,,Pick Up Key for Gold Chest,,TRUE,72000,-1,, +goldlegiondoorkey,Aelrynth,,,Pick Up Key for Door to Gold Legion,,TRUE,72000,-1,, +goldletterinprogress,Aelrynth,,,Turn in Timer/Counter for Lucky Gold Letters,,TRUE,604800,100,, +goldletterturnins,Aelrynth,Non-Quest,https://acportalstorm.com/wiki/Non-Quest,Counter for Lucky Gold Letter turn ins. See Collector; Black Hill Collector; Yukara Miko the Collector.,Counter for Lucky Gold Letter turn ins.,TRUE,0,100,"set by Black Hill Collector, Collector, Yukara Miko the Collector", +goldletterturnintimer,Aelrynth,Non-Quest,https://acportalstorm.com/wiki/Non-Quest,Countdown timer for Lucky Gold Letter turn ins. See Yukara Miko the Collector; Collector; Black Hill Collector.,Countdown timer for Lucky Gold Letter turn ins.,TRUE,604800,-1,"set by Black Hill Collector, Collector, Yukara Miko the Collector", +golemcoralviceroyslayerquest,Aelrynth,,,You are on the Mud Golem Sludge Lord Slayer Quest,,TRUE,0,11,set by Coral Golem Viceroy, +golemglacialmargraveslayerquest,Aelrynth,,,You are on the Mud Golem Sludge Lord Slayer Quest,,TRUE,0,11,set by Glacial Golem Margrave, +golemhuntingneftetkillcount,Aelrynth,,,Golem Hunting Neftet Kill Counter,,TRUE,0,25,, +golemhuntingneftetkilltask,Aelrynth,,,Golem Hunting Neftet Kill Task,,TRUE,72000,-1,, +golemironkingpinslayerquest,Aelrynth,,,You are on the Mud Golem Sludge Lord Slayer Quest,,TRUE,0,11,set by Copper Golem Kingpin, +golemmagmaexarchslayerquest,Aelrynth,,,You are on the Mud Golem Sludge Lord Slayer Quest,,TRUE,0,11,set by Magma Golem Exarch, +golemmudsludgelordslayerquest,Aelrynth,,,You are on the Mud Golem Sludge Lord Slayer Quest,,TRUE,0,11,set by Mud Golem Sludge Lord, +golemplatinumkingslayerquest,Aelrynth,,,You are on the Mud Golem Sludge Lord Slayer Quest,,TRUE,0,11,set by Platinum Golem Mountain King, +golemsamuraikillcount,Aelrynth,,,Golem Samurai Kill Counter,,TRUE,0,15,, +golemsamuraikilltask,Aelrynth,,,Golem Samurai Kill Task,,TRUE,72000,-1,, +golemstonediemosgiven,Aelrynth,,,Gave Diemos the Golem Stone,,FALSE,0,1,set by Gladiator Diemos, +gonjokuagreement,Aelrynth,,,Flagged for Gonjoku Agreement quest,,FALSE,0,1,set by Anton Sillezi, +gorgetnuhmudirafound,Aelrynth,,,This quest flag is obsolete.,,FALSE,0,1,, +gormlingstoutquest,Aelrynth,,,Gormling Stout Quest,,TRUE,72000,-1,set by Gormling the Sneaky Seneschal, +gotatlatlrenegaderaids,Aelrynth,,,Picked up Renegade Hunting Brace,,TRUE,72000,-1,, +gotaxerenegaderaids,Aelrynth,,,Picked up Renegade Axe,,TRUE,72000,-1,, +gotbowrenegaderaids,Aelrynth,,,Picked up Renegade Bow,,TRUE,72000,-1,, +gotcrossbowrenegaderaids,Aelrynth,,,Picked up Renegade Crossbow,,TRUE,72000,-1,, +gotdarktreerward,Aelrynth,,,turned in 1st crystal,,TRUE,72000,-1,set by Aun Talamura, +gotdec2002decoration,Aelrynth,,,Recieved Decoration.,,TRUE,72000,-1,"set by Anasha, Gift Box", +gotdecpresent,Aelrynth,,,Received present.,,TRUE,72000,-1,"set by Anasha, Gift Box", +gotdiamondidol,Aelrynth,,,You've looted a diamond idol recently.,,TRUE,72000,-1,, +gotelariwoodidol,Aelrynth,,,You've looted an elariwood idol recently.,,TRUE,72000,-1,, +gotfrozenfuryaward,Aelrynth,,,Player got sword,,TRUE,72000,-1,set by Sword of Frozen Fury, +gotgemportalmageacademy,Aelrynth,,,You have recently picked up the Black Gem,,TRUE,72000,-1,, +gothomecomingflag,Aelrynth,,,You already got your Homecoming Flag!,,FALSE,0,1,set by Jalina al-Hajj, +gotiolite,Aelrynth,,,Player was given Iolite,,TRUE,72000,-1,set by Anasha, +gotjesterlocation,Aelrynth,,,quest timer,,FALSE,0,1,set by Wall, +gotminnowtoken,Aelrynth,,,Player has recieved the first Minnow Title Token.,,FALSE,0,1,checked by Tackle Master, +gotolthoiatlatl,Aelrynth,,,Picked up note,,TRUE,72000,-1,set by Pincer Danta, +gotolthoiaxe,Aelrynth,,,Picked up note,,TRUE,72000,-1,set by Narg, +gotolthoikatar,Aelrynth,,,Picked up note,,TRUE,72000,-1,"set by Nanoc, Basher of Bugs", +gotolthoispear,Aelrynth,,,Picked up note,,TRUE,72000,-1,set by Teela, +gotpainbringerhead,Aelrynth,,,You've looted the head of The Painbringer.,,TRUE,72000,-1,, +gotrealaidainraiment,Aelrynth,,,Player has already received the Realaidain Raiment.,,FALSE,0,1,set by Adara al-Rajin, +gotrustedbrasskey,Aelrynth,,,You've picked up a Rusted Brass key.,,TRUE,72000,-1,, +gotsoulshatterreward,Aelrynth,,,turned in 3rd crystal,,TRUE,72000,-1,set by Student, +gotspeargivenheart,Aelrynth,,,got the spear,,TRUE,72000,-1,set by Spear of the Given Heart, +gotspeartokenhalf1,Aelrynth,,,got the spear token half,,TRUE,72000,-1,, +gotspeartokenhalf2,Aelrynth,,,got the spear token half,,TRUE,72000,-1,, +gottamianjournal,Aelrynth,,,Got Tamian Journal,,TRUE,72000,-1,set by Tian Li Quan, +gottamianjournalaward,Aelrynth,,,Got Tamian Journal Award,,TRUE,72000,-1,set by Astara Duskshield, +gottamiannote4award,Aelrynth,,,Got Tamian Note4 award,,TRUE,72000,-1,set by Astara Duskshield, +gottuskerfur,Aelrynth,,,You've looted infected tusker fur recently.,,TRUE,72000,-1,, +gotwardingring,Aelrynth,,,You've looted a warding ring recently.,,TRUE,72000,-1,, +graelislandcomplete0606,Aelrynth,,,Player has completed Raising Graels Island,,TRUE,72000,-1,set by Kiriel Shadowborn, +graelislandtempleeastaccess0606,Aelrynth,,,Player has access to Eastern Catacombs Portal,,FALSE,0,1,set by Kiriel Shadowborn, +graelislandtemplenorthaccess1215,Aelrynth,,,Player has access to Northern Catacombs Portal,,FALSE,0,1,set by Kiriel Shadowborn, +graelislandtemplewestaccess1215,Aelrynth,,,Player has access to Western Catacombs Portal,,FALSE,0,1,set by Kiriel Shadowborn, +graelschamber_flag,Aelrynth,,,Access granted to the Graels Chamber Upper Portal,,FALSE,0,1,, +graelschamberportalflag,Aelrynth,,,Player has access to Graels Chamber,,FALSE,0,1,, +graelschambershadow_flag,Aelrynth,,,Access granted to the Graels Chamber Upper Portal,,FALSE,0,1,, +graelsrage,Aelrynth,,,Flagged for entry into Grael's Rage dungeons,,FALSE,0,1,set by Ssavish, +graelssummoningchamber_start,Aelrynth,,,Player has started the Graels Summoning Chamber Quest,,FALSE,0,1,set by Jathaq al-Nishadina, +graelssummoningchamber_wait,Aelrynth,,,Player has completed Graels Summoning Chamber Quest,,TRUE,72000,-1,set by Jathaq al-Nishadina, +graveratkillcount,Aelrynth,,,Grave Rat Kill Counter,,TRUE,0,100,, +graveratkilltask,Aelrynth,,,Grave Rat Kill Task,,TRUE,72000,-1,, +graverobbercompleted_0213,Aelrynth,,,Received reward from Grularr,,TRUE,72000,-1,set by Grularr Wa'ydo, +graverobberstarted_0213,Aelrynth,,,Talked to Grularr in Kara to stamp quest,,FALSE,0,1,set by Grularr Wa'ydo, +graveyardskeletonkillcount,Aelrynth,,,Graveyard Skeleton Kill Counter,,TRUE,0,30,, +graveyardskeletonkilltask,Aelrynth,,,Graveyard Skeleton Kill Task,,TRUE,72000,-1,, +graveyardspiritkillcount,Aelrynth,,,Graveyard Spirit Kill Counter,,TRUE,0,10,, +graveyardspiritkilltask,Aelrynth,,,Graveyard Spirit Kill Task,,TRUE,72000,-1,, +graveyardwightkillcount,Aelrynth,,,Graveyard Wight Kill Counter,,TRUE,0,30,, +graveyardwightkilltask,Aelrynth,,,Graveyard Wight Kill Task,,TRUE,72000,-1,, +graveyardwispkillcount,Aelrynth,,,Graveyard Wisp Kill Counter,,TRUE,0,5,, +graveyardwispkilltask,Aelrynth,,,Graveyard Wisp Kill Task,,TRUE,72000,-1,, +grazertrust,Aelrynth,,,Pickup timer for Grazer Bug,,TRUE,72000,-1,, +greatcavepenguinegg,Aelrynth,,,Great Cave Penguin Egg Pickup Timer,,TRUE,72000,-1,, +greatershadowarmoraluvian1,Aelrynth,,,Greater Aluvian Shadow Armor 1,,FALSE,0,1,set by Alean the Steel Forger, +greatershadowarmoraluvian2,Aelrynth,,,Greater Aluvian Shadow Armor 2,,FALSE,0,1,set by Alean the Steel Forger, +greatershadowarmoraluvian3,Aelrynth,,,Greater Aluvian Shadow Armor 3,,FALSE,0,1,set by Alean the Steel Forger, +greatershadowarmorgharundim1,Aelrynth,,,Greater Gharundim Shadow Armor 1,,FALSE,0,1,set by Jibril ibn Rashid, +greatershadowarmorgharundim2,Aelrynth,,,Greater Gharundim Shadow Armor 2,,FALSE,0,1,set by Jibril ibn Rashid, +greatershadowarmorgharundim3,Aelrynth,,,Greater Gharundim Shadow Armor 3,,FALSE,0,1,set by Jibril ibn Rashid, +greatershadowarmorsho1,Aelrynth,,,Greater Sho Shadow Armor 1,,FALSE,0,1,set by Koga Hideki, +greatershadowarmorsho2,Aelrynth,,,Greater Sho Shadow Armor 2,,FALSE,0,1,set by Koga Hideki, +greatershadowarmorsho3,Aelrynth,,,Greater Sho Shadow Armor 3,,FALSE,0,1,set by Koga Hideki, +gredalinearcanerestoration,Aelrynth,,,Gredaline Arcane Restoration Scroll,,TRUE,72000,-1,, +gredalinedarkflame,Aelrynth,,,Gredaline Dark Flame Scroll,,TRUE,72000,-1,, +gredalineunnaturalpersistence,Aelrynth,,,Gredaline Unnatural Persistence Scroll,,TRUE,72000,-1,, +greenbloodgem,Aelrynth,,,Ricardo's Blood Gem - Green,,TRUE,72000,-1,, +greenmirecuirassquest,Aelrynth,,,Picked Up Broken Green Mire Cuirass,,TRUE,72000,-1,, +greenmireyariquest,Aelrynth,,,Picked Up Broken Green Mire Yari,,TRUE,72000,-1,, +gregorscarefullyrolledscrollpickedup,Aelrynth,Pickup timer for carefully rolled scroll,,Pickup timer for carefully rolled scroll,,TRUE,72000,-1,, +grievvershredderkillcount,Aelrynth,,,Grievver Shredder Kill Counter,,TRUE,0,15,, +grievvershredderkilltask,Aelrynth,,,Grievver Shredder Kill Task,,TRUE,72000,-1,, +grievversilk,Aelrynth,,,Player has picked up some Grievver Silk and cannot pick up more for 2 weeks.,,TRUE,72000,-1,checked by Verdentine Magnan, +grievverv,Aelrynth,,,Grievver Violator Kill Task,,TRUE,72000,-1,set by Moina, +grievvervkillcount,Aelrynth,,,Grievver Violator Kill Counter,,TRUE,0,100,set by Moina, +grimyseainvasionkey_pickup,Aelrynth,,,Pickup timer for Grimy Sea Invasion Key,,TRUE,72000,-1,, +gromnietoothbrushash,Aelrynth,,,You have been granted experience into your cooking skill.,,TRUE,72000,-1,set by Copper Vanurp, +gromnietoothbrushazure,Aelrynth,,,You have been granted experience into your cooking skill.,,TRUE,72000,-1,set by Copper Vanurp, +gromnietoothbrushbrass,Aelrynth,,,You have been granted experience into your cooking skill.,,TRUE,72000,-1,set by Copper Vanurp, +gromnietoothbrushcopper,Aelrynth,,,You have been granted experience into your cooking skill.,,TRUE,72000,-1,set by Copper Vanurp, +gromnietoothbrushebon,Aelrynth,,,You have been granted experience into your cooking skill.,,TRUE,72000,-1,set by Copper Vanurp, +gromnietoothbrushivory,Aelrynth,,,You have been granted experience into your cooking skill.,,TRUE,72000,-1,set by Copper Vanurp, +gromnietoothbrushjade,Aelrynth,,,You have been granted experience into your cooking skill.,,TRUE,72000,-1,set by Copper Vanurp, +gromnietoothbrushrust,Aelrynth,,,You have been granted experience into your cooking skill.,,TRUE,72000,-1,set by Copper Vanurp, +gromnietoothbrushsable,Aelrynth,,,You have been granted experience into your cooking skill.,,TRUE,72000,-1,set by Copper Vanurp, +gromnietoothbrushswamp,Aelrynth,,,You have been granted experience into your cooking skill.,,TRUE,72000,-1,set by Copper Vanurp, +gromnietoothpasteash,Aelrynth,,,You have been granted experience into your alchemy skill.,,TRUE,72000,-1,set by Tiffany Comfore, +gromnietoothpasteazure,Aelrynth,,,You have been granted experience into your alchemy skill.,,TRUE,72000,-1,set by Tiffany Comfore, +gromnietoothpastebrass,Aelrynth,,,You have been granted experience into your alchemy skill.,,TRUE,72000,-1,set by Tiffany Comfore, +gromnietoothpastecopper,Aelrynth,,,You have been granted experience into your alchemy skill.,,TRUE,72000,-1,set by Tiffany Comfore, +gromnietoothpasteebon,Aelrynth,,,You have been granted experience into your alchemy skill.,,TRUE,72000,-1,set by Tiffany Comfore, +gromnietoothpasteivory,Aelrynth,,,You have been granted experience into your alchemy skill.,,TRUE,72000,-1,set by Tiffany Comfore, +gromnietoothpastejade,Aelrynth,,,You have been granted experience into your alchemy skill.,,TRUE,72000,-1,set by Tiffany Comfore, +gromnietoothpasterust,Aelrynth,,,You have been granted experience into your alchemy skill.,,TRUE,72000,-1,set by Tiffany Comfore, +gromnietoothpastesable,Aelrynth,,,You have been granted experience into your alchemy skill.,,TRUE,72000,-1,set by Tiffany Comfore, +gromnietoothpasteswamp,Aelrynth,,,You have been granted experience into your alchemy skill.,,TRUE,72000,-1,set by Tiffany Comfore, +gromnietoothpickash,Aelrynth,,,You have been granted experience into your fletching skill.,,TRUE,72000,-1,set by Wils Morrem, +gromnietoothpickazure,Aelrynth,,,You have been granted experience into your fletching skill.,,TRUE,72000,-1,set by Wils Morrem, +gromnietoothpickbrass,Aelrynth,,,You have been granted experience into your fletching skill.,,TRUE,72000,-1,set by Wils Morrem, +gromnietoothpickcopper,Aelrynth,,,You have been granted experience into your fletching skill.,,TRUE,72000,-1,set by Wils Morrem, +gromnietoothpickebon,Aelrynth,,,You have been granted experience into your fletching skill.,,TRUE,72000,-1,set by Wils Morrem, +gromnietoothpickivory,Aelrynth,,,You have been granted experience into your fletching skill.,,TRUE,72000,-1,set by Wils Morrem, +gromnietoothpickjade,Aelrynth,,,You have been granted experience into your fletching skill.,,TRUE,72000,-1,set by Wils Morrem, +gromnietoothpickrust,Aelrynth,,,You have been granted experience into your fletching skill.,,TRUE,72000,-1,set by Wils Morrem, +gromnietoothpicksable,Aelrynth,,,You have been granted experience into your fletching skill.,,TRUE,72000,-1,set by Wils Morrem, +gromnietoothpickswamp,Aelrynth,,,You have been granted experience into your fletching skill.,,TRUE,72000,-1,set by Wils Morrem, +gromnuseye_pickup,Aelrynth,,,Pickup timer on Gromnus Eye.,,TRUE,72000,-1,, +guardianofthedarktitletoken,Aelrynth,,,Guardian of the Dark title token pickup timer,,TRUE,72000,-1,, +guardianofthederutrees_completed,Aelrynth,,,Player wait timer for the Guardian of the Deru Trees of Marae Lassel quest.,,TRUE,72000,-1,set by Aun Kimintari, +guardianofthederutrees_fetishhandedin,Aelrynth,,,Player has handed the Wharu Fetish to the Altar of Tthuun.,,FALSE,0,1,set by Altar of T'thuun, +guardianofthederutrees_flag,Aelrynth,,,"Player flag for Roots of Skuld, Urd and Verdandi portal.",,FALSE,0,1,set by Aun Kimintari, +guardianofthederutrees_startfetish,Aelrynth,,,Player has turned in the Corrupted Mana Shard for Guardian of the Deru Trees of Marae Lassel quest.,,FALSE,0,1,set by Aun Kimintari, +guardianofthederutrees_startjelly,Aelrynth,,,Player has started the Guardian of the Deru Trees of Marae Lassel quest.,,FALSE,0,1,set by Aun Kimintari, +guardianofthederutrees_startshard,Aelrynth,,,Player has turned in the Royal Jelly for Guardian of the Deru Trees of Marae Lassel quest.,,FALSE,0,1,set by Aun Kimintari, +guardianstatuekillcount,Aelrynth,,,Guardian Statue Kill Counter,,TRUE,0,10,, +guardianstatuekilltask,Aelrynth,,,Guardian Statue Kill Task,,TRUE,72000,-1,, +guardwinterbornflag,Aelrynth,,,Player has completed Aerbax Prodigal Banderling Quest at least once.,,FALSE,0,1,set by Guard Winterborn, +guppycounter,Aelrynth,,,Number of Minnows turned in.,,TRUE,0,100,set by Fishing Hole, +gurogcreationcompleted_1110,Aelrynth,,,Fayza Journal and Note Turn In,,TRUE,72000,-1,set by Fayza, +gurogcreationstarted_1110,Aelrynth,,,Mortified Soldier Journal and Note Turn In Start,,FALSE,0,1,set by Mortified Soldier, +gurogkillcount,Aelrynth,,,Gurog Kill Counter,,TRUE,0,20,, +gurogkilltask,Aelrynth,,,Gurog Kill Task,,TRUE,72000,-1,, +gurogpresentraidswait,Aelrynth,,,Player wait timer for Gurog Present Raids,,TRUE,72000,-1,set by Holiday Present, +gurukbasherkillcount,Aelrynth,,,Guruk Basher Kill Counter,,TRUE,0,40,set by Shiruuk, +gurukbasherkilltask,Aelrynth,,,Guruk Basher Kill Task,,TRUE,72000,-1,set by Shiruuk, +gurukcolossuskillcount,Aelrynth,,,Guruk Colossus Kill Counter,,TRUE,0,30,set by Brogosh, +gurukcolossuskilltask,Aelrynth,,,Guruk Colossus Kill Task,,TRUE,72000,-1,set by Brogosh, +gurukfiendkillcount,Aelrynth,,,Guruk Fiend Kill Counter,,TRUE,0,30,set by Mohor, +gurukfiendkilltask,Aelrynth,,,Guruk Fiend Kill Task,,TRUE,72000,-1,set by Mohor, +gurukmarauderkillcount,Aelrynth,,,Guruk Marauder Kill Counter,,TRUE,0,40,set by Kurket, +gurukmarauderkilltask,Aelrynth,,,Guruk Marauder Kill Task,,TRUE,72000,-1,set by Kurket, +gurukmonstrositykillcount,Aelrynth,,,Guruk Monstrosity Kill Counter,,TRUE,0,10,set by Borsh, +gurukmonstrositykilltask,Aelrynth,,,Guruk Monstrosity Kill Task,,TRUE,72000,-1,set by Borsh, +guruksmasherkillcount,Aelrynth,,,Guruk Smasher Kill Counter,,TRUE,0,40,set by Kushuk, +guruksmasherkilltask,Aelrynth,,,Guruk Smasher Kill Task,,TRUE,72000,-1,set by Kushuk, +gwillimalchemybag,Aelrynth,,,Gwillim's Alchemy Bag,,TRUE,72000,-1,, +gwillimalchemynote,Aelrynth,,,Gwillim's Alchemy Notes,,TRUE,72000,-1,, +gycoloinprogress,Aelrynth,,,Player has started GY Colo,,TRUE,3600,-1,set by GY Colo Time Keeper, +gycolomobkilled,Aelrynth,,,Player has killed a creature found in GY Colo,,TRUE,0,-1,, +gycoloornatebonekeyturnedin,Aelrynth,,,Player has turned in ornate bone key,,FALSE,0,1,set by Guardian Statue, +gycolorewardgiven,Aelrynth,,,Lord Cynreft Handed out reward,,TRUE,0,10,"set by Lady Tairla Mhoire, Lord Cynreft Mhoire, Ranger Lord Grymar Mhoire", +gycolorewardgiverinprogress,Aelrynth,,,Shade of Lord Cynreft Spawned,,TRUE,175,-1,"set by Bael'Zharon Summoner, Jester, Lady Tairla Mhoire and 4 more", +gycolowinrewardreceived,Aelrynth,,,Received Reward from GY Colo,,TRUE,190,-1,set by Lord Cynreft Mhoire, +hadfishinglicense,Aelrynth,,,Player has already gotten a fishing license at least once.,,FALSE,0,1,set by Tackle Master, +hagrashead,Aelrynth,,,Picked up Head of Big Chief Hagra,,TRUE,72000,-1,, +haltdericostritualquestflag,Aelrynth,,,One time Flag for Halt Dericost Ritual Quest,,FALSE,0,1,set by Sir Learth, +hamudsdemisecompleted_0511,Aelrynth,,,Completed Hamuds Demise,,TRUE,72000,-1,set by Devana bint Hamudi, +hamudsdemisestarted_0511,Aelrynth,,,Started Hamuds Demise,,FALSE,0,1,"set by Ivory Crafter, Ulna bint-Fasha the Ivory Crafter", +handofblightfinger_pickup,Aelrynth,,,Player has picked up Hand of Blightfinger,,TRUE,72000,-1,, +harbingercompletedaerbax,Aelrynth,,,Aerbax said that you are all cool.,,FALSE,0,1,set by Surface, +harbingercompletednuhmudira,Aelrynth,,,Nuhmudira said that you are all cool.,,FALSE,0,1,set by Surface, +harbingercompletedwaitissk,Aelrynth,,,Issk says wait your turn.,,TRUE,72000,-1,set by Issk, +harbingercompletedwaitvincadi,Aelrynth,,,Vincadi wants you to wait.,,TRUE,72000,-1,set by Vincadi, +harbingerempowered,Aelrynth,,,Flagged for Empowered Harbinger fight,,FALSE,0,1,set by Harbinger's Lair, +harbingerempoweredtokenpickup,Aelrynth,,,Empowered Harbinger Token pickup timer,,TRUE,72000,-1,, +harbingeressenceless,Aelrynth,,,Flagged for Essenceless Harbinger fight,,FALSE,0,1,set by Harbinger's Lair, +harbingeressencelesstokenpickup,Aelrynth,,,Essenceless Harbinger Token pickup timer,,TRUE,72000,-1,, +harbingerprodigal,Aelrynth,,,Flagged for Prodigal Harbinger fight,,FALSE,0,1,set by Hollow, +harbingerraisealchemy,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisearcane,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisearmortink,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiseassesscreature,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiseaxe,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisebow,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiseconversion,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisecooking,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisecreature,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisecrossbow,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisedagger,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisedeception,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisefletching,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisehealing,Aelrynth,,,I want to raise this skill,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiseitem,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiseitemtink,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisejump,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiseleadership,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiselife,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiselockpick,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiseloyalty,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisemace,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisemagic,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisemagictink,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisemelee,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisemissile,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiseperson,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiserun,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiseshield,Aelrynth,,,I want to raise this skill,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisespear,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisestaff,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisesword,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisethrown,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiseunarmed,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraisewar,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerraiseweapontink,Aelrynth,,,I want to raise this skill.,,FALSE,0,1,"set by Issk, Vincadi", +harbingerwarrior,Aelrynth,,,Player has fought against Harbinger and made a difference.,,FALSE,0,1,, +harbingerwarriorwait,Aelrynth,,,Player has received the harbinger arm token.,,TRUE,72000,-1,, +hardenedbone_pickup,Aelrynth,,,Player has picked up the Hardened Bone.,,TRUE,72000,-1,, +hardunnabandquest,Aelrynth,,,Retreive Hardunna's Wedding Band,,TRUE,72000,-1,, +hareltahkill1,Aelrynth,,,Give Aun Hareltah TribalTotemHea,,TRUE,72000,-1,"set by Aun Hareltah, Aun Kiriona, Aun Rukuona and 1 more", +harkerkilled,Aelrynth,,,Picked up the deflated Harker Head.,,TRUE,72000,-1,"checked by Hibdin Velos, Remmick", +harraagslairflag,Aelrynth,,,Player flag for drop location portal in Harraags Hideout,,FALSE,0,1,, +harvesterinitialquest,Aelrynth,,,Harvester in the Mist,,TRUE,72000,-1,set by Behdo Yii, +harvestreaperkillcount,Aelrynth,,,Harvest Reaper Kill Counter,,TRUE,0,10,, +harvestreaperkilltask,Aelrynth,,,Harvest Reaper Kill Task,,TRUE,72000,-1,, +hasatamarrbronze,Aelrynth,,,HasAtamarrBronze flag,,FALSE,0,1,set by Atamarr, +hasatamarrcopper,Aelrynth,,,HasAtamarrCopper flag,,FALSE,0,1,set by Atamarr, +hasatamarriron,Aelrynth,,,HasAtamarrIron flag,,FALSE,0,1,set by Atamarr, +hasatamarrsilver,Aelrynth,,,HasAtamarrSilver flag,,FALSE,0,1,set by Atamarr, +hasgemknathcore1,Aelrynth,,,Handed in Piece of Knath Core,,FALSE,0,1,set by Jester, +haslordstatueriddle,Aelrynth,,,Lord Test Statue Has Given Riddle,,FALSE,0,1,set by Statue, +hassnowglobecabin,Aelrynth,Player has recieved the Snowy Cabin Snowglobe.,,Player has recieved the Snowy Cabin Snowglobe.,Player has recieved the Snowy Cabin Snowglobe.,TRUE,5184000,-1,set by Blind Snowman, +hassnowglobeneydisa,Aelrynth,,,Handed in A Perfect Snowman Eye,,TRUE,72000,-1,set by Blind Snowman, +hassnowglobesnowman,Aelrynth,Player has recieved the Snowman Snowglobe.,,Player has recieved the Snowman Snowglobe.,Player has recieved the Snowman Snowglobe.,TRUE,72000,-1,set by Blind Snowman, +hassphinxriddle,Aelrynth,,,Player has received a riddle from the head.,,FALSE,0,1,set by Tribunal, +hastarsessence_pickup,Aelrynth,,,Player has picked up Hastars Essence,,TRUE,72000,-1,, +hatchrareidolpickup,Aelrynth,,,Rare Idol Pickup,,TRUE,72000,-1,checked by Ulgrim the Unquiet, +hatredsplinterpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +hauberklugian,Aelrynth,,,Lugian Commander Trophy,,TRUE,72000,-1,, +hauntedmansiondungeonpermission,Aelrynth,Frest Greelving's Haunted Mansion,https://acportalstorm.com/wiki/Frest_Greelving's_Haunted_Mansion,Player has permission to use Dungeon portal. See Frest Greelving.,Player has permission to use Dungeon portal,TRUE,72000,-1,set by Frest Greelving, +havefishinglicense,Aelrynth,,,Player has a fishing license.,,TRUE,72000,-1,set by Tackle Master, +heaboneflag,Aelrynth,,,Flagged to enter Hagra's Holdfast,,FALSE,0,1,set by Hea Kassoka, +heaboneflagtimer,Aelrynth,,,Hagra's Holdfast Portal Flag Timer,,TRUE,72000,-1,set by Hea Kassoka, +heaboneheadtimer,Aelrynth,,,Timer for reward from Hagras Head,,TRUE,72000,-1,, +heaboneheadturnin,Aelrynth,,,Timer for turning in Hagras Head,,TRUE,72000,-1,set by Hea Kassoka, +heabonetreatytimer,Aelrynth,,,Timer for reward from Hagras Treaty,,TRUE,72000,-1,, +heabonetreatyturnin,Aelrynth,,,Timer for turning in Hagras Treaty,,TRUE,72000,-1,set by Hea Kassoka, +headfazendaterror,Aelrynth,,,Picked Up Fazenda Terror's Head,,TRUE,72000,-1,, +headmorgluuk,Aelrynth,,,You've collected the head from Morgluuk's remains.,,TRUE,72000,-1,, +headofpontifexmaegris_pickup,Aelrynth,,,Player has picked up the Head of Pontifex Maegris,,TRUE,72000,-1,, +headofrheagapickuptimer,Aelrynth,,,Picked up Head of Rheaga,,TRUE,1728000,-1,, +headoftheapparitionolthoiqueenpickuptimer,Aelrynth,,,Picked up Head of the Apparition Olthoi Queen,,TRUE,72000,-1,, +headofthemukkirscion_pickup,Aelrynth,,,Player has picked up the Head of the Mukkir Scion,,TRUE,72000,-1,, +healingkitpickup,Aelrynth,,,Player has picked up an Academy healing potion,,TRUE,0,5,, +healthpickup,Aelrynth,,,Player has picked up an Academy health potion,,TRUE,0,15,, +heardblindsnowmansadstory,Aelrynth,,,Player has heard the Blind Snowmans sad story.,,TRUE,72000,-1,set by Blind Snowman, +hearthstone,Aelrynth,,,Unused Questflag,,TRUE,10800,-1,, +heartinnocenttaken,Aelrynth,,,You got the heart of Jaleh,,TRUE,72000,-1,set by Body of Jaleh al-Thani, +heartofarchmageaigonne_pickup,Aelrynth,,,Player has picked up the Heart of Archmage Aigonne,,TRUE,72000,-1,, +heartofarchmageaigonne_turnin,Aelrynth,,,PLayer has turned in the Heart of Archmage Aigonne,,FALSE,0,1,set by Jathaq al-Nishadina, +heartofinnocence,Aelrynth,,,Access to the Heart of the Innocent,,FALSE,0,1,set by Fir Tree, +heatnakareabet,Aelrynth,,,Player bet on Hea Tnakarea,,FALSE,0,1,set by Hea Tnakarea, +heatoneawacompleted,Aelrynth,,,Hea Toneawa and Aun Mariona quest. Toneawa sends players on this quest only once a day.,,TRUE,72000,-1,set by Hea Toneawa, +heawindreavekillcount,Aelrynth,,,Hea Windreave Kill Counter,,TRUE,0,25,set by Susana du Loc, +heawindreavekilltask,Aelrynth,,,Hea Windreave Kill Task,,TRUE,72000,-1,set by Susana du Loc, +helmoftremborh_pickup,Aelrynth,,,Pickup timer on Helm of TrembOrh.,,TRUE,72000,-1,, +helmsimulacra,Aelrynth,,,Helm of the Simulacra,,TRUE,72000,-1,, +helpedasheron,Aelrynth,,,You have entered a dungeon to try to help Asheron!,,FALSE,0,1,"set by Matron Hive East, Matron Hive North, Matron Hive South and 1 more", +helpedjonas,Aelrynth,,,You've helped out Jonas.,,FALSE,0,1,set by Jonas, +herotoken,Aelrynth,,,Pickup timer for Hero Tokens,,TRUE,72000,-1,, +highnestkiller,Aelrynth,,,Player assisted in killing a newbie nest.,,FALSE,0,1,, +highpriestacolytedead,Aelrynth,,,HighPriestAcolyteDead,,FALSE,0,1,set by High Priest's Acolyte, +highpriestfirstdead,Aelrynth,,,HighPriestFirstDead,,FALSE,0,1,set by High Priest's First, +highpriestoftthuunkillcount,Aelrynth,,,High Priest of T'thuun Kill Counter,,FALSE,0,1,, +highpriestoftthuunkilltask,Aelrynth,,,High Priest of T'thuun Kill Task,,TRUE,72000,-1,, +highpriestseconddead,Aelrynth,,,HighPriestSecondDead,,FALSE,0,1,set by High Priest's Second, +highpriestthirddead,Aelrynth,,,HighPriestThirdDead,,FALSE,0,1,set by High Priest's Third, +hiveevispincer_0513,Aelrynth,,,Hive Eviscerator Pincer,,TRUE,72000,-1,, +hivequeenkill,Aelrynth,,,quest timer,,FALSE,0,1,set by Olthoi Hive Queen, +hivewarriorpincer_0513,Aelrynth,,,quest timer,,TRUE,72000,-1,, +hizkribeaten,Aelrynth,,,You beat the temple of Hizk Ri.,,FALSE,0,1,set by Guardian, +hizkricomplete,Aelrynth,,,You've completed the Hizk Ri quest with a fellowship.,,TRUE,72000,-1,"set by Biting Ballistae, Portal to Izji Qo's Temple, Razorbound Flange and 7 more", +hizkrientrance,Aelrynth,,,You've been given the entrance exam for Hizk Ri's temple; go pass it!,,FALSE,0,1,set by Guardian, +hizkrientrance1,Aelrynth,,,So far so good you have one part of the entrance exam right!,,FALSE,0,1,set by Pillar, +hizkrientrance2,Aelrynth,,,So far so good you have one part of the entrance exam right!,,FALSE,0,1,set by Pillar, +hizkrientrance3,Aelrynth,,,So far so good you have one part of the entrance exam right!,,FALSE,0,1,set by Pillar, +hizkrientrance4,Aelrynth,,,So far so good you have one part of the entrance exam right!,,FALSE,0,1,set by Pillar, +hizkrientrancefail,Aelrynth,Hizk Ri,,You've failed the entrance exam to Hizk Ri's temple.,,FALSE,0,1,set by Pillar, +hizkrieye1,Aelrynth,,,You have selected the correct eye in the Gauntlet.,,FALSE,0,1,set by Eye of the Watcher, +hizkrieye2,Aelrynth,,,You have selected the correct eye in the Gauntlet.,,FALSE,0,1,set by Eye of the Watcher, +hizkrieye3,Aelrynth,,,You have selected the correct eye in the Gauntlet.,,FALSE,0,1,set by Eye of the Watcher, +hizkrieye4,Aelrynth,,,You have selected the correct eye in the Gauntlet.,,FALSE,0,1,set by Eye of the Watcher, +hizkrifinished,Aelrynth,,,You've collected the reward for the Hizk Ri quest.,,TRUE,72000,-1,"set by Hezhit, Jrvik, Zixki", +hizkrisarcophagus,Aelrynth,,,You've claimed the reward from the Sarcophagus of Hizk Ri.,,TRUE,72000,-1,"set by Sarcophagus of High Matriarch, Hizk Ri", +holchashead_pickup,Aelrynth,,,Pickup timer on Holchas Head.,,TRUE,72000,-1,, +hollownoteacademypickup,Aelrynth,,,Player has picked up the HOllow Minion Note,,FALSE,0,1,, +hollowsused,Aelrynth,,,Player has shown Elemental Talisman to a hollow.,,TRUE,0,15,checked by Hollow, +hollyjollyhelperquest,Aelrynth,,,Holly Jolly Helper Quest,,TRUE,72000,-1,, +holtburgafrincorn1204,Aelrynth,,,Retreive Alfrin's Bag of Corn Seed,,TRUE,72000,-1,, +holtburgafrindrudge1204,Aelrynth,,,Retreive the head of the Drudge Robber Baron for Alfrin.,,TRUE,72000,-1,, +holtburgafrinrye1204,Aelrynth,,,Retreive Alfrin's Bag of Rye Seed,,TRUE,72000,-1,, +holtburgafrinwheat1204,Aelrynth,,,Retreive Alfrin's Bag of Wheat Seed,,TRUE,72000,-1,, +holtburgcomplete,Aelrynth,,,Player has completed the Yaraq Regicide Quest,,TRUE,72000,-1,set by Sir Rylanan, +holtburggreetinggiven,Aelrynth,,,Rylanan has said hello to player,,FALSE,0,1,set by Sir Rylanan, +holtburgnotebrogord1204,Aelrynth,,,Retreive a note from Brogord,,TRUE,72000,-1,, +holtburgredoubtbowl1204,Aelrynth,,,Retreive Worcer's Antique Bowl,,TRUE,72000,-1,, +holtburgredoubtcandlestick1204,Aelrynth,,,Retreive Hardunna's Candlestick,,TRUE,72000,-1,, +holtburgredoubtcompleted_1111,Aelrynth,,,Completed the Holtburg Redoubt Quest,,TRUE,72000,-1,set by Worcer, +holtburgredoubtgoblet1204,Aelrynth,,,Retreive Worcer's Antique Goblet,,TRUE,72000,-1,, +holtburgredoubthandbell1204,Aelrynth,,,Retreive Hardunna's Handbell,,TRUE,72000,-1,, +holtburgredoubtlamp1204,Aelrynth,,,Retreive Hardunna's Lamp,,TRUE,72000,-1,, +holtburgredoubtmug1204,Aelrynth,,,Retreive Worcer's Antique Mug,,TRUE,72000,-1,, +holysymbolpickuptimer,Aelrynth,,,You have obtained the holy symbol from T'thuun Priest.,,TRUE,72000,-1,, +hookhealingmachine,Aelrynth,,,Healing Machine Hook,,TRUE,72000,-1,, +hopeslayerheart,Aelrynth,,,Heart of Shadow,,TRUE,1800,-1,, +hopeslayerobsidiandagger,Aelrynth,,,Obsidian Dagger,,TRUE,72000,-1,, +hopeslayerobsidiankey,Aelrynth,,,Obsidian Key,,TRUE,72000,-1,, +hopeslayersingularity,Aelrynth,,,Fragment of the Singularity,,TRUE,1800,-1,, +hopeslayerskull,Aelrynth,,,Skull of Avoren Palacost,,TRUE,1800,-1,, +hoshinodoorcounter,Aelrynth,,,quest timer,,TRUE,0,20,"set by Falatacot Temple Counter, Hoshino Courtyard Counter, Hoshino Courtyard Gen and 7 more", +hoshinofortarmorpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +hoshinofortkeypickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +hoshinofortpart2,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Ancient Altar, +hoshinomnemosyne1,Aelrynth,,,quest timer,,FALSE,0,1,set by Enchanted Mnemosyne, +hoshinomnemosyne2,Aelrynth,,,quest timer,,FALSE,0,1,set by Enchanted Mnemosyne, +hoshinomnemosyne3,Aelrynth,,,quest timer,,FALSE,0,1,set by Enchanted Mnemosyne, +hoshinomnemosynesdone,Aelrynth,,,quest timer,,FALSE,0,1,set by Enchanted Mnemosyne, +hoshinomustdie_flag,Aelrynth,,,Player has completed Harvesting the Twilight Bulb quest.,,FALSE,0,1,set by Norus, +hoshinotowercomplete_0812,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Mareeno Donn, +hoshinotowershortcut,Aelrynth,,,quest timer,,TRUE,3600,-1,, +hotcoalpickuptimer,Aelrynth,Picked up Hot Coal,,Picked up Hot Coal,,TRUE,72000,-1,, +housedeedhigh,Aelrynth,,,House Deed High,,TRUE,0,6,, +housedeedlow,Aelrynth,,,House Deed Low,,TRUE,0,4,, +housedeedmid,Aelrynth,,,House Deed Mid,,FALSE,0,1,, +housedeednogo,Aelrynth,,,House Deed Acquired,,TRUE,0,4,, +housedeedultra,Aelrynth,,,House Deed Ultra,,TRUE,0,10,, +housestatuebanderlinggiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuebentengiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuedrudgegiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuegolemgiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuegrievvergiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuegromniegiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuemosswartgiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuereedsharkgiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuesclavusgiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuesclavushighgiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatueshadowgiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatueskeletongiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatueskeletonhighgiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuethorstengiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuetumerokgiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuevirindigiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +housestatuezharalimgiven,Aelrynth,,,Player has given received this house statue and can't get another one for a week.,,TRUE,72000,-1,"set by Bhab, Arcanum Tinkerer", +hugemonougarib_pickup,Aelrynth,,,Player has picked up Huge Monouga Rib,,TRUE,72000,-1,, +huskregicidepickup,Aelrynth,,,Player has picked up the husk,,TRUE,72000,-1,"checked by Dame Tsaya, Stranger in Town", +icecampleathermaterialspickedup0805,Aelrynth,,,FineLeatherScraps Timer,,TRUE,72000,-1,, +icecampquestfinished0805,Aelrynth,,,NPC Timer for Halaetan Beach Camps,,TRUE,72000,-1,set by Camp Blacksmith, +icetachiturnedin,Aelrynth,,,Turned Ice Tachi into Ivory Crafter..,,TRUE,72000,-1,"set by Ivory Crafter, Ulna bint-Fasha the Ivory Crafter", +idoqcompleted_0413,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Olthoi Hive Queen's Remains, +idoqstarted_0413,Aelrynth,,,quest timer,,FALSE,0,1,set by Virindi Delegate, +ihopflag,Aelrynth,,,Player can enter Tanada House of Pancakes,,FALSE,0,1,set by Chow Doun, +ihoptooktip,Aelrynth,,,Player took tip from empty plate,,TRUE,0,7,, +ihopwait,Aelrynth,,,Tanada House of Pancakes reward cooldown,,TRUE,72000,-1,set by Chow Doun, +ikzisiktikarizikmaflag,Aelrynth,,,Player equipped Messengers Collar,,FALSE,0,1,set by Messenger's Collar, +illgottenrewards1,Aelrynth,,,Player has handed a reward gem to Kai and has two more trips.,,FALSE,0,1,"set by Kai Mallan, Sho Enchanter", +illgottenrewards2,Aelrynth,,,Player has handed a reward gem to Kai and has two more trips.,,FALSE,0,1,"set by Kai Mallan, Sho Enchanter", +illgottenrewards3,Aelrynth,,,Player has handed a reward gem to Kai and has two more trips.,,TRUE,72000,-1,"set by Kai Mallan, Sho Enchanter", +impiousquestironore,Aelrynth,,,Impious Staff Iron Ore Quest,,TRUE,3600,-1,, +impiousquestslag,Aelrynth,,,Impious Staff Slag Quest,,TRUE,72000,-1,, +impiousstaffbrokengiven,Aelrynth,,,Impious Broken Staff Given,,TRUE,72000,-1,"set by Harlune the Misanthrope, Roderick", +impiousstaffquest,Aelrynth,,,Impious Staff Quest,,TRUE,72000,-1,, +imprintingmote_pickup,Aelrynth,,,Player has picked up the Imprinting Mote at the bottom of Golem Sanctum.,,TRUE,72000,-1,, +incendiarygudardiankilltask,Aelrynth,,,incendiarygudardianKillTask,,TRUE,72000,-1,, +infiltrationbalorfuracquired0205,Aelrynth,,,You acquired a swatch of Balor's fur.,,TRUE,72000,-1,, +infiltrationcomplete_0511,Aelrynth,,,Handed Coda to Lord Kresovus,,TRUE,72000,-1,set by Lord Kresovus, +infiltrationnoteacquired0205,Aelrynth,,,You acquired the note from Kerrak.,,TRUE,72000,-1,, +infiltrationrobeacquired0205,Aelrynth,,,You acquired the Shadow Lugian robe.,,TRUE,72000,-1,, +infiltrationshadowlugianportaldestroyed0205,Aelrynth,,,You have been marked by the Darkness.,,FALSE,0,1,set by Shadow, +infiltrationshieldacquired0205,Aelrynth,,,You acquired the Shadow Lugian shield.,,TRUE,72000,-1,, +iniquitousfragment,Aelrynth,,,Pickup timer for Iniquitous Fragment - Sepulcher of Nightmares,,TRUE,72000,-1,, +insatiableeaterjaw,Aelrynth,,,Insatiable Eater Jaw,,TRUE,518400,-1,, +inscribedpurplegem,Aelrynth,,,Inscribed Purple gem,,TRUE,72000,-1,, +insidiousmonougahandin,Aelrynth,,,Handed in an insidious monouga idol.,,TRUE,72000,-1,"set by Ivory Crafter, Ulna bint-Fasha the Ivory Crafter", +intricatemukkirorbnotespickup,Aelrynth,,,Timer for Vaserio's Encoded Notes pickup,,TRUE,72000,-1,, +invasionquest01,Aelrynth,,,Kill north full invasion Brood Noble,,TRUE,72000,-1,"set by Olthoi Brood Noble, Olthoi Hive Brood", +invasionquest02,Aelrynth,,,Kill northeast full invasion Brood Noble,,TRUE,72000,-1,"set by Olthoi Brood Noble, Olthoi Hive Brood", +invasionquest03,Aelrynth,,,Kill southeast full invasion Brood Noble,,TRUE,72000,-1,"set by Olthoi Brood Noble, Olthoi Hive Brood", +invasionquest04,Aelrynth,,,Kill southwest full invasion Brood Noble,,TRUE,72000,-1,"set by Olthoi Brood Noble, Olthoi Hive Brood", +invasionquest05,Aelrynth,,,Kill northwest full invasion Brood Noble,,TRUE,72000,-1,"set by Olthoi Brood Noble, Olthoi Hive Brood", +invasionquest06,Aelrynth,,,Kill Dires 1 full invasion NobleC,,TRUE,72000,-1,set by Olthoi Noble, +invasionquest07,Aelrynth,,,Kill Dires 2 full invasion NobleC,,TRUE,72000,-1,set by Olthoi Noble, +invasionquest08,Aelrynth,,,Kill the Olthoi Queen!,,TRUE,72000,-1,set by Olthoi Queen, +invasionquest09,Aelrynth,,,Kill Dires 3 full invasion NobleC,,TRUE,72000,-1,set by Olthoi Noble, +invasionquest10,Aelrynth,,,Pick up Olthoi Carapace,,TRUE,72000,-1,, +invokercomplete,Aelrynth,,,Player has received the Invoker and cannot make it again.,,FALSE,0,1,, +invokingauntanuacomplete,Aelrynth,,,Players have completed the Invoker Quest and can do it again in 4 weeks for experience.,,TRUE,72000,-1,set by Aun Aulakhe, +invokingstonearwic30,Aelrynth,,,Player has turned in 30 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonearwic60,Aelrynth,,,Player has turned in 60 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonearwic90,Aelrynth,,,Player has turned in 90 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneasheronisland30,Aelrynth,,,Player has turned in 30 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneasheronisland60,Aelrynth,,,Player has turned in 60 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneasheronisland90,Aelrynth,,,Player has turned in 90 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneayan30,Aelrynth,,,Player has turned in 30 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneayan60,Aelrynth,,,Player has turned in 60 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneayan90,Aelrynth,,,Player has turned in 90 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonecandethkeep30,Aelrynth,,,Player has turned in 30 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonecandethkeep60,Aelrynth,,,Player has turned in 60 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonecandethkeep90,Aelrynth,,,Player has turned in 90 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonecolier30,Aelrynth,,,Player has turned in 30 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonecolier60,Aelrynth,,,Player has turned in 60 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonecolier90,Aelrynth,,,Player has turned in 90 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonefestival30,Aelrynth,,,Player has turned in 30 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonefestival60,Aelrynth,,,Player has turned in 60 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonefestival90,Aelrynth,,,Player has turned in 90 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneisleoftears30,Aelrynth,,,Player has turned in 30 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneisleoftears60,Aelrynth,,,Player has turned in 60 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneisleoftears90,Aelrynth,,,Player has turned in 90 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonemayoi30,Aelrynth,,,Player has turned in 30 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonemayoi60,Aelrynth,,,Player has turned in 60 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonemayoi90,Aelrynth,,,Player has turned in 90 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonemountesper30,Aelrynth,,,Player has turned in 30 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonemountesper60,Aelrynth,,,Player has turned in 60 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonemountesper90,Aelrynth,,,Player has turned in 90 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneosteth30,Aelrynth,,,Player has turned in 30 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneosteth60,Aelrynth,,,Player has turned in 60 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneosteth90,Aelrynth,,,Player has turned in 90 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonesilyun30,Aelrynth,,,Player has turned in 30 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonesilyun60,Aelrynth,,,Player has turned in 60 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonesilyun90,Aelrynth,,,Player has turned in 90 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonetoutou30,Aelrynth,,,Player has turned in 30 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonetoutou60,Aelrynth,,,Player has turned in 60 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstonetoutou90,Aelrynth,,,Player has turned in 90 Invoking Stones.,,FALSE,0,1,set by Royal Scout, +invokingstoneturnin,Aelrynth,,,Invoking Stones Turned In Bits,,TRUE,0,4095,, +invokingstoneturnincomplete,Aelrynth,,,Invoking Stones Turned In completed.,,FALSE,0,1,set by Asheron's Investigator, +ironbladecommander,Aelrynth,,,Iron Blade Commander,,TRUE,72000,-1,, +ironbladetrooperkillcount,Aelrynth,,,kill count,,TRUE,0,25,set by Lieutenant Micham, +ironbladetrooperkilltask,Aelrynth,,,kill task timer,,TRUE,72000,-1,set by Lieutenant Micham, +ironspinedchittickkills,Aelrynth,,,Iron Spined Chittick Kill Counter,,TRUE,0,50,set by Aidene, +ironspinedchitticktask,Aelrynth,,,Iron Spined Chittick Kill Task,,TRUE,72000,-1,set by Aidene, +ishaqslostkeycomplete_0511,Aelrynth,,,Returned Ishaq's Lost Key,,TRUE,72000,-1,set by Tanami Kei, +ishaqslostkeypickedupkey1204,Aelrynth,,,You've picked up Ishaq's Lost Key.,,TRUE,72000,-1,checked by Ishaq the Philosopher, +ishaqslostkeypickedupnotes1204,Aelrynth,,,You've picked up Ishaq's notes. For shame!,,TRUE,72000,-1,checked by Ishaq the Philosopher, +isinduleltkilled,Aelrynth,,,Player has killed a Lt in Spawn,,TRUE,0,-1,, +isparianarmscomplete,Aelrynth,,,Player has completed the steps to collect the IsparianArms,,TRUE,72000,-1,, +ithaencquidityingotpurified,Aelrynth,,,Purified the Ithaenc Quiddity Ingot,,TRUE,72000,-1,set by Well of Blood, +izjiqobeaten,Aelrynth,,,You've beaten the Temple of Izji Qo!,,FALSE,0,1,set by Guardian, +izjiqocomplete,Aelrynth,,,You've received a reward for the Temple of Izji Qo.,,TRUE,72000,-1,"set by Scroll of The Endless Well, Scroll of The Golden Wind, Scroll of The Soothing Wind", +jacobsaxepickup,Aelrynth,,,Picked Up Jacob's Axe,,TRUE,72000,-1,, +jademedalliondepths_pickup,Aelrynth,,,Player has picked up the Jade Medallion Depths,,TRUE,72000,-1,, +jambiyaabmimpickup,Aelrynth,,,Ma'yad ibn Ibsar Quest,,TRUE,72000,-1,, +jawaqheadwait,Aelrynth,,,Cooldown for Jawaq Head Turn In,,TRUE,72000,-1,set by Jawaq ibn Janath, +jestercandopart2,Aelrynth,,,quest timer,,FALSE,0,1,set by Laylana, +jesterfocuseswait,Aelrynth,,,Turned in Empowered Knath Core,,TRUE,72000,-1,set by Jester, +jesterfree0308,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Jester, +jestermarbleturnin,Aelrynth,,,Handed in Jesters Marbles,,FALSE,0,1,set by Jester, +jestermarkercomplete,Aelrynth,,,Handed in Jester Marker,,FALSE,0,1,set by Jester, +jesterpart1started,Aelrynth,,,quest timer,,FALSE,0,1,set by Laylana, +jesterpart1wait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Laylana, +jesterreachedcell,Aelrynth,,,quest timer,,FALSE,0,1,set by Jester's Cell, +jesterreachedhallway,Aelrynth,,,quest timer,,FALSE,0,1,set by Jester Checkpoint, +jesterrepeatrun0308,Aelrynth,,,quest timer,,FALSE,0,1,set by Jailer, +jittekraulilesser,Aelrynth,,,Lesser Jitte of Mi Krau-Li,,TRUE,72000,-1,, +jondorturnin,Aelrynth,,,Player has turned one or more faction books to Jondor,,TRUE,0,7,, +jondorturninwait,Aelrynth,,,Cooldown for Jondor Book Set Turn In,,TRUE,72000,-1,set by Jondor Torgren, +josefkeygiven,Aelrynth,,,Player has received Gaerlan's Key from Josef,,TRUE,72000,-1,set by Josef, +journalhigharchonkraest,Aelrynth,,,Pickup Flag for Journal of Kraest,,TRUE,72000,-1,, +journalibrexipickedup,Aelrynth,,,Picked up Ibrexi's journal.,,TRUE,72000,-1,, +journalixirpickedup,Aelrynth,,,Picked up Ixir's journal.,,TRUE,72000,-1,, +journaljexkipickedup,Aelrynth,,,Picked up Jexkii's journal.,,TRUE,72000,-1,, +journalkixktipickedup,Aelrynth,,,Picked up Kixkti's journal.,,TRUE,72000,-1,, +journalnoteturninwait,Aelrynth,,,Mortified Soldier Journal and Note Turn In,,TRUE,72000,-1,set by Mortified Soldier, +journalofasoldierpickup,Aelrynth,,,Journal of a Soldier pickup timer,,TRUE,72000,-1,, +jtmcanusecage_0613,Aelrynth,,,quest timer,,FALSE,0,1,set by Virindi Delegate, +jtmcompleted_0613,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Virindi Delegate, +jtmkeypickup_0613,Aelrynth,,,quest timer,,TRUE,72000,-1,checked by Virindi Delegate, +jtmstarted_0613,Aelrynth,,,quest timer,,FALSE,0,1,set by Virindi Delegate, +jungleorchidpickup,Aelrynth,,,Picked up a Jungle Orchid,,TRUE,72000,-1,, +kaosfeedbag,Aelrynth,,,Picked Up Farmer Kao's Feed Bag,,TRUE,72000,-1,, +kaosgardengloves,Aelrynth,,,Picked Up Farmer Kao's Gardening Gloves,,TRUE,72000,-1,, +kaosshovel,Aelrynth,,,Picked Up Farmer Kao's Shovel,,TRUE,72000,-1,, +kaoswaterbucket,Aelrynth,,,Picked Up Farmer Kao's Water Bucket,,TRUE,72000,-1,, +keepbannerclaimedwait,Aelrynth,,,Cooldown for Society Keep Banner claiming,,TRUE,300,-1,"set by Celestial Hand Banner of the Courtyard, Celestial Hand Banner of the Spire, Celestial Hand Banner of the Tower and 15 more", +keepbuffingarraywait,Aelrynth,,,Cooldown for Society Keep Buffing Array usage,,TRUE,30,-1,"set by Celestial Hand Buffing Array, Eldrytch Web Buffing Array, Radiant Blood Buffing Array", +keeprewardswait,Aelrynth,,,Cooldown for Keep PK reward,,TRUE,72000,-1,"set by Mitsuhara Kamekeka, Mitsuhara Ryuhi, Mitsuhara Takeo", +keepsupply,Aelrynth,,,Timer for Keep supply bonus reward,,TRUE,3600,-1,"set by Freebooter Celhan Stopgap!, Freebooter Eldweb Stopgap!, Freebooter Radblo Stopgap! and 3 more", +keepsupplywait,Aelrynth,,,Cooldown for Keep supply bonus reward,,TRUE,72000,-1,"set by Freebooter Celhan Stopgap!, Freebooter Eldweb Stopgap!, Freebooter Radblo Stopgap! and 3 more", +keerikbeaten,Aelrynth,,,You've beaten Keerik.,,FALSE,0,1,checked by Guard Sorchia, +keerikcomplete,Aelrynth,,,You've completed the Keerik quest.,,TRUE,72000,-1,set by Guard Sorchia, +keerikkilled,Aelrynth,,,You killed Keerik.,,FALSE,0,1,set by Guard Sorchia, +kerthumptheeartakerbet,Aelrynth,,,Player bet on Kerthump the EarTaker,,FALSE,0,1,set by Kerthump the Ear Taker, +keyaerfalle,Aelrynth,,,Aerfalle's Chest Key,,TRUE,72000,-1,, +keyaerfalleuber,Aelrynth,,,Aerfalle's Ornate Chest Key,,TRUE,72000,-1,, +keycontactreceived,Aelrynth,,,You have taken the key off the Renegade Lugian's corpse.,,TRUE,72000,-1,set by Corpse of Lugian Courier, +keyhammerempyreanacidpickup,Aelrynth,,,Player has picked up the Acid hammer.,,TRUE,72000,-1,, +keyhammerempyreanfirepickup,Aelrynth,,,Player has picked up the Fire hammer.,,TRUE,72000,-1,, +keyhammerempyreanicepickup,Aelrynth,,,Player has picked up the Ice hammer.,,TRUE,72000,-1,, +keyhammerempyreanlightningpickup,Aelrynth,,,Player has picked up the Lightning hammer.,,TRUE,72000,-1,, +keyjalehtaken,Aelrynth,,,You got the key to open Jaleh's Chest,,TRUE,72000,-1,, +keyknorrdefenderpickedup,Aelrynth,,,Picked up Defender Key,,TRUE,72000,-1,, +keyknorrelderpickedup,Aelrynth,,,Picked up Elder Key,,TRUE,72000,-1,, +keyknorrsentinelpickedup,Aelrynth,,,Picked up Sentinel Key,,TRUE,72000,-1,, +keynoir1,Aelrynth,,,You've received the prison key.,,TRUE,5400,-1,set by Key Ring, +keyoverlord,Aelrynth,,,Tumerok Overlord's Key,,TRUE,72000,-1,, +keyrewardpickedup,Aelrynth,,,This quest flag is obsolete.,,TRUE,0,3,, +kidnapprincesscomplete_0410,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Sir Draithon, +kidnapprincessstarted_0410,Aelrynth,,,quest timer,,FALSE,0,1,set by Sir Draithon, +kieriencorepickup,Aelrynth,quest timer,,quest timer,quest timer,TRUE,72000,-1,, +kilifzefirkillcount,Aelrynth,,,Kilif Zefir Kill Counter,,TRUE,0,35,, +kilifzefirkilltask,Aelrynth,,,Kilif Zefir Kill Task,,TRUE,72000,-1,, +killagurgcritterskilled,Aelrynth,,,Player has killed a creature found in Killagurg,,TRUE,0,-1,set by Killagurg Event Watcher, +killboshbosh_start,Aelrynth,,,Player has started Killing Bosh Bosh,,FALSE,0,1,set by Kuuru, +killboshbosh_wait,Aelrynth,,,Player wait timer for Killing Bosh Bosh,,TRUE,72000,-1,set by Kuuru, +killedmenacet,Aelrynth,,,Writ Nov Quest 1,,TRUE,57600,-1,"set by Dranith Menacet, Minion Leader", +killerphyntoswaspkillcount,Aelrynth,,,Killer Phyntos Wasp Kill Counter,,TRUE,0,50,, +killerphyntoswaspkilltask,Aelrynth,,,Killer Phyntos Wasp Kill Task,,TRUE,72000,-1,, +killphyntosqueenpickup1109,Aelrynth,,,Pickup timer for Phyntos Queen Abdomen,,TRUE,72000,-1,, +killtask-blightspirit,Aelrynth,,,Counter for Blight Spirit Kill Task,,TRUE,0,8,set by Candrus Steady-Hand, +killtask-blightspiritwait,Aelrynth,,,Cooldown for Blight Spirit Kill Task,,TRUE,72000,-1,set by Candrus Steady-Hand, +killtask-harvestreaper,Aelrynth,,,Harvest Reaper Kill Task,,TRUE,0,10,set by Majestic Pumpkin, +killtask-harvestreapercompletions,Aelrynth,,,Harvest Reaper Kill Task Completions,,TRUE,0,-1,set by Majestic Pumpkin, +killtask-pumpkinlord,Aelrynth,,,Pumpkin Lord Kill Task,,TRUE,0,3,set by Majestic Pumpkin, +killtaskaltereddrudges_0507,Aelrynth,,,Altered Drudges Kill Task,,TRUE,0,40,set by Jarvis Hammerstone, +killtaskaltereddrudgeswait_0507,Aelrynth,,,Altered Drudges Kill Task Wait Timer,,TRUE,72000,-1,set by Jarvis Hammerstone, +killtaskapostatevirindihigh_0710,Aelrynth,,,High level kill task for The Empyrean Portalspace Stabilizer Quest.,,TRUE,0,30,set by Emissary of Asheron, +killtaskapostatevirindilow_0710,Aelrynth,,,Low level kill task for The Empyrean Portalspace Stabilizer Quest.,,TRUE,0,30,set by Emissary of Asheron, +killtaskapostatevirindimid_0710,Aelrynth,,,Mid level kill task for The Empyrean Portalspace Stabilizer Quest.,,TRUE,0,30,set by Emissary of Asheron, +killtaskaugmenteddrudges_0507,Aelrynth,,,Augmented Drudges Kill Task,,TRUE,0,40,set by Jarvis Hammerstone, +killtaskaugmenteddrudgeswait_0507,Aelrynth,,,Augmented Drudges Kill Task Wait Timer,,TRUE,72000,-1,set by Jarvis Hammerstone, +killtaskbanishedcreature_0609,Aelrynth,,,Banished Creature Kill Task,,TRUE,0,10,set by Belinda du Loc, +killtaskbanishedcreaturewait_0609,Aelrynth,,,Banished Creature Kill Task Wait Timer,,TRUE,72000,-1,set by Belinda du Loc, +killtaskbloodshreth,Aelrynth,,,Blood Shreth Kill Task,,TRUE,0,10,set by San Ming, +killtaskbloodshrethwait,Aelrynth,,,Blood Shreth Kill Task Timer,,TRUE,72000,-1,set by San Ming, +killtaskcorruptedgravestones_1311,Aelrynth,,,Corrupted Gravestones Kill Task,,TRUE,0,6,set by Slubbley, +killtaskcorruptedgravestoneswait_1311,Aelrynth,,,Corrupted Gravestones Kill Task,,TRUE,72000,-1,set by Slubbley, +killtaskcrystallinewisps10109,Aelrynth,,,Crystalline Wisp Kill Task,,TRUE,0,100,set by Oorjit, +killtaskcrystallinewisps10109wait,Aelrynth,,,Crystalline Wisp Kill Task,,TRUE,72000,-1,set by Oorjit, +killtaskdesertareaarmoredillo_0511,Aelrynth,,,Armoredillo Hunting: Lost City of Neftet,,TRUE,0,30,set by Dame Tularin, +killtaskdesertareaarmoredillowait_0511,Aelrynth,,,Armoredillo Hunting: Lost City of Neftet,,TRUE,72000,-1,set by Dame Tularin, +killtaskdesertareagolem_0511,Aelrynth,,,Golem Hunting Lost City of Neftet,,TRUE,0,15,set by Sir Ibreh bin Kassim, +killtaskdesertareagolemwait_0511,Aelrynth,,,Golem Hunting Lost City of Neftet,,TRUE,72000,-1,set by Sir Ibreh bin Kassim, +killtaskdesertareamumiyah_0511,Aelrynth,,,Mumiyah Hunting Lost City of Neftet,,TRUE,0,30,set by Sir Adarl, +killtaskdesertareamumiyahwait_0511,Aelrynth,,,Mumiyah Hunting Lost City of Neftet,,TRUE,72000,-1,set by Sir Adarl, +killtaskdesertareareedshark_0511,Aelrynth,,,Reedshark Hunting Lost City of Neftet,,TRUE,0,30,set by Sir Hassim bin Tamarek, +killtaskdesertareareedsharkwait_0511,Aelrynth,,,Reedshark Hunting: Lost City of Neftet,,TRUE,72000,-1,set by Sir Hassim bin Tamarek, +killtaskdrudgelurkers_0507,Aelrynth,,,Drudge Lurker Kill Task,,TRUE,0,100,set by Jarvis Hammerstone, +killtaskdrudgelurkerswait_0507,Aelrynth,,,Drudge Lurkers Kill Task Wait Timer,,TRUE,72000,-1,set by Jarvis Hammerstone, +killtaskdrudgeraveners_0507,Aelrynth,,,Drudge Raveners Kill Task,,TRUE,0,50,set by Jarvis Hammerstone, +killtaskdrudgeravenerswait_0507,Aelrynth,,,Drudge Raveners Kill Task Wait Timer,,TRUE,72000,-1,set by Jarvis Hammerstone, +killtaskdrudgestalkers_0507,Aelrynth,,,Drudge Stalkers Kill Task,,TRUE,0,100,set by Jarvis Hammerstone, +killtaskdrudgestalkerswait_0507,Aelrynth,,,Drudge Stalkers Kill Task Wait Timer,,TRUE,72000,-1,set by Jarvis Hammerstone, +killtaskelemental_0609,Aelrynth,,,Elemental Kill Task,,TRUE,0,25,set by Zahir, +killtaskelementalwait_0609,Aelrynth,,,Elemental Kill Task Wait Timer,,TRUE,72000,-1,set by Zahir, +killtaskengineer1,Aelrynth,,,kill counter,,FALSE,0,1,set by Isin Dule, +killtaskengineer1completed,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +killtaskengineer2,Aelrynth,,,kill counter,,FALSE,0,1,set by Isin Dule, +killtaskengineer2completed,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +killtaskengineer3,Aelrynth,,,kill counter,,FALSE,0,1,set by Isin Dule, +killtaskengineer3completed,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +killtaskengineer4,Aelrynth,,,kill counter,,FALSE,0,1,set by Isin Dule, +killtaskengineer4completed,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +killtaskenragedshadows,Aelrynth,,,kill counter,,TRUE,0,20,set by Corrupted Crystal of Rage, +killtaskenragedshadowsstarted,Aelrynth,,,quest timer,,FALSE,0,1,set by Corrupted Crystal of Rage, +killtaskenragedshadowswait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Corrupted Crystal of Rage, +killtaskfallencreature_0609,Aelrynth,,,Fallen Creature Kill Task,,TRUE,0,10,set by Belinda du Loc, +killtaskfallencreaturewait_0609,Aelrynth,,,Fallen Creature Kill Task Wait Timer,,TRUE,72000,-1,set by Belinda du Loc, +killtaskgolemsamurai0812,Aelrynth,,,KillTaskGolemSamurai0812,,TRUE,0,5,set by Lieutenant Aurin, +killtaskgolemsamuraicompleted0812,Aelrynth,,,KillTaskGolemSamuraiCompleted0812,,TRUE,72000,-1,set by Lieutenant Aurin, +killtaskgraveyardgraverat_1107,Aelrynth,,,Grave Rat Kill Task,,TRUE,0,100,set by Lo Shoen, +killtaskgraveyardgraveratwait_1107,Aelrynth,,,Grave Rat Kill Task,,TRUE,72000,-1,set by Lo Shoen, +killtaskgraveyardskeleton_1309,Aelrynth,,,Graveyard Skeleton Kill Task,,TRUE,0,30,set by Yoite, +killtaskgraveyardskeletonwait_1309,Aelrynth,,,Graveyard Skeleton Kill Task,,TRUE,72000,-1,set by Yoite, +killtaskgraveyardspirit_1309,Aelrynth,,,Graveyard Spirit Kill Task,,TRUE,0,10,set by Aethelswith, +killtaskgraveyardspiritwait_1309,Aelrynth,,,Graveyard Spirit Kill Task,,TRUE,72000,-1,set by Aethelswith, +killtaskgraveyardwight_1309,Aelrynth,,,Graveyard Wight Kill Task,,TRUE,0,30,set by Gadi, +killtaskgraveyardwightwait_1309,Aelrynth,,,Graveyard Wight Kill Task,,TRUE,72000,-1,set by Gadi, +killtaskgraveyardwisp_1309,Aelrynth,,,Graveyard Wisp Kill Task,,TRUE,0,5,set by Renata, +killtaskgraveyardwispwait_1309,Aelrynth,,,Graveyard Wisp Kill Task,,TRUE,72000,-1,set by Renata, +killtaskguardianstatue,Aelrynth,,,quest timer,,TRUE,0,10,set by Shade of Fordroth, +killtaskguardianstatuewait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Shade of Fordroth, +killtaskguroghenchman1110,Aelrynth,,,Gurog Henchman Kill Counter,,TRUE,0,20,"set by Gregoria, Gurog Destroyer", +killtaskguroghenchmancompleted1110,Aelrynth,,,Gurog Henchmen Kill Task,,TRUE,72000,-1,"set by Gregoria, Gurog Destroyer", +killtaskgurogminion1110,Aelrynth,,,Gurog Minion Kill Counter,,TRUE,0,20,"set by Gregoria, Gurog Destroyer", +killtaskgurogminioncompleted1110,Aelrynth,,,Gurog Minion Kill Task,,TRUE,72000,-1,"set by Gregoria, Gurog Destroyer", +killtaskgurogsoldier1110,Aelrynth,,,Gurog Soldier Kill Counter,,TRUE,0,20,"set by Gregoria, Gurog Destroyer", +killtaskgurogsoldiercompleted1110,Aelrynth,,,Gurog Soldier Kill Task,,TRUE,72000,-1,"set by Gregoria, Gurog Destroyer", +killtaskintensewispscorinca,Aelrynth,,,Intense Crystalline Wisp Kill Task Corroding and Incalescent,,TRUE,0,25,set by Shade of Ja'qu, +killtaskintensewispscorincawait,Aelrynth,,,Crystalline Intense Wisp Kill Task Corroding and Incalescent,,FALSE,0,1,set by Lever, +killtaskintensewispsshivol,Aelrynth,,,Intense Crystalline Wisp Kill Task Shivering and Voltaic,,TRUE,0,25,set by Shade of Ja'qu, +killtaskintensewispsshivolwait,Aelrynth,,,Crystalline Intense Wisp Kill Task Shivering and Voltaic,,FALSE,0,1,set by Lever, +killtaskkilifzefir,Aelrynth,,,Kilif Zefir Kill Task,,TRUE,0,35,set by Hadiya bint Anan, +killtaskkilifzefirwait,Aelrynth,,,Kilif Zefir Kill Task Timer,,TRUE,72000,-1,set by Hadiya bint Anan, +killtaskmagshuthmoarsman,Aelrynth,,,Magshuth Moarsman Kill Task,,TRUE,0,20,"set by Denada Morningthaw, Elesandra Trembol, Jentha Strongarm", +killtaskmagshuthmoarsmanwait,Aelrynth,,,Magshuth Moarsman Kill Task,,TRUE,72000,-1,"set by Denada Morningthaw, Elesandra Trembol, Jentha Strongarm", +killtaskmcgreggortentacle_0908,Aelrynth,,,Tentacle of Tthuun Kill Task for Valerian McGreggor,,TRUE,0,50,set by Valerian McGreggor, +killtaskmcgreggortentaclewait_0908,Aelrynth,,,Tentacle of Tthuun Kill Task for Valerian McGreggor wait timer,,TRUE,72000,-1,set by Valerian McGreggor, +killtaskmghabhorrenteater,Aelrynth,,,Monthly Game Hunter Kill Task,,TRUE,0,10,"set by Rand, Game Hunter", +killtaskmghharvestreaper,Aelrynth,,,Monthly Game Hunter Kill Task,,TRUE,0,10,"set by Rand, Game Hunter", +killtaskmghpyrechampion,Aelrynth,,,Monthly Game Hunter Kill Task,,TRUE,0,10,"set by Rand, Game Hunter", +killtaskmghremoran,Aelrynth,,,Monthly Game Hunter Kill Task,,TRUE,0,10,"set by Rand, Game Hunter", +killtaskmghtumerok,Aelrynth,,,Monthly Game Hunter Kill Task,,TRUE,0,10,"set by Rand, Game Hunter", +killtaskmghundeadsailor,Aelrynth,,,Monthly Game Hunter Kill Task,,TRUE,0,10,"set by Rand, Game Hunter", +killtaskmghvoraciouseater,Aelrynth,,,Monthly Game Hunter Kill Task,,TRUE,0,10,"set by Rand, Game Hunter", +killtaskmghvscarecrows,Aelrynth,,,Monthly Game Hunter Kill Task,,TRUE,0,10,"set by Rand, Game Hunter", +killtaskmghwasp,Aelrynth,,,Monthly Game Hunter Kill Task,,TRUE,0,10,"set by Rand, Game Hunter", +killtaskmghwightcaptain,Aelrynth,,,Monthly Game Hunter Kill Task,,TRUE,0,10,"set by Rand, Game Hunter", +killtaskmoarsmanhighprieststarted,Aelrynth,,,KillTaskMoarsmanHighPriestStarted,,FALSE,0,1,"set by Kaymor ibn Dumandi, Lunbal Dolicci, Milos ibn Ashud", +killtaskmoarsmanhighpriestwait,Aelrynth,,,KillTaskMoarsmanHighPriestWait,,TRUE,72000,-1,"set by Kaymor ibn Dumandi, Lunbal Dolicci, Milos ibn Ashud", +killtaskmoguthmoarsman,Aelrynth,,,Moguth Moarsman Kill Task,,TRUE,0,60,"set by Berrando Piatelli, Marconi di Bellenesse, Ricaldo di Alduressa", +killtaskmoguthmoarsmanwait,Aelrynth,,,Moguth Moarsman Kill Task,,TRUE,72000,-1,"set by Berrando Piatelli, Marconi di Bellenesse, Ricaldo di Alduressa", +killtaskmosswartcynic_1121,Aelrynth,,,Holly Jolly Helper Kill Task,,TRUE,0,15,set by Osdryd, +killtaskmosswartcynicwait_1121,Aelrynth,,,Holly Jolly Helper Kill Task Wait Timer,,TRUE,72000,-1,set by Osdryd, +killtaskmosswarttownsfolk_0507,Aelrynth,,,Mosswart Townsfolk Kill Task,,TRUE,0,40,set by Corporal Massein, +killtaskmosswarttownsfolkwait_0507,Aelrynth,,,Mosswart Townsfolk Kill Task Wait Timer,,TRUE,72000,-1,set by Corporal Massein, +killtaskolthoidrone,Aelrynth,,,Olthoi Drone Kill Task,,TRUE,0,20,set by Olthoi Hunter, +killtaskolthoidronewait,Aelrynth,,,Olthoi Drone Kill Task,,TRUE,72000,-1,set by Olthoi Hunter, +killtaskolthoinettler,Aelrynth,,,Olthoi Nettler Kill Task,,TRUE,0,10,set by Olthoi Hunter, +killtaskolthoinettlerwait,Aelrynth,,,Olthoi Nettler Kill Task,,TRUE,72000,-1,set by Olthoi Hunter, +killtaskolthoinymph,Aelrynth,,,Olthoi Nymph Kill Task,,TRUE,0,20,set by Olthoi Hunter, +killtaskolthoinymphwait,Aelrynth,,,Olthoi Nymph Kill Task,,TRUE,72000,-1,set by Olthoi Hunter, +killtaskphyntoskiller1109,Aelrynth,,,Phyntos Wasp Kill Task,,TRUE,0,50,"set by Jonathan, Khanldun, Mik", +killtaskphyntoskillerwait1109,Aelrynth,,,Phyntos Wasp Kill Task,,TRUE,72000,-1,"set by Jonathan, Khanldun, Mik", +killtaskphyntoslarvae1109,Aelrynth,,,Phyntos Larvae Kill Task,,TRUE,0,20,"set by Alderic, Ghali al-Fariq, Haruki", +killtaskphyntoslarvaewait1109,Aelrynth,,,Phyntos Larvae Kill Task,,TRUE,72000,-1,"set by Alderic, Ghali al-Fariq, Haruki", +killtaskputridmoar_0307,Aelrynth,,,Putrid Moar Kill Task,,TRUE,0,25,set by Tibik, +killtaskputridmoarstarted_0307,Aelrynth,,,Putrid Moar Kill Task Started,,FALSE,0,1,set by Tibik, +killtaskputridmoarwait_0307,Aelrynth,,,Putrid Moar Kill Task Wait Timer,,TRUE,72000,-1,set by Tibik, +killtaskraregame_0609,Aelrynth,,,Rare Game Kill Task,,TRUE,0,50,set by Belinda du Loc, +killtaskraregamewait_0609,Aelrynth,,,Rare Game Kill Task Wait Timer,,TRUE,72000,-1,set by Belinda du Loc, +killtaskrifttenebrous0907,Aelrynth,,,Tenebrous Rift Kill Task Counter,,TRUE,0,350,set by Solange, +killtaskrifttenebrouswait0907,Aelrynth,,,Tenebrous Rift Kill Task,,TRUE,72000,-1,set by Solange, +killtaskriftumbral0907,Aelrynth,,,Umbral Rift Kill Task Counter,,TRUE,0,30,set by Solange, +killtaskriftumbralwait0907,Aelrynth,Umbral Rift Kill Task,,Umbral Rift Kill Task,Umbral Rift Kill Task,TRUE,72000,-1,set by Solange, +killtaskruschk_0301,Aelrynth,,,Ruschk Kill Task,,TRUE,0,30,set by Commander Rylane di Cinghalle, +killtaskrynthidcrystals,Aelrynth,,,kill counter,,TRUE,0,6,set by Lohrn, +killtaskrynthidcrystalswait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Lohrn, +killtaskrynthidminions0813,Aelrynth,,,kill counter,,TRUE,0,25,set by Marcus, +killtaskrynthidminionscompleted0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Marcus, +killtaskrynthidragercompleted0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Ranulf, +killtaskrynthidragers0813,Aelrynth,,,kill counter,,TRUE,0,15,set by Ranulf, +killtaskrynthidrares0813,Aelrynth,,,kill counter,,FALSE,0,1,set by Hernd, +killtaskrynthidrarescompleted0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Hernd, +killtaskrynthidriftcompleted0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Rhys, +killtaskrynthidrifts0813,Aelrynth,,,kill counter,,TRUE,0,10,set by Rhys, +killtaskrynthidslayercompleted0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Sylvanus, +killtaskrynthidslayers0813,Aelrynth,,,kill counter,,TRUE,0,15,set by Sylvanus, +killtaskrynthidsorcerercompleted0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Wido, +killtaskrynthidsorcerers0813,Aelrynth,,,kill counter,,TRUE,0,15,set by Wido, +killtaskrynthidwisps0813,Aelrynth,,,kill counter,,TRUE,0,3,set by Tillahan, +killtaskrynthidwispscompleted0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Tillahan, +killtasksawatobandit,Aelrynth,,,kill counter,,TRUE,0,15,set by Trap Door, +killtaskshadowvortex,Aelrynth,,,kill counter,,TRUE,0,3,set by Isin Dule, +killtaskshadowvortexcompleted,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +killtaskshoguthmoarsman,Aelrynth,,,Shoguth Moarsman Kill Task,,TRUE,0,40,"set by Dorn Bowspeaker, Gavin Hammerstone, Kylos Hunterson", +killtaskshoguthmoarsmanwait,Aelrynth,,,Shoguth Moarsman Kill Task,,TRUE,72000,-1,"set by Dorn Bowspeaker, Gavin Hammerstone, Kylos Hunterson", +killtasksmallfledglingmukkir0806,Aelrynth,,,Small Fledgling Mukkir Kill Counter,,TRUE,0,15,set by Royal Guard, +killtasksmallfledglingmukkircompleted0806,Aelrynth,,,Small Fledgling Mukkir Kill Task Timer,,TRUE,72000,-1,set by Royal Guard, +killtasksnowtusker0111,Aelrynth,,,Player killed x/20 Snow Tuskers.,,TRUE,0,20,, +killtasksoldier,Aelrynth,,,kill counter,,TRUE,0,15,"set by Black Ferah, Shadow Captain", +killtasksoldiercompleted,Aelrynth,,,quest timer,,FALSE,0,1,set by Shadow Captain, +killtaskspectralarchers0812,Aelrynth,,,KillTaskSpectralArchers0812,,TRUE,0,15,set by Sergeant Trebuus, +killtaskspectralarcherscompleted0812,Aelrynth,,,KillTaskSpectralArchersCompleted0812,,TRUE,72000,-1,set by Sergeant Trebuus, +killtaskspectralbloodmages0812,Aelrynth,,,KillTaskSpectralBloodMages0812,,TRUE,0,5,set by Lord Eorlinde, +killtaskspectralbloodmagescompleted0812,Aelrynth,,,KillTaskSpectralBloodmagesCompleted0812,,TRUE,72000,-1,set by Lord Eorlinde, +killtaskspectralbushi0812,Aelrynth,,,KillTaskSpectralBushi0812,,TRUE,0,10,set by Corporal Irashi, +killtaskspectralbushicompleted0812,Aelrynth,,,KillTaskSpectralBushiCompleted0812,,TRUE,72000,-1,set by Corporal Irashi, +killtaskspectralclawsblades0812,Aelrynth,,,KillTaskSpectralClawsBlades0812,,TRUE,0,10,set by Griffon, +killtaskspectralclawsbladescompleted0812,Aelrynth,,,KillTaskSpectralClawsBladesCompleted0812,,TRUE,72000,-1,set by Griffon, +killtaskspectralminions0812,Aelrynth,,,KillTaskSpectralMinions0812,,TRUE,0,15,set by Aun Kirtal, +killtaskspectralminionscompleted0812,Aelrynth,,,KillTaskSpectralMinionsCompleted0812,,TRUE,72000,-1,set by Aun Kirtal, +killtaskspectralninjas0812,Aelrynth,,,KillTaskSpectralNinjas0812,,TRUE,0,5,set by Hanamoto Aki'ko, +killtaskspectralninjascompleted0812,Aelrynth,,,KillTaskSpectralNinjasCompleted0812,,TRUE,72000,-1,set by Hanamoto Aki'ko, +killtaskspectralsamurai0812,Aelrynth,,,KillTaskSpectralSamurai0812,,TRUE,0,10,set by Lieutenant Takamaki, +killtaskspectralsamuraicompleted0812,Aelrynth,,,KillTaskSpectralSamuraiCompleted0812,,TRUE,72000,-1,set by Lieutenant Takamaki, +killtasktentacleoftthuun_0908,Aelrynth,,,Tentacle of Tthuun Kill Task,,TRUE,0,50,set by Tamara du Cinghalle, +killtasktentacleoftthuunwait_0908,Aelrynth,,,Tentacle of Tthuun Kill Task wait timer,,TRUE,72000,-1,set by Tamara du Cinghalle, +killtaskthreeeyedsnowman,Aelrynth,,,Three Eyed Snowman Kill Task,,TRUE,0,5,set by Blind Snowman, +killtaskthreeeyedsnowmanwait,Aelrynth,,,Three Eyed Snowman Kill Task Wait timer,,TRUE,72000,-1,set by Blind Snowman, +killtasktorgashstasks_0301,Aelrynth,,,Torgashs Tasks,,TRUE,0,30,set by Torgash, +killtasktormentedshadows,Aelrynth,,,kill counter,,TRUE,0,20,set by Corrupted Crystal of Torments, +killtasktormentedshadowsstarted,Aelrynth,,,quest timer,,FALSE,0,1,set by Corrupted Crystal of Torments, +killtasktormentedshadowswait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Corrupted Crystal of Torments, +killtasktoutoublockade,Aelrynth,,,kill counter,,TRUE,0,10,set by Isin Dule, +killtasktoutoublockadecompleted,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +killtasktoutouflyers0812,Aelrynth,,,Shadow Flyer Kill Task,,TRUE,0,15,set by Umbral Guard, +killtasktoutouflyerscompleted0812,Aelrynth,,,Shadow Flyer Kill Task,,TRUE,72000,-1,set by Umbral Guard, +killtasktoutougrievvers0812,Aelrynth,,,Grievver Shredder Kill Task,,TRUE,0,15,set by Royal Guard, +killtasktoutougrievverscompleted0812,Aelrynth,,,Grievver Shredder Kill Task,,TRUE,72000,-1,set by Royal Guard, +killtasktoutouknights0812,Aelrynth,,,Void Lord Kill Task,,TRUE,0,15,set by Royal Guard, +killtasktoutouknightscompleted0812,Aelrynth,,,Void Lord Kill Task,,TRUE,72000,-1,set by Royal Guard, +killtasktoutoumarguls0812,Aelrynth,,,Devourer Margul Kill Task,,TRUE,0,15,set by Umbral Guard, +killtasktoutoumargulscompleted0812,Aelrynth,,,Devourer Margul Kill Task,,TRUE,72000,-1,set by Umbral Guard, +killtasktoutoupillars0812,Aelrynth,,,Shadowy Pillar Kill Task,,TRUE,0,4,set by Royal Guard, +killtasktoutoupillarscompleted0812,Aelrynth,,,Shadowy Pillar Kill Task,,TRUE,72000,-1,set by Royal Guard, +killtasktoutoushadows0812,Aelrynth,,,Shadow Kill Task,,TRUE,0,25,set by Royal Guard, +killtasktoutoushadowscompleted0812,Aelrynth,,,Shadow Kill Task,,TRUE,72000,-1,set by Royal Guard, +killtasktoutoutownsfolk,Aelrynth,,,kill counter,,TRUE,0,5,set by Isin Dule, +killtasktoutoutownsfolkcompleted,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +killtasktumerokgladiator,Aelrynth,,,Tumerok Gladiator Kill Task,,TRUE,0,25,set by Lieutenant Rothe, +killtasktumerokgladiatorwait,Aelrynth,,,Tumerok Gladiator Kill Task,,TRUE,72000,-1,set by Lieutenant Rothe, +killtaskviridiananek,Aelrynth,,,kill counter,,TRUE,0,10,"set by Brellegia, Brellegia's Marker", +killtaskviridiananekwait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Brellegia, +killtaskviridianwasp,Aelrynth,,,kill counter,,TRUE,0,10,"set by Aangesilus, Aangesilus' Marker", +killtaskviridianwaspwait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Aangesilus, +killtaskviridianzefir,Aelrynth,,,kill counter,,TRUE,0,10,"set by Swift, Swift's Marker", +killtaskviridianzefirwait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Swift, +kingoolutangaenter,Aelrynth,,,Entrance to the Warrior's Lair.,,FALSE,0,1,set by Kleeoh, +kireebeaten,Aelrynth,,,You've beaten Kiree.,,FALSE,0,1,checked by Guard Fassel, +kireecomplete,Aelrynth,,,You've completed the Kiree quest.,,TRUE,72000,-1,set by Guard Fassel, +kireekilled,Aelrynth,,,You killed Kiree.,,FALSE,0,1,set by Guard Fassel, +kiviklirbeaten,Aelrynth,,,You've used the Eye.,,FALSE,0,1,set by Guardian of the Crypt, +kiviklircompleted,Aelrynth,,,You've used the Eye.,,TRUE,72000,-1,"set by Manacle of Biting Pain, Scroll of Artificant Chant, Scroll of Conjurant Chant and 4 more", +kiviklirfinished,Aelrynth,,,You've used the Eye.,,FALSE,0,1,"set by Coglock, Glogluuk, Plocagruuk", +knathandraskillcount,Aelrynth,,,K'nath An'dras Kill Counter,,TRUE,0,25,set by Nona, +knathandraskilltask,Aelrynth,,,K'nath An'dras Kill Task,,TRUE,72000,-1,set by Nona, +knifedahquest,Aelrynth,,,Retreive Nurbaha bint Dah's Knife,,TRUE,72000,-1,, +knightsofkarluncomplete,Aelrynth,,,Knights Of Karlun Complete,,FALSE,0,1,set by Grand Knight, +knightsofkarluncompletesilyun,Aelrynth,,,Knights Of Karlun Complete - Silyun,,FALSE,0,1,set by Grand Mother, +knightsstash,Aelrynth,,,Open timer for Knight's Stash Chest,,TRUE,518400,-1,, +knorrgem1,Aelrynth,,,Received Knorr Gem,,FALSE,0,1,"set by Olcris, Nuhmudira's Student", +knorrquiddityseedquestrepeat,Aelrynth,,,Flag for Knorr Quiddity Seed Quest initial turn in,,FALSE,0,1,set by Emissary of Asheron, +knorrquiddityseedwait,Aelrynth,,,Completed Knorr Quiddity Seed Quest,,TRUE,72000,-1,set by Asheron, +knorrquidityingotpurified,Aelrynth,,,Purified the Knorr Quiddity Ingot,,TRUE,72000,-1,set by Pool of Water, +knorrwait,Aelrynth,,,Waiting time before returning to Knorr,,TRUE,72000,-1,"set by Olcris, Nuhmudira's Student", +koihoataifragment_pickup,Aelrynth,,,Player has picked up the Koihoatai Fragment,,TRUE,72000,-1,, +korgluukofburbet,Aelrynth,,,Player bet on Korgluuk of Bur,,FALSE,0,1,set by Korgluuk of Bur, +kothmoxstaffgiven,Aelrynth,,,Kothmox Staff Given to lord test statue,,FALSE,0,1,set by Statue, +krankcollectionarmoredillo,Aelrynth,,,You have been given a quest to collect Armoredillo hides by Captain K'rank.,,FALSE,0,1,set by Captain K'rank, +krankcollectiongolem,Aelrynth,,,You have been given a quest to collect Golem hearts by Captain K'rank.,,FALSE,0,1,set by Captain K'rank, +krankcollectionsclavus,Aelrynth,,,You have been given a quest to collect Sclavus parts by Captain K'rank.,,FALSE,0,1,set by Captain K'rank, +krankdeliverydryreach,Aelrynth,,,You have been given a quest to deliver something to Dryreach by Captain K'rank.,,FALSE,0,1,set by Captain K'rank, +krankdeliverymacniall,Aelrynth,,,You have been given a quest to deliver something to MacNiall by Captain K'rank.,,FALSE,0,1,set by Captain K'rank, +krankdeliverystonehold,Aelrynth,,,You have been given a quest to deliver something to Stonehold by Captain K'rank.,,FALSE,0,1,set by Captain K'rank, +krankdeliverywaijhou,Aelrynth,,,You have been given a quest to deliver something to WaiJhou by Captain K'rank.,,FALSE,0,1,set by Captain K'rank, +krankmorgluuk,Aelrynth,,,You have spoken to Krank about that Burun named Morgluuk.,,FALSE,0,1,set by Captain K'rank, +krankquest,Aelrynth,,,Captain k'rank has given you a quest.,,TRUE,72000,-1,set by Captain K'rank, +krystnpcmoving,Aelrynth,,,Kryst NPC is in motion,,TRUE,10,1,"set by Aluvian Spearman, Gharu'ndim War Mage, Gharu'ndim Warrior and 1 more", +labportalgem120,Aelrynth,,,Player has turned in Monouga Laboratory Portal Attunement Gem to 120+ Bell,,FALSE,0,1,set by Bell, +labportalgem150,Aelrynth,,,Player has turned in Monouga Laboratory Portal Attunement Gem to 150+ Bell,,FALSE,0,1,set by Bell, +labportalgem80,Aelrynth,,,Player has turned in Monouga Laboratory Portal Attunement Gem to 80+ Bell,,FALSE,0,1,set by Bell, +labyrinthcomplete,Aelrynth,,,This quest flag is obsolete.,,FALSE,0,1,, +ladydaneelorecollectioncompleted_0612,Aelrynth,,,Player has completed the collection of Ore for Lady Dan'eel,,TRUE,72000,-1,set by Lady Dan'eel Trianna, +ladydaneelorecollectionstarted_0612,Aelrynth,,,Player has started the collection of Ore for Lady Dan'eel,,FALSE,0,1,set by Lady Dan'eel Trianna, +ladykiaraorecollectioncompleted_0612,Aelrynth,,,Player has completed the collection of Ore for Lady Kiara,,TRUE,72000,-1,set by Lady Kiara Trianna, +ladykiaraorecollectionstarted_0612,Aelrynth,,,Player has started the collection of Ore for Lady Kiara,,FALSE,0,1,set by Lady Kiara Trianna, +ladymashalflowercollectioncompleted_0612,Aelrynth,,,Player has completed the collection of flowers for Lady Mashal,,TRUE,72000,-1,set by Lady Mashal Trianna, +ladymashalflowercollectionstarted_0612,Aelrynth,,,Player has started the collection of flowers for Lady Mashal,,FALSE,0,1,set by Lady Mashal Trianna, +ladymhoirerewardwait,Aelrynth,,,quest timer,,TRUE,600,-1,set by Lady Tairla Mhoire, +ladysherathvinecollectioncompleted_0612,Aelrynth,,,Player has completed the collection of Vines for Lady Sherath,,TRUE,72000,-1,set by Lady Sherath Trianna, +ladysherathvinecollectionstarted_0612,Aelrynth,,,Player has started the collection of Vines for Lady Sherath,,FALSE,0,1,set by Lady Sherath Trianna, +largeaggregateshardpickup,Aelrynth,,,Picked up Large Aggregate Crystalline Shard,,TRUE,72000,-1,, +largebagoffood_pickup,Aelrynth,,,Player has picked up Large Bag of Food,,TRUE,72000,-1,, +largeempyreantomepickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +largegoldaetheriumcorefragmentpickup,Aelrynth,,,Picked up Large Gold Aetherium Core,,TRUE,72000,-1,, +largemonougarib_pickup,Aelrynth,,,Player has picked up Large Monouga Rib,,TRUE,72000,-1,, +largetome1pickuptimer,Aelrynth,,,Picked up Large Tome in Apostate Nexus,,TRUE,72000,-1,, +largetome2pickuptimer,Aelrynth,,,Picked up Large Tome in Frozen Wight Lair,,TRUE,72000,-1,, +largetome3pickuptimer,Aelrynth,,,Picked up Large Tome in Warded Dungeon Passage,,TRUE,72000,-1,, +largetome4pickuptimer,Aelrynth,,,Picked up Large Tome in Neftet Temple,,TRUE,72000,-1,, +lavushealingmachine,Aelrynth,,,Healing Machine Lavus,,TRUE,72000,-1,, +legendaryquestcounter_0913,Aelrynth,,,Number of Legendary Quests Completed for Contract,,TRUE,0,40,"set by Adrenkus, Aun Ol'tra, Darviss and 33 more", +legendaryquestsa,Aelrynth,,,BitField Stamp for Legendary Quests Completed,,TRUE,0,1048575,, +legendaryquestsb,Aelrynth,,,BitField Stamp for Legendary Quests Completed,,TRUE,0,1048575,, +leggingsacademypickup,Aelrynth,,,Player has picked up the Academy Leggings,,FALSE,0,1,checked by Samuel, +legkey48914pickup,Aelrynth,,,Picked up Legendary Key in Foundry of Izexi.,,TRUE,72000,-1,, +lesserbenedictionaug,Aelrynth,,,PERMANENT - Completion check for Asheron's Lesser Benediction Augment,,FALSE,0,1,set by Donatello Linante, +lessershadowarmoraluvian1,Aelrynth,,,Lesser Aluvian Shadow Armor 1,,FALSE,0,1,set by Alean the Steel Forger, +lessershadowarmoraluvian2,Aelrynth,,,Lesser Aluvian Shadow Armor 2,,FALSE,0,1,set by Alean the Steel Forger, +lessershadowarmoraluvian3,Aelrynth,,,Lesser Aluvian Shadow Armor 3,,FALSE,0,1,set by Alean the Steel Forger, +lessershadowarmorgharundim1,Aelrynth,,,Lesser Gharundim Shadow Armor 1,,FALSE,0,1,set by Jibril ibn Rashid, +lessershadowarmorgharundim2,Aelrynth,,,Lesser Gharundim Shadow Armor 2,,FALSE,0,1,set by Jibril ibn Rashid, +lessershadowarmorgharundim3,Aelrynth,,,Lesser Gharundim Shadow Armor 3,,FALSE,0,1,set by Jibril ibn Rashid, +lessershadowarmorsho1,Aelrynth,,,Lesser Sho Shadow Armor 1,,FALSE,0,1,set by Koga Hideki, +lessershadowarmorsho2,Aelrynth,,,Lesser Sho Shadow Armor 2,,FALSE,0,1,set by Koga Hideki, +lessershadowarmorsho3,Aelrynth,,,Lesser Sho Shadow Armor 3,,FALSE,0,1,set by Koga Hideki, +letterfromheartpickedup,Aelrynth,,,Player picked up A Leter From the Heart,,TRUE,72000,-1,, +lettergarsh,Aelrynth,,,Player has recieved LetterGarsh.,,FALSE,0,1,set by Renegade's Pack, +letterregicidemenacetpickup,Aelrynth,,,Player has picked up the Menacet Regicide Note,,TRUE,72000,-1,"checked by Dame Tsaya, Sir Rylanan, Sir Tenshin", +letterrylanan2given,Aelrynth,,,Player has delivered the full letter to Rylanan.,,FALSE,0,1,set by Dame Tsaya, +lettertenshin2given,Aelrynth,,,Player has delivered the full letter to Tenshin.,,FALSE,0,1,set by Sir Rylanan, +lettertocelcyndquest,Aelrynth,,,Letter To Celcynd Quest,,TRUE,518400,-1,, +lettertonomeapickuptimer,Aelrynth,,,Picked up Letter to Nomea,,TRUE,1728000,-1,, +lettertsaya2given,Aelrynth,,,Player has delivered the full letter to Tsaya.,,FALSE,0,1,set by Sir Tenshin, +leyleechsmedallion_pickup,Aelrynth,,,Player has picked up Ley Leechs Medallion,,TRUE,72000,-1,, +liazkbeaten,Aelrynth,,,Player defeated the tests of Liazk Itzi's Temple.,,FALSE,0,1,"set by Burun Ruuk Adherent Overseer, Burun Ruuk Seer Watcher, Burun Ruuk Shaman Keeper and 2 more", +lifestonefound1111,Aelrynth,,,Player talked to lifestone greeter,,FALSE,0,1,"set by Alcott, Eiichi, Ghaziyah and 1 more", +lightningcloud_0713,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Mysterious Portal, +lilithasbowgiven,Aelrynth,,,Gave Lilitha's Bow to Eldrista.,,TRUE,72000,-1,set by Eldrista the Adventurer, +linkofafalatacotchainpickuptimer,Aelrynth,,,Player has picked up Link of a Falatacot Chain,,TRUE,72000,-1,, +littoralsiraluunkillcount,Aelrynth,,,Littoral Siraluun Kill Counter,,TRUE,0,25,set by Rico Cellini, +littoralsiraluunkilltask,Aelrynth,,,Littoral Siraluun Kill Task,,TRUE,72000,-1,set by Rico Cellini, +lootfieldsupplies,Aelrynth,,,Looted field supply chest,,TRUE,518400,-1,, +lorcanecklacecompleted_1111,Aelrynth,,,Returned Lorca Sammel's Lost Necklace,,TRUE,72000,-1,, +lorcasammelnecklaceacquired,Aelrynth,,,Lorca Sammel's Lost Necklace,,TRUE,72000,-1,checked by Lorca Sammel, +lordgrymarrewardwait,Aelrynth,,,quest timer,,TRUE,600,-1,set by Ranger Lord Grymar Mhoire, +lordmarsanslogbookpickup,Aelrynth,,,Lord Marsan's Log Book Pick Up timer,,TRUE,72000,-1,"checked by Lieutenant Dialossa, Lieutenant Durgan", +lordtestfactionitempickuptimer,Aelrynth,,,You have obtained a quest item from lord test.,,TRUE,72000,-1,, +lordtesttempledoorwest,Aelrynth,,,Flagged to use Sclavus Temple Lord Test,,FALSE,0,1,, +loshoenspackratskilled_1107,Aelrynth,,,Check that Grave Rat KT is done before using bag. Different from bags 3 day timer.,,FALSE,0,1,set by Lo Shoen, +loshoenspacktimer_1107,Aelrynth,,,20 hour repeatable timer on obtaining Lo Shoens Rat Bait from Lo Shoens Pack,,TRUE,72000,-1,set by Lo Shoen's Pack, +losthopeinfusion,Aelrynth,,,Lost Hope Infusion,,TRUE,72000,-1,, +lostlorepagecompleted_0712,Aelrynth,,,Player has completed The Lost Lore Quest,,TRUE,72000,-1,set by Popkin of the Gate, +lostlorestarted_0712,Aelrynth,,,Player has starte The Lost Lore Quest,,FALSE,0,1,set by Popkin of the Gate, +lostmessengergotjournal,Aelrynth,,,Player has received Messengers Journal,,FALSE,0,1,set by Lost Messenger's Corpse, +lostmessengerinterceptedquest_start,Aelrynth,,,Player has started Intercepted Note portion of Lost Messenger Quest,,FALSE,0,1,set by Barsinni, +lostmessengerquest_start,Aelrynth,,,Player has started Lost Messenger Quest,,FALSE,0,1,set by Barsinni, +lostmessengerquest_wait,Aelrynth,,,Player has completed Lost Messenger Quest,,TRUE,72000,-1,set by Barsinni, +lostpetcollaracquired0805,Aelrynth,,,Lost Pet Darlings Collar Pickup,,TRUE,72000,-1,, +lostpetportal,Aelrynth,,,Flagged to enter Creepy Canyons dungeon,,FALSE,0,1,set by Xsao Lann, +lostpetquestcompleted0805,Aelrynth,,,Lost Pet Completed,,TRUE,72000,-1,set by Xsao Lann, +lownestkiller,Aelrynth,,,Player assisted in killing a newbie nest.,,FALSE,0,1,, +loyaltokahiri,Aelrynth,,,LoyalToKahiri,,FALSE,0,1,set by Ka'hiri, +loyaltoliamofgelid,Aelrynth,,,LoyalToLiamOfGelid,,FALSE,0,1,set by Liam of Gelid, +loyaltolordtyragar,Aelrynth,,,LoyalToLordTyragar,,FALSE,0,1,set by Lord Tyragar, +loyaltoshadeofladyadja,Aelrynth,,,LoyalToShadeOfLadyAdja,,FALSE,0,1,set by Shade of Lady Adja, +lubziklanagreement,Aelrynth,,,Flagged for Lubziklan Agreement quest,,FALSE,0,1,set by Anton Sillezi, +lubziklancoveapplequest,Aelrynth,,,DEPRECATED,,TRUE,72000,-1,, +lubziklanwarmapplepiequest,Aelrynth,,,DEPRECATED,,TRUE,72000,-1,, +lugianassaultcompleted_0913,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Commander Presk, +lugianassaultstarted_0913,Aelrynth,,,quest timer,,FALSE,0,1,set by Raksaa, +lugianbladeheart,Aelrynth,,,Lugian Blade of the Heart,,TRUE,72000,-1,, +lugianclotharm,Aelrynth,,,Lugian Cloth of the Arm,,TRUE,72000,-1,, +lugianstaffmind,Aelrynth,,,Lugian Staff of the Mind,,TRUE,72000,-1,, +lumaugskillquest,Aelrynth,,,Counter for Augmentation Skill Gem,,TRUE,0,2,set by Nalicana, +lunnumsdisappearancecompleted0106,Aelrynth,,,Track down the thief who took Lunnum. - Completed,,TRUE,72000,-1,set by Fiun Gaya, +lunnumsdisappearancestarted0106,Aelrynth,,,Flagging for start of quest,,FALSE,0,1,set by Fiun Gaya, +lunnumspyrequestcompleted0805,Aelrynth,,,Lunnum's Pyre Timer,,TRUE,72000,-1,set by Fiun Gaya, +lunnumspyrequeststarted0805,Aelrynth,,,Flagging for start of quest,,FALSE,0,1,set by Fiun Gaya, +lunnumsreturncomplete1006,Aelrynth,,,Player has completed Lunnums Return,,TRUE,72000,-1,set by Fiun Layeel, +lunnumsreturnstarted1006,Aelrynth,,,Player has started Lunnums Return,,FALSE,0,1,set by Fiun Layeel, +lurgisscorepickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +lurzasezzhereislairgiven,Aelrynth,,,Sezzherei's Lair given to Lurza,,FALSE,0,1,set by Lurza, +maceofhiranaith,Aelrynth,,,Mace of Hiranaith pickup timer,,TRUE,72000,-1,, +machinistparts,Aelrynth,,,BitField Stamp for Machinist Gloves quest parts,,TRUE,0,2097150,, +machinistpartscounter,Aelrynth,,,Number of alloy parts collected,,TRUE,0,20,set by Kaywin, +maddenedfiunheart,Aelrynth,,,Red Bull of Sanamar Quest,,TRUE,72000,-1,, +mageacademykey,Aelrynth,,,Mage Academy Coffin Key,,TRUE,72000,-1,, +maggotkillcount,Aelrynth,,,quest timer,,TRUE,0,8,set by Grub Test Stopgap, +magicitemtraining1,Aelrynth,,,You have been blessed by Bleeargh to learn item enchantment.,,FALSE,0,1,"set by Bleeargh, Mosswart Swamp Lord", +magicitemtraining2,Aelrynth,,,You have been blessed by Bleeargh to learn item enchantment.,,FALSE,0,1,"set by Bleeargh, Mosswart Swamp Lord", +magicitemtraining3,Aelrynth,,,You have been blessed by Bleeargh to learn item enchantment.,,FALSE,0,1,"set by Bleeargh, Mosswart Swamp Lord", +magicitemtraining4,Aelrynth,,,You have been blessed by Bleeargh to learn item enchantment.,,FALSE,0,1,"set by Bleeargh, Mosswart Swamp Lord", +magicitemtraining5,Aelrynth,,,You have been blessed by Bleeargh to learn item enchantment.,,FALSE,0,1,"set by Bleeargh, Mosswart Swamp Lord", +magicitemtraining6,Aelrynth,,,You have been blessed by Bleeargh to learn item enchantment.,,FALSE,0,1,"set by Bleeargh, Mosswart Swamp Lord", +magmaexarchcooldown,Aelrynth,,,Magma Golem Exarch Cooldown Timer,,TRUE,518400,-1,set by Aun Autuorea, +magmagolemexarchkillcount,Aelrynth,,,Magma Golem Exarch Kill Counter,,TRUE,0,5,, +magmagolemexarchkilltask,Aelrynth,,,Magma Golem Exarch Kill Task,,TRUE,72000,-1,, +magnificentbraceletpickuptimer,Aelrynth,,,Pick up Magnificent Bracelet Wait timer,,TRUE,72000,-1,, +magshuthmoarsmenkillcount,Aelrynth,,,Magshuth Moarsmen Kill Counter,,TRUE,0,20,, +magshuthmoarsmenkilltask,Aelrynth,,,Magshuth Moarsmen Kill Task,,TRUE,72000,-1,, +manapickup,Aelrynth,,,Player has picked up an Academy mana potion,,TRUE,0,15,, +maraefinalreward,Aelrynth,,,Give Aun Hareltah HeadOlthoiQueen,,TRUE,72000,-1,set by Aun Hareltah, +marauderlaircomplete,Aelrynth,,,Marauder Lair Complete,,FALSE,0,1,set by Grand Mother, +maraudersjaw,Aelrynth,,,Marauder's Lair Quest,,TRUE,72000,-1,, +marcustalkweek1,Aelrynth,,,quest timer,,FALSE,0,1,set by Marcus Manfried, +marcuswarned,Aelrynth,,,quest timer,,FALSE,0,1,set by Marcus Manfried, +markoftheoverlord_pickup,Aelrynth,,,Picked up Mark of the Overlord,,TRUE,72000,-1,checked by Lieutenant Rothe, +marriagecompleted,Aelrynth,,,Player has been married,,TRUE,72000,-1,"set by Grand Sentinel Ehcac, Grand Sentinel Muroba, Grand Sentinel Tretia", +marriagesymbolfriendship,Aelrynth,,,Player has picked up the Symbol of Friendship,,TRUE,72000,-1,, +marriagesymbolhonor,Aelrynth,,,Player has picked up the Symbol of Honor,,TRUE,72000,-1,, +marriagesymbollove,Aelrynth,,,Player has picked up the Symbol of Love,,TRUE,72000,-1,, +martinaidcomplete,Aelrynth,,,Players have made their choice about helping Martine.,,FALSE,0,1,set by Martine, +martinemask,Aelrynth,,,Player has picked up the Mask.,,TRUE,72000,-1,, +martinerobe,Aelrynth,,,Player has picked up the Robe.,,TRUE,72000,-1,, +maruuninformer1,Aelrynth,,,quest timer,,FALSE,0,1,"set by Jean, Luc", +maruuninformer2,Aelrynth,,,quest timer,,FALSE,0,1,"set by Jean, Luc", +maruuninformer3,Aelrynth,,,quest timer,,FALSE,0,1,"set by Jean, Luc", +maruunscrappickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +maruunstarted,Aelrynth,,,quest timer,,FALSE,0,1,set by Resonant Portal, +maruuntimeout,Aelrynth,,,quest timer,,TRUE,72000,-1,"set by Marcus Manfried, Wren the Curious", +maruunvirindiconfronted,Aelrynth,,,quest timer,,FALSE,0,1,"set by Jean, Luc", +maruunweek1done,Aelrynth,,,quest timer,,FALSE,0,1,"set by Marcus Manfried, Wren the Curious", +maruunweek2done,Aelrynth,,,quest timer,,FALSE,0,1,set by Marcus Manfried, +maruunweek3done,Aelrynth,,,quest timer,,FALSE,0,1,set by Marcus Manfried, +maruunweek4done,Aelrynth,,,quest timer,,FALSE,0,1,set by Marcus Manfried, +maskdirectoroct01,Aelrynth,,,Obsidian Director Mask,,TRUE,72000,-1,, +masknoir1,Aelrynth,,,You're wearing the bandit mask.,,FALSE,0,1,set by Bandit Mask, +masknoir1pickup,Aelrynth,,,You've picked up the bandit mask.,,TRUE,72000,-1,, +maskofblackwater_pickup,Aelrynth,,,Player has picked up the Mask of the Watcher of Black Water.,,TRUE,72000,-1,, +mastersealturnedin,Aelrynth,,,Gave Rytheran's Master Seal to Master's Sentinel,,FALSE,0,1,set by Master's Sentinel, +mastersmessageshardpickuptimer,Aelrynth,,,Player has picked up Excavation Masters Message Shard,,TRUE,72000,-1,, +mastersvoicecomplete0710,Aelrynth,,,Completed His Master's Voice - Handed Tomb Rubble to Ssavashka the Devoted,,FALSE,0,1,set by Ssavashka the Devoted, +mastersvoicecontractcomplete,Aelrynth,,,Contract Completed for His Master's Voice quest,,FALSE,0,1,, +mastersvoicerubbleacquired,Aelrynth,,,His Master's Voice Tomb Rubble Acquired,,TRUE,72000,-1,set by Tomb Rubble, +mastersvoicestarted_0511,Aelrynth,,,Flagging for start of quest,,FALSE,0,1,set by Ssavashka the Devoted, +mawpickedup,Aelrynth,,,Pickup timer for Bloodmouth Maw,,TRUE,72000,-1,, +maygetsword,Aelrynth,,,Player may pick up sword,,TRUE,72000,-1,set by Mage Syltyn Rillon, +mayoimoarsmencomplete_0508,Aelrynth,,,Player has completed the Mayoi portion of Moarsmen on the Shores,,TRUE,72000,-1,set by Guard Taizo, +mehirresearchcomplete0310,Aelrynth,,,Menhir Research Timer of 20 Hours,,TRUE,72000,-1,set by Cara the Apprentice, +meleemasterychange,Aelrynth,,,Changed Melee Mastery.,,FALSE,0,1,, +memorygamedroppedaxe,Aelrynth,,,You've dropped the memory game axe.,,TRUE,72000,-1,set by Axe, +memorygamedroppedmace,Aelrynth,,,You've dropped the memory game mace.,,TRUE,72000,-1,set by Mace, +memorygamedroppedspear,Aelrynth,,,You've dropped the memory game spear.,,TRUE,72000,-1,set by Spear, +memorygamedroppedsword,Aelrynth,,,You've dropped the memory game sword.,,TRUE,72000,-1,set by Sword, +memorygamepickedupaxe,Aelrynth,,,You've dropped the memory game axe.,,TRUE,180,-1,, +memorygamepickedupmace,Aelrynth,,,You've dropped the memory game mace.,,TRUE,180,-1,, +memorygamepickedupspear,Aelrynth,,,You've dropped the memory game spear.,,TRUE,180,-1,, +memorygamepickedupsword,Aelrynth,,,You've dropped the memory game sword.,,TRUE,180,-1,, +memorygamereceivedinstructions,Aelrynth,,,You've received the memory game instructions.,,TRUE,72000,-1,set by Statue, +menacetsnote,Aelrynth,,,Writ Nov Quest 2,,TRUE,72000,-1,checked by Arcanum Envoy, +menhirresearchnpccounter,Aelrynth,,,Menhir Research Ring Counter,,TRUE,0,20,"set by Cara the Apprentice, Menhir Ring Eight, Menhir Ring Eighteen and 18 more", +menhirresearchringscomplete,Aelrynth,,,Menhir Research Rings Complete Bitfield,,TRUE,0,1048575,, +menhirrubbleapickup,Aelrynth,,,Player has picked up MenhirRubbleA_xp and cannot pick it up again for one day,,TRUE,72000,-1,, +menhirrubblebpickup,Aelrynth,,,Player has picked up MenhirRubbleB_xp and cannot pick it up again for one day,,TRUE,72000,-1,, +menhirrubblecpickup,Aelrynth,,,Player has picked up MenhirRubbleC_xp and cannot pick it up again for one day,,TRUE,72000,-1,, +menhirrubbledpickup,Aelrynth,,,Player has picked up MenhirRubbleD_xp and cannot pick it up again for one day,,TRUE,72000,-1,, +menhirrubbleepickup,Aelrynth,,,Player has picked up MenhirRubbleE_xp and cannot pick it up again for one day,,TRUE,72000,-1,, +messengerscollar_pickup,Aelrynth,,,Player has picked up the Messengers Collar,,TRUE,72000,-1,, +messengerscollar_repeat,Aelrynth,,,Player has completed Messengers Collar quest at least once.,,FALSE,0,1,set by Fanzen San the Translator, +mfcritterkilled,Aelrynth,,,Counter for Monster Fights,,TRUE,0,7,set by Monster Fights Controller, +mgheasycompleted,Aelrynth,,,Monthly Game Hunter Kill Task wait timer.,,TRUE,72000,-1,"set by Rand, Game Hunter", +mghextremecompleted,Aelrynth,,,Monthly Game Hunter Kill Task wait timer.,,TRUE,72000,-1,"set by Rand, Game Hunter", +mghhardcompleted,Aelrynth,,,Monthly Game Hunter Kill Task wait timer.,,TRUE,72000,-1,"set by Rand, Game Hunter", +mghmoderatecompleted,Aelrynth,,,Monthly Game Hunter Kill Task wait timer.,,TRUE,72000,-1,"set by Rand, Game Hunter", +mghveryhardcompleted,Aelrynth,,,Monthly Game Hunter Kill Task wait timer.,,TRUE,72000,-1,"set by Rand, Game Hunter", +mhoirebrand1,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian Statue, +mhoirebrand1pickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +mhoirebrand2,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian Statue, +mhoirebrand2pickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +mhoirebrand3,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian Statue, +mhoirebrand3pickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +mhoirecastleflagcounter,Aelrynth,,,quest timer,,TRUE,0,3,set by Guardian Statue, +mhoirecastleflagstarted,Aelrynth,,,quest timer,,FALSE,0,1,set by Ancient Stones, +mhoirecastleflagwait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Guardian Statue, +mhoirecastlegotaccess,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian Statue, +mhoiregreathall,Aelrynth,,,Flagged for using the Mhoire Great Hall portal,,FALSE,0,1,set by Shade of Antemy, +mhoirenwcounter,Aelrynth,,,quest timer,,TRUE,0,4,"set by Guardian of Air, Guardian of Earth, Guardian of Fire and 2 more", +mhoirenwe1,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenwe2,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenwe3,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenwe4,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenwfail,Aelrynth,,,quest timer,,FALSE,0,1,"set by Guardian of Air, Guardian of Earth, Guardian of Fire and 1 more", +mhoirenwn1,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenwn2,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenwn3,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenwn4,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenwpass,Aelrynth,,,quest timer,,FALSE,0,1,"set by Guardian of Air, Guardian of Earth, Guardian of Fire and 1 more", +mhoirenwportalflag,Aelrynth,,,Mhoire NW portal flagging,,FALSE,0,1,"set by Guardian of Air, Guardian of Earth, Guardian of Fire and 1 more", +mhoirenws1,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenws2,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenws3,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenws4,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenww1,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenww2,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenww3,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoirenww4,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoiresegotsword,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoiresepass,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoireseportalflag,Aelrynth,,,Mhoire SE portal flagging,,FALSE,0,1,set by Guardian of Mhoire, +mhoiresignetringswait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Shade of Ormend, +mhoireswcounter,Aelrynth,,,quest timer,,TRUE,0,8,"set by Flames of Charity, Flames of Courage, Flames of Honesty and 5 more", +mhoireswpass,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Mhoire, +mhoireswportalflag,Aelrynth,,,Mhoire SW portal flagging,,FALSE,0,1,set by Guardian of Mhoire, +mhoiretrialscomplete,Aelrynth,,,quest timer,,FALSE,0,1,set by Shade of Antemy, +midnestkiller,Aelrynth,,,Player assisted in killing a newbie nest.,,FALSE,0,1,, +minnowcounter,Aelrynth,,,Number of Minnows turned in.,,TRUE,0,600,set by Fishing Hole, +minorstonewrit,Aelrynth,,,Player turned in a minor atlan stone to an Agent of the Arcanum,,FALSE,0,1,"set by Agent Dravos, Agent of the Arcanum", +mirrorshardpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +miserysplinterpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +mixingbasina,Aelrynth,,,quest timer,,FALSE,0,1,set by Mixing Basin, +mixingbasinb,Aelrynth,,,quest timer,,FALSE,0,1,set by Mixing Basin, +mixingbasinc,Aelrynth,,,quest timer,,FALSE,0,1,set by Mixing Basin, +mixingbasind,Aelrynth,,,quest timer,,FALSE,0,1,set by Mixing Basin, +moarsmenjailbreak,Aelrynth,,,Moarsmen Jailbreak,,TRUE,72000,-1,, +moguthmoarsmankillcount,Aelrynth,,,Moguth Moarsman Kill Counter,,TRUE,0,60,, +moguthmoarsmankilltask,Aelrynth,,,Moguth Moarsman Kill Task,,TRUE,72000,-1,, +mollycounter,Aelrynth,,,Number of Minnows turned in.,,TRUE,0,100,set by Fishing Hole, +monougaexperimentlogpickuptimer,Aelrynth,,,Pickup timer for Monouga Experiment Log,,TRUE,72000,-1,, +monsterfightwins,Aelrynth,,,Counter for how many wins in monster fights player has,,TRUE,0,10,set by Monster Fight Bookie, +monthlyquestbiweeklyone0710,Aelrynth,,,Player has completed the Biweekly Monthly Explorer Society Quest.,,TRUE,518400,-1,set by Esmond Fielding, +monthlyquestmonthlyone0710,Aelrynth,,,Player has completed the Monthly Monthly Explorer Society Quest.,,TRUE,518400,-1,set by Ansar El-Kerdany, +monthlyquestweeklyone0710,Aelrynth,,,Player has completed the Weekly Monthly Explorer Society Quest.,,TRUE,518400,-1,set by Niccolo De Luca, +morgluukkiller,Aelrynth,,,You were one of the first people to kill Morgluuk.,,FALSE,0,1,"set by Alec, Aun Faranua, Captain K'rank and 2 more", +morningstatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +mosswartexoduscloth,Aelrynth,,,You found the loincloth of the first Mire Witch.,,TRUE,72000,-1,, +mosswartexoduseye,Aelrynth,,,You found the eye of Drageerg.,,TRUE,72000,-1,, +mosswartexodushand,Aelrynth,,,You found the Hand of Vagurat.,,TRUE,72000,-1,, +mosswartexodusnecklace,Aelrynth,,,You found the Necklace of Leerargh.,,TRUE,72000,-1,, +mosswartexodusnecklacekey,Aelrynth,,,You found the key to open the necklace chest.,,TRUE,72000,-1,, +mosswartexodusspear,Aelrynth,,,You found the Spear of Kreerg.,,TRUE,72000,-1,, +mosswartexodusspearkey,Aelrynth,,,You found the Mosswart Chest Key.,,TRUE,72000,-1,, +mosswartexoduswarpaint,Aelrynth,,,You found the war paint used by the swamp lords.,,TRUE,72000,-1,, +mosswartidolitem,Aelrynth,,,You have picked up the Mosswart Item Enchantment teaching idol.,,TRUE,72000,-1,set by Mosswart Enchantment Idol, +mosswarttornshroud,Aelrynth,,,Torn Mosswart Shroud,,TRUE,72000,-1,, +mosswarttownsfolkkillcount,Aelrynth,,,Mosswart Townsfolk Kill Counter,,TRUE,0,40,, +mosswarttownsfolkkilltask,Aelrynth,,,Mosswart Townsfolk Kill Task,,TRUE,72000,-1,, +mosswartworshipperkillcount,Aelrynth,,,Mosswart Worshipper Kill Counter,,TRUE,0,175,set by Orfeo Orlando, +mosswartworshipperkilltask,Aelrynth,,,Mosswart Worshipper Kill Task,,TRUE,72000,-1,set by Orfeo Orlando, +mossyherb,Aelrynth,,,Allowed to pickup Mossy Herb,,FALSE,0,1,set by Gonjoku Den, +mottledcarenzikillcount,Aelrynth,,,Mottled Carenzi Kill Counter,,TRUE,0,50,set by Grania the Bold, +mottledcarenzikilltask,Aelrynth,,,Mottled Carenzi Kill Task,,TRUE,72000,-1,set by Grania the Bold, +moufreward,Aelrynth,,,Received Mouf Reward,,TRUE,72000,-1,set by Mouf, +mowenfighter,Aelrynth,,,TBD,,FALSE,0,1,set by Throne of the Tusker King, +mowenwait,Aelrynth,,,TBD,,TRUE,72000,-1,"set by Oolutanga, the Tusker King", +mowenwinner,Aelrynth,,,TBD,,FALSE,0,1,set by Mowen Udaun, +muckymoarsmankillcount,Aelrynth,,,Mucky Moarsman Kill Counter,,TRUE,0,50,set by Algar Oreksun, +muckymoarsmankilltask,Aelrynth,,,Mucky Moarsman Kill Task,,TRUE,72000,-1,set by Algar Oreksun, +muddaveusinsigniabadge,Aelrynth,,,Hunt for Muldaveus Insignia Badge,,TRUE,72000,-1,, +mudgolemsludgelordkillcount,Aelrynth,,,Mud Golem Sludge Lord Kill Counter,,TRUE,0,5,, +mudgolemsludgelordkilltask,Aelrynth,,,Mud Golem Sludge Lord Kill Task,,TRUE,72000,-1,, +mugoswaldgiven,Aelrynth,,,Gave Celcynd his mug,,TRUE,72000,-1,set by Celcynd the Dour, +mugoswaldtaken,Aelrynth,,,Took the mug,,TRUE,72000,-1,, +mukkiraspectofgraelquest_wait,Aelrynth,,,Player has completed Mukkir Aspect of Grael Quest,,TRUE,72000,-1,set by Varetha, +mukkirinfestedblackspeartemple_start,Aelrynth,,,Player has access to Mukkir Infested Black Spear Temple,,FALSE,0,1,set by Varetha, +muldaveustornpage1,Aelrynth,,,Hunt for Muldaveus Torn Journal Page 1,,TRUE,72000,-1,, +muldaveustornpage2,Aelrynth,,,Hunt for Muldaveus Torn Journal Page 2,,TRUE,72000,-1,, +muldaveustornpage3,Aelrynth,,,Hunt for Muldaveus Torn Journal Page 3,,TRUE,72000,-1,, +muldaveustornpage4,Aelrynth,,,Hunt for Muldaveus Torn Journal Page 4,,TRUE,72000,-1,, +mumiyahdaggercollectionstart,Aelrynth,,,mumiyah sacrificial dagger collection start,,FALSE,0,1,, +mumiyahdaggercollectionwait,Aelrynth,,,mumiyah sacrificial dagger collection wait,,TRUE,72000,-1,, +mumiyahhuntingneftet,Aelrynth,,,Mumiyah Hunting Neftet,,TRUE,72000,-1,, +mumufirstspeak,Aelrynth,,,TBD,,FALSE,0,1,, +mumuright,Aelrynth,,,Correct answer on Mu Mu,,FALSE,0,1,set by Mu Mu, +mutilatedfeather_pickup,Aelrynth,,,Pickup timer on Mutilated Turkey Feather.,,TRUE,72000,-1,, +mysticalmugflag,Aelrynth,,,Player stamp for Mystical Mug use,,FALSE,0,1,set by Ulgrim the Unpleasant, +nanjoustockadefinished_1012,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Shorikan, +nanjoustockadekeypickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +nanjoustockadestarted_1012,Aelrynth,,,quest timer,,FALSE,0,1,set by Shorikan, +nanjoustockadeswordpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +nantotownquest,Aelrynth,,,Nanto Town Quest,,TRUE,72000,-1,, +nantowaterbottlequest,Aelrynth,,,Nanto Water Bottle Quest,,TRUE,518400,-1,, +naughtyskeletonkillcount,Aelrynth,,,Naughty Skeleton Kill Counter,,TRUE,0,100,set by Taku Yukio, +naughtyskeletonkilltask,Aelrynth,,,Naughty Skeleton Kill Task,,TRUE,72000,-1,set by Taku Yukio, +necklaceoftheelementscomplete,Aelrynth,,,Necklace of the Elemental Adepts quest completed,,TRUE,72000,-1,set by Royal Guard Qumasha, +necklaceoftheelementsstarted,Aelrynth,,,Necklace Of The Elements quest started,,FALSE,0,1,set by Royal Guard Qumasha, +neftetdevicecrystalturninwait,Aelrynth,,,Neftet Mumiyah Device Crystals Turned in,,TRUE,72000,-1,set by Mu-miyah Device, +neftetfreehatsheput,Aelrynth,,,Free Hatsheput,,FALSE,0,1,set by Mu-miyah Device, +neftetfreehatsheputwait,Aelrynth,,,Neftet Free Hatsheput Wait,,TRUE,72000,-1,set by Hatshepsut, +neftetgrandvizierdead,Aelrynth,,,Neftet Temple Grand Vizier Killed,,FALSE,0,1,set by Drids Doorman Vizier Spawner, +neftettempleflagcomplete,Aelrynth,,,Neftet Temple Entrance Flag,,TRUE,72000,-1,set by Mu-miyah Device, +neftettempleladydead,Aelrynth,,,Neftet Temple Lady Killed,,FALSE,0,1,set by Drids Doorman Lady Spawner, +neftettemplezoneatotaldead,Aelrynth,,,Neftet Temple Zone A Kills,,TRUE,0,41,set by Drids Lower Doorman, +newbienestkiller,Aelrynth,,,Player assisted in killing a newbie nest.,,FALSE,0,1,, +newbiequeststampalarqas,Aelrynth,,,Al-Arqas Stamp Quest,,TRUE,72000,-1,, +newbiequeststampholtburg,Aelrynth,,,Holtburg Stamp Quest,,TRUE,72000,-1,, +newbiequeststamplytelthorpe,Aelrynth,,,Lytelthorpe Stamp Quest,,TRUE,72000,-1,, +newbiequeststampnanto,Aelrynth,,,Nanto Stamp Quest,,TRUE,72000,-1,, +newbiequeststamprithwic,Aelrynth,,,Rithwic Stamp Quest,,TRUE,72000,-1,, +newbiequeststampsamsur,Aelrynth,,,Samsur Stamp Quest,,TRUE,72000,-1,, +newbiequeststampshoushi,Aelrynth,,,Shoushi Stamp Quest,,TRUE,72000,-1,, +newbiequeststampyanshi,Aelrynth,,,Yanshi Stamp Quest,,TRUE,72000,-1,, +newbiequeststampyaraq,Aelrynth,,,Yaraq Stamp Quest,,TRUE,72000,-1,, +nexuscrawlcompleted0509,Aelrynth,,,Nexus Crawl Quest Wait Timer,,TRUE,72000,-1,set by Ned the Clever, +nexuscrawlresonatorturnin0509,Aelrynth,,,Player handed in Aetheric Resonator,,FALSE,0,1,set by Apostate Aetherium Deposit, +nexuscrawlstarted0509,Aelrynth,,,Player has started Nexus Crawl quest,,FALSE,0,1,set by Ned the Clever, +neydisatranscription,Aelrynth,,,Neydisa Frore Transcription,,TRUE,72000,-1,, +niffsnitchgive,Aelrynth,,,Counterfeit Writ Quest Arcanum Turn in,,TRUE,72000,-1,"set by Agent Dravos, Agent of the Arcanum", +niffsnitchuse,Aelrynth,,,Counterfeit Writ Quest Arcanum Turn in,,TRUE,72000,-1,"set by Agent Dravos, Agent of the Arcanum", +nightclubentrance1204,Aelrynth,,,Player has received permission to enter the Night Club duneon! Created for the December 2004 revision.,,FALSE,0,1,, +nightclubticket,Aelrynth,Night Club Ticket Picked up,,Night Club Ticket Picked up,,TRUE,3600,-1,, +nightmaregateflagged,Aelrynth,,,Flagged to Enter Nightmare Gate Dungeon,,TRUE,1987200,-1,set by Nightmare Gate, +ninjaacademyfinished_0812,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Darviss, +ninjaacademykeypickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +ninjaacademystarted_0812,Aelrynth,,,quest timer,,FALSE,0,1,set by Darviss, +ninjaacademyswordpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +nobleremainskillcount,Aelrynth,,,Noble Remains Kill Counter,,TRUE,0,10,, +nobleremainskilltask,Aelrynth,,,Noble Remains Kill Task,,TRUE,72000,-1,, +nodegolemturnins,Aelrynth,,,Player handed in Blighted Mana Crystal To Node Golem,,TRUE,0,-1,"set by A'mun Node Golem, Aerlinthe Node Golem, Esper Node Golem and 3 more", +nodegolemwait,Aelrynth,,,Players wait time to receive rewards for Tainted Ley Line Nodes,,TRUE,72000,-1,"set by A'mun Node Golem, Aerlinthe Node Golem, Esper Node Golem and 3 more", +nodeleechsmedallion_pickup,Aelrynth,,,Player has picked up Node Leechs Medallion,,TRUE,72000,-1,, +northernpedestalshard_pickup,Aelrynth,Player has picked up the Shard of the Northern Pedestal.,,Player has picked up the Shard of the Northern Pedestal.,Player has picked up the Shard of the Northern Pedestal.,TRUE,72000,-1,, +northernresonatingcrystalflag,Aelrynth,,,Player has turned in the Northern Resonator,,FALSE,0,1,set by Northern Resonating Crystal, +northernshroudcabalcomplete_0511,Aelrynth,,,Player has completed Northern Shroud Cabal,,TRUE,72000,-1,set by Nomendar al-Rakh, +northerntumerokinsignia,Aelrynth,Northern Tumerok Insignia,,Northern Tumerok Insignia,Northern Tumerok Insignia,TRUE,72000,-1,, +northinfiltratorshardpickup,Aelrynth,,,Northern Infiltrator Message Shard pickup timer,,TRUE,72000,-1,, +noteburunhistory1,Aelrynth,,,You have learned a little about Burun History.,,TRUE,72000,-1,, +noteburunhistory10,Aelrynth,,,You have learned a little about Burun History.,,TRUE,72000,-1,, +noteburunhistory2,Aelrynth,,,You have learned a little about Burun History.,,TRUE,72000,-1,, +noteburunhistory3,Aelrynth,,,You have learned a little about Burun History.,,TRUE,72000,-1,, +noteburunhistory4,Aelrynth,,,You have learned a little about Burun History.,,TRUE,72000,-1,, +noteburunhistory5,Aelrynth,,,You have learned a little about Burun History.,,TRUE,72000,-1,, +noteburunhistory6,Aelrynth,,,You have learned a little about Burun History.,,TRUE,72000,-1,, +noteburunhistory7,Aelrynth,,,You have learned a little about Burun History.,,TRUE,72000,-1,, +noteburunhistory8,Aelrynth,,,You have learned a little about Burun History.,,TRUE,72000,-1,, +noteburunhistory9,Aelrynth,,,You have learned a little about Burun History.,,TRUE,72000,-1,, +notedrudgescrawledpickup,Aelrynth,,,Yaraq Akyafi Quest,,TRUE,72000,-1,, +notedukeenricoacquired0905,Aelrynth,,,Pickup timer for To My Dear Uncle,,TRUE,72000,-1,set by Enrico di Bellenesse, +notefromaunbernawa,Aelrynth,,,Note from Aun Bernawa to Hea Toneawa,,TRUE,72000,-1,set by Aun Bernawa, +notemarionapickup,Aelrynth,,,Hea Toneawa and Aun Mariona quest You can only pickup up NoteMariona once a day.,,TRUE,72000,-1,, +notenuhmudiralabyrinth1pickup,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +notenuhmudiralabyrinth2pickup,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +notenuhmudiralabyrinth3pickup,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +notenuhmudiralabyrinth4pickup,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +notenuhmudiralabyrinth5pickup,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +notenuhmudiralabyrinth6pickup,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +notenuhmudiralabyrinth7pickup,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +notenuhmudiralabyrinth8pickup,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +noteregicideholtburgpickup,Aelrynth,,,Player has picked up the Cryptic Note,,TRUE,72000,-1,"checked by Reformed Bandit, Sir Rylanan", +novquest1,Aelrynth,,,Novemeber Quest 1,,TRUE,72000,-1,, +novquest2,Aelrynth,,,Novemeber Quest 2,,FALSE,0,1,, +novquest3,Aelrynth,,,Novemeber Quest 3,,TRUE,72000,-1,, +novquest4,Aelrynth,,,Novemeber Quest 4,,TRUE,72000,-1,, +novquest5,Aelrynth,,,Novemeber Quest 5,,TRUE,72000,-1,, +novquest6,Aelrynth,,,Novemeber Quest 6,,FALSE,0,1,, +npcbackpackkiviklir,Aelrynth,,,You've gotten the journal from the backpack.,,TRUE,72000,-1,set by Backpack, +nuhmudiratokenquestcomplete,Aelrynth,,,Nuhmudiras Token,,FALSE,0,1,"set by Agent Dravos, Agent of the Arcanum", +nullifiedsarcophagus,Aelrynth,Frest Greelving's Haunted Mansion,https://acportalstorm.com/wiki/Frest_Greelving's_Haunted_Mansion,Player defeated the Sarcophagus. See Frest Greelving; Dark Sarcophagus.,Player defeated the Sarcophagus,TRUE,72000,-1,set by Dark Sarcophagus, +numberpuzzlecompleted,Aelrynth,,,You've compleated the Clutch of Kings number puzzle.,,TRUE,72000,-1,"set by 29, 5, 55", +nurinopart1done,Aelrynth,,,quest timer,,FALSE,0,1,set by Nurino, +nurinopart1start,Aelrynth,,,quest timer,,FALSE,0,1,set by Nurino, +nurinopart2done,Aelrynth,,,quest timer,,FALSE,0,1,set by Nurino, +nurinopart2start,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Nurino, +nurinopart3done,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Nurino, +nurinopart3start,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Nurino, +nutboltgrievver,Aelrynth,,,Player has picked up a Griever nuts and bolts and cannot pick up another for 1 day.,,TRUE,72000,-1,, +nutboltgrievvergiven,Aelrynth,,,Player has given this spring and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +nutboltshadow,Aelrynth,,,Player has picked up a Shadow nuts and bolts and cannot pick up another for 1 day.,,TRUE,72000,-1,, +nutboltshadowgiven,Aelrynth,,,Player has given this spring and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +nutboltvirindi,Aelrynth,,,Player has picked up a Virindi nuts and bolts and cannot pick up another for 1 day.,,TRUE,72000,-1,, +nutboltvirindigiven,Aelrynth,,,Player has given this spring and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +nyrlehamoarsmankillcount,Aelrynth,,,Nyr'leha Moarsman Kill Counter,,TRUE,0,20,, +nyrlehamoarsmankilltask,Aelrynth,,,Nyr'leha Moarsman Kill Task,,TRUE,72000,-1,, +nyrlehasclavuskillcount,Aelrynth,,,Nyr'leha Sclavus Kill Counter,,TRUE,0,20,, +nyrlehasclavuskilltask,Aelrynth,,,Nyr'leha Sclavus Kill Task,,TRUE,72000,-1,, +occultusringtimer,Aelrynth,,,Collegium Occultus Ring pickup timer,,TRUE,72000,-1,set by Roderick, +offerburunpickedup,Aelrynth,,,You have picked up the Renegade's offer to the Burun.,,TRUE,72000,-1,, +offeringxikminru,Aelrynth,,,Pickup timer for Xik Minru Temple Offerings,,TRUE,72000,-1,, +oftrustbetrayalcomplete_0511,Aelrynth,,,Contract Repeat Timer for Of Trust And Betrayal,,TRUE,72000,-1,set by Jedeth Eckhart, +oilgiven,Aelrynth,,,Blacksmith gave the Oil,,FALSE,0,1,set by Academy Blacksmith, +oldmanmountainquest,Aelrynth,,,Old Man of the Mountain Quest,,TRUE,72000,-1,, +oldnectarpickup,Aelrynth,,,Old Nectar picked up from a Large Chest.,,TRUE,72000,-1,, +olthoidronekillcount,Aelrynth,,,Olthoi Drone Kill Counter,,TRUE,0,20,, +olthoidronekilltask,Aelrynth,,,Olthoi Drone Kill Task,,TRUE,72000,-1,, +olthoiexperimentlogpickuptimer,Aelrynth,,,Pickup timer for Olthoi Experiment Log,,TRUE,72000,-1,, +olthoihunting1,Aelrynth,,,Olthoi Hunting 1,,TRUE,72000,-1,checked by Behdo Yii, +olthoihunting2,Aelrynth,,,Olthoi Hunting 2,,TRUE,72000,-1,checked by Behdo Yii, +olthoihunting3,Aelrynth,,,Olthoi Hunting 3,,TRUE,72000,-1,checked by Behdo Yii, +olthoihunting4,Aelrynth,,,Olthoi Hunting 4,,TRUE,72000,-1,checked by Behdo Yii, +olthoihunting5,Aelrynth,,,Olthoi Hunting 5,,TRUE,72000,-1,checked by Behdo Yii, +olthoihunting6,Aelrynth,,,Olthoi Hunting 6,,TRUE,72000,-1,checked by Behdo Yii, +olthoihunting7,Aelrynth,,,Olthoi Hunting 7,,TRUE,72000,-1,checked by Behdo Yii, +olthoihunting8,Aelrynth,,,Olthoi Hunting 8,,TRUE,72000,-1,checked by Behdo Yii, +olthoijellyroyalderupickedup,Aelrynth,,,Player has picked up Royal Jelly for Deru Quest.,,FALSE,0,1,set by Pool of Goo, +olthoijellyroyalpickedup,Aelrynth,,,Player picked up OlthoiJellyRoyal.,,TRUE,72000,-1,set by Pool of Goo, +olthoinettlerkillcount,Aelrynth,,,Olthoi Nettler Kill Counter,,TRUE,0,10,, +olthoinettlerkilltask,Aelrynth,,,Olthoi Nettler Kill Task,,TRUE,72000,-1,, +olthoinymphkillcount,Aelrynth,,,Olthoi Nymph Kill Counter,,TRUE,0,20,, +olthoinymphkilltask,Aelrynth,,,Olthoi Nymph Kill Task,,TRUE,72000,-1,, +olthoiripperkillcount,Aelrynth,,,Olthoi Ripper Kill Counter,,TRUE,0,250,set by Marcello, +olthoiripperkilltask,Aelrynth,,,Olthoi Ripper Kill Task,,TRUE,72000,-1,set by Marcello, +olthoitokenexp,Aelrynth,,,Weekly Olthoi Token of the Experience turn-in,,TRUE,604800,-1,set by Mayor Trenlach, +olthoitokenkey,Aelrynth,,,Weekly Olthoi Token of the key turn-in,,TRUE,604800,-1,set by Mayor Trenlach, +olthoitokenlum,Aelrynth,,,Weekly Olthoi Token of Luminance turn-in,,TRUE,604800,-1,set by Mayor Trenlach, +olthoiveteransmedalturnin,Aelrynth,,,Player has turned in a Olthoi Veterans Medal to the Arcanum Mana-smith,,TRUE,1209600,-1,set by Arcanum Mana-smith, +onadepttest,Aelrynth,,,Player is taking Adept Test,,FALSE,0,1,"set by Aldrion of the Celestial Hand, Khadira of the Eldrytch Web, Shien Genda of the Radiant Blood", +onbrowerkquest,Aelrynth,,,You are on the Browerk Quest.,,TRUE,10800,-1,set by Watcher of the Dead, +oncowtipquest,Aelrynth,,,Player is on the Cow Tipping quest,,FALSE,0,1,set by Dwennon, +ongolemcoralviceroyslayerquest,Aelrynth,,,You are on the Mud Golem Sludge Lord Slayer Quest,,FALSE,0,1,set by Aun Aukherea, +ongolemglacialmargraveslayerquest,Aelrynth,,,You are on the Mud Golem Sludge Lord Slayer Quest,,FALSE,0,1,set by Aun Maerirea, +ongolemironkingpinslayerquest,Aelrynth,,,You are on the Mud Golem Sludge Lord Slayer Quest,,FALSE,0,1,set by Aun Tiulerea, +ongolemmagmaexarchslayerquest,Aelrynth,,,You are on the Mud Golem Sludge Lord Slayer Quest,,FALSE,0,1,set by Aun Autuorea, +ongolemmudsludgelordslayerquest,Aelrynth,,,You are on the Mud Golem Sludge Lord Slayer Quest,,FALSE,0,1,set by Aun Akuarea, +ongolemplatinumkingslayerquest,Aelrynth,,,You are on the Mud Golem Sludge Lord Slayer Quest,,FALSE,0,1,set by Aun Khekierea, +onjesterpart2,Aelrynth,,,quest timer,,FALSE,0,1,set by Jester's Prison Door, +onknighttest,Aelrynth,,,Player is taking Knight Test,,FALSE,0,1,"set by Francesca du Orza, Luciana du Maki, Viviana Fortiore", +onlordtest,Aelrynth,,,Player is taking Lord Test,,FALSE,0,1,"set by Gamri Nightshade, Istonia Charson, Philonius Porbandar", +onmastertest,Aelrynth,,,Player is taking Master Test,,FALSE,0,1,"set by Alicia Bladesworn, Brizinna du Corcosi, Hizuki Tama", +onquest,Aelrynth,,,Ruschk Challenger quest,,FALSE,0,1,set by Ruschk Challenger, +oracleluminancerewardsaccess_1110,Aelrynth,,,Flagged to earn Luminance,,FALSE,0,1,set by Nalicana, +oracleluminancerewardsqueststart_1110,Aelrynth,,,Kill Battle Lord Gregor and collect his Mnemosyne,,FALSE,0,1,set by Nalicana, +oracleportalentry,Aelrynth,,,Flagged to enter Frozen Tomb,,FALSE,0,1,set by Nalicana, +orangemonsterseed,Aelrynth,,,Orange Monster Seed counter,,TRUE,0,5,set by Drozer, +orbasteliary,Aelrynth,,,Asteliary Orb,,TRUE,72000,-1,, +orbenergycrystal,Aelrynth,,,Player has been given the new Energy Crystal,,TRUE,72000,-1,set by Representative of the Singularity, +orbhealingmachine,Aelrynth,,,Healing Machine Orb,,TRUE,72000,-1,, +orderscontactreceived,Aelrynth,,,You have taken the orders from the Renegade Fortress.,,FALSE,0,1,set by A Cluttered Table, +ordersforzrikux_pickup,Aelrynth,,,Player has picked up Orders for Zrikux,,TRUE,72000,-1,, +ordersmorgluukpickedup,Aelrynth,,,Picked up the orders from Morgluuk.,,TRUE,72000,-1,, +orderstorgluukpickedup,Aelrynth,,,Picked up the orders from Torgluuk.,,TRUE,72000,-1,, +ornatefalatacotmedallionpickuptimer,Aelrynth,,,Player has picked up Ornate Falatacot Medallion,,TRUE,72000,-1,, +ornatewritwait,Aelrynth,,,Cooldown for Ornate Armor Writ,,TRUE,2592000,-1,"set by Janaris bint Bazheer, Pak Li-Shung", +oswaldlair,Aelrynth,,,Gained access to Oswald's Lair,,TRUE,72000,-1,set by Chunk of Wood, +oswaldlogicwrong,Aelrynth,,,Failed the Logic Riddle,,FALSE,0,1,"set by Cao Cao, Mu Mu, Po Po and 1 more", +oswaldmanualacquired,Aelrynth,,,Acquired Seven Habits of Effective Adventurers,,FALSE,0,1,, +oswaldmanualcompleted,Aelrynth,,,PERMANENT - Chasing Oswald Quest,,FALSE,0,1,set by Huntsman of Silyun, +oswaldstep1,Aelrynth,,,Finished CSI 1,,TRUE,72000,-1,"set by Ulgrim the Unappreciated, Ulgrim the Unpleasant", +oswaldstep2,Aelrynth,,,Finished CSI 2,,TRUE,72000,-1,"set by Ro Bi-Jor, Apprentice Tailor", +oswaldstep3,Aelrynth,,,Finished CSI 3,,TRUE,72000,-1,set by Celcynd the Dour, +paidcomponentexchanger,Aelrynth,,,Player paid Component Exchanger.,,FALSE,0,1,set by Component Exchanger, +paidrareexchanger,Aelrynth,,,Player paid Rare Exchanger.,,FALSE,0,1,set by Rare Exchanger, +paidrespectstoantiusblackmoor,Aelrynth,,,Respects paid to Antius Blackmoor,,FALSE,0,1,set by Bier of Antius Blackmoor, +palenqualcompleted,Aelrynth,,,This stamp will alert Aun Imeitanua upon use that they have already spoken with him and exchanged their talisman for a weapon.,,TRUE,72000,-1,set by Aun Imeitanua, +palenqualhoeroagiven,Aelrynth,,,This stamp will alert Aun Imeitanua upon give that they have already spoken with him and should return the item.,,TRUE,72000,-1,set by Aun Imeitanua, +palenqualokanegiven,Aelrynth,,,This stamp will alert Aun Imeitanua upon give that they have already spoken with him and should return the item.,,TRUE,72000,-1,set by Aun Imeitanua, +palenqualtaiahagiven,Aelrynth,,,This stamp will alert Aun Imeitanua upon give that they have already spoken with him and should return the item.,,TRUE,72000,-1,set by Aun Imeitanua, +palenqualtewhategiven,Aelrynth,,,This stamp will alert Aun Imeitanua upon give that they have already spoken with him and should return the item.,,TRUE,72000,-1,set by Aun Imeitanua, +palenqualwaaikagiven,Aelrynth,,,This stamp will alert Aun Imeitanua upon give that they have already spoken with him and should return the item.,,TRUE,72000,-1,set by Aun Imeitanua, +pallidseainvasionkey_pickup,Aelrynth,,,Pickup timer for Pallid Sea Invasion Key,,TRUE,72000,-1,, +palliumobtained,Aelrynth,,,Aerfalle's Pallium,,TRUE,72000,-1,, +palmfortdefended1209,Aelrynth,,,Player wait time for Palm Fort.,,TRUE,72000,-1,set by Fort Commander, +palmfortsoldierdead,Aelrynth,,,NPC quest for counting Soldiers death.,,TRUE,0,5,set by Fort Commander, +paradoxcarapacepickup,Aelrynth,,,quest timer,,TRUE,72000,-1,checked by Ethan Wintermaine, +paradoxeggcount,Aelrynth,,,Player stamp for first egg turn in.,,FALSE,0,1,set by Adrien Swiftblade, +paradoxeggpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +paradoxeggstarted,Aelrynth,,,Player has spoke to Adrien Swiftblade.,,FALSE,0,1,set by Adrien Swiftblade, +paradoxeggwait,Aelrynth,,,Player stamp for egg turn in cooldown.,,TRUE,72000,-1,set by Adrien Swiftblade, +paradoxgrubkilltask,Aelrynth,,,Paradox Grub Kill Task,,TRUE,0,50,set by Alicia Swiftblade, +paradoxgrubkilltaskwait,Aelrynth,,,Paradox Grub Kill Task,,TRUE,72000,-1,set by Alicia Swiftblade, +paradoxinfusedpotion_pickup,Aelrynth,,,Player has picked up Paradox infused Potion,,TRUE,72000,-1,, +paradoxnymphkilltask,Aelrynth,,,Paradox Nymph Kill Task,,TRUE,0,50,set by Tomihino, +paradoxnymphkilltaskwait,Aelrynth,,,Paradox Nymph Kill Task,,TRUE,72000,-1,set by Tomihino, +paradoxqueenheadpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +paradoxqueenlair,Aelrynth,,,quest timer,,TRUE,72000,-1,, +paradoxqueenstarted,Aelrynth,,,quest timer,,FALSE,0,1,set by Ethan Wintermaine, +paradoxqueenwait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Ethan Wintermaine, +paradoxtouchedgrubkillcount,Aelrynth,,,Paradox-touched Grub Kill Counter,,TRUE,0,50,, +paradoxtouchedgrubkilltask,Aelrynth,,,Paradox-touched Grub Kill Task,,TRUE,72000,-1,, +paradoxtouchednymphkillcount,Aelrynth,,,Paradox-touched Nymph Kill Counter,,TRUE,0,50,, +paradoxtouchednymphkilltask,Aelrynth,,,Paradox-touched Nymph Kill Task,,TRUE,72000,-1,, +paragonstarted,Aelrynth,,,quest timer,,FALSE,0,1,set by Summercrown, +paragonweapons,Aelrynth,,,quest timer,,TRUE,0,51,set by Summercrown, +parfarrailfragment_pickup,Aelrynth,,,Player has picked up the Parfarrail Fragment,,TRUE,72000,-1,, +passwordvitriaka,Aelrynth,,,Have Vitriaka's password.,,TRUE,72000,-1,checked by Torch, +pathwardencomplete,Aelrynth,,,Visited the Pathwarden,,FALSE,0,1,"set by Pathwarden Koro Ijida, Pathwarden Qanara bint Qolosh, Pathwarden Thierra Molanti and 1 more", +pathwardenfound1111,Aelrynth,,,Player talked to pathwarden greeter,,FALSE,0,1,"set by Pathwarden Koro Ijida, Pathwarden Qanara bint Qolosh, Pathwarden Thierra Molanti and 1 more", +pauldronlugian,Aelrynth,,,Lugian Commander Trophy,,TRUE,72000,-1,, +pedestalhealingmachine,Aelrynth,,,Healing Machine Pedestal,,TRUE,72000,-1,, +pendantrenegade,Aelrynth,,,Player is wearing the PendantRenegade,,FALSE,0,1,set by Renegade Pendant, +perfectlyagedcoveciderquest,Aelrynth,,,Sea Temple Catacombs Quest,,TRUE,72000,-1,, +petdrudgecompleted_1111,Aelrynth,,,Completed Nen Ai's Pet Drudge,,TRUE,72000,-1,set by Nen Ai, +petgolemcastspellonowner,Aelrynth,,,Pet Golem cast spell on Pet Owner,,TRUE,30,-1,"set by Artisan Alchemist's Golem, Artisan Cook's Golem, Artisan Fletcher's Golem and 9 more", +petpenguinstart,Aelrynth,,,Started Pet Penguin Quest,,FALSE,0,1,set by Mr. P, +petpenguinwait,Aelrynth,,,Completed Pet Penguin Quest,,TRUE,2332800,-1,set by Mr. P, +petsave,Aelrynth,,,quest timer,,TRUE,0,7,, +petshopquestacquired,Aelrynth,,,Player is on Pet Shop Quest,,FALSE,0,1,set by Larinne Kerendova, +petshopquestcompleted,Aelrynth,,,Player has given all four letters to Larinne Kerendova and completed quest,,TRUE,72000,-1,set by Larinne Kerendova, +petshopquestcounter,Aelrynth,,,Pet Shop Quest Turnins,,TRUE,0,4,set by Larinne Kerendova, +pheraionssanctum_flag,Aelrynth,,,Access granted to Pheraions Sanctum,,FALSE,0,1,set by Hassim, +pheraionssanctumquest_start,Aelrynth,,,Player has started Pheraions Sanctum Quest,,FALSE,0,1,set by Hassim, +pheraionssanctumquest_wait,Aelrynth,,,Player has completed Pheraions Sanctum Quest,,TRUE,72000,-1,set by Hassim, +philterhizkritaken,Aelrynth,,,You've picked up the ancient philter. Now go collect the blood from the well of bloody tears.,,TRUE,300,-1,, +phyntoshivecomplete1109,Aelrynth,,,Collect Phyntos Hive Splinters,,TRUE,72000,-1,"set by Kenji, Narris, Zahid al-Din", +phyntoshoneycomplete1109,Aelrynth,,,Collect Phyntos Honey,,TRUE,72000,-1,"set by Kenji, Narris, Zahid al-Din", +phyntoslarvakillcount,Aelrynth,,,Phyntos Larva Kill Counter,,TRUE,0,20,, +phyntoslarvakilltask,Aelrynth,,,Phyntos Larva Kill Task,,TRUE,72000,-1,, +pickedupamethystcradle,Aelrynth,,,You picked up an Amethyst Cradle.,,TRUE,72000,-1,, +pickedupaquamarineprisms,Aelrynth,,,You picked up a cluster of Aquamarine Prisms.,,TRUE,72000,-1,, +pickedupazaxistoken,Aelrynth,,,Pickup timer for Azaxis Token,,TRUE,72000,-1,, +pickedupbookmoarsextremeuntranslated,Aelrynth,,,You picked up an Untranslated Tome.,,TRUE,72000,-1,, +pickedupbookmoarshighuntranslated,Aelrynth,,,You picked up an Untranslated Tome.,,TRUE,72000,-1,, +pickedupbookmoarslowuntranslated,Aelrynth,,,You picked up an Untranslated Tome.,,TRUE,72000,-1,, +pickedupbookmoarsmiduntranslated,Aelrynth,,,You picked up an Untranslated Tome.,,TRUE,72000,-1,, +pickedupbookmoarsnewbieuntranslated,Aelrynth,,,You picked up an Untranslated Tome.,,TRUE,72000,-1,, +pickedupbraceletrepugnant,Aelrynth,,,You've picked up the Repugnant Bracelet.,,TRUE,72000,-1,, +pickedupbreastplate0806,Aelrynth,,,quest timer,,TRUE,72000,-1,, +pickedupbroodmatrontail,Aelrynth,,,Picked up Brood Matron tail,,TRUE,72000,-1,, +pickedupbroodmatrontarsus,Aelrynth,,,Picked up Brood Matron tarsus,,TRUE,72000,-1,, +pickedupbroodmatrontibia,Aelrynth,,,Picked up Brood Matron tibia,,TRUE,72000,-1,, +pickedupbroodqueencarapace,Aelrynth,,,Picked up Brood Queen carapace,,TRUE,72000,-1,, +pickedupbroodqueenclaw,Aelrynth,,,Picked up Brood Queen claw,,TRUE,72000,-1,, +pickedupbroodqueencrest,Aelrynth,,,Picked up Brood Queen crest,,TRUE,72000,-1,, +pickedupbroodqueenfemur,Aelrynth,,,Picked up Brood Queen femur,,TRUE,72000,-1,, +pickedupbroodqueenhead,Aelrynth,,,Picked up Brood Queen Head,,TRUE,72000,-1,, +pickedupbroodqueenmetathorax,Aelrynth,,,Picked up Brood Queen Metathoraxr,,TRUE,72000,-1,, +pickedupburunfetish,Aelrynth,,,You have taken a Burun Fetish from the corpse of a raiding Burun.,,TRUE,72000,-1,, +pickedupchrysoberyl,Aelrynth,,,Picked up Chryoberyl,,TRUE,72000,-1,, +pickedupclawgibbering,Aelrynth,,,You have picked up the Gibbering Claw.,,TRUE,72000,-1,, +pickedupcoloredegg,Aelrynth,Picked up a Colored Egg,,Picked up a Colored Egg,,TRUE,72000,-1,, +pickedupcrowleyschampiontoken,Aelrynth,,,Pickup timer for Crowley's Champion Token,,TRUE,72000,-1,, +pickedupcrownbaronnuvillus,Aelrynth,,,You picked up the crown of Baron Nuvillus.,,TRUE,72000,-1,, +pickedupdailantiumcrystal,Aelrynth,,,Picked up a Dailantium Crystal.,,TRUE,72000,-1,, +pickedupdanshakibelongings,Aelrynth,,,Picked up DanshaKi's Belongings,,TRUE,72000,-1,, +pickedupdarktreecrystal,Aelrynth,,,picked up 1st crystal.,,TRUE,72000,-1,checked by Lartorus, +pickedupdarktuskerpaw,Aelrynth,,,Player has picked up Dark Tusker Paw,,TRUE,72000,-1,, +pickedupdemonswarmmatrontoken,Aelrynth,,,Pickup timer for Demon Swarm Matron Token,,TRUE,72000,-1,, +pickedupdonnarionkey,Aelrynth,,,Pickup timer for Donnarion Key,,TRUE,3600,-1,, +pickedupemeraldclasp,Aelrynth,,,You picked up an Emerald Clasp.,,TRUE,72000,-1,, +pickedupentemarreshead,Aelrynth,,,Picked up Baron Entemarres Head,,TRUE,72000,-1,, +pickedupgemportalsunkenmerenewbie,Aelrynth,,,You picked up an Adjanite Gem.,,TRUE,72000,-1,, +pickedupgirthdrudgefight,Aelrynth,,,You've picked up the Drudge Fight Belt.,,TRUE,72000,-1,, +pickedupgolemheartmagmadfd,Aelrynth,,,You've picked up Scold's magma golem heart.,,TRUE,72000,-1,, +pickedupharoushkey,Aelrynth,,,Pickup timer for Haroush Key,,TRUE,3600,-1,, +pickedupheadhomunculus,Aelrynth,,,You have picked up the Head of the Homunculus.,,TRUE,72000,-1,, +pickeduphiyppickaxe,Aelrynth,,,Picked up pickaxe,,TRUE,72000,-1,, +pickedupjadedais,Aelrynth,,,You picked up a Jade Dais.,,TRUE,72000,-1,, +pickedupjoroshikey,Aelrynth,,,Pickup timer for Joroshi Key,,TRUE,3600,-1,, +pickedupjournalgarethdain,Aelrynth,,,Picked up Gareth Dain's Journal.,,TRUE,72000,-1,, +pickedupjournalvitriaka,Aelrynth,,,Picked up Vitriaka's Journal.,,TRUE,72000,-1,, +pickedupkeyyaruldi,Aelrynth,,,You have picked up the Key to Yaruldi's Hoarde.,,TRUE,72000,-1,, +pickedupkingscrown,Aelrynth,,,Pickup timer for King's Crown,,TRUE,72000,-1,, +pickedupledger0806,Aelrynth,,,quest timer,,TRUE,72000,-1,, +pickedupmapauberean,Aelrynth,,,You picked up the Map of Auberean.,,TRUE,72000,-1,, +pickedupmarkerboss10x,Aelrynth,,,Pickup timer for Gladiator Diemos Token,,TRUE,518400,-1,, +pickedupmosswartstonedeath,Aelrynth,,,You have taken a Mosswart Mourning Stone from a Mosswart Corpse.,,TRUE,72000,-1,, +pickedupmosswartstonethanks,Aelrynth,,,You have picked up a Mosswart Thanking Stone.,,TRUE,72000,-1,, +pickedupnecklaceadjanite,Aelrynth,,,You picked up a Labyrinthine Necklace.,,TRUE,72000,-1,, +pickedupnecklaceshadowstone,Aelrynth,,,You've picked up the Shadow Stone Necklace.,,TRUE,72000,-1,, +pickedupnotebethelbrother,Aelrynth,,,You've picked up Bewren's Journal.,,TRUE,72000,-1,, +pickedupnotebethelcultist,Aelrynth,,,You've picked up Jaeget's Journal.,,TRUE,72000,-1,, +pickedupolthoifemur,Aelrynth,,,Picked up note,,TRUE,72000,-1,, +pickedupolthoilongclaw,Aelrynth,,,Picked up note,,TRUE,72000,-1,, +pickedupolthoiscoutnote1,Aelrynth,,,Picked up note,,TRUE,72000,-1,, +pickedupolthoiscoutnote2,Aelrynth,,,Picked up note,,TRUE,72000,-1,, +pickedupolthoiscoutnote3,Aelrynth,,,Picked up note,,TRUE,72000,-1,, +pickedupolthoiscoutnote4,Aelrynth,,,Picked up note,,TRUE,72000,-1,, +pickedupolthoiscoutnote5,Aelrynth,,,Picked up note,,TRUE,72000,-1,, +pickedupolthoiscoutnote6,Aelrynth,,,Picked up note,,TRUE,72000,-1,, +pickedupolthoiscoutnote7,Aelrynth,,,Picked up note,,TRUE,72000,-1,, +pickedupolthoiscoutnote8,Aelrynth,,,Picked up note,,TRUE,72000,-1,, +pickedupolthoistabclaw,Aelrynth,,,Picked up note,,TRUE,72000,-1,, +pickedupoverlordsword,Aelrynth,,,Picked up Tumerok Overlord's Sword,,TRUE,72000,-1,, +pickedupphatlewt,Aelrynth,,,Picked up Ulgrim's Stout,,TRUE,72000,-1,, +pickedupponmiconfession,Aelrynth,,,Picked up Pon Mi's confession,,TRUE,72000,-1,set by Corpse of Pon Mi, +pickeduppumpkinkingtoken,Aelrynth,,,Pickup timer for Pumpkin King Token,,TRUE,72000,-1,, +pickedupratkingstail,Aelrynth,,,Pickup timer for Rat King's Tail,,TRUE,72000,-1,, +pickeduprot2crystal,Aelrynth,,,Picked up ROT2 crystal,,TRUE,72000,-1,, +pickeduprottenegg,Aelrynth,Picked up a Rotten Egg,,Picked up a Rotten Egg,,TRUE,72000,-1,, +pickedupruschkfuneraryfetish,Aelrynth,,,Ruschk Funerary Fetish pickup timer,,TRUE,72000,-1,, +pickedupsarchophagushookable,Aelrynth,,,You picked up a coffin.,,TRUE,72000,-1,, +pickedupsarcophagushookable,Aelrynth,,,You've picked up the Shadow Stone Necklace.,,TRUE,72000,-1,, +pickedupshadeironorehammer,Aelrynth,,,Picked up Shade Iron Ore Hammer,,TRUE,72000,-1,, +pickedupsoulshattercrystal,Aelrynth,,,picked up 3rd crystal,,TRUE,72000,-1,checked by Lartorus, +pickedupspearyaja,Aelrynth,,,You have picked up Yaja's Reach.,,TRUE,72000,-1,, +pickedupstonefiststoken,Aelrynth,,,Pickup timer for Stone Fists Token,,TRUE,72000,-1,, +pickeduptasselmagic,Aelrynth,,,You've picked up a Woven Tassel of Sound Mind.,,TRUE,72000,-1,, +pickeduptasselmelee,Aelrynth,,,You've picked up a Woven Tassel of Discord.,,TRUE,72000,-1,, +pickeduptasselmissile,Aelrynth,,,You've picked up a Woven Tassel of Far Sight.,,TRUE,72000,-1,, +pickedupthemastertoken,Aelrynth,,,Pickup timer for The Master Token,,TRUE,72000,-1,, +pickedupthunderchickentoken,Aelrynth,,,Pickup timer for Thunder Chicken Token,,TRUE,72000,-1,, +pickeduptokenoublietteboss_0112,Aelrynth,,,quest timer,,TRUE,72000,-1,checked by Shade of Terelev, +pickeduptokenprodigaltusker_0807,Aelrynth,,,Player has picked up Prodigal Tusker Token,,TRUE,72000,-1,, +pickeduptokentitlegraverobber,Aelrynth,,,You picked up the Grave Robber Title Token.,,TRUE,72000,-1,, +pickedupulgrimsring,Aelrynth,,,Picked up Ulgrim's Stout,,TRUE,72000,-1,, +pickedupulgrimsstout,Aelrynth,,,Picked up Ulgrim's Stout,,TRUE,72000,-1,, +pickedupumbralcruciblebase,Aelrynth,Umbral Crucible Base Pickup,,Umbral Crucible Base pickup timer,,TRUE,72000,-1,, +pickedupumbralcrucibletop,Aelrynth,Umbral Crucible Top Pickup,,Umbral Crucible Top pickup timer,,TRUE,72000,-1,, +pickedupvalaracrystal,Aelrynth,,,picked up 2nd crystal,,TRUE,72000,-1,checked by Lartorus, +pickedupverymadcowtoken,Aelrynth,,,Pickup timer for Very Mad Cow Token,,TRUE,72000,-1,, +pickedupvirindisignet,Aelrynth,,,Picked up the signet,,TRUE,72000,-1,checked by Mage Syltyn Rillon, +pickedupzharalimemblem,Aelrynth,,,You've picked up a Crest of the Shagar Zharala.,,TRUE,72000,-1,checked by Yalik Ibn Ujsef, +pickedupzharalimforemanjournal,Aelrynth,,,You've picked up the Zharalim Foreman's Journal.,,TRUE,72000,-1,, +pickedupzharalimmasterjournal,Aelrynth,,,You've picked up the Zharalim Master's Journal.,,TRUE,72000,-1,, +pickupcastlepietruslogbook,Aelrynth,,,Picked up Castle Pietrus Log Book,,TRUE,1123200,-1,, +pickupdamagedstoneinfuser,Aelrynth,,,Picked up Damaged Stone Infuser,,TRUE,72000,-1,, +pickupdrudgefortblueprints,Aelrynth,,,Player has access to pick up Blueprints,,FALSE,0,1,set by Sergeant Shanks, +pickupnightbrieressence,Aelrynth,,,quest timer,,TRUE,14400,-1,, +pickupnorshuntyressence,Aelrynth,,,quest timer,,TRUE,14400,-1,, +pickuppenguinegg,Aelrynth,,,Flagged to pick up Penguin Egg,,FALSE,0,1,set by Especially Famished Eater, +pickupruschktotem,Aelrynth,,,Picked up Ruschk Totem. - Completed,,TRUE,72000,-1,, +pickuptumerokrecordbook,Aelrynth,,,Picked up Tumerok Record Book,,TRUE,1123200,-1,, +pickupwindfuryessence,Aelrynth,,,quest timer,,TRUE,14400,-1,, +pickupzerzelikyressence,Aelrynth,,,quest timer,,TRUE,14400,-1,, +pieceofknathcorepickuptimer,Aelrynth,,,Picked up Piece of Knath Core,,TRUE,72000,-1,, +pieceofpaperturnin,Aelrynth,,,Player has turned in the Piece of Paper to Researcher Tharin.,,FALSE,0,1,set by Researcher Tharin, +pileofrandompartspickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +plainmukkirorbnotespickup,Aelrynth,,,Timer for Alizari's Encoded notes pickup,,TRUE,72000,-1,, +platearmoredillokillcount,Aelrynth,,,Plate Armoredillo Kill Counter,,TRUE,0,25,set by Saqr, +platearmoredillokilltask,Aelrynth,,,Plate Armoredillo Kill Task,,TRUE,72000,-1,set by Saqr, +platinumgolemmountainkingkillcount,Aelrynth,,,Platinum Golem Mountain King Kill Counter,,TRUE,0,5,, +platinumgolemmountainkingkilltask,Aelrynth,,,Platinum Golem Mountain King Kill Task,,TRUE,72000,-1,, +platinuminvaderlordhelm,Aelrynth,,,Timer for Platinum Lord Helm,,TRUE,72000,-1,, +platinumknightmedallion,Aelrynth,,,Defense of Zaikhal Medallion Pickup Timer Platinum,,TRUE,72000,-1,set by Jun Sawashima, +platinumlegionchestkey,Aelrynth,,,Pick Up Key for Platinum Chest,,TRUE,72000,-1,, +platinumlegiondoorkey,Aelrynth,,,Pick Up Key for Door to Platinum Legion,,TRUE,72000,-1,, +playerreceivedrossumortatoken,Aelrynth,,,Check to see if player has already received Rossu Morta Token,,FALSE,0,1,set by Meerana du Renari, +playerreceivedsilverantoken,Aelrynth,,,Player has picked up a Silveran Token,,FALSE,0,1,"set by Silveran Atlatl Token, Silveran Axe Token, Silveran Bow Token and 8 more", +playerreceivedwhisperingbladetoken,Aelrynth,,,Check to see if player has already received Whispering Blade Token,,FALSE,0,1,set by Eddred the Wolf, +pluckerofeyes_repeat,Aelrynth,,,Player as completed Eye of Tthuun Quest once.,,FALSE,0,1,set by Tamara du Cinghalle, +pohwrongitemturnin,Aelrynth,,,Player has turned the wrong item into Pillar of Heart,,TRUE,0,3,set by Pillar of the Heart, +polardillokills,Aelrynth,,,Polar Dillo Kill Counter,,TRUE,0,10,set by Alessandro Mardor, +polardillotask,Aelrynth,,,Polar Dillo Kill Task Main Flag,,TRUE,72000,-1,set by Alessandro Mardor, +polarursuin,Aelrynth,,,Polar Ursuin Kill Task Main Flag Timer,,TRUE,72000,-1,set by Mariabella Varanese, +polarursuinkillcount,Aelrynth,,,Polar Ursuin Kill Counter,,TRUE,0,25,set by Mariabella Varanese, +polenoir1,Aelrynth,,,You're wielding the broken fishing pole.,,FALSE,0,1,set by Broken Fishing Pole, +polenoir1pickup,Aelrynth,,,You've picked up the broken fishing pole.,,TRUE,72000,-1,checked by Guard Chandler Hammett, +pookytokenpickuptimer,Aelrynth,Picked up Pooky Token,,Picked up Pooky Token,,TRUE,2332800,-1,, +popofirstspeak,Aelrynth,,,TBD,,FALSE,0,1,, +poporight,Aelrynth,,,Correct answer on Po Po,,FALSE,0,1,set by Po Po, +portalasugertemplepermissiongiven,Aelrynth,,,Player can go into Asuger Temple,,FALSE,0,1,set by Sir Rylanan, +portaldarklightpermissiongiven,Aelrynth,,,Player has picked up the husk,,FALSE,0,1,set by Dame Tsaya, +portaloubliettebypass,Aelrynth,,,Player can now enter the Oubliette.,,FALSE,0,1,set by Oubliette Gatekeeper, +portalpalenqualpermissiongiven,Aelrynth,,,This flag will alert the portal that players are allowed entry to the dungeon.,,FALSE,0,1,set by Aun Shimauri, +portalregicidewitshirepermissiongiven,Aelrynth,,,Player has permission to enter the portal to the bottom of the Witshire Dungeon,,FALSE,0,1,"set by Dame Tsaya, Sir Rylanan, Sir Tenshin", +portalservitoritemsstarted,Aelrynth,,,Player has talked to the Portal Servitor.,,FALSE,0,1,set by Portal Servitor, +portalspacepermissiongiven,Aelrynth,,,Player has received permission to enter the Portal Space dungeon. Created for the March 2004 revision.,,FALSE,0,1,set by Aun Aulakhe, +portalspaceriftsdone,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Marcus Manfried, +portalspaceriftsstarted,Aelrynth,,,quest timer,,FALSE,0,1,set by Marcus Manfried, +presentraidscounter,Aelrynth,,,quest timer,,TRUE,0,9,set by Drudge Balloon, +presentraidsreset,Aelrynth,,,Reward giver reset timer,,TRUE,300,-1,"set by Drudge Present Raids Reset Stopgap, Gurog Present Raids Reset Stopgap", +prismaticstonepickedup,Aelrynth,,,Player has picked up the uncut stone.,,TRUE,72000,-1,, +prismfragmentacidgiven,Aelrynth,,,Player has turned in the Acid Fragment,,FALSE,0,1,"set by Agent Dravos, Agent of the Arcanum", +prismfragmentacidpickup,Aelrynth,,,Player has picked up the Acid Fragment,,TRUE,72000,-1,, +prismfragmentfiregiven,Aelrynth,,,Player has turned in the Fire Fragment,,FALSE,0,1,"set by Agent Dravos, Agent of the Arcanum", +prismfragmentfirepickup,Aelrynth,,,Player has picked up the Fire Fragment,,TRUE,72000,-1,, +prismfragmenticegiven,Aelrynth,,,Player has turned in the Ice Fragment,,FALSE,0,1,"set by Agent Dravos, Agent of the Arcanum", +prismfragmenticepickup,Aelrynth,,,Player has picked up the Ice Fragment,,TRUE,72000,-1,, +prismfragmentlightninggiven,Aelrynth,,,Player has turned in the Lightning Fragment,,FALSE,0,1,"set by Agent Dravos, Agent of the Arcanum", +prismfragmentlightningpickup,Aelrynth,,,Player has picked up the Lightning Fragment,,TRUE,72000,-1,, +privatechambersshortcut,Aelrynth,,,quest timer,,TRUE,7200,-1,, +prodigalharby_completed,Aelrynth,,,Player has went through Portal after defeating Prodigal Harbinger.,,FALSE,0,1,checked by Vincadi, +prodigalharbykillshot,Aelrynth,,,Player has the Killshot on Prodigal Harbinger.,,FALSE,0,1,set by Harbinger, +prodigalhumancompleted_1107,Aelrynth,,,Player wait timer for completing Aerbaxs Prodigal Human,,TRUE,72000,-1,set by Ryukai Hiro, +prodigalhumanpotionacquired_1107,Aelrynth,,,Player has acquired the Paradox infused potion,,FALSE,0,1,set by Dojiro Sangi, +prodigalhumanrepeat_1107,Aelrynth,,,Player has completed Aerbaxs Prodigal Human at least once,,FALSE,0,1,checked by Ryukai Hiro, +prodigalmonougacompleted0707,Aelrynth,,,Player has completed Prodigal Monouga,,TRUE,72000,-1,set by Corporal Liao Chen, +prodigalmonougarepeat0707,Aelrynth,,,Player has completed Monouga Laboratory at least once before,,FALSE,0,1,set by Corporal Liao Chen, +prodigalmonougastarted0707,Aelrynth,,,Player has started Prodigal Monouga,,FALSE,0,1,set by Corporal Liao Chen, +prodigalshadowflag,Aelrynth,,,Player flag for upper Teleport Statue.,,FALSE,0,1,"set by Statue of Bael'Zharon, the Hopeslayer", +prodigalshadowrepeat,Aelrynth,,,Player has completed Aerbaxs Prodigal Shadow at least once.,,FALSE,0,1,set by Riordin Nightbane, +progenitorcrystal1pickup,Aelrynth,,,Picked up Progenitor Crystal,,TRUE,72000,-1,, +progenitorcrystal2pickup,Aelrynth,,,Picked up Progenitor Crystal,,TRUE,72000,-1,, +progenitorcrystal3pickup,Aelrynth,,,Picked up Progenitor Crystal,,TRUE,72000,-1,, +progenitorcrystal4pickup,Aelrynth,,,Picked up Progenitor Crystal,,TRUE,72000,-1,, +progenitorcrystal5pickup,Aelrynth,,,Picked up Progenitor Crystal,,TRUE,72000,-1,, +progenitorcrystal6pickup,Aelrynth,,,Picked up Progenitor Crystal,,TRUE,72000,-1,, +progenitoringotturnin,Aelrynth,,,Turned in Progenitor Ingot,,FALSE,0,1,set by Shade of Ja'qu, +progenitoringotwait,Aelrynth,,,Shade of Jaqu wait timer,,TRUE,72000,-1,set by Shade of Ja'qu, +progenitorsichorpickuptimer,Aelrynth,,,Picked up Progenitors Ichor,,TRUE,72000,-1,, +protectionorb,Aelrynth,,,Picked up Protection Orb,,FALSE,0,1,, +provinggrounds,Aelrynth,,,Player may enter the proving grounds,,FALSE,0,1,set by Platinum Golem, +provinggroundscomplete,Aelrynth,,,Player has finished the proving grounds,,TRUE,10800,-1,checked by Asheron's Platinum Golem, +provinggroundsextreme,Aelrynth,,,Unused Questflag,,TRUE,10800,-1,, +provinggroundsfloorwalk,Aelrynth,,,Player has completed the floor walk,,TRUE,10800,-1,, +provinggroundshigh,Aelrynth,,,Unused Questflag,,TRUE,10800,-1,, +provinggroundslow,Aelrynth,,,Unused Questflag,,TRUE,10800,-1,, +provinggroundsmid,Aelrynth,,,Unused Questflag,,TRUE,10800,-1,, +provinggroundsrollingdeath,Aelrynth,,,Player has finished the rolling death room,,TRUE,10800,-1,, +pumpkinkingcritterskilled,Aelrynth,,,Player has killed a creature found in Pumpkin King,,TRUE,0,-1,set by Pumpkin King Event Watcher, +putridmoarkillcount,Aelrynth,,,Putrid Moar Kill Counter,,TRUE,0,25,, +putridmoarkilltask,Aelrynth,,,Putrid Moar Kill Task,,TRUE,72000,-1,, +putridseainvasionkey_pickup,Aelrynth,,,Pickup timer for Putrid Sea Invasion Key,,TRUE,72000,-1,, +pyrealmoteayan,Aelrynth,,,Picked up an Pyreal Mote in Ayan Baqur Halls of Metos.,,TRUE,72000,-1,, +pyrealmoteayangiven,Aelrynth,Metos Motes,https://acportalstorm.com/wiki/Metos_Motes,Pyreal Mote in Ayan Baquar Halls of Metos given. See Golem Warden of Metos.,,FALSE,0,1,set by Golem Warden of Metos, +pyrealmotewai,Aelrynth,,,Picked up an Pyreal Mote in Wai Jhou Halls of Metos.,,TRUE,72000,-1,, +pyrealmotewaigiven,Aelrynth,,,Pyreal Mote in Wai Jhou Halls of Metos given.,,FALSE,0,1,set by Golem Warden of Metos, +qinxikitbeaten,Aelrynth,,,You've beaten the Qin Xikit temple.,,FALSE,0,1,set by Guardian, +qinxikitcomplete,Aelrynth,,,You've received the reward for the Qin Xikit Temple.,,TRUE,72000,-1,"set by Sarcophagus of High Matriarch, Qin Xikit", +qualityimprintingmote_pickup,Aelrynth,,,Player has picked up the Quality Imprinting Mote at the bottom of Crystal Mine Extreme.,,TRUE,72000,-1,, +queenelysaindangercompleted,Aelrynth,,,Player cooldown for Queen Elysa in Danger,,TRUE,72000,-1,set by Lord Dargeth, +queenelysaindangergaveyuudaibow,Aelrynth,,,Player gave Yuudai the Bow,,FALSE,0,1,set by Yuudai, +queenelysaindangerstart,Aelrynth,,,Player started to Queen Elysa in Danger,,FALSE,0,1,set by Lord Dargeth, +queenelysaindangertalkelysa,Aelrynth,,,Player talked Queen Elysa,,FALSE,0,1,set by Elysa Strathelar, +queenelysaindangertalkmessenger,Aelrynth,,,Player talked to Stranger,,FALSE,0,1,set by Messenger for The Stranger, +queenelysaindangertalkyuudai,Aelrynth,,,Player talked to Yuudai.,,FALSE,0,1,set by Yuudai, +questbanderlinghauntacquired0105,Aelrynth,,,Player is on Banderling Haunt Quest,,FALSE,0,1,set by Cyphis Suldow, +questbanderlinghauntcompleted0105,Aelrynth,,,Player has given the Murky Gem to Cyphis and completed quest,,TRUE,72000,-1,set by Cyphis Suldow, +questlittlestniffisnoteacquired1204,Aelrynth,,,You have acquired the Littlest Niffis note!,,TRUE,72000,-1,, +questreconnaissanceacquired0105,Aelrynth,,,Player is on Reconnaissance quest.,,FALSE,0,1,set by Aludi al-Jaladh, +questreconnaissancecompleted0105,Aelrynth,,,Player has given the Flying Machine Plans to Aludi and completed the quest.,,TRUE,72000,-1,set by Aludi al-Jaladh, +questrewardtimerone,Aelrynth,,,1 hour quest for contract testing.,,TRUE,3600,-1,, +questrumubaspear,Aelrynth,,,Spear Quest,,TRUE,72000,-1,set by Rumuba the Mosswart, +questzaikhaldefenseacquired,Aelrynth,,,Spoke with Jun Sawashima to start Zaikhal Defense,,FALSE,0,1,set by Jun Sawashima, +quiddityfragnorth,Aelrynth,,,1 piece of the purple fragment of pulsing energy.,,TRUE,72000,-1,, +quiddityfragsouth,Aelrynth,,,1 piece of the purple fragment of pulsing energy.,,TRUE,72000,-1,, +quiddityseedquestflag,Aelrynth,,,Flag for Quiddity Seed Quests,,FALSE,0,1,set by Emissary of Asheron, +rabbithutchkey,Aelrynth,,,Picked up Rabbit Hutch Key,,TRUE,72000,-1,, +radiantbloodmember,Aelrynth,,,Player is a member of Radiant Blood,,FALSE,0,1,set by Ayesha of the Radiant Blood, +radiantmanainfusionpickup_0209,Aelrynth,,,Player pickup timer for Radiant Mana Infusion.,,TRUE,72000,-1,, +radiantshardgiven,Aelrynth,,,Radiant Shard given to Lurza,,FALSE,0,1,set by Lurza, +rangedmasterychange,Aelrynth,,,Changed Ranged Mastery.,,FALSE,0,1,, +rankseainvasionkey_pickup,Aelrynth,,,Pickup timer for Rank Sea Invasion Key,,TRUE,72000,-1,, +rarecrystallineshardturnin,Aelrynth,,,Turned in Rare Crystalline Shard,,TRUE,72000,-1,set by Tokashi Ando, +raregamekillcount,Aelrynth,,,Rare Game Kill Counter,,TRUE,0,50,, +raregamekilltask,Aelrynth,,,Rare Game Kill Task,,TRUE,72000,-1,, +ratcatcherquestacquired,Aelrynth,,,Player is on Rat Catcher Quest,,FALSE,0,1,set by Lo Raen, +ratcatcherquestcompleted,Aelrynth,,,Player has completed the Rat Catcher Quest.,,TRUE,72000,-1,set by Lo Raen, +ratcatcherquestcounter,Aelrynth,,,Rat Catcher Counter,,TRUE,0,7,set by Lo Raen, +ravenfragment,Aelrynth,,,Pickup timer for Raven Fragment - Sepulcher of Nightmares,,TRUE,72000,-1,, +ravenouseaterjaw,Aelrynth,,,Ravenous Eater Jaw,,TRUE,72000,-1,checked by Clemenza, +recallsingularitycaul,Aelrynth,,,Picked up Recall Singularity Bore Recall.,,FALSE,0,1,, +recalltuskerisland,Aelrynth,,,Received the spell to return to Tusker Island.,,FALSE,0,1,set by Statue of Artificer's Wish, +receivedarcanepedestal,Aelrynth,,,Player has been given Arcane Pedestal and cannot pick up more for 2 weeks.,,TRUE,72000,-1,set by Slithe Tradittor, +receiveddecorationderethmapunframed,Aelrynth,,,Player has been given unframed Dereth Map and cannot pick up more for 2 weeks.,,TRUE,72000,-1,set by Alatar Locke, +receivedkiviklirarmor,Aelrynth,,,You've used the Eye.,,TRUE,72000,-1,"set by Sarcophagus of High Matriarch, Kivik Lir", +receivedliazkarmor,Aelrynth,,,Player has received the armor for Liazk Itzi's temple.,,TRUE,72000,-1,"set by Sarcophagus of High Matriarch, Liazk Itzi", +receivednewyearsgift,Aelrynth,,,Cooldown for New Years Gift,,TRUE,25920000,-1,set by Rayeesh the Holiday Planner, +receivednewyearsgift0105,Aelrynth,,,You have received a New Year's gift!,,FALSE,0,1,, +receivedpieceofpaper,Aelrynth,,,Player has received the Piece of Paper from Pile of Stained Papers.,,FALSE,0,1,set by Pile of Stained Papers, +receivedsmallicetotem,Aelrynth,,,Player received Small Ice Totem,,FALSE,0,1,set by Ruschk Ice Totem, +receivedthorstenarmorarmor,Aelrynth,,,Player has completed obtaining replica of Thorsten's Armor,,TRUE,72000,-1,set by Lia Tze, +receivedthorstenaxe,Aelrynth,,,Player has completed obtaining replica of Thorsten's Axe,,TRUE,72000,-1,set by Tai Wo, +receivedtitleinitiateoftheblade,Aelrynth,,,Player has Received the Title Initiate of the Blade.,,FALSE,0,1,"set by Ookami Kiri, Sayuji Jina", +receivedtoolonyxcutting,Aelrynth,,,You received an Onyx Cutting Tool from Fanzen San.,,TRUE,72000,-1,set by Fanzen San the Translator, +receivedwaxthorsten,Aelrynth,,,Player has recvd wax to mould Thorsten armor or axe,,TRUE,72000,-1,"set by Lia Tze, Tai Wo", +recruitsent,Aelrynth,,,Player has finished all quests in Area B Senior Guard has sent him to Area C.,,FALSE,0,1,set by Senior Guard, +redbloodgem,Aelrynth,,,Ricardo's Blood Gem - Red,,TRUE,72000,-1,, +redbullcomplete,Aelrynth,,,Red Bull Complete,,FALSE,0,1,set by Grand Knight, +redfireinfusion,Aelrynth,,,Red Fire SOLL Infusion,,TRUE,72000,-1,, +redletterinprogress,Aelrynth,Turn in Timer/Counter for Scarlet Red Letters,,Turn in Timer/Counter for Scarlet Red Letters,,TRUE,604800,100,, +redletterturnins,Aelrynth,Non-Quest,https://acportalstorm.com/wiki/Non-Quest,Counter for Scarlet Red Letter turn ins. See Black Hill Collector; Yukara Miko the Collector; Collector.,Counter for Scarlet Red Letter turn ins.,TRUE,0,100,"set by Black Hill Collector, Collector, Yukara Miko the Collector", +redletterturnintimer,Aelrynth,Non-Quest,https://acportalstorm.com/wiki/Non-Quest,Countdown timer for Scarlet Red Letter turn ins. See Collector; Yukara Miko the Collector; Black Hill Collector.,Countdown timer for Scarlet Red Letter turn ins.,TRUE,604800,-1,"set by Black Hill Collector, Collector, Yukara Miko the Collector", +redmonsterseed,Aelrynth,,,Red Monster Seed counter,,TRUE,0,5,set by Dionaea, +redspiremoarsmencomplete_0508,Aelrynth,,,Player has completed the Redspire portion of Moarsmen on the Shores,,TRUE,72000,-1,set by Guard Liaza, +redveinedgrubtaskwait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Guliant, +reedsharkhuntingneftetkillcount,Aelrynth,,,Reedshark Hunting Neftet Kill Counter,,TRUE,0,30,, +reedsharkhuntingneftetkilltask,Aelrynth,,,Reedshark Hunting Neftet Kill Task,,TRUE,72000,-1,, +reefhuntersreckreckblue126,Aelrynth,,,Reefhunters Riddle,,FALSE,0,1,set by Statue, +reefhuntersreckreckgreen112,Aelrynth,,,Reefhunters Riddle,,FALSE,0,1,set by Statue, +reefhuntersreckreckred150,Aelrynth,,,Reefhunters Riddle,,FALSE,0,1,set by Statue, +reeshanbeaten,Aelrynth,,,You've beaten Reeshan.,,FALSE,0,1,checked by Guard Ellyon, +reeshancomplete,Aelrynth,,,You've completed the Reeshan quest.,,TRUE,72000,-1,set by Guard Ellyon, +reeshankilled,Aelrynth,,,You killed Reeshan.,,FALSE,0,1,set by Guard Ellyon, +regaliamask,Aelrynth,,,Regalia Quest,,TRUE,72000,-1,, +regaliamaskdesecrator,Aelrynth,,,Picked up Virindi Desectrator Mask,,TRUE,72000,-1,, +regaliamaskextreme,Aelrynth,,,Player has collected the mask from a Virinidi Consul.,,TRUE,72000,-1,, +regaliamaskuber,Aelrynth,,,Player has collected the mask from a Virinidi Profatrix.,,TRUE,72000,-1,, +regaliamaskupper,Aelrynth,,,Greater Regalia Quest,,TRUE,72000,-1,, +regicidecomplete,Aelrynth,,,Player has finished the Regicide Quest,,TRUE,72000,-1,"set by Dame Tsaya, Sir Rylanan, Sir Tenshin", +regicidehusk,Aelrynth,,,Player has turned in HuskRegicide,,FALSE,0,1,set by Dame Tsaya, +regicidespherule,Aelrynth,,,Player has turned in spherule regicide,,FALSE,0,1,set by Sir Rylanan, +regicideuniform,Aelrynth,,,Player has turned Regicide Uniform,,FALSE,0,1,set by Sir Tenshin, +rehirbeaten,Aelrynth,,,You've beaten Rehir.,,FALSE,0,1,checked by Guard Lo Pan, +rehircomplete,Aelrynth,,,You've completed the Rehir quest.,,TRUE,72000,-1,set by Guard Lo Pan, +rehirkilled,Aelrynth,,,You killed Rehir.,,FALSE,0,1,set by Guard Lo Pan, +reignofterrorcomplete_0511,Aelrynth,,,Handed in Olthoi Chitin,,TRUE,72000,-1,set by Sergeant Maloth, +reignofterrorstarted_0511,Aelrynth,,,Spoke with Sergeant Maloth,,FALSE,0,1,set by Sergeant Maloth, +remasteredjittecartilage_turnin,Aelrynth,,,Player has turned in Cartilage to Mi Krau Li,,FALSE,0,1,set by Mi Krau-Li, +remasteredjittecompleted,Aelrynth,,,Player has completed Remastered Jitte Quest,,TRUE,72000,-1,set by Mi Krau-Li, +remasteredjittepyrealbar_turnin,Aelrynth,,,Player has turned in Pyreal Bar to Mi Krau Li,,FALSE,0,1,set by Mi Krau-Li, +remasteredjittestarted,Aelrynth,,,Player has spoke with Mi Krau Li,,FALSE,0,1,set by Mi Krau-Li, +remasteredjittethighbone_turnin,Aelrynth,,,Player has turned in Thighbone to Mi Krau Li,,FALSE,0,1,set by Mi Krau-Li, +remoransearaptorkillcount,Aelrynth,,,Remoran Sea Raptor Kill Counter,,TRUE,0,50,set by Peng-Ya, +remoransearaptorkilltask,Aelrynth,,,Remoran Sea Raptor Kill Task,,TRUE,72000,-1,set by Peng-Ya, +renaldmug,Aelrynth,,,Allowed to pickup Renald's Old Mug,,FALSE,0,1,set by Renald the Eldest, +renaldrefusal,Aelrynth,,,Flagged for Renald Refusal quest,,FALSE,0,1,set by Anton Sillezi, +renaldsoldmug,Aelrynth,,,Renald's Old Mug pickup,,TRUE,72000,-1,, +renegadebreastplategeneral,Aelrynth,,,You have taken the Tumerok Generals Breastplate.,,TRUE,72000,-1,, +renegadechorizite,Aelrynth,,,You have opened the chest containing Chorizite.,,TRUE,72000,-1,, +renegadehauberkpickedup,Aelrynth,,,You have picked up the Renegade's hauberk.,,TRUE,72000,-1,, +renegadehealing,Aelrynth,,,You have opened the chest containing Healing.,,TRUE,72000,-1,, +renegadehelmgeneral,Aelrynth,,,You have taken the Lugian Helm.,,TRUE,72000,-1,, +renegadeleggingspickedup,Aelrynth,,,You have picked up the Renegade's leggings.,,TRUE,72000,-1,, +renegadelockpicks,Aelrynth,,,You have opened the chest containing Lockpicks.,,TRUE,72000,-1,, +renegademanaoil,Aelrynth,,,You have opened the chest containing Mana Oil.,,TRUE,72000,-1,, +renegademeat,Aelrynth,,,You have opened the chest containing Meat.,,TRUE,72000,-1,, +renegaderanforward,Aelrynth,,,I have charged forward already.,,TRUE,0,4,"set by Gotrok Extas, Renegade Trooper, Renegade War Monger", +renegaderinga,Aelrynth,,,You have collected half of Kamenua's ring.,,TRUE,72000,-1,, +renegaderingb,Aelrynth,,,You have collected half of Kamenua's ring.,,TRUE,72000,-1,, +renegadevaultkey_pickup,Aelrynth,,,Player has picked up Vault Key in the 120+ Renegade Fortress.,,TRUE,72000,-1,, +repairedstonegiven,Aelrynth,,,Repaired Shadow Stone given to Shade of Shade of Farelaith,,FALSE,0,1,set by Shade of Farelaith, +repeatmonougaexperimentlog,Aelrynth,,,Player has turned in Monouga Experiment Log once before,,FALSE,0,1,set by Corporal Liao Chen, +repeatolthoiexperimentlog,Aelrynth,,,Player has turned in Olthoi Experiment Log once before,,FALSE,0,1,set by Corporal Liao Chen, +repeattuskerexperimentlog,Aelrynth,,,Player has turned in Tusker Experiment Log once before,,FALSE,0,1,set by Corporal Liao Chen, +repugeaterkillcount,Aelrynth,,,Repugnant Eater Kill Counter,,TRUE,0,50,set by Xun Yu, +repugnanteaterkilltask,Aelrynth,,,Repugnant Eater Kill Task,,TRUE,72000,-1,set by Xun Yu, +rescuingmoufpoptional,Aelrynth,,,Flag for optional Mouf Reward,,FALSE,0,1,set by Larinne Kerendova, +researchingthelostritualscomplete_0612,Aelrynth,,,Player counter for Sister tasks,,TRUE,0,15,"checked by Lady Dan'eel Trianna, Lady Kiara Trianna, Lady Mashal Trianna and 1 more", +rhandeviceretriever,Aelrynth,,,quest timer,,FALSE,0,1,set by Ler Rhan, +rhujunswampstonegiven,Aelrynth,,,Swamp Stone given to Rhujun,,FALSE,0,1,set by Rhujun, +riddlebed,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddleblack,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddlecoffin,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddledarkness,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddledeath,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddlee,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddleeyes,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddlefail,Aelrynth,,,Player has given the incorrect answer once.,,FALSE,0,1,"set by Bed, Black, Coffin and 17 more", +riddlefail2,Aelrynth,,,Player has given the incorrect answer twice.,,FALSE,0,1,"set by Bed, Black, Coffin and 17 more", +riddleflame,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddlehole,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddlehope,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddleman,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddlemushroom,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddlenothing,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddlering,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddlesilence,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddlestars,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddlesunlight,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddletime,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddletomorrow,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +riddlewind,Aelrynth,,,Player has received the corresponding Riddle.,,FALSE,0,1,set by Tribunal, +ringjalehtaken,Aelrynth,,,You got the ring of Jaleh,,TRUE,72000,-1,, +ringmaelstrom,Aelrynth,,,You've picked up one of the Dark Rings.,,TRUE,72000,-1,, +ringmaelstrom2,Aelrynth,,,You've picked up one of the Dark Rings.,,TRUE,72000,-1,, +ringofkarlun,Aelrynth,,,Knights of Karlun,,TRUE,72000,-1,, +ringofremembrancepickuptimer,Aelrynth,,,Picked up Ring of Remembrance,,TRUE,72000,-1,, +ringofremembranceturnedin,Aelrynth,,,Turned in Ring of Remembrance,,FALSE,0,1,set by Lord Rytheran, +ringofthesummoningadepts_pickup,Aelrynth,,,Player has picked up the Ring of the Summoning Adepts,,TRUE,72000,-1,, +ringquest01,Aelrynth,,,Give MenhirBell to any of the five Tumerok drummers on the Marae Plateau,,TRUE,72000,-1,"set by Aun Aanaua, Aun Gehaua, Aun Kahmaula and 2 more", +ringquest02,Aelrynth,,,Give MenhirRubbleE to MenhirDrummerN,,TRUE,72000,-1,"set by Aun Kahmaula, Aun Ngationa", +ringquest03,Aelrynth,,,Give MenhirRubbleD to MenhirDrummerNE,,TRUE,72000,-1,"set by Aun Gehaua, Aun Ngationa", +ringquest04,Aelrynth,,,Give MenhirRubbleC to MenhirDrummerSE,,TRUE,72000,-1,"set by Aun Ngationa, Aun Tanaua", +ringquest05,Aelrynth,,,Give MenhirRubbleB to MenhirDrummerSW,,TRUE,72000,-1,"set by Aun Laiaua, Aun Ngationa", +ringquest06,Aelrynth,,,Give MenhirRubbleA to MenhirDrummerNW,,TRUE,72000,-1,"set by Aun Aanaua, Aun Ngationa", +ringshieldingnorthacquired1204,Aelrynth,,,You have picked up RingShieldingNorth,,TRUE,72000,-1,, +ringshieldingsouthacquired1204,Aelrynth,,,You have picked up RingShieldingSouth,,TRUE,72000,-1,, +ringshieldingwestacquired1204,Aelrynth,,,You have picked up RingShieldingWest,,TRUE,72000,-1,, +rithwiccelcyndring,Aelrynth,,,Rithwic Ring Quest,,TRUE,72000,-1,"set by Brentsella, Mindorla", +rithwicmindorlaletter,Aelrynth,,,Rithwic Mindorla Quest,,TRUE,72000,-1,set by Celcynd the Dour, +ritualchambersflag,Aelrynth,,,Player is flagged to use other Ritual Chambers portals,,FALSE,0,1,set by Crystal Array, +ritualchestkeypickuptimer,Aelrynth,,,Picked up Ritual Chest Key,,TRUE,72000,-1,, +ritualhuntcompleted_0311,Aelrynth,,,Cooldown for Dericost Ritual Investigation,,TRUE,72000,-1,set by Sir Learth, +ritualhuntrepeat_0311,Aelrynth,,,Player has already done Dericost Ritual Investigation before,,FALSE,0,1,set by Sir Learth, +ritualhuntstarted_0311,Aelrynth,,,Player has started Dericost Ritual Investigation,,FALSE,0,1,set by Sir Learth, +ritualtimecompleted_0411,Aelrynth,,,Cooldown for Halt Dericost Ritual Quest,,TRUE,72000,-1,set by Lady Daenerah, +ritualtimestarted_0411,Aelrynth,,,Player has started Halt Dericost Ritual Quest,,FALSE,0,1,set by Lady Daenerah, +roadscomplete,Aelrynth,,,You complete the first task set forth by Nuhmudira.,,TRUE,72000,-1,"set by Camryn, Nuhmudira's Student, Nuhmudira", +roadsfailedhevkloz,Aelrynth,,,You failed to answer Hevk loz's question correctly.,,TRUE,72000,-1,"set by Portrait of Asheron Realaidain, Portrait of Avoren Palacost", +roadsfailedjifloz,Aelrynth,,,You failed to answer Jif loz's question correctly.,,TRUE,72000,-1,"set by Bust of Asheron Realaidain, Bust of Emperor Kellin II", +roadsfailedkirloz,Aelrynth,,,You failed to answer Kir loz's question correctly.,,TRUE,72000,-1,"set by Statue of Lauallana, Statue of Ualannan", +roadshevkloz,Aelrynth,,,You have spoken to Hevk Loz.,,FALSE,0,1,set by Hevk Loz, +roadsjifloz,Aelrynth,,,You have spoken to Jif Loz.,,FALSE,0,1,set by Jif Loz, +roadsjournal,Aelrynth,,,You found Nuhmudira's journal and know where to find her.,,FALSE,0,1,set by Open Journal, +roadskirloz,Aelrynth,,,You have spoken to Kir Loz.,,FALSE,0,1,set by Kir Loz, +roadsnuhmudira1,Aelrynth,,,You have been sent to collect a book for Nuhmudira.,,FALSE,0,1,"set by Camryn, Nuhmudira's Student, Nuhmudira", +roadsnuhmudira2,Aelrynth,,,You have been sent to collect an urn for Nuhmudira.,,FALSE,0,1,"set by Camryn, Nuhmudira's Student, Nuhmudira", +roadsnuhmudira3,Aelrynth,,,You have been sent to collect a corpse for Nuhmudira.,,FALSE,0,1,"set by Camryn, Nuhmudira's Student, Nuhmudira", +roadssuccesshevkloz,Aelrynth,,,You successfully answered Heck loz's question.,,FALSE,0,1,set by Portrait of Geraine IV, +roadssuccessjifloz,Aelrynth,,,You successfully answered Jif Loz's question.,,FALSE,0,1,set by Bust of Nali Valind, +roadssuccesskirloz,Aelrynth,,,You successfully answered Kir Loz's question.,,FALSE,0,1,set by Statue of Aurlanna, +roadstask1,Aelrynth,,,You complete the first task set forth by Nuhmudira.,,TRUE,72000,-1,set by Indecipherable Book, +roadstask2,Aelrynth,,,You complete the second task set forth by Nuhmudira.,,TRUE,72000,-1,set by Urn, +roadstask3,Aelrynth,,,You complete the third task set forth by Nuhmudira.,,TRUE,72000,-1,set by Sarcophgus of Xi Ru, +roadsundercoverantius,Aelrynth,,,You have undertaken a special mission for Antius.,,FALSE,0,1,"set by Camryn, Nuhmudira's Student, Nuhmudira", +roostbottleprogress_0904,Aelrynth,,,Bitfield based progress following the Assassin's Roost Bottle Line,,TRUE,518400,31,, +roostbottlestarted_0904,Aelrynth,,,Player has picked up the Contact Instructions (Bottle Clue),,TRUE,518400,-1,checked by Bottle, +roostcarenzikillcount,Aelrynth,,,Weak Mangy Carenzi Kill Task in Roost Dungeon,,TRUE,0,50,set by Maximas, +roostfloorpuzzlecomplete_0904,Aelrynth,,,Player has completed the Assassin's Roost Floor Puzzle,,TRUE,72000,-1,set by Lander, +roostjumppuzzlecomplete_0904,Aelrynth,,,Player has completed the Assassin's Roost Jump Puzzle,,TRUE,72000,-1,set by Maniel, +roostknowledgeprogress_0904,Aelrynth,,,Bitfield based progress following the Assassin's Roost Knowledge Line,,TRUE,518400,31,, +roostknowledgestarted_0904,Aelrynth,,,Player has picked up the Contact Instructions (Knowledge Clue),,TRUE,518400,-1,checked by Open Book, +roostratkillcount,Aelrynth,,,Black Rat Kill Task in Roost Dungeon,,TRUE,0,50,set by Ardenson, +roostsignprogress_0904,Aelrynth,,,Bitfield based progress following the Assassin's Roost Sign Line,,TRUE,518400,31,, +roostsignstarted_0904,Aelrynth,,,Player has picked up the Contact Instructions (Sign Clue),,TRUE,518400,-1,checked by Sign, +rossumortachapterhouse_flag,Aelrynth,,,Access granted to the Rossu Morta Chapterhouse,,FALSE,0,1,set by Ring of the Rossu Morta, +rossumortachapterhouseaccess_start,Aelrynth,,,Player has started Rossu Morta Chapterhouse Access Quest,,FALSE,0,1,set by Melaverre, +rossumortachapterhouseaccess_wait,Aelrynth,,,Player wait timer for Rossu Morta Chapterhouse Access Quest,,TRUE,72000,-1,set by Melaverre, +rossumortaloyaltyreset,Aelrynth,,,Loyalty with Rossu Morta faction reset,,FALSE,0,1,set by Lydda, +royalcloakbookscomplete,Aelrynth,,,Bitfield for the Strathelar Royal Books handed in,,TRUE,0,15,checked by Sir Daeglan, +royalcloakcomplete,Aelrynth,,,Completed Strathelar Royal Cloak Quest,,TRUE,72000,-1,set by Sir Daeglan, +rtwcompleted_1013,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Morgethais, +rtwkeypickup_1013,Aelrynth,,,quest timer,,TRUE,72000,-1,, +rtwstarted_1013,Aelrynth,,,quest timer,,FALSE,0,1,set by Morgethais, +rubycrimsonnightpickup,Aelrynth,,,Flagged to pickup the Ruby of Crimson Night,,FALSE,0,1,checked by Maqudh al Nishadina, +ruinedwatcherflagged,Aelrynth,,,Flagged to use Ruined Watcher,,FALSE,0,1,set by Ruined Watcher, +ruinedwatchertokengiven,Aelrynth,,,Token given to Ruined Watcher,,FALSE,0,1,set by Ruined Watcher, +ruschkaspectofgrael_start,Aelrynth,,,Player has started the Ruschk Aspect of Grael Quest,,FALSE,0,1,set by Lord Pyrovor, +ruschkaspectofgrael_wait,Aelrynth,,,Player has completed Ruschk Aspect of Grael Quest,,TRUE,72000,-1,set by Lord Pyrovor, +ruschkaspectofgraeldericostvault_start,Aelrynth,,,Player has started the Dericost Vault portion of Ruschk Aspect of Grael Quest,,FALSE,0,1,set by Lord Pyrovor, +ruschkkillcount,Aelrynth,,,Ruschk Kill Counter,,TRUE,0,30,, +ruschkkilltask,Aelrynth,,,Ruschk Kill Task,,TRUE,72000,-1,, +ruschkshardoftheblackspear_pickup,Aelrynth,,,Player has picked up Ruschk Shard of the Black Spear,,TRUE,72000,-1,, +rynthidartifacts1_0813,Aelrynth,,,quest timer,,FALSE,0,1,set by The Bringer of Light, +rynthidartifacts2_0813,Aelrynth,,,quest timer,,FALSE,0,1,set by The Bringer of Light, +rynthidartifacts3_0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by The Bringer of Light, +rynthidartifactsstarted_0813,Aelrynth,,,quest timer,,FALSE,0,1,set by The Bringer of Light, +rynthidartifactswait_0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by The Bringer of Light, +rynthidcrystalkillcount,Aelrynth,,,Rynthid Crystal Kill Counter,,TRUE,0,6,, +rynthidcrystalkilltask,Aelrynth,,,Rynthid Crystal Kill Task,,TRUE,72000,-1,, +rynthidgenesiskillcount,Aelrynth,,,Player has killed a creature in Rynthid Genesis.,,TRUE,0,-1,set by Rynthid Genesis Event Watcher, +rynthidminionskillcount,Aelrynth,,,Rynthid Minions Kill Counter,,TRUE,0,25,, +rynthidminionskilltask,Aelrynth,,,Rynthid Minions Kill Task,,TRUE,72000,-1,, +rynthidragerskillcount,Aelrynth,,,Rynthid Ragers Kill Counter,,TRUE,0,15,, +rynthidragerskilltask,Aelrynth,,,Rynthid Ragers Kill Task,,TRUE,72000,-1,, +rynthidrarebosskillcount,Aelrynth,,,Rynthid Rare Boss Kill Counter,,FALSE,0,1,, +rynthidrarebosskilltask,Aelrynth,,,Rynthid Rare Boss Kill Task,,TRUE,72000,-1,, +rynthidriftskillcount,Aelrynth,,,Rynthid Rifts Kill Counter,,TRUE,0,10,, +rynthidriftskilltask,Aelrynth,,,Rynthid Rifts Kill Task,,TRUE,72000,-1,, +rynthidslayerskillcount,Aelrynth,,,Rynthid Slayers Kill Counter,,TRUE,0,15,, +rynthidslayerskilltask,Aelrynth,,,Rynthid Slayers Kill Task,,TRUE,72000,-1,, +rynthidsorcererskillcount,Aelrynth,,,Rynthid Sorcerers Kill Counter,,TRUE,0,15,, +rynthidsorcererskilltask,Aelrynth,,,Rynthid Sorcerers Kill Task,,TRUE,72000,-1,, +rynthidtrainingcompleted_1013,Aelrynth,,,Player cooldown for completing Rynthid Training.,,TRUE,72000,-1,set by Rynthid Assessment Crystal, +rynthidtrainingstarted_1013,Aelrynth,,,Player has started Rynthid Training.,,FALSE,0,1,set by Rynthid Assessment Crystal, +rytheranjeweledringpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +rytheransuntranslatedjournalpickuptimer,Aelrynth,,,Picked up Rytherans Untranslated Journal,,TRUE,72000,-1,, +rythjournalrepeat,Aelrynth,,,Repeating Journal Quest,,FALSE,0,1,set by Danira the Dusty, +rythjournalstart,Aelrynth,,,Started Journal Quest,,FALSE,0,1,set by Danira the Dusty, +sackofbanderlingartifactspickuptimer,Aelrynth,,,Pick up timer for Sack of Banderling Artifacts,,TRUE,72000,-1,, +sacrificednuhmudira,Aelrynth,,,Player gave their life for Nuhmudira.,,FALSE,0,1,"set by Agent Dravos, Agent of the Arcanum, Balthazar, Royal Guardian and 6 more", +sacrificednuhmudiraagent,Aelrynth,,,This quest flag is obsolete.,,FALSE,0,1,"checked by Agent Dravos, Agent of the Arcanum, Balthazar, Royal Guardian and 5 more", +sacrificednuhmudirahunter,Aelrynth,,,This quest flag is obsolete.,,FALSE,0,1,, +sacritterdead,Aelrynth,,,NPC Check for total critters killed,,TRUE,0,40,set by Saving Asherons Wave Controller, +sahighacolytedead,Aelrynth,,,NPC Check for total critters killed,,TRUE,0,3,set by Saving Asherons Wave Controller, +sanamarflagged,Aelrynth,,,Sanamar flagged,,FALSE,0,1,set by Grand Knight, +sanctumguardiankilltask,Aelrynth,,,Sanctum Guardian Spirit KillTask for Harvesting the Bulb of Mornings quest.,,TRUE,0,10,set by Sanctum Guardian Spirit, +sanctumguardiankilltask_completed,Aelrynth,,,Sanctum Guardian Spirit KillTask completed.,,FALSE,0,1,set by Sanctum Guardian Spirit, +sanctumxiruenter,Aelrynth,,,You have been acknowledged as one who may enter Xi Ru's temple.,,FALSE,0,1,set by Door to Xi Ru's Sanctum, +sanctumxiruhevk,Aelrynth,,,You have been given Hevk Loz's blessing to enter Xi Ru's Temple.,,FALSE,0,1,set by Hevk Loz, +sanctumxirujif,Aelrynth,,,You have been given Jif Loz's blessing to enter Xi Ru's Temple.,,FALSE,0,1,set by Jif Loz, +sanctumxirukir,Aelrynth,,,You have been given Kir Loz's blessing to enter Xi Ru's Temple.,,FALSE,0,1,set by Kir Loz, +sandcaveflagcomplete,Aelrynth,,,Neftet Sand Caves Entrance Flag,,TRUE,72000,-1,set by Nephthys, +sandminifour_canenter_0511,Aelrynth,,,Flagged to enter Ancient portal for Idol of black crystal quest,,FALSE,0,1,set by Ancient Tablet of the Crystal Idol (Level 180+), +sandminifour_wait_0511,Aelrynth,,,Idol of black crystal quest,,TRUE,72000,-1,set by Bemeth the Gatherer, +sandminione_canenter_0511,Aelrynth,,,Flagged to enter Ancient portal for Crystal Staff,,FALSE,0,1,set by Ancient Tablet of the Crystal Staff (Level 180+), +sandminione_critterskilled_0511,Aelrynth,,,Incendiary Guardian Kill Counter,,TRUE,0,20,set by Altar of the Red Crystal, +sandminione_wait_0511,Aelrynth,,,Crystal Staff quest,,TRUE,72000,-1,set by Bemeth the Gatherer, +sandminithree_canenter_0511,Aelrynth,,,Flagged to enter Ancient portal for Green Amulet,,FALSE,0,1,set by Ancient Tablet of the Crystal Amulet (Level 180+), +sandminithree_critterskilled_0511,Aelrynth,,,corrupted flame collection,,TRUE,0,20,set by Corrupted Flame, +sandminithree_wait_0511,Aelrynth,,,Green Amulet quest,,TRUE,72000,-1,set by Bemeth the Gatherer, +sandminitwo_canenter_0511,Aelrynth,,,Flagged to enter Ancient portal for Red Crystal Sword,,FALSE,0,1,set by Ancient Tablet of the Crystal Sword (Level 180+), +sandminitwo_wait_0511,Aelrynth,,,Red Crystal Sword quest,,TRUE,72000,-1,set by Bemeth the Gatherer, +sandstonearmorkeypickedup,Aelrynth,,,You have aquired a sandstone armor key.,,TRUE,72000,-1,, +sandstonemagickeypickedup,Aelrynth,,,You have aquired a sandstone magic key.,,TRUE,72000,-1,, +sandstonemixedkeypickedup,Aelrynth,,,You have aquired a sandstone mixed key.,,TRUE,72000,-1,, +sandstoneweaponkeypickedup,Aelrynth,,,You have aquired a sandstone weapon key.,,TRUE,72000,-1,, +sarcophaguskillcount,Aelrynth,,,SarcophagusKillCount,,TRUE,0,4,set by Sergeant Freng, +sarcophaguskilltask,Aelrynth,,,SarcophagusKillTask,,TRUE,72000,-1,set by Sergeant Freng, +sarqahdrudgecharmquest,Aelrynth,,,Retreive a Drudge Charm for Sarqah bint Ak,,TRUE,72000,-1,set by Sarqah bint Ak, +saveapetfinished_1212,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Colton Reeyan, +saveapetstarted_1212,Aelrynth,,,quest timer,,FALSE,0,1,set by Colton Reeyan, +saveasheroncompleted0207,Aelrynth,,,Player has completed Saving Asheron Quest,,TRUE,72000,-1,set by Collector Golem, +saveasheronrepeat0207,Aelrynth,,,Player has completed Saving Asheron Quest at least once,,FALSE,0,1,set by Collector Golem, +saveasheronstarted0207,Aelrynth,,,Player has started Saving Asheron Quest,,FALSE,0,1,set by Collector Golem, +savefionawait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Fiona Woron, +savetownspersonwait,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Trapped Townsperson, +sawatoextortioncomplete0806,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Sergeant Huang, +sawatoextortiongotaccess0806,Aelrynth,,,quest timer,,FALSE,0,1,set by Unfriendly Barkeeper, +scallywagnoir1,Aelrynth,,,You've spoken to Jake.,,TRUE,72000,-1,set by Gentleman Jake Hawkins, +scepterlugian,Aelrynth,,,Lugian Commander Trophy,,TRUE,72000,-1,, +scepterlugianoct01,Aelrynth,,,Lugian Warlord Sceptre,,TRUE,72000,-1,, +sclavuspresentfirstguess,Aelrynth,,,Player has opened first Present in a two set for puzzle.,,FALSE,0,1,set by Present, +sclavuspresentmoarselffreed,Aelrynth,,,Player questbit for freed Moarself.,,TRUE,0,31,, +sclavuspresentportaldoor,Aelrynth,,,Player stamp for Impostor door.,,FALSE,0,1,set by Santa Sclavus, +sclavuspresentsopened,Aelrynth,,,Santa Sclavus Presents Opened Bits.,,TRUE,0,65535,, +sclavuspresentstart,Aelrynth,,,Player timer for Present Puzzle.,,TRUE,300,-1,set by Moarself, +sclavuspresentwait,Aelrynth,,,Player wat timer for Sclavus Santas House Quest.,,TRUE,72000,-1,set by Santa Sclavus, +sclavuspresentwrongguess,Aelrynth,,,Player counter for how many non-matches.,,TRUE,0,3,set by Present, +sclavusslayer,Aelrynth,,,Players has collected and worn the flesh of several sclavus.,,FALSE,0,1,set by Sclavus Guise, +scrapofshadowessence_pickup,Aelrynth,,,Player has picked up Scrap of Shadow Essence.,,TRUE,72000,-1,, +scrollofair_pickup,Aelrynth,,,Player has picked up the Scroll of Air,,TRUE,72000,-1,, +scrollofearth_pickup,Aelrynth,,,Player has picked up the Scroll of Earth,,TRUE,72000,-1,, +scrollofwater_pickup,Aelrynth,,,Player has picked up the Scroll of Water,,TRUE,72000,-1,, +sealbookcompleted_0611,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Asheron, +sealbookgotgem,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Avatar of the Deru, +sealbookguardiantalk,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian Spirit, +sealbookstarted_0611,Aelrynth,,,quest timer,,FALSE,0,1,set by Asheron, +sealedolthoipassage,Aelrynth,,,Player can enter the Sealed Olthoi Passage,,TRUE,7200,-1,set by Sealed Olthoi Passage, +sealedtomepickuptimer,Aelrynth,,,Picked up Sealed Tome,,TRUE,72000,-1,, +seatemplecatacombscompleted_1111,Aelrynth,,,Completed Brain Mansion Ruin (Lou Ka's Stolen Items),,TRUE,72000,-1,set by Lubziklan al-Luq, +secondsistercompleted_1112,Aelrynth,,,Player has completed Harvesting the Bulb of Harvests quest.,,TRUE,72000,-1,set by Adrenkus, +secondsisterstarted_1112,Aelrynth,,,Player has started Harvesting the Bulb of Harvests quest.,,FALSE,0,1,set by Adrenkus, +selainaforgiveness,Aelrynth,,,Player has been redeemed a Writ of Forgiveness with Selaina the Subtle,,TRUE,5184000,-1,set by Selaina the Subtle, +selainakilled,Aelrynth,,,Player has killed Selaina the Subtle,,FALSE,0,1,set by Selaina the Subtle, +selainamanakeywrit,Aelrynth,,,Player has turned in the Mana Key Writ to Selaina the Subtle,,TRUE,5184000,-1,set by Selaina the Subtle, +selainaornatewrit,Aelrynth,,,Player has turned in the Society Armor Writ to Selaina the Subtle,,TRUE,518400,-1,checked by Selaina the Subtle, +selainascorpion,Aelrynth,,,Player has been teleported by Selaina the Subtle,,TRUE,300,-1,set by Selaina the Subtle, +sentrytaskcomplete,Aelrynth,,,Sentry Task Completed,,FALSE,0,1,set by Sentry, +serpentburialgroundsbonepickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +serpentburialgroundsdone,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Kraytuss Nallah, +serpentburialgroundskeypickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +serpentburialgroundsstarted,Aelrynth,,,quest timer,,FALSE,0,1,set by Kraytuss Nallah, +shadeironcomplete,Aelrynth,,,Shade Iron Complete,,FALSE,0,1,set by Mekhmet, +shadeironstarted,Aelrynth,,,Shade Iron Started,,FALSE,0,1,set by Mekhmet, +shadeironwait,Aelrynth,,,Shade Iron quest cooldown,,TRUE,72000,-1,set by Mekhmet, +shadeofduleportal,Aelrynth,,,Flag to use Shade of Dule to summon portal,,FALSE,0,1,set by Shade of Dule, +shadeofduleportalfellow,Aelrynth,,,Flag for Fellow to use Shade of Dule to summon portal,,FALSE,0,1,set by Shade of Dule, +shadowarmoraluvian1,Aelrynth,,,Aluvian Shadow Armor 1,,FALSE,0,1,set by Alean the Steel Forger, +shadowarmoraluvian2,Aelrynth,,,Aluvian Shadow Armor 2,,FALSE,0,1,set by Alean the Steel Forger, +shadowarmoraluvian3,Aelrynth,,,Aluvian Shadow Armor 3,,FALSE,0,1,set by Alean the Steel Forger, +shadowarmorgharundim1,Aelrynth,,,Gharundim Shadow Armor 1,,FALSE,0,1,set by Jibril ibn Rashid, +shadowarmorgharundim2,Aelrynth,,,Gharundim Shadow Armor 2,,FALSE,0,1,set by Jibril ibn Rashid, +shadowarmorgharundim3,Aelrynth,,,Gharundim Shadow Armor 3,,FALSE,0,1,set by Jibril ibn Rashid, +shadowarmorsho1,Aelrynth,,,Sho Shadow Armor 1,,FALSE,0,1,set by Koga Hideki, +shadowarmorsho2,Aelrynth,,,Sho Shadow Armor 2,,FALSE,0,1,set by Koga Hideki, +shadowarmorsho3,Aelrynth,,,Sho Shadow Armor 3,,FALSE,0,1,set by Koga Hideki, +shadowaspectofgrael_wait,Aelrynth,,,Player has completed Shadow Aspect of Grael Quest,,TRUE,72000,-1,set by Abbess Zik'Lir, +shadowassaultdule,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +shadowcaptainsheaume,Aelrynth,,,Shadow Captain's Heaume,,TRUE,72000,-1,, +shadowchestkeypickuptimer,Aelrynth,,,Player has picked up Shadow Chest Key,,TRUE,72000,-1,, +shadowgempickuptimer,Aelrynth,,,Player has picked up Shadow Gem,,TRUE,72000,-1,, +shadowinvasion,Aelrynth,,,quest timer,,TRUE,0,6,"set by Black Ferah, Emissary of Asheron, Isin Dule and 1 more", +shadowinvasiontitle,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +shadowinvasionwait,Aelrynth,,,quest timer,,TRUE,72000,-1,"set by Black Ferah, Emissary of Asheron, Isin Dule and 1 more", +shadowshardoftheblackspear_pickup,Aelrynth,,,Player has picked up Shard of the Black Spear,,TRUE,72000,-1,, +shadowstone,Aelrynth,,,Shadow Stone Quest,,TRUE,72000,-1,, +shadowswintercomplete1205,Aelrynth,,,Shadows of Bitter Winter quest cooldown timer,,TRUE,72000,-1,set by Shade of Farelaith, +shadowswintercontractcomplete,Aelrynth,,,Contract Completed for the Shadows of Bitter Winter quest,,FALSE,0,1,, +shadowswinterstarted_0511,Aelrynth,,,Flagged for the Shadows of Bitter Winter quest,,FALSE,0,1,set by Shade of Farelaith, +shadowtouchedvirindiparadoxkillcount,Aelrynth,,,Shadow-touched Virindi Paradox Kill Counter,,TRUE,0,75,set by Guard Li, +shadowtouchedvirindiparadoxkilltask,Aelrynth,,,Shadow-touched Virindi Paradox Kill Task,,TRUE,72000,-1,set by Guard Li, +shadowtouchedvirindiquidioxkillcount,Aelrynth,,,Shadow-touched Virindi Quidiox Kill Counter,,TRUE,0,75,set by Guard Alfric, +shadowtouchedvirindiquidioxkilltask,Aelrynth,,,Shadow-touched Virindi Quidiox Kill Task,,TRUE,72000,-1,set by Guard Alfric, +shadowvortexdule,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +shadowvortexferah,Aelrynth,,,quest timer,,FALSE,0,1,set by Black Ferah, +shadowyvirindiessencepickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +shallowsgorgerkillcount,Aelrynth,,,Shallows Gorger Kill Counter,,TRUE,0,50,set by Dayla Bint Kazm, +shallowsgorgerkilltask,Aelrynth,,,Shallows Gorger Kill Task,,TRUE,72000,-1,set by Dayla Bint Kazm, +shamblingarchivistdestroyer,Aelrynth,,,Shambling Archivist Destroyer,,TRUE,72000,-1,, +shardofharraagsdaggerpickuptimer,Aelrynth,,,Pick up timer for Shard of Harraags Dagger,,TRUE,72000,-1,, +shardoftheabyssaltotempickuptimer,Aelrynth,,,Picked up Shard of the Abyssal Totem,,TRUE,72000,-1,, +shardoftheblackspearpickuptimer,Aelrynth,,,Player has picked up Shard of the Black Spear,,TRUE,72000,-1,, +shardsoulcrystal,Aelrynth,,,Shard of the Soul Crystal,,TRUE,72000,-1,, +shardturshtotemassaulthighacquired0105,Aelrynth,,,You have acquired a shard of the Tursh totem!,,TRUE,72000,-1,, +shardturshtotemassaultlowacquired0105,Aelrynth,,,You have acquired a shard of the Tursh totem!,,TRUE,72000,-1,, +shardturshtotemassaultmidacquired0105,Aelrynth,,,You have acquired a shard of the Tursh totem!,,TRUE,72000,-1,, +shardturshtotemassaultuberacquired0105,Aelrynth,,,You have acquired a shard of the Tursh totem!,,TRUE,72000,-1,, +shatteredcoresamplereceived,Aelrynth,,,Player stamp for receiving the Shattered Aetherium Core Sample.,,TRUE,300,-1,set by Large Shattered Aetherium Core, +shatteredmasterbloodstoneshardpickedup,Aelrynth,,,Pickup timer for Shattered Master Bloodstone,,TRUE,72000,-1,, +shellgamecompleted,Aelrynth,,,You've compleated the Clutch of Kings shell game puzzle.,,TRUE,72000,-1,set by Shell Table, +shellgameplaying,Aelrynth,,,You are currently playing the game.,,TRUE,1800,-1,set by Shell Table, +shellgameshellanswer1,Aelrynth,,,You have seen the shell game.,,TRUE,1800,-1,set by Shell Table, +shellgameshellanswer2,Aelrynth,,,You have seen the shell game.,,TRUE,1800,-1,set by Shell Table, +shellgameshellanswer3,Aelrynth,,,You have seen the shell game.,,TRUE,1800,-1,set by Shell Table, +shemzayellowjewelgiven,Aelrynth,,,Yellow Jewel given to Shemza,,FALSE,0,1,set by Shemza, +shendolaincrystal,Aelrynth,,,Shendolain Crystal,,TRUE,72000,-1,, +shieldcragstonestatuepickup,Aelrynth,,,Player has picked up this shield and cannot pick up another one for 1 day,,TRUE,72000,-1,, +shieldkitestatuepickup,Aelrynth,,,Player has picked up this shield and cannot pick up another one for 1 day,,TRUE,72000,-1,, +shieldquestspawnkilled,Aelrynth,,,Player has killed a critter in Spawn,,TRUE,0,-1,, +shieldroundstatuepickup,Aelrynth,,,Player has picked up this shield and cannot pick up another one for 1 day,,TRUE,72000,-1,, +shieldsimulacra,Aelrynth,,,Shield of the Simulacra,,TRUE,72000,-1,, +shieldsuperior,Aelrynth,,,You have picked up the Superior Shield.,,TRUE,72000,-1,, +shieldtowerstatuepickup,Aelrynth,,,Player has picked up this shield and cannot pick up another one for 1 day,,TRUE,72000,-1,, +shimshimfirstspeak,Aelrynth,,,TBD,,FALSE,0,1,, +shimshimright,Aelrynth,,,Correct answer on Shim Shim,,FALSE,0,1,set by Shim Shim, +shirtbeltsloraquest,Aelrynth,,,Retreive Beltslora's Pretty Shirt,,TRUE,72000,-1,, +shirtjalehtaken,Aelrynth,,,You got the heart of Jaleh,,TRUE,72000,-1,, +shiveringstonemajor,Aelrynth,,,Shivering Stone Major Quest,,TRUE,3600,-1,, +shiveringstoneminor,Aelrynth,,,Shivering Stone Minor Quest,,TRUE,3600,-1,, +shoguthmoarsmankillcount,Aelrynth,,,Shoguth Moarsman Kill Counter,,TRUE,0,40,, +shoguthmoarsmankilltask,Aelrynth,,,Shoguth Moarsman Kill Task,,TRUE,72000,-1,, +shonossoarfragment_pickup,Aelrynth,,,Player has picked up the Shonossoar Fragment,,TRUE,72000,-1,, +shoushibraidbracelet1204,Aelrynth,,,Retreive Bai Den's Bracelet,,TRUE,72000,-1,, +shoushibraidkatar1204,Aelrynth,,,Retreive Lou Ka's Katar,,TRUE,72000,-1,, +shoushibraidnecklace1204,Aelrynth,,,Retreive Bai Den's Necklace,,TRUE,72000,-1,, +shoushibraidring1204,Aelrynth,,,Retreive Bai Den's Ring,,TRUE,72000,-1,, +shoushibraidshuriken1204,Aelrynth,,,Retreive Lou Ka's Shouken,,TRUE,72000,-1,, +shoushibraidtrident1204,Aelrynth,,,Retreive Lou Ka's Trident,,TRUE,72000,-1,, +shoushicomplete,Aelrynth,,,Player has completed the Shoushi Regicide Quest,,TRUE,72000,-1,set by Sir Tenshin, +shoushigreetinggiven,Aelrynth,,,Tenshin has said hello to player,,FALSE,0,1,set by Sir Tenshin, +shoushinenaicheese1204,Aelrynth,,,Retreive Cheese for Nen Ai,,TRUE,72000,-1,, +shoushinenaicider1204,Aelrynth,,,Retreive Cider for Nen Ai,,TRUE,72000,-1,, +shoushistonecompassion,Aelrynth,,,Stone of Compassion Quest,,TRUE,72000,-1,, +shoushistonedetachment,Aelrynth,,,Stone of Detachment Quest,,TRUE,72000,-1,, +shoushistonediscipline1204,Aelrynth,,,Stone of Discipline Quest,,TRUE,72000,-1,, +shoushistonehumility1204,Aelrynth,,,Stone of Humility Quest,,TRUE,72000,-1,, +shrineofblackwater_flag,Aelrynth,,,Player flag to use the Shrine of Black Water,,FALSE,0,1,set by Pau Yajin, +shroudapathypickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +shroudbloodlustpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +shroudcabalnorthaccess0208,Aelrynth,,,Player has spoke to Nomendar al-Rakh,,FALSE,0,1,set by Nomendar al-Rakh, +shroudcabalsouthaccess0208,Aelrynth,,,Player has spoke to Nomendar al-Rakh,,FALSE,0,1,set by Nomendar al-Rakh, +shroudenvypickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +shroudspitepickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +shroudvirindioct01,Aelrynth,,,Virindi Shroud,,TRUE,72000,-1,, +shuntranslatedorderspickuptimer,Aelrynth,,,Pick up timer for Soul Hunters Untranslated Orders,,TRUE,72000,-1,, +siblackspeartemple_flag,Aelrynth,,,Access granted to the Shadow Infested Black Spear Temple,,FALSE,0,1,set by Abbess Zik'Lir, +sigiloflinvaktukalpickuptimer,Aelrynth,,,Pickup timer for Sigil of Linvak Tukal,,TRUE,72000,-1,, +signetfragmentcharged_pickup,Aelrynth,,,Player has picked up Signet Fragment from Charged Niche.,,TRUE,72000,-1,, +signetfragmentfiery_pickup,Aelrynth,,,Player has picked up Signet Fragment from the Fiery Alcove.,,TRUE,72000,-1,, +signetfragmentfrozen_pickup,Aelrynth,,,Player has picked up Signet Fragment from the Frozen Recess.,,TRUE,72000,-1,, +signetfragmentstinging_pickup,Aelrynth,,,Player has picked up Signet Fragment from the Stinging Corner.,,TRUE,72000,-1,, +silifiofcrimsonnightcomplete,Aelrynth,,,Silifi of Crimson Night quest cooldown timer,,TRUE,72000,-1,set by Maqudh al Nishadina, +silkoswaldtaken,Aelrynth,,,Took the torn shirt,,TRUE,72000,-1,, +silverinvaderlordhelm,Aelrynth,,,Timer for Silver Lord Helm,,TRUE,72000,-1,, +silverknightmedallion,Aelrynth,,,Defense of Zaikhal Medallion Pickup Timer Silver,,TRUE,72000,-1,set by Jun Sawashima, +silverlegionchestkey,Aelrynth,,,Pick Up Key for Silver Chest,,TRUE,72000,-1,, +silverlegiondoorkey,Aelrynth,,,Pick Up Key for Door to Silver Legion,,TRUE,72000,-1,, +silverscopetrooperkillcount,Aelrynth,,,kill count,,TRUE,0,25,set by Lieutenant Faen, +silverscopetrooperkilltask,Aelrynth,,,kill task timer,,TRUE,72000,-1,set by Lieutenant Faen, +silyunflagged,Aelrynth,,,Silyun flagged,,FALSE,0,1,set by Grand Mother, +simistatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +siraluunclawhairbrushbadlands1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Ihmenaura, +siraluunclawhairbrushkithless1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Ihmenaura, +siraluunclawhairbrushlittoral1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Ihmenaura, +siraluunclawhairbrushmarsh1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Ihmenaura, +siraluunclawhairbrushstrand1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Ihmenaura, +siraluunclawhairbrushtidal1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Ihmenaura, +siraluunclawhairbrushtimber1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Ihmenaura, +siraluunclawhairbrushuntamed1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Ihmenaura, +siraluunclawhairgelbadlands1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Kahuiura, +siraluunclawhairgelkithless1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Kahuiura, +siraluunclawhairgellittoral1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Kahuiura, +siraluunclawhairgelmarsh1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Kahuiura, +siraluunclawhairgelstrand1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Kahuiura, +siraluunclawhairgeltidal1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Kahuiura, +siraluunclawhairgeltimber1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Kahuiura, +siraluunclawhairgeluntamed1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Kahuiura, +siraluunclawhairpinbadlands1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Nireeura, +siraluunclawhairpinkithless1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Nireeura, +siraluunclawhairpinlittoral1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Nireeura, +siraluunclawhairpinmarsh1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Nireeura, +siraluunclawhairpinstrand1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Nireeura, +siraluunclawhairpintidal1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Nireeura, +siraluunclawhairpintimber1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Nireeura, +siraluunclawhairpinuntamed1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Nireeura, +siraluunclawscissorsbadlands1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Pitamaura, +siraluunclawscissorskithless1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Pitamaura, +siraluunclawscissorslittoral1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Pitamaura, +siraluunclawscissorsmarsh1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Pitamaura, +siraluunclawscissorsstrand1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Pitamaura, +siraluunclawscissorstidal1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Pitamaura, +siraluunclawscissorstimber1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Pitamaura, +siraluunclawscissorsuntamed1204,Aelrynth,,,You have turned in this item already.,,TRUE,72000,-1,set by Aun Pitamaura, +sircoretto,Aelrynth,,,Knights of Karlun - Sir Ginazio,,TRUE,72000,-1,set by Sir Ginazio, +sirginaziosword,Aelrynth,,,Pick up of Sir Ginazio's Sword,,TRUE,72000,-1,checked by Sir Ginazio, +sishaltislithiskillcount,Aelrynth,,,Sishalti Slithis Kill Counter,,TRUE,0,150,set by Zava bint Laurma, +sishaltislithiskilltask,Aelrynth,,,Sishalti Slithis Kill Task,,TRUE,72000,-1,set by Zava bint Laurma, +skeletonnoir1,Aelrynth,,,You've examined the skeleton.,,TRUE,5400,-1,set by Skeleton, +skillalterationgempickedup,Aelrynth,,,Picked up a skill alteration gem.,,TRUE,72000,-1,, +skillloweringgempickedup,Aelrynth,,,Picked up a forgetfulness gem.,,TRUE,72000,-1,, +skillpoint01,Aelrynth,,,Give Aun Hareltah any SkillToken,,TRUE,0,5,set by Aun Hareltah, +skillreset30day,Aelrynth,,,Used your 30 day skill reset at Asheron's Castle,,TRUE,2592000,-1,set by Fianhe, +skinmorgluuk,Aelrynth,,,You've collected the skin from Morgluuk's hide.,,TRUE,72000,-1,, +slippersjalehtaken,Aelrynth,,,You got the heart of Jaleh,,TRUE,72000,-1,, +slithistentacleskillcount,Aelrynth,,,Slithis Tentacles Kill Counter,,TRUE,0,50,, +slithistentacleskilltask,Aelrynth,,,Slithis Tentacles Kill Task,,TRUE,72000,-1,, +smallfledglingmukkirkillcount,Aelrynth,,,Small Fledgling Mukkir Kill Counter,,TRUE,0,15,, +smallfledglingmukkirkilltask,Aelrynth,,,Small Fledgling Mukkir Kill Task,,TRUE,72000,-1,, +smallshadowstatueturnins,Aelrynth,,,Player stamp for handing in Small Shadow Statue of the Hopeslayer,,TRUE,0,3,set by Riordin Nightbane, +smallshadowstatueturnins_wait,Aelrynth,,,Player wait timer for handing in Small Shadow Statue of the Hopeslayer,,TRUE,518400,-1,set by Riordin Nightbane, +smolderingstonemajor,Aelrynth,,,Smoldering Stone Major Quest,,TRUE,3600,-1,, +smolderingstoneminor,Aelrynth,,,Smoldering Stone Minor Quest,,TRUE,3600,-1,, +snowlillies,Aelrynth,,,Lila Fiori Snow Lillies,,TRUE,72000,-1,set by Lila Fiori, +snowmakerused,Aelrynth,,,You've set off some snow.,,TRUE,90,-1,set by Snowmaker, +snowtuskerkillcount,Aelrynth,,,Snow Tusker Kill Counter,,TRUE,0,20,set by Hunter, +snowtuskerkillleadercount,Aelrynth,,,Snow Tusker Leader Kill Counter,,TRUE,0,10,set by Hunter, +snowtuskerkillleadertask,Aelrynth,,,Snow Tusker Leader Kill Task,,TRUE,72000,-1,set by Hunter, +snowtuskerkilltask,Aelrynth,,,Snow Tusker Kill Task,,TRUE,72000,-1,set by Hunter, +snowtuskerkillwarriorcount,Aelrynth,,,Snow Tusker Warrior Kill Counter,,TRUE,0,20,set by Hunter, +snowtuskerkillwarriortask,Aelrynth,,,Snow Tusker Warrior Kill Task,,TRUE,72000,-1,set by Hunter, +socaugcommanderdefeated,Aelrynth,,,Defeated Society Aug Commander,,FALSE,0,1,set by Commander, +socaugdocumentsread,Aelrynth,,,Society Documents Read,,FALSE,0,1,set by Documents, +socaugprisonersfree,Aelrynth,,,Society Aug Dungeon Prisoners Freed,,FALSE,0,1,"set by Blood Captives Doorman, Hand Captives Doorman, Web Captives Doorman", +socaugzoneatotaldead,Aelrynth,,,Society Aug Dungeon Zone A West Killed,,TRUE,0,11,"set by Blood v Blood Doorman, Blood v Hand Doorman, Blood v Web Doorman and 6 more", +societyarmorwritwait,Aelrynth,,,Cooldown for Society Armor Writ turn in,,TRUE,72000,-1,"set by Society Breastplate Armorsmith, Society Gauntlets Armorsmith, Society Girth Armorsmith and 6 more", +societyauginprogress_0611,Aelrynth,,,SocietyAugInProgress_0611 Countdown to complete,,TRUE,2400,-1,set by Operations Specialist, +societyauginprogresswait,Aelrynth,,,Countdown to clean up after Society Aug run,,TRUE,60,-1,set by Operations Specialist, +societyaugneedreward_0210,Aelrynth,,,Society Aug Quest Started,,FALSE,0,1,set by Operations Specialist, +societyaugreward_0210,Aelrynth,,,SocietyAugReward_0210 Cooldown Timer,,TRUE,518400,-1,set by Operations Specialist, +societydamagedribbonsperdaycounter,Aelrynth,,,Limiter for amount of damaged ribbons a player has turned in per day,,TRUE,0,25,set by Commendations Officer, +societydamagedribbonsperdaytimer,Aelrynth,,,Timer for how often a player can turn in the limit of damaged ribbons,,TRUE,216000,-1,set by Commendations Officer, +societyflag,Aelrynth,,,Player is flagged for access to one or more societies,,TRUE,0,7,, +societymasterstipendcollectioncounter,Aelrynth,,,Counter for Society Stipends collected,,TRUE,0,-1,"set by Master Mhoire, Master Rhan, Master Tarkor'in", +societymasterstipendcollectiontimer,Aelrynth,,,Timer for how often a player can collect a society stipend,,TRUE,590400,-1,"set by Master Mhoire, Master Rhan, Master Tarkor'in", +societymember,Aelrynth,,,Player has joined a society,,TRUE,0,4,, +societyresetwait,Aelrynth,,,Cooldown for Society reset,,TRUE,2332800,-1,set by Gaston Shadowbound, +societyribbonsperdaycounter,Aelrynth,,,Limiter for amount of ribbons a player has turned in per day,,TRUE,0,200,set by Commendations Officer, +societyribbonsperdaytimer,Aelrynth,,,"Timer for how often a player can turn in the per rank, per day limit of ribbons",,TRUE,72000,-1,set by Commendations Officer, +solidmukkirorbnotespickup,Aelrynth,Timer for Halmeras Encoded Notes pickup,,Timer for Halmera's Encoded Notes pickup,Timer for Halmera's Encoded Notes pickup,TRUE,72000,-1,, +soulfearingvestrykey,Aelrynth,,,The key from the High Acolyte,,TRUE,18000,-1,, +soulfearingvestryskull,Aelrynth,,,The skull of the High Acolyte,,TRUE,72000,-1,, +soulhunterquestflag_1106,Aelrynth,,,Player is Flagged for Soul Hunters Lair,,FALSE,0,1,set by Hasin Lin, +soulhunterquestwait_1106,Aelrynth,,,Wait timer for Soul Hunters Quest,,TRUE,72000,-1,set by Hasin Lin, +soulhunterschamberflag_1106,Aelrynth,,,Player is Flagged for Soul Hunters Chamber Portal,,FALSE,0,1,set by Altar of Urdhinivix, +southernresonatingcrystalflag,Aelrynth,,,Player has turned in the Southern Resonator,,FALSE,0,1,set by Southern Resonating Crystal, +southernshroudcabalcomplete_0511,Aelrynth,,,Player has completed Southern Shroud Cabal,,TRUE,72000,-1,set by Nomendar al-Rakh, +southerntumerokinsignia,Aelrynth,,,Southern Tumerok Insignia,,TRUE,72000,-1,, +southinfiltratorshardpickup,Aelrynth,,,Southern Infiltrator Message Shard pickup timer,,TRUE,72000,-1,, +spareparts_0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Pile of Spare Parts, +sparkingstonemajor,Aelrynth,,,Sparking Stone Major Quest,,TRUE,3600,-1,, +sparkingstoneminor,Aelrynth,,,Sparking Stone Minor Quest,,TRUE,3600,-1,, +sparklingportalflag_0910,Aelrynth,,,Player flag to use Sparkling Portal,,TRUE,3600,-1,set by Emissary of Asheron, +spawnzenithcount,Aelrynth,,,Count for spawning a Zenith in the Portal Space Rifts quest,,TRUE,0,8,"set by Acid Plane Stopgap, Electric Plane Stopgap, Fire Plane Stopgap and 1 more", +speakcorrect,Aelrynth,,,TBD,,FALSE,0,1,, +speakincorrect,Aelrynth,,,TBD,,FALSE,0,1,, +spearofbaranaith,Aelrynth,,,Spear of Baranaith pickup timer,,TRUE,72000,-1,, +spearstatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +spectralarcherkillcount,Aelrynth,,,Spectral Archer Kill Counter,,TRUE,0,15,, +spectralarcherkilltask,Aelrynth,,,Spectral Archer Kill Task,,TRUE,72000,-1,, +spectralbladeandclawkillcount,Aelrynth,,,Spectral Blade and Claw Kill Counter,,TRUE,0,10,, +spectralbladeandclawkilltask,Aelrynth,,,Spectral Blade and Claw Kill Task,,TRUE,72000,-1,, +spectralbushikillcount,Aelrynth,,,Spectral Bushi Kill Counter,,TRUE,0,10,, +spectralbushikilltask,Aelrynth,,,Spectral Bushi Kill Task,,TRUE,72000,-1,, +spectralmagekillcount,Aelrynth,,,Spectral Mage Kill Counter,,TRUE,0,5,, +spectralmagekilltask,Aelrynth,,,Spectral Mage Kill Task,,TRUE,72000,-1,, +spectralminionkillcount,Aelrynth,,,Spectral Minion Kill Counter,,TRUE,0,15,, +spectralminionkilltask,Aelrynth,,,Spectral Minion Kill Task,,TRUE,72000,-1,, +spectralnanjoushoujenkillcount,Aelrynth,,,Spectral Nanjou Shou-jen Kill Counter,,TRUE,0,5,, +spectralnanjoushoujenkilltask,Aelrynth,,,Spectral Nanjou Shou-jen Kill Task,,TRUE,72000,-1,, +spectralsamuraikillcount,Aelrynth,,,Spectral Samurai Kill Counter,,TRUE,0,10,, +spectralsamuraikilltask,Aelrynth,,,Spectral Samurai Kill Task,,TRUE,72000,-1,, +spellcastinggloves,Aelrynth,,,Fiun Spell Casting Gloves NPC,,TRUE,72000,-1,set by Senior Sage Shibak, +spellcastingglovesactive,Aelrynth,,,Flagged to enter Abayar's Study,,FALSE,0,1,set by Senior Sage Shibak, +spheruleregicidepickup,Aelrynth,,,Player has picked up the Spherule,,TRUE,72000,-1,checked by Sir Rylanan, +spiketoothshead_pickuptimer,Aelrynth,,,Player has picked up Spiketooths Head,,TRUE,72000,-1,, +spirechunk_pickup,Aelrynth,,,Player has picked up Spire Chunk,,TRUE,72000,-1,, +spiredrudgedead,Aelrynth,,,NPC Kill Count,,TRUE,0,4,, +spiritdefendedwait,Aelrynth,,,Timer for defending a spirit in Hoshino Must Die.,,TRUE,300,-1,"set by Spirit of Dana'lith, Spirit of Khira'thi, Spirit of Rhia'ni", +spiritedapathy,Aelrynth,,,quest timer,,FALSE,0,1,set by Sapphire Annex, +spiritedbloodlust,Aelrynth,,,quest timer,,FALSE,0,1,set by Ruby Annex, +spiritedcompleted_0813,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Rinne Gorber, +spiritedenvy,Aelrynth,,,quest timer,,FALSE,0,1,set by Jade Annex, +spiritedspite,Aelrynth,,,quest timer,,FALSE,0,1,set by Amethyst Annex, +spiritedstarted_0813,Aelrynth,,,quest timer,,FALSE,0,1,set by Rinne Gorber, +splintersgivenulgrim,Aelrynth,,,Number of splinters handed to Ulgrim.,,TRUE,0,9,set by Ulgrim the Unpleasant, +splinterulgrimcombat,Aelrynth,,,Found Splinter10 of Ulgrim's Wand.,,FALSE,0,1,, +splinterulgrimeastham,Aelrynth,,,Found Splinter1 of Ulgrim's Wand.,,FALSE,0,1,set by Ulgrim the Underhanded, +splinterulgrimlytelthorpe,Aelrynth,,,Found Splinter2 of Ulgrim's Wand.,,FALSE,0,1,set by Ulgrim the Uncertain, +splinterulgrimrithwic,Aelrynth,,,Found Splinter3 of Ulgrim's Wand.,,FALSE,0,1,set by Ulgrim the Unintelligible, +splinterulgrimsamsur,Aelrynth,,,Found Splinter4 of Ulgrim's Wand.,,FALSE,0,1,set by Ulgrim the Uncooperative, +splinterulgrimsawato,Aelrynth,,,Found Splinter5 of Ulgrim's Wand.,,FALSE,0,1,set by Ulgrim the Unclean, +splinterulgrimshoushi,Aelrynth,,,Found Splinter6 of Ulgrim's Wand.,,FALSE,0,1,set by Ulgrim the Underdressed, +splinterulgrimtoutou,Aelrynth,,,Found Splinter7 of Ulgrim's Wand.,,FALSE,0,1,set by Ulgrim the Unreal, +splinterulgrimuziz,Aelrynth,,,Found Splinter8 of Ulgrim's Wand.,,FALSE,0,1,set by Ulgrim the Unlucky, +splinterulgrimyanshi,Aelrynth,,,Found Splinter9 of Ulgrim's Wand.,,FALSE,0,1,set by Ulgrim the Unbalanced, +splitgraelhighcomplete0806,Aelrynth,,,Player has completed Split Grael High,,TRUE,72000,-1,set by Hoshar ibn Jalaq, +splitgraelhighichorturnin0806,Aelrynth,,,Player has started Split Grael High,,FALSE,0,1,set by Hoshar ibn Jalaq, +splitgraellowbloodturnin0806,Aelrynth,,,Player has turned in Garaktars Blood to Lamorda,,FALSE,0,1,set by Lamorda Loschi, +splitgraellowcomplete0806,Aelrynth,,,Player has completed Splitting Grael Low Quest,,TRUE,72000,-1,set by Lamorda Loschi, +splitgraellowstarted0806,Aelrynth,,,Player has spoke with Lamorda,,FALSE,0,1,set by Lamorda Loschi, +splitgraelmidcomplete0806,Aelrynth,,,Player has completed Splitting Greal Mid,,FALSE,0,1,set by Soju Bo-Ki, +splitgraelmidessenceturnin0806,Aelrynth,,,Player has turned in Essence to Soju Bo-Ki,,FALSE,0,1,set by Soju Bo-Ki, +splitgraelmidstarted0806,Aelrynth,,,Player has spoke with Soju Bo-Ki,,FALSE,0,1,set by Soju Bo-Ki, +spokeayanamechiyoko,Aelrynth,,,quest timer,,FALSE,0,1,set by Ayaname Chiyoko, +spokenbobo,Aelrynth,,,TBD,,FALSE,0,1,"set by Oolutanga, the Tusker King", +spokenbrighteyes,Aelrynth,Oswald's Dirk Quest,https://acportalstorm.com/wiki/Oswald's_Dirk_Quest,TBD. See Brighteyes; the Tailor. In Oolatangas refuge.,TBD,FALSE,0,1,"set by Brighteyes, the Tailor", +spokentoeyekiviklirtriallogic,Aelrynth,,,You have spoken to the Logical Eye of the Watcher.,,FALSE,0,1,set by Eye of the Watcher, +spokentokielerea,Aelrynth,,,You've talked to Kielerea.,,FALSE,0,1,set by Aun Kielerea, +spokentostatuekiviklirarena,Aelrynth,,,You have spoken to the Guardian of the Arena.,,FALSE,0,1,set by Guardian of the Arena, +spoketershen,Aelrynth,,,quest timer,,FALSE,0,1,set by Ter Shen, +spoketofadsahil,Aelrynth,,,Player has spoken to Fadsahil al-Tashbi and been given the info on the quest.,,FALSE,0,1,set by Fadsahil al-Tashbi the Master Archmage, +spoketojondor,Aelrynth,,,Player spoke to Jondor,,FALSE,0,1,set by Jondor Torgren, +spoketolaedron,Aelrynth,,,Player spoke to Laedron the Geomancer,,FALSE,0,1,set by Laedron the Geomancer, +spoketolugianspy,Aelrynth,,,You have spoken to Toberik the Lugian Spy.,,FALSE,0,1,set by Toberik, +spoketomaqudh,Aelrynth,,,Maqudh spoken to,,FALSE,0,1,set by Maqudh al Nishadina, +spoketossavish,Aelrynth,,,Ssavish spoken to,,FALSE,0,1,set by Ssavish, +spoketrevor,Aelrynth,,,Spoke to Trevor Shunderson.,,TRUE,72000,-1,set by Trevor Shunderson, +spokewithastara,Aelrynth,,,Spoke With Astara.,,TRUE,72000,-1,set by Astara Duskshield, +spokewithdelton,Aelrynth,,,Spoke With Delton,,TRUE,72000,-1,set by Delton Hardor, +spokewithfallenmgr,Aelrynth,,,was in robbed warehouse,,TRUE,72000,-1,set by Aun Talamura, +spokewithsharia,Aelrynth,,,Spoke to Sharia Blackmist and started Ghost Hunter quest,,FALSE,0,1,set by Sharia Blackmist, +spokewithslithe,Aelrynth,,,Player has spoken with Slithe Tradittor and may go thru portal,,FALSE,0,1,set by Slithe Tradittor, +spokewithsyltyn,Aelrynth,,,Spoke With Syltyn,,TRUE,72000,-1,set by Mage Syltyn Rillon, +springgolem,Aelrynth,,,Player has picked up a Golem spring and cannot pick up another for 1 day.,,TRUE,72000,-1,, +springgolemgiven,Aelrynth,,,Player has given this spring and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +springsclavus,Aelrynth,,,Player has picked up a Sclavus spring and cannot pick up another for 1 day.,,TRUE,72000,-1,, +springsclavusgiven,Aelrynth,,,Player has given this spring and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +springskeleton,Aelrynth,,,Player has picked up a Skeleton spring and cannot pick up another for 1 day.,,TRUE,72000,-1,, +springskeletongiven,Aelrynth,,,Player has given this spring and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +springtumerok,Aelrynth,,,Player has picked up a Tumerok spring and cannot pick up another for 1 day.,,TRUE,72000,-1,, +springtumerokgiven,Aelrynth,,,Player has given this spring and cannot give another for one day.,,TRUE,72000,-1,set by Arcanum Researcher, +staffstatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +staminapickup,Aelrynth,,,Player has picked up an Academy stamina potion,,TRUE,0,15,, +startdarkisleflag,Aelrynth,,,Flagged to use Deep Mukkir portal,,FALSE,0,1,set by Lanaith, +startedfiregolems,Aelrynth,,,Fire Golem Kill Task started,,FALSE,0,1,set by Water Guardian, +startedoublietteboss_0112,Aelrynth,,,quest timer,,FALSE,0,1,set by Shade of Terelev, +startedwatergolems,Aelrynth,,,Water Golem Kill Task started,,FALSE,0,1,set by Flame Guardian, +startknorr,Aelrynth,,,Start the Knorr Quest,,FALSE,0,1,"set by Olcris, Nuhmudira's Student", +statuekiviklirguardianantechamber,Aelrynth,Kivik Lir Guardian,,You have spoken to the Guardian of the Antechamber.,,FALSE,0,1,set by Guardian, +statuekiviklirguardiantrial,Aelrynth,,,You have spoken to the Guardian of the Trials.,,FALSE,0,1,set by Guardian of the Trials, +stingingstonemajor,Aelrynth,,,Stinging Stone Major Quest,,TRUE,3600,-1,, +stingingstoneminor,Aelrynth,,,Stinging Stone Minor Quest,,TRUE,3600,-1,, +stipendscollectedinamonth,Aelrynth,,,Amount of stipends player has received within a 27 day period.,,TRUE,0,4,set by Monroe, +stipendtimer_0812,Aelrynth,,,Amount of stipends received.,,TRUE,518400,-1,set by Monroe, +stipendtimer_monthly,Aelrynth,,,Monthly timer for receiving up to 4 stipends.,,TRUE,2332800,-1,set by Monroe, +stolenamulet,Aelrynth,,,Thrungus Hovels,,TRUE,72000,-1,, +stolenbracelet,Aelrynth,,,Thrungus Hovels,,TRUE,72000,-1,, +stolenbrewkettle,Aelrynth,,,Thrungus Hovels,,TRUE,72000,-1,, +stolenewer,Aelrynth,,,Thrungus Hovels,,TRUE,72000,-1,, +stolenfryingpan,Aelrynth,,,Thrungus Hovels,,TRUE,72000,-1,, +stolennecklace,Aelrynth,,,Thrungus Hovels,,TRUE,72000,-1,, +stolenplatter,Aelrynth,,,Thrungus Hovels,,TRUE,72000,-1,, +stolenring,Aelrynth,,,Thrungus Hovels,,TRUE,72000,-1,, +stonebagcomplete,Aelrynth,,,Bits for completed Stone Bag,,TRUE,0,7,checked by Bucket, +stonefistscritterskilled,Aelrynth,,,Player has killed a creature found in Stone Fist,,TRUE,0,-1,set by Stone Fists Event Watcher, +stoneholdtranscription,Aelrynth,,,Stonehold Frore Transcription,,TRUE,72000,-1,, +stoneofalbarel_pickup,Aelrynth,,,Player has picked up the Stone of Albarel,,TRUE,72000,-1,, +stoneofrezarel_pickup,Aelrynth,,,Player has picked up the Stone of Rezarel.,,TRUE,72000,-1,, +stonetool,Aelrynth,,,Stone Tool Quest,,TRUE,3600,-1,, +storageboxpickup,Aelrynth,,,Picked up Storage Box (42111),,TRUE,72000,-1,, +storehousebypass,Aelrynth,,,This quest flag is obsolete.,,FALSE,0,1,, +storehousehientry,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +storehousehiwait,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +storehouselowentry,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +storehouselowwait,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +storehousemidentry,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +storehousemidwait,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +strangecrystalstart,Aelrynth,,,quest timer,,FALSE,0,1,set by Isin Dule, +strangedeviceinprogress,Aelrynth,,,Strange Device is giving out rewards.,,TRUE,120,-1,"set by Strange Device 1 Reward Giver, Strange Device 2 Reward Giver, Strange Device 4 Reward Giver", +strangemanagempickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +strongholdbuilder,Aelrynth,,,Your status for donations to all of the Stronghold Collectors.,,TRUE,0,100,"set by Aun Teverea, Caelis Renning, Kreavon", +strongholdbuildercomplete,Aelrynth,,,You have recieved your Stronghold Flag Stamp.,,FALSE,0,1,"set by Aun Teverea, Caelis Renning, Kreavon", +strongholdhumanbuilder,Aelrynth,,,Your status for donations to the Human Stronghold Collector.,,TRUE,0,201,set by Caelis Renning, +strongholdlugianbuilder,Aelrynth,,,Your status for donations to the Lugian Stronghold Collector.,,TRUE,0,201,set by Kreavon, +strongholdtumerokbuilder,Aelrynth,,,Your status for donations to the Tumerok Stronghold Collector.,,TRUE,0,201,set by Aun Teverea, +summoningadepts_flag,Aelrynth,,,Access granted to the Summoning Chamber and Binding Realm,,FALSE,0,1,set by Ring of the Summoning Adepts, +summoningcavecrystal1,Aelrynth,,,quest timer,,TRUE,1800,-1,set by Strange Crystal, +summoningcavecrystal2,Aelrynth,,,quest timer,,TRUE,1800,-1,set by Strange Crystal, +summoningcrystalcount,Aelrynth,,,Player has killed a summoning crystal.,,TRUE,0,-1,set by Torment Event Watcher, +summoningtthuuncounter,Aelrynth,,,Number of bosses killed,,TRUE,0,3,set by Tthuun Counter Stopgap, +summonmasterychange,Aelrynth,Changed Summoning Mastery,,Changed Summoning Mastery.,,FALSE,0,1,, +superbimprintingmotepickedup,Aelrynth,,,Picked up the Superb Imprinting Mote,,TRUE,518400,-1,, +suppliesturnedin1209,Aelrynth,,,Player wait time for Supply Saboteur.,,TRUE,72000,-1,set by Fort Commander, +suppliesturnedinch,Aelrynth,,,Player stamp for turning in CH Supplies.,,FALSE,0,1,set by Fort Commander, +suppliesturnedinew,Aelrynth,,,Player stamp for turning in EW Supplies.,,FALSE,0,1,set by Fort Commander, +suppliesturnedinrb,Aelrynth,,,Player stamp for turning in RB Supplies.,,FALSE,0,1,set by Fort Commander, +suzuharacomplete_0511,Aelrynth,,,Delivered Baijin's Care Package to Suzuhara Sheshumi,,TRUE,72000,-1,set by Suzuhara Sheshumi, +suzuharapackageacquired1204,Aelrynth,,,You have acquired Suzuhara's Package!,,TRUE,72000,-1,, +swordlongstatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +swordlostlight,Aelrynth,,,You have picked up the Sword of Lost Light.,,TRUE,72000,-1,, +swordofbellenese,Aelrynth,,,Sword of Bellenese Timer,,TRUE,72000,-1,, +swordofsorokupickuptimer,Aelrynth,,,Pickup timer for Sword of Soroku,,TRUE,1123200,-1,, +swordshortstatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +sylsfeartreasurekey,Aelrynth,,,Sylsfear Dungeon Chest Key,,TRUE,72000,-1,, +tachistatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +tainted1_0813,Aelrynth,,,quest timer,,FALSE,0,1,set by Aetherium Ore, +tainted2_0813,Aelrynth,,,quest timer,,FALSE,0,1,set by Aetherium Ore, +tainted3_0813,Aelrynth,,,quest timer,,FALSE,0,1,set by Aetherium Ore, +taintedall_0813,Aelrynth,,,quest timer,,FALSE,0,1,set by Aetherium Ore, +takenblackbookpages,Aelrynth,,,Taken a set of pages of the Black Book of Salt and Ash,,TRUE,72000,-1,set by Black Book of Salt and Ash, +takewaterlethe,Aelrynth,,,Player has picked up Water of Lethe.,,TRUE,72000,-1,, +talkedtoassistantrot2,Aelrynth,,,talked to Nuhmudira's Assistant,,FALSE,0,1,"set by Darhy, Assistant to Nuhmudira", +talkedtobuilder,Aelrynth,,,You have talked to the Stronghold Collectors.,,FALSE,0,1,"set by Aun Teverea, Caelis Renning, Kreavon", +talkedtodaliuskendmar,Aelrynth,,,Talked to Dalius Kendmar.,,TRUE,72000,-1,set by Dalius Kendmar, +talkedtoexstudentrot2,Aelrynth,,,Talked to Cydna Wren,,FALSE,0,1,set by Cydna Wren, +talkedtoladydain,Aelrynth,,,Talked to Lady Dain.,,TRUE,72000,-1,set by Talira Dain, +talkedtoliatzethorstenarmor,Aelrynth,,,Player has spoken with Lia Tze,,TRUE,72000,-1,set by Lia Tze, +talkedtolighthousehermit,Aelrynth,,,You've spoken to the Lighthouse Hermit recently.,,TRUE,72000,-1,set by Lighthouse Hermit, +talkedtoowner,Aelrynth,,,Player has already spoken with owner,,TRUE,72000,-1,set by Frest Greelving, +talkedtosnowmanmayor,Aelrynth,,,You recently talked to the Mayor of Frost Haven.,,TRUE,28800,-1,set by The Mayor, +talkedtotacklemaster,Aelrynth,,,Player has spoken to the Tacklemaster.,,FALSE,0,1,set by Tackle Master, +talkedtotaiwothorstenarmor,Aelrynth,,,Player has spoken with Tai Wo,,TRUE,72000,-1,set by Tai Wo, +talkedtozaikhaljeweler,Aelrynth,,,Talked to ROT2 Jeweler,,FALSE,0,1,set by Djusufa bint Huqis the Jeweler, +talkshadowcaptain,Aelrynth,,,quest timer,,FALSE,0,1,set by Black Ferah, +talkshadowsoldier,Aelrynth,,,quest timer,,FALSE,0,1,set by Shadow Captain, +tanadaclanmedallionturnin,Aelrynth,,,Player has turned in the Tanada Clan Masters Medallion.,,TRUE,0,-1,"set by Ookami Kiri, Sayuji Jina", +tanadaconsulsmessageshard_pickup,Aelrynth,,,Player has picked up Tanada Consuls Message Shard,,TRUE,72000,-1,, +tanadadirectives,Aelrynth,,,Counter for Tanada House of Water Directives,,TRUE,0,-1,set by Meshenq, +tanadadirectivespickup,Aelrynth,,,Pickup timer for Tanada House of Water Directives,,TRUE,72000,-1,, +tanadahouseofbreath_flag,Aelrynth,,,Player flag for Tanada House of Breath Portal,,FALSE,0,1,set by Tanada Shrine of Wind, +tanadahouseofearth_flag,Aelrynth,,,Player flag for Tanada House of Earth Portal,,FALSE,0,1,set by Ookami Kiri, +tanadahouseofearthcompleted,Aelrynth,,,Player wait timer for Tanada House of Earth Quest.,,TRUE,72000,-1,set by Sayuji Jina, +tanadahouseofearthmaster_flag,Aelrynth,,,Player flag for Tanada House of Earth Master Chambers Portal,,FALSE,0,1,set by Tanada Shrine of Metal, +tanadahouseofearthquest_flag,Aelrynth,,,Player has completed Tanada House of Storms Quest,,FALSE,0,1,set by Sayuji Jina, +tanadahouseofearthstarted,Aelrynth,,,Player has started Tanada House of Earth Quest,,FALSE,0,1,set by Sayuji Jina, +tanadahouseoffirecompleted,Aelrynth,,,Player wait timer for Tanada House of Fire Quest.,,TRUE,72000,-1,set by Tanada Han-Tu, +tanadahouseoffirequest_flag,Aelrynth,,,Player flag to start Tanada House of Fire Quest,,FALSE,0,1,set by Pau Yajin, +tanadahouseoffirestarted,Aelrynth,,,Player has started Tanada House of Fire Quest,,FALSE,0,1,set by Tanada Sajo, +tanadahouseofmetal_flag,Aelrynth,,,Player flag for Tanada House of Metal Portal,,FALSE,0,1,set by Tanada Shrine of Stone, +tanadahouseofstone_flag,Aelrynth,,,Player flag for Tanada House of Stone Portal,,FALSE,0,1,set by Tanada Shrine of Earth, +tanadahouseofstormscompleted,Aelrynth,,,Player wait timer for Tanada House of Storms Quest.,,TRUE,72000,-1,set by Sayuji Jina, +tanadahouseofstormsmaster_flag,Aelrynth,,,Player flag for Tanada House of Storms Master Chambers Portal,,FALSE,0,1,set by Tanada Shrine of Breath, +tanadahouseofstormsstarted,Aelrynth,,,Player has started Tanada House of Storms Quest,,FALSE,0,1,set by Sayuji Jina, +tanadahouseofwatercompleted,Aelrynth,,,Player wait timer for Tanada House of Water Quest.,,TRUE,72000,-1,set by Meshenq, +tanadahouseofwaterportal_flag,Aelrynth,,,Player flag for access to Tanada House of Water Portal,,FALSE,0,1,set by Tanada Gate Medallion, +tanadahouseofwaterquest_flag,Aelrynth,,,Player flag for Tanada House of Water Quest,,FALSE,0,1,set by Sayuji Jina, +tanadahouseofwaterstarted,Aelrynth,,,Player has started Tanada House of Water Quest,,FALSE,0,1,set by Meshenq, +tanadahouseofwind_flag,Aelrynth,,,Player flag for Tanada House of Wind Portal,,FALSE,0,1,set by Tanada Shrine of Storms, +tanadainterceptkeypickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +tanadaslaughterfinished_0912,Aelrynth,,,quest timer,,TRUE,72000,-1,"set by Kousha, Tanada Nanjou Kutekei", +tanadaslaughterkilltask_0912,Aelrynth,,,quest timer,,TRUE,0,6,set by Kousha, +tanadaslaughterscrollfinished_0912,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Kinchou, +tanadaslaughterscrollstarted_0912,Aelrynth,,,quest timer,,FALSE,0,1,set by Kinchou, +tanadatempleofblackwatercompleted,Aelrynth,,,Player wait timer for Tanada Temple of Black Water Quest.,,TRUE,72000,-1,set by Pau Yajin, +tanadatempleofblackwaterquest_flag,Aelrynth,,,Player flag to start Tanada Temple of Black Water Quest,,FALSE,0,1,"set by Meshenq, Pau Yajin", +tanadatempleofblackwaterstarted,Aelrynth,,,Player has started Tanada Temple of Black Water Quest,,FALSE,0,1,set by Pau Yajin, +tanadatoresentemplecanenter,Aelrynth,,,quest timer,,FALSE,0,1,"set by Kinchou, Kousha", +tanaegiven,Aelrynth,,,Aun Shimauri will give players permission to enter the Palenqual dungeon only once per month.,,TRUE,72000,-1,, +tanningoiltanuagiven,Aelrynth,,,Tikakhe has given players the tanning oil,,TRUE,72000,-1,, +tanuacompleted,Aelrynth,,,Once players complete the Tanua quest Bachus Flufens will stamp them so they can only go on the quest once/week.,,TRUE,72000,-1,set by Bachus Flufens, +tanuacompleted01,Aelrynth,,,Players may pick the key to the spear altar off the Tumerok Gladiator only once per week,,TRUE,72000,-1,, +tanuacompleted02,Aelrynth,,,Players may pick the key to the figurine altar off the Tumerok Shaman only once per week,,TRUE,72000,-1,, +taskcoraltowersstarted,Aelrynth,,,TaskCoralTowersStarted,,FALSE,0,1,"set by Akahana, Chiyo, Kiko", +taskcoraltowerswait,Aelrynth,,,TaskCoralTowersWait,,TRUE,72000,-1,"set by Akahana, Chiyo, Kiko", +taskdiblackcoralcomplete,Aelrynth,,,Black Coral Collecting Wait Dark Isle,,TRUE,72000,-1,"set by Daisei Chirana, Hidoshi Kawara, Manto Sakara", +taskdiblackcoralstarted,Aelrynth,,,Black Coral Collecting Dark Isle,,FALSE,0,1,"set by Daisei Chirana, Hidoshi Kawara, Manto Sakara", +taskdidelivery,Aelrynth,,,Society Task Dark Isle Delivery,,FALSE,0,1,set by The Deep, +taskdideliverywait,Aelrynth,,,Cooldown for Society Task Dark Isle Delivery,,TRUE,72000,-1,"set by Aisley Swiftfoot, Erline the Fleet, Rheda the Watcher", +taskdireportstarted,Aelrynth,,,Falatacot Journal Collecting Dark Isle,,FALSE,0,1,"set by Agbeart, Boroth Bearhand, Turvald Snorborgson", +taskdireportwait,Aelrynth,,,Falatacot Journal Collecting Wait Dark Isle,,TRUE,72000,-1,"set by Agbeart, Boroth Bearhand, Turvald Snorborgson", +taskdiruschkbosskilltask,Aelrynth,,,Counter for Society Task Vaeshok,,FALSE,0,1,"set by Keiji Sozoji, Sudeko Nojiri, Takahara Masikawa", +taskdiruschkbosskilltaskwait,Aelrynth,,,Cooldown for Society Task Vaeshok,,TRUE,72000,-1,"set by Keiji Sozoji, Sudeko Nojiri, Takahara Masikawa", +taskdiscoutcomplete,Aelrynth,,,Cooldown for Society Task Dark Isle Scouting,,TRUE,72000,-1,"set by Ali ibn Qasid, Qa'li al-Kesh, Rafin ibn Fezesh", +taskdiscoutstarted,Aelrynth,,,Society Task Dark Isle Scouting,,FALSE,0,1,"set by Ali ibn Qasid, Qa'li al-Kesh, Rafin ibn Fezesh", +taskdisocietyrocksfound,Aelrynth,,,Player has touched some rocks,,TRUE,0,7,, +taskfreebooterbanditbosskill,Aelrynth,,,Mana Hunter Boss Kill Task,,FALSE,0,1,"set by Armand di Bellenesse, Corrado Wardun, Giovanni di Alduressa", +taskfreebooterbanditbosskillwait,Aelrynth,,,Mana Hunter Boss Kill Task,,TRUE,72000,-1,"set by Armand di Bellenesse, Corrado Wardun, Giovanni di Alduressa", +taskfreebooterjungleflowercomplete,Aelrynth,,,Mana Flower Freebooter,,TRUE,72000,-1,"set by Giri bint Ashud, Leisall bint Jumadd, Ti'alla bint Ashud", +taskfreebooterjungleflowerstarted,Aelrynth,,,Mana Flower Freebooter,,FALSE,0,1,"set by Giri bint Ashud, Leisall bint Jumadd, Ti'alla bint Ashud", +taskfreebooterjunglelilycomplete,Aelrynth,,,Jungle Lily Freebooter,,TRUE,72000,-1,"set by Atsuko, Kojina, Satsuki", +taskfreebooterjunglelilystarted,Aelrynth,,,Jungle Lily Freebooter,,FALSE,0,1,"set by Atsuko, Kojina, Satsuki", +taskfreebootermoarglandcomplete,Aelrynth,,,Moar Freebooter,,TRUE,72000,-1,"set by Aurellia du Cinghalle, Elloisa du Cinghalle, Pia du Cinghalle", +taskfreebootermoarglandstarted,Aelrynth,,,Moar Gland Freebooter,,FALSE,0,1,"set by Aurellia du Cinghalle, Elloisa du Cinghalle, Pia du Cinghalle", +taskfreebootermoarsmankilltask,Aelrynth,,,Blessed Moarsman Kill Task,,TRUE,0,50,"set by Alexander Bowspeaker, Ian Foefinder, Kieran Stronghammer", +taskfreebootermoarsmankilltaskwait,Aelrynth,,,Blessed Moarsman Kill Task,,TRUE,72000,-1,"set by Alexander Bowspeaker, Ian Foefinder, Kieran Stronghammer", +taskgrave1bosskillstarted,Aelrynth,,,Shambling Archivist Kill Task,,FALSE,0,1,"set by Aldoro di Belleforte, Eccai Marinni, Garain di Spesi", +taskgrave1bosskillwait,Aelrynth,,,Shambling Archivists Kill Task,,TRUE,72000,-1,"set by Aldoro di Belleforte, Eccai Marinni, Garain di Spesi", +taskgrave1jawcollectstarted,Aelrynth,,,Pyre Skeleton Jawbone Collection,,FALSE,0,1,"set by Balon Strongarm, Cullum of Celdon, Hador the Vengeful", +taskgrave1jawcollectwait,Aelrynth,,,Pyre Skeleton Jawbone Collection,,TRUE,72000,-1,"set by Balon Strongarm, Cullum of Celdon, Hador the Vengeful", +taskgrave1wightmagekilltask,Aelrynth,,,White Blade Sorcerer Kill Task,,TRUE,0,12,"set by Idaris bint Qumal, Mashira bint Tamur, Zumaq al-Jaluzi", +taskgrave1wightmagewait,Aelrynth,,,White Blade Sorcerer Kill Task,,TRUE,72000,-1,"set by Idaris bint Qumal, Mashira bint Tamur, Zumaq al-Jaluzi", +taskgrave2fedexdelivered,Aelrynth,,,Delivered Massilor Supplies,,FALSE,0,1,set by Massilor the Withered, +taskgrave2fedexstarted,Aelrynth,,,Started Massilor Supplies,,FALSE,0,1,"set by Annelina Fabarin, Saphine Brauno, Streza du Vorchass", +taskgrave2fedexwait,Aelrynth,,,Massilor Supplies Cooldown,,TRUE,72000,-1,"set by Annelina Fabarin, Saphine Brauno, Streza du Vorchass", +taskgrave2wallcarvingstarted,Aelrynth,,,Started GraveYard Wall Carving,,FALSE,0,1,"set by Durvush the Dusty, Kalal ibn Dariz, Turiq al Qorra", +taskgrave2wallcarvingwait,Aelrynth,,,GraveYard Wall Carving Cooldown,,TRUE,72000,-1,"set by Durvush the Dusty, Kalal ibn Dariz, Turiq al Qorra", +taskmoarsmenartifactsstarted,Aelrynth,,,Moarsman Artifact Started,,FALSE,0,1,"set by Boshi Sutadasuto, Kanji Hatashiya, Kotaro Ueda", +taskmoarsmenartifactswait,Aelrynth,,,Moarsman Artifact Moarsman City,,TRUE,72000,-1,"set by Boshi Sutadasuto, Kanji Hatashiya, Kotaro Ueda", +taskspawnpoolsstarted,Aelrynth,,,TaskSpawnPoolsStarted,,FALSE,0,1,"set by Payla bint Dumandi, Shishalti bint Jaffa, Ualya bint Muyzal", +taskspawnpoolswait,Aelrynth,,,TaskSpawnPoolsWait,,TRUE,72000,-1,"set by Payla bint Dumandi, Shishalti bint Jaffa, Ualya bint Muyzal", +tattereddesolationmoarsmanritual_pickup,Aelrynth,,,Pickup timer for Tattered Desolation Moarsman Ritual,,TRUE,72000,-1,, +tattereddisgustingmoarsmanritual_pickup,Aelrynth,,,Pickup timer for Tattered Disgusting Moarsman Ritual,,TRUE,72000,-1,, +tatteredgrimymoarsmanritual_pickup,Aelrynth,,,Pickup timer for Tattered Grimy Moarsman Ritual,,TRUE,72000,-1,, +tatteredputridmoarsmanritual_pickup,Aelrynth,,,Pickup timer for Tattered Putrid Moarsman Ritual,,TRUE,72000,-1,, +tatteredrankmoarsmanritual_pickup,Aelrynth,,,Pickup timer for Tattered Rank Moarsman Ritual,,TRUE,72000,-1,, +tatteredverdantmoarsmanritual_pickup,Aelrynth,,,Pickup timer for Tattered Verdant Moarsman Ritual,,TRUE,72000,-1,, +tcsturnin1,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin10,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin11,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin12,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin13,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin14,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin15,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin16,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin17,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin18,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin2,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin3,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin4,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin5,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin6,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin7,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin8,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +tcsturnin9,Aelrynth,,,Player has turned in a piece of torn scrap,,FALSE,0,1,set by Jarvis Hammerstone, +temoscepterwait,Aelrynth,,,Cooldown for Temo Scepter Turn In,,TRUE,72000,-1,set by Kousu Temo, +templeappeasementchosen,Aelrynth,,,Player has been chosen to solve the Appeasement puzzle.,,FALSE,0,1,set by Guardian of the Restless Dead, +templeappeasementcomplete,Aelrynth,,,Fellowship has completed the Appeasement test.,,FALSE,0,1,set by Judge of the Appeasement, +templeappeasementspoken,Aelrynth,,,Fellowship has spoken to the Appeasement Statue.,,TRUE,900,-1,set by Guardian of the Restless Dead, +templearbiterspoken,Aelrynth,,,Fellowship has spoken to the Arbiter.,,FALSE,0,1,set by Arbiter, +templecunningchosen,Aelrynth,,,Player has been chosen to solve the Cunning puzzle.,,FALSE,0,1,set by Guardian of Fury, +templecunningcomplete,Aelrynth,,,Fellowship has completed the Cunning Test.,,FALSE,0,1,set by High Matron Arbiter, +templecunningspoken,Aelrynth,,,Fellowship has spoken to the Cunning Statue.,,TRUE,900,-1,set by Guardian of Fury, +templeeastwing,Aelrynth,,,Flagged to enter the Temple East wing,,FALSE,0,1,set by Shade of Farelaith, +templeenlightenmentbistort,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmentcomfrey,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmentdamiana,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmentdragonsblood,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmenteyebright,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmentginseng,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmenthawthorn,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmenthyssop,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmentmandrake,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmentmugwort,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmentmyrrh,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmentsaffron,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmentvervain,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmentwormwood,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeenlightenmentyarrow,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Enlightenment, +templeentranceflagged,Aelrynth,,,Turned in Blue Face Paint Recipe,,FALSE,0,1,set by Fiun Layeel, +templeforgetfulnessbistort,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnesscomfrey,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnessdamiana,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnessdragonsblood,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnesseyebright,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnessginseng,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnesshawthorn,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnesshyssop,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnessmandrake,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnessmugwort,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnessmyrrh,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnesssaffron,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnessvervain,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnesswormwood,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templeforgetfulnessyarrow,Aelrynth,,,Skill sellback quest.,,FALSE,0,1,set by Guardian of the Temple of Forgetfulness, +templekilledibrexijikti,Aelrynth,,,Fellowship has killed Ibrexi Jikti.,,FALSE,0,1,set by Consort Ibrexi Jikti, +templekilledjexkiki,Aelrynth,,,Fellowship has killed Jexki Ki.,,FALSE,0,1,set by Apprentice Jexki Ki, +templekilledkixktixri,Aelrynth,,,Fellowship has killed Kixkti Xri.,,FALSE,0,1,set by Matriarch Kixkti Xri, +templeliazka,Aelrynth,,,Liazk feeder A has taken a sacrifice.,,TRUE,45,-1,set by Eye of the Watcher, +templeliazkb,Aelrynth,,,Liazk feeder B has taken a sacrifice.,,TRUE,45,-1,set by Eye of the Watcher, +templeliazkburun100,Aelrynth,,,Player killed the boss Burun monster.,,FALSE,0,1,, +templeliazkburun40,Aelrynth,,,Player killed the boss Burun monster.,,FALSE,0,1,, +templeliazkburun60,Aelrynth,,,Player killed the boss Burun monster.,,FALSE,0,1,, +templeliazkburun80,Aelrynth,,,Player killed the boss Burun monster.,,FALSE,0,1,, +templeliazkc,Aelrynth,,,Liazk feeder C has taken a sacrifice.,,TRUE,45,-1,set by Eye of the Watcher, +templenorthwing,Aelrynth,,,Flagged to enter the Temple North wing,,FALSE,0,1,set by Shade of Farelaith, +templeofxikminru,Aelrynth,,,Picked up Aurulent Key,,TRUE,72000,-1,, +templereceivedshirt,Aelrynth,,,Player has obtained the Falatacot shirt,,TRUE,72000,-1,"set by Sarcophagus of High Matriarch, Ixir Zi", +templesacredstone,Aelrynth,,,Picked up the sacred stone.,,TRUE,3600,-1,, +templewitchosen,Aelrynth,,,Player has been chosen to solve the Wit puzzle.,,FALSE,0,1,set by Guardian of the Sacrificial Urns, +templewitcomplete,Aelrynth,,,Fellowship has completed the Wit test.,,FALSE,0,1,set by Judge of the Sacrifice, +templewitspoken,Aelrynth,,,Fellowship has spoken to the Wit Statue.,,TRUE,900,-1,set by Guardian of the Sacrificial Urns, +tentaclestthuuncomplete0408,Aelrynth,,,Player has completed Blightfinger,,TRUE,72000,-1,set by Merwart Mundagurg, +tentaclestthuunstarted0408,Aelrynth,,,Player has started Blightfinger,,FALSE,0,1,set by Merwart Mundagurg, +tentacleweaponpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +testhookerquest,Aelrynth,,,Hookin ain't easy.,,FALSE,0,1,set by EmoteTestHooker, +thearchivist_repeat,Aelrynth,,,Player has alread completed The Archivist Quest once,,FALSE,0,1,set by Ennio di Cinghalle, +thearchivist_start,Aelrynth,,,Player has started The Archivist Quest,,FALSE,0,1,set by Ennio di Cinghalle, +thearchivist_wait,Aelrynth,,,Player wait timer for The Archivist Quest,,TRUE,72000,-1,checked by Ennio di Cinghalle, +themastercritterskilled,Aelrynth,,,Player has killed a creature found in The Master,,TRUE,0,-1,set by The Master Event Watcher, +themasterpass24,Aelrynth,,,Access timer for The Master Pass,,TRUE,86400,-1,set by The Master, +thetooth,Aelrynth,,,Golems do have teeth,,TRUE,15,-1,, +thirdsistercompleted_1212,Aelrynth,,,Player has completed Harvesting the Bulb of Twilight quest.,,TRUE,72000,-1,set by Norus, +thirdsisterstarted_1212,Aelrynth,,,Player has started Harvesting the Bulb of tWILIGHT quest.,,FALSE,0,1,set by Norus, +thrungusfeedings,Aelrynth,,,kill counter,,TRUE,0,6,set by Baby Thrungus, +thrungushovels,Aelrynth,,,Thrungus Hovels Timer,,TRUE,72000,-1,set by Portal Guardian, +thrungushovelsitemturnin,Aelrynth,,,Thrungus Hovels item turn in counter.,,TRUE,0,8,set by Portal Guardian, +thughideoutcured,Aelrynth,,,quest timer,,FALSE,0,1,set by Fiona Woron, +thughideoutprisonbreak,Aelrynth,,,quest timer,,FALSE,0,1,"set by Fiona Woron, Thrungus, Trapped Townsperson", +thunderchickencritterskilled,Aelrynth,,,Player has killed a creature found in Thunder Chicken,,TRUE,0,-1,set by Thunder Chicken Event Watcher, +tihnhealingmachine,Aelrynth,,,Healing Machine Tihn,,TRUE,72000,-1,, +tokenacademygiven,Aelrynth,,,Second version of above so the NPC's use string will work,,FALSE,0,1,set by Guard, +tomenightmaresepulcher_0805,Aelrynth,,,Contract Repeat timer for Sepulcher of Nightmares,,TRUE,72000,-1,set by Sarkin Killcrane, +topathwarden,Aelrynth,,,Sent to the Pathwarden,,FALSE,0,1,"set by A'shadieeyah, Benjirou, Buckminster and 1 more", +torgashstasks,Aelrynth,,,Torgash's Tasks,,TRUE,72000,-1,, +tormentinnersanctum,Aelrynth,,,quest timer,,TRUE,72000,-1,, +tormentshardpickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +tornstripofparchmentpickuptimer,Aelrynth,,,Player has picked up Torn Strip of Parchment of Prophetess,,TRUE,72000,-1,, +totalfiregolemdead,Aelrynth,,,Fire Golem Kill Counter,,TRUE,0,5,set by Water Guardian, +totalgolemcoralviceroydead,Aelrynth,,,You have killed some Coral Golem Viceroys,,TRUE,0,10,set by Coral Golem Viceroy, +totalgolemglacialmargravedead,Aelrynth,,,You have killed some Glacial Golem Magraves,,TRUE,0,10,set by Glacial Golem Margrave, +totalgolemironkingpindead,Aelrynth,,,You have killed some Iron Golem Kingpins,,TRUE,0,10,set by Copper Golem Kingpin, +totalgolemmagmaexarchdead,Aelrynth,,,You have killed some Magma Golem Exarchs,,TRUE,0,10,set by Magma Golem Exarch, +totalgolemmudsludgelorddead,Aelrynth,,,You have killed some Mud Golem SLudge Lords,,TRUE,0,10,set by Mud Golem Sludge Lord, +totalgolemplatinumkingdead,Aelrynth,,,You have killed some Platinum Golem Mountain Kings,,TRUE,0,10,set by Platinum Golem Mountain King, +totalwatergolemdead,Aelrynth,,,Water Golem Kill Counter,,TRUE,0,5,set by Flame Guardian, +totemgiven,Aelrynth,,,Aun Shimauri has given players permission to enter the Palenqual Caverns,,FALSE,0,1,set by Aun Shimauri, +totheartenergycagedown,Aelrynth,,,Player is flagged for Trials Graduation Portal,,FALSE,0,1,set by Lord Kresovus, +tothebarkeep,Aelrynth,,,Sent to the Barkeep,,FALSE,0,1,"set by Alcott, Eiichi, Ghaziyah and 1 more", +totmbucketbalanced,Aelrynth,,,One of the Buckets is balanced in Trial of the Mind,,TRUE,0,2,, +touchedpvphateeffigy200205,Aelrynth,,,You received an XP award from the Effigy of Bitterness,,TRUE,300,-1,set by Effigy of Bitterness, +touchedpvphateeffigy400205,Aelrynth,,,You received an XP award from the Effigy of Anger,,TRUE,300,-1,set by Effigy of Anger, +touchedpvphateeffigy600205,Aelrynth,,,You received an XP award from the Effigy of Cruelty,,TRUE,300,-1,set by Effigy of Cruelty, +touchedpvphateeffigy800205,Aelrynth,,,You received an XP award from the Effigy of Slaughter,,TRUE,300,-1,set by Effigy of Slaughter, +touchedpvphatepillar200205,Aelrynth,,,You touched the Pillar of Bitterness,,TRUE,1800,-1,set by Pillar of Bitterness, +touchedpvphatepillar400205,Aelrynth,,,You touched the Pillar of Anger,,TRUE,1800,-1,set by Pillar of Anger, +touchedpvphatepillar600205,Aelrynth,,,You touched the Pillar of Cruelty,,TRUE,1800,-1,set by Pillar of Cruelty, +touchedpvphatepillar800205,Aelrynth,,,You touched the Pillar of Slaughter,,TRUE,1800,-1,set by Pillar of Slaughter, +towerdungeonaccess,Aelrynth,,,got access to tower portal,,TRUE,72000,-1,, +towerguardian100reward,Aelrynth,,,Player has turned in 100 material for Tower Guarding Repair,,FALSE,0,1,set by Asheron's Servant, +towerguardian50reward,Aelrynth,,,Player has turned in 50 material for Tower Guarding Repair,,FALSE,0,1,set by Asheron's Servant, +towerguardiankill,Aelrynth,,,Player has killed Tower Guardian,,FALSE,0,1,set by Tower Guardian, +towerguardianrepairs_completed,Aelrynth,,,Player has completed Tower Guardian Repairs,,FALSE,0,1,set by Asheron's Servant, +towerguardianrepairs_counter,Aelrynth,,,Player counter for Tower Guardian Repairs,,TRUE,0,200,set by Asheron's Servant, +tracingthestone,Aelrynth,,,Tracing The Stone,,TRUE,72000,-1,, +trackinggrael_wait,Aelrynth,,,Player has completed Tracking Grael Quest,,TRUE,72000,-1,set by Varlanna, +trackinggraelvargol_start,Aelrynth,,,Player has started the Vargol part of Tracking Grael Quest,,FALSE,0,1,set by Varlanna, +trackinggraelwhitespear_start,Aelrynth,,,Player has started the White Spear part of Tracking Grael Quest,,FALSE,0,1,set by Varlanna, +tradealliancemossyherb,Aelrynth,,,Mossy Herb Pickup Timer - Trade Alliance quest,,TRUE,72000,-1,, +tradealliancequestcompleted,Aelrynth,,,Trade Alliance Quest wait timer.,,TRUE,72000,-1,set by Anton Sillezi, +tradealliancequeststarted,Aelrynth,,,Trade Alliance Quest started.,,FALSE,0,1,set by Anton Sillezi, +tradejestercard,Aelrynth,,,Trading Jester card,,FALSE,0,1,"set by Arshid al-Qiyid, Mi Gan-Zo, Monty the Munificent", +trainingacademycomplete,Aelrynth,,,Completion of Training Academy for Exit,,TRUE,0,-1,, +trialoftheheart_flag,Aelrynth,,,Player is flagged for Trial of the Heart Portal,,FALSE,0,1,set by Pillar of the Mind, +trialofthemind_attempts,Aelrynth,,,Player attempts at Trial of the Mind Puzzle,,TRUE,0,3,"set by Bag of Stones, Bucket, Pillar of the Mind", +trialofthemind_flag,Aelrynth,,,Player is flagged for Trial of the Mind Portal,,FALSE,0,1,set by Shadow Kresovus, +trophymageacademy_1110,Aelrynth,,,quest timer,,TRUE,72000,-1,, +trustbetrayalbug0905,Aelrynth,,,Of Trust and Betrayal quest started.,,FALSE,0,1,set by Jedeth Eckhart, +trustbetrayalbugpickedup0905,Aelrynth,,,Pickup timer for Grazer Bug,,TRUE,72000,-1,, +tugofwar,Aelrynth,,,Fort Tethana Tug Of War,,TRUE,72000,-1,set by Jin Ghao, +tukoralieutenantkillcount,Aelrynth,,,Tukora Lieutenant Kill Counter,,TRUE,0,250,set by Claire Artmad, +tukoralieutenantkilltask,Aelrynth,,,Tukora Lieutenant Kill Task,,TRUE,72000,-1,set by Claire Artmad, +tumerokgladiatorkillcount,Aelrynth,,,Tumerok Gladiator Kill Counter,,TRUE,0,25,, +tumerokgladiatorkilltask,Aelrynth,,,Tumerok Gladiator Kill Task,,TRUE,72000,-1,, +tumerokvanguardamulet,Aelrynth,,,Tumerok Vanguard Amulet,,TRUE,72000,-1,, +tumerokvanguardcrossbow,Aelrynth,,,Tumerok Vanguard Crossbow,,TRUE,72000,-1,, +tumerokvanguardmorningstar,Aelrynth,,,Tumerok Vanguard Morningstar,,TRUE,72000,-1,, +tumerokwaraxequest,Aelrynth,,,Tumerok War Axe Quest,,TRUE,72000,-1,, +tumerokwarmacequest,Aelrynth,,,Tumerok War Mace Quest,,TRUE,72000,-1,, +tumerokwarspearquest,Aelrynth,,,Tumerok War Spear Quest,,TRUE,72000,-1,, +tumerokwarstaffquest,Aelrynth,,,Tumerok War Staff Quest,,TRUE,72000,-1,, +tunneloflove,Aelrynth,,,Flagged for entry into Tunnel Of Love,,FALSE,0,1,set by Xireri, +tunneloflovecooldown,Aelrynth,,,Timer for turn in of Butterscotch Suckling to Xireri,,TRUE,72000,-1,set by Xireri, +turbanjalehtaken,Aelrynth,,,You got the heart of Jaleh,,TRUE,72000,-1,, +turgoscorepickup,Aelrynth,Turgo Score Pickup,,quest timer,,TRUE,72000,-1,, +turnedinantiqueplatterhauntedmansion,Aelrynth,,,Player turned in platter,,TRUE,72000,-1,set by Frest Greelving, +turnedincoil,Aelrynth,,,Player has given Slithe the coil,,FALSE,0,1,set by Slithe Tradittor, +turnedincrystallineshard0311,Aelrynth,,,Player turned in a Crystalline Shard.,,TRUE,72000,20,, +turnedindailantiumcrystal,Aelrynth,,,Turned in a Daichroic Crystal to Student.,,TRUE,72000,-1,"set by Anasha, Emissary of Asheron", +turnedindais,Aelrynth,,,Player has given Slithe the Gelidate Dias,,FALSE,0,1,set by Slithe Tradittor, +turnedingear,Aelrynth,,,Player has given Slithe the gear,,FALSE,0,1,set by Slithe Tradittor, +turnedinheadhollowminion,Aelrynth,,,Turned in Hollow Minion Visage to the Mask Collector.,,FALSE,0,1,"set by Alexander the Deft, Janda Sulifiya, Tsua Kagemata", +turnedinimagingcrystal,Aelrynth,,,Player has given Slithe the imaging crystal with the required image,,FALSE,0,1,set by Slithe Tradittor, +turnedinjewelemeraldhauntedmansion,Aelrynth,,,Player turned in jewel,,TRUE,72000,-1,set by Frest Greelving, +turnedinnutbolt,Aelrynth,,,Player has given Slithe nut and bolt,,FALSE,0,1,, +turnedinplatespine,Aelrynth,,,Plate Armoredillo spine turned in,,FALSE,0,1,set by Maqudh al Nishadina, +turnedinrytheransmnemosynelacarra,Aelrynth,,,Turned Mnemosyne in to Lacarra,,TRUE,72000,-1,set by Lacarra Avanthi, +turnedinrytheransmnemosynezho,Aelrynth,,,Turned Mnemosyne in to Zho,,TRUE,72000,-1,set by Zho Heishan, +turnedinshirtpuffyhauntedmansion,Aelrynth,,,Player turned in shirt,,TRUE,72000,-1,set by Frest Greelving, +turnedinspring,Aelrynth,,,Player has given Slithe the spring,,FALSE,0,1,set by Slithe Tradittor, +turnedinvalaracrystal,Aelrynth,,,turned in 2nd crystal,,TRUE,72000,-1,set by Aun Talamura, +turshchallengercomplete,Aelrynth,,,Tursh Challenger Cooldown Timer,,TRUE,72000,-1,set by Ruschk Challenger, +turshscalp,Aelrynth,,,Tursh Scalp,,TRUE,72000,-1,, +turshtotemhighcomplete_0511,Aelrynth,,,Completed Assault (High),,TRUE,72000,-1,set by Tirenia, +turshtotemlowcomplete_0511,Aelrynth,,,Completed Assault (Low),,TRUE,72000,-1,set by Tirenia, +turshtotemmidcomplete_0511,Aelrynth,,,Completed Assault (Mid),,TRUE,72000,-1,set by Tirenia, +turshtotemubercomplete_0511,Aelrynth,,,Completed Assault (Expert),,TRUE,72000,-1,set by Tirenia, +tuskarmoredpickup,Aelrynth,,,Tusk picked up from an Armored Tusker.,,TRUE,72000,-1,, +tuskassailerpickup,Aelrynth,,,Tusk picked up from a Tusker Assailer.,,TRUE,72000,-1,, +tuskcrimsonbackpickup,Aelrynth,,,Tusk picked up from a Crimsonback Tusker.,,TRUE,72000,-1,, +tuskdevastatorpickup,Aelrynth,,,Tusk picked up from a Tusker Devastator.,,TRUE,72000,-1,, +tuskerbloodcollectionstart,Aelrynth,,,Snow Tusker Blood Sample Turning,,FALSE,0,1,set by Archmage Ichihiri, +tuskerbloodcollectionwait,Aelrynth,,,Snow Tusker Blood Sample Turning,,TRUE,72000,-1,set by Archmage Ichihiri, +tuskerexperimentlogpickuptimer,Aelrynth,,,Pickup timer for Tusker Experiment Log,,TRUE,72000,-1,, +tuskerg,Aelrynth,,,Tusker Guard Kill Task Main Flag,,TRUE,72000,-1,set by Shoichi, +tuskergkillcount,Aelrynth,,,Tusker Guard Kill Counter,,TRUE,0,500,set by Shoichi, +tuskerhelm,Aelrynth,,,Player has put on the Tusker Skull Helm.,,FALSE,0,1,set by Tusker Skull Helm, +tuskermask,Aelrynth,,,TBD,,FALSE,0,1,set by Tusker Mask, +tuskfemalepickup,Aelrynth,,,Tusk picked up from a Female Tusker.,,TRUE,72000,-1,, +tuskgoldenbackpickup,Aelrynth,,,Tusk picked up from a Goldenback Tusker.,,TRUE,72000,-1,, +tuskguardpickup,Aelrynth,,,Tusk picked up from a Tusker Guard.,,TRUE,72000,-1,, +tuskliberatorpickup,Aelrynth,,,Tusk picked up from a Tusker Liberator.,,TRUE,72000,-1,, +tuskmalepickup,Aelrynth,,,Tusk picked up from a Male Tusker.,,TRUE,72000,-1,, +tuskplatedpickup,Aelrynth,,,Tusk picked up from a Plated Tusker.,,TRUE,72000,-1,, +tuskrampagerpickup,Aelrynth,,,Tusk picked up from a Tusker Rampager.,,TRUE,72000,-1,, +tuskredeemerpickup,Aelrynth,,,Tusk picked up from a Tusker Redeemer.,,TRUE,72000,-1,, +tusksilverpickup,Aelrynth,,,Tusk picked up from a Silver Tusker.,,TRUE,72000,-1,, +tuskslavepickup,Aelrynth,,,Tusk picked up from a Tusker Slave.,,TRUE,72000,-1,, +tusksnowpickup_0513,Aelrynth,,,Tusk picked up from a Snow Leader Tusker.,,TRUE,72000,-1,, +twilightfragment,Aelrynth,,,Pickup timer for Twilight Fragment - Sepulcher of Nightmares,,TRUE,72000,-1,, +twistedrefugekillcount,Aelrynth,,,Player has killed a crystal in Twisted Refuge.,,TRUE,0,-1,set by Twisted Refuge Stopgap, +tyrinacorruptedessencearmorcount,Aelrynth,,,Corrupted Essence turn in counter for Armor Piece,,TRUE,0,-1,set by Tyrina of Arwic, +uberaerfallestaffobtained,Aelrynth,,,War Staff of Aerfalle,,TRUE,72000,-1,, +uberpalliumobtained,Aelrynth,,,Aerfalle's Supreme Pallium,,TRUE,72000,-1,, +ulgrimsbathrobegiven,Aelrynth,,,Found Splinter1 of Ulgrim's Wand.,,FALSE,0,1,, +ulgrimsbookcaseflag,Aelrynth,,,Access granted to use the Bookcase portal in Xarabydun,,FALSE,0,1,set by Ulgrim the Unquiet, +ulgrimsdrinkingcontestdrinking,Aelrynth,,,Player is competing in Ulgrims Drinking Contest,,FALSE,0,1,set by Stout, +ulgrimsdrinkingcontestdrinks,Aelrynth,,,Player is competing in Ulgrims Drinking Contest,,TRUE,0,5,set by Stout, +ulgrimsdrinkingcontestflag,Aelrynth,,,Player is competing in Ulgrims Drinking Contest,,FALSE,0,1,set by Ulgrim the Unpleasant, +ulgrimsdrinkingcontestwins,Aelrynth,,,Player stamp for ten wins in Ulgrims Drinking Contest,,TRUE,0,10,set by Ulgrim the Unpleasant, +uncoverrenegadescomplete0309,Aelrynth,,,Player wait time for Uncovering the Renegades,,TRUE,72000,-1,set by Aruq ibn Balthar, +uncoverrenegadesstarted0309,Aelrynth,,,Player started Uncovering the Renegades,,FALSE,0,1,set by Aruq ibn Balthar, +undeaddigbone1_0812,Aelrynth,,,quest timer,,FALSE,0,1,set by Mareeno Donn, +undeadjawcollection,Aelrynth,,,Undead Jaw Collection,,TRUE,72000,-1,, +undeadmechanismpickup1,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup10,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup11,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup12,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup13,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup14,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup15,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup16,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup17,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup18,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup19,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup2,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup20,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup3,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup4,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup5,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup6,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup7,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup8,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadmechanismpickup9,Aelrynth,,,Reign of Terror Part III - Undead Mechanism,,TRUE,72000,-1,, +undeadslayerwait,Aelrynth,,,Undead Slayer Quest Wait Timer,,TRUE,72000,-1,, +undercovercryptcompleted_1111,Aelrynth,,,Completed the Holtburg Redoubt Quest,,TRUE,72000,-1,, +underminernotestimer,Aelrynth,,,Underminer Notes pickup timer,,TRUE,72000,-1,, +unfinisheddericostphylactery_pickup,Aelrynth,,,Player has picked up Unfinished Dericost Phylactery,,TRUE,72000,-1,, +uniformregicidepickup,Aelrynth,,,Player has picked up UniformRegicide.,,TRUE,72000,-1,"checked by Ostentatious Farmer, Sir Tenshin", +unleashgearknightcomplete0909,Aelrynth,,,Player has completed Unleash Gear Knight Quest,,TRUE,72000,-1,set by Hei Shou, +unleashgearknightstart0909,Aelrynth,,,Player has started Unleash Gear Knight Quest,,FALSE,0,1,set by Hei Shou, +unreadabledericosttome,Aelrynth,,,Pickup Flag for Dericost Tome,,TRUE,72000,-1,, +untransdreamsaltash,Aelrynth,,,Picked Up Untranslated Dreams of Ash & Salt,,TRUE,72000,-1,, +untransgraelrebellionpickup,Aelrynth,,,Picked Up Untranslated Grael Rebellion,,TRUE,72000,-1,, +untranslatedboundfalatacotfragment_pickup,Aelrynth,,,Player has picked up the Untranslated Bound Falatacot Fragment,,TRUE,72000,-1,, +untranssongofgrael,Aelrynth,,,Picked Up Untranslated Song of Grael,,TRUE,72000,-1,, +upperinsatiablejaw,Aelrynth,,,Upper Insatiable Eater Jaw,,TRUE,72000,-1,checked by Clemenza, +usedattributereset,Aelrynth,,,Used attribute reset at Asheron's Castle,,TRUE,0,-1,set by Chafulumisa, +usedchestmfks,Aelrynth,,,Player used Chest of Mana Forge Keys.,,TRUE,3600,-1,set by Chest of Mana Forge Keys, +usedchestmmds,Aelrynth,,,Player used Chest of Trade Notes.,,TRUE,3600,-1,set by Chest of Trade Notes, +usedfloatingbottle,Aelrynth,,,You've used the floating bottle recently.,,TRUE,72000,-1,set by Floating Bottle, +usedfreeattributereset,Aelrynth,,,Used your free attribute reset at Asheron's Castle,,FALSE,0,1,set by Chafulumisa, +usedfreemeleemasteryreset,Aelrynth,,,Used free Melee Mastery Reset in Arwic,,FALSE,0,1,"set by Axe Mastery, Dagger Mastery, Mace Mastery and 5 more", +usedfreerangedmasteryreset,Aelrynth,,,Used free Ranged Mastery Reset in Arwic,,FALSE,0,1,"set by Bow Mastery, Crossbow Mastery, Magic Mastery and 1 more", +usedfreeskillreset,Aelrynth,,,Used your free skill reset at Asheron's Castle,,FALSE,0,1,set by Fianhe, +usedfreesummoningmasteryreset,Aelrynth,,,Used free Summoning Mastery Reset in Arwic,,FALSE,0,1,"set by Naturalist, Necromancer, Primalist", +usedheadhomunculus,Aelrynth,,,You have used the Head of the Homunculus.,,TRUE,7200,-1,, +usedlifestonecandethkeep,Aelrynth,,,Used the Candeth Keep Lifestone.,,FALSE,0,1,, +usedlumwisp15k,Aelrynth,,,Player used Luminance Wisp.,,TRUE,3600,-1,set by Luminance Wisp, +usedlumwisp30k,Aelrynth,,,Player used Luminance Wisp.,,TRUE,3600,-1,set by Luminance Wisp, +usedlumwisp5k,Aelrynth,,,Player used Luminance Wisp.,,TRUE,3600,-1,set by Luminance Wisp, +usedmeleemasteryreset,Aelrynth,,,Used Melee Mastery Reset in Arwic,,TRUE,2332800,-1,"set by Axe Mastery, Dagger Mastery, Mace Mastery and 5 more", +usedmhoirethrone,Aelrynth,,,quest timer,,FALSE,0,1,set by Ancient Throne, +usedmonolithdark,Aelrynth,,,You have used the Dark Monolith.,,TRUE,7200,-1,, +usednuhmudiralifestone,Aelrynth,,,Used new Nuhmudira Lifestone,,FALSE,0,1,"checked by Antius Blackmoor, Camryn, Nuhmudira's Student, Guard Audrey and 1 more", +usedpaintingtrialofheart,Aelrynth,,,Player has used the Painting in Trial of Heart,,FALSE,0,1,set by Painting of the Building of Linvak Tukal, +usedrangedmasteryreset,Aelrynth,,,Used Ranged Mastery Reset in Arwic,,TRUE,2332800,-1,"set by Bow Mastery, Crossbow Mastery, Magic Mastery and 1 more", +usedskillreset,Aelrynth,,,Used skill reset at Asheron's Castle,,TRUE,0,-1,set by Fianhe, +usedsummoningmasteryreset,Aelrynth,,,Used Summoning Mastery Reset in Arwic,,TRUE,2332800,-1,"set by Naturalist, Necromancer, Primalist", +utterdarknessrobepickup,Aelrynth,,,quest timer,,TRUE,72000,-1,, +variniafails,Aelrynth,,,Times player can incorrectly guess Varinia passwords,,TRUE,0,4,set by Varinia, +vaultofeternalslumberflag,Aelrynth,,,Player has access to Landscape Vault of Eternal Slumber portal,,FALSE,0,1,, +vendortimaruarmorer,Aelrynth,,,Timaru NPCs will recognize players who return to them within the next 60 minutes,,TRUE,3600,-1,set by Aun Maanuawa the Armorer, +vendortimarubarkeep,Aelrynth,,,Timaru NPCs will recognize players who return to them within the next 60 minutes,,TRUE,3600,-1,set by Aun Laranawa the Barkeep, +vendortimarubowyer,Aelrynth,,,Timaru NPCs will recognize players who return to them within the next 60 minutes,,TRUE,3600,-1,set by Aun Paikitea the Bowyer, +vendortimaruhealer,Aelrynth,,,Timaru NPCs will recognize players who return to them within the next 60 minutes,,TRUE,3600,-1,set by Aun Taguauri the Healer, +vendortimarujeweler,Aelrynth,,,Timaru NPCs will recognize players who return to them within the next 60 minutes,,TRUE,3600,-1,set by Aun Ngaiona the Jeweler, +vendortimarushaman,Aelrynth,,,Timaru NPCs will recognize players who return to them within the next 60 minutes,,TRUE,3600,-1,set by Aun Dreganaua the Elder Shaman, +vendortimarushopkeep,Aelrynth,,,Timaru NPCs will recognize players who return to them within the next 60 minutes,,TRUE,3600,-1,set by Aun Mireona the Shopkeep, +verymadcowwave1critterskilled,Aelrynth,,,Player has killed a creature found in Very Mad Cow,,TRUE,0,-1,set by VeryMadCow Event Watcher, +verymadcowwave2critterskilled,Aelrynth,,,Player has killed a creature found in Very Mad Cow,,TRUE,0,-1,set by VeryMadCow Event Watcher, +viamontianknightskillcount,Aelrynth,,,Viamontian Knights Kill Counter,,TRUE,0,30,, +viamontianknightskilltask,Aelrynth,,,Viamontian Knights Kill Task,,TRUE,72001,-1,, +viamontianmanatarmskillcount,Aelrynth,,,Viamontian Man-at-Arms Kill Counter,,TRUE,0,50,set by Robert Gutsmasher, +viamontianmanatarmskilltask,Aelrynth,,,Viamontian Man-at-Arms Kill Task,,TRUE,72000,-1,set by Robert Gutsmasher, +viridiananekshenkillcount,Aelrynth,,,Viridian A'nekshen Kill Counter,,TRUE,0,10,, +viridiananekshenkilltask,Aelrynth,,,Viridian A'nekshen Kill Task,,TRUE,72000,-1,, +viridianfail,Aelrynth,,,quest timer,,FALSE,0,1,, +viridianflag,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Ash, +viridianportal2rewardwait,Aelrynth,,,Viridian Portal 2 Rewards Cooldown,,TRUE,86400,-1,set by Viridian Portal, +viridianportal3rewardwait,Aelrynth,,,Viridian Portal 3 Rewards Cooldown,,TRUE,86400,-1,set by Viridian Portal, +viridianportal4rewardwait,Aelrynth,,,Viridian Portal 4 Rewards Cooldown,,TRUE,86400,-1,set by Viridian Portal, +viridianportal5rewardwait,Aelrynth,,,Viridian Portal 5 Rewards Cooldown,,TRUE,86400,-1,set by Viridian Portal, +viridianportal6rewardwait,Aelrynth,,,Viridian Portal 6 Rewards Cooldown,,TRUE,86400,-1,set by Viridian Portal, +viridianrecharge,Aelrynth,,,quest timer,,TRUE,20,-1,"set by Ancient Statue of the Viridian Rise, Ancient Statue of the Viridian Root, Viridian Portal", +viridianritual1,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Oak, +viridianritual2,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Hickory, +viridianritual3,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Birch, +viridianritual4,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Willow, +viridianritual5,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Maple, +viridianritual6,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Cedar, +viridianritual7,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Pine, +viridianritual8,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Spruce, +viridianritual9,Aelrynth,,,quest timer,,FALSE,0,1,set by Guardian of Yew, +viridianwaspkillcount,Aelrynth,,,Viridian Wasp Kill Counter,,TRUE,0,10,, +viridianwaspkilltask,Aelrynth,,,Viridian Wasp Kill Task,,TRUE,72000,-1,, +viridianzefirkillcount,Aelrynth,,,Viridian Zefir Kill Counter,,TRUE,0,10,, +viridianzefirkilltask,Aelrynth,,,Viridian Zefir Kill Task,,TRUE,72000,-1,, +virindiaxe,Aelrynth,,,Quintessence Axe,,TRUE,72000,-1,, +virindichimera,Aelrynth,,,Virindi Chimera,,TRUE,72000,-1,"set by Narrow Rift, Shallow Rift", +virindiessence,Aelrynth,,,Virindi Essence,,TRUE,72000,-1,, +virindiisland,Aelrynth,,,Singularity Island,,FALSE,0,1,set by Guardian of the Singularity, +virindikiller,Aelrynth,,,Ahurenga Collector will stamp players who bring him Virindi jewels and refuse to trade with them again,,TRUE,72000,-1,set by Hea Riketura the Collector, +virindikillerbagsiraluun,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillerbagsiraluun1,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillerbagsiraluun2,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillerbagsiraluun3,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillerbagsiraluun4,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillerbagsiraluun5,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillercarenzipeltburrower,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillercarenzipeltpouchling,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillercarenzipeltrabid,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillercarenzipeltsentry,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillercarenzipeltstalker,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillerdrudgecharm,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillerfeatherssiraluun,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillergolemheartforest,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillergolemheartmud,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillergolemheartsand,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillergolemheartvapor,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillergolemheartwater,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillerolthoiclaw,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillerpendantaun,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillersiraluunclawlittoral,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillersiraluunclawmarsh,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillersiraluunclawstrand,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillersiraluunclawtidal,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillersiraluunclawtimber,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindikillerwatergolemhearts,Aelrynth,,,This quest flag is obsolete.,,TRUE,72000,-1,, +virindimanacles,Aelrynth,,,Virindi Manacles,,TRUE,72000,-1,, +virindimasteramulet,Aelrynth,,,Virindi Master's Amulet,,TRUE,72000,-1,, +virindimessageshardpickuptimer,Aelrynth,,,Pick up timer for Virindi Message Shard,,TRUE,72000,-1,, +virindiparadoxkillcount,Aelrynth,,,Virindi Paradox Kill Counter,,TRUE,0,75,set by Guard Taziq, +virindiparadoxkilltask,Aelrynth,,,Virindi Paradox Kill Task,,TRUE,72000,-1,set by Guard Taziq, +virindiquidioxkillcount,Aelrynth,,,Virindi Quidiox Kill Counter,,TRUE,0,75,set by Guard Q'alia, +virindiquidioxkilltask,Aelrynth,,,Virindi Quidiox Kill Task,,TRUE,72000,-1,set by Guard Q'alia, +virindirescuecompleted0612,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Omarah, +virindirescuestarted0612,Aelrynth,,,quest timer,,FALSE,0,1,set by Omarah, +virinditatteredcloak,Aelrynth,,,Tattered Virindi Cloak,,TRUE,72000,-1,, +visionquest1,Aelrynth,,,quest timer,,TRUE,1800,-1,set by Keh Fire, +visionquest2,Aelrynth,,,quest timer,,TRUE,1800,-1,set by Keh Fire, +visionquest3,Aelrynth,,,quest timer,,TRUE,1800,-1,set by Keh Fire, +visionquest4,Aelrynth,,,quest timer,,TRUE,1800,-1,set by Keh Fire, +visionquestcompleted1007,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Leopold, +visionquestrepeat1007,Aelrynth,,,Player has completed Delving into Claudes Mind once.,,FALSE,0,1,set by Leopold, +visionqueststarted_0911,Aelrynth,,,quest timer,,FALSE,0,1,, +visitingshaman_flag,Aelrynth,,,Player has spoken to one of the Visiting Shamans while flagged to do so.,,FALSE,0,1,set by Visiting Shaman, +visitors4completed_0713,Aelrynth,,,quest timer,,TRUE,72000,-1,set by Virindi Delegate, +visitorsgotaccess_0713,Aelrynth,,,quest timer,,FALSE,0,1,set by Rynthid Crystal Access Device, +vissflagcomplete,Aelrynth,,,Flagged to use Vissidal Island portal,,FALSE,0,1,set by Watcher of the Deep, +voidcrystalfinished,Aelrynth,,,Retrieved Void Crystal,,FALSE,0,1,set by Balior, +voidcrystalflag,Aelrynth,,,Flagged for entering Collegium Occultus dungeon,,FALSE,0,1,set by Balior, +voidcrystalpickup,Aelrynth,,,Void Crystal pickup timer,,TRUE,72000,-1,, +voidlordkillcount,Aelrynth,,,Void Lord Kill Counter,,TRUE,0,15,, +voidlordkilltask,Aelrynth,,,Void Lord Kill Task,,TRUE,72000,-1,, +volkamagiven,Aelrynth,,,Aun Shimauri will give players permission to enter the Palenqual dungeon only once per month.,,TRUE,72000,-1,, +voraciouseaterjaw,Aelrynth,,,Voracious Eater Jaw,,TRUE,72000,-1,checked by Clemenza, +voraciouseaterkillcount,Aelrynth,,,Voracious Eater Kill Counter,,TRUE,0,50,set by Aun Ruperea, +voraciouseaterkilltask,Aelrynth,,,Voracious Eater Kill Task,,TRUE,72000,-1,set by Aun Ruperea, +warriorcorthosbet,Aelrynth,,,Player bet on Warrior Corthos,,FALSE,0,1,set by Warrior Corthos, +waspwingdone,Aelrynth,,,No more wasp wings for the Academy Collector,,FALSE,0,1,set by Academy Foreman, +waspwingdone1,Aelrynth,,,Second verson of above so Collector will work,,FALSE,0,1,set by Academy Foreman, +waspwinggiven,Aelrynth,,,Player has handed over a Carpenter Wasp wing in the Academy,,FALSE,0,1,set by Academy Foreman, +watchersmessageshardpickuptimer,Aelrynth,,,Pickup timer for Watchers Message Shard,,TRUE,72000,-1,, +waterbanewellquest,Aelrynth,,,Water Bane Well Quest,,TRUE,72000,-1,, +wavekillcount,Aelrynth,,,Player has killed a creature in the room.,,TRUE,0,-1,set by Wave Watcher, +weakenedharbingerreflectiveshard,Aelrynth,,,Weakened Harbinger Reflective Shard pickup timer,,TRUE,72000,-1,, +wearingmask0806,Aelrynth,,,quest timer,,FALSE,0,1,set by Sawato Bandit's Mask, +weedingofthederutree,Aelrynth,,,Weeding of the Deru Tree,,TRUE,72000,-1,, +weedingofthederutree_repeat,Aelrynth,,,Player as completed Weeding of the Deru Tree Quest once.,,FALSE,0,1,set by Valerian McGreggor, +wellbalancedlugiangreataxepickuptimer,Aelrynth,,,Pickup timer for Well Balanced Lugian Great Axe,,TRUE,72000,-1,, +westernpedestalshard_pickup,Aelrynth,,,Player has picked up the Shard of the Western Pedestal.,,TRUE,72000,-1,, +westernroyalhiveok,Aelrynth,,,quest timer,,TRUE,7200,-1,set by Olthoi Hive Eviscerator, +whisperingbladechapterhouse_flag,Aelrynth,,,Access granted to the Whispering Blade Chapterhouse,,FALSE,0,1,set by Ring of the Whispering Blade, +whisperingbladechapterhouseaccess_start,Aelrynth,,,Player has started Whispering Blade Chapterhouse Access Quest,,FALSE,0,1,set by Harkwull the Discreet, +whisperingbladechapterhouseaccess_wait,Aelrynth,,,Player wait timer for Whispering Blade Chapterhouse Access Quest,,TRUE,72000,-1,set by Harkwull the Discreet, +whisperingbladeinfiltrationcomplete,Aelrynth,,,Whispering Blade Infiltration Complete,,FALSE,0,1,set by Garmasi, +whisperingbladeinfiltrationstarted,Aelrynth,,,Whispering Blade Infiltration Started,,FALSE,0,1,set by Garmasi, +whisperingbladeinfiltrationwait,Aelrynth,,,Whispering Blade Infiltration quest cooldown,,TRUE,72000,-1,set by Garmasi, +whisperingbladeloyaltyreset,Aelrynth,,,Loyalty with Whispering Blade faction reset,,FALSE,0,1,set by Giordonni, +whitefireinfusion,Aelrynth,,,White Fire SOLL Infusion,,TRUE,72000,-1,, +whitetotemshard_pickup,Aelrynth,,,Player has picked up Shard of the White Totem,,TRUE,72000,-1,, +whitetotemtemple_flag,Aelrynth,,,Player flag for White Totem Gateway,,FALSE,0,1,set by White Totem Gateway, +wickedskeletonkillcount,Aelrynth,,,Wicked Skeleton Kill Counter,,TRUE,0,100,set by Ruqaya al Mubarak, +wickedskeletonkilltask,Aelrynth,,,Wicked Skeleton Kill Task,,TRUE,72000,-1,set by Ruqaya al Mubarak, +wieldingfishingpole,Aelrynth,Fishing,,Player has the fishing pole weilded.,,FALSE,0,1,"set by Fishing Pole, Fishing Rod (Advanced), Fishing Rod (Beginner) and 2 more", +wightbladesorcererkillcount,Aelrynth,,,Wight Blade Sorcerer Kill Counter,,TRUE,0,12,, +wightbladesorcererkilltask,Aelrynth,,,Wight Blade Sorcerer Kill Task,,TRUE,72000,-1,, +wightkilltask,Aelrynth,,,Wight Kill Task,,TRUE,72000,-1,, +witheredatollatlatl0105,Aelrynth,,,You have acquired the Anemic Atlatl! Now go out and kill something!,,TRUE,72000,-1,, +witheredatollaxe0105,Aelrynth,,,You have acquired the Insensate Axe! Now go out and kill something!,,TRUE,72000,-1,, +witheredatollbow0105,Aelrynth,,,You have acquired the Barren Bow! Now go out and kill something!,,TRUE,72000,-1,, +witheredatollcrossbow0105,Aelrynth,,,Wretched Crossbow pickup,,TRUE,72000,-1,, +witheredatollknuckles0105,Aelrynth,,,Lifeless Knuckles pickup,,TRUE,72000,-1,, +witheredatollstaff0105,Aelrynth,,,Soulless Staff pickup,,TRUE,72000,-1,, +witheredatollsword0105,Aelrynth,,,You have acquired the Sterile Sword! Now go out and kill something!,,TRUE,72000,-1,, +workersmotivated,Aelrynth,,,Counter for On Strike,,TRUE,0,10,"set by Mosswart Grunt, Mosswart Worker", +wrentalkweek1,Aelrynth,,,quest timer,,FALSE,0,1,set by Wren the Curious, +writingjhongmiaquest,Aelrynth,,,Writing Jhong MiA Quest,,TRUE,518400,-1,, +writingjhongmibquest,Aelrynth,,,Writing Jhong MiB Quest,,TRUE,72000,-1,, +writingjhongmicquest,Aelrynth,,,Writing Jhong MiC Quest,,TRUE,72000,-1,, +writofapology_0508,Aelrynth,,,Writ of Apology Quest - Player can get 1 Writ if they have this quest bestowed,,FALSE,0,1,checked by Royal Guard, +xbowstatuepickup,Aelrynth,,,Player has picked up this weapons and cannot pick up another one for 1 day,,TRUE,72000,-1,, +xikminrutrophy32024,Aelrynth,,,Offering of Xi Minru given,,FALSE,0,1,set by Shrine to Xik Minru, +xikminrutrophy70094,Aelrynth,,,Offering of Xi Minru given,,FALSE,0,1,set by Shrine to Xik Minru, +xikminrutrophy70095,Aelrynth,,,Offering of Xi Minru given,,FALSE,0,1,set by Shrine to Xik Minru, +xikminrutrophy70096,Aelrynth,,,Offering of Xi Minru given,,FALSE,0,1,set by Shrine to Xik Minru, +xikminrutrophy70097,Aelrynth,,,Offering of Xi Minru given,,FALSE,0,1,set by Shrine to Xik Minru, +yalainbookgiven,Aelrynth,,,Player has been given the Yalain books,,TRUE,72000,-1,set by Bookshelf, +yanshimatronclawtimer,Aelrynth,,,Yanshi Matron's Claw pickup timer,,TRUE,72000,-1,, +yanshimine,Aelrynth,,,Flagged to enter the Yanshi Lower Undermine,,FALSE,0,1,set by Royal Guard Adrana, +yanshitunnelsclaw1205,Aelrynth,,,Started the Yanshi Tunnels quest,,FALSE,0,1,set by Royal Guard Adrana, +yanshitunnelscomplete1205,Aelrynth,,,Yanshi Tunnels quest timer,,TRUE,72000,-1,set by Royal Guard Adrana, +yanshiwritingmid,Aelrynth,,,Writing Jhong MiD Quest,,TRUE,72000,-1,set by Dai Ya the Scholar, +yaojiloukaquest,Aelrynth,,,Yaoji Lou Ka Quest,,TRUE,72000,-1,, +yaraqahyaraletter,Aelrynth,,,Yaraq Ahyara Letter Quest,,TRUE,72000,-1,set by Ahyara, +yaraqapplecoveperfect1204,Aelrynth,,,Sea Temple Catacombs Quest,,TRUE,72000,-1,, +yaraqapplepiehot1204,Aelrynth,,,Sea Temple Catacombs Quest,,TRUE,72000,-1,, +yaraqbakingpancoveapple1204,Aelrynth,,,Sea Temple Catacombs Quest,,TRUE,72000,-1,, +yaraqcidercoveappleaged1204,Aelrynth,,,Sea Temple Catacombs Quest,,TRUE,72000,-1,, +yaraqciderhardcoveapple1204,Aelrynth,,,Sea Temple Catacombs Quest,,TRUE,72000,-1,, +yaraqcomplete,Aelrynth,,,Player has completed the Yaraq Regicide Quest,,TRUE,72000,-1,set by Dame Tsaya, +yaraqgreetinggiven,Aelrynth,,,Tsaya has said hello to player,,FALSE,0,1,set by Dame Tsaya, +yaraqheadmarionettemadstar1204,Aelrynth,,,Yaraq Akyafi Quest,,TRUE,72000,-1,, +yaraqknifecoveapple1204,Aelrynth,,,Sea Temple Catacombs Quest,,TRUE,72000,-1,, +yaraqnasunletter,Aelrynth,,,Yaraq Nasun Letter Quest,,TRUE,72000,-1,set by Nasun ibn Tifar, +yaraqnotecovecrypt1204,Aelrynth,,,Ma'yad ibn Ibsar Quest,,TRUE,72000,-1,, +yaraqregicidebanditgreeting,Aelrynth,,,Yaraq Bandit has said hello to player,,FALSE,0,1,set by Stranger in Town, +yaraqwinecoveapple1204,Aelrynth,,,Sea Temple Catacombs Quest,,TRUE,72000,-1,, +yellowmonsterseed,Aelrynth,,,Yellow Monster Seed counter,,TRUE,0,5,set by Sara Sen, +zaikhaldefensecoppercomplete_0511,Aelrynth,,,Completed Defense of Zaikhal (Copper),,TRUE,72000,-1,set by Jun Sawashima, +zaikhaldefensegoldcomplete_0511,Aelrynth,,,Completed Defense of Zaikhal (Gold),,TRUE,72000,-1,set by Jun Sawashima, +zaikhaldefenseplatinumcomplete_0511,Aelrynth,,,Completed Defense of Zaikhal (Platinum),,TRUE,72000,-1,set by Jun Sawashima, +zaikhaldefensesilvercomplete_0511,Aelrynth,,,Completed Defense of Zaikhal (Silver),,TRUE,72000,-1,set by Jun Sawashima, +zenithphase,Aelrynth,,,Time window for using the Rift Closing Device to spawn a Zenith in the Portal Space Rifts quest,,TRUE,180,-1,"set by Acid Plane Stopgap, Electric Plane Stopgap, Fire Plane Stopgap and 1 more", +zigguratentrance,Aelrynth,,,Player may enter any of the ziggurats,,FALSE,0,1,set by Asheron's Platinum Golem, +zombiebrainpickup,Aelrynth,,,Picked up a Decaying Zombie Brain Portion,,TRUE,72000,-1,, +zombiebutlerarm,Aelrynth,,,Turned in a Fresh Zombie Arm.,,TRUE,0,2,set by Ungrim the Unpleasant Smelling, +zombiebutlerhead,Aelrynth,,,Turned in a Fresh Zombie Head.,,FALSE,0,1,set by Ungrim the Unpleasant Smelling, +zombiebutlerleg,Aelrynth,,,Turned in a Fresh Zombie Leg.,,TRUE,0,2,set by Ungrim the Unpleasant Smelling, +zombiebutlertorso,Aelrynth,,,Turned in a Fresh Zombie Torso.,,FALSE,0,1,set by Ungrim the Unpleasant Smelling, +beaconcomplete,Aelrynth,,,,,,,,,TRUE +bulboftwilightseedgiven,Aelrynth,,,,,,,,,TRUE +burportalservitor,Aelrynth,,,,,,,,,TRUE +darkrecording1,Aelrynth,,,,,,,,,TRUE +darkrecording2,Aelrynth,,,,,,,,,TRUE +darkrockstart,Aelrynth,,,,,,,,,TRUE +defeatedbonecrunchrepeat,Aelrynth,,,,,,,,,TRUE +elderspiritssealstamp,Aelrynth,,,,,,,,,TRUE +furgalmushroomturnin,Aelrynth,,,,,,,,,TRUE +heartofmadness,Aelrynth,,,,,,,,,TRUE +leatherhandedin,Aelrynth,,,,,,,,,TRUE +maruuntestweek1,Aelrynth,,,,,,,,,TRUE +metalhandedin,Aelrynth,,,,,,,,,TRUE +mhoireswflame1,Aelrynth,,,,,,,,,TRUE +mhoireswflame2,Aelrynth,,,,,,,,,TRUE +mhoireswflame3,Aelrynth,,,,,,,,,TRUE +mhoireswflame4,Aelrynth,,,,,,,,,TRUE +mhoireswflame5,Aelrynth,,,,,,,,,TRUE +mhoireswflame6,Aelrynth,,,,,,,,,TRUE +mhoireswflame7,Aelrynth,,,,,,,,,TRUE +mhoireswflame8,Aelrynth,,,,,,,,,TRUE +oswaldjournal,Aelrynth,,,,,,,,,TRUE +pickedupquiddityingot,Aelrynth,,,,,,,,,TRUE +progenitoringotstarted,Aelrynth,,,,,,,,,TRUE +realaidaineasternvault,Aelrynth,,,,,,,,,TRUE +realaidainnorthernvault,Aelrynth,,,,,,,,,TRUE +realaidainwesternvault,Aelrynth,,,,,,,,,TRUE +seed1_0713,Aelrynth,,,,,,,,,TRUE +seed2_0713,Aelrynth,,,,,,,,,TRUE +seed3_0713,Aelrynth,,,,,,,,,TRUE +summoningcaverhan,Aelrynth,,,,,,,,,TRUE +thrungaldenportal,Aelrynth,,,,,,,,,TRUE +turshdungeonflag,Aelrynth,,,,,,,,,TRUE +turshscalpcount,Aelrynth,,,,,,,,,TRUE +ubermetos,Aelrynth,,,,,,,,,TRUE +ubermetoscatacombs,Aelrynth,,,,,,,,,TRUE +ubermetostemp10,Aelrynth,,,,,,,,,TRUE +viridianritualfail,Aelrynth,,,,,,,,,TRUE diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj b/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj new file mode 100644 index 0000000..f3dabeb --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj @@ -0,0 +1,37 @@ + + + + + RynthCore.Plugin.RynthAelrynth + 0.2.0 + aelrynth + Aelrynth + aelrynth.com|144.217.84.148 + Aelrynth*|Aeshnidae* + Aelrynth only: the server card (its mods, links, account setup), Aelrynth's leaderboards and Trials records in the Mini Remote, the account vault in Global Inventory, the difficulty tier for RynthAi, and Aelrynth's quests in RynthOracle. + + + + + + + + + + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs new file mode 100644 index 0000000..770834b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs @@ -0,0 +1,28 @@ +// ServerData.cs - What is known about Aelrynth (RynthAelrynth). Identity (id, hosts, world names) is in the csproj. +// Aelrynth isn't in the public server list; this comes from RynthCore's own Aelrynth support +// (Compatibility/AelrynthWire.cs, Net/AelrynthVaultWire.cs) and RynthOracle's quest pack. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9020, + Emulator = "ACE", + Ruleset = "PvE", + Summary = "Aelrynth (aelrynth.com), an ACE server with its own mods.", + Facts = new[] + { + "Bank mod: Radiance and Luminance banking (RynthCore reads its totals).", + "Skill Mastery mod (RynthCore shows mastery progress).", + "Account vault for mules (RynthCore reads its contents; RynthAelrynth puts it in Global Inventory, /rserver vault).", + "Its quest pack (quests.aelrynth.csv, from Aelrynth's world database) shows in RynthOracle's Quests tab.", + "RynthAelrynth's Leaderboards page (Server section, or /rserver): the /top boards and /trial dungeon records.", + "Difficulty tiers (awakened worlds, scaled copies: +5% monster health a tier): RynthAelrynth shares the tier with RynthAi, which keeps learned HP and kill numbers per tier.", + "The world was named Aeshnidae before; both names count.", + }, + Website = "https://aelrynth.com", + Source = "RynthCore's Aelrynth support and RynthOracle, 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/THIRD_PARTY_NOTICES.md b/Plugins/RynthCore.Plugin.RynthAelrynth/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..f930d75 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAelrynth/THIRD_PARTY_NOTICES.md @@ -0,0 +1,39 @@ +# Third-party notices: RynthAelrynth + +RynthAelrynth's quest pack (`Resources/quests.aelrynth.csv`, offered to RynthOracle's Quests tab +through "RynthServer.QuestPack") is generated from Aelrynth's own world database by +`Tools/RynthOracle.QuestPackGen`. Where a quest is also in **Oracle of Dereth**'s master quest list +(the Decal plugin for Asheron's Call by **Advis Eveldan**, GitHub: +[advis61](https://github.com/advis61/OracleOfDereth)), RynthOracle keeps that list's name and notes +and the pack only adds Aelrynth's timers and who sets the flag; a flag only another server's pack +knows takes that pack's text, which is Advis's. The pack was part of RynthOracle until 2026-10-21 +and moved here, with the server it belongs to. Thank you, Advis! + +- Upstream: https://github.com/advis61/OracleOfDereth +- Licence: MIT. The upstream README states "License: MIT". The repository has no separate + LICENSE file and names no copyright line, so the standard MIT text is reproduced below + with the author and the years of the repository's history. + +--- + +MIT License + +Copyright (c) 2024-2026 Advis Eveldan (GitHub: advis61) and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Plugins/RynthCore.Plugin.RynthColdeve/RynthCore.Plugin.RynthColdeve.csproj b/Plugins/RynthCore.Plugin.RynthColdeve/RynthCore.Plugin.RynthColdeve.csproj new file mode 100644 index 0000000..551ffc8 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthColdeve/RynthCore.Plugin.RynthColdeve.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthColdeve + 0.1.0 + coldeve + Coldeve + play.coldeve.ac + Coldeve + Coldeve only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthColdeve/ServerData.cs b/Plugins/RynthCore.Plugin.RynthColdeve/ServerData.cs new file mode 100644 index 0000000..ba07823 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthColdeve/ServerData.cs @@ -0,0 +1,18 @@ +// ServerData.cs - What is known about Coldeve (RynthColdeve). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "A PVE AC Server evolving to provide a end of retail experience running ACEmulator.", + Facts = new[] { "End-of-retail experience on ACEmulator." }, + Discord = "https://discord.gg/nUR4PHe", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestData.cs b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestData.cs new file mode 100644 index 0000000..deaf617 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestData.cs @@ -0,0 +1,428 @@ +// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. +// Moved here from RynthOracle (Data/Conquest.cs) on 2026-10-20: Conquest-only features live in RynthConquest. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; +using RynthCore.Plugin.ServerPack; + +namespace RynthCore.Plugin.RynthConquest; + +/// A labelled value from a server reply ("Pyreals" = "1,039,678,533 (4,158 MMDs)"). +internal sealed class NamedValue +{ + public string Name = ""; + public string Value = ""; +} + +/// One of ConquestAC's advanced augmentations (counts from "/augs"). +internal sealed class ConquestAug +{ + public readonly string Name; + public readonly int CoinCost; + public readonly double LumBase, LumPercent; + public int Count; + + public ConquestAug(string name, int coinCost, double lumBase, double lumPercent) + { + Name = name; CoinCost = coinCost; LumBase = lumBase; LumPercent = lumPercent; + } + + /// The next purchase's luminance (Conquest-ACE's tiered cost, as upstream mirrors it). + public long NextLuminanceCost() + { + long idx = Count; + (double tierBase, long pos) = idx >= 65 ? (LumBase * 30.0, idx - 65) + : idx >= 60 ? (LumBase * 12.0, idx - 60) + : idx >= 30 ? (LumBase * 4.8, idx - 30) + : idx >= 15 ? (LumBase * 2.4, idx - 15) + : (LumBase, idx); + // The server truncates to long; the epsilon keeps 6,229,499.9999 (binary floating point) at the + // confirmed in-game 6,229,500 (Creature at 25). + return (long)(tierBase * (1.0 + pos * LumPercent) + 1e-6); + } + + public string NextCostText() => + $"{CoinCost} coins, {(NextLuminanceCost() / 1_000_000.0).ToString("0.##", CultureInfo.InvariantCulture)}M lum"; + + private double ResistPercent() + { + const double MaxBonus = 0.32, LinearRate = 0.003, Tuning = 0.0034597; + const int LinearCap = 10; + if (Count <= 0) return 0.0; + double bonus = Count <= LinearCap + ? Count * LinearRate + : LinearCap * LinearRate + (MaxBonus - LinearCap * LinearRate) * (1.0 - Math.Pow(1.0 - Tuning, Count - LinearCap)); + return Math.Min(bonus, MaxBonus) * 100.0; + } + + /// The effect at the current count (upstream's reading of the Conquest-ACE source). + public string Effect() => Name switch + { + "Creature" => $"+{Count} to creature buffs, -{Count} to debuffs", + "Item" => $"+{Count}% attack/melee, +{Count * 0.5:0.#} blood/spirit, +{Count} AL", + "Life" => $"+{ResistPercent():0.##}% prot, +{ResistPercent():0.##}% vuln, +{Count * 0.10:0.##} regen, +{Count / 10} surge rating", + "War" => $"+{Count * 2}% war magic potency", + "Void" => $"+{Count * 1.5:0.##}% void magic potency", + "Melee" => $"+{Count} melee damage, +{Count * 1.5:0.#}% crit damage", + "Missile" => $"+{Count} missile damage, +{Count * 1.5:0.#}% crit damage", + "Duration" => $"+{Count * 5}% spell duration", + "Specialization" => $"+{Count} skill spec cap (now {70 + Count})", + _ => "", + }; +} + +/// A fellowship from "/fship list". +internal sealed class ConquestFellowship +{ + public string Name = "", Leader = "", Members = "", Location = ""; + + public int MemberCount + { + get + { + int slash = Members.IndexOf('/'); + return int.TryParse(slash >= 0 ? Members[..slash] : Members, out int n) ? n : 0; + } + } +} + +/// A row of a leaderboard. +internal sealed class BoardRow +{ + public int Rank; + public string Name = ""; + public string Value = ""; + public string Extra = ""; + public bool IsYou; +} + +/// One of ConquestAC's /top boards. +internal sealed class ConquestBoard +{ + public readonly string Key, Label, Header; + public readonly List Rows = new(); + public BoardRow? You; + public DateTime UpdatedUtc = DateTime.MinValue; + + public ConquestBoard(string key, string label, string header) { Key = key; Label = label; Header = header; } + + public string Command => "/top " + Key; +} + +/// +/// Everything Conquest-only: bank balances and bank commands ("/b", "/bank"), +/// advanced augmentations ("/augs"), enlightenment augmentations ("/enl augs"), the XP bonus +/// breakdown ("/bonus"), fellowships looking for members ("/fship list"), the /top boards, and +/// the void damage-over-time duration scaling. RynthConquest only feeds it chat while the server is +/// Conquest (and only loads there); every reply regex is anchored at the start of the line (after +/// an optional chat timestamp), as upstream does, so a pasted copy in a chat channel can't +/// overwrite your values. +/// +internal sealed class ConquestData +{ + private const string Ts = @"^\s*(?:\[[^\]]*\][\s:]*)?"; + + // /b balances + private static readonly Regex BankLine = new(Ts + @"\[BANK\]\s+(.+?):\s*(.*\S)\s*$"); + private static readonly Regex BankChrome = new(Ts + @"\[BANK\]\s+[^:]*:\s*$"); + private static readonly Regex EventToken = new(@"Event Tokens \[(.+?)\]"); + private static readonly Regex DepositReply = new(Ts + @"(?:No .+? (?:found|available) to deposit|Deposited\b.*)\s*$", RegexOptions.IgnoreCase); + // /augs + private static readonly Regex AugLine = new(Ts + @"(Creature|Item|Life|War|Void|Duration|Specialization|Melee|Missile):\s*([\d,]+)\b"); + private static readonly Regex AugChrome = new(Ts + @"(?:-{3,}|Advanced Augmentation Levels:|Use /aug info for per-level effect details\.)\s*$", RegexOptions.IgnoreCase); + // /enl augs + private static readonly Regex EnlLine = new(Ts + @"([A-Za-z][A-Za-z '\-]*?):\s*(([\d,]+)\s*\(\s*[\d,]+\s+max\s*\))\s*$"); + private static readonly Regex EnlChrome = new(Ts + @"Enlightenment Augmentations:\s*$"); + // /bonus + private static readonly Regex BonusLine = new(Ts + @"(Quest|Enlightenment|PK Dungeon|Augmentation|Equipment|Total) Bonus(?:\s*\(([^)]+)\))?:\s*(.+\S)\s*$"); + private static readonly Regex BonusChrome = new(Ts + @"={2,}\s*XP Bonuses\s*={2,}\s*$"); + // /fship list + private static readonly Regex FshipHeader = new(Ts + @"Fellowships looking for members"); + private static readonly Regex FshipLine = new(Ts + @"-\s+(.+?)\s+\(Leader:\s+(.+?)\)\s+\[(\d+/\d+)\](?:\s+@\s+(.+?))?\s*$"); + // /top + private static readonly Regex TopHeader = new(Ts + @"Top\s+(\d+)\s+Players?\s+by\s+(.+?):\s*$"); + private static readonly Regex TopEntry = new(Ts + @"(\d+):\s+([\d,]+)\s+-\s+(.+?)\s*$"); + private static readonly Regex TopSeparator = new(Ts + @"\.\.\.\s*$"); + + private static readonly string[] EnlOrder = + { + "Damage", "Damage Reduction", "Crit Damage", "Crit Damage Reduction", "Imbue", "Salvage", "Skill Credits", + "Stamina Benediction", "Mana Benediction", "Cleave", "Arrow Split", "Spell Chain", "Aetheria Surge", "Void Contagion", + }; + private static readonly Dictionary EnlCosts = new(StringComparer.OrdinalIgnoreCase) + { + ["Cleave"] = "1 Pristine Token", ["Arrow Split"] = "1 Pristine Token", ["Spell Chain"] = "1 Pristine Token", + ["Aetheria Surge"] = "1 Pristine Token", ["Void Contagion"] = "1 Pristine Token", + ["Damage"] = "2 Tokens", ["Damage Reduction"] = "2 Tokens", ["Crit Damage"] = "2 Tokens", + ["Crit Damage Reduction"] = "2 Tokens", ["Imbue"] = "2 Tokens", ["Salvage"] = "2 Tokens", + ["Skill Credits"] = "4 Tokens", ["Stamina Benediction"] = "4 Tokens", ["Mana Benediction"] = "4 Tokens", + }; + + public const int PyrealsPerMmd = 250_000; + + public readonly List Bank = new(); + public readonly List Augs = new() + { + new("Creature", 25, 2_500_000, 0.003825), new("Item", 100, 3_000_000, 0.006825), new("Life", 75, 2_500_000, 0.0095), + new("War", 50, 1_750_000, 0.00425), new("Void", 50, 1_800_000, 0.00425), new("Duration", 30, 1_400_000, 0.00625), + new("Specialization", 125, 3_000_000, 0.02), new("Melee", 50, 1_750_000, 0.00425), new("Missile", 50, 1_750_000, 0.00425), + }; + public List EnlAugs { get; private set; } = new(); + public readonly List Bonuses = new() + { + new() { Name = "Quest" }, new() { Name = "Enlightenment" }, new() { Name = "PK Dungeon" }, new() { Name = "Augmentation" }, + new() { Name = "Equipment" }, new() { Name = "Total (Kills)" }, new() { Name = "Total (Quest/Lum)" }, + }; + public readonly List Fellowships = new(); + public readonly List Boards = new() + { + new("augs", "Augs", "Total Augmentations"), new("deaths", "Deaths", "Deaths"), new("enl", "Enlightens", "Enlightenment"), + new("level", "Levels", "Level"), new("lum", "Luminance", "Banked Luminance"), new("bank", "Pyreals", "Banked Pyreals"), + new("qb", "QB", "Quest Bonus"), new("titles", "Titles", "Titles"), + }; + + public DateTime BankUtc = DateTime.MinValue, AugsUtc = DateTime.MinValue, EnlUtc = DateTime.MinValue, + BonusUtc = DateTime.MinValue, FshipUtc = DateTime.MinValue; + public int Revision { get; private set; } + + private readonly ServerChatRequest _bankReq = new(), _augReq = new(), _enlReq = new(), _bonusReq = new(), _fshipReq = new(), + _topReq = new(), _depositReq = new(); + private ConquestBoard? _collecting; + private long _collectingMs; + private int _collectingExpected = int.MaxValue; + private bool _collectingCleared; + + public static string EnlCost(string name) => EnlCosts.TryGetValue(name, out string? c) ? c : ""; + + public int AugTotal => Augs.Sum(a => a.Count); + public int DurationAugs => Augs.First(a => a.Name == "Duration").Count; + + public void Clear() + { + Bank.Clear(); + foreach (ConquestAug a in Augs) a.Count = 0; + EnlAugs = new List(); + foreach (NamedValue b in Bonuses) b.Value = ""; + Fellowships.Clear(); + foreach (ConquestBoard b in Boards) { b.Rows.Clear(); b.You = null; b.UpdatedUtc = DateTime.MinValue; } + BankUtc = AugsUtc = EnlUtc = BonusUtc = FshipUtc = DateTime.MinValue; + _collecting = null; + Revision++; + } + + // ── Requests (the plugin sends the command; each returns the command text) ── + + public string RequestBank(long now) { _bankReq.Sent(now); return "/b"; } + public string RequestAugs(long now) { _augReq.Sent(now); return "/augs"; } + public string RequestEnl(long now) { _enlReq.Sent(now); return "/enl augs"; } + public string RequestBonus(long now) { _bonusReq.Sent(now); return "/bonus"; } + public string RequestFships(long now) { _fshipReq.Sent(now); Fellowships.Clear(); Revision++; return "/fship list"; } + + public string RequestBoard(ConquestBoard board, long now) + { + _topReq.Sent(now); + Open(board, now); + return "/top " + board.Key; + } + + /// An automatic deposit: its reply is ours to hide. + public string AutoDeposit(long now) { _depositReq.Sent(now); return "/bank deposit"; } + + /// + /// A chat line: true when it was a reply this module reads; = it + /// answers a request RynthConquest sent (eligible to be hidden). + /// + public bool OnChatLine(string text, long now, out bool ours) + { + ours = false; + Match m; + + if (_depositReq.Awaiting(now) && DepositReply.IsMatch(text)) { ours = true; _depositReq.Extend(now); return true; } + + if ((m = BankLine.Match(text)).Success) + { + string name = EventToken.Replace(m.Groups[1].Value.Trim(), "$1"); + string value = m.Groups[2].Value.Trim(); + if (name == "Pyreals" && long.TryParse(value.Replace(",", ""), out long py)) + value += $" ({(py / PyrealsPerMmd).ToString("N0", CultureInfo.InvariantCulture)} MMDs)"; + NamedValue? e = Bank.FirstOrDefault(b => b.Name == name); + if (e != null) e.Value = value; else Bank.Add(new NamedValue { Name = name, Value = value }); + BankUtc = DateTime.UtcNow; + return Done(_bankReq, now, out ours); + } + if (_bankReq.Awaiting(now) && BankChrome.IsMatch(text)) return Done(_bankReq, now, out ours); + + if ((m = AugLine.Match(text)).Success) + { + ConquestAug? a = Augs.FirstOrDefault(x => x.Name == m.Groups[1].Value); + if (a != null && int.TryParse(m.Groups[2].Value.Replace(",", ""), out int c)) a.Count = c; + AugsUtc = DateTime.UtcNow; + return Done(_augReq, now, out ours); + } + if (_augReq.Awaiting(now) && AugChrome.IsMatch(text)) return Done(_augReq, now, out ours); + + if (EnlChrome.IsMatch(text)) + { + EnlAugs = new List(); + return Done(_enlReq, now, out ours); + } + if ((m = EnlLine.Match(text)).Success) + { + // "Label: N (M max)" is specific to the "/enl augs" reply (its header starts a fresh list). + string name = m.Groups[1].Value.Trim(); + var list = new List(EnlAugs.Where(x => x.Name != name)) { new() { Name = name, Value = m.Groups[2].Value.Trim() } }; + list.Sort((x, y) => Rank(x.Name).CompareTo(Rank(y.Name))); + EnlAugs = list; + EnlUtc = DateTime.UtcNow; + return Done(_enlReq, now, out ours); + } + + if ((m = BonusLine.Match(text)).Success) + { + string q = m.Groups[2].Value.Trim(); + string name = q.Length > 0 ? $"{m.Groups[1].Value} ({q})" : m.Groups[1].Value; + NamedValue? b = Bonuses.FirstOrDefault(x => x.Name == name); + if (b != null) b.Value = m.Groups[3].Value.Trim(); + BonusUtc = DateTime.UtcNow; + return Done(_bonusReq, now, out ours); + } + if (_bonusReq.Awaiting(now) && BonusChrome.IsMatch(text)) return Done(_bonusReq, now, out ours); + + if (FshipHeader.IsMatch(text)) + { + if (!_fshipReq.Awaiting(now)) Fellowships.Clear(); + FshipUtc = DateTime.UtcNow; + return Done(_fshipReq, now, out ours); + } + if ((m = FshipLine.Match(text)).Success) + { + Fellowships.Add(new ConquestFellowship + { + Name = m.Groups[1].Value.Trim(), Leader = m.Groups[2].Value.Trim(), Members = m.Groups[3].Value.Trim(), + Location = m.Groups[4].Success ? m.Groups[4].Value.Trim() : "", + }); + FshipUtc = DateTime.UtcNow; + return Done(_fshipReq, now, out ours); + } + + if ((m = TopHeader.Match(text)).Success) + { + ConquestBoard? board = Active(now) ?? Boards.FirstOrDefault(b => b.Header.Equals(m.Groups[2].Value.Trim(), StringComparison.OrdinalIgnoreCase)); + if (board == null) return false; + Open(board, now); + ClearOnce(); + _collectingExpected = int.TryParse(m.Groups[1].Value, out int n) ? n : int.MaxValue; + return Done(_topReq, now, out ours); + } + if ((m = TopEntry.Match(text)).Success && Active(now) is ConquestBoard cb) + { + ClearOnce(); + int.TryParse(m.Groups[1].Value, out int rank); + string name = m.Groups[3].Value.Trim(); + var row = new BoardRow { Rank = rank, Value = m.Groups[2].Value.Trim(), Name = name }; + if (name.EndsWith("(You)", StringComparison.OrdinalIgnoreCase)) + { + row.IsYou = true; + row.Name = name[..^5].Trim(); + cb.You = row; + } + if (rank <= _collectingExpected && cb.Rows.All(r => r.Rank != rank)) cb.Rows.Add(row); + cb.Rows.Sort((x, y) => x.Rank.CompareTo(y.Rank)); + cb.UpdatedUtc = DateTime.UtcNow; + _collectingMs = now; + return Done(_topReq, now, out ours); + } + if (Active(now) != null && TopSeparator.IsMatch(text)) return Done(_topReq, now, out ours); + + return false; + } + + private bool Done(ServerChatRequest req, long now, out bool ours) + { + ours = req.Awaiting(now); + req.Extend(now); + Revision++; + return true; + } + + private static int Rank(string name) + { + int i = Array.FindIndex(EnlOrder, n => n.Equals(name, StringComparison.OrdinalIgnoreCase)); + return i < 0 ? EnlOrder.Length : i; + } + + private void Open(ConquestBoard board, long now) + { + if (_collecting == board && now - _collectingMs < 15_000) return; + _collecting = board; + _collectingMs = now; + _collectingExpected = int.MaxValue; + _collectingCleared = false; + } + + private ConquestBoard? Active(long now) => _collecting != null && now - _collectingMs < 15_000 ? _collecting : null; + + private void ClearOnce() + { + if (_collectingCleared || _collecting == null) return; + _collecting.Rows.Clear(); + _collecting.You = null; + _collectingCleared = true; + } + + // ── Bank commands (Conquest-ACE's /bank; tokens are its one-letter currency codes) ── + + public sealed record Currency(string Label, string Token, long Multiplier = 1, long Max = long.MaxValue); + + public static readonly Currency[] Withdrawable = + { + new("Conquest Coins", "c"), new("Event Tokens", "e"), new("Legendary Keys", "k"), new("Pyreals", "p"), + new("Soul Fragments", "s"), new("MMD Notes (250k)", "n"), new("MM Notes (200k)", "n MM"), new("M Notes (100k)", "n M"), + new("D Notes (50k)", "n D"), new("C Notes (10k)", "n C"), new("L Notes (5k)", "n L"), new("X Notes (1k)", "n X"), + new("V Notes (500)", "n V"), new("I Notes (100)", "n I"), + }; + public const int DefaultWithdraw = 5; // MMD notes + + public static readonly Currency[] Transferable = + { + new("Legendary Keys", "k"), new("Luminance", "l"), new("MMD Notes (250k)", "p", 250_000, 1_000), new("Pyreals", "p"), + }; + public const int DefaultTransfer = 1; // Luminance + + /// "/bank withdraw <token> <n>", or null when the amount isn't a whole number above 0. + public static string? WithdrawCommand(Currency c, string amount) => + long.TryParse((amount ?? "").Replace(",", "").Trim(), out long n) && n > 0 ? $"/bank withdraw {c.Token} {n}" : null; + + /// "/bank transfer <token> <n> "name"", or null when the amount or name isn't usable. + public static string? TransferCommand(Currency c, string amount, string target) + { + target = (target ?? "").Trim().Replace("\"", ""); + if (target.Length == 0 || !long.TryParse((amount ?? "").Replace(",", "").Trim(), out long n) || n <= 0 || n > c.Max) return null; + try { return $"/bank transfer {c.Token} {checked(n * c.Multiplier)} \"{target}\""; } + catch (OverflowException) { return null; } + } + + // ── Levels and enlightenment (ConquestAC's levels 276-300, upstream's table) ── + + private static readonly long[] Levels276To300 = + { + 194665023377, 198152685223, 201689992550, 205277652043, 208916380445, + 212606904701, 216349962105, 220146300445, 223996678153, 227901864460, + 231862639544, 235879794689, 239954132442, 244086466776, 248277623248, + 252528439169, 256839763767, 261212458359, 265647396522, 270145464270, + 274707560226, 279334595807, 284027495403, 288787196561, 293614650176, + }; + public const int MaxLevel = 300; + + /// Total XP to reach a level 276-300 (0 otherwise). + public static long XpForLevel(int level) => level >= 276 && level <= 300 ? Levels276To300[level - 276] : 0; + + private static double EnlMultiplier(int target) => target >= 75 ? 7.5 : target >= 50 ? 5.0 : target >= 25 ? 2.5 : 1.0; + public static long EnlCoinCost(int target) => (long)(target * 100 * EnlMultiplier(target)); + public static long EnlLuminanceCost(int target) => (long)(target * 1_000_000L * EnlMultiplier(target)); + + /// Void DoT duration on ConquestAC: × (1 + Archmage's Endurance × 0.2 + Duration augs × 0.05). + public double VoidDurationMultiplier(int archmagesEndurance) => 1.0 + archmagesEndurance * 0.2 + DurationAugs * 0.05; +} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestFeature.cs b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestFeature.cs new file mode 100644 index 0000000..c631271 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestFeature.cs @@ -0,0 +1,143 @@ +// ConquestFeature.cs - What RynthConquest does on Conquest, without the host (ConquestPlugin.cs wires it +// to the engine, ConquestPages.cs draws it). Moved out of RynthOracle on 2026-10-20 so that only players +// who installed RynthConquest get Conquest's features, and the automatic /bank deposit with them: +// * reads the replies of Conquest's own commands (ConquestData: /b, /augs, /enl augs, /bonus, +// /fship list, /top) and the quest flags (/myquests, for the custom quest worklist), and hides +// the replies to its own requests when HideOwnReplies is on; +// * reads the advanced augmentations once after login (the Void DoT rule needs the Duration augs); +// * deposits everything at each ten-minute mark when AutoDeposit is on (off unless the player +// turned it on, in RynthOracle before or here); +// * works out the Void DoT duration rule for this character, which RynthOracle's Void timers read +// from the server profile ("voidDotDurationScale") instead of knowing about Conquest. +// Settings: rynthconquest.json (ServerPackSettings), taken over once from rynthoracle.json. +// Threads: everything here runs under Gate. Chat and tick come from the pump, the pages draw on the +// render thread holding it too; nothing in here calls the host. +// Pure: RynthServerPack.Tests covers it. +using System; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.ServerPack; + +namespace RynthCore.Plugin.RynthConquest; + +internal sealed class ConquestFeature +{ + public const string SettingAutoDeposit = "autoDeposit"; + public const string SettingHideOwnReplies = "hideOwnReplies"; + /// Set once rynthoracle.json's Conquest settings were taken over (they're never read again). + public const string MigrationMarker = "migratedFromRynthOracle"; + /// The profile value RynthOracle's Void timers apply ("RynthServer.Profile" values). + public const string VoidScaleKey = "voidDotDurationScale"; + /// After login, before the hidden /augs (RynthOracle's old timing: its quest read plus 4 s). + public const long AugsReadDelayMs = 10_000; + /// The character's level, XP and augmentation are read this often. + public const long CharacterReadMs = 1000; + + /// RynthConquest's pages (ConquestPages draws them): id, label, tooltip. + public static readonly (string Id, string Label, string Tooltip)[] PageList = + { + ("main", "Conquest", "Conquest: bank and auto-deposit, augmentations, levels past 275, fellowships and custom quests (RynthConquest)."), + ("boards", "Leaderboards", "Conquest's /top boards (RynthConquest)."), + }; + + /// Held for everything below (pump and render thread). + public readonly object Gate = new(); + public readonly ConquestData Data = new(); + public readonly QuestFlagStore Flags = new(); + + /// "/bank deposit" at every ten-minute mark (upstream's auto-deposit). Off by default. + public bool AutoDeposit; + /// Hide the replies to RynthConquest's own requests (a command typed by hand always shows). + public bool HideOwnReplies = true; + + // The character (ConquestPlugin reads them every CharacterReadMs). + public bool CharacterKnown; + public int Level, Enlightenment, ArchmagesEndurance; + public long TotalXp; + + private long _loginMs; + private bool _augsAsked; + private long _lastDepositBlock = -1; + + /// + /// Takes over the settings RynthOracle had for Conquest (rynthoracle.json at ), + /// once per settings file; a value that isn't there keeps this plugin's default (auto-deposit off, + /// hiding on, as they were in RynthOracle). True when it ran now. + /// + public static bool Migrate(ServerPackSettings settings, string oraclePath) => settings.MigrateOnce(MigrationMarker, s => + { + if (ServerPackSettings.ReadBoolFrom(oraclePath, "conquestAutoDeposit") is bool deposit) s.SetBool(SettingAutoDeposit, deposit); + if (ServerPackSettings.ReadBoolFrom(oraclePath, "hideOwnQuestReplies") is bool hide) s.SetBool(SettingHideOwnReplies, hide); + }); + + public void LoadSettings(ServerPackSettings s) + { + AutoDeposit = s.GetBool(SettingAutoDeposit, false); + HideOwnReplies = s.GetBool(SettingHideOwnReplies, true); + } + + public void SaveSettings(ServerPackSettings s) + { + bool changed = s.SetBool(SettingAutoDeposit, AutoDeposit); + changed |= s.SetBool(SettingHideOwnReplies, HideOwnReplies); + if (changed) s.Save(); + } + + /// A character logged in (or the plugin loaded in game): everything is read fresh. + public void Login(long nowMs) + { + _loginMs = nowMs; + _augsAsked = false; + Data.Clear(); + Flags.Clear(); + CharacterKnown = false; + Level = Enlightenment = ArchmagesEndurance = 0; + TotalXp = 0; + } + + public void Logout() + { + Data.Clear(); + Flags.Clear(); + CharacterKnown = false; + } + + /// + /// An incoming chat line on Conquest. True when it should be hidden: a reply to one of + /// RynthConquest's own requests, with HideOwnReplies on. + /// + public bool OnChatLine(string text, long nowMs) + { + string line = text.TrimEnd('\r', '\n'); + MyQuestsLine kind = Flags.OnChatLine(line, nowMs); + if (kind != MyQuestsLine.None) + return Flags.AwaitingOurs && HideOwnReplies && kind is MyQuestsLine.Quest or MyQuestsLine.Empty; + return Data.OnChatLine(line, nowMs, out bool ours) && ours && HideOwnReplies; + } + + /// The once-after-login /augs: the command to send now, or null. + public string? LoginAugsDue(long nowMs) + { + if (_augsAsked || nowMs - _loginMs <= AugsReadDelayMs) return null; + _augsAsked = true; + return Data.RequestAugs(nowMs); + } + + /// The automatic deposit: "/bank deposit" when one is due now, else null. + public string? AutoDepositDue(DateTime local, long nowMs) + => AutoDeposit && DepositDue(local, ref _lastDepositBlock) ? Data.AutoDeposit(nowMs) : null; + + /// + /// True once in each ten-minute block, at its first minute (:00, :10, :20 ... local time), as + /// upstream does; remembers the block already done. + /// + public static bool DepositDue(DateTime local, ref long lastBlock) + { + long block = local.Ticks / TimeSpan.TicksPerMinute / 10; + if (local.Minute % 10 != 0 || block == lastBlock) return false; + lastBlock = block; + return true; + } + + /// This character's Void DoT duration multiplier on Conquest (Archmage's Endurance and the Duration augs). + public double VoidScale => Data.VoidDurationMultiplier(ArchmagesEndurance); +} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestPages.cs b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestPages.cs new file mode 100644 index 0000000..27e3fae --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestPages.cs @@ -0,0 +1,417 @@ +// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. +// RynthOracle's Conquest tab (Views/ConquestTab.cs) and the Conquest half of its Leaderboards tab +// (Views/BoardsTab.cs), moved here on 2026-10-20 and redrawn with ImGui as RynthConquest's pages: +// sub-tabs of the Mini Remote's Server section while on Conquest, and tabs of the /rserver window. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.ServerPack; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthConquest; + +/// +/// The Conquest page (bank balances and bank commands, advanced and enlightenment augmentations, +/// levels past 275 and the XP bonus breakdown, fellowships looking for members, the custom quest +/// worklist: upstream's Bank, Conquest Augs, Conquest XP, Fship and Custom tabs) and the +/// Leaderboards page (Conquest's /top boards: upstream's Top Players tab). +/// Render thread: each page draws holding the feature's lock, and queues what it sends for the tick. +/// +internal sealed class ConquestPages +{ + private static readonly Vector4 Gold = new(1.00f, 0.84f, 0.30f, 1f); + private static readonly Vector4 Green = new(0.45f, 0.85f, 0.45f, 1f); + private static readonly Vector4 Grey = new(0.55f, 0.57f, 0.60f, 1f); + private static readonly Vector4 Selected = new(0.26f, 0.45f, 0.70f, 1f); + + private static readonly string[] Views = { "Bank", "Augs", "Enlightenment", "Experience", "Fellowships", "Custom quests" }; + private static readonly string[] FshipSorts = { "Name", "Leader", "Most members", "Location" }; + + private readonly ConquestFeature _f; + private readonly Func _active; + private readonly Action _runOnTick; + private readonly Func _send; + private readonly Action _print; + private readonly Action _saveSettings; + private readonly ServerRefreshRow _refresh = new(); + + private int _view; + private int _withdrawIndex = ConquestData.DefaultWithdraw, _transferIndex = ConquestData.DefaultTransfer; + private string _withdrawAmount = "", _transferAmount = "", _transferTarget = ""; + private int _fshipSort; + private int _board; + + /// RynthConquest's server is this world. + /// Queues work for the plugin tick (ServerPackPlugin.RunOnTick). + /// Sends a chat command as if typed (pump thread). + /// A line in the chat window (pump thread). + /// Writes the feature's settings (pump thread). + public ConquestPages(ConquestFeature feature, Func active, Action runOnTick, Func send, + Action print, Action saveSettings) + { + _f = feature; + _active = active; + _runOnTick = runOnTick; + _send = send; + _print = print; + _saveSettings = saveSettings; + } + + public ServerPage[] Pages() + { + var list = ConquestFeature.PageList; + return new[] + { + new ServerPage(list[0].Id, list[0].Label, list[0].Tooltip, DrawConquest), + new ServerPage(list[1].Id, list[1].Label, list[1].Tooltip, DrawBoards), + }; + } + + /// Logout: the next character's status lines start empty. + public void Reset() => _refresh.Reset(); + + // ── Conquest page ─────────────────────────────────────────────────── + + private void DrawConquest() + { + if (!Ready()) return; + lock (_f.Gate) + { + for (int i = 0; i < Views.Length; i++) + { + if (i > 0) ImGui.SameLine(); + if (Toggle(Views[i] + "##cq_v" + i, i == _view)) _view = i; + } + _refresh.Draw("cq" + _view, ConquestHelp(), RefreshConquest); + ImGui.Separator(); + switch (_view) + { + case 0: DrawBank(); break; + case 1: DrawAugs(); break; + case 2: DrawEnl(); break; + case 3: DrawXp(); break; + case 4: DrawFships(); break; + default: DrawCustom(); break; + } + ImGui.Spacing(); + bool hide = _f.HideOwnReplies; + if (ImGui.Checkbox("Hide the replies to RynthConquest's own requests##cq_hide", ref hide)) + { + _f.HideOwnReplies = hide; + _runOnTick(_saveSettings); + } + Tooltip("/b, /augs, /top, /myquests and the like when RynthConquest sends them. A command you type yourself always shows its reply."); + } + } + + /// True when the page has something to show; otherwise says why. + private bool Ready() + { + if (_active()) return true; + SafeImGui.TextWrapped("These pages are for Conquest. RynthCore doesn't see this world as Conquest " + + "(check RynthCore Options > Diagnostics, or /rserver info)."); + return false; + } + + private static string ReadAt(DateTime utc) => utc == DateTime.MinValue ? "not read yet" : $"read at {utc.ToLocalTime():HH:mm}"; + + private void DrawBank() + { + ConquestData cq = _f.Data; + SafeImGui.TextDisabled(ReadAt(cq.BankUtc)); + foreach (NamedValue b in cq.Bank.OrderBy(b => b.Name, StringComparer.OrdinalIgnoreCase)) + { + SafeImGui.TextDisabled(Cut(b.Name, 34)); + ImGui.SameLine(260f); + SafeImGui.Text(b.Value); + } + if (cq.Bank.Count == 0) SafeImGui.TextDisabled("No balances read yet."); + + ImGui.SeparatorText("Deposit"); + if (ImGui.Button("Deposit everything##cq_dep")) Queue("/bank deposit"); + Tooltip("Sends /bank deposit."); + bool auto = _f.AutoDeposit; + if (ImGui.Checkbox("Deposit by itself every ten minutes##cq_auto", ref auto)) + { + _f.AutoDeposit = auto; + _runOnTick(_saveSettings); + } + Tooltip("At :00, :10, :20 ... while you're logged in on Conquest. Its reply is hidden."); + + ImGui.SeparatorText("Withdraw"); + string[] wl = ConquestData.Withdrawable.Select(c => c.Label).ToArray(); + ImGui.SetNextItemWidth(200f); + if (ImGui.Combo("Currency##cq_wcur", ref _withdrawIndex, wl, wl.Length)) _withdrawIndex = Math.Clamp(_withdrawIndex, 0, wl.Length - 1); + ImGui.SetNextItemWidth(200f); + ImGui.InputText("Amount##cq_wamt", ref _withdrawAmount, 16); + if (ImGui.Button("Withdraw##cq_withdraw")) + { + string? cmd = ConquestData.WithdrawCommand(ConquestData.Withdrawable[_withdrawIndex], _withdrawAmount); + if (cmd == null) Print("Withdraw: type a whole number above 0."); + else Queue(cmd); + } + + ImGui.SeparatorText("Transfer to a character"); + string[] tl = ConquestData.Transferable.Select(c => c.Label).ToArray(); + ImGui.SetNextItemWidth(200f); + if (ImGui.Combo("Currency##cq_tcur", ref _transferIndex, tl, tl.Length)) _transferIndex = Math.Clamp(_transferIndex, 0, tl.Length - 1); + ImGui.SetNextItemWidth(200f); + ImGui.InputText("Amount##cq_tamt", ref _transferAmount, 16); + ImGui.SetNextItemWidth(200f); + ImGui.InputText("Character##cq_tgt", ref _transferTarget, 40); + if (ImGui.Button("Transfer##cq_transfer")) + { + string? cmd = ConquestData.TransferCommand(ConquestData.Transferable[_transferIndex], _transferAmount, _transferTarget); + if (cmd == null) Print("Transfer: type a whole number above 0 (MMD notes: at most 1,000) and a character name."); + else Queue(cmd); + } + } + + private void DrawAugs() + { + ConquestData cq = _f.Data; + SafeImGui.TextDisabled($"{ReadAt(cq.AugsUtc)}, {cq.AugTotal} in total"); + ImGui.TextDisabled("Aug"); ImGui.SameLine(120f); ImGui.TextDisabled("Have"); ImGui.SameLine(170f); + ImGui.TextDisabled("Next costs"); ImGui.SameLine(330f); ImGui.TextDisabled("Effect now"); + foreach (ConquestAug a in cq.Augs) + { + SafeImGui.Text(a.Name); + ImGui.SameLine(120f); + SafeImGui.Text(a.Count.ToString()); + ImGui.SameLine(170f); + SafeImGui.Text(a.NextCostText()); + ImGui.SameLine(330f); + SafeImGui.TextDisabled(Cut(a.Effect(), 48)); + Tooltip(a.Effect()); + } + } + + private void DrawEnl() + { + ConquestData cq = _f.Data; + SafeImGui.TextDisabled(ReadAt(cq.EnlUtc)); + foreach (NamedValue a in cq.EnlAugs) + { + SafeImGui.Text(Cut(a.Name, 26)); + ImGui.SameLine(200f); + SafeImGui.Text(a.Value); + ImGui.SameLine(360f); + SafeImGui.TextDisabled(ConquestData.EnlCost(a.Name)); + } + if (cq.EnlAugs.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); + } + + private void DrawXp() + { + ConquestData cq = _f.Data; + int level = _f.Level; + if (!_f.CharacterKnown) ImGui.TextDisabled("Reading your character..."); + ImGui.SeparatorText($"Level {level}"); + if (level >= ConquestData.MaxLevel) ImGui.TextUnformatted("Maximum level."); + else if (level < 275) + { + // Retail levels: RynthOracle's Character tab has the progress to the next one. + SafeImGui.TextDisabled($"Conquest's own levels start at 276. {Number(Math.Max(0, ConquestData.XpForLevel(276) - _f.TotalXp))} XP to level 276."); + } + else + { + long start = level >= 276 ? ConquestData.XpForLevel(level) : 0; + long next = ConquestData.XpForLevel(level + 1); + long toNext = Math.Max(0, next - _f.TotalXp); + long begin = level == 275 ? 191_226_310_247 : start; + float frac = next > begin ? (float)Math.Clamp((double)(_f.TotalXp - begin) / (next - begin), 0, 1) : 1f; + ImGui.ProgressBar(frac, new Vector2(-1f, 0f), $"{Number(toNext)} to level {level + 1}"); + long toMax = Math.Max(0, ConquestData.XpForLevel(ConquestData.MaxLevel) - _f.TotalXp); + SafeImGui.TextDisabled($"{Number(toMax)} to level {ConquestData.MaxLevel}"); + } + int target = _f.Enlightenment + 1; + ImGui.SeparatorText($"Enlightenment {_f.Enlightenment}"); + SafeImGui.Text($"Next costs {Number(ConquestData.EnlCoinCost(target))} coins and {(ConquestData.EnlLuminanceCost(target) / 1_000_000.0):0.##}M luminance"); + + ImGui.SeparatorText("Experience bonuses"); + SafeImGui.TextDisabled(ReadAt(cq.BonusUtc)); + foreach (NamedValue b in cq.Bonuses) + { + SafeImGui.TextDisabled(b.Name); + ImGui.SameLine(200f); + SafeImGui.Text(b.Value.Length > 0 ? b.Value : "-"); + } + } + + private void DrawFships() + { + ConquestData cq = _f.Data; + SafeImGui.TextDisabled($"{ReadAt(cq.FshipUtc)}, {cq.Fellowships.Count} looking for members"); + ImGui.SetNextItemWidth(160f); + ImGui.Combo("Sort##cq_fsort", ref _fshipSort, FshipSorts, FshipSorts.Length); + IEnumerable list = _fshipSort switch + { + 1 => cq.Fellowships.OrderBy(f => f.Leader, StringComparer.OrdinalIgnoreCase), + 2 => cq.Fellowships.OrderByDescending(f => f.MemberCount), + 3 => cq.Fellowships.OrderBy(f => f.Location, StringComparer.OrdinalIgnoreCase), + _ => cq.Fellowships.OrderBy(f => f.Name, StringComparer.OrdinalIgnoreCase), + }; + if (ImGui.BeginChild("##cq_fships", new Vector2(0f, 220f), ImGuiChildFlags.Borders)) + { + foreach (ConquestFellowship f in list) + { + SafeImGui.Text(Cut(f.Name, 26)); + ImGui.SameLine(200f); + SafeImGui.Text(Cut(f.Leader, 20)); + ImGui.SameLine(350f); + SafeImGui.Text(f.Members); + if (f.Location.Length > 0) { ImGui.SameLine(410f); SafeImGui.TextDisabled(Cut(f.Location, 26)); } + } + if (cq.Fellowships.Count == 0) ImGui.TextDisabled("None read yet. Press Refresh."); + } + ImGui.EndChild(); + } + + private void DrawCustom() + { + DateTime now = DateTime.UtcNow; + int i = 0; + foreach (CustomQuest q in CustomQuestList.All) + { + bool done = q.IsComplete(_f.Flags, now); + SafeImGui.TextColored(done ? Green : Grey, done ? "done" : "--"); + ImGui.SameLine(50f); + string status = q.Status(_f.Flags, now); + CustomQuest row = q; + if (ImGui.Selectable(Cut(q.Name, 34) + "##cq_cust" + i++, false, ImGuiSelectableFlags.None, new Vector2(280f, 0f))) + PrintEntry(row.Name, row.Flag, status, row.Hint, row.Url); + Tooltip("Click: the quest's hint in chat."); + ImGui.SameLine(340f); + SafeImGui.Text(status); + } + if (CustomQuestList.All.Count == 0) ImGui.TextDisabled("No custom quests listed."); + if (_f.Flags.LastReadUtc == DateTime.MinValue) ImGui.TextDisabled("Press Refresh to read your quest flags (/myquests) for their status."); + } + + /// An entry's name, status, hint and link in chat (upstream "thinks" them). + private void PrintEntry(string name, string flag, string status, string details, string url) + { + Print(flag.Length > 0 ? $"{name} ({flag}){(status.Length > 0 ? " - " + status : "")}" : name); + if (details.Length > 0) Print(details); + if (url.Length > 0) Print(url); + } + + // ── Leaderboards page ─────────────────────────────────────────────── + + private void DrawBoards() + { + if (!Ready()) return; + lock (_f.Gate) + { + ConquestData cq = _f.Data; + _board = Math.Clamp(_board, 0, cq.Boards.Count - 1); + for (int i = 0; i < cq.Boards.Count; i++) + { + if (i > 0) ImGui.SameLine(); + if (Toggle(cq.Boards[i].Label + "##cb_tab" + i, i == _board)) _board = i; + } + ConquestBoard b = cq.Boards[_board]; + _refresh.Draw("board" + b.Key, $"Sends {b.Command} and reads the reply.", () => Ask("board" + b.Key, () => b.UpdatedUtc.Ticks, b.Command, + now => cq.RequestBoard(b, now))); + ImGui.Separator(); + SafeImGui.TextDisabled(b.UpdatedUtc == DateTime.MinValue ? "not read yet" : $"read at {b.UpdatedUtc.ToLocalTime():HH:mm}"); + if (b.You != null) SafeImGui.Text($"You: #{b.You.Rank} with {b.You.Value}"); + if (ImGui.BeginChild("##cb_rows", Vector2.Zero, ImGuiChildFlags.Borders)) + { + ImGui.TextDisabled("Rank"); ImGui.SameLine(60f); ImGui.TextDisabled("Name"); ImGui.SameLine(280f); ImGui.TextDisabled("Value"); + foreach (BoardRow r in b.Rows) + { + SafeImGui.Text(r.Rank.ToString()); + ImGui.SameLine(60f); + if (r.IsYou) SafeImGui.TextColored(Gold, Cut(r.Name, 30)); + else SafeImGui.Text(Cut(r.Name, 30)); + ImGui.SameLine(280f); + SafeImGui.Text(r.Value); + if (r.Extra.Length > 0) { ImGui.SameLine(420f); SafeImGui.TextDisabled(Cut(r.Extra, 40)); } + } + if (b.Rows.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); + } + ImGui.EndChild(); + } + } + + // ── Refresh (RynthOracle's RefreshBar, Conquest's part) ────────────── + + private ServerRefreshResult RefreshConquest() + { + ConquestData cq = _f.Data; + switch (_view) + { + case 0: return Ask("bank", () => cq.BankUtc.Ticks, "/b", now => cq.RequestBank(now)); + case 1: return Ask("augs", () => cq.AugsUtc.Ticks, "/augs", now => cq.RequestAugs(now)); + case 2: return Ask("enl", () => cq.EnlUtc.Ticks, "/enl augs", now => cq.RequestEnl(now)); + case 3: return Ask("bonus", () => cq.BonusUtc.Ticks, "/bonus", now => cq.RequestBonus(now)); + case 4: return Ask("fship", () => cq.FshipUtc.Ticks, "/fship list", now => cq.RequestFships(now)); + default: + if (_refresh.CoolingDown("quests", Environment.TickCount64)) return new ServerRefreshResult(ServerRefreshRow.TooSoon); + QuestFlagStore flags = _f.Flags; + int rev = flags.Revision; + int wait = flags.ThrottleSecondsLeft(Environment.TickCount64); + if (wait > 0) return new ServerRefreshResult($"The server answers one /myquests a minute; try again in {wait}s (the flags shown are kept)."); + _runOnTick(() => + { + lock (_f.Gate) flags.Request(_send, Environment.TickCount64); + }); + return new ServerRefreshResult("Asked the server for your quest flags (/myquests).", () => flags.Revision != rev); + } + } + + private string ConquestHelp() => _view switch + { + 0 => "Sends /b and reads your balances.", + 1 => "Sends /augs and reads your advanced augmentations.", + 2 => "Sends /enl augs and reads your enlightenment augmentations.", + 3 => "Sends /bonus for the experience bonuses (your level is read from the game).", + 4 => "Sends /fship list and reads the fellowships looking for members.", + _ => "Sends /myquests: the custom quests' status comes from your quest flags.", + }; + + /// + /// Sends one of the page's own commands on the next tick (marking it as RynthConquest's, so its + /// reply can be hidden) and waits for to change. + /// + private ServerRefreshResult Ask(string key, Func state, string command, Action markSent) + { + if (_refresh.CoolingDown(key, Environment.TickCount64)) return new ServerRefreshResult(ServerRefreshRow.TooSoon); + long before = state(); + _runOnTick(() => + { + lock (_f.Gate) markSent(Environment.TickCount64); + if (!_send(command)) _print($"Couldn't send {command} (not in the world)."); + }); + return new ServerRefreshResult($"Sent {command}.", () => state() != before); + } + + // ── Helpers ───────────────────────────────────────────────────────── + + /// A command from a button, sent on the next tick. + private void Queue(string command) => _runOnTick(() => _send(command)); + + /// A line in chat, written on the next tick. + private void Print(string text) => _runOnTick(() => _print(text)); + + private static bool Toggle(string label, bool selected) + { + if (selected) ImGui.PushStyleColor(ImGuiCol.Button, Selected); + bool clicked = ImGui.SmallButton(label); + if (selected) ImGui.PopStyleColor(); + return clicked; + } + + private static void Tooltip(string text) + { + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(text); + } + + private static string Cut(string s, int max) => s.Length <= max ? s : s.Substring(0, Math.Max(0, max - 3)) + "..."; + + private static string Number(long n) => TimeText.Number(n); +} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/CustomQuests.cs b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/CustomQuests.cs new file mode 100644 index 0000000..6d0e033 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/CustomQuests.cs @@ -0,0 +1,63 @@ +// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. +// Moved here from RynthOracle (Data/CustomQuests.cs) on 2026-10-20, with Resources\customquests.csv. +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text; +using RynthCore.Plugin.RynthOracle.Data; + +namespace RynthCore.Plugin.RynthConquest; + +/// +/// Conquest's custom quest worklist (customquests.csv: Server, Name, QuestFlag, Url, Hint; every row +/// is Conquest's), upstream's Custom tab. The status comes from the character's quest flags +/// (/myquests, read with RynthOracle's parser, linked source). A repeatable counts as done only +/// while on cooldown (upstream's rule). +/// +internal sealed class CustomQuest +{ + public string Server = "", Name = "", Flag = "", Url = "", Hint = ""; + + public bool IsComplete(QuestFlagStore flags, DateTime utcNow) + { + if (!flags.TryGet(Flag, out QuestFlag q)) return false; + if (q.RepeatTime == TimeSpan.Zero) return q.Solves > 0; + return !q.Ready(utcNow); + } + + public string Status(QuestFlagStore flags, DateTime utcNow) + { + if (!flags.TryGet(Flag, out QuestFlag q)) return "ready"; + if (q.RepeatTime == TimeSpan.Zero) return q.Solves > 0 ? "completed" : "ready"; + return q.NextAvailable(utcNow); + } +} + +internal static class CustomQuestList +{ + /// The embedded list's logical name (RynthCore.Plugin.RynthConquest.csproj). + public const string ResourceName = "RynthConquest.customquests.csv"; + + public static List All { get; } = Load(); + + private static List Load() + { + var list = new List(); + Stream? stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName); + if (stream == null) return list; + using var r = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true); + r.ReadLine(); // Server,Name,QuestFlag,Url,Hint + while (r.ReadLine() is string line) + { + if (string.IsNullOrWhiteSpace(line)) continue; + string[] f = Csv.ParseLine(line); + list.Add(new CustomQuest + { + Server = Csv.Field(f, 0), Name = Csv.Field(f, 1), Flag = Csv.Field(f, 2).ToLowerInvariant(), + Url = Csv.Field(f, 3), Hint = Csv.Field(f, 4), + }); + } + return list; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/ConquestPlugin.cs b/Plugins/RynthCore.Plugin.RynthConquest/ConquestPlugin.cs new file mode 100644 index 0000000..906ca89 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/ConquestPlugin.cs @@ -0,0 +1,118 @@ +// ConquestPlugin.cs - RynthConquest's own features, through the shared server plugin's hooks +// (Plugins/Shared/ServerPack/ServerPackPlugin.cs). Everything Conquest-specific that RynthOracle used to +// carry lives here since 2026-10-20 (Conquest/ConquestFeature.cs says what), so a player without +// RynthConquest gets none of it, the automatic /bank deposit included. +using System; +using System.IO; +using RynthCore.Plugin.RynthConquest; + +namespace RynthCore.Plugin.ServerPack; + +public sealed partial class ServerPackPlugin +{ + private readonly ConquestFeature _conquest = new(); + private ConquestPages? _conquestPages; + private long _nextConquestCharacterMs; + + /// Where RynthOracle kept the Conquest settings before they moved here (read once). + internal static string OracleSettingsPath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json"); + + partial void ServerPages(System.Collections.Generic.List pages) + { + _conquestPages = new ConquestPages(_conquest, () => Active, RunOnTick, Send, + text => ChatLine($"[{RynthPluginInfo.Name}] {text}"), SaveConquestSettings); + pages.AddRange(_conquestPages.Pages()); + } + + partial void ServerInitialize() + { + if (ConquestFeature.Migrate(Settings, OracleSettingsPath)) + LogTagged("Took over RynthOracle's Conquest settings (auto-deposit, hiding own replies) from rynthoracle.json."); + lock (_conquest.Gate) _conquest.LoadSettings(Settings); + } + + private void SaveConquestSettings() + { + lock (_conquest.Gate) _conquest.SaveSettings(Settings); + } + + partial void ServerLoginComplete() + { + lock (_conquest.Gate) _conquest.Login(Environment.TickCount64); + _nextConquestCharacterMs = 0; + _conquestPages?.Reset(); + } + + partial void ServerLogout() + { + lock (_conquest.Gate) _conquest.Logout(); + _conquestPages?.Reset(); + } + + partial void ServerShutdown() => SaveConquestSettings(); + + partial void ServerChatText(string text, int chatType, ref bool eat) + { + if (!Active) return; + bool hide; + lock (_conquest.Gate) hide = _conquest.OnChatLine(text, Environment.TickCount64); + if (hide) eat = true; + } + + partial void ServerChatBar(string text) + { + // The player's own /myquests: its reply shows (QuestFlagStore tells it from RynthConquest's). + if (text.Equals("/myquests", StringComparison.OrdinalIgnoreCase)) _conquest.Flags.NoteTypedCommand(); + } + + partial void ServerTick(bool active) + { + if (!active) return; + long now = Environment.TickCount64; + string? augs, deposit; + lock (_conquest.Gate) + { + _conquest.Flags.Tick(now); + augs = _conquest.LoginAugsDue(now); + deposit = _conquest.AutoDepositDue(DateTime.Now, now); + } + if (augs != null) Send(augs); + if (deposit != null && Send(deposit)) ChatLine($"[{RynthPluginInfo.Name}] Auto-deposited to the bank."); + + if (now < _nextConquestCharacterMs) return; + _nextConquestCharacterMs = now + ConquestFeature.CharacterReadMs; + ReadConquestCharacter(); + } + + /// Level, XP, enlightenment and Archmage's Endurance (the Void DoT rule), then the rule for RynthOracle. + private void ReadConquestCharacter() + { + uint player = Host.HasGetPlayerId ? Host.GetPlayerId() : 0; + if (player == 0) return; + int level = Host.TryGetObjectIntProperty(player, 25, out int l) ? l : 0; // PropertyInt Level + int enl = Host.TryGetObjectIntProperty(player, 390, out int e) ? e : 0; // Enlightenment + int archmage = Host.TryGetObjectIntProperty(player, 238, out int a) ? a : 0; // AugmentationIncreasedSpellDuration + long xp = Host.HasGetObjectQuadProperty && Host.TryGetObjectQuadProperty(player, 1, out long x) ? x : 0; // TotalExperience + double scale; + lock (_conquest.Gate) + { + _conquest.Level = level; + _conquest.Enlightenment = enl; + _conquest.ArchmagesEndurance = archmage; + _conquest.TotalXp = xp; + _conquest.CharacterKnown = level > 0; + scale = _conquest.VoidScale; + } + SetProfileValue(ConquestFeature.VoidScaleKey, scale); + } + + partial void ServerInfoLines(Action line) + { + lock (_conquest.Gate) + { + line($"Auto-deposit {(_conquest.AutoDeposit ? "on" : "off")}; own replies {(_conquest.HideOwnReplies ? "hidden" : "shown")}" + + $"; Void DoT duration x{_conquest.VoidScale:0.##} ({_conquest.Data.DurationAugs} Duration augs)."); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Resources/customquests.csv b/Plugins/RynthCore.Plugin.RynthConquest/Resources/customquests.csv new file mode 100644 index 0000000..f935527 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/Resources/customquests.csv @@ -0,0 +1,7 @@ +Server,Name,QuestFlag,Url,Hint +Conquest,Darshmaul the Brutal,assaultonaimaru,,Shoushi - Portal to Fort 33.6S 74.9E - Kill Darshmaul the Brutal 34.3S 80.7E - Loot Finger - Shoushi - Give to Vovran 33.4S 72.8E +Conquest,Forgotten One,GhostDenCompleted,,Desolution Beach - Helsing 82.5N 43.5W - Den of Ghosts 82.4N 41.3W - Head North and hug left. Don't go downstairs - Defeat The Forgotten One and Loot Head - Back to Helsing +Conquest,Ice Giants,icegiantkilltask,,No hint available +Conquest,Thorsten's Tears,cragstonetearspickup,,No hint available +Conquest,Uber Bobo,uberpawlooted,,No hint available +Conquest,Uber Curator,uberrtwreward,,No hint available \ No newline at end of file diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Resources/quests.conquest.csv b/Plugins/RynthCore.Plugin.RynthConquest/Resources/quests.conquest.csv new file mode 100644 index 0000000..081fc71 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/Resources/quests.conquest.csv @@ -0,0 +1,547 @@ +QuestFlag,Server,Verified Conquest,Verified Levistras,Quest,Url,Info,Hint,Repeatable +123qbformenotthee,Conquest,Verified,,Crown Likes You,,123Qbformenotthee,123Qbformenotthee,FALSE +aaccicenodachiturnedin,Conquest,Verified,,Turned Ice Nodachi into Omaro Nagate.,,,Turned Ice Nodachi into Omaro Nagate.,TRUE +account_pathwarden_writ,Conquest,Verified,,Got writ from pathwarden on another character,,,Got writ from pathwarden on another character,TRUE +acidelementaltreasuremapfound,Conquest,Verified,,Acid Elemental Treasure Map,,,,FALSE +AdjaBucket,Conquest,Verified,,Adja's Bucket,,,,FALSE +aetheriumjewelry,Conquest,Verified,,,,,,FALSE +aetheriumjewelryreward,Conquest,Verified,,,,,,FALSE +aetheriumjewelryrewardbellas,Conquest,Verified,,,,,,FALSE +anekshaygemofknowledgecollectedinamonth,Conquest,Verified,,Amount of Anekshay Gem of Knowledges player has turned in within a 30 day period.,,,Amount of A'nekshay Gem of Knowledges player has turned in within a 30 day period.,FALSE +anekshaygemofknowledgetimer_monthly,Conquest,Verified,,Monthly timer for turning in up to 10 Anekshay Gem of Knowledges.,,,Monthly timer for turning in up to 10 A'nekshay Gem of Knowledges.,TRUE +anekshaygemoflesserknowledgecollectedinamonth,Conquest,Verified,,Amount of Anekshay Gems of Lesser Knowledge player has turned in within a 30 day period.,,,Amount of A'nekshay Gems of Lesser Knowledge player has turned in within a 30 day period.,FALSE +anekshayluminancecertificatecollectedinamonth,Conquest,Verified,,Amount of Anekshay Luminance Certificates player has turned in within a 30 day period.,,,Amount of A'nekshay Luminance Certificates player has turned in within a 30 day period.,FALSE +anekshayluminancecertificatetimer_monthly,Conquest,Verified,,Monthly timer for turning in up to 10 Anekshay Luminance Certificates.,,,Monthly timer for turning in up to 10 A'nekshay Luminance Certificates.,TRUE +anekshaytreasuremapfound,Conquest,Verified,,Treasure Maps,,Anekshay Treasure Map Found,Anekshay Treasure Map Found,FALSE +antiorpk?,Conquest,Verified,,Player Killer,,Antiorpk?,Antiorpk?,FALSE +ApexWeaponSetoichi,Conquest,Verified,,Setoichi's Apex Weapon,,,,FALSE +appleorchard1,Conquest,Verified,,,,,,FALSE +appleorchard2,Conquest,Verified,,,,,,FALSE +appleorchard3,Conquest,Verified,,,,,,FALSE +appleorcharddrudgehead,Conquest,Verified,,,,,,FALSE +appleorchardparticipation,Conquest,Verified,,,,,,FALSE +appleorchardshrethmeat,Conquest,Verified,,,,,,FALSE +appleorchardwaspwing,Conquest,Verified,,,,,,FALSE +apstipendtimer_0812,Conquest,Verified,,Stipends,,Apstipendtimer_0812,Apstipendtimer_0812,TRUE +arantahkill1,Conquest,Verified,Verified,Hunting Aun Ralirea,https://acportalstorm.com/wiki/Hunting_Aun_Ralirea,Give Clay Figurine to Hea Arantah.,PERMANENT - Give Hea Arantah FigurineRalirea,FALSE +ArantahKill1@GiveFigurine,Conquest,Verified,,Arantah's Figurine,,,,FALSE +armoredillotreasuremapfound,Conquest,Verified,,Treasure Maps,,Armoredillo Treasure Map Found,Armoredillo Treasure Map Found,FALSE +assaultonaimaru,Conquest,Verified,,Darshmaul,,You defeated Darshmaul and his Lugian forces.,You defeated Darshmaul and his Lugian forces.,TRUE +attributegems1,Conquest,Verified,Verified,Attribute and Skill Redistribution,https://acportalstorm.com/wiki/Attribute_and_Skill_Redistribution,Attribute gems received counter. See Warden of Lowering Endurance; Warden of Lowering Coordination; Warden of Lowering Strength (among others).,Attribute gems received counter,FALSE +auntumeroktreasuremapfound,Conquest,Verified,,Treasure Maps,,Aun Tumerok Treasure Map Found,Aun Tumerok Treasure Map Found,FALSE +AurochTreasureMapFound,Conquest,Verified,,Treasure Maps,,Auroch Treasure Map Found,,FALSE +babydragonkillcount,Conquest,Verified,,Baby Dragon Kill Task,,Babydragon Kill Count,Babydragon Kill Count,TRUE +BabyDragonKillTaskWait,Conquest,Verified,,Baby Dragon Kill Task,,,,FALSE +banderlingtreasuremapfound,Conquest,Verified,,Treasure Maps,,Banderling Treasure Map Found,Banderling Treasure Map Found,FALSE +banditshieldpickup,Conquest,Verified,,Bandit Shield,,Banditshield Pickup,Banditshield Pickup,TRUE +BarkBeetlesPruned,Conquest,Verified,,Tree Farm,,,,FALSE +beachbumreward,Conquest,Verified,,Beach Bum,,Beachbum Reward,Beachbum Reward,TRUE +beacongemgiven,Conquest,Verified,,Beacon Gem,,,,FALSE +bellascachelockout,Conquest,Verified,,Uber Bellas,,Bellas Cache Lockout,Bellas Cache Lockout,TRUE +BellasConsolationPrize,Conquest,Verified,,Uber Bellas,,,,FALSE +bellasprimaryrewardclaimed,Conquest,Verified,,Uber Bellas,,Bellas Primary Reward Claimed,Bellas Primary Reward Claimed,TRUE +blackdragonkillcount,Conquest,Verified,,Black Dragon Kill Task,,Blackdragon Kill Count,Blackdragon Kill Count,TRUE +blackdragonkilltask,Conquest,Verified,,Black Dragon Kill Task,,Blackdragon Kill Task,Blackdragon Kill Task,TRUE +blackdragonkilltaskstarted,Conquest,Verified,,Black Dragon Kill Task,,Black Dragon Kill Task Started,Black Dragon Kill Task Started,FALSE +blackringstep1,Conquest,Verified,,Black Ring,,Blackringstep1,Blackringstep1,FALSE +blackringstep2,Conquest,Verified,,Black Ring,,Blackringstep2,Blackringstep2,FALSE +blackringstep3,Conquest,Verified,,Black Ring,,Blackringstep3,Blackringstep3,FALSE +BleachedRabbitTreasureMapFound,Conquest,Verified,,Treasure Maps,,Bleached Rabbit Treasure Map Found,,FALSE +blightedmoarsmantreasuremapfound,Conquest,Verified,,Treasure Maps,,Blightedmoarsman Treasure Map Found,Blightedmoarsman Treasure Map Found,FALSE +blindedbylugians,Conquest,Verified,,Blinded by Lugians,,Blindedbylugians,Blindedbylugians,FALSE +BloodFlow,Conquest,Verified,,Blood Flow,,,,FALSE +bloodoath,Conquest,Verified,,Blood Oath,,Bloodoath,Bloodoath,FALSE +bloodstonecaptureblueteam,Conquest,Verified,,,,,,FALSE +bloodstonecapturereward,Conquest,Verified,,,,,,FALSE +braceletebuillantpickup,Conquest,Verified,,Elemental Bracelets,,,,FALSE +braceletfrigidpickup,Conquest,Verified,,Elemental Bracelets,,,,FALSE +braceletgalvanicpickup,Conquest,Verified,,Elemental Bracelets,,,,FALSE +braceletincalescentpickup,Conquest,Verified,,Elemental Bracelets,,,,FALSE +branithshirtpickup,Conquest,Verified,,Branith's Shirt,,Branithshirt Pickup,Branithshirt Pickup,TRUE +brevnatrewardclaimed,Conquest,Verified,,Brevnat,,Brevnat Reward Claimed,Brevnat Reward Claimed,TRUE +bronzedragonkillcount,Conquest,Verified,,Bronze Dragon Kill Task,,Bronzedragon Kill Count,Bronzedragon Kill Count,TRUE +bronzedragonkilltask,Conquest,Verified,,Bronze Dragon Kill Task,,Bronzedragon Kill Task,Bronzedragon Kill Task,TRUE +bronzedragonkilltaskstarted,Conquest,Verified,,Bronze Dragon Kill Task,,Bronzedragon Kill Task Started,Bronzedragon Kill Task Started,TRUE +buffshrinetokengiven,Conquest,Verified,,Buff Shrine Tutorial,,Buffshrine Token Given,Buffshrine Token Given,FALSE +buffshrinetutorial,Conquest,Verified,,Buff Shrine Tutorial,,Buffshrine Tutorial,Buffshrine Tutorial,FALSE +bugjuice,Conquest,Verified,,Bug Juice,,Bugjuice,Bugjuice,FALSE +bunnytreasuremapfound,Conquest,Verified,,Treasure Maps,,Bunny Treasure Map Found,Bunny Treasure Map Found,FALSE +burflagged(motes),Conquest,Verified,,Asheron's Trail,https://acportalstorm.com/wiki/Asheron's_Trail,One of three flags for 1-79 Portal to Bur. See Golem Warden of Metos.,One of three flags for 1-79 Portal to Bur,FALSE +BurnedCorpse,Conquest,Verified,,Burned Corpse,,,,FALSE +buruntreasuremapfound,Conquest,Verified,,Treasure Maps,,Burun Treasure Map Found,Burun Treasure Map Found,FALSE +CanRingYasujiroBell,Conquest,Verified,,Yasujiro's Bell,,,,FALSE +carenzitreasuremapfound,Conquest,Verified,,Treasure Maps,,Carenzi Treasure Map Found,Carenzi Treasure Map Found,FALSE +ChestBurUpperCatacomb1,Conquest,Verified,,Upper Catacombs,,,,FALSE +ChestBurUpperCatacomb2,Conquest,Verified,,Upper Catacombs,,,,FALSE +ChestBurUpperCatacomb3,Conquest,Verified,,Upper Catacombs,,,,FALSE +ChestBurUpperCatacomb4,Conquest,Verified,,Upper Catacombs,,,,FALSE +ChestBurUpperCatacomb5,Conquest,Verified,,Upper Catacombs,,,,FALSE +ChestBurUpperCatacomb6,Conquest,Verified,,Upper Catacombs,,,,FALSE +chestofskins,Conquest,Verified,,Chest of Skins,,,,TRUE +chickentreasuremapfound,Conquest,Verified,,Treasure Maps,,Chicken Treasure Map Found,Chicken Treasure Map Found,FALSE +chitticktreasuremapfound,Conquest,Verified,,Treasure Maps,,Chittick Treasure Map Found,Chittick Treasure Map Found,FALSE +cisgemtimer,Conquest,Verified,,CIS Gem Timer,,CIS Gem Timer,CIS Gem Timer,TRUE +cleansedstaff,Conquest,Verified,,,,,,FALSE +coloarenafiveaccess,Conquest,Verified,,,,,,FALSE +coloarenafouraccess,Conquest,Verified,,,,,,FALSE +commoncommonbanderlingessence,Conquest,Verified,,Creature Essences,,Commoncommonbanderlingessence,Commoncommonbanderlingessence,FALSE +commoncommoncowessence,Conquest,Verified,,Creature Essences,,Common Common Cow Essence,,FALSE +commoncommondrudgeessence,Conquest,Verified,,Creature Essences,,Common Common Drudge Essence,Common Common Drudge Essence,FALSE +commoncommongolemessence,Conquest,Verified,,Creature Essences,,Commoncommongolem Essence,Commoncommongolem Essence,FALSE +commoncommongrievveressence,Conquest,Verified,,Creature Essences,,Commoncommongrievveressence,Commoncommongrievveressence,FALSE +commoncommongromnieessence,Conquest,Verified,,Creature Essences,,Commoncommongromnie Essence,Commoncommongromnie Essence,FALSE +commoncommonlugianessence,Conquest,Verified,,Creature Essences,,Commoncommonlugian Essence,Commoncommonlugian Essence,FALSE +commoncommonpenguinessence,Conquest,Verified,,Creature Essences,,Commoncommonpenguin Essence,Commoncommonpenguin Essence,FALSE +commoncommonratessence,Conquest,Verified,,Creature Essences,,Commoncommonratessence,Commoncommonratessence,FALSE +commoncommonreedsharkessence,Conquest,Verified,,Creature Essences,,Commoncommonreedsharkessence,Commoncommonreedsharkessence,FALSE +commoncommonroosteressence,Conquest,Verified,,Creature Essences,,Commoncommonroosteressence,Commoncommonroosteressence,FALSE +CommonCommonTuskerEssence,Conquest,Verified,,Creature Essences,,,,FALSE +commoncommonundeadessence,Conquest,Verified,,Creature Essences,,Commoncommonundead Essence,Commoncommonundead Essence,FALSE +commoncommonwaspessence,Conquest,Verified,,Creature Essences,,Common Common Wasp Essence,Common Common Wasp Essence,FALSE +commoncommonwretchedessence,Conquest,Verified,,Creature Essences,,Commoncommonwretched Essence,Commoncommonwretched Essence,FALSE +commonlil'curatorbox,Conquest,Verified,,Creature Essences,,,,FALSE +commonmagichat,Conquest,Verified,,Creature Essences,,Commonmagichat,Commonmagichat,FALSE +Countdown2,Conquest,Verified,,Countdown,,,,FALSE +cowkingstreasure,Conquest,Verified,,Cow King's Treasure,,Cowkingstreasure,Cowkingstreasure,FALSE +cowtreasuremapfound,Conquest,Verified,,Treasure Maps,,Cow Treasure Map Found,Cow Treasure Map Found,FALSE +cragstonetearspickup,Conquest,Verified,,Tears of Cragstone,,Cragstonetears Pickup,Cragstonetears Pickup,TRUE +CrimsonBrokenHaft@2,Conquest,Verified,,Crimson Broken Haft,,,,FALSE +crownlikesrynthid,Conquest,Verified,,Crown Likes You,,Crownlikesrynthid,Crownlikesrynthid,FALSE +crownlovesnanners,Conquest,Verified,,Crown Likes You,,Crownlovesnanners,Crownlovesnanners,FALSE +crownneedsqb1337,Conquest,Verified,,Crown Likes You,,Crownneedsqb1337,Crownneedsqb1337,FALSE +crystaltreasuremapfound,Conquest,Verified,,Treasure Maps,,Crystal Treasure Map Found,Crystal Treasure Map Found,FALSE +DarkRecordingFalse,Conquest,Verified,,Dark Recordings,,,,FALSE +darktideforever,Conquest,Verified,,,,,,FALSE +DaySewersAccess,Conquest,Verified,,Sewers of Arwic,,,,FALSE +DaySewersReward,Conquest,Verified,,Sewers of Arwic,,,,FALSE +DeathRunTempleComplete,Conquest,Verified,,Death Run Temple,,,,FALSE +deepertunnelsreturntrip,Conquest,Verified,,Deeper Tunnels Return Trip,,,,FALSE +DefliedShieldFrame,Conquest,Verified,,The Defiled Armor,,,,FALSE +DefliedSkinInsert,Conquest,Verified,,The Defiled Armor,,,,FALSE +DefliedSkinStraps,Conquest,Verified,,The Defiled Armor,,,,FALSE +detailmukkirorbnotespickup,Conquest,Verified,,Timer for Gabilles Encoded Notes pickup,,,Timer for Gabille's Encoded Notes pickup,TRUE +DollTreasureMapFound,Conquest,Verified,,Treasure Maps,,Doll Treasure Map Found,,FALSE +donttellaroenas,Conquest,Verified,,Crown Likes You,,Donttellaroenas,Donttellaroenas,FALSE +DousedFlames,Conquest,Verified,,Doused Flames,,,,FALSE +DragonEggKillCount,Conquest,Verified,,Dragon Egg Kill Task,,,,FALSE +DragonEggKillTask,Conquest,Verified,,Dragon Egg Kill Task,,,,FALSE +DragonEggKillTaskStarted,Conquest,Verified,,Dragon Egg Kill Task,,,,FALSE +dragonhunter,Conquest,Verified,,Dragon Hunter,,Dragonhunter,Dragonhunter,TRUE +dragonislehunt,Conquest,Verified,,Dragon Isle,,,,FALSE +dragontraining,Conquest,Verified,,Dragon Isle,,,,FALSE +drudgetreasuremapfound,Conquest,Verified,,Treasure Maps,,Drudge Treasure Map Found,Drudge Treasure Map Found,FALSE +dustdevildeath,Conquest,Verified,,,,,,FALSE +easternpedestalshard_pickup,Conquest,Verified,,Player has picked up the Shard of the Eastern Pedestal.,,,Player has picked up the Shard of the Eastern Pedestal.,TRUE +eatertreasuremapfound,Conquest,Verified,,Treasure Maps,,Eater Treasure Map Found,Eater Treasure Map Found,FALSE +EggRetrievalTopHatWait@2,Conquest,Verified,,Egg Retrieval,,,,FALSE +elementaltreasuremapfound,Conquest,Verified,,Treasure Maps,,Elemental Treasure Map Found,Elemental Treasure Map Found,FALSE +EmbalmingFluidWielded,Conquest,Verified,,Embalming Fluid,,,,FALSE +enteredpkarena,Conquest,Verified,,PK Arena,,Enteredpkarena,Enteredpkarena,FALSE +eventcoinpickup,Conquest,Verified,,Event Coins,,Eventcoin Pickup,Eventcoin Pickup,TRUE +expeditiondeath,Conquest,Verified,,,,,,FALSE +faetreasuremapfound,Conquest,Verified,,Treasure Maps,,Fae Treasure Map Found,Fae Treasure Map Found,FALSE +fireelementaltreasuremapfound,Conquest,Verified,,Treasure Maps,,Fireelemental Treasure Map Found,Fireelemental Treasure Map Found,FALSE +FireSpearPickUp,Conquest,Verified,,Fire Spear,,,,FALSE +fireworks2026,Conquest,Verified,,Fireworks 2026,,Fireworks2026,Fireworks2026,FALSE +fiuntreasuremapfound,Conquest,Verified,,Treasure Maps,,Fiun Treasure Map Found,Fiun Treasure Map Found,FALSE +flickedunclesam,Conquest,Verified,,July 4th,,Flickedunclesam,Flickedunclesam,FALSE +FoodTreasureMapFound,Conquest,Verified,,Treasure Maps,,Food Treasure Map Found,,FALSE +forgestart,Conquest,Verified,,Twilight Forging,,,,FALSE +forgetfulness6days,Conquest,Verified,Verified,Attribute and Skill Redistribution,https://acportalstorm.com/wiki/Attribute_and_Skill_Redistribution,1 week skill forgetfulness timer. See Run Warden of Forgetfulness; Salvaging Warden of Forgetfulness; Heavy Weapons Warden of Forgetfulness (among others).,1 week skill forgetfulness timer.,TRUE +forgetfulnessgems1,Conquest,Verified,Verified,Attribute and Skill Redistribution,https://acportalstorm.com/wiki/Attribute_and_Skill_Redistribution,First Forgetfulness gems received counter. See Summoning Warden of Forgetfulness; Alchemy Warden of Forgetfulness; Void Magic Warden of Forgetfulness (among others).,First Forgetfulness gems received counter,FALSE +forgetfulnessgems2,Conquest,Verified,Verified,Attribute and Skill Redistribution,https://acportalstorm.com/wiki/Attribute_and_Skill_Redistribution,Second Forgetfulness gems received counter. See Dirty Fighting Warden of Forgetfulness; Dual Wield Warden of Forgetfulness; Recklessness Warden of Forgetfulness (among others).,Second Forgetfulness gems received counter,FALSE +fortbushikillcount,Conquest,Verified,,Fort Bushi Kill Task,,Fortbushi Kill Count,Fortbushi Kill Count,TRUE +fortbushikilltaskwait,Conquest,Verified,,Fort Bushi Kill Task,,Fortbushi Kill Task Cooldown,Fortbushi Kill Task Cooldown,TRUE +fortknightkillcount,Conquest,Verified,,Fort Knight Kill Task,,Fortknight Kill Count,Fortknight Kill Count,TRUE +fortknightkilltaskwait,Conquest,Verified,,Fort Knight Kill Task,,Fortknight Kill Task Cooldown,Fortknight Kill Task Cooldown,TRUE +fortshadowkillcount,Conquest,Verified,,Fort Shadow Kill Task,,Fortshadow Kill Count,Fortshadow Kill Count,TRUE +fortshadowkilltaskwait,Conquest,Verified,,Fort Shadow Kill Task,,Fortshadow Kill Task Cooldown,Fortshadow Kill Task Cooldown,TRUE +foundingfather,Conquest,Verified,,Founding Fathers,,,,FALSE +freedomfest,Conquest,Verified,,Freedom Fest,,Freedomfest,Freedomfest,TRUE +freeqbfreetendies,Conquest,Verified,,Crown Likes You,,Freeqbfreetendies,Freeqbfreetendies,FALSE +FrostElementalTreasureMapFound,Conquest,Verified,,Treasure Maps,,Frost Elemental Treasure Map Found,,FALSE +GaveCoals,Conquest,Verified,,Coals,,,,FALSE +gaveevilcouch,Conquest,Verified,Verified,Frest Greelving's Haunted Mansion,https://acportalstorm.com/wiki/Frest_Greelving's_Haunted_Mansion,Player was given the Evil Couch. See Frest Greelving.,Player was given the Evil Couch,TRUE +gearknightinvasionhighorecollectwait_1009,Conquest,Verified,,Turned in 10 Aetherium Ore in Direlands Invasion,,,Turned in 10 Aetherium Ore in Direlands Invasion,TRUE +gearknighttreasuremapfound,Conquest,Verified,,Treasure Maps,,Gearknight Treasure Map Found,Gearknight Treasure Map Found,FALSE +getthegoods,Conquest,Verified,,Get the Goods,,Getthegoods,Getthegoods,FALSE +ghostdencompleted,Conquest,Verified,,Ghost Den,,Ghostden Completed,Ghostden Completed,TRUE +ghostdenstarted,Conquest,Verified,,Ghost Den,,Ghostden Started,Ghostden Started,FALSE +ghostdrudgetokengiven,Conquest,Verified,,Ghost Drudge Tutorial,,Ghostdrudge Token Given,Ghostdrudge Token Given,FALSE +ghostdrudgetutorial,Conquest,Verified,,Ghost Drudge Tutorial,,Ghostdrudge Tutorial,Ghostdrudge Tutorial,FALSE +ghosttokenlooted,Conquest,Verified,,Forgotten One,,Ghosttoken Looted,Ghosttoken Looted,TRUE +ghosttreasuremapfound,Conquest,Verified,,Treasure Maps,,Ghost Treasure Map Found,Ghost Treasure Map Found,FALSE +glendenprisonchestopen,Conquest,Verified,,Glenden Prison Chest,,Glenden Prison Chest Open,GlendenPrisonChestOpen,TRUE +goldletterturnins,Conquest,Verified,Verified,Non-Quest,https://acportalstorm.com/wiki/Non-Quest,Counter for Lucky Gold Letter turn ins. See Collector; Black Hill Collector; Yukara Miko the Collector.,Counter for Lucky Gold Letter turn ins.,FALSE +goldletterturnintimer,Conquest,Verified,Verified,Non-Quest,https://acportalstorm.com/wiki/Non-Quest,Countdown timer for Lucky Gold Letter turn ins. See Yukara Miko the Collector; Collector; Black Hill Collector.,Countdown timer for Lucky Gold Letter turn ins.,TRUE +golemtreasuremapfound,Conquest,Verified,,Treasure Maps,,Golem Treasure Map Found,Golem Treasure Map Found,FALSE +gonestutorialcomplete,Conquest,Verified,,Gone's Tutorial,,Gones Tutorialcomplete,Gones Tutorialcomplete,FALSE +gonestutorialstart,Conquest,Verified,,Gone's Tutorial,,Gones Tutorialstart,Gones Tutorialstart,FALSE +gotroklugiantreasuremapfound,Conquest,Verified,,Treasure Maps,,Gotroklugian Treasure Map Found,Gotroklugian Treasure Map Found,FALSE +grievvertreasuremapfound,Conquest,Verified,,Treasure Maps,,Grievver Treasure Map Found,Grievver Treasure Map Found,FALSE +GrimacingRabbitTreasureMapFound,Conquest,Verified,,Treasure Maps,,Grimacing Rabbit Treasure Map Found,,FALSE +gromnietreasuremapfound,Conquest,Verified,,Treasure Maps,,Gromnie Treasure Map Found,Gromnie Treasure Map Found,FALSE +gurogtreasuremapfound,Conquest,Verified,,Treasure Maps,,Gurog Treasure Map Found,Gurog Treasure Map Found,FALSE +hassnowglobecabin,Conquest,Verified,,Player has recieved the Snowy Cabin Snowglobe.,,,Player has recieved the Snowy Cabin Snowglobe.,TRUE +hassnowglobesnowman,Conquest,Verified,,Player has recieved the Snowman Snowglobe.,,,Player has recieved the Snowman Snowglobe.,TRUE +hatredtunnels,Conquest,Verified,,Tunnels of Hatred,,Hatredtunnels,Hatredtunnels,FALSE +hauntedmansiondungeonpermission,Conquest,Verified,Verified,Frest Greelving's Haunted Mansion,https://acportalstorm.com/wiki/Frest_Greelving's_Haunted_Mansion,Player has permission to use Dungeon portal. See Frest Greelving.,Player has permission to use Dungeon portal,TRUE +heatumeroktreasuremapfound,Conquest,Verified,,Treasure Maps,,Heatumerok Treasure Map Found,Heatumerok Treasure Map Found,FALSE +hellbovinekillcount,Conquest,Verified,,Hell Bovine Kill Task,,Hellbovine Kill Count,Hellbovine Kill Count,TRUE +hellbovinekilltaskwait,Conquest,Verified,,Hell Bovine Kill Task,,Hellbovine Kill Task Cooldown,Hellbovine Kill Task Cooldown,TRUE +hellfiresorckillcount,Conquest,Verified,,Hellfire Sorcerer Kill Task,,Hellfiresorc Kill Count,Hellfiresorc Kill Count,TRUE +hellfiresorckilltaskwait,Conquest,Verified,,Hellfire Sorcerer Kill Task,,Hellfiresorc Kill Task Cooldown,Hellfiresorc Kill Task Cooldown,TRUE +hideandconquest,Conquest,Verified,,Hide and Conquest,,Hideandconquest,Hideandconquest,FALSE +historyderethvolipickup,Conquest,Verified,,History of Dereth,,Historyderethvoli Pickup,Historyderethvoli Pickup,TRUE +HizkRiEntranceFail,Conquest,Verified,,Hizk Ri,,,,FALSE +hmddarkseed,Conquest,Verified,,Uber HMD,,,,FALSE +hmddarkseedcountdown,Conquest,Verified,,Uber HMD,,,,FALSE +hmddarkseedhost,Conquest,Verified,,Uber HMD,,,,FALSE +hollowminiontreasuremapfound,Conquest,Verified,,Treasure Maps,,Hollowminion Treasure Map Found,Hollowminion Treasure Map Found,FALSE +hopeslayertreasuremapfound,Conquest,Verified,,Hope Slayer Treasure Map,,,,FALSE +hoshcachecooldown,Conquest,Verified,,Hosh Cache,,Hosh Cache Cooldown,Hosh Cache Cooldown,TRUE +humantreasuremapfound,Conquest,Verified,,Treasure Maps,,Human Treasure Map Found,Human Treasure Map Found,FALSE +icegiantkillcount,Conquest,Verified,,Ice Giant Kill Task,,Icegiant Kill Count,Icegiant Kill Count,TRUE +icegiantkilltask,Conquest,Verified,,Ice Giant Kill Task,,Icegiant Kill Task,Icegiant Kill Task,TRUE +IcyHideout,Conquest,Verified,,Icy Hideout,,,,FALSE +idahcachelockout,Conquest,Verified,,Idah Defense,,Idah Cache Lockout,Idah Cache Lockout,TRUE +idahcontribution,Conquest,Verified,,Idah Defense,,Idah Contribution,Idah Contribution,FALSE +IdahParticipation,Conquest,Verified,,Idah Defense,,,,FALSE +idahprimaryrewardclaimed,Conquest,Verified,,Idah Defense,,Idah Primary Reward Claimed,Idah Primary Reward Claimed,TRUE +idahtemp10,Conquest,Verified,,Idah Defense,,Idahtemp10,Idahtemp10,FALSE +IdahWave1,Conquest,Verified,,Idah Defense,,,,FALSE +IdahWave2,Conquest,Verified,,Idah Defense,,,,FALSE +IdahWave3,Conquest,Verified,,Idah Defense,,,,FALSE +IdahWave4,Conquest,Verified,,Idah Defense,,,,FALSE +IdahWave5,Conquest,Verified,,Idah Defense,,,,FALSE +idoltreasuremapfound,Conquest,Verified,,Treasure Maps,,Idol Treasure Map Found,Idol Treasure Map Found,FALSE +invasivespecies1,Conquest,Verified,,Invasive Species,,,,FALSE +invasivespecies2,Conquest,Verified,,Invasive Species,,,,FALSE +invasivespecies3,Conquest,Verified,,Invasive Species,,,,FALSE +invasivespeciesparticipation,Conquest,Verified,,Invasive Species,,,,FALSE +InvestigateDefiledTrail,Conquest,Verified,,The Defiled Armor,,,,FALSE +isanyonereadingthis,Conquest,Verified,,Crown Likes You,,Isanyonereadingthis,Isanyonereadingthis,FALSE +itachicachelockout,Conquest,Verified,,Itachi Defense,,Itachi Cache Lockout,Itachi Cache Lockout,TRUE +itachicontribution,Conquest,Verified,,Itachi Defense,,Itachi Contribution,Itachi Contribution,FALSE +ItachiParticipation,Conquest,Verified,,Itachi Defense,,,,FALSE +itachiprimaryrewardclaimed,Conquest,Verified,,Itachi Defense,,Itachi Primary Reward Claimed,Itachi Primary Reward Claimed,TRUE +ItachiWave1,Conquest,Verified,,Itachi Defense,,,,FALSE +ItachiWave2,Conquest,Verified,,Itachi Defense,,,,FALSE +ItachiWave3,Conquest,Verified,,Itachi Defense,,,,FALSE +ItachiWave4,Conquest,Verified,,Itachi Defense,,,,FALSE +ItachiWave5,Conquest,Verified,,Itachi Defense,,,,FALSE +JerikBladeStarted,Conquest,Verified,,Jerik's Blade,,,,FALSE +JerikKnifeQuest,Conquest,Verified,,Jerik's Blade,,,,FALSE +KeyOfSkins,Conquest,Verified,,Key of Skins,,,,FALSE +kieriencorepickup,Conquest,Verified,,quest timer,,,quest timer,TRUE +killtaskancientdrag,Conquest,Verified,,Ancient Dragon Kill Task,,,,FALSE +killtaskancientdragwait,Conquest,Verified,,Ancient Dragon Kill Task,,,,TRUE +killtaskblooddisciple,Conquest,Verified,,Blood Disciple Kill Task,,Kill Task Blood Disciple,Kill Task Blood Disciple,FALSE +KilltaskChaosDrag,Conquest,Verified,,Chaos Drudge Kill Task,,,,FALSE +killtaskchaosdragwait,Conquest,Verified,,quest timer,,,quest timer,TRUE +killtaskkhaodisciple,Conquest,Verified,,Khaos Disciple Kill Task,,Kill Taskkhaodisciple,Kill Taskkhaodisciple,TRUE +killtaskriftumbralwait0907,Conquest,Verified,,Umbral Rift Kill Task,,,Umbral Rift Kill Task,TRUE +killtasksawatoreddrag,Conquest,Verified,,Kill Task Sawato Red Dragon,,,,FALSE +killtasksawatoreddragwait,Conquest,Verified,,Kill Task Sawato Red Dragon,,,quest timer,TRUE +killtaskshoreking,Conquest,Verified,,kill counter,,,kill counter,FALSE +killtaskshorekingwait,Conquest,Verified,,Shore King Kill Task,,,,TRUE +KilltaskUmberclawRipper,Conquest,Verified,,Umberclaw Ripper Kill Task,,,,FALSE +KilltaskUmberclawRipperWait,Conquest,Verified,,Umberclaw Ripper Kill Task,,,,FALSE +KilltaskViridianGrom,Conquest,Verified,,Viridian Gromnie Kill Task,,,,FALSE +KilltaskViridianGromWait,Conquest,Verified,,Viridian Gromnie Kill Task,,,,FALSE +KilltaskViridianOak,Conquest,Verified,,Viridian Oak Kill Task,,,,FALSE +KilltaskViridianOakWait,Conquest,Verified,,Viridian Oak Kill Task,,,,FALSE +KilltaskViridianWisp,Conquest,Verified,,Viridian Wisp Kill Task,,,,FALSE +KilltaskViridianWispWait,Conquest,Verified,,Viridian Wisp Kill Task,,,,FALSE +knathteadtreasuremapfound,Conquest,Verified,,Treasure Maps,,Knathtead Treasure Map Found,Knathtead Treasure Map Found,FALSE +lceventcompleted,Conquest,Verified,,LC Event,,,-1,TRUE +LeapOfFaith,Conquest,Verified,,Leap of Faith,,,,FALSE +legacyshortcut,Conquest,Verified,,Shortcut,,Legacyshortcut,Legacyshortcut,TRUE +legendarykeyflayerskin73026,Conquest,Verified,,Legendary Flayer Skin Key,,,,FALSE +legendarylegendaryazaxisessence,Conquest,Verified,,,,,,FALSE +legendarylegendarybak'tshayessence,Conquest,Verified,,Creature Essences,,,,FALSE +legendarylegendarymudmouthessence,Conquest,Verified,,Creature Essences,,,,FALSE +legendarylegendarynexusmasteressence,Conquest,Verified,,,,,,FALSE +legendarylegendarypainbringeressence,Conquest,Verified,,Creature Essences,,Legendarylegendarypainbringer Essence,Legendarylegendarypainbringer Essence,FALSE +LegendaryLegendaryTargorEssence,Conquest,Verified,,Creature Essences,,,,FALSE +LegendaryLegendaryZefirEssence,Conquest,Verified,,Creature Essences,,,,FALSE +lightningelementaltreasuremapfound,Conquest,Verified,,Treasure Maps,,Lightning Elemental Treasure Map Found,Lightning Elemental Treasure Map Found,FALSE +lightningweaponstizamp,Conquest,Verified,,Lightning Weapons,,Received a Dragon Coin - Event Completed.,Received a Dragon Coin - Event Completed.,TRUE +lostsatchelpickup,Conquest,Verified,,Lost Satchel Pickup,,,You must wait to pick up this item again,TRUE +LotusPlucked,Conquest,Verified,,Lotus,,,,FALSE +LugianAssaultQalabar1,Conquest,Verified,,Lugian Assault on Qalabar,,,,FALSE +LugianAssaultQalabar2,Conquest,Verified,,Lugian Assault on Qalabar,,,,FALSE +LugianAssaultQalabar3,Conquest,Verified,,Lugian Assault on Qalabar,,,,FALSE +LugianAssaultQalabarParticipation,Conquest,Verified,,Lugian Assault on Qalabar,,,,FALSE +lugiantreasuremapfound,Conquest,Verified,,Treasure Maps,,Lugian Treasure Map Found,Lugian Treasure Map Found,FALSE +MacNiallBottle,Conquest,Verified,,MacNiall's Bottle,,,,FALSE +margultreasuremapfound,Conquest,Verified,,Treasure Maps,,Margul Treasure Map Found,Margul Treasure Map Found,FALSE +marionettetreasuremapfound,Conquest,Verified,,Treasure Maps,,Marionette Treasure Map Found,Marionette Treasure Map Found,FALSE +mattekartreasuremapfound,Conquest,Verified,,Treasure Maps,,Mattekar Treasure Map Found,Mattekar Treasure Map Found,FALSE +maythefourth,Conquest,Verified,,May the Fourth,,Maythefourth,Maythefourth,FALSE +metosassault1,Conquest,Verified,,,,,,FALSE +metosassault2,Conquest,Verified,,,,,,FALSE +metosassault3,Conquest,Verified,,,,,,FALSE +metosassault4,Conquest,Verified,,,,,,FALSE +metosassaultparticipation,Conquest,Verified,,,,,,FALSE +metosassaultreward,Conquest,Verified,,quest timer,,,quest timer,TRUE +MinorStoneWrit@2,Conquest,Verified,,Minor Stone Writ,,,,FALSE +MinorStoneWrit@3,Conquest,Verified,,Minor Stone Writ,,,,FALSE +minorstonewrit@4,Conquest,Verified,,Minor Stone Writ,,,,FALSE +mitetreasuremapfound,Conquest,Verified,,Treasure Maps,,Mite Treasure Map Found,Mite Treasure Map Found,FALSE +mithrilshieldpickup,Conquest,Verified,,Mithril Shield,,Mithrilshield Pickup,Mithrilshield Pickup,TRUE +moarsmantreasuremapfound,Conquest,Verified,,Treasure Maps,,Moarsman Treasure Map Found,Moarsman Treasure Map Found,FALSE +moartreasuremapfound,Conquest,Verified,,Treasure Maps,,Moar Treasure Map Found,Moar Treasure Map Found,FALSE +monougatreasuremapfound,Conquest,Verified,,Treasure Maps,,Monouga Treasure Map Found,Monouga Treasure Map Found,FALSE +moo?,Conquest,Verified,,Crown Likes You,,Moo?,Moo?,TRUE +morefreeqb,Conquest,Verified,,Crown Likes You,,Morefreeqb,Morefreeqb,FALSE +mosswartsbydesign,Conquest,Verified,,Mosswarts by Design,,Mosswartsbydesign,Mosswartsbydesign,FALSE +mosswarttreasuremapfound,Conquest,Verified,,Treasure Maps,,Mosswart Treasure Map Found,Mosswart Treasure Map Found,FALSE +mowenreward,Conquest,Verified,,TBD,,,TBD,TRUE +MuckThrown,Conquest,Verified,,Muck,,,,FALSE +MuckWielded,Conquest,Verified,,Muck,,,,FALSE +mukkirtreasuremapfound,Conquest,Verified,,Treasure Maps,,Mukkir Treasure Map Found,Mukkir Treasure Map Found,FALSE +muramasaisforging,Conquest,Verified,,Twilight Forging,,,,FALSE +mythicmythicdragonessence,Conquest,Verified,,Creature Essences,,,,FALSE +mythicmythicgaerlanessence,Conquest,Verified,,Creature Essences,,Mythicmythicgaerlanessence,Mythicmythicgaerlanessence,FALSE +mythicmythicladyaerfalleessence,Conquest,Verified,,Creature Essences,,,,FALSE +NastyRabbitTreasureMapFound,Conquest,Verified,,Treasure Maps,,Nasty Rabbit Treasure Map Found,,FALSE +nephthystransport,Conquest,Verified,,,,,,FALSE +NiffisMigration1,Conquest,Verified,,Niffis Migration,,,,FALSE +NiffisMigration2,Conquest,Verified,,Niffis Migration,,,,FALSE +NiffisMigration3,Conquest,Verified,,Niffis Migration,,,,FALSE +NiffisMigrationParticipation,Conquest,Verified,,Niffis Migration,,,,FALSE +NiffisMigrationReward,Conquest,Verified,,Niffis Migration,,,,FALSE +niffistreasuremapfound,Conquest,Verified,,Treasure Maps,,Niffis Treasure Map Found,Niffis Treasure Map Found,FALSE +NightSewersAccess,Conquest,Verified,,Twilight Sewers,,,,FALSE +NightSewersReward,Conquest,Verified,,Twilight Sewers,,,,FALSE +nobcachelockout,Conquest,Verified,,Nob Defense,,Nob Cache Lockout,Nob Cache Lockout,TRUE +nobcontribution,Conquest,Verified,,Nob Defense,,Nob Contribution,Nob Contribution,FALSE +NobCount,Conquest,Verified,,Nob Defense,,,,FALSE +NobParticipation,Conquest,Verified,,Nob Defense,,,,FALSE +nobprimaryrewardclaimed,Conquest,Verified,,Nob Defense,,Nob Primary Reward Claimed,Nob Primary Reward Claimed,TRUE +NobWave1,Conquest,Verified,,Nob Defense,,,,FALSE +NobWave2,Conquest,Verified,,Nob Defense,,,,FALSE +NobWave3,Conquest,Verified,,Nob Defense,,,,FALSE +NobWave4,Conquest,Verified,,Nob Defense,,,,FALSE +NobWave5,Conquest,Verified,,Nob Defense,,,,FALSE +nodachistart,Conquest,Verified,,Twilight Forging,,,,FALSE +northernpedestalshard_pickup,Conquest,Verified,,Player has picked up the Shard of the Northern Pedestal.,,,Player has picked up the Shard of the Northern Pedestal.,TRUE +northerntumerokinsignia,Conquest,Verified,,Northern Tumerok Insignia,,,Northern Tumerok Insignia,TRUE +nosoupforyou,Conquest,Verified,,Crown Likes You,,Nosoupforyou,Nosoupforyou,FALSE +nullifiedsarcophagus,Conquest,Verified,Verified,Frest Greelving's Haunted Mansion,https://acportalstorm.com/wiki/Frest_Greelving's_Haunted_Mansion,Player defeated the Sarcophagus. See Frest Greelving; Dark Sarcophagus.,Player defeated the Sarcophagus,TRUE +OldHickory1,Conquest,Verified,,Old Hickory,,,,FALSE +OldHickoryP1,Conquest,Verified,,Old Hickory,,,,FALSE +OldHickoryP2,Conquest,Verified,,Old Hickory,,,,FALSE +OldHickoryP3,Conquest,Verified,,Old Hickory,,,,FALSE +OldHickoryP4,Conquest,Verified,,Old Hickory,,,,FALSE +olthoideathrewardflag,Conquest,Verified,,Olthoi Death Reward,,,,FALSE +olthoiexperiments,Conquest,Verified,,Olthoi Experiments,,Olthoiexperiments,Olthoiexperiments,FALSE +olthoilarvaetreasuremapfound,Conquest,Verified,,Treasure Maps,,Olthoilarvae Treasure Map Found,Olthoilarvae Treasure Map Found,FALSE +olthoitreasuremapfound,Conquest,Verified,,Treasure Maps,,Olthoi Treasure Map Found,Olthoi Treasure Map Found,FALSE +paradoxolthoitreasuremapfound,Conquest,Verified,,Treasure Maps,,Paradoxolthoi Treasure Map Found,Paradoxolthoi Treasure Map Found,FALSE +peaceoath,Conquest,Verified,,Peace Oath,,Peace Oath,Peace Oath,FALSE +penguintreasuremapfound,Conquest,Verified,,Treasure Maps,,Penguin Treasure Map Found,Penguin Treasure Map Found,FALSE +phyntoswasptreasuremapfound,Conquest,Verified,,Treasure Maps,,Phyntoswasp Treasure Map Found,Phyntoswasp Treasure Map Found,FALSE +pickedupgrub,Conquest,Verified,,,,,,FALSE +pillarhellfirekillcount,Conquest,Verified,,Pillar Hellfire Kill Task,,Pillarhellfire Kill Count,Pillarhellfire Kill Count,TRUE +pillarhellfirekilltaskwait,Conquest,Verified,,Pillar Hellfire Kill Task,,Pillarhellfire Kill Task Cooldown,Pillarhellfire Kill Task Cooldown,TRUE +pillarjumper,Conquest,Verified,,Pillar Jumper,,Pillarjumper,Pillarjumper,FALSE +pitbeastdeath,Conquest,Verified,,,,,,FALSE +PlantedFlower,Conquest,Verified,,Tree Farm,,,,FALSE +plantedlotus,Conquest,Verified,,Planted Lotus,,,,FALSE +playersteppedthroughstopgap,Conquest,Verified,,Stopgap Portal,,,,FALSE +pledgeallegiancetoconquest,Conquest,Verified,,July 1st,,,,FALSE +portaljumper,Conquest,Verified,,Portal Jumper,,Portaljumper,Portaljumper,FALSE +PrayedAtTheTempleOfMules,Conquest,Verified,,Temple of Mules,,,,FALSE +pyrealmoteayangiven,Conquest,Verified,,Metos Motes,https://acportalstorm.com/wiki/Metos_Motes,Pyreal Mote in Ayan Baquar Halls of Metos given. See Golem Warden of Metos.,,FALSE +rabbittreasuremapfound,Conquest,Verified,,Treasure Maps,,Rabbit Treasure Map Found,Rabbit Treasure Map Found,FALSE +RareRareCrystalEssence,Conquest,Verified,,Creature Essences,,,,FALSE +RareRareEaterEssence,Conquest,Verified,,Creature Essences,,,,FALSE +rarerareghostessence,Conquest,Verified,,Creature Essences,,,,FALSE +rareraregrievveressence,Conquest,Verified,,Creature Essences,,,,FALSE +rareraregurogessence,Conquest,Verified,,Creature Essences,,Rare Rare Gurog Essence,Rare Rare Gurog Essence,FALSE +rarerarehollowessence,Conquest,Verified,,,,,,FALSE +RareRareIdolEssence,Conquest,Verified,,Creature Essences,,,,FALSE +rareraremonougaessence,Conquest,Verified,,Creature Essences,,,,FALSE +RareRareMukkirEssence,Conquest,Verified,,Creature Essences,,,,FALSE +rarerarepumpkinessence,Conquest,Verified,,Creature Essences,,Rarerarepumpkin Essence,Rarerarepumpkin Essence,FALSE +rarerareremoranessence,Conquest,Verified,,,,,,FALSE +rarerareruschkessence,Conquest,Verified,,Creature Essences,,,,FALSE +RareRareScarecrowEssence,Conquest,Verified,,Creature Essences,,,,FALSE +rareraresnowtuskeressence,Conquest,Verified,,Creature Essences,,,,FALSE +rareraretuskerprotectoressence,Conquest,Verified,,Creature Essences,,Rareraretuskerprotector Essence,Rareraretuskerprotector Essence,FALSE +rarerarevirindiessence,Conquest,Verified,,Creature Essences,,Rarerarevirindiessence,Rarerarevirindiessence,FALSE +ratpoison,Conquest,Verified,,,,,,FALSE +rattreasuremapfound,Conquest,Verified,,Treasure Maps,,Rat Treasure Map Found,Rat Treasure Map Found,FALSE +rebuilturenna,Conquest,Verified,,,,,,FALSE +redletterturnins,Conquest,Verified,Verified,Non-Quest,https://acportalstorm.com/wiki/Non-Quest,Counter for Scarlet Red Letter turn ins. See Black Hill Collector; Yukara Miko the Collector; Collector.,Counter for Scarlet Red Letter turn ins.,FALSE +redletterturnintimer,Conquest,Verified,Verified,Non-Quest,https://acportalstorm.com/wiki/Non-Quest,Countdown timer for Scarlet Red Letter turn ins. See Collector; Yukara Miko the Collector; Black Hill Collector.,Countdown timer for Scarlet Red Letter turn ins.,TRUE +reedsharktreasuremapfound,Conquest,Verified,,Treasure Maps,,Reedshark Treasure Map Found,Reedshark Treasure Map Found,FALSE +remorantreasuremapfound,Conquest,Verified,,Treasure Maps,,Remoran Treasure Map Found,Remoran Treasure Map Found,FALSE +respectokenlooted,Conquest,Verified,,Respec Token,,Respectoken Looted,Respectoken Looted,TRUE +rtwbossadds,Conquest,Verified,,Uber Curator,,Rtwbossadds,Rtwbossadds,FALSE +rtwcrystal,Conquest,Verified,,Uber Curator,,Rtwcrystal,Rtwcrystal,FALSE +rtwcurator1,Conquest,Verified,,Uber Curator,,Rtwcurator1,Rtwcurator1,FALSE +rtwcurator2,Conquest,Verified,,Uber Curator,,Rtwcurator2,Rtwcurator2,FALSE +rtwcurator3,Conquest,Verified,,Uber Curator,,Rtwcurator3,Rtwcurator3,FALSE +rtwcurator4,Conquest,Verified,,Uber Curator,,Rtwcurator4,Rtwcurator4,FALSE +RTWWave1,Conquest,Verified,,Uber Curator,,,,FALSE +RTWWave2,Conquest,Verified,,Uber Curator,,,,FALSE +RTWWave3,Conquest,Verified,,Uber Curator,,,,FALSE +RTWWave4,Conquest,Verified,,Uber Curator,,,,FALSE +ruschktreasuremapfound,Conquest,Verified,,Treasure Maps,,Ruschk Treasure Map Found,Ruschk Treasure Map Found,FALSE +salvagevendortutorial,Conquest,Verified,,Salvage Vendor Tutorial,,Salvage Vendor Tutorial,Salvage Vendor Tutorial,FALSE +SanctuaryDefenseParticipation,Conquest,Verified,,Sanctuary Defense,,,,FALSE +SanctuaryDefensePhase1Part1,Conquest,Verified,,Sanctuary Defense,,,,FALSE +SanctuaryDefensePhase1Part2,Conquest,Verified,,Sanctuary Defense,,,,FALSE +SanctuaryDefensePhase2Part1,Conquest,Verified,,Sanctuary Defense,,,,FALSE +SanctuaryDefensePhase2Part2,Conquest,Verified,,Sanctuary Defense,,,,FALSE +SanctuaryDefensePhase3Part1,Conquest,Verified,,Sanctuary Defense,,,,FALSE +SanctuaryDefensePhase3Part2,Conquest,Verified,,Sanctuary Defense,,,,FALSE +SanctuaryDefensePhase4Part1,Conquest,Verified,,Sanctuary Defense,,,,FALSE +SanctuaryDefensePhase4Part2,Conquest,Verified,,Sanctuary Defense,,,,FALSE +SanctuaryDefensePhase4Part3,Conquest,Verified,,Sanctuary Defense,,,,FALSE +sandshallows1access,Conquest,Verified,,Shallow Sands,,,,TRUE +sandshallows1reward,Conquest,Verified,,,,,,TRUE +sandshallows2access,Conquest,Verified,,,,,,TRUE +sandshallows2reward,Conquest,Verified,,,,,,TRUE +sandshallows3access,Conquest,Verified,,,,,,TRUE +sandshallows3reward,Conquest,Verified,,,,,,TRUE +sandshallows4access,Conquest,Verified,,,,,,TRUE +sandshallows4reward,Conquest,Verified,,,,,,TRUE +sclavustreasuremapfound,Conquest,Verified,,Treasure Maps,,Sclavus Treasure Map Found,Sclavus Treasure Map Found,FALSE +selainaorantewrit,Conquest,Verified,,Selaina Orante,,,,FALSE +shadowfortaccessed,Conquest,Verified,,Shadow Fort,,Shadowfortaccessed,Shadowfortaccessed,FALSE +shadowqueensspike,Conquest,Verified,,Shadow Queen's Spike,,,quest timer,TRUE +shadowqueensspikefirstturnin,Conquest,Verified,,Shadow Queen's Spike First Turn-In,,,,FALSE +shadowtreasuremapfound,Conquest,Verified,,Treasure Maps,,Shadow Treasure Map Found,Shadow Treasure Map Found,FALSE +shallowssharktreasuremapfound,Conquest,Verified,,Treasure Maps,,Shallowsshark Treasure Map Found,Shallowsshark Treasure Map Found,FALSE +ShirtBeltsloraHardQuest,Conquest,Verified,,Beltslora's Shirt,,,,FALSE +shrethtreasuremapfound,Conquest,Verified,,Treasure Maps,,Shreth Treasure Map Found,Shreth Treasure Map Found,FALSE +shrineofknowledgetokengiven,Conquest,Verified,,Shrine of Knowledge Tutorial,,Shrineofknowledge Token Given,Shrineofknowledge Token Given,FALSE +shrineofknowledgetutorial,Conquest,Verified,,Shrine of Knowledge Tutorial,,Shrineofknowledge Tutorial,Shrineofknowledge Tutorial,FALSE +simulacrumtreasuremapfound,Conquest,Verified,,Treasure Maps,,Simulacrum Treasure Map Found,Simulacrum Treasure Map Found,FALSE +siraluuntreasuremapfound,Conquest,Verified,,Treasure Maps,,Siraluun Treasure Map Found,Siraluun Treasure Map Found,FALSE +skeletontreasuremapfound,Conquest,Verified,,Treasure Maps,,Skeleton Treasure Map Found,Skeleton Treasure Map Found,FALSE +slaverevolt!1,Conquest,Verified,,,,,,FALSE +slaverevolt!2,Conquest,Verified,,,,,,FALSE +slaverevolt!3,Conquest,Verified,,,,,,FALSE +slaverevolt!4,Conquest,Verified,,,,,,FALSE +slaverevolt!5,Conquest,Verified,,,,,,FALSE +slaverevolt1,Conquest,Verified,,,,,,FALSE +slaverevolt2,Conquest,Verified,,,,,,FALSE +slaverevolt3,Conquest,Verified,,,,,,FALSE +slaverevolt4,Conquest,Verified,,,,,,FALSE +slaverevolt5,Conquest,Verified,,,,,,FALSE +slaverevoltparticipation,Conquest,Verified,,,,,,FALSE +slaverevoltreward,Conquest,Verified,,quest timer,,,quest timer,TRUE +slithistreasuremapfound,Conquest,Verified,,Treasure Maps,,Slithis Treasure Map Found,Slithis Treasure Map Found,FALSE +smolderingchesthatedtunnels,Conquest,Verified,,Smoldering Chest,,,,TRUE +Snowball,Conquest,Verified,,Snowball Fight,,,,FALSE +SnowballHits,Conquest,Verified,,Snowball Fight,,,,FALSE +snowmantreasuremapfound,Conquest,Verified,,Treasure Maps,,Snowman Treasure Map Found,Snowman Treasure Map Found,FALSE +solidmukkirorbnotespickup,Conquest,Verified,,Timer for Halmeras Encoded Notes pickup,,,Timer for Halmera's Encoded Notes pickup,TRUE +solosbighammer,Conquest,Verified,,Solo's Big Hammer,,,,FALSE +spokenbrighteyes,Conquest,Verified,Verified,Oswald's Dirk Quest,https://acportalstorm.com/wiki/Oswald's_Dirk_Quest,TBD. See Brighteyes; the Tailor. In Oolatangas refuge.,TBD,FALSE +SpokeToYasujiro,Conquest,Verified,,Yasujiro's Bell,,,,FALSE +startedforging,Conquest,Verified,,Twilight Forging,,,,FALSE +startthetears,Conquest,Verified,,Tears of Cragstone,,Startthetears,Startthetears,FALSE +StatueKivikLirGuardianAntechamber,Conquest,Verified,,Kivik Lir Guardian,,,,FALSE +statuetreasuremapfound,Conquest,Verified,,Treasure Maps,,Statue Treasure Map Found,Statue Treasure Map Found,FALSE +strongholdbuildercompletehelmgiven,Conquest,Verified,,Stronghold Builder,,,,FALSE +SummoningCaveDule,Conquest,Verified,,Summoning Cave,,,,FALSE +swarmtreasuremapfound,Conquest,Verified,,,,,,FALSE +SyndicateKTCompleted,Conquest,Verified,,Syndicate Wipeout,,,,FALSE +SyndicateWipeout,Conquest,Verified,,Syndicate Wipeout,,,,FALSE +TalkedToZahar,Conquest,Verified,,Zahar,,,,FALSE +targettreasuremapfound,Conquest,Verified,,,,,,FALSE +TenebrousEvidence,Conquest,Verified,,Tenebrous Evidence,,,,FALSE +TenebrousEvidenceGiven,Conquest,Verified,,Tenebrous Evidence,,,,FALSE +TheBlightedHiveDescent,Conquest,Verified,,The Blighted Hive,,,,FALSE +thequeenisdead,Conquest,Verified,,The Queen Is Dead,,,quest timer,TRUE +thereisnocowlevel,Conquest,Verified,,Crown Likes You,,Thereisnocowlevel,Thereisnocowlevel,FALSE +ThisFeelsWrong,Conquest,Verified,,This Feels Wrong,,,,FALSE +thorstenslegacy,Conquest,Verified,,Thorsten's Legacy,,Thorstenslegacy,Thorstenslegacy,FALSE +thorstenslegacycompleted,Conquest,Verified,,Thorsten's Legacy,,Thorstenslegacy Completed,,FALSE +throughthemazesidequest,Conquest,Verified,,Through the Maze Side Quest,,,quest timer,TRUE +thrungustreasuremapfound,Conquest,Verified,,Treasure Maps,,Thrungus Treasure Map Found,Thrungus Treasure Map Found,FALSE +timeshatteredstonepickup,Conquest,Verified,,Time-Shattered Stone,,Timeshatteredstone Pickup,Timeshatteredstone Pickup,FALSE +Torch,Conquest,Verified,,Torch,,,,FALSE +totemtokengiven,Conquest,Verified,,Totem Vendor Tutorial,,Totem Token Given,Totem Token Given,FALSE +totemvendortutorial,Conquest,Verified,,Totem Vendor Tutorial,,Totem Vendor Tutorial,Totem Vendor Tutorial,FALSE +TreasureTemple,Conquest,Verified,,Treasure Temple,,,,FALSE +treasurevaultdiver,Conquest,Verified,,Treasure Vault Diver,,Treasurevaultdiver,Treasurevaultdiver,FALSE +treefarmparticipant,Conquest,Verified,,Tree Farm,,Treefarmparticipant,Treefarmparticipant,TRUE +treefarmreceivedreward,Conquest,Verified,,Tree Farm,,Treefarmreceived Reward,Treefarmreceived Reward,TRUE +TreeFarmReward,Conquest,Verified,,Tree Farm,,,,FALSE +TreeHealed,Conquest,Verified,,Tree Farm,,,,FALSE +Trigram1,Conquest,Verified,,The Five Trigrams,,,,FALSE +Trigram2,Conquest,Verified,,The Five Trigrams,,,,FALSE +Trigram3,Conquest,Verified,,The Five Trigrams,,,,FALSE +Trigram4,Conquest,Verified,,The Five Trigrams,,,,FALSE +Trigram5,Conquest,Verified,,The Five Trigrams,,,,FALSE +tumeroktreasuremapfound,Conquest,Verified,,Treasure Maps,,Tumerok Treasure Map Found,Tumerok Treasure Map Found,FALSE +tunnelsdeath,Conquest,Verified,,,,,,FALSE +tuskertreasuremapfound,Conquest,Verified,,Treasure Maps,,Tusker Treasure Map Found,Tusker Treasure Map Found,FALSE +TwilightSewersAccess,Conquest,Verified,,Twilight Sewers,,,,FALSE +TwilightSewersReward,Conquest,Verified,,Twilight Sewers,,,,FALSE +UberBellas1,Conquest,Verified,,Uber Bellas,,,,FALSE +uberbellas2,Conquest,Verified,,Uber Bellas,,Uber Bellas 2,Uber Bellas 2,TRUE +uberbellas3,Conquest,Verified,,Uber Bellas,,Uber Bellas 3,,TRUE +UberBellas4,Conquest,Verified,,Uber Bellas,,,,FALSE +UberBellas6,Conquest,Verified,,Uber Bellas,,,,FALSE +UberHMD1,Conquest,Verified,,Uber Curator,,,,FALSE +UberHMD2,Conquest,Verified,,Uber Curator,,,,FALSE +UberHMDCacheLockout,Conquest,Verified,,Uber Curator,,,,FALSE +UberHMDConsolationPrize,Conquest,Verified,,Uber Curator,,,,FALSE +UberHMDPrimaryRewardClaimed,Conquest,Verified,,Uber Curator,,,,FALSE +ubermetos1,Conquest,Verified,,,,,,TRUE +ubermetosdustdevillockout,Conquest,Verified,,,,,,TRUE +ubermetosdustdevilprimary,Conquest,Verified,,,,,,TRUE +ubermetosexpeditionlockout,Conquest,Verified,,,,,,TRUE +ubermetosexpeditionprimary,Conquest,Verified,,,,,,TRUE +ubermetospitbeastlockout,Conquest,Verified,,,,,,TRUE +ubermetospitbeastprimary,Conquest,Verified,,,,,,TRUE +ubermetosrockbiterlockout,Conquest,Verified,,,,,,TRUE +ubermetosrockbiterprimary,Conquest,Verified,,,,,,TRUE +ubermetossiralfriclockout,Conquest,Verified,,,,,,TRUE +ubermetossiralfricprimary,Conquest,Verified,,,,,,TRUE +uberpawlooted,Conquest,Verified,,Uber Bobo,,You defeated the Prince of the Tuskers Oolatanga will be interested in this.,,TRUE +uberrtwcachelockout,Conquest,Verified,,Uber Curator,,Uberrtw Cache Lockout,Uberrtw Cache Lockout,TRUE +uberrtwconsolationprize,Conquest,Verified,,quest timer,,,quest timer,TRUE +UberRTWPop,Conquest,Verified,,Uber Curator,,,,FALSE +uberrtwreward,Conquest,Verified,,Uber Curator,,Uberrtw Reward,Uberrtw Reward,TRUE +uberslavemaster1,Conquest,Verified,,Uber Slave Master,,,,TRUE +uberslavemaster2,Conquest,Verified,,,,,,TRUE +uberslavemasterbutcherreward,Conquest,Verified,,Uber Slave Master,,,,TRUE +uberslavemastercachelockout,Conquest,Verified,,Uber Slave Master,,,,TRUE +uberslavemasterconsolationprize,Conquest,Verified,,,,,,TRUE +uberslavemasterprimaryrewardclaimed,Conquest,Verified,,Uber Slave Master,,,,TRUE +uberslavemasterstatuereward,Conquest,Verified,,,,,,TRUE +uberslavemastertwinsreward,Conquest,Verified,,,,,,TRUE +ulgrimsdrinkingcontestdrinking,Conquest,Verified,,,,,,FALSE +ulgrimsdrinkingcontestdrinks,Conquest,Verified,,,,,,FALSE +ulgrimsdrinkingcontestwins,Conquest,Verified,,,,,,FALSE +undeadmisery,Conquest,Verified,,Undead Misery,,Undeadmisery,Undeadmisery,FALSE +undeadtreasuremapfound,Conquest,Verified,,Treasure Maps,,Undead Treasure Map Found,Undead Treasure Map Found,FALSE +unknowntreasuremapfound,Conquest,Verified,,Treasure Maps,,Unknown Treasure Map Found,Unknown Treasure Map Found,FALSE +UrsuinTreasureMapFound,Conquest,Verified,,Treasure Maps,,Ursuin Treasure Map Found,,FALSE +urzastokengiven,Conquest,Verified,,Urza's Token Given,,Urzas Token Given,Urzas Token Given,FALSE +verdantenergy,Conquest,Verified,,,,,,FALSE +viamontianknighttreasuremapfound,Conquest,Verified,,Treasure Maps,,Viamontianknight Treasure Map Found,Viamontianknight Treasure Map Found,FALSE +viridianportalgreattreerewardwait,Conquest,Verified,,Viridian Portal Great Tree,,Viridian Portal Great Tree Rewards Cooldown,Viridian Portal Great Tree Rewards Cooldown,TRUE +virinditreasuremapfound,Conquest,Verified,,Treasure Maps,,Virindi Treasure Map Found,Virindi Treasure Map Found,FALSE +WaterHauled,Conquest,Verified,,Sanctuary Defense,,,,FALSE +weeventcompleted,Conquest,Verified,,Wintersebb Event Completed,,,,TRUE +werewolfhunt,Conquest,Verified,,Werewolf Hunt,,Werewolfhunt,Werewolfhunt,FALSE +wieldingfishingpole,Conquest,Verified,,Fishing,,,,FALSE +wieldingshovel,Conquest,Verified,,Wielding the Shovel,,Wieldingshovel,Wieldingshovel,FALSE +wisptreasuremapfound,Conquest,Verified,,Treasure Maps,,Wisp Treasure Map Found,Wisp Treasure Map Found,FALSE +YasujiroBellRang,Conquest,Verified,,Yasujiro's Bell,,,,FALSE +YasujiroRepeat,Conquest,Verified,,Yasujiro's Bell,,,,FALSE +YasujiroReward,Conquest,Verified,,Yasujiro's Bell,,,,FALSE +YasujiroStart,Conquest,Verified,,Yasujiro's Bell,,,,FALSE +yougotvitaeagain,Conquest,Verified,,You Got Vitae Again,,,,FALSE +zaharsblessing,Conquest,Verified,,Zahar's Blessing,,,,FALSE +zefirtreasuremapfound,Conquest,Verified,,Treasure Maps,,Zefir Treasure Map Found,Zefir Treasure Map Found,FALSE diff --git a/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj b/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj new file mode 100644 index 0000000..550509a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj @@ -0,0 +1,39 @@ + + + + + RynthCore.Plugin.RynthConquest + 0.2.0 + conquest + Conquest + acconquest.ddns.net + Conquest|ConquestAC + Conquest only: the server card, and Conquest's bank (with auto-deposit), augmentations, levels past 275, fellowships, custom quests and leaderboards in the Mini Remote, and Conquest's quests in RynthOracle. + + + + + + + + + + + + + + + + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs b/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs new file mode 100644 index 0000000..cc9468b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs @@ -0,0 +1,25 @@ +// ServerData.cs - What is known about Conquest (RynthConquest). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Development", + Summary = "Custom PvE server with live events, deep crafting, active development, and PK system.", + Facts = new[] + { + "Live events and deep crafting.", + "Has a PK system on a PvE server.", + "Its quest pack (quests.conquest.csv, Conquest's own quests) shows in RynthOracle's Quests tab.", + "RynthConquest's pages (Server section, or /rserver): bank and auto-deposit, augmentations, levels past 275, fellowships, custom quests, leaderboards.", + }, + Discord = "https://discord.gg/Gsadhhv72S", + Website = "https://dsc.gg/conquerac", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/THIRD_PARTY_NOTICES.md b/Plugins/RynthCore.Plugin.RynthConquest/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..2b666bd --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthConquest/THIRD_PARTY_NOTICES.md @@ -0,0 +1,44 @@ +# Third-party notices: RynthConquest + +RynthConquest's Conquest features (the bank, advanced and enlightenment augmentations, XP bonuses +and levels past 275, the fellowship list, the /top boards, the custom quest worklist, the +auto-deposit and the Void damage-over-time duration rule) are ported from **Oracle of Dereth**, a +Decal plugin for Asheron's Call by **Advis Eveldan** (GitHub: +[advis61](https://github.com/advis61/OracleOfDereth)). They were part of RynthOracle until +2026-10-20 and moved here so that only Conquest players carry them. Thank you, Advis! + +- Upstream: https://github.com/advis61/OracleOfDereth +- Ported from commit `ee618c6847b98b656a47ca87cc347441d206c547` (2026-10-01, version 2.3.0). +- Licence: MIT. The upstream README states "License: MIT". The repository has no separate + LICENSE file and names no copyright line, so the standard MIT text is reproduced below + with the author and the years of the repository's history. + +What came from upstream: `Resources\customquests.csv` (copied unchanged); `Resources\quests.conquest.csv`, +the master quest list's Conquest rows (split by its own Server column, lines unchanged; RynthOracle's +until 2026-10-21, now offered to RynthOracle's Quests tab through "RynthServer.QuestPack"); and the +logic of the features above, rewritten for RynthCore. Ported files say so in their header. RynthOracle's quest +flag parser (`QuestFlags.cs`, also ported from upstream) is compiled in as shared source. + +--- + +MIT License + +Copyright (c) 2024-2026 Advis Eveldan (GitHub: advis61) and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Plugins/RynthCore.Plugin.RynthDerptide/RynthCore.Plugin.RynthDerptide.csproj b/Plugins/RynthCore.Plugin.RynthDerptide/RynthCore.Plugin.RynthDerptide.csproj new file mode 100644 index 0000000..b1e82e5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDerptide/RynthCore.Plugin.RynthDerptide.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthDerptide + 0.1.0 + derptide + Derptide + ac.derptide.net + Derptide + Derptide only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthDerptide/ServerData.cs b/Plugins/RynthCore.Plugin.RynthDerptide/ServerData.cs new file mode 100644 index 0000000..6ef4066 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDerptide/ServerData.cs @@ -0,0 +1,25 @@ +// ServerData.cs - What is known about Derptide (RynthDerptide). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "EOR server that pushes custom content and Qol changes, All quest weapons have been upgraded to be useful, " + + "and usable. No quest item will EVER be better than lootgen, Live events, Ongoing story arcs. and TONS of tailoring options.", + Facts = new[] + { + "Quest weapons are upgraded to be useful, but never better than loot-generated items.", + "Live events and ongoing story arcs.", + "Many tailoring options.", + }, + Discord = "https://discord.gg/3gDTBVtfAg", + Website = "https://derptide.net", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj new file mode 100644 index 0000000..8b1faa3 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthDreamWeave + 0.1.0 + dreamweave + DreamWeave + play.acdreamweave.com + DreamWeave|Dream Weave + DreamWeave only: the server card (rules, server features, player commands, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs new file mode 100644 index 0000000..e17a30b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs @@ -0,0 +1,76 @@ +// ServerData.cs - What is known about DreamWeave (RynthDreamWeave). Identity (id, hosts, world names) is in the csproj. +// The features and commands come from the server's public source (ACE-DreamWeave: its README and the +// player-level chat commands under Source/ACE.Server/Command/Handlers). Stock ACE commands and the +// stage-test-shard grants (/myxp, /mylum, ...) are left out. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Development", + Summary = "PvE server pushing unmodified end-of-retail ToD to the limit. Lore driven, new class abilities, " + + "new crafting system, tons of QOL, up-to-date wiki.", + Facts = new[] + { + "Lore driven, built on end-of-retail Throne of Destiny.", + "New class abilities and a new crafting system.", + "Its wiki is kept up to date.", + "Class abilities: trainers sell ability tokens for class ability points (/abilities, /cavoucher).", + "Equipment and weapon mods on armor, clothing and jewelry (/mods).", + "Facets: several builds per character, including a PK facet (/facet).", + "In-game bank for pyreals, luminance, legendary keys, promissory and trade notes (/bank).", + "Account vault (mule) with its own vendor, shared with characters you choose (/mule).", + "Player market: browse, list and buy items (/market).", + "Realms and ephemeral instances (/realm, /exitinst).", + "Drift Network: a hall of linked drift-doors, recalled to with /dn (/tn for the retail Town Network).", + "Threads dungeons (/dd) and treasure-map dig sites (/digsite, /rrtm).", + "PvP arenas (1v1, 2v2, Tugak Brawl free-for-all) and battlegrounds on templates, with ratings (/arena).", + "Leaderboards for DPS, defense, waves, speed, level, bank, stamps, threads and PvP (/top).", + "XP, luminance and custom augmentations (/aug).", + "Experience bonuses: gear, augmentations, alt-character catch-up and offline (/bonus).", + "Fast tick opt-in: faster spell release, fast-chug and melee stick-to-target (/fasttick).", + "Web character sheet you can publish (/charsheet).", + }, + Commands = new[] + { + new ServerCommand("/bank", "deposit, withdraw, transfer and check banked currency (/b d deposits everything)"), + new ServerCommand("/mule", "summon your account vault's vendor, or manage who can use it"), + new ServerCommand("/market", "browse, list and buy items on the market"), + new ServerCommand("/abilities", "manage your class abilities"), + new ServerCommand("/cavoucher", "buy a class ability token for ability points, or refund an unused one"), + new ServerCommand("/facet", "show your facets; /facet switches build, /facet pk the PK facet"), + new ServerCommand("/mods", "summarize the equipment mods on what you wear"), + new ServerCommand("/aug", "augmentation list: /aug xp, /aug lum or /aug custom"), + new ServerCommand("/dn", "recall to the Drift Network (moving too far interrupts it)"), + new ServerCommand("/tn", "recall to the retail Town Network"), + new ServerCommand("/realm", "which realm and instance you are in"), + new ServerCommand("/exitinst", "leave the current ephemeral instance"), + new ServerCommand("/dd", "Threads dungeon status"), + new ServerCommand("/digsite", "status of the dig site you are at; /digsite bail ends one you dug"), + new ServerCommand("/rrtm", "reroll a treasure map's dig site to the one nearest you"), + new ServerCommand("/arena", "PvP arena: /arena join 1v1|2v2|tugak|bg, templates, status, rating, top"), + new ServerCommand("/top", "leaderboards: dps, defense, wave, speed, level, bank, stamp, thread, 1v1, 2v2, tugak, bg"), + new ServerCommand("/xp", "your experience progress"), + new ServerCommand("/quests", "your quest stamp progress"), + new ServerCommand("/bonus", "every experience bonus you have and the total (/altbonus, /offlinebonus)"), + new ServerCommand("/lph", "luminance per hour since login, or since /lph start"), + new ServerCommand("/pickupspeed", "your pick-up speed bonus, including permanent quest bonuses"), + new ServerCommand("/fasttick", "fast tick on, off, default or status"), + new ServerCommand("/dotdamage", "show or hide your damage-over-time tick messages"), + new ServerCommand("/summondamage", "show or hide a chat line for each hit your pets land"), + new ServerCommand("/summonattackontarget", "pets switch to the monster you last hit (on or off)"), + new ServerCommand("/relaria", "Aun Relaria repeat-kill aura visual: /relaria aura on|off"), + new ServerCommand("/charsheet", "publish a web character sheet (off, rotate)"), + new ServerCommand("/fi", "resend nearby monsters and NPCs (invisible creatures), once a minute"), + }, + Discord = "https://discord.gg/p2h3yca4BD", + Wiki = "https://wiki.acdreamweave.com", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13; features and commands from " + + "github.com/Awful-Waffle-Rofl/ACE-DreamWeave (4aa7de6), checked 2026-10-14", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthEversong/RynthCore.Plugin.RynthEversong.csproj b/Plugins/RynthCore.Plugin.RynthEversong/RynthCore.Plugin.RynthEversong.csproj new file mode 100644 index 0000000..b972d60 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthEversong/RynthCore.Plugin.RynthEversong.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthEversong + 0.1.0 + eversong + Eversong + eversong.abrdns.com + Eversong + Eversong only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthEversong/ServerData.cs b/Plugins/RynthCore.Plugin.RynthEversong/ServerData.cs new file mode 100644 index 0000000..916e5d6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthEversong/ServerData.cs @@ -0,0 +1,24 @@ +// ServerData.cs - What is known about Eversong (RynthEversong). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "Five difficulty worlds, quest bonuses, enlightenment & milestones, banking & lockboxes, invasions, optional classes.", + Facts = new[] + { + "Five difficulty worlds.", + "Quest bonuses, enlightenment and milestones.", + "Banking and lockboxes.", + "Invasions and optional classes.", + }, + Discord = "https://discord.gg/9eHxTb7p2J", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthFrostACE/RynthCore.Plugin.RynthFrostACE.csproj b/Plugins/RynthCore.Plugin.RynthFrostACE/RynthCore.Plugin.RynthFrostACE.csproj new file mode 100644 index 0000000..4baa0d6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthFrostACE/RynthCore.Plugin.RynthFrostACE.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthFrostACE + 0.1.0 + frostace + FrostACE + 172.111.230.127 + FrostACE|FrostfACE + FrostACE only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthFrostACE/ServerData.cs b/Plugins/RynthCore.Plugin.RynthFrostACE/ServerData.cs new file mode 100644 index 0000000..d103925 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthFrostACE/ServerData.cs @@ -0,0 +1,22 @@ +// ServerData.cs - What is known about FrostACE (RynthFrostACE). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Development", + Summary = "New accounts include lvl 275 starter characters. Retail character restoration also supported.", + Facts = new[] + { + "New accounts get level 275 starter characters.", + "Retail character restoration is supported.", + "Listed as \"FrostfACE\" in the public server list; it connects by IP address.", + }, + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthFrostcull/RynthCore.Plugin.RynthFrostcull.csproj b/Plugins/RynthCore.Plugin.RynthFrostcull/RynthCore.Plugin.RynthFrostcull.csproj new file mode 100644 index 0000000..04f81e2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthFrostcull/RynthCore.Plugin.RynthFrostcull.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthFrostcull + 0.1.0 + frostcull + Frostcull + frostcull.ddns.net + Frostcull + Frostcull only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthFrostcull/ServerData.cs b/Plugins/RynthCore.Plugin.RynthFrostcull/ServerData.cs new file mode 100644 index 0000000..d0e8e87 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthFrostcull/ServerData.cs @@ -0,0 +1,24 @@ +// ServerData.cs - What is known about Frostcull (RynthFrostcull). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "NO LEVEL/ATTRIBUTE CAP! 10x XP/Luminance, 25x Drop Rate, Quest Timers Reduced By 90%!", + Facts = new[] + { + "No level or attribute cap.", + "10x experience and luminance.", + "25x drop rate.", + "Quest timers 90% shorter.", + }, + Discord = "https://discord.gg/RQF7HgEZn4", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyParse.cs b/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyParse.cs new file mode 100644 index 0000000..984839f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyParse.cs @@ -0,0 +1,229 @@ +// BountyParse.cs - Parses ACECustom's bounty output (BountyManager / BountyCommands). +// +// The progress itself (PropertyString BountyProgress) is server-only, so the tracker reads +// what the server prints. All lines are ChatMessageType.Broadcast: +// /bounty list "Bounties:" header, then one line per reward of every active area: +// " {where}: {amount} {item} every {N kill(s)}[ (at most every {wait})] - you: {status}." +// footer "Bounty: type /bounty to see the bounties where you stand." +// or "Bounty: there are no bounties anywhere right now." +// /bounty "Bounty[ (all zones)| ({region})]: {amount} {item} - {status}." +// or "Bounty: there is no bounty here." +// status "{k} of {n} kills" | "unlocks in {wait}, then {N kill(s)} required" | "needs {qb} QB (you have {n})" +// events "Bounty unlocked: {item} - {N kill(s)} required." "Bounty complete! +{n} {item} gained." +// "Next bounty unlocks in {wait} - {N kill(s)} required." "Next bounty requires {N kill(s)}." +// held rewards: "Bounty: +{n} ..." / "Bounty: Your inventory is full. ..." +// wait "45 sec", "5 min", "2 min 30 sec", "1 hr 15 sec" (FormatWait); numbers use N0 grouping. +// A server without the bounty system answers "Unknown command: bounty". +using System; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthILT.Bounty; + +/// Where the player stands on one bounty reward. +internal enum BountyStatus +{ + /// Kills are counting: Kills of KillsRequired. + Counting = 0, + /// The cooldown after the last award runs; kills do not count until UnlockAtUtc. + Cooldown = 1, + /// The player's QB is below the reward's minimum; kills do not count. + NeedsQb = 2, +} + +/// One parsed status phrase. +internal readonly record struct BountyStatusInfo(BountyStatus Status, int Kills, int KillsRequired, + int WaitSeconds, long QbRequired, long QbHave); + +/// One "/bounty list" line. +internal readonly record struct BountyListLine(string Where, long Amount, string Item, int KillsRequired, + int CooldownSeconds, BountyStatusInfo Status); + +/// One "/bounty" (where you stand) line. Scope is "" (this dungeon/zone), "all zones" or a region name. +internal readonly record struct BountyHereLine(string Scope, long Amount, string Item, BountyStatusInfo Status); + +/// Kind of a bounty chat event. +internal enum BountyEventKind { Unlocked, Complete, NextCooldown, NextReady, Held } + +internal static class BountyParse +{ + private const RegexOptions Opt = RegexOptions.Compiled | RegexOptions.CultureInvariant; + private const string Num = @"\d[\d,]*"; + + // Status alternatives are spelled out inside the line patterns so backtracking can place the + // " - " separator correctly when an item name itself contains " - ". + private const string StatusPattern = + @"(?" + Num + @" of " + Num + @" kills?|unlocks in .+?, then " + Num + @" kills? required|needs " + + Num + @" QB \(you have " + Num + @"\))"; + + /// "/bounty list" reward line (leading indentation already trimmed). + private static readonly Regex ListLine = new( + @"^(?.+?): (?" + Num + @") (?.+?) every (?" + Num + @") kills?" + + @"(?: \(at most every (?[^)]+)\))? - you: " + StatusPattern + @"\.$", Opt); + + /// "/bounty" reward line. + private static readonly Regex HereLine = new( + @"^Bounty(?: \((?[^)]+)\))?: (?" + Num + @") (?.+?) - " + StatusPattern + @"\.$", Opt); + + private static readonly Regex Counting = new(@"^(?" + Num + @") of (?" + Num + @") kills?$", Opt); + private static readonly Regex Cooldown = new(@"^unlocks in (?.+?), then (?" + Num + @") kills? required$", Opt); + private static readonly Regex Qb = new(@"^needs (?" + Num + @") QB \(you have (?" + Num + @")\)$", Opt); + private static readonly Regex WaitPart = new(@"(?\d+)\s*(?hr|min|sec)\b", Opt); + + private static readonly Regex EvUnlocked = new(@"^Bounty unlocked: (?.+) - (?" + Num + @") kills? required\.$", Opt); + private static readonly Regex EvComplete = new(@"^Bounty complete! \+(?" + Num + @") (?.+) gained\.$", Opt); + private static readonly Regex EvNextWait = new(@"^Next bounty unlocks in (?.+?) - (?" + Num + @") kills? required\.$", Opt); + private static readonly Regex EvNextReady = new(@"^Next bounty requires (?" + Num + @") kills?\.$", Opt); + + /// "/bounty list" header line. + public const string ListHeader = "Bounties:"; + + /// True for the line that ends a "/bounty list" reply (footer or "no bounties anywhere"). + public static bool IsListTerminator(string text) + => text.StartsWith("Bounty: type /bounty", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("Bounty: there are no bounties anywhere", StringComparison.OrdinalIgnoreCase); + + /// True when the terminator says no bounty is active anywhere. + public static bool IsNoBountiesAnywhere(string text) + => text.StartsWith("Bounty: there are no bounties anywhere", StringComparison.OrdinalIgnoreCase); + + /// ACE's reply to a command the server doesn't register. + public static bool IsUnknownCommand(string text) + => text.StartsWith("Unknown command: bounty", StringComparison.OrdinalIgnoreCase); + + /// Parses a "/bounty list" reward line. + public static bool TryParseListLine(string text, out BountyListLine line) + { + line = default; + var m = ListLine.Match((text ?? string.Empty).Trim()); + if (!m.Success || !TryParseStatus(m.Groups["status"].Value, out var status)) return false; + int required = ToInt(m.Groups["kills"].Value); + int cooldown = m.Groups["cd"].Success ? ParseWaitSeconds(m.Groups["cd"].Value) : 0; + line = new BountyListLine(m.Groups["where"].Value.Trim(), ParseLong(m.Groups["amount"].Value), + m.Groups["item"].Value.Trim(), required, cooldown, status); + return true; + } + + /// Parses a "/bounty" (where you stand) reward line. + public static bool TryParseHereLine(string text, out BountyHereLine line) + { + line = default; + var m = HereLine.Match((text ?? string.Empty).Trim()); + if (!m.Success || !TryParseStatus(m.Groups["status"].Value, out var status)) return false; + line = new BountyHereLine(m.Groups["scope"].Success ? m.Groups["scope"].Value.Trim() : string.Empty, + ParseLong(m.Groups["amount"].Value), m.Groups["item"].Value.Trim(), status); + return true; + } + + /// Parses one status phrase (without the trailing period). + public static bool TryParseStatus(string text, out BountyStatusInfo status) + { + status = default; + string t = (text ?? string.Empty).Trim().TrimEnd('.'); + var m = Counting.Match(t); + if (m.Success) + { + status = new BountyStatusInfo(BountyStatus.Counting, ToInt(m.Groups["k"].Value), ToInt(m.Groups["n"].Value), 0, 0, 0); + return true; + } + m = Cooldown.Match(t); + if (m.Success) + { + status = new BountyStatusInfo(BountyStatus.Cooldown, 0, ToInt(m.Groups["n"].Value), + ParseWaitSeconds(m.Groups["wait"].Value), 0, 0); + return true; + } + m = Qb.Match(t); + if (m.Success) + { + status = new BountyStatusInfo(BountyStatus.NeedsQb, 0, 0, 0, + ParseLong(m.Groups["qb"].Value), ParseLong(m.Groups["have"].Value)); + return true; + } + return false; + } + + /// "2 min 30 sec" → 150, "1 hr 15 sec" → 3615. 0 when nothing parses. + public static int ParseWaitSeconds(string text) + { + long total = 0; + foreach (Match m in WaitPart.Matches(text ?? string.Empty)) + { + long v = ParseLong(m.Groups["v"].Value); + total += m.Groups["u"].Value switch { "hr" => v * 3600, "min" => v * 60, _ => v }; + } + return (int)Math.Min(total, int.MaxValue); + } + + /// + /// Recognises a bounty chat event (award, unlock, next cooldown, held reward). Item and + /// KillsRequired are filled when the line names them; WaitSeconds for "Next bounty unlocks in". + /// + public static bool TryParseEvent(string text, out BountyEventKind kind, out string item, out int killsRequired, out int waitSeconds) + { + kind = BountyEventKind.Held; + item = string.Empty; + killsRequired = 0; + waitSeconds = 0; + string t = (text ?? string.Empty).Trim(); + if (t.Length == 0) return false; + + Match m; + if ((m = EvUnlocked.Match(t)).Success) + { + kind = BountyEventKind.Unlocked; + item = m.Groups["item"].Value.Trim(); + killsRequired = ToInt(m.Groups["n"].Value); + return true; + } + if ((m = EvComplete.Match(t)).Success) + { + kind = BountyEventKind.Complete; + item = m.Groups["item"].Value.Trim(); + return true; + } + if ((m = EvNextWait.Match(t)).Success) + { + kind = BountyEventKind.NextCooldown; + waitSeconds = ParseWaitSeconds(m.Groups["wait"].Value); + killsRequired = ToInt(m.Groups["n"].Value); + return true; + } + if ((m = EvNextReady.Match(t)).Success) + { + kind = BountyEventKind.NextReady; + killsRequired = ToInt(m.Groups["n"].Value); + return true; + } + // Held-reward notices; the "/bounty" and "/bounty list" status lines also start with "Bounty: ". + if (t.StartsWith("Bounty: +", StringComparison.Ordinal) + || t.StartsWith("Bounty: Your inventory is full", StringComparison.OrdinalIgnoreCase)) + { + kind = BountyEventKind.Held; + return true; + } + return false; + } + + /// Key that identifies one reward of one area across refreshes. + public static string Key(string where, long amount, string item, int killsRequired) + => $"{where}|{amount}|{item}|{killsRequired}".ToLowerInvariant(); + + /// "1 hr 5 min", "45 sec", "2 days 3 hr". Negative spans read as 0 sec. + public static string Duration(TimeSpan span) + { + long s = Math.Max(0, (long)span.TotalSeconds); + if (s >= 86400) return $"{s / 86400} day{(s / 86400 == 1 ? "" : "s")}" + (s % 86400 >= 3600 ? $" {s % 86400 / 3600} hr" : ""); + if (s >= 3600) return $"{s / 3600} hr" + (s % 3600 >= 60 ? $" {s % 3600 / 60} min" : ""); + if (s >= 60) return $"{s / 60} min" + (s % 60 > 0 ? $" {s % 60} sec" : ""); + return $"{s} sec"; + } + + /// Digits with "," grouping removed; 0 when nothing parses. + internal static long ParseLong(string text) + { + string digits = (text ?? string.Empty).Replace(",", string.Empty).Trim(); + return long.TryParse(digits, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out long v) ? v : 0; + } + + private static int ToInt(string text) => (int)Math.Min(ParseLong(text), int.MaxValue); +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyTracker.cs b/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyTracker.cs new file mode 100644 index 0000000..8880ef2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyTracker.cs @@ -0,0 +1,714 @@ +// BountyTracker.cs - Every ACECustom bounty and this character's progress, for the engine's Bounties window. +// +// The server keeps the counts (PropertyString BountyProgress is server-only), so the tracker reads +// "/bounty list", which reports every active bounty on the server - wherever the player stands - +// with the player's kills, cooldown or QB requirement for each. The read is a quiet capture (the +// reply is eaten from chat) and runs only while the engine's Bounties window polls the export: +// * when the window opens (and the list is old or kills happened while it was closed), +// * a moment after each of this character's kills, +// * after a bounty chat event ("Bounty complete!", "Bounty unlocked:", "Next bounty ..."), +// * every PeriodicRefreshMinutes as a backstop, and on Refresh / "/ilt bounty refresh". +// Every read, whatever asked for it, waits for MinRefreshSeconds (at least 5 s) since the last +// one, and none is sent while the window is closed (RynthILT review, 2026-10-09). +// Lines the player prints themselves ("/bounty list", "/bounty") update the list too, and are +// never eaten: a /bounty the player types (NoteTypedCommand) turns the capture it overlaps into +// a shown one, and a typed "/bounty list" stands in for the tracker's next read. +// Cooldowns count down locally from the read time; when one ends the bounty shows 0 of N kills, +// which is what the server says too (an award resets the count before the cooldown starts). +// +// Everything runs on the plugin's game thread: OnTick, chat, kills and the engine's export polls. +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RynthCore.Plugin.RynthILT.Bounty; + +/// Persisted per character (bounties.json): the window's options and the last list read. +internal sealed class BountyState +{ + public bool RefreshOnKills = true; + public int MinRefreshSeconds = 10; + public int PeriodicRefreshMinutes = 5; + public bool HideQbLocked; + public bool SortByProgress; + public List Entries = new(); + public DateTime ListedUtc; + public bool NoneAnywhere; + public string LastEvent = string.Empty; + public DateTime LastEventUtc; +} + +/// One reward of one bounty area and where this character stands on it. +internal sealed class BountyEntry +{ + public string Where = string.Empty; + public long Amount; + public string Item = string.Empty; + public int KillsRequired; + public int CooldownSeconds; + /// A value. + public int Status; + public int Kills; + public DateTime UnlockAtUtc; + public long QbRequired; + public long QbHave; + /// Last time the kills went up or an award reset them (row highlight). + public DateTime ChangedUtc; +} + +/// +/// RynthPluginGetBountiesJson payload. Mirrored by RynthCore.Engine UI/Data/BountiesSnapshotJson.cs; +/// either side may add fields (unknown ones are skipped, missing ones keep their defaults). +/// +internal sealed class BountyBridgePayload +{ + [JsonPropertyName("unsupported")] public bool Unsupported; + [JsonPropertyName("reading")] public bool Reading; + [JsonPropertyName("status")] public string Status = string.Empty; + /// Seconds since the last list read; -1 = never. + [JsonPropertyName("listedAgoSec")] public int ListedAgoSec = -1; + [JsonPropertyName("noneAnywhere")] public bool NoneAnywhere; + [JsonPropertyName("lastEvent")] public string LastEvent = string.Empty; + [JsonPropertyName("lastEventAgoSec")] public int LastEventAgoSec = -1; + [JsonPropertyName("refreshOnKills")] public bool RefreshOnKills; + [JsonPropertyName("minRefreshSeconds")] public int MinRefreshSeconds; + [JsonPropertyName("periodicRefreshMinutes")] public int PeriodicRefreshMinutes; + [JsonPropertyName("hideQbLocked")] public bool HideQbLocked; + [JsonPropertyName("sortByProgress")] public bool SortByProgress; + /// Rows not shown because of HideQbLocked. + [JsonPropertyName("hiddenCount")] public int HiddenCount; + [JsonPropertyName("rows")] public List Rows = new(); +} + +/// One row of , with the status as of the poll. +internal sealed class BountyRow +{ + [JsonPropertyName("where")] public string Where = string.Empty; + [JsonPropertyName("amount")] public long Amount; + [JsonPropertyName("item")] public string Item = string.Empty; + [JsonPropertyName("killsRequired")] public int KillsRequired; + [JsonPropertyName("cooldownSeconds")] public int CooldownSeconds; + /// A value; an ended cooldown is already Counting. + [JsonPropertyName("status")] public int Status; + [JsonPropertyName("kills")] public int Kills; + [JsonPropertyName("unlockInSec")] public int UnlockInSec; + [JsonPropertyName("qbRequired")] public long QbRequired; + [JsonPropertyName("qbHave")] public long QbHave; + /// Kills went up (or an award reset them) in the last 15 seconds. + [JsonPropertyName("changed")] public bool Changed; +} + +internal sealed class BountyTracker +{ + /// The capture command; "/bounty all" is the same list. + public const string ListCommand = "/bounty list"; + /// Lowest allowed MinRefreshSeconds (the server is asked at most this often after kills). + public const int MinRefreshFloorSeconds = 5; + public const int MinRefreshCeilingSeconds = 300; + public const int PeriodicCeilingMinutes = 60; + public const string FileName = "bounties.json"; + + /// Wait after a kill so a burst of kills (and the server's own award lines) lands in one read. + private const long KillDebounceMs = 2000; + /// Wait after a bounty chat event before re-reading. + private const long EventDebounceMs = 1500; + /// The window counts as open while the engine polled the export this recently (it polls every second). + private const long WindowPollWindowMs = 3000; + /// A capture with no reply line by then is abandoned. + private const long FirstLineTimeoutMs = 10000; + /// A capture whose footer never came ends this long after its last line. + private const long IdleEndMs = 1500; + /// The engine may pass our own /bounty list back through the chat bar hook this soon after sending it. + private const long OwnEchoMs = 2000; + /// Longer chat lines are never parsed (no bounty line is near this; bounds the regex work). + private const int MaxLineLength = 512; + private const long SaveDebounceMs = 5000; + /// A list older than this is re-read when the window opens. + private static readonly TimeSpan OpenRefreshAge = TimeSpan.FromSeconds(30); + /// How long a row stays highlighted after its kills went up. + private static readonly TimeSpan ChangedHighlight = TimeSpan.FromSeconds(15); + + private readonly Action _send; + private readonly Action _chat; + private readonly Action _log; + private readonly string _filePath; + private readonly Func _clock; + private BountyState _s; + + // Scheduling. + private long _dueAtMs; // 0 = no read scheduled + private long _lastSentMs; // 0 = never this session + private long _lastPollMs; // last engine poll of the export; 0 = never + private bool _wasOpen; + private bool _stale; // kills or bounty events happened while the window was closed + + // The quiet "/bounty list" capture. + private bool _capActive; + private bool _capShown; // the player asked too (NoteTypedCommand): parse, never eat + private bool _expectEcho; // our /bounty list may come back through the chat bar hook + private long _capSentMs; + private long _capLastLineMs; // 0 = no reply line yet + private readonly List _capLines = new(); + + private bool _unsupported; + private string _status = string.Empty; + private bool _dirty; + private long _lastSaveMs; + + /// Sends a chat command to the server (Host.InvokeChatParser). + /// Prints a line to the player's chat window. + /// Writes to the RynthCore log. + /// bounties.json in the character folder; empty = not persisted. + /// Milliseconds clock; Environment.TickCount64 unless a test supplies one. + public BountyTracker(Action send, Action chat, Action log, string filePath, Func? clock = null) + { + _send = send; + _chat = chat; + _log = log; + _filePath = filePath ?? string.Empty; + _clock = clock ?? (() => Environment.TickCount64); + _s = Load(); + } + + private long NowMs => _clock(); + + /// The persisted state (host tests). + internal BountyState State => _s; + + /// True once the server answered "Unknown command: bounty" (no bounty system on this server). + public bool Unsupported => _unsupported; + + /// True while a "/bounty list" reply is being captured. + public bool Reading => _capActive; + + /// True while the engine's Bounties window is polling the export. + public bool WindowOpen => _lastPollMs != 0 && NowMs - _lastPollMs < WindowPollWindowMs; + + // ── Scheduling ────────────────────────────────────────────────────────── + + /// + /// Schedules a "/bounty list" read; the earliest pending request wins. Every read waits for + /// MinRefreshSeconds since the last one; false (a manual + /// refresh) waits only for the MinRefreshFloorSeconds floor. + /// + private void Schedule(long nowMs, long delayMs, bool respectMinInterval) + { + long due = nowMs + delayMs; + if (_lastSentMs != 0) + due = Math.Max(due, _lastSentMs + (respectMinInterval ? _s.MinRefreshSeconds : MinRefreshFloorSeconds) * 1000L); + if (_dueAtMs == 0 || due < _dueAtMs) _dueAtMs = due; + } + + /// + /// Manual refresh (window button, "/ilt bounty refresh"): retries an unsupported server and + /// reads as soon as the 5 s floor since the last read allows. Never sends with the window + /// closed: the next open reads instead. + /// + public string RequestRefresh() + { + _unsupported = false; + if (!WindowOpen) + { + _stale = true; + return "The list is read while the Bounties window is open (the ILT button, or /rc bounties)."; + } + long now = NowMs; + Schedule(now, 0, respectMinInterval: false); + return "Reading /bounty list..."; + } + + /// One of this character's kills (RynthILTPlugin.OnKillNotification). + public void OnKill() + { + if (!_s.RefreshOnKills || _unsupported) return; + if (WindowOpen) Schedule(NowMs, KillDebounceMs, respectMinInterval: true); + else _stale = true; + } + + private void Send(long nowMs) + { + if (_capActive) { _dueAtMs = 0; return; } + // The invariants, whatever scheduled this: the window is open, and the last read was at + // least MinRefreshFloorSeconds ago (else the read waits until then). + if (!WindowOpen) { _dueAtMs = 0; return; } + if (_lastSentMs != 0 && nowMs - _lastSentMs < MinRefreshFloorSeconds * 1000L) + { + _dueAtMs = _lastSentMs + MinRefreshFloorSeconds * 1000L; + return; + } + _dueAtMs = 0; + _lastSentMs = nowMs; + StartCapture(nowMs, shown: false); + _expectEcho = true; + try { _send(ListCommand); } + catch (Exception ex) + { + _capActive = false; + _expectEcho = false; + _status = "could not send /bounty list"; + _log($"[RynthILT] Bounties: sending {ListCommand} failed: {ex.Message}"); + } + } + + private void StartCapture(long nowMs, bool shown) + { + _capActive = true; + _capShown = shown; + _capSentMs = nowMs; + _capLastLineMs = 0; + _capLines.Clear(); + } + + /// + /// A "/bounty ..." the player typed (the plugin's OnChatBarEnter, passed on on the pump). + /// Its reply is never eaten: an overlapping capture of ours becomes a shown one, and a typed + /// "/bounty list" (or "/bounty all") starts a shown capture that counts as the next read, so + /// the tracker doesn't send its own on top. Our own command coming back through the chat + /// bar hook right after we sent it is recognised and ignored. + /// + public void NoteTypedCommand(string text) + { + string t = (text ?? string.Empty).Trim(); + long now = NowMs; + if (_expectEcho && now - _capSentMs <= OwnEchoMs && string.Equals(t, ListCommand, StringComparison.OrdinalIgnoreCase)) + { + _expectEcho = false; + return; + } + _expectEcho = false; + if (_capActive) { _capShown = true; return; } + if (!IsListCommand(t)) return; + _lastSentMs = now; + _dueAtMs = 0; + StartCapture(now, shown: true); + } + + /// "/bounty list" or "/bounty all" (or with ACE's '@' command prefix). + internal static bool IsListCommand(string text) + { + string[] parts = (text ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); + return parts.Length == 2 + && (parts[0].Equals("/bounty", StringComparison.OrdinalIgnoreCase) || parts[0].Equals("@bounty", StringComparison.OrdinalIgnoreCase)) + && (parts[1].Equals("list", StringComparison.OrdinalIgnoreCase) || parts[1].Equals("all", StringComparison.OrdinalIgnoreCase)); + } + + /// True for a chat-bar line that is a /bounty command (what the plugin passes to NoteTypedCommand). + public static bool IsBountyCommand(string? text) + { + string t = (text ?? string.Empty).TrimStart(); + if (!t.StartsWith("/bounty", StringComparison.OrdinalIgnoreCase) && !t.StartsWith("@bounty", StringComparison.OrdinalIgnoreCase)) + return false; + return t.Length == 7 || t[7] == ' '; // "/bounty" or "/bounty ...", not "/bountyhunter" + } + + public void Tick() + { + long now = NowMs; + if (_capActive) + { + if (_capLastLineMs == 0 && now - _capSentMs >= FirstLineTimeoutMs) + { + _capActive = false; + _expectEcho = false; + if (!_capShown) _status = "no reply to /bounty list"; + } + else if (_capLastLineMs != 0 && now - _capLastLineMs >= IdleEndMs) + { + FinishCapture(terminator: null); + } + } + + if (_dirty && now - _lastSaveMs >= SaveDebounceMs) Save(); + + bool open = WindowOpen; + if (!open) { _wasOpen = false; _dueAtMs = 0; return; } + + if (!_wasOpen) + { + _wasOpen = true; + if (_stale || _lastSentMs == 0 || DateTime.UtcNow - _s.ListedUtc > OpenRefreshAge) + Schedule(now, 0, respectMinInterval: true); + _stale = false; + } + + if (_s.PeriodicRefreshMinutes > 0 && _lastSentMs != 0 && now - _lastSentMs >= _s.PeriodicRefreshMinutes * 60_000L) + Schedule(now, 0, respectMinInterval: true); + + if (_dueAtMs != 0 && now >= _dueAtMs && !_unsupported) Send(now); + } + + private void FinishCapture(string? terminator) + { + _capActive = false; + _expectEcho = false; + bool complete = terminator != null; + bool none = complete && BountyParse.IsNoBountiesAnywhere(terminator!); + ApplyList(_capLines, complete, none, DateTime.UtcNow); + _status = complete ? string.Empty : "partial reply"; + _capLines.Clear(); + } + + // ── Chat ──────────────────────────────────────────────────────────────── + + /// + /// One chat line. Returns true when it belongs to our own "/bounty list" read and should be + /// eaten; everything else (the player's own bounty output, award lines) stays in chat. + /// + public bool OnChat(string text) + { + string t = (text ?? string.Empty).Trim(); + if (t.Length == 0 || t.Length > MaxLineLength) return false; + long now = NowMs; + + if (_capActive) + { + // A shown capture (the player asked too) parses the same lines but eats none. + bool eat = !_capShown; + if (BountyParse.IsUnknownCommand(t)) + { + _capActive = false; + _expectEcho = false; + _capLines.Clear(); + _unsupported = true; + _status = "this server has no /bounty command"; + _log("[RynthILT] Bounties: server has no /bounty command; automatic reads stopped."); + return eat; + } + if (t == BountyParse.ListHeader) { _capLastLineMs = now; return eat; } + if (BountyParse.TryParseListLine(t, out var captured)) { _capLines.Add(captured); _capLastLineMs = now; return eat; } + if (BountyParse.IsListTerminator(t)) { FinishCapture(t); return eat; } + } + + if (BountyParse.TryParseListLine(t, out var listLine)) + { + ApplyList(new[] { listLine }, complete: false, noneAnywhere: false, DateTime.UtcNow); + return false; + } + if (BountyParse.TryParseHereLine(t, out var here)) + { + ApplyHere(here, DateTime.UtcNow); + return false; + } + + if (BountyParse.TryParseEvent(t, out var kind, out _, out _, out _)) + { + _s.LastEvent = t; + _s.LastEventUtc = DateTime.UtcNow; + _dirty = true; + if (kind != BountyEventKind.Held) + { + // Awards can come every kill (a 1-kill bounty with no cooldown): the interval holds. + if (WindowOpen) Schedule(now, EventDebounceMs, respectMinInterval: true); + else _stale = true; + } + } + return false; + } + + // ── Applying server output (internal for the host tests) ──────────────── + + /// + /// Applies parsed "/bounty list" lines. A complete reply (footer seen) replaces the list in + /// server order; a partial one only updates or appends the rewards it names. + /// + internal void ApplyList(IReadOnlyList lines, bool complete, bool noneAnywhere, DateTime nowUtc) + { + var old = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var e in _s.Entries) + old[BountyParse.Key(e.Where, e.Amount, e.Item, e.KillsRequired)] = e; + + var fresh = new List(lines.Count); + foreach (var l in lines) + { + old.TryGetValue(BountyParse.Key(l.Where, l.Amount, l.Item, l.KillsRequired), out var prev); + var e = new BountyEntry + { + Where = l.Where, + Amount = l.Amount, + Item = l.Item, + KillsRequired = l.KillsRequired, + CooldownSeconds = l.CooldownSeconds, + ChangedUtc = prev?.ChangedUtc ?? default, + }; + ApplyStatus(e, l.Status, prev, nowUtc); + fresh.Add(e); + } + + if (complete) + { + _s.Entries = fresh; + } + else + { + foreach (var e in fresh) + { + string key = BountyParse.Key(e.Where, e.Amount, e.Item, e.KillsRequired); + int i = _s.Entries.FindIndex(x => string.Equals(BountyParse.Key(x.Where, x.Amount, x.Item, x.KillsRequired), + key, StringComparison.OrdinalIgnoreCase)); + if (i >= 0) _s.Entries[i] = e; else _s.Entries.Add(e); + } + } + if (complete || lines.Count > 0) _s.ListedUtc = nowUtc; + if (complete) _s.NoneAnywhere = noneAnywhere; + _dirty = true; + } + + /// + /// Applies a "/bounty" (where you stand) line to the one listed reward it can only mean. + /// Returns false when no reward or more than one matches. + /// + internal bool ApplyHere(BountyHereLine h, DateTime nowUtc) + { + BountyEntry? match = null; + foreach (var e in _s.Entries) + { + if (e.Amount != h.Amount || !string.Equals(e.Item, h.Item, StringComparison.OrdinalIgnoreCase)) continue; + if (h.Status.KillsRequired > 0 && e.KillsRequired != h.Status.KillsRequired) continue; + bool allZones = string.Equals(e.Where, "All zones", StringComparison.OrdinalIgnoreCase); + bool scopeOk = h.Scope.Length == 0 ? !allZones + : h.Scope.Equals("all zones", StringComparison.OrdinalIgnoreCase) ? allZones + : string.Equals(e.Where, h.Scope, StringComparison.OrdinalIgnoreCase); + if (!scopeOk) continue; + if (match != null) return false; // ambiguous: two areas pay the same reward + match = e; + } + if (match == null) return false; + + var prev = new BountyEntry { Status = match.Status, Kills = match.Kills }; + ApplyStatus(match, h.Status, prev, nowUtc); + _dirty = true; + return true; + } + + /// Copies a parsed status onto and stamps ChangedUtc when kills went up or an award reset them. + private static void ApplyStatus(BountyEntry e, BountyStatusInfo st, BountyEntry? prev, DateTime nowUtc) + { + e.Status = (int)st.Status; + e.Kills = st.Status == BountyStatus.Counting ? st.Kills : 0; + e.UnlockAtUtc = st.Status == BountyStatus.Cooldown ? nowUtc.AddSeconds(st.WaitSeconds) : default; + e.QbRequired = st.QbRequired; + e.QbHave = st.QbHave; + if (prev == null) return; + bool wasCounting = prev.Status == (int)BountyStatus.Counting; + bool gained = wasCounting && st.Status == BountyStatus.Counting && st.Kills > prev.Kills; + bool awarded = wasCounting && prev.Kills > 0 + && (st.Status == BountyStatus.Cooldown || (st.Status == BountyStatus.Counting && st.Kills < prev.Kills)); + if (gained || awarded) e.ChangedUtc = nowUtc; + } + + /// The status to show now: a cooldown that has ended is "0 of N kills". + internal static (BountyStatus Status, int Kills) Effective(BountyEntry e, DateTime nowUtc) + { + var st = (BountyStatus)e.Status; + if (st == BountyStatus.Cooldown && nowUtc >= e.UnlockAtUtc) return (BountyStatus.Counting, 0); + return (st, st == BountyStatus.Counting ? e.Kills : 0); + } + + /// "Closest first" order: counting by fraction left, then cooldowns by time left, then QB-locked. + private static double SortKey(BountyEntry e, DateTime now) + { + var (st, kills) = Effective(e, now); + return st switch + { + BountyStatus.Counting => e.KillsRequired > 0 ? 1.0 - kills / (double)e.KillsRequired : 1.0, + BountyStatus.Cooldown => 2.0 + Math.Min((e.UnlockAtUtc - now).TotalSeconds, 1e9) / 1e9, + _ => 4.0, + }; + } + + // ── Engine bridge ─────────────────────────────────────────────────────── + + /// RynthPluginGetBountiesJson. Each call also marks the window open for the read schedule. + public string BuildJson() + { + _lastPollMs = NowMs; + var now = DateTime.UtcNow; + var p = new BountyBridgePayload + { + Unsupported = _unsupported, + Reading = _capActive, + Status = _status, + ListedAgoSec = _s.ListedUtc == default ? -1 : AgoSeconds(now - _s.ListedUtc), + NoneAnywhere = _s.NoneAnywhere, + LastEvent = _s.LastEvent, + LastEventAgoSec = _s.LastEventUtc == default ? -1 : AgoSeconds(now - _s.LastEventUtc), + RefreshOnKills = _s.RefreshOnKills, + MinRefreshSeconds = _s.MinRefreshSeconds, + PeriodicRefreshMinutes = _s.PeriodicRefreshMinutes, + HideQbLocked = _s.HideQbLocked, + SortByProgress = _s.SortByProgress, + }; + + IEnumerable shown = _s.Entries; + if (_s.HideQbLocked) + { + p.HiddenCount = _s.Entries.Count(e => e.Status == (int)BountyStatus.NeedsQb); + shown = shown.Where(e => e.Status != (int)BountyStatus.NeedsQb); + } + if (_s.SortByProgress) shown = shown.OrderBy(e => SortKey(e, now)); + foreach (var e in shown) + { + var (st, kills) = Effective(e, now); + p.Rows.Add(new BountyRow + { + Where = e.Where, + Amount = e.Amount, + Item = e.Item, + KillsRequired = e.KillsRequired, + CooldownSeconds = e.CooldownSeconds, + Status = (int)st, + Kills = kills, + UnlockInSec = st == BountyStatus.Cooldown ? AgoSeconds(e.UnlockAtUtc - now) : 0, + QbRequired = e.QbRequired, + QbHave = e.QbHave, + Changed = e.ChangedUtc != default && now - e.ChangedUtc < ChangedHighlight, + }); + } + return JsonSerializer.Serialize(p, RynthILTJsonContext.Default.BountyBridgePayload); + } + + private static int AgoSeconds(TimeSpan span) => (int)Math.Clamp(span.TotalSeconds, 0, int.MaxValue); + + /// + /// RynthPluginBountyCommand: "refresh", or "set {option} {value}" with option one of + /// refreshonkills, minrefreshseconds, periodicminutes, hideqblocked, sortbyprogress. + /// + public string Command(string text) + { + string[] parts = (text ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 0) return string.Empty; + switch (parts[0].ToLowerInvariant()) + { + case "refresh": + case "read": + return RequestRefresh(); + case "set" when parts.Length >= 3: + return SetOption(parts[1], parts[2]); + default: + return $"unknown bounty command '{text}'"; + } + } + + private string SetOption(string name, string value) + { + bool on = value is "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase) + || value.Equals("on", StringComparison.OrdinalIgnoreCase); + int.TryParse(value, out int n); + switch (name.ToLowerInvariant()) + { + case "refreshonkills": _s.RefreshOnKills = on; break; + case "minrefreshseconds": _s.MinRefreshSeconds = Math.Clamp(n, MinRefreshFloorSeconds, MinRefreshCeilingSeconds); break; + case "periodicminutes": _s.PeriodicRefreshMinutes = Math.Clamp(n, 0, PeriodicCeilingMinutes); break; + case "hideqblocked": _s.HideQbLocked = on; break; + case "sortbyprogress": _s.SortByProgress = on; break; + default: return $"unknown bounty option '{name}'"; + } + _dirty = true; + return string.Empty; + } + + // ── Chat command ──────────────────────────────────────────────────────── + + /// "/ilt bounty [refresh|list]". + public void HandleChatCommand(string[] parts) + { + string verb = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "list"; + switch (verb) + { + case "refresh": + case "read": + _chat("[Bounties] " + RequestRefresh()); + break; + case "list": + case "print": + case "show": + PrintList(); + _chat("[Bounties] The Bounties window: the ILT button on the RynthCore bar, or /rc bounties."); + break; + default: + _chat("[Bounties] /ilt bounty [list|refresh] - list the tracked bounties, or re-read /bounty list (while the window is open)."); + break; + } + } + + /// One-line chat text for an entry. + internal static string Describe(BountyEntry e, DateTime nowUtc) + { + var (st, kills) = Effective(e, nowUtc); + string reward = $"{e.Amount:N0} {e.Item}"; + return st switch + { + BountyStatus.Counting => $"{e.Where}: {kills:N0}/{e.KillsRequired:N0} kills -> {reward}", + BountyStatus.Cooldown => $"{e.Where}: unlocks in {BountyParse.Duration(e.UnlockAtUtc - nowUtc)}, then {e.KillsRequired:N0} kills -> {reward}", + _ => $"{e.Where}: needs {e.QbRequired:N0} QB (you have {e.QbHave:N0}) -> {reward}", + }; + } + + /// "/ilt bounty list": the tracked bounties in chat. + public void PrintList() + { + if (_unsupported) { _chat("[Bounties] This server has no /bounty command."); return; } + if (_s.Entries.Count == 0) + { + _chat(_s.NoneAnywhere ? "[Bounties] No bounties are active anywhere right now." + : "[Bounties] Nothing read yet. Open the Bounties window (the ILT button, or /rc bounties)."); + return; + } + var now = DateTime.UtcNow; + string age = _s.ListedUtc == default ? "never" : BountyParse.Duration(now - _s.ListedUtc) + " ago"; + _chat($"[Bounties] {_s.Entries.Count} bounty reward(s), read {age}:"); + foreach (var e in _s.Entries) _chat("[Bounties] " + Describe(e, now)); + } + + // ── Persistence ───────────────────────────────────────────────────────── + + private BountyState Load() + { + var s = new BountyState(); + try + { + if (_filePath.Length > 0 && File.Exists(_filePath)) + s = JsonSerializer.Deserialize(File.ReadAllText(_filePath), RynthILTJsonContext.Default.BountyState) ?? new BountyState(); + } + catch (Exception ex) + { + _log($"[RynthILT] Bounties: {_filePath} unreadable, starting empty: {ex.Message}"); + s = new BountyState(); + } + s.Entries ??= new List(); + s.Entries.RemoveAll(e => e == null); + s.LastEvent ??= string.Empty; + s.MinRefreshSeconds = Math.Clamp(s.MinRefreshSeconds, MinRefreshFloorSeconds, MinRefreshCeilingSeconds); + s.PeriodicRefreshMinutes = Math.Clamp(s.PeriodicRefreshMinutes, 0, PeriodicCeilingMinutes); + return s; + } + + /// Writes bounties.json when something changed (also called at logout). + public void Save() + { + _lastSaveMs = NowMs; + if (!_dirty || _filePath.Length == 0) { _dirty = false; return; } + _dirty = false; + string json; + try { json = JsonSerializer.Serialize(_s, RynthILTJsonContext.Default.BountyState); } + catch (Exception ex) + { + _log($"[RynthILT] Bounties: saving {_filePath} failed: {ex.Message}"); + return; + } + // A failed write is said in chat once per folder (on ILT) and logged; it stays dirty so the + // next debounced save tries again. + if (!RynthCore.Plugin.Shared.DataWriteGuard.TrySave("the bounty list", _filePath, () => + { + string? dir = Path.GetDirectoryName(_filePath); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + string tmp = _filePath + ".tmp"; + File.WriteAllText(tmp, json); + File.Move(tmp, _filePath, overwrite: true); + })) + _dirty = true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs new file mode 100644 index 0000000..c59ac1f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs @@ -0,0 +1,173 @@ +// DataInterface.cs - RynthILT's side of the "RynthILT.Data" interface (Plugins/Shared/RynthIltDataApi.cs): +// the charms list and the bank balances (every character RynthILT has seen on this server) the +// Mini Remote's Charms and Banking tabs show, for other plugins to draw, with the charm Toggle and +// the bank verbs they send back; since version 2 also the pet breeding tracker's JSON and verbs; +// since version 3 the Temple guardians' JSON and verbs. (RynthOracle and RynthInventory drew them +// until 2026-10-21; those screens are RynthILT's own now, so no RynthSuite plugin reads this table.) +// +// The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never +// unloaded); after Release() it reports Version 0 and every function answers 0. Before login there +// is no controller: the JSON getters answer 0 (nothing to report) and the actions are refused. +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT; + +internal static unsafe class DataInterface +{ + /// Longest bank / breeding verb line taken (a transfer with a long character name fits easily). + private const int MaxVerbBytes = 256; + + private static RynthIltDataApiV1* _table; + private static volatile bool _released; + + /// The table for (, ), or 0 when it isn't ours. + public static IntPtr Query(string iface, uint version) + { + if (iface != RynthIltDataApiV1.InterfaceName || version < 1 || version > RynthIltDataApiV1.InterfaceVersion || _released) + return IntPtr.Zero; + if (_table == null) + { + var t = (RynthIltDataApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltDataApiV1)); + t->StructSize = (uint)sizeof(RynthIltDataApiV1); + t->GetCharmsJson = &GetCharmsJson; + t->GetBankJson = &GetBankJson; + t->ToggleCharm = &ToggleCharm; + t->BankCommand = &BankCommand; + t->GetPetBreedingJson = &GetPetBreedingJson; + t->PetBreedingCommand = &PetBreedingCommand; + t->GetGuardianJson = &GetGuardianJson; + t->GuardianCommand = &GuardianCommand; + t->Version = RynthIltDataApiV1.InterfaceVersion; + _table = t; + } + return (IntPtr)_table; + } + + /// Plugin shutdown: readers see Version 0 and re-query; every function answers 0. + public static void Release() + { + _released = true; + if (_table != null) _table->Version = 0; + } + + private static IltHubController? Hub => _released ? null : PluginExports.Runtime.Plugin?.Hub; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetCharmsJson(byte* buffer, int capacity) + { + try + { + string? json = Hub?.CharmsJson; + return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity); + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetBankJson(byte* buffer, int capacity) + { + try + { + string? json = Hub?.BankJson; + return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity); + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int ToggleCharm(uint objectId) + { + try + { + IltHubController? hub = Hub; + if (hub == null || objectId == 0) return 0; + hub.RequestCharmToggle(objectId); + return 1; + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int BankCommand(byte* utf8) + { + try + { + IltHubController? hub = Hub; + if (hub == null) return 0; + string? line = ReadVerb(utf8); + if (line == null) return 0; + hub.RequestBankVerb(line); + return 1; + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetPetBreedingJson(byte* buffer, int capacity) + { + try + { + string? json = Hub?.PetBreedingJson; + return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity); + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int PetBreedingCommand(byte* utf8) + { + try + { + IltHubController? hub = Hub; + if (hub == null) return 0; + string? line = ReadVerb(utf8); + if (line == null) return 0; + hub.RequestBreedingVerb(line); + return 1; + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetGuardianJson(byte* buffer, int capacity) + { + try + { + string? json = Hub?.GuardianJson; + return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity); + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GuardianCommand(byte* utf8) + { + try + { + IltHubController? hub = Hub; + if (hub == null) return 0; + string? line = ReadVerb(utf8); + if (line == null) return 0; + hub.RequestGuardianVerb(line); + return 1; + } + catch { return 0; } + } + + /// A reader's verb line, or null when it is empty, too long or not plain ASCII (no control characters reach a chat command). + private static string? ReadVerb(byte* utf8) + { + if (utf8 == null) return null; + int len = 0; + while (len < MaxVerbBytes && utf8[len] != 0) len++; + if (len == 0 || len >= MaxVerbBytes) return null; + string line = System.Text.Encoding.UTF8.GetString(utf8, len); + foreach (char c in line) + if (c < 0x20 || c > 0x7E) return null; + return line; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltAttributeRaiser.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltAttributeRaiser.cs new file mode 100644 index 0000000..23ac250 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltAttributeRaiser.cs @@ -0,0 +1,638 @@ +// IltAttributeRaiser.cs — Infinite attributes: spend unassigned XP with the server's /attr. +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// ACECustom (Infinite Leaftide) lets attributes and vitals go past the retail cap, so the +// client's XP tables stop applying. The server is the only source of truth: +// "/xp all" → "[XP] Your XP cost for next 1 Strength level is: 1,234" per stat +// "/attr " → "[ATTR] Strength attribute raised by 1, costing 1,234!" +// (Same commands UB's Leaftide XP Calculator drives; it raises one level at a time and +// re-reads the costs after each confirmation, which is what this does too.) +// +// Raise now / auto-raise run one loop: read costs → pick a stat → /attr 1 → wait for +// the [ATTR] reply → read costs again → ... until nothing ticked is affordable, a reply is +// not a success, or MaxRaisesPerRun. Only the ticked stats are ever spent on, never below +// the reserve (AttrKeepXp). Which stat comes next depends on the raise mode: +// Priority the first ticked stat in the order that is affordable (fills the top stat) +// RoundRobin one level per ticked stat in order, then around again +// Cheapest the ticked stat with the lowest next-level cost +// Manual +1 / +10 buttons send "/attr N" straight to the server (its reply shows in chat) +// once the known (+1) or projected (+10, 7.7% per level as in UB) cost fits the unassigned XP. +// +// Gated on ServerFeatureGate (via IltServerOptions.IsIltLikeWorld) and on the server not +// reporting /xp off. Everything here runs on the plugin pump thread. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltAttributeRaiser +{ + /// Raise modes (IltCharacterState.AttrRaiseMode). + public enum Mode { Priority = 0, RoundRobin = 1, Cheapest = 2 } + + /// /attr abbreviation, display name, vital? + public sealed record Stat(string Abbr, string Name, bool Vital); + + public static readonly Stat[] Stats = + { + new("str", "Strength", false), new("end", "Endurance", false), new("coo", "Coordination", false), + new("qui", "Quickness", false), new("foc", "Focus", false), new("sel", "Self", false), + new("hea", "Health", true), new("sta", "Stamina", true), new("man", "Mana", true), + }; + + /// UB's default priority (Coordination, Quickness, Strength, Endurance, Focus, Self, vitals). + public static readonly string[] DefaultOrder = { "coo", "qui", "str", "end", "foc", "sel", "hea", "sta", "man" }; + + public const int MaxRaisesPerRun = 200; + + /// + /// Per-level growth for projecting several levels from the one cost "/xp all" reports (UB's + /// Leaftide XP tab uses the same 7.7%). The server prices each level itself; this only labels + /// the +10 button and gates it on the XP you have. + /// + public const double ProjectedLevelGrowth = 0.077; + + private const long FirstAutoDelayMs = 30_000; // after login / arming, before the first auto run + private const int ReplyTimeoutMs = 8000; + /// A run with no reply/step for this long is ended (a lost callback must not wedge it). + private const long StallMs = 45_000; + + /// "Your base Strength is now 250!" / "Your base Maximum Health is now 900!" (older servers / UB wording). + private static readonly Regex BaseNow = new(@"Your base (?:Maximum )?(\w+) is now (\d+)!", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private readonly IltHubContext _ctx; + // Last known costs (display, and the passive chat reader). A run decides only from _runCosts: + // the costs in the "/xp all" reply read right before that step, never an older value. + private readonly Dictionary _cost = new(StringComparer.OrdinalIgnoreCase); + private Dictionary _runCosts = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _base = new(StringComparer.OrdinalIgnoreCase); + private long _costsAtMs; + private DateTime _costsAtLocal; + // Opening the Progression tab reads the costs once per login, like UB's XP tab does on load. + private bool _autoCostsTried; + + // Run state. _runId guards against a capture that completes after Stop / a newer run. + private enum Phase { Idle, ReadingCosts, Raising } + private Phase _phase; + private int _runId; + private bool _runAuto; + private int _runRaised; + private long _runSpent; + private readonly Dictionary _runGains = new(StringComparer.OrdinalIgnoreCase); + private int _rrNext; + private string _raisingAbbr = string.Empty; + private long _raisingCost; + + private long _lastProgressMs; + private long _nextAutoAtMs; + private volatile string _status = "Idle."; + private volatile string _lastRun = string.Empty; + + public IltAttributeRaiser(IltHubContext ctx) => _ctx = ctx; + + /// + /// True while another XP spender runs (IltProgression's spend-before-/enl loop sends /attr + /// outside the capture queue). Nothing here starts, by hand or on the timer, while it is. + /// + public Func? HoldOff { get; set; } + + private bool HeldOff + { + get { try { return HoldOff?.Invoke() == true; } catch { return false; } } + } + + private IltCharacterState C => _ctx.State.Character; + + public bool Running => _phase != Phase.Idle; + + // ── Order / selection helpers (also used by IltHubStore.Normalize) ───────── + + public static Stat? Find(string keyOrName) + { + if (string.IsNullOrWhiteSpace(keyOrName)) return null; + string k = keyOrName.Trim(); + foreach (var s in Stats) + if (s.Abbr.Equals(k, StringComparison.OrdinalIgnoreCase) || s.Name.Equals(k, StringComparison.OrdinalIgnoreCase)) + return s; + // Cost lines may say "MaxHealth" / "Maximum Health"; the reply may abbreviate. + string lower = k.ToLowerInvariant().Replace(" ", ""); + if (lower.StartsWith("maximum")) lower = lower.Substring(7); + else if (lower.StartsWith("max")) lower = lower.Substring(3); + foreach (var s in Stats) + if (s.Name.Equals(lower, StringComparison.OrdinalIgnoreCase) || lower.StartsWith(s.Abbr, StringComparison.Ordinal)) + return s; + return null; + } + + /// All nine abbreviations exactly once: saved order first, missing ones appended, junk dropped. + public static List RepairOrder(List? order) + { + var result = new List(); + foreach (string k in order ?? new List()) + { + Stat? s = Find(k); + if (s != null && !result.Contains(s.Abbr)) result.Add(s.Abbr); + } + foreach (string k in DefaultOrder) + if (!result.Contains(k)) result.Add(k); + return result; + } + + public static List RepairSelection(List? selection) + { + var result = new List(); + foreach (string k in selection ?? new List()) + { + Stat? s = Find(k); + if (s != null && !result.Contains(s.Abbr)) result.Add(s.Abbr); + } + return result; + } + + /// + /// Picks the next stat to raise. Pure (unit-testable): is the + /// priority order, the stats allowed, the + /// known next-level costs, what may be spent. Round robin starts at + /// and returns the index after the pick there. + /// + public static string? Pick(Mode mode, IReadOnlyList order, ICollection ticked, + IReadOnlyDictionary cost, long budget, ref int rrNext) + { + if (budget <= 0 || order.Count == 0) return null; + bool Affordable(string k) => ticked.Contains(k) && cost.TryGetValue(k, out long c) && c > 0 && c <= budget; + + switch (mode) + { + case Mode.RoundRobin: + for (int step = 0; step < order.Count; step++) + { + int i = ((rrNext % order.Count) + step) % order.Count; + if (!Affordable(order[i])) continue; + rrNext = i + 1; + return order[i]; + } + return null; + case Mode.Cheapest: + string? best = null; + long bestCost = long.MaxValue; + foreach (string k in order) // ties go to the higher-priority stat + { + if (!Affordable(k)) continue; + long c = cost[k]; + if (c < bestCost) { best = k; bestCost = c; } + } + return best; + default: + foreach (string k in order) + if (Affordable(k)) return k; + return null; + } + } + + // ── Gate ────────────────────────────────────────────────────────────────── + + /// Why the raiser can't run here, or null when it can. + public string? Blocker() + { + if (!_ctx.Options.IsIltLikeWorld) + return "Server features are off for this world (Settings > Misc > Server Features)."; + if (_ctx.Options.IsOff(IltFeature.Xp)) return "This server reports /xp as unavailable."; + if (!_ctx.Host.HasInvokeChatParser) return "This engine build can't send chat commands."; + return null; + } + + // ── Pump-thread lifecycle ───────────────────────────────────────────────── + + /// Tick. : another XP spender (auto-enlighten's loop) is running. + public void Tick(long nowMs, bool holdOff) + { + if (Running && nowMs - _lastProgressMs > StallMs) { Finish($"Stopped: no reply for {StallMs / 1000} s."); return; } + if (!C.AttrAutoRaise || Running || holdOff || HeldOff) return; + if (_nextAutoAtMs == 0) { _nextAutoAtMs = nowMs + FirstAutoDelayMs; return; } + if (nowMs < _nextAutoAtMs) return; + _nextAutoAtMs = nowMs + Math.Clamp(C.AttrAutoRaiseMinutes, 1, 1440) * 60_000L; + if (Blocker() != null || C.AttrRaiseStats.Count == 0) return; + if (_ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp) <= Math.Max(0, C.AttrKeepXp)) return; + Start(auto: true); + } + + /// Passive: keeps costs / base values current when the player runs the commands by hand. + public void OnChat(string text) + { + var cost = IltParse.XpCost.Match(text); + if (cost.Success) + { + Stat? s = Find(cost.Groups[1].Value); + if (s != null) { _cost[s.Abbr] = IltParse.ParseLeadingLong(cost.Groups[2].Value); MarkCostsRead(); } + return; + } + var now = BaseNow.Match(text); + if (now.Success) + { + Stat? s = Find(now.Groups[1].Value); + if (s != null && int.TryParse(now.Groups[2].Value, out int v)) _base[s.Abbr] = v; + } + } + + public void OnLogout() + { + _runId++; + _phase = Phase.Idle; + _cost.Clear(); + _runCosts.Clear(); + _base.Clear(); + _costsAtMs = 0; + _autoCostsTried = false; + _nextAutoAtMs = 0; + _status = "Idle."; + } + + // ── Runs ────────────────────────────────────────────────────────────────── + + /// Starts a spend run (manual "Raise now" or the auto timer). + public void Start(bool auto) + { + if (Running) return; + string? blocked = Blocker(); + if (blocked != null) { _status = blocked; return; } + if (HeldOff) { _status = "Auto-enlighten is spending XP right now; try again when it finishes."; return; } + if (C.AttrRaiseStats.Count == 0) { _status = "Tick at least one attribute or vital to raise."; return; } + + _runId++; + _runAuto = auto; + _runRaised = 0; + _runSpent = 0; + _runGains.Clear(); + _rrNext = 0; + _runCosts = new Dictionary(StringComparer.OrdinalIgnoreCase); + _lastProgressMs = IltHubContext.NowMs; + RynthLog.Trace(LogCat.IltProgression, $"attr raise run {_runId} start (auto={auto}, mode={(Mode)C.AttrRaiseMode}, keep={C.AttrKeepXp}, stats={string.Join(",", C.AttrRaiseStats)})"); + ReadCosts(_runId, thenStep: true); + } + + public void Stop(string why = "Stopped.") + { + if (!Running) return; + Finish(why); + } + + /// Re-reads the costs only (the panel's Refresh button). + public void RefreshCosts() + { + if (Running || Blocker() != null) return; + ReadCosts(_runId, thenStep: false); + } + + /// Reads the costs once per login when the Progression tab is first shown. Pump thread. + public void EnsureCosts() + { + if (_autoCostsTried || _costsAtMs != 0 || Running || Blocker() != null) return; + _autoCostsTried = true; + ReadCosts(_runId, thenStep: false); + } + + /// + /// XP for raises when the next one costs , + /// each level dearer than the last. Saturates at long.MaxValue. + /// + public static long ProjectCost(long nextCost, int levels) + { + if (nextCost <= 0 || levels <= 0) return 0; + double total = 0, step = nextCost; + for (int i = 0; i < levels; i++) + { + total += step; + step *= 1 + ProjectedLevelGrowth; + } + return total >= long.MaxValue ? long.MaxValue : (long)total; + } + + private void MarkCostsRead() + { + _costsAtMs = IltHubContext.NowMs; + _costsAtLocal = DateTime.Now; + } + + /// + /// "+N" button: sends "/attr abbr N"; the server's reply shows in chat. Refused up front when + /// the known (or, for N > 1, projected) cost is more than the unassigned XP, like UB's XP tab. + /// + public void RaiseManual(string key, int levels) + { + Stat? s = Find(key); + if (s == null || levels <= 0) return; + if (Running) { _status = "Wait for the current raise run to finish (or Stop it)."; return; } + string? blocked = Blocker(); + if (blocked != null) { _status = blocked; return; } + if (HeldOff) { _status = "Auto-enlighten is spending XP right now; try again when it finishes."; return; } + levels = Math.Min(levels, 1000); + if (_cost.TryGetValue(s.Abbr, out long next) && next > 0) + { + long need = ProjectCost(next, levels); + long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp); + if (need > have) + { + _status = $"Not enough unassigned XP for {s.Name} +{levels}: need {(levels > 1 ? "~" : "")}{IltParse.Compact(need)}, have {IltParse.Compact(have)}."; + return; + } + } + RynthLog.Trace(LogCat.IltProgression, $"attr manual raise {s.Abbr} +{levels}"); + int run = _runId; + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = $"/attr {s.Abbr} {levels}", + IsResponseLine = IsAttrReply, + IsTerminator = IsAttrReply, + IdleEndMs = 600, + FirstLineTimeoutMs = ReplyTimeoutMs, + Eat = false, + OnComplete = r => + { + string reply = r.TerminatorLine ?? r.Lines.FirstOrDefault() ?? (r.TimedOut ? "no reply" : ""); + _status = $"{s.Name} +{levels}: {reply}"; + if (run == _runId && !Running) ReadCosts(_runId, thenStep: false); + }, + }); + _status = $"Sent /attr {s.Abbr} {levels}..."; + } + + private static bool IsAttrReply(string t) + => t.StartsWith("[ATTR]", StringComparison.OrdinalIgnoreCase) || t.StartsWith("Your base", StringComparison.OrdinalIgnoreCase); + + private void ReadCosts(int run, bool thenStep) + { + // A plain refresh doesn't stack on one already queued; a run always gets its own reply. + if (!thenStep && _ctx.Capture.IsPending("/xp all")) return; + if (thenStep) + { + _phase = Phase.ReadingCosts; + if (_runRaised == 0) _status = "Reading XP costs (/xp all)..."; + } + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = "/xp all", + IsResponseLine = t => t.StartsWith("[XP]", StringComparison.OrdinalIgnoreCase), + IdleEndMs = 900, + FirstLineTimeoutMs = ReplyTimeoutMs, + Eat = true, + OnComplete = r => Guard(run, () => + { + if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Xp, IltTri.Off); if (run == _runId && thenStep) Finish("This server has no /xp command."); return; } + var fresh = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (string line in r.Lines) + { + var m = IltParse.XpCost.Match(line); + if (!m.Success) continue; + Stat? s = Find(m.Groups[1].Value); + if (s == null) continue; + fresh[s.Abbr] = IltParse.ParseLeadingLong(m.Groups[2].Value); + } + foreach (var kv in fresh) _cost[kv.Key] = kv.Value; + if (fresh.Count > 0) MarkCostsRead(); + RynthLog.Trace(LogCat.IltProgression, $"attr costs: {fresh.Count} line(s) (timedOut={r.TimedOut})"); + if (!thenStep || run != _runId || !Running) return; + if (fresh.Count == 0) { Finish(r.TimedOut ? "No reply to /xp all." : "No cost lines in the /xp all reply."); return; } + _runCosts = fresh; // a stat missing from this reply is not raised this step + _lastProgressMs = IltHubContext.NowMs; + Step(run); + }), + }); + } + + private void Step(int run) + { + if (run != _runId || !Running) return; + // The world can leave Server Features (or /xp go off) mid-run, and auto-enlighten can start. + if (Blocker() is string blocked) { Finish("Stopped: " + blocked); return; } + if (HeldOff) { Finish("Stopped: auto-enlighten started spending XP."); return; } + if (_runRaised >= MaxRaisesPerRun) { Finish($"Stopped after {MaxRaisesPerRun} raises (runs again later)."); return; } + + long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp); + long budget = have - Math.Max(0, C.AttrKeepXp); + var ticked = new HashSet(C.AttrRaiseStats, StringComparer.OrdinalIgnoreCase); + string? pick = Pick((Mode)Math.Clamp(C.AttrRaiseMode, 0, 2), C.AttrOrder, ticked, _runCosts, budget, ref _rrNext); + if (pick == null) + { + Finish(_runRaised == 0 + ? (budget <= 0 ? "Nothing to spend (unassigned XP is at or below the reserve)." + : "Nothing affordable among the ticked stats.") + : string.Empty); + return; + } + + Stat s = Find(pick)!; + _phase = Phase.Raising; + _raisingAbbr = s.Abbr; + _raisingCost = _runCosts.TryGetValue(s.Abbr, out long c) ? c : 0; + _status = $"Raising {s.Name} +1 (cost {IltParse.Compact(_raisingCost)})..."; + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = $"/attr {s.Abbr} 1", + IsResponseLine = IsAttrReply, + IsTerminator = IsAttrReply, + IdleEndMs = 600, + FirstLineTimeoutMs = ReplyTimeoutMs, + Eat = true, + OnComplete = r => Guard(run, () => OnRaiseReply(run, s, r)), + }); + } + + private void OnRaiseReply(int run, Stat s, IltChatResult r) + { + if (run != _runId || !Running) return; + string reply = r.TerminatorLine ?? r.Lines.FirstOrDefault() ?? string.Empty; + var ok = IltParse.AttrRaised.Match(reply); + var baseNow = BaseNow.Match(reply); + // The reply must be about the stat we raised (another /attr sender could answer first). + if (ok.Success && Find(ok.Groups[1].Value) != s) ok = Match.Empty; + if (baseNow.Success && Find(baseNow.Groups[1].Value) != s) baseNow = Match.Empty; + if (!ok.Success && !baseNow.Success) + { + RynthLog.Trace(LogCat.IltProgression, $"attr raise {s.Abbr}: not a success ('{reply}', timedOut={r.TimedOut}, unknown={r.UnknownCommand})"); + Finish(r.UnknownCommand ? "This server has no /attr command." + : reply.Length > 0 ? $"Server: {reply}" : "No reply to /attr."); + return; + } + + long spent = ok.Success ? IltParse.ParseLeadingLong(ok.Groups[3].Value) : _raisingCost; + int levels = ok.Success && int.TryParse(ok.Groups[2].Value, out int n) ? n : 1; + if (baseNow.Success && int.TryParse(baseNow.Groups[2].Value, out int v)) _base[s.Abbr] = v; + else if (_base.TryGetValue(s.Abbr, out int b)) _base[s.Abbr] = b + levels; + _runGains[s.Abbr] = (_runGains.TryGetValue(s.Abbr, out int g) ? g : 0) + levels; + _runRaised += levels; + _runSpent += spent; + _cost.Remove(s.Abbr); // its next level costs more; re-read before deciding again + _runCosts.Clear(); + _lastProgressMs = IltHubContext.NowMs; + _status = $"Raised {s.Name} (+{_runRaised} this run, {IltParse.Compact(_runSpent)} XP)..."; + ReadCosts(run, thenStep: true); + } + + /// Runs a capture callback; an exception ends the run instead of leaving it Running. + private void Guard(int run, Action body) + { + try { body(); } + catch (Exception ex) + { + RynthLog.Exception(LogCat.IltProgression, ex, "attr raise callback"); + if (run == _runId && Running) Finish("Stopped: internal error (see the RynthAi log)."); + } + } + + private void Finish(string reason) + { + _phase = Phase.Idle; + _runId++; // late callbacks from this run are ignored + string summary = _runRaised > 0 + ? "Raised " + string.Join(", ", C.AttrOrder.Where(_runGains.ContainsKey).Select(k => $"{Find(k)!.Name} +{_runGains[k]}")) + + $" ({IltParse.Compact(_runSpent)} XP)." + : string.Empty; + string text = (summary + (reason.Length > 0 ? (summary.Length > 0 ? " " : "") + reason : "")).Trim(); + if (text.Length == 0) text = "Done."; + _status = text; + _lastRun = $"{DateTime.Now:t} {(_runAuto ? "auto" : "manual")}: {text}"; + RynthLog.Trace(LogCat.IltProgression, $"attr raise run finished: {text}"); + if (_runRaised > 0) _ctx.Chat($"[Mini Remote] Attribute raise ({(_runAuto ? "auto" : "manual")}): {text}"); + } + + // ── Engine Skills panel bridge ──────────────────────────────────────────── + + /// Appends "attr":{...} for the Progression tab. + public void AppendJson(StringBuilder sb) + { + string? blocked = Blocker(); + long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp); + long budget = have - Math.Max(0, C.AttrKeepXp); + long now = IltHubContext.NowMs; + + sb.Append("\"attr\":{\"off\":").Append(blocked != null ? "true" : "false"); + Str(sb, "reason", blocked ?? string.Empty); + sb.Append(",\"auto\":").Append(C.AttrAutoRaise ? "true" : "false") + .Append(",\"every\":").Append(Math.Clamp(C.AttrAutoRaiseMinutes, 1, 1440)) + .Append(",\"mode\":").Append(Math.Clamp(C.AttrRaiseMode, 0, 2)) + .Append(",\"running\":").Append(Running ? "true" : "false"); + Str(sb, "keep", C.AttrKeepXp > 0 ? IltParse.Compact(C.AttrKeepXp) : "0"); + // The reserve box edits the exact number (the compact form above is lossy). + Str(sb, "keepFull", IltParse.N0(Math.Max(0, C.AttrKeepXp))); + Str(sb, "status", _status); + Str(sb, "lastRun", _lastRun); + Str(sb, "unassigned", $"Unassigned XP {IltParse.Compact(have)}" + + (C.AttrKeepXp > 0 ? $" (spendable {IltParse.Compact(Math.Max(0, budget))})" : "")); + string next = !C.AttrAutoRaise ? string.Empty + : Running ? "running" + : _nextAutoAtMs <= 0 ? "soon" + : IltParse.Duration(TimeSpan.FromMilliseconds(Math.Max(0, _nextAutoAtMs - now))); + Str(sb, "next", next); + Str(sb, "costsAge", _costsAtMs == 0 ? "costs not read yet" : $"costs read {Ago(now - _costsAtMs)} ago"); + Str(sb, "updated", _costsAtMs == 0 ? "-" : _costsAtLocal.ToString("HH:mm:ss")); + int level = _ctx.Inventory.PlayerInt(IltInventory.IntLevel); + long totalXp = _ctx.Inventory.PlayerQuad(IltInventory.QuadTotalXp); + Str(sb, "xpHeader", $"Level {(level > 0 ? level.ToString() : "?")} Total XP {(totalXp > 0 ? IltParse.Compact(totalXp) : "?")} Unassigned {IltParse.Compact(have)}"); + + var ticked = new HashSet(C.AttrRaiseStats, StringComparer.OrdinalIgnoreCase); + sb.Append(",\"rows\":["); + bool first = true; + foreach (string k in C.AttrOrder) + { + Stat? s = Find(k); + if (s == null) continue; + if (!first) sb.Append(','); + first = false; + bool known = _cost.TryGetValue(s.Abbr, out long c) && c > 0; + sb.Append('{'); + Str(sb, "key", s.Abbr, first: true); + Str(sb, "label", s.Name); + sb.Append(",\"vital\":").Append(s.Vital ? "true" : "false") + .Append(",\"on\":").Append(ticked.Contains(s.Abbr) ? "true" : "false") + .Append(",\"base\":").Append(_base.TryGetValue(s.Abbr, out int b) ? b : -1) + .Append(",\"afford\":").Append(known && c <= budget ? "true" : "false"); + Str(sb, "cost", known ? IltParse.Compact(c) : "?"); + // By hand (+1 / +10) only the unassigned XP limits, not the raiser's reserve. + long ten = known ? ProjectCost(c, 10) : 0; + sb.Append(",\"known\":").Append(known ? "true" : "false") + .Append(",\"afford1\":").Append(known && c <= have ? "true" : "false") + .Append(",\"afford10\":").Append(known && ten <= have ? "true" : "false"); + Str(sb, "cost10", known ? "~" + IltParse.Compact(ten) : "?"); + Str(sb, "costFull", known ? IltParse.N0(c) : ""); + Str(sb, "cost10Full", known ? IltParse.N0(ten) : ""); + sb.Append('}'); + } + sb.Append("]}"); + } + + private static string Ago(long ms) + { + long sec = Math.Max(0, ms / 1000); + return sec < 60 ? $"{sec}s" : sec < 3600 ? $"{sec / 60}m" : $"{sec / 3600}h {sec % 3600 / 60}m"; + } + + private static void Str(StringBuilder sb, string name, string value, bool first = false) + { + if (!first) sb.Append(','); + sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"'); + } + + /// "prog attr…" commands from the Skills panel. Returns false when the verb isn't ours. + public bool HandleRemote(string verb, string[] a) + { + string arg1 = a.Length > 1 ? a[1] : string.Empty; + string arg2 = a.Length > 2 ? a[2] : string.Empty; + switch (verb) + { + case "attrauto": + C.AttrAutoRaise = arg1.Equals("on", StringComparison.OrdinalIgnoreCase); + _nextAutoAtMs = C.AttrAutoRaise ? IltHubContext.NowMs + FirstAutoDelayMs : 0; + if (!C.AttrAutoRaise && Running && _runAuto) Stop("Auto-raise turned off."); + return true; + case "attrevery": + if (int.TryParse(arg1, out int min)) + { + C.AttrAutoRaiseMinutes = Math.Clamp(min, 1, 1440); + if (C.AttrAutoRaise) _nextAutoAtMs = IltHubContext.NowMs + C.AttrAutoRaiseMinutes * 60_000L; + } + return true; + case "attrmode": + if (int.TryParse(arg1, out int mode)) C.AttrRaiseMode = Math.Clamp(mode, 0, 2); + return true; + case "attrkeep": + if (arg1.Length == 0 || arg1 == "0") C.AttrKeepXp = 0; + else if (IltParse.TryParseAmount(arg1, out long keep)) C.AttrKeepXp = Math.Max(0, keep); + return true; + case "attron": + { + Stat? s = Find(arg1); + if (s == null) return true; + bool on = arg2.Equals("on", StringComparison.OrdinalIgnoreCase); + C.AttrRaiseStats.RemoveAll(x => x.Equals(s.Abbr, StringComparison.OrdinalIgnoreCase)); + if (on) C.AttrRaiseStats.Add(s.Abbr); + return true; + } + case "attrmove": + { + Stat? s = Find(arg1); + if (s == null) return true; + int i = C.AttrOrder.FindIndex(x => x.Equals(s.Abbr, StringComparison.OrdinalIgnoreCase)); + int j = arg2.Equals("up", StringComparison.OrdinalIgnoreCase) ? i - 1 + : arg2.Equals("top", StringComparison.OrdinalIgnoreCase) ? 0 : i + 1; + if (i < 0 || j < 0 || j >= C.AttrOrder.Count || i == j) return true; + string item = C.AttrOrder[i]; + C.AttrOrder.RemoveAt(i); + C.AttrOrder.Insert(j, item); + return true; + } + case "attrorderreset": + C.AttrOrder = new List(DefaultOrder); + return true; + case "attrraise": + if (int.TryParse(arg2, out int levels)) RaiseManual(arg1, levels); + return true; + case "attrrun": Start(auto: false); return true; + case "attrstop": Stop(); return true; + case "attrcosts": RefreshCosts(); return true; + } + return false; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltAugCosts.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltAugCosts.cs new file mode 100644 index 0000000..ae28ac6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltAugCosts.cs @@ -0,0 +1,228 @@ +// IltAugCosts.cs — luminance augmentation cost rules, per server (world name). +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// Defaults are UB's Leaftide Augs tab (correct for InfiniteLeaftide): +// level i (1-based) costs (Base + (i-1) * Base * LinearPercent/100) * multiplier(i) +// multiplier(i) = M0 below S1, M1 from S1, M2 from S2, M3 from S3, M4 from S4 +// (UB: 1 / 4 / 8 / 16 / 24; a tier starts AT its S level). +// Another server can change the multipliers and every aug's base, growth, S1..S4, target cap +// and coins per level from the Progression tab; those edits are saved for that world only in +// one shared file, so every character on the world prices augs the same way. +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// The saved file: one cost profile per world that was changed from the defaults. +public sealed class IltAugCostFile +{ + public Dictionary Servers = new(StringComparer.OrdinalIgnoreCase); +} + +/// A world's cost rules: the five tier multipliers and one row per aug. +public sealed class IltAugCostProfile +{ + public double[] Multipliers = (double[])IltAugCosts.DefaultMultipliers.Clone(); + public List Augs = new(); +} + +/// One aug's cost rule. Thresholds are 1-based levels; Cap 0 = no target limit. +public sealed class IltAugCostRow +{ + public string Key = string.Empty; + public long Base; + public double LinearPercent; + public int CoinsPerLevel; + public int S1, S2, S3, S4; + public int Cap; + + public IltAugCostRow Clone() => (IltAugCostRow)MemberwiseClone(); +} + +internal sealed class IltAugCosts +{ + /// UB's tier multipliers: below S1, from S1, from S2, from S3, from S4. + public static readonly double[] DefaultMultipliers = { 1, 4, 8, 16, 24 }; + + /// Highest target the planner accepts when an aug has no cap (keeps the plan sane). + public const int NoCapLimit = 100_000; + + /// Display order and labels; also the only keys a profile may hold. + public static readonly (string Key, string Label)[] Labels = + { + ("creature", "Creature"), ("item", "Item"), ("life", "Life"), ("war", "War"), ("void", "Void"), + ("duration", "Duration"), ("melee", "Melee"), ("missile", "Missile"), + ("specialization", "Specialization"), ("summon", "Summon"), + }; + + /// UB Augs.cs (ILT): cost models, coins per level and soft caps S1..S4; no target cap. + public static IltAugCostRow[] DefaultRows() => new[] + { + Row("creature", 750_000, 130, 3, 2750, 4000, 4750, 5250), + Row("item", 1_000_000, 165, 18, 1250, 2000, 3000, 3500), + Row("life", 975_000, 195, 12, 1000, 2000, 3000, 3750), + Row("war", 750_000, 140, 5, 1750, 2500, 3000, 3750), + Row("void", 800_000, 160, 5, 1750, 2500, 3000, 3750), + Row("duration", 400_000, 120, 5, 1000, 2000, 2500, 3000), + Row("melee", 750_000, 140, 5, 1750, 2500, 3000, 3750), + Row("missile", 750_000, 140, 5, 1750, 2500, 3000, 3750), + Row("specialization", 3_000_000, 200, 50, 1750, 2500, 3000, 3750), + Row("summon", 500_000, 125, 36, 1750, 2500, 3000, 3750), + }; + + private static IltAugCostRow Row(string key, long b, double lp, int coins, int s1, int s2, int s3, int s4) + => new() { Key = key, Base = b, LinearPercent = lp, CoinsPerLevel = coins, S1 = s1, S2 = s2, S3 = s3, S4 = s4, Cap = 0 }; + + /// The shared settings file. Tests point it at a scratch folder before first use. + public static string FilePath { get; set; } = Path.Combine(IltHubStore.SharedRoot, "ilt-aug-costs.json"); + + private IltAugCostFile? _file; + private string _lastJson = string.Empty; + private static readonly IltAugCostProfile Defaults = NewDefaultProfile(); + + public static string Label(string key) + { + foreach (var l in Labels) if (l.Key.Equals(key, StringComparison.OrdinalIgnoreCase)) return l.Label; + return key; + } + + private static IltAugCostProfile NewDefaultProfile() + => new() { Multipliers = (double[])DefaultMultipliers.Clone(), Augs = DefaultRows().ToList() }; + + private IltAugCostFile File_ + { + get + { + if (_file != null) return _file; + _file = new IltAugCostFile(); + try + { + if (File.Exists(FilePath)) + { + string json = File.ReadAllText(FilePath); + _file = JsonSerializer.Deserialize(json, IltHubJsonContext.Default.IltAugCostFile) ?? new IltAugCostFile(); + _lastJson = json; + } + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {FilePath}"); _file = new IltAugCostFile(); } + var fixedUp = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var kv in _file.Servers ?? new()) + if (kv.Value != null) fixedUp[kv.Key ?? string.Empty] = Normalize(kv.Value); + _file.Servers = fixedUp; + return _file; + } + } + + /// + /// Repairs a loaded or edited profile: five multipliers, exactly one row per known aug (missing + /// ones from the defaults, unknown ones dropped), non-negative values and S1 <= S2 <= S3 <= S4. + /// + public static IltAugCostProfile Normalize(IltAugCostProfile p) + { + var m = new double[5]; + for (int i = 0; i < 5; i++) + { + double v = p.Multipliers != null && i < p.Multipliers.Length ? p.Multipliers[i] : DefaultMultipliers[i]; + m[i] = double.IsFinite(v) ? Math.Clamp(v, 0, 1000) : DefaultMultipliers[i]; + } + p.Multipliers = m; + + var byKey = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var r in p.Augs ?? new()) if (r != null && !string.IsNullOrEmpty(r.Key)) byKey[r.Key] = r; + var rows = new List(Labels.Length); + foreach (var def in DefaultRows()) + { + var r = byKey.TryGetValue(def.Key, out var have) ? have : def; + r.Key = def.Key; + r.Base = Math.Max(0, r.Base); + r.LinearPercent = double.IsFinite(r.LinearPercent) ? Math.Clamp(r.LinearPercent, 0, 100_000) : def.LinearPercent; + r.CoinsPerLevel = Math.Max(0, r.CoinsPerLevel); + r.S1 = Math.Max(0, r.S1); + r.S2 = Math.Max(r.S1, r.S2); + r.S3 = Math.Max(r.S2, r.S3); + r.S4 = Math.Max(r.S3, r.S4); + r.Cap = Math.Max(0, r.Cap); + rows.Add(r); + } + p.Augs = rows; + return p; + } + + /// The rules for : its saved profile, or the UB defaults. + public IltAugCostProfile For(string world) + => File_.Servers.TryGetValue(world ?? string.Empty, out var p) ? p : Defaults; + + /// True when has its own saved rules. + public bool IsCustom(string world) => File_.Servers.ContainsKey(world ?? string.Empty); + + /// Applies an edit to 's rules (copying the defaults first) and saves. + public void Edit(string world, Action change) + { + string key = world ?? string.Empty; + if (!File_.Servers.TryGetValue(key, out var p)) + { + p = NewDefaultProfile(); + File_.Servers[key] = p; + } + change(p); + Normalize(p); + Save(); + } + + /// Drops 's saved rules: it goes back to the UB defaults. + public void Reset(string world) + { + if (File_.Servers.Remove(world ?? string.Empty)) Save(); + } + + private void Save() + { + try + { + string json = JsonSerializer.Serialize(File_, IltHubJsonContext.Default.IltAugCostFile); + if (json == _lastJson) return; + if (RynthCore.Plugin.Shared.DataWriteGuard.TrySave("the aug cost table", FilePath, () => + { + Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); + string tmp = FilePath + ".tmp"; + File.WriteAllText(tmp, json); + File.Move(tmp, FilePath, overwrite: true); + })) + _lastJson = json; + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {FilePath}"); } + } + + /// Highest target the planner allows for at current level . + public static int Ceiling(IltAugCostRow r, int cur) => Math.Max(cur, r.Cap > 0 ? r.Cap : NoCapLimit); + + /// + /// Luminance for levels cur+1 .. tgt. Same result as UB's per-level loop, summed per tier in + /// closed form: within a tier the per-level base grows linearly, so each tier is an arithmetic series. + /// + public static decimal LumCost(IltAugCostRow r, double[] mult, int cur, int tgt) + { + int first = Math.Max(1, cur + 1); + if (tgt < first) return 0; + decimal b = r.Base; + decimal step = b * (decimal)r.LinearPercent / 100m; + // Tier t covers levels [lo[t], hi[t]) (1-based); the last tier has no end. + long[] lo = { 1, r.S1, r.S2, r.S3, r.S4 }; + long[] hi = { r.S1, r.S2, r.S3, r.S4, long.MaxValue }; + decimal total = 0; + for (int t = 0; t < 5; t++) + { + long a = Math.Max(first, lo[t]); + long z = Math.Min(tgt, hi[t] - 1); + if (z < a) continue; + decimal n = z - a + 1; + // sum over i=a..z of (b + (i-1)*step) = n*b + step * sum(i-1) = n*b + step * n*(a-1 + z-1)/2 + decimal levels = n * b + step * (n * ((a - 1) + (z - 1)) / 2m); + total += levels * (decimal)mult[t]; + } + return total; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankCommands.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankCommands.cs new file mode 100644 index 0000000..e4782e2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankCommands.cs @@ -0,0 +1,188 @@ +// IltBankCommands.cs — The /bank commands the Banking tab sends, and the reply lines it collects. +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// Server contract (ACECustom PlayerCommands.HandleBank / Player_Bank, upstream 976606695): +// /b d [code] deposit everything (no code) or one kind; "Deposited N ", +// "No found to deposit", "Deposited all !". +// /b lum bank luminance tokens: "Starting Banked Lum", one "Deposited N x " +// a kind, "Ending Banked Lum"; "No luminance tokens found to deposit". +// /b w withdraw: "Withdrew ...", "You don't have enough ...", "Failed to create ...". +// /b w n [n] trade notes by denomination (i v x l c d m md mm mmd). +// /b t transfer; "Transferred {N0} {Currency} to {Name}[ (offline)]". +// /b t n trade notes' pyreal value, then "(Equivalent to Nx DENOM notes)". +// The recipient is one argument: a name with a space has to be in "quotes". +// Prestige Coins are bound to the character: "[BANK] Prestige Coins are bound to you and +// cannot be transferred." Pyreal peas and luminance tokens are deposit only. +// Items is the one table of what the server allows; the deposit, withdraw and transfer lists +// are built from it. Deposit, withdraw and transfer share one server throttle +// (bank_command_limit); a plain /bank balance doesn't touch it. Pure: no host calls, so the +// host tests cover it. +using System; +using System.Linq; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal static class IltBankCommands +{ + /// + /// One bank item: label, server code, and what the server allows for it. For trade notes + /// ("n") a withdrawal or transfer is by denomination and note count. + /// + internal sealed record BankItem(string Label, string Code, bool Deposit, bool Withdraw, bool Transfer); + + /// The trade-notes code: withdrawn and transferred by denomination. + public const string NotesCode = "n"; + + /// The luminance-tokens deposit: its own command, "/b lum". + public const string LuminanceTokensCode = "lum"; + + /// Everything the bank holds, in the server's order, with what it allows. + public static readonly BankItem[] Items = + { + new("Pyreals", "p", Deposit: true, Withdraw: true, Transfer: true), + new("Pyreal peas", "ps", Deposit: true, Withdraw: false, Transfer: false), + new("Luminance", "l", Deposit: true, Withdraw: true, Transfer: true), + new("Luminance tokens", LuminanceTokensCode, Deposit: true, Withdraw: false, Transfer: false), + new("Legendary keys", "k", Deposit: true, Withdraw: true, Transfer: true), + new("Mythical keys", "mk", Deposit: true, Withdraw: true, Transfer: true), + new("Enlightened coins", "e", Deposit: true, Withdraw: true, Transfer: true), + new("Weakly enlightened coins", "we", Deposit: true, Withdraw: true, Transfer: true), + new("Prestige coins", "pc", Deposit: true, Withdraw: true, Transfer: false), + new("Trade notes", NotesCode, Deposit: true, Withdraw: true, Transfer: true), + }; + + /// A deposit choice: label, and the command's argument after "/b d" ("" = all). + public static readonly (string Label, string Args)[] Deposits = + new[] { ("Everything", string.Empty) } + .Concat(Items.Where(i => i.Deposit).Select(i => (i.Label, i.Code))) + .ToArray(); + + /// A withdraw choice: label and the server code; "n" is trade notes (by denomination). + public static readonly (string Label, string Code)[] Withdrawals = + Items.Where(i => i.Withdraw).Select(i => (i.Label, i.Code)).ToArray(); + + /// A transfer choice: label and the server code; "n" moves trade notes' pyreal value. + public static readonly (string Label, string Code)[] Transfers = + Items.Where(i => i.Transfer).Select(i => (i.Label, i.Code)).ToArray(); + + /// Trade note denominations: label and code, in the server's order. + public static readonly (string Label, string Code, long Value)[] NoteDenominations = + { + ("I (100)", "i", 100), ("V (500)", "v", 500), ("X (1K)", "x", 1_000), ("L (5K)", "l", 5_000), + ("C (10K)", "c", 10_000), ("D (50K)", "d", 50_000), ("M (100K)", "m", 100_000), + ("MD (150K)", "md", 150_000), ("MM (200K)", "mm", 200_000), ("MMD (250K)", "mmd", 250_000), + }; + + /// The server refuses a trade-note withdrawal of more than this many notes; transfers use the same cap. + public const int MaxNoteCount = 50_000; + + /// "/b d", "/b d p", or "/b lum" for the luminance tokens; empty for an unknown index. + public static string Deposit(int index) + { + if (index < 0 || index >= Deposits.Length) return string.Empty; + string args = Deposits[index].Args; + if (args.Length == 0) return "/b d"; + return args == LuminanceTokensCode ? "/b lum" : "/b d " + args; + } + + /// + /// "/b w p 1000000", or "/b w n mmd 5" for trade notes ( is then the + /// note count). Empty (with ) when the input can't be sent. + /// + public static string Withdraw(int index, long amount, int denomination, out string error) + { + error = string.Empty; + if (index < 0 || index >= Withdrawals.Length) { error = "Pick what to withdraw."; return string.Empty; } + if (amount <= 0) { error = "Amount must be positive."; return string.Empty; } + string code = Withdrawals[index].Code; + if (code != NotesCode) return $"/b w {code} {amount}"; + if (!TryNote(denomination, amount, out string denom, out error)) return string.Empty; + return $"/b w n {denom} {amount}"; + } + + /// + /// "/bank t p 250000 Bob", "/bank t n mmd 4 \"Some Name\"" for trade notes ( + /// is then the note count). must already be a checked character name + /// (IltParse.CharacterName); a name with a space is quoted, as the server reads one argument. + /// Empty (with ) when the input can't be sent. + /// + public static string Transfer(int index, long amount, int denomination, string target, out string error) + { + error = string.Empty; + if (index < 0 || index >= Transfers.Length) { error = "Pick a currency."; return string.Empty; } + if (amount <= 0) { error = "Amount must be positive."; return string.Empty; } + target = (target ?? string.Empty).Trim(); + if (target.Length == 0) { error = "Enter a recipient."; return string.Empty; } + if (target.IndexOf('"') >= 0) { error = "Recipient must be a character name."; return string.Empty; } + string who = target.IndexOf(' ') >= 0 ? "\"" + target + "\"" : target; + string code = Transfers[index].Code; + if (code != NotesCode) return $"/bank t {code} {amount} {who}"; + if (!TryNote(denomination, amount, out string denom, out error)) return string.Empty; + return $"/bank t n {denom} {amount} {who}"; + } + + /// True when is the trade-notes transfer (denomination and count). + public static bool IsNoteTransfer(int index) => index >= 0 && index < Transfers.Length && Transfers[index].Code == NotesCode; + + /// The pyreal value of notes of (0 if unknown). + public static long NoteValue(int denomination, long count) => + denomination >= 0 && denomination < NoteDenominations.Length && count > 0 ? NoteDenominations[denomination].Value * count : 0; + + private static bool TryNote(int denomination, long count, out string code, out string error) + { + code = string.Empty; + error = string.Empty; + if (denomination < 0 || denomination >= NoteDenominations.Length) { error = "Pick a note denomination."; return false; } + if (count > MaxNoteCount) { error = $"At most {MaxNoteCount:N0} notes at a time."; return false; } + code = NoteDenominations[denomination].Code; + return true; + } + + /// + /// True for a line the server sends in reply to a deposit or withdrawal (so the tab can show + /// it as the result). Only lines the bank code writes; never "[BANK]" balance lines. + /// + public static bool IsActionReply(string line) + { + if (string.IsNullOrEmpty(line)) return false; + return line.StartsWith("Deposited ", StringComparison.Ordinal) + || line.StartsWith("Withdrew ", StringComparison.Ordinal) + || (line.StartsWith("No ", StringComparison.Ordinal) && line.EndsWith("to deposit", StringComparison.Ordinal)) + || line.StartsWith("Starting Banked Lum", StringComparison.Ordinal) + || line.StartsWith("Ending Banked Lum", StringComparison.Ordinal) + || line.StartsWith("Not deposited", StringComparison.Ordinal) + || line.StartsWith("You don't have enough", StringComparison.Ordinal) + || line.StartsWith("You cannot hold any more", StringComparison.Ordinal) + || line.StartsWith("You have not been luminance flagged", StringComparison.Ordinal) + || line.StartsWith("Failed to ", StringComparison.Ordinal) + || line.StartsWith("Warning: Requested", StringComparison.Ordinal) + || line.StartsWith("Amount must be", StringComparison.Ordinal) + || line.StartsWith("Cannot deposit while", StringComparison.Ordinal) + || line.StartsWith("[Deposit]", StringComparison.Ordinal) + || line.StartsWith("[Withdraw]", StringComparison.Ordinal) + || line.StartsWith("Invalid amount", StringComparison.Ordinal) + || line.StartsWith("Invalid denomination", StringComparison.Ordinal) + || line.StartsWith("Count must be", StringComparison.Ordinal) + || line.StartsWith("Count cannot exceed", StringComparison.Ordinal) + || line.StartsWith("You are not permitted to use bank commands", StringComparison.Ordinal); + } + + /// + /// True for a line the server sends in reply to a transfer: the result, the trade-note + /// equivalent, the throttle, or a refusal (unknown player, bound prestige coins, bad input). + /// + public static bool IsTransferReply(string line) + { + if (string.IsNullOrEmpty(line)) return false; + return line.StartsWith("Transferred ", StringComparison.Ordinal) + || line.StartsWith("(Equivalent to ", StringComparison.Ordinal) + || line.StartsWith("Character '", StringComparison.Ordinal) + || line.StartsWith("You cannot transfer", StringComparison.Ordinal) + || line.StartsWith("You don't have enough", StringComparison.Ordinal) + || line.StartsWith("[Transfer]", StringComparison.Ordinal) + || line.StartsWith("[BANK] Too many parameters", StringComparison.Ordinal) + || line.StartsWith("[BANK] Prestige Coins are bound", StringComparison.Ordinal) + || line.StartsWith("Invalid count", StringComparison.Ordinal) + || line.StartsWith("Invalid denomination", StringComparison.Ordinal); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankExport.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankExport.cs new file mode 100644 index 0000000..65b3949 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankExport.cs @@ -0,0 +1,151 @@ +// IltBankExport.cs - The bank JSON of "RynthILT.Data" (Plugins/Shared/RynthIltDataApi.cs): the +// Banking tab's balances, form choices and log for another plugin's view (every character here). +// +// Every character RynthILT has run on this server keeps its balances in its own hub.json +// (\\\hub.json, IltHubStore); the export lists them all, the +// logged-in character from its live state and the rest from their saved files (read on the pump +// at most every SiblingReadMs, so a reader polling every couple of seconds costs one directory +// listing now and then). Plus the form choices (IltBankCommands), the last action's reply and +// the recent transfers. Build is pure: the tests feed it rows. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.Json; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal static class IltBankExport +{ + /// How many recent transfers the JSON carries (newest first). + public const int MaxTransactions = 50; + + /// One character's balances as exported. + internal sealed record Row(string Name, bool Current, IltBankState Bank); + + /// + /// The bank JSON. : 1 the server has /bank, 0 not, -1 not known yet. + /// Rows are listed current character first, then by name. Plain ASCII. + /// + public static string Build(bool available, int enabled, string world, string character, IReadOnlyList rows, + string result, IReadOnlyList transactions) + { + var sb = new StringBuilder(4096); + sb.Append("{\"available\":").Append(available ? "true" : "false"); + sb.Append(",\"enabled\":").Append(Math.Clamp(enabled, -1, 1).ToString(CultureInfo.InvariantCulture)); + sb.Append(",\"world\":\"").Append(IltStyle.JsonEscape(world ?? string.Empty)).Append('"'); + sb.Append(",\"character\":\"").Append(IltStyle.JsonEscape(character ?? string.Empty)).Append('"'); + + var ordered = new List(rows); + ordered.Sort((a, b) => a.Current != b.Current ? (a.Current ? -1 : 1) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); + sb.Append(",\"characters\":["); + for (int i = 0; i < ordered.Count; i++) + { + Row r = ordered[i]; + IltBankState b = r.Bank; + if (i > 0) sb.Append(','); + sb.Append("{\"name\":\"").Append(IltStyle.JsonEscape(r.Name)).Append('"'); + sb.Append(",\"current\":").Append(r.Current ? "true" : "false"); + Num(sb, "pyreals", b.Pyreals); + Num(sb, "luminance", b.Luminance); + Num(sb, "legendaryKeys", b.LegendaryKeys); + Num(sb, "mythicalKeys", b.MythicalKeys); + Num(sb, "enlightenedCoins", b.EnlightenedCoins); + Num(sb, "weaklyEnlightenedCoins", b.WeaklyEnlightenedCoins); + Num(sb, "prestigeCoins", b.PrestigeCoins); + sb.Append(",\"updated\":\"").Append(Utc(b.LastUpdated)).Append("\"}"); + } + sb.Append(']'); + + sb.Append(",\"deposits\":["); + for (int i = 0; i < IltBankCommands.Deposits.Length; i++) + { + if (i > 0) sb.Append(','); + sb.Append('"').Append(IltStyle.JsonEscape(IltBankCommands.Deposits[i].Label)).Append('"'); + } + sb.Append(']'); + Choices(sb, "withdrawals", IltBankCommands.Withdrawals, w => w.Code == IltBankCommands.NotesCode); + Choices(sb, "transfers", IltBankCommands.Transfers, t => t.Code == IltBankCommands.NotesCode); + sb.Append(",\"notes\":["); + for (int i = 0; i < IltBankCommands.NoteDenominations.Length; i++) + { + var n = IltBankCommands.NoteDenominations[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"label\":\"").Append(IltStyle.JsonEscape(n.Label)).Append('"'); + Num(sb, "value", n.Value); + sb.Append('}'); + } + sb.Append(']'); + + sb.Append(",\"result\":\"").Append(IltStyle.JsonEscape(result ?? string.Empty)).Append('"'); + sb.Append(",\"transactions\":["); + int written = 0; + for (int i = transactions.Count - 1; i >= 0 && written < MaxTransactions; i--, written++) + { + IltBankTransaction t = transactions[i]; + if (written > 0) sb.Append(','); + sb.Append("{\"when\":\"").Append(t.Timestamp == default ? "" : t.Timestamp.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)).Append('"'); + sb.Append(",\"type\":\"").Append(IltStyle.JsonEscape(t.Type)).Append('"'); + Num(sb, "amount", t.Amount); + sb.Append(",\"currency\":\"").Append(IltStyle.JsonEscape(t.Currency)).Append('"'); + sb.Append(",\"player\":\"").Append(IltStyle.JsonEscape(t.OtherPlayer)).Append("\"}"); + } + sb.Append("]}"); + return sb.ToString(); + } + + private static void Num(StringBuilder sb, string name, long value) + => sb.Append(",\"").Append(name).Append("\":").Append(value.ToString(CultureInfo.InvariantCulture)); + + private static void Choices(StringBuilder sb, string name, (string Label, string Code)[] items, Func<(string Label, string Code), bool> notes) + { + sb.Append(",\"").Append(name).Append("\":["); + for (int i = 0; i < items.Length; i++) + { + if (i > 0) sb.Append(','); + sb.Append("{\"label\":\"").Append(IltStyle.JsonEscape(items[i].Label)).Append("\",\"notes\":") + .Append(notes(items[i]) ? "true" : "false").Append('}'); + } + sb.Append(']'); + } + + /// A local DateTime as ISO UTC ("" = never). + private static string Utc(DateTime local) => local == DateTime.MinValue || local == default + ? "" + : local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); + + /// + /// The other characters' saved balances: every <world folder>\*\hub.json except + /// . A file that can't be read is skipped (its character just + /// isn't listed). Characters never banked (no LastUpdated) are left out. + /// + public static List ReadSiblings(string currentFolder) + { + var rows = new List(); + if (string.IsNullOrEmpty(currentFolder)) return rows; + string? worldDir = Path.GetDirectoryName(currentFolder.TrimEnd('\\', '/')); + if (string.IsNullOrEmpty(worldDir) || !Directory.Exists(worldDir)) return rows; + string self = Path.GetFullPath(currentFolder).TrimEnd('\\', '/'); + foreach (string dir in Directory.EnumerateDirectories(worldDir)) + { + if (string.Equals(Path.GetFullPath(dir).TrimEnd('\\', '/'), self, StringComparison.OrdinalIgnoreCase)) continue; + string file = Path.Combine(dir, IltHubStore.StateFile); + if (!File.Exists(file)) continue; + try + { + using var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + var state = JsonSerializer.Deserialize(fs, IltHubJsonContext.Default.IltHubState); + IltBankState? bank = state?.Bank; + if (bank == null || bank.LastUpdated == DateTime.MinValue) continue; + rows.Add(new Row(Path.GetFileName(dir), false, bank)); + } + catch (Exception ex) + { + RynthLog.Trace(LogCat.IltBanking, $"bank export: skipped {file} ({ex.Message})"); + } + } + return rows; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankRoster.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankRoster.cs new file mode 100644 index 0000000..cd19062 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankRoster.cs @@ -0,0 +1,76 @@ +// IltBankRoster.cs - Every character's bank on this server, for the Banking tab's "Characters" table +// and the transfer form's recipient picker. SilentKelpie's (RynthInventory 0.1.1's Banking tab, RynthSuite +// PR 12, ported by hand 2026-10-19); it read RynthILT's bank export from RynthInventory's window and +// moved into RynthILT's own Banking tab on 2026-10-21 (one server's features live in its server plugin). +// The characters are the ones RynthILT keeps balances for on this server: the logged-in one from its +// live state, every other one from its saved hub.json (IltBankExport.ReadSiblings), so every account +// played on this PC with RynthILT loaded. (RynthInventory's version also listed characters Global +// Inventory knew without a balance yet, as "not read yet" rows; those carry no balance and are left out.) +// Pure: RynthILT.Tests covers it. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One character's balances as the Banking tab shows them (a copy: the render thread reads it). +internal sealed record IltBankRosterRow(string Name, bool Current, long Pyreals, long Luminance, long LegendaryKeys, long MythicalKeys, + long EnlightenedCoins, long WeaklyEnlightenedCoins, long PrestigeCoins, DateTime Updated) +{ + public static IltBankRosterRow From(string name, bool current, IltBankState b) => + new(name, current, b.Pyreals, b.Luminance, b.LegendaryKeys, b.MythicalKeys, b.EnlightenedCoins, b.WeaklyEnlightenedCoins, + b.PrestigeCoins, b.LastUpdated); +} + +internal static class IltBankRoster +{ + /// + /// The roster: the logged-in character first, then by name; a name listed twice keeps the current + /// character's row (its live state beats its saved file). + /// + public static IltBankRosterRow[] Build(IReadOnlyList rows) + { + var byName = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (IltBankExport.Row r in rows) + { + if (string.IsNullOrWhiteSpace(r.Name)) continue; + if (byName.TryGetValue(r.Name, out IltBankRosterRow? have) && have.Current && !r.Current) continue; + byName[r.Name] = IltBankRosterRow.From(r.Name, r.Current, r.Bank); + } + var list = new List(byName.Values); + list.Sort((a, b) => a.Current != b.Current ? (a.Current ? -1 : 1) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); + return list.ToArray(); + } + + /// The sums over every character with a balance read (one row of the same shape). + public static IltBankRosterRow Totals(IReadOnlyList roster) + { + long py = 0, lum = 0, lk = 0, mk = 0, ec = 0, wec = 0, pc = 0; + foreach (IltBankRosterRow r in roster) + { + if (r.Updated == DateTime.MinValue) continue; + py += r.Pyreals; lum += r.Luminance; lk += r.LegendaryKeys; mk += r.MythicalKeys; + ec += r.EnlightenedCoins; wec += r.WeaklyEnlightenedCoins; pc += r.PrestigeCoins; + } + return new IltBankRosterRow("Total", false, py, lum, lk, mk, ec, wec, pc, DateTime.MinValue); + } + + /// The other characters, by name: the transfer form's recipient picker. + public static List Others(IReadOnlyList roster) + { + var names = new List(); + foreach (IltBankRosterRow r in roster) if (!r.Current) names.Add(r.Name); + return names; + } + + /// "3m ago", "2h ago", "4d ago": how old a saved balance is; "-" when never read. + public static string Age(DateTime updatedLocal, DateTime nowLocal) + { + if (updatedLocal == DateTime.MinValue) return "-"; + TimeSpan d = nowLocal - updatedLocal; + if (d < TimeSpan.Zero) d = TimeSpan.Zero; + if (d.TotalMinutes < 1) return "just now"; + if (d.TotalHours < 1) return $"{(int)d.TotalMinutes}m ago"; + if (d.TotalDays < 1) return $"{(int)d.TotalHours}h ago"; + return $"{(int)d.TotalDays}d ago"; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs new file mode 100644 index 0000000..04ec369 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs @@ -0,0 +1,750 @@ +// IltBanking.cs — ILT banking: /bank balances, deposits, withdrawals, confirmed transfers, +// transaction log. Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// Render is the Mini Remote's "Banking" tab, with every character's bank on this server since 2026-10-21 +// (IltBankRoster: SilentKelpie's Banking tab from RynthInventory, which showed RynthILT's data there). The +// balances and log are also exported to other plugins through "RynthILT.Data" (IltBankExport; their verbs +// come back through RunVerb). +// +// Server contract (ACECustom PlayerCommands bank handler, upstream 2026-10-11): +// /bank → "[BANK] Your balances are:" then "[BANK] Pyreals: N", "Luminance:", +// "Legendary Keys:", "Mythical Keys:", "Enlightened Coins:", +// "Weakly Enlightened Coins:", "Prestige Coins: N (bound to you ...)". +// /b d, /b lum, /b w → deposits and withdrawals (IltBankCommands has the commands and replies). +// /bank t → "Transferred {N0} {Currency} to {Name}[ (offline)]" or an error; +// the recipient sees "Received {N0} {currency} from {Name}". +// /bank t n → trade notes' pyreal value, then "(Equivalent to ...)". +// What each item allows is IltBankCommands.Items (the server's table): Prestige Coins (pc) +// are bound (deposit and withdraw only); pyreal peas and luminance tokens deposit only. +// Deposit, withdraw and transfer share the server's bank_command_limit throttle; a balance +// refresh doesn't, so it has its own (client-side) spacing. +// Balance lines are parsed whenever they appear (player-typed /bank too) but only EATEN +// when the Hub asked. Transfers always need a confirmation (UB had none). +// Backstop (SilentKelpie's PR 12, narrowed): the capture queue eats a quiet refresh's reply, but if +// it misses, balance-dump lines arriving within QuietBalanceWindowMs of a quiet refresh are eaten +// here. Only the dump itself (header and "Label: N" lines): other [BANK] lines (errors, bound-coin +// notes), Transferred / Received lines, and balance reads nobody here asked for (a macro's or another +// plugin's /bank, outside the window) are left alone. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltBanking : IIltFeature +{ + /// Transfer currencies: display name, /bank t code (IltBankCommands.Transfers). + public static readonly (string Name, string Code)[] Currencies = IltBankCommands.Transfers; + private static readonly string[] CurrencyNames = Currencies.Select(c => c.Name).ToArray(); + private static readonly string[] DepositNames = IltBankCommands.Deposits.Select(d => d.Label).ToArray(); + private static readonly string[] WithdrawNames = IltBankCommands.Withdrawals.Select(w => w.Label).ToArray(); + private static readonly string[] NoteNames = IltBankCommands.NoteDenominations.Select(n => n.Label).ToArray(); + + /// Server throttle for deposit / withdraw / transfer (bank_command_limit). + private const long BankCommandSpacingMs = 5000; + /// Client spacing for balance refreshes (the server doesn't throttle a plain /bank). + private const long BalanceSpacingMs = 5000; + /// After a deposit or withdrawal, the balances are re-read this long after the reply. + private const long RefreshAfterActionMs = 1500; + + private readonly IltHubContext _ctx; + private readonly object _txLock = new(); + private readonly List _transactions; + private IltBankTransaction[] _txSnapshot = Array.Empty(); + private bool _txDirty; + + private long _lastBankCommandAt; + private long _lastBalanceAt; + private long _lastAutoRefreshAt; + /// When a quiet balance refresh is due after an action (0 = none). Pump thread. + private long _refreshDueAt; + /// Until then, money is moving between pack and bank (MovingMoney). Pump thread. + private long _moveUntil; + /// How long after a deposit / withdrawal reply the moved amounts are not income (covers the balance re-read). + private const long MoveWindowMs = 12_000; + /// Until this tick, a balance dump that reaches chat is the reply to a quiet Hub refresh (0 = no quiet refresh out). + private long _quietBalanceUntil; + /// How long after a quiet refresh is queued its leaked dump lines are still eaten here. + internal const long QuietBalanceWindowMs = 15_000; + + // Render-thread form state. + private string _amountText = string.Empty; + private string _withdrawText = string.Empty; + private string _txFilter = string.Empty; + private string _lastResult = string.Empty; + private volatile string _actionResult = string.Empty; + /// The newest action reply or error (deposit, withdrawal or transfer), for the bank export. + private volatile string _latestResult = string.Empty; + + /// + /// Another plugin is showing the balances (a "RynthILT.Data" reader): + /// the periodic quiet refresh runs as it does while the Mini Remote is open. Pump thread. + /// + public bool ReaderWatching; + + /// The newest action reply or error (any thread). + public string LatestResult => _latestResult; + + // Every character's balances on this server (IltBankRoster), built by the controller on the pump + // while the tab is on screen (the render thread marks it watched). + private volatile IltBankRosterRow[] _roster = Array.Empty(); + private long _rosterWatchedAt = long.MinValue / 2; + + /// Every character's balances on this server, logged-in one first (any thread). + public IltBankRosterRow[] Roster => _roster; + + /// Pump thread: the controller's latest roster. + public void PublishRoster(IltBankRosterRow[] rows) => _roster = rows ?? Array.Empty(); + + /// When the tab last drew the roster (any thread). + public long RosterWatchedAt => System.Threading.Interlocked.Read(ref _rosterWatchedAt); + + /// The roster is on screen: the controller keeps it fresh (render thread, or a test). + internal void MarkRosterWatched() => System.Threading.Interlocked.Exchange(ref _rosterWatchedAt, IltHubContext.NowMs); + + /// The transaction log as last published (any thread; oldest first). + public IReadOnlyList Transactions => _txSnapshot; + + /// The bank state (pump thread). + public IltBankState State => Bank; + + /// Raised (pump thread) after a balance line updates the state; Character rates use the deltas. + public event Action? BalanceChanged; + + public IltBanking(IltHubContext ctx) + { + _ctx = ctx; + _transactions = ctx.Store.LoadTransactions(); + PublishSnapshot(); + } + + private IltBankState Bank => _ctx.State.Bank; + public bool Enabled => _ctx.Options.IsOn(IltFeature.Bank); + + /// + /// True while a deposit or withdrawal is moving money between the pack and the bank (sent from + /// this tab or typed): session rates then re-baseline instead of counting it as income. Pump thread. + /// + public bool MovingMoney => IltHubContext.NowMs < _moveUntil; + + /// Exposed for the one-time UB import (mutated under the lock). + public void ImportUb(Func, string> importer) + { + string summary; + lock (_txLock) + { + summary = importer(_transactions); + _txDirty = true; + } + PublishSnapshot(); + RynthLog.Write(LogCat.IltBanking, $"[IltHub] UB sidecar import: {summary}"); + } + + // ── Commands ──────────────────────────────────────────────────────────── + + /// Queues a /bank balance refresh (eaten when ). + public void RequestRefresh(bool quiet) + { + RynthLog.Trace(LogCat.IltBanking, $"RequestRefresh(quiet={quiet})"); + if (_ctx.Capture.IsPending("/bank")) return; + long now = IltHubContext.NowMs; + if (now - _lastBalanceAt < BalanceSpacingMs) return; + _lastBalanceAt = now; + _quietBalanceUntil = quiet ? now + QuietBalanceWindowMs : 0; + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = "/bank", + IsResponseLine = t => t.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase), + IdleEndMs = 2000, + FirstLineTimeoutMs = 15000, + Eat = quiet, + OnComplete = r => + { + if (r.UnknownCommand) _ctx.Options.Set(IltFeature.Bank, IltTri.Off); + else if (r.Lines.Count > 0) _ctx.Options.Set(IltFeature.Bank, IltTri.On); + }, + }); + } + + /// + /// Validates and (after the UI confirm) sends a transfer. For trade notes + /// is the note count of . Pump thread. + /// Returns an error message, or empty when the command was queued. + /// + public string SendTransfer(int currencyIndex, long amount, string target, int denomination = -1) + { + RynthLog.Trace(LogCat.IltBanking, $"SendTransfer(currency={currencyIndex}, amount={amount}, denom={denomination}, target='{target}')"); + if (!Enabled) return "Bank is not available on this server."; + target = (target ?? string.Empty).Trim(); + // The recipient is spliced into a chat command, so only character-name characters are + // allowed: no '/', quotes, control characters or line breaks that could start a second command. + if (target.Length > 0 && !IltParse.CharacterName.IsMatch(target)) return "Recipient must be a character name (letters, spaces, ' and - only)."; + if (target.Equals(_ctx.CharName, StringComparison.OrdinalIgnoreCase)) return "You cannot transfer to yourself."; + string cmd = IltBankCommands.Transfer(currencyIndex, amount, denomination, target, out string error); + if (cmd.Length == 0) return error; + long now = IltHubContext.NowMs; + if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds."; + _lastBankCommandAt = now; + + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = cmd, + IsResponseLine = IltBankCommands.IsTransferReply, + IdleEndMs = 500, + FirstLineTimeoutMs = 8000, + Eat = false, + OnComplete = r => + { + _lastResult = r.Lines.Count > 0 ? r.Lines[^1] : (r.TimedOut ? "No reply from server." : string.Empty); + _latestResult = _lastResult; + // Balances changed: read them again shortly. + _refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs; + }, + }); + return string.Empty; + } + + /// + /// Sends a deposit ( index). Pump thread. Returns an + /// error message, or empty when the command was queued; the reply lands in the tab. + /// + public string SendDeposit(int index) + { + string cmd = IltBankCommands.Deposit(index); + if (cmd.Length == 0) return "Pick what to deposit."; + return SendAction(cmd, "Deposit"); + } + + /// + /// Sends a withdrawal ( index; for trade notes + /// is the note count). Pump thread; same result as SendDeposit. + /// + public string SendWithdraw(int index, long amount, int denomination) + { + string cmd = IltBankCommands.Withdraw(index, amount, denomination, out string error); + if (cmd.Length == 0) return error; + return SendAction(cmd, "Withdraw"); + } + + /// A deposit or withdrawal through the capture queue (shown, not eaten), then a quiet balance read. + private string SendAction(string cmd, string what) + { + RynthLog.Trace(LogCat.IltBanking, $"{what}: '{cmd}'"); + if (!Enabled) return "Bank is not available on this server."; + long now = IltHubContext.NowMs; + if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds."; + _lastBankCommandAt = now; + _moveUntil = now + MoveWindowMs; + _actionResult = what + " sent..."; + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = cmd, + IsResponseLine = IltBankCommands.IsActionReply, + IdleEndMs = 800, + FirstLineTimeoutMs = 8000, + Eat = false, + OnComplete = r => + { + _actionResult = r.Lines.Count > 0 ? string.Join("\n", r.Lines.TakeLast(6)) + : r.TimedOut ? "No reply from the server." : string.Empty; + _latestResult = _actionResult; + _refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs; + }, + }); + return string.Empty; + } + + /// + /// A bank verb line from "RynthILT.Data" BankCommand (Plugins/Shared/RynthIltDataApi.cs): + /// "refresh", "deposit i", "withdraw i amount note", "transfer i amount note name". The reader + /// has already confirmed a transfer with the player. Pump thread. Returns an error, or empty + /// when it was queued; either way the outcome shows in . + /// + public string RunVerb(string line) + { + string[] p = (line ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); + string err; + if (p.Length == 0) err = "Empty bank command."; + else if (p[0] == "refresh" && p.Length == 1) { RequestRefresh(quiet: true); return string.Empty; } + else if (p[0] == "deposit" && p.Length == 2 && int.TryParse(p[1], out int d)) err = SendDeposit(d); + else if (p[0] == "withdraw" && p.Length == 4 && int.TryParse(p[1], out int w) && long.TryParse(p[2], out long wa) + && int.TryParse(p[3], out int wn)) + err = SendWithdraw(w, wa, wn); + else if (p[0] == "transfer" && p.Length >= 5 && int.TryParse(p[1], out int c) && long.TryParse(p[2], out long ta) + && int.TryParse(p[3], out int tn)) + { + // The name may hold spaces; SendTransfer checks it is a character name. + string who = string.Join(' ', p, 4, p.Length - 4); + err = SendTransfer(c, ta, who, IltBankCommands.IsNoteTransfer(c) ? tn : -1); + if (err.Length == 0) _latestResult = "Transfer sent..."; + } + else err = "Unknown bank command."; + if (err.Length > 0) _latestResult = err; + RynthLog.Trace(LogCat.IltBanking, $"reader verb '{line}' -> {(err.Length > 0 ? err : "queued")}"); + return err; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + // Periodic quiet refresh only while the balances are on screen (the Hub, or a reader's + // Banking tab) and the server has /bank. + int every = Bank.AutoRefreshSeconds; + if (Enabled && (_ctx.WindowOpen || ReaderWatching) && every > 0 && nowMs - _lastAutoRefreshAt >= every * 1000L + && nowMs - _lastBalanceAt >= BalanceSpacingMs) + { + _lastAutoRefreshAt = nowMs; + RequestRefresh(quiet: true); + } + // The balance read a deposit, withdrawal or transfer asked for (retried until the spacing allows). + if (_refreshDueAt != 0 && nowMs >= _refreshDueAt && Enabled && nowMs - _lastBalanceAt >= BalanceSpacingMs) + { + _refreshDueAt = 0; + _lastAutoRefreshAt = nowMs; + RequestRefresh(quiet: true); + } + + if (_txDirty) + { + lock (_txLock) + { + _ctx.Store.SaveTransactionsIfDirty(_transactions); + _txDirty = false; + } + PublishSnapshot(); + } + } + + public bool OnChat(string text) + { + if (text.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase)) + { + bool dump = ParseBalanceLine(text); + // Eating is decided by the capture queue; this only backs it up for a quiet refresh's dump. + return EatLeakedDump(dump, IltHubContext.NowMs, _quietBalanceUntil); + } + // A deposit or withdrawal reply (ours or a typed /b): the next balance and pack changes are moves. + if (text.StartsWith("Deposited ", StringComparison.Ordinal) || text.StartsWith("Withdrew ", StringComparison.Ordinal)) + _moveUntil = Math.Max(_moveUntil, IltHubContext.NowMs + MoveWindowMs); + TryLogTransaction(text); + return false; + } + + public void OnLogout() + { + lock (_txLock) _ctx.Store.SaveTransactionsIfDirty(_transactions); + } + + // ── Parsing ───────────────────────────────────────────────────────────── + + /// + /// True when a quiet refresh's dump line that reached chat should be eaten here: it is a balance + /// line (see ) and a quiet refresh was queued within the window. + /// + internal static bool EatLeakedDump(bool isBalanceLine, long nowMs, long quietUntilMs) + => isBalanceLine && quietUntilMs != 0 && nowMs < quietUntilMs; + + /// The balance key a dump label belongs to ("Weakly Enlightened Coins" -> WeaklyEnlightenedCoins), or null. + internal static string? BalanceKeyFor(string label) + { + // Order matters: "Weakly Enlightened Coins" also contains "Enlightened Coins". + if (label.Contains("Prestige", StringComparison.OrdinalIgnoreCase)) return "PrestigeCoins"; + if (label.Contains("Weakly", StringComparison.OrdinalIgnoreCase)) return "WeaklyEnlightenedCoins"; + if (label.Contains("Enlightened", StringComparison.OrdinalIgnoreCase)) return "EnlightenedCoins"; + if (label.Contains("Mythical", StringComparison.OrdinalIgnoreCase)) return "MythicalKeys"; + if (label.Contains("Legendary", StringComparison.OrdinalIgnoreCase)) return "LegendaryKeys"; + if (label.Contains("Luminance", StringComparison.OrdinalIgnoreCase)) return "Luminance"; + if (label.Contains("Pyreal", StringComparison.OrdinalIgnoreCase)) return "Pyreals"; + return null; + } + + /// + /// True when a "[BANK] ..." line is part of the /bank balance dump: the "Your balances are:" header + /// or a "Label: N" line for a known currency. Errors, the bound-coin note and the like are not. + /// + internal static bool IsBalanceDumpLine(string text) + { + if (!text.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase)) return false; + string body = text.Substring("[BANK]".Length).Trim(); + if (body.StartsWith("Your balances", StringComparison.OrdinalIgnoreCase)) return true; + int colon = body.IndexOf(':'); + if (colon <= 0) return false; + if (body.Substring(colon + 1).Trim().Length == 0) return true; // a header ending in a colon + return BalanceKeyFor(body.Substring(0, colon).Trim()) != null; + } + + /// Reads a "[BANK] ..." line into the balances. Returns . + private bool ParseBalanceLine(string text) + { + if (!IsBalanceDumpLine(text)) return false; + string body = text.Substring("[BANK]".Length).Trim(); + int colon = body.IndexOf(':'); + if (colon <= 0 || body.Substring(colon + 1).Trim().Length == 0) return true; // a header: nothing to read + string label = body.Substring(0, colon).Trim(); + long value = IltParse.ParseLeadingLong(body.Substring(colon + 1)); + + switch (BalanceKeyFor(label)) + { + case "PrestigeCoins": Apply("PrestigeCoins", ref Bank.PrestigeCoins, value); break; + case "WeaklyEnlightenedCoins": Apply("WeaklyEnlightenedCoins", ref Bank.WeaklyEnlightenedCoins, value); break; + case "EnlightenedCoins": Apply("EnlightenedCoins", ref Bank.EnlightenedCoins, value); break; + case "MythicalKeys": Apply("MythicalKeys", ref Bank.MythicalKeys, value); break; + case "LegendaryKeys": Apply("LegendaryKeys", ref Bank.LegendaryKeys, value); break; + case "Luminance": Apply("Luminance", ref Bank.Luminance, value); break; + case "Pyreals": Apply("Pyreals", ref Bank.Pyreals, value); break; + default: return false; + } + + Bank.LastUpdated = DateTime.Now; + _ctx.Options.Set(IltFeature.Bank, IltTri.On); + return true; + } + + private void Apply(string key, ref long field, long value) + { + long old = field; + field = value; + if (old != value) + { + try { BalanceChanged?.Invoke(key, old, value); } catch { } + } + } + + private void TryLogTransaction(string text) + { + if (!(text.StartsWith("Transferred ", StringComparison.Ordinal) || text.StartsWith("Received ", StringComparison.Ordinal))) + return; + // Only server system lines are logged. Anything another player can author (tells, says, + // emotes, any bracketed channel) is rejected so quoted "Transferred ..." text can't + // forge entries in the transaction log. + if (IsPlayerAuthoredLine(text)) + { + RynthLog.Trace(LogCat.IltBanking, "transaction ignored (player-authored line): " + text); + return; + } + + var sent = IltParse.BankSent.Match(text); + var recv = sent.Success ? System.Text.RegularExpressions.Match.Empty : IltParse.BankReceived.Match(text); + var m = sent.Success ? sent : recv; + if (!m.Success) return; + + string other = IltParse.StripMarkup(m.Groups[3].Value).Replace(" (offline)", string.Empty).Trim(); + var tx = new IltBankTransaction + { + Timestamp = DateTime.Now, + Type = sent.Success ? "Sent" : "Received", + Amount = IltParse.ParseLeadingLong(m.Groups[1].Value), + Currency = m.Groups[2].Value.Trim(), + OtherPlayer = other, + Description = text, + }; + lock (_txLock) + { + _transactions.Add(tx); + if (_transactions.Count > IltHubStore.MaxTransactions) + _transactions.RemoveRange(0, _transactions.Count - IltHubStore.MaxTransactions); + _txDirty = true; + } + } + + /// True for chat another player could have written (tells, says, channel or emote markup). + private static bool IsPlayerAuthoredLine(string text) + => text.Contains(" RequestRefresh(quiet: true)); + ImGui.SameLine(); + if (ImGui.SmallButton("Copy##bank")) ImGui.SetClipboardText(BuildCopyLine()); + ImGui.SameLine(); + SafeImGui.TextDisabled(Bank.LastUpdated == DateTime.MinValue ? "never updated" : "updated " + Bank.LastUpdated.ToString("g")); + + if (ImGui.BeginTable("##iltbal", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV)) + { + Row("Pyreals", Bank.Pyreals); + Row("Luminance", Bank.Luminance); + Row("Legendary Keys", Bank.LegendaryKeys); + Row("Mythical Keys", Bank.MythicalKeys); + Row("Enlightened Coins", Bank.EnlightenedCoins); + Row("Weakly Enlightened Coins", Bank.WeaklyEnlightenedCoins); + Row("Prestige Coins", Bank.PrestigeCoins); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Bound to you: deposit and withdraw only, never transferred."); + ImGui.EndTable(); + } + + int refresh = Bank.AutoRefreshSeconds; + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Auto-refresh seconds (0 = off)", ref refresh, 30)) + Bank.AutoRefreshSeconds = refresh <= 0 ? 0 : Math.Max(30, refresh); + + RenderRoster(); + ImGui.Separator(); + RenderDepositWithdraw(); + ImGui.Separator(); + RenderTransferForm(); + ImGui.Separator(); + RenderTransactionLog(); + } + + /// + /// "Every character on this server": the balances RynthILT keeps for each character it has run here + /// (SilentKelpie's Banking tab, from RynthInventory 2026-10-21), with the totals. Only you: nothing more to show. + /// + private void RenderRoster() + { + MarkRosterWatched(); + IltBankRosterRow[] roster = _roster; + if (roster.Length <= 1) return; + if (!ImGui.CollapsingHeader($"Every character on this server ({roster.Length})##bankroster", ImGuiTreeNodeFlags.DefaultOpen)) return; + const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingStretchProp; + if (ImGui.BeginTable("##bankroster", 6, flags)) + { + ImGui.TableSetupColumn("Character", ImGuiTableColumnFlags.None, 1.3f); + ImGui.TableSetupColumn("Pyreals", ImGuiTableColumnFlags.None, 1.1f); + ImGui.TableSetupColumn("Luminance", ImGuiTableColumnFlags.None, 1.1f); + ImGui.TableSetupColumn("Keys L/M", ImGuiTableColumnFlags.None, 0.7f); + ImGui.TableSetupColumn("Coins E/W/P", ImGuiTableColumnFlags.None, 1.0f); + ImGui.TableSetupColumn("Updated", ImGuiTableColumnFlags.None, 0.8f); + ImGui.TableHeadersRow(); + DateTime now = DateTime.Now; + foreach (IltBankRosterRow r in roster) RosterRow(r.Current ? r.Name + " (you)" : r.Name, r, IltBankRoster.Age(r.Updated, now), false); + RosterRow("Total", IltBankRoster.Totals(roster), string.Empty, true); + ImGui.EndTable(); + } + ImGui.TextDisabled("Each character's last read balance; it updates when that character logs in with RynthILT."); + } + + private static void RosterRow(string name, IltBankRosterRow r, string updated, bool total) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + if (total) SafeImGui.TextColored(IltStyle.ColAmber, name); + else ImGui.TextUnformatted(name); + ImGui.TableNextColumn(); ImGui.TextUnformatted(IltParse.N0(r.Pyreals)); + ImGui.TableNextColumn(); ImGui.TextUnformatted(IltParse.N0(r.Luminance)); + ImGui.TableNextColumn(); ImGui.TextUnformatted($"{IltParse.N0(r.LegendaryKeys)}/{IltParse.N0(r.MythicalKeys)}"); + ImGui.TableNextColumn(); ImGui.TextUnformatted($"{IltParse.N0(r.EnlightenedCoins)}/{IltParse.N0(r.WeaklyEnlightenedCoins)}/{IltParse.N0(r.PrestigeCoins)}"); + ImGui.TableNextColumn(); if (updated.Length > 0) SafeImGui.TextDisabled(updated); + } + + private static void Row(string label, long value) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(label); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{IltParse.N0(value)} ({IltParse.Compact(value)})"); + } + + /// Deposit (one kind or everything, luminance tokens included) and withdraw (an amount, or trade notes). + private void RenderDepositWithdraw() + { + ImGui.TextColored(IltStyle.ColTeal, "Deposit"); + int dep = Math.Clamp(Bank.DepositIndex, 0, DepositNames.Length - 1); + ImGui.SetNextItemWidth(200); + if (ImGui.Combo("##bankdep", ref dep, DepositNames, DepositNames.Length)) Bank.DepositIndex = dep; + ImGui.SameLine(); + if (ImGui.Button("Deposit##bankdep")) + { + int index = dep; + _ctx.Post(() => { string err = SendDeposit(index); if (err.Length > 0) _actionResult = err; }); + } + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip(IltBankCommands.Deposit(dep) + "\nEverything banks all currencies, notes and luminance tokens." + + "\nThe server refuses while you are busy or moving."); + + ImGui.TextColored(IltStyle.ColTeal, "Withdraw"); + int wd = Math.Clamp(Bank.WithdrawIndex, 0, WithdrawNames.Length - 1); + ImGui.SetNextItemWidth(200); + if (ImGui.Combo("##bankwd", ref wd, WithdrawNames, WithdrawNames.Length)) Bank.WithdrawIndex = wd; + bool notes = IltBankCommands.Withdrawals[wd].Code == "n"; + int denom = Math.Clamp(Bank.WithdrawNoteIndex, 0, NoteNames.Length - 1); + if (notes) + { + ImGui.SameLine(); + ImGui.SetNextItemWidth(110); + if (ImGui.Combo("##bankwdnote", ref denom, NoteNames, NoteNames.Length)) Bank.WithdrawNoteIndex = denom; + } + ImGui.SetNextItemWidth(200); + ImGui.InputTextWithHint("##bankwdamt", notes ? "how many notes" : "amount, e.g. 250000, 1.5m", ref _withdrawText, 32u); + bool ok = IltParse.TryParseAmount(_withdrawText, out long amount); + ImGui.SameLine(); + ImGui.BeginDisabled(!ok); + if (ImGui.Button("Withdraw##bankwd")) + { + int index = wd, note = denom; + long amt = amount; + _ctx.Post(() => { string err = SendWithdraw(index, amt, note); if (err.Length > 0) _actionResult = err; }); + } + ImGui.EndDisabled(); + if (_withdrawText.Length > 0) + { + ImGui.SameLine(); + if (!ok) ImGui.TextColored(IltStyle.ColHp, "invalid amount"); + else if (notes) SafeImGui.TextDisabled("= " + IltParse.N0(amount * IltBankCommands.NoteDenominations[denom].Value) + " pyreals"); + else SafeImGui.TextDisabled("= " + IltParse.N0(amount)); + } + + string result = _actionResult; + if (result.Length > 0) SafeImGui.TextWrapped(result); + } + + private void RenderTransferForm() + { + ImGui.TextColored(IltStyle.ColTeal, "Transfer"); + int idx = Math.Clamp(Bank.TransferCurrencyIndex, 0, Currencies.Length - 1); + ImGui.SetNextItemWidth(200); + if (ImGui.Combo("Currency##xfer", ref idx, CurrencyNames, CurrencyNames.Length)) + Bank.TransferCurrencyIndex = idx; + bool notes = IltBankCommands.IsNoteTransfer(idx); + int denom = Math.Clamp(Bank.TransferNoteIndex, 0, NoteNames.Length - 1); + if (notes) + { + ImGui.SetNextItemWidth(200); + if (ImGui.Combo("Denomination##xfer", ref denom, NoteNames, NoteNames.Length)) Bank.TransferNoteIndex = denom; + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("The server moves the notes' pyreal value from your bank (/b t n )."); + } + + ImGui.SetNextItemWidth(200); + ImGui.InputTextWithHint("Amount##xfer", notes ? "how many notes" : "e.g. 250000, 1.5m, 2b", ref _amountText, 32u); + string target = Bank.TransferTarget; + ImGui.SetNextItemWidth(200); + if (ImGui.InputTextWithHint("Recipient##xfer", "character name", ref target, 64u)) + Bank.TransferTarget = target; + // Your other characters on this server, to fill the recipient with one click. + List others = IltBankRoster.Others(_roster); + if (others.Count > 0) + { + ImGui.SameLine(); + ImGui.SetNextItemWidth(150); + if (ImGui.BeginCombo("##xferpick", "Pick a character...")) + { + for (int i = 0; i < others.Count; i++) + if (ImGui.Selectable(others[i] + "##xferpick" + i)) Bank.TransferTarget = others[i]; + ImGui.EndCombo(); + } + } + + bool amountOk = IltParse.TryParseAmount(_amountText, out long amount); + if (_amountText.Length > 0) + { + ImGui.SameLine(); + if (!amountOk) ImGui.TextColored(IltStyle.ColHp, "invalid amount"); + else if (notes) SafeImGui.TextDisabled("= " + IltParse.N0(IltBankCommands.NoteValue(denom, amount)) + " pyreals"); + else SafeImGui.TextDisabled("= " + IltParse.N0(amount)); + } + + ImGui.BeginDisabled(!amountOk || string.IsNullOrWhiteSpace(Bank.TransferTarget)); + if (ImGui.Button("Send transfer...")) + { + int cur = idx, note = notes ? denom : -1; + long amt = amount; + string who = Bank.TransferTarget.Trim(); + string what = notes + ? $"{IltParse.N0(amt)} {IltBankCommands.NoteDenominations[denom].Label} trade notes ({IltParse.N0(IltBankCommands.NoteValue(denom, amt))} pyreals)" + : $"{IltParse.N0(amt)} {Currencies[cur].Name}"; + _ctx.Confirm("Confirm bank transfer", + $"Send {what} to {who}?\n\nThis cannot be undone.", + () => + { + string err = SendTransfer(cur, amt, who, note); + _lastResult = err.Length > 0 ? err : "Transfer sent..."; + }, + "Send"); + } + ImGui.EndDisabled(); + if (_lastResult.Length > 0) SafeImGui.TextWrapped(_lastResult); + } + + private void RenderTransactionLog() + { + var snap = _txSnapshot; + SafeImGui.TextColored(IltStyle.ColTeal, $"Transactions ({snap.Length})"); + ImGui.SameLine(); + ImGui.SetNextItemWidth(180); + ImGui.InputTextWithHint("##txfilter", "filter player / currency", ref _txFilter, 64u); + ImGui.SameLine(); + if (ImGui.SmallButton("Copy CSV")) ImGui.SetClipboardText(BuildCsv(snap)); + + if (ImGui.BeginTable("##ilttx", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.Resizable, + new Vector2(0, 220))) + { + ImGui.TableSetupScrollFreeze(0, 1); + ImGui.TableSetupColumn("When"); + ImGui.TableSetupColumn("Type"); + ImGui.TableSetupColumn("Amount"); + ImGui.TableSetupColumn("Currency"); + ImGui.TableSetupColumn("Player"); + ImGui.TableHeadersRow(); + for (int i = snap.Length - 1; i >= 0; i--) + { + var t = snap[i]; + if (_txFilter.Length > 0 + && !t.OtherPlayer.Contains(_txFilter, StringComparison.OrdinalIgnoreCase) + && !t.Currency.Contains(_txFilter, StringComparison.OrdinalIgnoreCase)) + continue; + ImGui.TableNextRow(); + ImGui.TableNextColumn(); ImGui.TextUnformatted(t.Timestamp.ToString("g")); + ImGui.TableNextColumn(); + SafeImGui.TextColored(t.Type == "Sent" ? IltStyle.ColAmber : IltStyle.ColGreen, t.Type); + ImGui.TableNextColumn(); ImGui.TextUnformatted(IltParse.N0(t.Amount)); + ImGui.TableNextColumn(); ImGui.TextUnformatted(t.Currency); + ImGui.TableNextColumn(); ImGui.TextUnformatted(t.OtherPlayer); + } + ImGui.EndTable(); + } + } + + /// One-line summary in UB's chat-paste format. + public string BuildCopyLine() + => $"Bank Balances - {_ctx.CharName} | P: {IltParse.N0(Bank.Pyreals)} | L: {IltParse.N0(Bank.Luminance)} | " + + $"LK: {IltParse.N0(Bank.LegendaryKeys)} | MK: {IltParse.N0(Bank.MythicalKeys)} | " + + $"Coins: {IltParse.N0(Bank.EnlightenedCoins)} | W Coins: {IltParse.N0(Bank.WeaklyEnlightenedCoins)} | " + + $"P Coins: {IltParse.N0(Bank.PrestigeCoins)} | " + + $"Updated: {(Bank.LastUpdated == DateTime.MinValue ? "never" : Bank.LastUpdated.ToString("g"))}"; + + private static string BuildCsv(IltBankTransaction[] rows) + { + var sb = new System.Text.StringBuilder("Timestamp,Type,Amount,Currency,Player\n"); + foreach (var t in rows) + sb.Append(t.Timestamp.ToString("s")).Append(',').Append(t.Type).Append(',').Append(t.Amount).Append(',') + .Append('"').Append(t.Currency.Replace("\"", "\"\"")).Append("\",\"") + .Append(t.OtherPlayer.Replace("\"", "\"\"")).Append("\"\n"); + return sb.ToString(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingEssence.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingEssence.cs new file mode 100644 index 0000000..a708eb3 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingEssence.cs @@ -0,0 +1,316 @@ +// IltBreedingEssence.cs - One carried combat pet essence, as the breeding tracker sees it. +// +// The facts come from the essence's appraisal (ACECustom [AssessmentProperty] qualities: bond 9053, +// male charges 9057, next breeding time float 9056, incense float 9058, neutered bool 9051, the +// male override 50053, juvenile 50054, Chromatic Catalyst 50055, the guardian's Offering 50056, +// maturity kills 9077, the mutation lines 9070..9075) and its LongDesc breeding block ("Sex: ...", +// "Growth: ...", "(shiny - cannot breed)"). Evaluate turns them into what the player needs to know: +// stud or dam, every breeding gate that fails, when it clears, growth, and the boosters applied. +// The gates are ACE PetDevice_Breeding's, with the thresholds from IltBreedingRules. +// +// Pure: no host calls (IltPetBreeding reads the host), so RynthILT.Tests checks it offline. +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// A gate's outcome for one essence. +internal enum BreedGate { Ready, Resting, NoCharges, Growing, Neutered, Shiny, LowBond, LowTier, NeedsId } + +/// What was read for one essence (host values; pump thread fills it). +internal sealed class BreedEssenceFacts +{ + public int Id; + public string Name = string.Empty; + public uint Wcid; + public bool HasId; + /// The essence's level requirement (a tier fallback for WCIDs outside the table). + public int UseLevel; + public int Bond; + /// The server's explicit sex (Tailoring Kit), or null to derive it from the object id. + public bool? MaleOverride; + public bool Neutered; + public bool JuvenileFlag; + /// PetMaturityKills: -1 when absent (the essence was never bred). + public int MaturityKills = -1; + /// PetMaleBreedingCharges: -1 when absent (a full stud). + public int MaleCharges = -1; + public double MaleRefreshUnix; + public double NextBreedUnix; + public double Incense; + public bool Catalyst; + public bool Offering; + public double MaturityXpMult; + public int MutDamage, MutDamageResist, MutCrit, MutVitality, MutPotency, MutationCount; + public int PotencyStored; + public bool Attuned; + public string LongDesc = string.Empty; +} + +/// One essence evaluated for breeding. Immutable; the UI and the reader JSON read it. +internal sealed record BreedEssence( + int Id, string Name, uint Wcid, bool HasId, int Tier, int Bond, bool Male, BreedGate Gate, string Status, + IReadOnlyList Problems, double ReadyAtUnix, int Charges, int ChargesMax, double RefillAtUnix, + bool Bred, bool Juvenile, int Stage, int Stages, string StageName, int Kills, int KillsRequired, int KillsToNext, + double Incense, bool Catalyst, bool Offering, bool Draught, IReadOnlyList Boosters, + int MutD, int MutDR, int MutC, int MutV, int MutP, bool Shiny, bool Unbound, int Potency) +{ + /// Every gate passes now. + public bool Ready => Gate == BreedGate.Ready; + /// The stat mutation lines (damage, damage resist, crit, vitality) summed. + public int StatMutations => MutD + MutDR + MutC + MutV; + /// "Stud" or "Dam". + public string Role => Male ? "Stud" : "Dam"; +} + +internal static class IltBreedingEssence +{ + /// Essence tiers, in the order of each family row below (ACE PetDeviceWcids petLevelIndexes). + public static readonly int[] Tiers = { 50, 80, 100, 125, 150, 180, 200, 250, 300 }; + + // ACECustom PetDeviceWcids: one row per combat pet family, tiers 50 .. 300 in order. "a-b" is a + // run of consecutive WCIDs. Rows copied from Source/ACE.Server/Factories/Tables/Wcids/PetDeviceWcids.cs. + private static readonly string[] FamilyRows = + { + "48942,48944,48945,48946,48947,48948,48956,787801001,787801037", + "49213-49219,787801002,787801038", + "49220-49226,787801003,787801039", + "49227-49232,49212,787801004,787801040", + "48972,49234-49239,787801005,787801041", + "49240-49246,787801006,787801042", + "49247-49253,787801007,787801043", + "49254-49259,49233,787801008,787801044", + "49421-49427,787801009,787801045", + "49428-49434,787801010,787801046", + "49435-49441,787801011,787801047", + "49442-49448,787801012,787801048", + "48959,48961,48963,48965,48967,48969,48957,787801013,787801049", + "49261-49267,787801014,787801050", + "49268-49274,787801015,787801051", + "49275-49280,49260,787801016,787801052", + "49282-49287,49281,787801017,787801053", + "49289-49294,49288,787801018,787801054", + "49296-49301,49295,787801019,787801055", + "49303-49308,49302,787801020,787801056", + "49310-49316,787801021,787801057", + "49317-49323,787801022,787801058", + "49324-49330,787801023,787801059", + "49331-49336,49309,787801024,787801060", + "49338-49344,787801025,787801061", + "49345-49351,787801026,787801062", + "49352-49358,787801027,787801063", + "49359-49364,49337,787801028,787801064", + "49366-49372,787801029,787801065", + "49373-49379,787801030,787801066", + "49380-49386,787801031,787801067", + "49387-49392,49365,787801032,787801068", + "49524-49530,787801033,787801069", + "49531-49537,787801034,787801070", + "49538-49544,787801035,787801071", + "49545-49551,787801036,787801072", + }; + + /// Each family row expanded (tests check every row has one WCID per tier). + internal static readonly uint[][] Families = Array.ConvertAll(FamilyRows, ExpandRow); + + private static readonly Dictionary TierByWcid = BuildTiers(); + + private static uint[] ExpandRow(string row) + { + var list = new List(9); + foreach (string token in row.Split(',')) + { + int dash = token.IndexOf('-'); + if (dash < 0) { list.Add(uint.Parse(token, CultureInfo.InvariantCulture)); continue; } + uint a = uint.Parse(token.AsSpan(0, dash), NumberStyles.Integer, CultureInfo.InvariantCulture); + uint b = uint.Parse(token.AsSpan(dash + 1), NumberStyles.Integer, CultureInfo.InvariantCulture); + for (uint w = a; w <= b; w++) list.Add(w); + } + return list.ToArray(); + } + + private static Dictionary BuildTiers() + { + var d = new Dictionary(); + foreach (uint[] row in Families) + for (int i = 0; i < row.Length && i < Tiers.Length; i++) + d[row[i]] = Tiers[i]; + return d; + } + + /// True for a combat pet essence WCID (the only kind that breeds). + public static bool IsCombatEssence(uint wcid) => TierByWcid.ContainsKey(wcid); + + /// The essence tier for a WCID, else the level requirement when it is a tier, else 0. + public static int TierOf(uint wcid, int useLevel = 0) + { + if (TierByWcid.TryGetValue(wcid, out int t)) return t; + return Array.IndexOf(Tiers, useLevel) >= 0 ? useLevel : 0; + } + + /// ACE PetDevice.IsMale without an override: murmur3 fmix32 on the object id, even = male. + public static bool DeriveIsMale(int objectId) + { + uint h = unchecked((uint)objectId); + h ^= h >> 16; + h = unchecked(h * 0x7feb352d); + h ^= h >> 15; + h = unchecked(h * 0x846ca68b); + h ^= h >> 16; + return (h & 1) == 0; + } + + /// "3h 05m", "42m", "20s" (0 or less = "now"). + public static string Duration(double seconds) + { + if (seconds <= 0) return "now"; + long s = (long)Math.Ceiling(seconds); + if (s >= 3600) return $"{s / 3600}h {s % 3600 / 60:00}m"; + if (s >= 60) return $"{s / 60}m"; + return $"{s}s"; + } + + /// + /// Evaluates one essence: role, every failing gate (the first is the headline), the ready time, + /// growth and boosters. is unix seconds. + /// + public static BreedEssence Evaluate(BreedEssenceFacts f, IltBreedingRules r, double nowUnix) + { + string desc = f.LongDesc ?? string.Empty; + bool male = f.MaleOverride ?? DeriveIsMale(f.Id); + int tier = TierOf(f.Wcid, f.UseLevel); + int bond = Math.Max(1, f.Bond); + bool shiny = desc.Contains("(shiny - cannot breed)", StringComparison.OrdinalIgnoreCase); + bool bred = f.MaturityKills >= 0; + bool juvenile = f.JuvenileFlag || desc.Contains("cannot breed yet", StringComparison.OrdinalIgnoreCase); + + // Stud charges refill lazily on the server: full again once the refill time has passed. + int max = Math.Max(0, r.GetInt(IltBreedingRules.MaleCharges)); + int charges = f.MaleCharges < 0 ? max : Math.Min(f.MaleCharges, max); + double refillAt = 0; + double refillH = r.Get(IltBreedingRules.MaleRefillHours); + if (male && f.MaleRefreshUnix > 0 && refillH > 0) + { + refillAt = f.MaleRefreshUnix + refillH * 3600.0; + if (nowUnix >= refillAt) { charges = max; refillAt = 0; } + } + if (male && charges >= max) refillAt = 0; + + // Growth (bred essences only): stage from credited kills, as ACE PetDevice_Maturity. + int required = Math.Max(1, r.GetInt(IltBreedingRules.MaturityKills)); + int stages = Math.Max(1, r.GetInt(IltBreedingRules.MaturityStages)); + int kills = Math.Max(0, f.MaturityKills); + int perStage = Math.Max(1, (int)Math.Ceiling(required / (double)stages)); + int stage = juvenile ? Math.Min(stages, kills / perStage + 1) : stages + 1; + int toNext = juvenile ? Math.Max(0, Math.Min(required, stage * perStage) - kills) : 0; + string stageName = juvenile ? r.StageName(stage) : bred ? "Adult" : string.Empty; + if (juvenile && IltBreedingRules.TryParseGrowth(desc, out string seenName, out int seenStage, out _, out int seenNext, out _, out int seenAdult)) + { + // The appraisal line is the server's own math: prefer it when it is there. + stage = seenStage; + stageName = seenName; + toNext = seenNext; + kills = Math.Max(kills, required - seenAdult); + } + + // Every failing gate, in the order the server checks them. + var problems = new List(); + BreedGate gate = BreedGate.Ready; + void Fail(BreedGate g, string text) + { + if (gate == BreedGate.Ready) gate = g; + problems.Add(text); + } + double readyAt = 0; + if (!f.HasId) Fail(BreedGate.NeedsId, "not appraised yet"); + if (f.Neutered) Fail(BreedGate.Neutered, "neutered (permanent)"); + if (shiny) Fail(BreedGate.Shiny, "shiny essences can't breed"); + if (juvenile) Fail(BreedGate.Growing, $"still growing: {stageName} ({Math.Max(0, required - kills)} kills to Adult)"); + int minTier = r.GetInt(IltBreedingRules.MinTier); + if (tier > 0 && tier < minTier) Fail(BreedGate.LowTier, $"tier {tier} (needs {minTier}+)"); + int minBond = r.GetInt(IltBreedingRules.MinBond); + if (f.HasId && bond < minBond) Fail(BreedGate.LowBond, $"bond {bond}/{minBond}"); + if (male && charges <= 0) + { + Fail(BreedGate.NoCharges, refillAt > 0 ? $"no charges (refill in {Duration(refillAt - nowUnix)})" : "no charges left"); + readyAt = Math.Max(readyAt, refillAt); + } + if (!male && f.NextBreedUnix > nowUnix) + { + Fail(BreedGate.Resting, $"resting ({Duration(f.NextBreedUnix - nowUnix)})"); + readyAt = Math.Max(readyAt, f.NextBreedUnix); + } + + string status = gate switch + { + BreedGate.Ready => male ? $"Ready ({charges}/{max})" : "Ready", + BreedGate.Resting => "Rest " + Duration(f.NextBreedUnix - nowUnix), + BreedGate.NoCharges => refillAt > 0 ? "0/" + max + " refill " + Duration(refillAt - nowUnix) : "0/" + max, + BreedGate.Growing => $"{stageName} {Math.Min(stage, stages)}/{stages}", + BreedGate.Neutered => "Neutered", + BreedGate.Shiny => "Shiny", + BreedGate.LowBond => $"Bond {bond}/{minBond}", + BreedGate.LowTier => $"Tier {tier}", + _ => "ID needed", + }; + + bool draught = f.MaturityXpMult > 1.0001; + var boosters = new List(4); + if (f.Incense > 0) boosters.Add(IltBreedingSupplies.IncenseName(f.Incense)); + if (f.Catalyst) boosters.Add("Chromatic Catalyst"); + if (f.Offering) boosters.Add("Offering of Subjugation"); + if (draught) boosters.Add("Nurturing Draught x" + f.MaturityXpMult.ToString("0.#", CultureInfo.InvariantCulture)); + + return new BreedEssence( + f.Id, f.Name, f.Wcid, f.HasId, tier, bond, male, gate, status, problems, readyAt, + male ? charges : 0, male ? max : 0, male ? refillAt : 0, + bred, juvenile, juvenile ? stage : 0, stages, stageName, kills, required, toNext, + Math.Max(0, f.Incense), f.Catalyst, f.Offering, draught, boosters, + Math.Max(0, f.MutDamage), Math.Max(0, f.MutDamageResist), Math.Max(0, f.MutCrit), Math.Max(0, f.MutVitality), + Math.Max(0, f.MutPotency), shiny, bred && !f.Attuned && desc.Contains("Bond: Unbound", StringComparison.OrdinalIgnoreCase), + Math.Max(0, f.PotencyStored)); + } +} + +/// What a stud + dam pairing would do: the gates both must pass, and the baby's odds. +internal sealed record BreedPairPlan(bool CanBreed, IReadOnlyList Blockers, double Incense, double ChanceBest, double ChanceWorst, + double PotencyChance, int InheritMin, int InheritMax, IReadOnlyList Notes); + +internal static class IltBreedingPlanner +{ + /// + /// Plans one pairing. Each stat line comes from one parent, so the baby inherits between the + /// sum of the lower lines and the sum of the higher lines; more inherited mutations lower the + /// stat mutation chance (the decay), so the best case is the fewest. + /// + public static BreedPairPlan Plan(BreedEssence stud, BreedEssence dam, IltBreedingRules r) + { + var blockers = new List(); + if (!stud.Male) blockers.Add($"{stud.Name} is female: the stud must be male."); + if (dam.Male) blockers.Add($"{dam.Name} is male: the dam must be female."); + if (stud.Id == dam.Id) blockers.Add("Pick two different essences."); + foreach (string p in stud.Problems) blockers.Add($"{stud.Name}: {p}"); + foreach (string p in dam.Problems) blockers.Add($"{dam.Name}: {p}"); + + int lo = Math.Min(stud.MutD, dam.MutD) + Math.Min(stud.MutDR, dam.MutDR) + Math.Min(stud.MutC, dam.MutC) + Math.Min(stud.MutV, dam.MutV); + int hi = Math.Max(stud.MutD, dam.MutD) + Math.Max(stud.MutDR, dam.MutDR) + Math.Max(stud.MutC, dam.MutC) + Math.Max(stud.MutV, dam.MutV); + double incense = r.CombinedIncense(stud.Incense, dam.Incense); + + var notes = new List + { + "The baby goes to the dam's owner: they need a free main-pack slot and burden room.", + $"Both pets in the same room of the breeding area ({r.RoomText()}); both owners *dance* within {r.Get(IltBreedingRules.DanceWindow):0.#}s.", + }; + if (stud.Catalyst || dam.Catalyst) notes.Add("Chromatic Catalyst: the baby rolls a fresh colour."); + if (r.Get(IltBreedingRules.GuardianEnabled) >= 0.5) + notes.Add(stud.Offering || dam.Offering + ? "Offering of Subjugation applied: the mating guardian comes weakened." + : $"A mating guardian rises: kill it within {r.Get(IltBreedingRules.GuardianSeconds):0}s for an Awakened Blessing mutation."); + if (incense > 0) notes.Add($"Incense +{incense * 100:0.#}% is used up by this breed."); + + return new BreedPairPlan(blockers.Count == 0, blockers, incense, + r.StatMutationChance(lo, incense), r.StatMutationChance(hi, incense), + Math.Clamp(r.Get(IltBreedingRules.PotencyMutation), 0, 1), lo, hi, notes); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingRules.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingRules.cs new file mode 100644 index 0000000..6ed05f8 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingRules.cs @@ -0,0 +1,445 @@ +// IltBreedingRules.cs - Infinite Leaftide's pet breeding rules as RynthILT knows them. +// +// ACECustom's breeding (Source/ACE.Server/WorldObjects/PetDevice_Breeding.cs, docs/PET_BREEDING_*.md) +// is driven by ServerConfig values the client is never sent. Each rule here therefore has three +// possible sources, best last: +// * ACE default - the ServerConfig default in ACECustom; +// * ILT profile - what Infinite Leaftide runs (deploy/PROD_DEPLOY_PLAN.md: decay 0.1, the +// mating guardian on, pet bond on, the Seedy Motel room); +// * seen on server - read back from this server's own text: the appraisal breeding block +// ("Sex: Male (9/10 breeding charges today) - refills in 3h 10m", "Growth: ..."), +// "@breed-debug" ("Allowed Target: whole landblock 0x106, Variant=2"), and +// breeding chat ("spent a breeding charge: 9/10 left today", "They have 90s ..."). +// A value seen on the server is saved with the character (IltPetState.Breeding) and wins from then on. +// +// Pure: no host calls, so RynthILT.Tests checks every parser offline. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// Where a breeding rule's value came from (later = more trusted). +internal enum BreedRuleSource { AceDefault = 0, IltProfile = 1, Server = 2 } + +/// One rule: stable key, label, unit, the ACE default and the ILT profile value (null = same as ACE). +internal sealed record BreedRuleDef(string Key, string Label, string Unit, double AceDefault, double? IltProfile, string Help); + +/// A rule's effective value and where it came from. +internal readonly record struct BreedRuleValue(BreedRuleDef Def, double Value, BreedRuleSource Source, DateTime SeenUtc); + +/// A value this server showed, saved with the character. +public sealed class IltLearnedRule +{ + public string Key = string.Empty; + public double Value; + public DateTime SeenUtc; +} + +/// One breeding event from chat (ritual, birth, growth, ...), newest last. +public sealed class IltBreedingEvent +{ + public DateTime Utc; + /// ritual, charge, birth, mutation, guardian, growth, adult, imprint, dance, debug. + public string Kind = string.Empty; + public string Text = string.Empty; +} + +/// The breeding tracker's saved part (IltPetState.Breeding). +public sealed class IltBreedingState +{ + /// Rules read back from this server (see IltBreedingRules). + public List Rules = new(); + /// Growth stage names this server uses, by stage (index 0 = stage 1); "" = not seen yet. + public List StageNames = new(); + /// Recent breeding events (capped at IltBreedingRules.MaxEvents). + public List Log = new(); + /// The last "@breed-debug" reply's lines and when it came. + public List LastDebug = new(); + public DateTime LastDebugUtc; +} + +/// What one "@breed-debug" reply said. +internal sealed record BreedDebugInfo(bool? Enabled, string Location, uint AllowedLandblock, int AllowedVariant, string AllowedKind, + bool? LocationOk, string ActivePet, string PetSex, int Partners); + +internal sealed class IltBreedingRules +{ + // ── Rule keys ─────────────────────────────────────────────────────────── + public const string Landblock = "landblock"; + public const string Variant = "variant"; + public const string DanceWindow = "dance_window_s"; + public const string MinTier = "min_tier"; + public const string MinBond = "min_bond"; + public const string MaleCharges = "male_charges"; + public const string MaleRefillHours = "male_refill_h"; + public const string FemaleRestHours = "female_rest_h"; + public const string BaseMutation = "base_mutation"; + public const string MutationDecay = "mutation_decay"; + public const string MutationFloor = "mutation_floor"; + public const string PotencyMutation = "potency_mutation"; + public const string IncenseCap = "incense_cap"; + public const string Inheritance = "inheritance"; + public const string GuardianEnabled = "guardian_enabled"; + public const string GuardianSeconds = "guardian_s"; + public const string MaturityKills = "maturity_kills"; + public const string MaturityStages = "maturity_stages"; + public const string MaturityShare = "maturity_share"; + + /// Breeding events kept with the character. + public const int MaxEvents = 60; + + /// ACECustom's default growth stage names (pet_maturity_stage_names). + public static readonly string[] DefaultStageNames = { "Newborn", "Whelp", "Juvenile", "Adolescent", "Young Adult" }; + + /// Every rule shown, in display order. Values copied from ACECustom ServerConfig and the ILT deploy plan. + public static readonly BreedRuleDef[] Defs = + { + new(Landblock, "Breeding room landblock", "hex", 0x0106, null, + "pet_breeding_allowed_landblock: the Seedy Motel (Ruggan's Annex, portal by Prof. Ruggan in Lin 54.7S 73.5E)."), + new(Variant, "Breeding room variant", "", 2, null, "pet_breeding_allowed_variant: the landblock variant the room is in."), + new(DanceWindow, "Dance window", "s", 5, null, "Both owners must *dance* (or @dance) within this many seconds."), + new(MinTier, "Minimum essence tier", "", 100, null, "Both parents must be at least this tier (50, 80, 100, ... 300)."), + new(MinBond, "Minimum bond", "", 100, null, "Both parents need this bond level (bond grows from kills; pet_bond must be on)."), + new(MaleCharges, "Stud charges", "", 10, null, "pet_breeding_male_max_charges: breeds a male can sire per refill."), + new(MaleRefillHours, "Stud refill", "h", 24, null, "pet_breeding_male_charge_reset_hours: charges refill this long after the last refill."), + new(FemaleRestHours, "Dam rest", "h", 4, null, "A female rests this long after each breed before she can breed again."), + new(BaseMutation, "Stat mutation chance", "%", 0.05, null, "pet_breeding_mutation_chance: the base chance of a stat mutation."), + new(MutationDecay, "Mutation decay", "", 0.0, 0.1, + "pet_breeding_mutation_decay: each stat mutation the baby inherits divides the chance by (1 + decay x mutations)."), + new(MutationFloor, "Mutation floor", "%", 0.02, null, "The stat mutation chance never drops below this."), + new(PotencyMutation, "Potency mutation chance", "%", 0.03, null, "An independent roll for a potency mutation."), + new(IncenseCap, "Incense cap", "%", 0.50, null, "Both parents' incense together adds at most this much."), + new(Inheritance, "Dominant line weight", "%", 0.55, null, "Each stat line comes from one parent, 55 / 45."), + new(GuardianEnabled, "Mating guardian", "on/off", 0, 1, + "pet_breeding_guardian_enabled: a spirit rises after the ritual; killing it in time grants an Awakened Blessing mutation."), + new(GuardianSeconds, "Guardian timer", "s", 90, null, "How long the two parents have to kill the guardian."), + new(MaturityKills, "Kills to adulthood", "", 300, null, "pet_maturity_kills_required: a bred baby grows up with this many credited kills."), + new(MaturityStages, "Growth stages", "", 5, null, "pet_maturity_stages: the growth stages before Adult."), + new(MaturityShare, "Kill credit share", "%", 0.10, null, + "A kill counts when the pet dealt this share of the victim's health and the victim's level is at least the essence tier."), + }; + + private static readonly Dictionary DefByKey = BuildIndex(); + + private static Dictionary BuildIndex() + { + var d = new Dictionary(StringComparer.Ordinal); + foreach (BreedRuleDef def in Defs) d[def.Key] = def; + return d; + } + + private readonly IltBreedingState _state; + + /// The saved breeding state; learned values are read from and written to it. + public IltBreedingRules(IltBreedingState state) => _state = state; + + /// The saved state these rules read and update. + public IltBreedingState State => _state; + + /// A copy that never changes (the render thread reads it while the pump learns). + public IltBreedingRules Frozen() + { + var copy = new IltBreedingState { StageNames = new List(_state.StageNames) }; + foreach (IltLearnedRule l in _state.Rules) + copy.Rules.Add(new IltLearnedRule { Key = l.Key, Value = l.Value, SeenUtc = l.SeenUtc }); + return new IltBreedingRules(copy); + } + + /// The effective value of rule (0 for an unknown key). + public double Get(string key) => Value(key).Value; + + /// A whole-number rule (charges, kills, tiers). + public int GetInt(string key) => (int)Math.Round(Get(key)); + + /// The effective value and its source. + public BreedRuleValue Value(string key) + { + if (!DefByKey.TryGetValue(key, out BreedRuleDef? def)) + return new BreedRuleValue(new BreedRuleDef(key, key, "", 0, null, ""), 0, BreedRuleSource.AceDefault, default); + foreach (IltLearnedRule l in _state.Rules) + if (l.Key == key) return new BreedRuleValue(def, l.Value, BreedRuleSource.Server, l.SeenUtc); + return def.IltProfile.HasValue + ? new BreedRuleValue(def, def.IltProfile.Value, BreedRuleSource.IltProfile, default) + : new BreedRuleValue(def, def.AceDefault, BreedRuleSource.AceDefault, default); + } + + /// Every rule's effective value, in display order. + public List All() + { + var list = new List(Defs.Length); + foreach (BreedRuleDef d in Defs) list.Add(Value(d.Key)); + return list; + } + + /// Records a value the server showed. True when it changed what RynthILT knew. + public bool Learn(string key, double value, DateTime utc) + { + if (!DefByKey.ContainsKey(key) || double.IsNaN(value) || double.IsInfinity(value)) return false; + foreach (IltLearnedRule l in _state.Rules) + { + if (l.Key != key) continue; + bool changed = Math.Abs(l.Value - value) > 1e-9; + l.Value = value; + l.SeenUtc = utc; + return changed; + } + _state.Rules.Add(new IltLearnedRule { Key = key, Value = value, SeenUtc = utc }); + return true; + } + + /// Applies every (key, value) an observer returned. True when anything changed. + public bool LearnAll(IEnumerable<(string Key, double Value)> seen, DateTime utc) + { + bool changed = false; + foreach ((string k, double v) in seen) changed |= Learn(k, v, utc); + return changed; + } + + /// Records a growth stage's name (1-based) as the server spelled it. + public bool LearnStageName(int stage, string name) + { + name = (name ?? string.Empty).Trim(); + if (stage < 1 || stage > 50 || name.Length == 0 || name.Length > 40) return false; + while (_state.StageNames.Count < stage) _state.StageNames.Add(string.Empty); + if (_state.StageNames[stage - 1] == name) return false; + _state.StageNames[stage - 1] = name; + return true; + } + + /// The name of growth stage (1-based): seen on the server, else ACE's default, else "Stage N". + public string StageName(int stage) + { + if (stage >= 1 && stage <= _state.StageNames.Count && _state.StageNames[stage - 1].Length > 0) + return _state.StageNames[stage - 1]; + if (stage >= 1 && stage <= DefaultStageNames.Length && GetInt(MaturityStages) == DefaultStageNames.Length) + return DefaultStageNames[stage - 1]; + return "Stage " + stage.ToString(CultureInfo.InvariantCulture); + } + + /// Appends an event, dropping the oldest past . + public void AddEvent(string kind, string text, DateTime utc) + { + _state.Log.Add(new IltBreedingEvent { Utc = utc, Kind = kind, Text = text }); + if (_state.Log.Count > MaxEvents) _state.Log.RemoveRange(0, _state.Log.Count - MaxEvents); + } + + // ── Mutation odds (ACE PetDevice_Breeding) ────────────────────────────── + + /// + /// The chance of a stat mutation for a baby that inherits + /// stat mutations, with from both parents (already capped): + /// clamp(max(floor, (base + incense) / (1 + decay x mutations)), 0, 1). + /// + public double StatMutationChance(int babyStatMutations, double incense) + { + double decay = Math.Max(0, Get(MutationDecay)); + double raw = (Get(BaseMutation) + Math.Max(0, incense)) / (1.0 + decay * Math.Max(0, babyStatMutations)); + return Math.Clamp(Math.Max(Get(MutationFloor), raw), 0.0, 1.0); + } + + /// Both parents' incense together, capped at the incense cap. + public double CombinedIncense(double a, double b) => Math.Clamp(Math.Max(0, a) + Math.Max(0, b), 0.0, Math.Max(0, Get(IncenseCap))); + + // ── Observers: what the server's own text says about its rules ────────── + + private const RegexOptions Rx = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; + + private static readonly Regex MaleLine = new(@"Sex:\s*Male\s*\((\d+)\s*/\s*(\d+) breeding charges today\)(?:\s*-\s*refills in (?:(\d+)h\s*)?(?:(\d+)m)?)?", Rx); + private static readonly Regex GrowthLine = new(@"Growth:\s*(.+?)\s+(\d+)\s*/\s*(\d+)\s*-\s*(\d+) kills to (.+?)(?:,\s*(\d+) to Adult)?\s*$", Rx | RegexOptions.Multiline); + private static readonly Regex ChargeSpent = new(@"spent a breeding charge:\s*(\d+)\s*/\s*(\d+) left today", Rx); + private static readonly Regex GuardianRise = new(@"They have (\d+)s to bring it down together", Rx); + private static readonly Regex GrownInto = new(@"has grown into an? (.+?)!.*\((\d+)\s*/\s*(\d+)\)", Rx); + private static readonly Regex DanceWindowLine = new(@"\*dance\* within (\d+(?:\.\d+)?) seconds", Rx); + private static readonly Regex DebugEnabled = new(@"Breeding System Enabled:\s*(True|False)", Rx); + private static readonly Regex DebugLocation = new(@"Your Location:\s*(.+)$", Rx); + private static readonly Regex DebugAllowed = new(@"Allowed Target:\s*(anywhere|whole landblock|exact cell)\s*0x([0-9A-F]+),\s*Variant=(-?\d+)\s*=>\s*Location Match:\s*(VALID|INVALID)", Rx); + private static readonly Regex DebugPet = new(@"Your Active Pet:\s*(.+)$", Rx); + private static readonly Regex DebugSex = new(@"^\s*Sex:\s*(.+)$", Rx); + private static readonly Regex DebugPartners = new(@"(?:Eligible breeding partners nearby|Valid Partner Candidates within 30m):\s*(\d+)", Rx); + + /// + /// What an essence's appraisal text says: the stud's charge max and refill window (from the + /// "refills in" countdown against the essence's last refill time), and the growth stage count. + /// + /// The appraisal LongDesc (string 16). + /// The essence's PetMaleChargesRefreshTime (0 = not sent). + /// Now, unix seconds. + public static List<(string Key, double Value)> FromAppraisal(string longDesc, double maleRefreshUnix, double nowUnix) + { + var seen = new List<(string, double)>(); + if (string.IsNullOrEmpty(longDesc)) return seen; + + Match m = MaleLine.Match(longDesc); + if (m.Success) + { + if (int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int max) && max > 0 && max < 1000) + seen.Add((MaleCharges, max)); + if ((m.Groups[3].Success || m.Groups[4].Success) && maleRefreshUnix > 0) + { + int h = m.Groups[3].Success ? int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture) : 0; + int min = m.Groups[4].Success ? int.Parse(m.Groups[4].Value, CultureInfo.InvariantCulture) : 0; + double refillAt = nowUnix + h * 3600.0 + min * 60.0; + double hours = Math.Round((refillAt - maleRefreshUnix) / 3600.0); + // The countdown is minute-rounded; only a whole-hour window that makes sense is taken. + if (hours >= 1 && hours <= 24 * 14) seen.Add((MaleRefillHours, hours)); + } + } + + Match g = GrowthLine.Match(longDesc); + if (g.Success && int.TryParse(g.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int stages) && stages >= 1 && stages <= 50) + seen.Add((MaturityStages, stages)); + return seen; + } + + /// + /// The growth line of an appraisal: current stage name, stage, stages, kills to the next stage + /// and to adulthood (-1 when the line has no "to Adult" part, i.e. the last stage). + /// + public static bool TryParseGrowth(string longDesc, out string stageName, out int stage, out int stages, out int toNext, out string nextName, out int toAdult) + { + stageName = nextName = string.Empty; + stage = stages = toNext = toAdult = 0; + if (string.IsNullOrEmpty(longDesc)) return false; + Match g = GrowthLine.Match(longDesc); + if (!g.Success) return false; + stageName = g.Groups[1].Value.Trim(); + int.TryParse(g.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stage); + int.TryParse(g.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stages); + int.TryParse(g.Groups[4].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out toNext); + nextName = g.Groups[5].Value.Trim(); + if (g.Groups[6].Success) int.TryParse(g.Groups[6].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out toAdult); + else { toAdult = toNext; nextName = "Adult"; } + return true; + } + + /// What one chat line says about the rules (a line can say nothing). + public static List<(string Key, double Value)> FromChat(string line) + { + var seen = new List<(string, double)>(); + if (string.IsNullOrEmpty(line)) return seen; + + Match m = ChargeSpent.Match(line); + if (m.Success && int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int max) && max > 0 && max < 1000) + seen.Add((MaleCharges, max)); + + m = GuardianRise.Match(line); + if (m.Success) + { + seen.Add((GuardianEnabled, 1)); + if (int.TryParse(m.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int s) && s > 0 && s < 3600) + seen.Add((GuardianSeconds, s)); + } + else if (line.Contains("The union stirs something", StringComparison.OrdinalIgnoreCase)) + seen.Add((GuardianEnabled, 1)); + + m = GrownInto.Match(line); + if (m.Success && int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int stages) && stages >= 1 && stages <= 50) + seen.Add((MaturityStages, stages)); + + m = DanceWindowLine.Match(line); + if (m.Success && double.TryParse(m.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double w) && w > 0 && w < 600) + seen.Add((DanceWindow, w)); + + foreach (string part in line.Split('\n')) + { + m = DebugAllowed.Match(part); + if (!m.Success) continue; + if (uint.TryParse(m.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint lb)) + seen.Add((Landblock, lb)); + if (int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v)) + seen.Add((Variant, v)); + } + return seen; + } + + /// The stage name a "has grown into a Whelp! ... (2/5)" line gives, with its stage number; false for any other line. + public static bool TryParseGrownInto(string line, out int stage, out string name) + { + stage = 0; + name = string.Empty; + Match m = GrownInto.Match(line ?? string.Empty); + if (!m.Success || !int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stage)) return false; + name = m.Groups[1].Value.Trim(); + return name.Length > 0; + } + + /// True for any line of an "@breed-debug" reply (one multi-line message, or its lines one by one). + public static bool IsDebugLine(string text) + { + if (string.IsNullOrEmpty(text)) return false; + return text.Contains("PET BREEDING DIAGNOSTICS", StringComparison.OrdinalIgnoreCase) + || DebugEnabled.IsMatch(text) || DebugLocation.IsMatch(text) || DebugAllowed.IsMatch(text) + || DebugPet.IsMatch(text) || DebugPartners.IsMatch(text) + || text.TrimStart().StartsWith("Sex:", StringComparison.OrdinalIgnoreCase) + || text.Contains("Ensure your partner has their pet summoned", StringComparison.OrdinalIgnoreCase) + || IsDebugEnd(text); + } + + /// The reply's closing rule of '=' (alone, or ending the whole message). + public static bool IsDebugEnd(string text) + => !string.IsNullOrEmpty(text) && text.TrimEnd().EndsWith("================================", StringComparison.Ordinal); + + /// Parses an "@breed-debug" reply (any mix of whole messages and single lines). + public static BreedDebugInfo ParseDebug(IEnumerable lines) + { + bool? enabled = null, ok = null; + string location = string.Empty, kind = string.Empty, pet = string.Empty, sex = string.Empty; + uint lb = 0; + int variant = -1, partners = -1; + foreach (string text in lines) + { + foreach (string raw in (text ?? string.Empty).Split('\n')) + { + string l = raw.TrimEnd('\r'); + Match m; + if ((m = DebugEnabled.Match(l)).Success) enabled = m.Groups[1].Value.Equals("True", StringComparison.OrdinalIgnoreCase); + else if ((m = DebugAllowed.Match(l)).Success) + { + kind = m.Groups[1].Value.ToLowerInvariant(); + uint.TryParse(m.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lb); + int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out variant); + ok = m.Groups[4].Value.Equals("VALID", StringComparison.OrdinalIgnoreCase); + } + else if ((m = DebugLocation.Match(l)).Success) location = m.Groups[1].Value.Trim(); + else if ((m = DebugPet.Match(l)).Success) pet = m.Groups[1].Value.Trim(); + else if ((m = DebugPartners.Match(l)).Success) int.TryParse(m.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out partners); + else if ((m = DebugSex.Match(l)).Success) sex = m.Groups[1].Value.Trim(); + } + } + return new BreedDebugInfo(enabled, location, lb, variant, kind, ok, pet, sex, partners); + } + + /// "0x0106 variant 2" (or "anywhere") for the rules list. + public string RoomText() + { + uint lb = (uint)Math.Max(0, Get(Landblock)); + int variant = GetInt(Variant); + if (lb == 0) return "anywhere"; + string place = lb > 0xFFFF ? "cell 0x" + lb.ToString("X8", CultureInfo.InvariantCulture) : "landblock 0x" + lb.ToString("X4", CultureInfo.InvariantCulture); + return variant >= 0 ? place + " variant " + variant.ToString(CultureInfo.InvariantCulture) : place; + } + + /// A rule value for display: "5%", "24h", "0x0106", "on", "10". + public static string Format(BreedRuleValue v) + { + switch (v.Def.Unit) + { + case "%": return (v.Value * 100.0).ToString("0.##", CultureInfo.InvariantCulture) + "%"; + case "h": return v.Value.ToString("0.#", CultureInfo.InvariantCulture) + "h"; + case "s": return v.Value.ToString("0.#", CultureInfo.InvariantCulture) + "s"; + case "hex": return "0x" + ((uint)Math.Max(0, v.Value)).ToString("X4", CultureInfo.InvariantCulture); + case "on/off": return v.Value >= 0.5 ? "on" : "off"; + default: return v.Value.ToString("0.##", CultureInfo.InvariantCulture); + } + } + + /// "ACE default", "ILT profile" or "seen on server". + public static string SourceText(BreedRuleSource s) => s switch + { + BreedRuleSource.Server => "seen on server", + BreedRuleSource.IltProfile => "ILT profile", + _ => "ACE default", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingSupplies.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingSupplies.cs new file mode 100644 index 0000000..33381d0 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingSupplies.cs @@ -0,0 +1,112 @@ +// IltBreedingSupplies.cs - Ivo's breeding supplies (ACECustom, Seedy Motel vendor) and when each can +// be used on an essence. +// +// WCIDs, prices and refusals copied from ACECustom (Player_Use.cs HandleActionUseOnTarget, the +// PetDevice.BreedingMath incense constants, docs/PET_BREEDING_PLAYER_GUIDE.md). RynthILT applies +// only the breeding boosters (incense, Nurturing Draught, Chromatic Catalyst, Offering of +// Subjugation), and only after the player confirms; the Neutering Kit is permanent and the kits, +// serum and tinctures are cosmetic, so those are counted, never used from here. +// +// Pure: RynthILT.Tests checks the refusals offline. +using System; +using System.Globalization; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One supply: key, WCID, name, what it does, Ivo's price, and whether the tracker can apply it. +internal sealed record BreedSupplyDef(string Key, uint Wcid, string Name, string Effect, long Price, bool Apply); + +internal static class IltBreedingSupplies +{ + public const string LesserIncense = "incense1"; + public const string RefinedIncense = "incense2"; + public const string ExquisiteIncense = "incense3"; + public const string Draught = "draught"; + public const string Catalyst = "catalyst"; + public const string Offering = "offering"; + public const string NeuteringKit = "neuter"; + public const string TailoringKit = "tailor"; + public const string FilledTailoringKit = "tailor_filled"; + public const string Serum = "serum"; + public const string Solidifying = "solidify"; + public const string Fading = "fade"; + + /// Every supply, boosters first. + public static readonly BreedSupplyDef[] All = + { + new(LesserIncense, 78780250, "Lesser Courtship Incense", "+2.5% stat mutation chance on the next breed.", 1_250_000, true), + new(RefinedIncense, 78780251, "Refined Courtship Incense", "+5% stat mutation chance on the next breed.", 2_500_000, true), + new(ExquisiteIncense, 78780252, "Exquisite Courtship Incense", "+10% stat mutation chance on the next breed.", 5_000_000, true), + new(Draught, 78780253, "Nurturing Draught", "A juvenile earns 2x maturity kill credit until adulthood.", 2_500_000, true), + new(Catalyst, 78780254, "Chromatic Catalyst", "The next baby rolls a fresh colour.", 2_500_000, true), + new(Offering, 78780255, "Offering of Subjugation", "The next mating guardian comes weakened.", 2_500_000, true), + new(NeuteringKit, 78780258, "Neutering Kit", "Permanently stops an essence from breeding.", 2_500_000, false), + new(TailoringKit, 78780259, "Tailoring Kit", "Extracts an essence's appearance.", 125_000_000, false), + new(FilledTailoringKit, 78780260, "Filled Tailoring Kit", "Applies an extracted appearance.", 0, false), + new(Serum, 78780257, "Mutagenic Serum", "Re-rolls an essence's colour.", 25_000_000, false), + new(Solidifying, 78780262, "Solidifying Tincture", "Makes the summoned pet less translucent.", 12_500_000, false), + new(Fading, 78780263, "Fading Tincture", "Makes the summoned pet more translucent.", 12_500_000, false), + }; + + /// The supply with this key, or null. + public static BreedSupplyDef? Find(string key) => Array.Find(All, s => s.Key == key); + + /// The incense bonus a supply gives (0 for anything else). + public static double IncenseBonus(string key) => key switch + { + LesserIncense => 0.025, + RefinedIncense => 0.05, + ExquisiteIncense => 0.10, + _ => 0, + }; + + /// "Refined incense +5%" for an applied bonus. + public static string IncenseName(double bonus) + { + string grade = bonus >= 0.0999 ? "Exquisite" : bonus >= 0.0499 ? "Refined" : "Lesser"; + return $"{grade} incense +{(bonus * 100).ToString("0.#", CultureInfo.InvariantCulture)}%"; + } + + /// + /// Why the server would refuse on (the server's own + /// checks, so nothing is spent on a refusal), or null when it would take it. + /// + public static string? RefuseReason(BreedSupplyDef s, BreedEssence e, IltBreedingRules r) + { + if (!s.Apply) return "Not applied from here."; + double incense = IncenseBonus(s.Key); + if (incense > 0) + { + if (e.Gate == BreedGate.Neutered) return "A neutered essence can't take incense."; + if (e.Incense >= incense - 1e-6) return $"Already primed with equal or stronger incense (+{e.Incense * 100:0.#}%)."; + return null; + } + return s.Key switch + { + Draught when !e.Juvenile => "Only a juvenile (still growing) can take a Nurturing Draught.", + Draught when e.Draught => "Already under a Nurturing Draught.", + Catalyst when e.Catalyst => "Already infused with a Chromatic Catalyst.", + Offering when r.Get(IltBreedingRules.GuardianEnabled) < 0.5 => "Mating guardians are off on this server.", + Offering when e.Offering => "Already under an Offering of Subjugation.", + _ => null, + }; + } + + /// A warning to show in the confirmation (a weaker incense being replaced), or "". + public static string Warning(BreedSupplyDef s, BreedEssence e) + { + double incense = IncenseBonus(s.Key); + if (incense > 0 && e.Incense > 0 && e.Incense < incense) + return $" It replaces the +{e.Incense * 100:0.#}% incense already on it (that one is lost)."; + return string.Empty; + } + + /// "1.25M", "125M", "-" for a price. + public static string PriceText(long price) + { + if (price <= 0) return "-"; + if (price >= 1_000_000) return (price / 1_000_000.0).ToString("0.##", CultureInfo.InvariantCulture) + "M"; + if (price >= 1_000) return (price / 1_000.0).ToString("0.#", CultureInfo.InvariantCulture) + "k"; + return price.ToString(CultureInfo.InvariantCulture); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBuffKeepers.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBuffKeepers.cs new file mode 100644 index 0000000..8380011 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBuffKeepers.cs @@ -0,0 +1,256 @@ +// IltBuffKeepers.cs — Rune-of-Dispel auto-dispel and Surging Strength keeper (Gear tab). +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// Both read the player's enchantment list once a second (one shared read). +// Dispel: classifies active spells by NAME (RynthAi's SpellDatabase, through RynthAi.Hub; it has no debuff flag): +// 1. Mire Foot (3051 / "mire"+"foot") → never (dispelling it is pointless) +// 2. user include list → dispel +// 3. beneficial pattern → keep +// 4. user exclude list → keep +// 5. known-harmful exact name or pattern → dispel +// and uses a Rune of Dispel (WCID 30133). Cooldown, verify after 2 s, up to 3 retries. +// Surging Strength: uses the Empowered Volcanic Ember when the buff is missing. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltBuffKeepers : IIltFeature +{ + private const int SpellMireFoot = 3051; + private const int MaxEnch = 256; + + private static readonly HashSet HarmfulExact = BuildHarmfulExact(); + private static readonly Regex HarmfulPattern = new( + @"\b(vulnerability|imperil|weakness|slowness|bane|exhaustion|mana burn|fester|curse of|blight of|burden of)\b", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + private static readonly Regex BeneficialPattern = new( + @"\b(invulnerability|invulnerable|protection|ward|armor|blessing|strength|coordination|endurance|quickness|focus|willpower|" + + @"regeneration|mana renewal|stamina renewal|health renewal|arcanum|cantrap|enhancement|augmentation|weave of|shroud of|" + + @"mantle of|cloak of|veil of|master's blessing|society|fellowship|loyalty|devotion)\b", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + private static HashSet BuildHarmfulExact() + { + var set = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (string s in new[] { "weakness other", "vulnerability other", "imperil other", "slowness other", + "bane other", "exhaustion other", "mana burn other", "fester other" }) + { + set.Add(s); + set.Add("incantation of " + s); + } + foreach (string s in new[] { "belly of lead", "gelidite's gift", "inferno's gift", "senescence", "archer's gift", + "swordsman's gift", "leaden feet", "heart of ice", "burning soul", "withering" }) + set.Add(s); + return set; + } + + private readonly IltHubContext _ctx; + private readonly uint[] _ids = new uint[MaxEnch]; + private readonly double[] _exp = new double[MaxEnch]; + private long _lastRead; + + // Dispel state + private long _dispelCooldownUntil; + private long _verifyAt; + private int _retries; + private volatile string[] _harmfulNow = Array.Empty(); + private volatile string _dispelStatus = "idle"; + + // Surging state + private long _surgeCooldownUntil; + private volatile bool _surgeActive; + private volatile string _surgeStatus = "idle"; + + // Render-thread edit buffers + private string _newInclude = string.Empty, _newExclude = string.Empty; + + public IltBuffKeepers(IltHubContext ctx) => _ctx = ctx; + + private IltGearState G => _ctx.State.Gear; + + /// True when this spell should be dispelled (precedence documented above). + public bool IsHarmful(int spellId, string name) + { + if (spellId == SpellMireFoot || (name.Contains("mire", StringComparison.OrdinalIgnoreCase) && name.Contains("foot", StringComparison.OrdinalIgnoreCase))) + return false; + if (G.DispelInclusions.ToArray().Any(i => i.Length > 0 && name.Contains(i, StringComparison.OrdinalIgnoreCase))) return true; + if (BeneficialPattern.IsMatch(name)) return false; + if (G.DispelExclusions.ToArray().Any(e => e.Length > 0 && name.Contains(e, StringComparison.OrdinalIgnoreCase))) return false; + string bare = StripTier(name); + return HarmfulExact.Contains(name) || HarmfulExact.Contains(bare) || HarmfulPattern.IsMatch(name); + } + + /// "Vulnerability Other VII" → "vulnerability other" (roman numeral suffix removed). + private static string StripTier(string name) + { + string n = name.Trim(); + int sp = n.LastIndexOf(' '); + if (sp > 0) + { + string tail = n.Substring(sp + 1); + if (tail.Length > 0 && tail.All(ch => "IVXL".IndexOf(char.ToUpperInvariant(ch)) >= 0)) n = n.Substring(0, sp); + } + return n.ToLowerInvariant(); + } + + private WorldObject? FindRune() + => _ctx.Inventory.FindByWcid(IltInventory.WcidRuneOfDispel) + ?? _ctx.Inventory.FindByName(n => n.Equals("Rune of Dispel", StringComparison.OrdinalIgnoreCase) + || (n.Contains("dispel", StringComparison.OrdinalIgnoreCase) && n.Contains("rune", StringComparison.OrdinalIgnoreCase))); + + private WorldObject? FindEmber() + => _ctx.Inventory.FindByName(n => n.Contains("empowered", StringComparison.OrdinalIgnoreCase) + && n.Contains("volcanic", StringComparison.OrdinalIgnoreCase) + && n.Contains("ember", StringComparison.OrdinalIgnoreCase)); + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + if (!G.AutoDispel && !G.SurgingStrength) return; + if (nowMs - _lastRead < 1000) return; + _lastRead = nowMs; + if (!_ctx.Host.HasReadPlayerEnchantments) return; + + int n = _ctx.Host.ReadPlayerEnchantments(_ids, _exp, MaxEnch); + if (n < 0) return; + n = Math.Min(n, MaxEnch); + + var harmful = new List(); + bool surge = false; + for (int i = 0; i < n; i++) + { + int id = unchecked((int)_ids[i]); + // Spell names are RynthAi's spell table (RynthAi.Hub SpellName); without RynthAi nothing is classified. + string name = _ctx.Ai.SpellName(id); + if (string.IsNullOrEmpty(name)) continue; + if (name.Contains("Surging Strength", StringComparison.OrdinalIgnoreCase)) surge = true; + if (G.AutoDispel && IsHarmful(id, name)) harmful.Add(name); + } + _harmfulNow = harmful.Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + _surgeActive = surge; + + if (G.AutoDispel) TickDispel(nowMs, harmful.Count > 0); + if (G.SurgingStrength) TickSurge(nowMs, surge); + } + + private void TickDispel(long now, bool anyHarmful) + { + // Verification / retry window after a rune use. + if (_verifyAt > 0) + { + if (now < _verifyAt) return; + if (!anyHarmful || _retries >= 3) + { + _dispelStatus = anyHarmful ? "debuffs remain after 3 retries" : "dispelled"; + _verifyAt = 0; + _dispelCooldownUntil = now + Math.Max(2, G.DispelCooldownSeconds) * 1000L; + return; + } + _retries++; + if (UseRune(now)) _verifyAt = now + 2500; + return; + } + + if (!anyHarmful) { _dispelStatus = "no harmful spells"; return; } + if (now < _dispelCooldownUntil) { _dispelStatus = "cooling down"; return; } + _retries = 0; + if (UseRune(now)) _verifyAt = now + 2000; + } + + private bool UseRune(long now) + { + if (_ctx.Inventory.IsBusy) return false; + var rune = FindRune(); + if (rune == null) { _dispelStatus = "no Rune of Dispel carried"; _dispelCooldownUntil = now + 30_000; _verifyAt = 0; return false; } + if (!_ctx.Inventory.Use(rune)) return false; + _dispelStatus = $"used {rune.Name} on {_harmfulNow.Length} debuff(s)"; + return true; + } + + private void TickSurge(long now, bool active) + { + if (active) { _surgeStatus = "Surging Strength active"; return; } + if (now < _surgeCooldownUntil || _ctx.Inventory.IsBusy) return; + var ember = FindEmber(); + if (ember == null) { _surgeStatus = "no Empowered Volcanic Ember carried"; _surgeCooldownUntil = now + 30_000; return; } + if (_ctx.Inventory.Use(ember)) _surgeStatus = "used " + ember.Name; + _surgeCooldownUntil = now + Math.Max(5, G.SurgingCooldownSeconds) * 1000L; + } + + public bool OnChat(string text) + { + if (!G.SurgingStrength) return false; + if (text.Contains("surging strength", StringComparison.OrdinalIgnoreCase)) + { + if (text.Contains("you cast", StringComparison.OrdinalIgnoreCase) && text.Contains("on yourself", StringComparison.OrdinalIgnoreCase)) + _surgeActive = true; + else if (text.Contains("has expired", StringComparison.OrdinalIgnoreCase)) + { + _surgeActive = false; + _surgeCooldownUntil = 0; // re-apply on the next read + } + } + return false; + } + + public void OnLogout() + { + _verifyAt = 0; + _harmfulNow = Array.Empty(); + } + + // ── UI (render thread) ────────────────────────────────────────────────── + + public void Render() + { + ImGui.TextColored(IltStyle.ColTeal, "Auto-dispel (Rune of Dispel)"); + bool ad = G.AutoDispel; + if (ImGui.Checkbox("Use a Rune of Dispel on harmful debuffs", ref ad)) G.AutoDispel = ad; + int cd = G.DispelCooldownSeconds; + ImGui.SetNextItemWidth(100); + if (ImGui.InputInt("Cooldown (s)##disp", ref cd)) G.DispelCooldownSeconds = Math.Max(2, cd); + SafeImGui.TextDisabled("Status: " + _dispelStatus); + var harm = _harmfulNow; + if (harm.Length > 0) SafeImGui.TextColored(IltStyle.ColAmber, "Harmful now: " + string.Join(", ", harm)); + if (ImGui.TreeNode("Always / never dispel lists")) + { + EditList("Always dispel (name contains)", G.DispelInclusions, ref _newInclude, "inc"); + EditList("Never dispel (name contains)", G.DispelExclusions, ref _newExclude, "exc"); + ImGui.TreePop(); + } + + ImGui.Separator(); + ImGui.TextColored(IltStyle.ColTeal, "Surging Strength"); + bool ss = G.SurgingStrength; + if (ImGui.Checkbox("Keep Surging Strength up (Empowered Volcanic Ember)", ref ss)) G.SurgingStrength = ss; + SafeImGui.TextDisabled("Status: " + (_surgeActive ? "active" : _surgeStatus)); + } + + private void EditList(string label, List list, ref string buffer, string id) + { + ImGui.TextUnformatted(label); + var snap = list.ToArray(); + for (int i = 0; i < snap.Length; i++) + { + SafeImGui.BulletText(snap[i]); + ImGui.SameLine(); + string victim = snap[i]; + if (ImGui.SmallButton($"x##{id}{i}")) _ctx.Post(() => list.Remove(victim)); + } + ImGui.SetNextItemWidth(200); + ImGui.InputTextWithHint($"##new{id}", "spell name text", ref buffer, 64u); + ImGui.SameLine(); + if (ImGui.SmallButton($"Add##{id}") && buffer.Trim().Length > 0) + { + string add = buffer.Trim(); + _ctx.Post(() => { if (!list.Contains(add, StringComparer.OrdinalIgnoreCase)) list.Add(add); }); + buffer = string.Empty; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharmTracker.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharmTracker.cs new file mode 100644 index 0000000..4581c2a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharmTracker.cs @@ -0,0 +1,144 @@ +// IltCharmTracker.cs — Every ACECustom registry charm's state: the Mini Remote's Charms tab +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// (IltCharms) and RynthPluginGetCharmsJson (an older engine's Settings "Charms Tracking" tab). +// +// Per charm it reports: +// acquired — "carried" (in pack / equipped now), "seen" (carried earlier this or a past +// session, remembered in IltCharacterState.CharmsSeen), or "no". +// active — "on" / "off" / "unknown". The charm's appraisal Use text ("Status: ON") wins; +// otherwise the player ability PropertyBool the server sets while it's active. +// The server deactivates abilities whose charm isn't possessed, so not carried = off. +// server — "off" when the server refused / reported the charm disabled, "on" when a feature +// dump reported it enabled, else "unknown" (clients can't query /charms). +// Pump thread only (inventory and property reads). +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltCharmTracker +{ + private readonly IltHubContext _ctx; + + public IltCharmTracker(IltHubContext ctx) => _ctx = ctx; + + /// + /// One charm's tracked state. is the carried copy a toggle uses + /// (the active one when one is on), 0 when none is carried. + /// + internal readonly record struct CharmState( + IltCharmDef Def, string Acquired, int Count, int Tier, int MaxTier, + IltTri Active, IltTri Server, DateTime LastSeenUtc, int ToggleId = 0); + + /// Evaluates every registry charm and refreshes the "seen" memory for carried ones. + public List Evaluate() + { + var inv = _ctx.Inventory; + var seenMap = _ctx.State.Character.CharmsSeen; + var result = new List(IltInventory.Charms.Length); + // One inventory pass, grouped by charm definition, instead of a WCID scan per charm. + var carried = new Dictionary>(); + foreach (var wo in inv.Items()) + { + var def = inv.CharmDefFor(wo); + if (def == null) continue; + if (!carried.TryGetValue(def, out var list)) carried[def] = list = new(); + list.Add(wo); + } + + foreach (var def in IltInventory.Charms) + { + carried.TryGetValue(def, out var items); + int count = items?.Count ?? 0; + int tier = 0, maxTier = 0, toggleId = 0; + IltTri active = IltTri.Off; + + if (count > 0) + { + // Server allows only one active charm per ability, so any ON item means ON. + bool anyOn = false, allKnown = true; + toggleId = items![0].Id; + foreach (var wo in items!) + { + var (t, m) = inv.CharmTier(wo); + if (t > tier) { tier = t; maxTier = m; } + var st = inv.CharmStatus(wo); + if (st == IltTri.On) { anyOn = true; toggleId = wo.Id; } + else if (st == IltTri.Unknown) allKnown = false; + } + if (anyOn) active = IltTri.On; + else if (def.PlayerFlag != 0 && inv.PlayerBool(def.PlayerFlag)) active = IltTri.On; + else active = allKnown ? IltTri.Off : IltTri.Unknown; + + if (!seenMap.TryGetValue(def.Name, out var seen)) seenMap[def.Name] = seen = new IltCharmSeen(); + if (tier > seen.Tier) { seen.Tier = tier; seen.MaxTier = maxTier; } + // Day resolution keeps the persisted state from changing (and re-saving) every poll. + var today = DateTime.UtcNow.Date; + if (seen.LastSeenUtc != today) seen.LastSeenUtc = today; + } + + seenMap.TryGetValue(def.Name, out var memory); + string acquired = count > 0 ? "carried" : memory != null ? "seen" : "no"; + if (count == 0 && memory != null) { tier = memory.Tier; maxTier = memory.MaxTier; } + + result.Add(new CharmState(def, acquired, count, tier, maxTier, active, + ServerState(def), memory?.LastSeenUtc ?? default, toggleId)); + } + return result; + } + + /// Server-side enabled state as far as the client has learned it. + private IltTri ServerState(IltCharmDef def) + { + var opts = _ctx.Options; + var tri = opts.Get(IltFeature.Charm(def.Name)); + // Universal Summoning Mastery also has a ServerConfig switch, reported separately. + if (Array.IndexOf(def.Wcids, IltInventory.WcidUniversalMasteryCharm) >= 0) + { + var cfg = opts.Get(IltFeature.UniversalMastery); + if (cfg == IltTri.Off || tri == IltTri.Off) return IltTri.Off; + if (cfg == IltTri.On || tri == IltTri.On) return IltTri.On; + } + return tri; + } + + /// JSON for RynthPluginGetCharmsJson. "available" is false off ILT-like worlds. + public string BuildJson() + { + var sb = new StringBuilder(4096); + bool available = _ctx.Options.IsIltLikeWorld; + sb.Append("{\"available\":").Append(available ? "true" : "false"); + sb.Append(",\"world\":\"").Append(IltStyle.JsonEscape(_ctx.Options.WorldName ?? string.Empty)).Append('"'); + if (!available) return sb.Append(",\"charms\":[]}").ToString(); + + var rows = Evaluate(); + sb.Append(",\"total\":").Append(rows.Count); + sb.Append(",\"acquiredCount\":").Append(rows.Count(r => r.Acquired != "no")); + sb.Append(",\"activeCount\":").Append(rows.Count(r => r.Active == IltTri.On)); + sb.Append(",\"charms\":["); + for (int i = 0; i < rows.Count; i++) + { + var r = rows[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"name\":\"").Append(IltStyle.JsonEscape(r.Def.Name)).Append('"'); + sb.Append(",\"effect\":\"").Append(IltStyle.JsonEscape(r.Def.Effect)).Append('"'); + sb.Append(",\"acquired\":\"").Append(r.Acquired).Append('"'); + sb.Append(",\"count\":").Append(r.Count); + sb.Append(",\"tier\":").Append(r.Tier); + sb.Append(",\"maxTier\":").Append(r.MaxTier); + sb.Append(",\"active\":\"").Append(TriText(r.Active)).Append('"'); + sb.Append(",\"server\":\"").Append(TriText(r.Server)).Append('"'); + sb.Append(",\"lastSeen\":\"") + .Append(r.LastSeenUtc == default ? string.Empty : r.LastSeenUtc.ToString("yyyy-MM-dd")) + .Append('"'); + // The carried copy a reader's Toggle uses ("RynthILT.Data" ToggleCharm); 0 = none carried. + sb.Append(",\"toggleId\":").Append(unchecked((uint)r.ToggleId)).Append('}'); + } + sb.Append("]}"); + return sb.ToString(); + } + + private static string TriText(IltTri t) => t switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" }; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharms.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharms.cs new file mode 100644 index 0000000..fe85b08 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharms.cs @@ -0,0 +1,266 @@ +// IltCharms.cs — The Mini Remote's "Charms" ILT tab: every ACECustom registry charm and the +// Guardian Hand, with their toggles. Other plugins read the same list and toggle through +// "RynthILT.Data" (BuildReaderJson / ToggleFromReader). +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// Per charm (IltCharmTracker): acquired ("carried" now, "stored" = carried before and remembered +// per character, or no), status ON / OFF from the charm's appraisal or the player's ability flag, +// best tier, and the server's switch when the client has learned it. A carried charm has a +// Toggle (using a charm flips it). The Guardian Hand isn't a registry charm (no published WCID), +// so it is matched by name or a configured WCID and listed under the table with its own Toggle. +// This was the engine Settings panel's "Charms Tracking" tab plus the Gear tab's charm strip. +// Scans run on the pump thread every 3 s while the Mini Remote is on screen; Render reads the +// published arrays only. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltCharms : IIltFeature +{ + private const long ScanIntervalMs = 3000; + + private readonly IltHubContext _ctx; + private readonly IltCharmTracker _tracker; + + /// A Guardian Hand carried now (name or WCID match). + private sealed record HandRow(int Id, string Name, IltTri Status, bool ServerDisabled); + + private volatile IltCharmTracker.CharmState[] _rows = Array.Empty(); + private volatile HandRow[] _hands = Array.Empty(); + private long _lastScan; + + public IltCharms(IltHubContext ctx, IltCharmTracker tracker) + { + _ctx = ctx; + _tracker = tracker; + } + + private IltGearState G => _ctx.State.Gear; + + private bool IsGuardianHand(WorldObject wo) + { + if (G.GuardianHandWcid != 0 && _ctx.Inventory.Wcid(wo) == G.GuardianHandWcid) return true; + string want = string.IsNullOrWhiteSpace(G.GuardianHandName) ? "Guardian Hand" : G.GuardianHandName.Trim(); + return wo.Name.Contains(want, StringComparison.OrdinalIgnoreCase) + || (wo.Name.Contains("guardian", StringComparison.OrdinalIgnoreCase) && wo.Name.Contains("hand", StringComparison.OrdinalIgnoreCase)); + } + + /// Pump thread: the registry table and the carried Guardian Hands. + private void Scan() + { + _rows = _tracker.Evaluate().ToArray(); + var inv = _ctx.Inventory; + var hands = new List(); + foreach (var wo in inv.Items().Where(IsGuardianHand)) + hands.Add(new HandRow(wo.Id, wo.Name, inv.CharmStatus(wo), _ctx.Options.IsOff(IltFeature.Charm("Guardian Hand")))); + _hands = hands.ToArray(); + } + + /// Uses (toggles) a charm (pump thread). + private void Toggle(int id) + { + var wo = _ctx.Inventory.Cache?[id]; + if (wo == null) return; + if (_ctx.Inventory.IsBusy) { _ctx.Chat("[Mini Remote] Busy - try the charm again in a moment."); return; } + _ctx.Inventory.Use(wo); + _lastScan = 0; // re-read the status soon (the appraisal refresh is throttled per item) + } + + /// + /// A Toggle from another plugin ("RynthILT.Data" ToggleCharm). Only + /// a registry charm or Guardian Hand the player carries is used, so a reader can't make the + /// client use anything else. Pump thread. True when it was used. + /// + public bool ToggleFromReader(uint id) + { + if (id == 0 || id > int.MaxValue) return false; + var inv = _ctx.Inventory; + foreach (var wo in inv.Items()) + { + if (wo.Id != (int)id) continue; + if (inv.CharmDefFor(wo) == null && !IsGuardianHand(wo)) return false; + Toggle(wo.Id); + return true; + } + return false; + } + + /// + /// The "RynthILT.Data" charms JSON: the registry charms + /// (IltCharmTracker.BuildJson) plus a "hands" array, every Guardian Hand carried now with its + /// object id (the Toggle's id), status and the server's switch. Pump thread. + /// + public string BuildReaderJson() + { + string json = _tracker.BuildJson(); + if (!_ctx.Options.IsIltLikeWorld || !json.EndsWith("]}", StringComparison.Ordinal)) return json; + var inv = _ctx.Inventory; + string server = _ctx.Options.Get(IltFeature.Charm("Guardian Hand")) switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" }; + var sb = new System.Text.StringBuilder(json, 0, json.Length - 1, json.Length + 256); + sb.Append(",\"hands\":["); + bool first = true; + foreach (var wo in inv.Items().Where(IsGuardianHand)) + { + if (!first) sb.Append(','); + first = false; + string active = inv.CharmStatus(wo) switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" }; + sb.Append("{\"id\":").Append(unchecked((uint)wo.Id)); + sb.Append(",\"name\":\"").Append(IltStyle.JsonEscape(wo.Name)).Append('"'); + sb.Append(",\"active\":\"").Append(active).Append('"'); + sb.Append(",\"server\":\"").Append(server).Append("\"}"); + } + return sb.Append("]}").ToString(); + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + if (!_ctx.WindowOpen || nowMs - _lastScan < ScanIntervalMs) return; + _lastScan = nowMs; + Scan(); + } + + public bool OnChat(string text) => false; + + public void OnLogout() + { + _rows = Array.Empty(); + _hands = Array.Empty(); + _lastScan = 0; + } + + // ── UI (render thread) ────────────────────────────────────────────────── + + public void Render() + { + var rows = _rows; + if (rows.Length == 0) + { + SafeImGui.TextDisabled(_ctx.WindowOpen ? "Reading your charms..." : "Open the Mini Remote to read your charms."); + RenderGuardianHand(); + return; + } + + int acquired = rows.Count(r => r.Acquired != "no"), active = rows.Count(r => r.Active == IltTri.On); + SafeImGui.TextColored(IltStyle.ColTeal, $"{acquired} of {rows.Length} acquired, {active} active"); + ImGui.SameLine(); + if (ImGui.SmallButton("Refresh##charms")) _ctx.Post(() => { _lastScan = 0; }); + + const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit + | ImGuiTableFlags.ScrollY; + float h = Math.Max(140f, ImGui.GetContentRegionAvail().Y - 110f); + if (ImGui.BeginTable("##iltcharms", 6, flags, new Vector2(0, h))) + { + ImGui.TableSetupScrollFreeze(0, 1); + ImGui.TableSetupColumn("Charm", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Acquired", ImGuiTableColumnFlags.WidthFixed, 64); + ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.WidthFixed, 44); + ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 40); + ImGui.TableSetupColumn("Server", ImGuiTableColumnFlags.WidthFixed, 58); + ImGui.TableSetupColumn("##toggle", ImGuiTableColumnFlags.WidthFixed, 52); + ImGui.TableHeadersRow(); + for (int i = 0; i < rows.Length; i++) RenderRow(i, rows[i]); + ImGui.EndTable(); + } + + RenderGuardianHand(); + ImGui.TextDisabled("Status comes from the charm's appraisal or your ability flag; a charm not carried is inactive."); + ImGui.TextDisabled("Stored = carried by this character before (remembered per character)."); + } + + private void RenderRow(int i, IltCharmTracker.CharmState r) + { + ImGui.PushID(i); + ImGui.TableNextRow(); + + ImGui.TableNextColumn(); + bool carried = r.Acquired == "carried"; + if (carried) ImGui.TextUnformatted(r.Def.Name); + else SafeImGui.TextColored(IltStyle.ColTextMute, r.Def.Name); + if (ImGui.IsItemHovered() && r.Def.Effect.Length > 0) SafeImGui.SetTooltip(r.Def.Effect); + + ImGui.TableNextColumn(); + if (carried) SafeImGui.TextColored(IltStyle.ColGreen, r.Count > 1 ? $"Carried x{r.Count}" : "Carried"); + else if (r.Acquired == "seen") + { + ImGui.TextColored(IltStyle.ColAmber, "Stored"); + if (ImGui.IsItemHovered() && r.LastSeenUtc != default) + SafeImGui.SetTooltip("Last carried " + r.LastSeenUtc.ToString("yyyy-MM-dd")); + } + else ImGui.TextDisabled("No"); + + ImGui.TableNextColumn(); + if (!carried) ImGui.TextDisabled("-"); + else if (r.Active == IltTri.On) ImGui.TextColored(IltStyle.ColGreen, "ON"); + else if (r.Active == IltTri.Off) ImGui.TextColored(IltStyle.ColTextMute, "OFF"); + else + { + ImGui.TextColored(IltStyle.ColAmber, "?"); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Waiting for the charm's appraisal."); + } + + ImGui.TableNextColumn(); + ImGui.TextUnformatted(r.Tier <= 0 ? "-" : r.MaxTier > 0 ? $"{r.Tier}/{r.MaxTier}" : r.Tier.ToString()); + + ImGui.TableNextColumn(); + if (r.Server == IltTri.Off) + { + ImGui.TextColored(IltStyle.ColHp, "Disabled"); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("The server refused or reported this charm as disabled."); + } + else if (r.Server == IltTri.On) ImGui.TextColored(IltStyle.ColGreen, "Enabled"); + else + { + ImGui.TextDisabled("-"); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Not reported. The server only tells players when a charm is refused."); + } + + ImGui.TableNextColumn(); + if (carried && r.ToggleId != 0 && r.Server != IltTri.Off) + { + int id = r.ToggleId; + if (ImGui.SmallButton("Toggle")) _ctx.Post(() => Toggle(id)); + } + ImGui.PopID(); + } + + /// The Guardian Hand (not a registry charm): each carried one with a Toggle, and how it is matched. + private void RenderGuardianHand() + { + var hands = _hands; + foreach (var h in hands) + { + ImGui.PushID(h.Id); + if (h.ServerDisabled) SafeImGui.TextDisabled($"{h.Name} - disabled on this server"); + else + { + var col = h.Status == IltTri.On ? IltStyle.ColGreen + : h.Status == IltTri.Off ? IltStyle.ColTextMute : IltStyle.ColAmber; + SafeImGui.TextColored(col, h.Status == IltTri.On ? "ON " : h.Status == IltTri.Off ? "OFF" : " ? "); + ImGui.SameLine(); + ImGui.TextUnformatted(h.Name); + ImGui.SameLine(); + int id = h.Id; + if (ImGui.SmallButton("Toggle")) _ctx.Post(() => Toggle(id)); + } + ImGui.PopID(); + } + + if (ImGui.TreeNode("Guardian Hand matching")) + { + string name = G.GuardianHandName; + ImGui.SetNextItemWidth(200); + if (ImGui.InputText("Name contains", ref name, 64u)) G.GuardianHandName = name; + int wcid = unchecked((int)G.GuardianHandWcid); + ImGui.SetNextItemWidth(140); + if (ImGui.InputInt("WCID (0 = name only)", ref wcid, 0)) G.GuardianHandWcid = unchecked((uint)Math.Max(0, wcid)); + ImGui.TreePop(); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChatCapture.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChatCapture.cs new file mode 100644 index 0000000..1a31b5d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChatCapture.cs @@ -0,0 +1,217 @@ +// IltChatCapture.cs — Shared "send a server command and collect its reply" helper. +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// Every ILT Hub feature that talks to ACECustom (/bank, /aug, /qb, /pets, /xp, /pb, +// the login probe, /myquests, ...) goes through this one queue so that: +// * only one capture is in flight at a time (replies can't be attributed to the wrong +// request), +// * reply lines can be eaten so a Hub refresh doesn't spam the chat window, +// * an "Unknown command: X" reply is recognised uniformly (feature not on this server). +// All methods must be called on the plugin pump thread (OnTick / OnChatWindowText). +using System; +using System.Collections.Generic; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// Describes one command whose reply should be captured. +internal sealed class IltChatRequest +{ + /// Text handed to InvokeChatParser, e.g. "/bank". + public string Command = string.Empty; + /// True for lines that belong to this reply (captured, refresh the idle timer). + public Func IsResponseLine = _ => false; + /// + /// Optional: only these response lines arm / refresh the idle timer. Header / banner lines + /// still capture, but idle completion waits until a progress line arrives (UB's /aug fetch: + /// dashes and "Advanced Augmentation Levels:" must not start the 2s idle before Creature:). + /// + public Func? ArmsIdle; + /// Optional: a line that ends the reply immediately (it is captured too). + public Func? IsTerminator; + /// The reply is complete after this long with no new response line. + public int IdleEndMs = 2000; + /// Give up if no response line arrives within this long. + public int FirstLineTimeoutMs = 15000; + /// Hide captured lines from the chat window. + public bool Eat = true; + /// Invoked once on the pump thread when the capture finishes for any reason. + public Action? OnComplete; +} + +/// What a capture produced. +internal sealed class IltChatResult +{ + public readonly List Lines = new(); + /// No response line ever arrived. + public bool TimedOut; + /// The server answered "Unknown command: …" for this command. + public bool UnknownCommand; + /// The engine had no InvokeChatParser, so nothing was sent. + public bool NotSent; + public string? TerminatorLine; +} + +internal sealed class IltChatCapture +{ + private readonly RynthCoreHost _host; + private readonly Queue _queue = new(); + + private IltChatRequest? _active; + private IltChatResult? _activeResult; + private long _sentAt; + private long _lastLineAt; + /// True once a response line that arms idle has arrived (always true when is null). + private bool _idleArmed; + + /// Minimum spacing between two sends so the server's own command throttles aren't tripped. + private const long SendSpacingMs = 400; + private long _lastSendAt; + + private static long NowMs => Environment.TickCount64; + + public IltChatCapture(RynthCoreHost host) => _host = host; + + /// True while a capture is in flight or queued. + public bool IsBusy => _active != null || _queue.Count > 0; + + /// True if a request with this exact command is queued or in flight (avoids duplicate refreshes). + public bool IsPending(string command) + { + if (_active != null && string.Equals(_active.Command, command, StringComparison.OrdinalIgnoreCase)) + return true; + foreach (var r in _queue) + if (string.Equals(r.Command, command, StringComparison.OrdinalIgnoreCase)) + return true; + return false; + } + + /// Queues a capture. It is sent from once earlier captures finish. + public void Enqueue(IltChatRequest request) + { + _queue.Enqueue(request); + RynthLog.Trace(LogCat.IltChat, $"enqueue '{request.Command}' (queue={_queue.Count}, busy={_active != null})"); + } + + /// Drops everything (logout / teardown). Pending callbacks are not invoked. + public void Clear() + { + if (_active != null || _queue.Count > 0) + RynthLog.Trace(LogCat.IltChat, $"clear: dropping active='{_active?.Command}' and {_queue.Count} queued"); + _queue.Clear(); + _active = null; + _activeResult = null; + } + + /// Starts queued captures and finishes the active one on idle/timeout. + public void Tick() + { + long now = NowMs; + if (_active != null && _activeResult != null) + { + bool gotAny = _activeResult.Lines.Count > 0; + // Idle completion only after a progress line when ArmsIdle is set (header alone is not enough). + bool idleReady = _active.ArmsIdle == null || _idleArmed; + if (gotAny && idleReady && now - _lastLineAt >= _active.IdleEndMs) + Finish(); + else if ((!gotAny || !idleReady) && now - _sentAt >= _active.FirstLineTimeoutMs) + { + _activeResult.TimedOut = true; + Finish(); + } + } + + if (_active == null && _queue.Count > 0 && now - _lastSendAt >= SendSpacingMs) + StartNext(now); + } + + /// + /// Feed every incoming chat line. Returns true when the line belonged to the active + /// capture and that capture asked for its lines to be eaten. + /// + public bool OnChatLine(string rawText) + { + if (_active == null || _activeResult == null) return false; + string text = rawText.Trim(); + if (text.Length == 0) return false; + + // "Unknown command: blackjack" — ACE GameActionTalk reply for unregistered commands. + if (text.StartsWith("Unknown command:", StringComparison.OrdinalIgnoreCase) + && CommandWordMatches(text.Substring("Unknown command:".Length).Trim())) + { + _activeResult.UnknownCommand = true; + _activeResult.Lines.Add(text); + bool eat = _active.Eat; + Finish(); + return eat; + } + + if (_active.IsTerminator != null && _active.IsTerminator(text)) + { + _activeResult.TerminatorLine = text; + _activeResult.Lines.Add(text); + bool eat = _active.Eat; + Finish(); + return eat; + } + + if (!_active.IsResponseLine(text)) return false; + _activeResult.Lines.Add(text); + // Header-only replies (e.g. /aug dashes + banner) must not start the idle clock. + if (_active.ArmsIdle == null || _active.ArmsIdle(text)) + { + _idleArmed = true; + _lastLineAt = NowMs; + } + RynthLog.Trace(LogCat.IltChat, $"line '{_active.Command}'{(_active.Eat ? " [eaten]" : "")}: {text}"); + return _active.Eat; + } + + private bool CommandWordMatches(string word) + { + if (_active == null) return false; + // Request "/bank t p 5 Bob" → command word "bank". + string cmd = _active.Command.TrimStart('/', '@'); + int sp = cmd.IndexOf(' '); + if (sp >= 0) cmd = cmd.Substring(0, sp); + return string.Equals(cmd, word, StringComparison.OrdinalIgnoreCase); + } + + private void StartNext(long now) + { + var req = _queue.Dequeue(); + var result = new IltChatResult(); + if (!_host.HasInvokeChatParser) + { + RynthLog.Trace(LogCat.IltChat, $"not sent '{req.Command}': engine has no InvokeChatParser"); + result.NotSent = true; + try { req.OnComplete?.Invoke(result); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltChat, ex, $"capture callback '{req.Command}'"); } + return; + } + + _active = req; + _activeResult = result; + _sentAt = now; + _lastLineAt = now; + _idleArmed = req.ArmsIdle == null; // no progress gate → idle can finish after any response line + _lastSendAt = now; + RynthLog.Trace(LogCat.IltChat, $"send '{req.Command}' (idle={req.IdleEndMs} ms, timeout={req.FirstLineTimeoutMs} ms, eat={req.Eat})"); + _host.InvokeChatParser(req.Command); + } + + private void Finish() + { + var req = _active; + var res = _activeResult; + _active = null; + _activeResult = null; + _idleArmed = false; + if (req == null || res == null) return; + RynthLog.Trace(LogCat.IltChat, + $"complete '{req.Command}' in {NowMs - _sentAt} ms: lines={res.Lines.Count} timedOut={res.TimedOut} " + + $"unknown={res.UnknownCommand} terminator={(res.TerminatorLine != null)}"); + try { req.OnComplete?.Invoke(res); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltChat, ex, $"capture callback '{req.Command}'"); } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs new file mode 100644 index 0000000..c3190ca --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs @@ -0,0 +1,672 @@ +// IltChunkClap.cs — Lugian-hammer chunking and /clap automation (Gear tab). +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// Chunk: uses the Lugian Aetheria Hammer on eligible items, one at a time. The rules follow ub-IT +// (Leaftide AetheriaChunkGuard / IsValidCorruptedWep / CorruptedChunkGuard): +// Aetheria — "Aetheria"/"Coalesced Aetheria" gems, not equipped, appraised, not flagged +// never-chunk (bool 9030), not tinkered (171) or imbued (179), never levelled +// (ItemTotalXp quad 4 == 0), no kept C / CD / CDR rating (gear ints 372 / 374 / 375; +// on by default; only a rating at or above the "rating level" keeps, a lower one +// chunks), and max level (int 319, up to 10 on ILT) under the configured cap. +// A levelled Coalesced piece gets the cap too; an unlevelled one (319 = 0 after +// appraisal, normal for Coalesced) is chunkable, as in ub-IT. RynthILT used to keep +// every unlevelled Coalesced piece forever. +// Corrupted — "Corrupted" melee/missile weapons, not equipped, not never-chunk, no tinks (171), +// no imbue (179), loot-gen workmanship (105) > 0, and cleave (292) <= 1, or <= 2 on a +// two-handed weapon that is not a thrust weapon (RynthILT used to cap every weapon +// at 1, so no two-handed corrupted weapon was ever chunked). Optional keep rules +// (Crushing Blow, Biting Strike, Armor Cleaving, slayer, multi-strike, elemental +// bonus, any spell, max damage, spell ids) are all off by default. +// Peace mode only unless ChunkInCombat. With ChunkInCombat on, a busy client in combat mode no +// longer blocks the hammer (a swinging bot is always busy); peace mode still waits for idle. +// Waits for the result line (10 s max); a target that leaves the pack first counts as chunked +// (ILT does not always send a known line). Each item's skip reason is logged when it changes +// and tallied in the status line. +// The tool is the "Lugian Aetheria Hammer" only. The Lugian Hammer weapons (Flaming, Acid, ...) +// are loot and chunk nothing: the server answers with no result line, so every item timed out +// into the skip list and the status sat on "nothing eligible" (SilentKelpie, 2026-10-15). +// Clap: "/clap all" converts aetheria + trinkets into coins server-side: red (Coalesced level 1-3, +// chunks, powder) with Empyrean Trinkets, blue with Falatacot Trinkets. Auto-clap sends it only +// when a pair is carried. Needs the AutoCraftingEnabled stamp; 30 min ± 2 min interval, first +// attempt ~1 min after enable. +using System; +using System.Collections.Generic; +using System.Linq; +using ImGuiNET; +using RynthCore.Loot; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltChunkClap : IIltFeature +{ + private const long ChunkResultWaitMs = 10_000; + private const long ClapFirstDelayMs = 60_000; + private const long ClapJitterMs = 120_000; + + private static readonly string[] ChunkDoneLines = + { + "You smash the aetheria with the hammer.", "The two artifacts link together effortlessly.", + "You successfully chunk the aetheria.", "You fail to chunk the aetheria.", + "The corrupted weapon is crushed into a fine powder.", "You smash the corrupted weapon with the hammer.", + "The corrupted weapon shatters into fragments.", "You fail to chunk the corrupted weapon.", + }; + private static readonly string[] ChunkRefusedLines = + { + "The aetheria is too powerful to chunk.", "You cannot chunk this aetheria.", + "The corrupted weapon is too powerful to chunk.", "You cannot chunk this corrupted weapon.", + }; + + private readonly IltHubContext _ctx; + private readonly Random _rng = new(); + + // Chunk state + private long _lastChunkAt; + private int _waitingOn; + private long _waitStartedAt; + private readonly HashSet _skip = new(); + private bool _manualPass; + private volatile string _chunkStatus = "idle"; + private int _chunked; + // Last skip reason per item, so each reason is logged once instead of every pass. + private readonly Dictionary _lastSkip = new(); + // Skip reasons of the current pass (reason -> items), shown in the status line. + private readonly Dictionary _passSkips = new(); + + // Clap state + private long _nextClapAt; + private volatile string _clapStatus = "idle"; + private bool _clapWasEnabled; + + public IltChunkClap(IltHubContext ctx) => _ctx = ctx; + + private IltGearState G => _ctx.State.Gear; + + // ── Chunk ─────────────────────────────────────────────────────────────── + + /// Infinite Leaftide's chunking tool. + internal const string HammerName = "Lugian Aetheria Hammer"; + + /// True for the chunking tool only, never a Lugian Hammer weapon. Pure: the tests drive it. + internal static bool IsChunkHammer(string name) => name.Equals(HammerName, StringComparison.OrdinalIgnoreCase); + + private WorldObject? FindHammer() + => _ctx.Inventory.Items().FirstOrDefault(wo => IsChunkHammer(wo.Name) && !_ctx.Inventory.IsEquipped(wo)); + + /// Item kinds the hammer works on (the name and class gate, before any appraisal). + internal enum ChunkKind { None, Aetheria, Corrupted } + + /// + /// Which chunk rules an item falls under, by class and name only. Aetheria chunks and powder + /// are clap material, not hammer targets. Pure: the tests drive it. + /// + internal static ChunkKind KindOf(AcObjectClass cls, string name) + { + if (cls == AcObjectClass.Gem) + { + if (name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase)) return ChunkKind.Aetheria; + if (name.Contains("Aetheria", StringComparison.OrdinalIgnoreCase) + && !name.Contains("Chunk", StringComparison.OrdinalIgnoreCase) + && !name.Contains("Powder", StringComparison.OrdinalIgnoreCase)) + return ChunkKind.Aetheria; + return ChunkKind.None; + } + if (cls is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon + && name.Contains("Corrupted", StringComparison.OrdinalIgnoreCase)) + return ChunkKind.Corrupted; + return ChunkKind.None; + } + + /// An aetheria piece's chunk facts, read after appraisal. + internal readonly record struct AetheriaFacts( + bool Coalesced, int MaxLevel, bool NeverChunk, long ItemXp, int Tinkers, int Imbue, + int Crit, int CritDamage, int CritDamageResist, string? Unreadable = null); + + /// + /// Why an aetheria piece is kept, or null when it may be chunked (ub-IT AetheriaChunkGuard plus + /// RynthILT's C / CD / CDR keep switches). Pure: the tests drive it. + /// + /// is set when the item's properties could not be read (the + /// host lacks a reader or the appraisal never arrived). A property that failed to read looks + /// exactly like one the item lacks (level 0, no XP, no tinks), so such a piece is kept: an + /// "unlevelled" Coalesced piece is only chunked when its level was truly read as none. + /// + /// + internal static string? AetheriaSkip(IltGearState g, in AetheriaFacts f) + { + if (f.Unreadable != null) return $"item data unreadable ({f.Unreadable})"; + if (f.NeverChunk) return "never-chunk flag"; + if (f.Tinkers != 0 || f.Imbue != 0) return "tinkered or imbued"; + if (f.ItemXp != 0) return "has item XP"; + if (KeptForRatings(g, f.Crit, f.CritDamage, f.CritDamageResist)) return "kept for its C / CD / CDR rating"; + if (!UnderChunkCap(f.MaxLevel, g.ChunkAetheriaUnderLevel, f.Coalesced)) + return f.MaxLevel > 0 ? "level at or above the cap" : "no level read"; + return null; + } + + /// Why an aetheria item is kept (null = chunk it); "appraising" while its data is missing. + private string? AetheriaSkip(WorldObject wo) + { + var inv = _ctx.Inventory; + if (inv.IsEquipped(wo)) return "equipped"; + if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return Appraising; } + string? gap = inv.ReadGap(wo, quads: true); + var f = new AetheriaFacts( + Coalesced: wo.Name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase), + MaxLevel: inv.Int(wo, IltInventory.IntItemMaxLevel), + NeverChunk: inv.Bool(wo, IltInventory.BoolNeverChunk), + ItemXp: inv.Quad(wo, IltInventory.QuadItemTotalXp), + Tinkers: inv.Int(wo, IltInventory.IntNumTimesTinkered), + Imbue: inv.Int(wo, IltInventory.IntImbuedEffect), + Crit: inv.Int(wo, IltInventory.IntGearCrit), + CritDamage: inv.Int(wo, IltInventory.IntGearCritDamage), + CritDamageResist: inv.Int(wo, IltInventory.IntGearCritDamageResist), + Unreadable: gap); + return AetheriaSkip(G, f); + } + + /// The chunk cap in range: 1 (chunk nothing by level) to one past the ILT maximum (every level). + internal static int ClampUnderLevel(int under) => Math.Clamp(under, 1, IltInventory.AetheriaMaxLevel + 1); + + /// + /// True when an aetheria's max level (int 319) is under the cap. A levelled Coalesced piece + /// (ACECustom rolls 1-10; level 6+ can carry a rating) gets the same cap. Level 0 after + /// appraisal: an unlevelled Coalesced piece is chunkable (ub-IT: "ItemMaxLevel 0 after assess + /// is normal"); any other aetheria with no level is never chunked. Pure: the tests drive it. + /// + internal static bool UnderChunkCap(int maxLevel, int under, bool coalesced = false) + => maxLevel > 0 ? maxLevel < ClampUnderLevel(under) : coalesced && maxLevel == 0; + + /// Highest rating level the keep threshold accepts. + internal const int MaxRatingLevel = 50; + + /// The rating keep threshold in range: 1 (any rating keeps) to . + internal static int ClampRatingLevel(int level) => Math.Clamp(level, 1, MaxRatingLevel); + + /// + /// True when an aetheria's C / CD / CDR rating is one the settings keep: its keep switch is on and + /// the rating is at or above the rating level (). + /// A rating below that level does not protect the piece, so e.g. a C 1 Coalesced Aetheria chunks + /// with the level at 2 while a C 2 one is kept. Pure: the tests drive it. + /// + internal static bool KeptForRatings(IltGearState g, int crit, int critDamage, int critDamageResist) + { + int min = ClampRatingLevel(g.KeepAetheriaRatingAtLeast); + return (g.KeepAetheriaWithCrit && crit >= min) + || (g.KeepAetheriaWithCritDamage && critDamage >= min) + || (g.KeepAetheriaWithCritDamageResist && critDamageResist >= min); + } + + private const string Appraising = "appraising"; + private const int SkillTwoHandedCombat = 41; + private const int WeaponTypeTwoHanded = 11; + private const int AttackTypeThrust = 2; + + /// A corrupted weapon's chunk facts, read after appraisal. + internal sealed record CorruptedFacts + { + public bool NeverChunk { get; init; } + public int Tinkers { get; init; } + public int Imbue { get; init; } + public int Workmanship { get; init; } + public int AttackType { get; init; } + public int Cleaving { get; init; } + public int WieldSkill { get; init; } + public int WeaponType { get; init; } + public double CritFrequency { get; init; } + public double CritMultiplier { get; init; } + public double IgnoreArmor { get; init; } + public int Slayer { get; init; } + public int ElementalBonus { get; init; } + public int MaxDamage { get; init; } + public IReadOnlyList Spells { get; init; } = Array.Empty(); + /// What could not be read (null = everything the rules need was); see AetheriaFacts.Unreadable. + public string? Unreadable { get; init; } + } + + /// + /// The most cleave a chunkable corrupted weapon may have (ub-IT IsValidCorruptedWep): 2 on a + /// two-handed weapon that is not a thrust weapon, 1 on everything else. Pure: the tests drive it. + /// + internal static int MaxChunkCleave(int wieldSkill, int weaponType, int attackType) + => (wieldSkill == SkillTwoHandedCombat || weaponType == WeaponTypeTwoHanded) && attackType != AttackTypeThrust ? 2 : 1; + + /// + /// Why a corrupted weapon is kept, or null when it may be chunked: ub-IT's hard rules, then its + /// IdleActs keep rules from the settings. Pure: the tests drive it. + /// + internal static string? CorruptedSkip(IltGearState g, CorruptedFacts f) + { + // A property that failed to read looks like one the weapon lacks (0), which would chunk it. + if (f.Unreadable != null) return $"item data unreadable ({f.Unreadable})"; + + // Hard rules (always on). + if (f.NeverChunk) return "never-chunk flag"; + if (f.Tinkers != 0 || f.Imbue != 0) return "tinkered or imbued"; + if (f.Workmanship <= 0) return "no workmanship"; + if (f.Cleaving > MaxChunkCleave(f.WieldSkill, f.WeaponType, f.AttackType)) return "cleave over the limit"; + + // Keep rules (each off by default). + if (g.KeepCorruptedCrushingBlow && f.CritFrequency > 0) return "kept: Crushing Blow"; + if (g.KeepCorruptedBitingStrike && f.CritMultiplier > 0) return "kept: Biting Strike"; + if (g.KeepCorruptedArmorCleaving && f.IgnoreArmor > 0) return "kept: Armor Cleaving"; + if (g.KeepCorruptedAnySlayer && f.Slayer > 0) return "kept: slayer"; + if (g.KeepCorruptedMultiStrike && f.AttackType is 160 or 166 or 486) return "kept: multi-strike"; + if (g.KeepCorruptedElementalBonus && f.ElementalBonus > 0) return "kept: elemental bonus"; + if (g.KeepCorruptedMaxDamageAtLeast > 0 && f.MaxDamage >= g.KeepCorruptedMaxDamageAtLeast) return "kept: max damage"; + if (f.Spells.Count > 0) + { + if (g.KeepCorruptedAnySpell) return "kept: has a spell"; + var deny = ParseSpellIds(g.KeepCorruptedSpellIds); + if (deny.Count > 0 && f.Spells.Any(deny.Contains)) return "kept: listed spell"; + } + return null; + } + + /// Positive spell ids from a comma / semicolon / whitespace separated list. Pure: the tests drive it. + internal static HashSet ParseSpellIds(string? csv) + { + var ids = new HashSet(); + if (string.IsNullOrWhiteSpace(csv)) return ids; + foreach (var part in csv.Split(new[] { ',', ';', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) + if (int.TryParse(part, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int id) && id > 0) + ids.Add(id); + return ids; + } + + /// Why a corrupted weapon is kept (null = chunk it); "appraising" while its data is missing. + private string? CorruptedSkip(WorldObject wo) + { + var inv = _ctx.Inventory; + if (inv.IsEquipped(wo)) return "equipped"; + if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return Appraising; } + bool needDoubles = G.KeepCorruptedCrushingBlow || G.KeepCorruptedBitingStrike || G.KeepCorruptedArmorCleaving; + bool needSpells = G.KeepCorruptedAnySpell || !string.IsNullOrWhiteSpace(G.KeepCorruptedSpellIds); + var f = new CorruptedFacts + { + Unreadable = inv.ReadGap(wo, doubles: needDoubles, spells: needSpells), + NeverChunk = inv.Bool(wo, IltInventory.BoolNeverChunk), + Tinkers = inv.Int(wo, IltInventory.IntNumTimesTinkered), + Imbue = inv.Int(wo, IltInventory.IntImbuedEffect), + Workmanship = inv.Int(wo, IltInventory.IntItemWorkmanship), + AttackType = inv.Int(wo, IltInventory.IntAttackType), + Cleaving = inv.Int(wo, IltInventory.IntCleaving), + WieldSkill = inv.Int(wo, IltInventory.IntWieldSkillType), + WeaponType = inv.Int(wo, IltInventory.IntWeaponType), + CritFrequency = inv.Double(wo, IltInventory.FloatCriticalFrequency), + CritMultiplier = inv.Double(wo, IltInventory.FloatCriticalMultiplier), + IgnoreArmor = inv.Double(wo, IltInventory.FloatIgnoreArmor), + Slayer = inv.Int(wo, IltInventory.IntSlayerCreatureType), + ElementalBonus = inv.Int(wo, IltInventory.IntElementalDamageBonus), + MaxDamage = inv.Int(wo, IltInventory.IntDamage), + // Spells are only read when a spell rule is on (the read copies the item's spell list). + Spells = needSpells ? inv.SpellIds(wo) : Array.Empty(), + }; + return CorruptedSkip(G, f); + } + + /// + /// Chunk is allowed while the client is busy only in combat mode with ChunkInCombat on (ub-IT + /// AutoChunkCombatBusyPolicy v2.0.1059: a swinging bot is always busy). Peace mode still waits + /// for idle so the hammer never interrupts another use. Pure: the tests drive it. + /// + internal static bool AllowsChunkWhileBusy(bool isBusy, bool isPeace, bool chunkInCombat) + => !isBusy || (!isPeace && chunkInCombat); + + private WorldObject? NextChunkTarget() + { + _passSkips.Clear(); + foreach (var wo in _ctx.Inventory.Items()) + { + if (_skip.Contains(wo.Id)) continue; + string? reason; + switch (KindOf(wo.ObjectClass, wo.Name)) + { + case ChunkKind.Aetheria when G.AutoChunkAetheria || _manualPass: + reason = AetheriaSkip(wo); + break; + case ChunkKind.Corrupted when G.AutoChunkCorrupted || _manualPass: + reason = CorruptedSkip(wo); + break; + default: + continue; + } + if (reason == null) { _lastSkip.Remove(wo.Id); return wo; } + NoteSkip(wo, reason); + } + return null; + } + + /// Tallies a skip for the status line and logs it once per item and reason. + private void NoteSkip(WorldObject wo, string reason) + { + _passSkips[reason] = _passSkips.TryGetValue(reason, out int n) ? n + 1 : 1; + if (reason == Appraising) return; + if (_lastSkip.TryGetValue(wo.Id, out string? last) && last == reason) return; + _lastSkip[wo.Id] = reason; + RynthLog.Write(LogCat.IltGear, $"chunk: keep 0x{(uint)wo.Id:X8} '{wo.Name}': {reason}"); + } + + /// "3 kept for its C / CD / CDR rating, 1 appraising" — the current pass's skips. + private string PassSkipSummary() + => string.Join(", ", _passSkips.OrderByDescending(kv => kv.Value).Select(kv => $"{kv.Value} {kv.Key}")); + + /// Runs one chunk pass now (both item kinds) regardless of the auto toggles. + public void ChunkNow() + { + RynthLog.Trace(LogCat.IltGear, $"ChunkNow()"); + _manualPass = true; + _lastChunkAt = 0; + _skip.Clear(); // a manual pass gives the items that got no answer another try + _chunkStatus = "manual pass started"; + } + + private void TickChunk(long now) + { + if (!G.AutoChunkAetheria && !G.AutoChunkCorrupted && !_manualPass) return; + + if (_waitingOn != 0) + { + int id = _waitingOn; + switch (WaitOutcome(now - _waitStartedAt, _ctx.Inventory.Items().Any(wo => wo.Id == id))) + { + case ChunkWait.Waiting: + return; + case ChunkWait.Gone: + _chunked++; + RynthLog.Write(LogCat.IltGear, $"chunk: 0x{(uint)id:X8} left the pack with no result line; counted as chunked"); + break; + case ChunkWait.TimedOut: + _skip.Add(id); // still carried and no result line: don't hammer the same item forever + RynthLog.Write(LogCat.IltGear, $"chunk: no result line for 0x{(uint)id:X8} in {ChunkResultWaitMs / 1000} s, skipped until a manual pass"); + break; + } + _waitingOn = 0; + } + if (now - _lastChunkAt < Math.Max(500, G.ChunkIntervalMs)) return; + _lastChunkAt = now; + + bool peace = _ctx.Inventory.InPeaceMode; + if (!G.ChunkInCombat && !peace) { _chunkStatus = "waiting for peace mode"; return; } + if (!AllowsChunkWhileBusy(_ctx.Inventory.IsBusy, peace, G.ChunkInCombat)) { _chunkStatus = "waiting for idle"; return; } + + var hammer = FindHammer(); + if (hammer == null) { _chunkStatus = $"no {HammerName} carried"; _manualPass = false; return; } + var target = NextChunkTarget(); + if (target == null) + { + string kept = PassSkipSummary(); + _chunkStatus = (_chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible") + + (kept.Length > 0 ? $"; not chunked: {kept}" : "") + + (_skip.Count > 0 ? $"; {_skip.Count} skipped with no answer (Chunk now retries them)" : ""); + _manualPass = false; + return; + } + if (_ctx.Inventory.UseOn(hammer, unchecked((uint)target.Id))) + { + _waitingOn = target.Id; + _waitStartedAt = now; + _chunkStatus = "chunking " + target.Name; + } + } + + // ── Clap ──────────────────────────────────────────────────────────────── + + internal enum ClapPart { None, Red, Blue, Empyrean, Falatacot } + + /// + /// Which side of /clap an item feeds (ACECustom PlayerCommands.HandleClap): red material (Red + /// Coalesced Aetheria, chunks, powder) pairs with Ancient Empyrean Trinkets, blue with Ancient + /// Falatacot Trinkets. Coalesced counts only unrevealed and at level 1-3; level 0 (not read yet) + /// counts, and the server has the last word. With no WCID yet, the chunk and trinket names + /// decide. Pure: the tests drive it. + /// + internal static ClapPart ClapPartOf(uint wcid, string name, int maxLevel) + { + bool lowCoalesced = name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase) && maxLevel <= 3; + switch (wcid) + { + case IltInventory.WcidRedCoalescedAetheria: return lowCoalesced ? ClapPart.Red : ClapPart.None; + case IltInventory.WcidBlueCoalescedAetheria: return lowCoalesced ? ClapPart.Blue : ClapPart.None; + case IltInventory.WcidRedAetheriaChunk: + case IltInventory.WcidRedAetheriaPowder: return ClapPart.Red; + case IltInventory.WcidBlueAetheriaChunk: + case IltInventory.WcidBlueAetheriaPowder: return ClapPart.Blue; + case IltInventory.WcidEmpyreanTrinket: return ClapPart.Empyrean; + case IltInventory.WcidFalatacotTrinket: return ClapPart.Falatacot; + case 0: break; + default: return ClapPart.None; + } + if (name.Equals("Red Aetheria Chunk", StringComparison.OrdinalIgnoreCase)) return ClapPart.Red; + if (name.Equals("Blue Aetheria Chunk", StringComparison.OrdinalIgnoreCase)) return ClapPart.Blue; + if (name.Equals("Ancient Empyrean Trinket", StringComparison.OrdinalIgnoreCase)) return ClapPart.Empyrean; + if (name.Equals("Ancient Falatacot Trinket", StringComparison.OrdinalIgnoreCase)) return ClapPart.Falatacot; + return ClapPart.None; + } + + /// + /// True when /clap has a pair to work with: red material and an Empyrean Trinket, or blue + /// material and a Falatacot Trinket. One side alone gets "You don't have any aetheria materials". + /// Pure: the tests drive it. + /// + internal static bool CanClap(IEnumerable parts) + { + bool red = false, blue = false, empyrean = false, falatacot = false; + foreach (var part in parts) + { + switch (part) + { + case ClapPart.Red: red = true; break; + case ClapPart.Blue: blue = true; break; + case ClapPart.Empyrean: empyrean = true; break; + case ClapPart.Falatacot: falatacot = true; break; + } + } + return (red && empyrean) || (blue && falatacot); + } + + private bool HasClapMaterials() + { + var inv = _ctx.Inventory; + return CanClap(inv.Items().Where(wo => !inv.IsEquipped(wo)) + .Select(wo => ClapPartOf(inv.Wcid(wo), wo.Name, inv.Int(wo, IltInventory.IntItemMaxLevel)))); + } + + /// Sends "/clap all" through the capture queue (reply stays visible). + public void ClapNow(bool manual) + { + RynthLog.Trace(LogCat.IltGear, $"ClapNow(manual={manual})"); + if (_ctx.Options.IsOff(IltFeature.Clap)) { _clapStatus = "/clap is not available (server or AutoCraftingEnabled stamp)"; return; } + if (_ctx.Capture.IsPending("/clap all")) return; + if (!manual && !HasClapMaterials()) { _clapStatus = "no aetheria and trinket pair carried (red + Empyrean, blue + Falatacot)"; return; } + _clapStatus = "sending /clap all..."; + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = "/clap all", + IsResponseLine = t => t.StartsWith("Deposited ", StringComparison.Ordinal) + || t.StartsWith("[Clap]", StringComparison.OrdinalIgnoreCase) + || t.Contains("aetheria materials", StringComparison.OrdinalIgnoreCase) + || t.Contains("AutoCraftingEnabled", StringComparison.OrdinalIgnoreCase), + IdleEndMs = 800, + FirstLineTimeoutMs = 10_000, + Eat = false, + OnComplete = r => + { + if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Clap, IltTri.Off); _clapStatus = "/clap not available"; return; } + _clapStatus = r.Lines.Count > 0 ? r.Lines[^1] : "no reply"; + if (r.Lines.Any(l => l.StartsWith("Deposited ", StringComparison.Ordinal))) _ctx.Options.Set(IltFeature.Clap, IltTri.On); + }, + }); + } + + private void TickClap(long now) + { + // Automation only runs once the server has positively confirmed /clap (unknown = wait). + if (!G.AutoClap || !_ctx.Options.IsOn(IltFeature.Clap)) { _clapWasEnabled = false; return; } + if (!_clapWasEnabled) + { + _clapWasEnabled = true; + _nextClapAt = now + ClapFirstDelayMs; + _clapStatus = "first auto-clap in ~1 min"; + return; + } + if (now < _nextClapAt) return; + long interval = Math.Max(5, G.ClapIntervalMinutes) * 60_000L; + _nextClapAt = now + interval + (long)((_rng.NextDouble() * 2 - 1) * ClapJitterMs); + ClapNow(manual: false); + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + TickChunk(nowMs); + TickClap(nowMs); + } + + internal enum ChunkResult { None, Busy, Done, Refused } + + /// Where a chunk in flight stands when no chat line has ended the wait. + internal enum ChunkWait { Waiting, Gone, TimedOut } + + /// + /// The wait for a chunk with no result line yet. The hammer destroys the target, so a target + /// that has left the pack was chunked: ILT does not always send a line the classifier knows + /// (Silentkelpie 2026-10-18: a Red Aetheria Chunk arrived and UseDone had no error, yet the + /// item was still filed as skipped after 10 s). Still carried after the wait = timed out. + /// Pure: the tests drive it. + /// + internal static ChunkWait WaitOutcome(long elapsedMs, bool targetStillCarried) + => !targetStillCarried ? ChunkWait.Gone + : elapsedMs >= ChunkResultWaitMs ? ChunkWait.TimedOut + : ChunkWait.Waiting; + + /// + /// What a chat line says about the chunk in flight. ILT names the item and the tool ("You + /// smash the Corrupted Sword with the Lugian Aetheria Hammer."), so a line naming a corrupted + /// item with the hammer, powder or shatter is a result too (combat's "You smash Foo for 147" + /// names neither). Pure: the tests drive it. + /// + internal static ChunkResult ClassifyChat(string text) + { + if (text.StartsWith("You're too busy", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You are too busy", StringComparison.OrdinalIgnoreCase)) + return ChunkResult.Busy; + if (ChunkRefusedLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase))) return ChunkResult.Refused; + if (ChunkDoneLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase))) return ChunkResult.Done; + if (text.Contains("corrupted", StringComparison.OrdinalIgnoreCase) + && (text.Contains("hammer", StringComparison.OrdinalIgnoreCase) || text.Contains("powder", StringComparison.OrdinalIgnoreCase) + || text.Contains("shatter", StringComparison.OrdinalIgnoreCase))) + return ChunkResult.Done; + return ChunkResult.None; + } + + public bool OnChat(string text) + { + if (_waitingOn == 0) return false; + switch (ClassifyChat(text)) + { + case ChunkResult.Busy: + _waitingOn = 0; // retry the same item next interval + break; + case ChunkResult.Done: + _chunked++; + _waitingOn = 0; + break; + case ChunkResult.Refused: + _skip.Add(_waitingOn); + _waitingOn = 0; + break; + } + return false; + } + + public void OnLogout() + { + _waitingOn = 0; + _skip.Clear(); + _lastSkip.Clear(); + _manualPass = false; + _clapWasEnabled = false; + } + + // ── UI (render thread) ────────────────────────────────────────────────── + + public void Render() + { + SafeImGui.TextColored(IltStyle.ColTeal, $"Chunking ({HammerName})"); + bool a = G.AutoChunkAetheria, c = G.AutoChunkCorrupted, comb = G.ChunkInCombat; + if (ImGui.Checkbox("Auto-chunk low aetheria", ref a)) G.AutoChunkAetheria = a; + ImGui.SameLine(); + if (ImGui.Checkbox("Auto-chunk corrupted weapons", ref c)) G.AutoChunkCorrupted = c; + if (ImGui.Checkbox("Allow while in combat mode", ref comb)) G.ChunkInCombat = comb; + int under = G.ChunkAetheriaUnderLevel; + ImGui.SetNextItemWidth(100); + if (ImGui.InputInt("Chunk aetheria with max level below", ref under)) G.ChunkAetheriaUnderLevel = ClampUnderLevel(under); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip($"Infinite Leaftide aetheria goes up to level {IltInventory.AetheriaMaxLevel}; {IltInventory.AetheriaMaxLevel + 1} chunks every level.\nA levelled Coalesced Aetheria gets the cap too; an unlevelled one (level 0 after appraisal) is chunked, as in ub-IT."); + bool kc = G.KeepAetheriaWithCrit, kcd = G.KeepAetheriaWithCritDamage, kcdr = G.KeepAetheriaWithCritDamageResist; + ImGui.TextUnformatted("Never chunk aetheria with:"); + ImGui.SameLine(); + if (ImGui.Checkbox("C##keepc", ref kc)) G.KeepAetheriaWithCrit = kc; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit rating (GearCrit)."); + ImGui.SameLine(); + if (ImGui.Checkbox("CD##keepcd", ref kcd)) G.KeepAetheriaWithCritDamage = kcd; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit Damage rating (GearCritDamage)."); + ImGui.SameLine(); + if (ImGui.Checkbox("CDR##keepcdr", ref kcdr)) G.KeepAetheriaWithCritDamageResist = kcdr; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit Damage Resist rating (GearCritDamageResist)."); + int ratingAt = G.KeepAetheriaRatingAtLeast; + ImGui.SetNextItemWidth(100); + if (ImGui.InputInt("Keep when the rating is at least##keeprating", ref ratingAt)) G.KeepAetheriaRatingAtLeast = ClampRatingLevel(ratingAt); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Rating level for the C / CD / CDR switches above (Coalesced Aetheria and revealed aetheria).\n" + + "At or above this level: kept. Below it: the rating does not protect the piece, so it chunks\n" + + "if the level cap and the other rules allow. 1 = any rating keeps."); + if (ImGui.TreeNode("Corrupted weapon keep rules##corrkeep")) + { + // ub-IT IdleActs > Corr Chunk: each matching rule keeps the weapon. + bool cb = G.KeepCorruptedCrushingBlow, bs = G.KeepCorruptedBitingStrike, acl = G.KeepCorruptedArmorCleaving; + bool sl = G.KeepCorruptedAnySlayer, ms = G.KeepCorruptedMultiStrike, el = G.KeepCorruptedElementalBonus, sp = G.KeepCorruptedAnySpell; + if (ImGui.Checkbox("Crushing Blow##ck", ref cb)) G.KeepCorruptedCrushingBlow = cb; + ImGui.SameLine(); + if (ImGui.Checkbox("Biting Strike##ck", ref bs)) G.KeepCorruptedBitingStrike = bs; + ImGui.SameLine(); + if (ImGui.Checkbox("Armor Cleaving##ck", ref acl)) G.KeepCorruptedArmorCleaving = acl; + if (ImGui.Checkbox("Any slayer##ck", ref sl)) G.KeepCorruptedAnySlayer = sl; + ImGui.SameLine(); + if (ImGui.Checkbox("Multi-strike##ck", ref ms)) G.KeepCorruptedMultiStrike = ms; + ImGui.SameLine(); + if (ImGui.Checkbox("Elemental bonus##ck", ref el)) G.KeepCorruptedElementalBonus = el; + if (ImGui.Checkbox("Any spell##ck", ref sp)) G.KeepCorruptedAnySpell = sp; + int maxDmg = G.KeepCorruptedMaxDamageAtLeast; + ImGui.SetNextItemWidth(100); + if (ImGui.InputInt("Keep max damage at least (0 = off)##ck", ref maxDmg)) G.KeepCorruptedMaxDamageAtLeast = Math.Max(0, maxDmg); + string ids = G.KeepCorruptedSpellIds ?? ""; + ImGui.SetNextItemWidth(220); + if (ImGui.InputText("Keep spell ids##ck", ref ids, 512)) G.KeepCorruptedSpellIds = ids; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Comma or space separated spell ids: a corrupted weapon carrying any of them is kept."); + SafeImGui.TextDisabled("Always kept: tinkered, imbued, no workmanship, cleave over 1 (2 on two-handed, non-thrust)."); + ImGui.TreePop(); + } + if (ImGui.Button("Chunk eligible items now...")) _ctx.Confirm("Chunk items", + "Run one chunk pass now on every eligible aetheria and corrupted weapon?\nChunked items are destroyed.", + ChunkNow, "Chunk"); + SafeImGui.TextDisabled("Status: " + _chunkStatus); + + ImGui.Separator(); + ImGui.TextColored(IltStyle.ColTeal, "Clap (/clap all)"); + if (_ctx.Options.IsOff(IltFeature.Clap)) + { + ImGui.TextColored(IltStyle.ColTextMute, "Not available (server off or AutoCraftingEnabled stamp missing)."); + return; + } + bool ac = G.AutoClap; + if (ImGui.Checkbox("Auto-clap periodically", ref ac)) G.AutoClap = ac; + int mins = G.ClapIntervalMinutes; + ImGui.SetNextItemWidth(100); + if (ImGui.InputInt("Interval (min)", ref mins)) G.ClapIntervalMinutes = Math.Max(5, mins); + if (ImGui.SmallButton("Clap now")) _ctx.Post(() => ClapNow(manual: true)); + ImGui.SameLine(); + SafeImGui.TextDisabled(_clapStatus); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltDynamicStampList.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltDynamicStampList.cs new file mode 100644 index 0000000..29c3903 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltDynamicStampList.cs @@ -0,0 +1,274 @@ +// IltDynamicStampList.cs - Infinite Leaftide's Dynamic Stamps: the list (Resources\dynstamps.csv) and +// the rules that tell a stamp had from one missing. SilentKelpie's (RynthSuite PR 12, RynthOracle 0.6.0, +// ported by hand onto our lineage 2026-10-19), where the stamps were rows of RynthOracle's Quests list; +// moved here on 2026-10-21 with RynthOracle's other Infinite Leaftide parts (one server's features live +// in its server plugin). The page that shows them is IltDynamicStamps.cs. +// The flags come from /myquests through RynthOracle's parser (QuestFlags.cs, linked source). +// Pure: RynthILT.Tests covers it. +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using RynthCore.Plugin.RynthOracle.Data; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// +/// One Infinite Leaftide Dynamic Stamp (dynstamps.csv): an NPC hand-in that puts a +/// "Dynamic_N_..." quest flag on the character. List from the players' "ExtraDyn" sheet +/// (10.13.2026, one sheet per area, the wiki's Dynamic Stamps page); NPCs that give no stamp +/// are left out. A stamp is a one-time flag: having it in /myquests means it's done. +/// +internal sealed class DynamicStamp +{ + public string Area = ""; + /// Where in the area (a town, a dungeon, coordinates), or "". + public string Place = ""; + public string Npc = ""; + /// What the NPC gives back (the sheet's "X gives you Y"), or "". + public string Reward = ""; + /// The quest flag, lower case (as QuestFlagStore keys it). + public string Stamp = ""; + public string Note = ""; + + /// The NPC, else the place (a few sheet rows only name the spot). + public string Label => Npc.Length > 0 ? Npc : Place; + + /// + /// The flag this character has for the stamp, or null. The sheet has a few stamps copied + /// without their closing "!" or cut short: those also match with "!" added and, when at + /// least long, the one Dynamic flag on the character starting + /// with them. + /// + public string? MatchedFlag(QuestFlagStore flags) + { + if (flags.TryGet(Stamp, out _)) return Stamp; + if (Stamp.EndsWith('!')) return null; + if (flags.TryGet(Stamp + "!", out _)) return Stamp + "!"; + if (Stamp.Length < MinPrefixLength) return null; + string? only = null; + foreach (string key in flags.Flags.Keys) + { + if (!key.StartsWith(Stamp, StringComparison.OrdinalIgnoreCase)) continue; + if (only != null) return null; // more than one: can't tell which + only = key; + } + return only; + } + + public bool Have(QuestFlagStore flags) => MatchedFlag(flags) != null; + + // Sheet areas that are groupings, not places on the map. + private static readonly HashSet NotPlaces = new(StringComparer.OrdinalIgnoreCase) + { + "Looking Around", "Odd Stamps", "Odd Stamps 2", + }; + + /// + /// Where RynthNav should go for this stamp, best first (RynthNav takes the first that is on its + /// map): the coordinates in the note or the place, the place and its parts ("Mhoire Castle - + /// Great Hall" also tries "Mhoire Castle"), the NPC, then the area. Empty when there is nothing. + /// + public List NavCandidates() + { + var list = new List(); + void Add(string s) + { + s = s.Trim().Trim('.', ',', ';', ':').Trim(); + if (s.Length >= 4 && !char.IsDigit(s[0]) && !list.Contains(s, StringComparer.OrdinalIgnoreCase)) list.Add(s); + } + + foreach (string text in new[] { Note, Place }) + if (NavTargets.FirstCoords(text) is string c && !list.Contains(c)) list.Add(c); + + string place = NavTargets.WithoutCoords(Place); + place = Regex.Replace(place, @"\b(at|in the|nearby)\b", " ", RegexOptions.IgnoreCase); + place = Regex.Replace(place, @"\s+", " ").Trim(); + Add(place); + foreach (string part in place.Split(new[] { " - ", " / ", "(", ")" }, StringSplitOptions.RemoveEmptyEntries)) + Add(part); + Add(Npc); + if (!NotPlaces.Contains(Area)) Add(Area); + return list; + } + + /// A truncated stamp shorter than this is matched exactly only (too many flags share a short stem). + public const int MinPrefixLength = 14; +} + +internal static class DynamicStampList +{ + /// Dynamic stamp quest flags start with this (lower case). + public const string FlagPrefix = "dynamic_"; + + /// The embedded list's resource name (the csproj). + public const string ResourceName = "RynthILT.dynstamps.csv"; + + public static List All { get; } = Load(); + + /// The areas in list order (Facility Hub, Looking Around, ...). + public static List Areas { get; } = BuildAreas(); + + /// + /// Dynamic stamps on this character that the list doesn't have (new or unlisted NPCs), so the + /// page can show them and the count isn't only what the sheet knows. + /// + public static List Unlisted(QuestFlagStore flags) + { + var matched = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (DynamicStamp s in All) + if (s.MatchedFlag(flags) is string f) matched.Add(f); + var extra = new List(); + foreach (string key in flags.Flags.Keys) + if (key.StartsWith(FlagPrefix, StringComparison.OrdinalIgnoreCase) && !matched.Contains(key)) + extra.Add(key); + extra.Sort(StringComparer.OrdinalIgnoreCase); + return extra; + } + + private static List Load() + { + try + { + using Stream? stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName); + if (stream == null) return new List(); + using var r = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true); + return Parse(r); + } + catch (Exception) + { + // A missing or unreadable list must not take the page down with it. + return new List(); + } + } + + /// + /// Reads a dynstamps.csv (a header row, then one NPC hand-in a row). A row whose stamp isn't a + /// "dynamic_" flag, or repeats one already read, is skipped; a missing column reads as empty. + /// Internal for the tests. + /// + internal static List Parse(TextReader r) + { + var list = new List(); + Dictionary col = Csv.MapColumns(r.ReadLine() ?? ""); + int cArea = Csv.Column(col, "Area"), cPlace = Csv.Column(col, "Place"), cNpc = Csv.Column(col, "Npc"), + cReward = Csv.Column(col, "Reward"), cStamp = Csv.Column(col, "Stamp"), cNote = Csv.Column(col, "Note"); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + while (r.ReadLine() is string line) + { + if (string.IsNullOrWhiteSpace(line)) continue; + string[] f = Csv.ParseLine(line); + string stamp = Csv.Field(f, cStamp).Trim().ToLowerInvariant(); + if (!stamp.StartsWith(FlagPrefix, StringComparison.Ordinal) || !seen.Add(stamp)) continue; + list.Add(new DynamicStamp + { + Area = Csv.Field(f, cArea), + Place = Csv.Field(f, cPlace), + Npc = Csv.Field(f, cNpc), + Reward = Csv.Field(f, cReward), + Stamp = stamp, + Note = Csv.Field(f, cNote), + }); + } + return list; + } + + private static List BuildAreas() + { + var areas = new List(); + foreach (DynamicStamp s in All) + if (!areas.Contains(s.Area)) areas.Add(s.Area); + return areas; + } +} + +/// +/// What the Dynamic Stamps page lists and sends, worked out without the game (the page's buttons and +/// RynthILT.Tests use it): the rows with their status, the filters, RynthNav's line and the hand-in. +/// +internal static class DynamicStampText +{ + /// One listed stamp and whether this character has it. + internal sealed record Row(DynamicStamp Stamp, bool Have); + + /// The Show filter: every stamp, the missing ones, or the ones had. + internal enum Show { All, Missing, Have } + + /// Every listed stamp, in list order, with its status from . + public static List Rows(IReadOnlyList stamps, QuestFlagStore flags) + { + var rows = new List(stamps.Count); + foreach (DynamicStamp s in stamps) rows.Add(new Row(s, s.Have(flags))); + return rows; + } + + /// + /// The rows the page shows: in ("" = every area), matching + /// , and with every word of in the NPC, place, + /// reward, area, stamp or note (any case). + /// + public static List Filter(IReadOnlyList rows, string? search, string? area, Show show) + { + string[] terms = (search ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + var shown = new List(); + foreach (Row r in rows) + { + DynamicStamp s = r.Stamp; + if (!string.IsNullOrEmpty(area) && !string.Equals(s.Area, area, StringComparison.Ordinal)) continue; + if (show == Show.Missing && r.Have || show == Show.Have && !r.Have) continue; + string hay = $"{s.Npc} {s.Place} {s.Reward} {s.Area} {s.Stamp} {s.Note}"; + bool all = true; + foreach (string t in terms) + if (hay.IndexOf(t, StringComparison.OrdinalIgnoreCase) < 0) { all = false; break; } + if (all) shown.Add(r); + } + return shown; + } + + /// + /// "<verb> a || b || c" for RynthNav's "/rnav" (go walks the route, route plans it in chat, + /// arrow points at it; RynthNav takes the first candidate on its map), or "" when there is nowhere to go. + /// + public static string NavLine(string verb, DynamicStamp s) + { + List targets = s.NavCandidates(); + return targets.Count == 0 ? string.Empty : verb + " " + string.Join(" || ", targets); + } + + /// A name made safe to put inside a chat command: no control characters. + public static string ForCommand(string name) + { + var sb = new StringBuilder(name.Length); + foreach (char ch in name) if (ch >= ' ' && ch != '\u007f') sb.Append(ch); + return sb.ToString().Trim(); + } + + /// "/ub give 1 <parchment> to <npc>": RynthAi finds the NPC by name and hands it over. + public static string GiveCommand(string parchment, string npc) => $"/ub give 1 {ForCommand(parchment)} to {ForCommand(npc)}"; + + /// True for RynthAi's answer to a "/ub give" it doesn't have. + public static bool IsGiveRejection(string? line) => line != null && line.IndexOf("Unrecognized /ub", StringComparison.OrdinalIgnoreCase) >= 0; + + /// Why Give Parchment can't be used now (its tooltip); null when it can. + public static string? GiveUnavailableReason(bool rynthAiLoaded, bool giveMissing) + { + if (giveMissing) + return "The loaded RynthAi has no \"/ub give\" (it answered \"Unrecognized /ub command\"). Update RynthAi, or hand the Parchment over yourself."; + if (!rynthAiLoaded) + return "Needs RynthAi: the hand-in is RynthAi's \"/ub give\". It isn't loaded (or you aren't logged in), so give the Parchment to the NPC yourself."; + return null; + } + + /// The chat lines for a stamp: the NPC, its stamp and whether this character has it, where, the reward and any coordinates. + public static List PrintLines(DynamicStamp s, bool have) + { + string where = s.Place.Length > 0 ? $"{s.Area}, {s.Place}" : s.Area; + string details = where + (s.Reward.Length > 0 ? $" - gives {s.Reward}" : "") + (s.Note.Length > 0 ? $" - {s.Note}" : ""); + var lines = new List { $"{s.Label} ({s.Stamp}) - {(have ? "have" : "missing")}" }; + if (details.Length > 0) lines.Add(details); + return lines; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltDynamicStamps.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltDynamicStamps.cs new file mode 100644 index 0000000..1d88614 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltDynamicStamps.cs @@ -0,0 +1,411 @@ +// IltDynamicStamps.cs - The Dynamic Stamps page: Infinite Leaftide's NPC hand-ins that put a one-time +// "Dynamic_N_..." flag on the character, which of them this character has, RynthNav's way there and +// the Parchment hand-in. SilentKelpie's (RynthSuite PR 12, RynthOracle 0.6.0, ported by hand onto our +// lineage 2026-10-19), first as rows of RynthOracle's Quests list ("/ro dynamic"); moved here on +// 2026-10-21 as RynthILT's own page: the Mini Remote's Quests section ("Dynamic Stamps", surface +// "section:ilt-dynstamps") and its own window ("/ilt stamps"). The list and its rules are +// IltDynamicStampList.cs. +// +// Quest flags: RynthILT reads every /myquests reply that passes through chat (RynthOracle's at login, +// the player's, RynthAi's polls) with RynthOracle's /myquests parser (QuestFlags.cs, linked source). +// "Read quest flags" sends one of its own and hides that reply. Go / Route / Arrow ask RynthNav +// ("/rnav a || b"); Give Parchment hands one Parchment from the packs to the stamp's NPC through +// RynthAi's "/ub give" (asked first, disabled without RynthAi or when it answers "Unrecognized /ub +// command"), then the flags are read again once the NPC has had time to answer. +// +// Threads: OnChat / Tick on the pump (dormant off ILT, as every Hub feature); Render on the render +// thread, reading the pump's snapshot and posting its buttons (IltHubContext.Post / Confirm). +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Threading; +using ImGuiNET; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltDynamicStamps : IIltFeature +{ + /// The page counts as on screen this long after it was last drawn. + private const long WatchMs = 4000; + /// The packs are scanned for a Parchment at most this often while the page is on screen. + private const long ParchmentScanMs = 1500; + /// A /myquests read this long after a Parchment hand-in (the walk there and the NPC's answer). + internal const long HandInRefreshMs = 8000; + /// "Unrecognized /ub command" this soon after a give is the answer to it. + private const long GiveRejectionMs = 5000; + /// The RynthNav plugin and its command broker action. + private const string NavPlugin = "RynthNav", NavAction = "rnav"; + + private readonly IltHubContext _ctx; + private readonly QuestFlagStore _flags = new(); + + // Pump state. + private int _builtRevision = -1; + private string? _builtParchment; + private bool _builtGiveOk; + private long _parchmentScanAt; + private string? _parchment; + private long _refreshAt; + private long _giveSentAt = long.MinValue / 2; + private bool _giveMissing; + + // Shared: the render thread's last draw, the pump's snapshot and the last action's outcome. + private long _watchedAt = long.MinValue / 2; + private volatile Snapshot _snap = Snapshot.Empty; + private volatile string _status = string.Empty; + + // Render thread only: the filters and the opened stamp. + private string _search = string.Empty; + private int _area; // 0 = every area, else DynamicStampList.Areas[n - 1] + private int _show; // DynamicStampText.Show + private string _selected = string.Empty; + + /// What the page draws, built on the pump. + internal sealed class Snapshot + { + public static readonly Snapshot Empty = new(); + public bool Built; + public IReadOnlyList Rows = Array.Empty(); + public IReadOnlyList Unlisted = Array.Empty(); + public int Have; + public bool Loading, Disabled; + public DateTime LastReadUtc = DateTime.MinValue; + public long ThrottledUntilMs = long.MinValue / 2; + /// A Parchment carried (null = none). + public string? Parchment; + /// Why Give Parchment can't be used (null = it can). + public string? GiveReason; + } + + public IltDynamicStamps(IltHubContext ctx) => _ctx = ctx; + + /// The flags read from /myquests (tests read them). + internal QuestFlagStore Flags => _flags; + + /// The last snapshot (tests). + internal Snapshot Current => _snap; + + /// The last action's outcome ("" = none yet). + internal string Status => _status; + + /// Render thread (or a test): the page is on screen, so the pump keeps its snapshot fresh. + internal void MarkWatched() => Interlocked.Exchange(ref _watchedAt, IltHubContext.NowMs); + + /// AC's thread (the chat bar): a "/myquests" went out, RynthILT's own or typed. Only interlocked state. + public void NoteTypedMyQuests() => _flags.NoteTypedCommand(); + + // ── Pump ─────────────────────────────────────────────────────────────── + + public bool OnChat(string text) + { + long now = IltHubContext.NowMs; + if (now - _giveSentAt < GiveRejectionMs && !_giveMissing && DynamicStampText.IsGiveRejection(text)) + { + _giveMissing = true; + _status = "RynthAi has no \"/ub give\": hand the Parchment over yourself."; + } + MyQuestsLine kind = _flags.OnChatLine(text, now); + // Only the reply to RynthILT's own request is hidden; the player's and other plugins' show as they would. + return _flags.AwaitingOurs && kind is MyQuestsLine.Quest or MyQuestsLine.Empty; + } + + public void Tick(long nowMs) + { + _flags.Tick(nowMs); + RefreshAfterHandIn(nowMs); + if (nowMs - Interlocked.Read(ref _watchedAt) >= WatchMs) return; + if (_parchmentScanAt == 0 || nowMs - _parchmentScanAt >= ParchmentScanMs) + { + _parchmentScanAt = nowMs; + _parchment = CarriedParchment(); + } + bool giveOk = DynamicStampText.GiveUnavailableReason(_ctx.Ai.Available, _giveMissing) == null; + if (_flags.Revision == _builtRevision && _parchment == _builtParchment && giveOk == _builtGiveOk && _snap.Built) return; + _builtRevision = _flags.Revision; + _builtParchment = _parchment; + _builtGiveOk = giveOk; + Rebuild(); + } + + /// The snapshot from the flags, the carried Parchment and RynthAi's state. Pump thread. + internal void Rebuild() + { + List rows = DynamicStampText.Rows(DynamicStampList.All, _flags); + int have = 0; + foreach (DynamicStampText.Row r in rows) if (r.Have) have++; + _snap = new Snapshot + { + Built = true, + Rows = rows, + Unlisted = DynamicStampList.Unlisted(_flags), + Have = have, + Loading = _flags.Loading, + Disabled = _flags.ServerDisabled, + LastReadUtc = _flags.LastReadUtc, + ThrottledUntilMs = _flags.ThrottledUntilMs, + Parchment = _parchment, + GiveReason = DynamicStampText.GiveUnavailableReason(_ctx.Ai.Available, _giveMissing), + }; + } + + public void OnLogout() + { + _flags.Clear(); + _snap = Snapshot.Empty; + _builtRevision = -1; + _parchment = _builtParchment = null; + _parchmentScanAt = 0; + _refreshAt = 0; + _giveSentAt = long.MinValue / 2; + _giveMissing = false; + _status = string.Empty; + } + + /// Sends /myquests (its reply hidden). Pump thread. + internal void RequestFlags() + { + long now = IltHubContext.NowMs; + if (_flags.Request(cmd => _ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser(cmd), now)) + { + _status = "Reading your quest flags (/myquests)..."; + return; + } + int wait = _flags.ThrottleSecondsLeft(now); + _status = wait > 0 ? $"The server answers one /myquests a minute; try again in {wait}s (the stamps shown are kept)." + : _flags.Loading ? "Your quest flags are already being read." + : "Your quest flags were asked for a moment ago; wait a few seconds."; + } + + /// The read after a hand-in, when it is due: now, or when the server's once-a-minute wait ends. + private void RefreshAfterHandIn(long now) + { + if (_refreshAt == 0 || now < _refreshAt || _flags.Loading) return; + int wait = _flags.ThrottleSecondsLeft(now); + if (wait > 0) { _refreshAt = now + wait * 1000L; return; } + _refreshAt = 0; + _flags.Request(cmd => _ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser(cmd), now); + } + + /// "/rnav <verb> a || b || c" to RynthNav. Pump thread. + internal void Nav(string verb, DynamicStamp s) + { + string line = DynamicStampText.NavLine(verb, s); + if (line.Length == 0) return; + bool sent = _ctx.Host.HasSendPluginCommand && _ctx.Host.SendPluginCommand(NavPlugin, NavAction, line); + _status = !sent ? "RynthNav isn't loaded (it plans and walks the route)." + : verb == "go" ? "RynthNav is planning the route and walking it (its chat lines say how)." + : verb == "arrow" ? "RynthNav's arrow points at it." + : "RynthNav's route is in chat. Go walks it."; + } + + /// The stamp in chat (RynthChat makes coordinates a RynthNav arrow link). Pump thread. + internal void Print(DynamicStamp s) + { + bool have = s.Have(_flags); + foreach (string line in DynamicStampText.PrintLines(s, have)) _ctx.Chat("[ILT Stamps] " + line); + } + + /// Hands one to the stamp's NPC (RynthAi's "/ub give"). Pump thread. + internal void Give(DynamicStamp s, string parchment) + { + string? why = DynamicStampText.GiveUnavailableReason(_ctx.Ai.Available, _giveMissing); + if (why != null) { _status = why; return; } + long now = IltHubContext.NowMs; + _giveSentAt = now; // an "Unrecognized /ub command" in the next moments turns the button off + bool sent = _ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser(DynamicStampText.GiveCommand(parchment, s.Npc)); + _parchmentScanAt = 0; // read the packs again after the give + // The stamp is a quest flag: read /myquests again once the NPC has had time to answer. + if (sent) _refreshAt = now + HandInRefreshMs; + _status = sent + ? $"Giving {parchment} to {s.Npc} (RynthAi does the give; it says so in chat if {s.Npc} isn't in sight)." + : "Could not send the give."; + } + + /// + /// The name of a Parchment carried (the main pack and its side packs, one level deep as AC packs + /// go), or null: any item whose name has "Parchment" in it. Pump thread. + /// + private string? CarriedParchment() + { + var host = _ctx.Host; + uint me = host.GetPlayerId(); + if (me == 0 || !host.HasGetContainerContents) return null; + var buf = new uint[512]; + var packs = new List { me }; + for (int p = 0; p < packs.Count && p < 16; p++) + { + int n = Math.Min(host.GetContainerContents(packs[p], buf), buf.Length); + for (int i = 0; i < n; i++) + { + uint id = buf[i]; + if (!host.TryGetObjectName(id, out string name)) continue; + if (name.IndexOf("Parchment", StringComparison.OrdinalIgnoreCase) >= 0) return name; + if (p == 0) packs.Add(id); + } + } + return null; + } + + // ── UI (render thread) ──────────────────────────────────────────────── + + private static readonly string[] ShowNames = { "Every stamp", "Missing", "Had" }; + + /// The page's body, into the current window (the Mini Remote's view or "/ilt stamps"). + public void Render() + { + MarkWatched(); + Snapshot s = _snap; + SafeImGui.TextColored(IltStyle.ColTeal, "Dynamic Stamps"); + ImGui.SameLine(); + ImGui.TextDisabled("one-time quest flags (Dynamic_1_...) from handing items to NPCs"); + if (!s.Built) + { + ImGui.TextDisabled("Reading the list..."); + return; + } + + int listed = s.Rows.Count; + string bar = $"{s.Have} / {listed} listed stamps" + (s.Unlisted.Count > 0 ? $" (+{s.Unlisted.Count} not in the list)" : ""); + ImGui.ProgressBar(listed == 0 ? 0f : (float)s.Have / listed, new Vector2(-1, 0), bar); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("List: the players' ExtraDyn sheet (10.13.2026). Click a stamp for RynthNav's route to it and the Parchment hand-in."); + + long now = IltHubContext.NowMs; + if (s.Disabled) SafeImGui.TextColored(IltStyle.ColHp, "This server has /myquests turned off, so the stamps can't be read."); + else if (s.Loading) SafeImGui.TextColored(IltStyle.ColAmber, "Reading your quest flags..."); + else if (s.LastReadUtc == DateTime.MinValue) ImGui.TextDisabled("Quest flags not read yet: press Read quest flags (or type /myquests)."); + else SafeImGui.TextDisabled($"Quest flags read at {s.LastReadUtc.ToLocalTime():HH:mm}."); + if (ImGui.SmallButton("Read quest flags##dystamps")) _ctx.Post(RequestFlags); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Sends /myquests (the reply is hidden). The server answers one a minute."); + if (now < s.ThrottledUntilMs) + { + ImGui.SameLine(); + SafeImGui.TextDisabled($"again in {(s.ThrottledUntilMs - now + 999) / 1000}s"); + } + + ImGui.SetNextItemWidth(180); + ImGui.InputText("Search##dystamps", ref _search, 64u); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Words to find: an NPC, place, area, reward, stamp or note."); + ImGui.SameLine(); + var areas = new List(DynamicStampList.Areas.Count + 1) { "Every area" }; + areas.AddRange(DynamicStampList.Areas); + _area = Math.Clamp(_area, 0, areas.Count - 1); + ImGui.SetNextItemWidth(150); + ImGui.Combo("##dystamps.area", ref _area, areas.ToArray(), areas.Count); + ImGui.SameLine(); + _show = Math.Clamp(_show, 0, ShowNames.Length - 1); + ImGui.SetNextItemWidth(110); + ImGui.Combo("##dystamps.show", ref _show, ShowNames, ShowNames.Length); + + string? area = _area > 0 ? areas[_area] : null; + List rows = DynamicStampText.Filter(s.Rows, _search, area, (DynamicStampText.Show)_show); + SafeImGui.TextDisabled($"{rows.Count} shown"); + + DynamicStamp? open = null; + bool openHave = false; + float height = Math.Max(120f, ImGui.GetContentRegionAvail().Y - (_selected.Length > 0 ? 170f : 40f)); + const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.ScrollY | ImGuiTableFlags.SizingStretchProp; + if (ImGui.BeginTable("##dystamps", 4, flags, new Vector2(0, height))) + { + ImGui.TableSetupScrollFreeze(0, 1); + ImGui.TableSetupColumn("##have", ImGuiTableColumnFlags.WidthFixed, 40); + ImGui.TableSetupColumn("NPC", ImGuiTableColumnFlags.None, 1.2f); + ImGui.TableSetupColumn("Area", ImGuiTableColumnFlags.None, 0.9f); + ImGui.TableSetupColumn("Place", ImGuiTableColumnFlags.None, 1.3f); + ImGui.TableHeadersRow(); + for (int i = 0; i < rows.Count; i++) + { + DynamicStampText.Row r = rows[i]; + DynamicStamp st = r.Stamp; + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + SafeImGui.TextColored(r.Have ? IltStyle.ColGreen : IltStyle.ColHp, r.Have ? "have" : "need"); + ImGui.TableNextColumn(); + bool selected = _selected == st.Stamp; + if (ImGui.Selectable(Cut(st.Label, 40) + "##dy" + i, selected, ImGuiSelectableFlags.SpanAllColumns)) + { + _selected = selected ? string.Empty : st.Stamp; + // As its Quests row did: picking a stamp asks RynthNav for the route at once. + if (!selected && st.NavCandidates().Count > 0) _ctx.Post(() => Nav("route", st)); + } + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(Tooltip(st)); + ImGui.TableNextColumn(); + SafeImGui.TextDisabled(Cut(st.Area, 28)); + ImGui.TableNextColumn(); + SafeImGui.TextDisabled(Cut(st.Place, 40)); + if (selected) { open = st; openHave = r.Have; } + } + ImGui.EndTable(); + } + if (rows.Count == 0) ImGui.TextDisabled("No stamps match."); + + if (_selected.Length > 0 && open == null) + foreach (DynamicStampText.Row r in s.Rows) + if (r.Stamp.Stamp == _selected) { open = r.Stamp; openHave = r.Have; break; } + if (open != null) RenderSelected(s, open, openHave); + + if (s.Unlisted.Count > 0 && ImGui.CollapsingHeader($"On this character, not in the list ({s.Unlisted.Count})##dyunlisted")) + foreach (string f in s.Unlisted) SafeImGui.TextDisabled(f); + string status = _status; + if (status.Length > 0) SafeImGui.TextDisabled(status); + } + + /// The opened stamp: where RynthNav goes, Go / Route / Arrow, Chat, and the Parchment hand-in. + private void RenderSelected(Snapshot s, DynamicStamp st, bool have) + { + List targets = st.NavCandidates(); + ImGui.SeparatorText("Navigate to " + Cut(st.Label, 40)); + SafeImGui.TextDisabled(targets.Count == 0 + ? "No place, coordinates or area to go to for this stamp." + : "Where: " + Cut(string.Join(" or ", targets), 90)); + if (targets.Count > 0) + { + if (ImGui.Button("Go (auto nav)##dynav")) _ctx.Post(() => Nav("go", st)); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("RynthNav plans the route (walking, portals, recalls, the dungeon's entrance) and walks it."); + ImGui.SameLine(); + if (ImGui.Button("Route##dynav")) _ctx.Post(() => Nav("route", st)); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Only plan it: RynthNav prints the steps in chat."); + ImGui.SameLine(); + if (ImGui.Button("Arrow##dynav")) _ctx.Post(() => Nav("arrow", st)); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Only point RynthNav's arrow at it."); + ImGui.SameLine(); + } + if (ImGui.Button("Chat##dynav")) _ctx.Post(() => Print(st)); + ImGui.SameLine(); + if (ImGui.Button("Close##dynav")) _selected = string.Empty; + SafeImGui.TextColored(have ? IltStyle.ColGreen : IltStyle.ColAmber, have ? "You have this stamp." : "You don't have this stamp yet."); + + // The hand-in: a Parchment from your packs to the stamp's NPC (RynthAi's /ub give), asked first. + if (st.Npc.Length == 0) return; + string? parchment = s.Parchment; + if (parchment == null) + { + SafeImGui.TextDisabled("No Parchment in your packs to give " + Cut(st.Npc, 30) + "."); + return; + } + if (s.GiveReason != null) + { + // Greyed text in place of the button, so it can't be clicked into a command nobody answers. + SafeImGui.TextDisabled("[Give " + Cut(parchment, 24) + "]"); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(s.GiveReason); + return; + } + if (ImGui.Button("Give " + Cut(parchment, 24).Replace("#", "") + "##dygive")) + _ctx.Confirm("Give Parchment", $"Give one {parchment} to {st.Npc}? It leaves your pack for good.", () => Give(st, parchment), "Give it"); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip($"Hands one {parchment} to {st.Npc} (it asks first). Stand near them (or Go first): AC walks you the last bit."); + } + + /// A stamp's hover text: area, place, reward and note. + private static string Tooltip(DynamicStamp s) + { + var parts = new List(4); + foreach (string p in new[] { s.Area, s.Place, s.Reward.Length > 0 ? "gives " + s.Reward : "", s.Note }) + if (!string.IsNullOrWhiteSpace(p)) parts.Add(p); + return Cut(string.Join(" - ", parts), 300); + } + + private static string Cut(string s, int max) => s.Length <= max ? s : s.Substring(0, Math.Max(0, max - 3)) + "..."; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltEquipSuits.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltEquipSuits.cs new file mode 100644 index 0000000..23a2345 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltEquipSuits.cs @@ -0,0 +1,265 @@ +// IltEquipSuits.cs — UtilityBelt-style equipment profiles (.utl VTank loot files) (Gear tab, P2). +// +// A suit is a VTank loot profile: every carried wearable whose first matching rule is +// Keep belongs to the suit. Loading a suit: +// 1. dequip phase — equipped wearables NOT in the suit go to a pack with a free slot +// (IltObjects.FindPackFor; never into a full pack — that crashes the client); +// 2. equip phase — suit items that aren't worn are used (AC equips on use). +// One action per 100 ms tick and only while not busy. An item is abandoned after 15 +// attempts; the whole load bails after 10 s with no progress. +// The profile is matched by RynthAi's VTank loot evaluator (RynthAi.Hub LootKeeps), so suits need +// RynthAi. Search order: RynthILT EquipProfiles\, EquipProfiles, the same two in the RynthAi +// folder (where they lived before the move), then UB's equip folders. +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using ImGuiNET; +using RynthCore.Loot; +using RynthCore.Install; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltEquipSuits : IIltFeature +{ + private const int MaxAttemptsPerItem = 15; + private const long NoProgressBailMs = 10_000; + private const long StepMs = 100; + + private readonly IltHubContext _ctx; + + // Load job (pump thread) + private readonly Queue _dequip = new(); + private readonly Queue _equip = new(); + private readonly Dictionary _attempts = new(); + private bool _running; + private long _lastStep, _lastProgress; + private int _doneCount; + private volatile string _status = "idle"; + + // Render snapshots + private volatile string[] _profiles = Array.Empty(); + private volatile string[] _preview = Array.Empty(); + private int _selected; + + public IltEquipSuits(IltHubContext ctx) => _ctx = ctx; + + private static readonly AcObjectClass[] WearableClasses = + { + AcObjectClass.Armor, AcObjectClass.Clothing, AcObjectClass.Gem, AcObjectClass.Jewelry, + AcObjectClass.MeleeWeapon, AcObjectClass.MissileWeapon, AcObjectClass.WandStaffOrb, + }; + + // ── Profile discovery ─────────────────────────────────────────────────── + + private IEnumerable SearchDirs() + { + foreach (string baseDir in new[] { IltHubStore.SharedRoot, RynthInstallPaths.RynthAiDir }) + { + string root = Path.Combine(baseDir, "EquipProfiles"); + if (_ctx.CharName.Length > 0) yield return Path.Combine(root, _ctx.CharName); + yield return root; + } + string ub = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Decal Plugins", "UtilityBelt"); + string world = _ctx.Options.WorldName; + if (world.Length > 0 && _ctx.CharName.Length > 0) yield return Path.Combine(ub, world, _ctx.CharName, "equip"); + if (world.Length > 0) yield return Path.Combine(ub, world, "equip"); + yield return Path.Combine(ub, "equip"); + } + + /// All .utl profiles, first directory wins for duplicate names. + public List<(string Name, string Path)> ListProfiles() + { + var seen = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (string dir in SearchDirs()) + { + try + { + if (!Directory.Exists(dir)) continue; + foreach (string f in Directory.GetFiles(dir, "*.utl")) + { + string n = Path.GetFileNameWithoutExtension(f); + if (!seen.ContainsKey(n)) seen[n] = f; + } + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltGear, ex, $"equip dir {dir}"); } + } + return seen.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase).Select(k => (k.Key, k.Value)).ToList(); + } + + private string? ResolveProfile(string? name) + { + if (string.IsNullOrWhiteSpace(name)) name = _ctx.CharName; + name = name!.Trim(); + if (name.EndsWith(".utl", StringComparison.OrdinalIgnoreCase)) name = name[..^4]; + return ListProfiles().FirstOrDefault(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Path; + } + + /// Items the suit wants worn (first matching rule is Keep; RynthAi evaluates the profile). + private List? SuitItems(string path, out string error) + { + error = string.Empty; + var candidates = new List(); + foreach (var wo in _ctx.Inventory.Items()) + { + if (Array.IndexOf(WearableClasses, wo.ObjectClass) < 0) continue; + if (_ctx.Inventory.Int(wo, IltInventory.IntValidLocations) == 0) continue; + candidates.Add(wo); + } + uint[] ids = candidates.Select(w => unchecked((uint)w.Id)).ToArray(); + if (!_ctx.Ai.LootKeeps(path, ids, out bool[] keep, out error)) return null; + var list = new List(); + for (int i = 0; i < candidates.Count; i++) + if (keep[i]) list.Add(candidates[i]); + return list; + } + + // ── Commands (pump thread) ────────────────────────────────────────────── + + public void RefreshProfileList() => _profiles = ListProfiles().Select(p => p.Name).ToArray(); + + /// Lists what a load would do without doing it. Returns lines (also shown in the UI). + public List Test(string? name) + { + var lines = new List(); + string? path = ResolveProfile(name); + if (path == null) { lines.Add($"Profile not found: {name ?? _ctx.CharName}"); _preview = lines.ToArray(); return lines; } + var suit = SuitItems(path, out string err); + if (suit == null) { lines.Add(err); _preview = lines.ToArray(); return lines; } + var suitIds = suit.Select(s => s.Id).ToHashSet(); + foreach (var wo in _ctx.Inventory.Items().Where(w => _ctx.Inventory.IsEquipped(w) && !suitIds.Contains(w.Id) + && Array.IndexOf(WearableClasses, w.ObjectClass) >= 0)) + lines.Add("dequip " + wo.Name); + foreach (var wo in suit.Where(w => !_ctx.Inventory.IsEquipped(w))) lines.Add("equip " + wo.Name); + if (lines.Count == 0) lines.Add("Already wearing this suit."); + _preview = lines.ToArray(); + return lines; + } + + /// Starts loading a suit. + public string Load(string? name) + { + RynthLog.Trace(LogCat.IltGear, $"Suits.Load(name='{name}')"); + if (_running) return "A suit load is already running."; + if (!_ctx.Host.HasMoveItemInternal || !_ctx.Host.HasUseObject) return "Engine lacks MoveItemInternal/UseObject."; + string? path = ResolveProfile(name); + if (path == null) return $"Profile not found: {name ?? _ctx.CharName}"; + var suit = SuitItems(path, out string err); + if (suit == null) return err; + + var suitIds = suit.Select(s => s.Id).ToHashSet(); + _dequip.Clear(); _equip.Clear(); _attempts.Clear(); + foreach (var wo in _ctx.Inventory.Items().Where(w => _ctx.Inventory.IsEquipped(w) && !suitIds.Contains(w.Id) + && Array.IndexOf(WearableClasses, w.ObjectClass) >= 0)) + _dequip.Enqueue(wo.Id); + foreach (var wo in suit.Where(w => !_ctx.Inventory.IsEquipped(w))) _equip.Enqueue(wo.Id); + + if (_dequip.Count + _equip.Count == 0) return "Already wearing this suit."; + _running = true; + _doneCount = 0; + _lastProgress = IltHubContext.NowMs; + _ctx.State.Gear.LastEquipProfile = Path.GetFileNameWithoutExtension(path); + _status = $"loading {Path.GetFileNameWithoutExtension(path)}: {_dequip.Count} off, {_equip.Count} on"; + return _status; + } + + public void Cancel(string why) + { + RynthLog.Trace(LogCat.IltGear, $"Suits.Cancel(why='{why}')"); + _running = false; + _dequip.Clear(); + _equip.Clear(); + _status = why; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + if (!_running || nowMs - _lastStep < StepMs) return; + _lastStep = nowMs; + if (nowMs - _lastProgress > NoProgressBailMs) { Cancel($"no progress for 10 s - stopped ({_doneCount} done)"); return; } + if (_ctx.Inventory.IsBusy) return; + + var cache = _ctx.Inventory.Cache; + if (cache == null) { Cancel("cache not ready"); return; } + + // Dequip phase first so slots are free for the suit. + if (_dequip.Count > 0) + { + int id = _dequip.Peek(); + var wo = cache[id]; + if (wo == null || !_ctx.Inventory.IsEquipped(wo)) { _dequip.Dequeue(); Progress(nowMs); return; } + if (!Attempt(id)) { _dequip.Dequeue(); return; } + int pack = IltObjects.FindPackFor(_ctx.Host, cache, includeMainPack: true, requireFree: 1); + if (pack == 0) { Cancel("no free pack slot for dequipped items - stopped"); return; } + _ctx.Host.MoveItemInternal(unchecked((uint)id), unchecked((uint)pack), 0, Math.Max(1, _ctx.Inventory.StackSize(wo))); + return; + } + + if (_equip.Count > 0) + { + int id = _equip.Peek(); + var wo = cache[id]; + if (wo == null || _ctx.Inventory.IsEquipped(wo)) { _equip.Dequeue(); Progress(nowMs); return; } + if (!Attempt(id)) { _equip.Dequeue(); return; } + _ctx.Inventory.Use(wo); + return; + } + + _running = false; + _status = $"suit loaded ({_doneCount} changes)"; + } + + /// Counts an attempt; false once the item has used up its attempts. + private bool Attempt(int id) + { + int n = _attempts.TryGetValue(id, out int a) ? a + 1 : 1; + _attempts[id] = n; + return n <= MaxAttemptsPerItem; + } + + private void Progress(long now) + { + _doneCount++; + _lastProgress = now; + } + + public bool OnChat(string text) => false; + public void OnLogout() => Cancel("idle"); + + // ── UI (render thread) ────────────────────────────────────────────────── + + public void Render() + { + ImGui.TextColored(IltStyle.ColTeal, "Equipment suits (.utl)"); + if (ImGui.SmallButton("Rescan profiles")) _ctx.Post(RefreshProfileList); + var profiles = _profiles; + if (profiles.Length == 0) + { + SafeImGui.TextDisabled($"No .utl files found ({System.IO.Path.Combine(IltHubStore.SharedRoot, "EquipProfiles")}, the RynthAi folder's EquipProfiles or UtilityBelt equip folders)."); + } + else + { + _selected = Math.Clamp(_selected, 0, profiles.Length - 1); + ImGui.SetNextItemWidth(220); + ImGui.Combo("Suit", ref _selected, profiles, profiles.Length); + string pick = profiles[_selected]; + ImGui.SameLine(); + if (ImGui.SmallButton("Test")) _ctx.Post(() => Test(pick)); + ImGui.SameLine(); + if (ImGui.SmallButton("Load...")) + _ctx.Confirm("Load equipment suit", $"Swap to suit '{pick}'?\nItems not in the suit are moved to your packs.", + () => _ctx.Chat("[Mini Remote] " + Load(pick)), "Load"); + if (_running) + { + ImGui.SameLine(); + if (ImGui.SmallButton("Cancel")) _ctx.Post(() => Cancel("cancelled by player")); + } + } + SafeImGui.TextDisabled("Status: " + _status); + foreach (string l in _preview) SafeImGui.BulletText(l); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs new file mode 100644 index 0000000..bd88c27 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs @@ -0,0 +1,362 @@ +// IltFeatureCatalog.cs — Every Infinite Leaftide feature RynthILT supports, in one list. +// +// Each entry says what the feature is, where it lives in the Rynth tools, and how its state is +// known. Detection is client-side only: the server type comes from the login (the world name, +// RynthCore's "ilt" verdict), and the ILT profile below is the known set of what Infinite +// Leaftide runs, taken from ACECustom (its ServerConfig defaults and deploy/PROD_DEPLOY_PLAN.md, +// e.g. pet bond and potency on in prod, pet strain off since launch). The server is never asked +// for a list; what it returns on its own (probe replies, chat) refines the profile: +// * Profile (IltKnown.Profile): on in ILT (T11, split arrows, pet breeding, ...). On with the +// ILT world; a server refusal seen in chat turns it off. +// * Profile off (IltKnown.ProfileOff): an ACECustom option ILT runs with off (pet strain, +// defense scaling, the pyreal refill). Off with the ILT world; a chat line only the feature +// sends (e.g. a pyreal refill) turns it on. +// * Checked (IltKnown.Checked): the login probe answers it (/bank, /aug, /xp, /pets, ...). +// "checking" until the reply arrives, then on or off. +// * No server bit at all (the Temple guardians, Paragon gear): content, on with the ILT world. +// Off an ILT world nothing is claimed: every state is unknown. +// The list feeds the ILT settings window ("/ilt settings", IltSettingsView/) and "/ra hub features". +// Server facts copied from ACECustom: Fellowship.MaxFellows = 29 (Source/ACE.Server/Entity/ +// Fellowship.cs), Zone Share (ZoneShareManager) and the fellowship luminance share. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One Leaftide feature: id, display text, where it lives, and the server bit that says whether it's on. +/// Stable id. +/// Display name. +/// Character, Items, Fellowship or Activities (the list's sections). +/// Where the Rynth tools handle it. +/// One line on what the server does. +/// The IltServerOptions key probes and chat refusals set; null = content built into ACECustom (on with the world). +/// How the state is known while the bit hasn't been set (see ). +internal sealed record IltFeatureInfo(string Key, string Label, string Group, string Where, string Description, string? ServerBit, + IltKnown Known = IltKnown.Profile); + +/// How a feature's state is known on an ILT world before (or without) a server answer. +internal enum IltKnown +{ + /// On in ILT: on with the ILT world unless chat shows it off. + Profile, + /// The login probe answers it: "checking" until the reply arrives. + Checked, + /// Off in ILT: off with the ILT world unless chat shows it on. + ProfileOff, +} + +/// The quest bonus list as the profile JSON carries it ("questBonus"), for RynthOracle's Quests tab. +/// The server has /qb turned off. +/// Bumped per parsed "/qb list"; 0 = not loaded this session. +/// The server's quest bonus count; -1 = unknown. +/// One line on the last request ("loading...", "12 completed, 3 incomplete", ...). +/// Completed bonus flags, sorted. +/// Incomplete bonus flags, sorted. +internal sealed record IltQuestBonusInfo(bool Disabled, int Generation, long Count, string Status, + IReadOnlyList Completed, IReadOnlyList Incomplete); + +internal static class IltFeatureCatalog +{ + public const string GroupCharacter = "Character"; + public const string GroupItems = "Items"; + public const string GroupPets = "Pets"; + public const string GroupFellowship = "Fellowship"; + public const string GroupCombat = "Combat"; + public const string GroupActivities = "Activities"; + + /// The section order of the list (ACECustom's "/ilt features" uses the same). + public static readonly string[] Groups = { GroupCharacter, GroupItems, GroupPets, GroupFellowship, GroupCombat, GroupActivities }; + + /// ACECustom's fellowship member limit (Fellowship.MaxFellows); retail is 9. + public const int IltFellowshipMax = 29; + + /// A retail fellowship's member limit. + public const int RetailFellowshipMax = 9; + + /// Every Leaftide feature RynthILT supports, in display order. + public static readonly IltFeatureInfo[] All = + { + // Character progression and money. + new("bank", "Banking", GroupCharacter, "Mini Remote > Banking tab; Remote tab bank line", + "Bank pyreals, luminance, keys and coins; deposit, withdraw and transfer (/bank).", IltFeature.Bank, IltKnown.Checked), + new("bank_notes", "Trade note banking", GroupCharacter, "Mini Remote > Banking tab (trade notes)", + "Deposit trade notes as pyreals, withdraw any note from I to MMD, transfer note value (/bank d n).", "bank_notes"), + new("guardian", "Guardian (infinite base attributes)", GroupCharacter, "Guardian panel (/rc guardian)", + "Temple of Enlightenment guardians raise base attributes past the retail cap.", null), + new("attributes", "Infinite raised attributes", GroupCharacter, "Skills > Progression > Attributes", + "Spend unassigned XP on attributes past the retail max (/xp, /attr).", IltFeature.Xp, IltKnown.Checked), + new("augmentations", "Infinite augmentations", GroupCharacter, "Skills > Progression > Augmentations", + "Luminance augmentations far past retail: Creature 6000, Item / Life / War / Void 4000 (/aug).", IltFeature.Aug, IltKnown.Checked), + new("aug_charms", "Augmentation counter charms", GroupCharacter, "Skills > Progression > Augmentations", + "Triune Weave and the school charms add to your aug counts past the purchase cap (/aug).", "aug_charms"), + new("enlightenment", "Enlightenment", GroupCharacter, "Skills > Progression > Enlightenment", + "Enlightenment tiers past retail, with medallions, sigils and crests (/enl).", IltFeature.Enl, IltKnown.Checked), + new("ilt_skills", "Spend XP and train skills in one go", GroupCharacter, "Chat: /ilt xp, /ilt train", + "Spends all unspent XP into trained skills, or trains every affordable skill, in priority order.", "ilt_skills"), + new("leaderboards", "Leaderboards", GroupCharacter, "Chat: /top", + "Server leaderboards: quest bonus, level, enlightenment, augs, bank, pets and more (/top).", "leaderboards"), + + // Items, loot and crafting. + new("paragon_armor", "Paragon armor", GroupItems, "Item info (RynthAi): Paragon sets and levels", + "Paragon armor progression; the 50th Armor Paragon gates enlightenment past 300.", null), + new("paragon_weapons", "Paragon weapons", GroupItems, "Item info (RynthAi): Paragon sets and levels", + "Paragon weapon progression (Paragon Missile, Caster and Melee sets).", null), + new("paragon_jewelry", "Paragon jewelry", GroupItems, "Item info (RynthAi): Paragon sets and levels", + "Paragon jewelry progression; the 50th Paragon gates enlightenment past 150.", null), + new("t11", "T11 items", GroupItems, "Item info and loot rules (RynthAi, RynthCore Loot Editor)", + "Tier 11 to 25 gear (Zone Control tiers): tiers, gear grades, property slots and modifiers.", "t11"), + new("t11_scaling", "T11+ weapon scaling", GroupItems, "Item info (RynthAi)", + "T11+ weapons scale with your augs and have aug wield floors; from T16, charm counts too.", "t11_scaling"), + new("t11_craft_gate", "T11+ crafting rules (crafting uniqueness)", GroupItems, "Mini Remote > Gear tab", + "On T11+ items the server refuses an imbue or tink that would replace a better value, and limits materials per item type.", + "t11_craft_gate"), + new("split_arrows", "Split arrows", GroupItems, "Mini Remote > Gear > Split arrows", + "Missile weapons carry split arrows, added with White Quartz salvage.", "split_arrows"), + new("charms", "Charms", GroupItems, "Mini Remote > Charms tab", + "Registry charms and the Guardian Hand, with their toggles; each charm is listed in the Charms section.", "charms"), + new("clap", "Chunk clap (auto craft)", GroupItems, "Mini Remote > Gear tab", + "Turns aetheria, chunks and trinkets into banked enlightened coins (/clap all).", IltFeature.Clap, IltKnown.Checked), + + // Pets. + new("pets", "Pet log", GroupPets, "Mini Remote > Pets tab", "Captured pets, registered with Professor Ruggan (/pets).", IltFeature.Pets, IltKnown.Checked), + new("shinies", "Shiny log", GroupPets, "Mini Remote > Pets tab", "Rare shiny creature variants you captured (/shinies).", IltFeature.Shinies, IltKnown.Checked), + new("monster_capture", "Monster capture", GroupPets, "Mini Remote > Pets tab", + "Siphon lenses capture a creature\'s look into a pet essence (<=20% health or under 20 HP; Asheron\'s Lens skips the gate). Auto-capture is the checkbox on the Pets roster.", "monster_capture"), + new("pet_breeding", "Pet breeding", GroupPets, "Mini Remote > Pets > Breeding", + "Breed two combat pet devices at the Seedy Motel for inherited and mutated offspring (/dance).", "pet_breeding"), + new("pet_maturity", "Pet maturity", GroupPets, "Mini Remote > Pets > Breeding", + "Bred pets start small and weak and grow up with kills.", "pet_maturity"), + new("pet_bond", "Pet bond", GroupPets, "Mini Remote > Pets tab", + "Pets gain bond XP from kills, which scales their stats (/top bonds). On in ILT (breeding needs bond 100).", IltFeature.PetBond), + new("pet_potency", "Pet potency", GroupPets, "Mini Remote > Pets tab", + "Savage Echo residue raises a pet's potency (/echo-notify). On in ILT.", IltFeature.PetPotency), + new("pet_strain", "Pet strain", GroupPets, "Mini Remote > Pets tab", + "High pet potency lowers the owner's damage rating. Off in ILT since launch.", "pet_strain", IltKnown.ProfileOff), + new("pet_refill", "Summon essence refill", GroupPets, "Mini Remote > Pets tab", + "Pays pyreals to refill an empty essence when you summon (needs its charm). Off by default; a refill message in chat shows it on.", IltFeature.PetRefill, IltKnown.ProfileOff), + new("universal_mastery", "Universal summoning mastery", GroupPets, "Mini Remote > Pets tab", + "Use pet essences of any summoning mastery (needs its charm).", IltFeature.UniversalMastery), + new("pet_naming", "Pet names", GroupPets, "Chat: /pet-name", + "Ask for a name for your pet; staff approve it (/pet-name).", "pet_naming"), + + // Fellowship. + new("fellowship_large", "Large fellowships (up to 29)", GroupFellowship, "The game's fellowship panel", + "Fellowships hold up to 29 members instead of retail's 9.", "fellowship_size"), + new("fship", "Fellowship commands", GroupFellowship, "ILT fellowship window (/ilt fellow)", + "Create, invite, invite your landblock, list nearby, leave and disband from chat (/fship).", "fship"), + new("zone_share", "Zone Share", GroupFellowship, "Mini Remote > Session Stats (luminance, pass-up)", + "XP and luminance shared with everyone in a Zone Share area, capped at a fellowship's size.", "zone_share"), + new("fellowship_luminance", "Fellowship luminance share", GroupFellowship, "Mini Remote > Session Stats (luminance, pass-up)", + "Luminance splits among fellows the way XP does.", "fellowship_luminance"), + new("fellowship_blackjack", "Fellowship Blackjack", GroupFellowship, "Mini Remote > Games tab", + "Blackjack played as a fellowship (/fblackjack).", IltFeature.FBlackjack, IltKnown.Checked), + + // Combat. + new("smart_ring", "Smart ring spells", GroupCombat, "Chat: /ilt smartring", + "Ring spells hit everything in their radius, with double and triple procs (/ilt smartring on|off).", "smart_ring"), + new("dmgformat", "Damage number format", GroupCombat, "Chat: /ilt dmgformat", + "Damage shown plain, with commas, or short (K/M/B) (/ilt dmgformat).", "dmgformat"), + new("overkill", "Overkill on kill messages", GroupCombat, "Chat: /ilt showoverkill", + "Kill and death messages show the overkill amount (/ilt showoverkill).", "overkill"), + new("missile_power", "Missile power bar damage", GroupCombat, "Combat", + "The missile accuracy bar scales damage from 1x to 2.5x.", "missile_power"), + new("t11_hit_gate", "T11+ hit gate", GroupCombat, "Combat", + "Attacks on v11+ monsters miss unless your aug counts meet that tier's requirement.", "t11_hit_gate"), + new("v11_endgame", "v11+ endgame scaling", GroupCombat, "Combat", + "Percent-of-max-HP damage, compressed vulnerabilities and tougher v11+ monsters.", "v11_endgame"), + new("defense_scaling", "Defense scaling", GroupCombat, "Combat", + "Curbs extreme evasion at very high defense skill. Off by default in ACECustom.", "defense_scaling", IltKnown.ProfileOff), + + // Activities. + new("quests", "Quest tracker", GroupActivities, "Mini Remote > Quests tab", + "Your quest timers from the server (/myquests).", IltFeature.Quests, IltKnown.Checked), + new("quest_bonus", "Quest bonus", GroupActivities, "Mini Remote > Quests tab (quest bonus)", + "Each quest completed adds to your XP bonus; the list (/qb).", IltFeature.Qb, IltKnown.Checked), + new("bounties", "Bounties", GroupActivities, "Bounties window (/rc bounties)", "ACECustom bounties and your progress.", "bounties"), + new("rifts", "Greater Rifts", GroupActivities, "Chat: /rift", "Private, timed dungeon runs that scale by tier (/rift).", "rifts"), + new("room_assign", "Room Assign dungeons", GroupActivities, "Portals and recalls", + "One-player rooms with their own spawns.", "room_assign"), + new("portal_requirements", "Aug / ENL / QB portals", GroupActivities, "Portals", + "Portals that need augmentations, an enlightenment level or a quest bonus.", "portal_requirements"), + new("powerball", "Powerball", GroupActivities, "Mini Remote > Games tab", "The Powerball lottery (/pb).", IltFeature.Powerball, IltKnown.Checked), + new("blackjack", "Blackjack", GroupActivities, "Mini Remote > Games tab", "Blackjack against the house (/blackjack).", IltFeature.Blackjack, IltKnown.Checked), + new("unstuck", "Unstuck", GroupActivities, "Chat: /unstuck", "Gets you out of a stuck portal or spot (/unstuck).", "unstuck"), + }; + + /// The entry with , or null. + public static IltFeatureInfo? Find(string key) + { + foreach (IltFeatureInfo f in All) + if (f.Key.Equals(key, StringComparison.OrdinalIgnoreCase)) return f; + return null; + } + + /// + /// A feature's state on an ILT world: what the server returned (a probe reply or a refusal in + /// chat) when it did; else the ILT profile: On for content and , + /// Off for , Unknown ("checking") for probed features. + /// Off ILT nothing is claimed: Unknown. + /// + public static IltTri StateOf(IltFeatureInfo f, bool iltWorld, Func bit) + { + if (!iltWorld) return IltTri.Unknown; + if (f.ServerBit == null) return IltTri.On; + IltTri reported = bit(f.ServerBit); + if (reported != IltTri.Unknown) return reported; + return f.Known switch + { + IltKnown.Profile => IltTri.On, + IltKnown.ProfileOff => IltTri.Off, + _ => IltTri.Unknown, + }; + } + + /// + /// A charm's state: charms are part of the ILT profile, so on with the ILT world unless the + /// server refused one in chat (e.g. "Auto-Rebuff Charm is currently disabled globally"). + /// + public static IltTri CharmStateOf(bool iltWorld, IltTri reported) + => !iltWorld ? IltTri.Unknown : reported != IltTri.Unknown ? reported : IltTri.On; + + /// Prefix of a charm's server key (IltFeature.Charm): "charm:manabarrier". + public const string CharmKeyPrefix = "charm:"; + + /// + /// Display text for a key the settings view lists: a catalog feature (its label, group and + /// description with where it lives and how its state is known), a charm ("charm:..." under + /// Charms, named from the charm registry), or any other server bit as itself under "Other". + /// + public static (string Label, string Group, string Tooltip) Describe(string key) + { + IltFeatureInfo? f = Find(key); + if (f != null) return (f.Label, f.Group, f.Description + "\nWhere: " + f.Where + "\n" + HowKnown(f)); + if (key.StartsWith(CharmKeyPrefix, StringComparison.OrdinalIgnoreCase)) + { + const string charmNote = "Part of ILT: on unless the server refuses it in chat."; + foreach (IltCharmDef def in IltInventory.Charms) + if (IltFeature.Charm(def.Name).Equals(key, StringComparison.OrdinalIgnoreCase)) + return (def.Name, GroupCharms, (def.Effect.Length > 0 ? def.Effect + "\n" : string.Empty) + + "Where: Mini Remote > Charms tab\n" + charmNote); + return (key.Substring(CharmKeyPrefix.Length), GroupCharms, charmNote); + } + return (key, GroupOther, "A server switch RynthILT reads from chat."); + } + + /// One line on where a feature's state comes from (tooltips). + private static string HowKnown(IltFeatureInfo f) => f.ServerBit == null + ? "Built into ILT: on with the world." + : f.Known switch + { + IltKnown.Checked => "Checked at login: the server's reply decides.", + IltKnown.ProfileOff => "Off in ILT: on only if the server shows it in chat.", + _ => "Part of ILT: on unless the server refuses it in chat.", + }; + + /// The settings view's extra sections after . + public const string GroupCharms = "Charms"; + public const string GroupOther = "Other"; + + /// Short state text for the list and chat: "on", "off" or "checking". + public static string StateText(IltTri state) => state switch + { + IltTri.On => "on", + IltTri.Off => "off", + _ => "checking", + }; + + /// The fellowship member limit: ACECustom's 29 on an ILT world, retail's 9 elsewhere. + public static int FellowshipMax(bool iltWorld) => iltWorld ? IltFellowshipMax : RetailFellowshipMax; + + /// + /// The "RynthILT.Server" profile JSON (schema in Plugins/Shared/RynthIltServerApi.cs). Pure: + /// everything comes in as arguments, so the tests build it without a client. Plain ASCII. + /// + public static string BuildProfileJson(bool iltWorld, string world, bool forced, string source, DateTime checkedUtc, + Func bit, IltQuestBonusInfo? questBonus = null) + { + var sb = new StringBuilder(4096); + sb.Append("{\"ilt\":").Append(iltWorld ? "true" : "false"); + sb.Append(",\"world\":\"").Append(Escape(world)).Append('"'); + sb.Append(",\"forced\":").Append(forced ? "true" : "false"); + sb.Append(",\"source\":\"").Append(Escape(source)).Append('"'); + sb.Append(",\"checked\":\"") + .Append(checkedUtc == DateTime.MinValue ? "" : checkedUtc.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)) + .Append('"'); + + sb.Append(",\"features\":["); + for (int i = 0; i < All.Length; i++) + { + IltFeatureInfo f = All[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"key\":\"").Append(Escape(f.Key)) + .Append("\",\"label\":\"").Append(Escape(f.Label)) + .Append("\",\"group\":\"").Append(Escape(f.Group)) + .Append("\",\"state\":").Append(((int)StateOf(f, iltWorld, bit)).ToString(CultureInfo.InvariantCulture)) + .Append(",\"where\":\"").Append(Escape(f.Where)).Append("\"}"); + } + sb.Append(']'); + + int State(string key) => (int)StateOf(Find(key)!, iltWorld, bit); + sb.Append(",\"fellowship\":{\"maxMembers\":").Append(FellowshipMax(iltWorld).ToString(CultureInfo.InvariantCulture)) + .Append(",\"zoneShare\":").Append(State("zone_share").ToString(CultureInfo.InvariantCulture)) + .Append(",\"blackjack\":").Append(State("fellowship_blackjack").ToString(CultureInfo.InvariantCulture)) + .Append(",\"luminanceShare\":").Append(State("fellowship_luminance").ToString(CultureInfo.InvariantCulture)) + .Append('}'); + + // The /qb list (ILT worlds only): RynthOracle's Quests tab draws it. + if (questBonus != null && iltWorld) + { + sb.Append(",\"questBonus\":{\"disabled\":").Append(questBonus.Disabled ? "true" : "false") + .Append(",\"generation\":").Append(questBonus.Generation.ToString(CultureInfo.InvariantCulture)) + .Append(",\"count\":").Append(questBonus.Count.ToString(CultureInfo.InvariantCulture)) + .Append(",\"status\":\"").Append(Escape(questBonus.Status)).Append('"'); + AppendList(sb, "completed", questBonus.Completed); + AppendList(sb, "incomplete", questBonus.Incomplete); + sb.Append('}'); + } + sb.Append('}'); + return sb.ToString(); + + static void AppendList(StringBuilder b, string name, IReadOnlyList items) + { + b.Append(",\"").Append(name).Append("\":["); + for (int i = 0; i < items.Count; i++) + { + if (i > 0) b.Append(','); + b.Append('"').Append(Escape(items[i])).Append('"'); + } + b.Append(']'); + } + } + + /// JSON string body: quotes, backslashes and control characters escaped, anything non-ASCII as \uXXXX. + private static string Escape(string? s) + { + if (string.IsNullOrEmpty(s)) return string.Empty; + var sb = new StringBuilder(s.Length + 8); + foreach (char c in s) + { + if (c == '"') sb.Append("\\\""); + else if (c == '\\') sb.Append("\\\\"); + else if (c < 0x20 || c > 0x7E) sb.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)); + else sb.Append(c); + } + return sb.ToString(); + } + + /// The chat listing for "/ra hub features": one line per feature, ASCII only. + public static List BuildChatLines(bool iltWorld, Func bit) + { + var lines = new List(All.Length + Groups.Length); + foreach (string g in Groups) + { + var parts = new List(); + foreach (IltFeatureInfo f in All) + if (f.Group == g) parts.Add($"{f.Label} [{StateText(StateOf(f, iltWorld, bit))}]"); + lines.Add($"{g}: {string.Join(", ", parts)}"); + } + return lines; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGames.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGames.cs new file mode 100644 index 0000000..0a91a26 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGames.cs @@ -0,0 +1,255 @@ +// IltGames.cs — ILT Hub "Games" tab + hand HUD (P2): Blackjack, Fellowship Blackjack, Powerball. +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// Every bet / ticket purchase spends banked luminance, so each one needs a confirm. +// Blackjack is commented out on the current ACECustom build ("Unknown command: +// blackjack"); the pad only appears when the login probe found the command. +// /blackjack , /hit, /stand, /double, /split (fellowship: /fblackjack, /fhit, ...; max 100B) +// /pb (info), /pb buy <1-500>, /pb tickets +// The HUD is a small always-on-top window shown while a hand is in progress. +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Text.RegularExpressions; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltGames : IIltFeature +{ + private const long FBlackjackMaxBet = 100_000_000_000; + private static readonly Regex Dealt = new(@"^You were dealt (?:a |an )?(?.+?)\.$", RegexOptions.Compiled); + private static readonly Regex MyValue = new(@"Your (?:initial )?hand value is (?:now )?(?\d+)", RegexOptions.Compiled); + private static readonly Regex DealerValue = new(@"Rand's (?:current )?hand value is (?\d+)", RegexOptions.Compiled); + + private readonly IltHubContext _ctx; + + // Hand state (pump thread writes, render thread reads — simple fields / snapshot list) + private volatile bool _handActive; + private volatile bool _fellowshipHand; + private volatile string[] _cards = Array.Empty(); + private volatile int _myValue, _dealerValue; + private volatile string _lastResult = string.Empty; + + // Powerball info + private volatile string _pbDraw = string.Empty, _pbJackpot = string.Empty, _pbPrice = string.Empty, _pbStatus = string.Empty; + + // Render-thread input + private string _bjBetText = string.Empty, _fbjBetText = string.Empty; + + public IltGames(IltHubContext ctx) => _ctx = ctx; + + private IltGamesState S => _ctx.State.Games; + + public bool AnyGameAvailable => _ctx.Options.IsOn(IltFeature.Blackjack) || _ctx.Options.IsOn(IltFeature.FBlackjack) + || !_ctx.Options.IsOff(IltFeature.Powerball); + + // ── Commands (pump thread) ────────────────────────────────────────────── + + private void Send(string cmd) + { + if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(cmd); + } + + private void StartBlackjack(bool fellowship, long bet) + { + _fellowshipHand = fellowship; + _cards = Array.Empty(); + _myValue = _dealerValue = 0; + _lastResult = string.Empty; + Send($"/{(fellowship ? "fblackjack" : "blackjack")} {bet}"); + } + + private void HandAction(string verb) => Send("/" + (_fellowshipHand ? "f" : "") + verb); + + public void RequestPowerballInfo() + { + RynthLog.Trace(LogCat.IltGames, $"RequestPowerballInfo()"); + if (_ctx.Options.IsOff(IltFeature.Powerball) || _ctx.Capture.IsPending("/pb")) return; + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = "/pb", + IsResponseLine = t => t.StartsWith("[Powerball]", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("Draw #", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("Jackpot Pool", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("Ticket Price", StringComparison.OrdinalIgnoreCase), + IdleEndMs = 1200, + FirstLineTimeoutMs = 8000, + Eat = true, + OnComplete = r => + { + if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Powerball, IltTri.Off); return; } + if (r.Lines.Count > 0) _ctx.Options.Set(IltFeature.Powerball, IltTri.On); + foreach (string l in r.Lines) ParsePowerball(l); + RynthLog.Trace(LogCat.IltGames, $"/pb info: {r.Lines.Count} line(s), timedOut={r.TimedOut}"); + _pbStatus = r.Lines.Count > 0 ? "updated " + DateTime.Now.ToString("t") : "no reply"; + }, + }); + } + + private void ParsePowerball(string l) + { + string t = l.Trim(); + if (t.StartsWith("Draw #", StringComparison.OrdinalIgnoreCase)) _pbDraw = t; + else if (t.StartsWith("Jackpot Pool", StringComparison.OrdinalIgnoreCase)) _pbJackpot = t; + else if (t.StartsWith("Ticket Price", StringComparison.OrdinalIgnoreCase)) _pbPrice = t; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) { } + + public bool OnChat(string text) + { + // Powerball lines typed by the player still update the panel. + if (text.StartsWith("[Powerball]", StringComparison.OrdinalIgnoreCase)) + { + if (text.Contains("You bought", StringComparison.OrdinalIgnoreCase) || text.Contains("Insufficient", StringComparison.OrdinalIgnoreCase)) + _pbStatus = text; + return false; + } + string t = text.Trim(); + if (t.StartsWith("Draw #", StringComparison.OrdinalIgnoreCase) || t.StartsWith("Jackpot Pool", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("Ticket Price", StringComparison.OrdinalIgnoreCase)) + { + ParsePowerball(t); + return false; + } + + // Blackjack + var d = Dealt.Match(text); + if (d.Success) + { + var list = new List(_cards) { d.Groups["card"].Value }; + _cards = list.ToArray(); + _handActive = true; + return false; + } + var mv = MyValue.Match(text); + if (mv.Success) { _myValue = int.Parse(mv.Groups["v"].Value); _handActive = true; } + var dv = DealerValue.Match(text); + if (dv.Success) _dealerValue = int.Parse(dv.Groups["v"].Value); + if (text.StartsWith("The game begins!", StringComparison.OrdinalIgnoreCase)) _handActive = true; + + if (text.StartsWith("Blackjack! You win", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You won with", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("You tied with Rand", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You lost with", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("You busted", StringComparison.OrdinalIgnoreCase)) + _lastResult = text; + if (text.StartsWith("The blackjack game has ended", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("You are not currently in a blackjack game", StringComparison.OrdinalIgnoreCase)) + _handActive = false; + if (text.StartsWith("You don't have enough luminance to place this bet", StringComparison.OrdinalIgnoreCase)) + { + _lastResult = text; + _handActive = false; + } + return false; + } + + public void OnLogout() + { + _handActive = false; + _cards = Array.Empty(); + } + + // ── UI (render thread) ────────────────────────────────────────────────── + + public void Render() + { + bool bj = _ctx.Options.IsOn(IltFeature.Blackjack), fbj = _ctx.Options.IsOn(IltFeature.FBlackjack); + if (!bj && !fbj && _ctx.Options.IsOff(IltFeature.Powerball)) + { + ImGui.TextColored(IltStyle.ColTextMute, "No games are enabled on this server."); + return; + } + bool hud = _ctx.State.GamesHudVisible; + if (ImGui.Checkbox("Show hand HUD while playing", ref hud)) _ctx.State.GamesHudVisible = hud; + + if (bj && ImGui.CollapsingHeader("Blackjack", ImGuiTreeNodeFlags.DefaultOpen)) RenderBlackjack(false, ref _bjBetText); + if (fbj && ImGui.CollapsingHeader("Fellowship Blackjack", ImGuiTreeNodeFlags.DefaultOpen)) RenderBlackjack(true, ref _fbjBetText); + if (!bj && !fbj) ImGui.TextDisabled("Blackjack is not enabled on this server."); + if (!_ctx.Options.IsOff(IltFeature.Powerball) && ImGui.CollapsingHeader("Powerball", ImGuiTreeNodeFlags.DefaultOpen)) RenderPowerball(); + } + + private void RenderBlackjack(bool fellowship, ref string betText) + { + string id = fellowship ? "fbj" : "bj"; + if (betText.Length == 0) betText = IltParse.Compact(fellowship ? S.FellowshipBlackjackBet : S.BlackjackBet).ToLowerInvariant(); + ImGui.SetNextItemWidth(160); + ImGui.InputTextWithHint($"Bet (luminance)##{id}", "e.g. 1m, 500k", ref betText, 24u); + bool ok = IltParse.TryParseAmount(betText, out long bet) && (!fellowship || bet <= FBlackjackMaxBet); + ImGui.SameLine(); + SafeImGui.TextDisabled(ok ? IltParse.N0(bet) : fellowship ? "invalid (max 100B)" : "invalid"); + + ImGui.BeginDisabled(!ok || _handActive); + if (ImGui.Button($"Deal...##{id}")) + { + long b = bet; + if (fellowship) S.FellowshipBlackjackBet = b; else S.BlackjackBet = b; + _ctx.Confirm(fellowship ? "Fellowship Blackjack" : "Blackjack", + $"Bet {IltParse.N0(b)} banked luminance on a new hand?", () => StartBlackjack(fellowship, b), "Bet"); + } + ImGui.EndDisabled(); + + if (_handActive && _fellowshipHand == fellowship) RenderHandButtons(id); + if (_lastResult.Length > 0 && _fellowshipHand == fellowship) SafeImGui.TextWrapped(_lastResult); + } + + private void RenderHandButtons(string id) + { + ImGui.TextUnformatted($"Hand: {string.Join(", ", _cards)} ({_myValue}) Rand: {(_dealerValue > 0 ? _dealerValue.ToString() : "?")}"); + if (ImGui.Button($"Hit##{id}")) _ctx.Post(() => HandAction("hit")); + ImGui.SameLine(); + if (ImGui.Button($"Stand##{id}")) _ctx.Post(() => HandAction("stand")); + ImGui.SameLine(); + if (ImGui.Button($"Double...##{id}")) + _ctx.Confirm("Double down", "Double your bet on this hand?", () => HandAction("double"), "Double"); + ImGui.SameLine(); + if (ImGui.Button($"Split...##{id}")) + _ctx.Confirm("Split", "Split this hand (places a second bet)?", () => HandAction("split"), "Split"); + } + + private void RenderPowerball() + { + if (ImGui.SmallButton("Refresh##pb")) _ctx.Post(RequestPowerballInfo); + ImGui.SameLine(); + if (ImGui.SmallButton("My tickets")) _ctx.Post(() => Send("/pb tickets")); + if (_pbDraw.Length > 0) ImGui.TextUnformatted(_pbDraw); + if (_pbJackpot.Length > 0) ImGui.TextUnformatted(_pbJackpot); + if (_pbPrice.Length > 0) ImGui.TextUnformatted(_pbPrice); + // Buying spends banked luminance, so it needs a positive server confirmation of /pb. + if (!_ctx.Options.IsOn(IltFeature.Powerball)) + { + ImGui.TextDisabled("Ticket purchases unlock once the server confirms /pb (press Refresh)."); + if (_pbStatus.Length > 0) SafeImGui.TextWrapped(_pbStatus); + return; + } + int qty = S.PowerballQuantity; + ImGui.SetNextItemWidth(120); + if (ImGui.InputInt("Tickets", ref qty)) S.PowerballQuantity = Math.Clamp(qty, 1, 500); + ImGui.SameLine(); + if (ImGui.Button("Buy...")) + { + int q = S.PowerballQuantity; + _ctx.Confirm("Powerball", $"Buy {q} Powerball ticket(s)?\n{(_pbPrice.Length > 0 ? _pbPrice : "Tickets cost banked luminance.")}", + () => Send($"/pb buy {q}"), "Buy"); + } + if (_pbStatus.Length > 0) SafeImGui.TextWrapped(_pbStatus); + } + + /// Small HUD with the current hand; called every frame by the Hub UI. + public void RenderHud() + { + if (!_handActive || !_ctx.State.GamesHudVisible) return; + ImGui.SetNextWindowSize(new Vector2(300, 0), ImGuiCond.FirstUseEver); + bool open = true; + if (ImGui.Begin("Blackjack HUD##iltbjhud", ref open, ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse)) + { + SafeImGui.TextColored(IltStyle.ColAmber, _fellowshipHand ? "Fellowship Blackjack" : "Blackjack"); + RenderHandButtons("hud"); + } + ImGui.End(); + if (!open) _ctx.State.GamesHudVisible = false; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGear.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGear.cs new file mode 100644 index 0000000..a986d5a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGear.cs @@ -0,0 +1,78 @@ +// IltGear.cs — ILT Hub "Gear" tab: the gear tools. +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// The sections are separate modules (buff keepers, chunk/clap, split arrows, equipment suits) +// that this tab just lays out, plus RynthAi's VTank .usd importer (it edits RynthAi's own rules, +// so it stayed in RynthAi and is drawn here through RynthAi.Hub RenderSection). The charm strip (registry charms and the Guardian +// Hand, with their toggles) is the Charms tab now (IltCharms). The Rings inscription chain +// (IltRingChainRunner) is SilentKelpie's RynthAi Crafting > Rings, moved here 2026-10-15. +using ImGuiNET; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltGear : IIltFeature +{ + public IltBuffKeepers Keepers { get; } + public IltChunkClap ChunkClap { get; } + public IltSplitArrows Split { get; } + public IltEquipSuits Suits { get; } + public IltRingChainRunner Rings { get; } + + private readonly IltHubContext _ctx; + + public IltGear(IltHubContext ctx) + { + Keepers = new IltBuffKeepers(ctx); + ChunkClap = new IltChunkClap(ctx); + Split = new IltSplitArrows(ctx); + Suits = new IltEquipSuits(ctx); + // The two pack jobs that answer craft dialogs never run together. + Rings = new IltRingChainRunner(ctx, () => Split.Running); + Split.Blocked = () => Rings.Running; + _ctx = ctx; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + Keepers.Tick(nowMs); + ChunkClap.Tick(nowMs); + Split.Tick(nowMs); + Suits.Tick(nowMs); + Rings.Tick(nowMs); + } + + public bool OnChat(string text) + { + bool eat = Keepers.OnChat(text); + eat |= ChunkClap.OnChat(text); + eat |= Split.OnChat(text); + eat |= Suits.OnChat(text); + eat |= Rings.OnChat(text); + return eat; + } + + public void OnLogout() + { + Keepers.OnLogout(); + ChunkClap.OnLogout(); + Split.OnLogout(); + Suits.OnLogout(); + Rings.OnLogout(); + } + + // ── UI (render thread) ────────────────────────────────────────────────── + + public void Render() + { + if (ImGui.CollapsingHeader("Dispel / Surging Strength", ImGuiTreeNodeFlags.DefaultOpen)) Keepers.Render(); + if (ImGui.CollapsingHeader("Chunking / Clap")) ChunkClap.Render(); + if (ImGui.CollapsingHeader("Split arrows")) Split.Render(); + if (ImGui.CollapsingHeader("Equipment suits")) Suits.Render(); + if (ImGui.CollapsingHeader("Rings (inscription chain)")) Rings.Render(); + if (ImGui.CollapsingHeader("VirindiTank import") && !_ctx.Ai.RenderSection(RynthCore.Plugin.Shared.RynthAiHub.SectionVTankImport)) + ImGui.TextDisabled("The VirindiTank .usd import fills RynthAi's rules: it comes with RynthAi, which isn't loaded."); + ImGui.TextDisabled("Charms and the Guardian Hand are on the Charms tab."); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs new file mode 100644 index 0000000..48ad99d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs @@ -0,0 +1,656 @@ +// IltGuardian.cs - Temple of Enlightenment guardians (ILT Hub "Guardian" window). +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// * Riddle translator: incoming "Guardian of ... tells you / says" lines (when chat auto-detect +// is on) and pasted text go through IltGuardianPhrasebook; the answer shows here and on the +// Mini Remote. +// * Hand-in: gives one of the answer item to the guardian (GiveObjectTo). For the Temple +// guardian, when none is carried and "buy missing" is on, it first buys one from the open or +// nearest vendor (VendorBuy). Runs as a small pump-thread state machine with timeouts; the +// client busy state is respected between steps. +// * Attribute tracker: IltTempleAttributes. +// * Reader: the same state as JSON with verbs back ("RynthILT.Data" version 3), for RynthOracle's +// Quests tab. The automation (auto hand-in, buy if missing) stays here either way. +// +// Threading: OnChat / Tick / commands run on the pump thread; Render only reads volatile fields +// and posts actions through IltHubContext.Post. +using System; +using System.Linq; +using System.Numerics; +using ImGuiNET; +using RynthCore.Loot; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltGuardian : IIltFeature +{ + /// The same guardian + answer from chat within this window is one prompt (tells repeat lines). + private const long DebounceMs = 2500; + private const long HandInTimeoutMs = 45_000; + private const long VendorOpenTimeoutMs = 10_000; + private const long BuyTimeoutMs = 10_000; + private const long ItemArriveTimeoutMs = 8_000; + private const long BusyRetryMs = 400; + private const int MaxGiveAttempts = 5; + /// How far (meters) to look for the guardian and a vendor. + private const double SearchRangeMeters = 60.0; + /// + /// PublicWeenieDesc BF_VENDOR. The world cache files vendors as creatures (Monster / Npc), never + /// AcObjectClass.Vendor, so vendors are recognised by this weenie flag. + /// + private const uint BfVendor = 0x200; + /// The Mini Remote shows the last answer for this long. + public static readonly TimeSpan AnswerShownFor = TimeSpan.FromMinutes(10); + + private enum Step { Idle, FindItem, OpenVendor, WaitVendor, Buy, WaitBuy, WaitItem, Give } + + private readonly IltHubContext _ctx; + private string _lastFingerprint = string.Empty; + private long _lastEmitAt; + + // Last prompt (written on the pump thread, read by the render thread). + private volatile string _lastLine = string.Empty; + private volatile string _lastAnswer = string.Empty; + private volatile string _lastNpc = string.Empty; + private long _lastAnswerTicksUtc; + private volatile string _handInStatus = "idle"; + + // Hand-in state machine (pump thread only). + private Step _step = Step.Idle; + private string _item = string.Empty; + private string _npc = string.Empty; + private bool _asked; + private long _startedAt; + private long _stepDeadline; + private long _nextStepAt; + private uint _vendorId; + private uint _buyRequest; + private int _giveAttempts; + + // Render-thread UI state. + private string _input = string.Empty; + + public IltGuardian(IltHubContext ctx, IltQuestBonus quests) + { + _ctx = ctx; + Attributes = new IltTempleAttributes(ctx, quests); + } + + public IltTempleAttributes Attributes { get; } + + private IltGuardianState S => _ctx.State.Guardian; + + /// Last answer item ("" until a guardian prompt was translated). + public string LastAnswer => _lastAnswer; + /// Guardian the last answer goes to. + public string LastNpc => _lastNpc; + /// The hand-in sequence is running. + public bool HandInRunning => _step != Step.Idle; + public string HandInStatus => _handInStatus; + + /// Time since the last answer (MaxValue when there is none). + public TimeSpan LastAnswerAge + { + get + { + long t = System.Threading.Interlocked.Read(ref _lastAnswerTicksUtc); + return t == 0 ? TimeSpan.MaxValue : DateTime.UtcNow - new DateTime(t, DateTimeKind.Utc); + } + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + Attributes.Tick(nowMs); + StepHandIn(nowMs); + } + + public bool OnChat(string text) + { + if (!S.AutoDetectFromChat || !IltGuardianPhrasebook.LooksLikeIncomingGuardianLine(text)) return false; + _lastLine = text.Trim(); + string answer = IltGuardianPhrasebook.Translate(text); + if (!IltGuardianPhrasebook.IsAnswer(answer)) return false; + + string npc = IltGuardianPhrasebook.TurnInNpcFromLine(text); + long now = IltHubContext.NowMs; + string fingerprint = npc + "|" + answer; + if (fingerprint == _lastFingerprint && now - _lastEmitAt < DebounceMs) return false; + _lastFingerprint = fingerprint; + _lastEmitAt = now; + + SetAnswer(answer, npc); + _ctx.Chat($"[ILT Guardian] {npc} wants: {answer}"); + RynthLog.Write(LogCat.IltHub, $"[IltGuardian] chat answer '{answer}' for {npc}"); + if (S.AutoHandIn) StartHandIn(answer, npc, asked: false); + return false; // never hide the guardian's own lines + } + + public void OnLogout() + { + StopHandIn("stopped (logout)"); + Attributes.OnLogout(); + } + + private void SetAnswer(string answer, string npc) + { + _lastAnswer = answer; + _lastNpc = npc; + System.Threading.Interlocked.Exchange(ref _lastAnswerTicksUtc, DateTime.UtcNow.Ticks); + } + + /// Translates pasted text; a real answer becomes the current answer. Pump thread. + public string TranslateManual(string text) + { + string answer = IltGuardianPhrasebook.Translate(text); + if (!IltGuardianPhrasebook.IsAnswer(answer)) return answer; + string npc = IltGuardianPhrasebook.TurnInNpcFromInput(text); + _lastLine = text.Trim(); + SetAnswer(answer, npc); + return $"{answer} (give to {npc})"; + } + + // ── Hand-in ───────────────────────────────────────────────────────────── + + /// Starts giving to . Pump thread. + public string StartHandIn(string item, string npc, bool asked) + { + if (!IltGuardianPhrasebook.IsAnswer(item)) return "No answer to hand in yet."; + if (!_ctx.Host.HasGiveObjectTo) return SetStatus("can't give items: update the RynthCore engine (API v62+)."); + _item = item; + _npc = string.IsNullOrWhiteSpace(npc) ? IltGuardianPhrasebook.AttributeGuardian : npc; + _asked = asked; + _startedAt = IltHubContext.NowMs; + _nextStepAt = 0; + _vendorId = 0; + _buyRequest = 0; + _giveAttempts = 0; + _step = Step.FindItem; + RynthLog.Write(LogCat.IltHub, $"[IltGuardian] hand-in start: '{_item}' -> {_npc} ({(asked ? "asked" : "auto")})"); + return SetStatus($"handing {_item} to {_npc}..."); + } + + /// Stops a running hand-in. + public void StopHandIn(string why = "stopped") + { + if (_step == Step.Idle) return; + _step = Step.Idle; + SetStatus(why); + RynthLog.Write(LogCat.IltHub, $"[IltGuardian] hand-in {why}"); + } + + private string SetStatus(string text) + { + _handInStatus = text; + return text; + } + + private void Fail(string why) + { + _step = Step.Idle; + SetStatus("failed: " + why); + _ctx.Chat($"[ILT Guardian] Hand-in failed: {why}"); + RynthLog.Write(LogCat.IltHub, $"[IltGuardian] hand-in failed: {why}"); + } + + private void Next(Step step, long nowMs, long timeoutMs = 0) + { + _step = step; + _stepDeadline = timeoutMs > 0 ? nowMs + timeoutMs : 0; + } + + private void StepHandIn(long nowMs) + { + if (_step == Step.Idle || nowMs < _nextStepAt) return; + if (nowMs - _startedAt > HandInTimeoutMs) { Fail("timed out"); return; } + if (_stepDeadline != 0 && nowMs > _stepDeadline) { Fail(TimeoutText(_step)); return; } + + var host = _ctx.Host; + switch (_step) + { + case Step.FindItem: + if (FindHandInItem() != null) { Next(Step.Give, nowMs); break; } + if (!IsTempleGuardian(_npc) || !S.BuyMissingFromVendor) { LogItemNearMisses(); Fail($"no {_item} in your packs"); break; } + Next(Step.OpenVendor, nowMs); + break; + + case Step.OpenVendor: + { + if (!host.HasVendorTrade) { Fail($"no {_item} carried and vendor buying needs a newer RynthCore engine"); break; } + if (host.TryGetVendorInfo(out var open)) { _vendorId = open.VendorId; Next(Step.Buy, nowMs); break; } + var vendor = Nearest(IsVendor); + if (vendor == null) { LogVendorSearch(); Fail($"no {_item} carried and no vendor within {SearchRangeMeters:0} m"); break; } + RynthLog.Write(LogCat.IltHub, $"[IltGuardian] vendor for '{_item}': {vendor.Name} 0x{(uint)vendor.Id:X8}"); + SetStatus($"opening {vendor.Name} to buy {_item}..."); + host.UseFor(unchecked((uint)vendor.Id), "IltGuardian", $"buy {_item} for the Temple guardian", + _asked ? UseKind.Asked : UseKind.Auto); + Next(Step.WaitVendor, nowMs, VendorOpenTimeoutMs); + break; + } + + case Step.WaitVendor: + if (host.TryGetVendorInfo(out var info) && info.ItemCount > 0) { _vendorId = info.VendorId; Next(Step.Buy, nowMs); } + break; + + case Step.Buy: + { + if (!host.TryGetVendorInfo(out var v)) { Fail("the vendor closed"); break; } + if (v.TradeInFlight) { _nextStepAt = nowMs + BusyRetryMs; break; } + string want = NormalizeName(_item); + var match = host.GetVendorItems().FirstOrDefault(i => NormalizeName(i.Name) == want); + if (match == null) { Fail($"{v.Name} doesn't sell {_item}"); break; } + _buyRequest = host.VendorBuy(match.ObjectId, 1, v.VendorId); + if (_buyRequest == 0) + { + string why = host.TryGetVendorTradeStatus(out var st) && st.Message.Length > 0 ? st.Message : "refused"; + Fail($"couldn't buy {_item}: {why}"); + break; + } + SetStatus($"buying {_item} from {v.Name}..."); + Next(Step.WaitBuy, nowMs, BuyTimeoutMs); + break; + } + + case Step.WaitBuy: + if (!host.TryGetVendorTradeStatus(out var status) || status.RequestId != _buyRequest || !status.IsFinished) break; + if (!status.Succeeded) { Fail($"couldn't buy {_item}: {(status.Message.Length > 0 ? status.Message : status.Result.ToString())}"); break; } + Next(Step.WaitItem, nowMs, ItemArriveTimeoutMs); + break; + + case Step.WaitItem: + if (FindHandInItem() != null) Next(Step.Give, nowMs); + break; + + case Step.Give: + GiveStep(nowMs); + break; + } + } + + private void GiveStep(long nowMs) + { + if (_ctx.Inventory.IsBusy) + { + SetStatus("waiting for the client (busy)..."); + _nextStepAt = nowMs + BusyRetryMs; + return; + } + var item = FindHandInItem(); + if (item == null) { LogItemNearMisses(); Fail($"no {_item} in your packs"); return; } + var npc = Nearest(wo => wo.Name.Contains(_npc, StringComparison.OrdinalIgnoreCase)); + if (npc == null) { Fail($"{_npc} isn't nearby"); return; } + + int stack = _ctx.Inventory.StackSize(item); + bool ok = _ctx.Host.GiveObjectTo(unchecked((uint)item.Id), unchecked((uint)npc.Id), stack > 1 ? 1 : 0); + RynthLog.Write(LogCat.IltHub, $"[IltGuardian] give '{item.Name}' 0x{(uint)item.Id:X8} (stack {stack}) -> {npc.Name} 0x{(uint)npc.Id:X8}: {ok}"); + if (ok) + { + _step = Step.Idle; + SetStatus($"gave {item.Name} to {npc.Name}"); + _ctx.Chat($"[ILT Guardian] Gave {item.Name} to {npc.Name}."); + return; + } + if (++_giveAttempts >= MaxGiveAttempts) { Fail("the give was refused"); return; } + _nextStepAt = nowMs + BusyRetryMs; + } + + private static string TimeoutText(Step step) => step switch + { + Step.WaitVendor => "the vendor didn't open", + Step.WaitBuy => "the vendor didn't answer the purchase", + Step.WaitItem => "the bought item didn't arrive", + _ => "timed out", + }; + + private static bool IsTempleGuardian(string npc) => + npc.Contains(IltGuardianPhrasebook.TempleGuardian, StringComparison.OrdinalIgnoreCase); + + /// + /// A carried (not wielded) item named like the answer (case and spacing ignored). Reads AC's + /// live container contents: the cache's inventory set lags a purchase and also holds the open + /// vendor's stock, which can't be given. + /// + private WorldObject? FindHandInItem() + { + string want = NormalizeName(_item); + return CarriedItems().FirstOrDefault(wo => NormalizeName(wo.Name) == want && !_ctx.Inventory.IsEquipped(wo)); + } + + /// Live walk of the player's pack and side packs (falls back to the cache without the engine call). + private System.Collections.Generic.IReadOnlyList CarriedItems() + => _ctx.Inventory.Cache?.GetDirectInventory(forceRefresh: true) ?? Array.Empty(); + + /// Lower-case, trimmed, single-spaced name for comparisons. + private static string NormalizeName(string name) + => string.Join(' ', (name ?? string.Empty).Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant(); + + /// Logs carried items sharing a word with the answer, so a name mismatch shows in the log. + private void LogItemNearMisses() + { + var items = CarriedItems(); + var words = NormalizeName(_item).Split(' ').Where(w => w.Length > 3).ToArray(); + var similar = items.Where(wo => words.Any(w => wo.Name.Contains(w, StringComparison.OrdinalIgnoreCase))) + .Take(8).Select(wo => $"'{wo.Name}' 0x{(uint)wo.Id:X8}").ToArray(); + RynthLog.Write(LogCat.IltHub, + $"[IltGuardian] no '{_item}' among {items.Count} carried items; similar names: {(similar.Length > 0 ? string.Join(", ", similar) : "none")}"); + } + + /// A vendor (weenie BF_VENDOR flag, or a cache entry already classed Vendor). + private bool IsVendor(WorldObject wo) + { + if (wo.ObjectClass == AcObjectClass.Vendor) return true; + var host = _ctx.Host; + return host.HasGetObjectBitfield && host.TryGetObjectBitfield(unchecked((uint)wo.Id), out uint bf) && (bf & BfVendor) != 0; + } + + /// Logs every vendor the cache sees with its distance (vendor search found none in range). + private void LogVendorSearch() + { + var cache = _ctx.Inventory.Cache; + int playerId = unchecked((int)_ctx.Inventory.PlayerId); + if (cache == null || playerId == 0) { RynthLog.Write(LogCat.IltHub, "[IltGuardian] vendor search: no world cache / player"); return; } + var landscape = cache.GetLandscapeObjects().ToList(); + var vendors = landscape.Where(IsVendor).Take(8) + .Select(wo => $"'{wo.Name}' 0x{(uint)wo.Id:X8} {cache.Distance(playerId, wo.Id):0.0} m").ToArray(); + RynthLog.Write(LogCat.IltHub, + $"[IltGuardian] vendor search: {landscape.Count} landscape objects, bitfield={(_ctx.Host.HasGetObjectBitfield ? "yes" : "no")}, " + + $"vendors: {(vendors.Length > 0 ? string.Join(", ", vendors) : "none")}"); + } + + /// Nearest landscape object matching within SearchRangeMeters. + private WorldObject? Nearest(Func match) + { + var cache = _ctx.Inventory.Cache; + int playerId = unchecked((int)_ctx.Inventory.PlayerId); + if (cache == null || playerId == 0) return null; + WorldObject? best = null; + double bestDist = SearchRangeMeters; + foreach (var wo in cache.GetLandscapeObjects()) + { + if (!match(wo)) continue; + double d = cache.Distance(playerId, wo.Id); + if (d <= bestDist) { bestDist = d; best = wo; } + } + return best; + } + + // ── Commands ──────────────────────────────────────────────────────────── + + /// + /// "/ra guardian translate <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status". + /// "window" is handled by the controller. Pump thread. + /// + public void HandleCommand(string[] args) + { + string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "status"; + string rest = args.Length > 1 ? string.Join(" ", args.Skip(1)) : string.Empty; + switch (sub) + { + case "translate": + case "t": + _ctx.Chat("[ILT Guardian] " + TranslateManual(rest)); + break; + case "handin": + case "give": + _ctx.Chat("[ILT Guardian] " + StartHandIn(_lastAnswer, _lastNpc, asked: true)); + break; + case "stop": + StopHandIn(); + _ctx.Chat("[ILT Guardian] Hand-in stopped."); + break; + case "chat": + S.AutoDetectFromChat = Toggle(rest, S.AutoDetectFromChat); + _ctx.Chat($"[ILT Guardian] Chat auto-detect {(S.AutoDetectFromChat ? "on" : "off")}."); + break; + case "auto": + S.AutoHandIn = Toggle(rest, S.AutoHandIn); + _ctx.Chat($"[ILT Guardian] Auto hand-in {(S.AutoHandIn ? "on" : "off")}."); + break; + case "buy": + S.BuyMissingFromVendor = Toggle(rest, S.BuyMissingFromVendor); + _ctx.Chat($"[ILT Guardian] Buy missing Temple items {(S.BuyMissingFromVendor ? "on" : "off")}."); + break; + case "refresh": + _ctx.Chat("[ILT Guardian] " + Attributes.Refresh()); + break; + case "status": + _ctx.Chat($"[ILT Guardian] chat={(S.AutoDetectFromChat ? "on" : "off")} auto={(S.AutoHandIn ? "on" : "off")} buy={(S.BuyMissingFromVendor ? "on" : "off")} " + + $"answer={(_lastAnswer.Length > 0 ? $"{_lastAnswer} -> {_lastNpc}" : "-")} hand-in: {_handInStatus}"); + foreach (var r in Attributes.Snapshot) + _ctx.Chat($"[ILT Guardian] {r.Attribute,-12} {r.Npc,-16} #{r.Count} {r.Status} {r.Eta}"); + break; + default: + _ctx.Chat("[ILT Guardian] /ra guardian [window [show|hide]|translate |handin|stop|chat on|off|auto on|off|buy on|off|refresh|status]"); + break; + } + } + + // ── Reader ("RynthILT.Data" GetGuardianJson / GuardianCommand; RynthOracle's Quests tab) ── + + /// + /// The reader JSON (Plugins/Shared/RynthIltDataApi.cs header has the shape): the switches, the + /// last answer and hand-in status, and the attribute turn-in rows. Built on demand: everything it + /// reads is volatile or an immutable snapshot. Any thread. + /// + public string ReaderJson(string world) + { + TimeSpan age = LastAnswerAge; + return BuildJson(world, S.AutoDetectFromChat, S.AutoHandIn, S.BuyMissingFromVendor, S.CooldownHoursAssumed, + _lastAnswer, _lastNpc, age == TimeSpan.MaxValue ? -1 : (long)age.TotalSeconds, + IltGuardianPhrasebook.MessageOf(_lastLine), HandInRunning, _handInStatus, Attributes.SyncedUtc, Attributes.Snapshot); + } + + /// The reader JSON from its parts. Pure: the tests drive it. + internal static string BuildJson(string world, bool chat, bool auto, bool buy, int cooldownHours, + string answer, string npc, long answerAgeSec, string heard, bool running, string status, + DateTime syncedUtc, System.Collections.Generic.IReadOnlyList rows) + { + var sb = new System.Text.StringBuilder(1024); + sb.Append("{\"available\":true"); + Str(sb, "world", world); + sb.Append(",\"chat\":").Append(chat ? "true" : "false"); + sb.Append(",\"auto\":").Append(auto ? "true" : "false"); + sb.Append(",\"buy\":").Append(buy ? "true" : "false"); + sb.Append(",\"cooldownHours\":").Append(cooldownHours); + Str(sb, "answer", answer); + Str(sb, "npc", npc); + sb.Append(",\"answerAgeSec\":").Append(answerAgeSec); + Str(sb, "heard", heard); + sb.Append(",\"running\":").Append(running ? "true" : "false"); + Str(sb, "status", status); + Str(sb, "synced", syncedUtc == DateTime.MinValue ? "" : syncedUtc.ToString("yyyy-MM-ddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture)); + sb.Append(",\"rows\":["); + for (int i = 0; i < rows.Count; i++) + { + IltTempleAttrStatus r = rows[i]; + if (i > 0) sb.Append(','); + sb.Append('{'); + Str(sb, "attribute", r.Attribute, first: true); + Str(sb, "npc", r.Npc); + sb.Append(",\"count\":").Append(r.Count); + Str(sb, "status", r.Status); + Str(sb, "eta", r.Eta); + sb.Append(",\"ready\":").Append(r.Ready ? "true" : "false"); + sb.Append(",\"exact\":").Append(r.FromMyQuests ? "true" : "false"); + sb.Append('}'); + } + sb.Append("]}"); + return sb.ToString(); + } + + private static void Str(System.Text.StringBuilder sb, string name, string? value, bool first = false) + { + if (!first) sb.Append(','); + sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"'); + } + + /// + /// A reader's verb line (header of Plugins/Shared/RynthIltDataApi.cs): handin | stop | refresh | + /// chat on|off | auto on|off | buy on|off. The reader shows the new state, so the switches don't + /// echo in chat; hand-in and refresh report as the Guardian window's buttons do. Pump thread. + /// + public void RunVerb(string line) + { + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 0) return; + string arg = parts.Length > 1 ? parts[1] : ""; + switch (parts[0].ToLowerInvariant()) + { + case "handin": StartHandIn(_lastAnswer, _lastNpc, asked: true); break; + case "stop": StopHandIn(); break; + case "refresh": _ctx.Chat("[ILT Guardian] " + Attributes.Refresh()); break; + case "chat": S.AutoDetectFromChat = Toggle(arg, S.AutoDetectFromChat); break; + case "auto": S.AutoHandIn = Toggle(arg, S.AutoHandIn); break; + case "buy": S.BuyMissingFromVendor = Toggle(arg, S.BuyMissingFromVendor); break; + default: + RynthLog.Trace(LogCat.IltHub, $"[IltGuardian] reader verb ignored: {line}"); + return; + } + RynthLog.Write(LogCat.IltHub, $"[IltGuardian] reader verb: {line}"); + } + + private static bool Toggle(string mode, bool current) => mode.Trim().ToLowerInvariant() switch + { + "on" or "true" or "1" or "show" => true, + "off" or "false" or "0" or "hide" => false, + _ => !current, + }; + + // ── UI (render thread) ────────────────────────────────────────────────── + + /// Guardian window body. + public void Render() + { + if (ImGui.CollapsingHeader("Riddle translator", ImGuiTreeNodeFlags.DefaultOpen)) RenderTranslator(); + ImGui.Spacing(); + if (ImGui.CollapsingHeader("Attribute turn-ins", ImGuiTreeNodeFlags.DefaultOpen)) RenderTracker(); + } + + private void RenderTranslator() + { + var s = S; + // Plain bool writes; the pump thread reads them on its next tick. + bool chat = s.AutoDetectFromChat; + if (ImGui.Checkbox("Detect from chat##grdchat", ref chat)) s.AutoDetectFromChat = chat; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Translate the guardians' tells as they arrive and show the answer here and on the Mini Remote."); + ImGui.SameLine(); + bool auto = s.AutoHandIn; + if (ImGui.Checkbox("Auto hand-in##grdauto", ref auto)) s.AutoHandIn = auto; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("After a chat answer, give one of the item to the guardian automatically."); + ImGui.SameLine(); + bool buy = s.BuyMissingFromVendor; + if (ImGui.Checkbox("Buy if missing##grdbuy", ref buy)) s.BuyMissingFromVendor = buy; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Temple guardian: when you carry none, buy one from the open or nearest vendor first."); + + string line = _lastLine; + if (line.Length > 0) + { + ImGui.TextDisabled("Heard:"); + ImGui.SameLine(); + ImGui.PushTextWrapPos(0f); + SafeImGui.TextDisabled(IltGuardianPhrasebook.MessageOf(line)); + ImGui.PopTextWrapPos(); + } + + string answer = _lastAnswer, npc = _lastNpc; + if (answer.Length > 0) + { + SafeImGui.TextColored(IltStyle.ColTeal, answer); + ImGui.SameLine(); + SafeImGui.TextDisabled("-> " + npc); + if (HandInRunning) + { + if (ImGui.SmallButton("Stop##grdstop")) _ctx.Post(() => StopHandIn()); + } + else if (ImGui.SmallButton("Hand in##grdgive")) + { + _ctx.Post(() => StartHandIn(answer, npc, asked: true)); + } + } + else ImGui.TextDisabled("No guardian answer yet."); + SafeImGui.TextDisabled("Hand-in: " + _handInStatus); + + ImGui.Spacing(); + ImGui.InputTextMultiline("##grdinput", ref _input, 2048u, new Vector2(-1, 54)); + if (ImGui.Button("Translate##grdtr")) + { + string text = _input; + _ctx.Post(() => _ctx.Chat("[ILT Guardian] " + TranslateManual(text))); + } + ImGui.SameLine(); + if (ImGui.Button("Clear##grdclr")) _input = string.Empty; + ImGui.SameLine(); + ImGui.TextDisabled("Paste a spell word or the riddle's question line."); + } + + private void RenderTracker() + { + if (ImGui.SmallButton("Refresh##grdref")) _ctx.Post(() => _ctx.Chat("[ILT Guardian] " + Attributes.Refresh())); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-read /myquests and /qb list (the server allows each once a minute)."); + ImGui.SameLine(); + DateTime synced = Attributes.SyncedUtc; + SafeImGui.TextDisabled(synced == DateTime.MinValue ? "/qb not read this session" : $"/qb read {synced.ToLocalTime():t}"); + ImGui.SameLine(); + if (ImGui.SmallButton("Reset counts##grdreset")) + _ctx.Confirm("Reset turn-in counts", "Forget the turn-in counts and cooldown estimates taken from /qb wait stamps? (/myquests counts are not affected.)", + Attributes.ResetCounts, "Reset"); + + var rows = Attributes.Snapshot; + if (rows.Length > 0 && ImGui.BeginTable("##grdattr", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingStretchProp)) + { + ImGui.TableSetupColumn("Attribute", ImGuiTableColumnFlags.None, 1.0f); + ImGui.TableSetupColumn("NPC", ImGuiTableColumnFlags.None, 1.3f); + ImGui.TableSetupColumn("#", ImGuiTableColumnFlags.None, 0.35f); + ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.None, 0.9f); + ImGui.TableSetupColumn("Next", ImGuiTableColumnFlags.None, 1.5f); + ImGui.TableHeadersRow(); + foreach (var r in rows) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Attribute); + ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Npc); + ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Count.ToString()); + ImGui.TableNextColumn(); + var col = r.Ready ? IltStyle.ColGreen + : r.Status == "Unknown" ? IltStyle.ColTextMute + : IltStyle.ColAmber; + SafeImGui.TextColored(col, r.Status); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip(r.FromMyQuests ? "From /myquests (exact)." : "From /qb wait stamps (count and timer are estimates)."); + ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Eta); + } + ImGui.EndTable(); + } + + int hours = S.CooldownHoursAssumed; + ImGui.SetNextItemWidth(140); + if (ImGui.SliderInt("Assumed cooldown (h)##grdhours", ref hours, 1, 72)) S.CooldownHoursAssumed = hours; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Used only for rows /myquests doesn't report: how long a /qb wait stamp lasts."); + } + + /// + /// Mini Remote line: the last answer (for AnswerShownFor) with a Give / Stop button. + /// Draws nothing when there is no recent answer. Render thread. + /// + public void RenderRemoteLine() + { + string answer = _lastAnswer, npc = _lastNpc; + if (answer.Length == 0 || LastAnswerAge > AnswerShownFor) return; + ImGui.TextColored(IltStyle.ColTextMute, "Guardian:"); + ImGui.SameLine(); + SafeImGui.TextColored(IltStyle.ColTeal, answer); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"Give to {npc}\nHand-in: {_handInStatus}"); + ImGui.SameLine(); + if (HandInRunning) + { + if (ImGui.SmallButton("Stop##mrgrd")) _ctx.Post(() => StopHandIn()); + } + else if (ImGui.SmallButton("Give##mrgrd")) + { + _ctx.Post(() => StartHandIn(answer, npc, asked: true)); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardianPhrasebook.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardianPhrasebook.cs new file mode 100644 index 0000000..67773c7 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardianPhrasebook.cs @@ -0,0 +1,221 @@ +// IltGuardianPhrasebook.cs - Temple of Enlightenment spell words and Guardian of Attribute +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// Enlightenment riddles mapped to the item each guardian wants (Infinite Leaftide). +// +// Pure functions only (no host calls), so the Guardian window may translate on the render thread. +// The riddle table matches on the closing question line; lead-in lines alone return "No match". +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal static class IltGuardianPhrasebook +{ + public const string TempleGuardian = "Guardian of the Temple of Enlightenment"; + public const string AttributeGuardian = "Guardian of Attribute Enlightenment"; + + /// Chat prefixes of an incoming guardian line ("tells you" or ACE's environmental "says"). + private static readonly string[] IncomingPrefixes = + { + TempleGuardian + " tells you", + AttributeGuardian + " tells you", + TempleGuardian + " says", + AttributeGuardian + " says", + }; + + /// Help text returned when nothing was pasted. + public const string PasteHint = "Paste a spell word or riddle text, then Translate."; + + /// Help text returned when the text didn't match any spell word or riddle. + public const string NoMatchHint = "No match: paste more lines from the guardian (especially the question line ending with ?)."; + + private static readonly Dictionary TempleSpells = new(StringComparer.OrdinalIgnoreCase) + { + { "Boquar", "Mugwort" }, { "Feazh", "Damiana" }, { "Kenrak", "Amaranth" }, + { "Puish", "Saffron" }, { "Shurov", "Comfrey" }, { "Volae", "Eyebright" }, + { "Cruath", "Ginseng" }, { "Helkas", "Wormwood" }, { "Malar", "Hyssop" }, + { "Quavosh", "Dragonsblood" }, { "Tugak", "Vervain" }, { "Yanoi", "Bistort" }, + { "Equin", "Mandrake" }, { "Jevak", "Myrrh" }, { "Ozhur", "Frankincense" }, + { "Roiga", "Yarrow" }, { "Uthoi", "Henbane" }, { "Zojak", "Hawthorn" }, + }; + + /// Spell words longest first so a short word never shadows a longer one. + private static readonly KeyValuePair[] TempleSpellsByLength = + TempleSpells.OrderByDescending(p => p.Key.Length).ToArray(); + + /// Normalized riddle phrases (longest first) and the item each answers. + private static readonly (string Needle, string Item)[] AttributeClues = BuildAttributeClues(); + + /// The same riddles split into meaningful words for the fuzzy fallback. + private static readonly (string Item, string[] Words)[] AttributeClueWords = + AttributeClues.Select(c => (c.Item, TokenizeMeaningfulWords(c.Needle))).ToArray(); + + private static (string, string)[] BuildAttributeClues() + { + var raw = new (string Phrase, string Item)[] + { + ("what stone of shadow wields such arm", "Powdered Onyx"), + ("what stone defends the mortal clay", "Powdered Agate"), + ("what heavy stone keeps adventurers healed", "Powdered Hematite"), + ("what heavy stone keeps adventure's healed", "Powdered Hematite"), + ("what honeyed stone bids pain to leave", "Powdered Amber"), + ("what draught unweaves that mages send", "Chorizite"), + ("what gem of life beats deep within", "Powdered Bloodstone"), + ("what ruddy gem calls vigor nigh", "Powdered Carnelian"), + ("what lunar gem gives peace to mind", "Powdered Moonstone"), + ("what verdant gem reveals the way", "Powdered Malachite"), + ("what crystal tunes the life it soothes", "Powdered Quartz"), + ("what gem of sky makes items nice", "Powdered Turquoise"), + ("what vial holds my burning scar", "Brimstone"), + ("which draught brings forth the fire's scent", "Turpeth"), + ("race the wind yet leave no trace", "Cadmia"), + ("grant the hand a dancer grace", "Cadmia"), + ("no wings I bear yet fleet I flee", "Cadmia"), + ("what draught awakens speed in thee", "Cadmia"), + ("what deaught awakens speed in thee", "Cadmia"), + ("what potion turns mana-use to one", "Cinnabar"), + ("what azure draught makes thunder weep", "Cobalt"), + ("what draught commands the winter's tide", "Colcothar"), + ("what pale draught prevents acid's writhe", "Gypsum"), + ("whate pale draught prevents acid's writhe", "Gypsum"), + ("what liquid turns heart grey between", "Quicksilver"), + ("what potion pierces the unseen end", "Realgar"), + ("what shadowed draught makes swiftness lie", "Stibnite"), + ("what verdant vial hides cuts unseen", "Verdigris"), + ("what potion shakes both flesh and floor", "Vitriol"), + ("what river wood trades life as art", "Alder Talisman"), + ("what wood enchants both bane and skill", "Ashwood Talisman"), + ("what pale wood casts the striker's bane", "Birch Talisman"), + ("what sacred stem keeps harm outside", "Cedar Talisman"), + ("what dark wood diminishes the foe's own tune", "Blackthorn Talisman"), + ("what hardwood charm makes others stand", "Ebony Talisman"), + ("what aged branch makes circles run", "Elder Talisman"), + ("what mystic bough binds here to yore", "Hazel Talisman"), + ("what poisoned branch brings creeping death", "Hemlock Talisman"), + ("what steadfast wood makes volleys rained", "Oak Talisman"), + ("what living wand makes allies mend", "Poplar Talisman"), + ("what sacred wood the self amends", "Rowan Talisman"), + ("what supple wood restores me here", "Willow Talisman"), + ("what ancient bough lets lifeblood grow", "Yew Talisman"), + }; + return raw.Select(t => (NormalizePhrase(t.Phrase), t.Item)) + .OrderByDescending(t => t.Item1.Length) + .ToArray(); + } + + /// Lowercase, curly apostrophes folded, punctuation collapsed to single spaces. + private static string NormalizePhrase(string s) + { + if (string.IsNullOrWhiteSpace(s)) return string.Empty; + string lower = s.Trim().ToLowerInvariant().Replace('\u2019', '\''); + var sb = new StringBuilder(lower.Length); + bool pendingSpace = false; + foreach (char c in lower) + { + bool wordCh = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '\''; + if (!wordCh) { pendingSpace = true; continue; } + if (pendingSpace && sb.Length > 0) { sb.Append(' '); pendingSpace = false; } + sb.Append(c); + } + return sb.ToString().Trim(); + } + + /// Words of 3+ letters minus question / filler words. + private static string[] TokenizeMeaningfulWords(string normalized) => + normalized.Split(' ', StringSplitOptions.RemoveEmptyEntries) + .Where(w => w.Length >= 3 && w is not ("what" or "which" or "the" or "and" or "for")) + .ToArray(); + + /// + /// Typo-tolerant fallback: the riddle whose words overlap the input best, needing at least four + /// shared words and 72% of the riddle's words so a near-miss never maps to the wrong item. + /// + private static string? TryFuzzyAttributeMatch(string blob) + { + var inputWords = TokenizeMeaningfulWords(blob); + if (inputWords.Length == 0) return null; + var inputSet = new HashSet(inputWords, StringComparer.Ordinal); + string? bestItem = null; + double bestScore = 0d; + foreach (var (item, words) in AttributeClueWords) + { + if (words.Length == 0) continue; + int matches = words.Count(inputSet.Contains); + double score = (double)matches / words.Length; + if (matches >= 4 && score >= 0.72d && score > bestScore) + { + bestScore = score; + bestItem = item; + } + } + return bestItem; + } + + /// Resolves guardian text to an item name, or one of the help strings. + public static string Translate(string raw) + { + string blob = NormalizePhrase(raw); + if (blob.Length == 0) return PasteHint; + + var tokens = Regex.Split(blob, @"[^a-z0-9']+").Where(t => t.Length > 0).ToList(); + foreach (var pair in TempleSpellsByLength) + if (tokens.Any(t => t.Equals(pair.Key, StringComparison.OrdinalIgnoreCase))) + return pair.Value; + foreach (var pair in TempleSpellsByLength) + if (blob.Contains(pair.Key.ToLowerInvariant(), StringComparison.Ordinal)) + return pair.Value; + foreach (var (needle, item) in AttributeClues) + if (needle.Length > 0 && blob.Contains(needle, StringComparison.Ordinal)) + return item; + return TryFuzzyAttributeMatch(blob) ?? NoMatchHint; + } + + /// False for the help strings Translate returns when nothing matched. + public static bool IsAnswer(string translation) => + !string.IsNullOrWhiteSpace(translation) && translation != PasteHint && translation != NoMatchHint; + + /// True when the line starts like an incoming guardian tell / say. + public static bool LooksLikeIncomingGuardianLine(string raw) + { + if (string.IsNullOrWhiteSpace(raw)) return false; + string t = raw.TrimStart(); + foreach (string prefix in IncomingPrefixes) + if (t.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + return true; + return false; + } + + /// The guardian to give the item to, read from an incoming line (Attribute when unclear). + public static string TurnInNpcFromLine(string raw) + { + if (!string.IsNullOrEmpty(raw) && raw.Contains(TempleGuardian, StringComparison.OrdinalIgnoreCase)) + return TempleGuardian; + return AttributeGuardian; + } + + /// + /// The guardian for manually pasted text: the name in a pasted chat line, else a Temple spell + /// word means the Temple guardian, else the Attribute guardian. + /// + public static string TurnInNpcFromInput(string raw) + { + if (string.IsNullOrWhiteSpace(raw)) return AttributeGuardian; + if (raw.Contains(TempleGuardian, StringComparison.OrdinalIgnoreCase)) return TempleGuardian; + if (raw.Contains(AttributeGuardian, StringComparison.OrdinalIgnoreCase)) return AttributeGuardian; + foreach (string word in TempleSpells.Keys) + if (raw.Contains(word, StringComparison.OrdinalIgnoreCase)) + return TempleGuardian; + return AttributeGuardian; + } + + /// The quoted message of a guardian line ("... tells you, \"text\"" → text); the line itself otherwise. + public static string MessageOf(string line) + { + int open = line.IndexOf('"'); + int close = line.LastIndexOf('"'); + return open >= 0 && close > open ? line.Substring(open + 1, close - open - 1).Trim() : line.Trim(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubContext.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubContext.cs new file mode 100644 index 0000000..ced863c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubContext.cs @@ -0,0 +1,114 @@ +// IltHubContext.cs — Shared services handed to every ILT Hub feature. +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. What the +// features borrowed from RynthAi's internals now comes through Ai (RynthAi.Hub, RynthAiClient). +// +// Threading contract: +// * Feature Tick / OnChat run on the plugin pump thread and may call the host freely. +// * Feature Render runs on the ImGui render thread and must NOT call AC actions directly. +// It calls Post(...) to run work on the next pump tick, or Confirm(...) to ask the +// player first (the confirmed action is then posted). +using System; +using System.Collections.Concurrent; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// A yes/no question waiting for the player (a modal over the Mini Remote). +internal sealed class IltConfirmRequest +{ + public string Title = "Confirm"; + public string Message = string.Empty; + public string YesLabel = "Yes"; + /// Runs on the pump thread after the player clicks Yes. + public Action? OnYes; +} + +internal sealed class IltHubContext +{ + private readonly ConcurrentQueue _posted = new(); + private readonly ConcurrentQueue _confirms = new(); + + public IltHubContext(RynthCoreHost host, IltHubState state, IltHubStore store, IltChatCapture capture, + IltServerOptions options, IltInventory inventory, IltSettings settings, RynthAiClient ai) + { + Host = host; + State = state; + Store = store; + Capture = capture; + Options = options; + Inventory = inventory; + Settings = settings; + Ai = ai; + } + + public RynthCoreHost Host { get; } + public IltHubState State { get; } + public IltHubStore Store { get; } + public IltChatCapture Capture { get; } + public IltServerOptions Options { get; } + public IltInventory Inventory { get; } + + /// RynthILT's settings (the server list). Edits are saved through . + public IltSettings Settings { get; } + + /// Saves (pump thread). + public void SaveSettings() => IltSettingsStore.Save(Settings); + + /// RynthAi's services (the Mini Remote, /myquests, spell names, loot matching); each says when RynthAi is missing. + public RynthAiClient Ai { get; } + + /// Logged-in character name (resolved at login). + public string CharName = string.Empty; + + /// True when the Mini Remote is on screen (features use it to gate auto-refreshes). + public bool WindowOpen => State.WindowVisible; + + /// + /// Shows the Mini Remote on one of its ILT tabs (set by the controller). Any thread: it only + /// records the tab and the show request, which the next frame applies. + /// + public Action? ShowTab; + + /// Writes a local chat line (never sent to the server). + public void Chat(string text) + { + if (Host.HasWriteToChat) Host.WriteToChat(text, 1); + } + + /// Queues work for the next pump tick (safe from the render thread). + public void Post(Action action) => _posted.Enqueue(action); + + /// Asks the player to confirm before runs on the pump thread. + public void Confirm(string title, string message, Action onYes, string yesLabel = "Yes") + => _confirms.Enqueue(new IltConfirmRequest { Title = title, Message = message, OnYes = onYes, YesLabel = yesLabel }); + + /// Render thread: takes the next pending confirmation, if any. + public bool TryTakeConfirm(out IltConfirmRequest request) => _confirms.TryDequeue(out request!); + + /// Pump thread: runs everything posted since the last tick. + public void DrainPosted() + { + int guard = 0; + while (guard++ < 64 && _posted.TryDequeue(out var a)) + { + try { a(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "posted action"); } + } + } + + /// Elapsed-ms clock used for every Hub timer. + public static long NowMs => Environment.TickCount64; +} + +/// Contract every Hub feature module implements. +internal interface IIltFeature +{ + /// Pump-thread tick (~every plugin tick). + void Tick(long nowMs); + + /// Pump-thread chat line. Return true to hide the line from the chat window. + bool OnChat(string text); + + /// Logout / teardown: stop automation, drop transient state. + void OnLogout(); +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs new file mode 100644 index 0000000..afd4bfe --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs @@ -0,0 +1,913 @@ +// IltHubController.cs — Owns the ILT features behind the Mini Remote's ILT tabs: state, services, +// feature modules, commands. +// Originally SilentKelpie's ILT Hub controller (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// RynthILTPlugin creates one controller per login session and forwards: +// OnTick → Tick() (pump thread) +// OnChatWindowText → OnChat() (pump thread; returns true to eat the line) +// OnRender → Render() (render thread: Games HUD, confirmations) +// the ILT "/ra hub ...", "/ra guardian ...", "/ra bounty ..." verbs (RynthAi forwards them +// through RynthILT.Hub Command) and "/ilt ..." → HandleCommand() +// OnLogout / teardown → OnLogout() +// The ILT sections are tabs of RynthAi's Mini Remote (RenderTab, through RynthILT.Hub); the +// Guardian is RynthCore's ILT panel (RenderGuardianPanel, RynthPluginRenderEmbed "guardian"), +// and bounties are RynthILT's Bounties window (RynthCore's ILT button), so "/ra bounty" and +// "/ra guardian window" open those engine panels. The Mini Remote's Quests and Pets tabs are +// RynthAi's (every world); RynthILT adds their ILT sections (the /qb list, the /pets and +// /shinies logs). On any world that isn't ILT-like every feature here stays dormant (no probes, +// no chat, no tabs). +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltHubController +{ + private const long SaveIntervalMs = 5000; + + private readonly IltHubContext _ctx; + private readonly IltHubUi _ui; + private readonly List _features = new(); + private long _lastSaveAt; + private int _questGeneration; // RynthAi's /myquests refreshes seen (NoteQuestTrackerOutcome) + private bool _availabilityAnnounced; // "open the Mini Remote" hint printed this session + private volatile int _forceRequest = -1; // SetForceIlt from another thread, applied on the next tick + private long _tabDrawnAt = long.MinValue / 2; // a tab drawn as RynthCore's section view (render thread) + private const long TabDrawnMs = 2000; + + // "RynthILT.Data" (Plugins/Shared/RynthIltDataApi.cs): the charms and bank snapshots, rebuilt on + // the pump every DataRebuildMs only while a reader has asked within DataWatchMs. + private const long DataRebuildMs = 2000; + private const long DataWatchMs = 6000; + /// How often the other characters' saved balances are re-read for the bank export. + private const long SiblingReadMs = 15_000; + private long _charmsReadAt, _bankReadAt; // set by readers (any thread, Interlocked) + private long _charmsBuiltAt, _bankBuiltAt, _siblingsReadAt; + private volatile string _charmsJson = string.Empty; + private volatile string _bankJson = string.Empty; + + // "RynthILT.Server" profile JSON (RynthOracle: feature states, fellowship rules, the /qb list). Rebuilt ~1 s. + private const long ProfileRebuildMs = 1000; + private long _profileBuiltAt; + private volatile string _profileJson = string.Empty; + private List _siblings = new(); + + public IltBanking Banking { get; } + public IltSessionRates Rates { get; } + /// The quest bonus list (/qb): the Quests tab's section and the Temple tracker's stamps. + public IltQuestBonus QuestBonus { get; } + /// The /pets and /shinies logs (the Pets tab's section). + public IltPetLogs PetLogs { get; } + /// The pet breeding tracker (the Pets tab's Breeding sub-tab, and the "RynthILT.Data" breeding JSON). + public IltPetBreeding Breeding { get; } + /// The Pets tab's ACECustom sections: pet charms, the summon-from-empty refill path, siphon auto-capture. + public IltPetAutomation PetAutomation { get; } + public IltProgression Progression { get; } + public IltGear Gear { get; } + public IltGames Games { get; } + /// Registry charm acquired / active / server state (the Charms tab and RynthILTGetCharmsJson). + public IltCharmTracker Charms { get; } + /// The Mini Remote's Charms tab (registry charms with toggles, the Guardian Hand). + public IltCharms CharmsTab { get; } + /// Temple guardians: riddle translator, hand-in, attribute turn-in tracker. + public IltGuardian Guardian { get; } + /// Vaulted Dungeons keeper (Mini Remote tab). ILT-only and behind its master switch (State.VaultedDungeonsEnabled), off by default. + public IltVaultedDungeons VaultedDungeons { get; } + /// The Empyrean Handler's lethal ring: asks RynthAi to back away (RynthAi.Hub BackAwayFrom). + public IltRingEvade RingEvade { get; } + /// T11 gear: the "/aug" wield counters for RynthAi's loot rules, "/ilt t11". + public IltT11 T11 { get; } + /// + /// Dynamic Stamps (from RynthOracle 2026-10-21): the NPC stamps had and missing, RynthNav's way there + /// and the Parchment hand-in (the Mini Remote's Quests section, "/ilt stamps"). + /// + public IltDynamicStamps DynamicStamps { get; } + + /// True while this character's copy from RynthAi is unfinished (IltHubStore.WritesBlocked). + /// The character's RynthAi folder while that copy is unfinished (read-only fallback). + public IltHubController(RynthCoreHost host, string charFolder, IltSettings settings, RynthAiClient ai, + Func? writesBlocked = null, string? legacyFolder = null) + { + var store = new IltHubStore(host, charFolder); + if (writesBlocked != null) store.WritesBlocked = writesBlocked; + store.LegacyFolder = legacyFolder; + var state = store.LoadState(); + var capture = new IltChatCapture(host); + var inventory = new IltInventory(host, new IltObjects(host)); + IltHubContext? ctxRef = null; + var options = new IltServerOptions(host, capture, state, text => ctxRef?.Chat(text), () => settings); + _ctx = new IltHubContext(host, state, store, capture, options, inventory, settings, ai); + ctxRef = _ctx; + + Banking = new IltBanking(_ctx); + PetLogs = new IltPetLogs(_ctx); + Breeding = new IltPetBreeding(_ctx); + PetAutomation = new IltPetAutomation(_ctx); + Rates = new IltSessionRates(_ctx); + QuestBonus = new IltQuestBonus(_ctx); + Progression = new IltProgression(_ctx); + Gear = new IltGear(_ctx); + Games = new IltGames(_ctx); + Charms = new IltCharmTracker(_ctx); + CharmsTab = new IltCharms(_ctx, Charms); + Guardian = new IltGuardian(_ctx, QuestBonus); + VaultedDungeons = new IltVaultedDungeons(_ctx); + RingEvade = new IltRingEvade(_ctx); + T11 = new IltT11(_ctx); + DynamicStamps = new IltDynamicStamps(_ctx); + _features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, PetAutomation, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, VaultedDungeons, Guardian, RingEvade, T11, DynamicStamps }); + + Banking.BalanceChanged += Rates.OnBankBalanceChanged; + Rates.MovingMoney = () => Banking.MovingMoney; + options.ProbeReplyTap = OnProbeReply; + _ui = new IltHubUi(this, _ctx); + _ctx.ShowTab = section => _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), "show"); + RebuildProfile(); + } + + /// + /// The latest "RynthILT.Server" profile JSON: Leaftide features, fellowship rules and the /qb + /// list (Plugins/Shared/RynthIltServerApi.cs). Rebuilt on the pump about once a second so any + /// thread (ServerInterface) may read it. + /// + public string ProfileJson => _profileJson; + + /// Rebuilds from the current server options. Pump thread. + private void RebuildProfile() + { + IltServerOptions o = _ctx.Options; + _profileJson = IltFeatureCatalog.BuildProfileJson( + o.IsIltLikeWorld, o.WorldName, _ctx.State.ForceLeaftideFeatures, + o.Source ?? string.Empty, o.LastRefreshUtc, o.Get, + QuestBonus.Snapshot()); + } + + /// + /// The charms JSON ("RynthILT.Data" GetCharmsJson). Reading it marks the charms as watched, so + /// the pump keeps the snapshot fresh while a reader is showing it; "" until the first rebuild + /// after that. Any thread. + /// + public string CharmsJson + { + get { System.Threading.Interlocked.Exchange(ref _charmsReadAt, IltHubContext.NowMs); return _charmsJson; } + } + + /// The bank JSON ("RynthILT.Data" GetBankJson), as . + public string BankJson + { + get { System.Threading.Interlocked.Exchange(ref _bankReadAt, IltHubContext.NowMs); return _bankJson; } + } + + /// A reader's charm Toggle, posted to the pump (IltCharms checks the id). Any thread. + public void RequestCharmToggle(uint objectId) + => _ctx.Post(() => + { + if (!_ctx.Options.IsIltLikeWorld) return; + if (!CharmsTab.ToggleFromReader(objectId)) + RynthLog.Trace(LogCat.IltGear, $"reader toggle refused: 0x{objectId:X8} isn't a carried charm"); + _charmsBuiltAt = 0; // show the new state on the next tick + }); + + /// + /// The pet breeding JSON ("RynthILT.Data" GetPetBreedingJson). + /// Reading it keeps the tracker scanning; "" off an ILT world or before its first scan. Any thread. + /// + public string PetBreedingJson => _ctx.Options.IsIltLikeWorld ? Breeding.ReaderJson : string.Empty; + + /// A reader's breeding verb line, posted to the pump (IltPetBreeding.RunVerb). Any thread. + public void RequestBreedingVerb(string line) + => _ctx.Post(() => + { + if (!_ctx.Options.IsIltLikeWorld) return; + Breeding.RunVerb(line); + }); + + /// + /// The Temple guardian JSON ("RynthILT.Data" GetGuardianJson): switches, last answer, hand-in + /// status and attribute turn-ins. "" off an ILT world. Any thread. + /// + public string GuardianJson => _ctx.Options.IsIltLikeWorld ? Guardian.ReaderJson(_ctx.Options.WorldName) : string.Empty; + + /// A reader's guardian verb line, posted to the pump (IltGuardian.RunVerb). Any thread. + public void RequestGuardianVerb(string line) + => _ctx.Post(() => + { + if (!_ctx.Options.IsIltLikeWorld) return; + Guardian.RunVerb(line); + }); + + /// A reader's bank verb line, posted to the pump (IltBanking.RunVerb). Any thread. + public void RequestBankVerb(string line) + => _ctx.Post(() => + { + if (!_ctx.Options.IsIltLikeWorld) return; + Banking.RunVerb(line); + _bankBuiltAt = 0; + }); + + /// Pump: rebuilds the charms / bank snapshots a reader (or the Banking tab's every-character table) is watching. + private void RebuildReaderData(long now) + { + if (now - System.Threading.Interlocked.Read(ref _charmsReadAt) < DataWatchMs && now - _charmsBuiltAt >= DataRebuildMs) + { + _charmsBuiltAt = now; + _charmsJson = CharmsTab.BuildReaderJson(); + } + + bool bankWatched = now - System.Threading.Interlocked.Read(ref _bankReadAt) < DataWatchMs; + Banking.ReaderWatching = bankWatched; + // The Banking tab's every-character table (IltBankRoster) uses the same rows while it is on screen. + bool rosterWatched = now - Banking.RosterWatchedAt < DataWatchMs; + if (!bankWatched && !rosterWatched || now - _bankBuiltAt < DataRebuildMs) return; + _bankBuiltAt = now; + if (_siblingsReadAt == 0 || now - _siblingsReadAt >= SiblingReadMs) + { + _siblingsReadAt = now; + _siblings = IltBankExport.ReadSiblings(_ctx.Store.CharFolder); + } + IltServerOptions o = _ctx.Options; + string me = _ctx.CharName.Length > 0 ? _ctx.CharName : System.IO.Path.GetFileName(_ctx.Store.CharFolder.TrimEnd('\\', '/')); + var rows = new List(_siblings.Count + 1) { new(me, true, _ctx.State.Bank) }; + rows.AddRange(_siblings); + if (rosterWatched) Banking.PublishRoster(IltBankRoster.Build(rows)); + if (!bankWatched) return; + int enabled = o.IsOn(IltFeature.Bank) ? 1 : o.IsOff(IltFeature.Bank) ? 0 : -1; + _bankJson = IltBankExport.Build(o.IsIltLikeWorld, enabled, o.WorldName, me, rows, Banking.LatestResult, Banking.Transactions); + } + + public IltHubState State => _ctx.State; + public IltServerOptions Options => _ctx.Options; + internal IltHubContext Context => _ctx; + + /// World is ILT-like and the server has at least one ILT feature on. + public bool Available => _ctx.Options.IsIltLikeWorld && _ctx.Options.AnyFeatureOn; + + /// + /// Whether a section can be shown now: the ILT tabs and the Guardian need server features. + /// Character (moved to RynthOracle) always answers true so its redirect is never refused. + /// + public bool SectionAvailable(IltSection section) => section switch + { + IltSection.Character => true, + IltSection.Banking => Available && !_ctx.Options.IsOff(IltFeature.Bank), + IltSection.Games => Available && Games.AnyGameAvailable, + // Content, not a server feature bit: an ILT world and the master switch. + IltSection.VaultedDungeons => _ctx.Options.IsIltLikeWorld && VaultedDungeons.MasterEnabled(), + _ => Available, + }; + + /// + /// The Mini Remote offers the Infinite Leaftide tabs: an ILT-like world (or the Force-ILT + /// override from RynthCore Options > Diagnostics). The tabs then follow . + /// + public bool OffersTabs => _ctx.Options.IsIltLikeWorld; + + /// Whether the Mini Remote's tab bar shows . + public bool TabShown(IltSection section) => OffersTabs && IltSections.IsTab(section) && SectionAvailable(section); + + /// Render thread: one Mini Remote ILT tab's body (RynthAi's MiniRemoteHud draws the tab bar). + public void RenderTab(IltSection section) => _ui.RenderTab(section); + + /// Render thread: a tab was just drawn as RynthCore's section view (it counts as the Mini Remote on screen). + public void NoteTabDrawn() => System.Threading.Interlocked.Exchange(ref _tabDrawnAt, IltHubContext.NowMs); + + /// + /// Render thread: the ILT session extras (coins, pyreals, item conversions) in RynthCore's Mini + /// Remote "Session Stats" section, below RynthAi's session stats (surface "section:ilt-rates"). + /// + public void RenderRatesSection() => _ui.RenderRatesSection(); + + /// Render thread: the /qb list in RynthILT's own Quests section (surface "section:ilt-questbonus"). + public void RenderQuestBonusSection() => _ui.RenderQuestBonusSection(); + + /// Render thread: the Guardian panel's body (RynthPluginRenderEmbed "guardian"). + public void RenderGuardianPanel() => _ui.RenderGuardianPanel(); + + /// + /// Render thread: the Dynamic Stamps page (surface "section:ilt-dynstamps" in RynthILT's Quests + /// section, and the "/ilt stamps" window); a line saying so off ILT. + /// + public void RenderDynamicStamps() + { + if (!_ctx.Options.IsIltLikeWorld) + { + ImGuiNET.ImGui.TextDisabled("Dynamic Stamps are an Infinite Leaftide quest line; this world isn't treated as ILT."); + return; + } + DynamicStamps.Render(); + } + + /// + /// Render thread: the pet breeding tracker ("/ilt breeding"; RynthAi's Mini Remote also shows it + /// as the Pets tab's Breeding). A line saying so off ILT or where the server has pet breeding off. + /// + public void RenderBreedingWindowBody() + { + if (!_ctx.Options.IsIltLikeWorld) + { + ImGuiNET.ImGui.TextDisabled("Pet breeding is an Infinite Leaftide feature; this world isn't treated as ILT."); + return; + } + if (_ctx.Options.IsOff(RynthCore.Plugin.Shared.RynthIltHub.FeaturePetBreeding)) + { + ImGuiNET.ImGui.TextDisabled("This server has pet breeding switched off."); + return; + } + Breeding.RenderSection(); + } + + /// Render thread: one of the sections RynthAi draws (RynthILT.Hub RenderSection); false = nothing drawn. + public bool RenderSection(string id) => _ui.RenderSection(id); + + /// The Force-ILT world override (world identity only; features still come from the server). Set from any thread. + public bool ForceIltWorld + { + get => _ctx.State.ForceLeaftideFeatures; + set => _forceRequest = value ? 1 : 0; + } + + /// Re-asks the server which features are on (safe from the render thread: posted to the pump). + public void RequestOptionsRefresh() => _ctx.Post(() => _ctx.Options.Refresh(manual: true)); + + // ── Lifecycle ─────────────────────────────────────────────────────────── + + /// + /// Login: remember the character, schedule the options check, import UB data once. + /// : the character's RynthAi profile had "Force enable" ticked. + /// + public void OnLoginComplete(string charName, bool forceFromMigration) + { + _ctx.CharName = charName ?? string.Empty; + if (forceFromMigration) _ctx.State.ForceLeaftideFeatures = true; + RynthLog.Event(LogEvents.IltLogin, $"login: char='{_ctx.CharName}' world='{_ctx.Options.WorldName}'"); + _ctx.Options.OnLoginComplete(); + _ctx.Inventory.Reset(); + Rates.Reset(); + _questGeneration = 0; + + if (!_ctx.State.UbSidecarsImported && _ctx.CharName.Length > 0) + { + _ctx.State.UbSidecarsImported = true; + string world = _ctx.Options.WorldName; + Banking.ImportUb(tx => _ctx.Store.ImportUbSidecars(_ctx.State, tx, world, _ctx.CharName)); + } + } + + /// A RynthAi /myquests refresh ended since the last look: tell the options (the "quests" bit). + private void PollQuestOutcome() + { + if (!_ctx.Ai.TryGetQuestStatus(out var st) || st.Generation == _questGeneration) return; + _questGeneration = st.Generation; + if (st.Generation > 0) _ctx.Options.NoteQuestTrackerOutcome(st.Disabled != 0, st.Count); + } + + /// Pump-thread tick. + public void Tick() + { + long now = IltHubContext.NowMs; + int force = _forceRequest; + if (force >= 0) + { + _forceRequest = -1; + _ctx.State.ForceLeaftideFeatures = force == 1; + } + _ctx.DrainPosted(); + _ctx.Capture.Tick(); + _ctx.Options.Tick(); + PollQuestOutcome(); + + // The charms / bank snapshots other plugins read (RynthILT.Data), only while watched. + try { RebuildReaderData(now); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "RebuildReaderData"); } + + // The profile other plugins read ("RynthILT.Server"): world, feature states, fellowship, /qb. + if (now - _profileBuiltAt >= ProfileRebuildMs) + { + _profileBuiltAt = now; + try { RebuildProfile(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "RebuildProfile"); } + } + + // "Mini Remote on screen" gates bank auto-refresh and the gear / split-arrow scans: RynthAi's Mini + // Remote, or one of the tabs drawn as RynthCore's section view in the last couple of seconds. + _ctx.State.WindowVisible = _ctx.Ai.MiniRemoteVisible + || now - System.Threading.Interlocked.Read(ref _tabDrawnAt) < TabDrawnMs; + + // One hint per session once the server confirms ILT features. The Mini Remote is separate + // from the main RynthAi panel, so say how to open it. + if (!_availabilityAnnounced && Available) + { + _availabilityAnnounced = true; + if (!_ctx.State.WindowVisible) + _ctx.Chat("[Mini Remote] ILT server features detected. Open the Mini Remote (bar button, /rc miniremote) for the ILT tabs."); + } + + // Every feature here is Infinite Leaftide's: dormant on any other world. + if (_ctx.Options.IsIltLikeWorld) + { + foreach (var f in _features) + { + try { f.Tick(now); } + catch (Exception ex) { RynthLog.Exception(CategoryOf(f), ex, $"{f.GetType().Name}.Tick"); } + } + } + + // Expire an unanswered chat confirmation so a stale "/ra hub confirm" can't fire it later. + if (_pendingAction != null && now - _pendingAt > ConfirmWindowMs) + { + RynthLog.Event(LogEvents.IltConfirmation, $"confirmation expired: {_pendingLabel}"); + _ctx.Chat($"[Mini Remote] Confirmation for '{_pendingLabel}' expired."); + ClearPending(); + } + + if (now - _lastSaveAt >= SaveIntervalMs) + { + _lastSaveAt = now; + _ctx.Store.SaveStateIfDirty(_ctx.State); + } + } + + /// A creature's health update from the server (RynthPluginOnUpdateHealth): auto-capture's fallback health read. + public void OnUpdateHealth(uint objectId, float healthRatio) + { + if (!_ctx.Options.IsIltLikeWorld) return; + PetAutomation.NoteHealth(objectId, healthRatio); + } + + /// + /// The sub-tabs RynthILT adds to one of RynthAi's tabs (RynthILT.Hub GetSubTabs): the Pets tab's + /// Breeding on an ILT world whose server hasn't reported pet breeding off. (Id, label) pairs; the + /// id is a RenderSection id. Any thread. + /// + public (string Id, string Label)[] SubTabs(string parent) + { + if (!string.Equals(parent, RynthCore.Plugin.Shared.RynthServerHub.TabParentPets, StringComparison.OrdinalIgnoreCase) + || !_ctx.Options.IsIltLikeWorld || _ctx.Options.IsOff(RynthCore.Plugin.Shared.RynthIltHub.FeaturePetBreeding)) + return Array.Empty<(string, string)>(); + return new[] { (RynthCore.Plugin.Shared.RynthIltHub.SectionPetBreeding, "Breeding") }; + } + + /// + /// RynthILT.Hub GetSetting: a setting another plugin mirrors (RynthServerHub.Setting*), -1 when not offered + /// (unknown key, or off an ILT world: the engine row then hides). Any thread. + /// + public int GetSetting(string key) => key switch + { + RynthCore.Plugin.Shared.RynthServerHub.SettingVaultedDungeons when _ctx.Options.IsIltLikeWorld + => _ctx.State.VaultedDungeonsEnabled ? 1 : 0, + _ => -1, + }; + + /// + /// RynthILT.Hub GetText: a short text RynthAi shows (RynthServerHub.Text*); "" for an unknown id, and + /// the session tail off ILT. Any thread. + /// + public string GetText(string id) => id switch + { + RynthCore.Plugin.Shared.RynthServerHub.TextServerId => IltSectionsManifest.Server, + RynthCore.Plugin.Shared.RynthServerHub.TextSessionReport when _ctx.Options.IsIltLikeWorld => _ui.SessionReportTail(), + _ => string.Empty, + }; + + /// RynthILT.Hub SetSetting: false for an unknown key. Saved with the state (next periodic save). Any thread. + public bool SetSetting(string key, int value) + { + if (key != RynthCore.Plugin.Shared.RynthServerHub.SettingVaultedDungeons) return false; + bool on = value != 0; + if (_ctx.State.VaultedDungeonsEnabled != on) + RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons master switch {(on ? "on" : "off")} (Settings window)"); + _ctx.State.VaultedDungeonsEnabled = on; + return true; + } + + /// The server's killer notification (pump thread): restarts the Vaulted Dungeons no-kill timer, on ILT only. + public void OnKillNotification() + { + if (!_ctx.Options.IsIltLikeWorld) return; + try { VaultedDungeons.OnKillNotification(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "VaultedDungeons.OnKillNotification"); } + } + + /// Pump-thread chat line. Returns true when the line should be hidden. + public bool OnChat(string text, int chatType = -1) + { + if (string.IsNullOrEmpty(text)) return false; + string line = text.TrimEnd('\r', '\n'); + _ctx.Options.OnChatLine(line); + bool eat = _ctx.Capture.OnChatLine(line); + if (!_ctx.Options.IsIltLikeWorld) return eat; + // The ring line needs its chat type (a player repeating it is ignored). + try { RingEvade.OnChatLine(line, chatType); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "IltRingEvade.OnChatLine"); } + foreach (var f in _features) + { + try { eat |= f.OnChat(line); } + catch (Exception ex) { RynthLog.Exception(CategoryOf(f), ex, $"{f.GetType().Name}.OnChat"); } + } + return eat; + } + + /// Maps a feature module to its diagnostics category so its trace/exception lines land in its own file. + private static LogCat CategoryOf(IIltFeature f) => f switch + { + IltBanking => LogCat.IltBanking, + IltPetLogs or IltPetBreeding or IltPetAutomation => LogCat.IltPets, + IltSessionRates => LogCat.IltRates, + IltQuestBonus or IltDynamicStamps => LogCat.IltQuests, + IltProgression => LogCat.IltProgression, + IltGear or IltCharms => LogCat.IltGear, + IltGames => LogCat.IltGames, + IltVaultedDungeons => LogCat.IltHub, + _ => LogCat.IltHub, + }; + + /// Logout / teardown: stop automation and flush to disk. + public void OnLogout() + { + RynthLog.Event(LogEvents.IltLogout, $"logout: stopping features for '{_ctx.CharName}'"); + ClearPending(); + foreach (var f in _features) + { + try { f.OnLogout(); } + catch (Exception ex) { RynthLog.Exception(CategoryOf(f), ex, $"{f.GetType().Name}.OnLogout"); } + } + _ctx.Capture.Clear(); + _ctx.Store.SaveStateIfDirty(_ctx.State); + } + + /// + /// JSON for the engine Skills panel's Progression tab (RynthILTGetProgressionJson). + /// "available" is false off ILT-like worlds; the panel then hides the ILT sections. Pump thread. + /// + public string BuildProgressionJson() + { + var sb = new System.Text.StringBuilder(2048); + sb.Append("{\"available\":").Append(Available ? "true" : "false"); + sb.Append(",\"world\":\"").Append(IltStyle.JsonEscape(_ctx.Options.WorldName ?? string.Empty)).Append("\","); + Progression.AppendSnapshotJson(sb); + sb.Append('}'); + return sb.ToString(); + } + + /// JSON for RynthILTGetCharmsJson / RynthPluginGetCharmsJson (an older engine's Settings "Charms Tracking" tab). Pump thread. + public string BuildCharmsJson() => Charms.BuildJson(); + + /// Render thread: Games HUD and confirmation popups. + public void Render() => _ui.Render(); + + // ── Probe taps: reuse login-probe replies so tabs fill without extra commands ── + + private void OnProbeReply(string key, IltChatResult r) + { + if (r.Lines.Count == 0) return; + switch (key) + { + case IltFeature.Aug: + Progression.ApplyAugLines(r.Lines); + // Probe's OnComplete is not RequestAugs' — drain a queued Refresh current / empty retry. + Progression.AfterExternalAugCapture(); + break; + case IltFeature.Pets: PetLogs.ApplyRoster(false, r.Lines); break; + case IltFeature.Shinies: PetLogs.ApplyRoster(true, r.Lines); break; + case IltFeature.Qb: QuestBonus.ApplyQbProbe(r.Lines); break; + // Bank lines are parsed passively by IltBanking.OnChat as they arrive. + } + } + + // ── Commands ──────────────────────────────────────────────────────────── + + /// + /// The ILT verbs: "/ra hub [open <ILT tab> [show|hide|toggle]|tab <ILT tab>|refresh|bank|status| + /// force on|off|servers [list]|profile save|load|list ...|suit list|test|load ...|clap|attr ...| + /// confirm|cancel]" (RynthAi keeps show/hide/toggle and its own Quests / Pets tabs, and forwards + /// the rest here; "/ilt hub ..." comes straight here), "/ra bounty [show|hide|toggle]" (aliases + /// bounties / bountys: RynthCore's ILT Bounties panel), "/ra guardian ..." (window: RynthCore's + /// ILT Guardian panel; the rest IltGuardian.HandleCommand) and "rates reset" (the Mini Remote's + /// Reset XP). Pump thread. Returns false if not handled. + /// + public bool HandleCommand(string verb, string[] args) + { + RynthLog.Event(LogEvents.IltCommand, $"command: /ra {verb} {string.Join(" ", args)}".TrimEnd()); + if (verb.Equals("rates", StringComparison.OrdinalIgnoreCase)) + { + // "rates reset": the coin / pyreal session starts over with RynthAi's session stats. + Rates.Reset(); + return true; + } + if (IsBountyVerb(verb)) + { + // Bounties are RynthILT's Bounties window (RynthCore's ILT button); open that panel. + OpenEnginePanel("bounties", "Bounties", args.Length > 0 ? args[0] : "toggle"); + return true; + } + if (verb.Equals("guardian", StringComparison.OrdinalIgnoreCase)) + { + // "/ra guardian window [show|hide|toggle]" opens RynthCore's ILT Guardian panel; + // everything else is the Guardian's. + if (args.Length > 0 && args[0].Equals("window", StringComparison.OrdinalIgnoreCase)) + OpenEnginePanel("guardian", "Guardian", args.Length > 1 ? args[1] : "toggle"); + else + Guardian.HandleCommand(args); + return true; + } + if (!verb.Equals("hub", StringComparison.OrdinalIgnoreCase)) return false; + + string cmd = args.Length > 0 ? args[0].ToLowerInvariant() : "help"; + string rest = args.Length > 1 ? string.Join(" ", args.Skip(1)) : string.Empty; + switch (cmd) + { + case "show": + case "hide": + case "toggle": + // The Mini Remote is RynthAi's ("/ilt hub show" lands here). + _ctx.Chat("[Mini Remote] " + _ctx.Ai.MiniRemoteTab(IltSections.RemoteTab, cmd)); + break; + case "open": + if (args.Length > 1 && IsBountyVerb(args[1])) + { + OpenEnginePanel("bounties", "Bounties", args.Length > 2 ? args[2] : "toggle"); + break; + } + if (args.Length < 2 || !IltSections.TryParse(args[1], out IltSection section)) + { + // Quests and Pets are RynthAi's tabs: not ours to open. + if (args.Length >= 2 && IltSections.IsUniversalTabName(args[1])) return false; + _ctx.Chat("[Mini Remote] Usage: /ra hub open pets|banking|gear|charms|games|vaulted|guardian|bounties [show|hide|toggle] (character: /ro character, quests: /ro)"); + break; + } + OpenSection(section, args.Length > 2 ? args[2] : "toggle"); + break; + case "tab": + // The engine's dashboard: it opens its Mini Remote window itself, so only switch tabs. + if (args.Length > 1 && IltSections.TryParse(args[1], out IltSection tab) && IltSections.MovedCommand(tab) is string moved) + OpenMoved(tab, moved); + else if (args.Length > 1 && IltSections.TryParse(args[1], out tab) && IltSections.IsTab(tab)) + _ctx.Ai.MiniRemoteTab(IltSections.TabId(tab), "select"); + else + return false; // the Remote tab or a RynthAi tab: RynthAi's + break; + case "refresh": _ctx.Options.Refresh(manual: true); break; + case "bank": Banking.RequestRefresh(quiet: false); break; + // "/ilt qb": reads the /qb list again (the Quests tab's quest bonus section). + case "qb": _ctx.Chat("[RynthILT] " + QuestBonus.RefreshQb()); break; + case "status": PrintStatus(); break; + case "features": PrintFeatures(); break; + case "force": + _ctx.State.ForceLeaftideFeatures = !rest.Equals("off", StringComparison.OrdinalIgnoreCase); + _ctx.Chat(IltServerOptions.EngineDecides + ? $"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")} for this character (RynthCore counts it unless /rc server ilt off). Use /ra hub refresh to re-check the server." + : $"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")}. Use /ra hub refresh to re-check the server."); + break; + case "servers": HandleServers(rest); break; + case "profile": HandleProfile(args.Skip(1).ToArray()); break; + case "suit": HandleSuit(args.Skip(1).ToArray()); break; + case "clap": Gear.ChunkClap.ClapNow(manual: true); break; + case "attr": HandleAttr(args.Skip(1).ToArray()); break; + case "confirm": RunPending(); break; + case "cancel": + _ctx.Chat(_pendingAction != null ? $"[Mini Remote] Cancelled '{_pendingLabel}'." : "[Mini Remote] Nothing to cancel."); + ClearPending(); + break; + default: + _ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|features|force on|off|servers [list]|clap|confirm|cancel"); + _ctx.Chat("[Mini Remote] /ra hub open pets|banking|gear|charms|games|vaulted [show|hide|toggle] (Mini Remote tabs; character: /ro character, quests: /ro)"); + _ctx.Chat("[Mini Remote] /ilt vaulted [on|off|toggle|status] (Vaulted Dungeons; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons)"); + _ctx.Chat("[Mini Remote] /ra hub profile list|save [shared]|load /ra hub suit list|test|load [name]"); + _ctx.Chat("[Mini Remote] /ra hub attr run|stop|costs|status|auto on|off|every |raise (Skills panel > Progression)"); + _ctx.Chat("[Mini Remote] /ra quests refresh (quiet /myquests) /ra pets [show|hide] /ilt qb (the quest bonus list)"); + _ctx.Chat("[Mini Remote] /ra guardian [window|translate |handin|stop|chat on|off|auto on|off|buy on|off|refresh|status] (window: ILT button > Guardian)"); + _ctx.Chat("[Mini Remote] /ra bounty [show|hide|toggle] (RynthCore's ILT button > Bounties, /rc bounties)"); + _ctx.Chat("[Mini Remote] The ILT verbs also work as /ilt hub ..., /ilt guardian ... (RynthILT)."); + break; + } + return true; + } + + /// "/ra hub features": every Leaftide feature RynthILT supports, with the server's state for each. + private void PrintFeatures() + { + IltServerOptions o = _ctx.Options; + string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world"; + _ctx.Chat($"[Mini Remote] Leaftide features on {world} ({(o.IsIltLikeWorld ? "ILT world" : "not an ILT world")}, " + + $"fellowships up to {IltFeatureCatalog.FellowshipMax(o.IsIltLikeWorld)}):"); + foreach (string line in IltFeatureCatalog.BuildChatLines(o.IsIltLikeWorld, o.Get)) + _ctx.Chat("[Mini Remote] " + line); + } + + /// "/ra hub servers [list | <names, comma separated> | default]": which world names count as Infinite Leaftide. + private void HandleServers(string rest) + { + string arg = rest.Trim(); + if (arg.Length > 0 && !arg.Equals("list", StringComparison.OrdinalIgnoreCase)) + { + var list = arg.Equals("default", StringComparison.OrdinalIgnoreCase) + ? new List(ServerFeatureGate.DefaultServerNames) + : ServerFeatureGate.ParseList(arg); + if (list.Count == 0) { _ctx.Chat("[Mini Remote] Usage: /ra hub servers | default | list"); return; } + _ctx.Settings.ServerNames = list; + _ctx.SaveSettings(); + } + _ctx.Chat("[Mini Remote] ILT world names: " + ServerFeatureGate.FormatList(ServerFeatureGate.Patterns(_ctx.Settings))); + _ctx.Chat("[Mini Remote] " + ServerFeatureGate.Describe(_ctx.Options.WorldName, _ctx.Settings, _ctx.State.ForceLeaftideFeatures)); + } + + /// "/ra hub attr ...": the attribute raiser from chat (same verbs as the Progression tab). + private void HandleAttr(string[] a) + { + var raiser = Progression.Attributes; + string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "status"; + switch (sub) + { + case "run": raiser.HandleRemote("attrrun", new[] { "attrrun" }); break; + case "stop": raiser.HandleRemote("attrstop", new[] { "attrstop" }); break; + case "costs": raiser.HandleRemote("attrcosts", new[] { "attrcosts" }); break; + case "auto": raiser.HandleRemote("attrauto", new[] { "attrauto", a.Length > 1 ? a[1] : "off" }); break; + case "every": raiser.HandleRemote("attrevery", new[] { "attrevery", a.Length > 1 ? a[1] : "5" }); break; + case "raise" when a.Length > 2: raiser.HandleRemote("attrraise", new[] { "attrraise", a[1], a[2] }); break; + default: + var c = _ctx.State.Character; + string blocked = raiser.Blocker() ?? "ready"; + _ctx.Chat($"[Mini Remote] Attribute raiser: {blocked}; auto={(c.AttrAutoRaise ? $"on every {c.AttrAutoRaiseMinutes}m" : "off")} " + + $"mode={(IltAttributeRaiser.Mode)c.AttrRaiseMode} keep={IltParse.Compact(c.AttrKeepXp)} " + + $"stats={(c.AttrRaiseStats.Count > 0 ? string.Join(",", c.AttrOrder.Where(c.AttrRaiseStats.Contains)) : "none ticked")}"); + return; + } + } + + /// "/ra bounty", "/ra bounties" and the "/ra bountys" spelling all reach the Bounties panel. + public static bool IsBountyVerb(string verb) + => verb.Equals("bounty", StringComparison.OrdinalIgnoreCase) + || verb.Equals("bounties", StringComparison.OrdinalIgnoreCase) + || verb.Equals("bountys", StringComparison.OrdinalIgnoreCase); + + /// + /// Applies show / hide / toggle to a section: a Mini Remote tab, or for the Guardian + /// RynthCore's ILT panel. Says what happened. + /// + private void OpenSection(IltSection section, string mode) + { + if (IltSections.MovedCommand(section) is string moved) + { + // Character left the Mini Remote: open its new home instead. + if (!mode.Equals("hide", StringComparison.OrdinalIgnoreCase)) OpenMoved(section, moved); + return; + } + if (!IltSections.IsTab(section)) + { + OpenEnginePanel(IltSections.TabId(section), IltSections.Label(section), mode); + return; + } + if (section == IltSection.VaultedDungeons && !SectionAvailable(section)) + { + _ctx.Chat(_ctx.Options.IsIltLikeWorld + ? "[Mini Remote] The Vaulted Dungeons tab is off: turn on \"Vaulted Dungeons\" in the ILT settings (/ilt settings; also Settings > Navigation) (the master switch, off by default)." + : "[Mini Remote] Vaulted Dungeons is not available on this server (Infinite Leaftide / ACECustom only)."); + return; + } + string reply = _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), mode); + if (!SectionAvailable(section) && !mode.Equals("hide", StringComparison.OrdinalIgnoreCase)) + reply = $"The {IltSections.Label(section)} tab shows once the server reports that feature on."; + _ctx.Chat("[Mini Remote] " + reply); + } + + /// + /// Opens the new home of a section that moved out of the Mini Remote (RynthOracle's Character + /// tab) by running its chat command, or says where it is when the command can't run (an older + /// RynthCore, or RynthOracle not loaded). Pump thread. + /// + public void OpenMoved(IltSection section, string command) + { + if (_ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser(command)) + return; + _ctx.Chat($"[Mini Remote] {IltSections.Label(section)} moved to RynthOracle's Character tab ({command}); " + + "the ILT session rates are in the Mini Remote's Session Stats."); + } + + /// + /// Opens / closes one of RynthCore's ILT panels ("/rc bounties|guardian [show|hide|toggle]") + /// through the engine's chat dispatcher. Pump thread. + /// + public void OpenEnginePanel(string rcVerb, string label, string mode) + { + string m = (mode ?? string.Empty).ToLowerInvariant() switch + { + "show" or "on" or "open" => "show", + "hide" or "off" or "close" => "hide", + _ => "toggle", + }; + if (_ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser($"/rc {rcVerb} {m}")) + return; + _ctx.Chat($"[Mini Remote] {label} is a RynthCore ILT panel: the bar's ILT button, or /rc {rcVerb}."); + } + + /// "show"/"on" → true, "hide"/"off" → false, anything else flips . + private static bool ResolveToggle(string mode, bool current) => mode switch + { + "show" or "on" or "true" or "1" => true, + "hide" or "off" or "false" or "0" => false, + _ => !current, + }; + + private void PrintStatus() + { + var o = _ctx.Options; + _ctx.Chat($"[Mini Remote] World '{o.WorldName}' ILT={o.IsIltLikeWorld} force={_ctx.State.ForceLeaftideFeatures} source={(o.Source.Length > 0 ? o.Source : "none")} " + + $"refreshed={(o.LastRefreshUtc == DateTime.MinValue ? "never" : o.LastRefreshUtc.ToLocalTime().ToString("t"))}"); + var bits = o.SnapshotBits(); + string on = string.Join(", ", bits.Where(b => b.Value == 1).Select(b => b.Key)); + string off = string.Join(", ", bits.Where(b => b.Value == 0).Select(b => b.Key)); + _ctx.Chat("[Mini Remote] on: " + (on.Length > 0 ? on : "-")); + _ctx.Chat("[Mini Remote] off: " + (off.Length > 0 ? off : "-")); + } + + private void HandleProfile(string[] a) + { + string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "list"; + if (sub == "list") + { + var names = _ctx.Store.ListProfiles(); + _ctx.Chat("[Mini Remote] Profiles: " + (names.Count > 0 ? string.Join(", ", names) : "(none)")); + return; + } + if (a.Length < 2) { _ctx.Chat("[Mini Remote] Usage: /ra hub profile save [shared] | load "); return; } + if (sub == "save") + { + bool shared = a.Length > 2 && a[2].Equals("shared", StringComparison.OrdinalIgnoreCase); + _ctx.Chat(_ctx.Store.SaveProfile(_ctx.State, a[1], shared, out string err) + ? $"[Mini Remote] Saved {(shared ? "shared " : "")}profile '{a[1]}'." : "[Mini Remote] Save failed: " + err); + } + else if (sub == "load") + { + // Loading replaces the Hub's current settings, so it needs an explicit confirm. + string profile = a[1]; + RequestConfirm($"load Hub profile '{profile}' (replaces current Hub settings)", () => + _ctx.Chat(_ctx.Store.LoadProfile(_ctx.State, profile, out string err) + ? $"[Mini Remote] Loaded profile '{profile}'." : "[Mini Remote] Load failed: " + err)); + } + } + + // ── Chat confirmations for destructive commands ───────────────────────── + + /// How long a "/ra hub confirm" stays valid after the prompt. + private const long ConfirmWindowMs = 20000; + + private string? _pendingLabel; + private Action? _pendingAction; + private long _pendingAt; + + /// Arms a single pending action; a newer request replaces an older one. + private void RequestConfirm(string label, Action action) + { + _pendingLabel = label; + _pendingAction = action; + _pendingAt = IltHubContext.NowMs; + RynthLog.Event(LogEvents.IltConfirmation, $"confirmation requested: {label}"); + _ctx.Chat($"[Mini Remote] About to {label}. Type /ra hub confirm within {ConfirmWindowMs / 1000} s, or /ra hub cancel."); + } + + /// Runs the pending action if one is armed and still inside its window. + private void RunPending() + { + var action = _pendingAction; + string? label = _pendingLabel; + bool fresh = action != null && IltHubContext.NowMs - _pendingAt <= ConfirmWindowMs; + ClearPending(); + if (!fresh || action == null) { _ctx.Chat("[Mini Remote] Nothing to confirm."); return; } + + RynthLog.Event(LogEvents.IltConfirmation, $"confirmed: {label}"); + try { action(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, $"confirmed action '{label}'"); } + } + + private void ClearPending() + { + _pendingAction = null; + _pendingLabel = null; + _pendingAt = 0; + } + + private void HandleSuit(string[] a) + { + string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "list"; + string? name = a.Length > 1 ? string.Join(" ", a.Skip(1)) : null; + switch (sub) + { + case "list": + var list = Gear.Suits.ListProfiles(); + _ctx.Chat("[Mini Remote] Suits: " + (list.Count > 0 ? string.Join(", ", list.Select(p => p.Name)) : "(none)")); + break; + case "test": + foreach (string l in Gear.Suits.Test(name)) _ctx.Chat("[Mini Remote] " + l); + break; + case "load": + // Equipping a suit swaps gear mid-session, so it needs an explicit confirm. + RequestConfirm($"equip suit '{name ?? "(auto)"}'", () => _ctx.Chat("[Mini Remote] " + Gear.Suits.Load(name))); + break; + default: + _ctx.Chat("[Mini Remote] Usage: /ra hub suit list|test [name]|load [name]"); + break; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs new file mode 100644 index 0000000..c2d34dc --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs @@ -0,0 +1,364 @@ +// IltHubState.cs — Persisted per-character state for the ILT Hub (Infinite Leaftide tools). +// Originally SilentKelpie's ILT Hub state in RynthAi; moved to RynthILT 2026-10-13. +// +// Lives in %APPDATA%\RynthCore\RynthILT\\\hub.json (IltHubStore). The first +// login with RynthILT copies RynthAi's \ilt-hub.json there (IltMigration), so the +// shape stays compatible with that file: the parts that stayed with RynthAi's universal Mini +// Remote tabs (the Pets tab's settings, the quest tracker's filter and favorites, the VTank +// import path) are simply not read here any more. Serialized with the NativeAOT source-generated +// IltHubJsonContext (IncludeFields = true), so plain public fields are used throughout. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// Root of everything the Hub remembers between sessions. +public sealed class IltHubState +{ + /// Bumped when the shape changes in a way that needs a migration. + public int SchemaVersion = 1; + + // ── Window / shell ────────────────────────────────────────────────────── + /// + /// Hub UI on screen: the Mini Remote or any ILT section window (IltHubController.Tick keeps it + /// current). Bank auto-refresh and the gear / split-arrow scans run only while it is true. + /// + public bool WindowVisible; + /// Unused since the tabbed Hub window was retired; kept so old files still load. + public int SelectedTab; + public bool GamesHudVisible = true; + + /// + /// "This world is an ACECustom/ILT shard even though its name isn't InfiniteLeaftide." + /// World-identity override ONLY: it makes the Hub ask the server for its options, it + /// never turns a feature on by itself. + /// + public bool ForceLeaftideFeatures; + + /// True once the one-time UtilityBelt sidecar import has run for this character. + public bool UbSidecarsImported; + + /// + /// True once the RynthAi settings that moved to RynthILT on 2026-10-20 (the Pets tab's ACECustom + /// options, ...) were copied from this character's RynthAi files (IltMigration.ImportRynthAiSettings). + /// + public bool RynthAiSettingsImported; + + /// Last-seen server feature bits. Cache only — overwritten by every login refresh. + public IltServerOptionsSnapshot ServerOptions = new(); + + public IltBankState Bank = new(); + public IltPetState Pet = new(); + public IltCharacterState Character = new(); + public IltGearState Gear = new(); + public IltGamesState Games = new(); + public IltGuardianState Guardian = new(); + /// Infinite Leaftide combat helpers (moved from RynthAi's profile 2026-10-20). + public IltCombatState Combat = new(); + + /// + /// The Vaulted Dungeons keeper's master switch (off by default): while off it does nothing (no + /// recalls, no /rc quit, no tab). RynthAi's "Vaulted Dungeons" setting until 2026-10-20 (copied once); + /// set in the ILT settings ("/ilt settings") or the engine's Settings > Navigation row (RynthAi + /// mirrors it through RynthILT.Hub GetSetting / SetSetting). + /// + public bool VaultedDungeonsEnabled; + + /// ACECustom T11 gear (IltT11): the item-aug override (moved from RynthAi's profile 2026-10-20). + public IltT11State T11 = new(); + + /// The ILT sections of RynthAi's Remote tab (moved from RynthAi's huds.json 2026-10-20). + public IltRemoteState Remote = new(); +} + +// ── RynthAi's Remote tab ──────────────────────────────────────────────────── + +public sealed class IltRemoteState +{ + /// The Remote tab's Bank section (ILT bank balances). Was RynthAi's MiniShowBank. + public bool ShowBank = true; + /// The Remote tab's Guardian line (the last Temple guardian answer). Was RynthAi's MiniShowGuardian. + public bool ShowGuardian = true; +} + +// ── T11 ───────────────────────────────────────────────────────────────────── + +public sealed class IltT11State +{ + /// + /// The item augmentation count T11 wield gates use ("T11: Can Wield" in RynthAi's loot rules) instead + /// of the "/aug" reply's; -1 = automatic (read from /aug). "/ilt t11 augs <n|auto>". Was RynthAi's + /// T11ItemAugsOverride. + /// + public int ItemAugsOverride = -1; +} + +// ── Combat ────────────────────────────────────────────────────────────────── + +public sealed class IltCombatState +{ + /// + /// When the Empyrean Handler channels its lethal ring and the character is inside it, have RynthAi + /// back-jump away and re-engage (IltRingEvade; RynthAi acts only while its macro runs with combat + /// on). On by default because it is gated that way. Was RynthAi's HandlerRingEvade. + /// + public bool HandlerRingEvade = true; +} + +/// Cached result of the server-options check (see IltServerOptions). +public sealed class IltServerOptionsSnapshot +{ + public string WorldName = string.Empty; + /// "probe" (the login probe) or "" (never refreshed). + public string Source = string.Empty; + public DateTime LastRefreshUtc = DateTime.MinValue; + /// Feature key → -1 unknown, 0 off, 1 on. + public Dictionary Bits = new(StringComparer.OrdinalIgnoreCase); +} + +// ── Banking ───────────────────────────────────────────────────────────────── + +public sealed class IltBankState +{ + public long Pyreals; + public long Luminance; + public long LegendaryKeys; + public long MythicalKeys; + public long EnlightenedCoins; + public long WeaklyEnlightenedCoins; + /// Bound to the character: deposit and withdraw only, never transferred. + public long PrestigeCoins; + public DateTime LastUpdated = DateTime.MinValue; + + /// Last transfer recipient typed into the transfer form. + public string TransferTarget = string.Empty; + public int TransferCurrencyIndex; + /// Transfer form's trade-note denomination (IltBankCommands.NoteDenominations; 9 = MMD). + public int TransferNoteIndex = 9; + + /// Deposit / withdraw form choices (IltBankCommands.Deposits / Withdrawals / NoteDenominations). + public int DepositIndex; + public int WithdrawIndex; + public int WithdrawNoteIndex = 9; + + /// Re-issue /bank every N seconds while the Hub is open (0 = manual only). + public int AutoRefreshSeconds = 120; +} + +/// One "Transferred …" / "Received …" bank line seen in chat. +public sealed class IltBankTransaction +{ + public DateTime Timestamp; + /// "Sent" or "Received". + public string Type = string.Empty; + public string Currency = string.Empty; + public long Amount; + public string OtherPlayer = string.Empty; + public string Description = string.Empty; +} + +// ── Pet ───────────────────────────────────────────────────────────────────── + +public sealed class IltPetState +{ + /// Last captured /pets and /shinies rosters (display only; the Pets tab's logs). + public List PetLog = new(); + public List ShinyLog = new(); + /// The breeding tracker: rules this server showed, growth stage names, recent events (IltPetBreeding). + public IltBreedingState Breeding = new(); + + // ACECustom's parts of the Pets tab (IltPetAutomation, moved from RynthAi 2026-10-20; copied once + // from RynthAi's miniremote.json by IltMigration.ImportRynthAiSettings). New names on purpose: an + // old ilt-hub.json copy still carries RynthAi's UsePyrealRefillPath / AutoCaptureEnabled / + // CaptureLensIndex from before 2026-10-13, and those stale values must not be read back. + /// + /// Summon from an EMPTY essence while the Summon Essence Refill charm is on (the server refills it + /// from banked pyreals). Still needs the server to confirm the feature (RynthAi.Hub's PetManager + /// asks AllowSummonOnEmpty). + /// + public bool RefillFromEmpty; + /// Use the chosen siphon lens on the nearest creature once it is weak enough (off by default). + public bool AutoCapture; + /// Index into PetCaptureRules.Lenses (Flawed to Asheron's). + public int CaptureLens; + // The Pets tab's own settings (roster, healing / cosmetic pets) are RynthAi's (its miniremote.json). +} + +// ── Character ─────────────────────────────────────────────────────────────── + +public sealed class IltCharacterState +{ + /// Item → coin conversion table used by the session-rates strip. + public List ItemConversions = new() + { + new IltItemConversion { ItemName = "Strawberry Jam Jar", ItemsPerConversion = 100, CoinsPerConversion = 10 }, + new IltItemConversion { ItemName = "Ancient Pyreal", ItemsPerConversion = 100, CoinsPerConversion = 37 }, + }; + + /// Augmentation planner targets, keyed by aug type (lowercase). + public Dictionary AugTargets = new(StringComparer.OrdinalIgnoreCase); + /// Luminance price of one Enlightened Coin (planner math only; 0 = don't price coins). + public long LumPerEnlightenedCoin; + + /// Enlightenment planner target level (0 = current + 5). + public int EnlTargetLevel; + public int EnlightenedCoinsPerToken = 20; + /// + /// Auto-enlighten preference. Even when true it stays DISARMED each session until the + /// player confirms in the Hub, and the server's own Yes/No dialog is never auto-clicked. + /// + public bool AutoEnlightenEnabled; + public int AutoEnlightenCheckSeconds = 30; + /// Spend unassigned XP with /attr before sending /enl (enlightening wipes unspent XP). + public bool AutoEnlightenSpendXpFirst; + + // ── Attribute raiser (IltAttributeRaiser; Skills panel > Progression) ── + /// Spend unassigned XP on the ticked attributes/vitals every AttrAutoRaiseMinutes. + public bool AttrAutoRaise; + public int AttrAutoRaiseMinutes = 5; + /// IltAttributeRaiser.Mode: 0 priority (top of the order first), 1 round robin, 2 cheapest first. + public int AttrRaiseMode; + /// Unassigned XP the raiser never spends. + public long AttrKeepXp; + /// /attr abbreviations in raise-priority order (all nine; repaired on load). + public List AttrOrder = new(IltAttributeRaiser.DefaultOrder); + /// /attr abbreviations the raiser may spend on ("Raise now" and auto-raise). + public List AttrRaiseStats = new(); + + /// Quest bonus (/qb) list filter. (The /myquests tracker's filter and favorites are RynthAi's.) + public string QbFilter = string.Empty; + // The ILT sections are Mini Remote tabs now (HudState.MiniRemoteTab); the old per-section + // "window open" flags in older files are ignored on load. + + /// + /// Registry charms this character has carried, keyed by charm name. Lets the Charms Tracking + /// tab report "acquired" for charms that are now in storage (the client only sees carried items). + /// + public Dictionary CharmsSeen = new(StringComparer.OrdinalIgnoreCase); +} + +/// Last time a charm was seen in the character's possession, with its best tier. +public sealed class IltCharmSeen +{ + public int Tier; + public int MaxTier; + public DateTime LastSeenUtc; +} + +public sealed class IltItemConversion +{ + public string ItemName = string.Empty; + public int ItemsPerConversion = 100; + public int CoinsPerConversion; +} + +// ── Gear ──────────────────────────────────────────────────────────────────── + +public sealed class IltGearState +{ + // Dispel (Rune of Dispel on harmful debuffs) + public bool AutoDispel; + public int DispelCooldownSeconds = 10; + /// Spell-name substrings that are ALWAYS dispelled. + public List DispelInclusions = new(); + /// Spell-name substrings that are NEVER dispelled. + public List DispelExclusions = new(); + + // Surging Strength (Empowered Volcanic Ember keeper) + public bool SurgingStrength; + public int SurgingCooldownSeconds = 15; + + // Aetheria / corrupted-weapon chunking + public bool AutoChunkAetheria; + public bool AutoChunkCorrupted; + public bool ChunkInCombat; + public int ChunkIntervalMs = 2000; + /// + /// Only chunk aetheria whose max level is below this (Coalesced Aetheria too). Infinite Leaftide + /// aetheria goes up to level , so the cap runs to one past it. + /// + public int ChunkAetheriaUnderLevel = 4; + /// Never chunk aetheria carrying a Crit rating (C, GearCrit 372; ILT tier-10 sigils of level 6+). + public bool KeepAetheriaWithCrit = true; + /// Never chunk aetheria carrying a Crit Damage rating (CD, GearCritDamage 374). + public bool KeepAetheriaWithCritDamage = true; + /// Never chunk aetheria carrying a Crit Damage Resist rating (CDR, GearCritDamageResist 375). + public bool KeepAetheriaWithCritDamageResist = true; + /// + /// Rating level for the C / CD / CDR keep switches: a rating at or above this keeps the piece, + /// a lower one does not protect it (it chunks if the other rules allow). 1 = any rating keeps. + /// + public int KeepAetheriaRatingAtLeast = 1; + + // Corrupted-weapon keep rules (ub-IT IdleActs > Corr Chunk). All off by default, as in ub-IT: + // the hard rules (unmodified, workmanship, cleaving, never-chunk) always apply on top. + /// Never chunk a corrupted weapon with Crushing Blow (CriticalFrequency float 147 > 0). + public bool KeepCorruptedCrushingBlow; + /// Never chunk a corrupted weapon with Biting Strike (CriticalMultiplier float 136 > 0). + public bool KeepCorruptedBitingStrike; + /// Never chunk a corrupted weapon with Armor Cleaving (IgnoreArmor float 155 > 0). + public bool KeepCorruptedArmorCleaving; + /// Never chunk a corrupted weapon with any slayer (SlayerCreatureType int 166 > 0). + public bool KeepCorruptedAnySlayer; + /// Never chunk a multi-strike corrupted weapon (AttackType int 47 = 160 / 166 / 486). + public bool KeepCorruptedMultiStrike; + /// Never chunk a corrupted weapon with an elemental damage bonus (int 204 > 0). + public bool KeepCorruptedElementalBonus; + /// Never chunk a corrupted weapon with any spell on it. + public bool KeepCorruptedAnySpell; + /// Never chunk a corrupted weapon whose max damage (int 44) is at least this. 0 = off. + public int KeepCorruptedMaxDamageAtLeast; + /// Spell ids (comma / space separated): never chunk a corrupted weapon carrying any of them. + public string KeepCorruptedSpellIds = ""; + + // Auto-clap (/clap all) + public bool AutoClap; + public int ClapIntervalMinutes = 30; + + // Guardian Hand charm (WCID unpublished — name match until set) + public uint GuardianHandWcid; + public string GuardianHandName = "Guardian Hand"; + + // Split arrows (White Quartz imbue on missile weapons) + public int SplitArrowTarget = 3; + public bool SplitIgnoreImbued = true; + + // Equipment profiles (.utl suits). (The VTank .usd import path is RynthAi's: the importer stayed there.) + public string LastEquipProfile = string.Empty; + + // Rings inscription chain (IltRingChainRunner; SilentKelpie's, moved from RynthAi's Crafting tab) + /// Recipe id (IltRingChain.Recipes) to how many times to craft it. Pump thread only. + public Dictionary RingRuns = new(StringComparer.OrdinalIgnoreCase); + /// Answer the server's craft dialog Yes for the queued combines (engine API v85). + public bool RingAnswerCraftDialog = true; + /// Craft and inscribe in combat mode too (servers with combat-mode crafting). + public bool RingAllowInCombat; +} + +// ── Games ─────────────────────────────────────────────────────────────────── + +public sealed class IltGamesState +{ + public long BlackjackBet = 1_000_000; + public long FellowshipBlackjackBet = 1_000_000; + public int PowerballQuantity = 1; +} + +// ── Guardian (Temple of Enlightenment) ────────────────────────────────────── + +public sealed class IltGuardianState +{ + /// Translate incoming guardian tells and show the answer (Guardian window + Mini Remote). + public bool AutoDetectFromChat = true; + /// After a chat answer, give the item to the guardian automatically. + public bool AutoHandIn; + /// Temple guardian only: buy one of the item from the nearest vendor when none is carried. + public bool BuyMissingFromVendor = true; + + /// Assumed attribute turn-in cooldown when only /qb wait stamps are known (hours). + public int CooldownHoursAssumed = 20; + /// Turn-ins counted from /qb wait-stamp transitions, keyed by attribute (fallback when /myquests lacks the flag). + public Dictionary TurnInCounts = new(StringComparer.OrdinalIgnoreCase); + /// Estimated end of each attribute's cooldown (UTC), keyed by attribute (same fallback). + public Dictionary CooldownUntilUtc = new(StringComparer.OrdinalIgnoreCase); +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs new file mode 100644 index 0000000..4c15401 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs @@ -0,0 +1,494 @@ +// IltHubStore.cs — Disk persistence for the ILT Hub. +// Originally SilentKelpie's ILT Hub store in RynthAi; moved to RynthILT 2026-10-13. +// +// Files (RynthILT's folder, %APPDATA%\RynthCore\RynthILT; = \): +// \hub.json live Hub state (IltHubState) +// \bank-transactions.json bank transaction log (capped) +// \profiles\.json named per-character Hub profiles +// Profiles\.json named profiles shared by every character +// They were ilt-hub.json, ilt-hub-transactions.json, ilt-hub-profiles\ (RynthAi's per-character +// settings folder) and RynthAi\IltHubProfiles\; IltMigration copies them over on the first login. +// Saves are dirty-checked (the serialized JSON is compared to what was last written) so +// the periodic save in Tick costs nothing when nothing changed. A one-time import pulls +// UtilityBelt's bankdata sidecars so players keep their balances and history. +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltHubStore +{ + /// Maximum bank transactions kept on disk (oldest dropped first). + public const int MaxTransactions = 1000; + + /// RynthILT's folder: shared profiles, aug costs and equipment suits (overridable for the tests). + public static string SharedRoot = RynthILTPlugin.SettingsRoot; + + public const string StateFile = "hub.json"; + public const string TransactionsFile = "bank-transactions.json"; + public const string ProfilesFolder = "profiles"; + + private readonly RynthCoreHost _host; + private readonly string _charFolder; + private string _lastStateJson = string.Empty; + private string _lastTxJson = string.Empty; + + public IltHubStore(RynthCoreHost host, string charFolder) + { + _host = host; + _charFolder = charFolder ?? string.Empty; + } + + /// + /// True while this character's copy from RynthAi is unfinished (IltMigration): the state, the + /// bank log and per-character profiles are not written, so no fresh file shadows a RynthAi + /// original that hasn't been copied yet. Shared profiles still save. + /// + public Func WritesBlocked = static () => false; + + /// + /// The character's RynthAi folder while its copy is unfinished: a file RynthILT doesn't have yet + /// is read from there (read only) when it can be; otherwise the Hub runs from the defaults. + /// + public string? LegacyFolder; + + private bool Blocked() + { + try { return WritesBlocked(); } + catch { return true; } + } + + /// A RynthAi original read without locking it (it may be held open elsewhere). Null when it can't be. + private string? ReadLegacy(string fileName) + { + if (string.IsNullOrEmpty(LegacyFolder)) return null; + string path = Path.Combine(LegacyFolder, fileName); + try + { + if (!File.Exists(path)) return null; + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var sr = new StreamReader(fs); + return sr.ReadToEnd(); + } + catch (Exception ex) + { + RynthLog.Write(LogCat.IltStore, $"RynthAi's {path} can't be read yet ({ex.Message}); running from the defaults until it is copied."); + return null; + } + } + + public string CharFolder => _charFolder; + private string StatePath => Path.Combine(_charFolder, StateFile); + private string TxPath => Path.Combine(_charFolder, TransactionsFile); + private string CharProfileDir => Path.Combine(_charFolder, ProfilesFolder); + internal static string SharedProfileDir => Path.Combine(SharedRoot, "Profiles"); + + // ── State ─────────────────────────────────────────────────────────────── + + /// Loads the live state, returning defaults when the file is missing or unreadable. + public IltHubState LoadState() + { + try + { + if (_charFolder.Length > 0 && File.Exists(StatePath)) + { + string json = File.ReadAllText(StatePath); + var s = JsonSerializer.Deserialize(json, IltHubJsonContext.Default.IltHubState); + if (s != null) + { + Normalize(s); + _lastStateJson = json; + return s; + } + } + else if (ReadLegacy("ilt-hub.json") is string legacyJson) + { + var s = JsonSerializer.Deserialize(legacyJson, IltHubJsonContext.Default.IltHubState); + if (s != null) { Normalize(s); return s; } + } + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {StatePath}"); } + return new IltHubState(); + } + + /// Writes the state only when its JSON differs from the last write. + public void SaveStateIfDirty(IltHubState state) + { + if (_charFolder.Length == 0) return; + try + { + string json = JsonSerializer.Serialize(state, IltHubJsonContext.Default.IltHubState); + if (json == _lastStateJson) return; + if (Blocked()) return; // the copy from RynthAi isn't finished: never shadow its hub.json + // A failure is said in chat once per folder (on ILT) and logged; the next periodic save retries. + if (DataWriteGuard.TrySave("the ILT Hub state", StatePath, () => + { + Directory.CreateDirectory(_charFolder); + WriteAtomic(StatePath, json); + })) + _lastStateJson = json; + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {StatePath}"); } + } + + /// Repairs null collections / out-of-range values after deserialization. + private static void Normalize(IltHubState s) + { + s.ServerOptions ??= new IltServerOptionsSnapshot(); + s.ServerOptions.Bits = new Dictionary(s.ServerOptions.Bits ?? new(), StringComparer.OrdinalIgnoreCase); + s.Bank ??= new IltBankState(); + s.Pet ??= new IltPetState(); + s.Pet.PetLog ??= new(); + s.Pet.ShinyLog ??= new(); + s.Pet.Breeding ??= new(); + s.Pet.Breeding.Rules ??= new(); + s.Pet.Breeding.StageNames ??= new(); + s.Pet.Breeding.Log ??= new(); + s.Pet.Breeding.LastDebug ??= new(); + s.Pet.CaptureLens = Math.Clamp(s.Pet.CaptureLens, 0, PetCaptureRules.Lenses.Length - 1); + s.Pet.Breeding.Rules.RemoveAll(r => r == null || string.IsNullOrEmpty(r.Key)); + s.Pet.Breeding.Log.RemoveAll(e => e == null); + for (int i = 0; i < s.Pet.Breeding.StageNames.Count; i++) s.Pet.Breeding.StageNames[i] ??= string.Empty; + if (s.Pet.Breeding.Log.Count > IltBreedingRules.MaxEvents) + s.Pet.Breeding.Log.RemoveRange(0, s.Pet.Breeding.Log.Count - IltBreedingRules.MaxEvents); + s.Character ??= new IltCharacterState(); + s.Character.ItemConversions ??= new(); + s.Character.AugTargets = new Dictionary(s.Character.AugTargets ?? new(), StringComparer.OrdinalIgnoreCase); + s.Character.AttrOrder = IltAttributeRaiser.RepairOrder(s.Character.AttrOrder); + s.Character.AttrRaiseStats = IltAttributeRaiser.RepairSelection(s.Character.AttrRaiseStats); + s.Character.AttrAutoRaiseMinutes = Math.Clamp(s.Character.AttrAutoRaiseMinutes, 1, 1440); + s.Character.AttrRaiseMode = Math.Clamp(s.Character.AttrRaiseMode, 0, 2); + s.Character.AttrKeepXp = Math.Max(0, s.Character.AttrKeepXp); + s.Character.CharmsSeen = new Dictionary(s.Character.CharmsSeen ?? new(), StringComparer.OrdinalIgnoreCase); + s.Gear ??= new IltGearState(); + s.Gear.DispelInclusions ??= new(); + s.Gear.DispelExclusions ??= new(); + s.Gear.RingRuns = new Dictionary(s.Gear.RingRuns ?? new(), StringComparer.OrdinalIgnoreCase); + s.Games ??= new IltGamesState(); + s.Combat ??= new IltCombatState(); + s.T11 ??= new IltT11State(); + s.Remote ??= new IltRemoteState(); + if (s.T11.ItemAugsOverride < -1) s.T11.ItemAugsOverride = -1; + s.Guardian ??= new IltGuardianState(); + s.Guardian.TurnInCounts = new Dictionary(s.Guardian.TurnInCounts ?? new(), StringComparer.OrdinalIgnoreCase); + s.Guardian.CooldownUntilUtc = new Dictionary(s.Guardian.CooldownUntilUtc ?? new(), StringComparer.OrdinalIgnoreCase); + s.Guardian.CooldownHoursAssumed = Math.Clamp(s.Guardian.CooldownHoursAssumed, 1, 72); + s.SelectedTab = Math.Clamp(s.SelectedTab, 0, 4); + s.Gear.SplitArrowTarget = Math.Clamp(s.Gear.SplitArrowTarget, 0, 10); + } + + // ── Transactions ──────────────────────────────────────────────────────── + + public List LoadTransactions() + { + try + { + if (_charFolder.Length > 0 && File.Exists(TxPath)) + { + string json = File.ReadAllText(TxPath); + var list = JsonSerializer.Deserialize(json, IltHubJsonContext.Default.IltBankTransactionList); + if (list != null) { _lastTxJson = json; return list; } + } + else if (ReadLegacy("ilt-hub-transactions.json") is string legacyJson) + { + var list = JsonSerializer.Deserialize(legacyJson, IltHubJsonContext.Default.IltBankTransactionList); + if (list != null) return list; + } + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {TxPath}"); } + return new List(); + } + + public void SaveTransactionsIfDirty(List list) + { + if (_charFolder.Length == 0) return; + try + { + if (list.Count > MaxTransactions) + list.RemoveRange(0, list.Count - MaxTransactions); + string json = JsonSerializer.Serialize(list, IltHubJsonContext.Default.IltBankTransactionList); + if (json == _lastTxJson) return; + if (Blocked()) return; // as SaveStateIfDirty + if (DataWriteGuard.TrySave("the bank transaction log", TxPath, () => + { + Directory.CreateDirectory(_charFolder); + WriteAtomic(TxPath, json); + })) + _lastTxJson = json; + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {TxPath}"); } + } + + // ── Profiles ──────────────────────────────────────────────────────────── + + /// Lists profile names. Shared ones are prefixed "shared:". + public List ListProfiles() + { + var names = new List(); + try + { + if (Directory.Exists(CharProfileDir)) + names.AddRange(Directory.GetFiles(CharProfileDir, "*.json").Select(Path.GetFileNameWithoutExtension).OfType()); + if (Directory.Exists(SharedProfileDir)) + names.AddRange(Directory.GetFiles(SharedProfileDir, "*.json").Select(p => "shared:" + Path.GetFileNameWithoutExtension(p))); + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"list profiles"); } + names.Sort(StringComparer.OrdinalIgnoreCase); + return names; + } + + /// Saves the preference parts of as a named profile. + public bool SaveProfile(IltHubState state, string name, bool shared, out string error) + { + error = string.Empty; + string safe = SanitizeName(name); + if (safe.Length == 0) { error = "Profile name is empty."; return false; } + if (!shared && Blocked()) + { + error = "this character's Hub data is still being copied from RynthAi (see the log); save it as a shared profile, or try again later."; + return false; + } + try + { + string dir = shared ? SharedProfileDir : CharProfileDir; + var copy = Clone(state); + StripRuntime(copy); + string json = JsonSerializer.Serialize(copy, IltHubJsonContext.Default.IltHubState); + string path = Path.Combine(dir, safe + ".json"); + // The player asked for this save: the caller shows the reason (and the fix) itself. + return DataWriteGuard.TrySave("the Hub profile", path, () => + { + Directory.CreateDirectory(dir); + WriteAtomic(path, json); + }, out error, callerShows: true); + } + catch (Exception ex) { error = ex.Message; return false; } + } + + /// + /// Loads a profile onto , keeping runtime data (balances, + /// server bits, rosters, import flag) from the current state. + /// + public bool LoadProfile(IltHubState target, string name, out string error) + { + error = string.Empty; + bool shared = name.StartsWith("shared:", StringComparison.OrdinalIgnoreCase); + string safe = SanitizeName(shared ? name.Substring(7) : name); + string path = Path.Combine(shared ? SharedProfileDir : CharProfileDir, safe + ".json"); + try + { + if (!File.Exists(path)) { error = $"Profile not found: {name}"; return false; } + var p = JsonSerializer.Deserialize(File.ReadAllText(path), IltHubJsonContext.Default.IltHubState); + if (p == null) { error = "Profile file is empty."; return false; } + Normalize(p); + target.Pet = KeepRosters(p.Pet, target.Pet); + target.Character = p.Character; + target.Gear = p.Gear; + target.Games = p.Games; + target.Bank.AutoRefreshSeconds = p.Bank.AutoRefreshSeconds; + target.ForceLeaftideFeatures = p.ForceLeaftideFeatures; + target.GamesHudVisible = p.GamesHudVisible; + return true; + } + catch (Exception ex) { error = ex.Message; return false; } + } + + private static IltPetState KeepRosters(IltPetState incoming, IltPetState current) + { + incoming.PetLog = current.PetLog; + incoming.ShinyLog = current.ShinyLog; + // The breeding tracker holds this object; it is the character's own (not a profile setting). + incoming.Breeding = current.Breeding; + return incoming; + } + + private static IltHubState Clone(IltHubState s) + => JsonSerializer.Deserialize(JsonSerializer.Serialize(s, IltHubJsonContext.Default.IltHubState), + IltHubJsonContext.Default.IltHubState) ?? new IltHubState(); + + /// Removes character-specific runtime data before a profile is written. + private static void StripRuntime(IltHubState s) + { + s.ServerOptions = new IltServerOptionsSnapshot(); + var keepRefresh = s.Bank.AutoRefreshSeconds; + s.Bank = new IltBankState { AutoRefreshSeconds = keepRefresh }; + s.Pet.PetLog = new(); + s.Pet.ShinyLog = new(); + s.Pet.Breeding = new(); + s.UbSidecarsImported = false; + s.WindowVisible = false; + } + + private static string SanitizeName(string name) + { + var invalid = Path.GetInvalidFileNameChars(); + return new string((name ?? string.Empty).Trim().Where(c => !invalid.Contains(c)).ToArray()); + } + + // ── UtilityBelt sidecar import ────────────────────────────────────────── + + /// + /// One-time import of UB's bankdata (balances, transactions) and item conversions. + /// Searches Documents\Decal Plugins\UtilityBelt\<world>\<char>; when the world is + /// unknown every world folder containing the character is tried. Returns a summary. + /// + public string ImportUbSidecars(IltHubState state, List txLog, string world, string charName) + { + if (string.IsNullOrWhiteSpace(charName)) return "character name unknown"; + string ubRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Decal Plugins", "UtilityBelt"); + if (!Directory.Exists(ubRoot)) return "no UtilityBelt folder"; + + var charDirs = new List(); + if (!string.IsNullOrWhiteSpace(world)) + charDirs.Add(Path.Combine(ubRoot, world, charName)); + try + { + foreach (string w in Directory.GetDirectories(ubRoot)) + { + string d = Path.Combine(w, charName); + if (!charDirs.Contains(d, StringComparer.OrdinalIgnoreCase)) charDirs.Add(d); + } + } + catch { /* unreadable Documents subfolder: fall through with what we have */ } + + foreach (string dir in charDirs) + { + string bankDir = Path.Combine(dir, "bankdata"); + if (!Directory.Exists(bankDir) && !Directory.Exists(dir)) continue; + + int parts = 0; + parts += ImportBalances(Path.Combine(bankDir, "bankbalances.json"), state.Bank) ? 1 : 0; + int tx = ImportTransactions(Path.Combine(bankDir, "transactions.json"), txLog); + int conv = ImportConversions(new[] + { + Path.Combine(bankDir, "itemconversions.json"), + Path.Combine(dir, "itemconversions.json"), + }, state.Character.ItemConversions); + + if (parts + tx + conv > 0) + return $"imported from {dir}: balances {(parts > 0 ? "yes" : "no")}, {tx} transactions, {conv} conversions"; + } + return "no UtilityBelt bank data found for " + charName; + } + + private bool ImportBalances(string path, IltBankState bank) + { + if (!File.Exists(path)) return false; + try + { + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return false; + bank.Pyreals = ReadLong(root, "Pyreals"); + bank.Luminance = ReadLong(root, "Luminance"); + bank.LegendaryKeys = ReadLong(root, "LegendaryKeys"); + bank.MythicalKeys = ReadLong(root, "MythicalKeys"); + bank.EnlightenedCoins = ReadLong(root, "EnlightenedCoins"); + bank.WeaklyEnlightenedCoins = ReadLong(root, "WeaklyEnlightenedCoins"); + if (TryGetProp(root, "LastUpdated", out var lu) && lu.ValueKind == JsonValueKind.String && lu.TryGetDateTime(out var dt)) + bank.LastUpdated = dt; + return true; + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"UB balances import"); return false; } + } + + private int ImportTransactions(string path, List txLog) + { + if (!File.Exists(path)) return 0; + try + { + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + if (doc.RootElement.ValueKind != JsonValueKind.Array) return 0; + int added = 0; + foreach (var e in doc.RootElement.EnumerateArray()) + { + if (e.ValueKind != JsonValueKind.Object) continue; + var t = new IltBankTransaction + { + Type = ReadString(e, "Type"), + Currency = ReadString(e, "Currency"), + Amount = ReadLong(e, "Amount"), + OtherPlayer = ReadString(e, "OtherPlayer"), + Description = ReadString(e, "Description"), + }; + if (TryGetProp(e, "Timestamp", out var ts) && ts.ValueKind == JsonValueKind.String && ts.TryGetDateTime(out var dt)) + t.Timestamp = dt; + // Skip exact duplicates so re-running the import can't double the log. + if (txLog.Any(x => x.Timestamp == t.Timestamp && x.Amount == t.Amount && x.OtherPlayer == t.OtherPlayer)) continue; + txLog.Add(t); + added++; + } + txLog.Sort((a, b) => a.Timestamp.CompareTo(b.Timestamp)); + return added; + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"UB transactions import"); return 0; } + } + + private int ImportConversions(string[] paths, List table) + { + foreach (string path in paths) + { + if (!File.Exists(path)) continue; + try + { + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + if (doc.RootElement.ValueKind != JsonValueKind.Array) continue; + int added = 0; + foreach (var e in doc.RootElement.EnumerateArray()) + { + string name = ReadString(e, "ItemName"); + if (name.Length == 0) continue; + var existing = table.FirstOrDefault(c => c.ItemName.Equals(name, StringComparison.OrdinalIgnoreCase)); + if (existing == null) { existing = new IltItemConversion { ItemName = name }; table.Add(existing); added++; } + existing.ItemsPerConversion = Math.Max(1, (int)ReadLong(e, "ItemsPerConversion")); + existing.CoinsPerConversion = (int)ReadLong(e, "CoinsPerConversion"); + } + return added; + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"UB conversions import"); } + } + return 0; + } + + // ── JSON helpers (case-insensitive property access) ───────────────────── + + private static bool TryGetProp(JsonElement obj, string name, out JsonElement value) + { + foreach (var p in obj.EnumerateObject()) + if (p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { value = p.Value; return true; } + value = default; + return false; + } + + private static long ReadLong(JsonElement obj, string name) + { + if (!TryGetProp(obj, name, out var v)) return 0; + if (v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long l)) return l; + if (v.ValueKind == JsonValueKind.String) return IltParse.ParseLeadingLong(v.GetString() ?? string.Empty); + return 0; + } + + private static string ReadString(JsonElement obj, string name) + { + if (!TryGetProp(obj, name, out var v)) return string.Empty; + return v.ValueKind switch + { + JsonValueKind.String => v.GetString() ?? string.Empty, + JsonValueKind.Number => v.GetRawText(), + _ => string.Empty, + }; + } + + /// Write-then-rename so a crash mid-write never leaves a truncated file. + private static void WriteAtomic(string path, string contents) + { + string tmp = path + ".tmp"; + File.WriteAllText(tmp, contents); + File.Move(tmp, path, overwrite: true); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs new file mode 100644 index 0000000..4e840ba --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs @@ -0,0 +1,401 @@ +// IltHubUi.cs — The ILT sections' ImGui bodies (render thread only). +// Originally SilentKelpie's ILT Hub UI (RynthAi IltHub/); moved to RynthILT 2026-10-13, with the +// ILT parts of RynthAi's Mini Remote (the Remote tab's Bank section and Guardian line, the menu's +// Infinite Leaftide items) that read the Hub's state. +// +// The ILT sections are tabs of RynthAi's Mini Remote (its MiniRemoteHud draws the tab bar and +// calls RenderTab through RynthILT.Hub): Banking, Gear, Charms and Games. A tab is offered only +// while the server reports its feature on. The Character tab left the Mini Remote on 2026-10-13: +// - the session rates are RynthCore's Mini Remote "Session Stats" section (RenderRatesSection, +// surface "section:ilt-rates"), below RynthAi's one session; +// - the character overview and session are RynthOracle's Character tab ("/ro character"); +// - the "Treat this world as ILT" override and the ILT world names are RynthCore's +// Options > Diagnostics server selection only ("/ra hub force" and "/ra hub servers" remain). +// The /qb list (RynthAi's Quests tab before it moved to RynthOracle) is RynthILT's own "Quests" +// section on the rail (RenderQuestBonusSection, surface "section:ilt-questbonus"). +// RenderSection draws the ILT pieces inside RynthAi's own surfaces (the Remote tab, the Pets tab, +// the Mini Remote menu). The Guardian is a RynthCore ILT panel (the bar's ILT button, next to +// Bounties), drawn through RenderGuardianPanel. Render() keeps the floating extras: the Games HUD and the confirmation +// modal. Augmentations / Enlightenment / XP planning live on the engine Skills panel. All AC +// actions go through IltHubContext.Post / Confirm so nothing here touches the game directly. +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltHubUi +{ + private const string ConfirmPopupId = "Confirm##iltconfirm"; + private static readonly Vector4 ColLabel = new(0.80f, 0.84f, 0.90f, 1f); + + /// Where a server is forced now (the only place: RynthCore's Options window). + private const string ForceHint = "To force a server, use RynthCore Options > Diagnostics > server selection (/rc diagnostics)."; + + /// RynthCore's command that opens Options > Diagnostics (RynthCore 2026.10.5.54+). + private const string DiagnosticsCommand = "/rc diagnostics"; + + private readonly IltHubController _hub; + private readonly IltHubContext _ctx; + private IltConfirmRequest? _confirm; + private bool _confirmOpened; + // The last tab body drawn (for one shown log event per tab change); -1 = none yet. + private int _lastTabLogged = -1; + + public IltHubUi(IltHubController hub, IltHubContext ctx) + { + _hub = hub; + _ctx = ctx; + } + + /// The floating extras: Games HUD and the confirmation modal. + public void Render() + { + _hub.Games.RenderHud(); + RenderConfirm(); + } + + /// Draws one Mini Remote ILT tab's body into the current (child) window. + public void RenderTab(IltSection section) + { + if ((int)section != _lastTabLogged) + { + _lastTabLogged = (int)section; + RynthLog.Event(LogEvents.IltWindowShown, $"{IltSections.Label(section)} tab shown (world='{_ctx.Options.WorldName}', available={_hub.Available})"); + } + switch (section) + { + case IltSection.Banking: _hub.Banking.Render(); break; + case IltSection.Gear: _hub.Gear.Render(); break; + case IltSection.Charms: _hub.CharmsTab.Render(); break; + case IltSection.Games: _hub.Games.Render(); break; + case IltSection.VaultedDungeons: _hub.VaultedDungeons.Render(); break; + default: + // A saved tab id from before the move: say where the section lives now. + if (IltSections.MovedCommand(section) is string moved) + MovedLink(section, moved); + break; + } + } + + /// + /// The ILT session extras in RynthCore's Mini Remote "Session Stats" section (surface + /// "section:ilt-rates", the Infinite Leaftide group): coins, pyreals and item conversions. + /// XP, luminance and kills are RynthAi's session stats, drawn above it in the same section. + /// + public void RenderRatesSection() + { + if (!_hub.Available) + { + RenderHeader(); + RenderUnavailable(); + return; + } + _hub.Rates.Render(extrasOnly: true); + ImGui.TextDisabled("XP planner, Augmentations and Enlightenment: Skills panel > Progression."); + } + + /// + /// The quest bonus list (/qb) in RynthILT's own Mini Remote "Quests" section (surface + /// "section:ilt-questbonus"); it was a section of RynthAi's Quests tab, which moved to RynthOracle. + /// + public void RenderQuestBonusSection() + { + if (!_ctx.Options.IsIltLikeWorld) + { + RenderHeader(); + RenderUnavailable(); + return; + } + _hub.QuestBonus.RenderQb(); + } + + /// + /// One of the ILT pieces RynthAi draws in its own surfaces (RynthServerHub.Section*, RynthIltHub.Section*). False when + /// there is nothing to draw (unknown id, or not an ILT world). + /// + public bool RenderSection(string id) + { + var o = _ctx.Options; + switch (id) + { + case RynthServerHub.SectionRemoteBank: + if (!o.IsIltLikeWorld || o.IsOff(IltFeature.Bank) || !_ctx.State.Remote.ShowBank) return false; + RenderRemoteBank(); + return true; + case RynthServerHub.SectionRemoteGuardian: + if (!o.IsIltLikeWorld || !_ctx.State.Remote.ShowGuardian) return false; + _hub.Guardian.RenderRemoteLine(); + return true; + case RynthServerHub.SectionRemoteStats: + if (!o.IsIltLikeWorld) return false; + RenderRemoteStats(); + return true; + case RynthServerHub.SectionRemoteOptions: + if (!o.IsIltLikeWorld) return false; + RenderRemoteOptions(); + return true; + case RynthIltHub.SectionQuestBonus: + if (!o.IsIltLikeWorld) return false; + _hub.QuestBonus.RenderSection(); + return true; + case RynthServerHub.SectionPetLogs: + if (!o.IsIltLikeWorld) return false; + _hub.PetLogs.RenderSection(); + return true; + case RynthIltHub.SectionPetBreeding: + if (!o.IsIltLikeWorld) return false; + _hub.Breeding.RenderSection(); + return true; + case RynthServerHub.SectionPetCharms: + if (!o.IsIltLikeWorld) return false; + _hub.PetAutomation.RenderCharms(); + return true; + case RynthServerHub.SectionPetCapture: + if (!o.IsIltLikeWorld) return false; + _hub.PetAutomation.RenderCapture(); + return true; + case RynthServerHub.SectionServerStatus: + return RenderIltStatus(); + case RynthServerHub.SectionServerMenu: + return RenderLocalMenu(); + default: + return false; + } + } + + /// + /// The Guardian panel's body (RynthCore's ILT Guardian panel, RynthPluginRenderEmbed + /// "guardian"), or why it's idle while the server hasn't reported ILT features. + /// + public void RenderGuardianPanel() + { + if (!_hub.SectionAvailable(IltSection.Guardian)) + { + RenderHeader(); + ImGui.Separator(); + RenderUnavailable(); + return; + } + _hub.Guardian.Render(); + } + + /// A button that opens a moved section's new home (posted: the command runs on the pump). + private void MovedLink(IltSection section, string command) + { + const string home = "RynthOracle > Character"; + SafeImGui.TextDisabled($"{IltSections.Label(section)} moved to {home}; the ILT session rates are in Session Stats."); + if (ImGui.SmallButton($"Open {home}##moved{(int)section}")) + _ctx.Post(() => _hub.OpenMoved(section, command)); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(command); + } + + /// The world and when the server's ILT features were last read, with a Refresh. + private void RenderHeader() + { + var o = _ctx.Options; + string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world"; + SafeImGui.TextColored(o.IsIltLikeWorld ? IltStyle.ColTeal : IltStyle.ColTextMute, world); + ImGui.SameLine(); + SafeImGui.TextDisabled(o.IsRefreshing ? "checking server options..." + : o.LastRefreshUtc == DateTime.MinValue ? "server options not checked yet" + : $"options via {o.Source} @ {o.LastRefreshUtc.ToLocalTime():t}"); + ImGui.SameLine(); + if (ImGui.SmallButton("Refresh##opts")) _ctx.Post(() => o.Refresh(manual: true)); + } + + private void RenderUnavailable() + { + var o = _ctx.Options; + if (!o.IsIltLikeWorld) + { + SafeImGui.TextWrapped("This is not an Infinite Leaftide / ACECustom world, so the ILT tools are idle. " + ForceHint); + } + else if (o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue) + { + ImGui.TextWrapped("Checking which ILT features this server has enabled..."); + } + else + { + ImGui.TextWrapped("The server did not report any ILT features as enabled. Press Refresh to check again."); + } + } + + // ── RynthAi's Mini Remote: the Remote tab's Stats lines and Options switches ── + + /// Coins and pyreals per hour under RynthAi's per-hour lines (the Remote tab's Stats). + private void RenderRemoteStats() + { + var r = _hub.Rates.Summary; + Stat("Coins:", Compact(r.CoinsPerHour) + "/h"); + Stat("Pyr:", Compact(r.PyrealsPerHour) + "/h"); + } + + /// The Remote tab's ILT sections' switches, in RynthAi's Options popup. + private void RenderRemoteOptions() + { + var st = _ctx.State.Remote; + bool bank = st.ShowBank, guardian = st.ShowGuardian; + if (ImGui.Checkbox("Bank##iltmrbank", ref bank)) st.ShowBank = bank; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Infinite Leaftide bank balances (RynthILT)."); + if (ImGui.Checkbox("Guardian answer##iltmrguardian", ref guardian)) st.ShowGuardian = guardian; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("The last Temple guardian answer with a Give button (RynthILT)."); + } + + /// The tail of RynthAi's one-line session report: the coin / pyreal rates (RynthServerHub.TextSessionReport). + public string SessionReportTail() + { + var r = _hub.Rates.Summary; + return $", Coins {Compact(r.CoinsPerHour)}/h, Pyr {Compact(r.PyrealsPerHour)}/h"; + } + + // ── RynthAi's Mini Remote: the Remote tab's Bank section ──────────────── + + private void RenderRemoteBank() + { + var b = _ctx.State.Bank; + if (b.LastUpdated == DateTime.MinValue) + { + // Nothing read yet this install: offer a quiet /bank (the Banking tab has the full view). + ImGui.TextDisabled("Bank: not loaded yet"); + ImGui.SameLine(); + if (ImGui.SmallButton("Load##mrbank")) _ctx.Post(() => _hub.Banking.RequestRefresh(quiet: true)); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Reads your bank balances (/bank, reply hidden). The Banking tab has the details."); + BankLink(); + return; + } + Stat("P:", Compact(b.Pyreals)); + Stat("Lum:", Compact(b.Luminance)); + BankLink(); + if (!ImGui.BeginTable("##mrbank", 2, ImGuiTableFlags.SizingStretchSame)) return; + ImGui.TableNextColumn(); Stat("LK:", Compact(b.LegendaryKeys)); + ImGui.TableNextColumn(); Stat("MK:", Compact(b.MythicalKeys)); + ImGui.TableNextColumn(); Stat("EC:", Compact(b.EnlightenedCoins)); + ImGui.TableNextColumn(); Stat("WE:", Compact(b.WeaklyEnlightenedCoins)); + // Prestige Coins (ACECustom 2026-10-04): only once the server has reported some. + if (b.PrestigeCoins > 0) { ImGui.TableNextColumn(); Stat("PC:", Compact(b.PrestigeCoins)); } + ImGui.EndTable(); + } + + /// The Bank line's link to RynthILT's own Banking tab (Infinite Leaftide's bank stays RynthILT's). + private void BankLink() + { + if (!_hub.SectionAvailable(IltSection.Banking)) return; + ImGui.SameLine(); + if (ImGui.SmallButton("Bank##mrbanklink")) + _ctx.Ai.MiniRemoteTab(IltSections.TabId(IltSection.Banking), "show"); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("The Banking tab: deposits, withdrawals and transfers (/ra hub open banking)."); + } + + private static void Stat(string label, string value) + { + SafeImGui.TextColored(ColLabel, label); + ImGui.SameLine(); + ImGui.TextUnformatted(value); + } + + /// The Mini Remote's compact numbers (RynthAi's HudDraw.Compact): 12.3k, 4.5m, 1.2b. + private static string Compact(double v) + { + double a = Math.Abs(v); + if (a >= 1e9) return (v / 1e9).ToString("0.0") + "b"; + if (a >= 1e6) return (v / 1e6).ToString("0.0") + "m"; + if (a >= 1e4) return (v / 1e3).ToString("0.0") + "k"; + return v.ToString("0"); + } + + // ── RynthAi's Mini Remote menu: the Infinite Leaftide section ────────── + + /// + /// Under the Infinite Leaftide section while no ILT feature is on: why, where a server is + /// forced (RynthCore Options > Diagnostics only) and a server-features refresh. False when + /// features are on. + /// + private bool RenderIltStatus() + { + if (_hub.Available) return false; + var o = _ctx.Options; + SafeImGui.TextDisabled(!o.IsIltLikeWorld ? "Not an ILT world." + : o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue ? "Checking server features..." + : "No ILT features reported."); + if (!o.IsIltLikeWorld && ImGui.MenuItem("Force a server... (Options > Diagnostics)##mrforce", DiagnosticsCommand)) + _ctx.Post(() => { if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(DiagnosticsCommand); }); + if (!o.IsIltLikeWorld && ImGui.IsItemHovered()) SafeImGui.SetTooltip(ForceHint); + if (ImGui.MenuItem("Refresh server features##mrrefresh")) _hub.RequestOptionsRefresh(); + return true; + } + + /// + /// RynthILT's own Infinite Leaftide entries, for when RynthCore sends no server list (older + /// RynthCore, or its ImGui layer off): the tabs, where Character went, and the Guardian / + /// Bounties panels. + /// + private bool RenderLocalMenu() + { + if (!_hub.OffersTabs) return false; + ImGui.Separator(); + ImGui.TextDisabled("Server: Infinite Leaftide"); + foreach (IltSection section in IltSections.Tabs) + { + if (ImGui.MenuItem(IltSections.Label(section) + "##mrlocal", string.Empty, false, _hub.SectionAvailable(section))) + _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), "show"); + } + if (ImGui.MenuItem("Character##mrlocal", IltSections.OracleCharacterCommand)) + _ctx.Post(() => _hub.OpenMoved(IltSection.Character, IltSections.OracleCharacterCommand)); + if (ImGui.MenuItem("Guardian##mrlocal", "/rc guardian", false, _hub.SectionAvailable(IltSection.Guardian))) + _ctx.Post(() => _hub.OpenEnginePanel("guardian", "Guardian", "show")); + if (ImGui.MenuItem("Bounties##mrlocal", "/rc bounties")) + _ctx.Post(() => _hub.OpenEnginePanel("bounties", "Bounties", "show")); + RenderIltStatus(); + return true; + } + + // ── Confirmation modal ────────────────────────────────────────────────── + + private void RenderConfirm() + { + if (_confirm == null) + { + if (!_ctx.TryTakeConfirm(out var next)) return; + _confirm = next; + _confirmOpened = false; + } + if (!_confirmOpened) + { + ImGui.OpenPopup(ConfirmPopupId); + _confirmOpened = true; + } + + ImGui.SetNextWindowSize(new Vector2(420, 0), ImGuiCond.Appearing); + bool keepOpen = true; + if (ImGui.BeginPopupModal(ConfirmPopupId, ref keepOpen, ImGuiWindowFlags.AlwaysAutoResize)) + { + SafeImGui.TextColored(IltStyle.ColAmber, _confirm.Title); + ImGui.Separator(); + SafeImGui.TextWrapped(_confirm.Message); + ImGui.Spacing(); + if (ImGui.Button(_confirm.YesLabel + "##iltyes", new Vector2(120, 0))) + { + var act = _confirm.OnYes; + if (act != null) _ctx.Post(act); + _confirm = null; + ImGui.CloseCurrentPopup(); + } + ImGui.SameLine(); + if (ImGui.Button("Cancel##iltno", new Vector2(120, 0))) + { + _confirm = null; + ImGui.CloseCurrentPopup(); + } + ImGui.EndPopup(); + } + else + { + // Closed with the title-bar X (or never opened): treat as cancel. + _confirm = null; + } + if (!keepOpen) _confirm = null; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs new file mode 100644 index 0000000..6fe2672 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs @@ -0,0 +1,391 @@ +// IltInventory.cs — Shared item / player-property helper for every ILT Hub feature. +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. Items come +// from RynthILT's host-backed IltObjects instead of RynthAi's WorldObjectCache. +// +// One place for: WCID lookups (cached — the engine call is cheap but not free), stack +// counting, "is it equipped", appraisal requests (throttled), charm ON/OFF status from the +// appraisal Use text, and player int/bool/quad reads. Features never talk to the cache or +// the host for item facts directly, so behaviour (and its edge cases) stays consistent. +// Pump-thread only. +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Loot; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// +/// Registered ACECustom charm (CharmAbilityRegistry): display name, every known WCID (base + +/// tier variants), the player PropertyBool the server sets while the ability is active (0 when +/// it is kept in memory only, like Auto-Rebuff) and a one-line effect summary. +/// +internal sealed record IltCharmDef(string Name, uint[] Wcids, uint PlayerFlag = 0, string Effect = ""); + +internal sealed class IltInventory +{ + // ── Well-known WCIDs (ACECustom content) ──────────────────────────────── + public const uint WcidPyreal = 273; + public const uint WcidEnlightenedCoin = 300004; + public const uint WcidEnlToken = 300000; + public const uint WcidEnlMedallion = 90000217; + public const uint WcidEnlSigil = 300101189; + public const uint WcidEnlCrest = 98769999; + public const uint WcidEncapsulatedSpirit = 49485; + public const uint WcidRuneOfDispel = 30133; + public const uint WcidSummonRefillCharm = 78780030; + public const uint WcidUniversalMasteryCharm = 78780031; + public static readonly uint[] WcidInfiniteCastingStone = { 777700019, 777700055 }; + // Aetheria (ACECustom Aetheria.cs / PlayerCommands /clap). The Coalesced WCIDs stay the same once + // revealed (name "Aetheria", equipment set given), and /clap takes only unrevealed level 1-3 ones. + public const uint WcidBlueCoalescedAetheria = 42635; + public const uint WcidRedCoalescedAetheria = 42636; + public const uint WcidYellowCoalescedAetheria = 42637; + public const uint WcidRedAetheriaChunk = 310147; + public const uint WcidBlueAetheriaChunk = 310149; + public const uint WcidYellowAetheriaChunk = 310150; + public const uint WcidRedAetheriaPowder = 42644; + public const uint WcidBlueAetheriaPowder = 300019; + public const uint WcidEmpyreanTrinket = 34276; + public const uint WcidFalatacotTrinket = 34277; + + // ── Property ids used by several features ─────────────────────────────── + public const uint IntStackSize = 12; + public const uint IntValidLocations = 9; + public const uint IntLevel = 25; + public const uint IntMaxStructure = 91; + public const uint IntStructure = 92; + public const uint IntNumTimesTinkered = 171; + public const uint IntImbuedEffect = 179; + public const uint IntCleaving = 292; + // Corrupted-weapon chunk rules (ub-IT Leaftide.IsValidCorruptedWep / CorruptedChunkGuard). + /// ACE PropertyInt.Damage — a weapon's max damage. + public const uint IntDamage = 44; + /// ACE PropertyInt.AttackType — 2 = thrust; 160 / 166 / 486 are the multi-strike masks. + public const uint IntAttackType = 47; + /// ACE PropertyInt.ItemWorkmanship — loot-gen Craft (salvage-bag workmanship is not on weapons). + public const uint IntItemWorkmanship = 105; + /// ACE PropertyInt.WieldSkillType — 41 (Two Handed Combat) for two-handed weapons. + public const uint IntWieldSkillType = 159; + /// ACE PropertyInt.SlayerCreatureType. + public const uint IntSlayerCreatureType = 166; + /// ACE PropertyInt.ElementalDamageBonus. + public const uint IntElementalDamageBonus = 204; + /// ACE PropertyInt.WeaponType — 11 = TwoHanded. + public const uint IntWeaponType = 353; + /// ACE PropertyFloat.CriticalMultiplier — Biting Strike. + public const uint FloatCriticalMultiplier = 136; + /// ACE PropertyFloat.CriticalFrequency — Crushing Blow. + public const uint FloatCriticalFrequency = 147; + /// ACE PropertyFloat.IgnoreArmor — Armor Cleaving. + public const uint FloatIgnoreArmor = 155; + public const uint IntItemMaxLevel = 319; + /// Highest aetheria level on Infinite Leaftide (ACECustom AetheriaChance rolls up to 10; retail stops at 5). + public const int AetheriaMaxLevel = 10; + /// Gear ratings ILT aetheria can carry: C, CD and CDR (PropertyInt GearCrit / GearCritDamage / GearCritDamageResist). + public const uint IntGearCrit = 372; + public const uint IntGearCritDamage = 374; + public const uint IntGearCritDamageResist = 375; + public const uint IntSummoningMastery = 362; + public const uint IntEnlightenment = 390; + public const uint IntSplitArrowCount = 9031; + public const uint IntMaterialType = 131; + public const uint IntUses = 92; + /// ACECustom charm item: current tier (PropertyInt.CharmLevel). + public const uint IntCharmLevel = 50005; + /// ACECustom charm item: highest tier for this charm line (PropertyInt.CharmMaxLevel). + public const uint IntCharmMaxLevel = 50006; + public const uint StrUse = 14; + public const uint QuadTotalXp = 1; + public const uint QuadAvailableXp = 2; + public const uint QuadItemTotalXp = 4; + /// ACECustom PropertyInt64.BankedLuminance (sent with each XP batch). + public const uint QuadBankedLuminance = 9005; + public const uint BoolNeverChunk = 9030; + public const uint BoolPyrealRefillActive = 9049; + public const uint BoolUniversalMasteryActive = 50038; + + /// + /// Every charm in ACECustom's CharmAbilityRegistry (WCIDs and player flags match the server's + /// WCIDToAbilityId map and PropertyBool ids). Guardian Hand is not a registry charm and has no + /// published WCID — see IltGear. + /// + public static readonly IltCharmDef[] Charms = + { + new("Mana Barrier", new uint[] { 777700001, 777700054, 777710004, 777720004 }, 50010, + "Mana absorbs incoming damage (better ratio at higher tiers)."), + new("Infinite Casting", WcidInfiniteCastingStone, 50028, + "Infinite Casting Stone: spells cast without consuming components."), + new("Asheron's Favor", new uint[] { 777700020, 777710002, 777720002 }, 50030, + "+10 / 15 / 20% health and +50 / 100 / 250 natural armor."), + new("Artisan's", new uint[] { 777700021, 777710003, 777720003 }, 50031, + "Imbue success chance +4 / 8 / 12%."), + new("Shrapnel", new uint[] { 777700022 }, 50032, + "Tectonic Rifts cast as Rocky Shrapnel (Rocky Shrapnel must be learned)."), + new("Agony", new uint[] { 777700023 }, 50033, + "Tectonic Rifts I casts as Ring of Unspeakable Agony (the spell must be learned)."), + new("Split Cast", new uint[] { 777700024 }, 50035, + "Streak, Arc and Bolt spells split to several nearby targets."), + new("Explosive Arrow", new uint[] { 777700025, 777710005, 777720005 }, 50036, + "Arrow hits detonate an elemental ring at the target."), + new("Omni Strike", new uint[] { 777700026 }, 50037, + "Melee hits use the damage type the target is weakest to."), + new("Fork", new uint[] { 777700027, 777710007, 777720007 }, 50039, + "Streak, Arc and Bolt projectiles fork to nearby enemies (50 / 75 / 100% damage)."), + new("Auto-Rebuff", new uint[] { 777700300 }, 0, + "Keeps your buffs up automatically."), + new("Summon Essence Refill", new uint[] { WcidSummonRefillCharm }, BoolPyrealRefillActive, + "Refills an empty pet essence from banked pyreals when you summon."), + new("Universal Summoning Mastery", new uint[] { WcidUniversalMasteryCharm }, BoolUniversalMasteryActive, + "Use pet essences of any summoning mastery."), + }; + + private readonly RynthCoreHost _host; + private readonly IltObjects _cache; + /// AC's CM_Combat value for peace mode (RynthAi's CombatMode.NonCombat). + private const int CombatModeNonCombat = 1; + private readonly Dictionary _wcidCache = new(); + private readonly Dictionary _lastIdRequest = new(); + + /// Don't re-request appraisal for the same object more often than this. + private const long IdRequestThrottleMs = 30_000; + + public IltInventory(RynthCoreHost host, IltObjects cache) + { + _host = host; + _cache = cache; + } + + public RynthCoreHost Host => _host; + public IltObjects Cache => _cache; + public uint PlayerId => _host.GetPlayerId(); + + // ── Player state ──────────────────────────────────────────────────────── + + /// The client busy hourglass is up (an action is in progress). + public bool IsBusy => _host.HasGetBusyState && _host.GetBusyState() != 0; + + /// Player is in peace mode (combat mode NonCombat). True when the engine can't tell. + public bool InPeaceMode => !_host.HasGetCurrentCombatMode || _host.GetCurrentCombatMode() == CombatModeNonCombat; + + public int PlayerInt(uint stype, int fallback = 0) + => _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(PlayerId, stype, out int v) ? v : fallback; + + public bool PlayerBool(uint stype) + => _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(PlayerId, stype, out bool v) && v; + + public long PlayerQuad(uint stype) + => _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(PlayerId, stype, out long v) ? v : 0; + + /// Current/max health from the engine vitals read (0/0 when unavailable). + public (uint Cur, uint Max) PlayerHealth() + { + if (_host.HasGetPlayerVitals && _host.TryGetPlayerVitals(out uint h, out uint mh, out _, out _, out _, out _)) + return (h, mh); + return (0, 0); + } + + // ── Item facts ────────────────────────────────────────────────────────── + + /// All items the player carries or wears (snapshot). + public IEnumerable Items() => _cache.GetInventory(); + + /// Weenie class id, cached per object (0 when unknown). + public uint Wcid(WorldObject wo) + { + if (_wcidCache.TryGetValue(wo.Id, out uint w) && w != 0) return w; + if (_host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)wo.Id), out w)) + _wcidCache[wo.Id] = w; + return w; + } + + public int Int(WorldObject wo, uint stype, int fallback = 0) => wo.Values(unchecked((int)stype), fallback); + + public bool Bool(WorldObject wo, uint stype) + => _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(unchecked((uint)wo.Id), stype, out bool v) && v; + + public long Quad(WorldObject wo, uint stype) + => _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(unchecked((uint)wo.Id), stype, out long v) ? v : 0; + + /// A float (PropertyFloat) value; 0 when the host cannot read it or the item has none. + public double Double(WorldObject wo, uint stype) + => _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(unchecked((uint)wo.Id), stype, out double v) ? v : 0; + + /// The spell ids on an item (empty when none or the host cannot read them). + public IReadOnlyList SpellIds(WorldObject wo) + { + if (!_host.HasGetObjectSpellIds) return Array.Empty(); + var buf = new uint[64]; + int n = _host.GetObjectSpellIds(unchecked((uint)wo.Id), buf, buf.Length); + if (n <= 0) return Array.Empty(); + var ids = new int[Math.Min(n, buf.Length)]; + for (int i = 0; i < ids.Length; i++) ids[i] = unchecked((int)buf[i]); + return ids; + } + + public string Str(WorldObject wo, uint stype) + => _host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(unchecked((uint)wo.Id), stype, out string v) ? v ?? string.Empty : string.Empty; + + /// Stack size (1 for non-stackables). + public int StackSize(WorldObject wo) => Math.Max(1, Int(wo, IntStackSize, 1)); + + /// Remaining uses on a structure item (essences, kits, salvage bags). + public int Uses(WorldObject wo) => Int(wo, IntStructure, 0); + + public bool IsEquipped(WorldObject wo) + => wo.WieldedLocation > 0 || (wo.Wielder != 0 && unchecked((uint)wo.Wielder) == PlayerId); + + public bool HasAppraisal(WorldObject wo) + => !_host.HasHasAppraisalData || _host.HasAppraisalData(unchecked((uint)wo.Id)); + + /// + /// Why an item's property reads cannot be trusted (null = they can). Every property read here + /// answers 0 / false both for "the item has none" and for "the host cannot read it", so a chunk + /// rule that acts on a 0 must first know the read was real: the host must expose the readers + /// and confirm the item's appraisal arrived. adds the 64-bit reads + /// (item XP), the float reads and the + /// spell list, for the rules that use them. + /// + public string? ReadGap(WorldObject wo, bool quads = false, bool doubles = false, bool spells = false) + { + if (!_host.HasGetObjectIntProperty) return "int properties"; + if (!_host.HasGetObjectBoolProperty) return "bool properties"; + if (quads && !_host.HasGetObjectQuadProperty) return "item XP"; + if (doubles && !_host.HasGetObjectDoubleProperty) return "float properties"; + if (spells && !_host.HasGetObjectSpellIds) return "spells"; + if (!_host.HasHasAppraisalData || !_host.HasAppraisalData(unchecked((uint)wo.Id))) return "appraisal"; + return null; + } + + /// Requests appraisal data, throttled per object. Returns true if a request was sent. + public bool RequestAppraisal(WorldObject wo) + { + if (!_host.HasRequestId) return false; + long now = Environment.TickCount64; + if (_lastIdRequest.TryGetValue(wo.Id, out long last) && now - last < IdRequestThrottleMs) return false; + _lastIdRequest[wo.Id] = now; + return _host.RequestId(unchecked((uint)wo.Id)); + } + + // ── Finders / counters ────────────────────────────────────────────────── + + public WorldObject? FindByWcid(params uint[] wcids) + => Items().FirstOrDefault(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0); + + public IEnumerable AllByWcid(params uint[] wcids) + => Items().Where(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0); + + public WorldObject? FindByName(Func predicate) + => Items().FirstOrDefault(wo => predicate(wo.Name)); + + /// Total stack count of items with any of the given WCIDs. + public long CountByWcid(params uint[] wcids) + => AllByWcid(wcids).Sum(wo => (long)StackSize(wo)); + + /// Total stack count of items whose name matches exactly (case-insensitive). + public long CountByName(string name) + => Items().Where(wo => wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Sum(wo => (long)StackSize(wo)); + + /// Total stack count of a sigil-chain item (singular or plural stack name; see IltSigilChain.NameIs). + public long CountByChainName(string chainName) + => Items().Where(wo => IltSigilChain.NameIs(wo.Name, chainName)).Sum(wo => (long)StackSize(wo)); + + /// + /// True when the player carries spell components or an Infinite Casting Stone that isn't + /// known to be switched OFF (an OFF stone doesn't waive components). + /// + public bool HasCastingSupplies() + => AllByWcid(WcidInfiniteCastingStone).Any(stone => CharmStatus(stone) != IltTri.Off) + || Items().Any(wo => wo.ObjectClass == AcObjectClass.SpellComponent); + + /// Free main-pack slots (best effort: capacity minus direct children; -1 when unknown). + public int FreeMainPackSlots() + { + var cache = _cache; + int player = unchecked((int)PlayerId); + int capacity = PlayerInt(IltObjects.IntItemsCapacity, 102); + int used = cache.GetDirectInventory() + .Count(wo => wo.Container == player && wo.WieldedLocation <= 0 && wo.ObjectClass != AcObjectClass.Container); + return Math.Max(0, capacity - used); + } + + // ── Charms ────────────────────────────────────────────────────────────── + + /// + /// ON/OFF/Unknown from the appraisal Use text ("... Status: ON"). Requests appraisal + /// (throttled) when the text isn't loaded yet. + /// + public IltTri CharmStatus(WorldObject charm) + { + string use = Str(charm, StrUse); + if (use.Length == 0) + { + RequestAppraisal(charm); + return IltTri.Unknown; + } + if (use.Contains("Status: ON", StringComparison.OrdinalIgnoreCase)) return IltTri.On; + if (use.Contains("Status: OFF", StringComparison.OrdinalIgnoreCase)) return IltTri.Off; + return IltTri.Unknown; + } + + /// + /// Charm tier and max tier from the item's CharmLevel / CharmMaxLevel ints, else parsed from + /// the appraisal Use text ("Charm [Tier 2/3]"). (0, 0) until the appraisal is loaded. + /// + public (int Tier, int MaxTier) CharmTier(WorldObject charm) + { + int tier = Int(charm, IntCharmLevel, 0), max = Int(charm, IntCharmMaxLevel, 0); + if (tier > 0) return (tier, max); + var m = CharmTierText.Match(Str(charm, StrUse)); + if (!m.Success) return (0, 0); + int.TryParse(m.Groups[1].Value, out tier); + if (m.Groups[2].Success) int.TryParse(m.Groups[2].Value, out max); + return (tier, max); + } + + private static readonly System.Text.RegularExpressions.Regex CharmTierText = + new(@"Charm \[Tier (\d+)(?:/(\d+))?\]", System.Text.RegularExpressions.RegexOptions.CultureInvariant); + + /// Charm definition for an item (by WCID), or null. + public IltCharmDef? CharmDefFor(WorldObject wo) + { + uint w = Wcid(wo); + if (w == 0) return null; + return Charms.FirstOrDefault(c => Array.IndexOf(c.Wcids, w) >= 0); + } + + /// + /// Every charm the player carries: registered WCIDs plus anything whose Use text starts + /// with "Charm [Tier" (generic ACECustom charm format, catches charms added later). + /// + public List CarriedCharms() + { + var list = new List(); + foreach (var wo in Items()) + { + if (CharmDefFor(wo) != null) { list.Add(wo); continue; } + if (wo.ObjectClass is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.Armor + or AcObjectClass.Clothing or AcObjectClass.Container or AcObjectClass.Corpse) + continue; + if (Str(wo, StrUse).StartsWith("Charm [Tier", StringComparison.OrdinalIgnoreCase) + || wo.Name.EndsWith(" Charm", StringComparison.OrdinalIgnoreCase)) + list.Add(wo); + } + return list; + } + + // ── Actions ───────────────────────────────────────────────────────────── + + public bool Use(WorldObject wo) => _host.HasUseObject && _host.UseObject(unchecked((uint)wo.Id)); + + public bool UseOn(WorldObject source, uint targetId) + => _host.HasUseObjectOn && _host.UseObjectOn(unchecked((uint)source.Id), targetId); + + /// Forgets cached WCIDs / appraisal throttles (logout). + public void Reset() + { + _wcidCache.Clear(); + _lastIdRequest.Clear(); + _cache.Clear(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltLog.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltLog.cs new file mode 100644 index 0000000..7e728fc --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltLog.cs @@ -0,0 +1,196 @@ +// IltLog.cs - RynthILT's diagnostics log: the ILT features' trace categories and key events, +// written to %APPDATA%\RynthCore\RynthILT\Logs\RynthILT_yyyy-MM-dd.txt. +// +// The ILT Hub logged through RynthAi's RynthLog (LogCat.Ilt*, LogEvents.Ilt*) while it lived in +// RynthAi; the moved code keeps the same calls (RynthLog.Write / Trace / Exception / Event), so +// this is a small RynthLog of RynthILT's own: +// Write file (always) and the engine log +// Trace file, only while that category is traced ("/ilt trace on|off") +// Exception file and the engine log, always +// Event as Write for the key events (login, options refreshed, ...); trace-only events +// as Trace +// "/ilt debug on" echoes trace and exception lines to chat (local only). Lines are queued on any +// thread and written by Pump() on the plugin pump. +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Text; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT; + +/// One trace category per ILT feature (the names RynthAi's ILT Hub used). +internal enum LogCat +{ + IltHub, + IltOptions, + IltChat, + IltStore, + IltBanking, + IltPets, + IltQuests, + IltProgression, + IltRates, + IltGear, + IltGames, +} + +/// Named key events (the ILT Hub's catalogue in RynthAi's RynthLog). +internal static class LogEvents +{ + public const string IltLogin = "IltHub.Login"; + public const string IltWorldCheck = "IltHub.WorldCheck"; + public const string IltOptionsRefreshStart = "IltHub.OptionsRefreshStart"; + public const string IltOptionsRefreshed = "IltHub.OptionsRefreshed"; + public const string IltWindowShown = "IltHub.WindowShown"; + public const string IltWindowHidden = "IltHub.WindowHidden"; + public const string IltCommand = "IltHub.Command"; + public const string IltConfirmation = "IltHub.Confirmation"; + public const string IltLogout = "IltHub.Logout"; + /// /aug ApplyAugLines outcome (Progress Refresh current / login probe). + public const string IltAugLoad = "IltHub.AugLoad"; + + /// Events written as a normal log line; the rest only while their category is traced. + internal static readonly Dictionary Catalog = new(StringComparer.Ordinal) + { + [IltLogin] = (LogCat.IltHub, true), + [IltWorldCheck] = (LogCat.IltOptions, true), + [IltOptionsRefreshStart] = (LogCat.IltOptions, false), + [IltOptionsRefreshed] = (LogCat.IltOptions, true), + [IltWindowShown] = (LogCat.IltHub, true), + [IltWindowHidden] = (LogCat.IltHub, false), + [IltCommand] = (LogCat.IltHub, false), + [IltConfirmation] = (LogCat.IltHub, false), + [IltLogout] = (LogCat.IltHub, false), + [IltAugLoad] = (LogCat.IltProgression, true), + }; +} + +internal static class RynthLog +{ + private static readonly ConcurrentQueue Pending = new(); + private static readonly ConcurrentQueue PendingChat = new(); + private static readonly bool[] Traced = new bool[Enum.GetValues().Length]; + private static RynthCoreHost _host; + private static bool _hasHost; + private static string _directory = string.Empty; + + /// Echo trace and exception lines to the chat window ("/ilt debug on"). + public static volatile bool DebugToChat; + + /// Where the daily files go (tests point it at a scratch folder). + public static string Directory => _directory; + + public static void Init(RynthCoreHost host, string? directory = null) + { + _host = host; + _hasHost = true; + _directory = directory ?? Path.Combine(RynthILTPlugin.SettingsRoot, "Logs"); + } + + /// Drops the host (plugin shutdown): nothing is written to it afterwards. + public static void Shutdown() + { + Pump(); + _hasHost = false; + } + + public static void Write(LogCat cat, string message) + { + Enqueue(cat, message); + HostLog(message); + } + + public static void Trace(LogCat cat, string message) + { + if (!IsTracing(cat)) return; + Enqueue(cat, message); + if (DebugToChat) Chat($"[RynthILT {cat}] {message}"); + } + + public static void Exception(LogCat cat, Exception ex, string context = "") + { + string line = $"EXCEPTION {(context.Length > 0 ? context + ": " : "")}{ex.GetType().Name}: {ex.Message}"; + Enqueue(cat, line + Environment.NewLine + ex.StackTrace); + HostLog(line); + if (DebugToChat) Chat($"[RynthILT {cat}] {line}"); + } + + public static void Event(string eventKey, string message) + { + if (!LogEvents.Catalog.TryGetValue(eventKey, out var e)) { Write(LogCat.IltHub, $"[{eventKey}] {message}"); return; } + if (e.Info) Write(e.Cat, $"[{eventKey}] {message}"); + else Trace(e.Cat, $"[{eventKey}] {message}"); + } + + /// True when would record the event (an Info event, or a traced Trace one). + public static bool IsEventEnabled(string eventKey) + => !LogEvents.Catalog.TryGetValue(eventKey, out var e) || e.Info || IsTracing(e.Cat); + + public static bool IsTracing(LogCat cat) => (int)cat >= 0 && (int)cat < Traced.Length && Traced[(int)cat]; + + public static void SetTracing(LogCat cat, bool on) + { + if ((int)cat >= 0 && (int)cat < Traced.Length) Traced[(int)cat] = on; + } + + /// Every category on or off; returns how many. + public static int SetTracingAll(bool on) + { + for (int i = 0; i < Traced.Length; i++) Traced[i] = on; + return Traced.Length; + } + + public static bool TryParseCategory(string name, out LogCat cat) + { + if (Enum.TryParse(name, ignoreCase: true, out cat)) return true; + return Enum.TryParse("Ilt" + name, ignoreCase: true, out cat); + } + + public static string TracedList() + { + var on = new List(); + foreach (LogCat c in Enum.GetValues()) if (IsTracing(c)) on.Add(c.ToString()); + return on.Count == 0 ? "none" : string.Join(", ", on); + } + + /// Writes the queued lines (plugin pump). + public static void Pump() + { + int lines = 0; + while (lines++ < 20 && PendingChat.TryDequeue(out string? chat)) + { + if (!_hasHost) continue; + try { if (_host.HasWriteToChat) _host.WriteToChat(chat, 1); } catch { } + } + if (Pending.IsEmpty || _directory.Length == 0) return; + var sb = new StringBuilder(); + int n = 0; + while (n++ < 2000 && Pending.TryDequeue(out string? line)) sb.Append(line).Append(Environment.NewLine); + try + { + System.IO.Directory.CreateDirectory(_directory); + File.AppendAllText(Path.Combine(_directory, $"RynthILT_{DateTime.Now:yyyy-MM-dd}.txt"), sb.ToString()); + } + catch { /* a log that can't be written must never break a feature */ } + } + + private static void Enqueue(LogCat cat, string message) + { + if (Pending.Count > 20000) return; // nothing is draining (no pump): don't grow forever + Pending.Enqueue($"{DateTime.Now:HH:mm:ss.fff} [{cat}] {message}"); + } + + private static void HostLog(string message) + { + if (!_hasHost) return; + try { _host.Log("[RynthILT] " + message); } catch { } + } + + /// Queued for the pump (trace lines can come from the render thread). + private static void Chat(string text) + { + if (PendingChat.Count < 200) PendingChat.Enqueue(text); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltMigration.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltMigration.cs new file mode 100644 index 0000000..0955cb8 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltMigration.cs @@ -0,0 +1,344 @@ +// IltMigration.cs - Carries the ILT Hub's saved data over from RynthAi (2026-10-13). +// +// While the ILT Hub lived in RynthAi it saved per character in RynthAi's settings folder +// (\SettingsProfiles\\\: ilt-hub.json, +// ilt-hub-transactions.json, ilt-hub-profiles\) and for every character in the RynthAi folder +// (IltHubProfiles\, ilt-aug-costs.json); the server list and the "Force enable" override were +// fields of each RynthAi profile (FeatureServerNames, ForceServerFeatures). +// +// RynthILT keeps its own files (IltHubStore, IltSettingsStore). On a character's first login +// with RynthILT (no hub.json yet) the old files are COPIED, never moved or deleted: RynthAi no +// longer reads them, and a rollback to an older RynthAi still finds them. Existing RynthILT files +// are never overwritten. The character's active RynthAi profile adds its world names to +// RynthILT's list and, when it had "Force enable" ticked, ticks this character's "Treat this world +// as ILT". The shared files are copied once (IltSettings.SharedFilesMigrated). Pump thread. +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using RynthCore.Install; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// +/// The fields of a RynthAi profile RynthILT reads (the rest of the file is ignored): the two Server +/// Features fields, and the settings that moved to RynthILT on 2026-10-20 (null when the profile +/// predates them: the default applies). +/// +public sealed class IltLegacyProfileFlags +{ + public List? FeatureServerNames; + public bool ForceServerFeatures; + /// RynthAi's Empyrean Handler ring evade (on by default there too). + public bool? HandlerRingEvade; + /// RynthAi's Vaulted Dungeons master switch (off by default). + public bool? EnableVaultedDungeons; + /// RynthAi's T11 item-aug override (-1 = automatic). + public int? T11ItemAugsOverride; +} + +/// The Remote tab switches of RynthAi's huds.json that moved to RynthILT (2026-10-20). +public sealed class IltLegacyHuds +{ + public bool? MiniShowBank; + public bool? MiniShowGuardian; +} + +/// The Pets tab fields of RynthAi's miniremote.json that moved to RynthILT (2026-10-20). +public sealed class IltLegacyMiniRemote +{ + public IltLegacyPetTab? Pet; +} + +public sealed class IltLegacyPetTab +{ + public bool? UsePyrealRefillPath; + public bool? AutoCaptureEnabled; + public int? CaptureLensIndex; +} + +internal static class IltMigration +{ + /// RynthAi's per-server profile folders (overridable for the tests). + public static string LegacyProfilesBase = Path.Combine(RynthInstallPaths.RynthAiDir, "SettingsProfiles"); + + /// RynthAi's folder (shared profiles, aug costs; overridable for the tests). + public static string LegacySharedRoot = RynthInstallPaths.RynthAiDir; + + /// RynthAi's folder for profiles saved before they went per server. + private const string LegacyServerFolder = "ACEmulator"; + + /// RynthAi's file-name sanitizer (LegacyDashboardRenderer.SanitizeFileName). + internal static string RynthAiSafeName(string name) + { + var sb = new StringBuilder(name.Length); + foreach (char c in name) + sb.Append(char.IsLetterOrDigit(c) || c == '\'' || c == '-' ? c : '_'); + return sb.ToString(); + } + + /// RynthAi's settings folder for this character: the world's, else the pre-per-server one. Null when neither exists. + public static string? FindLegacyCharFolder(string world, string charName) + { + if (string.IsNullOrWhiteSpace(charName)) return null; + string safeChar = RynthAiSafeName(charName.Trim()); + var candidates = new List(); + if (!string.IsNullOrWhiteSpace(world)) + { + string safeWorld = RynthAiSafeName(world.Trim()); + if (safeWorld.Length > 0) candidates.Add(Path.Combine(LegacyProfilesBase, safeWorld, safeChar)); + } + candidates.Add(Path.Combine(LegacyProfilesBase, LegacyServerFolder, safeChar)); + foreach (string dir in candidates) + if (Directory.Exists(dir) && (File.Exists(Path.Combine(dir, "ilt-hub.json")) + || File.Exists(Path.Combine(dir, "ilt-hub-transactions.json")) + || Directory.Exists(Path.Combine(dir, "ilt-hub-profiles")) + || File.Exists(Path.Combine(dir, "active_profile.txt")) + || File.Exists(Path.Combine(dir, LegacyMiniRemoteFile)) + || File.Exists(Path.Combine(dir, "Default.json")))) + return dir; + return null; + } + + /// Whether 's copy from RynthAi failed and hasn't been finished yet. + public static bool IsPending(IltSettings settings, string charFolder) + { + if (string.IsNullOrEmpty(charFolder)) return false; + foreach (string f in settings.PendingCharacterMigrations ?? new List()) + if (string.Equals(f, charFolder, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + private static void SetPending(IltSettings settings, string charFolder, bool pending) + { + settings.PendingCharacterMigrations ??= new List(); + settings.PendingCharacterMigrations.RemoveAll(f => string.Equals(f, charFolder, StringComparison.OrdinalIgnoreCase)); + if (pending) settings.PendingCharacterMigrations.Add(charFolder); + } + + /// + /// First login of a character with RynthILT: copies its RynthAi ILT Hub files into + /// (only when it has no hub.json yet, or an earlier copy failed + /// part-way) and folds its RynthAi Server Features into . + /// says whether the profile had "Force enable" ticked. Returns what + /// was done (for the log), empty when nothing. When a file can't be copied the folder is marked + /// pending in (save them): the Hub then writes nothing there and the + /// next call copies what is still missing (never overwriting). + /// + public static List MigrateCharacter(string newFolder, string world, string charName, IltSettings settings, out bool forceIlt) + { + forceIlt = false; + var done = new List(); + if (string.IsNullOrEmpty(newFolder)) return done; + bool wasPending = IsPending(settings, newFolder); + if (!wasPending && File.Exists(Path.Combine(newFolder, IltHubStore.StateFile))) return done; + string? legacy = FindLegacyCharFolder(world, charName); + if (legacy == null) + { + // The RynthAi files are gone: nothing left to wait for. + if (wasPending) { SetPending(settings, newFolder, false); done.Add("the RynthAi files of an unfinished copy are gone; RynthILT's own files are used from now on"); } + return done; + } + + int failed = 0; + if (CopyIfMissing(Path.Combine(legacy, "ilt-hub.json"), Path.Combine(newFolder, IltHubStore.StateFile), ref failed)) + done.Add("ilt-hub.json"); + if (CopyIfMissing(Path.Combine(legacy, "ilt-hub-transactions.json"), Path.Combine(newFolder, IltHubStore.TransactionsFile), ref failed)) + done.Add("ilt-hub-transactions.json"); + int profiles = CopyFolder(Path.Combine(legacy, "ilt-hub-profiles"), Path.Combine(newFolder, IltHubStore.ProfilesFolder), ref failed); + if (profiles > 0) done.Add($"{profiles} Hub profile(s)"); + if (failed > 0) + { + SetPending(settings, newFolder, true); + done.Add($"{failed} file(s) NOT copied (see the lines above; the originals in {legacy} are untouched). " + + "The Hub saves nothing for this character until they are; tried again every few minutes and at each login"); + } + else if (wasPending) + { + SetPending(settings, newFolder, false); + done.Add("the earlier unfinished copy is complete"); + } + + if (ReadProfileFlags(legacy, out IltLegacyProfileFlags flags)) + { + int added = MergeServerNames(settings, flags.FeatureServerNames); + if (added > 0) done.Add($"{added} server name(s) from the RynthAi profile"); + if (flags.ForceServerFeatures) + { + forceIlt = true; + done.Add("\"Force enable\" -> Treat this world as ILT"); + } + } + return done; + } + + /// + /// Once for every character: RynthAi's shared Hub profiles and aug-cost table into + /// (never over a file RynthILT already has). Returns what was done. + /// Marked done only when every copy worked: a failed one is tried again at the next login. + /// + public static List MigrateShared(IltSettings settings, string newRoot) + { + var done = new List(); + if (settings.SharedFilesMigrated) return done; + int failed = 0; + int profiles = CopyFolder(Path.Combine(LegacySharedRoot, "IltHubProfiles"), Path.Combine(newRoot, "Profiles"), ref failed); + if (profiles > 0) done.Add($"{profiles} shared Hub profile(s)"); + if (CopyIfMissing(Path.Combine(LegacySharedRoot, "ilt-aug-costs.json"), Path.Combine(newRoot, "ilt-aug-costs.json"), ref failed)) + done.Add("ilt-aug-costs.json"); + if (failed == 0) settings.SharedFilesMigrated = true; + else done.Add($"{failed} shared file(s) NOT copied; tried again at the next login"); + return done; + } + + /// RynthAi's per-character Mini Remote file (the Pets tab's settings). + public const string LegacyMiniRemoteFile = "miniremote.json"; + + /// RynthAi's per-character HUD file (the Remote tab's section switches). + public const string LegacyHudsFile = "huds.json"; + + /// + /// Once per character (IltHubState.RynthAiSettingsImported): the RynthAi settings that moved to + /// RynthILT on 2026-10-20 are copied from the character's RynthAi files into : + /// from miniremote.json the Pets tab's ACECustom options (summon from empty with the refill + /// charm, siphon auto-capture and its lens); from the active profile (as ReadProfileFlags) the + /// Empyrean Handler ring evade, the Vaulted Dungeons master switch and the T11 item-aug override; + /// from huds.json the Remote tab's Bank / Guardian switches. The RynthAi files are only read (RynthAi keeps the + /// old fields readable and no longer uses them). A character with no RynthAi files keeps + /// RynthILT's defaults. Returns what was copied (for the log); empty when nothing was done. + /// + public static List ImportRynthAiSettings(IltHubState state, string world, string charName) + { + var done = new List(); + if (state.RynthAiSettingsImported || string.IsNullOrWhiteSpace(charName)) return done; + string? legacy = FindLegacyCharFolder(world, charName); + if (legacy != null) + { + if (ReadJson(Path.Combine(legacy, LegacyMiniRemoteFile), IltHubJsonContext.Default.IltLegacyMiniRemote) is { Pet: { } pet }) + { + if (pet.UsePyrealRefillPath is bool refill) { state.Pet.RefillFromEmpty = refill; done.Add($"summon from empty essences {(refill ? "on" : "off")}"); } + if (pet.AutoCaptureEnabled is bool capture) { state.Pet.AutoCapture = capture; done.Add($"auto-capture {(capture ? "on" : "off")}"); } + if (pet.CaptureLensIndex is int lens) + { + state.Pet.CaptureLens = Math.Clamp(lens, 0, PetCaptureRules.Lenses.Length - 1); + done.Add("capture lens " + PetCaptureRules.LensAt(state.Pet.CaptureLens).Name); + } + } + if (ReadJson(Path.Combine(legacy, LegacyHudsFile), IltHubJsonContext.Default.IltLegacyHuds) is { } huds) + { + if (huds.MiniShowBank is bool bank) { state.Remote.ShowBank = bank; if (!bank) done.Add("the Remote tab's Bank hidden"); } + if (huds.MiniShowGuardian is bool g) { state.Remote.ShowGuardian = g; if (!g) done.Add("the Remote tab's Guardian line hidden"); } + } + if (ReadProfileFlags(legacy, out IltLegacyProfileFlags flags)) + { + if (flags.HandlerRingEvade is bool ring) { state.Combat.HandlerRingEvade = ring; done.Add($"Empyrean Handler ring evade {(ring ? "on" : "off")}"); } + if (flags.EnableVaultedDungeons is bool vaulted) { state.VaultedDungeonsEnabled = vaulted; done.Add($"Vaulted Dungeons master switch {(vaulted ? "on" : "off")}"); } + if (flags.T11ItemAugsOverride is int augs && augs >= 0) { state.T11.ItemAugsOverride = augs; done.Add($"T11 item augmentations fixed at {augs:N0}"); } + } + } + state.RynthAiSettingsImported = true; + if (done.Count == 0) done.Add(legacy == null ? "no RynthAi settings for this character (defaults kept)" : "nothing set in RynthAi (defaults kept)"); + return done; + } + + /// A JSON file read with , or null (missing or unreadable: logged). + private static T? ReadJson(string path, System.Text.Json.Serialization.Metadata.JsonTypeInfo info) where T : class + { + try + { + return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path), info) : null; + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.IltStore, ex, $"migration: read {path}"); + return null; + } + } + + /// The character's active RynthAi profile's Server Features fields. + internal static bool ReadProfileFlags(string legacyCharFolder, out IltLegacyProfileFlags flags) + { + flags = new IltLegacyProfileFlags(); + try + { + string active = "Default"; + string marker = Path.Combine(legacyCharFolder, "active_profile.txt"); + if (File.Exists(marker)) + { + string name = File.ReadAllText(marker).Trim(); + if (name.Length > 0) active = name; + } + string path = Path.Combine(legacyCharFolder, active + ".json"); + if (!File.Exists(path)) return false; + var f = JsonSerializer.Deserialize(File.ReadAllText(path), IltHubJsonContext.Default.IltLegacyProfileFlags); + if (f == null) return false; + flags = f; + return true; + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.IltStore, ex, "migration: RynthAi profile read"); + return false; + } + } + + /// Adds the names the list doesn't have yet (case-insensitive); returns how many. + internal static int MergeServerNames(IltSettings settings, IEnumerable? names) + { + if (names == null) return 0; + int added = 0; + foreach (string n in ServerFeatureGate.ParseList(string.Join(",", names))) + { + if (settings.ServerNames.Any(have => have.Equals(n, StringComparison.OrdinalIgnoreCase))) continue; + settings.ServerNames.Add(n); + added++; + } + return added; + } + + /// + /// Copies to unless the source is missing or the + /// target exists. A failed copy is never silent: it is logged and said in chat once per folder + /// (DataWriteGuard, on ILT), with the reason and the fix and where the original still is, and + /// counted in . + /// + private static bool CopyIfMissing(string from, string to, ref int failed) + { + try + { + if (!File.Exists(from) || File.Exists(to)) return false; + } + catch { return false; } + string fromDir = Path.GetDirectoryName(from) ?? from; + bool ok = DataWriteGuard.TrySave($"{Path.GetFileName(from)} carried over from RynthAi (the original is still in {fromDir})", to, () => + { + Directory.CreateDirectory(Path.GetDirectoryName(to)!); + File.Copy(from, to); + }); + if (!ok) failed++; + return ok; + } + + private static int CopyFolder(string from, string to, ref int failed) + { + int n = 0; + string[] files; + try + { + if (!Directory.Exists(from)) return 0; + files = Directory.GetFiles(from, "*.json"); + } + catch (Exception ex) + { + failed++; + RynthLog.Exception(LogCat.IltStore, ex, $"migration: list {from}"); + return 0; + } + foreach (string f in files) + if (CopyIfMissing(f, Path.Combine(to, Path.GetFileName(f)), ref failed)) n++; + return n; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs new file mode 100644 index 0000000..d111074 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs @@ -0,0 +1,129 @@ +// IltParse.cs — Shared parsing / formatting helpers for ILT Hub server output. +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// Centralised so every feature uses the same number parsing (commas, k/m/b/t suffixes), +// the same compact K/M/B display, and the same regexes. Regexes are static and built once; +// RegexOptions.Compiled is harmless under NativeAOT (it falls back to the interpreter). +using System; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal static class IltParse +{ + private const RegexOptions Opt = RegexOptions.Compiled | RegexOptions.CultureInvariant; + + /// + /// "/aug" level line: "Creature:1,234", "Duration: 1,234", or "Specialize: 2". + /// Trailing notes ("Triune Weave: 5 (adds ...)") are allowed; the planner only keeps known keys. + /// + public static readonly Regex AugLine = new(@"^(\w+)\s*:\s*(\d[\d,.\s']*)", Opt); + + /// "/pets" / "/shinies" roster entry: "12. Shiny Drudge Ravener". + public static readonly Regex RosterLine = new(@"^\s*(\d+)\.\s+(.+)$", Opt); + + /// Bank-command amount entry: "1.5m", "250,000", "2b". + public static readonly Regex AmountInput = new(@"^([\d,.]+)\s*([kmbt]?)$", Opt | RegexOptions.IgnoreCase); + + /// AC character name: starts with a letter, then letters, spaces, apostrophes or hyphens (max 32). + public static readonly Regex CharacterName = new(@"^[A-Za-z][A-Za-z '\-]{0,31}$", Opt); + + /// A comma-grouped or plain integer as printed by ACE's N0 format. + public const string AmountPattern = @"(?:\d{1,3}(?:,\d{3})+|\d+)"; + + /// "Transferred 5,000 Pyreals to Bob" (optional " (offline)" / trailing "--- note"). + public static readonly Regex BankSent = new( + @"^Transferred (" + AmountPattern + @") ([^']+?) to ([^-]+?)(?:\s*---.*)?$", Opt); + + /// "Received 5,000 Pyreals from Bob". + public static readonly Regex BankReceived = new( + @"^Received (" + AmountPattern + @") ([^']+?) from (.+?)(?:\s*---.*)?$", Opt); + + /// "/xp all" cost line: "[XP] Your XP cost for next 1 Strength level is: 1,234". + public static readonly Regex XpCost = new(@"\[XP\] Your XP cost for next 1 (\w+) level is: ([\d,]+)", Opt); + + /// "/attr" success: "[ATTR] Strength attribute raised by 10, costing 1,234!". + public static readonly Regex AttrRaised = new(@"^\[ATTR\] (\w+) attribute raised by (\d+), costing ([\d,]+)", Opt); + + private static readonly Regex GroupedInt = new(@"^\d{1,3}(?:[,.\s']\d{3})+|^\d+", RegexOptions.CultureInvariant); + + /// + /// The level in an AugLine value: digits grouped by a comma, period, space or apostrophe + /// ("4,300", "4.300", "4 300", "4'300") read as one number; "2 (adds 5)" as 2; "1.5" as 1. 0 when absent. + /// + public static long ParseAugValue(string text) + { + if (string.IsNullOrEmpty(text)) return 0; + var m = GroupedInt.Match(text.Trim()); + if (!m.Success) return 0; + var digits = new System.Text.StringBuilder(m.Value.Length); + foreach (char c in m.Value) if (char.IsDigit(c)) digits.Append(c); + return long.TryParse(digits.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out long v) ? v : 0; + } + + /// Strips commas and parses the leading integer; 0 when absent. + public static long ParseLeadingLong(string text) + { + if (string.IsNullOrEmpty(text)) return 0; + string s = text.Replace(",", string.Empty).Trim(); + int end = 0; + while (end < s.Length && char.IsDigit(s[end])) end++; + return end > 0 && long.TryParse(s.AsSpan(0, end), NumberStyles.None, CultureInfo.InvariantCulture, out long v) ? v : 0; + } + + /// + /// Parses a user-entered amount with optional k/m/b/t suffix ("1.5m" → 1,500,000). + /// Returns false for empty, negative, or overflowing input. + /// + public static bool TryParseAmount(string input, out long amount) + { + amount = 0; + var m = AmountInput.Match((input ?? string.Empty).Trim()); + if (!m.Success) return false; + if (!decimal.TryParse(m.Groups[1].Value.Replace(",", string.Empty), NumberStyles.AllowDecimalPoint, + CultureInfo.InvariantCulture, out decimal baseVal)) + return false; + decimal mult = char.ToLowerInvariant(m.Groups[2].Value.Length > 0 ? m.Groups[2].Value[0] : ' ') switch + { + 'k' => 1_000m, + 'm' => 1_000_000m, + 'b' => 1_000_000_000m, + 't' => 1_000_000_000_000m, + _ => 1m, + }; + decimal total = Math.Floor(baseVal * mult); + if (total <= 0 || total > long.MaxValue) return false; + amount = (long)total; + return true; + } + + /// Compact display: 950 → "950", 12_300 → "12.3K", 4_500_000 → "4.50M", 2e9 → "2.00B". + public static string Compact(double value) + { + double a = Math.Abs(value); + string s = a >= 1e12 ? (value / 1e12).ToString("0.00", CultureInfo.InvariantCulture) + "T" + : a >= 1e9 ? (value / 1e9).ToString("0.00", CultureInfo.InvariantCulture) + "B" + : a >= 1e6 ? (value / 1e6).ToString("0.00", CultureInfo.InvariantCulture) + "M" + : a >= 1e3 ? (value / 1e3).ToString("0.0", CultureInfo.InvariantCulture) + "K" + : value.ToString("0", CultureInfo.InvariantCulture); + return s; + } + + /// Full grouped display: 1234567 → "1,234,567". + public static string N0(long value) => value.ToString("N0", CultureInfo.InvariantCulture); + + /// "3d 4h 12m 5s" style duration; "ready" when zero or negative. + public static string Duration(TimeSpan span) + { + if (span <= TimeSpan.Zero) return "ready"; + if (span.TotalDays >= 1) return $"{(int)span.TotalDays}d {span.Hours}h {span.Minutes}m"; + if (span.TotalHours >= 1) return $"{span.Hours}h {span.Minutes}m {span.Seconds}s"; + if (span.TotalMinutes >= 1) return $"{span.Minutes}m {span.Seconds}s"; + return $"{span.Seconds}s"; + } + + /// Strips "<Tell:…>" style markup the chat window sometimes leaves on names. + public static string StripMarkup(string text) + => Regex.Replace(text ?? string.Empty, @"<[^>]*>", string.Empty).Trim(); +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetAutomation.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetAutomation.cs new file mode 100644 index 0000000..e24efa5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetAutomation.cs @@ -0,0 +1,394 @@ +// IltPetAutomation.cs — ACECustom's parts of RynthAi's Pets tab: the pet charms, the "summon from an +// empty essence" refill path and siphon-lens auto-capture. +// Moved out of RynthAi's MiniRemote/PetsTab.cs 2026-10-20 (originally SilentKelpie's IltPets, ILT +// Hub): summoning is every server's, so the roster, healing and cosmetic pets stay RynthAi's, but +// these three are ACECustom content and live here now. +// +// * Pet charms (section "pets-charms"): Summon Essence Refill (the server refills an empty essence +// from banked pyreals) and Universal Summoning Mastery, read from the charm's appraisal text and +// the player bools the server stamps, plus the "no spell components" warning when the server +// requires them. The refill opt-in feeds RynthAi's PetManager through RynthILT.Hub +// AllowSummonOnEmpty (cached here every tick; an unknown state never spends pyreals). +// * Auto siphon capture (section "pets-capture", ACECustom MonsterCapture): when enabled, uses the +// chosen lens on the nearest attackable creature within 5 m once it is <=20% health or under +// 20 HP (Asheron's Lens skips the health gate). Resonance still needs a prior failed capture on +// the server. Bounded per creature and overall (PetCaptureThrottle). +// Ticks only on an ILT-like world (IltHubController); the sections draw nothing elsewhere. +using System; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltPetAutomation : IIltFeature +{ + private const long CaptureThinkMs = 250; + private const long CaptureCooldownMs = 2500; + private const long CaptureFailBackoffMs = 8000; + private const long CharmScanMs = 2000; + private const long GateMs = 500; + + private readonly IltHubContext _ctx; + private readonly PetCaptureThrottle _captureThrottle = new(); + private long _lastCaptureThink; + private long _captureCooldownUntil; + private long _lastCharmScan; + private long _lastGate; + + // Read by the render thread and (AllowSummonOnEmpty) by RynthAi's pump. + private volatile string _captureStatus = "off"; + private volatile bool _uiRefillActive; + private volatile bool _uiMasteryActive; + private volatile bool _uiHasCasting = true; + private volatile bool _allowSummonOnEmpty; + + // The server's health updates (RynthPluginOnUpdateHealth), for creatures the client has no vitals for. + private const int MaxHealthEntries = 512; + private readonly object _healthGate = new(); + private readonly System.Collections.Generic.Dictionary _healthRatios = new(); + + public IltPetAutomation(IltHubContext ctx) => _ctx = ctx; + + private IltPetState S => _ctx.State.Pet; + + /// The auto-capture line under the switch (render thread). + public string CaptureStatus => _captureStatus; + + /// + /// RynthILT.Hub AllowSummonOnEmpty: the last tick's answer, false off an ILT world. Any thread. + /// + public bool AllowSummonOnEmpty => _ctx.Options.IsIltLikeWorld && _allowSummonOnEmpty; + + // ── Charms / gates ────────────────────────────────────────────────────── + + /// Summon Essence Refill charm is carried and switched on (or the server stamped the player bool). + public bool RefillCharmActive() + { + var inv = _ctx.Inventory; + if (inv.PlayerBool(IltInventory.BoolPyrealRefillActive)) return true; + var charm = inv.FindByWcid(IltInventory.WcidSummonRefillCharm); + return charm != null && inv.CharmStatus(charm) == IltTri.On; + } + + public bool MasteryCharmActive() + { + if (_ctx.Options.IsOff(IltFeature.UniversalMastery)) return false; + var inv = _ctx.Inventory; + if (inv.PlayerBool(IltInventory.BoolUniversalMasteryActive)) return true; + var charm = inv.FindByWcid(IltInventory.WcidUniversalMasteryCharm); + return charm != null && inv.CharmStatus(charm) == IltTri.On; + } + + /// + /// Summon from an empty essence (spends banked pyreals) only when the player opted in, the refill + /// charm is active, and the server has positively confirmed the feature: either the feature check + /// reported pet_refill on, or the server stamped the player's refill bool. Pump thread. + /// + internal bool ComputeAllowSummonOnEmpty() + { + if (!S.RefillFromEmpty || !_ctx.Options.IsIltLikeWorld || !RefillCharmActive()) return false; + bool confirmed = _ctx.Options.IsOn(IltFeature.PetRefill) + || _ctx.Inventory.PlayerBool(IltInventory.BoolPyrealRefillActive); + if (!confirmed) RynthLog.Trace(LogCat.IltPets, "summon-on-empty refused: pet_refill not confirmed by the server"); + return confirmed; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + if (nowMs - _lastGate >= GateMs) + { + _lastGate = nowMs; + _allowSummonOnEmpty = ComputeAllowSummonOnEmpty(); + } + if (nowMs - _lastCharmScan >= CharmScanMs) + { + _lastCharmScan = nowMs; + // Host reads (and appraisal requests) happen here, never on the render thread. + _uiRefillActive = RefillCharmActive(); + _uiMasteryActive = MasteryCharmActive(); + _uiHasCasting = _ctx.Inventory.HasCastingSupplies(); + } + if (nowMs - _lastCaptureThink >= CaptureThinkMs) + { + _lastCaptureThink = nowMs; + TickCapture(nowMs); + } + } + + /// ACECustom MonsterCapture replies: back off after a refuse so lenses aren't burned. Never eats. + public bool OnChat(string text) + { + if (!S.AutoCapture || string.IsNullOrEmpty(text)) return false; + long now = IltHubContext.NowMs; + if (PetCaptureLines.IsSuccess(text)) + { + _captureStatus = "captured"; + _captureThrottle.RecordSuccess(); + _captureCooldownUntil = now + CaptureCooldownMs; + } + else if (ContainsAny(text, + "too strong", + "blind rage", + "cannot be siphoned", + "cannot be captured", + "No creatures nearby", + "already dead", + "already being captured", + "hasn't failed a capture", + "echo has faded", + "Failed to consume")) + { + _captureStatus = "refused: " + Truncate(text, 48); + _captureCooldownUntil = now + CaptureFailBackoffMs; + } + else if (ContainsAny(text, "siphon failed", "lens shatters", "resisted your capture", "resonance fades")) + { + _captureStatus = "failed (creature may enrage)"; + _captureCooldownUntil = now + CaptureFailBackoffMs; + } + return false; + } + + /// A creature's health ratio from the server (RynthPluginOnUpdateHealth; any thread). + public void NoteHealth(uint objectId, float ratio) + { + if (objectId == 0 || float.IsNaN(ratio)) return; + lock (_healthGate) + { + if (_healthRatios.Count >= MaxHealthEntries) _healthRatios.Clear(); + _healthRatios[unchecked((int)objectId)] = Math.Clamp(ratio, 0f, 1f); + } + } + + /// The last health ratio the server sent for a creature, -1 when none. + private float HealthRatio(int id) + { + lock (_healthGate) return _healthRatios.TryGetValue(id, out float v) ? v : -1f; + } + + public void OnLogout() + { + lock (_healthGate) _healthRatios.Clear(); + _captureCooldownUntil = 0; + _captureStatus = "off"; + _captureThrottle.Reset(); + _allowSummonOnEmpty = false; + } + + private static bool ContainsAny(string text, params string[] parts) + { + foreach (string p in parts) + if (text.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0) return true; + return false; + } + + private static string Truncate(string s, int max) => s.Length <= max ? s : s[..(max - 3)] + "..."; + + // ── Auto siphon capture (ACECustom MonsterCapture) ─────────────────────── + + /// + /// When Auto Capture is on, use the chosen siphon lens on the nearest attackable creature within + /// 5 m once ACECustom's health gate is met (≤20% or under 20 HP; Asheron's skips it). The server + /// picks the nearest creature itself, so this fires only when that nearest candidate is already + /// weak enough: a full-health neighbour closer than the wounded target won't waste a lens. + /// + internal void TickCapture(long now) + { + if (!S.AutoCapture) + { + _captureStatus = "off"; + return; + } + if (_ctx.Options.IsOff(RynthIltHub.FeatureMonsterCapture)) + { + _captureStatus = "monster capture disabled on this server"; + return; + } + if (now < _captureCooldownUntil) + { + long left = (_captureCooldownUntil - now + 999) / 1000; + if (!_captureStatus.StartsWith("waiting", StringComparison.Ordinal)) + _captureStatus = $"waiting {left}s"; + return; + } + var inv = _ctx.Inventory; + if (inv.IsBusy) { _captureStatus = "busy"; return; } + + var lens = PetCaptureRules.LensAt(S.CaptureLens); + var lensItem = inv.FindByWcid(lens.Wcid); + if (lensItem == null) + { + _captureStatus = $"no {lens.Name} carried"; + return; + } + + if (!TryFindNearestCaptureTarget(out WorldObject? target, out double distM, out uint curHp, out uint maxHp)) + { + _captureStatus = "no attackable creature within 5 m"; + return; + } + + if (!PetCaptureRules.InRange(distM)) + { + _captureStatus = $"{target!.Name} at {distM:0.0} m (need <={PetCaptureRules.CaptureRangeM:0} m)"; + return; + } + + if (!PetCaptureRules.CanAttempt(lens, curHp, maxHp)) + { + float pct = maxHp > 0 ? curHp * 100f / maxHp : -1f; + _captureStatus = pct >= 0 + ? $"{target!.Name} at {pct:0}% / {curHp} HP (need <={PetCaptureRules.CaptureMaxHealthFraction:P0} or <{PetCaptureRules.CaptureMaxHealthPoints} HP)" + : $"{target!.Name}: health unknown"; + return; + } + + if (!_captureThrottle.MayAttempt(target!.Id, now)) + { + _captureStatus = $"{target.Name}: {PetCaptureThrottle.MaxTriesPerTarget} tries, no capture; left alone for {_captureThrottle.BlockedSecondsLeft(target.Id, now)}s"; + return; + } + + if (!inv.Use(lensItem)) + { + _captureStatus = "UseObject refused"; + return; + } + _captureThrottle.RecordAttempt(target.Id, now); + if (_captureThrottle.Exhausted) + { + // Backstop: this many lenses with no recognized capture means something is off. Stop, don't keep burning them. + S.AutoCapture = false; + RynthLog.Write(LogCat.IltPets, + $"auto-capture: {PetCaptureThrottle.MaxTriesWithoutSuccess} lens uses without a capture reply; auto-capture switched off"); + } + + float shown = maxHp > 0 ? curHp * 100f / maxHp : 0f; + _captureStatus = $"using {lens.Name} on {target.Name} ({shown:0}% / {curHp} HP)"; + _captureCooldownUntil = now + CaptureCooldownMs; + RynthLog.Write(LogCat.IltPets, + $"auto-capture: {lens.Name} -> 0x{target.Id:X8} '{target.Name}' d={distM:0.0}m hp={curHp}/{maxHp}"); + } + + /// + /// Nearest attackable landscape creature within capture range, with vitals from the host when + /// available, else the server's last health ratio (fraction-only gate). A creature with neither + /// is skipped: no health, no capture decision. + /// + private bool TryFindNearestCaptureTarget(out WorldObject? best, out double bestDist, out uint curHp, out uint maxHp) + { + best = null; + bestDist = double.MaxValue; + curHp = maxHp = 0; + var host = _ctx.Host; + var objects = _ctx.Inventory.Cache; + uint playerId = _ctx.Inventory.PlayerId; + if (playerId == 0) return false; + int pid = unchecked((int)playerId); + string ownPrefix = _ctx.CharName.Length > 0 ? _ctx.CharName + "'s " : string.Empty; + + foreach (var wo in objects.GetLandscape()) + { + if (wo == null || wo.Id == pid) continue; + if (wo.ObjectClass != RynthCore.Loot.AcObjectClass.Monster) continue; + if (ownPrefix.Length > 0 && wo.Name.StartsWith(ownPrefix, StringComparison.Ordinal)) continue; + // Skip corpses / non-attackable when the host can tell. + if (host.HasObjectIsAttackable && !host.ObjectIsAttackable(unchecked((uint)wo.Id))) continue; + + double d = objects.Distance(pid, wo.Id); + if (d < 0 || d > PetCaptureRules.CaptureRangeM || d >= bestDist) continue; + + if (!TryReadCreatureVitals(wo.Id, out uint h, out uint mh)) continue; + if (h == 0) continue; // dead + + best = wo; + bestDist = d; + curHp = h; + maxHp = mh; + } + return best != null; + } + + /// + /// Absolute vitals via TryGetTargetVitals when bound; else the health ratio as a 0-1000 scale so + /// only the fraction half of ACECustom's gate can fire. + /// + private bool TryReadCreatureVitals(int id, out uint cur, out uint max) + { + cur = max = 0; + var host = _ctx.Host; + if (host.HasGetTargetVitals + && host.TryGetTargetVitals(unchecked((uint)id), out uint h, out uint mh, out _, out _, out _, out _) + && mh > 0) + { + cur = h; + max = mh; + return true; + } + float ratio = HealthRatio(id); + if (ratio < 0f) return false; + // Synthetic scale: ratio 0.20 -> 200/1000 so IsWeakEnough's fraction half matches. + max = 1000; + cur = (uint)Math.Clamp((int)Math.Round(ratio * 1000f), 1, 1000); + return true; + } + + // ── UI (render thread): the Pets tab's ACECustom sections ──────────────── + + /// The pet charms and the refill opt-in (section "pets-charms"). + public void RenderCharms() + { + ImGui.Separator(); + SafeImGui.TextColored(IltStyle.ColTeal, "Pet charms"); + var o = _ctx.Options; + bool refillOff = o.IsOff(IltFeature.PetRefill); + ImGui.TextUnformatted("Summon Essence Refill: " + (refillOff ? "disabled on this server" : _uiRefillActive ? "ON" : "off / not carried")); + ImGui.BeginDisabled(refillOff); + bool usePath = S.RefillFromEmpty; + if (ImGui.Checkbox("Summon from empty essences while the refill charm is ON (spends banked pyreals)", ref usePath)) + S.RefillFromEmpty = usePath; + ImGui.EndDisabled(); + ImGui.TextUnformatted("Universal Summoning Mastery: " + + (o.IsOff(IltFeature.UniversalMastery) ? "disabled on this server" : _uiMasteryActive ? "ON" : "off / not carried")); + if (!o.IsOff(IltFeature.RequireComps) && !_uiHasCasting) + SafeImGui.TextColored(IltStyle.ColAmber, "No spell components or Infinite Casting Stone carried."); + } + + /// Siphon-lens auto-capture: enable + which lens to use (section "pets-capture"). + public void RenderCapture() + { + ImGui.Separator(); + SafeImGui.TextColored(IltStyle.ColTeal, "Monster capture"); + bool captureOff = _ctx.Options.IsOff(RynthIltHub.FeatureMonsterCapture); + ImGui.BeginDisabled(captureOff); + bool en = S.AutoCapture; + if (ImGui.Checkbox("Auto-capture when a creature is weak enough", ref en)) + { + S.AutoCapture = en; + _ctx.Post(_captureThrottle.Reset); + } + if (ImGui.IsItemHovered()) + { + SafeImGui.SetTooltip( + "Uses the selected siphon lens on the nearest attackable creature within 5 m once it is\n" + + "at or below 20% health or under 20 HP (ACECustom MonsterCapture). Asheron's Lens skips\n" + + "the health gate. Resonance Lens still needs a prior failed capture on the server.\n" + + "Off by default. Stops on its own after 5 tries on one creature (it is left alone for 2 min)\n" + + "or 15 lens uses in a row with no capture."); + } + ImGui.SameLine(); + ImGui.SetNextItemWidth(120); + int lens = Math.Clamp(S.CaptureLens, 0, PetCaptureRules.LensNames.Length - 1); + if (ImGui.Combo("##petcapturelens", ref lens, PetCaptureRules.LensNames, PetCaptureRules.LensNames.Length)) + S.CaptureLens = lens; + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("Which siphon lens to use. Must be carried in your pack."); + ImGui.EndDisabled(); + if (captureOff) + SafeImGui.TextDisabled("Monster capture is disabled on this server."); + else + SafeImGui.TextDisabled("Status: " + _captureStatus); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetBreeding.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetBreeding.cs new file mode 100644 index 0000000..70f9147 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetBreeding.cs @@ -0,0 +1,790 @@ +// IltPetBreeding.cs - The pet breeding tracker: the Breeding sub-tab of RynthAi's Mini Remote Pets tab, +// drawn here (RynthILT.Hub section "pets-breeding"; RynthAi only hosts it), and the same data as JSON +// for other plugins ("RynthILT.Data" v2 GetPetBreedingJson / PetBreedingCommand). +// Originally SilentKelpie's (2026-10-15, his RynthILT 0.2.7); ported into RynthILT 0.3.1 without his +// RynthOracle Pet Breeding tab: breeding is Leaftide's, so only this plugin draws it. +// +// What it does, on Infinite Leaftide only: +// * reads every carried combat essence (appraisal qualities + the LongDesc breeding block) and +// evaluates it with IltBreedingEssence: stud / dam, each gate that fails, when it clears, growth; +// * counts Ivo's supplies and applies a breeding booster to an essence after the player confirms; +// * runs "@breed-debug" (quietly) for the room check and "@dance" to start the ritual; +// * logs breeding chat (ritual, charge spent, birth, guardian, growth, adulthood, imprint); +// * learns this server's rules from its own text (IltBreedingRules) and reports what it sees to +// the Leaftide feature profile (the pet_breeding / pet_maturity bits). +// Essences are read only while someone is looking (the section drawn, or a reader asking for the +// JSON within WatchMs), so an unwatched tracker costs nothing. +// Threading: Tick / OnChat / actions on the pump; Render on the ImGui thread reads only the +// immutable snapshot and posts actions. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Numerics; +using System.Text; +using ImGuiNET; +using RynthCore.Loot; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// Everything the breeding UI and reader JSON show, rebuilt whole on the pump. +/// is a frozen copy of the rules: the render thread plans with it while the pump learns. +internal sealed record BreedingSnapshot( + IReadOnlyList Essences, IReadOnlyList<(BreedSupplyDef Def, long Count)> Supplies, + IReadOnlyList Rules, IReadOnlyList Events, BreedDebugInfo? Debug, DateTime DebugUtc, + IltTri Enabled, IltTri Maturity, IltTri Bond, string Room, int FreeSlots, string Message, double NowUnix, bool Built, + IltBreedingRules RulesView) +{ + public static readonly BreedingSnapshot Empty = new(Array.Empty(), Array.Empty<(BreedSupplyDef, long)>(), + Array.Empty(), Array.Empty(), null, default, IltTri.Unknown, IltTri.Unknown, + IltTri.Unknown, string.Empty, -1, string.Empty, 0, false, new IltBreedingRules(new IltBreedingState())); +} + +internal sealed class IltPetBreeding : IIltFeature +{ + /// Feature bits this tracker reports (IltFeatureCatalog's pet_breeding / pet_maturity rows). + public const string BitBreeding = RynthIltHub.FeaturePetBreeding; + public const string BitMaturity = "pet_maturity"; + + /// ACE commands: the diagnostics reply, and the courtship dance. + public const string DebugCommand = "@breed-debug"; + public const string DanceCommand = "@dance"; + + // ACECustom pet device qualities (AssessmentProperty, sent with the appraisal). + private const uint StrLongDesc = 16; + private const uint IntUseRequiresLevel = 369; + private const uint IntUseLevelRequirement = 364; + private const uint IntBondLevel = 9053; + private const uint IntPotencyStored = 9056; + private const uint IntMaleCharges = 9057; + private const uint IntMutDamage = 9070, IntMutDamageResist = 9071, IntMutCrit = 9072, IntMutVitality = 9073, IntMutPotency = 9074; + private const uint IntMutationCount = 9075; + private const uint IntMaturityKills = 9077; + private const uint FloatNextBreeding = 9056; + private const uint FloatMaleRefresh = 9057; + private const uint FloatIncense = 9058; + private const uint FloatMaturityXpMult = 9059; + private const uint BoolBondAttuned = 9047; + private const uint BoolNeutered = 9051; + private const uint BoolMaleOverride = 50053; + private const uint BoolJuvenile = 50054; + private const uint BoolCatalyst = 50055; + private const uint BoolOffering = 50056; + + /// The tracker reads essences while it was looked at within this long. + private const long WatchMs = 6000; + /// How often a watched tracker re-reads the essences. + private const long ScanMs = 2000; + /// Appraisal requests per scan for essences not yet appraised. + private const int AppraisePerScan = 2; + + private readonly IltHubContext _ctx; + private readonly IltBreedingRules _rules; + private long _watchedAt; // Interlocked: render thread and readers mark it + private long _scannedAt; + private bool _refreshAll; // re-appraise every essence on the next scan (after an event) + private string _message = string.Empty; + private volatile BreedingSnapshot _snap = BreedingSnapshot.Empty; + private volatile string _readerJson = string.Empty; + + // Render-thread selections (ids of carried essences; 0 = none). + private int _studId, _damId, _targetId; + + public IltPetBreeding(IltHubContext ctx) + { + _ctx = ctx; + _rules = new IltBreedingRules(ctx.State.Pet.Breeding); + } + + /// The rules (tests and the controller). + internal IltBreedingRules Rules => _rules; + + /// The latest snapshot (any thread). + public BreedingSnapshot Snapshot => _snap; + + /// Someone is looking: keep the essences fresh for a while (any thread). + public void MarkWatched() => System.Threading.Interlocked.Exchange(ref _watchedAt, IltHubContext.NowMs); + + /// The reader JSON ("RynthILT.Data" GetPetBreedingJson); reading it marks the tracker watched. Any thread. + public string ReaderJson + { + get { MarkWatched(); return _readerJson; } + } + + private static double UnixNow => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000.0; + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + if (nowMs - System.Threading.Interlocked.Read(ref _watchedAt) > WatchMs) return; + if (_scannedAt != 0 && nowMs - _scannedAt < ScanMs) return; + _scannedAt = nowMs; + Scan(); + } + + public bool OnChat(string text) + { + if (string.IsNullOrEmpty(text)) return false; + DateTime utc = DateTime.UtcNow; + bool changed = _rules.LearnAll(IltBreedingRules.FromChat(text), utc); + foreach (string raw in text.Split('\n')) + { + string line = raw.Trim(); + string? kind = EventKind(line); + if (kind == null) continue; + _rules.AddEvent(kind, line, utc); + changed = true; + if (kind is "ritual" or "birth" or "charge") _ctx.Options.Set(BitBreeding, IltTri.On); + if (kind is "growth" or "adult") + { + _ctx.Options.Set(BitMaturity, IltTri.On); + if (IltBreedingRules.TryParseGrownInto(line, out int stage, out string name)) _rules.LearnStageName(stage, name); + } + // The essences changed on the server (charges, rest, a baby, growth): read them again soon. + if (kind is not "dance") { _refreshAll = true; _scannedAt = 0; } + } + if (changed) RynthLog.Trace(LogCat.IltPets, "breeding: chat updated rules / events"); + return false; + } + + public void OnLogout() + { + _snap = BreedingSnapshot.Empty; + _readerJson = string.Empty; + _scannedAt = 0; + _message = string.Empty; + } + + /// The event kind of a breeding chat line, or null for any other line. + internal static string? EventKind(string line) + { + if (line.Length == 0) return null; + if (line.StartsWith("The mating ritual has begun between", StringComparison.OrdinalIgnoreCase)) return "ritual"; + if (line.Contains("spent a breeding charge", StringComparison.OrdinalIgnoreCase)) return "charge"; + if (line.Contains("A baby pet has been born", StringComparison.OrdinalIgnoreCase)) return "birth"; + if (line.StartsWith("The union stirs something", StringComparison.OrdinalIgnoreCase)) return "guardian"; + if (line.Contains("yields to its parents", StringComparison.OrdinalIgnoreCase)) return "guardian"; + if (line.Contains("Awakened Blessing", StringComparison.OrdinalIgnoreCase)) return "mutation"; + if (line.Contains("spectral guardian dissolves", StringComparison.OrdinalIgnoreCase)) return "guardian"; + if (line.Contains("has grown into a", StringComparison.OrdinalIgnoreCase)) return "growth"; + if (line.Contains("has reached adulthood", StringComparison.OrdinalIgnoreCase)) return "adult"; + if (line.Contains("has imprinted on you", StringComparison.OrdinalIgnoreCase)) return "imprint"; + if (line.StartsWith("[Breeding] Your pet performs the courtship dance", StringComparison.OrdinalIgnoreCase)) return "dance"; + if (line.StartsWith("You administer the Nurturing Draught", StringComparison.OrdinalIgnoreCase)) return "supply"; + if (line.StartsWith("You have permanently spayed/neutered", StringComparison.OrdinalIgnoreCase)) return "supply"; + return null; + } + + // ── Scan (pump) ───────────────────────────────────────────────────────── + + /// Reads every carried combat essence and the supplies, then rebuilds the snapshot and reader JSON. + private void Scan() + { + IltInventory inv = _ctx.Inventory; + RynthCoreHost host = _ctx.Host; + double now = UnixNow; + DateTime utc = DateTime.UtcNow; + var essences = new List(); + int appraised = 0; + bool sawBlock = false, sawGrowth = false; + + foreach (WorldObject wo in inv.Items()) + { + uint wcid = inv.Wcid(wo); + if (!IltBreedingEssence.IsCombatEssence(wcid) && !LooksLikeEssence(wo, inv)) continue; + + BreedEssenceFacts f = ReadFacts(host, inv, wo, wcid); + if (f.LongDesc.Contains("Sex:", StringComparison.Ordinal)) sawBlock = true; + if (f.LongDesc.Contains("Growth:", StringComparison.Ordinal)) sawGrowth = true; + _rules.LearnAll(IltBreedingRules.FromAppraisal(f.LongDesc, f.MaleRefreshUnix, now), utc); + if (IltBreedingRules.TryParseGrowth(f.LongDesc, out string stageName, out int stage, out _, out _, out _, out _)) + _rules.LearnStageName(stage, stageName); + essences.Add(IltBreedingEssence.Evaluate(f, _rules, now)); + + // Appraise what isn't loaded (a few per scan), or everything after a breeding event. + if ((_refreshAll || !f.HasId) && appraised < (_refreshAll ? 32 : AppraisePerScan) && inv.RequestAppraisal(wo)) + appraised++; + } + _refreshAll = false; + + // The server only writes the breeding block while breeding is on: seeing it is the server saying so. + if (sawBlock) _ctx.Options.Set(BitBreeding, IltTri.On); + if (sawGrowth) _ctx.Options.Set(BitMaturity, IltTri.On); + + essences.Sort((a, b) => + { + int c = b.Ready.CompareTo(a.Ready); + if (c != 0) return c; + c = b.Male.CompareTo(a.Male); + return c != 0 ? c : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); + }); + + var supplies = new List<(BreedSupplyDef, long)>(IltBreedingSupplies.All.Length); + foreach (BreedSupplyDef s in IltBreedingSupplies.All) supplies.Add((s, inv.CountByWcid(s.Wcid))); + + IltBreedingState st = _rules.State; + BreedDebugInfo? debug = st.LastDebug.Count > 0 ? IltBreedingRules.ParseDebug(st.LastDebug) : null; + var events = st.Log.Select(e => new IltBreedingEvent { Utc = e.Utc, Kind = e.Kind, Text = e.Text }).ToArray(); + + var snap = new BreedingSnapshot(essences, supplies, _rules.All(), events, debug, st.LastDebugUtc, + EnabledState(), _ctx.Options.Get(BitMaturity), _ctx.Options.Get(IltFeature.PetBond), + _rules.RoomText(), inv.FreeMainPackSlots(), _message, now, true, _rules.Frozen()); + _snap = snap; + _readerJson = BuildJson(snap, _rules, _ctx.Options.WorldName); + } + + /// The pet_breeding state the Leaftide profile shows (reported, else the ILT profile's "on"). + private IltTri EnabledState() + { + IltTri t = _ctx.Options.Get(BitBreeding); + return t != IltTri.Unknown ? t : _ctx.Options.IsIltLikeWorld ? IltTri.On : IltTri.Unknown; + } + + /// An essence outside the WCID table (a new family) that the server gave a breeding block. + private static bool LooksLikeEssence(WorldObject wo, IltInventory inv) + => wo.Name.EndsWith("Essence", StringComparison.OrdinalIgnoreCase) + && inv.Str(wo, StrLongDesc).Contains("Sex:", StringComparison.Ordinal); + + private static BreedEssenceFacts ReadFacts(RynthCoreHost host, IltInventory inv, WorldObject wo, uint wcid) + { + uint id = unchecked((uint)wo.Id); + var f = new BreedEssenceFacts + { + Id = wo.Id, + Name = wo.Name, + Wcid = wcid, + HasId = inv.HasAppraisal(wo), + Bond = inv.Int(wo, IntBondLevel), + PotencyStored = inv.Int(wo, IntPotencyStored), + MutDamage = inv.Int(wo, IntMutDamage), + MutDamageResist = inv.Int(wo, IntMutDamageResist), + MutCrit = inv.Int(wo, IntMutCrit), + MutVitality = inv.Int(wo, IntMutVitality), + MutPotency = inv.Int(wo, IntMutPotency), + MutationCount = inv.Int(wo, IntMutationCount), + Neutered = TryBool(host, id, BoolNeutered, out bool n) && n, + JuvenileFlag = TryBool(host, id, BoolJuvenile, out bool j) && j, + Catalyst = TryBool(host, id, BoolCatalyst, out bool c) && c, + Offering = TryBool(host, id, BoolOffering, out bool o) && o, + Attuned = TryBool(host, id, BoolBondAttuned, out bool a) && a, + NextBreedUnix = TryDouble(host, id, FloatNextBreeding), + MaleRefreshUnix = TryDouble(host, id, FloatMaleRefresh), + Incense = TryDouble(host, id, FloatIncense), + MaturityXpMult = TryDouble(host, id, FloatMaturityXpMult), + LongDesc = inv.Str(wo, StrLongDesc), + }; + f.UseLevel = inv.Int(wo, IntUseRequiresLevel); + if (f.UseLevel <= 0) f.UseLevel = inv.Int(wo, IntUseLevelRequirement); + if (TryBool(host, id, BoolMaleOverride, out bool male)) f.MaleOverride = male; + // Absent and 0 differ for these two: absent = never bred / a full stud. + f.MaturityKills = TryInt(host, id, IntMaturityKills, out int kills) ? kills : -1; + f.MaleCharges = TryInt(host, id, IntMaleCharges, out int charges) ? charges : -1; + return f; + } + + private static bool TryBool(RynthCoreHost host, uint id, uint stype, out bool v) + { + v = false; + return host.HasGetObjectBoolProperty && host.TryGetObjectBoolProperty(id, stype, out v); + } + + private static bool TryInt(RynthCoreHost host, uint id, uint stype, out int v) + { + v = 0; + return host.HasGetObjectIntProperty && host.TryGetObjectIntProperty(id, stype, out v); + } + + private static double TryDouble(RynthCoreHost host, uint id, uint stype) + => host.HasGetObjectDoubleProperty && host.TryGetObjectDoubleProperty(id, stype, out double v) ? v : 0; + + // ── Actions (pump) ────────────────────────────────────────────────────── + + /// Re-appraises every essence and rescans. + public void RefreshAll() + { + _refreshAll = true; + _scannedAt = 0; + MarkWatched(); + } + + /// Runs "@breed-debug" quietly and keeps its reply (the room check, partners nearby). + public void RequestDebug() + { + if (_ctx.Capture.IsPending(DebugCommand)) return; + _message = "Asking the server for breeding diagnostics..."; + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = DebugCommand, + IsResponseLine = IltBreedingRules.IsDebugLine, + IsTerminator = IltBreedingRules.IsDebugEnd, + IdleEndMs = 1500, + FirstLineTimeoutMs = 8000, + Eat = true, + OnComplete = ApplyDebug, + }); + _scannedAt = 0; + } + + private void ApplyDebug(IltChatResult r) + { + if (r.UnknownCommand) { _message = "This server has no @breed-debug (no pet breeding here)."; _ctx.Options.Set(BitBreeding, IltTri.Off); return; } + if (r.NotSent) { _message = "This RynthCore can't send chat commands."; return; } + if (r.Lines.Count == 0) { _message = "No reply to @breed-debug."; return; } + DateTime utc = DateTime.UtcNow; + IltBreedingState st = _rules.State; + st.LastDebug = new List(r.Lines); + st.LastDebugUtc = utc; + foreach (string l in r.Lines) _rules.LearnAll(IltBreedingRules.FromChat(l), utc); + BreedDebugInfo d = IltBreedingRules.ParseDebug(r.Lines); + if (d.Enabled.HasValue) _ctx.Options.Set(BitBreeding, d.Enabled.Value ? IltTri.On : IltTri.Off); + _message = d.Enabled == false ? "The server says breeding is switched off." + : d.LocationOk == true ? $"You're in the breeding room. Partners nearby: {Math.Max(0, d.Partners)}." + : d.LocationOk == false ? $"Not in the breeding room ({_rules.RoomText()})." + : "Diagnostics read."; + _rules.AddEvent("debug", _message, utc); + _scannedAt = 0; + } + + /// Starts the courtship dance ("@dance"); the breed happens when a partner dances in time. + public void Dance() + { + if (!_ctx.Host.HasInvokeChatParser) { _message = "This RynthCore can't send chat commands."; return; } + _ctx.Host.InvokeChatParser(DanceCommand); + _message = $"Danced. Your partner must *dance* within {_rules.Get(IltBreedingRules.DanceWindow):0.#}s with their pet in the same room."; + _scannedAt = 0; + } + + /// + /// Uses a supply on a carried essence, re-checking both are still here and that the server would + /// take it. Returns a message for the UI. Called after the player confirmed. + /// + public string ApplySupply(string key, int essenceId) + { + BreedSupplyDef? def = IltBreedingSupplies.Find(key); + if (def == null || !def.Apply) return _message = "That supply isn't applied from here."; + IltInventory inv = _ctx.Inventory; + WorldObject? item = inv.FindByWcid(def.Wcid); + if (item == null) return _message = $"No {def.Name} in your pack."; + BreedEssence? e = _snap.Essences.FirstOrDefault(x => x.Id == essenceId); + if (e == null || !inv.Items().Any(wo => wo.Id == essenceId)) return _message = "That essence isn't in your pack any more."; + string? refuse = IltBreedingSupplies.RefuseReason(def, e, _rules); + if (refuse != null) return _message = refuse; + if (inv.IsBusy) return _message = "You're busy; try again in a moment."; + bool sent = inv.UseOn(item, unchecked((uint)essenceId)); + _message = sent ? $"Used {def.Name} on {e.Name}." : $"Couldn't use {def.Name} (the engine refused)."; + if (sent) _rules.AddEvent("supply", _message, DateTime.UtcNow); + RefreshAll(); + return _message; + } + + /// + /// A reader's verb line ("RynthILT.Data" PetBreedingCommand): refresh, debug, dance, + /// or "apply <supplyKey> <essenceId>" (the reader confirmed it with the player). Pump thread. + /// + public void RunVerb(string line) + { + string[] parts = (line ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 0) return; + switch (parts[0].ToLowerInvariant()) + { + case "refresh": RefreshAll(); break; + case "debug": RequestDebug(); break; + case "dance": Dance(); break; + case "apply" when parts.Length == 3 && int.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int id): + ApplySupply(parts[1], id); + break; + default: + RynthLog.Trace(LogCat.IltPets, $"breeding: unknown reader verb '{line}'"); + break; + } + } + + // ── Reader JSON ───────────────────────────────────────────────────────── + + /// The reader JSON (Plugins/Shared/RynthIltDataApi.cs header has the shape). + internal static string BuildJson(BreedingSnapshot s, IltBreedingRules r, string world) + { + var sb = new StringBuilder(4096); + sb.Append("{\"available\":true"); + Str(sb, "world", world); + Str(sb, "enabled", TriText(s.Enabled)); + Str(sb, "maturity", TriText(s.Maturity)); + Str(sb, "bond", TriText(s.Bond)); + Str(sb, "room", s.Room); + sb.Append(",\"freeSlots\":").Append(s.FreeSlots); + Str(sb, "message", s.Message); + + sb.Append(",\"essences\":["); + for (int i = 0; i < s.Essences.Count; i++) + { + BreedEssence e = s.Essences[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"id\":").Append(e.Id); + Str(sb, "name", e.Name); + Str(sb, "sex", e.Male ? "M" : "F"); + sb.Append(",\"tier\":").Append(e.Tier).Append(",\"bond\":").Append(e.Bond); + sb.Append(",\"ready\":").Append(e.Ready ? "true" : "false"); + Str(sb, "status", e.Status); + double readyIn = e.ReadyAtUnix > s.NowUnix ? e.ReadyAtUnix - s.NowUnix : 0; + sb.Append(",\"readyIn\":").Append((long)Math.Ceiling(readyIn)); + sb.Append(",\"charges\":").Append(e.Charges).Append(",\"chargesMax\":").Append(e.ChargesMax); + sb.Append(",\"juvenile\":").Append(e.Juvenile ? "true" : "false"); + Str(sb, "stage", e.StageName); + sb.Append(",\"kills\":").Append(e.Kills).Append(",\"killsRequired\":").Append(e.KillsRequired); + sb.Append(",\"mutations\":").Append(e.StatMutations).Append(",\"potencyMutations\":").Append(e.MutP); + Arr(sb, "problems", e.Problems); + Arr(sb, "boosters", e.Boosters); + sb.Append('}'); + } + sb.Append(']'); + + // Ready pairings, best odds first (the fewest inherited mutations keeps the decay low). + var studs = s.Essences.Where(e => e.Male && e.Ready).ToList(); + var dams = s.Essences.Where(e => !e.Male && e.Ready).ToList(); + var pairs = new List<(BreedEssence Stud, BreedEssence Dam, BreedPairPlan Plan)>(); + foreach (BreedEssence st in studs) + foreach (BreedEssence d in dams) + pairs.Add((st, d, IltBreedingPlanner.Plan(st, d, r))); + pairs.Sort((a, b) => b.Plan.ChanceBest.CompareTo(a.Plan.ChanceBest)); + sb.Append(",\"pairs\":["); + for (int i = 0; i < pairs.Count && i < 6; i++) + { + if (i > 0) sb.Append(','); + sb.Append('{'); + Str(sb, "stud", pairs[i].Stud.Name, first: true); + Str(sb, "dam", pairs[i].Dam.Name); + sb.Append(",\"chanceBest\":").Append(pairs[i].Plan.ChanceBest.ToString("0.####", CultureInfo.InvariantCulture)); + sb.Append(",\"chanceWorst\":").Append(pairs[i].Plan.ChanceWorst.ToString("0.####", CultureInfo.InvariantCulture)); + sb.Append(",\"inheritMin\":").Append(pairs[i].Plan.InheritMin).Append(",\"inheritMax\":").Append(pairs[i].Plan.InheritMax); + sb.Append('}'); + } + sb.Append(']'); + + sb.Append(",\"supplies\":["); + for (int i = 0; i < s.Supplies.Count; i++) + { + (BreedSupplyDef def, long count) = s.Supplies[i]; + if (i > 0) sb.Append(','); + sb.Append('{'); + Str(sb, "key", def.Key, first: true); + Str(sb, "name", def.Name); + Str(sb, "effect", def.Effect); + sb.Append(",\"count\":").Append(count).Append(",\"price\":").Append(def.Price); + sb.Append(",\"apply\":").Append(def.Apply ? "true" : "false"); + // Essences the server would take this on now (the reader's Use buttons). + var targets = def.Apply && count > 0 + ? s.Essences.Where(e => IltBreedingSupplies.RefuseReason(def, e, r) == null).Select(e => e.Id).ToList() + : new List(); + sb.Append(",\"targets\":[").Append(string.Join(',', targets)).Append(']'); + sb.Append('}'); + } + sb.Append(']'); + + sb.Append(",\"rules\":["); + for (int i = 0; i < s.Rules.Count; i++) + { + BreedRuleValue v = s.Rules[i]; + if (i > 0) sb.Append(','); + sb.Append('{'); + Str(sb, "label", v.Def.Label, first: true); + Str(sb, "value", IltBreedingRules.Format(v)); + Str(sb, "source", IltBreedingRules.SourceText(v.Source)); + Str(sb, "help", v.Def.Help); + sb.Append('}'); + } + sb.Append(']'); + + sb.Append(",\"events\":["); + int start = Math.Max(0, s.Events.Count - 20); + for (int i = s.Events.Count - 1; i >= start; i--) + { + IltBreedingEvent e = s.Events[i]; + if (i != s.Events.Count - 1) sb.Append(','); + sb.Append('{'); + Str(sb, "when", e.Utc.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture), first: true); + Str(sb, "kind", e.Kind); + Str(sb, "text", e.Text); + sb.Append('}'); + } + sb.Append(']'); + + if (s.Debug != null) + { + BreedDebugInfo d = s.Debug; + sb.Append(",\"debug\":{"); + Str(sb, "when", s.DebugUtc.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture), first: true); + Str(sb, "enabled", d.Enabled == null ? "unknown" : d.Enabled.Value ? "on" : "off"); + Str(sb, "location", d.Location); + Str(sb, "match", d.LocationOk == null ? "" : d.LocationOk.Value ? "valid" : "invalid"); + Str(sb, "pet", d.ActivePet); + Str(sb, "sex", d.PetSex); + sb.Append(",\"partners\":").Append(d.Partners); + sb.Append('}'); + } + sb.Append('}'); + return sb.ToString(); + } + + private static string TriText(IltTri t) => t switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" }; + + private static void Str(StringBuilder sb, string name, string? value, bool first = false) + { + if (!first) sb.Append(','); + sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"'); + } + + private static void Arr(StringBuilder sb, string name, IReadOnlyList values) + { + sb.Append(",\"").Append(name).Append("\":["); + for (int i = 0; i < values.Count; i++) + { + if (i > 0) sb.Append(','); + sb.Append('"').Append(IltStyle.JsonEscape(values[i])).Append('"'); + } + sb.Append(']'); + } + + // ── UI (render thread): Mini Remote > Pets > Breeding ─────────────────── + + /// The Breeding tab's body (RynthIltHub.SectionPetBreeding). + public void RenderSection() + { + MarkWatched(); + BreedingSnapshot s = _snap; + + RenderHeader(s); + if (!s.Built) + { + ImGui.TextDisabled("Reading your essences..."); + return; + } + ImGui.Separator(); + RenderEssences(s); + RenderPlanner(s); + RenderSupplies(s); + RenderRules(s); + RenderEvents(s); + RenderGuide(s); + } + + private void RenderHeader(BreedingSnapshot s) + { + Vector4 col = s.Enabled == IltTri.Off ? IltStyle.ColHp : IltStyle.ColTeal; + SafeImGui.TextColored(col, s.Enabled switch + { + IltTri.Off => "Pet breeding is off on this server.", + IltTri.On => $"Pet breeding: on. Breeding room: {s.Room}.", + _ => "Pet breeding: not confirmed yet (run Diagnostics in the breeding room).", + }); + if (s.Bond == IltTri.Off) SafeImGui.TextColored(IltStyle.ColAmber, "Pet bond is off here, so bond can't reach the breeding minimum."); + + if (ImGui.SmallButton("Refresh##brrefresh")) _ctx.Post(RefreshAll); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-appraise every essence (charges, rest timers, bond, growth)."); + ImGui.SameLine(); + if (ImGui.SmallButton("Diagnostics##brdebug")) _ctx.Post(RequestDebug); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("@breed-debug: are you in the breeding room, your summoned pet, partners nearby (reply hidden, shown here)."); + ImGui.SameLine(); + if (ImGui.SmallButton("Dance##brdance")) + _ctx.Confirm("Courtship dance", + "Dance now? If your partner dances within the window with both pets summoned in the same room, the breed happens:" + + " the stud spends a charge, the dam rests, incense is used up and the baby goes to the dam's owner.", + Dance, "Dance"); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("@dance (the same as typing *dance*). Both owners must dance within the window."); + + if (s.Message.Length > 0) SafeImGui.TextDisabled(s.Message); + if (s.FreeSlots == 0) SafeImGui.TextColored(IltStyle.ColAmber, "Your main pack is full: as the dam's owner you couldn't receive the baby."); + } + + private void RenderEssences(BreedingSnapshot s) + { + int ready = s.Essences.Count(e => e.Ready); + if (!ImGui.CollapsingHeader($"Essences ({ready} ready of {s.Essences.Count})###bress", ImGuiTreeNodeFlags.DefaultOpen)) return; + if (s.Essences.Count == 0) + { + ImGui.TextDisabled("No combat pet essences in your pack."); + return; + } + + const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.ScrollY; + float h = Math.Min(260f, 26f + s.Essences.Count * ImGui.GetTextLineHeightWithSpacing()); + if (!ImGui.BeginTable("##brtable", 6, flags, new Vector2(0, h))) return; + ImGui.TableSetupScrollFreeze(0, 1); + ImGui.TableSetupColumn("Essence", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Sex", ImGuiTableColumnFlags.WidthFixed, 34); + ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 34); + ImGui.TableSetupColumn("Bond", ImGuiTableColumnFlags.WidthFixed, 38); + ImGui.TableSetupColumn("Breeding", ImGuiTableColumnFlags.WidthFixed, 130); + ImGui.TableSetupColumn("Muts", ImGuiTableColumnFlags.WidthFixed, 40); + ImGui.TableHeadersRow(); + for (int i = 0; i < s.Essences.Count; i++) + { + BreedEssence e = s.Essences[i]; + ImGui.PushID(i); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + bool picked = e.Id == _studId || e.Id == _damId; + if (ImGui.Selectable(SafeText(e.Name) + "##sel", picked, ImGuiSelectableFlags.SpanAllColumns)) + { + if (e.Male) _studId = e.Id; else _damId = e.Id; + _targetId = e.Id; + } + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(Tooltip(e)); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(e.Male ? "M" : "F"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(e.Tier > 0 ? e.Tier.ToString(CultureInfo.InvariantCulture) : "?"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(e.HasId ? e.Bond.ToString(CultureInfo.InvariantCulture) : "?"); + ImGui.TableNextColumn(); + Vector4 col = e.Ready ? IltStyle.ColGreen + : e.Gate is BreedGate.Resting or BreedGate.NoCharges or BreedGate.Growing or BreedGate.NeedsId ? IltStyle.ColAmber + : IltStyle.ColTextMute; + SafeImGui.TextColored(col, e.Status); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(e.MutP > 0 ? $"{e.StatMutations}+{e.MutP}p" : e.StatMutations.ToString(CultureInfo.InvariantCulture)); + ImGui.PopID(); + } + ImGui.EndTable(); + ImGui.TextDisabled("Click a male to pick the stud, a female for the dam (and the supply target). Hover for details."); + } + + private static string Tooltip(BreedEssence e) + { + var sb = new StringBuilder(); + sb.Append(e.Name).Append('\n').Append(e.Role).Append(", tier ").Append(e.Tier > 0 ? e.Tier.ToString(CultureInfo.InvariantCulture) : "?") + .Append(", bond ").Append(e.Bond); + if (e.Male) sb.Append("\nCharges ").Append(e.Charges).Append('/').Append(e.ChargesMax); + if (e.Bred) sb.Append(e.Juvenile ? $"\nGrowing: {e.StageName}, {e.KillsToNext} kills to the next stage, {Math.Max(0, e.KillsRequired - e.Kills)} to Adult" : "\nBred: Adult"); + if (e.Unbound) sb.Append("\nUnbound: imprints on the first character to summon it."); + sb.Append($"\nMutations: damage {e.MutD}, damage resist {e.MutDR}, crit {e.MutC}, vitality {e.MutV}, potency {e.MutP}"); + if (e.Boosters.Count > 0) sb.Append("\nBoosters: ").Append(string.Join(", ", e.Boosters)); + foreach (string p in e.Problems) sb.Append("\n- ").Append(p); + return sb.ToString(); + } + + private void RenderPlanner(BreedingSnapshot s) + { + if (!ImGui.CollapsingHeader("Pair planner###brplan")) return; + BreedEssence? stud = s.Essences.FirstOrDefault(e => e.Id == _studId && e.Male); + BreedEssence? dam = s.Essences.FirstOrDefault(e => e.Id == _damId && !e.Male); + PickCombo("Stud##brstud", s.Essences.Where(e => e.Male).ToList(), stud, id => _studId = id); + PickCombo("Dam##brdam", s.Essences.Where(e => !e.Male).ToList(), dam, id => _damId = id); + if (stud == null || dam == null) + { + ImGui.TextDisabled("Pick a stud and a dam (yours, or an alt's carried here) to see the odds."); + ImGui.TextDisabled("Breeding needs two owners: each dances with their own summoned pet."); + return; + } + BreedPairPlan p = IltBreedingPlanner.Plan(stud, dam, s.RulesView); + if (p.CanBreed) SafeImGui.TextColored(IltStyle.ColGreen, "Both are ready to breed."); + foreach (string b in p.Blockers) SafeImGui.TextColored(IltStyle.ColAmber, b); + SafeImGui.Text($"Stat mutation chance: {Pct(p.ChanceWorst)} to {Pct(p.ChanceBest)} (baby inherits {p.InheritMin}-{p.InheritMax} stat mutations)"); + SafeImGui.Text($"Potency mutation chance: {Pct(p.PotencyChance)}" + (p.Incense > 0 ? $"; incense +{p.Incense * 100:0.#}%" : "")); + foreach (string n in p.Notes) SafeImGui.BulletText(n); + } + + private static void PickCombo(string label, List list, BreedEssence? current, Action set) + { + ImGui.SetNextItemWidth(260); + if (!ImGui.BeginCombo(label, current != null ? SafeText(current.Name) : "(none)")) return; + foreach (BreedEssence e in list) + { + if (ImGui.Selectable($"{SafeText(e.Name)} - {SafeText(e.Status)}##{e.Id}", current != null && current.Id == e.Id)) set(e.Id); + } + ImGui.EndCombo(); + } + + private void RenderSupplies(BreedingSnapshot s) + { + long carried = s.Supplies.Sum(x => x.Count); + if (!ImGui.CollapsingHeader($"Supplies ({carried} carried)###brsup")) return; + BreedEssence? target = s.Essences.FirstOrDefault(e => e.Id == _targetId); + PickCombo("Use on##brtarget", s.Essences.ToList(), target, id => _targetId = id); + ImGui.TextDisabled("Ivo sells these at the Seedy Motel. Boosters are spent by the essence's next breed."); + for (int i = 0; i < s.Supplies.Count; i++) + { + (BreedSupplyDef def, long count) = s.Supplies[i]; + ImGui.PushID("sup" + i); + Vector4 col = count > 0 ? IltStyle.ColGreen : IltStyle.ColTextMute; + SafeImGui.TextColored(col, $"{count,3} {def.Name}"); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"{def.Effect}\nIvo's price: {IltBreedingSupplies.PriceText(def.Price)} pyreals"); + if (def.Apply && count > 0 && target != null) + { + ImGui.SameLine(300); + string? refuse = IltBreedingSupplies.RefuseReason(def, target, s.RulesView); + if (refuse != null) + { + ImGui.TextDisabled("can't"); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(refuse); + } + else if (ImGui.SmallButton("Use")) + { + string key = def.Key; + int id = target.Id; + _ctx.Confirm("Use " + def.Name, + $"Use {def.Name} on {target.Name}? {def.Effect}{IltBreedingSupplies.Warning(def, target)}", + () => ApplySupply(key, id), "Use"); + } + } + ImGui.PopID(); + } + } + + private void RenderRules(BreedingSnapshot s) + { + if (!ImGui.CollapsingHeader("Server rules###brrules")) return; + ImGui.TextDisabled("Values this server showed win over the ILT profile, which wins over ACE's defaults."); + foreach (BreedRuleValue v in s.Rules) + { + SafeImGui.Text(v.Def.Label); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(v.Def.Help); + ImGui.SameLine(200); + SafeImGui.Text(IltBreedingRules.Format(v)); + ImGui.SameLine(280); + SafeImGui.TextColored(v.Source == BreedRuleSource.Server ? IltStyle.ColGreen : IltStyle.ColTextMute, + IltBreedingRules.SourceText(v.Source)); + } + if (s.Debug != null) + { + ImGui.Separator(); + SafeImGui.TextDisabled($"Last diagnostics ({s.DebugUtc.ToLocalTime():g}):"); + BreedDebugInfo d = s.Debug; + if (d.Location.Length > 0) SafeImGui.BulletText("You: " + d.Location); + if (d.LocationOk.HasValue) SafeImGui.BulletText(d.LocationOk.Value ? "In the breeding room" : "Not in the breeding room"); + if (d.ActivePet.Length > 0) SafeImGui.BulletText("Pet: " + d.ActivePet + (d.PetSex.Length > 0 ? " (" + d.PetSex + ")" : "")); + if (d.Partners >= 0) SafeImGui.BulletText($"Partners nearby: {d.Partners}"); + } + } + + private static void RenderEvents(BreedingSnapshot s) + { + if (!ImGui.CollapsingHeader($"Recent events ({s.Events.Count})###brevents")) return; + if (s.Events.Count == 0) ImGui.TextDisabled("Nothing yet: rituals, births, growth and charges land here."); + for (int i = s.Events.Count - 1, shown = 0; i >= 0 && shown < 20; i--, shown++) + { + IltBreedingEvent e = s.Events[i]; + SafeImGui.TextDisabled(e.Utc.ToLocalTime().ToString("MM-dd HH:mm", CultureInfo.InvariantCulture)); + ImGui.SameLine(90); + SafeImGui.TextWrapped(e.Text); + } + } + + private static void RenderGuide(BreedingSnapshot s) + { + if (!ImGui.CollapsingHeader("How to breed###brguide")) return; + SafeImGui.BulletText($"Go to the Seedy Motel (portal by Prof. Ruggan in Lin, 54.7S 73.5E); breeding room {s.Room}."); + SafeImGui.BulletText("Two owners: one summons a male (stud), the other a female (dam). Both pets in the same room."); + SafeImGui.BulletText("Both parents: tier 100+, bond 100+, adult, not shiny, not neutered. The stud needs a charge, the dam must have rested."); + SafeImGui.BulletText("Both owners *dance* (or @dance) within a few seconds. The baby goes to the dam's owner (free pack slot needed)."); + SafeImGui.BulletText("A mating guardian may rise: both parents kill it in time for an Awakened Blessing mutation."); + SafeImGui.BulletText("The baby imprints on whoever summons it first, and grows up with kills (Nurturing Draught doubles the credit)."); + } + + private static string Pct(double v) => (v * 100).ToString("0.##", CultureInfo.InvariantCulture) + "%"; + + /// Item names go into ImGui labels, where "##" would start the hidden id. + private static string SafeText(string s) => (s ?? string.Empty).Replace("#", ""); +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetCaptureRules.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetCaptureRules.cs new file mode 100644 index 0000000..c978268 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetCaptureRules.cs @@ -0,0 +1,166 @@ +// IltPetCaptureRules.cs — ACECustom MonsterCapture thresholds for siphon lenses (pure; no host). +// Moved from RynthAi's Pets tab (MiniRemote/PetCaptureRules.cs) 2026-10-20 with the auto-capture +// itself (IltPetAutomation): monster capture is ACECustom's, so it is RynthILT's. +// +// Copied from ACECustom Source/ACE.Server/Entity/MonsterCapture.cs so the client can tell when +// a creature is weak enough to siphon before using a lens. Keep these numbers in lockstep with +// the server: CaptureMaxHealthFraction / CaptureMaxHealthPoints / CaptureRangeM and the lens +// WCID table in PetGuideController. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One siphon lens the Pets tab can auto-use (name, WCID, whether health is gated). +internal readonly struct PetCaptureLens +{ + public PetCaptureLens(string name, uint wcid, bool bypassesHealthGate) + { + Name = name; + Wcid = wcid; + BypassesHealthGate = bypassesHealthGate; + } + + public string Name { get; } + public uint Wcid { get; } + /// Asheron's (and Debug) lenses skip the 20% / 20 HP gate. + public bool BypassesHealthGate { get; } +} + +/// +/// When a siphon lens can be used, matching ACECustom MonsterCapture.UseCaptureCrystal. +/// A creature is weak enough when its health fraction is ≤ 20% OR its current HP is under 20 +/// (whichever comes first). Asheron's Lens skips that check. +/// +internal static class PetCaptureRules +{ + /// A lens targets the nearest attackable creature within this many meters. + public const float CaptureRangeM = 5.0f; + + /// Siphon once at or below this fraction of max health… + public const float CaptureMaxHealthFraction = 0.20f; + + /// …or below this many hit points (the gate is OR with the fraction). + public const int CaptureMaxHealthPoints = 20; + + /// + /// Lenses the player can pick for auto-capture. Order is the combo index. + /// Resonance needs a prior failed capture (server-side); Asheron's bypasses the health gate. + /// + public static readonly PetCaptureLens[] Lenses = + { + new("Flawed Siphon Lens", 78780001, bypassesHealthGate: false), + new("Pristine Siphon Lens", 78780002, bypassesHealthGate: false), + new("Perfect Siphon Lens", 78780003, bypassesHealthGate: false), + new("Resonance Lens", 78780010, bypassesHealthGate: false), + new("Asheron's Lens", 78780012, bypassesHealthGate: true), + }; + + /// Combo labels for the Pets tab (same order as ). + public static readonly string[] LensNames = + { + "Flawed", "Pristine", "Perfect", "Resonance", "Asheron's", + }; + + public static PetCaptureLens LensAt(int index) + { + int i = Math.Clamp(index, 0, Lenses.Length - 1); + return Lenses[i]; + } + + /// + /// True when ACECustom would accept a siphon on this creature for a normal (non-bypass) lens. + /// Pass current/max when known; when only a 0–1 ratio is known, pass ratio as current and 1 as max + /// (then only the fraction half of the gate can fire). + /// + public static bool IsWeakEnough(uint currentHp, uint maxHp) + { + if (currentHp == 0) return false; // dead — server refuses + if (maxHp == 0) return false; + float pct = (float)currentHp / maxHp; + // Server: refuse when pct > 0.20 AND current >= 20. Allowed otherwise. + return pct <= CaptureMaxHealthFraction || currentHp < CaptureMaxHealthPoints; + } + + /// Same gate from a 0–1 health ratio only (no absolute HP). Dead / unknown = false. + public static bool IsWeakEnoughRatio(float healthRatio) + { + if (healthRatio <= 0f || healthRatio > 1f) return false; + return healthRatio <= CaptureMaxHealthFraction; + } + + /// True when this lens may be used given the creature's vitals (bypass lenses always, if alive). + public static bool CanAttempt(PetCaptureLens lens, uint currentHp, uint maxHp) + { + if (currentHp == 0) return false; + if (lens.BypassesHealthGate) return maxHp == 0 || currentHp > 0; + return IsWeakEnough(currentHp, maxHp); + } + + /// Distance gate: ACECustom CaptureRangeM. + public static bool InRange(double distanceM) => distanceM >= 0 && distanceM <= CaptureRangeM; +} + +/// +/// A brake on the auto-capture loop. Auto-capture fires a lens every couple of seconds and only stops +/// on reply strings it guesses at, so an unrecognized reply (or a creature the server never lets go of) +/// would burn lenses without end. This caps consecutive tries per target and, as a backstop, consecutive +/// tries over all targets; both reset on a recognized success. Pure: the tests drive it. +/// +internal sealed class PetCaptureThrottle +{ + /// Lens uses on one creature, with no success in between, before it is left alone. + public const int MaxTriesPerTarget = 5; + + /// How long a creature that used up its tries is left alone (ms). + public const long TargetBlockMs = 120_000; + + /// Lens uses over all creatures with no success before auto-capture switches itself off. + public const int MaxTriesWithoutSuccess = 15; + + private readonly Dictionary _tries = new(); + private readonly Dictionary _blockedUntil = new(); + private int _sinceSuccess; + + /// Consecutive lens uses with no recognized success (all targets). + public int TriesWithoutSuccess => _sinceSuccess; + + /// True when the backstop was hit: the caller should switch auto-capture off. + public bool Exhausted => _sinceSuccess >= MaxTriesWithoutSuccess; + + /// False while this target is blocked (it used its tries) or the backstop is hit. + public bool MayAttempt(int targetId, long nowMs) + { + if (Exhausted) return false; + if (_blockedUntil.TryGetValue(targetId, out long until)) + { + if (nowMs < until) return false; + _blockedUntil.Remove(targetId); // block served: a fresh set of tries + _tries.Remove(targetId); + } + return true; + } + + /// Seconds left on this target's block, 0 when it is not blocked. + public long BlockedSecondsLeft(int targetId, long nowMs) + => _blockedUntil.TryGetValue(targetId, out long until) && nowMs < until ? (until - nowMs + 999) / 1000 : 0; + + /// Count a lens use on this target; blocks it once it reaches . + public void RecordAttempt(int targetId, long nowMs) + { + _sinceSuccess++; + int n = _tries.TryGetValue(targetId, out int t) ? t + 1 : 1; + _tries[targetId] = n; + if (n >= MaxTriesPerTarget) _blockedUntil[targetId] = nowMs + TargetBlockMs; + } + + /// A recognized success reply: everything starts over. + public void RecordSuccess() => Reset(); + + public void Reset() + { + _tries.Clear(); + _blockedUntil.Clear(); + _sinceSuccess = 0; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs new file mode 100644 index 0000000..e32b9be --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs @@ -0,0 +1,87 @@ +// IltPetLogs.cs — The ACECustom /pets and /shinies logs, shown in RynthAi's universal Pets tab +// (RynthILT.Hub section "pets-logs"). +// Originally the roster-capture part of SilentKelpie's IltPets (ILT Hub, RynthAi); split out and +// moved to RynthILT 2026-10-13. The Pets tab itself (essence roster, combat / healing / cosmetic +// pets) stayed in RynthAi (MiniRemote/PetsTab.cs): summoning is every server's, these two commands +// are ACECustom's (as are the pet charms, the refill path and siphon capture: IltPetAutomation, +// moved 2026-10-20). +using System; +using System.Collections.Generic; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltPetLogs : IIltFeature +{ + private readonly IltHubContext _ctx; + + public IltPetLogs(IltHubContext ctx) => _ctx = ctx; + + private IltPetState S => _ctx.State.Pet; + + /// Captures /pets or /shinies into the state (quiet). + public void RequestRoster(bool shinies) + { + RynthLog.Trace(LogCat.IltPets, $"RequestRoster(shinies={shinies})"); + string cmd = shinies ? "/shinies" : "/pets"; + if (_ctx.Capture.IsPending(cmd)) return; + string header = shinies ? "Your Shiny Log" : "Your Pet Log"; + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = cmd, + IsResponseLine = t => t.Contains(header, StringComparison.OrdinalIgnoreCase) || IltParse.RosterLine.IsMatch(t), + IsTerminator = t => t.Contains(header + " is empty", StringComparison.OrdinalIgnoreCase), + IdleEndMs = 1500, + FirstLineTimeoutMs = 10000, + Eat = true, + OnComplete = r => + { + if (r.UnknownCommand) { _ctx.Options.Set(shinies ? IltFeature.Shinies : IltFeature.Pets, IltTri.Off); return; } + if (r.Lines.Count == 0) return; + _ctx.Options.Set(shinies ? IltFeature.Shinies : IltFeature.Pets, IltTri.On); + ApplyRoster(shinies, r.Lines); + }, + }); + } + + /// Also used by the login probe tap so the roster fills without a second command. + public void ApplyRoster(bool shinies, List lines) + { + RynthLog.Trace(LogCat.IltPets, $"ApplyRoster(shinies={shinies}, lines={lines.Count})"); + var list = new List(); + foreach (string l in lines) + { + var m = IltParse.RosterLine.Match(l); + if (m.Success) list.Add(m.Groups[2].Value.Trim()); + } + if (shinies) S.ShinyLog = list; else S.PetLog = list; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) { } + public bool OnChat(string text) => false; + public void OnLogout() { } + + // ── UI (render thread): the Pets tab's last section ───────────────────── + + public void RenderSection() + { + ImGui.Separator(); + RenderRoster("Pet log", false, IltFeature.Pets, S.PetLog); + RenderRoster("Shiny log", true, IltFeature.Shinies, S.ShinyLog); + } + + private void RenderRoster(string label, bool shinies, string key, List list) + { + if (_ctx.Options.IsOff(key)) return; + var snap = list.ToArray(); + if (ImGui.TreeNode($"{label} ({snap.Length})##{key}")) + { + if (ImGui.SmallButton($"Refresh##{key}")) _ctx.Post(() => RequestRoster(shinies)); + foreach (string s in snap) SafeImGui.BulletText(s); + ImGui.TreePop(); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs new file mode 100644 index 0000000..0977bc5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs @@ -0,0 +1,882 @@ +// IltProgression.cs — Augmentation and Enlightenment planners, drawn by the engine's +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// Skills panel (Progression tab) from AppendSnapshotJson; edits arrive via HandleRemote. +// +// Augs : "/aug" levels + the per-server cost rules in IltAugCosts (UB's ILT model by default: +// level i costs base + (i-1)*(base*LP/100), times 1/4/8/16/24 from S1..S4), coins per level. +// Enl : tier material/luminance table, requirement checklist, "/enl" on confirm. The +// server pops its own Yes/No dialog — the host cannot (and must not) click it. +// Optional auto-enlighten is disarmed every session and needs a hard confirm. +// XP : the Skills panel plans attribute/vital raises from the client's exact XP tables; +// this module spends unassigned XP ("/attr") before an auto-enlighten, and owns the +// infinite-attribute raiser (IltAttributeRaiser: server costs from "/xp all", manual +// or timed raises in a chosen order) drawn in the same tab. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltProgression : IIltFeature +{ + // ── Augmentation cost rules ───────────────────────────────────────────── + + /// Per-server aug cost rules (UB's ILT model unless this world was changed). + public IltAugCosts AugCosts { get; } = new(); + + /// The rules for the world we're on. + private IltAugCostProfile AugProfile => AugCosts.For(_ctx.Options.WorldName); + + // ── Enlightenment ─────────────────────────────────────────────────────── + + private const int BaseLevelForEnl = 275; + private const long AutoEnlCooldownMs = 60_000; + private const uint SpellVitae = 666; + + /// Materials for reaching enlightenment level (one step). + public static (string Item, uint Wcid, int Count, decimal Lum) EnlStepCost(int t) + { + if (t <= 5) return ("none", 0, 0, 0); + int count = t - 5; + if (t <= 50) return ("Enlightenment Tokens", IltInventory.WcidEnlToken, count, 0); + if (t <= 150) return ("Enlightenment Tokens", IltInventory.WcidEnlToken, count, t * 100_000_000m); + if (t <= 300) return ("Enlightenment Medallions", IltInventory.WcidEnlMedallion, count, t * 1_000_000_000m); + decimal mult = 1m + 0.5m * ((t - 300 - 1) / 50); + decimal lum = Math.Ceiling(t * 2_000_000_000m * mult); + return t <= 325 ? ("Enlightenment Sigils", IltInventory.WcidEnlSigil, count, lum) + : ("Enlightenment Crests", IltInventory.WcidEnlCrest, count, lum); + } + + // ── XP ────────────────────────────────────────────────────────────────── + + /// /attr abbreviation, display name, attribute stype (0 = vital), vital stype. + private static readonly (string Abbr, string Name, uint Attr, uint Vital)[] Stats = + { + ("str", "Strength", 1, 0), ("end", "Endurance", 2, 0), ("coo", "Coordination", 4, 0), + ("qui", "Quickness", 3, 0), ("foc", "Focus", 5, 0), ("sel", "Self", 6, 0), + ("hea", "Health", 0, 1), ("sta", "Stamina", 0, 3), ("man", "Mana", 0, 5), + }; + + private readonly IltHubContext _ctx; + private readonly Dictionary _augLevels = new(StringComparer.OrdinalIgnoreCase); + private volatile string _augStatus = "not loaded"; + // Opening the Progression tab pulls "/aug" once per login when nothing has loaded the levels yet. + private bool _augAutoTried; + /// Second Refresh current while /aug is already queued or in flight (UB coalesces the same way). + private bool _augRefreshAgain; + /// One silent retry after the login probe left Current empty (chat-hold / ArmsIdle race). + private bool _augProbeRetryDone; + /// Passive /aug window: accept AugLine chat until this tick (like T11's report parser). + private long _augPassiveUntilMs; + + // Cached player facts for the render thread (refreshed in Tick). + private volatile int _enl, _level, _freeSlots; + private long _unassignedXp; + private volatile bool _peace, _hasVitae; + private readonly long[] _enlHave = new long[4]; // tokens, medallions, sigils, crests + // 301-325 sigil chain stock (pack items by name; EnlightenedCoins = bank + pack). Pump thread only. + private IltSigilStock _chain = new(); + private long _lastFactsAt; + private readonly uint[] _enchIds = new uint[256]; + private readonly double[] _enchExp = new double[256]; + + // Auto-enlighten (armed only after the in-session confirm). + private bool _autoArmed; + private long _lastAutoCheck; + private long _lastEnlSentAt = -AutoEnlCooldownMs; + private volatile string _enlStatus = string.Empty; + + // XP spend-before-enlighten loop. + private bool _spending; + private int _spendIdx, _spendSent, _spendNoProgress; + private long _spendLastAt, _spendLastXp; + private Action? _afterSpend; + + /// Infinite-attribute raiser (Progression tab "Attribute raiser" section). + public IltAttributeRaiser Attributes { get; } + + public IltProgression(IltHubContext ctx) + { + _ctx = ctx; + // Never two /attr spenders at once: the raiser waits while the spend-before-/enl loop runs. + Attributes = new IltAttributeRaiser(ctx) { HoldOff = () => _spending }; + } + + private IltCharacterState C => _ctx.State.Character; + + // ── Commands ──────────────────────────────────────────────────────────── + + public void RequestAugs() + { + RynthLog.Trace(LogCat.IltProgression, $"RequestAugs()"); + if (_ctx.Options.IsOff(IltFeature.Aug)) + { + _augStatus = "/aug is off for this world"; + return; + } + // Coalesce: a click during an in-flight /aug (login probe or a prior Refresh) runs again + // when that capture finishes — including via AfterExternalAugCapture for the probe. + if (_ctx.Capture.IsPending("/aug")) + { + _augRefreshAgain = true; + _augStatus = "refresh queued (waiting for current /aug)..."; + return; + } + _augStatus = "loading..."; + _augPassiveUntilMs = IltHubContext.NowMs + 30_000; // also accept lines if capture finishes early + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = "/aug", + IsResponseLine = t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) || IltParse.AugLine.IsMatch(t), + // Idle must not start on the banner alone — chat-hold / pump lag used to finish with 0 level lines. + ArmsIdle = t => IltParse.AugLine.IsMatch(t), + IdleEndMs = 2500, + // Login + chat-hold backlog can push Creature: past the old 15s first-line window. + FirstLineTimeoutMs = 30_000, + Eat = true, + OnComplete = r => + { + if (r.UnknownCommand) + { + _ctx.Options.Set(IltFeature.Aug, IltTri.Off); + _augStatus = "/aug not available"; + _augRefreshAgain = false; + return; + } + ApplyAugLines(r.Lines); + if (r.TimedOut) + { + int have; + lock (_augLevels) have = _augLevels.Count; + if (have == 0) + _augStatus = "timed out waiting for /aug level lines"; + } + DrainAugRefreshAgain(); + }, + }); + } + + /// + /// Login probe finished its "/aug" capture (or another path applied lines). Drains a queued + /// Refresh current and, if the probe left Current empty, retries once. + /// + public void AfterExternalAugCapture() + { + if (DrainAugRefreshAgain()) return; + int have; + lock (_augLevels) have = _augLevels.Count; + if (have > 0 || _augProbeRetryDone || _ctx.Options.IsOff(IltFeature.Aug)) return; + if (_ctx.Capture.IsPending("/aug")) return; + _augProbeRetryDone = true; + RynthLog.Event(LogEvents.IltAugLoad, "aug probe left Current empty — retrying /aug once"); + RequestAugs(); + } + + /// Runs a coalesced Refresh current if one was queued. Returns true when it did. + private bool DrainAugRefreshAgain() + { + if (!_augRefreshAgain) return false; + _augRefreshAgain = false; + RequestAugs(); + return true; + } + + /// Parses "/aug" output (also fed from the login probe and passive chat). + public void ApplyAugLines(List lines) + { + RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines(lines={lines.Count})"); + int n = 0; + foreach (string l in lines) + { + if (TryApplyAugLine(l)) n++; + } + if (n > 0) + { + _augStatus = $"{n} aug types @ {DateTime.Now:t}"; + _augPassiveUntilMs = IltHubContext.NowMs + 8_000; + } + else + { + bool sawBanner = false; + foreach (string l in lines) + { + if (l.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase)) + { sawBanner = true; break; } + } + _augStatus = sawBanner + ? "no level lines yet (banner only — waiting / retry)" + : "no aug lines in reply"; + // Keep the passive reader open so late Creature: lines still fill Current. + if (sawBanner) _augPassiveUntilMs = IltHubContext.NowMs + 15_000; + } + RynthLog.Event(LogEvents.IltAugLoad, $"ApplyAugLines: {_augStatus} (raw={lines.Count})"); + } + + /// Applies one "/aug" Type: N line. Returns true when a known planner key was updated. + private bool TryApplyAugLine(string raw) + { + var m = IltParse.AugLine.Match((raw ?? string.Empty).Trim()); + if (!m.Success) return false; + string key = m.Groups[1].Value.ToLowerInvariant(); + if (key == "specialize") key = "specialization"; + // Planner rows only; charm / Triune Weave lines are ignored here (T11 reads those). + bool known = false; + foreach (var (k, _) in IltAugCosts.Labels) + if (k.Equals(key, StringComparison.OrdinalIgnoreCase)) { known = true; break; } + if (!known) return false; + lock (_augLevels) _augLevels[key] = (int)IltParse.ParseAugValue(m.Groups[2].Value); + return true; + } + + /// Sends "/enl" (server shows the confirmation dialog). Pump thread. + public void SendEnlighten(string why) + { + RynthLog.Trace(LogCat.IltProgression, $"SendEnlighten(why='{why}')"); + if (!_ctx.Host.HasInvokeChatParser) return; + _lastEnlSentAt = IltHubContext.NowMs; + _ctx.Host.InvokeChatParser("/enl"); + _enlStatus = $"/enl sent ({why}) - click Yes in the AC dialog to confirm."; + _ctx.Chat("[Mini Remote] " + _enlStatus); + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + if (nowMs - _lastFactsAt >= 2000) + { + _lastFactsAt = nowMs; + RefreshFacts(); + } + TickSpend(nowMs); + Attributes.Tick(nowMs, holdOff: _spending); + + if (_autoArmed && C.AutoEnlightenEnabled && !_spending + && nowMs - _lastAutoCheck >= Math.Max(10, C.AutoEnlightenCheckSeconds) * 1000L) + { + _lastAutoCheck = nowMs; + TryAutoEnlighten(nowMs); + } + } + + public bool OnChat(string text) + { + Attributes.OnChat(text); + // Passive /aug reader: updates Current even when the capture idle finished on the banner alone + // (chat-hold backlog) or the player typed /aug by hand. Window opens on the header. + string t = text; + if (t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase)) + _augPassiveUntilMs = IltHubContext.NowMs + 8_000; + else if (IltHubContext.NowMs <= _augPassiveUntilMs && TryApplyAugLine(t)) + { + _augPassiveUntilMs = IltHubContext.NowMs + 8_000; + int n; + lock (_augLevels) n = _augLevels.Count; + _augStatus = $"{n} aug types @ {DateTime.Now:t}"; + } + if (text.Contains("You have become enlightened", StringComparison.OrdinalIgnoreCase) + || text.Contains("You have risen to a higher tier of enlightenment", StringComparison.OrdinalIgnoreCase)) + { + _enlStatus = "Enlightened! " + DateTime.Now.ToString("t"); + _lastFactsAt = 0; + } + return false; + } + + public void OnLogout() + { + _autoArmed = false; + _spending = false; + Attributes.OnLogout(); + lock (_augLevels) _augLevels.Clear(); + _augAutoTried = false; + _augRefreshAgain = false; + _augProbeRetryDone = false; + _augPassiveUntilMs = 0; + _augStatus = "not loaded"; + } + + // ── Facts / auto ──────────────────────────────────────────────────────── + + private void RefreshFacts() + { + var inv = _ctx.Inventory; + _enl = inv.PlayerInt(IltInventory.IntEnlightenment); + _level = inv.PlayerInt(IltInventory.IntLevel); + _unassignedXp = inv.PlayerQuad(IltInventory.QuadAvailableXp); + _peace = inv.InPeaceMode; + _freeSlots = inv.FreeMainPackSlots(); + _enlHave[0] = inv.CountByWcid(IltInventory.WcidEnlToken); + _enlHave[1] = inv.CountByWcid(IltInventory.WcidEnlMedallion); + _enlHave[2] = inv.CountByWcid(IltInventory.WcidEnlSigil); + _enlHave[3] = inv.CountByWcid(IltInventory.WcidEnlCrest); + _chain = new IltSigilStock + { + Sigils = _enlHave[2], + EnlightenedCoins = _ctx.State.Bank.EnlightenedCoins + inv.CountByWcid(IltInventory.WcidEnlightenedCoin), + AscensionCoins = inv.CountByChainName(IltSigilChain.AscensionCoin), + LifebloodElixirs = inv.CountByChainName(IltSigilChain.LifebloodElixir), + LifebloomResins = inv.CountByChainName(IltSigilChain.LifebloomResin), + YalaniTrinkets = inv.CountByChainName(IltSigilChain.YalaniTrinket), + NecrolyticExtracts = inv.CountByChainName(IltSigilChain.NecrolyticExtract), + LifeSplitters = inv.CountByChainName(IltSigilChain.LifeSplitter), + Plants = inv.CountByChainName(IltSigilChain.Plant), + }; + + _hasVitae = false; + if (_ctx.Host.HasReadPlayerEnchantments) + { + int n = _ctx.Host.ReadPlayerEnchantments(_enchIds, _enchExp, _enchIds.Length); + for (int i = 0; i < Math.Min(n, _enchIds.Length); i++) + if (_enchIds[i] == SpellVitae) { _hasVitae = true; break; } + } + } + + private long HaveFor(uint wcid) => wcid switch + { + IltInventory.WcidEnlToken => _enlHave[0], + IltInventory.WcidEnlMedallion => _enlHave[1], + IltInventory.WcidEnlSigil => _enlHave[2], + IltInventory.WcidEnlCrest => _enlHave[3], + _ => 0, + }; + + /// Checks the client-visible requirements for the next enlightenment. Empty = ready. + private List NextEnlBlockers() + { + var list = new List(); + int next = _enl + 1; + if (_level < BaseLevelForEnl + _enl) list.Add($"Need character level {BaseLevelForEnl + _enl} (have {_level})."); + if (!_peace) list.Add("Must be in peace mode."); + if (_hasVitae) list.Add("Must not have vitae."); + var cost = EnlStepCost(next); + if (cost.Count > 0 && HaveFor(cost.Wcid) < cost.Count) + { + // Sigils: the server takes finished sigils only, but say how many the craft chain could still make. + string craft = cost.Wcid == IltInventory.WcidEnlSigil + ? $"; the craft chain can make {IltParse.N0(IltSigilChain.Fulfillable(_chain) - _chain.Sigils)} more" + : string.Empty; + list.Add($"Need {cost.Count} {cost.Item} (have {HaveFor(cost.Wcid)}{craft})."); + } + if (cost.Lum > 0 && _ctx.State.Bank.Luminance < cost.Lum) list.Add($"Need {IltParse.Compact((double)cost.Lum)} banked luminance."); + return list; + } + + private void TryAutoEnlighten(long now) + { + if (_ctx.Options.IsOff(IltFeature.Enl)) return; + if (Attributes.Running) return; // the raiser is spending XP; check again next interval + if (now - _lastEnlSentAt < AutoEnlCooldownMs) return; + if (NextEnlBlockers().Count > 0) return; + if (C.AutoEnlightenSpendXpFirst && _unassignedXp > 0) + StartSpend(() => SendEnlighten("auto")); + else + SendEnlighten("auto"); + } + + // ── XP spend loop: cycles /attr 1 until unassigned XP stops dropping ── + + private void StartSpend(Action then) + { + _spending = true; + _spendIdx = 0; + _spendSent = 0; + _spendNoProgress = 0; + _spendLastAt = 0; + _spendLastXp = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp); + _afterSpend = then; + _enlStatus = "Spending unassigned XP before enlightening..."; + } + + private void TickSpend(long now) + { + if (!_spending || now - _spendLastAt < 300) return; + _spendLastAt = now; + + long xp = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp); + if (xp < _spendLastXp) _spendNoProgress = 0; else if (_spendSent > 0) _spendNoProgress++; + _spendLastXp = xp; + + // Stop after a full stat cycle with no XP drop, when XP is gone, or at the safety cap. + if (xp <= 0 || _spendNoProgress >= Stats.Length || _spendSent >= 300) + { + _spending = false; + var next = _afterSpend; + _afterSpend = null; + next?.Invoke(); + return; + } + if (_ctx.Inventory.IsBusy) return; + _ctx.Host.InvokeChatParser($"/attr {Stats[_spendIdx].Abbr} 1"); + _spendIdx = (_spendIdx + 1) % Stats.Length; + _spendSent++; + } + + // ── Engine Skills panel bridge (pump thread) ──────────────────────────── + // The engine's Skills panel draws Augmentations and Enlightenment from this snapshot and + // sends edits back as "prog ..." remote commands (HandleRemote). Planner math stays here so + // the Hub and the Skills panel can never disagree. Numbers are preformatted for display. + + /// Appends "aug":{...},"enl":{...},"attr":{...} to . Pump thread. + public void AppendSnapshotJson(StringBuilder sb) + { + // The snapshot is only polled while the Progression tab is open, so this is "on first view". + EnsureAugs(); + Attributes.EnsureCosts(); + AppendAugJson(sb); + sb.Append(','); + AppendEnlJson(sb); + sb.Append(','); + Attributes.AppendJson(sb); + } + + /// Pulls "/aug" once per login when the levels haven't been loaded (login probe or by hand). + private void EnsureAugs() + { + if (_augAutoTried || _ctx.Options.IsOff(IltFeature.Aug) || !_ctx.Host.HasInvokeChatParser) return; + bool loaded; + lock (_augLevels) loaded = _augLevels.Count > 0; + _augAutoTried = true; + if (!loaded) RequestAugs(); + } + + /// One aug's plan line: current level, clamped target, luminance and coins to get there. + private readonly record struct AugPlan(IltAugCostRow Def, string Label, int Cur, int Tgt, int Ceiling, decimal Lum, long Coins) + { + public int Inc => Tgt - Cur; + } + + private List BuildAugPlan() + { + Dictionary levels; + lock (_augLevels) levels = new Dictionary(_augLevels, StringComparer.OrdinalIgnoreCase); + var profile = AugProfile; + var plan = new List(profile.Augs.Count); + foreach (var a in profile.Augs) + { + int cur = levels.TryGetValue(a.Key, out int c) ? c : 0; + int ceiling = IltAugCosts.Ceiling(a, cur); + int tgt = Math.Clamp(C.AugTargets.TryGetValue(a.Key, out int t) ? t : cur, cur, ceiling); + plan.Add(new AugPlan(a, IltAugCosts.Label(a.Key), cur, tgt, ceiling, + IltAugCosts.LumCost(a, profile.Multipliers, cur, tgt), (long)(tgt - cur) * a.CoinsPerLevel)); + } + return plan; + } + + private void AppendAugJson(StringBuilder sb) + { + var plan = BuildAugPlan(); + + sb.Append("\"aug\":{\"off\":").Append(Bool(_ctx.Options.IsOff(IltFeature.Aug))); + Str(sb, "status", _augStatus); + sb.Append(",\"lumPerCoin\":").Append(C.LumPerEnlightenedCoin).Append(",\"rows\":["); + for (int i = 0; i < plan.Count; i++) + { + var p = plan[i]; + if (i > 0) sb.Append(','); + sb.Append('{'); + Str(sb, "key", p.Def.Key, first: true); + Str(sb, "label", p.Label); + sb.Append(",\"cur\":").Append(p.Cur).Append(",\"tgt\":").Append(p.Tgt).Append(",\"cap\":").Append(p.Ceiling) + .Append(",\"inc\":").Append(p.Inc); + Str(sb, "lum", p.Lum > 0 ? IltParse.Compact((double)p.Lum) : "-"); + sb.Append(",\"coins\":").Append(p.Coins).Append('}'); + } + sb.Append(']'); + + decimal totalLum = plan.Sum(p => p.Lum); + long totalCoins = plan.Sum(p => p.Coins); + long bankCoins = _ctx.State.Bank.EnlightenedCoins; + long lumPerCoin = C.LumPerEnlightenedCoin; + long coinsShort = Math.Max(0, totalCoins - bankCoins); + + // Totals row (UB's TOTALS line) and the e-coin summary under the table. + sb.Append(",\"totCur\":").Append(plan.Sum(p => p.Cur)) + .Append(",\"totTgt\":").Append(plan.Sum(p => p.Tgt)) + .Append(",\"totInc\":").Append(plan.Sum(p => p.Inc)) + .Append(",\"totCoins\":").Append(totalCoins); + Str(sb, "totLum", totalLum > 0 ? IltParse.Compact((double)totalLum) : "-"); + Str(sb, "coinsLine", $"E-coins needed: {IltParse.N0(totalCoins)} banked: {IltParse.N0(bankCoins)} short: {IltParse.N0(coinsShort)}"); + Str(sb, "lumToBuy", coinsShort == 0 ? "Lum to buy e-coins: none needed" + : lumPerCoin > 0 ? $"Lum to buy e-coins: ~{IltParse.Compact((double)coinsShort * lumPerCoin)}" + : "Lum to buy e-coins: set Lum per coin"); + // Older engine builds read these three. + Str(sb, "total", $"Total: {IltParse.Compact((double)totalLum)} luminance, {IltParse.N0(totalCoins)} coins"); + Str(sb, "short", coinsShort > 0 + ? $"Coins short: {IltParse.N0(coinsShort)}" + (lumPerCoin > 0 ? $" (~{IltParse.Compact((double)coinsShort * lumPerCoin)} luminance to buy)" : "") + : string.Empty); + Str(sb, "banked", $"Banked luminance: {IltParse.Compact(_ctx.State.Bank.Luminance)}"); + Str(sb, "copyDiscord", AugDiscordText(plan)); + Str(sb, "copyIngame", AugIngameText(plan)); + AppendAugCostJson(sb); + sb.Append('}'); + } + + /// "cfg":{...}: this world's cost rules for the "Cost settings" editor. + private void AppendAugCostJson(StringBuilder sb) + { + string world = _ctx.Options.WorldName; + var p = AugProfile; + var inv = System.Globalization.CultureInfo.InvariantCulture; + sb.Append(",\"cfg\":{"); + Str(sb, "world", world.Length > 0 ? world : "unknown world", first: true); + sb.Append(",\"custom\":").Append(Bool(AugCosts.IsCustom(world))).Append(",\"mults\":["); + for (int i = 0; i < p.Multipliers.Length; i++) + sb.Append(i > 0 ? "," : "").Append(p.Multipliers[i].ToString("R", inv)); + sb.Append("],\"rows\":["); + for (int i = 0; i < p.Augs.Count; i++) + { + var r = p.Augs[i]; + if (i > 0) sb.Append(','); + sb.Append('{'); + Str(sb, "key", r.Key, first: true); + Str(sb, "label", IltAugCosts.Label(r.Key)); + sb.Append(",\"base\":").Append(r.Base) + .Append(",\"pct\":").Append(r.LinearPercent.ToString("R", inv)) + .Append(",\"coins\":").Append(r.CoinsPerLevel) + .Append(",\"s1\":").Append(r.S1).Append(",\"s2\":").Append(r.S2) + .Append(",\"s3\":").Append(r.S3).Append(",\"s4\":").Append(r.S4) + .Append(",\"cap\":").Append(r.Cap).Append('}'); + } + sb.Append("]}"); + } + + /// "augcfg <aug> <field> <value>": one cost-rule edit for this world. + private void EditAugRule(string key, string field, string value) + { + var inv = System.Globalization.CultureInfo.InvariantCulture; + bool isInt = int.TryParse(value, System.Globalization.NumberStyles.Integer, inv, out int iv); + bool isNum = double.TryParse(value, System.Globalization.NumberStyles.Float, inv, out double dv); + long amount = 0; + bool isAmount = field == "base" && IltParse.TryParseAmount(value, out amount); + if (!isInt && !isNum && !isAmount) return; + AugCosts.Edit(_ctx.Options.WorldName, p => + { + var r = p.Augs.FirstOrDefault(x => x.Key.Equals(key, StringComparison.OrdinalIgnoreCase)); + if (r == null) return; + switch (field) + { + case "base": if (isAmount) r.Base = amount; break; + case "pct": if (isNum) r.LinearPercent = dv; break; + case "coins": if (isInt) r.CoinsPerLevel = iv; break; + case "s1": if (isInt) r.S1 = iv; break; + case "s2": if (isInt) r.S2 = iv; break; + case "s3": if (isInt) r.S3 = iv; break; + case "s4": if (isInt) r.S4 = iv; break; + case "cap": if (isInt) r.Cap = iv; break; + } + }); + } + + /// + /// UB's "Copy Discord" table in a code block. ASCII only: the engine reads the snapshot as ANSI. + /// + private string AugDiscordText(List plan) + { + string name = string.IsNullOrEmpty(_ctx.CharName) ? "character" : _ctx.CharName; + string rule = new('-', 56); + var t = new StringBuilder(); + t.Append("```\n").Append("Augmentations - ").Append(name).Append('\n').Append(rule).Append('\n'); + t.Append($"{"Type",-15} {"Current",-8} {"Target",-8} {"Inc",-5} {"Lum Cost",-10} {"Coins",-6}\n").Append(rule).Append('\n'); + foreach (var p in plan) + { + if (p.Cur <= 0 && p.Tgt <= 0) continue; + string lum = p.Lum > 0 ? IltParse.Compact((double)p.Lum) : "-"; + t.Append($"{p.Label,-15} {p.Cur,-8} {p.Tgt,-8} {p.Inc,-5} {lum,-10} {p.Coins,-6}\n"); + } + decimal totalLum = plan.Sum(p => p.Lum); + t.Append(rule).Append('\n'); + t.Append($"{"TOTALS:",-15} {plan.Sum(p => p.Cur),-8} {plan.Sum(p => p.Tgt),-8} {plan.Sum(p => p.Inc),-5} " + + $"{(totalLum > 0 ? IltParse.Compact((double)totalLum) : "-"),-10} {plan.Sum(p => p.Coins),-6}\n"); + t.Append("```"); + return t.ToString(); + } + + /// UB's "Copy In-Game": one line of current levels with short names, for pasting into chat. + private string AugIngameText(List plan) + { + string name = string.IsNullOrEmpty(_ctx.CharName) ? "character" : _ctx.CharName; + var parts = plan.Where(p => p.Cur > 0).Select(p => $"{AugShortName(p.Def.Key)}: {IltParse.N0(p.Cur)}").ToList(); + return parts.Count == 0 + ? $"Augmentation Levels - {name}: none loaded" + : $"Augmentation Levels - {name} ({IltParse.N0(plan.Sum(p => p.Cur))} total): {string.Join(", ", parts)}"; + } + + private static string AugShortName(string key) => key switch + { + "creature" => "Crit", + "duration" => "Dur", + "specialization" => "Spec", + "summon" => "Sum", + "melee" => "Mel", + "missile" => "Mis", + _ => char.ToUpperInvariant(key[0]) + key.Substring(1), + }; + + private void AppendEnlJson(StringBuilder sb) + { + int enl = _enl; + sb.Append("\"enl\":{\"off\":").Append(Bool(_ctx.Options.IsOff(IltFeature.Enl))); + Str(sb, "header", $"Enlightenment {enl} Level {_level} Unassigned XP {IltParse.Compact(_unassignedXp)}"); + var next = EnlStepCost(enl + 1); + Str(sb, "next", $"Next ({enl + 1}): " + (next.Count > 0 + ? $"{next.Count} {next.Item} (have {HaveFor(next.Wcid)})" + (next.Lum > 0 ? $" + {IltParse.Compact((double)next.Lum)} lum" : "") + : "no materials")); + + int target = C.EnlTargetLevel <= enl ? enl + 5 : C.EnlTargetLevel; + sb.Append(",\"enl\":").Append(enl).Append(",\"target\":").Append(target).Append(",\"plan\":["); + var totals = new Dictionary(); + decimal lumTotal = 0; + for (int t = enl + 1; t <= Math.Max(enl + 1, target) && t <= enl + 500; t++) + { + var s = EnlStepCost(t); + if (s.Count > 0) totals[s.Item] = (totals.TryGetValue(s.Item, out long v) ? v : 0) + s.Count; + lumTotal += s.Lum; + } + bool firstLine = true; + foreach (var kv in totals) { StrItem(sb, $"{IltParse.N0(kv.Value)} {kv.Key}", ref firstLine); } + if (lumTotal > 0) + StrItem(sb, $"{IltParse.Compact((double)lumTotal)} luminance (banked {IltParse.Compact(_ctx.State.Bank.Luminance)})", ref firstLine); + sb.Append(']'); + + int coinsPerToken = C.EnlightenedCoinsPerToken; + sb.Append(",\"coinsPerToken\":").Append(coinsPerToken); + string tokensShort = string.Empty; + if (totals.TryGetValue("Enlightenment Tokens", out long tokNeed) && coinsPerToken > 0) + { + long shortTok = Math.Max(0, tokNeed - _enlHave[0]); + if (shortTok > 0) tokensShort = $"Tokens short: {shortTok} (~{IltParse.N0(shortTok * coinsPerToken)} coins)"; + } + Str(sb, "tokensShort", tokensShort); + + AppendEnlCalculatorJson(sb, enl, target, totals, lumTotal); + + var blockers = NextEnlBlockers(); + sb.Append(",\"blockers\":["); + bool firstBlocker = true; + foreach (string b in blockers) StrItem(sb, b, ref firstBlocker); + sb.Append(']'); + Str(sb, "serverChecks", $"Server also checks: not in a dungeon, free pack slots ({(_freeSlots >= 0 ? _freeSlots.ToString() : "?")} free), " + + "all luminance augs (past 10), society master (past 30)."); + sb.Append(",\"auto\":").Append(Bool(C.AutoEnlightenEnabled)) + .Append(",\"armed\":").Append(Bool(_autoArmed)) + .Append(",\"spendFirst\":").Append(Bool(C.AutoEnlightenSpendXpFirst)) + .Append(",\"checkEvery\":").Append(C.AutoEnlightenCheckSeconds); + Str(sb, "status", _enlStatus); + sb.Append('}'); + } + + /// Per-level rows the calculator lists at most (a bigger range is summarised in the totals). + private const int EnlLevelRowsMax = 100; + + /// + /// UB-IT's Enlighten calculator: per-level table (green while stock lasts, the sigil chain counted), + /// material summary (still need / have), the 301-325 sigil chain, and the e-coin line shared with + /// token conversion. Appends "levels", "materials", "chain", "chainNote", "ecoins", "ecoinsLum". + /// + private void AppendEnlCalculatorJson(StringBuilder sb, int enl, int target, Dictionary totals, decimal lumTotal) + { + // Simulated stock: tokens, medallions, crests on hand, sigils via the chain, banked luminance. + long tok = _enlHave[0], med = _enlHave[1], crest = _enlHave[3]; + decimal lum = (decimal)_ctx.State.Bank.Luminance; + var chain = _chain.Clone(); + long sigilCraftable = IltSigilChain.Fulfillable(chain); + + sb.Append(",\"levels\":["); + int last = Math.Min(Math.Max(enl + 1, target), enl + EnlLevelRowsMax); + for (int t = enl + 1; t <= last; t++) + { + var s = EnlStepCost(t); + bool ok = lum >= s.Lum; + if (ok && s.Count > 0) + { + switch (s.Wcid) + { + case IltInventory.WcidEnlToken: ok = tok >= s.Count; if (ok) tok -= s.Count; break; + case IltInventory.WcidEnlMedallion: ok = med >= s.Count; if (ok) med -= s.Count; break; + case IltInventory.WcidEnlSigil: ok = sigilCraftable >= s.Count; if (ok) sigilCraftable -= s.Count; break; + default: ok = crest >= s.Count; if (ok) crest -= s.Count; break; + } + } + if (ok) lum -= s.Lum; + if (t > enl + 1) sb.Append(','); + sb.Append("{\"t\":").Append(t); + Str(sb, "item", ShortItem(s.Item)); + sb.Append(",\"count\":").Append(s.Count); + Str(sb, "lum", s.Lum > 0 ? IltParse.Compact((double)s.Lum) : "-"); + sb.Append(",\"ok\":").Append(Bool(ok)).Append('}'); + } + sb.Append(']'); + + // Material summary: Still need = demand minus what is on hand. + long sigilsNeed = totals.TryGetValue("Enlightenment Sigils", out long sn) ? sn : 0; + var shortfall = IltSigilChain.Shortfall(sigilsNeed, _chain); + decimal bankLum = (decimal)_ctx.State.Bank.Luminance; + sb.Append(",\"materials\":["); + bool firstMat = true; + void Mat(string label, string need, string have, bool ok) + { + if (!firstMat) sb.Append(','); + firstMat = false; + sb.Append('{'); + Str(sb, "label", label, first: true); + Str(sb, "need", need); + Str(sb, "have", have); + sb.Append(",\"ok\":").Append(Bool(ok)).Append('}'); + } + if (lumTotal > 0) + { + decimal lumStill = Math.Max(0, lumTotal - bankLum); + Mat("Luminance", lumStill > 0 ? IltParse.Compact((double)lumStill) : "0", IltParse.Compact((double)bankLum), lumStill == 0); + } + void Item(string key, string label, long have, bool extraOk = false) + { + if (!totals.TryGetValue(key, out long need)) return; + long still = Math.Max(0, need - have); + Mat(label, IltParse.N0(still), IltParse.N0(have), still == 0 || extraOk); + } + Item("Enlightenment Tokens", "Tokens", _enlHave[0]); + Item("Enlightenment Medallions", "Medallions", _enlHave[1]); + Item("Enlightenment Sigils", "Sigils", _enlHave[2], extraOk: shortfall.Covered); + Item("Enlightenment Crests", "Crests", _enlHave[3]); + sb.Append(']'); + + // Sigil chain rows (only when the plan reaches 301-325). + sb.Append(",\"chain\":["); + if (sigilsNeed > 0) + { + bool firstRow = true; + void Row(string label, long need, long have, bool ok, bool craft) + { + if (!firstRow) sb.Append(','); + firstRow = false; + sb.Append('{'); + Str(sb, "label", label, first: true); + sb.Append(",\"need\":").Append(need).Append(",\"have\":").Append(have) + .Append(",\"ok\":").Append(Bool(ok)).Append(",\"craft\":").Append(Bool(craft)).Append('}'); + } + Row("Ascension Coins", shortfall.AscensionToCraft, _chain.AscensionCoins, + shortfall.AscensionToCraft == 0 || (shortfall.CoinsShort == 0 && shortfall.TrinketsShort == 0), true); + Row("Lifeblood Elixirs", shortfall.ElixirsToCraft, _chain.LifebloodElixirs, + shortfall.ElixirsToCraft == 0 || (shortfall.ExtractsShort == 0 && shortfall.SplittersShort == 0 && shortfall.PlantsShort == 0), true); + Row("Lifebloom Resins", shortfall.ResinsToCraft, _chain.LifebloomResins, + shortfall.ResinsToCraft == 0 || (shortfall.SplittersShort == 0 && shortfall.PlantsShort == 0), true); + Row("E-coins", shortfall.CoinsShort, _chain.EnlightenedCoins, shortfall.CoinsShort == 0, false); + Row("Ancient Yalani Trinkets", shortfall.TrinketsShort, _chain.YalaniTrinkets, shortfall.TrinketsShort == 0, false); + Row("Necrolytic Extracts", shortfall.ExtractsShort, _chain.NecrolyticExtracts, shortfall.ExtractsShort == 0, false); + Row("Life Splitters", shortfall.SplittersShort, _chain.LifeSplitters, shortfall.SplittersShort == 0, false); + Row("Plants", shortfall.PlantsShort, _chain.Plants, shortfall.PlantsShort == 0, false); + } + sb.Append(']'); + Str(sb, "chainNote", sigilsNeed > 0 + ? $"Sigil = Lifeblood Elixir + Ascension Coin. {IltParse.N0(shortfall.SigilsToCraft)} to craft; " + + (shortfall.Covered ? "the chain covers them." : "Need = crafts left (in-between items) or mats to get (raw items).") + : string.Empty); + + // E-coins: Ascension Coin crafts first, then token conversion at the shop price. + long tokNeed = totals.TryGetValue("Enlightenment Tokens", out long tn) ? tn : 0; + IltSigilChain.EcoinDemand(_chain.EnlightenedCoins, shortfall.CoinsForCraft, Math.Max(0, tokNeed - _enlHave[0]), + C.EnlightenedCoinsPerToken, out _, out long tokensStill, out long coinsNeeded); + Str(sb, "ecoins", tokNeed > 0 || shortfall.CoinsForCraft > 0 + ? $"E-coins needed: {IltParse.N0(coinsNeeded)} have {IltParse.N0(_chain.EnlightenedCoins)} (bank + pack)" + + (shortfall.CoinsForCraft > 0 ? $" Ascension Coins use {IltParse.N0(shortfall.CoinsForCraft)}" : "") + + (tokensStill > 0 ? $" tokens still {IltParse.N0(tokensStill)}" : "") + : string.Empty); + long lumPerCoin = C.LumPerEnlightenedCoin; + Str(sb, "ecoinsLum", coinsNeeded <= 0 ? string.Empty + : lumPerCoin > 0 ? $"Lum to buy e-coins: ~{IltParse.Compact((double)coinsNeeded * lumPerCoin)}" + : "Lum to buy e-coins: set Lum per e-coin (Augmentations)"); + } + + /// Short label for the per-level table's item column. + private static string ShortItem(string item) => item switch + { + "Enlightenment Tokens" => "Tokens", + "Enlightenment Medallions" => "Medallions", + "Enlightenment Sigils" => "Sigils", + "Enlightenment Crests" => "Crests", + _ => "-", + }; + + private static string Bool(bool b) => b ? "true" : "false"; + + private static void Str(StringBuilder sb, string name, string value, bool first = false) + { + if (!first) sb.Append(','); + sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"'); + } + + private static void StrItem(StringBuilder sb, string value, ref bool first) + { + if (!first) sb.Append(','); + first = false; + sb.Append('"').Append(IltStyle.JsonEscape(value)).Append('"'); + } + + /// + /// "prog" remote command from the engine Skills panel. Pump thread. The panel asks its own + /// confirmation before "enlighten" and "autoenl on|arm", so none is asked here. + /// + public void HandleRemote(string[] a) + { + if (a.Length == 0) return; + RynthLog.Trace(LogCat.IltProgression, $"HandleRemote({string.Join(" ", a)})"); + string arg1 = a.Length > 1 ? a[1] : string.Empty; + int.TryParse(a.Length > 2 ? a[2] : arg1, out int n); + string verb = a[0].ToLowerInvariant(); + if (verb.StartsWith("attr", StringComparison.Ordinal) && Attributes.HandleRemote(verb, a)) return; + switch (verb) + { + case "augload": RequestAugs(); break; + case "augreset": + // UB's "Reset Target": every target back to the current level. + lock (_augLevels) + foreach (var (key, _) in IltAugCosts.Labels) + C.AugTargets[key] = _augLevels.TryGetValue(key, out int c) ? c : 0; + break; + case "augtarget" when a.Length > 2: + foreach (var def in AugProfile.Augs) + { + if (!def.Key.Equals(arg1, StringComparison.OrdinalIgnoreCase)) continue; + int cur; + lock (_augLevels) cur = _augLevels.TryGetValue(def.Key, out int c) ? c : 0; + C.AugTargets[def.Key] = Math.Clamp(n, 0, IltAugCosts.Ceiling(def, cur)); + break; + } + break; + case "augmult" when a.Length > 2: + // "augmult ": tier 0 is below S1, tier 4 is from S4 on. + if (int.TryParse(arg1, out int tier) && tier is >= 0 and <= 4 + && double.TryParse(a[2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double mult)) + AugCosts.Edit(_ctx.Options.WorldName, p => p.Multipliers[tier] = mult); + break; + case "augcfg" when a.Length > 3: + EditAugRule(arg1, a[2].ToLowerInvariant(), a[3]); + break; + case "augcfgreset": + AugCosts.Reset(_ctx.Options.WorldName); + break; + case "lumpercoin": + if (IltParse.TryParseAmount(arg1, out long lpc)) C.LumPerEnlightenedCoin = Math.Max(0, lpc); + break; + case "enltarget": C.EnlTargetLevel = Math.Max(_enl + 1, n); break; + case "coinspertoken": C.EnlightenedCoinsPerToken = Math.Max(0, n); break; + case "enlighten": SendEnlighten("manual, Skills panel"); break; + case "autoenl": + switch (arg1.ToLowerInvariant()) + { + case "on": + C.AutoEnlightenEnabled = true; + _autoArmed = true; + _ctx.Chat("[Mini Remote] Auto-enlighten armed for this session."); + break; + case "arm": if (C.AutoEnlightenEnabled) _autoArmed = true; break; + default: C.AutoEnlightenEnabled = false; _autoArmed = false; break; + } + break; + case "spendfirst": C.AutoEnlightenSpendXpFirst = arg1.Equals("on", StringComparison.OrdinalIgnoreCase); break; + case "checkevery": C.AutoEnlightenCheckSeconds = Math.Max(10, n); break; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs new file mode 100644 index 0000000..991a923 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs @@ -0,0 +1,209 @@ +// IltQuestBonus.cs — The ACECustom quest bonus list ("/qb list"), shown in RynthAi's universal +// Quests tab (RynthILT.Hub section "quests-qb") and read by the Temple attribute tracker. +// Originally the /qb half of SilentKelpie's IltQuests (ILT Hub, RynthAi); split out and moved to +// RynthILT 2026-10-13. The /myquests tracker half stayed in RynthAi (MiniRemote/QuestsTab.cs): +// /myquests is every server's, /qb is ACECustom's. +// +// "/qb list" prints a completed and an incomplete section; both are tracked separately (UB +// merged them). Server throttles /qb to once per minute. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using System.Text.RegularExpressions; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltQuestBonus : IIltFeature +{ + private static readonly Regex KillTaskRegex = new(@"(killtask|killcount|slayerquest|totalgolem.*dead|(kills$))", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + private static readonly Regex QbFlagLine = new(@"^[a-zA-Z0-9_\-!@\(\)?]+$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private const long QbCooldownMs = 60_000; + + private readonly IltHubContext _ctx; + private long _lastQbAt = -QbCooldownMs; + + // QB results (replaced wholesale; read by the render thread). + private volatile string[] _qbCompleted = Array.Empty(); + private volatile string[] _qbIncomplete = Array.Empty(); + private volatile string _qbStatus = "not loaded"; + private long _qbCount = -1; + private volatile int _qbGeneration; // bumped per successful "/qb list"; 0 = never loaded this session + + public IltQuestBonus(IltHubContext ctx) => _ctx = ctx; + + /// The /myquests flag kinds (RynthAi's QuestsTab.Classify, which the Temple tracker reads by). + public enum QuestKind { Timed, KillTask, Once } + + public static QuestKind Classify(QuestRecord r) + { + if (KillTaskRegex.IsMatch(r.Key) && r.MaxSolves >= 0) return QuestKind.KillTask; + if (r.MaxSolves == 1 && r.Solves <= 1) return QuestKind.Once; + return QuestKind.Timed; + } + + /// Captures "/qb list" (quiet). + public string RefreshQb() + { + RynthLog.Trace(LogCat.IltQuests, $"RefreshQb()"); + if (_ctx.Options.IsOff(IltFeature.Qb)) return "/qb is disabled on this server."; + long now = IltHubContext.NowMs; + if (now - _lastQbAt < QbCooldownMs) + return $"Wait {(QbCooldownMs - (now - _lastQbAt)) / 1000}s (server allows one /qb per minute)."; + if (_ctx.Capture.IsPending("/qb list")) return "Already loading..."; + _lastQbAt = now; + _qbStatus = "loading..."; + + _ctx.Capture.Enqueue(new IltChatRequest + { + Command = "/qb list", + IsResponseLine = IsQbLine, + IsTerminator = t => t.Contains("Quest bonus list is empty", StringComparison.OrdinalIgnoreCase) + || t.Contains("\"qb\" is not currently enabled", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("[QB] This command may only be run once every", StringComparison.OrdinalIgnoreCase), + IdleEndMs = 5000, + FirstLineTimeoutMs = 30000, + Eat = true, + OnComplete = OnQbResult, + }); + return "Loading quest bonus list..."; + } + + private static bool IsQbLine(string t) + { + if (t.StartsWith("Your completed quest bonus list", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("Your incomplete quest bonus list", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase)) + return true; + if (!QbFlagLine.IsMatch(t)) return false; + if (t.StartsWith("You ", StringComparison.Ordinal) || t.StartsWith("The ", StringComparison.Ordinal)) return false; + return !(t.Contains("You have", StringComparison.OrdinalIgnoreCase) || t.Contains("command", StringComparison.OrdinalIgnoreCase) + || t.Contains("enabled", StringComparison.OrdinalIgnoreCase) || t.Contains("list", StringComparison.OrdinalIgnoreCase)); + } + + private void OnQbResult(IltChatResult r) + { + if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Qb, IltTri.Off); _qbStatus = "/qb not available"; return; } + if (r.TerminatorLine != null) + { + if (r.TerminatorLine.Contains("not currently enabled", StringComparison.OrdinalIgnoreCase)) + { _ctx.Options.Set(IltFeature.Qb, IltTri.Off); _qbStatus = "/qb is disabled on this server"; return; } + if (r.TerminatorLine.Contains("only be run once", StringComparison.OrdinalIgnoreCase)) + { _qbStatus = "rate limited by the server"; return; } + } + if (r.TimedOut) { _qbStatus = "no reply from server"; return; } + _ctx.Options.Set(IltFeature.Qb, IltTri.On); + + var done = new List(); + var todo = new List(); + List? current = null; + foreach (string line in r.Lines) + { + if (line.StartsWith("Your completed quest bonus list", StringComparison.OrdinalIgnoreCase)) { current = done; continue; } + if (line.StartsWith("Your incomplete quest bonus list", StringComparison.OrdinalIgnoreCase)) { current = todo; continue; } + if (line.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase)) + { + int colon = line.IndexOf(':'); + if (colon > 0) _qbCount = IltParse.ParseLeadingLong(line.Substring(colon + 1)); + continue; + } + if (line.Contains("is empty", StringComparison.OrdinalIgnoreCase)) continue; + (current ?? done).Add(line.Trim()); + } + done.Sort(StringComparer.OrdinalIgnoreCase); + todo.Sort(StringComparer.OrdinalIgnoreCase); + _qbCompleted = done.ToArray(); + _qbIncomplete = todo.ToArray(); + _qbStatus = $"{done.Count} completed, {todo.Count} incomplete"; + _qbGeneration++; + } + + /// Increments each time a "/qb list" reply is parsed (0 = not loaded this session). + public int QbGeneration => _qbGeneration; + + /// + /// Snapshot for the "RynthILT.Server" profile JSON (Oracle Quests / Fellowship). Pump thread. + /// + public IltQuestBonusInfo Snapshot() => + new(_ctx.Options.IsOff(IltFeature.Qb), _qbGeneration, _qbCount, _qbStatus, _qbCompleted, _qbIncomplete); + + /// True when the last "/qb list" (completed or incomplete) contains the flag. + public bool QbHasFlag(string flag) + { + if (string.IsNullOrWhiteSpace(flag)) return false; + foreach (string f in _qbCompleted) + if (f.Equals(flag, StringComparison.OrdinalIgnoreCase)) return true; + foreach (string f in _qbIncomplete) + if (f.Equals(flag, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + /// Login probe tap: "/qb" (no args) prints the count line. + public void ApplyQbProbe(List lines) + { + RynthLog.Trace(LogCat.IltQuests, $"ApplyQbProbe(lines={lines.Count})"); + foreach (string line in lines) + if (line.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase)) + { + int colon = line.IndexOf(':'); + if (colon > 0) _qbCount = IltParse.ParseLeadingLong(line.Substring(colon + 1)); + } + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) { } + public bool OnChat(string text) => false; + public void OnLogout() + { + _qbCompleted = Array.Empty(); + _qbIncomplete = Array.Empty(); + _qbCount = -1; + _qbStatus = "not loaded"; + _qbGeneration = 0; + } + + // ── UI (render thread) ────────────────────────────────────────────────── + + /// The Quests tab's "Quest bonus (/qb)" section (collapsed header; ILT worlds only). + public void RenderSection() + { + if (ImGui.CollapsingHeader("Quest bonus (/qb)##qbwin")) RenderQb(); + } + + public void RenderQb() + { + if (_ctx.Options.IsOff(IltFeature.Qb)) + { + ImGui.TextColored(IltStyle.ColTextMute, "/qb is disabled on this server."); + return; + } + if (ImGui.SmallButton("Load /qb list")) _ctx.Post(() => _ctx.Chat("[Mini Remote] " + RefreshQb())); + ImGui.SameLine(); + long count = _qbCount; + SafeImGui.TextDisabled((count >= 0 ? $"QB count {IltParse.N0(count)} - " : "") + _qbStatus); + + string filter = _ctx.State.Character.QbFilter; + ImGui.SetNextItemWidth(220); + if (ImGui.InputTextWithHint("##qbfilter", "filter flags", ref filter, 64u)) + _ctx.State.Character.QbFilter = filter; + + RenderQbList("Incomplete", _qbIncomplete, filter, IltStyle.ColAmber); + RenderQbList("Completed", _qbCompleted, filter, IltStyle.ColGreen); + } + + private static void RenderQbList(string label, string[] items, string filter, Vector4 color) + { + var shown = filter.Length == 0 ? items : items.Where(i => i.Contains(filter, StringComparison.OrdinalIgnoreCase)).ToArray(); + if (ImGui.TreeNode($"{label} ({shown.Length})##qb{label}")) + { + if (ImGui.SmallButton($"Copy##qbc{label}")) ImGui.SetClipboardText(string.Join(Environment.NewLine, shown)); + foreach (string s in shown) SafeImGui.TextColored(color, s); + ImGui.TreePop(); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChain.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChain.cs new file mode 100644 index 0000000..f0e1883 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChain.cs @@ -0,0 +1,130 @@ +// IltRingChain.cs - Infinite Leaftide's ring inscription chain (Gear tab > Rings), from UB-IT's +// ImbueSpellCraftDefinitions / SpellcraftInventoryPolicy. SilentKelpie's RynthAi Crafting > Rings +// (MiniRemote/Crafting/RingChain.cs), moved to RynthILT 2026-10-15: it is Leaftide-only. +// +// Step 1: Quill of Infliction used on a Trophy -> Enlightened Quill of Infliction +// Step 2: Enlightened Quill used on Ink of Partition -> partition quill +// Step 3: partition quill used on a Glyph -> "Inscription of ..." scroll +// Then each scroll is used on a ring / jewelry / weapon. +// +// Pure: ingredient matching (case-insensitive substrings with alternates and one exclude), the +// craft queue order and the scroll-to-target pairing. IltRingChainRunner does the using. +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One ingredient: the first of found in an item's name, unless it also has . +internal sealed record IltRingIngredient(string Label, string[] Names, string Exclude = ""); + +/// One combine: is used on . +/// 1 quill + trophy, 2 + ink, 3 + glyph: the queue runs every tier-1 run first. +/// Step 3: the words the resulting inscription scroll's name carries. +internal sealed record IltRingRecipe(string Id, int Tier, string Name, string Notes, + IltRingIngredient Tool, IltRingIngredient Target, string[] ScrollMarkers); + +internal static class IltRingChain +{ + /// Every inscription scroll's name has this. + public const string InscriptionMarker = "Inscription of"; + /// Most runs of one recipe the tab queues. + public const int MaxRuns = 99; + + private static readonly IltRingIngredient PartitionQuill = new("Enlightened Infliction Quill of Partition", + new[] { "Enlightened Infliction Quill of Partition", "Enlightened Quill of Infliction of Partition" }); + + private static IltRingRecipe Glyph(string id, string element, string scroll) => new( + id, 3, $"Step 3: {element} glyph - {scroll}", + $"Partition quill used on Glyph of {element} -> Inscription of {scroll} scroll.", + PartitionQuill, + // The full glyph name: a short one can match the wrong stack. + new IltRingIngredient($"Glyph of {element}", new[] { $"Glyph of {element}" }), + new[] { scroll, element }); + + /// The chain, in UB-IT's order. + public static readonly IltRingRecipe[] Recipes = + { + new("ring2_step1_quill_trophy", 1, "Step 1: Quill of Infliction + Trophy", + "Quill of Infliction used on a Trophy -> Enlightened Quill of Infliction.", + new IltRingIngredient("Quill of Infliction", new[] { "Quill of Infliction", "Infliction Quill" }, Exclude: "Enlightened"), + // Not plain "Trophy": scrolls and kits carry that word too. + new IltRingIngredient("Trophy", new[] { "Royal Summons", "Empyrean Trophy", "Summoning Gem" }), + Array.Empty()), + new("ring2_step2_ink", 2, "Step 2: Enlightened Quill + Ink of Partition", + "Enlightened Quill of Infliction (from Step 1) used on Ink of Partition -> partition quill.", + new IltRingIngredient("Enlightened Quill of Infliction", + new[] { "Enlightened Quill of Infliction", "Enlightened Infliction Quill", "Enlightened Infliction Quill of" }, Exclude: "Partition"), + new IltRingIngredient("Ink of Partition", new[] { "Ink of Partition", "Partition Ink" }), + Array.Empty()), + Glyph("ring2_glyph_bludgeoning", "Bludgeoning", "Tectonic Rifts"), + Glyph("ring2_glyph_lightning", "Lightning", "Eye of the Storm"), + Glyph("ring2_glyph_piercing", "Piercing", "Nuhmudira's Spines"), + Glyph("ring2_glyph_nether", "Nether", "Clouded Soul"), + Glyph("ring2_glyph_corrosion", "Corrosion", "Searing Disc"), + Glyph("ring2_glyph_frost", "Frost", "Halo of Frost"), + Glyph("ring2_glyph_slashing", "Slashing", "Horizon's Blades"), + Glyph("ring2_glyph_flame", "Flame", "Cassius' Ring of Fire"), + }; + + /// True when an item's name is this ingredient. + public static bool Matches(string? name, IltRingIngredient ing) + { + if (string.IsNullOrEmpty(name)) return false; + if (ing.Exclude.Length > 0 && name.IndexOf(ing.Exclude, StringComparison.OrdinalIgnoreCase) >= 0) return false; + foreach (string n in ing.Names) + if (n.Length > 0 && name.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0) return true; + return false; + } + + /// + /// The craft queue: every Step 1 run, then every Step 2 run, then the glyphs, each tier in + /// definition order (a later tier's ingredients come out of the earlier one). + /// + public static List Expand(Func runs) + { + var queue = new List(); + foreach (var r in Recipes.OrderBy(r => r.Tier)) + { + int n = Math.Clamp(runs(r.Id), 0, MaxRuns); + for (int i = 0; i < n; i++) queue.Add(r); + } + return queue; + } + + /// The glyph recipe a scroll came from (null when its name has no known marker). + public static IltRingRecipe? GlyphOf(string? scrollName) + { + if (string.IsNullOrEmpty(scrollName)) return null; + foreach (var r in Recipes) + foreach (string m in r.ScrollMarkers) + if (scrollName.IndexOf(m, StringComparison.OrdinalIgnoreCase) >= 0) return r; + return null; + } + + public static bool IsInscriptionScroll(string? name) + => !string.IsNullOrEmpty(name) && name.IndexOf(InscriptionMarker, StringComparison.OrdinalIgnoreCase) >= 0; + + /// The order scrolls are listed and used in: by glyph recipe id, unknown ones last by name. + public static string ScrollOrderKey(string? scrollName) => GlyphOf(scrollName)?.Id ?? "zzz_" + scrollName; + + /// + /// Pairs scrolls with targets the way UB-IT does: scrolls by glyph recipe id (unknown ones + /// last, by name), targets by object id, one scroll per target. + /// + public static List<(int Scroll, int Target)> PairScrolls(IEnumerable<(int Id, string Name)> scrolls, IEnumerable targets) + { + var ordered = scrolls + .OrderBy(s => ScrollOrderKey(s.Name), StringComparer.Ordinal) + .ThenBy(s => s.Id) + .ToList(); + var pairs = new List<(int, int)>(); + int i = 0; + foreach (int t in targets.Distinct().OrderBy(x => x)) + { + if (i >= ordered.Count) break; + pairs.Add((ordered[i++].Id, t)); + } + return pairs; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChainRunner.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChainRunner.cs new file mode 100644 index 0000000..d4b9106 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChainRunner.cs @@ -0,0 +1,557 @@ +// IltRingChainRunner.cs - Crafts Infinite Leaftide's ring inscription chain and applies the scrolls +// (Gear tab > Rings). SilentKelpie's RynthAi RingChainRunner (MiniRemote/Crafting/), moved to +// RynthILT 2026-10-15 and run on the ILT Hub's context; its settings are the Gear state's +// (IltGearState.RingRuns, RingAnswerCraftDialog, RingAllowInCombat), saved with the Hub. +// +// Tick runs on the pump thread; Render on the render thread reads the volatile snapshots and +// posts the commands (IltHubContext.Post / Confirm). +// Crafting: the queue from IltRingChain.Expand, one combine at a time: +// 1. gates: peace mode (unless allowed in combat for servers with combat crafting), not busy, +// no other ILT pack job (the split-arrow imbuer); +// 2. find the tool and the target by name; a later step's ingredients come out of the earlier +// combine, so a missing one is looked for again for a while (inventory lag) before giving up; +// 3. arm the engine's confirmation answer (API v85; Yes: the player queued it) and use tool on +// target; without v85 (or with the answer off) the player clicks Yes in AC's dialog; +// 4. the combine is done when the tool or the target stack shrinks or the output shows up. +// No sign of it stops the job instead of retrying, so nothing is crafted twice. +// Scrolls: each "Inscription of ..." scroll is used on its target (the item selected in AC, or +// the carried jewelry paired the UB-IT way) and is done when it leaves the pack. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using ImGuiNET; +using RynthCore.Loot; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One line of the Rings scan: a recipe header (Found null) or an ingredient. +/// 0 found, 1 comes from an earlier step, 2 missing. +internal sealed record IltRingScanLine(string Text, string? Found, int State); + +internal sealed class IltRingChainRunner : IIltFeature +{ + private const uint ErrorYoureTooBusy = 0x1D; + private const long StepTimeoutMs = 15_000; + /// The player answers AC's own dialog: give them time. + private const long ManualTimeoutMs = 60_000; + private const long StepGapMs = 700; + private const long RetryDelayMs = 1_500; + private const int MaxBusyRetries = 3; + /// A missing ingredient is looked for this often and this many times (~10 s). + private const long LookAgainMs = 250; + private const int LookTries = 40; + private const long RunsViewMs = 1000; + + private static readonly Regex CannotUse = new(@"^The .+ cannot be used on the .+\.$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private enum Mode { Idle, Craft, Apply } + + private readonly IltHubContext _ctx; + /// True while another ILT job (the split-arrow imbuer) is using the pack. + private readonly Func _blocked; + + // Job (pump thread) + private Mode _mode; + private List _queue = new(); + private List<(int Scroll, int Target)> _pairs = new(); + private int _index, _crafted, _lookTries, _busyRetries, _confSeq, _errSeq; + private bool _waiting, _manual; + private long _stepAt, _nextAt, _runsViewAt; + // Counts before the current combine (craft) / the scroll's stack (apply). + private long _toolBefore, _targetBefore, _outputBefore; + private int _scrollStackBefore; + + // Render snapshots + private volatile string _status = "idle"; + private volatile IltRingScanLine[] _scan = Array.Empty(); + private volatile (int Id, string Name)[] _scrolls = Array.Empty<(int, string)>(); + private volatile (int Id, string Name)[] _jewelry = Array.Empty<(int, string)>(); + // Runs per recipe (IltRingChain.Recipes order), copied from the Gear state on the pump. + private volatile int[] _runsView = new int[IltRingChain.Recipes.Length]; + private volatile bool _running; + + public IltRingChainRunner(IltHubContext ctx, Func blocked) + { + _ctx = ctx; + _blocked = blocked; + } + + public bool Running => _running; + public string Status => _status; + public IltRingScanLine[] ScanLines => _scan; + /// The inscription scrolls the last scan found. + public (int Id, string Name)[] Scrolls => _scrolls; + + private RynthCoreHost Host => _ctx.Host; + private IltInventory Inv => _ctx.Inventory; + private IltGearState G => _ctx.State.Gear; + + /// Pump thread: the saved run count for a recipe. + private int Runs(string id) => G.RingRuns.TryGetValue(id, out int n) ? n : 0; + + /// Pump thread: sets a recipe's run count (0 removes it) and the render copy. + public void SetRuns(string id, int runs) + { + runs = Math.Clamp(runs, 0, IltRingChain.MaxRuns); + if (runs == 0) G.RingRuns.Remove(id); + else G.RingRuns[id] = runs; + PublishRuns(); + } + + private void PublishRuns() + { + var view = new int[IltRingChain.Recipes.Length]; + for (int i = 0; i < view.Length; i++) view[i] = Runs(IltRingChain.Recipes[i].Id); + _runsView = view; + } + + // ── Inventory ─────────────────────────────────────────────────────────── + + private IEnumerable Carried() => Inv.Items().Where(w => !Inv.IsEquipped(w)); + + private WorldObject? Find(IltRingIngredient ing) => Carried().FirstOrDefault(w => IltRingChain.Matches(w.Name, ing)); + + private long Count(IltRingIngredient ing) => Carried().Where(w => IltRingChain.Matches(w.Name, ing)).Sum(w => (long)Inv.StackSize(w)); + + private long ScrollCount() => Carried().Where(w => IltRingChain.IsInscriptionScroll(w.Name)).Sum(w => (long)Inv.StackSize(w)); + + /// What a recipe makes, counted: Step 1 the enlightened quill, Step 2 the partition quill, Step 3 a scroll. + private long OutputCount(IltRingRecipe r) => r.Tier switch + { + 1 => Count(IltRingChain.Recipes[1].Tool), + 2 => Count(IltRingChain.Recipes[2].Tool), + _ => ScrollCount(), + }; + + // ── Scan ──────────────────────────────────────────────────────────────── + + /// + /// Lists every queued recipe's ingredients, marking the ones a later step only gets from an + /// earlier combine (UB-IT's "(after Step 1)"), the carried inscription scrolls and the carried + /// jewelry they can go on. Pump thread. + /// + public void Scan() + { + var lines = new List(); + bool Stocked(int tier) => IltRingChain.Recipes + .Where(r => r.Tier == tier && Runs(r.Id) > 0) + .All(r => Find(r.Tool) != null && Find(r.Target) != null); + bool tier1 = Stocked(1), tier2 = Stocked(2); + bool any = false, blocking = false; + foreach (var r in IltRingChain.Recipes) + { + int runs = Runs(r.Id); + if (runs <= 0) continue; + any = true; + lines.Add(new IltRingScanLine($"{r.Name} x{runs}", null, 0)); + foreach (var ing in new[] { r.Tool, r.Target }) + { + var found = Find(ing); + if (found != null) { lines.Add(new IltRingScanLine(ing.Label, $"{found.Name} ({Count(ing)})", 0)); continue; } + string? later = r.Tier == 2 && !tier1 ? "(after Step 1)" + : r.Tier == 3 && !tier1 ? "(after Step 1)" + : r.Tier == 3 && !tier2 ? "(after Step 2)" + : null; + if (later == null) blocking = true; + lines.Add(new IltRingScanLine(ing.Label, later ?? "(not found)", later == null ? 2 : 1)); + } + } + _scan = lines.ToArray(); + RefreshScrolls(); + _status = !any ? "set how many times to craft at least one recipe" + : blocking ? "missing ingredients are marked (not found)" + : "ready: Create runs every Step 1, then Step 2, then Step 3"; + } + + private void RefreshScrolls() + { + _scrolls = Carried().Where(w => IltRingChain.IsInscriptionScroll(w.Name)) + .Select(w => (w.Id, w.Name ?? string.Empty)) + .OrderBy(s => IltRingChain.ScrollOrderKey(s.Item2), StringComparer.Ordinal) + .ToArray(); + _jewelry = Carried().Where(w => w.ObjectClass == AcObjectClass.Jewelry) + .Select(w => (w.Id, w.Name ?? string.Empty)) + .OrderBy(j => j.Id) + .ToArray(); + } + + // ── Job control (pump thread) ─────────────────────────────────────────── + + /// Crafts the queued recipes (after the tab's confirm). + public void Create() + { + if (_running) return; + if (_blocked()) { _status = "the split-arrow imbuer is running"; return; } + var queue = IltRingChain.Expand(Runs); + if (queue.Count == 0) { _status = "set how many times to craft at least one recipe"; return; } + Begin(Mode.Craft); + _queue = queue; + _status = $"crafting {queue.Count} combine(s)"; + RynthLog.Write(LogCat.IltGear, $"[Rings] create, {queue.Count} combine(s)"); + } + + /// Uses one scroll on the item selected in AC. + public void ApplyToSelected(int scrollId) + { + uint sel = Host.GetSelectedItemId(); + if (sel == 0) { _status = "select the ring or item in AC first"; return; } + if (unchecked((int)sel) == scrollId) { _status = "the scroll itself is selected: select the ring or item"; return; } + ApplyPairs(new List<(int, int)> { (scrollId, unchecked((int)sel)) }); + } + + /// Pairs the carried scrolls with these items (the carried jewelry) and uses them. + public void ApplyToItems(IReadOnlyList targetIds) + { + RefreshScrolls(); + if (_scrolls.Length == 0) { _status = "no inscription scroll in the pack (name has \"Inscription of\")"; return; } + if (targetIds.Count == 0) { _status = "no jewelry carried (worn items aren't inscribed)"; return; } + ApplyPairs(IltRingChain.PairScrolls(_scrolls, targetIds)); + } + + private void ApplyPairs(List<(int Scroll, int Target)> pairs) + { + if (_running) return; + if (_blocked()) { _status = "the split-arrow imbuer is running"; return; } + if (pairs.Count == 0) { _status = "nothing to apply"; return; } + Begin(Mode.Apply); + _pairs = pairs; + _status = $"applying {pairs.Count} inscription(s)"; + RynthLog.Write(LogCat.IltGear, $"[Rings] apply {pairs.Count} inscription(s)"); + } + + private void Begin(Mode mode) + { + _mode = mode; + _index = 0; + _crafted = 0; + _lookTries = 0; + _busyRetries = 0; + _waiting = false; + _nextAt = 0; + _running = true; + } + + public void Stop(string why) + { + if (_waiting && Host.HasConfirmationAnswers) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0); + _mode = Mode.Idle; + _waiting = false; + _running = false; + _queue = new List(); + _pairs = new List<(int, int)>(); + _status = why; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void OnLogout() + { + Stop("idle"); + _scan = Array.Empty(); + _scrolls = Array.Empty<(int, string)>(); + _jewelry = Array.Empty<(int, string)>(); + } + + public void Tick(long nowMs) + { + if (nowMs - _runsViewAt >= RunsViewMs) + { + // A profile load replaces the Gear state: follow it. + _runsViewAt = nowMs; + PublishRuns(); + } + if (_mode == Mode.Idle) return; + if (_waiting) { Wait(nowMs); return; } + if (nowMs < _nextAt) return; + if (!G.RingAllowInCombat && !Inv.InPeaceMode) { _status = "waiting for peace mode"; return; } + if (Inv.IsBusy) return; + + if (_mode == Mode.Craft) NextCombine(nowMs); + else NextScroll(nowMs); + } + + private void NextCombine(long nowMs) + { + if (_index >= _queue.Count) + { + Stop($"done - {_crafted} combine(s)"); + RefreshScrolls(); + RynthLog.Write(LogCat.IltGear, $"[Rings] done, {_crafted} combine(s)"); + return; + } + var r = _queue[_index]; + var tool = Find(r.Tool); + var target = Find(r.Target); + if (tool == null || target == null) + { + string label = tool == null ? r.Tool.Label : r.Target.Label; + if (++_lookTries <= LookTries) + { + _nextAt = nowMs + LookAgainMs; + _status = $"{r.Name}: looking for {label}"; + return; + } + Stop($"{r.Name}: no {label} in the pack"); + return; + } + _lookTries = 0; + + _toolBefore = Count(r.Tool); + _targetBefore = Count(r.Target); + _outputBefore = OutputCount(r); + if (!Use(tool, target, $"Rings: {r.Name} ({_index + 1}/{_queue.Count})")) + { + Stop($"{r.Name}: the use request didn't go out"); + return; + } + string ask = _manual ? " - click Yes in AC's craft dialog" : ""; + _status = $"{r.Name} ({_index + 1}/{_queue.Count}): {tool.Name} on {target.Name}{ask}"; + } + + private void NextScroll(long nowMs) + { + if (_index >= _pairs.Count) + { + Stop($"done - {_crafted} inscription(s) applied"); + RefreshScrolls(); + return; + } + var (scrollId, targetId) = _pairs[_index]; + var scroll = Inv.Cache?[scrollId]; + var target = Inv.Cache?[targetId]; + if (scroll == null || target == null) + { + // UB-IT moves on past a pair whose scroll or item is gone. + _status = $"inscription {_index + 1}: the scroll or the item is gone - skipped"; + _index++; + _nextAt = nowMs + StepGapMs; + return; + } + if (Inv.IsEquipped(target)) { Stop($"{target.Name} is equipped: take it off to inscribe it"); return; } + _scrollStackBefore = Inv.StackSize(scroll); + if (!Use(scroll, target, $"Rings: {scroll.Name} on {target.Name}")) + { + Stop("the use request didn't go out"); + return; + } + string ask = _manual ? " - click Yes in AC's dialog" : ""; + _status = $"inscription {_index + 1}/{_pairs.Count}: {scroll.Name} on {target.Name}{ask}"; + } + + /// Arms the dialog answer (Yes: the player asked for this) and uses source on target. + private bool Use(WorldObject source, WorldObject target, string why) + { + _manual = !(G.RingAnswerCraftDialog && Host.HasConfirmationAnswers + && Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, (int)StepTimeoutMs) == 1); + _confSeq = Host.TryGetLastConfirmation(out int cs, out _, out _, out _, out _) ? cs : 0; + _errSeq = Host.TryGetLastWeenieError(out int es, out _, out _, out _) ? es : 0; + if (!Host.UseOnFor(unchecked((uint)source.Id), unchecked((uint)target.Id), "IltRings", why, UseKind.Asked)) + { + if (!_manual) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0); + return false; + } + _waiting = true; + _stepAt = Environment.TickCount64; + return true; + } + + private void Wait(long nowMs) + { + if (Host.TryGetLastConfirmation(out int seq, out uint type, out int pct, out int outcome, out _) + && seq != _confSeq && type == RynthCoreHost.ConfirmationKind.CraftInteraction) + { + _confSeq = seq; + if (outcome == RynthCoreHost.ConfirmationOutcome.Declined) { Stop("the craft dialog was answered No"); return; } + if (outcome is RynthCoreHost.ConfirmationOutcome.Shown or RynthCoreHost.ConfirmationOutcome.SendFailed) + { + _manual = true; + _status = $"click Yes in AC's craft dialog ({(pct >= 0 ? pct + "%" : "chance not shown")})"; + } + } + + if (Host.TryGetLastWeenieError(out int es, out uint error, out _, out _) && es != _errSeq) + { + _errSeq = es; + // Busy: the server did nothing, so the same combine can go again. + if (error == ErrorYoureTooBusy && ++_busyRetries <= MaxBusyRetries) + { + _waiting = false; + _nextAt = nowMs + RetryDelayMs; + _status = $"server says busy - trying again ({_busyRetries}/{MaxBusyRetries})"; + return; + } + Stop($"the server refused it (error 0x{error:X})"); + return; + } + + if (Done()) { Next(nowMs); return; } + + if (nowMs - _stepAt > (_manual ? ManualTimeoutMs : StepTimeoutMs)) + Stop(_manual ? "no answer to AC's dialog - stopped" : "no result seen - stopped (check the pack before going on)"); + } + + /// The current combine or inscription went through. + private bool Done() + { + if (_mode == Mode.Craft) + { + var r = _queue[_index]; + return Count(r.Tool) < _toolBefore || Count(r.Target) < _targetBefore || OutputCount(r) > _outputBefore; + } + var scroll = Inv.Cache?[_pairs[_index].Scroll]; + return scroll == null || Inv.StackSize(scroll) < _scrollStackBefore; + } + + private void Next(long nowMs) + { + _waiting = false; + _busyRetries = 0; + _crafted++; + _index++; + _nextAt = nowMs + StepGapMs; + } + + /// "cannot be used on" ends the job: the names didn't match what the server expects. Never eaten. + public bool OnChat(string text) + { + if (!_waiting || string.IsNullOrEmpty(text)) return false; + if (CannotUse.IsMatch(text)) Stop(text); + return false; + } + + // ── UI (render thread) ────────────────────────────────────────────────── + + /// The ring inscription chain: runs per recipe, Scan / Create / Stop, then the scrolls. + public void Render() + { + ImGui.TextDisabled("Quill of Infliction -> Enlightened Quill -> partition quill -> glyph -> Inscription scroll -> ring."); + int[] runsView = _runsView; + if (ImGui.BeginTable("##ringrecipes", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp)) + { + ImGui.TableSetupColumn("Runs", ImGuiTableColumnFlags.WidthFixed, 100); + ImGui.TableSetupColumn("Recipe"); + for (int i = 0; i < IltRingChain.Recipes.Length; i++) + { + var r = IltRingChain.Recipes[i]; + ImGui.PushID(r.Id); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + int n = i < runsView.Length ? runsView[i] : 0; + ImGui.SetNextItemWidth(90); + if (ImGui.InputInt("##runs", ref n, 1)) + { + string id = r.Id; + int runs = Math.Clamp(n, 0, IltRingChain.MaxRuns); + var shown = (int[])runsView.Clone(); + shown[i] = runs; + _runsView = shown; // shown at once; the pump saves it and republishes + _ctx.Post(() => SetRuns(id, runs)); + } + ImGui.TableNextColumn(); + ImGui.TextUnformatted(r.Name); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(r.Notes); + ImGui.PopID(); + } + ImGui.EndTable(); + } + + bool answer = G.RingAnswerCraftDialog, combat = G.RingAllowInCombat; + if (ImGui.Checkbox("Answer the craft dialog##rings", ref answer)) G.RingAnswerCraftDialog = answer; + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Answers AC's craft confirmation Yes for each combine you queued (needs RynthCore plugin API v85).\nOff, or on an older RynthCore: click Yes in AC's dialog yourself."); + ImGui.SameLine(); + if (ImGui.Checkbox("Allow in combat mode##rings", ref combat)) G.RingAllowInCombat = combat; + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Only for servers that allow crafting in combat mode."); + + bool running = Running; + bool blocked = _blocked(); + ImGui.BeginDisabled(running); + if (ImGui.Button("Scan##rings")) _ctx.Post(Scan); + ImGui.SameLine(); + ImGui.BeginDisabled(blocked); + if (ImGui.Button("Create##rings")) + { + int[] view = _runsView; + int total = IltRingChain.Expand(id => + { + int k = Array.FindIndex(IltRingChain.Recipes, x => x.Id == id); + return k >= 0 && k < view.Length ? view[k] : 0; + }).Count; + _ctx.Confirm("Rings chain", $"Craft {total} combine(s)?\n\nEvery Step 1 run goes first, then Step 2, then Step 3.\nThe ingredients are used up.", + Create, "Create"); + } + ImGui.EndDisabled(); + ImGui.EndDisabled(); + ImGui.SameLine(); + ImGui.BeginDisabled(!running); + if (ImGui.Button("Stop##rings")) _ctx.Post(() => Stop("stopped by player")); + ImGui.EndDisabled(); + ImGui.SameLine(); + if (blocked && !running) ImGui.TextColored(IltStyle.ColAmber, "the split-arrow imbuer is running"); + else SafeImGui.TextDisabled(Status); + + var lines = ScanLines; + if (lines.Length > 0 && ImGui.BeginTable("##ringscan", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.Borders | ImGuiTableFlags.SizingStretchProp)) + { + foreach (var l in lines) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + if (l.Found == null) { SafeImGui.TextColored(IltStyle.ColTeal, l.Text); continue; } + ImGui.TextUnformatted(" " + l.Text); + ImGui.TableNextColumn(); + if (l.State == 0) ImGui.TextUnformatted(l.Found); + else if (l.State == 1) SafeImGui.TextDisabled(l.Found); + else SafeImGui.TextColored(IltStyle.ColAmber, l.Found); + } + ImGui.EndTable(); + } + + ImGui.Separator(); + RenderScrolls(running || blocked); + } + + /// The carried inscription scrolls: one to the selected item, or all to the carried jewelry. + private void RenderScrolls(bool busy) + { + ImGui.TextColored(IltStyle.ColTeal, "Inscription scrolls"); + var scrolls = Scrolls; + if (scrolls.Length == 0) { ImGui.TextDisabled("None carried (Scan to look again)."); return; } + + ImGui.BeginDisabled(busy); + foreach (var (id, name) in scrolls) + { + ImGui.PushID(id); + if (ImGui.SmallButton("Apply to selected")) + { + int scrollId = id; + string scrollName = name; + _ctx.Confirm("Ring inscription", $"Use {scrollName} on the item selected in AC?", + () => ApplyToSelected(scrollId), "Apply"); + } + ImGui.SameLine(); + ImGui.TextUnformatted(name); + ImGui.PopID(); + } + + // UB-IT pairs the scrolls with a scan's items; here the carried (not worn) jewelry. + var jewelry = _jewelry; + var targets = jewelry.Select(j => j.Id).ToList(); + ImGui.BeginDisabled(targets.Count == 0); + if (ImGui.Button($"Apply all to the carried jewelry ({targets.Count})")) + { + int pairs = Math.Min(targets.Count, scrolls.Length); + _ctx.Confirm("Ring inscriptions", $"Use {pairs} inscription scroll(s) on the carried jewelry, one each?", + () => ApplyToItems(targets), "Apply"); + } + ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + SafeImGui.SetTooltip("Scrolls in glyph order go on the jewelry in your pack (not worn) in id order (UB-IT's pairing).\n" + + (jewelry.Length == 0 ? "No jewelry carried (Scan to look again)." + : string.Join("\n", jewelry.Select(j => j.Name)))); + ImGui.EndDisabled(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingEvade.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingEvade.cs new file mode 100644 index 0000000..aa7eb6d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingEvade.cs @@ -0,0 +1,121 @@ +// IltRingEvade.cs — Infinite Leaftide's Empyrean Handler lethal ring: hear it, and have RynthAi jump clear. +// Moved out of RynthAi's CombatManager 2026-10-20 (Silentkelpie's PR 12): the Handler is ACECustom +// content, so the detection and its setting are RynthILT's; RynthAi keeps the generic back-away it +// does on request (RynthAi.Hub BackAwayFrom: face the danger, run-back jump, hold attacks until the +// jump settles, re-engage the same target; only while its macro runs with combat on). +// +// ACECustom's Handler emote: "The handler briefly channels infused Empyrean hatred to release a lethal +// ring." The ring can't be melee-evaded; inside its cast radius the character dies. On that line, when +// an Empyrean Handler is near, ask RynthAi to back away from the nearest one (12 yards, or Ring Range +// when RynthAi's is larger). One request per HandlerRingCooldownMs. +// Setting: IltHubState.Combat.HandlerRingEvade (on by default; the ILT settings view, "/ilt settings"). +using System; +using RynthCore.Loot; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltRingEvade : IIltFeature +{ + internal const string ChannelHint = "channels infused Empyrean hatred to release a lethal ring"; + internal const string ChannelStart = "The handler briefly channels"; + internal const string HandlerName = "Empyrean Handler"; + /// Yards: the Handler's lethal ring is treated as at least this wide (RynthAi widens it to Ring Range). + internal const float DangerYards = 12f; + /// Back-jump charge (ms): run-back + jump must clear about the ring's radius. + internal const int JumpHoldMs = 750; + internal const long CooldownMs = 4_000; + + private readonly IltHubContext _ctx; + private long _lastRequestAt = long.MinValue; + + public IltRingEvade(IltHubContext ctx) => _ctx = ctx; + + /// What the last ring line did (for the log and the tests). + public string LastOutcome { get; private set; } = string.Empty; + + /// + /// True when is the Handler's channel line (not a player repeating it). + /// The channel is an Emote (0x0C), which counts as player speech elsewhere, so it is anchored on + /// the phrase that starts the line; mid-line only for a chat type that can't be player speech. + /// + internal static bool IsChannelLine(string? text, int chatType) + { + if (string.IsNullOrEmpty(text)) return false; + bool anchored = + ChatSource.StartsWithMarker(text, ChannelStart, StringComparison.OrdinalIgnoreCase) + || (ChatSource.StartsWithMarker(text, "The handler", StringComparison.OrdinalIgnoreCase) + && text.IndexOf(ChannelHint, StringComparison.OrdinalIgnoreCase) >= 0); + if (anchored) return true; + // Mid-line only when the type is clearly not player speech (some clients strip "The "). + if (chatType is ChatSource.Speech or ChatSource.Tell or ChatSource.OutgoingTell or ChatSource.Channel + or ChatSource.ChannelSend or ChatSource.Allegiance or ChatSource.Fellowship) + return false; + if (text.IndexOf(ChannelHint, StringComparison.OrdinalIgnoreCase) < 0) return false; + return text.IndexOf(" says,", StringComparison.OrdinalIgnoreCase) < 0 + && text.IndexOf(" tells you,", StringComparison.OrdinalIgnoreCase) < 0; + } + + /// + /// A chat line with its type (pump thread; IltHubController.OnChat, ILT only). On the Handler's + /// channel line asks RynthAi to back away from the nearest Handler. Never eats the line. + /// + public void OnChatLine(string text, int chatType) + { + if (!_ctx.State.Combat.HandlerRingEvade || !IsChannelLine(text, chatType)) return; + long now = IltHubContext.NowMs; + if (_lastRequestAt != long.MinValue && now - _lastRequestAt < CooldownMs) return; + + if (!TryFindNearestHandler(out int handlerId, out double dist)) + { + Outcome("Handler lethal-ring channel heard, but no Empyrean Handler is nearby: no jump."); + return; + } + _lastRequestAt = now; + int r = _ctx.Ai.BackAwayFrom(unchecked((uint)handlerId), DangerYards, JumpHoldMs); + Outcome(r switch + { + RynthAiHub.BackAwayStarted => $"Empyrean Handler lethal ring: RynthAi backs away from it ({dist:0.0} m).", + RynthAiHub.BackAwayOutside => $"Empyrean Handler lethal ring: the Handler is {dist:0.0} m away, outside the ring; staying put.", + RynthAiHub.BackAwayUnknownObject => "Empyrean Handler lethal ring: RynthAi has no position for the Handler; no jump.", + RynthAiHub.BackAwayJumpRefused => "Empyrean Handler lethal ring: in range, but RynthAi's back-jump did not start.", + int.MinValue => "Empyrean Handler lethal ring: " + RynthAiClient.NotLoaded + " (the back-away is RynthAi's).", + _ => "Empyrean Handler lethal ring: RynthAi isn't fighting (macro or combat off), so it doesn't take the keyboard.", + }); + } + + private void Outcome(string text) + { + LastOutcome = text; + RynthLog.Write(LogCat.IltHub, "[RingEvade] " + text); + } + + /// The nearest Empyrean Handler the client knows (a creature with that in its name). + private bool TryFindNearestHandler(out int id, out double dist) + { + id = 0; + dist = double.MaxValue; + var objects = _ctx.Inventory.Cache; + int me = unchecked((int)_ctx.Inventory.PlayerId); + if (me == 0) return false; + foreach (var wo in objects.GetLandscape()) + { + if (wo == null || wo.ObjectClass != AcObjectClass.Monster) continue; + if (wo.Name.IndexOf(HandlerName, StringComparison.OrdinalIgnoreCase) < 0) continue; + double d = objects.Distance(me, wo.Id); + if (d >= dist) continue; + dist = d; + id = wo.Id; + } + return id != 0; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) { } + + /// Unused: the controller passes the chat type (OnChatLine). + public bool OnChat(string text) => false; + + public void OnLogout() => _lastRequestAt = long.MinValue; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs new file mode 100644 index 0000000..342c92a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs @@ -0,0 +1,81 @@ +// IltSalvage.cs - Infinite Leaftide's own tinkering salvage, for the Mini Remote's Crafting tab. +// +// Served through RynthILT's "RynthServer.Profile" JSON (ProfileInterface.cs, the "salvage" list), +// which RynthAi's Crafting tab shows under "Server tinkering" on ILT; RynthAi itself knows no +// server's recipes. Taken from UB-IT's LeaftideImbueHelper via SilentKelpie (his RynthAi Crafting +// tab, rynth/RynthSuite PR 12, moved here 2026-10-15): the weapon crit lines (Yellow Garnet, +// Turquoise, White Quartz, Abyssal-Touched Gems, Tourmaline, Wool), Tiger Eye on missile weapons, +// Leather as the post-cap tink, the jewelry rating salvages (Silver, Copper, Green Jade, +// Tourmaline, and Serpentine + Steel sharing a cap of 10) and the trinket tiers (Diamond, Ruby, +// Gromnie Hide, Pyreal, prepared on Ammunition). ILT's recipes live in its database, so their +// chances are the server's: the Crafting runner reads the confirmation's percent. +using RynthCore.Plugin.ServerPack; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal static class IltSalvage +{ + /// + /// Leaftide trinkets (compass, goggles, scarab, watch, puzzle box, tops): jewelry that takes the + /// Trinkets bench's recipes (UB-IT's IsLeaftideTrinketJewelry; RynthAi's TinkerCatalog.IsTrinket until + /// 2026-10-20). Sent in the profile's "trinkets" (RynthServer.Profile). + /// + internal static readonly string[] TrinketNames = { "compass", "goggles", "scarab", "watch", "puzzle box", "top" }; + /// "top" but not "topaz". + internal static readonly string[] TrinketExcept = { "topaz" }; + + // MaterialType (131) ids. + private const int Wool = 8, BlackGarnet = 15, Diamond = 20, GreenJade = 24, Ruby = 38, TigerEye = 42, Tourmaline = 43, + Turquoise = 44, WhiteQuartz = 46, YellowGarnet = 48, Leather = 52, GromnieHide = 54, Copper = 59, Pyreal = 62, + Silver = 63, Steel = 64, Serpentine = 71; + + // ILT's flag ints on the item: 2 = that salvage is on. + public const int IntJewelCopper = 370, IntJewelGreenJade = 371, IntJewelSilver = 374, IntJewelTourmaline = 375; + public const int IntTrinketDiamond = 384, IntTrinketRuby = 385, IntTrinketGromnie = 386, IntTrinketPyreal = 387; + + /// Steel and Serpentine stack on ILT jewelry, at most this many combined. + public const string JewelryStackGroup = "jewelry-stack"; + public const int JewelryStackCap = 10; + + private const string Once = "once", Tink = "tink"; + private const string PostCap = "100% tink once the 10 ordinary tinks are on"; + + public static readonly ServerSalvage[] Rows = + { + new("melee", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70), + new("melee", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80), + new("melee", WhiteQuartz, "Cleaving (no tink slot)", Once, UsesTinkSlot: false, Order: 90), + new("melee", BlackGarnet, "Crit line (bag of Abyssal-Touched Gems)", Once, NameMatch: "Abyssal", Order: 100), + new("melee", Tourmaline, "Crit line (no tink slot)", Once, UsesTinkSlot: false, Order: 104), + new("melee", Wool, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 108), + new("melee", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true), + + new("missile", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70), + new("missile", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80), + new("missile", BlackGarnet, "Crit line (bag of Abyssal-Touched Gems)", Once, NameMatch: "Abyssal", Order: 100), + new("missile", Tourmaline, "Crit line (no tink slot)", Once, UsesTinkSlot: false, Order: 104), + new("missile", Wool, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 108), + new("missile", TigerEye, "+missile defense bonus", Tink, Order: 230), + new("missile", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true), + + new("caster", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70), + new("caster", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80), + new("caster", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true), + + // ILT keeps these in their own ints (370-376) with their own cap, not the 10 tinker slots. + new("jewelry", Silver, "+1 critical damage rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelSilver, Order: 10), + new("jewelry", Copper, "+1 damage rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelCopper, Order: 20), + new("jewelry", GreenJade, "+1 damage resist rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelGreenJade, Order: 30), + new("jewelry", Tourmaline, "+1 critical damage resist rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelTourmaline, Order: 40), + new("jewelry", Serpentine, "+1 critical rating (stacks with Steel, 10 max)", Tink, UsesTinkSlot: false, Order: 50, + StackGroup: JewelryStackGroup, StackCap: JewelryStackCap), + new("jewelry", Steel, "Steel stack tier (stacks with Serpentine, 10 max)", Tink, UsesTinkSlot: false, Order: 60, + StackGroup: JewelryStackGroup, StackCap: JewelryStackCap), + + // UB-IT's trinket imbues, in its order: Diamond, Ruby, Gromnie Hide, Pyreal. + new("trinkets", Diamond, "Trinket tier: Diamond", Once, UsesTinkSlot: false, AppliedInt: IntTrinketDiamond, Prepared: true, Order: 10), + new("trinkets", Ruby, "Trinket tier: Ruby", Once, UsesTinkSlot: false, AppliedInt: IntTrinketRuby, Prepared: true, Order: 20), + new("trinkets", GromnieHide, "Trinket tier: Gromnie Hide", Once, UsesTinkSlot: false, AppliedInt: IntTrinketGromnie, Prepared: true, Order: 30), + new("trinkets", Pyreal, "Trinket tier: Pyreal", Once, UsesTinkSlot: false, AppliedInt: IntTrinketPyreal, Prepared: true, Order: 40), + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs new file mode 100644 index 0000000..0972686 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs @@ -0,0 +1,144 @@ +// IltSections.cs - The Infinite Leaftide tabs of RynthAi's Mini Remote and the Guardian panel. +// Originally SilentKelpie's ILT Hub sections (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// Banking, Gear, Charms, Games and Vaulted Dungeons are Mini Remote tabs: RynthAi's MiniRemoteHud draws the tab bar +// (after its Remote, Pets and Crafting tabs) and asks RynthILT for each tab's body (RynthILT.Hub +// GetTabs / RenderTab); "/ra hub open
" picks one, and with RynthCore's sections rail +// RynthAi lists them as "section:" views (Inventory). Guardian is a RynthCore ILT panel +// instead (the bar's ILT button, next to Bounties; "/rc guardian"), drawn by this plugin through +// RynthPluginRenderEmbed("guardian"). The Pets tab is RynthAi's (every server: summoning essences +// aren't ILT's); quests are RynthOracle's. +// +// Character was a Mini Remote tab until 2026-10-13. It moved out: +// the character overview and session -> RynthOracle's Character tab ("/ro character"); +// the ILT session rates -> RynthCore's Mini Remote "Session Stats" section +// (RynthILT's own surface "section:ilt-rates"); +// the force-server override -> RynthCore Options > Diagnostics only. +// Its names still parse, so old links and commands land on the new home (MovedCommand). Charms and +// Banking are Infinite Leaftide's own screens and stay RynthILT's tabs. +using System; +using System.Numerics; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// ILT sections: the Mini Remote's ILT tabs, the one that moved out, then the Guardian panel. +internal enum IltSection +{ + /// Moved out (2026-10-13): RynthOracle's Character tab and the Session Stats section. + Character, + Banking, + Gear, + Games, + /// + /// Vaulted Dungeons keeper (portal-recall gem + kill-client). A Mini Remote tab on ILT worlds only, + /// and only while its "Vaulted Dungeons" master switch (/ilt settings, Settings > Navigation) is on. + /// + VaultedDungeons, + /// Registry charms (acquired / status / tier / server) and the Guardian Hand. + Charms, + // Keep Guardian last. + Guardian, +} + +internal static class IltSections +{ + /// The ILT tabs, in tab-bar order (RynthAi puts them after its own tabs). + public static readonly IltSection[] Tabs = + { + IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, IltSection.VaultedDungeons, + }; + + /// The Mini Remote's own tab (the remote itself): its tab id. + public const string RemoteTab = ""; + + /// RynthOracle's Character tab: the character overview and this session. + public const string OracleCharacterCommand = "/ro character"; + + public static string Label(IltSection s) => s switch + { + IltSection.Character => "Character", + IltSection.Banking => "Banking", + IltSection.Gear => "Gear", + IltSection.Games => "Games", + IltSection.VaultedDungeons => "Vaulted Dungeons", + IltSection.Charms => "Charms", + IltSection.Guardian => "Guardian", + _ => s.ToString(), + }; + + /// + /// The section's tab id: saved as RynthAi's HudState.MiniRemoteTab and sent by the engine's + /// dashboard ("/ra hub tab <id>", "/rc miniremote tab <id>"). TryParse reads it back. + /// + public static string TabId(IltSection s) => s switch + { + IltSection.Character => "character", + IltSection.Banking => "banking", + IltSection.Gear => "gear", + IltSection.Games => "games", + IltSection.VaultedDungeons => "vaulted", + IltSection.Charms => "charms", + IltSection.Guardian => "guardian", + _ => s.ToString().ToLowerInvariant(), + }; + + /// True for the sections drawn as Mini Remote tabs (Banking, Gear, Charms, Games, Vaulted Dungeons). + public static bool IsTab(IltSection s) => s is IltSection.Banking or IltSection.Gear or IltSection.Charms or IltSection.Games + or IltSection.VaultedDungeons; + + /// + /// Where a section that moved out of the Mini Remote lives now, as the chat command that opens + /// it; null for a section that is still RynthILT's (a tab or the Guardian panel). + /// + public static string? MovedCommand(IltSection s) => s switch + { + IltSection.Character => OracleCharacterCommand, + _ => null, + }; + + /// "quests" / "pets" (and their aliases): not ILT sections (RynthAi's Pets tab, RynthOracle's quests). + public static bool IsUniversalTabName(string text) => (text ?? string.Empty).Trim().ToLowerInvariant() switch + { + "quests" or "quest" or "pets" or "pet" => true, + _ => false, + }; + + /// Parses a "/ra hub open" section name (a few aliases accepted). + public static bool TryParse(string text, out IltSection section) + { + switch ((text ?? string.Empty).Trim().ToLowerInvariant()) + { + case "character": case "char": case "rates": section = IltSection.Character; return true; + case "banking": case "bank": section = IltSection.Banking; return true; + case "gear": section = IltSection.Gear; return true; + case "games": case "game": section = IltSection.Games; return true; + case "vaulted": case "vaulteddungeons": case "vaulted-dungeons": + section = IltSection.VaultedDungeons; return true; + case "charms": case "charm": section = IltSection.Charms; return true; + case "guardian": case "temple": case "riddle": section = IltSection.Guardian; return true; + default: section = IltSection.Gear; return false; + } + } + + /// + /// Size of a Mini Remote tab's body (the old section window's default size): the tab draws in a + /// child this big, and the Mini Remote (or the engine window hosting it) fits to it. + /// + public static Vector2 TabSize(IltSection section) => section switch + { + IltSection.Banking => new Vector2(560, 520), + IltSection.Gear => new Vector2(560, 520), + IltSection.Charms => new Vector2(560, 520), + IltSection.Games => new Vector2(520, 440), + IltSection.VaultedDungeons => new Vector2(360, 420), + _ => new Vector2(520, 440), + }; + + /// "show" / "hide" / "toggle" (anything else toggles) applied to the current state. + public static bool Resolve(string mode, bool current) => (mode ?? string.Empty).ToLowerInvariant() switch + { + "show" or "on" or "open" => true, + "hide" or "off" or "close" => false, + _ => !current, + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltServerOptions.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltServerOptions.cs new file mode 100644 index 0000000..15ddef1 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltServerOptions.cs @@ -0,0 +1,376 @@ +// IltServerOptions.cs — Per-feature enable bits for the ILT Hub, read from the server. +// Originally SilentKelpie's ILT Hub (RynthAi); moved to RynthILT 2026-10-13. +// +// UB gated every Leaftide tool on a single test (WorldName == "InfiniteLeaftide" or a +// Force checkbox). That lies on shards where the operator turned Powerball, /myquests or +// a charm off. This module instead keeps one tri-state bit per feature: +// * World identity: ServerFeatureGate (RynthILT's server list, or this character's +// override / the Hub's ForceLeaftideFeatures) decides whether we even ASK — it never +// switches a feature on by itself. +// * Everything is decided on the Rynth side: the server is never asked for a feature list +// (ACECustom has none; "/ilt features" prints "Coming Soon"). IltFeatureCatalog's ILT +// profile says what the server runs, and these bits only record what the server returned: +// * Login probe: one pass of read-only commands (/bank, /aug, /qb, /pets, /shinies, /xp, +// /pb, /blackjack, /fblackjack, /clap with no args). Replies are eaten. +// /enl is NEVER probed — it opens the enlightenment confirmation dialog. +// * Passive: explicit server refusals seen in chat at any time flip a bit to Off +// ("Powerball lottery is not currently active", "myquests is not currently enabled", ...), +// and lines only an enabled feature sends flip it On (a summon-time pyreal refill). +// Unknown bits are treated as OFF by anything that spends currency or runs automation. +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthILT.IltSettingsView; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// Feature keys used by the gate table. +internal static class IltFeature +{ + public const string Bank = "bank"; + public const string Aug = "aug"; + public const string Enl = "enl"; + public const string Qb = "qb"; + public const string Pets = "pets"; + public const string Shinies = "shinies"; + public const string Xp = "xp"; + public const string Blackjack = "blackjack"; + public const string FBlackjack = "fblackjack"; + public const string Powerball = "powerball"; + public const string Quests = "quests"; + public const string Clap = "clap"; + public const string PetRefill = "pet_refill"; + public const string UniversalMastery = "universal_mastery"; + public const string RequireComps = "require_spell_comps"; + public const string PetBond = "pet_bond"; + public const string PetPotency = "pet_potency"; + + /// Key for a per-charm "enabled" bit, e.g. Charm("Guardian Hand") → "charm:guardianhand". + public static string Charm(string charmName) + { + var chars = (charmName ?? string.Empty).Where(char.IsLetterOrDigit).Select(char.ToLowerInvariant).ToArray(); + return "charm:" + new string(chars); + } +} + +/// Tri-state feature value. +internal enum IltTri { Unknown = -1, Off = 0, On = 1 } + +internal sealed class IltServerOptions +{ + private readonly RynthCoreHost _host; + private readonly IltChatCapture _capture; + private readonly IltHubState _state; + private readonly Action _chat; + private readonly Func _settings; + + /// Feeds probe replies to features that can reuse them (e.g. /bank → Banking balances). + public Action? ProbeReplyTap; + + private bool _refreshInFlight; + private int _probesOutstanding; + private long _loginAt; + private bool _loginRefreshDone; + + /// Wait this long after login before the one-shot refresh so chat/world are settled. + private const long LoginRefreshDelayMs = 6000; + + /// + /// Upper bound on waiting for the world name. The engine hook / launch-context file can report + /// it well after the 6 s delay (late inject, Decal coexistence); deciding "not ILT" on an empty + /// name would leave every feature bit Unknown and the Hub hidden for the whole session. + /// + private const long WorldNameWaitMs = 60000; + + public IltServerOptions(RynthCoreHost host, IltChatCapture capture, IltHubState state, Action chat, + Func? settings = null) + { + _host = host; + _capture = capture; + _state = state; + _chat = chat; + _settings = settings ?? (() => null); + } + + // ── Identity ──────────────────────────────────────────────────────────── + + /// World name as reported by the engine login hook (empty if unknown). + public string WorldName + { + get + { + if (_host.HasGetWorldName && _host.TryGetWorldName(out string n) && !string.IsNullOrWhiteSpace(n)) + return n.Trim(); + return _state.ServerOptions.WorldName ?? string.Empty; + } + } + + /// RynthCore's id for Infinite Leaftide in its server verdicts. + public const string EngineServerId = "ilt"; + + /// + /// RynthCore (2026.10.5.47+) decides whether this is Infinite Leaftide: one world check for + /// the engine and every plugin, with its per-character override ("/rc server ilt on|off|auto"). + /// True once its first verdict has arrived (IltEngineVerdict). + /// + public static bool EngineDecides => IltEngineVerdict.Active.HasValue; + + /// + /// RynthILT's own verdict: the world name is in the server list (IltSettings), or this + /// character's "Treat this world as ILT" is on (ServerFeatureGate). This is what the status + /// export reports to the engine, which adds it to its own detection (never echo the engine's + /// verdict back, or it would latch on). + /// + public bool IsIltLikeWorldLocal + { + get + { + if (_state.ForceLeaftideFeatures) return true; + IltSettings? s; + try { s = _settings(); } catch { s = null; } + return ServerFeatureGate.IsEnabled(WorldName, s, _state.ForceLeaftideFeatures); + } + } + + /// + /// True when the world is (or is declared to be) an ACECustom/ILT shard. With a RynthCore + /// that sends server verdicts, its verdict (which already includes ours, IsIltLikeWorldLocal, + /// unless this character's override is off); otherwise our own. + /// + public bool IsIltLikeWorld + { + get + { + bool? engine = IltEngineVerdict.Active; + return engine ?? IsIltLikeWorldLocal; + } + } + + /// True while the login probe is running. + public bool IsRefreshing => _refreshInFlight; + + public string Source => _state.ServerOptions.Source; + public DateTime LastRefreshUtc => _state.ServerOptions.LastRefreshUtc; + + // ── Bit access ────────────────────────────────────────────────────────── + + public IltTri Get(string key) + => _state.ServerOptions.Bits.TryGetValue(key, out int v) ? (IltTri)Math.Clamp(v, -1, 1) : IltTri.Unknown; + + /// True only when the server positively reported the feature as available. + public bool IsOn(string key) => Get(key) == IltTri.On; + + /// True when the server positively reported the feature as unavailable. + public bool IsOff(string key) => Get(key) == IltTri.Off; + + public void Set(string key, IltTri value) + { + // Every feature gate reads these bits, so each transition is traced (IltOptions). + IltTri old = Get(key); + _state.ServerOptions.Bits[key] = (int)value; + if (old != value) RynthLog.Trace(LogCat.IltOptions, $"feature '{key}': {old} -> {value}"); + } + + /// At least one feature bit is On (Hub window shows only then, unless Force is on). + public bool AnyFeatureOn => _state.ServerOptions.Bits.Values.Any(v => v == 1); + + /// All known bits for the status display. + public IReadOnlyList> SnapshotBits() + => _state.ServerOptions.Bits.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase).ToList(); + + // ── Lifecycle ─────────────────────────────────────────────────────────── + + /// Called at login: schedules the one-shot refresh (never a recurring timer). + public void OnLoginComplete() + { + _loginAt = Environment.TickCount64; + _loginRefreshDone = false; + } + + /// + /// Pump-thread tick: fires the delayed login refresh once. While the world name is still + /// unknown it keeps checking (a cheap string compare per tick) until the name arrives or + /// WorldNameWaitMs expires; only a known non-ILT world, or the timeout, ends the wait. + /// + public void Tick() + { + if (_loginRefreshDone || _loginAt == 0) return; + long sinceLogin = Environment.TickCount64 - _loginAt; + if (sinceLogin < LoginRefreshDelayMs) return; + + if (IsIltLikeWorld) + { + _loginRefreshDone = true; + RynthLog.Event(LogEvents.IltWorldCheck, + $"world check: '{WorldName}' is ILT-like (force={_state.ForceLeaftideFeatures}) - refreshing server options"); + Refresh(manual: false); + return; + } + + // World not reported yet: try again next tick rather than concluding "not ILT". RynthCore's + // verdict trails the world name by up to a second (its push), and before its first push + // there is none: keep checking for the same window rather than conclude early. + if ((string.IsNullOrEmpty(WorldName) || EngineDecides || !IltEngineVerdict.Pushed) + && sinceLogin < WorldNameWaitMs) + return; + + _loginRefreshDone = true; + RynthLog.Event(LogEvents.IltWorldCheck, + $"world check: '{WorldName}' is not ILT-like - login refresh skipped (waited {sinceLogin / 1000}s)"); + } + + /// + /// Runs the probe refresh. Manual refreshes report progress in chat; the login refresh is + /// silent. + /// + public void Refresh(bool manual) + { + if (_refreshInFlight) + { + if (manual) _chat("[Mini Remote] Server options refresh already running."); + return; + } + if (!IsIltLikeWorld) + { + if (manual) + _chat(EngineDecides + ? "[Mini Remote] RynthCore doesn't treat this world as Infinite Leaftide (/rc server ilt on forces it for this character; /rc server names ilt add adds the world)." + : "[Mini Remote] This world is not in the Server Features list (Settings > Misc: add it, or tick the override)."); + return; + } + + _refreshInFlight = true; + _state.ServerOptions.WorldName = WorldName; + RynthLog.Event(LogEvents.IltOptionsRefreshStart, $"refresh start (manual={manual}, world='{WorldName}')"); + if (manual) _chat("[Mini Remote] Refreshing server options..."); + + _state.ServerOptions.Source = "probe"; + RunProbes(manual); + } + + // ── Probe ─────────────────────────────────────────────────────────────── + + /// One read-only probe: command, reply recogniser, feature key. + private readonly record struct Probe(string Key, string Command, Func IsReply); + + private static readonly Probe[] Probes = + { + new(IltFeature.Bank, "/bank", t => t.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase) + || t.Contains("not permitted to use bank", StringComparison.OrdinalIgnoreCase)), + new(IltFeature.Aug, "/aug", t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) + || IltParse.AugLine.IsMatch(t)), + new(IltFeature.Qb, "/qb", t => t.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("[QB]", StringComparison.OrdinalIgnoreCase)), + new(IltFeature.Pets, "/pets", t => t.Contains("Your Pet Log", StringComparison.OrdinalIgnoreCase) + || IltParse.RosterLine.IsMatch(t) || t.Contains("Professor Ruggan", StringComparison.OrdinalIgnoreCase)), + new(IltFeature.Shinies, "/shinies", t => t.Contains("Your Shiny Log", StringComparison.OrdinalIgnoreCase) + || IltParse.RosterLine.IsMatch(t) || t.Contains("Shiny creatures", StringComparison.OrdinalIgnoreCase)), + new(IltFeature.Xp, "/xp", t => t.StartsWith("[XP]", StringComparison.OrdinalIgnoreCase)), + new(IltFeature.Powerball, "/pb", t => t.StartsWith("[Powerball]", StringComparison.OrdinalIgnoreCase)), + new(IltFeature.Blackjack, "/blackjack", IsParamErrorOr("blackjack", "bet amount")), + new(IltFeature.FBlackjack,"/fblackjack", IsParamErrorOr("blackjack", "bet amount")), + new(IltFeature.Clap, "/clap", IsParamErrorOr("clap", "AutoCraftingEnabled")), + }; + + /// Recognises ACE's wrong-parameter-count reply (command exists) or a keyword reply. + private static Func IsParamErrorOr(string keyword, string keyword2) => t => + t.StartsWith("Invalid parameter count", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("Usage:", StringComparison.OrdinalIgnoreCase) + || t.StartsWith("@" + keyword, StringComparison.OrdinalIgnoreCase) + || t.Contains(keyword2, StringComparison.OrdinalIgnoreCase) + || (t.Contains(keyword, StringComparison.OrdinalIgnoreCase) && !t.StartsWith(" IltParse.AugLine.IsMatch(t) : null, + IdleEndMs = 1500, + FirstLineTimeoutMs = 8000, + Eat = true, + OnComplete = r => + { + // Unknown command → Off. Any recognised reply → On. Silence → leave Unknown. + if (r.UnknownCommand) Set(probe.Key, IltTri.Off); + else if (r.Lines.Count > 0) Set(probe.Key, IltTri.On); + RynthLog.Trace(LogCat.IltOptions, $"probe {probe.Command}: lines={r.Lines.Count} unknown={r.UnknownCommand} timedOut={r.TimedOut}"); + try { ProbeReplyTap?.Invoke(probe.Key, r); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltOptions, ex, $"probe tap {probe.Key}"); } + if (--_probesOutstanding <= 0) CompleteRefresh(manual); + }, + }); + } + } + + private void CompleteRefresh(bool manual) + { + _refreshInFlight = false; + _state.ServerOptions.LastRefreshUtc = DateTime.UtcNow; + int on = _state.ServerOptions.Bits.Values.Count(v => v == 1); + int off = _state.ServerOptions.Bits.Values.Count(v => v == 0); + // Building the per-bit list is skipped unless the event is actually going to be recorded. + if (RynthLog.IsEventEnabled(LogEvents.IltOptionsRefreshed)) + RynthLog.Event(LogEvents.IltOptionsRefreshed, $"options refreshed via {Source} (manual={manual}): {on} on, {off} off - " + + string.Join(" ", _state.ServerOptions.Bits.Select(b => $"{b.Key}={b.Value}"))); + if (manual) + _chat($"[Mini Remote] Server options refreshed via {Source}: {on} on, {off} off."); + } + + // ── Passive refusals ──────────────────────────────────────────────────── + + /// + /// Watches every chat line for explicit server refusals (bit Off) and for lines only an + /// enabled feature sends (bit On). Cheap substring checks; runs on the pump thread. + /// + public void OnChatLine(string text) + { + if (text.Contains("Powerball lottery is not currently active", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.Powerball, IltTri.Off); + else if (text.Contains("\"myquests\" is not currently enabled", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.Quests, IltTri.Off); + else if (text.Contains("\"qb\" is not currently enabled", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.Qb, IltTri.Off); + else if (text.Contains("must have received the AutoCraftingEnabled quest stamp", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.Clap, IltTri.Off); + else if (text.Contains("Universal Summoning Mastery is not enabled on this server", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.UniversalMastery, IltTri.Off); + else if (text.Contains("Auto-Rebuff Charm is currently disabled globally", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.Charm("Auto-Rebuff"), IltTri.Off); + else if (text.Contains("not permitted to use bank commands", StringComparison.OrdinalIgnoreCase)) + Set(IltFeature.Bank, IltTri.Off); + else if (IsPyrealRefillLine(text)) + Set(IltFeature.PetRefill, IltTri.On); + } + + /// + /// ACECustom's summon-time refill messages (PetDevice.TryApplyPyrealAutoRefillBeforeSummon). The + /// server sends them only while pet_device_pyreal_auto_refill_enabled is on, so any of them + /// proves the refill is on even when the profile says it's off. + /// + internal static bool IsPyrealRefillLine(string text) + => text.Contains("charge on your summoning essence", StringComparison.OrdinalIgnoreCase) + || text.Contains("pyreals to auto-replenish your summoning essence", StringComparison.OrdinalIgnoreCase); + + /// Records what the login /myquests refresh learned (called by the Hub after the Meta tracker finishes). + public void NoteQuestTrackerOutcome(bool disabled, int recordCount) + { + if (disabled) Set(IltFeature.Quests, IltTri.Off); + else if (recordCount > 0) Set(IltFeature.Quests, IltTri.On); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs new file mode 100644 index 0000000..0a5f326 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs @@ -0,0 +1,291 @@ +// IltSessionRates.cs — Session earnings / per-hour rates for Infinite Leaftide: the coins, pyreals and +// item conversions RynthCore's Mini Remote "Session Stats" section shows under "Server: Infinite +// Leaftide" (surface "section:ilt-rates", 2026-10-13; it was the ILT Character tab before). +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// Sources (all passive — nothing is sent to the server except the optional bank refresh +// the Banking tab already does): +// XP, luminance (total, last 5 min, allegiance pass-up) and kills: RynthAi's Mini Remote +// session stats (RynthAi.Hub SessionStats) — RynthTracker's SessionStats code, so this +// table, the Mini Remote and the Tracker panel count them the same way (2026-10-11). +// Without RynthAi those rows are left out. +// Coins positive bank Enlightened Coins deltas + carried coin (WCID 300004) gains. +// Pyreals positive bank pyreal deltas + carried pyreal (WCID 273) gains; MMD = 250k. +// Items gains of each item in the item→coin conversion table (carried count), +// converted to potential coins with ItemsPerConversion / CoinsPerConversion. +// A deposit or withdrawal only moves money between pack and bank: while Banking reports one +// (MovingMoney) the coin and pyreal baselines follow along without counting a gain. +using System; +using System.Collections.Generic; +using System.Linq; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltSessionRates : IIltFeature +{ + private const long PyrealsPerMmd = 250_000; + private const long SampleIntervalMs = 5000; + private const long RowsIntervalMs = 1000; + private const string PassUpLabel = " pass-up"; + + private readonly IltHubContext _ctx; + private DateTime _start = DateTime.UtcNow; + + private long _coins; + private long _pyreals; + + // Carried-item baselines (last seen counts) for gain tracking. + private long _lastInvCoins = -1; + private long _lastInvPyreals = -1; + private readonly Dictionary _lastItemCounts = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _itemGains = new(StringComparer.OrdinalIgnoreCase); + private long _lastSampleAt; + private long _lastRowsAt; + + // Render snapshot. + private volatile RateRow[] _rows = Array.Empty(); + // Shared = one of RynthAi's session stats rows (XP, luminance, kills), which the Session Stats + // section already shows above this table; the embedded view leaves those out. + private sealed record RateRow(string Label, string Total, string PerHour, bool Shared = false); + + /// Coin and pyreal per-hour figures for the Mini Remote HUD (rebuilt every sample). + public sealed record RateSummary(double CoinsPerHour, double PyrealsPerHour); + private static readonly RateSummary EmptySummary = new(0, 0); + private volatile RateSummary _summary = EmptySummary; + + /// Latest coin / pyreal summary (safe from the render thread). + public RateSummary Summary => _summary; + /// When the coin / pyreal session (or the last Reset) started. + public DateTime SessionStartUtc => _start; + + public IltSessionRates(IltHubContext ctx) => _ctx = ctx; + + /// True while money moves between pack and bank (set by the controller from Banking). Pump thread. + public Func? MovingMoney { get; set; } + + private bool Moving => MovingMoney?.Invoke() ?? false; + + /// Banking hook: bank balance changed (pump thread). + public void OnBankBalanceChanged(string key, long oldValue, long newValue) + { + RynthLog.Trace(LogCat.IltRates, $"balance {key}: {oldValue} -> {newValue}"); + // The first read after login only establishes the baseline (old value is the stale cache). + if (_lastSampleAt == 0) return; + if (Moving) return; // a deposit, not income + long delta = newValue - oldValue; + if (delta <= 0) return; // spending / sending isn't income + if (key == "EnlightenedCoins") _coins += delta; + else if (key == "Pyreals") _pyreals += delta; + } + + /// Coins, pyreals and item gains start over (login, or with ). + public void Reset() + { + RynthLog.Trace(LogCat.IltRates, $"Reset()"); + _start = DateTime.UtcNow; + _coins = _pyreals = 0; + _lastInvCoins = _lastInvPyreals = -1; + _lastItemCounts.Clear(); + _itemGains.Clear(); + _lastSampleAt = 0; + _lastRowsAt = 0; + _summary = EmptySummary; + } + + /// The player's reset (this tab, the Mini Remote): coins here and the shared session stats together. Pump thread. + public void ResetAll() + { + Reset(); + _ctx.Ai.ResetSessionStats(); + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + FollowSharedSession(); + // The shared stats move every 0.5 s; their rows refresh each second, coins every 5 s. + if (nowMs - _lastSampleAt < SampleIntervalMs) + { + if (nowMs - _lastRowsAt >= RowsIntervalMs) { _lastRowsAt = nowMs; BuildRows(); } + return; + } + _lastSampleAt = nowMs; + _lastRowsAt = nowMs; + var inv = _ctx.Inventory; + + long coinGain = Gain(ref _lastInvCoins, inv.CountByWcid(IltInventory.WcidEnlightenedCoin)); + long pyrealGain = Gain(ref _lastInvPyreals, inv.CountByWcid(IltInventory.WcidPyreal)); + // A withdrawal: the baselines moved, nothing earned. + if (!Moving) + { + _coins += coinGain; + _pyreals += pyrealGain; + } + + // ToArray: the render thread edits this table. + foreach (var conv in _ctx.State.Character.ItemConversions.ToArray()) + { + if (string.IsNullOrWhiteSpace(conv.ItemName)) continue; + long count = inv.CountByName(conv.ItemName); + long last = _lastItemCounts.TryGetValue(conv.ItemName, out long l) ? l : -1; + long gain = Gain(ref last, count); + _lastItemCounts[conv.ItemName] = last; + if (gain > 0) _itemGains[conv.ItemName] = (_itemGains.TryGetValue(conv.ItemName, out long g) ? g : 0) + gain; + } + + BuildRows(); + } + + private long _sharedStartTicks; // RynthAi's session start as last seen (0 = not yet) + + /// + /// The coins / pyreals start over with RynthAi's shared session (its Reset XP, or a session that + /// restarted): one clock for both, without RynthAi telling RynthILT. Pump thread. + /// + private void FollowSharedSession() + { + if (!_ctx.Ai.TryGetSessionStats(out SessionStatsV1 s) || s.StartUtcTicks == 0) return; + if (_sharedStartTicks != 0 && s.StartUtcTicks > _sharedStartTicks) + { + RynthLog.Trace(LogCat.IltRates, "RynthAi's session restarted: coins and pyreals start over too"); + Reset(); + } + _sharedStartTicks = s.StartUtcTicks; + } + + /// Positive change since the last sample; the first sample only sets the baseline. + private static long Gain(ref long last, long current) + { + if (last < 0) { last = current; return 0; } + long d = current - last; + last = current; + return d > 0 ? d : 0; + } + + // Luminance chat goes to RynthAi's session stats (its OnChatWindowText). + public bool OnChat(string text) => false; + + public void OnLogout() => Reset(); + + // ── Rows ──────────────────────────────────────────────────────────────── + + private void BuildRows() + { + double hours = Math.Max((DateTime.UtcNow - _start).TotalHours, 1.0 / 3600); + _summary = new RateSummary(_coins / hours, _pyreals / hours); + var rows = new List(); + if (_ctx.Ai.TryGetSessionStats(out SessionStatsV1 s)) + { + rows.Add(new RateRow("XP", IltParse.Compact(s.Xp), IltParse.Compact(s.XpPerHour), Shared: true)); + rows.Add(new RateRow("Luminance", IltParse.Compact(s.Lum), IltParse.Compact(s.LumPerHour), Shared: true)); + // Per hour at the last five minutes' pace. + rows.Add(new RateRow(" last 5 min", IltParse.Compact(s.LumLast5Min), IltParse.Compact(s.LumLast5Min * 12.0), Shared: true)); + if (s.PassUpTracked != 0) + rows.Add(new RateRow(PassUpLabel, IltParse.Compact(s.LumPassUp), IltParse.Compact(s.PassUpPerHour), Shared: true)); + rows.Add(new RateRow("Kills", s.Kills.ToString(), s.KillsPerHour.ToString("0"), Shared: true)); + } + rows.Add(new RateRow("Enlightened Coins", IltParse.Compact(_coins), IltParse.Compact(_coins / hours))); + rows.Add(new RateRow("Pyreals", IltParse.Compact(_pyreals), IltParse.Compact(_pyreals / hours))); + rows.Add(new RateRow(" as MMD", (_pyreals / (double)PyrealsPerMmd).ToString("0.0"), (_pyreals / (double)PyrealsPerMmd / hours).ToString("0.0"))); + + double potentialCoins = 0; + foreach (var conv in _ctx.State.Character.ItemConversions.ToArray()) + { + if (!_itemGains.TryGetValue(conv.ItemName, out long gained) || gained == 0) continue; + double coins = conv.ItemsPerConversion > 0 ? gained / (double)conv.ItemsPerConversion * conv.CoinsPerConversion : 0; + potentialCoins += coins; + rows.Add(new RateRow(" " + conv.ItemName, IltParse.N0(gained), IltParse.Compact(gained / hours))); + } + if (potentialCoins > 0) + rows.Add(new RateRow("Potential coins (items)", potentialCoins.ToString("0"), (potentialCoins / hours).ToString("0.0"))); + _rows = rows.ToArray(); + } + + /// What the pass-up figure is (shared with the Mini Remote's Stats). + public const string PassUpTooltip = + "Luminance that reached your bank without a \"You've banked\" line: your vassals' pass-up.\n" + + "Fellowship and Zone Share splits arrive the same silent way and are included."; + + // ── UI (render thread) ────────────────────────────────────────────────── + + /// + /// True in the Mini Remote's Session Stats section: RynthAi's XP / luminance / kills rows are + /// drawn there already (one session), so only the ILT coins, pyreals and items are listed. + /// + public void Render(bool extrasOnly = false) + { + // The session clock is RynthAi's session stats' (it and the coins reset together). + var start = _ctx.Ai.TryGetSessionStats(out SessionStatsV1 v) && v.SessionSeconds > 0 && v.StartUtcTicks > 0 + ? new DateTime(v.StartUtcTicks, DateTimeKind.Utc) : _start; + SafeImGui.TextDisabled($"Session {IltParse.Duration(DateTime.UtcNow - start)}"); + ImGui.SameLine(); + if (ImGui.SmallButton("Reset##rates")) _ctx.Post(ResetAll); + + if (ImGui.BeginTable("##iltrates", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV)) + { + ImGui.TableSetupColumn("Metric"); + ImGui.TableSetupColumn("Session"); + ImGui.TableSetupColumn("Per hour"); + ImGui.TableHeadersRow(); + foreach (var r in _rows) + { + if (extrasOnly && r.Shared) continue; + ImGui.TableNextRow(); + ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Label); + if (ReferenceEquals(r.Label, PassUpLabel) && ImGui.IsItemHovered()) SafeImGui.SetTooltip(PassUpTooltip); + ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Total); + ImGui.TableNextColumn(); SafeImGui.TextColored(IltStyle.ColTeal, r.PerHour); + } + ImGui.EndTable(); + } + + if (ImGui.TreeNode("Item -> coin conversions")) + { + RenderConversionEditor(); + ImGui.TreePop(); + } + } + + private string _newItemName = string.Empty; + + private void RenderConversionEditor() + { + var list = _ctx.State.Character.ItemConversions; + int remove = -1; + for (int i = 0; i < list.Count; i++) + { + var c = list[i]; + ImGui.PushID(i); + ImGui.TextUnformatted(c.ItemName); + ImGui.SameLine(220); + int items = c.ItemsPerConversion, coins = c.CoinsPerConversion; + ImGui.SetNextItemWidth(70); + if (ImGui.InputInt("items", ref items, 0)) c.ItemsPerConversion = Math.Max(1, items); + ImGui.SameLine(); + ImGui.SetNextItemWidth(70); + if (ImGui.InputInt("coins", ref coins, 0)) c.CoinsPerConversion = Math.Max(0, coins); + ImGui.SameLine(); + if (ImGui.SmallButton("x")) remove = i; + ImGui.PopID(); + } + if (remove >= 0) + { + var victim = list[remove]; + _ctx.Post(() => list.Remove(victim)); + } + + ImGui.SetNextItemWidth(200); + ImGui.InputTextWithHint("##newconv", "exact item name", ref _newItemName, 96u); + ImGui.SameLine(); + if (ImGui.SmallButton("Add") && _newItemName.Trim().Length > 0 + && !list.Any(c => c.ItemName.Equals(_newItemName.Trim(), StringComparison.OrdinalIgnoreCase))) + { + var added = new IltItemConversion { ItemName = _newItemName.Trim(), ItemsPerConversion = 100, CoinsPerConversion = 0 }; + _ctx.Post(() => list.Add(added)); + _newItemName = string.Empty; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs new file mode 100644 index 0000000..ed96a5f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs @@ -0,0 +1,95 @@ +// IltSettings.cs - RynthILT's own settings (every character): which world names are Infinite +// Leaftide. Lives in %APPDATA%\RynthCore\RynthILT\settings.json. +// +// The list was RynthAi's Settings > Misc "Server Features" (FeatureServerNames, saved with each +// RynthAi profile). RynthILT keeps one list for every character; the first time a character +// logs in with RynthILT, IltMigration folds that character's RynthAi list into this one. +// Edited with "/ilt servers " (the Character tab's editor went with the tab, 2026-10-13; +// RynthCore Options > Diagnostics lists the world names RynthCore uses). +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +public sealed class IltSettings +{ + public int SchemaVersion = 1; + + /// World-name patterns that count as Infinite Leaftide ('*' wildcard, case-insensitive). + public List ServerNames = new(ServerFeatureGate.DefaultServerNames); + + /// The shared RynthAi files (Hub profiles, aug costs) were copied over once. + public bool SharedFilesMigrated; + + /// + /// RynthILT character folders whose copy from RynthAi failed part-way (IltMigration). Until it + /// succeeds the Hub writes nothing there (a fresh file would shadow the RynthAi original and + /// stop it ever being copied); the copy is retried at each login and every few minutes. + /// + public List PendingCharacterMigrations = new(); +} + +/// Loads and saves ; a broken or missing file reads as the defaults. +internal static class IltSettingsStore +{ + public const string FileName = "settings.json"; + + /// Overridable for the tests. + public static string Folder = RynthILTPlugin.SettingsRoot; + + public static string FilePath => Path.Combine(Folder, FileName); + + public static IltSettings Load() + { + try + { + if (File.Exists(FilePath)) + { + var s = JsonSerializer.Deserialize(File.ReadAllText(FilePath), IltHubJsonContext.Default.IltSettings); + if (s != null) + { + s.ServerNames = ServerFeatureGate.ParseList(string.Join(",", s.ServerNames ?? new List())); + if (s.ServerNames.Count == 0) s.ServerNames = new List(ServerFeatureGate.DefaultServerNames); + return s; + } + } + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {FilePath}"); } + return new IltSettings(); + } + + public static void Save(IltSettings settings) + { + try + { + string json = JsonSerializer.Serialize(settings, IltHubJsonContext.Default.IltSettings); + DataWriteGuard.TrySave("RynthILT's settings", FilePath, () => + { + Directory.CreateDirectory(Folder); + string tmp = FilePath + ".tmp"; + File.WriteAllText(tmp, json); + File.Move(tmp, FilePath, overwrite: true); + }); + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {FilePath}"); } + } +} + +// Source-generated System.Text.Json only (NativeAOT; never reflection-serialize plugin types: +// the reflection cache keeps the old plugin generation alive across a hot reload). +[JsonSerializable(typeof(IltSettings))] +[JsonSerializable(typeof(IltHubState))] +[JsonSerializable(typeof(List), TypeInfoPropertyName = "IltBankTransactionList")] +[JsonSerializable(typeof(IltAugCostFile))] +[JsonSerializable(typeof(IltLegacyProfileFlags))] +[JsonSerializable(typeof(IltLegacyMiniRemote))] +[JsonSerializable(typeof(IltLegacyHuds))] +[JsonSourceGenerationOptions( + WriteIndented = true, + IncludeFields = true, + PropertyNameCaseInsensitive = true)] +internal partial class IltHubJsonContext : JsonSerializerContext { } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSigilChain.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSigilChain.cs new file mode 100644 index 0000000..3e41a28 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSigilChain.cs @@ -0,0 +1,115 @@ +// IltSigilChain.cs - The Enlightenment Sigil craft chain for /enl 301-325 (ACECustom tier 5: +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// T - 5 sigils and T x 2B luminance per target level T). Every craft is one plus one makes one: +// Enlightened Coin + Ancient Yalani Trinket = Ascension Coin +// Life Splitter + Plant = Lifebloom Resin +// Lifebloom Resin + Necrolytic Extract = Lifeblood Elixir +// Lifeblood Elixir + Ascension Coin = Enlightenment Sigil +// Pure math (no host access) so the planner and the host tests share it. Mirrors UB-IT's +// EnlightenmentSigilChainPolicy. +using System; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// Stack counts of every item in the sigil chain. +internal sealed class IltSigilStock +{ + public long Sigils, AscensionCoins, LifebloodElixirs, LifebloomResins; + public long EnlightenedCoins, YalaniTrinkets, NecrolyticExtracts, LifeSplitters, Plants; + + public IltSigilStock Clone() => (IltSigilStock)MemberwiseClone(); +} + +/// +/// What a sigil demand still needs after using stock from the top of the chain down. "ToCraft" are +/// crafts left to do (intermediates); "Short" are raw materials left to get. +/// +internal sealed class IltSigilShortfall +{ + public long SigilsNeeded, SigilsToCraft, AscensionToCraft, ElixirsToCraft, ResinsToCraft; + /// E-coins the Ascension Coin crafts use (before stock). + public long CoinsForCraft; + public long CoinsShort, TrinketsShort, ExtractsShort, SplittersShort, PlantsShort; + + /// Stock (with the whole chain) covers every sigil. + public bool Covered => CoinsShort == 0 && TrinketsShort == 0 && ExtractsShort == 0 && SplittersShort == 0 && PlantsShort == 0; +} + +internal static class IltSigilChain +{ + public const int FirstTarget = 301; + public const int LastTarget = 325; + + // Item names (ACECustom ships no WCIDs for these yet, so they are counted by name). + public const string AscensionCoin = "Ascension Coin"; + public const string YalaniTrinket = "Ancient Yalani Trinket"; + public const string LifeSplitter = "Life Splitter"; + public const string Plant = "Plant"; + public const string LifebloomResin = "Lifebloom Resin"; + public const string NecrolyticExtract = "Necrolytic Extract"; + public const string LifebloodElixir = "Lifeblood Elixir"; + + public static bool IsSigilTarget(int t) => t >= FirstTarget && t <= LastTarget; + + /// Sigils for target levels current+1 .. target that fall inside 301-325 (T - 5 each). + public static long SigilsForRange(int current, int target) + { + long total = 0; + for (int t = Math.Max(current + 1, FirstTarget); t <= Math.Min(target, LastTarget); t++) + total += Math.Max(0, t - 5); + return total; + } + + /// Shortfall for : sigils first, then coins / elixirs, then resins, then raws. + public static IltSigilShortfall Shortfall(long sigilsNeeded, IltSigilStock stock) + { + var s = new IltSigilShortfall { SigilsNeeded = Math.Max(0, sigilsNeeded) }; + if (s.SigilsNeeded == 0) return s; + stock ??= new IltSigilStock(); + s.SigilsToCraft = Short(s.SigilsNeeded, stock.Sigils); + s.AscensionToCraft = Short(s.SigilsToCraft, stock.AscensionCoins); + s.ElixirsToCraft = Short(s.SigilsToCraft, stock.LifebloodElixirs); + s.CoinsForCraft = s.AscensionToCraft; + s.CoinsShort = Short(s.AscensionToCraft, stock.EnlightenedCoins); + s.TrinketsShort = Short(s.AscensionToCraft, stock.YalaniTrinkets); + s.ResinsToCraft = Short(s.ElixirsToCraft, stock.LifebloomResins); + s.ExtractsShort = Short(s.ElixirsToCraft, stock.NecrolyticExtracts); + s.SplittersShort = Short(s.ResinsToCraft, stock.LifeSplitters); + s.PlantsShort = Short(s.ResinsToCraft, stock.Plants); + return s; + } + + /// Sigils the stock can make: finished sigils plus the scarcer of the two craft paths. + public static long Fulfillable(IltSigilStock stock) + { + if (stock == null) return 0; + long coins = stock.AscensionCoins + Math.Min(stock.EnlightenedCoins, stock.YalaniTrinkets); + long resins = stock.LifebloomResins + Math.Min(stock.LifeSplitters, stock.Plants); + long elixirs = stock.LifebloodElixirs + Math.Min(resins, stock.NecrolyticExtracts); + return stock.Sigils + Math.Min(coins, elixirs); + } + + /// + /// Splits the e-coin pool between Ascension Coin crafts (served first) and token conversion. + /// is what is still to get for both. + /// + public static void EcoinDemand(long coinsHave, long coinsForSigils, long tokensShort, int coinsPerToken, + out long tokensFromCoins, out long tokensStill, out long coinsNeeded) + { + long rate = Math.Max(1, coinsPerToken); + long have = Math.Max(0, coinsHave), sigil = Math.Max(0, coinsForSigils), tok = Math.Max(0, tokensShort); + tokensFromCoins = Math.Min(tok, Math.Max(0, have - sigil) / rate); + tokensStill = tok - tokensFromCoins; + coinsNeeded = Math.Max(0, sigil - have) + tokensStill * rate; + } + + /// True for a chain item name (stack names may be plural; "Plant" must be the whole name). + public static bool NameIs(string itemName, string chainName) + { + string n = (itemName ?? string.Empty).Trim(); + return n.Equals(chainName, StringComparison.OrdinalIgnoreCase) + || n.Equals(chainName + "s", StringComparison.OrdinalIgnoreCase); + } + + private static long Short(long demand, long have) => Math.Max(0, demand - Math.Max(0, have)); +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSplitArrows.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSplitArrows.cs new file mode 100644 index 0000000..01d86f1 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSplitArrows.cs @@ -0,0 +1,210 @@ +// IltSplitArrows.cs — Split-arrow imbuer (Gear tab, P2). +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// ILT missile weapons carry a split-arrow count (int 9031). Each White Quartz salvage +// application adds one split and uses one tink. Per weapon: +// needed = min(target - current, 10 - tinks, 10 - current) +// The imbuer applies full (100-unit) White Quartz bags, lowest workmanship first, with +// UseObjectOn(salvage, weapon). AC then shows its own craft confirmation — the player +// clicks it; the imbuer waits (20 s) for the "successfully applies" / "fails to apply" +// line before the next step. Nothing is ever applied without the Hub confirm first. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using ImGuiNET; +using RynthCore.Loot; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltSplitArrows : IIltFeature +{ + private const int MaterialWhiteQuartz = 46; + private const uint IntNumItemsInMaterial = 170; + private const uint IntItemWorkmanship = 105; + private const long StepTimeoutMs = 20_000; + + private static readonly Regex Applied = new( + @"^(?[\w\s]+) successfully applies the (?[\w\s\-]+?)(\sSalvage.*)(\s?\(100\))?\s\(workmanship (?\d+\.\d+)\) to the (?[\w\s\'\-]+)\.$", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex Failed = new( + @"^(?[\w\s]+) fails to apply the (?[\w\s\-]+?)(\sSalvage.*)(\s?\(100\))?\s\(workmanship (?\d+\.\d+)\) to the (?[\w\s\'\-]+)\.", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + + private readonly IltHubContext _ctx; + + // Job state (pump thread) + private int _weaponId; + private int _remaining; + private bool _waiting; + private long _stepStartedAt; + private volatile string _status = "idle"; + + // Render snapshot of eligible weapons + private volatile WeaponRow[] _weapons = Array.Empty(); + private long _lastScan; + private sealed record WeaponRow(int Id, string Name, int Splits, int Tinks, bool Imbued, int Needed); + + public IltSplitArrows(IltHubContext ctx) => _ctx = ctx; + + private IltGearState G => _ctx.State.Gear; + public bool Running => _weaponId != 0; + + /// True while another ILT pack job (the Rings chain) is running: no imbue starts then. + public Func? Blocked; + + private int Needed(WorldObject w) + { + var inv = _ctx.Inventory; + int cur = inv.Int(w, IltInventory.IntSplitArrowCount); + int tinks = inv.Int(w, IltInventory.IntNumTimesTinkered); + int target = Math.Clamp(G.SplitArrowTarget, 0, 10); + return Math.Max(0, Math.Min(target - cur, Math.Min(10 - tinks, 10 - cur))); + } + + /// Full White Quartz bags, lowest workmanship first. + private List QuartzBags() + { + var inv = _ctx.Inventory; + return inv.Items() + .Where(wo => wo.ObjectClass == AcObjectClass.Salvage + && (inv.Int(wo, IltInventory.IntMaterialType) == MaterialWhiteQuartz || wo.Name.Contains("White Quartz", StringComparison.OrdinalIgnoreCase)) + && inv.Uses(wo) >= 100) + .OrderBy(Workmanship) + .ToList(); + } + + private double Workmanship(WorldObject bag) + { + int total = _ctx.Inventory.Int(bag, IntItemWorkmanship); + int items = Math.Max(1, _ctx.Inventory.Int(bag, IntNumItemsInMaterial, 1)); + return total / (double)items; + } + + /// Starts imbuing one weapon (pump thread, after the UI confirm). + public void Start(int weaponId) + { + var w = _ctx.Inventory.Cache?[weaponId]; + if (w == null) { _status = "weapon not found"; return; } + if (Blocked?.Invoke() == true) { _status = "the Rings chain is running"; return; } + if (_ctx.Inventory.IsEquipped(w)) { _status = "unequip the weapon first"; return; } + int need = Needed(w); + if (need <= 0) { _status = $"{w.Name} needs no more splits"; return; } + _weaponId = weaponId; + _remaining = need; + _waiting = false; + _status = $"imbuing {w.Name}: {need} application(s)"; + } + + public void Stop(string why) + { + _weaponId = 0; + _waiting = false; + _status = why; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + if (nowMs - _lastScan >= 3000 && _ctx.WindowOpen) + { + _lastScan = nowMs; + ScanWeapons(); + } + if (_weaponId == 0) return; + + if (_waiting) + { + if (nowMs - _stepStartedAt > StepTimeoutMs) Stop("no result within 20 s (craft dialog not confirmed?) - stopped"); + return; + } + if (_remaining <= 0) { Stop("done"); return; } + if (_ctx.Inventory.IsBusy) return; + + var bag = QuartzBags().FirstOrDefault(); + if (bag == null) { Stop("out of full White Quartz bags"); return; } + if (_ctx.Inventory.UseOn(bag, unchecked((uint)_weaponId))) + { + _waiting = true; + _stepStartedAt = nowMs; + _status = $"applying {bag.Name} - confirm the craft dialog in AC ({_remaining} left)"; + } + } + + public bool OnChat(string text) + { + if (!_waiting) return false; + if (Applied.IsMatch(text)) + { + _waiting = false; + _remaining--; + _status = $"applied ({_remaining} left)"; + } + else if (Failed.IsMatch(text)) + { + // A failed tink still consumes a tink slot — recompute from the weapon. + _waiting = false; + var w = _ctx.Inventory.Cache?[_weaponId]; + _remaining = w != null ? Math.Min(_remaining, Needed(w)) : 0; + _status = $"application failed ({_remaining} left)"; + } + return false; + } + + public void OnLogout() => Stop("idle"); + + private void ScanWeapons() + { + var inv = _ctx.Inventory; + var rows = new List(); + foreach (var wo in inv.Items()) + { + if (wo.ObjectClass != AcObjectClass.MissileWeapon) continue; + bool imbued = inv.Int(wo, IltInventory.IntImbuedEffect) != 0; + if (imbued && G.SplitIgnoreImbued) continue; + rows.Add(new WeaponRow(wo.Id, wo.Name, inv.Int(wo, IltInventory.IntSplitArrowCount), + inv.Int(wo, IltInventory.IntNumTimesTinkered), imbued, Needed(wo))); + } + _weapons = rows.OrderByDescending(r => r.Needed).ThenBy(r => r.Name).ToArray(); + _bagCount = QuartzBags().Count; + } + + private volatile int _bagCount; + + // ── UI (render thread) ────────────────────────────────────────────────── + + public void Render() + { + ImGui.TextColored(IltStyle.ColTeal, "Split arrows (White Quartz)"); + int tgt = G.SplitArrowTarget; + ImGui.SetNextItemWidth(120); + if (ImGui.SliderInt("Target splits", ref tgt, 0, 10)) G.SplitArrowTarget = tgt; + ImGui.SameLine(); + bool skip = G.SplitIgnoreImbued; + if (ImGui.Checkbox("Skip imbued weapons", ref skip)) G.SplitIgnoreImbued = skip; + SafeImGui.TextDisabled($"Full White Quartz bags carried: {_bagCount}"); + + foreach (var w in _weapons) + { + ImGui.PushID(w.Id); + ImGui.TextUnformatted($"{w.Name} splits {w.Splits}, tinks {w.Tinks}{(w.Imbued ? ", imbued" : "")}"); + ImGui.SameLine(); + ImGui.BeginDisabled(w.Needed <= 0 || Running); + if (ImGui.SmallButton($"Imbue +{w.Needed}")) + { + var row = w; + _ctx.Confirm("Split-arrow imbue", + $"Apply {row.Needed} White Quartz bag(s) to {row.Name}?\n\nEach application uses a tink and can fail.\n" + + "AC will ask you to confirm every craft.", + () => Start(row.Id), "Start"); + } + ImGui.EndDisabled(); + ImGui.PopID(); + } + if (_weapons.Length == 0) ImGui.TextDisabled("No missile weapons carried."); + if (Running && ImGui.SmallButton("Stop imbuing")) _ctx.Post(() => Stop("stopped by player")); + SafeImGui.TextDisabled("Status: " + _status); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltStyle.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltStyle.cs new file mode 100644 index 0000000..55f7f15 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltStyle.cs @@ -0,0 +1,59 @@ +// IltStyle.cs - The colours the ILT tabs and panels draw with (RynthAi's dashboard palette, so +// the tabs look the same inside RynthAi's Mini Remote as when they lived there), the dashboard +// style for RynthILT's own windows, and a JSON string escaper for the hand-built exports. +using System.Numerics; +using ImGuiNET; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal static class IltStyle +{ + internal static readonly Vector4 ColTeal = new(0.15f, 0.85f, 0.90f, 1.00f); + internal static readonly Vector4 ColAmber = new(0.91f, 0.70f, 0.20f, 1.00f); + internal static readonly Vector4 ColGreen = new(0.25f, 0.85f, 0.45f, 1.00f); + internal static readonly Vector4 ColTextMute = new(0.55f, 0.65f, 0.75f, 1.00f); + internal static readonly Vector4 ColHp = new(0.85f, 0.20f, 0.20f, 1.00f); + + /// + /// RynthAi's dashboard colours for a window of RynthILT's own (Games HUD, confirmations, the + /// Guardian panel). Returns how many colours to pop. Inside RynthAi's Mini Remote the style + /// is already pushed. + /// + internal static int PushDashboardStyle() + { + ImGui.PushStyleColor(ImGuiCol.FrameBg, new Vector4(0.18f, 0.22f, 0.28f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, new Vector4(0.24f, 0.30f, 0.38f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.FrameBgActive, new Vector4(0.30f, 0.38f, 0.48f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.CheckMark, new Vector4(0.85f, 0.90f, 1.00f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.PopupBg, new Vector4(0.10f, 0.14f, 0.20f, 0.98f)); + ImGui.PushStyleColor(ImGuiCol.Header, new Vector4(0.20f, 0.28f, 0.36f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.HeaderHovered, new Vector4(0.26f, 0.36f, 0.46f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.HeaderActive, new Vector4(0.32f, 0.44f, 0.58f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.TitleBg, new Vector4(0.14f, 0.18f, 0.24f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.TitleBgActive, new Vector4(0.22f, 0.30f, 0.40f, 1.00f)); + ImGui.PushStyleColor(ImGuiCol.TitleBgCollapsed, new Vector4(0.10f, 0.14f, 0.20f, 0.85f)); + return 11; + } + + /// Minimal JSON string escaper for hand-built export JSON. + internal static string JsonEscape(string s) + { + var sb = new System.Text.StringBuilder(s.Length + 8); + foreach (char c in s) + { + 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: + if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4")); + else sb.Append(c); + break; + } + } + return sb.ToString(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltT11.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltT11.cs new file mode 100644 index 0000000..1c7d642 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltT11.cs @@ -0,0 +1,213 @@ +// IltT11.cs — ACECustom T11 (tier 11+ gear): the player's wield counters for RynthAi's loot rules, and +// "/ilt t11" (also "/ra t11", which RynthAi passes on). +// Moved out of RynthAi 2026-10-20 (RynthAiT11Command.cs and its "/aug" chat feed): the counters and the +// command are ACECustom's, so RynthILT reads them; RynthAi keeps the loot keys and the evaluator +// (Loot/T11ItemSupport.cs, users' .utl profiles use them) and gets the counters through RynthAi.Hub +// SetPlayerCounter. +// +// * Counters: ACECustom doesn't send them at login ([SendOnLogin] is off), so they come from the +// "/aug" reply (RynthILT's login probe asks for it on ILT), read by the shared T11AugReportParser. +// The item-aug override (IltHubState.T11.ItemAugsOverride, "/ilt t11 augs ") replaces the +// /aug Item count. Each change is reported to RynthAi, and every ResendMs anyway (RynthAi may have +// reloaded or logged in later); -1 = unknown. +// * "/ilt t11 [status | augs | refresh | item [0xId]]": the counters, the override, a fresh +// "/aug", and how the selected item's T11 text reads (tier, grade, modifiers, the loot keys' values). +// Ticks only on an ILT-like world (IltHubController): elsewhere RynthAi's counters stay unknown. +using System; +using System.Globalization; +using System.Linq; +using RynthCore.Loot.T11; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal sealed class IltT11 : IIltFeature +{ + private const long ResendMs = 5_000; + + // ACE string properties of an item's appraisal (RynthAi's StringValueKey). + private const uint StrName = 1, StrUse = 14, StrLongDesc = 16; + + private readonly IltHubContext _ctx; + private readonly T11AugReportParser _parser = new(); + private long _sentAt = long.MinValue; + private bool _dirty = true; + private int _overrideApplied = int.MinValue; + + public IltT11(IltHubContext ctx) => _ctx = ctx; + + /// The counters this character's "/aug" reply gave, with the override applied. + public T11PlayerAugs Player { get; } = new(); + + /// How many counters the last report to RynthAi carried (for the tests). + public int LastReported { get; private set; } + + private IltT11State S => _ctx.State.T11; + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + int ov = S.ItemAugsOverride; + if (ov != _overrideApplied) + { + _overrideApplied = ov; + Player.ItemAugOverride = ov >= 0 ? ov : null; + _dirty = true; + } + if (!_dirty && _sentAt != long.MinValue && nowMs - _sentAt < ResendMs) return; + Report(); + _sentAt = nowMs; + _dirty = false; + } + + /// The "/aug" reply's counter lines. Never eats (the login probe's capture decides that). + public bool OnChat(string text) + { + if (_parser.Feed(text, IltHubContext.NowMs, Player)) _dirty = true; + return false; + } + + public void OnLogout() + { + Player.Clear(); + _dirty = true; + _sentAt = long.MinValue; + } + + /// Every counter to RynthAi (-1 for an unknown one). Pump thread. + private void Report() + { + int n = 0; + foreach ((T11Counter counter, _) in T11Catalog.CounterNames) + { + long? v = Player.Get(counter); + if (_ctx.Ai.SetPlayerCounter(unchecked((uint)counter), v ?? -1)) n++; + } + LastReported = n; + } + + // ── "/ilt t11 ..." ────────────────────────────────────────────────────── + + /// "/ilt t11 [status | augs <n|auto> | refresh | item [0xId]]" (args after "t11"). Pump thread. + public void HandleCommand(string[] args) + { + string sub = args.Length >= 1 ? args[0].ToLowerInvariant() : string.Empty; + switch (sub) + { + case "": + case "status": + PrintStatus(); + break; + case "augs": + SetOverride(args.Length >= 2 ? args[1] : string.Empty); + break; + case "refresh": + if (!_ctx.Host.HasInvokeChatParser) { _ctx.Chat("[RynthILT] This engine can't send chat commands."); break; } + _ctx.Host.InvokeChatParser("/aug"); + _ctx.Chat("[RynthILT] T11: sent /aug - the counters update from its reply."); + break; + case "item": + PrintItem(args.Length >= 2 ? args[1] : null); + break; + default: + _ctx.Chat("[RynthILT] Usage: /ilt t11 [augs | refresh | item [0xId]] (also /ra t11)"); + break; + } + } + + /// The counters the "T11: Can Wield" loot key compares wield gates against. + private void PrintStatus() + { + string updated = Player.UpdatedUtc is DateTime t ? t.ToLocalTime().ToString("t", CultureInfo.CurrentCulture) : "never"; + _ctx.Chat($"[RynthILT] === T11 loot (last /aug read: {updated}) ==="); + foreach ((T11Counter counter, string name) in T11Catalog.CounterNames) + { + long? v = Player.Get(counter); + string source = counter == T11Counter.ItemAugmentations && S.ItemAugsOverride >= 0 ? " (override)" : string.Empty; + _ctx.Chat($"[RynthILT] {name}: {(v.HasValue ? v.Value.ToString("N0", CultureInfo.CurrentCulture) : "unknown")}{source}"); + } + if (Player.UpdatedUtc == null && S.ItemAugsOverride < 0) + _ctx.Chat("[RynthILT] Unknown counters make \"T11: Can Wield\" -1. Use /ilt t11 refresh, or /ilt t11 augs ."); + if (!_ctx.Ai.Available) + _ctx.Chat("[RynthILT] (The loot rules are RynthAi's; it isn't loaded, so nothing uses these yet.)"); + } + + /// "/ilt t11 augs <n|auto>": the item-aug override (-1 = read from /aug), saved with the Hub's state. + private void SetOverride(string arg) + { + int value; + if (arg.Equals("auto", StringComparison.OrdinalIgnoreCase) || arg == "-1") + value = -1; + else if (!int.TryParse(arg.Replace(",", string.Empty), NumberStyles.Integer, CultureInfo.InvariantCulture, out value) || value < 0) + { + _ctx.Chat("[RynthILT] Usage: /ilt t11 augs (n = your item augmentation count)"); + return; + } + S.ItemAugsOverride = value; + Tick(IltHubContext.NowMs); // applied and reported now + _ctx.Chat(value < 0 + ? "[RynthILT] T11: item augmentations now come from /aug." + : $"[RynthILT] T11: item augmentations fixed at {value:N0} for loot rules."); + } + + /// "/ilt t11 item [0xId]": the parsed T11 text of an item (the selected item by default). + private void PrintItem(string? idArg) + { + var host = _ctx.Host; + uint id = 0; + if (!string.IsNullOrEmpty(idArg)) + uint.TryParse(idArg.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? idArg[2..] : idArg, + NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id); + if (id == 0 && host.HasGetSelectedItemId) id = host.GetSelectedItemId(); + if (id == 0) { _ctx.Chat("[RynthILT] T11: select an item first (or pass 0xId)."); return; } + + int iid = unchecked((int)id); + var inv = _ctx.Inventory; + WorldObject? item = inv.Cache[iid]; + string name = item?.Name ?? string.Empty; + if (item == null) { _ctx.Chat($"[RynthILT] T11: the client doesn't know 0x{id:X8}."); return; } + if (name.Length == 0) name = inv.Str(item, StrName); + var server = new T11ServerProps(inv.Int(item, (uint)T11Catalog.PropZcTier, 0), + inv.Int(item, (uint)T11Catalog.PropWeaponAugScaleTier, 0), + inv.Int(item, (uint)T11Catalog.PropWeaponAugScaleQuality, -1)); + T11ItemInfo info = T11ItemInfo.Parse(name, inv.Str(item, StrLongDesc), inv.Str(item, StrUse), server); + if (!info.IsT11) + { + bool appraised = !host.HasHasAppraisalData || host.HasAppraisalData(id); + _ctx.Chat(appraised + ? $"[RynthILT] T11: {name} is not a T11 item." + : $"[RynthILT] T11: {name} isn't appraised yet - ID it and try again."); + return; + } + + _ctx.Chat($"[RynthILT] === T11: {name} (0x{id:X8}) ==="); + _ctx.Chat($"[RynthILT] Tier {(info.TierIsExact ? info.Tier.ToString(CultureInfo.InvariantCulture) : "~" + info.Tier.ToString(CultureInfo.InvariantCulture))}" + + (info.Grade != null ? $", grade {info.Grade} ({info.DamagePercent}% of max damage)" : string.Empty) + + (info.WeaponQuality >= 0 ? $", quality {info.WeaponQuality}/1000" : string.Empty) + + (info.GearGrade != null ? $", gear grade {info.GearGrade} ({info.GearGradeLines} lines)" : string.Empty) + + (info.ZoneLocked ? ", zone locked" : string.Empty)); + if (info.PropertySlots >= 0 || info.Tainted) + _ctx.Chat("[RynthILT] Properties " + + (info.PropertySlots < 0 ? "?" : info.PropertySlotCap > 0 ? $"{info.PropertySlots} of {info.PropertySlotCap}" : info.PropertySlots.ToString(CultureInfo.InvariantCulture)) + + (info.Tainted ? ", tainted (bags no longer work)" : string.Empty)); + foreach (T11WieldGate g in info.WieldGates) + _ctx.Chat($"[RynthILT] Wield requires {g.Amount:N0} {T11Catalog.CounterName(g.Counter)}"); + foreach (T11Modifier m in info.Modifiers) + { + string band = m.Min.HasValue && m.Max.HasValue ? $" [{m.Min}-{m.Max}] roll {m.RollPercent}%" : string.Empty; + string marks = (m.Tinkered != 0 ? $" ({m.Tinkered:+#;-#} tinkered)" : string.Empty) + + (m.BuiltIn ? " (built-in)" : string.Empty) + (m.Locked ? " (locked)" : string.Empty); + _ctx.Chat($"[RynthILT] Mod {m.Name} {(m.IsSlotSpecial ? "(special)" : "+" + m.Value)}{band}{marks}"); + } + foreach ((string proc, double chance) in info.Procs) + _ctx.Chat($"[RynthILT] Cast on strike: {proc} ({chance.ToString("0.#", CultureInfo.CurrentCulture)}%)"); + + int canWield = T11Keys.TryGetValue(info, T11Keys.CanWield, Player, out int cw) ? cw : -1; + _ctx.Chat($"[RynthILT] Can wield: {(canWield == 1 ? "yes" : canWield == 0 ? "no" : "unknown (no /aug read, or not appraised)")}" + + $", modifier ratings {info.ModifierRatingTotal}, average roll {info.AverageRollPercent}%"); + string keys = string.Join(", ", T11Keys.Names() + .Where(k => k.Id < T11Keys.ModifierBase) + .Select(k => $"{k.Name.Replace("T11: ", string.Empty)}={(T11Keys.TryGetValue(info, k.Id, Player, out int v) ? v : 0)}")); + _ctx.Chat($"[RynthILT] Loot keys (RynthAi's loot rules read the same): {keys}"); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltTempleAttributes.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltTempleAttributes.cs new file mode 100644 index 0000000..efb6c29 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltTempleAttributes.cs @@ -0,0 +1,296 @@ +// IltTempleAttributes.cs - Temple of Enlightenment attribute turn-in tracker (Guardian window). +// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. +// +// One row per Fiun attribute NPC plus the Guardian of Attribute Enlightenment riddle. Each row +// prefers the timed flag from /myquests (solves + exact cooldown). When /myquests lacks the flag +// it falls back to the "/qb list" wait stamp: a stamp appearing between two lists counts one +// turn-in and starts an estimated cooldown (CooldownHoursAssumed). Fallback counts and timers +// persist in IltGuardianState. +// +// Rows come from "infi attribute.csv" (RynthAi folder, then Documents\Asheron's Call - the UB +// location) when present: npc, attribute, stamp [, myQuestsKey]. Built-in rows missing from the +// file are appended. Pump thread computes; the render thread only reads Snapshot. +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using RynthCore.Install; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One tracked turn-in: the NPC, its attribute, the /qb wait flag and the /myquests keys to try. +internal sealed class IltTempleAttrRow +{ + public IltTempleAttrRow(string npc, string attribute, string stamp, string? myQuestsKey = null) + { + Npc = npc.Trim(); + Attribute = attribute.Trim(); + QbWaitFlag = ExtractQbFlag(stamp); + var keys = new List(); + void Add(string? k) + { + if (string.IsNullOrWhiteSpace(k)) return; + string t = k.Trim().ToLowerInvariant(); + if (!keys.Contains(t)) keys.Add(t); + } + Add(myQuestsKey); + Add(QbWaitFlag); + if (QbWaitFlag.EndsWith("Wait", StringComparison.OrdinalIgnoreCase) && QbWaitFlag.Length > 4) + Add(QbWaitFlag[..^4]); + MyQuestsKeys = keys.ToArray(); + } + + public string Npc { get; } + public string Attribute { get; } + /// /qb flag name (e.g. TempleAttributeStrengthWait). + public string QbWaitFlag { get; } + /// Lowercase /myquests keys in lookup order: CSV override, the wait flag, the flag without "Wait". + public string[] MyQuestsKeys { get; } + + /// "You've stamped X!" → "X"; a bare flag name is returned trimmed. + private static string ExtractQbFlag(string stamp) + { + string s = (stamp ?? string.Empty).Trim(); + const string prefix = "You've stamped "; + if (s.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) s = s[prefix.Length..]; + return s.Trim().TrimEnd('!', ' ', '\t', '\r', '\n'); + } +} + +/// What the Guardian window shows for one row. +internal sealed record IltTempleAttrStatus(string Attribute, string Npc, int Count, string Status, string Eta, bool Ready, bool FromMyQuests); + +internal sealed class IltTempleAttributes +{ + private const long RebuildIntervalMs = 1000; + private const string CsvName = "infi attribute.csv"; + + private static readonly IltTempleAttrRow[] DefaultRows = + { + new("Fiun Luunere", "Strength", "TempleAttributeStrengthWait"), + new("Fiun Bayaas", "Coordination", "TempleAttributeCoordinationWait"), + new("Fiun Ruun", "Endurance", "TempleAttributeEnduranceWait"), + new("Fiun Riish", "Quickness", "TempleAttributeQuicknessWait"), + new("Fiun Vasherr", "Focus", "TempleAttributeFocusWait"), + new("Fiun Noress", "Willpower", "TempleAttributeSelfWait"), + new("Fiun Vaelesh", "Health", "TempleAttributeHealthWait"), + new("Fiun Torrun", "Stamina", "TempleAttributeStamWait"), + new("Fiun Saeluun", "Mana", "TempleAttributeManaWait"), + new("Guardian (Attr)", "Riddle", "TempleAttributeRiddleWait"), + }; + + private readonly IltHubContext _ctx; + private readonly IltQuestBonus _quests; + private readonly IltTempleAttrRow[] _rows; + // Wait-stamp presence per attribute at the previous "/qb list" (session only: a transition + // needs two lists in the same session). + private readonly Dictionary _lastHadWait = new(StringComparer.OrdinalIgnoreCase); + private int _seenQbGeneration; + private long _lastRebuildAt = -RebuildIntervalMs; + + private volatile IltTempleAttrStatus[] _snapshot = Array.Empty(); + private DateTime _syncedUtc = DateTime.MinValue; + + public IltTempleAttributes(IltHubContext ctx, IltQuestBonus quests) + { + _ctx = ctx; + _quests = quests; + _rows = LoadRows(out string source); + RynthLog.Write(LogCat.IltHub, $"[IltGuardian] attribute rows: {_rows.Length} from {source}"); + } + + /// Rows as last computed (render thread reads this). + public IltTempleAttrStatus[] Snapshot => _snapshot; + + /// When the quest data behind the rows last changed (MinValue = never this session). + public DateTime SyncedUtc => _syncedUtc; + + private IltGuardianState S => _ctx.State.Guardian; + + // ── Rows file ─────────────────────────────────────────────────────────── + + /// The CSV in RynthILT's folder, the RynthAi folder (where it lived), else UB's Documents location; built-in rows otherwise. + private static IltTempleAttrRow[] LoadRows(out string source) + { + string[] candidates = + { + Path.Combine(IltHubStore.SharedRoot, CsvName), + Path.Combine(RynthInstallPaths.RynthAiDir, CsvName), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Asheron's Call", CsvName), + }; + foreach (string path in candidates) + { + try + { + if (!File.Exists(path)) continue; + var rows = ParseCsv(File.ReadAllLines(path)); + if (rows.Count == 0) continue; + source = path; + return MergeMissingDefaults(rows); + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, $"read {path}"); } + } + source = "built-in table"; + return DefaultRows; + } + + /// npc, attribute, stamp [, myQuestsKey]; a header row and blank lines are skipped. + private static List ParseCsv(string[] lines) + { + var rows = new List(); + foreach (string raw in lines) + { + string line = raw.Trim().TrimStart('\uFEFF'); + if (line.Length == 0) continue; + if (line.StartsWith("npc", StringComparison.OrdinalIgnoreCase) && line.Contains("attribute", StringComparison.OrdinalIgnoreCase)) + continue; + string[] seg = line.Split(','); + if (seg.Length < 3) continue; + string npc = seg[0].Trim(), attr = seg[1].Trim(); + string stamp; + string? key = null; + if (seg.Length == 4) { stamp = seg[2].Trim(); key = seg[3].Trim(); } + else stamp = string.Join(",", seg.Skip(2)).Trim(); // a full stamp chat line may contain commas + if (npc.Length == 0 || attr.Length == 0 || stamp.Length == 0) continue; + rows.Add(new IltTempleAttrRow(npc, attr, stamp, key)); + } + return rows; + } + + private static IltTempleAttrRow[] MergeMissingDefaults(List loaded) + { + var seen = new HashSet(loaded.Select(r => r.QbWaitFlag), StringComparer.OrdinalIgnoreCase); + foreach (var def in DefaultRows) + if (seen.Add(def.QbWaitFlag)) loaded.Add(def); + return loaded.ToArray(); + } + + // ── Pump thread ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + int gen = _quests.QbGeneration; + if (gen != _seenQbGeneration) + { + _seenQbGeneration = gen; + if (gen > 0) ApplyQbTransitions(); + _syncedUtc = DateTime.UtcNow; + } + if (nowMs - _lastRebuildAt < RebuildIntervalMs) return; + _lastRebuildAt = nowMs; + Rebuild(); + } + + /// Re-asks the server for /myquests and "/qb list" (each limited to once a minute). + public string Refresh() => $"{_ctx.Ai.RefreshQuests()} {_quests.RefreshQb()}"; + + /// Forgets the counted turn-ins and estimated cooldowns (the /qb fallback only). + public void ResetCounts() + { + S.TurnInCounts.Clear(); + S.CooldownUntilUtc.Clear(); + _lastRebuildAt = long.MinValue / 2; + } + + public void OnLogout() + { + _lastHadWait.Clear(); + _seenQbGeneration = 0; + _syncedUtc = DateTime.MinValue; + } + + private bool TryQuest(IltTempleAttrRow row, out QuestRecord rec) + { + rec = null!; + // /myquests is RynthAi's quest tracker (RynthAi.Hub); without RynthAi the /qb stamps decide. + foreach (string key in row.MyQuestsKeys) + if (_ctx.Ai.TryGetQuestFlag(key, out rec)) return true; + return false; + } + + /// A new "/qb list" arrived: count wait stamps that appeared since the previous list. + private void ApplyQbTransitions() + { + int hours = Math.Max(1, S.CooldownHoursAssumed); + foreach (var row in _rows) + { + string key = row.Attribute; + bool hasWait = _quests.QbHasFlag(row.QbWaitFlag); + if (!TryQuest(row, out _)) + { + if (_lastHadWait.TryGetValue(key, out bool had) && !had && hasWait) + { + S.TurnInCounts[key] = (S.TurnInCounts.TryGetValue(key, out int n) ? n : 0) + 1; + S.CooldownUntilUtc[key] = DateTime.UtcNow.AddHours(hours); + RynthLog.Write(LogCat.IltHub, $"[IltGuardian] {key} turn-in counted from /qb (now {S.TurnInCounts[key]})"); + } + if (!hasWait) S.CooldownUntilUtc.Remove(key); + } + _lastHadWait[key] = hasWait; + } + } + + private void Rebuild() + { + bool qbLoaded = _quests.QbGeneration > 0; + int hours = Math.Max(1, S.CooldownHoursAssumed); + var list = new IltTempleAttrStatus[_rows.Length]; + for (int i = 0; i < _rows.Length; i++) + { + var row = _rows[i]; + if (TryQuest(row, out var rec)) + { + list[i] = FromQuest(row, rec); + continue; + } + + string key = row.Attribute; + int count = S.TurnInCounts.TryGetValue(key, out int c) ? c : 0; + if (!qbLoaded) + { + list[i] = new(key, row.Npc, count, "Unknown", "Refresh", false, false); + continue; + } + if (!_quests.QbHasFlag(row.QbWaitFlag)) + { + list[i] = new(key, row.Npc, count, "Ready", "-", true, false); + continue; + } + + // Wait stamp present: show the estimated cooldown, starting one if none is known. + if (!S.CooldownUntilUtc.TryGetValue(key, out DateTime until)) + S.CooldownUntilUtc[key] = until = DateTime.UtcNow.AddHours(hours); + until = AsUtc(until); + TimeSpan left = until - DateTime.UtcNow; + list[i] = left > TimeSpan.Zero + ? new(key, row.Npc, count, "Wait stamp", $"~{IltParse.Duration(left)} (est.)", false, false) + : new(key, row.Npc, count, "Wait stamp", "ready? (est.)", false, false); + } + _snapshot = list; + } + + /// A row backed by its /myquests flag: exact solves and cooldown. + private static IltTempleAttrStatus FromQuest(IltTempleAttrRow row, QuestRecord rec) + { + switch (IltQuestBonus.Classify(rec)) + { + case IltQuestBonus.QuestKind.KillTask: + return new(row.Attribute, row.Npc, rec.Solves, "Kill task", $"{rec.Solves}/{rec.MaxSolves}", false, true); + case IltQuestBonus.QuestKind.Once: + return new(row.Attribute, row.Npc, rec.Solves, "Once", rec.Solves >= 1 ? "done" : "-", false, true); + default: + if (rec.IsReady()) return new(row.Attribute, row.Npc, rec.Solves, "Ready", "now", true, true); + TimeSpan left = rec.TimeUntilReady(); + string at = DateTime.Now.Add(left).ToString("ddd HH:mm"); + return new(row.Attribute, row.Npc, rec.Solves, "Cooldown", $"{IltParse.Duration(left)} ({at})", false, true); + } + } + + /// Stored times may load as Unspecified; they were written as UTC. + private static DateTime AsUtc(DateTime dt) => dt.Kind switch + { + DateTimeKind.Utc => dt, + DateTimeKind.Local => dt.ToUniversalTime(), + _ => DateTime.SpecifyKind(dt, DateTimeKind.Utc), + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs new file mode 100644 index 0000000..18d362f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs @@ -0,0 +1,920 @@ +// IltVaultedDungeons.cs — Mini Remote "Vaulted Dungeons" tab (ILT / ACECustom only). +// Written by Silentkelpie (RynthSuite PR #12), a port of the UtilityBelt VaultedDungeons.lua script +// (owner 2026-09-27 / 2026-10-03): keeps the character in one Vaulted Dungeon via a tied Portal +// Recall Gem, and optionally /rc quit after N minutes without a kill. +// +// Safety rules (the owner's, added when it was taken in): +// * ILT only. The module does nothing (no tick work, no recall, no quit, no tab) unless +// IltServerOptions.IsIltLikeWorld says this is an Infinite Leaftide / ACECustom world, the same +// verdict every other ILT feature follows. A command answers "not available on this server". +// * Master switch, off by default: IltHubState.VaultedDungeonsEnabled (the ILT settings, and the +// engine's Settings > Navigation row RynthAi mirrors; RynthAi's profile setting until 2026-10-20, +// copied once). It is the only copy. While it is off the module +// ignores AutoStart, never ticks, sends no recall and no /rc quit, and the tab is hidden. Turning +// it off while running stops the keeper at once and says so once. +// * Active is never resumed from the saved settings. It starts when the player turns it on, or on +// arriving in the chosen dungeon with Auto Start On Arrival on (master on); a relog starts Off. +// * No recall gem while RynthAi is in combat, buffing or waiting on the server, or the client is +// busy: the recall waits until it is clear (a warning on the normal 30 s cadence). +// * /rc quit goes out at most once per activation, and only if Active, ILT and the master are all +// still true at the moment of sending. +// * The no-kill timer restarts on the luminance line, on the server's killer notification (a +// killing blow of yours) and on a pet-capture success reply. Kills by pets or fellows that pay +// no luminance still don't count; the tab says so. +using System; +using System.Collections.Generic; +using System.IO; +using System.Numerics; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using ImGuiNET; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One known Vaulted Dungeon (landblock high word; the client does not see the layer). +internal readonly record struct VaultedDungeon(string Name, uint Landblock); + +internal sealed class IltVaultedDungeons : IIltFeature +{ + // Keep order stable: saved picks are by 1-based index into this list. + private static readonly VaultedDungeon[] Dungeons = + { + new("Tyrant's Quarry", 0x01F7), + new("Tusgian Barracks", 0x8C03), + new("Wailing Cells", 0x01C2), + new("Chamber of Idols", 0x5649), + new("Fiun Redoubt", 0x0178), // added 2026-09-27 + new("Tumerok Tunnels", 0x5754), // added 2026-10-03 + }; + + private static readonly string[] GemNames = + { + "Primary Portal Recall Gem", + "Secondary Portal Recall Gem", + }; + + private static readonly (string Name, float Value)[] Powers = + { + ("Fast", 0f), ("Medium", 0.5f), ("Full Power", 1f), + }; + + private static readonly int[] QuitPresets = { 1, 2, 5, 10, 15, 30 }; + + private const long FirstRecallAfterMs = 1000; + private const long RecallAfterMs = 5000; + private const int QuitMin = 1, QuitMax = 30; + private const long WarnEveryMs = 30_000; + private const string SettingsFileName = "settings.json"; + private const string SettingsBadFileName = "settings.unreadable.json"; + + private const string CmdMetaOff = "/vt opt set EnableMeta False"; + private const string CmdNavOff = "/vt opt set EnableNav False"; + private const string CmdRepeatOn = "/ub playeroption AutoRepeatAttack on"; + private const string CmdAttackBar = "/vt setattackbar "; + private const string CmdQuit = "/rc quit"; + + // System line only (no player sender): "You've banked 1,234 Luminance." + private static readonly Regex KillLine = new( + @"^You've banked [\d,]+ Luminance\.\s*$", + RegexOptions.Compiled | RegexOptions.CultureInvariant); + + /// Why the keeper is idle (): "" = it may run. + private const string GateWorld = "world", GateMaster = "master"; + + private readonly IltHubContext _ctx; + private readonly object _gate = new(); + private Cfg _cfg = new(); + private bool _loaded; + private bool _dirty; + private string? _lastGoodJson; + + // Seams (the tests fake them): the master switch, what RynthAi is doing, the clock, the gem use. + internal Func MasterEnabled; + internal Func Activity; + internal Func Clock = () => IltHubContext.NowMs; + /// Uses the named gem from the pack; false when the pack has none. + internal Func UseGem; + + // Runtime (pump thread). + private long _outSinceMs; + private long _lastRecallMs; + private long _clockStartMs; + private long _realKillMs; + private bool _wasInside; + private bool _quitSent; + private long _lastWarnMs = -WarnEveryMs; + private string _publishedGate = "?"; + private string _state = "paused"; // paused / setup / in / out / portal / nogem + private long? _quitLeftMs; + private bool? _presentBefore; + private long _idleSecs; + private long _inSinceMs; + private long _portalSinceMs; + private int _kills; + private long _dungeonSecs; + private long _lastTickMs; + + // Snapshot for the render thread (copied under _gate). + private Snapshot _snap = Snapshot.Empty; + + public IltVaultedDungeons(IltHubContext ctx) + { + _ctx = ctx; + MasterEnabled = () => _ctx.State.VaultedDungeonsEnabled; + Activity = () => _ctx.Ai.Activity(); + UseGem = gemName => + { + var gem = _ctx.Inventory.FindByName(n => n.Equals(gemName, StringComparison.OrdinalIgnoreCase)); + if (gem == null) return false; + _ctx.Inventory.Use(gem); + return true; + }; + } + + /// Whether the keeper is running (tests, status). + internal bool IsActive => _cfg.Active; + + private long Now() => Clock(); + + /// + /// The two hard rules, asked fresh each time: an ILT-like world, and the master switch on. + /// says which one failed ("" when allowed). + /// + private bool Allowed(out string gate) + { + gate = !_ctx.Options.IsIltLikeWorld ? GateWorld : !MasterEnabled() ? GateMaster : string.Empty; + return gate.Length == 0; + } + + /// Same, for commands and the tab: why the keeper can't be used now (null = it can). + private static string? GateReply(string gate) => gate switch + { + GateWorld => "Not available on this server (Infinite Leaftide / ACECustom only).", + GateMaster => "Off: turn on \"Vaulted Dungeons\" in the ILT settings (/ilt settings; also Settings > Navigation) first (the master switch, off by default).", + _ => null, + }; + + // ── Persistence ───────────────────────────────────────────────────────── + + private string SettingsDir => Path.Combine(_ctx.Store.CharFolder, "VaultedDungeons"); + private string SettingsPath => Path.Combine(SettingsDir, SettingsFileName); + + private void EnsureLoaded() + { + if (_loaded) return; + _loaded = true; + try + { + string path = SettingsPath; + if (!File.Exists(path)) return; + string text = File.ReadAllText(path); + var cfg = JsonSerializer.Deserialize(text, IltVaultedDungeonsJsonContext.Default.Cfg); + if (cfg == null) return; + _cfg = Sanitize(cfg); + _lastGoodJson = text; + } + catch (Exception ex) + { + RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons: settings load failed: {ex.Message}"); + } + } + + private void SaveIfDirty() + { + if (!_dirty) return; + _dirty = false; + try + { + Directory.CreateDirectory(SettingsDir); + string path = SettingsPath; + // Corrupt / mid-write: keep a copy, then rewrite from last good + current cfg. + if (File.Exists(path)) + { + try + { + string existing = File.ReadAllText(path); + if (_lastGoodJson == null) + JsonSerializer.Deserialize(existing, IltVaultedDungeonsJsonContext.Default.Cfg); // throws if bad + } + catch + { + try + { + File.Copy(path, Path.Combine(SettingsDir, SettingsBadFileName), overwrite: true); + _ctx.Chat("[Vaulted Dungeons] settings.json would not read — kept a copy as " + + SettingsBadFileName + "."); + } + catch { /* best effort */ } + } + } + string json = JsonSerializer.Serialize(_cfg, IltVaultedDungeonsJsonContext.Default.Cfg); + File.WriteAllText(path, json); + _lastGoodJson = json; + } + catch (Exception ex) + { + RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons: settings save failed: {ex.Message}"); + } + } + + private static Cfg Sanitize(Cfg c) + { + // Never resumed from disk: the file keeps its "active" field, but a relog (or turning the + // master switch back on) starts Off. Auto Start On Arrival is the only way back in by itself. + c.Active = false; + c.Dungeon = ClampInt(c.Dungeon, 0, Dungeons.Length, 0); + c.Gem = ClampInt(c.Gem, 0, GemNames.Length, 0); + c.QuitMinutes = ClampInt(c.QuitMinutes, QuitMin, QuitMax, 2); + c.AttackPower = Powers[PowerIndex(c.AttackPower)].Value; + return c; + } + + private static int ClampInt(int v, int lo, int hi, int def) + => v < lo || v > hi ? def : v; + + private static int PowerIndex(float v) + { + int best = 0; + float bestGap = float.MaxValue; + for (int i = 0; i < Powers.Length; i++) + { + float gap = Math.Abs(Powers[i].Value - v); + if (gap < bestGap) { best = i; bestGap = gap; } + } + return best; + } + + private static string PowerText(float p) + { + string t = p.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture); + return t; + } + + // ── IIltFeature ───────────────────────────────────────────────────────── + + public void Tick(long nowMs) + { + // The hard rules first: ILT only, master switch on. Nothing below runs otherwise (not even + // reading the settings file), and a keeper that was running is stopped on the spot. + if (!Allowed(out string gate)) + { + StopForGate(gate); + PublishGate(gate); + return; + } + + EnsureLoaded(); + SaveIfDirty(); + + // Time in dungeon (kills/hour): only while last state was "in". + if (_lastTickMs > 0 && _state == "in") + _dungeonSecs += Math.Max(0, (nowMs - _lastTickMs) / 1000); + _lastTickMs = nowMs; + + if (!_ctx.Host.HasGetPlayerPose || !_ctx.Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _) || cell == 0) + { + Publish(); + return; + } + + uint landblock = cell >> 16; + bool portaling = _ctx.Host.HasIsPortaling && _ctx.Host.IsPortaling(); + VaultedDungeon? dungeon = _cfg.Dungeon > 0 && _cfg.Dungeon <= Dungeons.Length + ? Dungeons[_cfg.Dungeon - 1] + : null; + + // Present check (for Auto Start / arrive actions) even while Off. + if (dungeon == null) + _presentBefore = null; + else if (!portaling) + { + bool here = landblock == dungeon.Value.Landblock; + if (here && _presentBefore != true) OnArrive(dungeon.Value, nowMs); + _presentBefore = here; + } + + _quitLeftMs = null; + if (!_cfg.Active) + { + _state = "paused"; + _outSinceMs = 0; + Publish(); + return; + } + + string? gemName = _cfg.Gem > 0 && _cfg.Gem <= GemNames.Length ? GemNames[_cfg.Gem - 1] : null; + if (dungeon == null || gemName == null) + { + _state = "setup"; + _wasInside = false; + Warn(nowMs, dungeon == null + ? "Pick a dungeon in the Vaulted Dungeons tab." + : "Pick a recall gem in the Vaulted Dungeons tab."); + Publish(); + return; + } + + bool inside = landblock == dungeon.Value.Landblock; + if (inside && !portaling) + { + if (!_wasInside) + { + _clockStartMs = nowMs; + _inSinceMs = nowMs; + } + _wasInside = true; + _outSinceMs = 0; + _portalSinceMs = 0; + _state = "in"; + _idleSecs = Math.Max(0, (nowMs - _clockStartMs) / 1000); + if (_cfg.Quit) + { + long quitAfterMs = _cfg.QuitMinutes * 60_000L; + _quitLeftMs = Math.Max(0, quitAfterMs - (nowMs - _clockStartMs)); + if (nowMs - _clockStartMs >= quitAfterMs && !_quitSent) + { + // Once per activation, and only if ILT, the master switch and Active are all + // still true right now (asked again: they may have changed since the top of the tick). + string nowGate = string.Empty; + if (!_cfg.Active || !Allowed(out nowGate)) + { + StopForGate(nowGate); + PublishGate(nowGate); + return; + } + _quitSent = true; + _ctx.Chat($"[Vaulted Dungeons] No kill in {_cfg.QuitMinutes} minute" + + (_cfg.QuitMinutes == 1 ? "" : "s") + " — quitting."); + Invoke(CmdQuit); + } + } + Publish(); + return; + } + + _wasInside = false; + if (portaling) + { + _state = "portal"; + _outSinceMs = 0; + if (_portalSinceMs == 0) _portalSinceMs = nowMs; + Publish(); + return; + } + _portalSinceMs = 0; + + if (_outSinceMs == 0) _outSinceMs = nowMs; + _state = "out"; + + bool tried = _lastRecallMs >= _outSinceMs; + bool due = (!tried && nowMs - _outSinceMs >= FirstRecallAfterMs) + || (tried && nowMs - _lastRecallMs >= RecallAfterMs); + if (due) + { + // Not in the middle of a fight, a buff chain or an unanswered use/cast: the recall waits + // (still due, so it goes out on the first clear tick) and says so on the normal cadence. + string? busy = BusyReason(); + if (busy != null) + { + _state = "busy"; + Warn(nowMs, $"Waiting to use the {gemName}: {busy}."); + } + else if (UseGem(gemName)) + { + _lastRecallMs = nowMs; + _ctx.Chat($"[Vaulted Dungeons] Not in {dungeon.Value.Name} — using the {gemName}."); + } + else + { + _state = "nogem"; + Warn(nowMs, $"No {gemName} in your pack."); + } + } + Publish(); + } + + /// + /// Why a recall gem must not be used now, or null when it may. RynthAi's activity (its "RynthAi.Activity" + /// bits: combat, buffing, loot, salvage, crafting, a use/cast waiting on the server) and the client's + /// busy hourglass; RynthAi not answering counts as busy (nothing is known, so nothing is used). + /// + private string? BusyReason() + { + RynthAiActivity? a = Activity(); + if (a is null) return "RynthAi is not ready"; + RynthAiActivity f = a.Value; + if ((f & RynthAiActivity.Combat) != 0) return "RynthAi is in combat"; + if ((f & RynthAiActivity.Buffing) != 0) return "RynthAi is buffing"; + if ((f & RynthAiActivity.ServerAction) != 0) return "RynthAi is waiting on the server"; + if ((f & RynthAiActivity.Looting) != 0) return "RynthAi is looting"; + if ((f & RynthAiActivity.Salvaging) != 0) return "RynthAi is salvaging"; + if ((f & RynthAiActivity.Crafting) != 0) return "RynthAi is crafting"; + if (_ctx.Inventory.IsBusy) return "the client is busy"; + return null; + } + + /// + /// A rule failed (not ILT any more, or the master switch went off): a running keeper stops at once + /// and says so once; an idle one has nothing to do. Safe to call every tick. + /// + private void StopForGate(string gate) + { + _outSinceMs = 0; + _wasInside = false; + _quitLeftMs = null; + _presentBefore = null; + if (!_cfg.Active) return; + _cfg.Active = false; + _dirty = true; + _state = "paused"; + _ctx.Chat("[Vaulted Dungeons] Stopped: " + (gate == GateWorld + ? "this is not an Infinite Leaftide / ACECustom world." + : "\"Vaulted Dungeons\" (the master switch) was turned off.")); + SaveIfDirty(); + } + + /// The idle snapshot (only when the reason changes: nothing else runs while gated). + private void PublishGate(string gate) + { + if (gate == _publishedGate) return; + _publishedGate = gate; + Publish(gate); + } + + public bool OnChat(string text) + { + if (string.IsNullOrEmpty(text)) return false; + string line = text.TrimEnd(); + bool luminance = KillLine.IsMatch(line); + // A pet-capture success counts as a kill for the timer too (the same replies RynthAi's Pets + // tab matches); nothing else is guessed. + if (!luminance && !PetCaptureLines.IsSuccess(line)) return false; + if (!_cfg.Active || !Allowed(out _)) return false; + NoteKill(Now(), countKill: luminance); + return false; // never eat the luminance line + } + + /// + /// The server's killer notification: this character landed a killing blow (RynthILTPlugin + /// .OnKillNotification, pump thread). Restarts the no-kill timer, like the luminance line. + /// + public void OnKillNotification() + { + if (!_cfg.Active || !Allowed(out _)) return; + NoteKill(Now(), countKill: false); + } + + /// Restarts the Kill Client timer. The kill counter moves only on the luminance line (one per kill). + private void NoteKill(long now, bool countKill) + { + _clockStartMs = now; + _realKillMs = now; + if (countKill && _state == "in") _kills++; + Publish(); + } + + public void OnLogout() + { + // Logging out ends the run: Active is never carried over (see Sanitize). + _cfg.Active = false; + SaveIfDirty(); + _wasInside = false; + _outSinceMs = 0; + _presentBefore = null; + _state = "paused"; + Publish(); + } + + // ── Arrive / commands ─────────────────────────────────────────────────── + + private void OnArrive(VaultedDungeon dungeon, long nowMs) + { + // Only called while ILT and the master switch are on (Tick's gate), so Auto Start is honoured here only. + if (_cfg.AutoStart && !_cfg.Active) + { + Activate(nowMs); + _ctx.Chat($"[Vaulted Dungeons] Arrived in {dungeon.Name} — switched On (Auto Start On Arrival)."); + } + // The arrival settings are part of running the keeper: nothing is sent while it is Off. + if (!_cfg.Active) return; + if (_cfg.DisableMeta) Invoke(CmdMetaOff); + if (_cfg.DisableNav) Invoke(CmdNavOff); + if (_cfg.RepeatAttack) Invoke(CmdRepeatOn); + if (_cfg.SetPower) Invoke(CmdAttackBar + PowerText(_cfg.AttackPower)); + } + + private void Invoke(string cmd) + { + if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(cmd); + } + + private void Warn(long nowMs, string text) + { + if (nowMs - _lastWarnMs < WarnEveryMs) return; + _lastWarnMs = nowMs; + _ctx.Chat("[Vaulted Dungeons] " + text); + } + + /// Pump-thread: /ilt vaulted [on|off|toggle|status]. + public bool HandleCommand(string[] args) + { + // ILT only, master switch on: otherwise the only answer is why (the keeper itself stays idle). + if (!Allowed(out string gate)) + { + if (_cfg.Active) StopForGate(gate); + _ctx.Chat("[Vaulted Dungeons] " + GateReply(gate)); + return true; + } + + EnsureLoaded(); + string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "status"; + switch (sub) + { + case "on": + case "start": + SetActive(true); + return true; + case "off": + case "stop": + SetActive(false); + _ctx.Chat("[Vaulted Dungeons] Off."); + return true; + case "toggle": + SetActive(!_cfg.Active); + if (!_cfg.Active) _ctx.Chat("[Vaulted Dungeons] Off."); + return true; + default: + string d = _cfg.Dungeon > 0 && _cfg.Dungeon <= Dungeons.Length + ? Dungeons[_cfg.Dungeon - 1].Name : "(none)"; + string g = _cfg.Gem > 0 && _cfg.Gem <= GemNames.Length + ? GemNames[_cfg.Gem - 1] : "(none)"; + _ctx.Chat($"[Vaulted Dungeons] {(_cfg.Active ? "On" : "Off")} — dungeon={d}, gem={g}, " + + $"kill-client={(_cfg.Quit ? $"{_cfg.QuitMinutes}m" : "off")}, state={_state}."); + _ctx.Chat("[Vaulted Dungeons] /ilt vaulted [on|off|toggle|status] (Mini Remote tab; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons)"); + return true; + } + } + + /// Starts the keeper (the player's own action, or Auto Start On Arrival). Pump thread; ILT and master already checked. + private void Activate(long nowMs) + { + _cfg.Active = true; + _dirty = true; + _outSinceMs = 0; + _wasInside = false; // the no-kill clock starts when the first in-dungeon tick sees us inside + _clockStartMs = nowMs; + _quitSent = false; // /rc quit: once per activation + _lastRecallMs = 0; + Publish(); + } + + private void SetActive(bool value) + { + if (value) + { + // From the tab's button too (posted to the pump): re-check, the switch may have gone off since. + if (!Allowed(out string gate)) + { + _ctx.Chat("[Vaulted Dungeons] " + GateReply(gate)); + return; + } + EnsureLoaded(); + if (!_cfg.Active) + { + Activate(Now()); + _ctx.Chat("[Vaulted Dungeons] On."); + } + return; + } + _cfg.Active = false; + _outSinceMs = 0; + _dirty = true; + _clockStartMs = Now(); + _wasInside = false; + _quitLeftMs = null; + _state = "paused"; + Publish(); + } + + // ── Render snapshot ───────────────────────────────────────────────────── + + private void Publish(string gate = "") + { + _publishedGate = gate; + lock (_gate) + { + _snap = new Snapshot( + _cfg.Active, _cfg.Dungeon, _cfg.Gem, _cfg.Quit, _cfg.QuitMinutes, + _cfg.ShowInDungeon, _cfg.AutoStart, _cfg.DisableMeta, _cfg.DisableNav, + _cfg.RepeatAttack, _cfg.SetPower, _cfg.AttackPower, + _state, _quitLeftMs, _idleSecs, _inSinceMs, _outSinceMs, _portalSinceMs, + _realKillMs, _kills, _dungeonSecs, Now(), gate); + } + } + + private Snapshot Take() + { + lock (_gate) return _snap; + } + + // ── UI (render thread) ────────────────────────────────────────────────── + + private bool _showAdvanced; + // Pending edits from the UI, applied on the next pump tick via Post. + private void PostEdit(Action edit) + { + _ctx.Post(() => + { + if (!Allowed(out _)) return; // gated while it waited: an edit changes nothing + EnsureLoaded(); + edit(_cfg); + _dirty = true; + Publish(); + }); + } + + public void Render() + { + // Settings load on the pump (Tick); the window only reads the snapshot. + Snapshot s = Take(); + + Vector4 colLabel = new(0.53f, 0.53f, 0.53f, 1f); + Vector4 colValue = new(1f, 1f, 1f, 1f); + Vector4 colGreen = new(0.27f, 0.80f, 0.40f, 1f); + Vector4 colAmber = new(0.95f, 0.65f, 0.20f, 1f); + Vector4 colRed = new(0.90f, 0.30f, 0.30f, 1f); + Vector4 colPurple = new(0.72f, 0.52f, 0.95f, 1f); + Vector4 colTitleRed = new(0.85f, 0.25f, 0.25f, 1f); + + // Title row: Vaulted (red) Dungeons (white) + On/Off + Advanced. + ImGui.TextColored(colTitleRed, "Vaulted"); + ImGui.SameLine(0, ImGui.CalcTextSize(" ").X); + ImGui.TextColored(colValue, "Dungeons"); + + // Not offered right now (the tab is hidden then; this covers a stale frame or a direct open). + if (s.Gate.Length > 0) + { + ImGui.Separator(); + ImGui.TextWrapped(GateReply(s.Gate) ?? "Not available."); + return; + } + ImGui.SameLine(0, 16); + Vector4 pill = s.Active ? colGreen : new(0.85f, 0.10f, 0.10f, 1f); + ImGui.PushStyleColor(ImGuiCol.Button, pill); + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, pill); + ImGui.PushStyleColor(ImGuiCol.ButtonActive, pill); + ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.05f, 0.05f, 0.05f, 1f)); + if (ImGui.SmallButton((s.Active ? " On " : " Off ") + "##vdactive")) + _ctx.Post(() => SetActive(!s.Active)); + ImGui.PopStyleColor(4); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip(s.Active + ? "On: keeping this character in the chosen dungeon.\nClick: turn off." + : "Off: doing nothing.\nClick: turn on."); + ImGui.SameLine(); + if (ImGui.SmallButton("Advanced##vdoptions")) _showAdvanced = !_showAdvanced; + + ImGui.Separator(); + + float labelW = ImGui.CalcTextSize("Recall Gem").X + 12; + void Label(string text) + { + ImGui.AlignTextToFramePadding(); + ImGui.TextColored(colLabel, text); + ImGui.SameLine(labelW); + } + + // Status + var (statusWord, statusCol) = s.State switch + { + "in" => ("In Dungeon", colGreen), + "out" => ("Recalling", colAmber), + "portal" => ("Portal Space", colPurple), + "setup" => ("Setup Needed", colAmber), + "nogem" => ("No Gem", colRed), + "busy" => ("Waiting (busy)", colAmber), + _ => ("Not Running", colRed), + }; + long since = s.State == "in" ? s.InSinceMs + : s.State == "out" ? s.OutSinceMs + : s.State == "portal" ? s.PortalSinceMs : 0; + string statusText = statusWord; + if (since > 0) + { + long secs = Math.Max(0, (s.NowMs - since) / 1000); + long h = secs / 3600, m = (secs / 60) % 60, sec = secs % 60; + statusText += h > 0 ? $" ({h}:{m:D2}:{sec:D2})" : $" ({m}:{sec:D2})"; + } + Label("Status"); + ImGui.TextColored(statusCol, statusText); + + // Dungeon combo (0 = pick, 1..N = Dungeons[i-1]) + Label("Dungeon"); + string[] dungeonChoices = BuildDungeonChoices(); + int dungeonIdx = s.Dungeon; + ImGui.SetNextItemWidth(260); + if (ImGui.Combo("##vddungeon", ref dungeonIdx, dungeonChoices, dungeonChoices.Length)) + PostEdit(c => { c.Dungeon = dungeonIdx; }); + + Label("Recall Gem"); + string[] gemChoices = { "Pick a gem", GemNames[0], GemNames[1] }; + int gemIdx = s.Gem; + ImGui.SetNextItemWidth(260); + if (ImGui.Combo("##vdgem", ref gemIdx, gemChoices, gemChoices.Length)) + PostEdit(c => { c.Gem = gemIdx; }); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Tie this gem to the dungeon's portal first."); + + Label("Last Kill"); + if (s.State == "in" && s.RealKillMs > 0) + ImGui.TextUnformatted($"{(s.NowMs - s.RealKillMs) / 1000} s ago"); + else + ImGui.TextUnformatted("-"); + + Label("Session"); + string perHour = s.DungeonSecs < 60 ? "-" + : Commas((long)(s.Kills * 3600.0 / Math.Max(1, s.DungeonSecs))); + ImGui.TextUnformatted($"{Commas(s.Kills)} kills ({perHour} Per Hour)"); + + if (s.QuitLeftMs is long left && s.QuitMinutes > 0) + { + float frac = (float)(left / (double)(s.QuitMinutes * 60_000L)); + string barLabel = $"Kill Client ({left / 60_000}:{(left / 1000) % 60:D2})"; + ImGui.ProgressBar(Math.Clamp(frac, 0f, 1f), new Vector2(-1, ImGui.GetTextLineHeight()), barLabel); + } + + if (_showAdvanced) + { + ImGui.Separator(); + ImGui.TextColored(colValue, "Advanced"); + + bool quit = s.Quit; + if (ImGui.Checkbox("Kill Client##vdquit", ref quit)) + { + bool on = quit; + _ctx.Post(() => + { + if (!Allowed(out _)) return; + EnsureLoaded(); + _cfg.Quit = on; + _cfg.QuitMinutes = ClampInt(_cfg.QuitMinutes, QuitMin, QuitMax, 2); + _clockStartMs = Now(); + _dirty = true; + Publish(); + }); + } + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("No kill for the set minutes in the dungeon: /rc quit closes the client (once per run).\n" + + "The timer restarts on the server's \"You've banked N Luminance.\" line, on your own killing blow,\n" + + "and on a successful pet capture. Kills by pets or fellows that pay you no luminance\n" + + "do NOT restart it, so keep the minutes generous if you hunt with pets."); + + ImGui.SameLine(); + ImGui.TextColored(colLabel, "after"); + ImGui.SameLine(); + if (ImGui.SmallButton($"{s.QuitMinutes} minute{(s.QuitMinutes == 1 ? "" : "s")}##vdmincycle")) + _ctx.Post(() => + { + if (!Allowed(out _)) return; + EnsureLoaded(); + _cfg.QuitMinutes = StepPreset(_cfg.QuitMinutes, +1); + _clockStartMs = Now(); + _dirty = true; + Publish(); + }); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + _ctx.Post(() => + { + if (!Allowed(out _)) return; + EnsureLoaded(); + _cfg.QuitMinutes = StepPreset(_cfg.QuitMinutes, -1); + _clockStartMs = Now(); + _dirty = true; + Publish(); + }); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Minutes with no kill before Kill Client quits.\nClick: longer. Right-click: shorter. (1, 2, 5, 10, 15, 30)"); + + BoolRow("Auto Start On Arrival##vdautostart", s.AutoStart, + v => PostEdit(c => c.AutoStart = v), + "Switch On by itself when you arrive in the chosen dungeon (logging in there counts)."); + + BoolRow("Disable Meta##vdnometa", s.DisableMeta, + v => PostEdit(c => c.DisableMeta = v), + "On arriving: " + CmdMetaOff); + + BoolRow("Disable Nav##vdnonav", s.DisableNav, + v => PostEdit(c => c.DisableNav = v), + "On arriving: " + CmdNavOff); + + BoolRow("Repeat Attacks On##vdrepeat", s.RepeatAttack, + v => PostEdit(c => c.RepeatAttack = v), + "On arriving: " + CmdRepeatOn); + + BoolRow("Set Attack Power##vdpower", s.SetPower, + v => PostEdit(c => c.SetPower = v), + "On arriving: " + CmdAttackBar + PowerText(s.AttackPower)); + ImGui.SameLine(); + int pi = PowerIndex(s.AttackPower); + if (ImGui.SmallButton(Powers[pi].Name + "##vdpowercycle")) + PostEdit(c => c.AttackPower = Powers[(pi + 1) % Powers.Length].Value); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + PostEdit(c => c.AttackPower = Powers[(pi - 1 + Powers.Length) % Powers.Length].Value); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Fast (0), Medium (0.5) or Full Power (1).\nClick: next. Right-click: back."); + } + + ImGui.Spacing(); + ImGui.TextDisabled("Note: the client sees the landblock, not the layer - standing in the retail copy also counts as \"in it\"."); + ImGui.TextDisabled("Kill Client: pet or fellow kills that pay you no luminance do not restart its timer."); + ImGui.TextDisabled("Recalls wait while RynthAi is in combat, buffing or waiting on the server."); + ImGui.TextDisabled("/ilt vaulted [on|off|toggle|status]"); + } + + private static void BoolRow(string id, bool value, Action set, string tip) + { + bool v = value; + if (ImGui.Checkbox(id, ref v)) set(v); + if (ImGui.IsItemHovered()) ImGui.SetTooltip(tip); + } + + private static string[] BuildDungeonChoices() + { + var list = new string[Dungeons.Length + 1]; + list[0] = "Pick a dungeon"; + for (int i = 0; i < Dungeons.Length; i++) list[i + 1] = Dungeons[i].Name; + return list; + } + + private static int StepPreset(int current, int dir) + { + if (dir > 0) + { + foreach (int m in QuitPresets) if (m > current) return m; + return QuitPresets[0]; + } + for (int i = QuitPresets.Length - 1; i >= 0; i--) + if (QuitPresets[i] < current) return QuitPresets[i]; + return QuitPresets[^1]; + } + + private static string Commas(long n) + { + string s = Math.Abs(n).ToString(); + var chars = new List(); + for (int i = 0; i < s.Length; i++) + { + if (i > 0 && (s.Length - i) % 3 == 0) chars.Add(','); + chars.Add(s[i]); + } + return (n < 0 ? "-" : "") + new string(chars.ToArray()); + } + + // ── Config / snapshot types ───────────────────────────────────────────── + + // internal (not private) so the source-generated IltVaultedDungeonsJsonContext can reach it. + internal sealed class Cfg + { + public bool Active { get; set; } + /// 0 = none, 1..N = Dungeons index. + public int Dungeon { get; set; } + /// 0 = none, 1 = primary, 2 = secondary. + public int Gem { get; set; } + public bool Quit { get; set; } + public int QuitMinutes { get; set; } = 2; + public bool ShowInDungeon { get; set; } + public bool AutoStart { get; set; } + public bool DisableMeta { get; set; } + public bool DisableNav { get; set; } + public bool RepeatAttack { get; set; } + public bool SetPower { get; set; } + public float AttackPower { get; set; } + } + + private readonly record struct Snapshot( + bool Active, int Dungeon, int Gem, bool Quit, int QuitMinutes, + bool ShowInDungeon, bool AutoStart, bool DisableMeta, bool DisableNav, + bool RepeatAttack, bool SetPower, float AttackPower, + string State, long? QuitLeftMs, long IdleSecs, long InSinceMs, long OutSinceMs, long PortalSinceMs, + long RealKillMs, int Kills, long DungeonSecs, long NowMs, string Gate) + { + /// Before the first tick (the tab is only offered while the keeper may run). + public static Snapshot Empty => new(false, 0, 0, false, 2, + false, false, false, false, false, false, 0f, + "paused", null, 0, 0, 0, 0, 0, 0, 0, 0, string.Empty); + } +} + +// Source-generated JSON only: the NativeAOT build (what the installer ships) has reflection-based +// serialization turned off, so JsonSerializer.Deserialize(text, options) failed there and the +// Vaulted Dungeons settings never loaded or saved. Same file format as before (camelCase, +// indented, nulls left out, case-sensitive property names on read). +[JsonSerializable(typeof(IltVaultedDungeons.Cfg))] +[JsonSourceGenerationOptions( + WriteIndented = true, + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +internal partial class IltVaultedDungeonsJsonContext : JsonSerializerContext { } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltWorld.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltWorld.cs new file mode 100644 index 0000000..4defa34 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltWorld.cs @@ -0,0 +1,294 @@ +// IltWorld.cs - RynthILT's view of the game's objects, read straight from the host. +// +// The ILT Hub read items through RynthAi's WorldObjectCache while it lived in RynthAi. RynthILT +// has no cache of its own events, so this asks the client directly (the way RynthSort's +// InventoryReader does): the player's pack and side packs through GetContainerContents (the +// main pack's list also holds the side packs and the worn and wielded items), everything +// else the client knows through GetLiveObjectIds. Names, classes and container links are taken +// at each scan; property reads (Values) are live. A scan is kept for ScanMs, so the many +// Items() calls of one tick cost one walk; GetDirectInventory(forceRefresh: true) walks again. +// Pump thread only (the render thread only ever sees snapshots the features built). +using System; +using System.Collections.Generic; +using RynthCore.Loot; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One object as RynthILT sees it: identity from the last scan, properties read live. +internal sealed class WorldObject +{ + private readonly IltObjects _owner; + + internal WorldObject(IltObjects owner, int id, string name, AcObjectClass objectClass, int container) + { + _owner = owner; + Id = id; + Name = name ?? string.Empty; + ObjectClass = objectClass; + DirectContainerId = container; + } + + public int Id { get; } + public string Name { get; } + public AcObjectClass ObjectClass { get; } + + /// The container the scan found it in (the player or a side pack); 0 off the player. + public int DirectContainerId { get; } + + /// The container it is in now (live), else where the scan found it. + public int Container => _owner.ContainerOf(Id, DirectContainerId); + + /// Who wields it (live; 0 = nobody). + public int Wielder => _owner.WielderOf(Id); + + /// Where it is wielded (live; 0 = not wielded). + public int WieldedLocation => _owner.WieldedLocationOf(Id); + + /// An int property, read live ( when unknown). + public int Values(int key, int defaultValue) => _owner.IntProperty(Id, unchecked((uint)key), defaultValue); +} + +/// The player's items and the objects around, from host calls. +internal sealed class IltObjects +{ + // Property and type ids (AC's). + internal const uint IntItemsCapacity = 6; + internal const uint IntCurrentWieldedLocation = 10; + internal const uint IntDamageType = 45; + private const uint ItemTypeCreature = 0x00000010; + private const uint ItemTypeContainer = 0x00000200; + private const long ScanMs = 1000; + private const int MainPackSlots = 102; + + private readonly RynthCoreHost _host; + private uint[] _buf = new uint[512]; + private List _inventory = new(); + private Dictionary _byId = new(); + private long _scannedAt = long.MinValue; + private uint _scannedPlayer; + + public IltObjects(RynthCoreHost host) => _host = host; + + /// Forgets the last scan (logout). + public void Clear() + { + _inventory = new List(); + _byId = new Dictionary(); + _scannedAt = long.MinValue; + _scannedPlayer = 0; + } + + // ── Inventory ─────────────────────────────────────────────────────────── + + /// Everything the player carries or wears (a snapshot, at most ScanMs old). + public IEnumerable GetInventory() => Scan(force: false); + + /// The same walk; reads the client again now. + public IReadOnlyList GetDirectInventory(bool forceRefresh = false) => Scan(forceRefresh); + + /// A carried item by id, else any object the client knows by id (null when it knows none). + public WorldObject? this[int id] + { + get + { + Scan(force: false); + if (_byId.TryGetValue(id, out var wo)) return wo; + uint uid = unchecked((uint)id); + if (id == 0 || !_host.HasGetObjectName || !_host.TryGetObjectName(uid, out string name)) return null; + return new WorldObject(this, id, name, Classify(uid), 0); + } + } + + private List Scan(bool force) + { + long now = Environment.TickCount64; + uint player = _host.GetPlayerId(); + if (!force && player == _scannedPlayer && now - _scannedAt < ScanMs) return _inventory; + _scannedAt = now; + _scannedPlayer = player; + if (player == 0 || !_host.HasGetContainerContents) { _inventory = new(); _byId = new(); return _inventory; } + + var list = new List(256); + var byId = new Dictionary(256); + int pid = unchecked((int)player); + foreach (uint id in Contents(player)) + { + if (id == 0) continue; + uint type = ItemType(id); + Add(list, byId, id, type, pid); + // Side packs: containers with room for items (foci hold none). + if ((type & ItemTypeContainer) == 0) continue; + if (!_host.TryGetObjectIntProperty(id, IntItemsCapacity, out int cap) || cap <= 0) continue; + foreach (uint inner in Contents(id)) + if (inner != 0) Add(list, byId, inner, ItemType(inner), unchecked((int)id)); + } + _inventory = list; + _byId = byId; + return list; + } + + private void Add(List list, Dictionary byId, uint id, uint type, int container) + { + int iid = unchecked((int)id); + if (byId.ContainsKey(iid)) return; + string name = _host.HasGetObjectName && _host.TryGetObjectName(id, out string n) ? n ?? string.Empty : string.Empty; + var wo = new WorldObject(this, iid, name, ClassifyByItemType(type), container); + list.Add(wo); + byId[iid] = wo; + } + + private uint[] Contents(uint container) + { + int n = _host.GetContainerContents(container, _buf); + if (n >= _buf.Length) + { + _buf = new uint[Math.Max(n + 64, _buf.Length * 2)]; + n = _host.GetContainerContents(container, _buf); + } + if (n <= 0) return Array.Empty(); + var ids = new uint[Math.Min(n, _buf.Length)]; + Array.Copy(_buf, ids, ids.Length); + return ids; + } + + // ── The world around ──────────────────────────────────────────────────── + + /// Creatures the client knows (monsters, NPCs, vendors, pets), not carried. + public IEnumerable GetLandscape() => Around(creaturesOnly: true); + + /// Every object the client knows that the player doesn't carry. + public IEnumerable GetLandscapeObjects() => Around(creaturesOnly: false); + + private List Around(bool creaturesOnly) + { + var result = new List(); + if (!_host.HasGetLiveObjectIds) return result; + Scan(force: false); + uint player = _host.GetPlayerId(); + foreach (uint id in _host.GetLiveObjectIds()) + { + if (id == 0 || id == player || _byId.ContainsKey(unchecked((int)id))) continue; + uint type = ItemType(id); + if (creaturesOnly && (type & ItemTypeCreature) == 0) continue; + if (!_host.HasGetObjectName || !_host.TryGetObjectName(id, out string name) || string.IsNullOrEmpty(name)) continue; + result.Add(new WorldObject(this, unchecked((int)id), name, ClassifyByItemType(type), 0)); + } + return result; + } + + /// Metres between two objects (double.MaxValue when either position can't be read). + public double Distance(int id1, int id2) + { + if (!_host.TryGetObjectPosition(unchecked((uint)id1), out uint cell1, out float x1, out float y1, out float z1)) return double.MaxValue; + if (!_host.TryGetObjectPosition(unchecked((uint)id2), out uint cell2, out float x2, out float y2, out float z2)) return double.MaxValue; + float gx1 = ((cell1 >> 24) & 0xFF) * 192f + x1; + float gy1 = ((cell1 >> 16) & 0xFF) * 192f + y1; + float gx2 = ((cell2 >> 24) & 0xFF) * 192f + x2; + float gy2 = ((cell2 >> 16) & 0xFF) * 192f + y2; + float dx = gx1 - gx2, dy = gy1 - gy2, dz = z1 - z2; + double d = Math.Sqrt(dx * dx + dy * dy + dz * dz); + return double.IsFinite(d) ? d : double.MaxValue; + } + + // ── Live reads ────────────────────────────────────────────────────────── + + internal int IntProperty(int id, uint stype, int defaultValue) + => _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(unchecked((uint)id), stype, out int v) ? v : defaultValue; + + internal int ContainerOf(int id, int scanned) + { + if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(unchecked((uint)id), out uint container, out _, out _)) + return unchecked((int)container); + return scanned; + } + + internal int WielderOf(int id) + { + if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(unchecked((uint)id), out _, out uint wielder, out _)) + return unchecked((int)wielder); + return _host.HasGetObjectWielderInfo && _host.TryGetObjectWielderInfo(unchecked((uint)id), out uint w, out _) ? unchecked((int)w) : 0; + } + + internal int WieldedLocationOf(int id) + { + if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(unchecked((uint)id), out _, out uint wielder, out uint location) && wielder != 0) + return unchecked((int)location); + return Math.Max(0, IntProperty(id, IntCurrentWieldedLocation, 0)); + } + + private uint ItemType(uint id) => _host.HasGetItemType && _host.TryGetItemType(id, out uint t) ? t : 0; + + private AcObjectClass Classify(uint id) => ClassifyByItemType(ItemType(id)); + + // ── Packs ─────────────────────────────────────────────────────────────── + + /// + /// A side pack with at least free slots (the one with the most), + /// else the main pack when and it has a slot, else 0. Foci + /// and packs whose capacity isn't known never qualify (a move into a full pack crashes the + /// client). RynthAi's WorldObjectCache.FindPackFor, on this view. + /// + public static int FindPackFor(RynthCoreHost host, IltObjects? objects, bool includeMainPack, int requireFree) + { + if (objects == null) return 0; + int playerId = unchecked((int)host.GetPlayerId()); + if (playerId == 0) return 0; + if (requireFree < 1) requireFree = 1; + var inv = objects.GetDirectInventory(forceRefresh: true); + int bestPack = 0, bestFree = 0, mainUsed = 0; + foreach (var p in inv) + { + if (p.DirectContainerId != playerId) continue; + bool isPack = p.ObjectClass == AcObjectClass.Container; + bool isFoci = p.ObjectClass == AcObjectClass.Foci || p.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0; + if (!isPack && !isFoci && p.WieldedLocation <= 0 && p.Wielder == 0) mainUsed++; + if (!isPack || isFoci) continue; + int capacity = p.Values(unchecked((int)IntItemsCapacity), 0); + if (capacity <= 0) continue; + int used = 0; + foreach (var it in inv) + if (it.DirectContainerId == p.Id && it.ObjectClass != AcObjectClass.Container) used++; + int free = capacity - used; + if (free >= requireFree && free > bestFree) { bestFree = free; bestPack = p.Id; } + } + if (bestPack != 0) return bestPack; + if (!includeMainPack) return 0; + return MainPackSlots - mainUsed > 0 ? playerId : 0; + } + + // ── Classification (RynthAi's WorldObjectCache.ClassifyByItemType) ────── + + internal static AcObjectClass ClassifyByItemType(uint t) + { + if (t == 0) return AcObjectClass.Unknown; + if ((t & 0x00000010) != 0) return AcObjectClass.Monster; + if ((t & 0x00040000) != 0) return AcObjectClass.TradeNote; + if ((t & 0x00080000) != 0) return AcObjectClass.ManaStone; + if ((t & 0x00001000) != 0) return AcObjectClass.SpellComponent; + if ((t & 0x00000800) != 0) return AcObjectClass.Gem; + if ((t & 0x00004000) != 0) return AcObjectClass.Key; + if ((t & 0x10000000) != 0) return AcObjectClass.Lifestone; + if ((t & 0x40000000) != 0) return AcObjectClass.Salvage; + if ((t & 0x20000000) != 0) return AcObjectClass.Ust; + if ((t & 0x00400000) != 0) return AcObjectClass.BaseCooking; + if ((t & 0x00800000) != 0) return AcObjectClass.BaseAlchemy; + if ((t & 0x02000000) != 0) return AcObjectClass.BaseFletching; + if ((t & 0x04000000) != 0) return AcObjectClass.CraftedAlchemy; + if ((t & 0x08000000) != 0) return AcObjectClass.CraftedFletching; + if ((t & 0x00100000) != 0) return AcObjectClass.Services; + if ((t & 0x00010000) != 0) return AcObjectClass.Portal; + if ((t & 0x00002000) != 0) return AcObjectClass.Book; + if ((t & 0x00000200) != 0) return AcObjectClass.Container; + if ((t & 0x00008000) != 0) return AcObjectClass.WandStaffOrb; + if ((t & 0x00000100) != 0) return AcObjectClass.MissileWeapon; + if ((t & 0x00000002) != 0) return AcObjectClass.Armor; + if ((t & 0x00000001) != 0) return AcObjectClass.MeleeWeapon; + if ((t & 0x00000004) != 0) return AcObjectClass.Clothing; + if ((t & 0x00000008) != 0) return AcObjectClass.Jewelry; + if ((t & 0x00000020) != 0) return AcObjectClass.Food; + if ((t & 0x00000040) != 0) return AcObjectClass.Money; + if ((t & 0x00000080) != 0) return AcObjectClass.Misc; + return AcObjectClass.Unknown; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs new file mode 100644 index 0000000..7053f4d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs @@ -0,0 +1,317 @@ +// RynthAiClient.cs - RynthILT's side of the "RynthAi.Hub" interface (Plugins/Shared/RynthAiHubApi.cs): +// the Mini Remote that hosts the ILT tabs, the /myquests tracker, spell names, VTank loot-profile +// matching, the .usd importer and the Mini Remote's session stats. +// +// The table is looked up through the host (API v68) and kept for RecheckMs; Reset() (login, logout, +// shutdown) and a table whose Version went to 0 (RynthAi shut down) force a fresh lookup, so a +// RynthAi that loads after RynthILT, is reloaded or isn't installed is handled: every call then +// reports "no RynthAi" and the ILT features that need it say so. The pointer is kept in a volatile +// field so the render thread (RenderSection) can use what the pump looked up; the table is never +// freed by RynthAi (its Version is zeroed instead), so a stale pointer is safe to read. +using System; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT.Hub; + +/// One /myquests flag as RynthAi has it (QuestRecord's fields the Temple tracker reads). +internal sealed class QuestRecord +{ + public string Key = string.Empty; + public int Solves; + public int MaxSolves; + public DateTime CompletedOn = DateTime.MinValue; + public TimeSpan RepeatTime = TimeSpan.Zero; + + /// RynthAi's QuestRecord.IsReady (UB's): the timer ran out and it isn't a once-only flag. + public bool IsReady() + { + if ((CompletedOn + RepeatTime) > DateTime.UtcNow) return false; + return !(MaxSolves == 1 && Solves <= 1); + } + + /// Time until the flag can be solved again (zero when ready). + public TimeSpan TimeUntilReady() + { + var left = (CompletedOn + RepeatTime) - DateTime.UtcNow; + return left > TimeSpan.Zero ? left : TimeSpan.Zero; + } +} + +internal sealed unsafe class RynthAiClient +{ + public const string NotLoaded = "needs RynthAi (not loaded)"; + private const long RecheckMs = 3000; + + private readonly RynthCoreHost _host; + private RynthAiHubApiV1* _t; // pump-thread copy + private IntPtr _renderTable; // what the render thread uses (volatile) + private bool _checked; + private long _checkedAt; + + private bool _pinned; // tests: a table handed in, never looked up + + public RynthAiClient(RynthCoreHost host) => _host = host; + + /// Tests only: use (a fake RynthAi's table) and never look it up. + internal void UseTableForTests(IntPtr table) + { + _pinned = true; + _t = (RynthAiHubApiV1*)table; + _checked = true; + System.Threading.Volatile.Write(ref _renderTable, table); + } + + /// Forget the table; the next call looks it up again (login, logout, RynthAi reload). + public void Reset() + { + if (_pinned) return; + _t = null; + _checked = false; + System.Threading.Volatile.Write(ref _renderTable, IntPtr.Zero); + } + + /// The table, looked up at most every RecheckMs (pump thread). + private RynthAiHubApiV1* Table + { + get + { + if (_pinned) return _t; + long now = Environment.TickCount64; + if (_checked && now - _checkedAt < RecheckMs && (_t == null || _t->Version >= 1)) return _t; + _checked = true; + _checkedAt = now; + _t = null; + if (_host.HasGetPluginInterface) + { + var t = (RynthAiHubApiV1*)_host.GetPluginInterface(RynthAiHub.PluginName, RynthAiHubApiV1.InterfaceName, RynthAiHubApiV1.InterfaceVersion); + if (t != null && t->Version >= 1 && t->StructSize >= RynthAiHubApiV1.BaseStructSize) _t = t; + } + System.Threading.Volatile.Write(ref _renderTable, (IntPtr)_t); + return _t; + } + } + + /// Pump thread: refreshes the lookup (the render thread only reads what this found). + public void Tick() => _ = Table; + + /// True when RynthAi's interface is there (pump thread). + public bool Available => Table != null; + + /// Any thread: the table the pump last found, if RynthAi hasn't shut down since. + private RynthAiHubApiV1* AnyThreadTable + { + get + { + var t = (RynthAiHubApiV1*)System.Threading.Volatile.Read(ref _renderTable); + return t != null && t->Version >= 1 ? t : null; + } + } + + // ── Mini Remote ───────────────────────────────────────────────────────── + + /// Puts the Mini Remote on a tab (any thread). The reply, or why it couldn't. + public string MiniRemoteTab(string tabId, string mode) + { + var t = AnyThreadTable; + if (t == null || t->MiniRemoteTab == null) return "The Mini Remote is RynthAi's; RynthAi isn't loaded."; + byte* reply = stackalloc byte[256]; + reply[0] = 0; + using var id = new Utf8(tabId); + using var m = new Utf8(mode); + int ok = t->MiniRemoteTab(id.P, m.P, reply, 256); + string text = Marshal.PtrToStringUTF8((IntPtr)reply) ?? string.Empty; + return ok != 0 ? text : (text.Length > 0 ? text : "The Mini Remote is not available yet."); + } + + /// True while the Mini Remote is on screen (any thread). + public bool MiniRemoteVisible + { + get + { + var t = AnyThreadTable; + return t != null && t->MiniRemoteVisible != null && t->MiniRemoteVisible() != 0; + } + } + + // ── Vaulted Dungeons (activity) ───────────────────────────────────────── + // The master switch is RynthILT's own since 2026-10-20 (IltHubState.VaultedDungeonsEnabled); + // RynthAi.Hub VaultedDungeonsEnabled is no longer read. + + /// + /// What RynthAi is doing now (its "RynthAi.Activity" interface: combat, buffing, loot, a use or cast + /// waiting on the server...); null when RynthAi isn't loaded or isn't ready. Resolved again every + /// call, as that interface requires (a RynthAi reload frees its table). Pump thread. + /// + public RynthAiActivity? Activity() + { + if (!_host.HasGetPluginInterface) return null; + try + { + var act = (RynthAiActivityApiV1*)_host.GetPluginInterface(RynthAiHub.PluginName, RynthAiActivityApiV1.InterfaceName, RynthAiActivityApiV1.InterfaceVersion); + if (act == null || act->Version < 1 || act->StructSize < (uint)sizeof(RynthAiActivityApiV1) || act->GetActivityFlags == null) return null; + uint flags = 0; + return act->GetActivityFlags(&flags) != 0 ? (RynthAiActivity)flags : null; + } + catch + { + return null; // a RynthAi mid-reload: not there this tick + } + } + + // ── Combat ────────────────────────────────────────────────────────────── + + /// + /// Asks RynthAi to back away from (RynthAi.Hub BackAwayFrom): a + /// RynthAiHub.BackAway* result, or int.MinValue when RynthAi isn't loaded or is older than the + /// call. Pump thread. + /// + public int BackAwayFrom(uint objectId, float radiusYards, int holdMs) + { + var t = Table; + if (t == null || !RynthAiHubApiV1.Has(t, RynthAiHubApiV1.BackAwayFromOffset) || t->BackAwayFrom == null) return int.MinValue; + return t->BackAwayFrom(objectId, radiusYards, holdMs); + } + + /// + /// Reports one player wield counter to RynthAi's loot rules (RynthAi.Hub SetPlayerCounter; the T11 + /// "Can Wield" key): < 0 = unknown. False without RynthAi (or an older one). Pump thread. + /// + public bool SetPlayerCounter(uint propertyId, long value) + { + var t = Table; + return t != null && RynthAiHubApiV1.Has(t, RynthAiHubApiV1.SetPlayerCounterOffset) + && t->SetPlayerCounter != null && t->SetPlayerCounter(propertyId, value) != 0; + } + + // ── Quests (/myquests) ────────────────────────────────────────────────── + + /// A /myquests flag from RynthAi's tracker (pump thread). + public bool TryGetQuestFlag(string key, out QuestRecord rec) + { + rec = null!; + var t = Table; + if (t == null || t->QuestFlag == null || string.IsNullOrWhiteSpace(key)) return false; + QuestFlagV1 f = default; + using var k = new Utf8(key); + if (t->QuestFlag(k.P, &f) == 0) return false; + rec = new QuestRecord + { + Key = key.ToLowerInvariant(), + Solves = f.Solves, + MaxSolves = f.MaxSolves, + CompletedOn = new DateTime(Math.Max(0, f.CompletedOnUtcTicks), DateTimeKind.Utc), + RepeatTime = TimeSpan.FromSeconds(Math.Max(0, f.RepeatSeconds)), + }; + return true; + } + + /// The tracker's state (pump thread); false without RynthAi or before login. + public bool TryGetQuestStatus(out QuestStatusV1 status) + { + status = default; + var t = Table; + if (t == null || t->QuestStatus == null) return false; + QuestStatusV1 s = default; + if (t->QuestStatus(&s) == 0) return false; + status = s; + return true; + } + + /// A quiet /myquests refresh through RynthAi's Quests tab (its cooldown applies). Pump thread. + public string RefreshQuests() + { + var t = Table; + if (t == null || t->QuestRefresh == null) return "The quest tracker " + NotLoaded + "."; + byte* reply = stackalloc byte[256]; + reply[0] = 0; + t->QuestRefresh(reply, 256); + return Marshal.PtrToStringUTF8((IntPtr)reply) ?? string.Empty; + } + + // ── Spells, loot profiles ─────────────────────────────────────────────── + + /// A spell's name from RynthAi's spell table ("" when unknown or no RynthAi). Pump thread. + public string SpellName(int spellId) + { + var t = Table; + if (t == null || t->SpellName == null || spellId <= 0) return string.Empty; + byte* buf = stackalloc byte[160]; + int n = t->SpellName(unchecked((uint)spellId), buf, 160); + return n <= 0 ? string.Empty : Marshal.PtrToStringUTF8((IntPtr)buf) ?? string.Empty; + } + + /// + /// Evaluates a VTank .utl profile on : keep[i] is true when that item's + /// first matching rule is Keep. False (with the reason) when it couldn't. Pump thread. + /// + public bool LootKeeps(string utlPath, uint[] ids, out bool[] keep, out string error) + { + keep = new bool[ids.Length]; + error = string.Empty; + var t = Table; + if (t == null || t->LootKeeps == null) { error = "equipment suits " + NotLoaded; return false; } + byte[] flags = new byte[ids.Length]; + byte* err = stackalloc byte[256]; + err[0] = 0; + int ok; + using (var p = new Utf8(utlPath)) + fixed (uint* pids = ids) + fixed (byte* pf = flags) + ok = t->LootKeeps(p.P, pids, ids.Length, pf, err, 256); + if (ok == 0) { error = Marshal.PtrToStringUTF8((IntPtr)err) ?? "could not read profile"; return false; } + for (int i = 0; i < ids.Length; i++) keep[i] = flags[i] != 0; + return true; + } + + // ── Session stats ─────────────────────────────────────────────────────── + + /// The Mini Remote's session (any thread); false without RynthAi or before login. + public bool TryGetSessionStats(out SessionStatsV1 stats) + { + stats = default; + var t = AnyThreadTable; + if (t == null || t->SessionStats == null) return false; + SessionStatsV1 s = default; + if (t->SessionStats(&s) == 0) return false; + stats = s; + return true; + } + + /// Starts the Mini Remote's session over (any thread). + public void ResetSessionStats() + { + var t = AnyThreadTable; + if (t != null && t->SessionReset != null) t->SessionReset(); + } + + // ── RynthAi's sections drawn in RynthILT's tabs ───────────────────────── + + /// Render thread: draws one of RynthAi's sections; false (nothing drawn) without RynthAi. + public bool RenderSection(string id) + { + var t = AnyThreadTable; + if (t == null || t->RenderSection == null) return false; + using var s = new Utf8(id); + return t->RenderSection(s.P) != 0; + } + + /// A NUL-terminated UTF-8 copy of a string for one call. + private readonly struct Utf8 : IDisposable + { + public readonly byte* P; + + public Utf8(string? s) + { + s ??= string.Empty; + int n = Encoding.UTF8.GetByteCount(s); + P = (byte*)NativeMemory.Alloc((nuint)(n + 1)); + fixed (char* c = s) Encoding.UTF8.GetBytes(c, s.Length, P, n); + P[n] = 0; + } + + public void Dispose() => NativeMemory.Free(P); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/ServerFeatureGate.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/ServerFeatureGate.cs new file mode 100644 index 0000000..3f06a8f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Hub/ServerFeatureGate.cs @@ -0,0 +1,115 @@ +// ServerFeatureGate.cs — Which worlds get the ILT / infinite-attribute features. +// Originally part of SilentKelpie's ILT Hub in RynthAi; moved to RynthILT 2026-10-13. +// +// One gate for everything ILT-shaped: the Mini Remote's ILT tabs, the Guardian, the Skills +// panel's Progression planners and the attribute raiser. A world is "on" when: +// * its name matches one of the server patterns (IltSettings.ServerNames, '*' wildcard, +// case-insensitive; defaults cover InfiniteLeaftide; "/ilt servers" +// edits them — they were RynthAi's Settings > Misc "Server Features" list), or +// * this character's override is on ("Treat this world as ILT", +// "/ra hub force on"; also set by migration from RynthAi's "Force enable" profile flag). +// The gate only decides whether RynthILT ASKS the server; each feature still follows the +// server's own report (IltServerOptions bits), so a shard with /xp off keeps the raiser off. +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RynthCore.Plugin.RynthILT.Hub; + +internal static class ServerFeatureGate +{ + /// Patterns a fresh install starts with (the names the old hard-coded check accepted). + public static readonly string[] DefaultServerNames = { "InfiniteLeaftide", "*Leaftide*" }; + + /// The patterns in force (null settings: the defaults). + public static IReadOnlyList Patterns(IltSettings? settings) + => settings?.ServerNames is { Count: > 0 } list ? list : DefaultServerNames; + + /// True when matches one of . + public static bool NameMatches(string world, IEnumerable? patterns, out string matched) + { + matched = string.Empty; + if (string.IsNullOrWhiteSpace(world) || patterns == null) return false; + foreach (string p in patterns) + { + if (string.IsNullOrWhiteSpace(p)) continue; + if (!Matches(world.Trim(), p.Trim())) continue; + matched = p.Trim(); + return true; + } + return false; + } + + /// Case-insensitive match where '*' stands for any run of characters (anywhere in the pattern). + public static bool Matches(string text, string pattern) + { + if (pattern.Length == 0) return false; + if (!pattern.Contains('*')) return text.Equals(pattern, StringComparison.OrdinalIgnoreCase); + + string[] parts = pattern.Split('*'); + int pos = 0; + for (int i = 0; i < parts.Length; i++) + { + string part = parts[i]; + if (part.Length == 0) continue; + if (i == 0) + { + if (!text.StartsWith(part, StringComparison.OrdinalIgnoreCase)) return false; + pos = part.Length; + continue; + } + if (i == parts.Length - 1) + return text.Length - pos >= part.Length && text.EndsWith(part, StringComparison.OrdinalIgnoreCase); + int at = text.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase); + if (at < 0) return false; + pos = at + part.Length; + } + return true; + } + + /// + /// RynthILT's own gate: the character's override, or the world name in the list. RynthCore's + /// verdict, once it sends one, takes over in IltServerOptions.IsIltLikeWorld; this stays ours + /// (it is what the status export reports, IltServerOptions.IsIltLikeWorldLocal). + /// + public static bool IsEnabled(string world, IltSettings? settings, bool forceOn) + => forceOn || NameMatches(world, Patterns(settings), out _); + + /// "InfiniteLeaftide, *Leaftide*" → trimmed, de-duplicated list (case-insensitive). + public static List ParseList(string? text) + { + var list = new List(); + if (string.IsNullOrWhiteSpace(text)) return list; + foreach (string raw in text.Split(new[] { ',', ';', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)) + { + string p = raw.Trim(); + if (p.Length > 0 && !list.Contains(p, StringComparer.OrdinalIgnoreCase)) list.Add(p); + } + return list; + } + + public static string FormatList(IEnumerable? patterns) + => patterns == null ? string.Empty : string.Join(", ", patterns.Where(p => !string.IsNullOrWhiteSpace(p))); + + /// One status line: the world, whether the features are on, and why. + public static string Describe(string world, IltSettings? settings, bool forceOn) + { + world = (world ?? string.Empty).Trim(); + string shown = world.Length > 0 ? $"'{world}'" : "(not logged in)"; + var engine = IltSettingsView.IltEngineVerdict.Server; + if (engine != null) + { + string why = engine.Force == "on" ? "forced on for this character" + : engine.Force == "off" ? "forced off for this character" + : engine.Detected ? "RynthCore recognises the world" : "RynthCore doesn't recognise the world"; + return $"This world {shown}: {(engine.Active ? "ON" : "OFF")} - {why}."; + } + if (NameMatches(world, Patterns(settings), out string matched)) + return $"This world {shown}: ON - matches '{matched}'."; + if (forceOn) + return $"This world {shown}: ON - \"Treat this world as ILT\" is ticked."; + return world.Length > 0 + ? $"This world {shown}: OFF - not in the list. Add it, or tick \"Treat this world as ILT\"." + : "This world: not logged in yet."; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/HubInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/HubInterface.cs new file mode 100644 index 0000000..d0541e7 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/HubInterface.cs @@ -0,0 +1,280 @@ +// HubInterface.cs - RynthILT's side of the "RynthServer.Hub" interface (Plugins/Shared/RynthServerHubApi.cs), served also +// under its own older name "RynthILT.Hub" (RynthIltHubApi.cs): the table RynthPluginQueryInterface hands RynthAi, and the functions behind it. +// +// The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never +// unloaded, so its functions stay callable): RynthAi's render thread may still hold the pointer +// while plugins shut down, and every function here returns "nothing" once Release() has run +// (Version 0, no plugin). Threads as the interface says: the render-thread functions draw into +// the caller's current ImGui window; the pump-thread Command runs the ILT verb at once. +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT; + +internal static unsafe class HubInterface +{ + private static RynthServerHubApiV1* _table; + private static volatile bool _released; + + /// The live controller, or null (before login, after logout, after shutdown). + private static IltHubController? Hub => _released ? null : PluginExports.Runtime.Plugin?.Hub; + + /// The table for (, ), or 0 when it isn't ours. + public static IntPtr Query(string iface, uint version) + { + // Its own name, and the neutral one RynthAi asks the active server's owner for (the same table). + if ((iface != RynthIltHub.InterfaceName && iface != RynthServerHubApiV1.InterfaceName) + || version < 1 || version > RynthServerHubApiV1.InterfaceVersion || _released) + return IntPtr.Zero; + if (_table == null) + { + var t = (RynthServerHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerHubApiV1)); + t->StructSize = (uint)sizeof(RynthServerHubApiV1); + t->IsServerWorld = &IsIltWorld; + t->GetFeature = &GetFeature; + t->GetRates = &GetRates; + t->GetForceServer = &GetForceIlt; + t->SetForceServer = &SetForceIlt; + t->GetTabs = &GetTabs; + t->RenderTab = &RenderTab; + t->RenderSection = &RenderSection; + t->Command = &Command; + t->AllowSummonOnEmpty = &AllowSummonOnEmpty; + t->GetSubTabs = &GetSubTabs; + t->GetSetting = &GetSetting; + t->SetSetting = &SetSetting; + t->GetText = &GetText; + t->Version = RynthServerHubApiV1.InterfaceVersion; + _table = t; + } + return (IntPtr)_table; + } + + /// Plugin shutdown: callers see Version 0 and re-query; the functions answer "nothing". + public static void Release() + { + _released = true; + if (_table != null) _table->Version = 0; + } + + private static string? Utf8(byte* p) => p == null ? null : Marshal.PtrToStringUTF8((IntPtr)p); + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int IsIltWorld() + { + try { return Hub?.Options.IsIltLikeWorld == true ? 1 : 0; } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetFeature(byte* key) + { + try + { + var hub = Hub; + string? k = Utf8(key); + if (hub == null || string.IsNullOrEmpty(k) || !hub.Options.IsIltLikeWorld) return -1; + return (int)hub.Options.Get(k); + } + catch { return -1; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetRates(double* coinsPerHour, double* pyrealsPerHour) + { + try + { + var hub = Hub; + if (hub == null || !hub.Options.IsIltLikeWorld) return 0; + var r = hub.Rates.Summary; + if (coinsPerHour != null) *coinsPerHour = r.CoinsPerHour; + if (pyrealsPerHour != null) *pyrealsPerHour = r.PyrealsPerHour; + return 1; + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetForceIlt() + { + try { return Hub?.ForceIltWorld == true ? 1 : 0; } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static void SetForceIlt(int on) + { + try + { + var hub = Hub; + if (hub != null) hub.ForceIltWorld = on != 0; + } + catch { } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetTabs(ServerHubTabV1* tabs, int capacity) + { + try + { + var hub = Hub; + if (hub == null) return 0; + var all = IltSections.Tabs; + if (tabs != null) + { + for (int i = 0; i < all.Length && i < capacity; i++) + { + IltSection s = all[i]; + ServerHubTabV1* t = &tabs[i]; + WriteUtf8(IltSections.TabId(s), t->Id, 24); + WriteUtf8(IltSections.Label(s), t->Label, 32); + var size = IltSections.TabSize(s); + t->Width = size.X; + t->Height = size.Y; + uint flags = 0; + if (hub.TabShown(s)) flags |= RynthServerHub.TabShown; + if (hub.SectionAvailable(s)) flags |= RynthServerHub.TabAvailable; + t->Flags = flags; + } + } + return all.Length; + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int RenderTab(byte* id) + { + try + { + var hub = Hub; + if (hub == null || !IltSections.TryParse(Utf8(id) ?? string.Empty, out IltSection s) || !IltSections.IsTab(s)) return 0; + hub.RenderTab(s); + return 1; + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.IltHub, ex, "RenderTab"); + return 0; + } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int RenderSection(byte* id) + { + try + { + var hub = Hub; + string? s = Utf8(id); + return hub != null && s != null && hub.RenderSection(s) ? 1 : 0; + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.IltHub, ex, "RenderSection"); + return 0; + } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Command(byte* text) + { + try + { + var plugin = _released ? null : PluginExports.Runtime.Plugin; + string? line = Utf8(text); + if (plugin == null || string.IsNullOrWhiteSpace(line) || line.Length > 512) return 0; + return plugin.RunForwardedCommand(line) ? 1 : 0; + } + catch { return 0; } + } + + /// The Pets tab's summon-from-empty gate (IltPetAutomation's last tick; 0 off ILT). + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int AllowSummonOnEmpty() + { + try { return Hub?.PetAutomation.AllowSummonOnEmpty == true ? 1 : 0; } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetSubTabs(byte* parent, ServerHubTabV1* tabs, int capacity) + { + try + { + var hub = Hub; + string? p = Utf8(parent); + if (hub == null || p == null) return 0; + var all = hub.SubTabs(p); + if (tabs != null) + { + for (int i = 0; i < all.Length && i < capacity; i++) + { + ServerHubTabV1* t = &tabs[i]; + WriteUtf8(all[i].Id, t->Id, 24); + WriteUtf8(all[i].Label, t->Label, 32); + t->Width = 0; + t->Height = 0; + t->Flags = RynthServerHub.TabShown | RynthServerHub.TabAvailable; + } + } + return all.Length; + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetSetting(byte* key) + { + try + { + var hub = Hub; + string? k = Utf8(key); + return hub == null || k == null ? -1 : hub.GetSetting(k); + } + catch { return -1; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int SetSetting(byte* key, int value) + { + try + { + var hub = Hub; + string? k = Utf8(key); + return hub != null && k != null && hub.SetSetting(k, value) ? 1 : 0; + } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetText(byte* id, byte* buffer, int capacity) + { + try + { + var hub = Hub; + string? k = Utf8(id); + if (hub == null || k == null || buffer == null || capacity <= 0) return 0; + string text = hub.GetText(k); + if (text.Length == 0) { buffer[0] = 0; return 0; } + WriteUtf8(text, buffer, capacity); + int n = 0; + while (n < capacity && buffer[n] != 0) n++; + return n; + } + catch { return 0; } + } + + /// Writes as NUL-terminated UTF-8 into a fixed buffer, truncated to fit. + private static void WriteUtf8(string s, byte* dest, int capacity) + { + byte[] bytes = Encoding.UTF8.GetBytes(s); + int n = Math.Min(bytes.Length, capacity - 1); + for (int i = 0; i < n; i++) dest[i] = bytes[i]; + dest[n] = 0; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipCommands.cs b/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipCommands.cs new file mode 100644 index 0000000..ef919a4 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipCommands.cs @@ -0,0 +1,62 @@ +// IltFellowshipCommands.cs - Infinite Leaftide's fellowship chat commands (ACECustom /fship). +// +// ACECustom (Source/ACE.Server/Command/Handlers/PlayerCommands.cs, "fship") adds these on top +// of retail's fellowship panel; its fellowships hold up to 29 (Fellowship.MaxFellows). The list +// is kept in the shared "servercommands" form (Plugins/Shared/ServerCommandShare.cs) and drawn by +// RynthILT's fellowship window (IltFellowshipUi, "/ilt fellow"). +// A name with spaces is sent quoted; ACE's command parser joins "two words". Pure: no ImGui, no host. +using System; +using System.Collections.Generic; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.IltFellowship; + +internal static class IltFellowshipCommands +{ + /// The RynthCore section the commands belong to. + public const string Section = "fellowship"; + + /// RynthCore's server id for Infinite Leaftide. + public const string ServerId = "ilt"; + + /// The server's display name. + public const string ServerName = "Infinite Leaftide"; + + /// ACECustom's fellowship size (Fellowship.MaxFellows; retail is 9). + public const int MaxFellows = 29; + + /// The /fship commands, in button order. + public static readonly IReadOnlyList Commands = new[] + { + new ServerCommand("Create", "/fship create", "A", + "Create a fellowship with the name in the box (you lead it). Up to " + MaxFellows + " members on ILT."), + new ServerCommand("Invite", "/fship add", "a", + "Invite the player named in the box, or your selected player when the box is empty."), + new ServerCommand("Dismiss", "/fship remove", "ac", + "Leader: remove the player named in the box, or your selected player when the box is empty."), + new ServerCommand("Invite landblock", "/fship landblock", "c", + "Invite every player in your landblock (not in the Marketplace). Over level 50, only level 50+ players are invited."), + new ServerCommand("List nearby", "/fship list", "", + "The fellowships in your area and their leaders (wider in VOD and T10). Once every 10 seconds."), + new ServerCommand("Leave", "/fship leave", "c", + "Leave your fellowship."), + new ServerCommand("Disband", "/fship disband", "c", + "Leader: disband your fellowship."), + new ServerCommand("Help", "/fship", "", + "The server's /fship help."), + }; + + /// The set while ILT is active; with no commands when it isn't (a receiver drops it). + public static ServerCommandSet Set(bool active) => + new(Section, ServerId, ServerName, active ? Commands : Array.Empty()); + + /// The "servercommands" payload for . + public static string Payload(bool active) => ServerCommandShare.Build(Set(active)); + + /// + /// ILT is active: RynthCore's verdict once it has sent one (), + /// else the world name has "Leaftide" in it (RynthCore's default ILT names). + /// + public static bool IsActive(bool? engineActive, string? worldName) => + engineActive ?? (worldName ?? string.Empty).IndexOf("Leaftide", StringComparison.OrdinalIgnoreCase) >= 0; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipUi.cs b/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipUi.cs new file mode 100644 index 0000000..6c009c9 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipUi.cs @@ -0,0 +1,44 @@ +// IltFellowshipUi.cs - The "ILT fellowship" view: Infinite Leaftide's /fship commands as buttons. +// +// Drawn in its own window ("/ilt fellow"). Clicks queue the chat command for the plugin tick. +// Render thread only. +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.IltFellowship; + +internal sealed class IltFellowshipUi +{ + private const string WindowTitle = "ILT fellowship (RynthILT)##rynthilt_fellowship"; + + private static readonly ServerCommandSet Set = IltFellowshipCommands.Set(active: true); + + private readonly ServerCommandPanel _panel = new("iltfship"); + private readonly Func _send; + + /// The standalone window is open ("/ilt fellow"). + public bool WindowOpen; + + /// Queues a chat command for the plugin tick; false when it can't. + public IltFellowshipUi(Func send) => _send = send; + + /// The standalone window, while open. + public void RenderWindow() + { + if (!WindowOpen) return; + ImGui.SetNextWindowSize(new Vector2(420, 170), ImGuiCond.FirstUseEver); + bool open = WindowOpen; + if (ImGui.Begin(WindowTitle, ref open)) RenderBody(); + ImGui.End(); + WindowOpen = open; + } + + /// The view's content, into the current window. + public void RenderBody() + { + SafeImGui.TextDisabled("Infinite Leaftide /fship (up to " + IltFellowshipCommands.MaxFellows + " members)"); + _panel.Render(Set, _send); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSectionsManifest.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSectionsManifest.cs new file mode 100644 index 0000000..1b000e3 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltSectionsManifest.cs @@ -0,0 +1,133 @@ +// IltSectionsManifest.cs - What RynthILT adds to RynthCore's Mini Remote sections (RynthPluginGetSectionsJson, +// schema 1: UI/Sections/SectionManifest.cs in RynthCore). +// +// always (Infinite Leaftide views, shown while RynthCore treats this world as ILT) +// Session Stats ("char") the ILT session extras section:ilt-rates +// Fellowship ILT's /fship commands section:ilt-fellowship +// Quests (RynthILT's own) the /qb list section:ilt-questbonus +// Dynamic Stamps (RynthOracle's section:ilt-dynstamps +// until 2026-10-21) +// while the Hub shows them (an ILT world; each once the server reports its feature) +// Inventory Gear, Charms, Banking section:gear|charms|banking +// Games (RynthILT's own) Games section:games +// Nav Vaulted Dungeons (master switch) section:vaulted +// The Mini Remote tabs were listed by RynthAi, which hosted them, until 2026-10-20; RynthILT lists and +// draws them itself now (RynthPluginRenderEmbed "section:"), so RynthAi's manifest names no +// server's tabs. Their names stay the same, so "/rc miniremote tab charms|banking" finds them. +// Pure: the tabs come in as a list, so the tests build it offline. +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.Json; +using RynthCore.Plugin.RynthILT.Hub; + +namespace RynthCore.Plugin.RynthILT; + +internal static class IltSectionsManifest +{ + /// RynthCore's id for Infinite Leaftide. + public const string Server = "ilt"; + + /// One Mini Remote tab as the Hub has it now. + internal readonly record struct Tab(string Id, float Width, float Height, bool Shown, bool Available); + + private const string NotReportedNote = "Shows once the server reports this ILT feature on (the ILT settings can ask again)."; + + /// Where each tab goes: section, label, order, tooltip. A tab not listed here isn't offered. + internal static readonly Dictionary Placement = new() + { + ["gear"] = ("inventory", "Gear", 210, "ILT gear tools (RynthILT)."), + ["charms"] = ("inventory", "Charms", 220, "ILT charms and Guardian Hands: acquired, status, tier, toggles (RynthILT)."), + ["banking"] = ("inventory", "Banking", 230, "Your ILT bank: balances, deposits, withdrawals and transfers (RynthILT)."), + ["games"] = ("games", "Games", 100, "ILT games (RynthILT)."), + // Listed only while the Hub shows the tab: the master switch is on, on an ILT world. + ["vaulted"] = ("nav", "Vaulted Dungeons", 220, + "Keep the character in one Vaulted Dungeon (RynthILT; master switch: /ilt settings or Settings > Navigation)."), + }; + + /// The surface of a tab's view ("section:gear"). + public static string SurfaceOf(string tabId) => "section:" + tabId; + + /// The tab a "section:<tab>" surface draws, when it names one placed here. + public static bool TryTabOf(string surface, out IltSection section) + { + section = IltSection.Gear; + if (!surface.StartsWith("section:", System.StringComparison.Ordinal)) return false; + string id = surface.Substring("section:".Length); + if (!Placement.ContainsKey(id) || !IltSections.TryParse(id, out section) || !IltSections.IsTab(section)) return false; + return IltSections.TabId(section) == id; + } + + /// The Hub's tabs now (empty without a Hub). Render thread. + public static List TabsOf(IltHubController? hub) + { + var list = new List(); + if (hub == null) return list; + foreach (IltSection s in IltSections.Tabs) + { + var size = IltSections.TabSize(s); + list.Add(new Tab(IltSections.TabId(s), size.X, size.Y, hub.TabShown(s), hub.SectionAvailable(s))); + } + return list; + } + + /// The manifest JSON (UTF-8 text, schema 1). + public static string Build(IReadOnlyList tabs) + { + using var stream = new MemoryStream(4096); + using (var w = new Utf8JsonWriter(stream)) + { + w.WriteStartObject(); + w.WriteNumber("version", 1); + w.WriteStartArray("sections"); + Section(w, "quests", "Quests", 1160); + Section(w, "games", "Games", 1150); + w.WriteEndArray(); + w.WriteStartArray("contributions"); + View(w, "char", "ILT session rates (RynthILT)", RynthILTPlugin.RatesSurface, primary: false, 0, 220, enabled: true, note: "", + "Enlightened Coins, pyreals and item conversions this session, on the same clock as RynthAi's session stats (RynthILT).", 120); + View(w, "fellowship", "ILT fellowship (RynthILT)", RynthILTPlugin.FellowshipSurface, primary: false, 0, 110, enabled: true, note: "", + "Infinite Leaftide's /fship commands: create, invite, dismiss, invite your landblock, list nearby, leave, disband (RynthILT; also /ilt fellow).", 120); + View(w, "quests", "Quest bonus (/qb)", RynthILTPlugin.QuestBonusSurface, primary: true, 520, 440, enabled: true, note: "", + "Infinite Leaftide's quest bonus list: completed and incomplete /qb flags (RynthILT; the quest list, timers and rewards are RynthOracle's, /ro).", 100); + View(w, "quests", "Dynamic Stamps", RynthILTPlugin.DynamicStampsSurface, primary: true, 600, 560, enabled: true, note: "", + "Infinite Leaftide's Dynamic Stamps: the NPC stamps you have and are missing, RynthNav's way there and the Parchment hand-in (RynthILT; also /ilt stamps).", 110); + foreach (Tab t in tabs) + { + if (!t.Shown || !Placement.TryGetValue(t.Id, out var place)) continue; + View(w, place.Section, place.Label, SurfaceOf(t.Id), primary: true, t.Width, t.Height, t.Available, + t.Available ? string.Empty : NotReportedNote, place.Tooltip, place.Order); + } + w.WriteEndArray(); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(stream.ToArray()); + } + + private static void Section(Utf8JsonWriter w, string id, string label, int order) + { + w.WriteStartObject(); + w.WriteString("id", id); + w.WriteString("label", label); + w.WriteNumber("order", order); + w.WriteEndObject(); + } + + private static void View(Utf8JsonWriter w, string section, string label, string surface, bool primary, float width, float height, + bool enabled, string note, string tooltip, int order) + { + w.WriteStartObject(); + w.WriteString("section", section); + w.WriteString("server", Server); + w.WriteString("label", label); + w.WriteString("surface", surface); + w.WriteBoolean("primary", primary); + if (width > 0) w.WriteNumber("width", width); + if (height > 0) w.WriteNumber("height", height); + w.WriteBoolean("enabled", enabled); + if (note.Length > 0) w.WriteString("note", note); + if (tooltip.Length > 0) w.WriteString("tooltip", tooltip); + w.WriteNumber("order", order); + w.WriteEndObject(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltEngineVerdict.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltEngineVerdict.cs new file mode 100644 index 0000000..f14c026 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltEngineVerdict.cs @@ -0,0 +1,32 @@ +// IltEngineVerdict.cs - RynthCore's Infinite Leaftide verdict as RynthILT last heard it. +// +// RynthCore decides whether this world is ILT once, for itself and every plugin, with this +// character's Auto / On / Off override ("/rc server ilt"). RynthILT reads that verdict from the +// engine's server list (plugin API v86, GetServerStateJson; the plugin tick polls it into +// IltSettingsModel.Engine). The Hub's world check (IltServerOptions, ServerFeatureGate) follows it +// once one has arrived; before that, or on an engine older than v86, RynthILT's own server list +// and "Treat this world as ILT" decide. +// +// RynthILT's status export must keep reporting its own verdict, not this one: the engine adds +// RynthILT's verdict to its detection, and an echo would keep ILT on after "/rc ilt auto". +// Any thread: one volatile reference read. +using System.Threading; + +namespace RynthCore.Plugin.RynthILT.IltSettingsView; + +internal static class IltEngineVerdict +{ + private static IltSettingsModel? _model; + + /// The model the plugin feeds from RynthCore's server list (RynthILTPlugin's constructor). + public static void Attach(IltSettingsModel? model) => Volatile.Write(ref _model, model); + + /// RynthCore has sent its server list at least once since login (it may list no ILT). + public static bool Pushed => Volatile.Read(ref _model)?.Engine != null; + + /// RynthCore's ILT entry; null until a RynthCore with the server list (v86) has sent one. + public static IltServerView? Server => Volatile.Read(ref _model)?.Engine?.Server; + + /// RynthCore's verdict for this world; null when it hasn't given one. + public static bool? Active => Server?.Active; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsModel.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsModel.cs new file mode 100644 index 0000000..97f7bd1 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsModel.cs @@ -0,0 +1,114 @@ +// IltSettingsModel.cs - RynthILT's copy of the Infinite Leaftide settings (the "ILT settings" view). +// +// Nothing here is decided by RynthILT; it shows and edits what others own: +// * RynthCore owns the world verdict, this character's Auto / On / Off override and the ILT +// world-name list. RynthILT reads the verdict from its server list (plugin API v86, +// GetServerStateJson, parsed by Plugins/Shared/EngineServerState.cs): the plugin tick polls +// it every 2 s and publishes the "ilt" entry here (ApplyServerState). The world names aren't +// in that list; "/rc server names ilt" prints them. Edits go back as RynthCore commands: +// "/rc server ilt auto|on|off" and "/rc server names ilt add|remove ". +// * RynthILT's own Hub reads which ILT features the server has on; the plugin tick publishes +// them (PublishFeatures). +// Each is one immutable snapshot published with a single reference write, so the render thread +// always reads a whole one. Pure (no host calls): RynthILT.Tests covers it. +using System; +using System.Collections.Generic; +using System.Threading; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.IltSettingsView; + +/// RynthCore's verdict for Infinite Leaftide. +internal sealed record IltServerView(string Name, bool Active, string Force, bool Detected, string Reason); + +/// What RynthCore's server list says: the ILT verdict (null if it lists no "ilt"). +internal sealed record IltEngineView(IltServerView? Server); + +/// The Hub's server read: the world, its last check, and each feature (-1 unknown, 0 off, 1 on). +internal sealed record IltFeatureView(string World, string Source, string LastCheck, bool Checking, bool IltLike, + KeyValuePair[] Features); + +internal sealed class IltSettingsModel +{ + /// RynthCore's id for Infinite Leaftide. + public const string ServerId = Hub.IltServerOptions.EngineServerId; + + /// Longest pattern RynthCore keeps (EngineSettings.MaxIltServerNameLength). + public const int MaxPattern = 64; + + /// The RynthCore command that prints the ILT world names (and hosts) in chat. + public const string NamesListCommand = "/rc server names " + ServerId; + + private IltEngineView? _engine; + private IltFeatureView? _features; + + /// The last server list from RynthCore (null until one arrives). Any thread. + public IltEngineView? Engine => Volatile.Read(ref _engine); + + /// The last feature read (null until the Hub publishes one). Any thread. + public IltFeatureView? Features => Volatile.Read(ref _features); + + /// RynthCore's server list (GetServerStateJson); null (no answer) keeps the last one. Any thread. + public void ApplyServerState(EngineServerState? state) + { + IltEngineView? view = FromServerState(state); + if (view != null) Volatile.Write(ref _engine, view); + } + + /// The Hub's own feature read (plugin tick); null clears it. Any thread. + public void PublishFeatures(IltFeatureView? view) => Volatile.Write(ref _features, view); + + /// Logout: the next character's world and features come fresh. + public void Clear() + { + Volatile.Write(ref _engine, null); + Volatile.Write(ref _features, null); + } + + /// The ILT verdict from RynthCore's server list; null for no list. + public static IltEngineView? FromServerState(EngineServerState? state) + { + if (state == null) return null; + EngineServer? s = state.Find(ServerId); + return new IltEngineView(s == null ? null + : new IltServerView(s.Name.Length > 0 ? s.Name : "Infinite Leaftide", s.Active, NormalizeForce(s.Force), s.Detected, s.Reason)); + } + + /// "auto", "on" or "off" (anything else is shown as auto). + public static string NormalizeForce(string? force) => (force ?? string.Empty).Trim().ToLowerInvariant() switch + { + "on" => "on", + "off" => "off", + _ => "auto", + }; + + /// The RynthCore command that sets this character's override; "" for an unknown mode. + public static string ForceCommand(string mode) => mode switch + { + "auto" or "on" or "off" => "/rc server " + ServerId + " " + mode, + _ => string.Empty, + }; + + /// + /// The RynthCore command that adds or removes a world-name pattern, or "" (with + /// ) when the pattern can't be sent: empty, longer than + /// , or with a control character or '/' (it is spliced into a command). + /// + public static string NamesCommand(bool add, string? pattern, out string error) + { + error = string.Empty; + string p = (pattern ?? string.Empty).Trim(); + if (p.Length == 0) { error = "Enter a world name ('*' matches any text)."; return string.Empty; } + if (p.Length > MaxPattern) { error = $"At most {MaxPattern} characters."; return string.Empty; } + foreach (char c in p) + if (char.IsControl(c) || c == '/' || c >= 128) + { + error = "World names are plain text (no '/', line breaks or special characters)."; + return string.Empty; + } + return "/rc server names " + ServerId + (add ? " add " : " remove ") + p; + } + + /// A feature's state as text. + public static string StateText(int value) => value switch { 1 => "on", 0 => "off", _ => "unknown" }; +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs new file mode 100644 index 0000000..187cc48 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs @@ -0,0 +1,237 @@ +// IltSettingsUi.cs - The "ILT settings" view: RynthILT's copy of the Infinite Leaftide settings. +// +// Drawn in its own window ("/ilt settings"). Shows RynthCore's verdict and reason, this character's +// Auto / On / Off override, the ILT world names (edited through RynthCore), this character's ILT +// options (the settings that moved here from RynthAi on 2026-10-20: the Empyrean Handler ring +// evade, ...; saved in the Hub's state), and every ILT feature with the state RynthILT's Hub read +// from the server (IltSettingsModel has where each comes from). +// Edits are RynthCore commands, queued for the plugin tick; the next server-list poll shows the +// result. Render thread only. +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.IltSettingsView; + +internal sealed class IltSettingsUi +{ + private static readonly Vector4 Teal = new(0.30f, 0.85f, 0.80f, 1f); + private static readonly Vector4 Mute = new(0.60f, 0.62f, 0.66f, 1f); + private static readonly Vector4 Warn = new(0.95f, 0.55f, 0.45f, 1f); + + private const string WindowTitle = "ILT settings (RynthILT)##rynthilt_settings"; + + private readonly IltSettingsModel _model; + private readonly Action _runCommand; + private readonly Func _refreshFeatures; + private readonly Func _hub; + private string _newName = string.Empty; + private string _status = string.Empty; + + /// The standalone window is open ("/ilt settings"). + public bool WindowOpen; + + /// Queues a RynthCore command (run on the plugin tick). + /// Asks the Hub to read the server's features again; false before it exists. + /// This character's Hub (its options live in the Hub's state); null before login. + public IltSettingsUi(IltSettingsModel model, Action runCommand, Func refreshFeatures, Func? hub = null) + { + _model = model; + _runCommand = runCommand; + _refreshFeatures = refreshFeatures; + _hub = hub ?? (() => null); + } + + /// The standalone window, while open. + public void RenderWindow() + { + if (!WindowOpen) return; + ImGui.SetNextWindowSize(new Vector2(440, 480), ImGuiCond.FirstUseEver); + bool open = WindowOpen; + if (ImGui.Begin(WindowTitle, ref open)) RenderBody(); + ImGui.End(); + WindowOpen = open; + } + + /// The view's content, into the current window. + public void RenderBody() + { + RenderVerdict(); + ImGui.Separator(); + RenderCharacterOptions(); + ImGui.Separator(); + RenderFeatures(); + if (_status.Length > 0) + { + ImGui.Separator(); + SafeImGui.TextWrapped(_status); + } + } + + private void RenderVerdict() + { + IltEngineView? engine = _model.Engine; + if (engine == null) + { + ImGui.TextWrapped("Waiting for RynthCore's server list (it needs plugin API v86). Until then RynthILT's own " + + "world list and this character's 'Treat this world as ILT' (/ra hub force on|off) decide."); + return; + } + + IltServerView? s = engine.Server; + if (s == null) + { + ImGui.TextDisabled("RynthCore doesn't list Infinite Leaftide."); + } + else + { + SafeImGui.TextColored(s.Active ? Teal : Mute, s.Active ? s.Name + ": on for this world" : s.Name + ": not this world"); + if (s.Reason.Length > 0) + { + ImGui.PushStyleColor(ImGuiCol.Text, Mute); + SafeImGui.TextWrapped(s.Reason); + ImGui.PopStyleColor(); + } + + // Read only: a server is forced in one place, RynthCore Options > Diagnostics (2026-10-13). + string force = s.Force switch { "on" => "forced on", "off" => "forced off", _ => "auto (detected)" }; + SafeImGui.TextDisabled("This character: " + force + " (change it in RynthCore Options > Diagnostics)"); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("RynthCore's server selection (Options > Diagnostics) forces a server for this character,\nor /rc server ilt auto|on|off in chat."); + } + + ImGui.Spacing(); + ImGui.TextUnformatted("ILT world names"); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Worlds whose name matches one of these count as Infinite Leaftide ('*' matches any text).\nThe launch host is checked too. Kept by RynthCore for every character."); + ImGui.SameLine(); + if (ImGui.SmallButton("List in chat##iltnames")) + { + _runCommand(IltSettingsModel.NamesListCommand); + _status = "RynthCore lists the names in chat (" + IltSettingsModel.NamesListCommand + ")."; + } + ImGui.SetNextItemWidth(220); + bool enter = ImGui.InputTextWithHint("##iltnewname", "world name, * = any text", ref _newName, (uint)IltSettingsModel.MaxPattern, + ImGuiInputTextFlags.EnterReturnsTrue); + ImGui.SameLine(); + if (ImGui.Button("Add##iltname") || enter) + { + string cmd = IltSettingsModel.NamesCommand(true, _newName, out string err); + if (Send(cmd, err, "Adding '" + _newName.Trim() + "'...")) _newName = string.Empty; + } + ImGui.SameLine(); + if (ImGui.Button("Remove##iltname")) + { + string cmd = IltSettingsModel.NamesCommand(false, _newName, out string err); + if (Send(cmd, err, "Removing '" + _newName.Trim() + "'...")) _newName = string.Empty; + } + } + + /// + /// This character's Infinite Leaftide options: the ones that were RynthAi settings until + /// 2026-10-20 (copied over once). Saved with the Hub's state. + /// + private void RenderCharacterOptions() + { + ImGui.TextUnformatted("This character"); + IltHubController? hub = _hub(); + if (hub == null) + { + ImGui.TextDisabled("Shown once this character is logged in."); + return; + } + IltHubState st = hub.State; + bool vaulted = st.VaultedDungeonsEnabled; + if (ImGui.Checkbox("Vaulted Dungeons (the keeper's master switch)##iltvaulted", ref vaulted)) st.VaultedDungeonsEnabled = vaulted; + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Off by default. While off the Vaulted Dungeons keeper does nothing: no recalls, no /rc quit, no Mini\n" + + "Remote tab. On: the \"Vaulted Dungeons\" tab shows, where you pick a dungeon and a tied Portal Recall\n" + + "Gem and start it (/ilt vaulted on). Also in RynthCore's Settings > Navigation (it was a RynthAi setting)."); + bool ring = st.Combat.HandlerRingEvade; + if (ImGui.Checkbox("Evade the Empyrean Handler's lethal ring##iltring", ref ring)) st.Combat.HandlerRingEvade = ring; + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("When an Empyrean Handler channels its lethal ring and you are within 12 yards (or RynthAi's\n" + + "Ring Range if larger), RynthAi back-jumps away and re-engages. Only while RynthAi's macro\n" + + "is running with combat on. On by default (it was RynthAi's \"Evade Handler Ring\")."); + int augs = st.T11.ItemAugsOverride; + SafeImGui.TextDisabled(augs >= 0 + ? $"T11 item augmentations: fixed at {augs:N0} for RynthAi's loot rules (/ilt t11 augs auto to read /aug)" + : "T11 item augmentations: read from /aug (/ilt t11 augs fixes them; /ilt t11 shows the counters)"); + } + + /// + /// The server's ILT features, one collapsible section per group (Character, Items, Pets, + /// Fellowship, Combat, Activities, then the charms and any other bit chat or a probe set), with + /// how many are on and each feature's state; the tooltip says where the Rynth tools handle it. + /// + private void RenderFeatures() + { + IltFeatureView? f = _model.Features; + ImGui.TextUnformatted("Server features"); + ImGui.SameLine(); + if (ImGui.SmallButton("Refresh##iltfeatures")) + _status = _refreshFeatures() ? "Checking the server again..." : "Not ready yet (log in first)."; + if (f == null) + { + ImGui.TextWrapped("RynthILT reads which ILT features the server has on once this character is logged in. Not read yet."); + return; + } + + string when = f.Checking ? "checking the server..." : f.LastCheck.Length == 0 ? "not checked yet" : "checked " + f.LastCheck; + SafeImGui.TextDisabled((f.World.Length > 0 ? f.World : "unknown world") + " - " + when + + (f.Source.Length > 0 ? " (" + f.Source + ")" : string.Empty)); + if (!f.IltLike) ImGui.TextDisabled("This world isn't treated as Infinite Leaftide, so the server isn't asked."); + if (f.Features.Length == 0) + { + ImGui.TextDisabled("The server hasn't reported any ILT features yet."); + return; + } + + var groups = new Dictionary>(StringComparer.Ordinal); + foreach (var kv in f.Features) + { + var (label, group, tooltip) = IltFeatureCatalog.Describe(kv.Key); + if (!groups.TryGetValue(group, out var rows)) groups[group] = rows = new(); + rows.Add((label, tooltip, kv.Value)); + } + foreach (string group in FeatureGroups()) + { + if (!groups.TryGetValue(group, out var rows)) continue; + int on = 0, off = 0; + foreach (var r in rows) { if (r.State == 1) on++; else if (r.State == 0) off++; } + if (!ImGui.CollapsingHeader($"{group} ({on} of {rows.Count} on)##iltfg_{group}")) continue; + for (int i = 0; i < rows.Count; i++) + { + var r = rows[i]; + SafeImGui.TextColored(r.State == 1 ? Teal : r.State == 0 ? Warn : Mute, IltSettingsModel.StateText(r.State)); + ImGui.SameLine(80); + SafeImGui.Text(r.Label); + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(r.Tooltip); + } + } + } + + /// The feature sections in display order: the catalog's groups, then Charms and Other. + private static IEnumerable FeatureGroups() + { + foreach (string g in IltFeatureCatalog.Groups) yield return g; + yield return IltFeatureCatalog.GroupCharms; + yield return IltFeatureCatalog.GroupOther; + } + + /// Queues , or shows when it is empty. + private bool Send(string command, string error, string pending) + { + if (command.Length == 0) + { + _status = error; + return false; + } + _runCommand(command); + _status = pending; + return true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs new file mode 100644 index 0000000..1df4102 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs @@ -0,0 +1,312 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthILT; + +public static unsafe class PluginExports +{ + internal static readonly RynthPluginRuntime Runtime = new(); + + // Typed interfaces (host GetPluginInterface, API v68): "RynthILT.Hub" v1, the ILT tabs and + // sections RynthAi's Mini Remote hosts (Plugins/Shared/RynthServerHubApi.cs, HubInterface.cs), and + // "RynthServer.Profile" v1, ILT's settings and tinkering salvage for any reader, as every server + // plugin serves its own (Plugins/Shared/RynthServerProfileApi.cs, ProfileInterface.cs), and + // "RynthILT.Data" v1..v3, the charms list and bank balances with their actions, the pet breeding + // tracker and the Temple guardians (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs), and + // "RynthILT.Server" v1, the Leaftide feature / fellowship / quest bonus profile RynthOracle reads + // (Plugins/Shared/RynthIltServerApi.cs, ServerInterface.cs). + // Fixed signature: void* (const char* iface, uint version). + [UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })] + private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version) + { + try + { + string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? ""; + IntPtr table = HubInterface.Query(iface, version); + if (table != IntPtr.Zero) return table; + table = ServerInterface.Query(iface, version); + if (table != IntPtr.Zero) return table; + table = ProfileInterface.Query(iface, version); + return table != IntPtr.Zero ? table : DataInterface.Query(iface, version); + } + catch + { + return IntPtr.Zero; + } + } + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Shutdown() + { + // An exception escaping an UnmanagedCallersOnly export fail-fasts the client under NativeAOT. + try { Runtime.Shutdown(); } catch { } + try { HubInterface.Release(); } catch { } + try { ServerInterface.Release(); } catch { } + try { ProfileInterface.Release(); } catch { } + try { DataInterface.Release(); } catch { } + foreach (IntPtr p in new[] { Interlocked.Exchange(ref _bountiesPtr, IntPtr.Zero), Interlocked.Exchange(ref _progressionPtr, IntPtr.Zero), + Interlocked.Exchange(ref _statusPtr, IntPtr.Zero), Interlocked.Exchange(ref _sectionsPtr, IntPtr.Zero) }) + if (p != IntPtr.Zero) Marshal.FreeCoTaskMem(p); + _sectionsJson = null; + } + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetName() => RynthILTPlugin.NamePointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetVersion() => RynthILTPlugin.VersionPointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Tick() => Runtime.OnTick(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnLoginComplete() => Runtime.OnLoginComplete(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnLogout() => Runtime.OnLogout(); + + // Bounty lines (and eating the reply to the tracker's own /bounty list). + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) + => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); + + // The ILT Hub's floating windows (Games HUD, confirmations) in the engine's ImGui frame. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Render() => Runtime.OnRender(); + + /// The engine calls this instead of RynthPluginRender while its ImGui shell is off. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderOverlay", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void RenderOverlay() + { + try { Runtime.Plugin?.OnRenderOverlay(); } + catch { /* an exception crossing UnmanagedCallersOnly would fail-fast the client */ } + } + + /// + /// Engine panels drawn by RynthILT (render thread): "guardian" is the engine's Guardian ILT + /// panel (RynthCore's GuardianFace); "section:ilt-rates" (the ILT session extras, Session Stats), + /// "section:ilt-fellowship" (the /fship commands), "section:ilt-questbonus" (the /qb list, + /// RynthILT's Quests section) and "section:ilt-settings" (the ILT settings, for an engine that + /// still asks) are RynthCore's Mini Remote sections. ":popout" is added when one is popped out + /// into a window of its own, and RynthILT draws in the engine's current context either way. The + /// Guardian panel is user-sized (want echoes the size given); a section reports the height it + /// used. "section:gear|charms|banking|games|vaulted" are the Mini Remote ILT tabs as RynthCore's + /// section views (RynthILT lists them since 2026-10-20; RynthAi did before), sized to the tab. + /// 1 = drawn, 0 = not ready / unknown surface. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })] + public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight) + { + try + { + if (surface == null) return 0; + ReadOnlySpan name = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(surface); + if (name.EndsWith(":popout"u8)) name = name[..^":popout"u8.Length]; + var plugin = Runtime.Plugin; + if (plugin == null) return 0; + if (name.SequenceEqual("guardian"u8)) + { + if (!plugin.RenderEmbeddedGuardian()) return 0; + if (wantWidth != null) *wantWidth = width; + if (wantHeight != null) *wantHeight = height; + return 1; + } + string? view = name.SequenceEqual("section:ilt-settings"u8) ? RynthILTPlugin.SettingsSurface + : name.SequenceEqual("section:ilt-fellowship"u8) ? RynthILTPlugin.FellowshipSurface + : name.SequenceEqual("section:ilt-rates"u8) ? RynthILTPlugin.RatesSurface + : name.SequenceEqual("section:ilt-questbonus"u8) ? RynthILTPlugin.QuestBonusSurface + : null; + if (view == null) + { + // "section:gear", "section:banking", ...: the Mini Remote ILT tabs RynthILT lists (IltSectionsManifest). + if (name.Length > 64 || !name.StartsWith("section:"u8)) return 0; + if (!plugin.RenderEmbeddedTab(System.Text.Encoding.UTF8.GetString(name), out float tabW, out float tabH)) return 0; + if (wantWidth != null) *wantWidth = tabW > 0 ? tabW : width; + if (wantHeight != null) *wantHeight = tabH > 0 ? tabH : height; + return 1; + } + if (!plugin.RenderEmbedded(view, out float wantH)) return 0; + if (wantWidth != null) *wantWidth = width; + if (wantHeight != null) *wantHeight = wantH; + return 1; + } + catch + { + return 0; // an exception crossing UnmanagedCallersOnly would fail-fast the client + } + } + + // "/ilt ..." commands, and noticing a /bounty the player typed (its reply is never eaten). + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) + => Runtime.OnChatBarEnter(textUtf16, eatFlag); + + // Creatures' health from the server (siphon auto-capture's fallback health read, IltPetAutomation). + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) + => Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth); + + // This character's kills re-read the bounty list (while the Bounties window is open). + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnKillNotification", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnKillNotification(IntPtr textUtf16) => Runtime.OnKillNotification(textUtf16); + + // ── Bounties bridge (the engine's ImGui Bounties window, UI/Data/BountiesData.cs) ────── + // UTF-8 both ways. Polling the getter is what keeps the tracker's reads running, so only + // the engine's Bounties source may call it (on the plugin pump, 1 s, on ILT only). + // Alloc-new → swap → free-old: the previous reply stays valid until the next call. + + private static IntPtr _bountiesPtr = IntPtr.Zero; + + /// The tracked bounties as JSON (BountyBridgePayload); 0 before login. + [UnmanagedCallersOnly(EntryPoint = "RynthILTGetBountiesJson", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetBountiesJson() + { + try + { + string? json = Runtime.Plugin?.Bounties?.BuildJson(); + return json == null ? IntPtr.Zero : Utf8Swap(ref _bountiesPtr, json); + } + catch { return IntPtr.Zero; } + } + + /// "refresh" or "set {option} {value}" (BountyTracker.Command). + [UnmanagedCallersOnly(EntryPoint = "RynthILTBountyCommand", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void BountyCommand(IntPtr utf8Text) + { + try + { + if (utf8Text == IntPtr.Zero) return; + string? text = Marshal.PtrToStringUTF8(utf8Text); + if (string.IsNullOrEmpty(text) || text.Length > 256) return; + Runtime.Plugin?.Bounties?.Command(text); + } + catch { } + } + + // ── The ILT Hub for the engine (the Skills panel's Progression tab, IltInfo) ───────── + + private static IntPtr _progressionPtr = IntPtr.Zero; + + /// + /// The Skills panel's Progression tab (ILT augmentations / enlightenment / the attribute raiser), + /// as RynthAi's RynthPluginGetProgressionJson was: {"available":false} until the Hub exists and + /// off ILT. UTF-8; the previous reply stays valid until the next call. Engine pump thread only. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthILTGetProgressionJson", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetProgressionJson() + { + try + { + string json = Runtime.Plugin?.Hub?.BuildProgressionJson() ?? "{\"available\":false}"; + return Utf8Swap(ref _progressionPtr, json); + } + catch { return IntPtr.Zero; } + } + + /// + /// One command from the engine (UTF-8): "prog ..." (the Progression tab's edits) or an ILT + /// "/ra" verb without "/ra" ("hub refresh", "guardian handin"). Engine pump thread. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthILTCommand", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Command(IntPtr utf8Text) + { + try + { + if (utf8Text == IntPtr.Zero) return; + string? text = Marshal.PtrToStringUTF8(utf8Text); + if (string.IsNullOrWhiteSpace(text) || text.Length > 512) return; + Runtime.Plugin?.RunEngineCommand(text); + } + catch { } + } + + /// + /// (action, value) from the engine's plugin-command broker (Host.SendPluginCommand): "prog" with + /// the Progression tab's arguments (RynthAi forwards an older engine's "prog" here), or an ILT + /// verb. Copied and run on RynthILT's next tick. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi) + { + try + { + string action = actionAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(actionAnsi) ?? string.Empty) : string.Empty; + if (action.Length == 0 || action.Length > 32) return; + var plugin = Runtime.Plugin; + if (plugin == null) return; + if (RynthILTPlugin.IsParsedRemoteAction(action)) + { + // RynthCore's "servermenu" push (a few KB): answered here, never queued as an ILT verb. + plugin.ApplyRemoteCommand(action, valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty); + return; + } + string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty; + if (action.Length + value.Length > 512) return; + plugin.EnqueueRemoteCommand(action, value); + } + catch { /* never let a managed exception cross the native boundary */ } + } + + private static IntPtr _statusPtr = IntPtr.Zero; + + /// + /// What RynthILT knows about the world (UTF-8 JSON, previous reply valid until the next call): + /// {"loaded":true,"ilt":bool,"forced":bool,"available":bool,"world":"..."}. "ilt" is RynthILT's + /// own verdict (its server list or this character's "Treat this world as ILT"), never the + /// engine's verdict echoed back: the engine's IltInfo adds it to its own detection, and an + /// echo would keep ILT on after "/rc ilt auto". Engine pump thread. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthILTGetStatusJson", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetStatusJson() + { + try + { + var hub = Runtime.Plugin?.Hub; + string json = hub == null + ? "{\"loaded\":true,\"ilt\":false,\"forced\":false,\"available\":false,\"world\":\"\"}" + : "{\"loaded\":true,\"ilt\":" + (hub.Options.IsIltLikeWorldLocal ? "true" : "false") + + ",\"forced\":" + (hub.ForceIltWorld ? "true" : "false") + + ",\"available\":" + (hub.Available ? "true" : "false") + + ",\"world\":\"" + RynthCore.Plugin.RynthILT.Hub.IltStyle.JsonEscape(hub.Options.WorldName) + "\"}"; + return Utf8Swap(ref _statusPtr, json); + } + catch { return IntPtr.Zero; } + } + + private static IntPtr _sectionsPtr = IntPtr.Zero; + private static string? _sectionsJson; + + /// + /// RynthCore 2026.10.5.46+ (optional): what RynthILT adds to the Mini Remote's sections (UTF-8 + /// JSON, schema 1; RynthILTPlugin.BuildSectionsJson). Null before login. An unchanged manifest + /// keeps the same buffer. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetSectionsJson() + { + try + { + string? json = Runtime.Plugin?.BuildSectionsJson(); + if (json == null) return IntPtr.Zero; + if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr; + _sectionsJson = json; + return Utf8Swap(ref _sectionsPtr, json); + } + catch { return IntPtr.Zero; } + } + + private static IntPtr Utf8Swap(ref IntPtr slot, string json) + { + IntPtr newPtr = Marshal.StringToCoTaskMemUTF8(json); + IntPtr oldPtr = Interlocked.Exchange(ref slot, newPtr); + if (oldPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(oldPtr); + return newPtr; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs new file mode 100644 index 0000000..6398efd --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs @@ -0,0 +1,105 @@ +// ProfileInterface.cs - RynthILT's side of "RynthServer.Profile" (Plugins/Shared/RynthServerProfileApi.cs): +// Infinite Leaftide's settings as JSON for other plugins, the same interface and JSON writer the +// server plugins use (Plugins/Shared/ServerPack/ServerPackProfile.cs). RynthCore's GetServerStateJson +// names RynthILT as the owner of "ilt"; a reader (RynthAi's Crafting tab, ...) then asks it for this. +// The profile carries ILT's tinkering salvage (Hub/IltSalvage.cs). +// +// As ServerPackInterface: the table is allocated once per loaded copy of RynthILT and never freed; +// after Release() it reports Version 0 and GetProfileJson answers 0. Before the Hub is up the profile +// still describes the server (active false, no world). +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.ServerPack; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT; + +internal static unsafe class ProfileInterface +{ + private static RynthServerProfileApiV1* _table; + private static volatile bool _released; + + /// What RynthILT knows about its server (identity from the csproj's manifest properties). + internal static readonly ServerPackInfo Info = + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Emulator = "ACE", + Salvage = IltSalvage.Rows, + // Leaftide trinkets (UB-IT's IsLeaftideTrinketJewelry): the Crafting tab's Trinkets bench, not Jewelry. + TrinketNames = IltSalvage.TrinketNames, + TrinketExcept = IltSalvage.TrinketExcept, + Source = "RynthILT; salvage from UB-IT's LeaftideImbueHelper (via SilentKelpie)", + }; + + /// The last JSON handed out, and what it was built for (rebuilt only when that changes). + private sealed record Snapshot(bool Active, string World, string Json); + private static Snapshot? _last; + + /// The table for (, ), or 0 when it isn't ours. + public static IntPtr Query(string iface, uint version) + { + if (iface != RynthServerProfileApiV1.InterfaceName || version < 1 || version > RynthServerProfileApiV1.InterfaceVersion || _released) + return IntPtr.Zero; + if (_table == null) + { + var t = (RynthServerProfileApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerProfileApiV1)); + t->StructSize = (uint)sizeof(RynthServerProfileApiV1); + t->GetProfileJson = &GetProfileJson; + t->Version = RynthServerProfileApiV1.InterfaceVersion; + _table = t; + } + return (IntPtr)_table; + } + + /// Plugin shutdown: readers see Version 0 and re-query; GetProfileJson answers 0. + public static void Release() + { + _released = true; + if (_table != null) _table->Version = 0; + } + + /// + /// The JSON to hand out for RynthILT's verdict () and the world name. + /// Any thread. + /// + internal static string CurrentJson(bool active, string? world) + { + world ??= string.Empty; + Snapshot? last = Volatile.Read(ref _last); + if (last != null && last.Active == active && last.World == world) return last.Json; + string json = ServerPackProfile.BuildJson(Info, RynthPluginInfo.Name, RynthPluginInfo.Version, active, world); + Volatile.Write(ref _last, new Snapshot(active, world, json)); + return json; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetProfileJson(byte* buffer, int capacity) + { + try + { + if (_released) return 0; + IltHubController? hub = PluginExports.Runtime.Plugin?.Hub; + string json = CurrentJson(hub?.Options.IsIltLikeWorld == true, hub?.Options.WorldName); + return Write(json, buffer, capacity); + } + catch { return 0; } + } + + /// + /// Copies as NUL-terminated UTF-8 into the caller's buffer when it fits, + /// and returns its byte length either way (length >= capacity: too small, nothing written). + /// + internal static int Write(string json, byte* buffer, int capacity) + { + int length = Encoding.UTF8.GetByteCount(json); + if (buffer == null || capacity <= length) return length; + fixed (char* src = json) + Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity); + buffer[length] = 0; + return length; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Resources/dynstamps.csv b/Plugins/RynthCore.Plugin.RynthILT/Resources/dynstamps.csv new file mode 100644 index 0000000..6691ea9 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/Resources/dynstamps.csv @@ -0,0 +1,244 @@ +Area,Place,Npc,Reward,Stamp,Note +"Facility Hub","Folthid Cellar","Raxanza Folthid","O-Yoroi Leggings","Dynamic_1_Aq2hMsFmW!","" +"Facility Hub","Folthid Cellar","Felscuda","Healing Rabbit Pie","Dynamic_1_&9jiyTB!","8.8S, 53.1E" +"Facility Hub","Folthid Cellar","Mi Krau-Li","examines your Parchment","Dynamic_1_WAuFukcRLoL5!","" +"Looking Around","","Le-Ai Rea","Blue Molly","Dynamic_1_XH!!nh#^NaRp!","75.9S 57.3E" +"Looking Around","Frost Haven","Robert","Greater Celdon Shadow Sleeves","Dynamic_1_HLq&!","" +"Looking Around","Frost Haven","Elijah","Homemade Stout","Dynamic_1_MpBeVDU!","" +"Looking Around","Frost Haven","Emma","Frost Slingshot","Dynamic_1_bEt6H5ECwGb2!","" +"Looking Around","Frost Haven","Chef Pleist","Stone Mace","Dynamic_1_HgaUKA#hxa!","" +"Looking Around","Frost Haven","The Mayor","Fried Egg","Dynamic_1_MRfxp5!g!","" +"Looking Around","Frost Haven","Numb","Perfect Coruscating Isparian Mace","Dynamic_1_z8LpGZpe4rq!","" +"Looking Around","Land Bridge Staging Complex","Director's Majordomo","Spitter Trochanter Metamorphi","Dynamic_1_FZYLYrAW1Zb!","" +"Looking Around","Frost Haven","Mossy Chamber","Broken Virindi","Dynamic_1_ANND","" +"Looking Around","Freebooter","Jusad the Collector","Renegade Atlatl of the Mountains","Dynamic_1_!mqkm9M!","" +"Looking Around","Lum Seer","Shade of Lady Adja","Frost Board with Nail","Dynamic_1_ps6iG^P!ndH!","" +"Looking Around","Frost Haven","Ka'hiri","Hearty Spiced Applesauce","Dynamic_1_s5MAzDcP9!","" +"Looking Around","Frost Haven","Liam of Gelid","Composite Crossbow with Handle","Dynamic_1_7cv3O^MTLLKzs&!","" +"Looking Around","84.1N, 44.1E","Aerlinthe Node Golem","Silifi of Crimson Stars","Dynamic_1_D6YxLUyUIW!","84.1N, 44.1E" +"Looking Around","62.0N, 18.0E","Esper Node Golem","Composite Bow with Handle","Dynamic_1_LE5V8SVHG!","62.0N, 18.0E" +"Looking Around","93.8N, 67.4W","Halaetan Node Golem","Slashing Longbow","Dynamic_1_QfLhcZJ64Hkold!","93.8N, 67.4W" +"Looking Around","64.8S, 59.3E","Linvak Node Golem","Greater Celdon Shadow Girth","Dynamic_1_V8&t5$!","64.8S, 59.3E" +"Looking Around","Ulgrim Island","Ulgrim the Unappreciated","Applesauce","Dynamic_1_x!zs79y!","" +"Looking Around","Fake Niffis Crate Quest","Chef Jonus","Fish","Dynamic_1_j&T!ZrQwKvo!","" +"Looking Around","Frost Haven","Larnia","Acid Hand Axe","Dynamic_1_88P$YBwEl!","" +"Looking Around","Tanada Chamber of Scroll / Fire","Tanada Han-Tu","Hearty Ice Cream","Dynamic_1_STjY86!0Iu8x!","" +"Looking Around","Frost Haven","Tanada Hido","Acid Mace","Dynamic_1_3ZhBEF!","" +"Looking Around","Frost Haven","Tanada Shouka","Pouch of Dried Meat","Dynamic_1_YgClBFy!","" +"Looking Around","Gerent's Compound at 87.2S, 17.5W","Representative of the Singularity","Fish","Dynamic_1_qkU0b^i!","87.2S, 17.5W" +"Odd Stamps","93.2N, 48.2W in the Shattered Outlands","Arialle du Bellenesse","Healing Holtburger","Dynamic_1_ADm5RsrDGCbT!","93.2N, 48.2W" +"Odd Stamps","Crater","Silencia's Magma Golem","Slicing Royal Atlatl","Dynamic_1_fR730X5VsPULE5!","" +"Odd Stamps","Colosseum","Master Arbitrator","Palenqual's Tewhate","Dynamic_1_XnFt&!","" +"Odd Stamps","","Colosseum Ticket Vendor","Silifi of Crimson Stars","Dynamic_1_luguukhgZg!","" +"Odd Stamps","Beach Fort","Suzuhara Sheshumi","Silifi of Crimson Stars","Dynamic_1_n5u2imCs!","" +"Odd Stamps","Obsidian Plains","Varetha","Major Smoldering Atlan Bow","Dynamic_1_P1&xxk5!","44.3S, 62.5W" +"Odd Stamps","Crystal Crag","Oorjit","Perfect Shimmering Isparian Bow","Dynamic_1_lPn&BaZ!","" +"Odd Stamps","","Jyotsana","Cragstone Farms Mac&Cheese","Dynamic_1_YCGJJ7cA!","" +"Odd Stamps","","Tokashi Ando","Perfect Dissolving Isparian Crossbow","Dynamic_1_R#HIf!","" +"Odd Stamps","Ries Woron's Story","Thrungus","Expired Stamina Draught","Dynamic_1_eMJVhyPzaa$aGn!","" +"Odd Stamps","Mite Maze","Roderick","Apple Pie","Dynamic_1_#C^p&w0gV$$!","" +"Odd Stamps","Sawato","Ssavish","Composite Bow with Handle","Dynamic_1_NMlDXfx2t!","" +"Odd Stamps","dryreach rescue","Dansha-Ki","Composite Bow with Handle","Dynamic_1_FnXoHWS&kaM!","" +"Odd Stamps","Seat of Knorr","Arikas, Warden of Knorr","Hearty Healing Rabbit Noodle","Dynamic_1_aWOWTc30f4","" +"Odd Stamps","Swamp Garden","Terese","Diforsa Bracers","Dynamic_1_PTy0kqqTLP1Dn^!","" +"Odd Stamps","Dark Isle","Tyrina of Arwic","Major Shadow Gauntlets","Dynamic_1_zJNxGBc!","84.7n 58.7e" +"Odd Stamps","Dark Isle","Francois di Terli","Habraeloi","Dynamic_1_3!Og!","" +"Odd Stamps 2","Aun Settlement 82.7N 21.2E.","Aun Tikakhe","Good Chilling Isparian Mace","Dynamic_1_hafO$cQvbkg!","82.7N 21.2E" +"Odd Stamps 2","","Aun Saritea","Health Tonic","Dynamic_1_7yW17JvMHKu!","" +"Odd Stamps 2","","Aun Aulakhe","Mana Rabbit Pie","Dynamic_1_5xE2TM!","" +"Odd Stamps 2","Lost Wish Cottages (Arwic) 42.6n 62.4e","Lartorus","Pants","Dynamic_1_$GB72K!","42.6n 62.4e" +"Odd Stamps 2","Catacombs of Opposition","Ripper","Gladiatorial Tunic","Dynamic_1_69Rjbany2pKD!","" +"Odd Stamps 2","","Rat Nose","Fine Atlan Staff","Dynamic_1_eBlku!","" +"Odd Stamps 2","","Nanoc, Basher of Bugs","Mana Potion","Dynamic_1_XCTiy!","" +"Odd Stamps 2","","Narg","Iron Rusted Mace","Dynamic_1_S!AhI!","" +"Odd Stamps 2","","Scout Luzumin Abigwei","Alduressa Helm","Dynamic_1_NFf5!","" +"Odd Stamps 2","","Teela","Orange Molly","Dynamic_1_Bl#Y!","" +"Odd Stamps 2","","Scout Tel al-Arat","Envoy's Heaume","Dynamic_1_AJ3Wm9Bk!","" +"Odd Stamps 2","","Pincer Danta","Olthoi Sollerets","Dynamic_1_VezOOBWbn43KU!!","" +"Odd Stamps 2","Vissidal","Merwart Pelagurg","Superior Smoldering Atlan Staff","Dynamic_1_DOIC1!","" +"Odd Stamps 2","Vissidal","Merwart Urglurg","Butter Knife of Slaying","Dynamic_1_&!iRR#RrhnGA!","" +"Odd Stamps 2","Vissidal","Dayla Bint Kazm","Hearty Healing Chicken Pie","Dynamic_1_nDAXG!","" +"Odd Stamps 2","Vissidal","Peng-Ya","Major Dissolving Isparian Crossbow","Dynamic_1_sx^9H^&Mnqp!","" +"Odd Stamps 2","Vissidal","Colista Fluress","Lesser Amuli Shadow Leggings","Dynamic_1_Ej!Zz!","" +"Odd Stamps 2","99.7S 96.7W","Surloshen Realaidain","Hammer of Lightning","Dynamic_1_tiiFC!","99.7S 96.7W" +"Odd Stamps 2","Silyiun - 89.1N 47.6W","Fiun Gaya","Enhanced Shadow Gauntlets","Dynamic_1_hev0!","89.1N 47.6W" +"Odd Stamps 2","Hermit - Thrungus Hole","Hermit","Scored Amuli Leggings","Dynamic_1_rDBG!","" +"Odd Stamps 2","93.2N 48.2W - Eastwatch","Commander Rylane di Cinghalle","Acid Crossbow","Dynamic_1_pZpx41&!","93.2N 48.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Arbelests","Healing Carrot Soup","Dynamic_1_L3Hb3O!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Fists","Platemail Breastplate","Dynamic_1_xj&USOHNL9K&!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Bows","Tasty Stout","Dynamic_1_hw2LNdjT6!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Atlatls","Composite Crossbow with Handle","Dynamic_1_P6!!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Axes","Three Eyed Guppy","Dynamic_1_xX^IHjOo##J$8E!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Blades","Flaming Weeping Dagger","Dynamic_1_iFuvP!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Staves","Composite Crossbow","Dynamic_1_J$JV&VKf!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Orbs","Health Tincture","Dynamic_1_S&JMdWiBDy!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Maces","Wooden Scarecrow Guise","Dynamic_1_^pTx!","32.0N, 43.2W" +"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Knives","Scalemail Hauberk","Dynamic_1_6ZR$k^$Srwc3g!","32.0N, 43.2W" +"Odd Stamps 2","83.4S 97.2E - Ithaenc","Abbess Zik'Lir","Hearty Fish Noodle","Dynamic_1_jmCfm1p5a!","83.4S 97.2E" +"Odd Stamps 2","72.8N,25.0W - Stonehold nearby","Lord Pyrovor","Enhanced Shadow Greaves","Dynamic_1_Tw$7Zwmutan!","72.8N,25.0W" +"Odd Stamps 2","VoD Encampment","Guard Alfric","Bowl of Rice","Dynamic_1_LZkvsu4Ln2$h!","" +"Odd Stamps 2","VoD Encampment","Guard Taziq","Blackfire Shadow Sollerets","Dynamic_1_t9uxr!","" +"Odd Stamps 2","VoD Encampment","Guard Q'alia","Ancient Relic Gauntlets","Dynamic_1_m1KeUXELMuH!","" +"Odd Stamps 2","VoD Encampment","Guard Li","Frost Hatchet","Dynamic_1_XgrV$!","" +"Odd Stamps 2","77.7S 97.0E Ithaenc","Shah-hi","Katar","Dynamic_1_G3N9HSXlowLT$!","77.7S 97.0E" +"Odd Stamps 2","Releasing the Light - Reward Room","Calitoth","Fish","Dynamic_1_mu^91#T!","" +"Odd Stamps 2","VoD Encampment","Guardian of the Forbidden","Princely Runed Dart Flinger","Dynamic_1_#BELoT72Ib!","Small Creepy Statue" +"Odd Stamps 2","Shattered Outlands 94.0n 45.9w","Torgash","examines your Parchment","Dynamic_1_S","94.0n 45.9w" +"Odd Stamps 2","Hoshino Must Die last room","Spirit of Bist'elle","Enhanced Shadow Breastplate","Dynamic_1_b!","" +"Bandit Castle","","Karwin, the Lunatic","Chainmail Pauldrons","Dynamic_1_HIlMkY!","" +"Bandit Castle","","Kiriel Shadowborn","Healing Apple Pie","Dynamic_1_WBzVFJpFUzHkC!","" +"Bandit Castle","","Jourgensson","Hearty Healing Mushroom Pie","Dynamic_1_$W&Pl4!","" +"Bandit Castle","","Gillian the Poacher","Peppermint Ice Cream","Dynamic_1_5oLp!","" +"Bandit Castle","","Alison Dulane","Amuli Shadow Leggings","Dynamic_1_079u9!","" +"Bandit Castle","","Arianna the Adept","Expired Stamina Draught","Dynamic_1_hZIsyYE!!OmcQ!","" +"Bandit Castle","","Shanrek the Forger","Sparring Shirt","Dynamic_1_fbcmDRC!","" +"Bandit Castle","","Neela Nashua","Perfect Dissolving Isparian Spear","Dynamic_1_4tXQFu&&o!","" +"Bandit Castle","","Gwillim, the Apprentice","Lightning Flanged Mace","Dynamic_1_is#X6rBaprU!","" +"Bur","","Drogur","Frost Yari","Dynamic_1_KS8e32dtk7t!","" +"Bur","","Collector Golem","Upper Exoskeleton Metamorphi","Dynamic_1_4xdYA1QvaiDf^!","" +"Bur","","Kuurak","Hearty Healing Chicken Noodle","Dynamic_1_Zapx!","" +"Bur","","Furgal","Spitter Thorax Metamorphi","Dynamic_1_4rk&MTz!","" +"Bur","","Tibik","Gear Crossbow","Dynamic_1_!Ce^d!","" +"Bur","","Nimeruuk","Greater Celdon Shadow Sleeves","Dynamic_1_zIX1Sf6FJt!","" +"Bur","","Kurket","Acidic Rejuvenation","Dynamic_1_snVaz#0Ze3R#4M!","" +"Bur","","Brogosh","Lugian Morning Star","Dynamic_1_$9YdvC2jYTxWZ!","" +"Bur","","Mohor","Quality Isparian Crossbow","Dynamic_1_qpXiWqwBTN4!","" +"Bur","","Kushuk","Silifi of Crimson Stars","Dynamic_1_3ISBG!","" +"Bur","","Borsh","Health Tonic","Dynamic_1_Jh4!","" +"Bur","","Kuuru","Electric Compound Bow","Dynamic_1_vNktko1!","" +"Bur","","Torgluuk, High Shaman of Kor-Gursha","Stout","Dynamic_1_2yxpXSMY!","" +"Bur","","Scout Leader Tmauruk","Hood","Dynamic_1_fEiU!","" +"Bur","","Gruuk'lar","Rynthid Tentacle Dagger","Dynamic_1_xFipmT1!","" +"Gear Knight","Inner Sea Gearknight Invasion","Lieutenant Micham","Dabus","Dynamic_1_CQxkFJvoJrVx!","" +"Gear Knight","Inner Sea Gearknight Invasion","Sir Oakley","Composite Crossbow with Handle","Dynamic_1_lh9wOaXR0!","" +"Gear Knight","Inner Sea Gearknight Invasion","Lieutenant Faen","Blunt Bow","Dynamic_1_Vz#gp!","" +"Gear Knight","Inner Sea Gearknight Invasion","Sir Stavitor","Red Tea","Dynamic_1_ogt05i!","" +"Gear Knight","Inner Sea Gearknight Invasion","Dame Alistra","Superb Flaming Isparian Claw","Dynamic_1_y!","" +"Gear Knight","Direland Gearknight Invasion","Sir Yanov","Major Shadow Greaves","Dynamic_1_BlAckAuHU#!","" +"Gear Knight","Direland Gearknight Invasion","Sir Durnstad","Silifi of Crimson Stars","Dynamic_1_#Dfd!","" +"Gear Knight","Direland Gearknight Invasion","Squire Tylaen","Good Coruscating Isparian Atlatl","Dynamic_1_i1Cxg8Bt!","" +"Gear Knight","Direland Gearknight Invasion","Dame Trielle","Frost Yari","Dynamic_1_h^MdsKZ$6SSD!","" +"Gear Knight","Direland Gearknight Invasion","T'ing Douzen","Panaq","Dynamic_1_p0BEy$e!","" +"Gear Knight","Atamarr Tasks Dungeon","Bronze Gauntlet Knight-Commander","Frost Greataxe","Dynamic_1_REv&biyDw!","" +"Gear Knight","Direland Gearknight Invasion","Copper Cog Craftsmaster","Greater Amuli Leggings of Frost","Dynamic_1_4uls5J!","" +"Wai Jhou","","Kreavon","Skeleton Fish","Dynamic_1_KrPl9N5!","" +"Wai Jhou","","Aun Teverea","Singularity Crossbow","Dynamic_1_Y9wg!RfKHoyL!","" +"Wai Jhou","","Nona","Fish","Dynamic_1_JrzQr8U!","" +"Wai Jhou","","Zho Heishan","Bandit Dagger","Dynamic_1_Abm8qK2!","" +"Wai Jhou","","Sarkin Killcrane","Shadow Tassets","Dynamic_1_mb7NAtZEdBaz!","" +"Wai Jhou","","Riordin Nightbane","Hafted Serpent Spear","Dynamic_1_cCzQdsl5JxLC!","" +"Wai Jhou","","Lacarra Avanthi","Shou-jen Shozoku Trousers","Dynamic_1_ip&NsyQ!","" +"Wai Jhou","","Xanda Har","Gold Fish","Dynamic_1_1CiKW8^x^$!","" +"Rynthid","","Lohrn","Shreth Hide Shoes","Dynamic_1_cS!mivYZ^b!cAA!","" +"Rynthid","","Rhys","Plate Leggings","Dynamic_1_A!!","" +"Rynthid","","Morgethais","Silifi of Crimson Stars","Dynamic_1_wDTf#!","" +"Rynthid","","Geilla","Audetaunga's Korua of the Mountains","Dynamic_1_&dNG5U4!","" +"Rynthid","","Rinne Gorber","Brilliant Celdon Leggings","Dynamic_1_ln!Lx!","" +"Rynthid","","Aun Ol'tra","Small Beer","Dynamic_1_&^3Hve4JXH^!","" +"Rynthid","","Ranulf","Prismatic Celdon Sleeves","Dynamic_1_8n2l!","" +"Rynthid","","Sylvanus","Ursuin Hide Coat","Dynamic_1_veaD!","" +"Rynthid","","Marcus","Fish","Dynamic_1_bpNCu!rsf45Fk!","" +"Rynthid","","Ilte Krongal","Hearty Mana Rabbit Noodle","Dynamic_1_AusVgDl!","" +"Rynthid","","The Bringer of Light","Peppermint Hot Chocolate","Dynamic_1_LrpV!62!","" +"Paradox Camp","Paradox Olthoi Camp","Ethan Wintermaine","Superb Flaming Isparian Bow","Dynamic_1_PPtO6!7dB!","" +"Paradox Camp","","Adrien Swiftblade","Oak Stormwood Crossbow","Dynamic_1_R^1Uv!J8k!","" +"Paradox Camp","","Alicia Swiftblade","Badlands Siraluun Dress","Dynamic_1_G0Rn1lOZKj7C!","" +"Paradox Camp","","Tomihino","Dart Flinger","Dynamic_1_!$cc!","" +"Paradox Camp","North Olthoi Burrow","Peda's Assistant","examines your Parchment","Dynamic_1_3ddaHUzi!","" +"Paradox Camp","North Olthoi Burrow","Peda","examines your Parchment","Dynamic_1_1R9O85L$b!","" +"Paradox Camp","North Olthoi Burrow","Crusher","examines your Parchment","Dynamic_1_a&Z2!","" +"Paradox Camp","North Olthoi Burrow","Deena","examines your Parchment","Dynamic_1_cIZV2uDB6B!","" +"Paradox Camp","North Olthoi Burrow","Mac","examines your Parchment","Dynamic_1_5x^G2$X9!","" +"Paradox Camp","North Olthoi Burrow","Swift-Eye","examines your Parchment","Dynamic_1_o$yT7al7ZTxv!","" +"Paradox Camp","North Olthoi Burrow","Sasha","examines your Parchment","Dynamic_1_CvzZIz!","" +"Paradox Camp","North Olthoi Burrow","Dead-Eye","examines your Parchment","Dynamic_1_fP9y!","" +"Paradox Camp","North Olthoi Burrow","Lash","examines your Parchment","Dynamic_1_AniHdl4wtIuF0!","" +"Paradox Camp","North Olthoi Burrow","Long-Shot","examines your Parchment","Dynamic_1_jJ^yEFc#m^M!","" +"Graveyard","","Renata","Singularity Spear","Dynamic_1_1fDZO3!","" +"Graveyard","","Yoite","Composite Bow with Handle","Dynamic_1_OG6jdId!","" +"Graveyard","","Gadi","Scored Celdon Girth","Dynamic_1_ELgh#!","" +"Graveyard","","Aethelswith","Leather Helm","Dynamic_1_cF!","" +"Graveyard","","Mhoire Soldier","Superb Isparian Bow","Dynamic_1_VgB#WcZOIA!","North Soldier - Opposite side of bunker" +"Graveyard","","Mhoire Soldier","Hafted Gromnie Banner with Crest","Dynamic_1_z$DX!","South Soldier - Opposite side of bunker" +"Graveyard","","Apep-tek the Tolerant","Spectacular Lager","Dynamic_1_Y55^MqgC!","Above ground, outside bunker 65.3w 44.0w" +"Graveyard","","Laylana","Stiletto","Dynamic_1_&SRgbH!","Above ground, outside bunker 65.2s 44.3w" +"Graveyard","","Lo Shoen","Amateur Explorer Pants","Dynamic_1_102!pkgn8wAYSe!","Floating Platform - Level 50 req" +"Graveyard","","Slubbley","Healing Cake","Dynamic_1_mDaEh7!","" +"Graveyard","","Jailer","Good Shimmering Isparian Bow","Dynamic_1_2Hm6DL!","NE bunker aboveground 64.9s 44.1w" +"Graveyard","","Kousu Temo","Fried Mushroom Rice Dough","Dynamic_1_QUXbn6!","EW Initiation guy, 64.2s 44.0w" +"Graveyard","","Candrus Steady-Hand","Academy Mana Potion","Dynamic_1_BKq6N6nXoR!","CH Initiation guy, 65.8s 45.3w" +"Graveyard","","Ancient Stones","Bandit Flaming Jambiya","Dynamic_1_xL!g4ZoCuv!H","Pile of stones at 66.5s 44.7w" +"Graveyard","Mhoire Castle - Great Hall","Ancient Throne","Taiaha","Dynamic_1_&y4ettwcivZ5Nm!","" +"Graveyard","Mhoire Castle - Great Hall","Shade of Antemy","Left Peg Leg","Dynamic_1_CphV&!","" +"Graveyard","Mhoire Castle - Great Hall","Shade of Fordroth","Perfect Chilling Isparian Atlatl","Dynamic_1_M0u7js^$E!","" +"Graveyard","Mhoire Castle - Great Hall","Shade of Terelev","Silifi of Crimson Stars","Dynamic_1_XPvw!","" +"Graveyard","Mhoire Castle - Great Hall","Guliant","Celdon Girth of Acid","Dynamic_1_aCEEdQil42!","" +"Neftet","","T'ing Setsuko","Flaming Broad Sword","Dynamic_1_JfmjJmY0O8r!","" +"Neftet","","Nephthys","Red Tea","Dynamic_1_mnJCjm5QR$s&!","" +"Neftet","","Fahneph","Gear Crossbow","Dynamic_1_owGS9WGJ1Q!","" +"Neftet","","Nekshla","Mana Pumpkin Pie","Dynamic_1_AAQ1#!","" +"Neftet","","Sir Hassim bin Tamarek","Enhanced Shadow Greaves","Dynamic_1_r7zID$U!","" +"Neftet","","Sir Adarl","Bobo's Stout","Dynamic_1_SoBgM6JPckOY9!","" +"Neftet","","Sir Ibreh bin Kassim","Expired Mana Tincture","Dynamic_1_aVMuY!","" +"Neftet","","Sir Daeglan","Quality Coruscating Isparian Crossbow","Dynamic_1_n!","" +"Neftet","","Bemeth the Gatherer","Lesser Koujia Breastplate of Acid","Dynamic_1_bda1WYoI!","" +"Neftet","","Hammah al Rundik","Olthoi Greaves","Dynamic_1_9v^POv6ADt3r!","" +"Neftet","22.2S 8.7E","Kaltus","Composite Bow with Handle","Dynamic_1_xWYS3fqIjPN!","22.2S 8.7E Not Dangerous run" +"Frozen Valley","","Sir Donovan","Pickled Egg","Dynamic_1_ypu2L!","" +"Frozen Valley","","Sir Learth","Royal Cabbage","Dynamic_1_xpAJDzm$!","" +"Frozen Valley","","Lady Daenerah","Acid Spadone","Dynamic_1_$SDp1uWx8wq$!","" +"Frozen Valley","","Gregoria, Gurog Destroyer","Chocolate Gromnie","Dynamic_1_!vr&1c1Ug1XI!","" +"Frozen Valley","","Hunter","Hearty Healing Chicken Pie","Dynamic_1_Sy!9l0FAJFI!","" +"Frozen Valley","","Leilah","Lightning Silifi","Dynamic_1_uyoL!","" +"Frozen Valley","","Halvor","Noble Quarterstaff","Dynamic_1_LfLac!","" +"Frozen Valley","","Kumiko","Expired Health Potion","Dynamic_1_TB!q!","" +"Frozen Valley","","Archmage Ichihiri","Arbalest","Dynamic_1_HzvCs4B2!","" +"Hoshino Tent","","Sergeant Trebuus","Soldier Pincer Metamorphi","Dynamic_1_GQIb1mF!","" +"Hoshino Tent","","Sergeant Freng","Lightning War Axe","Dynamic_1_wVJm&#Lpz7AQ#F","" +"Hoshino Tent","","Aun Kirtal","Arena Bow","Dynamic_1_V9ffGx!","" +"Hoshino Tent","","Lieutenant Aurin","Enhanced Smoldering Atlan Sword","Dynamic_1_4qlVcAWbM!","" +"Hoshino Tent","","Lord Eorlinde","Major Shadow Gauntlets","Dynamic_1_zkzTna!","" +"Hoshino Tent","","Griffon","Mana Elixir","Dynamic_1_b4^F&M1^uG!","" +"Hoshino Tent","","Hanamoto Aki'ko","Lightning Nekode","Dynamic_1_3Qlg!","" +"Hoshino Tent","","Corporal Irashi","Lesser Koujia Shadow Leggings","Dynamic_1_2DBoreKEH!","" +"Hoshino Tent","","Lieutenant Takamaki","Silifi of Crimson Stars","Dynamic_1_#hzL!","" +"Hoshino Tent","","Lieutenant Roothe","Fried Rabbit","Dynamic_1_XuH!z7l!","" +"Viridian Rise","","Brellegia","Greater Celdon Breastplate of Acid","Dynamic_1_mCyu9F!","Requires Viridian Rise Recall Gem" +"Viridian Rise","","Summercrown","Tachi","Dynamic_1_R8H6nh!","" +"Viridian Rise","","Aangesilus","Slashing Compound Bow","Dynamic_1_2LJyvGJL!","" +"Viridian Rise","","Dridge","Greater Amuli Leggings of Flame","Dynamic_1_LP3Ee7tH!","" +"Viridian Rise","","Kervim'telek","Ursuin Hide Coat","Dynamic_1_E5$S!","" +"Viridian Rise","","Swift","Fried Chicken","Dynamic_1_hYVV!","" +"Ayan","","Aludi al-Jaladh","Seasoned Explorer Gauntlets","Dynamic_1_7$I7bC!","" +"Ayan","","Aun Javhalrea, the Game Warden","Frost Ono","Dynamic_1_UdRA9W!","" +"Ayan","","Aun Khekierea","Rich Mocha","Dynamic_1_Yt1uiSkCgK!","" +"Ayan","","Aun Aukherea","Chocolate Cookie","Dynamic_1_G$iqi763E!","" +"Ayan","","Shuthoth","Silifi of Crimson Stars","Dynamic_1_CkuPj0IwP!","" +"Ayan","","Yuan Hanzu","Acid Hatchet","Dynamic_1_t^CiJAt2TBz17!","" +"Ayan","","Joku Shunja","Dho Life Apprentice Robe","Dynamic_1_&X4EDhy!","" +"Ayan","","Aaminah","Upgraded Marksman's Robe","Dynamic_1_YlHC^cbS!","" +"Ayan","","Anfram Mellow","Ulgrim's Bunny Slippers","Dynamic_1_$MJj0ytiSy0CKN!","" +"Ayan","","Alishia bint Aldan","Lightning Hatchet","Dynamic_1_87z&&Ok2o&jo!","" +"Ayan","","Vierana du Canamorra","Fine Shadow Atlan Mace","Dynamic_1_qtZdY0C!ae!","" +"Ayan","","Qurakh al-Taal","Hearty Mana Beef Stew","Dynamic_1_Ug2snTqb44!","" +"Ayan","","Laedron the Geomancer","Fine Stinging Atlan Spear","Dynamic_1_2lXQdqHWxPU!","" +"Ayan","","Rohula bint Ludun","Arena Staff","Dynamic_1_SjjPqyCHNigY!","" +"Ayan","","Guard Winterborn","Silifi of Crimson Stars","Dynamic_1_!fzudXFZV0Je3!","" +"Ayan","","Ennio di Cinghalle","Perfect Chilling Isparian Claw","Dynamic_1_fYP!","" +"Ayan","","Lydda","Pathwarden Scale Hauberk","Dynamic_1_neYBz15!","" +"Ayan","","Gaston Shadowbound","Major Shadow Tassets","Dynamic_1_jdMT!","" +"Ayan","","Harkwull the Discreet","Quality Flaming Isparian Crossbow","Dynamic_1_Bq7Brhg!","" +"Ayan","","Tanami Kei","Souldrinker","Dynamic_1_en!","" +"Ayan","","Lamorda Loschi","Major Shadow Sollerets","Dynamic_1_2xn4LwsUdh!","" +"Ayan","","Soju Bo-Ki","Composite Crossbow with Handle","Dynamic_1_ADDKG!","" +"Ayan","","Hoshar ibn Jalaq","High Balance Testing Coat","Dynamic_1_bZ4bc!","" +"Ayan","","Guard Bey","Tasty Stout","Dynamic_1_&!4f5YlXZ!","" +"Ayan","","Ishaq the Philosopher","Enhanced Skeletal Atlatl","Dynamic_1_H3UNETkRXTX!","" +"Candeth Keep","","Morathe gives you","Superb Isparian Atlatl","Dynamic_1_g9M7bV3z3#S!","" +"Candeth Keep","","Aun Autuorea gives you","Singularity Katar","Dynamic_1_5kEI0!","" +"Candeth Keep","","Talira Dain","Composite Bow","Dynamic_1_5i1z1Mb!","No text about being given item, it just shows up in backpack" +"Candeth Keep","","Dalius Kendmar gives you","Undead Guise","Dynamic_1_YFrw!","" +"Candeth Keep","","Grania the Bold gives you","Composite Crossbow with Handle","Dynamic_1_DaevbVP!","" +"Candeth Keep","","Yukara Miko the Collector","Acid Longbow","Dynamic_1_F1r^qTQ!","" +"Candeth Keep","","Ryukai Hiro","Good Olthoi Pauldrons","Dynamic_1_HeucrAy6c!","" +"Candeth Keep","","Garaena the Emissary","Seasoned Explorer Arbalest","Dynamic_1_es^0FY!","Aerlinthe Portal NPC" diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj new file mode 100644 index 0000000..0268ebd --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj @@ -0,0 +1,152 @@ + + + + + net10.0-windows + x86 + win-x86 + Library + true + enable + true + Shared + true + Size + false + RynthCore.Plugin.RynthILT + RynthCore.Plugin.RynthILT + x86 + + 66 + + ilt + Infinite Leaftide + infiniteleaftide.online + InfiniteLeaftide|*Leaftide* + Infinite Leaftide (ACECustom) features: the ILT Hub (the Mini Remote's ILT tabs: banking, gear, charms, games, Vaulted Dungeons; the Pets tab's charms, siphon capture and breeding), the Guardian, the Dynamic Stamps, bounties, progression, the attribute raiser, the ring inscription chain, the Empyrean Handler ring evade, the T11 loot counters, the ILT settings and the /fship fellowship commands. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthILTJsonContext.cs b/Plugins/RynthCore.Plugin.RynthILT/RynthILTJsonContext.cs new file mode 100644 index 0000000..81a0c77 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthILTJsonContext.cs @@ -0,0 +1,13 @@ +using System.Text.Json.Serialization; +using RynthCore.Plugin.RynthILT.Bounty; + +namespace RynthCore.Plugin.RynthILT; + +// Source-generated System.Text.Json only: never reflection-serialize plugin types (the +// reflection cache keeps the old plugin generation alive across a hot reload). +[JsonSerializable(typeof(BountyState))] +[JsonSerializable(typeof(BountyBridgePayload))] +[JsonSourceGenerationOptions( + IncludeFields = true, + PropertyNameCaseInsensitive = true)] +internal partial class RynthILTJsonContext : JsonSerializerContext { } diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs new file mode 100644 index 0000000..22f19a3 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs @@ -0,0 +1,1089 @@ +// RynthILTPlugin.cs - Infinite Leaftide (ACECustom) features, kept out of RynthAi and the engine core. +// +// Two features, both shown only on ILT: +// * Bounties (Bounty/BountyTracker.cs): the engine's Bounties window (the bar's ILT button, +// /rc bounties). Its reads run only while that window polls RynthILTGetBountiesJson, and the +// engine polls only on ILT. +// * The ILT Hub (Hub/, SilentKelpie's, moved here from RynthAi 2026-10-13): the Mini Remote's +// ILT tabs (Banking, Gear, Charms, Games; RynthAi's Mini Remote hosts them through +// RynthILT.Hub, HubInterface.cs, and lists them on RynthCore's sections rail; the Gear tab has +// the Rings inscription chain; the Character tab moved to RynthOracle's Character tab), its +// own Mini Remote sections (BuildSectionsJson: the ILT session extras in Session Stats, the +// /fship buttons in Fellowship, the /qb list in a Quests section), its sections in RynthAi's +// Pets / Remote tabs, the Guardian panel (RynthPluginRenderEmbed "guardian"), +// the Skills panel's Progression data (RynthILTGetProgressionJson, "prog ..." through +// RynthILTCommand), server feature detection, and the charms and bank balances for other +// plugins ("RynthILT.Data", DataInterface.cs). Every feature stays dormant off an ILT-like +// world (IltServerOptions: no probes, no chat). +// +// Second: a copy of the ILT settings (IltSettingsView/): RynthCore's verdict, this character's +// override (read only: it is set in RynthCore Options > Diagnostics), the ILT world names and +// every feature the Hub read from the server, in its own window ("/ilt settings"). The verdict +// comes from RynthCore's server list (plugin API v86, polled every 2 s), and the Hub follows it +// once one arrives (IltEngineVerdict). +// +// Moved from RynthAi on 2026-10-20 (Hub/): the Pets tab's ACECustom parts (IltPetAutomation), the +// Empyrean Handler ring detection (IltRingEvade; RynthAi.Hub BackAwayFrom does the jump), the T11 +// "/aug" counters and "/ilt t11" (IltT11; RynthAi.Hub SetPlayerCounter), the Vaulted Dungeons +// master switch, the Remote tab's ILT parts, and the Mini Remote ILT tab views on RynthCore's rail +// (IltSectionsManifest.cs, RenderEmbeddedTab). Their settings were copied once from the +// character's RynthAi files (IltMigration.ImportRynthAiSettings, at the Hub's start). +// +// Third: ILT's fellowship commands (IltFellowship/, ACECustom /fship) as buttons in RynthCore's +// Fellowship section and their own window ("/ilt fellow"). While ILT is active the list is also +// sent to RynthAi ("servercommands"), whose Fellowship view draws them; an empty list clears it. +// +// Threads: OnTick, OnChatWindowText, OnKillNotification, login/logout and the engine's export calls +// run on the plugin pump. OnChatBarEnter runs on AC's main thread (the engine's dispatcher queues it +// there, our own InvokeChatParser too), and RynthAi forwards its "/ra hub ..." verbs from there too, +// so commands only queue and run on the next tick. OnRender / RenderEmbed and the RynthILT.Hub +// render functions run on the render thread and only read what the pump built; the settings and +// fellowship windows queue their chat commands for the tick. +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using ImGuiNET; +using RynthCore.Plugin.RynthILT.Bounty; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.RynthILT.IltFellowship; +using RynthCore.Plugin.RynthILT.IltSettingsView; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; + +namespace RynthCore.Plugin.RynthILT; + +public sealed class RynthILTPlugin : RynthPluginBase +{ + internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthILT"); + // Previous release: 0.3.2. + internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.3"); + + /// + /// The settings view's surface. Not in the sections manifest (the force-server override lives + /// only in RynthCore Options > Diagnostics), but still drawn for an engine that asks. + /// + internal const string SettingsSurface = "section:ilt-settings"; + + /// The ILT session extras' surface in RynthCore's Mini Remote "Session Stats" section. + internal const string RatesSurface = "section:ilt-rates"; + + /// The fellowship commands' surface in RynthCore's Fellowship section. + internal const string FellowshipSurface = "section:ilt-fellowship"; + + /// + /// The quest bonus list (/qb) in RynthILT's own Mini Remote "Quests" section (it was part of + /// RynthAi's Quests tab, which moved to RynthOracle; Infinite Leaftide's /qb stays RynthILT's). + /// + internal const string QuestBonusSurface = "section:ilt-questbonus"; + + /// + /// Dynamic Stamps in RynthILT's Quests section (from RynthOracle's Quests list, 2026-10-21; also + /// the "/ilt stamps" window). + /// + internal const string DynamicStampsSurface = "section:ilt-dynstamps"; + + /// RynthAi's name for the plugin-command broker (its Fellowship view draws our commands). + private const string RynthAiPlugin = "RynthAi"; + + private readonly IltSettingsModel _settingsModel = new(); + private readonly IltSettingsUi _settingsUi; + private readonly IltFellowshipUi _fellowshipUi; + // The Hub pages' own windows ("/ilt stamps", "/ilt breeding"): set by commands on the tick, by + // the window's close button on the render thread (plain bool writes). + private volatile bool _stampsWindowOpen, _breedingWindowOpen; + // Chat commands from the settings and fellowship windows (render thread), run on the next tick. + private readonly ConcurrentQueue _chatCommands = new(); + private const int MaxQueuedChatCommands = 32; + + public RynthILTPlugin() + { + _settingsUi = new IltSettingsUi(_settingsModel, cmd => QueueChatCommand(cmd), RefreshFeatures, () => _hub); + _fellowshipUi = new IltFellowshipUi(QueueChatCommand); + IltEngineVerdict.Attach(_settingsModel); + } + + /// Render thread: queues a chat command for the tick; false when the engine can't run one. + private bool QueueChatCommand(string command) + { + if (!Host.HasInvokeChatParser || _chatCommands.Count >= MaxQueuedChatCommands) return false; + _chatCommands.Enqueue(command); + return true; + } + + /// Wait this long after login for the character's name before tracking without a save file. + private const long NameWaitMs = 30_000; + private const long NameRetryMs = 1_000; + + private bool _loginComplete; + private long _loginAtMs; + private long _nextNameTryMs; + private long _nextHubTryMs; + private BountyTracker? _bounties; + private IltHubController? _hub; + // An unfinished copy from RynthAi (IltMigration pending): the Hub writes nothing for this + // character and the copy is retried every MigrationRetryMs; once it works the Hub restarts on + // the copied files. + private const long MigrationRetryMs = 120_000; + private volatile bool _hubWritesBlocked; + private long _nextMigrationRetryMs; + private string _hubFolder = string.Empty, _hubWorld = string.Empty, _hubChar = string.Empty; + private bool _forceOnRestart; + private RynthAiClient? _ai; + private IltSettings _settings = new(); + + // "/ilt ..." lines from OnChatBarEnter and RynthAi's forwarded "/ra" verbs, run on the next tick. + private readonly ConcurrentQueue _commands = new(); + // "/bounty ..." lines from OnChatBarEnter (typed by the player, or our own coming back through + // the engine's dispatcher), passed to the tracker before the next chat line or tick. + private readonly ConcurrentQueue _typedBounty = new(); + // Engine / plugin commands (RynthPluginApplyRemoteCommand: "prog ..." from RynthAi or an older engine). + private readonly ConcurrentQueue _engineCommands = new(); + + /// The Bounties window's tracker (PluginExports); null until login. + internal BountyTracker? Bounties => _bounties; + + /// The ILT Hub for the logged-in character (HubInterface, PluginExports); null until its name is known. + internal IltHubController? Hub => _hub; + + public override int Initialize() + { + RynthLog.Init(Host); + // The Hub's windows and RynthAi-hosted tabs draw through the engine's cimgui module. + ImGuiNativeBinding.Ensure(msg => RynthLog.Write(LogCat.IltHub, msg)); + // Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line each. + UseAudit.Reset("RynthILT", null); + // Saves (Hub state, bank log, profiles, settings, bounty list, the copies from RynthAi) say + // when they fail and why (Plugins/Shared/DataWriteGuard.cs): always in the log, in chat + // once per folder, and only on an ILT world (PostDataWriteProblems). + DataWriteGuard.Reset(); + DataWriteGuard.PluginName = "RynthILT"; + DataWriteGuard.LogSink = msg => RynthLog.Write(LogCat.IltStore, + msg.StartsWith("[RynthILT] ", StringComparison.Ordinal) ? msg.Substring(11) : msg); + _ai = new RynthAiClient(Host); + _settings = IltSettingsStore.Load(); + Host.Log("[RynthILT] Plugin initialized."); + return 0; + } + + // Also called on a freshly (re)loaded plugin while already in game. + public override void OnLoginComplete() + { + SaveBounties(); + StopHub(); + _bounties = null; + _loginComplete = true; + _loginAtMs = Environment.TickCount64; + _nextNameTryMs = 0; + _nextHubTryMs = 0; + _ai?.Reset(); + PollServerState(force: true); + TryStartBounties(); + TryStartHub(); + } + + public override void OnLogout() + { + SaveBounties(); + _bounties = null; + StopHub(); + _ai?.Reset(); + _loginComplete = false; + ClearSharedFellowshipCommands(); + while (_commands.TryDequeue(out _)) { } + while (_typedBounty.TryDequeue(out _)) { } + while (_engineCommands.TryDequeue(out _)) { } + while (_chatCommands.TryDequeue(out _)) { } + _settingsModel.Clear(); + _serverStateJson = string.Empty; + } + + // Plugin unload (hot reload, update, client closing): keep the list and the Hub state for the + // next copy. No broker call while the engine unloads us: RynthAi drops the fellowship commands + // once they stop arriving (ServerCommandModel.StaleMs). + public override void Shutdown() + { + SaveBounties(); + StopHub(); + HubInterface.Release(); + IltEngineVerdict.Attach(null); + RynthLog.Shutdown(); + } + + public override void OnTick() + { + try { RynthLog.Pump(); } catch { } + if (!_loginComplete) return; + _ai?.Tick(); + PollServerState(force: false); + if (_bounties == null) TryStartBounties(); + if (_hub == null) TryStartHub(); + DrainTypedBounty(); + while (_commands.TryDequeue(out string[]? parts)) RunCommand(parts); + while (_engineCommands.TryDequeue(out string? engineCommand)) RunEngineCommand(engineCommand); + DrainChatCommands(); + _bounties?.Tick(); + try { _hub?.Tick(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "Tick"); } + RetryPendingMigration(); + PostDataWriteProblems(); + try { PublishHubFeatures(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "PublishHubFeatures"); } + try { ShareFellowshipCommands(); } + catch (Exception ex) { Host.Log($"[RynthILT] Fellowship commands to RynthAi failed: {ex.Message}"); } + } + + // ── ILT fellowship commands for RynthAi's Fellowship view (IltFellowship/) ── + + private const long FellowshipShareCheckMs = 2000; + private const long FellowshipShareResendMs = 10_000; + private long _fellowshipShareNextAt; + private long _fellowshipShareSentAt; + // The last payload RynthAi took; empty when nothing was delivered (or after a clear). + private string _fellowshipShareLast = string.Empty; + + /// + /// Plugin tick: sends RynthAi ILT's fellowship commands while ILT is active (an empty list when + /// it isn't), when that changes and every (RynthAi may load + /// later, and drops a list that stops arriving). Nothing on an engine without the broker. + /// + private void ShareFellowshipCommands() + { + if (!Host.HasSendPluginCommand) return; + long now = Environment.TickCount64; + if (now < _fellowshipShareNextAt) return; + _fellowshipShareNextAt = now + FellowshipShareCheckMs; + + bool active = IltActive(); + // Nothing to clear when RynthAi never got a list. + if (!active && _fellowshipShareLast.Length == 0) return; + string payload = IltFellowshipCommands.Payload(active); + if (payload == _fellowshipShareLast && now - _fellowshipShareSentAt < FellowshipShareResendMs) return; + _fellowshipShareSentAt = now; + // Not delivered (RynthAi not installed or not loaded yet): the resend timer tries again. + if (Host.SendPluginCommand(RynthAiPlugin, ServerCommandShare.Action, payload)) + _fellowshipShareLast = active ? payload : string.Empty; + } + + /// Clears RynthAi's copy of the fellowship commands (logout) if it has one. + private void ClearSharedFellowshipCommands() + { + if (_fellowshipShareLast.Length == 0) return; + _fellowshipShareLast = string.Empty; + _fellowshipShareNextAt = 0; + try + { + if (Host.HasSendPluginCommand) + Host.SendPluginCommand(RynthAiPlugin, ServerCommandShare.Action, IltFellowshipCommands.Payload(active: false)); + } + catch { /* RynthAi drops a list that stops arriving */ } + } + + /// + /// The Hub's world check (RynthCore's verdict once it has one, else RynthILT's server list and + /// "Treat this world as ILT"); before the Hub exists, the engine verdict or the world name + /// (IltFellowshipCommands.IsActive). + /// + private bool IltActive() + { + var hub = _hub; + if (hub != null) return hub.Options.IsIltLikeWorld; + bool? engine = IltEngineVerdict.Active; + string world = engine == null && Host.HasGetWorldName && Host.TryGetWorldName(out string w) ? w : string.Empty; + return IltFellowshipCommands.IsActive(engine, world); + } + + // ── RynthCore's Mini Remote sections ───────────────────────────────────── + + /// + /// The broker actions answered on arrival rather than queued for the tick: RynthCore's + /// "servermenu" push (2026.10.5.47+, every 10 s) and the older "iltfeatures" text. + /// + internal static bool IsParsedRemoteAction(string action) => + action.Equals("servermenu", StringComparison.OrdinalIgnoreCase) + || action.Equals("iltfeatures", StringComparison.OrdinalIgnoreCase); + + /// + /// RynthPluginApplyRemoteCommand "servermenu" / "iltfeatures". Any thread. Taken and dropped: + /// the same verdicts, overrides and world names reach the settings model from RynthCore's + /// server list (plugin API v86, PollServerState), which RynthILT reads itself, so the push is + /// only acknowledged (it must not fall through to the ILT verbs). + /// + internal void ApplyRemoteCommand(string action, string value) { } + + /// + /// RynthPluginRenderEmbed: (Session Stats), + /// (Fellowship), (RynthILT's Quests section) or + /// in RynthCore's Mini Remote, drawn into the engine's current + /// window and context (popped-out windows have their own). is the + /// height it used. False until login or for another surface. Render thread. + /// + internal bool RenderEmbedded(string surface, out float wantHeight) + { + wantHeight = 0; + if (!_loginComplete) return false; + Action? body = surface switch + { + SettingsSurface => _settingsUi.RenderBody, + FellowshipSurface => _fellowshipUi.RenderBody, + RatesSurface => RenderRatesSurface, + QuestBonusSurface => RenderQuestBonusSurface, + DynamicStampsSurface => RenderDynamicStampsSurface, + _ => null, + }; + if (body == null) return false; + IntPtr previous = ImGui.GetCurrentContext(); + IntPtr context = previous != IntPtr.Zero ? previous : Host.ImGuiContext; + if (context == IntPtr.Zero) return false; + ImGui.SetCurrentContext(context); + try + { + float startY = ImGui.GetCursorPosY(); + body(); + wantHeight = MathF.Max(40f, ImGui.GetCursorPosY() - startY + 4f); + return true; + } + catch (Exception ex) + { + Host.Log($"[RynthILT] View {surface} failed: {ex.Message}"); + return false; + } + finally { ImGui.SetCurrentContext(previous); } + } + + /// The ILT session extras (render thread), or a line saying they start with the Hub. + private void RenderRatesSurface() + { + IltHubController? hub = _hub; + if (hub == null) { ImGui.TextDisabled("ILT session rates start once RynthILT's Hub is ready."); return; } + hub.RenderRatesSection(); + } + + /// The /qb list (render thread), or a line saying it starts with the Hub. + private void RenderQuestBonusSurface() + { + IltHubController? hub = _hub; + if (hub == null) { ImGui.TextDisabled("The quest bonus list starts once RynthILT's Hub is ready."); return; } + hub.RenderQuestBonusSection(); + } + + /// Dynamic Stamps (render thread), or a line saying they start with the Hub. + private void RenderDynamicStampsSurface() + { + IltHubController? hub = _hub; + if (hub == null) { ImGui.TextDisabled("Dynamic Stamps start once RynthILT's Hub is ready."); return; } + hub.RenderDynamicStamps(); + } + + /// + /// RynthPluginGetSectionsJson (schema 1, UI/Sections/SectionManifest.cs in RynthCore): the ILT + /// session extras in Session Stats ("char"), the fellowship commands in Fellowship, the /qb list in + /// a Quests section of RynthILT's own, and the Mini Remote ILT tabs the Hub shows (Gear, Charms, + /// Banking in Inventory, Games in a section of RynthILT's own, Vaulted Dungeons in Nav), all + /// Infinite Leaftide areas (shown while RynthCore treats this world as ILT). IltSectionsManifest.cs. + /// The tabs were listed by RynthAi, which hosted them, until 2026-10-20. Null before login. + /// + internal string? BuildSectionsJson() => _loginComplete ? IltSectionsManifest.Build(IltSectionsManifest.TabsOf(_hub)) : null; + + /// + /// RynthPluginRenderEmbed "section:<tab>": one Mini Remote ILT tab as RynthCore's section view + /// (IltSectionsManifest lists them), drawn into the engine's current window and context in the + /// dashboard colours. / are the tab's + /// size. False until the Hub exists, or for a surface that is no ILT tab. Render thread. + /// + internal bool RenderEmbeddedTab(string surface, out float wantWidth, out float wantHeight) + { + wantWidth = wantHeight = 0; + IltHubController? hub = _hub; + if (!_loginComplete || hub == null || !IltSectionsManifest.TryTabOf(surface, out IltSection section)) return false; + IntPtr previous = ImGui.GetCurrentContext(); + IntPtr context = previous != IntPtr.Zero ? previous : Host.ImGuiContext; + if (context == IntPtr.Zero) return false; + ImGui.SetCurrentContext(context); + int pushed = IltStyle.PushDashboardStyle(); + try + { + var size = IltSections.TabSize(section); + wantWidth = size.X; + wantHeight = size.Y; + hub.NoteTabDrawn(); + hub.RenderTab(section); + return true; + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.IltHub, ex, "RenderEmbeddedTab " + surface); + return false; + } + finally + { + ImGui.PopStyleColor(pushed); + ImGui.SetCurrentContext(previous); + } + } + + /// Plugin tick: runs the settings and fellowship views' chat commands through the engine. + private void DrainChatCommands() + { + while (_chatCommands.TryDequeue(out string? command)) + { + if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command)) + ChatLine("[RynthILT] RynthCore didn't take: " + command); + } + } + + private const long ServerStatePollMs = 2000; + private long _serverStateNextAt; + private string _serverStateJson = string.Empty; + + /// + /// Plugin tick, every 2 s (and at login): RynthCore's server list (plugin API v86, + /// GetServerStateJson) into the settings model, whose "ilt" entry the Hub's world check follows + /// (IltEngineVerdict). Parsed only when the text changed. An older engine leaves it empty, and + /// RynthILT's own list decides. + /// + private void PollServerState(bool force) + { + long now = Environment.TickCount64; + if (!force && now < _serverStateNextAt) return; + _serverStateNextAt = now + ServerStatePollMs; + try + { + if (!Host.HasGetServerStateJson || !Host.TryGetServerStateJson(out string json) || json == _serverStateJson) return; + _serverStateJson = json; + _settingsModel.ApplyServerState(EngineServerState.Parse(json)); + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "PollServerState"); } + } + + private const long FeaturePublishMs = 1000; + private long _featurePublishNextAt; + + /// + /// Plugin tick, at most once a second: the Hub's server read (world, last check, feature bits) + /// for the ILT settings view (IltSettingsModel.PublishFeatures); cleared while there is no Hub. + /// + private void PublishHubFeatures() + { + long now = Environment.TickCount64; + if (now < _featurePublishNextAt) return; + _featurePublishNextAt = now + FeaturePublishMs; + var hub = _hub; + if (hub == null) + { + _settingsModel.PublishFeatures(null); + return; + } + var options = hub.Options; + DateTime last = options.LastRefreshUtc; + string when = last == default ? string.Empty : last.ToLocalTime().ToString("HH:mm:ss"); + _settingsModel.PublishFeatures(new IltFeatureView(options.WorldName, options.Source ?? string.Empty, when, + options.IsRefreshing, options.IsIltLikeWorld, BuildFeatureRows(options))); + } + + /// + /// The settings view's feature rows: every catalog feature with its state (IltFeatureCatalog), + /// then each ILT charm ("charm:...", on with the world unless refused in chat), then any other + /// bit chat or a probe set that the catalog doesn't show. Pump thread. + /// + private static KeyValuePair[] BuildFeatureRows(IltServerOptions options) + { + bool ilt = options.IsIltLikeWorld; + var rows = new List>(IltFeatureCatalog.All.Length + 32); + var shown = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (IltFeatureInfo f in IltFeatureCatalog.All) + { + rows.Add(new KeyValuePair(f.Key, (int)IltFeatureCatalog.StateOf(f, ilt, options.Get))); + if (f.ServerBit != null) shown.Add(f.ServerBit); + } + foreach (IltCharmDef def in IltInventory.Charms) + { + string key = IltFeature.Charm(def.Name); + rows.Add(new KeyValuePair(key, (int)IltFeatureCatalog.CharmStateOf(ilt, options.Get(key)))); + shown.Add(key); + } + foreach (var bit in options.SnapshotBits()) + if (shown.Add(bit.Key)) rows.Add(bit); + return rows.ToArray(); + } + + /// + /// The save failures queued by DataWriteGuard, in chat once the Hub knows this is an ILT world + /// (or "Treat this world as ILT"). Off ILT they stay in the log only: nothing ILT shows there. + /// + private void PostDataWriteProblems() + { + if (DataWriteGuard.PendingCount == 0 || _hub?.OffersTabs != true || !Host.HasWriteToChat) return; + DataWriteGuard.DrainChat(line => Host.WriteToChat(line, 2)); + } + + // ── ILT settings ───────────────────────────────────────────────────────── + + /// Asks the Hub to read the server's ILT features again (as "/ilt hub refresh", on the next tick). Render thread. + private bool RefreshFeatures() + { + if (!_loginComplete || _hub == null) return false; + _commands.Enqueue(new[] { "/ilt", "hub", "refresh" }); + return true; + } + + public override void OnChatWindowText(string? text, int chatType, ref int eat) + { + if (string.IsNullOrEmpty(text)) return; + try + { + // The Hub eats its own probe / capture replies (IltChatCapture). + if (_hub?.OnChat(text, chatType) == true) eat = 1; + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnChat"); } + if (_bounties == null) return; + DrainTypedBounty(); + try + { + // Eats only the reply to the tracker's own /bounty list (BountyTracker.OnChat). + if (_bounties.OnChat(text)) eat = 1; + } + catch (Exception ex) + { + Host.Log($"[RynthILT] Bounty chat parse failed: {ex.Message}"); + } + } + + public override void OnChatBarEnter(string? text, ref int eat) + { + if (!_loginComplete || string.IsNullOrEmpty(text)) return; + string trimmed = text.Trim(); + // A /bounty going out: its reply must not be eaten (BountyTracker.NoteTypedCommand). Never eaten here. + if (BountyTracker.IsBountyCommand(trimmed)) + { + _typedBounty.Enqueue(trimmed); + return; + } + // A /myquests going out (RynthILT's own, typed, or another plugin's): the stamps page tells its + // own reply from the others (QuestFlagStore.NoteTypedCommand; interlocked only). Never eaten here. + if (trimmed.Equals("/myquests", StringComparison.OrdinalIgnoreCase)) + { + _hub?.DynamicStamps.NoteTypedMyQuests(); + return; + } + if (!trimmed.Equals("/ilt", StringComparison.OrdinalIgnoreCase) + && !trimmed.StartsWith("/ilt ", StringComparison.OrdinalIgnoreCase)) + return; + eat = 1; + _commands.Enqueue(trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries)); + } + + // A creature's health from the server: siphon auto-capture's fallback health read (ILT only). + public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) + { + try { _hub?.OnUpdateHealth(targetId, healthRatio); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnUpdateHealth"); } + } + + // The server's killer notification: this character landed the killing blow. + public override void OnKillNotification(string? deathMessage) + { + _bounties?.OnKill(); + _hub?.OnKillNotification(); + } + + private void DrainTypedBounty() + { + while (_typedBounty.TryDequeue(out string? typed)) + _bounties?.NoteTypedCommand(typed); + } + + // ── Rendering (render thread) ──────────────────────────────────────────── + + /// + /// The Hub's floating extras (Games HUD, confirmations) and the standalone ILT settings and + /// fellowship windows ("/ilt settings", "/ilt fellow") in the engine's ImGui frame. + /// + public override void OnRender() + { + var hub = _hub; + if (!_loginComplete || Host.ImGuiContext == IntPtr.Zero) return; + if (hub == null && !_settingsUi.WindowOpen && !_fellowshipUi.WindowOpen) return; + IntPtr previous = ImGui.GetCurrentContext(); + ImGui.SetCurrentContext(Host.ImGuiContext); + try + { + try { hub?.Render(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnRender"); } + try { _settingsUi.RenderWindow(); } + catch (Exception ex) { Host.Log($"[RynthILT] Settings window failed: {ex.Message}"); _settingsUi.WindowOpen = false; } + try { _fellowshipUi.RenderWindow(); } + catch (Exception ex) { Host.Log($"[RynthILT] Fellowship window failed: {ex.Message}"); _fellowshipUi.WindowOpen = false; } + if (hub != null) + { + bool stamps = _stampsWindowOpen, breeding = _breedingWindowOpen; + RenderPageWindow("Dynamic Stamps (RynthILT)##rynthilt_stamps", ref stamps, new System.Numerics.Vector2(600, 560), hub.RenderDynamicStamps); + RenderPageWindow("Pet Breeding (RynthILT)##rynthilt_breeding", ref breeding, new System.Numerics.Vector2(600, 600), hub.RenderBreedingWindowBody); + if (!stamps) _stampsWindowOpen = false; + if (!breeding) _breedingWindowOpen = false; + } + } + finally { ImGui.SetCurrentContext(previous); } + } + + /// + /// One Hub page in a window of its own ("/ilt stamps", "/ilt breeding"), in the dashboard colours; + /// goes false when the player closes it. Render thread. + /// + private void RenderPageWindow(string title, ref bool open, System.Numerics.Vector2 size, Action body) + { + if (!open) return; + int pushed = IltStyle.PushDashboardStyle(); + try + { + ImGui.SetNextWindowSize(size, ImGuiCond.FirstUseEver); + if (ImGui.Begin(title, ref open)) body(); + ImGui.End(); + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.IltHub, ex, "window " + title); + open = false; + } + finally { ImGui.PopStyleColor(pushed); } + } + + /// The same while the engine's ImGui shell is off (RynthPluginRenderOverlay), in the dashboard colours. + internal void OnRenderOverlay() + { + var hub = _hub; + if (!_loginComplete || hub == null || Host.ImGuiContext == IntPtr.Zero) return; + IntPtr previous = ImGui.GetCurrentContext(); + ImGui.SetCurrentContext(Host.ImGuiContext); + int pushed = IltStyle.PushDashboardStyle(); + try { hub.Render(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnRenderOverlay"); } + finally + { + ImGui.PopStyleColor(pushed); + ImGui.SetCurrentContext(previous); + } + } + + /// + /// RynthPluginRenderEmbed "guardian": the Temple guardian tools inside RynthCore's Guardian + /// panel (the bar's ILT button), drawn into the engine's current ImGui window and context + /// (a popped-out panel has its own context, not Host.ImGuiContext; switching to the main one + /// there crashed the client, 2026-10-11). False (nothing drawn) until login and the Hub exist. + /// + internal bool RenderEmbeddedGuardian() + { + var hub = _hub; + if (!_loginComplete || hub == null || Host.ImGuiContext == IntPtr.Zero) return false; + IntPtr previous = ImGui.GetCurrentContext(); + if (previous == IntPtr.Zero) ImGui.SetCurrentContext(Host.ImGuiContext); + int pushed = IltStyle.PushDashboardStyle(); + try + { + hub.RenderGuardianPanel(); + return true; + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.IltHub, ex, "RenderEmbeddedGuardian"); + return false; + } + finally + { + ImGui.PopStyleColor(pushed); + if (previous == IntPtr.Zero) ImGui.SetCurrentContext(previous); + } + } + + // ── Commands ───────────────────────────────────────────────────────────── + + /// + /// RynthILT.Hub Command: an ILT "/ra" verb RynthAi forwards ("hub bank", "guardian handin", + /// "bounty show", "rates reset"). Decides at once whether it is ours (RynthAi answers the rest) + /// and queues it for the next tick. Any thread. + /// + internal bool RunForwardedCommand(string line) + { + string[] words = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (words.Length == 0 || !IsIltVerb(words)) return false; + var parts = new string[words.Length + 1]; + parts[0] = "/ra"; + Array.Copy(words, 0, parts, 1, words.Length); + _commands.Enqueue(parts); + return true; + } + + /// + /// The verbs RynthILT answers: the ILT "/ra hub" verbs (not RynthAi's Quests / Pets tabs or its + /// Remote tab), "/ra guardian", "/ra bounty|bounties|bountys", "rates" and "t11". + /// + internal static bool IsIltVerb(string[] words) + { + string verb = words[0].ToLowerInvariant(); + switch (verb) + { + case "guardian": case "bounty": case "bounties": case "bountys": case "rates": case "t11": + return true; + case "ub": + // ub-IT's ACECustom verbs RynthAi passes on ("/ub qblist", "/ub augs"). + return words.Length >= 2 && words[1].ToLowerInvariant() is "qblist" or "augs"; + case "hub": + if (words.Length < 2) return false; // "/ra hub" alone toggles RynthAi's Mini Remote + string sub = words[1].ToLowerInvariant(); + if (sub is "open") + return words.Length < 3 || !IltSections.IsUniversalTabName(words[2]); + if (sub is "tab") + return words.Length >= 3 && IltSections.TryParse(words[2], out IltSection t) && IltSections.IsTab(t); + return true; + default: + return false; + } + } + + private void RunCommand(string[] parts) + { + // RynthAi's forwarded "/ra ..." and "/ilt hub|guardian|bounty ..." reach the Hub alike. + bool fromRa = parts.Length > 0 && parts[0].Equals("/ra", StringComparison.OrdinalIgnoreCase); + string verb = parts.Length >= 2 ? parts[1].ToLowerInvariant() : "help"; + string[] args = parts.Length > 2 ? parts[2..] : Array.Empty(); + + if (!fromRa && (verb == "bounty" || verb == "bounties" || verb == "bountys")) + { + // "/ilt bounty [list|refresh]": the tracker's own chat commands ("/ra bounty" opens the window). + if (_bounties == null) ChatLine("[RynthILT] Bounties not ready (not logged in yet)."); + else _bounties.HandleChatCommand(parts); + return; + } + switch (verb) + { + case "trace": HandleTrace(args); return; + case "debug": + RynthLog.DebugToChat = args.Length > 0 ? args[0].Equals("on", StringComparison.OrdinalIgnoreCase) : !RynthLog.DebugToChat; + ChatLine($"[RynthILT] Debug-to-chat is {(RynthLog.DebugToChat ? "ON" : "off")} (traced: {RynthLog.TracedList()})."); + return; + case "servers": + verb = "hub"; + args = Prepend("servers", args); + break; + case "bounty": + case "bounties": + case "bountys": + case "guardian": + case "hub": + case "rates": + break; + case "ub": + { + // ub-IT's "/ub qblist" and "/ub augs" (RynthAi passes them on): ACECustom's own commands. + string sub = args.Length > 0 ? args[0].ToLowerInvariant() : string.Empty; + string? server = sub == "qblist" ? "/qb list" : sub == "augs" ? "/aug" : null; + if (server == null) { ChatLine("[RynthILT] /ub qblist or /ub augs"); return; } + if (_hub?.Options.IsIltLikeWorld != true) { ChatLine($"[RynthILT] /ub {sub}: not an Infinite Leaftide world."); return; } + if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(server)) ChatLine("[RynthILT] RynthCore didn't take: " + server); + return; + } + case "t11": + { + // "/ilt t11 ..." and RynthAi's "/ra t11 ..." (T11 loot counters; IltT11). + if (_hub == null) { ChatLine("[RynthILT] ILT features not ready (log in first)."); return; } + _hub.T11.HandleCommand(args); + return; + } + case "vaulted": + case "vaulteddungeons": + { + // "/ilt vaulted [on|off|toggle|status]": the Vaulted Dungeons keeper (ILT only; the + // module answers "not available" elsewhere, and while the master switch is off). + if (_hub == null) { ChatLine("[RynthILT] ILT features not ready (log in first)."); return; } + _hub.VaultedDungeons.HandleCommand(args); + return; + } + case "settings": + case "options": + { + // "/ilt settings [show|hide|toggle]": the ILT settings window. + string mode = args.Length >= 1 ? args[0].ToLowerInvariant() : "toggle"; + _settingsUi.WindowOpen = mode switch { "show" or "on" => true, "hide" or "off" => false, _ => !_settingsUi.WindowOpen }; + return; + } + case "stamps": + case "stamp": + case "dynamic": + case "dyn": + case "dyno": + { + // "/ilt stamps [show|hide|toggle]": the Dynamic Stamps window (RynthOracle's "/ro dynamic" until 2026-10-21). + string mode = args.Length >= 1 ? args[0].ToLowerInvariant() : "toggle"; + _stampsWindowOpen = IltSections.Resolve(mode, _stampsWindowOpen); + if (_stampsWindowOpen && _hub?.Options.IsIltLikeWorld == false) + ChatLine("[RynthILT] Dynamic Stamps are an Infinite Leaftide quest line; this world isn't treated as ILT."); + return; + } + case "breeding": + case "breed": + { + // "/ilt breeding [show|hide|toggle]": the pet breeding window (RynthOracle's Pet Breeding tab until 2026-10-21; + // RynthAi's Mini Remote shows the same tracker as Pets > Breeding). + string mode = args.Length >= 1 ? args[0].ToLowerInvariant() : "toggle"; + _breedingWindowOpen = IltSections.Resolve(mode, _breedingWindowOpen); + return; + } + case "fellow": + case "fellowship": + case "fship": + { + // "/ilt fellow [show|hide|toggle]": the ILT fellowship commands window. + string mode = args.Length >= 1 ? args[0].ToLowerInvariant() : "toggle"; + _fellowshipUi.WindowOpen = mode switch { "show" or "on" => true, "hide" or "off" => false, _ => !_fellowshipUi.WindowOpen }; + return; + } + case "help": + ChatLine("[RynthILT] /ilt hub ... (the Mini Remote's ILT tabs; same as /ra hub ...), /ilt guardian ..., /ilt servers [list||default],"); + ChatLine("[RynthILT] /ilt bounty [list|refresh] - the tracked ACECustom bounties (the Bounties window: the ILT button on the RynthCore bar, or /rc bounties),"); + ChatLine("[RynthILT] /ilt vaulted [on|off|toggle|status] - Vaulted Dungeons keeper (ILT only; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons, off by default),"); + ChatLine("[RynthILT] /ilt t11 [augs |refresh|item [0xId]] - T11 loot: the /aug wield counters RynthAi's loot rules use, the item-aug override, an item's T11 text (also /ra t11),"); + ChatLine("[RynthILT] /ilt settings [show|hide|toggle] - the ILT settings: the world verdict, the ILT world names and the server's features (force a server: RynthCore Options > Diagnostics),"); + ChatLine("[RynthILT] /ilt fellow [show|hide|toggle] - ILT's /fship commands as buttons (also in the Mini Remote's Fellowship section),"); + ChatLine("[RynthILT] /ilt stamps [show|hide|toggle] - the Dynamic Stamps (also in the Mini Remote's Quests section); /ilt breeding [show|hide|toggle] - pet breeding (also the Mini Remote's Pets > Breeding),"); + ChatLine("[RynthILT] /ilt trace [on|off], /ilt debug [on|off]."); + return; + default: + // "/ilt bank", "/ilt attr run", ...: the Hub's verbs without "hub". + args = Prepend(verb, args); + verb = "hub"; + break; + } + if (_hub == null) + { + ChatLine("[RynthILT] ILT features not ready (log in first)."); + return; + } + try + { + if (!_hub.HandleCommand(verb, args)) + ChatLine($"[RynthILT] Unknown command: {string.Join(" ", parts)}. /ilt help"); + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "command"); } + } + + private static string[] Prepend(string first, string[] rest) + { + var a = new string[rest.Length + 1]; + a[0] = first; + Array.Copy(rest, 0, a, 1, rest.Length); + return a; + } + + /// "/ilt trace <category|all|list> [on|off]". + private void HandleTrace(string[] args) + { + string target = args.Length > 0 ? args[0] : "list"; + bool on = args.Length < 2 || !args[1].Equals("off", StringComparison.OrdinalIgnoreCase); + if (target.Equals("list", StringComparison.OrdinalIgnoreCase) || target.Equals("status", StringComparison.OrdinalIgnoreCase)) + { + ChatLine($"[RynthILT] Traced: {RynthLog.TracedList()}. Categories: {string.Join(", ", Enum.GetNames())}. Log folder: {RynthLog.Directory}"); + return; + } + if (target.Equals("all", StringComparison.OrdinalIgnoreCase) || target.Equals("ilt", StringComparison.OrdinalIgnoreCase)) + { + int n = RynthLog.SetTracingAll(on); + ChatLine($"[RynthILT] Tracing {(on ? "enabled" : "disabled")} for {n} categories."); + return; + } + if (!RynthLog.TryParseCategory(target, out LogCat cat)) + { + ChatLine($"[RynthILT] Unknown trace category '{target}'. /ilt trace list"); + return; + } + RynthLog.SetTracing(cat, on); + ChatLine($"[RynthILT] Trace {cat}: {(on ? "ON" : "off")}"); + } + + /// RynthILTCommand: "prog ..." (the Skills panel's Progression tab) and the Hub verbs, from the engine. Pump thread. + internal void RunEngineCommand(string text) + { + string[] words = text.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (words.Length == 0) return; + if (words[0].Equals("prog", StringComparison.OrdinalIgnoreCase)) + { + if (_hub == null) { ChatLine("[RynthILT] ILT features not ready (log in first)."); return; } + try { _hub.Progression.HandleRemote(words[1..]); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltProgression, ex, "prog command"); } + return; + } + if (IsIltVerb(words)) RunForwardedCommand(text); + } + + /// RynthPluginApplyRemoteCommand (any thread): "prog" + its arguments, or an ILT verb; run on the next tick. + internal void EnqueueRemoteCommand(string action, string value) + { + if (_engineCommands.Count < 64) _engineCommands.Enqueue((action + " " + value).Trim()); + } + + private void ChatLine(string text) + { + if (Host.HasWriteToChat) Host.WriteToChat(text, 1); + } + + // ── The ILT Hub ────────────────────────────────────────────────────────── + + /// + /// Starts the Hub once the character's name is known (its files are per character). The first + /// time a character logs in with RynthILT its RynthAi ILT Hub files are copied over (IltMigration). + /// + private void TryStartHub() + { + long now = Environment.TickCount64; + if (now < _nextHubTryMs || _hub != null || _ai == null) return; + _nextHubTryMs = now + NameRetryMs; + + uint me = Host.GetPlayerId(); + if (me == 0 || !Host.HasGetObjectName || !Host.TryGetObjectName(me, out string charName) || string.IsNullOrWhiteSpace(charName)) + return; + string world = Host.HasGetWorldName && Host.TryGetWorldName(out string w) && !string.IsNullOrWhiteSpace(w) ? w.Trim() : string.Empty; + string folder = CharacterFolder(world, charName); + bool force = false; + try + { + var lines = new List(IltMigration.MigrateShared(_settings, SettingsRoot)); + lines.AddRange(IltMigration.MigrateCharacter(folder, world, charName, _settings, out force)); + if (lines.Count > 0) + { + IltSettingsStore.Save(_settings); + RynthLog.Write(LogCat.IltStore, $"Carried the ILT Hub's saved data over from RynthAi for {charName}: {string.Join(", ", lines)}."); + } + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, "migration"); } + + force |= _forceOnRestart; + _forceOnRestart = false; + bool pending = IltMigration.IsPending(_settings, folder); + _hubWritesBlocked = pending; + _hubFolder = folder; + _hubWorld = world; + _hubChar = charName; + _nextMigrationRetryMs = now + MigrationRetryMs; + if (pending) + RynthLog.Write(LogCat.IltStore, $"{charName}'s Hub data isn't all copied from RynthAi yet: the Hub saves nothing for this character " + + "until it is (read from RynthAi's files where it can; retried every 2 minutes and at each login)."); + try + { + _hub = new IltHubController(Host, folder, _settings, _ai, () => _hubWritesBlocked, + pending ? IltMigration.FindLegacyCharFolder(world, charName) : null); + // Once per character: the RynthAi settings that moved here on 2026-10-20. + var imported = IltMigration.ImportRynthAiSettings(_hub.State, world, charName); + if (imported.Count > 0) + RynthLog.Write(LogCat.IltStore, $"Carried {charName}'s RynthAi settings that moved to RynthILT over: {string.Join(", ", imported)}."); + _hub.OnLoginComplete(charName, force); + } + catch (Exception ex) + { + _hub = null; + RynthLog.Exception(LogCat.IltHub, ex, "start"); + } + } + + /// + /// Pump: while this character's copy from RynthAi is unfinished, tries it again every + /// MigrationRetryMs. When it completes the Hub is stopped (still writing nothing, so the copied + /// files stay as they are) and started again on them. + /// + private void RetryPendingMigration() + { + if (_hub == null || !_hubWritesBlocked) return; + long now = Environment.TickCount64; + if (now < _nextMigrationRetryMs) return; + _nextMigrationRetryMs = now + MigrationRetryMs; + try + { + var lines = IltMigration.MigrateCharacter(_hubFolder, _hubWorld, _hubChar, _settings, out bool force); + if (lines.Count > 0) + { + IltSettingsStore.Save(_settings); + RynthLog.Write(LogCat.IltStore, $"Retried copying {_hubChar}'s ILT Hub data from RynthAi: {string.Join(", ", lines)}."); + } + if (IltMigration.IsPending(_settings, _hubFolder)) return; + _forceOnRestart = force; + StopHub(); // _hubWritesBlocked is still true: the logout save writes nothing + _nextHubTryMs = 0; + TryStartHub(); // loads the copied files; saves from now on + RynthLog.Write(LogCat.IltStore, $"{_hubChar}'s ILT Hub data is copied; the Hub restarted on it."); + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, "migration retry"); } + } + + private void StopHub() + { + var hub = _hub; + _hub = null; + if (hub == null) return; + try { hub.OnLogout(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "logout"); } + } + + /// %APPDATA%\RynthCore\RynthILT\{world}\{character} (the bounty list's folder too). + internal static string CharacterFolder(string world, string charName) + => Path.Combine(SettingsRoot, SafeName(world.Length > 0 ? world : "UnknownWorld"), SafeName(charName)); + + // ── Bounties ───────────────────────────────────────────────────────────── + + /// Starts the tracker once the character's name is known (its save file is per character). + private void TryStartBounties() + { + long now = Environment.TickCount64; + if (now < _nextNameTryMs) return; + _nextNameTryMs = now + NameRetryMs; + + string file = BountyFilePath(out bool named); + if (!named && now - _loginAtMs < NameWaitMs) return; + if (!named) Host.Log("[RynthILT] Bounties: no character name; the list won't be saved this session."); + _bounties = new BountyTracker(SendCommand, ChatLine, Host.Log, file); + } + + private void SaveBounties() + { + try { _bounties?.Save(); } + catch (Exception ex) { Host.Log($"[RynthILT] Bounties: save failed: {ex.Message}"); } + } + + /// The tracker's only way to the server: one chat command (Host.InvokeChatParser). + private void SendCommand(string command) + { + if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command)) + throw new InvalidOperationException("the engine's chat parser is not available"); + } + + /// + /// %APPDATA%\RynthCore\RynthILT\{world}\{character}\bounties.json, or "" (no save file) while + /// the character's name is unknown. Both names are reduced to safe folder names. + /// + private string BountyFilePath(out bool named) + { + named = false; + uint me = Host.GetPlayerId(); + if (me == 0 || !Host.HasGetObjectName || !Host.TryGetObjectName(me, out string charName) + || string.IsNullOrWhiteSpace(charName)) + return string.Empty; + string world = Host.HasGetWorldName && Host.TryGetWorldName(out string w) && !string.IsNullOrWhiteSpace(w) + ? w : "UnknownWorld"; + named = true; + return Path.Combine(SettingsRoot, SafeName(world), SafeName(charName), BountyTracker.FileName); + } + + /// RynthILT's settings folder: %APPDATA%\RynthCore\RynthILT. + internal static string SettingsRoot => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthILT"); + + /// A name safe as one folder: invalid characters become '_', no leading/trailing dots or spaces, at most 64 chars. + internal static string SafeName(string name) + { + char[] invalid = Path.GetInvalidFileNameChars(); + var chars = name.Trim().ToCharArray(); + for (int i = 0; i < chars.Length; i++) + if (Array.IndexOf(invalid, chars[i]) >= 0 || chars[i] == '/' || chars[i] == '\\') chars[i] = '_'; + string s = new string(chars).Trim(' ', '.'); + if (s.Length > 64) s = s.Substring(0, 64).TrimEnd(' ', '.'); + return s.Length == 0 ? "_" : s; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/ServerInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/ServerInterface.cs new file mode 100644 index 0000000..fd8272d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/ServerInterface.cs @@ -0,0 +1,82 @@ +// ServerInterface.cs - RynthILT's side of the "RynthILT.Server" interface (Plugins/Shared/RynthIltServerApi.cs): +// the profile JSON other plugins read (RynthOracle's Quests qb list and feature list until 2026-10-21; +// RynthILT's own Quests section and settings window show them now): +// the Leaftide feature list with the server's state for each, and the server's fellowship rules. +// +// Restored 2026-10-16: this export was dropped when "RynthServer.Profile" (salvage / identity) was +// added, so Oracle still detected ILT via RynthCore but never received feature / qb / fellowship +// data from RynthILT. Hub + Data stay separate; this table is the feature-profile channel. +// +// The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never +// unloaded); after Release() it reports Version 0 and GetProfileJson answers 0. Before login there +// is no controller, so the profile is the not-ILT default (every feature unknown, retail fellowships). +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT; + +internal static unsafe class ServerInterface +{ + private static RynthIltServerApiV1* _table; + private static volatile bool _released; + + /// The profile before any login: not an ILT world, nothing known (built once). + private static readonly string NotLoggedInJson = + IltFeatureCatalog.BuildProfileJson(false, string.Empty, false, string.Empty, DateTime.MinValue, _ => IltTri.Unknown); + + /// The table for (, ), or 0 when it isn't ours. + public static IntPtr Query(string iface, uint version) + { + if (iface != RynthIltServerApiV1.InterfaceName || version < 1 || version > RynthIltServerApiV1.InterfaceVersion || _released) + return IntPtr.Zero; + if (_table == null) + { + var t = (RynthIltServerApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltServerApiV1)); + t->StructSize = (uint)sizeof(RynthIltServerApiV1); + t->GetProfileJson = &GetProfileJson; + t->Version = RynthIltServerApiV1.InterfaceVersion; + _table = t; + } + return (IntPtr)_table; + } + + /// Plugin shutdown: readers see Version 0 and re-query; GetProfileJson answers 0. + public static void Release() + { + _released = true; + if (_table != null) _table->Version = 0; + } + + /// The JSON to hand out now: the live controller's snapshot, or the not-logged-in default. + internal static string CurrentJson() + => (_released ? null : PluginExports.Runtime.Plugin?.Hub?.ProfileJson) ?? NotLoggedInJson; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetProfileJson(byte* buffer, int capacity) + { + try + { + if (_released) return 0; + return ProfileInterface.Write(CurrentJson(), buffer, capacity); + } + catch { return 0; } + } + + /// + /// Copies as NUL-terminated UTF-8 into the caller's buffer when it fits, + /// and returns its byte length either way (length >= capacity: too small, nothing written). + /// + internal static int Write(string json, byte* buffer, int capacity) + { + int length = Encoding.UTF8.GetByteCount(json); + if (buffer == null || capacity <= length) return length; + fixed (char* src = json) + Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity); + buffer[length] = 0; + return length; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthLeafDawn/RynthCore.Plugin.RynthLeafDawn.csproj b/Plugins/RynthCore.Plugin.RynthLeafDawn/RynthCore.Plugin.RynthLeafDawn.csproj new file mode 100644 index 0000000..7cba983 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLeafDawn/RynthCore.Plugin.RynthLeafDawn.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthLeafDawn + 0.1.0 + leafdawn + LeafDawn + leafdawn.hopto.org + LeafDawn + LeafDawn only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthLeafDawn/ServerData.cs b/Plugins/RynthCore.Plugin.RynthLeafDawn/ServerData.cs new file mode 100644 index 0000000..78e22f2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLeafDawn/ServerData.cs @@ -0,0 +1,22 @@ +// ServerData.cs - What is known about LeafDawn (RynthLeafDawn). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "A PVE Server thats goal is to mimic end of game retail. With some custom content", + Facts = new[] + { + "End-of-retail with some custom content.", + "Not the same server as Leafdawning.", + }, + Discord = "https://discord.gg/c2QUBPwPZF", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthLeafdawning/RynthCore.Plugin.RynthLeafdawning.csproj b/Plugins/RynthCore.Plugin.RynthLeafdawning/RynthCore.Plugin.RynthLeafdawning.csproj new file mode 100644 index 0000000..33d6188 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLeafdawning/RynthCore.Plugin.RynthLeafdawning.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthLeafdawning + 0.1.0 + leafdawning + Leafdawning + leafdawning.duckdns.org + Leafdawning + Leafdawning only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthLeafdawning/ServerData.cs b/Plugins/RynthCore.Plugin.RynthLeafdawning/ServerData.cs new file mode 100644 index 0000000..7114a19 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLeafdawning/ServerData.cs @@ -0,0 +1,24 @@ +// ServerData.cs - What is known about Leafdawning (RynthLeafdawning). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "A standard, no-frills PvE end-of-retail ACE Asheron's Call server. Runs on dedicated hardware with the ability " + + "to host a large number of players. Enforced 3 account limit.", + Facts = new[] + { + "Standard, no-frills end-of-retail.", + "Not the same server as LeafDawn.", + }, + AccountLimit = "3 accounts (enforced)", + Discord = "https://discord.gg/sQpDgAzSXB", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthLevistras/Resources/quests.levistras.csv b/Plugins/RynthCore.Plugin.RynthLevistras/Resources/quests.levistras.csv new file mode 100644 index 0000000..3650633 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLevistras/Resources/quests.levistras.csv @@ -0,0 +1,465 @@ +QuestFlag,Server,Verified Conquest,Verified Levistras,Quest,Url,Info,Hint,Repeatable +aaccacidaxepickup,Levistras,,Verified,Picked up an Acid Axe from Suntik,,,, +aaccacidaxeturnin,Levistras,,Verified,Turned in an Acid Axe to Omaro Nagate,,,, +aaccacidgreataxepickup,Levistras,,Verified,Picked up an Acid Greataxe from Suntik,,,, +aaccacidgreataxeturnin,Levistras,,Verified,Turned in an Acid Greataxe to Omaro Nagate,,,, +aaccacidspikedclubpickup,Levistras,,Verified,Picked up an Acid Spiked Club from Suntik,,,, +aaccacidspikedclubturnin,Levistras,,Verified,Turned in an Acid Spiked Club to Omaro Nagate,,,, +aaccacidtofunpickup,Levistras,,Verified,Picked up an Acid Tofun from Suntik,,,, +aaccacidtofunturnin,Levistras,,Verified,Turned in an Acid Tofun to Omaro Nagate,,,, +aaccancientarbalestpickup,Levistras,,Verified,Picked up the ancient Empyrean arbalest from the Mayoi Sewers,,,, +aaccancientbreastplatepickup,Levistras,,Verified,Picked up the ancient Empyrean breastplate from the Mayoi Sewers,,,, +aaccancientgauntletspickup,Levistras,,Verified,Picked up the ancient Empyrean breastplate from the Mayoi Sewers,,,, +aaccancientgirthpickup,Levistras,,Verified,Picked up the ancient Empyrean gauntlets from the Mayoi Sewers,,,, +aaccancientheaumepickup,Levistras,,Verified,Picked up the ancient Empyrean heaume from the Mayoi Sewers,,,, +aaccancientsleevespickup,Levistras,,Verified,Picked up the ancient Empyrean sleeves from the Mayoi Sewers,,,, +aaccancientsolleretspickup,Levistras,,Verified,Picked up the ancient Empyrean sollerets from the Mayoi Sewers,,,, +aaccbaronnuvilluskeypickup,Levistras,,Verified,Picked up Baron Nuvillus' key,,,, +aaccbaronslightningswordquest,Levistras,,Verified,Picked up the Baron's Lightning Long Sword,,,, +aaccbatteredleatherjournalpickup,Levistras,,Verified,Picked up Martine's battered leather journal from the Banderling Conquest Dungeon,,,, +aaccbranithsamuletpickup,Levistras,,Verified,Picked up Branith's amulet,,,, +aaccbranithsamuletturnin,Levistras,,Verified,Turned in Branith's amulet,,,, +aaccbranithsbracerspickup,Levistras,,Verified,Picked up Branith's bracers,,,, +aaccbranithsbracersturnin,Levistras,,Verified,Turned in Branith's bracers,,,, +aaccbranithsglovespickup,Levistras,,Verified,Picked up Branith's gloves,,,, +aaccbranithsglovesturnin,Levistras,,Verified,Turned in Branith's gloves,,,, +aaccbranithshoodpickup,Levistras,,Verified,Picked up Branith's hood,,,, +aaccbranithshoodturnin,Levistras,,Verified,Turned in Branith's hood,,,, +aaccbranithsleggingspickup,Levistras,,Verified,Picked up Branith's leggings,,,, +aaccbranithsleggingsturnin,Levistras,,Verified,Turned in Branith's leggings,,,, +aaccbranithsresearchnotesturnin,Levistras,,Verified,Turned in Branith's research notes,,,, +aaccbranithsshirtpickup,Levistras,,Verified,Picked up Branith's shirt,,,, +aaccbranithsshirtturnin,Levistras,,Verified,Turned in Branith's shirt,,,, +aaccbranithsshoespickup,Levistras,,Verified,Picked up Branith's shoes,,,, +aaccbranithsshoesturnin,Levistras,,Verified,Turned in Branith's shoes,,,, +aaccbranithsstaffpickup,Levistras,,Verified,Picked up Branith's staff,,,, +aaccbranithsstaffturnin,Levistras,,Verified,Turned in Branith's staff,,,, +aaccbrokenarmorpickup,Levistras,,Verified,Picked up a set of broken armor,,,, +aaccbrokenarmorturnin,Levistras,,Verified,Turned in a set of broken armor,,,, +aacccircletofthesummonerquest,Levistras,,Verified,Picked Up the Circlet of the Summoner,,,, +aacccoliercrossbowquest,Levistras,,Verified,Picked up a Colier Crossbow,,,, +aacccursedironstaffquest,Levistras,,Verified,Picked up the Cursed Iron Staff,,,, +aaccdaggeroftikolaquest,Levistras,,Verified,Picked Up the Dagger of Tikola,,,, +aaccdanshakisbelongingspickup,Levistras,,Verified,Picked up Dansha-Ki's belongings,,,, +aaccdanshakisbelongingsturnin,Levistras,,Verified,Turned in Dansha-Ki's belongings,,,, +aaccdrywitheredleatherboundjournalpickup,Levistras,,Verified,Picked up Martine's dry withered leather bound journal from the Mosswart Maze,,,, +aaccdulldaggerquest,Levistras,,Verified,Picked Up the Dull Dagger,,,, +aaccfierybatonquest,Levistras,,Verified,Picked Up the Fiery Baton,,,, +aaccfieryrobequest,Levistras,,Verified,Picked Up the Fiery Robe,,,, +aaccfieryshieldquest,Levistras,,Verified,Picked Up the Fiery Shield,,,, +aaccfrestemeraldpickup,Levistras,,Verified,Picked up Frest Greelving's emerald,,,, +aaccfrestplatterpickup,Levistras,,Verified,Picked up Frest Greelving's antique platter,,,, +aaccfrestshirtpickup,Levistras,,Verified,Picked up Frest Greelving's puffy shirt,,,, +aaccgiantcluboffirepickup,Levistras,,Verified,Picked up a Giant Club of Fire from a Banderling Pillager,,,, +aaccgiantcluboffireturnin,Levistras,,Verified,Turned in a Giant Club of Fire to Omaro Nagate,,,, +aaccglendenwooddungeontreasure,Levistras,,Verified,Picked up the treasure chest key for the Glenden Wood Dungeon,,,, +aaccgreenmirebootsquest,Levistras,,Verified,Picked Up Broken Green Mire Boots,,,, +aaccgreenmiregauntletsquest,Levistras,,Verified,Picked Up Broken Green Mire Gauntlets,,,, +aaccgreenmirekabutonquest,Levistras,,Verified,Picked Up Broken Green Mire Kabuton,,,, +aaccgreenmireleggingsquest,Levistras,,Verified,Picked Up Broken Green Mire Leggings,,,, +aaccgreenmiremagariyariquest,Levistras,,Verified,Picked Up Broken Green Mire Magari Yari,,,, +aaccgreenmireshieldquest,Levistras,,Verified,Picked Up Broken Green Mire Shield,,,, +aaccgreenmiresleevesquest,Levistras,,Verified,Picked Up Broken Green Mire Sleeves,,,, +aacchammeroflightningpickup,Levistras,,Verified,Picked up a Hammer of Lightning from the Bellig Tower Revenant,,,, +aacchammeroflightningturnin,Levistras,,Verified,Turned in a Hammer of Lightning to Omaro Nagate,,,, +aaccicenaginatapickup,Levistras,,Verified,Picked up an Ice Naginata from a Mosswart Mucker,,,, +aaccicenodachipickup,Levistras,,Verified,Picked up an Ice Nodachi from a Mosswart Mucker,,,, +aaccicetachipickup,Levistras,,Verified,Picked up an Ice Tachi from a Mosswart Mucker,,,, +aacciceyaripickup,Levistras,,Verified,Picked up an Ice Yari from a Mosswart Mucker,,,, +aaccjooffirepickup,Levistras,,Verified,Picked up a Jo of Fire from a Banderling Pillager,,,, +aaccjooffireturnin,Levistras,,Verified,Turned in a Jo of Fire to Omaro Nagate,,,, +aacclilithasbootspickup,Levistras,,Verified,Picked up Lilitha's Boots,,,, +aacclilithasbootsturnin,Levistras,,Verified,Turned in Lilitha's Boots,,,, +aacclilithasbowpickup,Levistras,,Verified,Picked up Lilitha's Bow,,,, +aacclilithasbowturnin,Levistras,,Verified,Turned in Lilitha's Bow,,,, +aacclilithascoatpickup,Levistras,,Verified,Picked up Lilitha's Coat,,,, +aacclilithascoatturnin,Levistras,,Verified,Turned in Lilitha's Coat,,,, +aacclilithasgauntletspickup,Levistras,,Verified,Picked up Lilitha's Gauntlets,,,, +aacclilithasgauntletsturnin,Levistras,,Verified,Turned in Lilitha's Gauntlets,,,, +aacclilithashelmpickup,Levistras,,Verified,Picked up Lilitha's Helm,,,, +aacclilithashelmturnin,Levistras,,Verified,Turned in Lilitha's Helm,,,, +aacclilithaspantspickup,Levistras,,Verified,Picked up Lilitha's Pants,,,, +aacclilithaspantsturnin,Levistras,,Verified,Turned in Lilitha's Pants,,,, +aacclilithasspearpickup,Levistras,,Verified,Picked up Lilitha's Spear,,,, +aacclilithasspearturnin,Levistras,,Verified,Turned in Lilitha's Spear,,,, +aacclilithastrinketpickup,Levistras,,Verified,Picked up Lilitha's Trinket,,,, +aacclilithastrinketturnin,Levistras,,Verified,Turned in Lilitha's Trinket,,,, +aaccmitequeensstaffpickup,Levistras,,Verified,Picked up the Mite Queen's staff,,,, +aaccmitequeensstaffturnin,Levistras,,Verified,Turned in the Mite Queen's staff,,,, +aaccmorningstaroflightningpickup,Levistras,,Verified,Picked up a Morning Star of Lightning from the Bellig Tower Revenant,,,, +aaccmorningstaroflightningturnin,Levistras,,Verified,Turned in a Morning Star of Lightning to Omaro Nagate,,,, +aaccnabutoffirepickup,Levistras,,Verified,Picked up a Nabut of Fire from a Banderling Pillager,,,, +aaccnabutoffireturnin,Levistras,,Verified,Turned in a Nabut of Fire to Omaro Nagate,,,, +aaccnaginataoffirepickup,Levistras,,Verified,Picked up a Naginata of Fire from a Banderling Plunderer,,,, +aaccnaginataoffireturnin,Levistras,,Verified,Turned in a Naginata of Fire to Omaro Nagate,,,, +aaccnuvillusbootsturnin,Levistras,,Verified,Turned in the Boots of Nuvillus to MacGyre,,,, +aaccnuvillusbowturnin,Levistras,,Verified,Turned in the Gelid Bow to MacGyre,,,, +aaccnuvillusbracersturnin,Levistras,,Verified,Turned in the Bracers of Nuvillus to MacGyre,,,, +aaccnuvilluscrownturnin,Levistras,,Verified,Turned in the Crown of Bone to MacGyre,,,, +aaccnuvillusgauntletsturnin,Levistras,,Verified,Turned in the Gauntlets of Nuvillus to MacGyre,,,, +aaccnuvillusleggingsturnin,Levistras,,Verified,Turned in the Leggings of Nuvillus to MacGyre,,,, +aaccnuvillussceptreturnin,Levistras,,Verified,Turned in the Gelid Sceptre to MacGyre,,,, +aaccnuvillusshieldturnin,Levistras,,Verified,Turned in the Gelid Shield to MacGyre,,,, +aaccnuvillusshirtturnin,Levistras,,Verified,Turned in the Shirt of Nuvillus to MacGyre,,,, +aaccnuvillussword2hturnin,Levistras,,Verified,Turned in the Great Blade of Ice to MacGyre,,,, +aaccnuvillusswordfwturnin,Levistras,,Verified,Turned in the Swift Blade of Ice to MacGyre,,,, +aaccnuvillusswordhwturnin,Levistras,,Verified,Turned in the Heavy Blade of Ice to MacGyre,,,, +aaccnuvillusswordlwturnin,Levistras,,Verified,Turned in the Light Blade of Ice to MacGyre,,,, +aaccpikeoffirepickup,Levistras,,Verified,Picked up a Pike of Fire from a Banderling Plunderer,,,, +aaccpikeoffireturnin,Levistras,,Verified,Turned in a Pike of Fire to Omaro Nagate,,,, +aaccquadrelleoflightningpickup,Levistras,,Verified,Picked up a Quadrelle of Lightning from the Bellig Tower Revenant,,,, +aaccquadrelleoflightningturnin,Levistras,,Verified,Turned in a Quadrelle of Lightning to Omaro Nagate,,,, +aaccquarterstaffoffirepickup,Levistras,,Verified,Picked up a Quarter Staff of Fire from a Banderling Pillager,,,, +aaccquarterstaffoffireturnin,Levistras,,Verified,Turned in a Quarter Staff of Fire to Omaro Nagate,,,, +aaccrobeoftikolaquest,Levistras,,Verified,Picked Up the Robe of Tikola,,,, +aaccsclavussummoningstonequest,Levistras,,Verified,Picked Up the Sclavus Summoning Stone,,,, +aaccsnakeskinglovesquest,Levistras,,Verified,Picked Up the Snake Skin Gloves,,,, +aaccspearoffirepickup,Levistras,,Verified,Picked up a Spear of Fire from a Banderling Plunderer,,,, +aaccspearoffireturnin,Levistras,,Verified,Turned in a Spear of Fire to Omaro Nagate,,,, +aaccstaffofnullificationpickup,Levistras,,Verified,Picked up the Staff of Nullification,,,, +aaccstaffofnullificationturnin,Levistras,,Verified,Turned in the Staff of Nullification,,,, +aaccsuperiorgauntletsquest,Levistras,,Verified,Picked Up the Superior Gauntlets,,,, +aaccsuperiorhelmquest,Levistras,,Verified,Picked Up the Superior Helm,,,, +aaccsuperiorscimitarquest,Levistras,,Verified,Picked Up the Superior Scimitar,,,, +aacctatteredursuinrugpickup,Levistras,,Verified,Picked up a tattered Ursuin rug,,,, +aacctatteredursuinrugturnin,Levistras,,Verified,Turned in a tattered Ursuin rug,,,, +aaccthieftrailkeymfkpickupquest,Levistras,,Verified,Picked Up Mana Forged Key,,,, +aaccthieftrailkeymfkturninquest,Levistras,,Verified,Turned in Mana Forged Key,,,, +aacctibrisamulicoatpickup,Levistras,,Verified,Picked up Tibri's Amuli Coat,,,, +aacctibrisamulicoatturnin,Levistras,,Verified,Turned in Tibri's Amuli Coat,,,, +aacctibrisamulileggingspickup,Levistras,,Verified,Picked up Tibri's Amuli Leggings,,,, +aacctibrisamulileggingsturnin,Levistras,,Verified,Turned in Tibri's Amuli Leggings,,,, +aacctibrisfirespearturnin,Levistras,,Verified,Turned in Tibri's Fire Spear,,,, +aacctibrisprotectivepantspickup,Levistras,,Verified,Picked up Tibri's Protective Pants,,,, +aacctibrisprotectivepantsturnin,Levistras,,Verified,Turned in Tibri's Protective Pants,,,, +aacctibrisprotectiveshirtpickup,Levistras,,Verified,Picked up Tibri's Protective Shirt,,,, +aacctibrisprotectiveshirtturnin,Levistras,,Verified,Turned in Tibri's Protective Shirt,,,, +aacctridentoffirepickup,Levistras,,Verified,Picked up a Trident of Fire from a Banderling Plunderer,,,, +aacctridentoffireturnin,Levistras,,Verified,Turned in a Trident of Fire to Omaro Nagate,,,, +aacctrothyrsbootspickup,Levistras,,Verified,Picked up Trothyr's Boots,,,, +aacctrothyrsbootsturnin,Levistras,,Verified,Turned in Trothyr's Boots to the Spirit of Trothyr,,,, +aacctrothyrscuirasspickup,Levistras,,Verified,Picked up Trothyr's Cuirass,,,, +aacctrothyrscuirassturnin,Levistras,,Verified,Turned in Trothyr's Cuirass to the Spirit of Trothyr,,,, +aacctrothyrsgauntletspickup,Levistras,,Verified,Picked up Trothyr's Gauntlets,,,, +aacctrothyrsgauntletsturnin,Levistras,,Verified,Turned in Trothyr's Gauntlets to the Spirit of Trothyr,,,, +aacctrothyrshammerpickup,Levistras,,Verified,Picked up Trothyr's War Hammer,,,, +aacctrothyrshammerturnin,Levistras,,Verified,Turned in Trothyr's War Hammer to the Spirit of Trothyr,,,, +aacctrothyrshelmpickup,Levistras,,Verified,Picked up Trothyr's Helm,,,, +aacctrothyrshelmturnin,Levistras,,Verified,Turned in Trothyr's Helm to the Spirit of Trothyr,,,, +aacctrothyrsleggingspickup,Levistras,,Verified,Picked up Trothyr's Leggings,,,, +aacctrothyrsleggingsturnin,Levistras,,Verified,Turned in Trothyr's Leggings to the Spirit of Trothyr,,,, +aacctrothyrsshieldpickup,Levistras,,Verified,Picked up Trothyr's Shield,,,, +aacctrothyrsshieldturnin,Levistras,,Verified,Turned in Trothyr's Shield to the Spirit of Trothyr,,,, +aacctrothyrssleevespickup,Levistras,,Verified,Picked up Trothyr's Sleeves,,,, +aacctrothyrssleevesturnin,Levistras,,Verified,Turned in Trothyr's Sleeves to the Spirit of Trothyr,,,, +aaccwarhammeroflightningpickup,Levistras,,Verified,Picked up a War Hammer of Lightning from the Bellig Tower Revenant,,,, +aaccwarhammeroflightningturnin,Levistras,,Verified,Turned in a War Hammer of Lightning to Omaro Nagate,,,, +aaccyuvuokisbelongingspickup,Levistras,,Verified,Picked up Yu Vuo-Ki's belongings,,,, +aaccyuvuokisbelongingsturnin,Levistras,,Verified,Turned in Yu Vuo-Ki's belongings,,,, +account_fireflycd1,Levistras,,Verified,Account Completed Firefly Tourney,,,, +account_fishingcd1,Levistras,,Verified,Account Completed Fishing Tourney,,,, +account_lecuseddrudgeslotmachine,Levistras,,Verified,Used the Drudge Slot Machine,,,, +account_nov24_turkey_event,Levistras,,Verified,Tossed some Pies,,,, +account_nov25_turkey_event,Levistras,,Verified,Tossed some Pies,,,, +account_pumpkin_patch_event,Levistras,,Verified,Pumpkin Patch Event,,,, +account_xmas_2022,Levistras,,Verified,Got Xmas 2022 reward,,,, +ambersharvested,Levistras,,Verified,Player has recently harvested Amber Crystal,,,, +apostatesparkling,Levistras,,Verified,Apostate Sparkling,,,, +attributegems1_gems_of_lowering_coordination_freebies,Levistras,,Verified,Gems of Lowering: Coordination Freebie,,,, +attributegems1_gems_of_lowering_endurance_freebies,Levistras,,Verified,Gems of Lowering: Endurance Freebie,,,, +attributegems1_gems_of_lowering_focus_freebies,Levistras,,Verified,Gems of Lowering: Focus Freebie,,,, +attributegems1_gems_of_lowering_quickness_freebies,Levistras,,Verified,Gems of Lowering: Quickness Freebie,,,, +attributegems1_gems_of_lowering_self_freebies,Levistras,,Verified,Gems of Lowering: Self Freebie,,,, +attributegems1_gems_of_lowering_strength_freebies,Levistras,,Verified,Gems of Lowering: Strength Freebie,,,, +bossingotseal,Levistras,,Verified,Boss Ingot Seal,,,, +catacombstempaccess,Levistras,,Verified,Player has temporary access to the Catacombs,,,, +completed_egk_reading,Levistras,,Verified,Completed aetheric resonance collection,,,, +cursed_bracelet,Levistras,,Verified,Looted cursed bracetlet,,,, +etsaloteaterjaw,Levistras,,Verified,Etsalot Jaw,,,, +etsaloteyelid,Levistras,,Verified,Etsalot eye lid,,,, +exarchfight,Levistras,,Verified,Exarch Fight,,,, +facesmukkircontractcomplete,Levistras,,Verified,Contract Completed for Faces of Mukkir quest,,,, +falatacottempleshortcut,Levistras,,Verified,Falatacot Temple Shortcut,,,, +firefly1_completed,Levistras,,Verified,Completed Fishing Tourney Second Place,,,, +firstcontact_firstcompletion,Levistras,,Verified,First completion of the First Contact quest,,,, +forgetfulnessgems_alchemy_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Alchemy 1,,,, +forgetfulnessgems_cooking_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Cooking 1,,,, +forgetfulnessgems_deception_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Deception 1,,,, +forgetfulnessgems_deception_gems_of_forgetfulness2,Levistras,,Verified,Gems of Forgetfulness: Deception 2,,,, +forgetfulnessgems_dirty_fighting_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Dirty Fighting 1,,,, +forgetfulnessgems_dirty_fighting_gems_of_forgetfulness2,Levistras,,Verified,Gems of Forgetfulness: Dirty Fighting 2,,,, +forgetfulnessgems_dual_wield_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Dual Wield 1,,,, +forgetfulnessgems_dual_wield_gems_of_forgetfulness2,Levistras,,Verified,Gems of Forgetfulness: Dual Wield 2,,,, +forgetfulnessgems_finesse_weapons_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Finesse Weapons 1,,,, +forgetfulnessgems_healing_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Healing 1,,,, +forgetfulnessgems_leadership_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Leadership 1,,,, +forgetfulnessgems_light_weapons_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Light Weapons 1,,,, +forgetfulnessgems_lockpick_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Lockpick 1,,,, +forgetfulnessgems_lockpick_gems_of_forgetfulness2,Levistras,,Verified,Gems of Forgetfulness: Lockpick 2,,,, +forgetfulnessgems_magic_defense_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Magic Defense 1,,,, +forgetfulnessgems_melee_defense_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Melee Defense 1,,,, +forgetfulnessgems_missile_defense_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Missile Defense 1,,,, +forgetfulnessgems_missile_weapons_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Missile Weapons 1,,,, +forgetfulnessgems_missile_weapons_gems_of_forgetfulness2,Levistras,,Verified,Gems of Forgetfulness: Missile Weapons 2,,,, +forgetfulnessgems_recklessness_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Recklessness 1,,,, +forgetfulnessgems_shield_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Shield 1,,,, +forgetfulnessgems_sneak_attack_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Sneak Attack 1,,,, +forgetfulnessgems_sneak_attack_gems_of_forgetfulness2,Levistras,,Verified,Gems of Forgetfulness: Sneak Attack 2,,,, +forgetfulnessgems_summoning_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Summoning 1,,,, +forgetfulnessgems_two_handed_gems_of_forgetfulness1,Levistras,,Verified,Gems of Forgetfulness: Two Handed 1,,,, +forgetfulness_alchemy_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Alchemy Cooldown,,,, +forgetfulness_cooking_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Cooking Cooldown,,,, +forgetfulness_deception_gems_of_forgetfulness13days,Levistras,,Verified,Gems of Forgetfulness: Deception Cooldown,,,, +forgetfulness_deception_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Deception Cooldown,,,, +forgetfulness_dirty_fighting_gems_of_forgetfulness13days,Levistras,,Verified,Gems of Forgetfulness: Dirty Fighting Cooldown,,,, +forgetfulness_dirty_fighting_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Dirty Fighting Cooldown,,,, +forgetfulness_dual_wield_gems_of_forgetfulness13days,Levistras,,Verified,Gems of Forgetfulness: Dual Wield Cooldown,,,, +forgetfulness_dual_wield_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Dual Wield Cooldown,,,, +forgetfulness_finesse_weapons_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Finesse Weapons Cooldown,,,, +forgetfulness_healing_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Healing Cooldown,,,, +forgetfulness_leadership_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Leadership Cooldown,,,, +forgetfulness_light_weapons_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Light Weapons Cooldown,,,, +forgetfulness_lockpick_gems_of_forgetfulness13days,Levistras,,Verified,Gems of Forgetfulness: Lockpick Cooldown,,,, +forgetfulness_lockpick_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Lockpick Cooldown,,,, +forgetfulness_magic_defense_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Magic Defense Cooldown,,,, +forgetfulness_melee_defense_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Melee Defense Cooldown,,,, +forgetfulness_missile_defense_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Missile Defense Cooldown,,,, +forgetfulness_missile_weapons_gems_of_forgetfulness13days,Levistras,,Verified,Gems of Forgetfulness: Missile Weapons Cooldown,,,, +forgetfulness_missile_weapons_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Missile Weapons Cooldown,,,, +forgetfulness_recklessness_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Recklessness Cooldown,,,, +forgetfulness_shield_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Shield Cooldown,,,, +forgetfulness_sneak_attack_gems_of_forgetfulness13days,Levistras,,Verified,Gems of Forgetfulness: Sneak Attack Cooldown,,,, +forgetfulness_sneak_attack_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Sneak Attack Cooldown,,,, +forgetfulness_summoning_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Summoning Cooldown,,,, +forgetfulness_two_handed_gems_of_forgetfulness6days,Levistras,,Verified,Gems of Forgetfulness: Two Handed Cooldown,,,, +forget_alchemy_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Alchemy Freebie,,,, +forget_arcane_lore_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Arcane Lore Freebie,,,, +forget_armor_tinkering_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Armor Tinkering Freebie,,,, +forget_assess_creature_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Assess Creature Freebie,,,, +forget_assess_person_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Assess Person Freebie,,,, +forget_cooking_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Cooking Freebie,,,, +forget_creature_enchantment_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Creature Enchantment Freebie,,,, +forget_deception_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Deception Freebie,,,, +forget_dirty_fighting_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Dirty Fighting Freebie,,,, +forget_dual_wield_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Dual Wield Freebie,,,, +forget_finesse_weapons_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Finesse Weapons Freebie,,,, +forget_fletching_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Fletching Freebie,,,, +forget_healing_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Healing Freebie,,,, +forget_heavy_weapons_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Heavy Weapons Freebie,,,, +forget_item_enchantment_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Item Enchantment Freebie,,,, +forget_item_tinkering_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Item Tinkering Freebie,,,, +forget_jump_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Jump Freebie,,,, +forget_leadership_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Leadership Freebie,,,, +forget_life_magic_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Life Magic Freebie,,,, +forget_light_weapons_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Light Weapons Freebie,,,, +forget_lockpick_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Lockpick Freebie,,,, +forget_loyalty_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Loyalty Freebie,,,, +forget_magic_defense_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Magic Defense Freebie,,,, +forget_magic_item_tinkering_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Magic Item Tinkering Freebie,,,, +forget_mana_conversion_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Mana Conversion Freebie,,,, +forget_melee_defense_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Melee Defense Freebie,,,, +forget_missile_defense_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Missile Defense Freebie,,,, +forget_missile_weapons_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Missile Weapons Freebie,,,, +forget_recklessness_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Recklessness Freebie,,,, +forget_run_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Run Freebie,,,, +forget_salvaging_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Salvaging Freebie,,,, +forget_shield_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Shield Freebie,,,, +forget_sneak_attack_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Sneak Attack Freebie,,,, +forget_summoning_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Summoning Freebie,,,, +forget_two_handed_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Two Handed Freebie,,,, +forget_void_magic_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Void Magic Freebie,,,, +forget_war_magic_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: War Magic Freebie,,,, +forget_weapon_tinkering_gems_of_forgetfulness_freebie,Levistras,,Verified,Gems of Forgetfulness: Weapon Tinkering Freebie,,,, +fortifiedpyrealingot,Levistras,,Verified,Fortified Pyreal Ingot,,,, +found_treasure,Levistras,,Verified,Completed Found_Treasure,,,, +frozenpresentpickuptimer,Levistras,,Verified,Picked up Frozen Present,,,, +gave_nether_stone_gkenpc,Levistras,,Verified,Turned in Shadownether stone to knox,,,, +gave_shivering_stone_gkenpc,Levistras,,Verified,Turned in shivering stone to knox,,,, +gave_smoldering_stone_gkenpc,Levistras,,Verified,Turned in smoldering stone to knox,,,, +gave_sparking_stone_gkenpc,Levistras,,Verified,Turned in sparking stone to knox,,,, +gave_stinging_stone_gkenpc,Levistras,,Verified,Turned in stinging stone to knox,,,, +golemmagmaexarch_kt,Levistras,,Verified,Magma Golem Exarch Kill Task,,,, +golemmagmaexarch_kt_wait,Levistras,,Verified,Magma Golem Exarch Kill Task Cooldown,,,, +greathallshortcut,Levistras,,Verified,Great Hall Shortcut,,,, +gregorscarefullyrolledscrollpickedup,Levistras,,Verified,Pickup timer for carefully rolled scroll,,,, +hearthseekerrecruitmentletter,Levistras,,Verified,Platinum Letter turned in,,,, +hotcoalpickuptimer,Levistras,,Verified,Picked up Hot Coal,,,, +impintedingotturnin,Levistras,,Verified,Imprinted Ingot Turn-In,,,, +lecobtainedaurochbackpack,Levistras,,Verified,Obtained the Explorer's Auroch Backpack,,,, +lecobtainedaurochtier1reward,Levistras,,Verified,Obtained the Auroch League tier 1 reward,,,, +lecobtainedaurochtier2reward,Levistras,,Verified,Obtained the Auroch League tier 2 reward,,,, +lecobtainedaurochtier3reward,Levistras,,Verified,Obtained the Auroch League tier 3 reward,,,, +lecobtainedaurochtier4reward,Levistras,,Verified,Obtained the Auroch League tier 4 reward,,,, +lecobtainedaurochtier5reward,Levistras,,Verified,Obtained the Auroch League tier 5 reward,,,, +lecobtainedcowboytitle,Levistras,,Verified,Obtained the Cowboy title,,,, +lecobtainedexplorerstowel,Levistras,,Verified,Obtained the Explorer's Towel,,,, +lecobtainedsaltandash,Levistras,,Verified,Obtained a free Black Page of Salt and Ash,,,, +lecusedpackdrudgeballoon,Levistras,,Verified,Used the Pack Drudge Balloon,,,, +legendaryquestsc,Levistras,,Verified,BitField Stamp for Legendary Quests Completed,,,, +lordbalthallfree,Levistras,,Verified,Spoke With Lord Balthall,,,, +ltfight,Levistras,,Verified,LT Fight,,,, +monsterplantseedturnin,Levistras,,Verified,Turned in the Monster Plant Seed Recently,,,, +monsterplantseedwait,Levistras,,Verified,Picked up the Monster Plant Seed Recently,,,, +nightclubticket,Levistras,,Verified,Night Club Ticket Picked up,,,, +notgreedy,Levistras,,Verified,Used the chest 5 times,,,, +nov24_pie_pickup,Levistras,,Verified,Completed Pie Pickup,,,, +nov24_still_have_pie,Levistras,,Verified,Completed Pie Pickup,,,, +nov25_pie_pickup,Levistras,,Verified,Completed Pie Pickup,,,, +nov25_still_have_pie,Levistras,,Verified,Completed Pie Pickup,,,, +obtainedcrestofthefalatacotlords,Levistras,,Verified,Picked up the Crest of the Falatacot Lords,,,, +obtainedcrownofmeqot,Levistras,,Verified,Picked up the Crown of Meqot,,,, +obtainedshardofthegreatwork,Levistras,,Verified,Picked up the Shard of The Greak Work,,,, +opened_a_map,Levistras,,Verified,Completed Opened_A_Map,,,, +pickedupcoloredegg,Levistras,,Verified,Picked up a Colored Egg,,,, +pickeduprottenegg,Levistras,,Verified,Picked up a Rotten Egg,,,, +pickedupumbralcruciblebase,Levistras,,Verified,Umbral Crucible Base Pickup,,,, +pickedupumbralcrucibletop,Levistras,,Verified,Umbral Crucible Top Pickup,,,, +pookytokenpickuptimer,Levistras,,Verified,Picked up Pooky Token,,,, +randomsalvagehighreward,Levistras,,Verified,Random high salvage quest,,,, +randomsalvagelowrewardtest,Levistras,,Verified,Random low salvage quest,,,, +randomsalvagemidreward,Levistras,,Verified,Random mid salvage quest,,,, +rawaug,Levistras,,Verified,Raw Aug Gem,,,, +recivedrewardstatue1-2,Levistras,,Verified,Used 1-2 statue,,,, +recivedrewardstatue2-3,Levistras,,Verified,Used 2-3 statue,,,, +recivedrewardstatue3-4,Levistras,,Verified,Used 3-4 statue,,,, +recivedrewardstatue4-5,Levistras,,Verified,Used 4-5 statue,,,, +recivedrewardstatue5-6,Levistras,,Verified,Used 5-6 statue,,,, +recivedrewardstatue6-7,Levistras,,Verified,Used 6-7 statue,,,, +redletterinprogress,Levistras,,Verified,Turn in Timer/Counter for Scarlet Red Letters,,,, +rqornatepyrealkey,Levistras,,Verified,RQ Ornate Pyreal Key,,,, +scav_hunt_feb_2007469blackfireatlanstone,Levistras,,Verified,Scavenger Hunt (Feb): Black Fire Atlan Stone,,,, +scav_hunt_feb_201029295blankaugmentationgem,Levistras,,Verified,Scavenger Hunt (Feb): Blank Augmentation Gem,,,, +scav_hunt_feb_201134583bonedagger,Levistras,,Verified,Scavenger Hunt (Feb): Bone Dagger,,,, +scav_hunt_feb_201328928burunsoakedsoulstone,Levistras,,Verified,Scavenger Hunt (Feb): Burun Soaked Soul Stone,,,, +scav_hunt_feb_20227807ancientdiamondidol,Levistras,,Verified,Scavenger Hunt (Feb): Ancient Diamond Idol,,,, +scav_hunt_feb_2038909bloodofthehopeslayer,Levistras,,Verified,Scavenger Hunt (Feb): Blood Of The Hopeslayer,,,, +scav_hunt_feb_204260cabbage,Levistras,,Verified,Scavenger Hunt (Feb): Cabbage,,,, +scav_hunt_feb_20541513pathwardentrinket,Levistras,,Verified,Scavenger Hunt (Feb): Pathwarden Trinket,,,, +scav_hunt_feb_20632274moarsmuck,Levistras,,Verified,Scavenger Hunt (Feb): Moarsmuck,,,, +scav_hunt_feb_2075768poofysnowball,Levistras,,Verified,Scavenger Hunt (Feb): Poofy Snowball,,,, +scav_hunt_feb_20822620carvedtuskerstatue,Levistras,,Verified,Scavenger Hunt (Feb): Carved Tusker Statue,,,, +scav_hunt_feb_20935876coruscatingolthoiscentgland,Levistras,,Verified,Scavenger Hunt (Feb): Coruscating Olthoi Scent Gland,,,, +scav_hunt_jul_10759muddytowel,Levistras,,Verified,Scavenger Hunt (Jul): Muddy Towel,,,, +scav_hunt_jul_11710writofrefuge,Levistras,,Verified,Scavenger Hunt (Jul): Writ Of Refuge,,,, +scav_hunt_jul_22578bunchofnanners,Levistras,,Verified,Scavenger Hunt (Jul): Bunch Of Nanners,,,, +scav_hunt_jul_262chicken,Levistras,,Verified,Scavenger Hunt (Jul): Chicken,,,, +scav_hunt_jul_273apyreal,Levistras,,Verified,Scavenger Hunt (Jul): A Pyreal,,,, +scav_hunt_jul_32036goldniffistentacle,Levistras,,Verified,Scavenger Hunt (Jul): Gold Niffis Tentacle,,,, +scav_hunt_jul_32484ahugelumpofcoal,Levistras,,Verified,Scavenger Hunt (Jul): A Huge Lump Of Coal,,,, +scav_hunt_jul_42710alignedmanastone,Levistras,,Verified,Scavenger Hunt (Jul): Aligned Mana Stone,,,, +scav_hunt_jul_44240a'nekshaytoken,Levistras,,Verified,Scavenger Hunt (Jul): A'nekshay Token,,,, +scav_hunt_jul_516peerlesslockpick,Levistras,,Verified,Scavenger Hunt (Jul): Peerless Lockpick,,,, +scav_hunt_jul_5758carrot,Levistras,,Verified,Scavenger Hunt (Jul): Carrot,,,, +scav_hunt_jul_6126majorstingingstone,Levistras,,Verified,Scavenger Hunt (Jul): Major Stinging Stone,,,, +scav_hunt_jul_70051bloodmouthmaw,Levistras,,Verified,Scavenger Hunt (Jul): Bloodmouth Maw,,,, +scav_hunt_jul_800050scavengerhuntbook,Levistras,,Verified,Scavenger Hunt (Jul): Scavenger Hunt Book,,,, +scav_hunt_oct120259bread,Levistras,,Verified,Scavenger Hunt (Oct): Bread,,,, +scav_hunt_oct12107429aerlinthemonarchshirt,Levistras,,Verified,Scavenger Hunt (Oct): Aerlinthe Monarch Shirt,,,, +scav_hunt_oct12118425idolgem,Levistras,,Verified,Scavenger Hunt (Oct): Idol Gem,,,, +scav_hunt_oct12122024fullmu-miyahguise,Levistras,,Verified,Scavenger Hunt (Oct): Full Mu Miyah Guise,,,, +scav_hunt_oct121246423stipend,Levistras,,Verified,Scavenger Hunt (Oct): Stipend,,,, +scav_hunt_oct121320631prismatictaper,Levistras,,Verified,Scavenger Hunt (Oct): Prismatic Taper,,,, +scav_hunt_oct12528738half-digestedvirindimask,Levistras,,Verified,Scavenger Hunt (Oct): Half Digested Virindi Mask,,,, +scav_hunt_oct126265meat,Levistras,,Verified,Scavenger Hunt (Oct): Meat,,,, +scav_hunt_oct12832511shieldofyanshi,Levistras,,Verified,Scavenger Hunt (Oct): Shield Of Yanshi,,,, +scav_hunt_oct1299511goldengromnie,Levistras,,Verified,Scavenger Hunt (Oct): Golden Gromnie,,,, +scav_hunt_oct_209295intricatecarvingtool,Levistras,,Verified,Scavenger Hunt (Oct): Intricate Carving Tool,,,, +scav_hunt_oct_2102463milk,Levistras,,Verified,Scavenger Hunt (Oct): Milk,,,, +scav_hunt_oct_2116624shadowfragment,Levistras,,Verified,Scavenger Hunt (Oct): Shadow Fragment,,,, +scav_hunt_oct_21222614treasure,Levistras,,Verified,Scavenger Hunt (Oct): Treasure,,,, +scav_hunt_oct_225670temptingapple,Levistras,,Verified,Scavenger Hunt (Oct): Tempting Apple,,,, +scav_hunt_oct_231451specialcheese,Levistras,,Verified,Scavenger Hunt (Oct): Special Cheese,,,, +scav_hunt_oct_2406353pyrealmote,Levistras,,Verified,Scavenger Hunt (Oct): Pyreal Mote,,,, +scav_hunt_oct_241038456manaforgekey,Levistras,,Verified,Scavenger Hunt (Oct): Mana Forge Key,,,, +scav_hunt_oct_2411300050brasslootsack,Levistras,,Verified,Scavenger Hunt (Oct): Brass Loot Sack,,,, +scav_hunt_oct_24127581chorizite,Levistras,,Verified,Scavenger Hunt (Oct): Chorizite,,,, +scav_hunt_oct_2433965tippedpackcow,Levistras,,Verified,Scavenger Hunt (Oct): Tipped Pack Cow,,,, +scav_hunt_oct_2434751mortarandpestle,Levistras,,Verified,Scavenger Hunt (Oct): Mortar And Pestle,,,, +scav_hunt_oct_24430480antiquemug,Levistras,,Verified,Scavenger Hunt (Oct): Antique Mug,,,, +scav_hunt_oct_24612689diamondpowder,Levistras,,Verified,Scavenger Hunt (Oct): Diamond Powder,,,, +scav_hunt_oct_24749485encapsulatedspirit,Levistras,,Verified,Scavenger Hunt (Oct): Encapsulated Spirit,,,, +scav_hunt_oct_24811018brokenpyrealbell,Levistras,,Verified,Scavenger Hunt (Oct): Broken Pyreal Bell,,,, +scav_hunt_oct_2523328elaboratefieldrations,Levistras,,Verified,Scavenger Hunt (Oct): Elaborate Field Rations,,,, +scav_hunt_oct_265126bottleofwater,Levistras,,Verified,Scavenger Hunt (Oct): Bottle Of Water,,,, +scav_hunt_oct_2727439coffin,Levistras,,Verified,Scavenger Hunt (Oct): Coffin,,,, +scav_hunt_oct_2822117evilcouch,Levistras,,Verified,Scavenger Hunt (Oct): Evil Couch,,,, +scav_hunt_oct_2930983snowlily,Levistras,,Verified,Scavenger Hunt (Oct): Snow Lily,,,, +summonmasterychange,Levistras,,Verified,Changed Summoning Mastery,,,, +tourneydelay,Levistras,,Verified,Tourney delay,,,, +tourneyfishing1_completed,Levistras,,Verified,Completed Fishing Tourney,,,, +tourneyfishing2_completed,Levistras,,Verified,Completed Fishing Tourney,,,, +turgoscorepickup,Levistras,,Verified,Turgo Score Pickup,,,, +twinedlinen_gke,Levistras,,Verified,Gave Linen,,,, +uberbsdalchemistessence,Levistras,,Verified,Uber BSD Alchemist Essence looted,,,, +uberbsdalchemistjewel,Levistras,,Verified,Uber BSD Alchemist Jewel looted,,,, +uberbsdarbrimsnote,Levistras,,Verified,Arbrims Note has been picked up,,,, +uberbsdboss1loot1received,Levistras,,Verified,Uber BSD Boss1 Loot1 Received,,,, +uberbsdboss1loot2received,Levistras,,Verified,Uber BSD Boss1 Loot2 Received,,,, +uberbsdboss2loot1received,Levistras,,Verified,Uber BSD Boss2 Loot1 Received,,,, +uberbsdboss2loot2received,Levistras,,Verified,Uber BSD Boss2 Loot2 Received,,,, +uberbsdboss3loot1received,Levistras,,Verified,Uber BSD Boss3 Loot1 Received,,,, +uberbsdboss3loot2received,Levistras,,Verified,Uber BSD Boss3 Loot2 Received,,,, +uberbsdboss4loot1received,Levistras,,Verified,Uber BSD Boss4 Loot1 Received,,,, +uberbsdboss4loot2received,Levistras,,Verified,Uber BSD Boss4 Loot2 Received,,,, +uberbsdboss4pyrealshardreceived,Levistras,,Verified,Uber BSD Boss4 Pyreal Shard Received,,,, +uberbsdeastwingcachekey,Levistras,,Verified,Uber BSD East Wing Cache Key looted,,,, +uberbsdeastwingcachereceived,Levistras,,Verified,Uber BSD East Wing Loot Received,,,, +uberbsdflaggedtoenter,Levistras,,Verified,Flagged to enter Uber BSD,,,, +uberbsdgatekeeperessence,Levistras,,Verified,Uber BSD Gatekeeper Essence looted,,,, +uberbsdgatekeeperjewel,Levistras,,Verified,Uber BSD Gatekeeper Jewel looted,,,, +uberbsdglowingpyrealshard,Levistras,,Verified,Uber BSD Glowing Pyreal Shard looted,,,, +uberbsdobliteratorheart,Levistras,,Verified,Uber BSD Black Spawn Obliterator Heart looted,,,, +uberbsdobliteratorheartreceived,Levistras,,Verified,Uber BSD Obliterator's Heart Received,,,, +uberbsdoverseeressence,Levistras,,Verified,Uber BSD Inquisitor Essence looted,,,, +uberbsdoverseerjewel,Levistras,,Verified,Uber BSD Inquisitor Jewel looted,,,, +uberbsdquartermasteressence,Levistras,,Verified,Uber BSD Quartermaster Essence looted,,,, +uberbsdquartermasterjewel,Levistras,,Verified,Uber BSD Quartermaster Jewel looted,,,, +uberbsdquartermasterkey,Levistras,,Verified,Uber BSD Quartermaster Key looted,,,, +uberbsdtheodolitemanareading,Levistras,,Verified,Turned in the charged mana stone,,,, +uberbsdvirindiweaponreceived,Levistras,,Verified,Uber BSD Virindi Weapon Received,,,, +uberbsdwardorb,Levistras,,Verified,Arbrims Note has been picked up,,,, +uberbsdwestwingcachereceived,Levistras,,Verified,Uber BSD West Wing Loot Received,,,, +ubermetosbezoar,Levistras,,Verified,Player picked up Pit Beast Bezoar,,,, +ubermetosburning,Levistras,,Verified,Player picked up Burning Bone,,,, +ubermetoscrumbs,Levistras,,Verified,Player picked up Rockbiters Crumbs,,,, +ubermetosfingerbone,Levistras,,Verified,Player picked up Expedition Leader's Fingerbone,,,, +ubermetosloveletter,Levistras,,Verified,Player received Sir Alfric's Love Letter,,,, +ubermetosmagnetite,Levistras,,Verified,Player picked up Magnetite,,,, +ubermetossand,Levistras,,Verified,Player picked up Devil's Sand,,,, +ubermetossliver,Levistras,,Verified,Player picked up Corrupted Sliver,,,, +ubermetossouls,Levistras,,Verified,Liberated Souls of lost adventurers have come to your aid,,,, +ubermetostears,Levistras,,Verified,Player picked up Tears of Metos,,,, +ubermetostemp60,Levistras,,Verified,Uber Metos: 60-Second Timer,,,, +ubermetosveins,Levistras,,Verified,Player picked up Veins of Nergul,,,, +usedginsarc,Levistras,,Verified,Used Gins Arc,,,, +usedhirasarc,Levistras,,Verified,Used Hiras Arc,,,, +usedinfilsarc,Levistras,,Verified,Used Infils Arc,,,, +usedskimsarc,Levistras,,Verified,Used Skims Arc,,,, +used_leg_chest,Levistras,,Verified,Used the chest 5 times,,,, +used_mp_50_board,Levistras,,Verified,Used Market Place 50 quest board,,,, +used_mp_60_board,Levistras,,Verified,Used Market Place 60 quest board,,,, +used_mp_70_board,Levistras,,Verified,Used Market Place 70 quest board,,,, +used_mp_80_board,Levistras,,Verified,Used Market Place 80 quest board,,,, +used_mp_90_board,Levistras,,Verified,Used Market Place 90 quest board,,,, +viss_bug_collection1_complete,Levistras,,Verified,Completed Viss Bug Collection1 Complete,,,, +weaponrefundcanfieldcleaver,Levistras,,Verified,Weapon Refund: Canfield Cleaver,,,, +weaponrefundchitincracker,Levistras,,Verified,Weapon Refund: Chitin Cracker,,,, +weaponrefundcountrenarisequalizer,Levistras,,Verified,Weapon Refund: Count Renari's Equalizer,,,, +weaponrefunddartflicker,Levistras,,Verified,Weapon Refund: Dart Flicker,,,, +weaponrefunddriftersatlatl,Levistras,,Verified,Weapon Refund: Drifter's Atlatl,,,, +weaponrefundheartofdarkestflame,Levistras,,Verified,Weapon Refund: Heart of Darkest Flame,,,, +weaponrefunditakasnaginata,Levistras,,Verified,Weapon Refund: Itaka's Naginata,,,, +weaponrefundmorrigansvanity,Levistras,,Verified,Weapon Refund: Morrigan's Vanity,,,, +weaponrefundpillaroffearlessness,Levistras,,Verified,Weapon Refund: Pillar of Fearlessness,,,, +weaponrefundrevenantsscythe,Levistras,,Verified,Weapon Refund: Revenant's Scythe,,,, +weaponrefundridgebackdagger,Levistras,,Verified,Weapon Refund: Ridgeback Dagger,,,, +weaponrefundsmite,Levistras,,Verified,Weapon Refund: Smite,,,, +weaponrefundspearoflosttruths,Levistras,,Verified,Weapon Refund: Spear of Lost Truths,,,, +weaponrefundstaffofallaspects,Levistras,,Verified,Weapon Refund: Staff of All Aspects,,,, +weaponrefundstaffoftendrils,Levistras,,Verified,Weapon Refund: Staff of Tendrils,,,, +weaponrefundsubjugator,Levistras,,Verified,Weapon Refund: Subjugator,,,, +weeklyhighgradeturnedin100,Levistras,,Verified,100 High Grade Pyreal turned in,,,, +winthurasgardenpermflag,Levistras,,Verified,Character is flagged to enter Winthuras Gardens,,,, +wr_portal_access,Levistras,,Verified,Warrior's Rest: Portal Access,,,, +wr_portal_fragment,Levistras,,Verified,Warrior's Rest: Portal Fragment,,,, +wr_turn_in_complete,Levistras,,Verified,Warrior's Rest: Turn-In Complete,,,, diff --git a/Plugins/RynthCore.Plugin.RynthLevistras/RynthCore.Plugin.RynthLevistras.csproj b/Plugins/RynthCore.Plugin.RynthLevistras/RynthCore.Plugin.RynthLevistras.csproj new file mode 100644 index 0000000..eb0db33 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLevistras/RynthCore.Plugin.RynthLevistras.csproj @@ -0,0 +1,24 @@ + + + + + RynthCore.Plugin.RynthLevistras + 0.1.0 + levistras + Levistras + levistras.acportalstorm.com + Levistras + Levistras only: the server card (rules, account limits, botting policy, account setup) in the Mini Remote, and Levistras's quests in RynthOracle. + + + + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthLevistras/ServerData.cs b/Plugins/RynthCore.Plugin.RynthLevistras/ServerData.cs new file mode 100644 index 0000000..2325b1b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLevistras/ServerData.cs @@ -0,0 +1,24 @@ +// ServerData.cs - What is known about Levistras (RynthLevistras). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Summary = "Botting-free PvE server (automation is not allowed). 2 account limit.", + Facts = new[] + { + "Botting-free: automation is not allowed.", + "2 account limit.", + "Its quest pack (quests.levistras.csv, Levistras's own quests) shows in RynthOracle's Quests tab.", + }, + AccountLimit = "2 accounts", + Botting = BottingPolicy.Forbidden, + BottingNote = "automation is not allowed", + Source = "RynthCore's launcher server list (KnownServerCatalog.cs), checked 2026-10-21", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthLevistras/THIRD_PARTY_NOTICES.md b/Plugins/RynthCore.Plugin.RynthLevistras/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..094793d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthLevistras/THIRD_PARTY_NOTICES.md @@ -0,0 +1,39 @@ +# Third-party notices: RynthLevistras + +RynthLevistras's quest pack (`Resources/quests.levistras.csv`, offered to RynthOracle's Quests tab +through "RynthServer.QuestPack") is **Oracle of Dereth**'s Levistras rows: the master quest list of +that Decal plugin for Asheron's Call by **Advis Eveldan** (GitHub: +[advis61](https://github.com/advis61/OracleOfDereth)), split by its own Server column. The rows +were part of RynthOracle until 2026-10-21 and moved here, with the server they belong to. +Thank you, Advis! + +- Upstream: https://github.com/advis61/OracleOfDereth +- Taken from commit `ee618c6847b98b656a47ca87cc347441d206c547` (2026-10-01, version 2.3.0); the + lines themselves are unchanged. +- Licence: MIT. The upstream README states "License: MIT". The repository has no separate + LICENSE file and names no copyright line, so the standard MIT text is reproduced below + with the author and the years of the repository's history. + +--- + +MIT License + +Copyright (c) 2024-2026 Advis Eveldan (GitHub: advis61) and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Plugins/RynthCore.Plugin.RynthPortalStorm/RynthCore.Plugin.RynthPortalStorm.csproj b/Plugins/RynthCore.Plugin.RynthPortalStorm/RynthCore.Plugin.RynthPortalStorm.csproj new file mode 100644 index 0000000..e4e0182 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthPortalStorm/RynthCore.Plugin.RynthPortalStorm.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthPortalStorm + 0.1.0 + portalstorm + PortalStorm + ac.portalstorm.us.com + PortalStorm|Portal Storm + PortalStorm only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthPortalStorm/ServerData.cs b/Plugins/RynthCore.Plugin.RynthPortalStorm/ServerData.cs new file mode 100644 index 0000000..164b6ce --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthPortalStorm/ServerData.cs @@ -0,0 +1,26 @@ +// ServerData.cs - What is known about PortalStorm (RynthPortalStorm). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + // Not the usual 9000. + Port = 9020, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "15 Tiers, 10 Enlightenments, Infinite Lum Augs, Optional Hard Mode, Custom Skills, Years of custom content.", + Facts = new[] + { + "15 loot tiers.", + "10 enlightenments and infinite luminance augmentations.", + "Optional hard mode.", + "Custom skills and years of custom content.", + "Connects on port 9020, not 9000.", + }, + Discord = "https://discord.gg/YeX6mupcf", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthReefcull/RynthCore.Plugin.RynthReefcull.csproj b/Plugins/RynthCore.Plugin.RynthReefcull/RynthCore.Plugin.RynthReefcull.csproj new file mode 100644 index 0000000..0c7e1ef --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthReefcull/RynthCore.Plugin.RynthReefcull.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthReefcull + 0.1.0 + reefcull + Reefcull + reefcull.gdleac.com + Reefcull + Reefcull only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthReefcull/ServerData.cs b/Plugins/RynthCore.Plugin.RynthReefcull/ServerData.cs new file mode 100644 index 0000000..16ad01a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthReefcull/ServerData.cs @@ -0,0 +1,21 @@ +// ServerData.cs - What is known about Reefcull (RynthReefcull). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "GDLE", + Ruleset = "PvE", + Status = "Stable", + Summary = "A PVE Server thats goal is to mimic end of game retail.", + Facts = new[] + { + "End-of-retail experience on GDLE (not ACE): set the launcher's emulator to Gdle.", + }, + Discord = "https://discord.gg/3ngsm6e", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthSundering/RynthCore.Plugin.RynthSundering.csproj b/Plugins/RynthCore.Plugin.RynthSundering/RynthCore.Plugin.RynthSundering.csproj new file mode 100644 index 0000000..e6a833d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSundering/RynthCore.Plugin.RynthSundering.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthSundering + 0.1.0 + sundering + Sundering + ace.sunderingac.com + Sundering|The Sundering + Sundering only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthSundering/ServerData.cs b/Plugins/RynthCore.Plugin.RynthSundering/ServerData.cs new file mode 100644 index 0000000..4396287 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthSundering/ServerData.cs @@ -0,0 +1,25 @@ +// ServerData.cs - What is known about Sundering (RynthSundering). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "The Sundering is a 3 active character limit, PVE server targeting an End of Retail feel with convenience " + + "modifications, custom content, and pre-planned weekend/weekday bonuses.", + Facts = new[] + { + "End-of-retail feel with convenience changes and custom content.", + "Planned weekend and weekday bonuses.", + }, + AccountLimit = "3 active characters", + Discord = "https://discord.gg/XgHpcVbmJA", + Website = "https://sunderingac.com", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthThistlecrown/RynthCore.Plugin.RynthThistlecrown.csproj b/Plugins/RynthCore.Plugin.RynthThistlecrown/RynthCore.Plugin.RynthThistlecrown.csproj new file mode 100644 index 0000000..1bbcd5f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThistlecrown/RynthCore.Plugin.RynthThistlecrown.csproj @@ -0,0 +1,17 @@ + + + + + RynthCore.Plugin.RynthThistlecrown + 0.1.0 + thistlecrown + Thistlecrown + thistlecrown.ddns.net + Thistlecrown + Thistlecrown only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthThistlecrown/ServerData.cs b/Plugins/RynthCore.Plugin.RynthThistlecrown/ServerData.cs new file mode 100644 index 0000000..13a10f7 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThistlecrown/ServerData.cs @@ -0,0 +1,19 @@ +// ServerData.cs - What is known about Thistlecrown (RynthThistlecrown). Identity (id, hosts, world names) is in the csproj. +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerData +{ + public static ServerPackInfo Create() => + new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) + { + Port = 9000, + Emulator = "ACE", + Ruleset = "PvE", + Status = "Stable", + Summary = "Everyone welcome! 3 account limit. Recreation of TD.", + Facts = new[] { "A recreation of the retail Thistledown (TD) server." }, + AccountLimit = "3 accounts", + Discord = "https://discord.gg/uhZ3hn7", + Source = "public AC server list (acresources/serverslist), checked 2026-10-13", + }; +} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthThreads/PluginExports.cs new file mode 100644 index 0000000..44f0fc7 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThreads/PluginExports.cs @@ -0,0 +1,55 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthThreads; + +/// +/// C ABI exports. Nothing may throw out of an [UnmanagedCallersOnly] method (it would take +/// acclient.exe down): every export goes through RynthPluginRuntime, which catches and logs. +/// The window goes through the engine's script windows (host calls from the plugin's own tick), +/// so there is no render callback. +/// +public static unsafe class PluginExports +{ + private static readonly RynthPluginRuntime Runtime = new(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Shutdown() => Runtime.Shutdown(); + + // UTF-8 literals live in the module's read-only data: nothing to allocate or free. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetName() => LiteralPointer("RynthThreads"u8); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8); + + private static IntPtr LiteralPointer(ReadOnlySpan literal) + { + fixed (byte* p = literal) + return (IntPtr)p; + } + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Tick() => Runtime.OnTick(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnLoginComplete() => Runtime.OnLoginComplete(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnLogout() => Runtime.OnLogout(); + + // The Fragment Press lines (read only; nothing is eaten). + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) + => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); + + // "/rthreads ..." commands. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag); +} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/RynthCore.Plugin.RynthThreads.csproj b/Plugins/RynthCore.Plugin.RynthThreads/RynthCore.Plugin.RynthThreads.csproj new file mode 100644 index 0000000..27c9213 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThreads/RynthCore.Plugin.RynthThreads.csproj @@ -0,0 +1,40 @@ + + + + + + net10.0-windows + x86 + win-x86 + Library + true + enable + true + Shared + true + Size + false + RynthCore.Plugin.RynthThreads + RynthCore.Plugin.RynthThreads + x86 + + 66 + DreamWeave only: records Fragment Press results and shows the odds of each modifier per component. + + + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthThreads/RynthThreadsPlugin.cs b/Plugins/RynthCore.Plugin.RynthThreads/RynthThreadsPlugin.cs new file mode 100644 index 0000000..12ae818 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThreads/RynthThreadsPlugin.cs @@ -0,0 +1,334 @@ +// RynthThreadsPlugin.cs - DreamWeave's "Threads" gem crafting: records every Fragment Press result +// from chat and shows the odds of each modifier with each component (DreamWeave components give a +// chance of each modifier, not a fixed one). +// +// Active only on DreamWeave (the world name contains "DreamWeave"); anywhere else it reads nothing, +// shows no window and only answers /rthreads to say so. Presses go to one file shared by every +// character and client on the PC (Threads/PressStore.cs); the window shows what the inference +// (Threads/PressInference.cs) makes of all of them. +// +// Threads: OnTick, OnChatWindowText and login/logout run on the plugin pump. OnChatBarEnter may run +// on AC's main thread, so it only queues the command. +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; +using RynthCore.Plugin.RynthThreads.Threads; +using RynthCore.Plugin.RynthThreads.Ui; +using RynthCore.Plugin.RynthThreads.Views; +using RynthCore.PluginCore; + +namespace RynthCore.Plugin.RynthThreads; + +public sealed class RynthThreadsPlugin : RynthPluginBase +{ + public const string Version = "0.1.0"; + private const string Command = "/rthreads"; + private const long IdentityRetryMs = 1_000; + /// Wait this long after login for the character's name before recording without it. + private const long NameWaitMs = 30_000; + /// How often the shared file is checked for other clients' presses. + private const long PollMs = 2_000; + private const long PassIntervalMs = 5_000; + + private readonly PressParser _parser = new(); + private readonly UiHost _ui = new(); + private readonly ConcurrentQueue _commands = new(); + private PressStore? _store; + private UiWindow? _window; + private ThreadsPanel? _panel; + private ThreadsReport? _report; + private int _reportVersion = -1; + + private bool _inWorld; + private bool _checked; // the world is known (DreamWeave or not) + private bool _active; // on DreamWeave: reading chat, showing the window + private long _loginAtMs; + private long _nextIdentityTryMs; + private long _nextPollMs; + private string _world = string.Empty; + private string _character = string.Empty; + private bool _noUiLogged; + + public override int Initialize() + { + _ui.Log = msg => Host.Log(msg); + _panel = new ThreadsPanel + { + Report = CurrentReport, + Presses = () => _store?.Presses ?? (IReadOnlyList)Array.Empty(), + Export = Export, + Notice = Notice, + }; + _window = _ui.Add(new UiWindow("RynthThreads/Main", "RynthThreads") + { + DefaultWidth = 440f, DefaultHeight = 480f, MinWidth = 320f, MinHeight = 220f, + }); + Host.Log($"[RynthThreads] {Version} initialized (DreamWeave only). {Command} shows or hides the window; {Command} stats|export."); + return 0; + } + + /// True for DreamWeave's world name (any case, any decoration around it). + internal static bool IsDreamWeave(string? world) => + !string.IsNullOrEmpty(world) && world.IndexOf("DreamWeave", StringComparison.OrdinalIgnoreCase) >= 0; + + // The engine calls this on a real login and on a freshly (re)loaded plugin already in game. + public override void OnLoginComplete() + { + _inWorld = true; + _checked = false; + _active = false; + _character = string.Empty; + _loginAtMs = Environment.TickCount64; + _nextIdentityTryMs = _loginAtMs; + } + + public override void OnLogout() + { + SaveFinished(_parser.Flush("logout")); + _inWorld = false; + _checked = false; + _active = false; + if (_window != null) { _window.Visible = false; _window.NeedsPass = true; } + _ui.SubmitEmpty(Host); + } + + // Plugin unload (hot reload, update, client closing): keep a half-read press. + public override void Shutdown() + { + SaveFinished(_parser.Flush("logout")); + _store?.FlushPending(); + _ui.SubmitEmpty(Host); + } + + public override void OnChatWindowText(string? text, int chatType, ref int eat) + { + if (!_active || string.IsNullOrEmpty(text)) return; + List? done = _parser.Feed(text, Environment.TickCount64); + if (done == null) return; + foreach (Press p in done) SaveFinished(p); + } + + // May run on AC's thread: classify and queue only. + public override void OnChatBarEnter(string? text, ref int eat) + { + if (string.IsNullOrWhiteSpace(text)) return; + string t = text.Trim(); + if (!t.StartsWith(Command, StringComparison.OrdinalIgnoreCase) + || (t.Length > Command.Length && !char.IsWhiteSpace(t[Command.Length]))) + return; + eat = 1; + _commands.Enqueue(t.Substring(Command.Length).Trim()); + } + + public override void OnTick() + { + long now = Environment.TickCount64; + while (_commands.TryDequeue(out string? cmd)) RunCommand(cmd); + if (_inWorld && !_checked && now >= _nextIdentityTryMs) TryIdentify(now); + if (!_active || _store == null) return; + + SaveFinished(_parser.Tick(now)); + if (now >= _nextPollMs) + { + _nextPollMs = now + PollMs; + _store.FlushPending(); + if (_store.Poll() > 0 && _window != null) _window.NeedsPass = true; + } + + if (!Host.HasUi || _window == null || _panel == null) return; + _ui.Poll(Host); + Record(_window, now); + _ui.Submit(Host, now); + } + + /// Learns the world (and the character's name) after login; starts on DreamWeave. + private void TryIdentify(long now) + { + _nextIdentityTryMs = now + IdentityRetryMs; + if (!Host.HasGetWorldName || !Host.TryGetWorldName(out string world) || string.IsNullOrWhiteSpace(world)) return; + + uint me = Host.GetPlayerId(); + string name = string.Empty; + bool named = me != 0 && Host.HasGetObjectName && Host.TryGetObjectName(me, out name) && !string.IsNullOrWhiteSpace(name); + if (!named && now - _loginAtMs < NameWaitMs && IsDreamWeave(world)) return; + + _world = world.Trim(); + _character = named ? name.Trim() : string.Empty; + _checked = true; + _active = IsDreamWeave(_world); + if (!_active) + { + Host.Log($"[RynthThreads] {_world} isn't DreamWeave: idle."); + return; + } + _store ??= new PressStore(PressStore.DefaultFolder); + _store.Poll(); + _nextPollMs = now + PollMs; + if (_window != null) _window.NeedsPass = true; + Host.Log($"[RynthThreads] recording Fragment Press results for {(_character.Length > 0 ? _character : "this character")} on {_world}; " + + $"{_store.Presses.Count} presses so far in {_store.FilePath}"); + } + + // ── Presses ───────────────────────────────────────────────────────────── + + private void SaveFinished(Press? p) + { + if (p == null || _store == null) return; + p.Server = _world; + p.Character = _character; + string? error = _store.Record(p); + if (_window != null) _window.NeedsPass = true; + + string level = p.FragmentLevel?.ToString(CultureInfo.InvariantCulture) ?? "?"; + string what = p.Complete + ? $"{p.Modifiers.Count} modifier{(p.Modifiers.Count == 1 ? "" : "s")}" + : "incomplete"; + Print($"Saved press {_store.Presses.Count}: {p.Fragment} (Level {level}), {p.ComponentsText} - {what}."); + if (error != null) + { + Host.Log($"[RynthThreads] couldn't write {_store.FilePath} yet: {error}"); + Print("The press file is busy; it will be written in a moment."); + } + } + + private ThreadsReport CurrentReport() + { + if (_store == null) return new ThreadsReport(); + if (_report == null || _reportVersion != _store.Version) + { + _report = PressInference.Build(_store.Presses); + _reportVersion = _store.Version; + } + return _report; + } + + private string Notice() + { + if (_store == null) return string.Empty; + var parts = new List(); + if (_store.PendingCount > 0) parts.Add($"{_store.PendingCount} press(es) waiting to be written"); + if (_store.BadLines > 0) parts.Add($"{_store.BadLines} unreadable line(s) in the file skipped"); + return string.Join("; ", parts); + } + + private void Export() + { + if (_store == null) return; + try + { + string path = _store.ExportCsv(DateTime.Now); + Print($"Exported {_store.Presses.Count} presses to {path}"); + } + catch (Exception ex) + { + Print($"Export failed: {ex.Message}"); + } + } + + // ── Commands ──────────────────────────────────────────────────────────── + + private void RunCommand(string arg) + { + string word = arg.Split(' ', StringSplitOptions.RemoveEmptyEntries) is { Length: > 0 } w ? w[0].ToLowerInvariant() : string.Empty; + if (word is "help" or "?") + { + Print($"DreamWeave only: records Fragment Press results and shows the odds of each modifier per component. {Command} shows or hides the window; {Command} stats; {Command} export."); + return; + } + if (!_inWorld) { Print("Log in first."); return; } + if (!_checked) { Print("Still finding out which server this is; try again in a moment."); return; } + if (!_active) + { + Print($"RynthThreads is for DreamWeave only (this is {_world})."); + return; + } + switch (word) + { + case "": + if (_window == null) return; + _window.Visible = !_window.Visible; + _window.NeedsPass = true; + if (_window.Visible && !Host.HasUi && !_noUiLogged) + { + _noUiLogged = true; + Print($"This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Presses are still recorded: {Command} stats."); + } + break; + case "stats": + foreach (string line in StatsLines(CurrentReport(), _store!.FilePath)) Print(line); + break; + case "export": + Export(); + break; + default: + Print($"{Command} [stats | export | help]"); + break; + } + } + + /// + /// The short /rthreads stats summary: totals, then one line per component (at most 6) and No + /// components with its top 5 modifiers by rate ("Guarded 75%", "+" when more likely with it). + /// The Affinity group is left out: every gem has one. + /// + internal static List StatsLines(ThreadsReport r, string file) + { + var lines = new List + { + $"{r.Total} press{(r.Total == 1 ? "" : "es")} ({r.Usable} complete, {r.Incomplete} incomplete) by {r.Characters} character{(r.Characters == 1 ? "" : "s")}; {r.Modifiers.Count} modifiers seen.", + }; + var groups = new List(r.Components); + if (r.NoComponents != null) groups.Add(r.NoComponents); + int shown = 0; + foreach (GroupReport g in groups) + { + if (shown++ == 6) { lines.Add($"... and {groups.Count - 6} more (see the window)."); break; } + var sb = new StringBuilder(); + sb.Append(g.Name).Append(" (").Append(g.Presses).Append("): "); + int n = 0; + foreach (Odds o in g.Odds) + { + if (o.IsGroup) continue; + if (n == 5) break; + if (n++ > 0) sb.Append(", "); + sb.Append(o.Modifier).Append(' ') + .Append(Math.Round(o.Rate * 100).ToString("0", CultureInfo.InvariantCulture)).Append('%'); + if (o.MoreLikely) sb.Append('+'); + } + lines.Add(sb.ToString()); + } + if (groups.Any(g => g.Odds.Any(o => o.MoreLikely))) lines.Add("+ = more likely with it than without."); + if (r.Total == 0) lines.Add("Press a Raw Fragment at a Fragment Press to start."); + lines.Add("File: " + file); + return lines; + } + + private void Print(string text) + { + if (!Host.HasWriteToChat || !Host.WriteToChat("[RynthThreads] " + text, 1)) + Host.Log("[RynthThreads] " + text); + } + + /// A pass when one is wanted, or now and then while visible. + private void Record(UiWindow w, long now) + { + bool due = w.NeedsPass || (w.Visible && now >= w.NextPassMs); + if (!due) return; + w.NeedsPass = false; + w.NextPassMs = now + PassIntervalMs; + w.Begin(); + try + { + _panel!.Draw(w); + } + catch (Exception ex) + { + w.TextWrapped($"Something went wrong drawing this window: {ex.GetType().Name}: {ex.Message}"); + Host.Log($"[RynthThreads] {w.Key} pass failed: {ex}"); + } + w.End(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Threads/Press.cs b/Plugins/RynthCore.Plugin.RynthThreads/Threads/Press.cs new file mode 100644 index 0000000..1689e42 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThreads/Threads/Press.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthThreads.Threads; + +/// One number in a modifier's description, with the form it was written in. +internal readonly struct ModNumber +{ + /// "x1.38" multiplier. + public const string Mult = "mult"; + /// "12%". + public const string Pct = "pct"; + /// "+29" (or "-5"): a signed amount, e.g. a rating. + public const string Plus = "plus"; + /// A plain number. + public const string Num = "num"; + + public readonly double Value; + public readonly string Kind; + /// As written ("x1.38", "12%", "+29", "75"). + public readonly string Text; + + public ModNumber(double value, string kind, string text) + { + Value = value; + Kind = kind; + Text = text; + } +} + +/// One "Name - description" line of the gem's block. +internal sealed class GemModifier +{ + public string Name = string.Empty; + public string Description = string.Empty; + public List Numbers = new(); +} + +/// +/// One press at a Fragment Press, as the server told it in chat. Everything the server says is +/// kept as said (numbers raw): "Level 190, 4 entries." goes into ResultLevel and Entries without +/// guessing what entries are. +/// +internal sealed class Press +{ + /// Random id, so a press read back from the shared file isn't counted twice. + public string Id = string.Empty; + public DateTime TimeUtc; + public string Server = string.Empty; + public string Character = string.Empty; + + /// "Raw Fragment" from "Using the Raw Fragment (Level 185) with the Fragment Press". + public string Fragment = string.Empty; + public int? FragmentLevel; + /// "Fragment Press". + public string Tool = string.Empty; + + /// The "Pressed. ..." line ("Pressed. It holds."), or "" when none came. + public string Outcome = string.Empty; + /// A "Components selected: ..." (or "No components ...") line came. + public bool ComponentsSeen; + /// Sorted, case-insensitively. + public List Components = new(); + /// The "... drawn at random." line, or "". + public string RandomNote = string.Empty; + public List Modifiers = new(); + public int? ResultLevel; + public int? Entries; + + /// Ended on its "Level N, M entries." line. False: timed out, or another "Using ..." line came first. + public bool Complete; + /// Why it ended: "done", "timeout", "next use", "logout". + public string End = string.Empty; + + /// The press's own lines, in order. + public List Raw = new(); + /// Lines that came while the press was open but didn't fit it (other players' chat, or text not known yet). + public List Extra = new(); + + /// The press says "It holds." (the only success text seen so far). + public bool Held => Outcome.IndexOf("holds", StringComparison.OrdinalIgnoreCase) >= 0; + + /// Used by the inference: a finished press with its whole gem block. + public bool Usable => Complete && Modifiers.Count > 0; + + public bool HasComponent(string name) + { + foreach (string c in Components) + if (string.Equals(c, name, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + public bool HasModifier(string name) + { + foreach (GemModifier m in Modifiers) + if (string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + public GemModifier? FindModifier(string name) + { + foreach (GemModifier m in Modifiers) + if (string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase)) return m; + return null; + } + + public string ComponentsText => Components.Count == 0 ? "no components" : string.Join(", ", Components); + + public static string NewId() => Guid.NewGuid().ToString("N").Substring(0, 16); +} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressInference.cs b/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressInference.cs new file mode 100644 index 0000000..85239aa --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressInference.cs @@ -0,0 +1,458 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; + +namespace RynthCore.Plugin.RynthThreads.Threads; + +/// +/// One modifier's rate in a set of presses (a component's, a combination's, ...), with its rate +/// in the other presses for comparison. +/// +internal sealed class Odds +{ + /// The modifier's name, or for any "<Material> Affinity". + public string Modifier = string.Empty; + /// Presses in the set that had it, of . + public int Hits, N; + /// False for the All presses row: nothing to compare with. + public bool Compared; + /// The other presses (without the component, ...) that had it, of ; 0 = no data. + public int OtherHits, OtherN; + /// One-sided Fisher exact p: chance of a rate this much higher here if the set made no difference. + public double P = 1; + /// Clearly higher here than in the other presses (Fisher p < 0.05 or the 95% intervals apart). + public bool MoreLikely; + /// Its numbers in these presses ("x1.38 to x1.52"). + public string Values = string.Empty; + /// For the Affinity group: presses per material, most first. + public List<(string Material, int Hits)> Split = new(); + + public double Rate => N == 0 ? 0 : (double)Hits / N; + public double? OtherRate => OtherN == 0 ? null : (double)OtherHits / OtherN; + public bool IsGroup => Modifier == PressInference.AffinityGroup; +} + +internal enum GroupKind { All, Component, Combination, NoComponents } + +/// (fragment level, result level, entries) and how many presses gave it. +internal readonly record struct ResultCount(int? FragmentLevel, int? ResultLevel, int? Entries, int Count); + +/// A set of presses: All presses, one component's, one exact combination's, or those with no component. +internal sealed class GroupReport +{ + public string Name = string.Empty; + public GroupKind Kind; + /// The components (one for a component row, several for a combination, none otherwise). + public List Members = new(); + public int Presses; + public double AvgModifiers; + public int MinModifiers, MaxModifiers; + /// Most common first. + public List Results = new(); + /// Every modifier seen in these presses, likeliest first. + public List Odds = new(); + + /// What the comparison column is: "without", "other presses", "with components", or "". + public string OtherLabel => Kind switch + { + GroupKind.Component => "without", + GroupKind.Combination => "other presses", + GroupKind.NoComponents => "with components", + _ => string.Empty, + }; + + public Odds? Find(string modifier) => + Odds.FirstOrDefault(o => o.Modifier.Equals(modifier, StringComparison.OrdinalIgnoreCase)); +} + +internal sealed class ModifierReport +{ + /// The modifier's name, or . + public string Name = string.Empty; + public bool IsGroup; + public string Example = string.Empty; + /// "reward" (loot, salvage), "harder" (monster health, damage, numbers) or "" when the text doesn't say plainly. + public string Tag = string.Empty; + /// Its rate over all usable presses. + public Odds Overall = new(); + /// Its rate in presses with no components (against presses with some); null when there are none. + public Odds? NoComponents; + /// Its rate with each component and combination (0% included), likeliest first. + public List<(GroupReport Group, Odds Odds)> ByGroup = new(); + public string Values = string.Empty; + /// (fragment level, presses, values), lowest level first; level null = unknown. + public List<(int? Level, int Count, string Values)> ByLevel = new(); + + public int Seen => Overall.Hits; +} + +internal sealed class ThreadsReport +{ + public int Total, Usable, Incomplete, Characters; + /// Every usable press (the baseline); null when there are none. + public GroupReport? All; + public List Components = new(); + /// Exact combinations of two or more components. + public List Combinations = new(); + /// Presses with no components (the plain random draw); null when there are none. + public GroupReport? NoComponents; + public List Modifiers = new(); + + public GroupReport? Component(string name) => + Components.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + + public GroupReport? Combination(string name) => + Combinations.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + + public ModifierReport? Modifier(string name) => + Modifiers.FirstOrDefault(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); +} + +/// +/// The odds of each modifier from the recorded presses. On DreamWeave a component gives a chance of +/// each modifier, not a fixed one, so for every set of presses (All presses, each component, each +/// exact combination of components, no components) this counts how often each modifier came: +/// hits/N, with a 95% Wilson interval, against its rate in the presses outside the set. +/// +/// Only finished presses with their gem block count (Press.Usable); a finished press without a +/// "Components selected" line counts as one with no components. Every gem carries one +/// "<Material> Affinity": those are counted together as the Affinity group, with the split by +/// material. +/// +/// "More likely with X": the rate with X is above the rate without and either the one-sided Fisher +/// exact p is under 0.05 or the two 95% intervals don't overlap. "Always ... so far" only for 100% +/// over at least 10 presses. +/// +internal static class PressInference +{ + public const string AffinityGroup = "Affinity"; + private const string AffinitySuffix = " Affinity"; + private const double Z = 1.96; + /// Intervals are shown below this many presses. + public const int IntervalBelow = 50; + public const int AlwaysAtLeast = 10; + + public static ThreadsReport Build(IReadOnlyList all) + { + var report = new ThreadsReport { Total = all.Count }; + var used = new List(); + var characters = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (Press p in all) + { + if (p.Character.Length > 0) characters.Add(p.Character); + if (!p.Complete) report.Incomplete++; + if (p.Usable) used.Add(p); + } + report.Usable = used.Count; + report.Characters = characters.Count; + if (used.Count == 0) return report; + + List components = Distinct(used.SelectMany(p => p.Components)); + List keys = Distinct(used.SelectMany(Keys)); + + report.All = Group("All presses", GroupKind.All, new List(), used, used); + + foreach (string c in components) + report.Components.Add(Group(c, GroupKind.Component, new List { c }, used, used.Where(p => p.HasComponent(c)).ToList())); + SortGroups(report.Components); + + foreach (var g in used.Where(p => p.Components.Count > 1).GroupBy(ComboKey, StringComparer.OrdinalIgnoreCase)) + { + List members = g.First().Components.OrderBy(x => x, StringComparer.OrdinalIgnoreCase).ToList(); + report.Combinations.Add(Group(string.Join(" + ", members), GroupKind.Combination, members, used, g.ToList())); + } + SortGroups(report.Combinations); + + List plain = used.Where(p => p.Components.Count == 0).ToList(); + if (plain.Count > 0) + report.NoComponents = Group("No components", GroupKind.NoComponents, new List(), used, plain); + + foreach (string k in keys) + { + List with = used.Where(p => Has(p, k)).ToList(); + var mr = new ModifierReport + { + Name = k, + IsGroup = k == AffinityGroup, + Example = Find(with[^1], k)!.Description, + Overall = Count(k, used, null), + Values = Values(with, k), + }; + mr.Tag = Tag(mr.Example); + if (report.NoComponents != null) mr.NoComponents = Count(k, plain, used.Where(p => p.Components.Count > 0).ToList()); + foreach (GroupReport gr in report.Components.Concat(report.Combinations)) + mr.ByGroup.Add((gr, gr.Find(k) ?? Count(k, Members(used, gr), Others(used, gr)))); + mr.ByGroup.Sort((a, b) => + { + int byOdds = CompareOdds(a.Odds, b.Odds); + return byOdds != 0 ? byOdds : string.Compare(a.Group.Name, b.Group.Name, StringComparison.OrdinalIgnoreCase); + }); + foreach (var g in with.GroupBy(p => p.FragmentLevel).OrderBy(g => g.Key ?? int.MaxValue)) + mr.ByLevel.Add((g.Key, g.Count(), Values(g, k))); + report.Modifiers.Add(mr); + } + report.Modifiers.Sort((a, b) => b.Seen != a.Seen ? b.Seen.CompareTo(a.Seen) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); + return report; + } + + // ── Groups ────────────────────────────────────────────────────────────── + + private static GroupReport Group(string name, GroupKind kind, List members, List used, List set) + { + var g = new GroupReport { Name = name, Kind = kind, Members = members, Presses = set.Count }; + if (set.Count == 0) return g; + g.AvgModifiers = set.Average(p => (double)p.Modifiers.Count); + g.MinModifiers = set.Min(p => p.Modifiers.Count); + g.MaxModifiers = set.Max(p => p.Modifiers.Count); + g.Results = set.GroupBy(p => (p.FragmentLevel, p.ResultLevel, p.Entries)) + .Select(x => new ResultCount(x.Key.FragmentLevel, x.Key.ResultLevel, x.Key.Entries, x.Count())) + .OrderByDescending(r => r.Count).ThenBy(r => r.ResultLevel ?? int.MaxValue).ThenBy(r => r.Entries ?? int.MaxValue) + .ToList(); + List? others = kind == GroupKind.All ? null : Others(used, g, set); + foreach (string k in Distinct(set.SelectMany(Keys))) + g.Odds.Add(Count(k, set, others)); + g.Odds.Sort(CompareOdds); + return g; + } + + private static void SortGroups(List groups) => + groups.Sort((a, b) => b.Presses != a.Presses ? b.Presses.CompareTo(a.Presses) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); + + /// The presses a component or combination row covers. + private static List Members(List used, GroupReport g) => g.Kind switch + { + GroupKind.Component => used.Where(p => p.HasComponent(g.Members[0])).ToList(), + GroupKind.Combination => used.Where(p => ComboKey(p).Equals(ComboKey(g.Members), StringComparison.OrdinalIgnoreCase)).ToList(), + GroupKind.NoComponents => used.Where(p => p.Components.Count == 0).ToList(), + _ => used, + }; + + /// The presses a row is compared with: without the component, not this combination, with components. + private static List Others(List used, GroupReport g, List? set = null) + { + var inSet = new HashSet(set ?? Members(used, g)); + return used.Where(p => !inSet.Contains(p)).ToList(); + } + + private static string ComboKey(Press p) => ComboKey(p.Components); + + private static string ComboKey(IEnumerable components) => + string.Join("\n", components.Select(c => c.ToLowerInvariant()).OrderBy(c => c, StringComparer.Ordinal)); + + /// Likeliest first; then more presses; then by name. + private static int CompareOdds(Odds a, Odds b) + { + if (a.Rate != b.Rate) return b.Rate.CompareTo(a.Rate); + if (a.Hits != b.Hits) return b.Hits.CompareTo(a.Hits); + return string.Compare(a.Modifier, b.Modifier, StringComparison.OrdinalIgnoreCase); + } + + /// Modifier in , against (null = no comparison). + internal static Odds Count(string k, List set, List? others) + { + var o = new Odds { Modifier = k, N = set.Count, Compared = others != null }; + foreach (Press p in set) + if (Has(p, k)) o.Hits++; + if (others != null) + { + o.OtherN = others.Count; + foreach (Press p in others) + if (Has(p, k)) o.OtherHits++; + if (o.OtherN > 0 && o.N > 0) + { + o.P = FisherGreater(o.Hits, o.N, o.OtherHits, o.OtherN); + bool apart = Wilson(o.Hits, o.N).Low > Wilson(o.OtherHits, o.OtherN).High; + o.MoreLikely = o.Rate > o.OtherRate!.Value && (o.P < 0.05 || apart); + } + } + o.Values = Values(set, k); + if (k == AffinityGroup) + { + var split = new Dictionary(StringComparer.OrdinalIgnoreCase); + var names = new List(); + foreach (Press p in set) + foreach (string mat in p.Modifiers.Select(m => Material(m.Name)).OfType().Distinct(StringComparer.OrdinalIgnoreCase)) + { + if (!split.ContainsKey(mat)) { split[mat] = 0; names.Add(mat); } + split[mat]++; + } + o.Split = names.Select(n => (n, split[n])) + .OrderByDescending(x => x.Item2).ThenBy(x => x.n, StringComparer.OrdinalIgnoreCase).ToList(); + } + return o; + } + + // ── Modifier keys (the Affinity group) ────────────────────────────────── + + /// "Amethyst" for "Amethyst Affinity", else null. + internal static string? Material(string modifier) => + modifier.Length > AffinitySuffix.Length && modifier.EndsWith(AffinitySuffix, StringComparison.OrdinalIgnoreCase) + ? modifier.Substring(0, modifier.Length - AffinitySuffix.Length).Trim() + : null; + + /// The name the counts use: for any affinity, else the modifier's own. + internal static string Key(string modifier) => Material(modifier) != null ? AffinityGroup : modifier; + + private static IEnumerable Keys(Press p) => p.Modifiers.Select(m => Key(m.Name)); + + private static bool Has(Press p, string k) => Find(p, k) != null; + + private static GemModifier? Find(Press p, string k) + { + if (k != AffinityGroup) return p.FindModifier(k); + foreach (GemModifier m in p.Modifiers) + if (Material(m.Name) != null) return m; + return null; + } + + /// "Affinity (any)" for the group, else the name. + internal static string Display(string k) => k == AffinityGroup ? "Affinity (any)" : k; + + // ── Statistics ────────────────────────────────────────────────────────── + + /// 95% Wilson score interval for of . + internal static (double Low, double High) Wilson(int hits, int n) + { + if (n <= 0) return (0, 1); + double p = (double)hits / n, z2 = Z * Z; + double denom = 1 + z2 / n; + double centre = (p + z2 / (2 * n)) / denom; + double half = Z * Math.Sqrt(p * (1 - p) / n + z2 / (4.0 * n * n)) / denom; + return (Math.Max(0, centre - half), Math.Min(1, centre + half)); + } + + /// + /// One-sided Fisher exact test: the chance of or more hits in a set of + /// when + hits are spread at random + /// over the + presses. + /// + internal static double FisherGreater(int a, int n, int c, int m) + { + int total = n + m, hits = a + c; + if (total == 0) return 1; + double logAll = LogChoose(total, n), sum = 0; + for (int x = a; x <= Math.Min(n, hits); x++) + { + if (hits - x > m) continue; + sum += Math.Exp(LogChoose(hits, x) + LogChoose(total - hits, n - x) - logAll); + } + return Math.Min(1, sum); + } + + private static double LogChoose(int n, int k) + { + if (k < 0 || k > n) return double.NegativeInfinity; + double r = 0; + for (int i = 1; i <= k; i++) r += Math.Log(n - k + i) - Math.Log(i); + return r; + } + + // ── Text ──────────────────────────────────────────────────────────────── + + private static string Pct(double v) => Math.Round(v * 100).ToString("0", CultureInfo.InvariantCulture); + + /// "75% (3/4, 30-95%)"; the interval only below presses. + internal static string OddsText(Odds o) + { + if (o.N == 0) return "no data"; + if (o.N >= IntervalBelow) return $"{Pct(o.Rate)}% ({o.Hits}/{o.N})"; + var (lo, hi) = Wilson(o.Hits, o.N); + return $"{Pct(o.Rate)}% ({o.Hits}/{o.N}, {Pct(lo)}-{Pct(hi)}%)"; + } + + /// "without: 20% (1/5)", "without: no data", or "" when not compared. + internal static string OtherText(Odds o, string label) + { + if (!o.Compared || label.Length == 0) return string.Empty; + return o.OtherN == 0 ? label + ": no data" : $"{label}: {Pct(o.OtherRate!.Value)}% ({o.OtherHits}/{o.OtherN})"; + } + + /// "more likely with Lead Scarab", "always with Lead Scarab so far" (100% over 10+), or "". + internal static string LikelyText(Odds o, GroupReport g) + { + if (!o.MoreLikely) return string.Empty; + string who = g.Kind == GroupKind.NoComponents ? "no components" : g.Name; + return o.Hits == o.N && o.N >= AlwaysAtLeast ? $"always with {who} so far" : $"more likely with {who}"; + } + + /// "Amethyst 1, Iron 1" for the Affinity group's split, else "". + internal static string SplitText(Odds o) => + string.Join(", ", o.Split.Select(s => $"{s.Material} {s.Hits}")); + + /// "5.25 modifiers per press (5-6)". + internal static string ModifiersText(GroupReport g) + { + string avg = g.AvgModifiers.ToString("0.##", CultureInfo.InvariantCulture); + string range = g.MinModifiers == g.MaxModifiers ? "" : $" ({g.MinModifiers}-{g.MaxModifiers})"; + return $"{avg} modifiers per press{range}"; + } + + /// "L185 -> 175, 3 entries: 4" per result, most common first. + internal static string ResultsText(GroupReport g) => + string.Join("; ", g.Results.Select(r => + $"L{N(r.FragmentLevel)} -> {N(r.ResultLevel)}, {N(r.Entries)} entries: {r.Count}")); + + private static string N(int? v) => v?.ToString(CultureInfo.InvariantCulture) ?? "?"; + + private static List Distinct(IEnumerable names) + { + var list = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (string n in names) + if (n.Length > 0 && seen.Add(n)) list.Add(n); + list.Sort(StringComparer.OrdinalIgnoreCase); + return list; + } + + /// + /// The modifier's numbers across presses, position by position: "x1.38 to x1.52, 12%". Empty + /// when it has none. + /// + internal static string Values(IEnumerable presses, string k) + { + var ranges = new List<(string Kind, double Min, double Max)>(); + foreach (Press p in presses) + { + GemModifier? gm = Find(p, k); + if (gm == null) continue; + for (int i = 0; i < gm.Numbers.Count; i++) + { + ModNumber n = gm.Numbers[i]; + if (i >= ranges.Count) ranges.Add((n.Kind, n.Value, n.Value)); + else ranges[i] = (ranges[i].Kind, Math.Min(ranges[i].Min, n.Value), Math.Max(ranges[i].Max, n.Value)); + } + } + var sb = new StringBuilder(); + foreach (var (kind, min, max) in ranges) + { + if (sb.Length > 0) sb.Append(", "); + sb.Append(Format(kind, min)); + if (max != min) sb.Append(" to ").Append(Format(kind, max)); + } + return sb.ToString(); + } + + internal static string Format(string kind, double v) + { + string s = v.ToString("0.##", CultureInfo.InvariantCulture); + return kind switch + { + ModNumber.Mult => "x" + s, + ModNumber.Pct => s + "%", + ModNumber.Plus => v >= 0 ? "+" + s : s, + _ => s, + }; + } + + /// "reward" or "harder" when the description says so plainly, else "". + internal static string Tag(string description) + { + string d = description.ToLowerInvariant(); + bool reward = d.Contains("loot") || d.Contains("salvage") || d.Contains("drop"); + bool harder = d.Contains("monsters have") || d.Contains("more monsters") || d.Contains("monsters attack") + || d.Contains("boss attacks") || d.Contains("hitting harder"); + return reward == harder ? string.Empty : reward ? "reward" : "harder"; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressParser.cs b/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressParser.cs new file mode 100644 index 0000000..bc99d6c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressParser.cs @@ -0,0 +1,250 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthThreads.Threads; + +/// +/// Reads Fragment Press results out of chat, one line at a time. A press starts at +/// "Using the Raw Fragment (Level 185) with the Fragment Press" +/// and collects, in any order and with other chat in between: +/// "Pressed. It holds." the outcome (any "Pressed..." line) +/// "Components selected: A, B" (or "No components ...") +/// "Remaining slots drawn at random." (any "... drawn at random" line) +/// "The gem carries:" then one " Name - description" line per modifier +/// and ends at "Level 190, 4 entries." (complete). A press that never gets there is still saved, +/// marked incomplete: after without a line of its own, when another +/// "Using ..." line comes, or at logout. Lines that don't fit are kept in the press's Extra list +/// (other players' chat lands there too). Never throws on odd text. +/// +internal sealed class PressParser +{ + /// A press's lines arrive within the same second; this long without one ends it. + public const long TimeoutMs = 15_000; + private const int MaxLineLength = 400; + private const int MaxRawLines = 80; + private const int MaxExtraLines = 40; + private const int MaxModifiers = 40; + + private static readonly RegexOptions Opt = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; + private static readonly Regex UseRx = new(@"^Using (?:the |an? )?(?.+?) with (?:the |an? )?(?[^.]*\bPress)\b", Opt); + private static readonly Regex LevelInName = new(@"^(?.*?)\s*\(\s*Level\s+(?\d+)\s*\)\s*$", Opt); + private static readonly Regex ComponentsRx = new(@"^Components?(?: selected)?\s*:\s*(?.*)$", Opt); + private static readonly Regex NoComponentsRx = new(@"^No components\b", Opt); + private static readonly Regex CarriesRx = new(@"^The [^:]{1,40} carries\s*:?\s*$", Opt); + private static readonly Regex EndRx = new(@"^Level\s+(?\d+)\s*(?:,\s*(?\d+)\s+entr(?:y|ies))?\s*\.?\s*$", Opt); + // "Name - description": a short name of letters, spaces, apostrophes and hyphens. + private static readonly Regex ModifierRx = new(@"^(?[A-Za-z][A-Za-z' \-]{0,47}?)\s+[-–—]\s+(?.+)$", Opt); + private static readonly Regex NumberRx = new( + @"(?[x×]\s?\d+(?:\.\d+)?)|(?[+\-]\d+(?:\.\d+)?)(?!\d|\.\d|\s?%)|(?[+\-]?\d+(?:\.\d+)?\s?%)|(?\d+(?:\.\d+)?))", + RegexOptions.CultureInvariant); + + private enum State { Idle, Open, Carries } + + private State _state = State.Idle; + private Press? _press; + private long _lastOwnLineMs; + + /// A press is being read. + public bool Busy => _press != null; + + /// + /// Feeds one chat message (it may hold several lines). Returns the presses it finished, or + /// null. is a monotonic clock (Environment.TickCount64). + /// + public List? Feed(string? text, long nowMs) + { + if (string.IsNullOrEmpty(text)) return null; + List? done = null; + foreach (string piece in text.Split('\n')) + { + string line = piece.TrimEnd('\r', ' ', '\t'); + if (line.Trim().Length == 0) continue; + if (line.Length > MaxLineLength) line = line.Substring(0, MaxLineLength); + try + { + Press? finished = FeedLine(line, nowMs); + if (finished != null) (done ??= new List()).Add(finished); + } + catch + { + // Odd text must never stop chat; the line is just not used. + } + } + return done; + } + + /// Ends a press that has gone quiet. Returns it (incomplete), or null. + public Press? Tick(long nowMs) + { + if (_press == null || nowMs - _lastOwnLineMs < TimeoutMs) return null; + return Finish("timeout"); + } + + /// Ends whatever is open (logout, unload). Returns it (incomplete), or null. + public Press? Flush(string reason) => _press == null ? null : Finish(reason); + + private Press? FeedLine(string line, long nowMs) + { + string t = line.Trim(); + Press? previous = null; + + if (t.StartsWith("Using ", StringComparison.OrdinalIgnoreCase)) + { + Match use = UseRx.Match(t); + if (_press != null) previous = Finish("next use"); + if (!use.Success) return previous; + Start(use, line, nowMs); + return previous; + } + if (_press == null) return null; + + if (_state == State.Carries) + { + Match mod = ModifierRx.Match(t); + // Modifier lines are indented; an unindented one must still look exactly like "Name - text". + bool indented = line.Length > 0 && char.IsWhiteSpace(line[0]); + if (mod.Success && (indented || !LooksLikeChat(t))) + { + if (_press.Modifiers.Count < MaxModifiers) _press.Modifiers.Add(MakeModifier(mod)); + Own(line, nowMs); + return null; + } + } + + Match end = EndRx.Match(t); + if (end.Success) + { + _press.ResultLevel = Int(end.Groups["lvl"].Value); + if (end.Groups["entries"].Success) _press.Entries = Int(end.Groups["entries"].Value); + Own(line, nowMs); + return Finish("done", complete: true); + } + if (t.StartsWith("Pressed", StringComparison.OrdinalIgnoreCase) && _press.Outcome.Length == 0) + { + _press.Outcome = t; + Own(line, nowMs); + return null; + } + Match comps = ComponentsRx.Match(t); + if (comps.Success && !_press.ComponentsSeen) + { + _press.ComponentsSeen = true; + _press.Components = SplitComponents(comps.Groups["list"].Value); + Own(line, nowMs); + return null; + } + if (NoComponentsRx.IsMatch(t) && !_press.ComponentsSeen) + { + _press.ComponentsSeen = true; + Own(line, nowMs); + return null; + } + if (t.IndexOf("drawn at random", StringComparison.OrdinalIgnoreCase) >= 0 && _press.RandomNote.Length == 0) + { + _press.RandomNote = t; + Own(line, nowMs); + return null; + } + if (CarriesRx.IsMatch(t)) + { + _state = State.Carries; + Own(line, nowMs); + return null; + } + + // Not ours (or not known yet): keep it beside the press, don't let it extend the timeout. + if (_press.Extra.Count < MaxExtraLines) _press.Extra.Add(line); + return null; + } + + private void Start(Match use, string line, long nowMs) + { + string item = use.Groups["item"].Value.Trim(); + var p = new Press + { + Id = Press.NewId(), + TimeUtc = DateTime.UtcNow, + Tool = use.Groups["tool"].Value.Trim(), + Fragment = item, + }; + Match lv = LevelInName.Match(item); + if (lv.Success) + { + p.Fragment = lv.Groups["name"].Value.Trim(); + p.FragmentLevel = Int(lv.Groups["lvl"].Value); + } + _press = p; + _state = State.Open; + Own(line, nowMs); + } + + private void Own(string line, long nowMs) + { + if (_press!.Raw.Count < MaxRawLines) _press.Raw.Add(line); + _lastOwnLineMs = nowMs; + } + + private Press Finish(string reason, bool complete = false) + { + Press p = _press!; + p.Complete = complete; + p.End = reason; + _press = null; + _state = State.Idle; + return p; + } + + /// Chat from players and channels ("Bob says, ...", "[Trade] ...", "You tell ..."). + private static bool LooksLikeChat(string t) => + t.StartsWith("[", StringComparison.Ordinal) || t.Contains(" says, ") || t.Contains(" tells you") + || t.StartsWith("You ", StringComparison.Ordinal) || t.Contains('"'); + + internal static List SplitComponents(string list) + { + var result = new List(); + string s = list.Trim().TrimEnd('.'); + if (s.Length == 0 || s.Equals("none", StringComparison.OrdinalIgnoreCase)) return result; + foreach (string part in s.Replace(" and ", ",", StringComparison.OrdinalIgnoreCase).Split(',')) + { + string c = part.Trim(); + if (c.Length > 0 && !result.Exists(x => x.Equals(c, StringComparison.OrdinalIgnoreCase))) result.Add(c); + } + result.Sort(StringComparer.OrdinalIgnoreCase); + return result; + } + + private static GemModifier MakeModifier(Match m) + { + string desc = m.Groups["desc"].Value.Trim(); + return new GemModifier + { + Name = m.Groups["name"].Value.Trim(), + Description = desc, + Numbers = Numbers(desc), + }; + } + + /// Every number in a description with its form: x1.38, 12%, +29 (or -5), 75. + internal static List Numbers(string text) + { + var list = new List(); + foreach (Match m in NumberRx.Matches(text)) + { + string kind; + string raw; + if (m.Groups["mult"].Success) { kind = ModNumber.Mult; raw = m.Groups["mult"].Value; } + else if (m.Groups["plus"].Success) { kind = ModNumber.Plus; raw = m.Groups["plus"].Value; } + else if (m.Groups["pct"].Success) { kind = ModNumber.Pct; raw = m.Groups["pct"].Value; } + else { kind = ModNumber.Num; raw = m.Groups["num"].Value; } + string digits = raw.TrimStart('x', '×', '+').TrimEnd('%').Trim(); + if (double.TryParse(digits, NumberStyles.Float, CultureInfo.InvariantCulture, out double v)) + list.Add(new ModNumber(v, kind, raw.Replace(" ", string.Empty))); + } + return list; + } + + private static int? Int(string s) => + int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) ? v : null; +} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressStore.cs b/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressStore.cs new file mode 100644 index 0000000..1a016c6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressStore.cs @@ -0,0 +1,346 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.Json; +using System.Threading; + +namespace RynthCore.Plugin.RynthThreads.Threads; + +/// +/// Every press, one JSON object per line, in one file shared by all characters and clients on the +/// PC (%LOCALAPPDATA%\RynthCore\RynthThreads\presses.jsonl). Appends open the file for writing +/// alone, so two clients never mix their lines: a writer that finds it busy tries again a few +/// times, and a press that still can't be written waits for . +/// Reading follows the file's growth (), so other clients' presses show up. +/// Written by hand with Utf8JsonWriter and read with JsonDocument: plugin types never go through +/// System.Text.Json's serializer (its cache would keep an old plugin alive across a hot reload). +/// +internal sealed class PressStore +{ + public const string FileName = "presses.jsonl"; + private const int AppendTries = 4; + private const int AppendWaitMs = 15; + private const int MaxPending = 200; + + private readonly List _presses = new(); + private readonly HashSet _ids = new(StringComparer.Ordinal); + private readonly List _pending = new(); + private long _readOffset; + + public readonly string Folder; + public string FilePath => Path.Combine(Folder, FileName); + + /// Every press read or recorded, oldest first. + public IReadOnlyList Presses => _presses; + /// Presses recorded here that couldn't be written yet. + public int PendingCount => _pending.Count; + /// Lines in the file that couldn't be read (kept in the file, skipped here). + public int BadLines { get; private set; } + /// Bumped whenever changes. + public int Version { get; private set; } + + public PressStore(string folder) => Folder = folder; + + /// %LOCALAPPDATA%\RynthCore\RynthThreads. + public static string DefaultFolder => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "RynthThreads"); + + // ── Writing ───────────────────────────────────────────────────────────── + + /// + /// Keeps the press and appends it to the file. Returns null when written, else why not (it + /// stays pending and tries again). + /// + public string? Record(Press p) + { + if (p.Id.Length == 0) p.Id = Press.NewId(); + Add(p); + string? error = TryAppend(ToJson(p)); + if (error != null && _pending.Count < MaxPending) _pending.Add(p); + return error; + } + + /// Writes presses that found the file busy before. Returns how many are still waiting. + public int FlushPending() + { + while (_pending.Count > 0) + { + if (TryAppend(ToJson(_pending[0])) != null) break; + _pending.RemoveAt(0); + } + return _pending.Count; + } + + /// Appends one line, retrying briefly while another writer holds the file. + internal string? TryAppend(string json) + { + byte[] bytes = Encoding.UTF8.GetBytes(json + "\n"); + string? last = null; + for (int attempt = 0; attempt < AppendTries; attempt++) + { + try + { + Directory.CreateDirectory(Folder); + // FileShare.Read: readers may look, no other writer gets in until this line is down. + using var fs = new FileStream(FilePath, FileMode.Append, FileAccess.Write, FileShare.Read); + fs.Write(bytes, 0, bytes.Length); + return null; + } + catch (IOException ex) + { + last = ex.Message; + } + catch (UnauthorizedAccessException ex) + { + return ex.Message; + } + if (attempt < AppendTries - 1) Thread.Sleep(AppendWaitMs * (attempt + 1)); // at most 90 ms on the pump + } + return last ?? "the file is busy"; + } + + // ── Reading ───────────────────────────────────────────────────────────── + + /// Reads what was added to the file since the last read (everything the first time). Returns the number of new presses. + public int Poll() + { + string path = FilePath; + long length; + try + { + var info = new FileInfo(path); + if (!info.Exists) return 0; + length = info.Length; + } + catch { return 0; } + + if (length < _readOffset) _readOffset = 0; // replaced or cut short: read it all again (ids keep it from doubling) + if (length == _readOffset) return 0; + + byte[] data; + try + { + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + fs.Seek(_readOffset, SeekOrigin.Begin); + data = new byte[length - _readOffset]; + int got = 0; + while (got < data.Length) + { + int n = fs.Read(data, got, data.Length - got); + if (n <= 0) break; + got += n; + } + if (got < data.Length) Array.Resize(ref data, got); + } + catch { return 0; } + + // Only whole lines; a line still being written is read next time. + int lastNewline = Array.LastIndexOf(data, (byte)'\n'); + if (lastNewline < 0) return 0; + _readOffset += lastNewline + 1; + + int added = 0; + foreach (string line in Encoding.UTF8.GetString(data, 0, lastNewline).Split('\n')) + { + string l = line.Trim(); + if (l.Length == 0) continue; + Press? p = FromJson(l); + if (p == null) { BadLines++; continue; } + if (Add(p)) added++; + } + return added; + } + + private bool Add(Press p) + { + if (p.Id.Length > 0 && !_ids.Add(p.Id)) return false; + // Kept in time order (other clients' lines can land out of order). + int at = _presses.Count; + while (at > 0 && _presses[at - 1].TimeUtc > p.TimeUtc) at--; + _presses.Insert(at, p); + Version++; + return true; + } + + // ── JSON ──────────────────────────────────────────────────────────────── + + internal static string ToJson(Press p) + { + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = false })) + { + w.WriteStartObject(); + w.WriteNumber("v", 1); + w.WriteString("id", p.Id); + w.WriteString("time", p.TimeUtc.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture)); + w.WriteString("server", p.Server); + w.WriteString("character", p.Character); + w.WriteString("fragment", p.Fragment); + WriteInt(w, "fragmentLevel", p.FragmentLevel); + w.WriteString("tool", p.Tool); + w.WriteString("outcome", p.Outcome); + w.WriteBoolean("componentsSeen", p.ComponentsSeen); + w.WriteStartArray("components"); + foreach (string c in p.Components) w.WriteStringValue(c); + w.WriteEndArray(); + w.WriteString("random", p.RandomNote); + w.WriteStartArray("modifiers"); + foreach (GemModifier m in p.Modifiers) + { + w.WriteStartObject(); + w.WriteString("name", m.Name); + w.WriteString("description", m.Description); + w.WriteStartArray("numbers"); + foreach (ModNumber n in m.Numbers) + { + w.WriteStartObject(); + w.WriteNumber("value", n.Value); + w.WriteString("kind", n.Kind); + w.WriteString("text", n.Text); + w.WriteEndObject(); + } + w.WriteEndArray(); + w.WriteEndObject(); + } + w.WriteEndArray(); + WriteInt(w, "resultLevel", p.ResultLevel); + WriteInt(w, "entries", p.Entries); + w.WriteBoolean("complete", p.Complete); + w.WriteString("end", p.End); + WriteStrings(w, "raw", p.Raw); + WriteStrings(w, "extra", p.Extra); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(ms.ToArray()); + } + + private static void WriteInt(Utf8JsonWriter w, string name, int? v) + { + if (v.HasValue) w.WriteNumber(name, v.Value); + else w.WriteNull(name); + } + + private static void WriteStrings(Utf8JsonWriter w, string name, List list) + { + w.WriteStartArray(name); + foreach (string s in list) w.WriteStringValue(s); + w.WriteEndArray(); + } + + /// One line back into a press, or null when it isn't one. Unknown fields are ignored, missing ones left empty. + internal static Press? FromJson(string line) + { + try + { + using JsonDocument doc = JsonDocument.Parse(line); + JsonElement r = doc.RootElement; + if (r.ValueKind != JsonValueKind.Object) return null; + var p = new Press + { + Id = Str(r, "id"), + Server = Str(r, "server"), + Character = Str(r, "character"), + Fragment = Str(r, "fragment"), + FragmentLevel = IntOrNull(r, "fragmentLevel"), + Tool = Str(r, "tool"), + Outcome = Str(r, "outcome"), + ComponentsSeen = Bool(r, "componentsSeen"), + Components = Strings(r, "components"), + RandomNote = Str(r, "random"), + ResultLevel = IntOrNull(r, "resultLevel"), + Entries = IntOrNull(r, "entries"), + Complete = Bool(r, "complete"), + End = Str(r, "end"), + Raw = Strings(r, "raw"), + Extra = Strings(r, "extra"), + }; + p.Components.Sort(StringComparer.OrdinalIgnoreCase); + if (DateTime.TryParse(Str(r, "time"), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime t)) + p.TimeUtc = t.ToUniversalTime(); + if (r.TryGetProperty("modifiers", out JsonElement mods) && mods.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement m in mods.EnumerateArray()) + { + if (m.ValueKind != JsonValueKind.Object) continue; + var gm = new GemModifier { Name = Str(m, "name"), Description = Str(m, "description") }; + if (gm.Name.Length == 0) continue; + if (m.TryGetProperty("numbers", out JsonElement nums) && nums.ValueKind == JsonValueKind.Array) + foreach (JsonElement n in nums.EnumerateArray()) + if (n.ValueKind == JsonValueKind.Object && n.TryGetProperty("value", out JsonElement v) && v.TryGetDouble(out double d)) + gm.Numbers.Add(new ModNumber(d, Str(n, "kind"), Str(n, "text"))); + p.Modifiers.Add(gm); + } + } + return p; + } + catch + { + return null; + } + } + + private static string Str(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; + + private static bool Bool(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True; + + private static int? IntOrNull(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : null; + + private static List Strings(JsonElement o, string name) + { + var list = new List(); + if (o.TryGetProperty(name, out JsonElement a) && a.ValueKind == JsonValueKind.Array) + foreach (JsonElement e in a.EnumerateArray()) + if (e.ValueKind == JsonValueKind.String) list.Add(e.GetString() ?? string.Empty); + return list; + } + + // ── CSV ───────────────────────────────────────────────────────────────── + + /// Writes every press as CSV into this folder (presses-yyyyMMdd-HHmmss.csv). Returns the path. + public string ExportCsv(DateTime localNow) + { + Directory.CreateDirectory(Folder); + string path = Path.Combine(Folder, "presses-" + localNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture) + ".csv"); + File.WriteAllText(path, Csv(_presses), new UTF8Encoding(true)); + return path; + } + + internal static string Csv(IEnumerable presses) + { + var sb = new StringBuilder(); + sb.Append("time_utc,server,character,fragment,fragment_level,outcome,components,result_level,entries,complete,modifier_count,modifiers\r\n"); + foreach (Press p in presses) + { + var mods = new List(); + foreach (GemModifier m in p.Modifiers) mods.Add(m.Name + ": " + m.Description); + Cell(sb, p.TimeUtc.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)); sb.Append(','); + Cell(sb, p.Server); sb.Append(','); + Cell(sb, p.Character); sb.Append(','); + Cell(sb, p.Fragment); sb.Append(','); + Cell(sb, p.FragmentLevel?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); sb.Append(','); + Cell(sb, p.Outcome); sb.Append(','); + Cell(sb, string.Join("; ", p.Components)); sb.Append(','); + Cell(sb, p.ResultLevel?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); sb.Append(','); + Cell(sb, p.Entries?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); sb.Append(','); + Cell(sb, p.Complete ? "yes" : "no (" + p.End + ")"); sb.Append(','); + Cell(sb, p.Modifiers.Count.ToString(CultureInfo.InvariantCulture)); sb.Append(','); + Cell(sb, string.Join(" | ", mods)); + sb.Append("\r\n"); + } + return sb.ToString(); + } + + private static void Cell(StringBuilder sb, string s) + { + // A spreadsheet would run a cell starting with = + - @ as a formula: start it with ' instead. + if (s.Length > 0 && s[0] is '=' or '+' or '-' or '@') s = "'" + s; + bool quote = s.IndexOfAny(new[] { ',', '"', '\n', '\r' }) >= 0; + if (!quote) { sb.Append(s); return; } + sb.Append('"').Append(s.Replace("\"", "\"\"")).Append('"'); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiFormat.cs b/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiFormat.cs new file mode 100644 index 0000000..d54717a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiFormat.cs @@ -0,0 +1,130 @@ +using System; + +namespace RynthCore.Plugin.RynthThreads.Ui; + +/// +/// Display-list format 1 for the engine's script windows (RynthSuite +/// Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2-4.3; the engine's DisplayListParser.cs is the source of +/// truth). Little-endian. Only the ops these windows draw are listed. +/// +internal static class UiFormat +{ + public const uint Magic = 0x31575352; // 'RSW1' + public const ushort FormatVersion = 1; + public const uint BodyUnchanged = 0xFFFFFFFF; + public const int MaxString = 4096; + public const int MaxStr8 = 128; + public const int MaxOps = 1500; // engine limit per window + public const int MaxBodyBytes = 64 * 1024; // engine limit per window + public const byte OpHasBlock = 1; + + // Ops + public const byte OpEnd = 0x00; + public const byte OpText = 0x01; + public const byte OpTextColored = 0x02; + public const byte OpTextWrapped = 0x03; + public const byte OpTextDisabled = 0x04; + public const byte OpBulletText = 0x05; + public const byte OpSeparatorText = 0x06; + public const byte OpSeparator = 0x10; + public const byte OpSameLine = 0x11; + public const byte OpSpacing = 0x13; + public const byte OpDummy = 0x14; + public const byte OpIndent = 0x15; + public const byte OpUnindent = 0x16; + public const byte OpButton = 0x20; + public const byte OpCheckbox = 0x21; + public const byte OpSliderInt = 0x22; + public const byte OpInputText = 0x24; + public const byte OpCombo = 0x25; + public const byte OpSelectable = 0x26; + public const byte OpProgressBar = 0x27; + public const byte OpImage = 0x28; // op level 2 (engines from 2026-09-30) + public const byte OpPushID = 0x30; + public const byte OpPopID = 0x31; + public const byte OpPushStyleColor = 0x32; + public const byte OpPopStyleColor = 0x33; + public const byte OpSetItemTooltip = 0x38; + public const byte OpChild = 0x40; + public const byte OpCollapsingHeader = 0x41; + + // Window flags + public const uint FlagVisible = 1u << 0; + public const uint FlagShowInBar = 1u << 1; + /// With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from + /// 2026-10-11; older ones ignore it and list the window in the Scripts menu). + public const uint FlagBarButton = 1u << 11; + public const uint FlagNoScrollbar = 1u << 5; + + // Image icon kinds (op level 2) + public const byte IconKindIcon = 0; // a 0x06 texture id + public const byte IconKindObject = 1; // a live object's icon with underlay and overlay + + // Selectable flags + public const uint SelectableAllowDoubleClick = 4; + + // Event types + public const ushort EvClicked = 1; + public const ushort EvBool = 2; + public const ushort EvInt = 3; + public const ushort EvText = 5; + public const ushort EvOpen = 6; + public const ushort EvVisibility = 8; + public const ushort EvError = 10; + + // ImGuiCol ids the engine accepts in PushStyleColor (ImGui.NET 1.91.6.1) + public const int ColText = 0; + public const int ColButton = 21; + public const int ColButtonHovered = 22; + public const int ColHeader = 24; + + // InputText flags + public const uint InputAutoSelectAll = 4096; + /// The text box reports Enter (its event carries submitted = true). + public const uint InputEnterReturnsTrue = 32; + + // CollapsingHeader flags + public const uint TreeDefaultOpen = 32; + + public static uint Fnv1a(ReadOnlySpan bytes, uint hash = 2166136261) + { + foreach (byte b in bytes) + { + hash ^= b; + hash *= 16777619; + } + return hash; + } + + /// The length of cut to at most bytes without splitting a character. + public static int CutUtf8(ReadOnlySpan s, int max) + { + if (s.Length <= max) return s.Length; + int n = Math.Max(0, max); + while (n > 0 && (s[n] & 0xC0) == 0x80) n--; + return n; + } + + /// An ImGui U32 colour (0xAABBGGRR) from RGB bytes. + public static uint Rgb(byte r, byte g, byte b, byte a = 255) => + ((uint)a << 24) | ((uint)b << 16) | ((uint)g << 8) | r; +} + +/// Colours RynthThreads uses (copied from RynthSort) (0xAABBGGRR). +internal static class UiColors +{ + public static readonly uint Green = UiFormat.Rgb(110, 210, 110); + public static readonly uint Red = UiFormat.Rgb(225, 95, 95); + public static readonly uint Yellow = UiFormat.Rgb(235, 205, 90); + public static readonly uint Grey = UiFormat.Rgb(150, 150, 150); + public static readonly uint Gold = UiFormat.Rgb(230, 180, 60); + /// Upstream's "destruction" highlight: deep pink brightened by half (255, 30, 220). + public static readonly uint Destruction = UiFormat.Rgb(255, 30, 220); + public static readonly uint TabActive = UiFormat.Rgb(60, 110, 170); + public static readonly uint TabActiveHover = UiFormat.Rgb(75, 130, 195); + public static readonly uint OtherServer = UiFormat.Rgb(150, 185, 235); + public static readonly uint Stale = UiFormat.Rgb(225, 150, 80); + public static readonly uint White = UiFormat.Rgb(255, 255, 255); + /// The Lua script's amber (paused, full packs): 1.0, 0.75, 0.25. + public static readonly uint Amber = UiFormat.Rgb(255, 191, 64); +} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiHost.cs b/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiHost.cs new file mode 100644 index 0000000..f660d49 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiHost.cs @@ -0,0 +1,202 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Text; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthThreads.Ui; + +/// +/// The plugin's side of the engine's script windows (API v71): polls the engine's events into +/// the windows' handlers and submits the window set when something changed. Plugin pump thread +/// only (inside the plugin's own tick), as the engine requires. +/// +internal sealed class UiHost +{ + private readonly List _windows = new(); + private readonly Dictionary _byHash = new(); + private byte[] _events = new byte[8192]; + private byte[] _submit = new byte[64 * 1024]; + private uint _lastSeq; + private bool _submittedSomething; + private long _retryAtMs; + private long _lastErrorLogMs; + + public Action? Log; + + public IReadOnlyList Windows => _windows; + + public UiWindow Add(UiWindow w) + { + _windows.Add(w); + _byHash[w.Hash] = w; + return w; + } + + /// Drains the engine's queued events into the windows' handlers. + public void Poll(RynthCoreHost host) + { + if (!host.HasUi || !_submittedSomething) return; + for (int round = 0; round < 8; round++) + { + int n = host.UiPollEvents(_events, out int remaining); + if (n > 0) Apply(_events.AsSpan(0, n)); + if (remaining == 0) break; + if (n == 0) Array.Resize(ref _events, _events.Length * 2); // one event didn't fit + } + } + + private void Apply(ReadOnlySpan data) + { + int pos = 0; + while (data.Length - pos >= 16) + { + ushort type = BinaryPrimitives.ReadUInt16LittleEndian(data[pos..]); + int size = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 2)..]); + if (size < 16 || size > data.Length - pos) break; + uint seq = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 4)..]); + uint window = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 8)..]); + uint key = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 12)..]); + ReadOnlySpan p = data.Slice(pos + 16, size - 16); + pos += size; + if (seq > _lastSeq) _lastSeq = seq; + + _byHash.TryGetValue(window, out UiWindow? w); + switch (type) + { + case UiFormat.EvClicked when w != null && p.Length >= 2: + int count = BinaryPrimitives.ReadUInt16LittleEndian(p); + for (int i = 0; i < Math.Min(count, 4); i++) w.Dispatch(key, new UiEvent(type)); + break; + case UiFormat.EvBool when w != null && p.Length >= 1: + w.Dispatch(key, new UiEvent(type, b: p[0] != 0)); + break; + case UiFormat.EvInt when w != null && p.Length >= 4: + w.Dispatch(key, new UiEvent(type, i: BinaryPrimitives.ReadInt32LittleEndian(p))); + break; + case UiFormat.EvText when w != null && p.Length >= 3: + { + int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p[1..]), p.Length - 3); + w.Dispatch(key, new UiEvent(type, text: Encoding.UTF8.GetString(p.Slice(3, n)), submitted: p[0] != 0)); + break; + } + case UiFormat.EvOpen when w != null && p.Length >= 1: + w.Dispatch(key, new UiEvent(type, b: p[0] != 0)); + break; + case UiFormat.EvVisibility when w != null && p.Length >= 1: + // The player closed it (X) or opened it (bar menu / command): theirs wins. + w.Visible = p[0] != 0; + w.NeedsPass = true; + break; + case UiFormat.EvError when p.Length >= 2: + { + int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p), p.Length - 2); + Log?.Invoke("[RynthThreads] window error: " + Encoding.UTF8.GetString(p.Slice(2, n))); + break; + } + } + } + } + + /// Sends the window set when any window's list or header changed. + public void Submit(RynthCoreHost host, long nowMs) + { + if (!host.HasUi || nowMs < _retryAtMs) return; + bool changed = !_submittedSomething && _windows.Count > 0; + foreach (UiWindow w in _windows) + if (w.BodyDirty || w.HeaderDirty) { changed = true; break; } + if (!changed) return; + + int pos = Write(); + int rc = host.UiSubmit(_submit.AsSpan(0, pos)); + if (rc == 0) + { + foreach (UiWindow w in _windows) w.MarkSubmitted(w.BodyDirty); + _submittedSomething = true; + } + else + { + // Nothing was applied; the engine keeps the previous lists. Try again in a second. + _retryAtMs = nowMs + 1000; + if (nowMs - _lastErrorLogMs > 10_000) + { + _lastErrorLogMs = nowMs; + Log?.Invoke($"[RynthThreads] the engine refused the window list ({rc})."); + } + } + } + + /// Removes every window from the engine (logout, shutdown). Their placement is kept by the engine. + public void SubmitEmpty(RynthCoreHost host) + { + if (!host.HasUi || !_submittedSomething) return; + Span b = stackalloc byte[16]; + BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic); + BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion); + BinaryPrimitives.WriteUInt16LittleEndian(b[6..], 0); + BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq); + BinaryPrimitives.WriteUInt32LittleEndian(b[12..], 16); + if (host.UiSubmit(b) == 0) + { + _submittedSomething = false; + foreach (UiWindow w in _windows) w.ForgetSubmitted(); + } + } + + private int Write() + { + int size = 16; + foreach (UiWindow w in _windows) size += 2 * (1 + UiFormat.MaxStr8) + 4 + 32 + 8 + (w.BodyDirty ? w.Body.Length : 0); + if (_submit.Length < size) _submit = new byte[Math.Max(size, _submit.Length * 2)]; + Span b = _submit; + + BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic); + BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion); + BinaryPrimitives.WriteUInt16LittleEndian(b[6..], (ushort)_windows.Count); + // Every event polled so far has been applied (handlers run as they arrive). + BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq); + int pos = 16; + foreach (UiWindow w in _windows) + { + pos = Str8(b, pos, w.KeyUtf8); + pos = Str8(b, pos, Encoding.UTF8.GetBytes(w.Title ?? string.Empty)); + BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.Flags); pos += 4; + pos = F32(b, pos, w.DefaultWidth); + pos = F32(b, pos, w.DefaultHeight); + pos = F32(b, pos, w.MinWidth); + pos = F32(b, pos, w.MinHeight); + pos = F32(b, pos, float.NaN); // RequestSize: none + pos = F32(b, pos, float.NaN); + pos = F32(b, pos, float.NaN); // RequestPos: none + pos = F32(b, pos, float.NaN); + BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.ListSeq); pos += 4; + if (w.BodyDirty) + { + ReadOnlySpan body = w.Body; + BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], (uint)body.Length); pos += 4; + body.CopyTo(b[pos..]); + pos += body.Length; + } + else + { + BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], UiFormat.BodyUnchanged); pos += 4; + } + } + BinaryPrimitives.WriteUInt32LittleEndian(b[12..], (uint)pos); + return pos; + } + + private static int Str8(Span b, int pos, ReadOnlySpan s) + { + int n = UiFormat.CutUtf8(s, UiFormat.MaxStr8); + b[pos] = (byte)n; + s[..n].CopyTo(b[(pos + 1)..]); + return pos + 1 + n; + } + + private static int F32(Span b, int pos, float v) + { + BinaryPrimitives.WriteSingleLittleEndian(b[pos..], v); + return pos + 4; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiWindow.cs b/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiWindow.cs new file mode 100644 index 0000000..bbbdea9 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiWindow.cs @@ -0,0 +1,515 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Plugin.RynthThreads.Ui; + +/// One input from the engine for a widget (a click, a new value, an open state). +internal readonly struct UiEvent +{ + public readonly ushort Type; + public readonly bool Bool; + public readonly int Int; + public readonly string Text; + public readonly bool Submitted; + + public UiEvent(ushort type, bool b = false, int i = 0, string? text = null, bool submitted = false) + { + Type = type; + Bool = b; + Int = i; + Text = text ?? string.Empty; + Submitted = submitted; + } +} + +/// +/// One script window (engine API v71) and its recorder. A render pass records ImGui-style calls +/// into a display list; every widget's handler (click, value change) is kept by its widget key +/// until the next pass, so an event from the engine runs the code that drew that widget. +/// +/// Widget keys are FNV-1a(id, window hash): RynthThreads names every widget itself, so it needs +/// no ID stack. ImGui sees "label###id": its ID comes from the id alone, so labels can change. +/// The engine echoes the key in events and keys its per-widget local values by it. +/// +internal sealed class UiWindow +{ + public readonly string Key; + public readonly byte[] KeyUtf8; + public readonly uint Hash; + + public string Title; + public bool Visible; + public bool ShowInBar = true; + /// With ShowInBar: the window has its own button on the RynthCore bar (title as the + /// tooltip) rather than a line in the Scripts menu. + public bool BarButton = true; + public float DefaultWidth, DefaultHeight, MinWidth, MinHeight; + + /// A pass is wanted at the next chance (input arrived, it was just shown, data changed). + public bool NeedsPass = true; + public long NextPassMs; + + // The list as recorded by the last pass, and what the engine last accepted. + private byte[] _body = new byte[16 * 1024]; + private int _len; + private int _ops; + private bool _cut; + private byte[] _sentBody = Array.Empty(); + private int _sentLen = -1; + public uint ListSeq { get; private set; } + internal bool BodyDirty; + + // Header as last accepted by the engine. + private string? _sentTitle; + private uint _sentFlags; + private float _sentDw = float.NaN, _sentDh, _sentMw, _sentMh; + + private Dictionary> _handlers = new(); + private Dictionary> _next = new(); + private readonly Dictionary _openStates = new(); + + // Child blocks: where each open block's u32 length sits, or -1 when the block was dropped. + private readonly int[] _blocks = new int[16]; + private int _blockDepth; + private byte[] _tmp = new byte[512]; + + public UiWindow(string key, string title) + { + Key = key; + KeyUtf8 = Encoding.UTF8.GetBytes(key); + Hash = UiFormat.Fnv1a(KeyUtf8); + Title = title; + } + + public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0) + | (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0); + + public bool HeaderDirty => + _sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight + || _sentMw != MinWidth || _sentMh != MinHeight; + + public ReadOnlySpan Body => _body.AsSpan(0, _len); + + // ── Pass ──────────────────────────────────────────────────────────────── + + public void Begin() + { + _len = 0; + _ops = 0; + _cut = false; + _blockDepth = 0; + _next.Clear(); + } + + /// Ends the pass: closes open blocks, writes End, and notes whether the list changed. + public void End() + { + while (_blockDepth > 0) EndChild(); + if (_cut) + { + // Room was kept for this line (see Room). + int p = BeginOp(UiFormat.OpTextDisabled); + Str("(more than fits in one window; narrow the list)"); + EndOp(p); + } + Ensure(4); + _body[_len++] = UiFormat.OpEnd; + _body[_len++] = 0; + _body[_len++] = 0; + _body[_len++] = 0; + + (_handlers, _next) = (_next, _handlers); + bool differs = _sentLen != _len || !_body.AsSpan(0, _len).SequenceEqual(_sentBody.AsSpan(0, _sentLen)); + if (differs && !BodyDirty) ListSeq++; + BodyDirty = differs; + } + + /// The engine accepted the last submit: remember what it now has. + internal void MarkSubmitted(bool bodySent) + { + if (bodySent) + { + if (_sentBody.Length < _len) _sentBody = new byte[_body.Length]; + _body.AsSpan(0, _len).CopyTo(_sentBody); + _sentLen = _len; + BodyDirty = false; + } + _sentTitle = Title; + _sentFlags = Flags; + _sentDw = DefaultWidth; _sentDh = DefaultHeight; _sentMw = MinWidth; _sentMh = MinHeight; + } + + /// The engine dropped every window (logout, empty submit): send everything again next time. + internal void ForgetSubmitted() + { + _sentLen = -1; + _sentTitle = null; + BodyDirty = _len > 0; + } + + internal void Dispatch(uint widgetKey, in UiEvent e) + { + if (_handlers.TryGetValue(widgetKey, out Action? h)) + h(e); + NeedsPass = true; + } + + // ── Widgets ───────────────────────────────────────────────────────────── + + public uint KeyOf(string id) + { + int max = Encoding.UTF8.GetMaxByteCount(id.Length); + if (_tmp.Length < max) _tmp = new byte[Math.Max(max, _tmp.Length * 2)]; + int n = Encoding.UTF8.GetBytes(id, _tmp); + return UiFormat.Fnv1a(_tmp.AsSpan(0, n), Hash); + } + + public void Text(string text) => WriteText(UiFormat.OpText, text); + public void TextDisabled(string text) => WriteText(UiFormat.OpTextDisabled, text); + public void TextWrapped(string text) => WriteText(UiFormat.OpTextWrapped, text); + public void BulletText(string text) => WriteText(UiFormat.OpBulletText, text); + public void SeparatorText(string text) => WriteText(UiFormat.OpSeparatorText, text); + + public void TextColored(uint abgr, string text) + { + if (!Room()) return; + int p = BeginOp(UiFormat.OpTextColored); + U32(abgr); + Str(text); + EndOp(p); + } + + public void Separator() + { + if (!Room()) return; + EndOp(BeginOp(UiFormat.OpSeparator)); + } + + public void Spacing() + { + if (!Room()) return; + EndOp(BeginOp(UiFormat.OpSpacing)); + } + + /// Next item on the same line, logical units from the content start (0 = right after). + public void SameLine(float x = 0f, float spacing = -1f) + { + if (!Room()) return; + int p = BeginOp(UiFormat.OpSameLine); + F32(x); + F32(spacing); + EndOp(p); + } + + public void Dummy(float w, float h) + { + if (!Room()) return; + int p = BeginOp(UiFormat.OpDummy); + F32(w); + F32(h); + EndOp(p); + } + + /// Moves the following items right by logical units, until . + public void Indent(float w) + { + if (!Room()) return; + int p = BeginOp(UiFormat.OpIndent); + F32(w); + EndOp(p); + } + + public void Unindent(float w) + { + if (!Room()) return; + int p = BeginOp(UiFormat.OpUnindent); + F32(w); + EndOp(p); + } + + public void Button(string label, string id, Action onClick, float w = 0f, float h = 0f, bool small = false) + { + if (!Room()) return; + uint key = KeyOf(id); + int p = BeginOp(UiFormat.OpButton); + U32(key); + Str(label + "###" + id); + F32(w); + F32(h); + U8(small ? (byte)1 : (byte)0); + EndOp(p); + _next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); }; + } + + public void SmallButton(string label, string id, Action onClick) => Button(label, id, onClick, small: true); + + /// A button drawn highlighted when (tabs, toggles). + public void ToggleButton(string label, string id, bool active, Action onClick, bool small = false) + { + if (active) + { + PushStyleColor(UiFormat.ColButton, UiColors.TabActive); + PushStyleColor(UiFormat.ColButtonHovered, UiColors.TabActiveHover); + } + Button(label, id, onClick, small: small); + if (active) PopStyleColor(2); + } + + public void Checkbox(string label, string id, bool value, Action set) + { + if (!Room()) return; + uint key = KeyOf(id); + int p = BeginOp(UiFormat.OpCheckbox); + U32(key); + Str(label + "###" + id); + U8(value ? (byte)1 : (byte)0); + EndOp(p); + _next[key] = e => { if (e.Type == UiFormat.EvBool) set(e.Bool); }; + } + + /// An integer slider from to (clamped by the engine). + public void SliderInt(string label, string id, int value, int min, int max, Action set, string format = "%d") + { + if (!Room()) return; + uint key = KeyOf(id); + int p = BeginOp(UiFormat.OpSliderInt); + U32(key); + Str(label + "###" + id); + I32(value); + I32(min); + I32(max); + Str(format); + EndOp(p); + _next[key] = e => { if (e.Type == UiFormat.EvInt) set(Math.Clamp(e.Int, min, max)); }; + } + + /// A text box; gets every edit (submitted = Enter was pressed). + public void InputText(string label, string id, string value, int maxLen, Action set, uint flags = 0) => + InputText(label, id, value, maxLen, (text, _) => set(text), flags); + + /// A text box; gets every edit and whether Enter was pressed. + public void InputText(string label, string id, string value, int maxLen, Action set, uint flags = 0) + { + if (!Room()) return; + maxLen = Math.Clamp(maxLen, 1, UiFormat.MaxString); + uint key = KeyOf(id); + int p = BeginOp(UiFormat.OpInputText); + U32(key); + Str(label + "###" + id); + Str(value ?? string.Empty, maxLen); + U16((ushort)maxLen); + U32(flags); + EndOp(p); + _next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text, e.Submitted); }; + } + + public void Combo(string label, string id, int index, IReadOnlyList items, Action set) + { + if (!Room()) return; + uint key = KeyOf(id); + int count = Math.Min(items.Count, 512); + int p = BeginOp(UiFormat.OpCombo); + U32(key); + Str(label + "###" + id); + I32(index); + U16((ushort)count); + for (int i = 0; i < count; i++) Str(items[i]); + EndOp(p); + _next[key] = e => { if (e.Type == UiFormat.EvInt) set(e.Int); }; + } + + public void Selectable(string label, string id, bool selected, Action onClick, float w = 0f, float h = 0f) + { + if (!Room()) return; + uint key = KeyOf(id); + int p = BeginOp(UiFormat.OpSelectable); + U32(key); + Str(label + "###" + id); + U8(selected ? (byte)1 : (byte)0); + U32(0); + F32(w); + F32(h); + EndOp(p); + _next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); }; + } + + public void ProgressBar(float fraction, float w, float h, string overlay) + { + if (!Room()) return; + int p = BeginOp(UiFormat.OpProgressBar); + F32(float.IsFinite(fraction) ? Math.Clamp(fraction, 0f, 1f) : 0f); + F32(w); + F32(h); + Str(overlay ?? string.Empty); + EndOp(p); + } + + /// + /// An icon (op level 2): = a 0x06 + /// texture id, = a live object. Engines without op level + /// 2 skip it (the caller checks first so the layout doesn't shift). + /// + public void Image(byte kind, uint id, float w, float h) + { + if (!Room()) return; + int p = BeginOp(UiFormat.OpImage); + U8(kind); + U32(id); + F32(w); + F32(h); + F32(0f); F32(0f); // uv0 + F32(1f); F32(1f); // uv1 + U32(0xFFFFFFFFu); // tint: as is + U32(0u); // border: none + EndOp(p); + } + + /// Tooltip for the item just drawn. + public void Tooltip(string text) + { + if (!Room() || string.IsNullOrEmpty(text)) return; + int p = BeginOp(UiFormat.OpSetItemTooltip); + Str(text); + EndOp(p); + } + + public void PushStyleColor(int colId, uint abgr) + { + if (!Room()) return; + int p = BeginOp(UiFormat.OpPushStyleColor); + U16((ushort)colId); + U32(abgr); + EndOp(p); + } + + /// Pops are dropped when the list is cut short; the engine pops leftovers at the scope's end. + public void PopStyleColor(int count = 1) + { + if (!Room()) return; + int p = BeginOp(UiFormat.OpPopStyleColor); + U8((byte)Math.Clamp(count, 1, 255)); + EndOp(p); + } + + /// + /// A collapsing header; returns whether to record its contents. The open state is the + /// player's (kept from the engine's Open events), so a header stays as they left it. + /// + public bool CollapsingHeader(string label, string id, bool defaultOpen = false) + { + uint key = KeyOf(id); + bool open = _openStates.TryGetValue(key, out bool o) ? o : defaultOpen; + if (!Room()) return false; + int p = BeginOp(UiFormat.OpCollapsingHeader); + U32(key); + Str(label + "###" + id); + U32(defaultOpen ? UiFormat.TreeDefaultOpen : 0); + U8(open ? (byte)1 : (byte)0); + EndOp(p); + _next[key] = e => { if (e.Type == UiFormat.EvOpen) _openStates[key] = e.Bool; }; + return open; + } + + /// A scrolling region; h 0 = fill the rest of the window. Must be closed with . + public void BeginChild(string id, float w = 0f, float h = 0f, bool border = true) + { + if (_blockDepth >= _blocks.Length) throw new InvalidOperationException("child regions nested too deep"); + if (!Room()) + { + _blocks[_blockDepth++] = -1; + return; + } + uint key = KeyOf(id); + int p = BeginOp(UiFormat.OpChild, UiFormat.OpHasBlock); + U32(key); + Str(id); + F32(w); + F32(h); + U8(border ? (byte)1 : (byte)0); + U32(0); + EndOp(p); + _blocks[_blockDepth++] = _len; + U32(0); // BlockLength, patched by EndChild + } + + public void EndChild() + { + if (_blockDepth == 0) return; + int at = _blocks[--_blockDepth]; + if (at < 0) return; + BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(at), (uint)(_len - (at + 4))); + } + + // ── Writing ───────────────────────────────────────────────────────────── + + /// + /// Whether another op fits. Room is kept for the closing "list cut short" line and the End + /// op, so the list never goes over the engine's limits (it refuses an over-limit list whole). + /// + private bool Room() + { + if (_cut) return false; + if (_ops < UiFormat.MaxOps - 8 && _len < UiFormat.MaxBodyBytes - 4096) return true; + _cut = true; + return false; + } + + private void WriteText(byte code, string text) + { + if (!Room()) return; + int p = BeginOp(code); + Str(text); + EndOp(p); + } + + private int BeginOp(byte code, byte opFlags = 0) + { + _ops++; + Ensure(4); + _body[_len++] = code; + _body[_len++] = opFlags; + _len += 2; // PayloadLength, patched by EndOp + return _len; + } + + private void EndOp(int payloadStart) + { + int length = _len - payloadStart; + BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(payloadStart - 2), (ushort)Math.Min(length, ushort.MaxValue)); + } + + private void Ensure(int extra) + { + if (_len + extra <= _body.Length) return; + int size = _body.Length; + while (size < _len + extra) size *= 2; + Array.Resize(ref _body, size); + } + + private void U8(byte v) { Ensure(1); _body[_len++] = v; } + private void U16(ushort v) { Ensure(2); BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), v); _len += 2; } + private void U32(uint v) { Ensure(4); BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; } + private void I32(int v) { Ensure(4); BinaryPrimitives.WriteInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; } + + private void F32(float v) + { + Ensure(4); + BinaryPrimitives.WriteSingleLittleEndian(_body.AsSpan(_len), float.IsFinite(v) ? v : 0f); + _len += 4; + } + + /// str: u16 length + UTF-8, cut to on a character boundary. + private void Str(string s, int maxBytes = UiFormat.MaxString) + { + s ??= string.Empty; + ReadOnlySpan src = s.Length > maxBytes ? s.AsSpan(0, maxBytes) : s.AsSpan(); + Ensure(2 + Encoding.UTF8.GetMaxByteCount(src.Length)); + int at = _len + 2; + Span dst = _body.AsSpan(at); + int n = UiFormat.CutUtf8(dst[..Encoding.UTF8.GetBytes(src, dst)], maxBytes); + BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), (ushort)n); + _len = at + n; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Views/ThreadsPanel.cs b/Plugins/RynthCore.Plugin.RynthThreads/Views/ThreadsPanel.cs new file mode 100644 index 0000000..c9a5d13 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthThreads/Views/ThreadsPanel.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using RynthCore.Plugin.RynthThreads.Threads; +using RynthCore.Plugin.RynthThreads.Ui; + +namespace RynthCore.Plugin.RynthThreads.Views; + +/// +/// The RynthThreads window: a summary line and Export, then three tabs. Components: All presses +/// (the baseline), each component, each exact combination and No components, each opening to the +/// rate of every modifier seen in its presses (hits/presses, a 95% range while few, the rate +/// without it), modifiers per press and the results. Modifiers: each one's overall rate, its rate +/// with each component, its values by fragment level. Presses: the newest first, each opening to +/// its modifiers and raw chat lines. +/// Recorded on the pump thread, replayed by the engine. +/// +internal sealed class ThreadsPanel +{ + private enum Tab { Components, Modifiers, Presses } + + private const int MaxPressesShown = 60; + private Tab _tab = Tab.Components; + + public Func Report = () => new ThreadsReport(); + public Func> Presses = () => Array.Empty(); + public Action Export = () => { }; + /// Extra status (pending writes, unreadable lines), or "". + public Func Notice = () => string.Empty; + + public void Draw(UiWindow w) + { + ThreadsReport r = Report(); + w.Text($"{r.Total} press{(r.Total == 1 ? "" : "es")}, {r.Usable} complete" + (r.Incomplete > 0 ? $", {r.Incomplete} incomplete" : "") + + $" ({r.Characters} character{(r.Characters == 1 ? "" : "s")})"); + w.SameLine(); + w.SmallButton("Export CSV", "export", Export); + w.Tooltip("Writes every press to a CSV file next to presses.jsonl (the folder is named in chat)"); + string notice = Notice(); + if (notice.Length > 0) w.TextColored(UiColors.Amber, notice); + + w.ToggleButton("Components", "tab.c", _tab == Tab.Components, () => _tab = Tab.Components, small: true); + w.SameLine(); + w.ToggleButton("Modifiers", "tab.m", _tab == Tab.Modifiers, () => _tab = Tab.Modifiers, small: true); + w.SameLine(); + w.ToggleButton("Presses", "tab.p", _tab == Tab.Presses, () => _tab = Tab.Presses, small: true); + w.Separator(); + + w.BeginChild("body", 0f, 0f, border: false); + if (r.Total == 0) + w.TextWrapped("No presses yet. Press a Raw Fragment at a Fragment Press: the result is read from chat and saved for every character on this PC."); + else if (_tab == Tab.Components) DrawComponents(w, r); + else if (_tab == Tab.Modifiers) DrawModifiers(w, r); + else DrawPresses(w); + w.EndChild(); + } + + // ── Components ────────────────────────────────────────────────────────── + + private static void DrawComponents(UiWindow w, ThreadsReport r) + { + w.TextWrapped("Each component gives a chance of each modifier. Rates are how often it came: hits/presses, " + + "with a 95% range while presses are few, and the rate without the component to compare."); + if (r.All is { } all) DrawGroup(w, all, "c:(all)"); + if (r.Components.Count == 0) + w.TextDisabled("No complete press with a component yet."); + foreach (GroupReport c in r.Components) DrawGroup(w, c, "c:" + c.Name); + foreach (GroupReport c in r.Combinations) DrawGroup(w, c, "k:" + c.Name); + if (r.NoComponents is { } nc) DrawGroup(w, nc, "c:(none)"); + } + + private static void DrawGroup(UiWindow w, GroupReport g, string id) + { + if (!w.CollapsingHeader($"{g.Name} ({g.Presses} press{(g.Presses == 1 ? "" : "es")})", id)) return; + w.Indent(8f); + if (g.Kind == GroupKind.All) w.TextDisabled("Every complete press: the baseline."); + else if (g.Kind == GroupKind.Combination) w.TextDisabled("Presses with exactly these components."); + else if (g.Kind == GroupKind.NoComponents) w.TextDisabled("The plain random draw: no component used."); + w.TextDisabled(PressInference.ModifiersText(g)); + w.TextDisabled("Results: " + PressInference.ResultsText(g)); + foreach (Odds o in g.Odds) DrawOdds(w, PressInference.Display(o.Modifier), o, g); + w.Unindent(8f); + } + + /// "Guarded 75% (3/4, 30-95%); without: no data; x1.83 to x1.91", green when more likely. + private static void DrawOdds(UiWindow w, string label, Odds o, GroupReport g) + { + var parts = new List { $"{label} {PressInference.OddsText(o)}" }; + string other = PressInference.OtherText(o, g.OtherLabel); + if (other.Length > 0) parts.Add(other); + if (o.Values.Length > 0) parts.Add(o.Values); + string likely = PressInference.LikelyText(o, g); + if (likely.Length > 0) parts.Add(likely); + string line = string.Join("; ", parts); + if (likely.Length > 0) + { + w.PushStyleColor(UiFormat.ColText, UiColors.Green); + w.BulletText(line); + w.PopStyleColor(); + } + else w.BulletText(line); + if (o.IsGroup && o.Split.Count > 0) w.TextDisabled(" " + PressInference.SplitText(o)); + } + + // ── Modifiers ─────────────────────────────────────────────────────────── + + private static void DrawModifiers(UiWindow w, ThreadsReport r) + { + if (r.Modifiers.Count == 0) w.TextDisabled("No complete press yet."); + foreach (ModifierReport m in r.Modifiers) + { + string tag = m.Tag.Length > 0 ? " [" + m.Tag + "]" : ""; + if (!w.CollapsingHeader($"{PressInference.Display(m.Name)} {PressInference.OddsText(m.Overall)}{tag}", "m:" + m.Name)) continue; + w.Indent(8f); + w.TextWrapped(m.Example); + w.Text("All presses: " + PressInference.OddsText(m.Overall)); + if (m.NoComponents is { } nc && r.NoComponents is { } ncg) DrawOdds(w, "No components", nc, ncg); + if (m.ByGroup.Count > 0) + { + w.SeparatorText("By component"); + foreach (var (g, o) in m.ByGroup) DrawOdds(w, g.Name, o, g); + } + if (m.IsGroup && m.Overall.Split.Count > 0) + { + w.SeparatorText("By material"); + foreach (var (mat, hits) in m.Overall.Split) + w.BulletText($"{mat}: {PressInference.OddsText(new Odds { Hits = hits, N = m.Overall.N })}"); + } + if (m.Values.Length > 0) w.Text("Values: " + m.Values); + if (m.ByLevel.Count > 1 || (m.ByLevel.Count == 1 && m.ByLevel[0].Level != null)) + { + w.SeparatorText("By fragment level"); + foreach (var (level, count, values) in m.ByLevel) + w.BulletText($"{(level?.ToString(CultureInfo.InvariantCulture) ?? "?")}: {(values.Length > 0 ? values : "-")} ({count} press{(count == 1 ? "" : "es")})"); + } + w.Unindent(8f); + } + } + + // ── Presses ───────────────────────────────────────────────────────────── + + private void DrawPresses(UiWindow w) + { + IReadOnlyList presses = Presses(); + int shown = 0; + for (int i = presses.Count - 1; i >= 0 && shown < MaxPressesShown; i--, shown++) + { + Press p = presses[i]; + if (!w.CollapsingHeader(PressTitle(p), "p:" + p.Id)) continue; + w.Indent(8f); + w.TextDisabled($"{p.Character} on {p.Server}, {p.TimeUtc.ToLocalTime():yyyy-MM-dd HH:mm:ss}"); + if (p.Outcome.Length > 0) w.Text(p.Outcome); + w.Text("Components: " + (p.ComponentsSeen ? p.ComponentsText : "(no line)")); + foreach (GemModifier m in p.Modifiers) w.BulletText(m.Name + " - " + m.Description); + if (p.ResultLevel != null || p.Entries != null) + w.Text($"Level {p.ResultLevel?.ToString(CultureInfo.InvariantCulture) ?? "?"}, {p.Entries?.ToString(CultureInfo.InvariantCulture) ?? "?"} entries"); + if (!p.Complete) w.TextColored(UiColors.Amber, "Incomplete: " + EndText(p.End)); + w.SeparatorText("Chat lines"); + foreach (string line in p.Raw) w.TextDisabled(line); + if (p.Extra.Count > 0) + { + w.SeparatorText("Other lines while it was open"); + foreach (string line in p.Extra) w.TextDisabled(line); + } + w.Unindent(8f); + } + if (presses.Count > MaxPressesShown) + w.TextDisabled($"The newest {MaxPressesShown} of {presses.Count}; Export CSV has them all."); + } + + internal static string PressTitle(Press p) + { + string lvl = p.FragmentLevel?.ToString(CultureInfo.InvariantCulture) ?? "?"; + string to = p.ResultLevel != null ? " -> " + p.ResultLevel.Value.ToString(CultureInfo.InvariantCulture) : ""; + string state = p.Complete ? $"{p.Modifiers.Count} modifiers" : "incomplete"; + return $"{p.TimeUtc.ToLocalTime():MM-dd HH:mm} L{lvl}{to} {p.ComponentsText} ({state})"; + } + + private static string EndText(string end) => end switch + { + "timeout" => "the press's lines stopped before its Level line", + "next use" => "another item was used before its Level line", + "logout" => "logged out before its Level line", + _ => end, + }; +} diff --git a/Plugins/Shared/PetCaptureLines.cs b/Plugins/Shared/PetCaptureLines.cs new file mode 100644 index 0000000..72777e7 --- /dev/null +++ b/Plugins/Shared/PetCaptureLines.cs @@ -0,0 +1,29 @@ +// PetCaptureLines.cs - The chat lines that mean an ACECustom siphon-lens capture worked. +// +// RynthILT's (linked source): its siphon auto-capture (IltPetAutomation, RynthAi's Pets tab's until +// 2026-10-20) reads them to time the next lens (success -> short cooldown), and its Vaulted Dungeons +// keeper counts a capture as a kill for its "Kill Client" timer (a hunter who captures instead of +// killing is not idle). They are the MonsterCapture success replies; nothing new is guessed here. +using System; + +namespace RynthCore.Plugin.Shared; + +internal static class PetCaptureLines +{ + /// Substrings of the success replies (matched case-insensitively). + private static readonly string[] Success = + { + "successfully siphoned the essence", + "The echo resonates perfectly", + "The essence is captured", + }; + + /// True when is a capture-success reply. + public static bool IsSuccess(string? text) + { + if (string.IsNullOrEmpty(text)) return false; + foreach (string part in Success) + if (text.IndexOf(part, StringComparison.OrdinalIgnoreCase) >= 0) return true; + return false; + } +} diff --git a/Plugins/Shared/RynthIltDataApi.cs b/Plugins/Shared/RynthIltDataApi.cs new file mode 100644 index 0000000..35e32a6 --- /dev/null +++ b/Plugins/Shared/RynthIltDataApi.cs @@ -0,0 +1,723 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthIltDataApi.cs +// The "RynthILT.Data" interface: the Infinite Leaftide data RynthILT's Mini Remote Charms +// and Banking tabs show, for other plugins to draw. RynthOracle (charms, Pet Breeding, the +// Temple guardians) and RynthInventory (Banking) read it until 2026-10-21, when those screens +// became RynthILT's own (a shared plugin never shows one server's data); no RynthSuite plugin +// reads it now, and it stays for any other reader: +// - the registry charms and Guardian Hands (GetCharmsJson, ToggleCharm); +// - the bank balances of every character RynthILT has seen on this server, and +// deposits, withdrawals, transfers and balance reads (GetBankJson, BankCommand); +// - version 2: the pet breeding tracker (GetPetBreedingJson, PetBreedingCommand). +// Separate from "RynthServer.Profile" (the server's settings) and "RynthILT.Hub" (RynthAi's +// exact-version table) so neither has to change for this. +// Compiled into RynthILT and its readers (linked source), so the layout can't drift. +// +// Rules (as the other shared interfaces): +// - Append-only: new functions go at the end, and Version goes up. +// - Strings are UTF-8, NUL-terminated. The JSON itself is plain ASCII. +// - Every function returns safely (no exception crosses the boundary). +// - The table is allocated once per loaded copy of RynthILT and never freed; shutdown +// sets Version to 0, and a reader re-queries (host GetPluginInterface) when it sees that. +// - Reading a JSON says "someone is looking": RynthILT rebuilds that snapshot on its pump +// (every couple of seconds) only while it is being read, so an idle reader costs nothing. +// +// GetCharmsJson payload (IltCharms.BuildReaderJson; read leniently): +// { "available": true, "world": "InfiniteLeaftide", "total": 28, "acquiredCount": 5, "activeCount": 3, +// "charms": [ { "name": "Mana Barrier", "effect": "...", "acquired": "carried"|"seen"|"no", +// "count": 1, "tier": 3, "maxTier": 5, "active": "on"|"off"|"unknown", +// "server": "on"|"off"|"unknown", "lastSeen": "2026-10-13", "toggleId": 1234567 } ], +// "hands": [ { "id": 1234568, "name": "Guardian Hand", "active": "on"|"off"|"unknown", +// "server": "on"|"off"|"unknown" } ] } +// "hands" are the Guardian Hands carried now (not a registry charm); "id" is their Toggle id. +// +// GetBankJson payload (IltBankExport.Build; read leniently): +// { "available": true, "enabled": 1, "world": "InfiniteLeaftide", "character": "Name", +// "characters": [ { "name": "Name", "current": true, "pyreals": 0, "luminance": 0, +// "legendaryKeys": 0, "mythicalKeys": 0, "enlightenedCoins": 0, +// "weaklyEnlightenedCoins": 0, "prestigeCoins": 0, "updated": "2026-10-13T21:25:37Z" } ], +// "deposits": ["Everything", ...], "withdrawals": [ { "label": "Pyreals", "notes": false } ], +// "transfers": [ { "label": "Pyreals", "notes": false } ], "notes": [ { "label": "MMD", "value": 250000 } ], +// "result": "Deposited ...", "transactions": [ { "when": "...", "type": "Sent", "amount": 1, +// "currency": "Pyreals", "player": "Who" } ] } +// "enabled": 1 the server has /bank, 0 it doesn't, -1 not known yet. +// +// BankCommand verbs (ASCII, space separated; the reply lands in "result"): +// refresh quiet /bank balance read +// deposit +// withdraw (amount = note count for trade notes) +// transfer +// The reader confirms a transfer with the player before sending it (RynthILT doesn't ask again). +// +// Version 2 (RynthILT 0.3.1) appends GetPetBreedingJson and PetBreedingCommand: the data of the +// pet breeding tracker RynthILT draws in the Mini Remote's Pets > Breeding sub-tab (and, until +// 2026-10-21, RynthOracle's Pet Breeding tab). Readers still query version 1 and accept a version-1 table, so charms +// and the bank keep working with an older RynthILT; they use the breeding functions only when +// the table says Version >= 2 and is that big (HasPetBreeding). +// +// GetPetBreedingJson payload (IltPetBreeding.BuildJson; read leniently): +// { "available": true, "world": "...", "enabled": "on"|"off"|"unknown", "maturity": "...", "bond": "...", +// "room": "landblock 0x0106 variant 2", "freeSlots": 12, "message": "...", +// "essences": [ { "id": 1234, "name": "...", "sex": "M"|"F", "tier": 150, "bond": 120, "ready": true, +// "status": "Ready (9/10)", "readyIn": 0, "charges": 9, "chargesMax": 10, "juvenile": false, +// "stage": "Adult", "kills": 300, "killsRequired": 300, "mutations": 2, "potencyMutations": 1, +// "problems": ["..."], "boosters": ["..."] } ], +// "pairs": [ { "stud": "...", "dam": "...", "chanceBest": 0.05, "chanceWorst": 0.04, "inheritMin": 0, "inheritMax": 2 } ], +// "supplies": [ { "key": "incense2", "name": "...", "effect": "...", "count": 1, "price": 2500000, "apply": true, +// "targets": [1234] } ], +// "rules": [ { "label": "...", "value": "10", "source": "seen on server", "help": "..." } ], +// "events": [ { "when": "2026-10-15 20:15", "kind": "birth", "text": "..." } ], newest first +// "debug": { "when": "...", "enabled": "on", "location": "...", "match": "valid"|"invalid"|"", "pet": "...", +// "sex": "...", "partners": 1 } } +// PetBreedingCommand verbs (ASCII): refresh | debug | dance | apply +// The reader confirms "apply" and "dance" with the player first (RynthILT doesn't ask again). +// +// Version 3 (RynthILT 0.2.20) appends GetGuardianJson and GuardianCommand (the Temple guardians, +// on RynthOracle's Quests tab until 2026-10-21). Readers use them only when Version >= 3 and the table is that big +// (HasGuardian); a version-2 table still answers charms, the bank and breeding (V2Size). +// +// GetGuardianJson payload (IltGuardian.BuildJson; read leniently): +// { "available": true, "world": "...", "chat": true, "auto": false, "buy": true, "cooldownHours": 20, +// "answer": "Pyreal", "npc": "Guardian of ...", "answerAgeSec": 42 (-1 none yet), "heard": "...", +// "running": false, "status": "idle", "synced": "2026-10-18T19:05:00Z" ("" /qb not read), +// "rows": [ { "attribute": "Strength", "npc": "...", "count": 3, "status": "Ready", "eta": "", +// "ready": true, "exact": true } ] } exact = from /myquests (else /qb estimates) +// GuardianCommand verbs (ASCII): handin | stop | refresh | chat on|off | auto on|off | buy on|off +// Auto hand-in and buying a missing Temple item run inside RynthILT whatever the reader shows. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.Shared; + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct RynthIltDataApiV1 +{ + public const string InterfaceName = "RynthILT.Data"; + public const uint InterfaceVersion = 3; + + /// The size of a version-1 table (everything before GetPetBreedingJson) on this platform. + public static uint V1Size + { + get + { + RynthIltDataApiV1 t = default; + return (uint)((byte*)&t.GetPetBreedingJson - (byte*)&t); + } + } + + /// The size of a version-2 table (everything before GetGuardianJson) on this platform. + public static uint V2Size + { + get + { + RynthIltDataApiV1 t = default; + return (uint)((byte*)&t.GetGuardianJson - (byte*)&t); + } + } + + public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down + public uint StructSize; // sizeof(RynthIltDataApiV1) as RynthILT built it + + /// + /// GetCharmsJson(buffer, capacity): the charms JSON (UTF-8, NUL-terminated) when it fits; returns + /// its length without the NUL (capacity or more = too small, nothing written; 0 = nothing to report). + /// + public delegate* unmanaged[Cdecl] GetCharmsJson; + + /// GetBankJson(buffer, capacity): the bank JSON, same contract as GetCharmsJson. + public delegate* unmanaged[Cdecl] GetBankJson; + + /// + /// ToggleCharm(objectId): uses the carried charm with that id (a "toggleId" from the charms JSON). + /// RynthILT checks it is one of the player's charms before using it. 1 = queued, 0 = refused. + /// + public delegate* unmanaged[Cdecl] ToggleCharm; + + /// BankCommand(utf8 verb line): queues a bank verb (header above). 1 = queued, 0 = refused. + public delegate* unmanaged[Cdecl] BankCommand; + + // ── Version 2 ─────────────────────────────────────────────────────────── + + /// GetPetBreedingJson(buffer, capacity): the pet breeding JSON, same contract as GetCharmsJson. + public delegate* unmanaged[Cdecl] GetPetBreedingJson; + + /// PetBreedingCommand(utf8 verb line): queues a breeding verb (header above). 1 = queued, 0 = refused. + public delegate* unmanaged[Cdecl] PetBreedingCommand; + + // ── Version 3 ─────────────────────────────────────────────────────────── + + /// GetGuardianJson(buffer, capacity): the Temple guardian JSON, same contract as GetCharmsJson. + public delegate* unmanaged[Cdecl] GetGuardianJson; + + /// GuardianCommand(utf8 verb line): queues a guardian verb (header above). 1 = queued, 0 = refused. + public delegate* unmanaged[Cdecl] GuardianCommand; +} + +/// +/// A reader of "RynthILT.Data". Looks the table up through the host, +/// re-queried while RynthILT is missing or after it unloads (Version 0), and copies a JSON out on +/// request. Pump thread only. +/// +public sealed unsafe class RynthIltDataClient +{ + private const long RequeryMs = 10_000; + private const int MaxBuffer = 256 * 1024; + private const string PluginName = "RynthILT"; + + private RynthIltDataApiV1* _table; + private long _nextQueryAt; + private byte[] _buffer = new byte[8192]; + + /// RynthILT answered with the table (last lookup). + public bool Connected => _table != null && _table->Version >= 1; + + /// The charms JSON now ("" without RynthILT). + public string ReadCharms(RynthCoreHost host, long now) + { + RynthIltDataApiV1* t = Table(host, now); + return t == null || t->GetCharmsJson == null ? "" : Read(t->GetCharmsJson); + } + + /// The bank JSON now ("" without RynthILT). + public string ReadBank(RynthCoreHost host, long now) + { + RynthIltDataApiV1* t = Table(host, now); + return t == null || t->GetBankJson == null ? "" : Read(t->GetBankJson); + } + + /// The pet breeding JSON now ("" without a RynthILT that has the tracker). + public string ReadPetBreeding(RynthCoreHost host, long now) + { + RynthIltDataApiV1* t = Table(host, now); + return !HasPetBreeding(t) || t->GetPetBreedingJson == null ? "" : Read(t->GetPetBreedingJson); + } + + /// The loaded RynthILT has the breeding tracker (table version 2 or later). + public bool PetBreedingSupported => HasPetBreeding(_table); + + /// Queues a breeding verb line (see the header). False without RynthILT or when it refused. + public bool PetBreedingCommand(RynthCoreHost host, long now, string verbLine) + { + RynthIltDataApiV1* t = Table(host, now); + if (!HasPetBreeding(t) || t->PetBreedingCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false; + byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0"); + try + { + fixed (byte* p = bytes) return t->PetBreedingCommand(p) == 1; + } + catch { return false; } + } + + private static bool HasPetBreeding(RynthIltDataApiV1* t) + => t != null && t->Version >= 2 && t->StructSize >= RynthIltDataApiV1.V2Size; + + /// The Temple guardian JSON now ("" without a RynthILT that has it, version 3). + public string ReadGuardian(RynthCoreHost host, long now) + { + RynthIltDataApiV1* t = Table(host, now); + return !HasGuardian(t) || t->GetGuardianJson == null ? "" : Read(t->GetGuardianJson); + } + + /// The loaded RynthILT has the guardian functions (table version 3 or later). + public bool GuardianSupported => HasGuardian(_table); + + /// Queues a guardian verb line (see the header). False without RynthILT or when it refused. + public bool GuardianCommand(RynthCoreHost host, long now, string verbLine) + { + RynthIltDataApiV1* t = Table(host, now); + if (!HasGuardian(t) || t->GuardianCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false; + byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0"); + try + { + fixed (byte* p = bytes) return t->GuardianCommand(p) == 1; + } + catch { return false; } + } + + private static bool HasGuardian(RynthIltDataApiV1* t) + => t != null && t->Version >= 3 && t->StructSize >= (uint)sizeof(RynthIltDataApiV1); + + /// Asks RynthILT to use a carried charm. False without RynthILT or when it refused. + public bool ToggleCharm(RynthCoreHost host, long now, uint objectId) + { + RynthIltDataApiV1* t = Table(host, now); + if (t == null || t->ToggleCharm == null || objectId == 0) return false; + try { return t->ToggleCharm(objectId) == 1; } + catch { return false; } + } + + /// Queues a bank verb line (see the header). False without RynthILT or when it refused. + public bool BankCommand(RynthCoreHost host, long now, string verbLine) + { + RynthIltDataApiV1* t = Table(host, now); + if (t == null || t->BankCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false; + byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0"); + try + { + fixed (byte* p = bytes) return t->BankCommand(p) == 1; + } + catch { return false; } + } + + /// The table, re-queried when it is missing or RynthILT has shut down (Version 0). + private RynthIltDataApiV1* Table(RynthCoreHost host, long now) + { + if (_table != null && _table->Version >= 1) return _table; + _table = null; + if (now < _nextQueryAt || !host.HasGetPluginInterface) return null; + _nextQueryAt = now + RequeryMs; + // Version 1 is asked for and a version-1-sized table taken, so an older RynthILT still answers. + var p = (RynthIltDataApiV1*)host.GetPluginInterface(PluginName, RynthIltDataApiV1.InterfaceName, 1); + if (p != null && p->Version >= 1 && p->StructSize >= RynthIltDataApiV1.V1Size) + _table = p; + return _table; + } + + /// Copies a JSON out, growing the buffer once when RynthILT says it didn't fit. + private string Read(delegate* unmanaged[Cdecl] get) + { + for (int attempt = 0; attempt < 2; attempt++) + { + int len; + try + { + fixed (byte* b = _buffer) len = get(b, _buffer.Length); + } + catch { return ""; } + if (len <= 0) return ""; + if (len < _buffer.Length) return Encoding.UTF8.GetString(_buffer, 0, len); + if (len + 1 > MaxBuffer) return ""; + _buffer = new byte[len + 1024]; + } + return ""; + } +} + +/// One registry charm from the charms JSON. +public sealed record IltCharmRow(string Name, string Effect, string Acquired, int Count, int Tier, int MaxTier, + string Active, string Server, string LastSeen, uint ToggleId) +{ + /// Carried now (in the pack or equipped). + public bool Carried => Acquired == "carried"; +} + +/// A Guardian Hand carried now: its object id (the Toggle's id), name, status and the server's switch. +public sealed record IltHandRow(uint Id, string Name, string Active, string Server); + +/// The charms JSON parsed. without RynthILT; every field read leniently. +public sealed class IltCharmsView +{ + public static readonly IltCharmsView None = new(); + + /// RynthILT answered. + public bool Loaded { get; private init; } + /// An Infinite Leaftide world (charms exist). + public bool Available { get; private init; } + public string World { get; private init; } = ""; + public int Acquired { get; private init; } + public int Active { get; private init; } + public IReadOnlyList Charms { get; private init; } = Array.Empty(); + /// The Guardian Hands carried now (none from an older RynthILT). + public IReadOnlyList Hands { get; private init; } = Array.Empty(); + + public static IltCharmsView Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return None; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return None; + var rows = new List(); + if (root.TryGetProperty("charms", out JsonElement cs) && cs.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement c in cs.EnumerateArray()) + { + if (c.ValueKind != JsonValueKind.Object) continue; + string name = IltJson.Str(c, "name"); + if (name.Length == 0) continue; + rows.Add(new IltCharmRow(name, IltJson.Str(c, "effect"), IltJson.Str(c, "acquired", "no"), + (int)IltJson.Long(c, "count"), (int)IltJson.Long(c, "tier"), (int)IltJson.Long(c, "maxTier"), + IltJson.Str(c, "active", "unknown"), IltJson.Str(c, "server", "unknown"), IltJson.Str(c, "lastSeen"), + (uint)Math.Clamp(IltJson.Long(c, "toggleId"), 0, uint.MaxValue))); + } + } + var hands = new List(); + foreach (JsonElement h in IltJson.Array(root, "hands")) + { + uint id = (uint)Math.Clamp(IltJson.Long(h, "id"), 0, uint.MaxValue); + if (id == 0) continue; // no id = nothing a Toggle could use + hands.Add(new IltHandRow(id, IltJson.Str(h, "name", "Guardian Hand"), IltJson.Str(h, "active", "unknown"), + IltJson.Str(h, "server", "unknown"))); + } + return new IltCharmsView + { + Loaded = true, + Available = IltJson.Bool(root, "available"), + World = IltJson.Str(root, "world"), + Acquired = (int)IltJson.Long(root, "acquiredCount"), + Active = (int)IltJson.Long(root, "activeCount"), + Charms = rows, + Hands = hands, + }; + } + catch (JsonException) { return None; } + } +} + +/// One character's saved bank balances from the bank JSON. +public sealed record IltBankRow(string Name, bool Current, long Pyreals, long Luminance, long LegendaryKeys, long MythicalKeys, + long EnlightenedCoins, long WeaklyEnlightenedCoins, long PrestigeCoins, DateTime UpdatedUtc); + +/// A bank form choice: its label and whether the amount is a trade-note count. +public sealed record IltBankChoice(string Label, bool Notes); + +/// A trade-note denomination: label and pyreal value. +public sealed record IltBankNote(string Label, long Value); + +/// One logged transfer. +public sealed record IltBankTx(string When, string Type, long Amount, string Currency, string Player); + +/// The bank JSON parsed. without RynthILT; every field read leniently. +public sealed class IltBankView +{ + public static readonly IltBankView None = new(); + + /// RynthILT answered. + public bool Loaded { get; private init; } + /// An Infinite Leaftide world (bank commands exist). + public bool Available { get; private init; } + /// 1 the server has /bank, 0 not, -1 not known yet. + public int Enabled { get; private init; } = -1; + public string World { get; private init; } = ""; + public string Character { get; private init; } = ""; + public string Result { get; private init; } = ""; + public IReadOnlyList Characters { get; private init; } = Array.Empty(); + public IReadOnlyList Deposits { get; private init; } = Array.Empty(); + public IReadOnlyList Withdrawals { get; private init; } = Array.Empty(); + public IReadOnlyList Transfers { get; private init; } = Array.Empty(); + public IReadOnlyList Notes { get; private init; } = Array.Empty(); + public IReadOnlyList Transactions { get; private init; } = Array.Empty(); + + public static IltBankView Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return None; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return None; + + var chars = new List(); + foreach (JsonElement c in IltJson.Array(root, "characters")) + { + string name = IltJson.Str(c, "name"); + if (name.Length == 0) continue; + DateTime updated = DateTime.MinValue; + string when = IltJson.Str(c, "updated"); + if (when.Length > 0 + && DateTime.TryParse(when, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t)) + updated = t; + chars.Add(new IltBankRow(name, IltJson.Bool(c, "current"), IltJson.Long(c, "pyreals"), IltJson.Long(c, "luminance"), + IltJson.Long(c, "legendaryKeys"), IltJson.Long(c, "mythicalKeys"), IltJson.Long(c, "enlightenedCoins"), + IltJson.Long(c, "weaklyEnlightenedCoins"), IltJson.Long(c, "prestigeCoins"), updated)); + } + + var deposits = new List(); + if (root.TryGetProperty("deposits", out JsonElement ds) && ds.ValueKind == JsonValueKind.Array) + foreach (JsonElement d in ds.EnumerateArray()) + if (d.ValueKind == JsonValueKind.String) deposits.Add(d.GetString() ?? ""); + + var notes = new List(); + foreach (JsonElement n in IltJson.Array(root, "notes")) + notes.Add(new IltBankNote(IltJson.Str(n, "label"), IltJson.Long(n, "value"))); + + var tx = new List(); + foreach (JsonElement x in IltJson.Array(root, "transactions")) + tx.Add(new IltBankTx(IltJson.Str(x, "when"), IltJson.Str(x, "type"), IltJson.Long(x, "amount"), + IltJson.Str(x, "currency"), IltJson.Str(x, "player"))); + + return new IltBankView + { + Loaded = true, + Available = IltJson.Bool(root, "available"), + Enabled = (int)Math.Clamp(IltJson.Long(root, "enabled", -1), -1, 1), + World = IltJson.Str(root, "world"), + Character = IltJson.Str(root, "character"), + Result = IltJson.Str(root, "result"), + Characters = chars, + Deposits = deposits, + Withdrawals = Choices(root, "withdrawals"), + Transfers = Choices(root, "transfers"), + Notes = notes, + Transactions = tx, + }; + } + catch (JsonException) { return None; } + } + + private static List Choices(JsonElement root, string name) + { + var list = new List(); + foreach (JsonElement c in IltJson.Array(root, name)) + list.Add(new IltBankChoice(IltJson.Str(c, "label"), IltJson.Bool(c, "notes"))); + return list; + } + + /// The bank verb lines (header of this file); pure so the tests check them. + public static string RefreshVerb() => "refresh"; + public static string DepositVerb(int index) => "deposit " + index.ToString(CultureInfo.InvariantCulture); + public static string WithdrawVerb(int index, long amount, int note) + => string.Join(' ', "withdraw", index.ToString(CultureInfo.InvariantCulture), amount.ToString(CultureInfo.InvariantCulture), + note.ToString(CultureInfo.InvariantCulture)); + public static string TransferVerb(int currency, long amount, int note, string recipient) + => string.Join(' ', "transfer", currency.ToString(CultureInfo.InvariantCulture), amount.ToString(CultureInfo.InvariantCulture), + note.ToString(CultureInfo.InvariantCulture), (recipient ?? "").Trim()); +} + +/// One carried combat essence from the pet breeding JSON. +public sealed record IltBreedEssenceRow(int Id, string Name, bool Male, int Tier, int Bond, bool Ready, string Status, long ReadyIn, + int Charges, int ChargesMax, bool Juvenile, string Stage, int Kills, int KillsRequired, + int Mutations, int PotencyMutations, IReadOnlyList Problems, IReadOnlyList Boosters); + +/// A ready stud + dam pairing and its stat mutation odds (0..1). +public sealed record IltBreedPairRow(string Stud, string Dam, double ChanceBest, double ChanceWorst, int InheritMin, int InheritMax); + +/// A breeding supply: count carried, Ivo's price, and the essence ids the server would take it on now. +public sealed record IltBreedSupplyRow(string Key, string Name, string Effect, long Count, long Price, bool Apply, IReadOnlyList Targets); + +/// One breeding rule: its value and where it came from ("seen on server", "ILT profile", "ACE default"). +public sealed record IltBreedRuleRow(string Label, string Value, string Source, string Help); + +/// One breeding event (newest first in the view). +public sealed record IltBreedEventRow(string When, string Kind, string Text); + +/// The last "@breed-debug" reply: when, the switch, where you were, the room check, your pet, partners nearby. +public sealed record IltBreedDebugRow(string When, string Enabled, string Location, string Match, string Pet, string Sex, int Partners); + +/// The pet breeding JSON parsed. without RynthILT; every field read leniently. +public sealed class IltBreedingView +{ + public static readonly IltBreedingView None = new(); + + /// RynthILT answered. + public bool Loaded { get; private init; } + public bool Available { get; private init; } + public string World { get; private init; } = ""; + /// "on", "off" or "unknown": the server's pet breeding switch as RynthILT knows it. + public string Enabled { get; private init; } = "unknown"; + public string Maturity { get; private init; } = "unknown"; + public string Bond { get; private init; } = "unknown"; + public string Room { get; private init; } = ""; + /// Free main-pack slots (-1 unknown). + public int FreeSlots { get; private init; } = -1; + public string Message { get; private init; } = ""; + public IReadOnlyList Essences { get; private init; } = Array.Empty(); + public IReadOnlyList Pairs { get; private init; } = Array.Empty(); + public IReadOnlyList Supplies { get; private init; } = Array.Empty(); + public IReadOnlyList Rules { get; private init; } = Array.Empty(); + public IReadOnlyList Events { get; private init; } = Array.Empty(); + public IltBreedDebugRow? Debug { get; private init; } + + public static IltBreedingView Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return None; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return None; + + var essences = new List(); + foreach (JsonElement e in IltJson.Array(root, "essences")) + { + string name = IltJson.Str(e, "name"); + if (name.Length == 0) continue; + essences.Add(new IltBreedEssenceRow((int)IltJson.Long(e, "id"), name, IltJson.Str(e, "sex") == "M", + (int)IltJson.Long(e, "tier"), (int)IltJson.Long(e, "bond"), IltJson.Bool(e, "ready"), IltJson.Str(e, "status"), + IltJson.Long(e, "readyIn"), (int)IltJson.Long(e, "charges"), (int)IltJson.Long(e, "chargesMax"), + IltJson.Bool(e, "juvenile"), IltJson.Str(e, "stage"), (int)IltJson.Long(e, "kills"), (int)IltJson.Long(e, "killsRequired"), + (int)IltJson.Long(e, "mutations"), (int)IltJson.Long(e, "potencyMutations"), + IltJson.Strings(e, "problems"), IltJson.Strings(e, "boosters"))); + } + + var pairs = new List(); + foreach (JsonElement p in IltJson.Array(root, "pairs")) + pairs.Add(new IltBreedPairRow(IltJson.Str(p, "stud"), IltJson.Str(p, "dam"), IltJson.Double(p, "chanceBest"), + IltJson.Double(p, "chanceWorst"), (int)IltJson.Long(p, "inheritMin"), (int)IltJson.Long(p, "inheritMax"))); + + var supplies = new List(); + foreach (JsonElement s in IltJson.Array(root, "supplies")) + { + var targets = new List(); + if (s.TryGetProperty("targets", out JsonElement ts) && ts.ValueKind == JsonValueKind.Array) + foreach (JsonElement t in ts.EnumerateArray()) + if (t.ValueKind == JsonValueKind.Number && t.TryGetInt32(out int id)) targets.Add(id); + supplies.Add(new IltBreedSupplyRow(IltJson.Str(s, "key"), IltJson.Str(s, "name"), IltJson.Str(s, "effect"), + IltJson.Long(s, "count"), IltJson.Long(s, "price"), IltJson.Bool(s, "apply"), targets)); + } + + var rules = new List(); + foreach (JsonElement r in IltJson.Array(root, "rules")) + rules.Add(new IltBreedRuleRow(IltJson.Str(r, "label"), IltJson.Str(r, "value"), IltJson.Str(r, "source"), IltJson.Str(r, "help"))); + + var events = new List(); + foreach (JsonElement ev in IltJson.Array(root, "events")) + events.Add(new IltBreedEventRow(IltJson.Str(ev, "when"), IltJson.Str(ev, "kind"), IltJson.Str(ev, "text"))); + + IltBreedDebugRow? debug = null; + if (root.TryGetProperty("debug", out JsonElement d) && d.ValueKind == JsonValueKind.Object) + debug = new IltBreedDebugRow(IltJson.Str(d, "when"), IltJson.Str(d, "enabled", "unknown"), IltJson.Str(d, "location"), + IltJson.Str(d, "match"), IltJson.Str(d, "pet"), IltJson.Str(d, "sex"), (int)IltJson.Long(d, "partners", -1)); + + return new IltBreedingView + { + Loaded = true, + Available = IltJson.Bool(root, "available"), + World = IltJson.Str(root, "world"), + Enabled = IltJson.Str(root, "enabled", "unknown"), + Maturity = IltJson.Str(root, "maturity", "unknown"), + Bond = IltJson.Str(root, "bond", "unknown"), + Room = IltJson.Str(root, "room"), + FreeSlots = (int)IltJson.Long(root, "freeSlots", -1), + Message = IltJson.Str(root, "message"), + Essences = essences, + Pairs = pairs, + Supplies = supplies, + Rules = rules, + Events = events, + Debug = debug, + }; + } + catch (JsonException) { return None; } + } + + /// The breeding verb lines (header of this file); pure so the tests check them. + public static string RefreshVerb() => "refresh"; + public static string DebugVerb() => "debug"; + public static string DanceVerb() => "dance"; + public static string ApplyVerb(string supplyKey, int essenceId) + => string.Join(' ', "apply", (supplyKey ?? "").Trim(), essenceId.ToString(CultureInfo.InvariantCulture)); +} + +/// One Temple attribute turn-in from the guardian JSON. +public sealed record IltGuardianRow(string Attribute, string Npc, int Count, string Status, string Eta, bool Ready, bool Exact); + +/// The Temple guardian JSON parsed. without RynthILT; every field read leniently. +public sealed class IltGuardianView +{ + public static readonly IltGuardianView None = new(); + + /// RynthILT answered. + public bool Loaded { get; private init; } + public bool Available { get; private init; } + public string World { get; private init; } = ""; + /// Translate the guardians' tells as they arrive. + public bool Chat { get; private init; } + /// Give the answer item to the guardian automatically after a chat answer. + public bool Auto { get; private init; } + /// Buy a missing Temple item from the nearest vendor first. + public bool Buy { get; private init; } + public int CooldownHours { get; private init; } + public string Answer { get; private init; } = ""; + public string Npc { get; private init; } = ""; + /// Seconds since the last answer (-1 none yet). + public long AnswerAgeSec { get; private init; } = -1; + public string Heard { get; private init; } = ""; + /// A hand-in is running. + public bool Running { get; private init; } + public string Status { get; private init; } = ""; + /// When /qb was last read (MinValue never). + public DateTime SyncedUtc { get; private init; } = DateTime.MinValue; + public IReadOnlyList Rows { get; private init; } = Array.Empty(); + + public static IltGuardianView Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return None; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return None; + var rows = new List(); + foreach (JsonElement r in IltJson.Array(root, "rows")) + { + string attr = IltJson.Str(r, "attribute"); + if (attr.Length == 0) continue; + rows.Add(new IltGuardianRow(attr, IltJson.Str(r, "npc"), (int)IltJson.Long(r, "count"), IltJson.Str(r, "status"), + IltJson.Str(r, "eta"), IltJson.Bool(r, "ready"), IltJson.Bool(r, "exact"))); + } + DateTime synced = DateTime.MinValue; + string when = IltJson.Str(root, "synced"); + if (when.Length > 0 + && DateTime.TryParse(when, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t)) + synced = t; + return new IltGuardianView + { + Loaded = true, + Available = IltJson.Bool(root, "available"), + World = IltJson.Str(root, "world"), + Chat = IltJson.Bool(root, "chat"), + Auto = IltJson.Bool(root, "auto"), + Buy = IltJson.Bool(root, "buy"), + CooldownHours = (int)IltJson.Long(root, "cooldownHours"), + Answer = IltJson.Str(root, "answer"), + Npc = IltJson.Str(root, "npc"), + AnswerAgeSec = IltJson.Long(root, "answerAgeSec", -1), + Heard = IltJson.Str(root, "heard"), + Running = IltJson.Bool(root, "running"), + Status = IltJson.Str(root, "status"), + SyncedUtc = synced, + Rows = rows, + }; + } + catch (JsonException) { return None; } + } + + /// The guardian verb lines (header of this file); pure so the tests check them. + public static string HandInVerb() => "handin"; + public static string StopVerb() => "stop"; + public static string RefreshVerb() => "refresh"; + /// "chat on", "auto off", "buy on": is chat, auto or buy. + public static string SwitchVerb(string name, bool on) => (name ?? "").Trim().ToLowerInvariant() + (on ? " on" : " off"); +} + +/// Lenient JSON field reads shared by the views above. +internal static class IltJson +{ + public static string Str(JsonElement o, string name, string fallback = "") => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? fallback : fallback; + + public static bool Bool(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True; + + public static long Long(JsonElement o, string name, long fallback = 0) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long l) ? l : fallback; + + public static double Double(JsonElement o, string name, double fallback = 0) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out double d) ? d : fallback; + + /// The string items of an array field (other kinds skipped). + public static List Strings(JsonElement o, string name) + { + var list = new List(); + if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return list; + foreach (JsonElement e in a.EnumerateArray()) + if (e.ValueKind == JsonValueKind.String) list.Add(e.GetString() ?? ""); + return list; + } + + public static IEnumerable Array(JsonElement o, string name) + { + if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) yield break; + foreach (JsonElement e in a.EnumerateArray()) + if (e.ValueKind == JsonValueKind.Object) yield return e; + } +} diff --git a/Plugins/Shared/RynthIltHubApi.cs b/Plugins/Shared/RynthIltHubApi.cs new file mode 100644 index 0000000..cb30689 --- /dev/null +++ b/Plugins/Shared/RynthIltHubApi.cs @@ -0,0 +1,45 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthIltHubApi.cs +// RynthILT's own names around the server hub (Shared/RynthServerHubApi.cs). +// RynthILT serves the "RynthServer.Hub" table (RynthServerHubApiV1) under that +// neutral name and under its older one, "RynthILT.Hub" (every RynthILT since the +// interface's first release answers that one). The section, tab, text, feature +// and setting ids RynthAi uses are RynthServerHub's; the ids here are Infinite +// Leaftide's alone (its sub-tab, its quest list, ACECustom's feature keys). +// Until 2026-10-21 this file held the whole interface (class RynthIltHub, +// structs RynthIltHubApiV1 / IltTabV1); the ids kept their values. +// Compiled into RynthILT only (linked source). +// ============================================================================ + +namespace RynthCore.Plugin.Shared; + +/// RynthILT's constants around the "RynthServer.Hub" interface. +public static class RynthIltHub +{ + /// The providing plugin's display name. + public const string PluginName = "RynthILT"; + + /// + /// RynthILT's own name for the RynthServer.Hub table (the same table; RynthServerHubApiV1 is its layout). + /// Older RynthAi asked for this name first. + /// + public const string InterfaceName = "RynthILT.Hub"; + + /// Quests tab: the "Quest bonus (/qb)" list. + public const string SectionQuestBonus = "quests-qb"; + /// + /// Pets tab, Breeding sub-tab: the pet breeding tracker, the sub-tab's whole body (RynthILT 0.3.1+; + /// older copies draw nothing). Since 2026-10-20 RynthAi shows it because GetSubTabs(TabParentPets) + /// lists it (RynthILT: an ILT world unless FeaturePetBreeding is off); older RynthAi decided itself. + /// + public const string SectionPetBreeding = "pets-breeding"; + + /// ACECustom feature keys (GetFeature) beside RynthServerHub.FeatureQuests. + public const string FeaturePetRefill = "pet_refill"; + public const string FeatureUniversalMastery = "universal_mastery"; + /// ACECustom siphon lenses (monster capture into a pet essence). + public const string FeatureMonsterCapture = "monster_capture"; + public const string FeatureRequireComps = "require_spell_comps"; + /// Pet breeding (the Pets tab's Breeding sub-tab is hidden while the server reports it off). + public const string FeaturePetBreeding = "pet_breeding"; +} diff --git a/Plugins/Shared/RynthIltServerApi.cs b/Plugins/Shared/RynthIltServerApi.cs new file mode 100644 index 0000000..29bca59 --- /dev/null +++ b/Plugins/Shared/RynthIltServerApi.cs @@ -0,0 +1,75 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthIltServerApi.cs +// The "RynthILT.Server" interface: what RynthILT knows about the Infinite Leaftide +// server, for any plugin that wants it without drawing RynthILT's UI (RynthOracle read it +// for its About and Quests tabs until 2026-10-21; RynthILT's settings window and Quests +// section show the same now, and no RynthSuite plugin reads it). One call hands out a JSON snapshot: whether this is an +// ILT world, every Leaftide feature RynthILT supports with the server's state for it, +// and the server's fellowship rules. +// Separate from "RynthILT.Hub" (RynthIltHubApi.cs) so that interface, which RynthAi asks +// for at an exact version, never has to change for this. +// Compiled into RynthILT and its readers (linked source), so the layout can't drift. +// +// Rules (as the other shared interfaces): +// - Append-only: new functions go at the end, and Version goes up. +// - Strings are UTF-8, NUL-terminated. The JSON itself is plain ASCII. +// - Every function returns safely (no exception crosses the boundary). +// - The table is allocated once per loaded copy of RynthILT and never freed; shutdown +// sets Version to 0, and a reader re-queries (host GetPluginInterface) when it sees that. +// +// GetProfileJson payload (every field may be missing on an older RynthILT; read leniently): +// { +// "ilt": true, // ILT world (its world list, or the character's override) +// "world": "InfiniteLeaftide", // the world name the server announced ("" before login) +// "forced": false, // "Treat this world as ILT" is on +// "source": "probe", // where the feature bits came from ("ilt-features", "probe", "") +// "checked": "2026-10-13T21:25:37Z", // last server-options check (UTC), "" = never +// "features": [ { "key": "bank", "label": "Banking", "group": "Character", +// "state": 1, "where": "Mini Remote > Banking tab" }, ... ], +// // state: 1 on, 0 off, -1 not known yet +// "fellowship": { "maxMembers": 29, "zoneShare": 1, "blackjack": 0, "luminanceShare": 1 }, +// "questBonus": { "disabled": false, "generation": 2, "count": 41, "status": "12 completed, 3 incomplete", +// "completed": [ "flag", ... ], "incomplete": [ "flag", ... ] } +// // the /qb list; ILT worlds only (generation 0 = not loaded yet) +// } +// ============================================================================ + +using System.Runtime.InteropServices; + +namespace RynthCore.Plugin.Shared; + +/// Constants of the "RynthILT.Server" interface. +public static class RynthIltServer +{ + /// The providing plugin's display name. + public const string PluginName = "RynthILT"; + + /// Feature state in the profile JSON: the server reports it on. + public const int StateOn = 1; + /// Feature state: the server reports it off. + public const int StateOff = 0; + /// Feature state: not known yet (not checked, not an ILT world, or no RynthILT). + public const int StateUnknown = -1; + + /// A retail fellowship's member limit (what a reader assumes without RynthILT). + public const int RetailFellowshipMax = 9; +} + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct RynthIltServerApiV1 +{ + public const string InterfaceName = "RynthILT.Server"; + public const uint InterfaceVersion = 1; + + public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down + public uint StructSize; // sizeof(RynthIltServerApiV1) as RynthILT built it + + /// + /// GetProfileJson(buffer, capacity): writes the profile JSON (UTF-8, NUL-terminated) into + /// buffer when it fits, and returns its length in bytes without the NUL. A return value of + /// capacity or more means nothing was written: call again with a bigger buffer. 0 = nothing + /// to report (RynthILT shutting down). Any thread (it hands out a snapshot RynthILT's pump + /// rebuilds about once a second). + /// + public delegate* unmanaged[Cdecl] GetProfileJson; +} diff --git a/Plugins/Shared/ServerPack/ServerChatRequest.cs b/Plugins/Shared/ServerPack/ServerChatRequest.cs new file mode 100644 index 0000000..4bd477e --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerChatRequest.cs @@ -0,0 +1,23 @@ +// ServerChatRequest.cs - "the server plugin just sent this command": a short time window in which the +// command's reply counts as the plugin's own, so the server's code (ServerPackPlugin.ServerChatText) +// can hide replies to its own requests and still show the same command typed by hand. A time window, +// as RynthOracle has always done it (ported from Oracle of Dereth by Advis Eveldan, MIT): these replies +// carry nothing tying them to the request. Each reply line extends it, so a long reply stays ours to its end. +// Pure: RynthServerPack.Tests covers it. +namespace RynthCore.Plugin.ServerPack; + +internal sealed class ServerChatRequest +{ + public const long WindowMs = 5000; + private long _untilMs; + + public void Sent(long nowMs) => _untilMs = nowMs + WindowMs; + public void Clear() => _untilMs = 0; + public bool Awaiting(long nowMs) => nowMs < _untilMs; + + /// A reply line arrived: keep the window open a little longer. + public void Extend(long nowMs) + { + if (Awaiting(nowMs)) _untilMs = nowMs + 2000 > _untilMs ? nowMs + 2000 : _untilMs; + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackExports.cs b/Plugins/Shared/ServerPack/ServerPackExports.cs new file mode 100644 index 0000000..57dc39d --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackExports.cs @@ -0,0 +1,159 @@ +// ServerPackExports.cs - The native exports every server plugin has (compiled into each one). +// UnmanagedCallersOnly entry points can't live in a generic or shared assembly, so each server +// plugin compiles this file itself, around its own ServerPackPlugin. +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.ServerPack; + +public static unsafe class ServerPackExports +{ + private static readonly RynthPluginRuntime Runtime = new(); + + /// The live plugin (null before init and after shutdown). + internal static ServerPackPlugin? Plugin => Runtime.Plugin; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); + + /// + /// Plugin API v68 plugin-to-plugin interfaces: "RynthServer.Profile" v1 (ServerPackInterface), + /// the server's settings for any plugin RynthCore's GetServerStateJson points at this one, and + /// "RynthServer.QuestPack" v1, the server's own quest list when the plugin has one. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })] + private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version) + { + try + { + string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? ""; + return ServerPackInterface.Query(iface, version); + } + catch + { + return IntPtr.Zero; // an exception crossing UnmanagedCallersOnly would fail-fast the client + } + } + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Shutdown() + { + try { ServerPackInterface.Release(); } catch { } + Runtime.Shutdown(); + IntPtr old = Interlocked.Exchange(ref _sectionsPtr, IntPtr.Zero); + if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old); + _sectionsJson = null; + } + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetName() => ServerPackPlugin.NamePointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetVersion() => ServerPackPlugin.VersionPointer; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Tick() => Runtime.OnTick(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnLoginComplete() => Runtime.OnLoginComplete(); + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnLogout() => Runtime.OnLogout(); + + // "/rserver ..." commands. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag); + + // Incoming chat, for the server's own code (ServerPackPlugin.ServerChatText). Pump thread. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); + + /// The standalone server card ("/rserver"). Render thread. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void Render() + { + try { Runtime.OnRender(); } + catch { /* an exception crossing UnmanagedCallersOnly would fail-fast the client */ } + } + + /// + /// The engine's plugin-command broker: "servermenu" from RynthCore (2026.10.5.48+). The ANSI + /// strings are copied before returning (the caller frees them); the payload is only parsed, so + /// any thread is fine. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi) + { + try + { + string action = actionAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(actionAnsi) ?? string.Empty) : string.Empty; + if (action.Length == 0 || action.Length > 32) return; + string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty; + Runtime.Plugin?.ApplyRemoteCommand(action, value); + } + catch { /* never let a managed exception cross the native boundary */ } + } + + /// + /// RynthCore's Mini Remote sections: "section:server-<id>" (":popout" added in a popped-out + /// window) draws the server card into the engine's current window, "section:server-<id>.<page>" + /// one of the server's own pages (ServerPackPages). 1 = drawn, 0 = not ready or not ours. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })] + public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight) + { + try + { + if (surface == null) return 0; + string name = Marshal.PtrToStringUTF8((IntPtr)surface) ?? string.Empty; + if (name.EndsWith(":popout", StringComparison.Ordinal)) name = name[..^":popout".Length]; + var plugin = Runtime.Plugin; + if (plugin == null) return 0; + float wantH; + if (name.Equals(ServerPackPlugin.SettingsSurface, StringComparison.Ordinal)) + { + if (!plugin.RenderEmbeddedCard(out wantH)) return 0; + } + else + { + string? page = ServerPackPages.PageIdOf(name, RynthPluginInfo.ServerId); + if (page == null || !plugin.RenderEmbeddedPage(page, out wantH)) return 0; + } + if (wantWidth != null) *wantWidth = width; + if (wantHeight != null) *wantHeight = wantH; + return 1; + } + catch + { + return 0; // an exception crossing UnmanagedCallersOnly would fail-fast the client + } + } + + private static IntPtr _sectionsPtr = IntPtr.Zero; + private static string? _sectionsJson; + + /// + /// RynthCore 2026.10.5.46+: the server and the card's Mini Remote spot (UTF-8 JSON, schema 1). + /// Null before login. An unchanged manifest keeps the same buffer. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetSectionsJson() + { + try + { + string? json = Runtime.Plugin?.BuildSectionsJson(); + if (json == null) return IntPtr.Zero; + if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr; + _sectionsJson = json; + IntPtr newPtr = Marshal.StringToCoTaskMemUTF8(json); + IntPtr oldPtr = Interlocked.Exchange(ref _sectionsPtr, newPtr); + if (oldPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(oldPtr); + return newPtr; + } + catch { return IntPtr.Zero; } + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackInfo.cs b/Plugins/Shared/ServerPack/ServerPackInfo.cs new file mode 100644 index 0000000..b7a6d8f --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackInfo.cs @@ -0,0 +1,110 @@ +// ServerPackInfo.cs - What a server plugin knows about its game server (shared by every server plugin). +// +// Identity (id, name, hosts, world names) comes from the plugin's csproj through RynthPluginInfo, the +// same values the engine reads from the embedded manifest, so detection has one source. The rest is +// what is publicly known about the server (ServerData.cs in each project): connection, rule set, +// summary, links, account limits and the botting policy. Unknown stays empty; nothing is guessed. +// Pure: RynthServerPack.Tests compiles it. +using System; + +namespace RynthCore.Plugin.ServerPack; + +/// What the server's rules say about bots (RynthAi automation). +internal enum BottingPolicy +{ + /// Not published here: check the server's own rules. + Unknown, + Allowed, + /// Allowed with limits (attended only, a client cap, ...): see . + Restricted, + /// The server forbids bots. + Forbidden, +} + +/// A chat command the server adds, and what it does. +internal sealed record ServerCommand(string Command, string What); + +/// +/// A salvage the server's own recipes apply (beyond retail tinkering), shown on the Mini Remote's +/// Crafting tab under "Server tinkering". +/// +/// The Crafting tab: "armor", "melee", "missile", "caster", "jewelry", "items" or "trinkets". +/// The bag's MaterialType (131), e.g. 64 = Steel. +/// What it does, one short line. +/// "tink" (repeatable), "imbue" (one per item) or "once" (one application). +/// Counts toward the item's 10 tinks. +/// The bag's name must contain this (bags that share a material id); "" = any. +/// An int property of the item that reads 2 once this salvage is on it (0 = none). +/// The bag must first be prepared on the chosen tier's Ammunition (its name then carries the tier). +/// Apply order on the tab (lower first); 0 = by kind (imbues, then tinks, then one-application rows). +/// Applied last, and only once the item's tink slots are full. +/// Rows with the same group share one cap per item (); "" = none. +/// The group's combined cap per item (with ). +internal sealed record ServerSalvage(string Bench, int Material, string Effect, string Kind = "tink", + bool UsesTinkSlot = true, string NameMatch = "", int AppliedInt = 0, + bool Prepared = false, int Order = 0, bool AfterCap = false, + string StackGroup = "", int StackCap = 0); + +internal sealed class ServerPackInfo +{ + public ServerPackInfo(string id, string name, string[] hosts, string[] worldNames) + { + Id = (id ?? string.Empty).Trim().ToLowerInvariant(); + Name = string.IsNullOrWhiteSpace(name) ? Id : name.Trim(); + Hosts = hosts ?? Array.Empty(); + WorldNames = worldNames ?? Array.Empty(); + } + + /// The engine's id for the server ("coldeve"); a built-in one ("ilt", "aelrynth") keeps the engine's own detection. + public string Id { get; } + public string Name { get; } + /// Connect hosts (the first is the one players are given). + public string[] Hosts { get; } + /// World names the server announces at login. + public string[] WorldNames { get; } + + public int Port { get; init; } = 9000; + /// "ACE" or "GDLE" (the launcher's emulator setting). + public string Emulator { get; init; } = "ACE"; + /// "PvE" or "PvP". + public string Ruleset { get; init; } = "PvE"; + /// "Stable", "Development", ... as the server list says. + public string Status { get; init; } = string.Empty; + /// The server's own one-paragraph description. + public string Summary { get; init; } = string.Empty; + /// Notable rules and features, one line each. + public string[] Facts { get; init; } = Array.Empty(); + /// Chat commands the server adds (only ones known to exist). + public ServerCommand[] Commands { get; init; } = Array.Empty(); + /// The server's own tinkering salvage (only recipes known to exist); empty = none defined. + public ServerSalvage[] Salvage { get; init; } = Array.Empty(); + /// + /// Jewelry that is a trinket on this server (the Crafting tab's Trinkets bench, not Jewelry): name + /// words, case-insensitive, and words that rule a name out again ("top" but not "topaz"). Empty: + /// the server has no trinkets (retail: every jewelry piece is Jewelry). + /// + public string[] TrinketNames { get; init; } = Array.Empty(); + public string[] TrinketExcept { get; init; } = Array.Empty(); + /// "3 accounts", "3 active characters", ...; empty when not published. + public string AccountLimit { get; init; } = string.Empty; + public BottingPolicy Botting { get; init; } = BottingPolicy.Unknown; + /// The rule in the server's words, when there is one. + public string BottingNote { get; init; } = string.Empty; + public string Discord { get; init; } = string.Empty; + public string Website { get; init; } = string.Empty; + public string Wiki { get; init; } = string.Empty; + /// Where the facts come from, and when they were checked. + public string Source { get; init; } = string.Empty; + + /// "play.coldeve.ac:9000" (the first host), or "" with none. + public string Address => Hosts.Length == 0 ? string.Empty : Hosts[0] + ":" + Port; + + /// The botting line for the card. + public string BottingText => Botting switch + { + BottingPolicy.Allowed => "Allowed" + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty), + BottingPolicy.Restricted => "Restricted" + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty), + BottingPolicy.Forbidden => "Forbidden" + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty), + _ => "Not published here - check the server's rules" + (Discord.Length > 0 ? " (Discord)" : string.Empty), + }; +} diff --git a/Plugins/Shared/ServerPack/ServerPackInterface.cs b/Plugins/Shared/ServerPack/ServerPackInterface.cs new file mode 100644 index 0000000..4cb9ea4 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackInterface.cs @@ -0,0 +1,138 @@ +// ServerPackInterface.cs - A server plugin's side of "RynthServer.Profile" +// (Plugins/Shared/RynthServerProfileApi.cs): the server's settings as JSON (ServerPackProfile) for +// other plugins, answered through RynthPluginQueryInterface (ServerPackExports). Since 2026-10-21 also +// "RynthServer.QuestPack" (Plugins/Shared/RynthServerQuestPackApi.cs): the server's own quest list +// (ServerPackQuestPack), offered only by a plugin whose project has one. +// +// The tables are allocated once per loaded copy of the plugin and never freed (a plugin DLL is never +// unloaded); after Release() they report Version 0 and their functions answer 0. Before the plugin is +// up, or between characters, the profile still describes the server (active false, no world). +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.ServerPack; + +internal static unsafe class ServerPackInterface +{ + private static RynthServerProfileApiV1* _table; + private static RynthServerQuestPackApiV1* _packTable; + private static volatile bool _released; + // The quest pack's info JSON, built once (the pack is embedded and never changes). + private static string? _packInfo; + + /// The last JSON handed out, and what it was built for (rebuilt only when that changes). + private sealed record Snapshot(bool Active, string World, int ValuesRevision, string Json); + private static Snapshot? _last; + + /// The table for (, ), or 0 when it isn't ours. + public static IntPtr Query(string iface, uint version) + { + if (iface == RynthServerQuestPackApiV1.InterfaceName) return QueryQuestPack(version); + if (iface != RynthServerProfileApiV1.InterfaceName || version < 1 || version > RynthServerProfileApiV1.InterfaceVersion || _released) + return IntPtr.Zero; + if (_table == null) + { + var t = (RynthServerProfileApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerProfileApiV1)); + t->StructSize = (uint)sizeof(RynthServerProfileApiV1); + t->GetProfileJson = &GetProfileJson; + t->Version = RynthServerProfileApiV1.InterfaceVersion; + _table = t; + } + return (IntPtr)_table; + } + + /// + /// "RynthServer.QuestPack": the table when this plugin has a pack (Resources\quests.<id>.csv), + /// else 0, so a reader sees "no pack" the same way as "no such plugin". + /// + private static IntPtr QueryQuestPack(uint version) + { + if (version < 1 || version > RynthServerQuestPackApiV1.InterfaceVersion || _released) return IntPtr.Zero; + if (PackInfoJson().Length == 0) return IntPtr.Zero; + if (_packTable == null) + { + var t = (RynthServerQuestPackApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerQuestPackApiV1)); + t->StructSize = (uint)sizeof(RynthServerQuestPackApiV1); + t->GetPackInfoJson = &GetPackInfoJson; + t->GetPackCsv = &GetPackCsv; + t->Version = RynthServerQuestPackApiV1.InterfaceVersion; + _packTable = t; + } + return (IntPtr)_packTable; + } + + /// The pack's info JSON ("" without a pack). Any thread. + private static string PackInfoJson() => + _packInfo ??= ServerPackQuestPack.BuildInfoJson(ServerPackPlugin.StaticInfo, RynthPluginInfo.Name, + RynthPluginInfo.Version.Length > 0 ? RynthPluginInfo.Version : "0.1.0", ServerPackQuestPack.Csv); + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetPackInfoJson(byte* buffer, int capacity) + { + try { return _released ? 0 : Write(PackInfoJson(), buffer, capacity); } + catch { return 0; } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetPackCsv(byte* buffer, int capacity) + { + try { return _released || PackInfoJson().Length == 0 ? 0 : Write(ServerPackQuestPack.Csv, buffer, capacity); } + catch { return 0; } + } + + /// Plugin shutdown: readers see Version 0 and re-query; the functions answer 0. + public static void Release() + { + _released = true; + if (_table != null) _table->Version = 0; + if (_packTable != null) _packTable->Version = 0; + } + + /// The JSON to hand out now. Any thread: the plugin's state is read through volatile fields. + internal static string CurrentJson(ServerPackPlugin? plugin) + { + ServerPackInfo info = plugin?.Info ?? ServerPackPlugin.StaticInfo; + bool active = plugin?.Active ?? false; + string world = plugin?.World ?? string.Empty; + int valuesRevision = plugin?.ProfileValues.Revision ?? -1; + Snapshot? last = Volatile.Read(ref _last); + if (last != null && last.Active == active && last.World == world && last.ValuesRevision == valuesRevision) return last.Json; + KeyValuePair[] values = plugin != null + ? plugin.ProfileValues.Snapshot(out valuesRevision) + : Array.Empty>(); + string json = ServerPackProfile.BuildJson(info, RynthPluginInfo.Name, RynthPluginInfo.Version, active, world, values); + Volatile.Write(ref _last, new Snapshot(active, world, valuesRevision, json)); + return json; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetProfileJson(byte* buffer, int capacity) + { + try + { + if (_released) return 0; + return Write(CurrentJson(ServerPackExports.Plugin), buffer, capacity); + } + catch { return 0; } + } + + /// + /// Copies as NUL-terminated UTF-8 into the caller's buffer when it fits, + /// and returns its byte length either way (length >= capacity: too small, nothing written). + /// The quest pack's CSV goes the same way. + /// + internal static int Write(string json, byte* buffer, int capacity) + { + int length = Encoding.UTF8.GetByteCount(json); + if (buffer == null || capacity <= length) return length; + fixed (char* src = json) + Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity); + buffer[length] = 0; + return length; + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackModel.cs b/Plugins/Shared/ServerPack/ServerPackModel.cs new file mode 100644 index 0000000..b38ad05 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackModel.cs @@ -0,0 +1,242 @@ +// ServerPackModel.cs - A server plugin's view of "is this my server", and what it tells RynthCore. +// +// RynthCore owns the verdict. Each server plugin declares its server in its Mini Remote sections +// manifest (RynthPluginGetSectionsJson, "servers"), so RynthCore detects it (connect host, then the +// announced world name), applies this character's Auto / On / Off override, and pushes the result +// to the plugin as "servermenu" (RynthCore UI/ServerMenus.cs): +// V id name active 0/1 force auto|on|off detected 0/1 reason +// Other line kinds are RynthAi's menus and are skipped. Until a push arrives (an engine older than +// 2026.10.5.48), the plugin falls back to matching the world name itself. +// +// Pushes arrive on whichever thread sent them; each is parsed into one immutable view and published +// with a single reference write, so the render thread always reads a whole one. +// Pure (no host calls): RynthServerPack.Tests covers it. +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; + +namespace RynthCore.Plugin.ServerPack; + +/// RynthCore's verdict for this plugin's server. +internal sealed record ServerVerdictView(string Name, bool Active, string Force, bool Detected, string Reason); + +internal sealed class ServerPackModel +{ + /// Payloads longer than this are not ours (a push is a few hundred bytes). + public const int MaxPayload = 64 * 1024; + + private readonly ServerPackInfo _info; + private ServerVerdictView? _engine; + private long _engineAtMs; + + public ServerPackModel(ServerPackInfo info) => _info = info; + + public ServerPackInfo Info => _info; + + /// The last RynthCore verdict for this server (null until a push lists it). Any thread. + public ServerVerdictView? Engine => Volatile.Read(ref _engine); + + /// When the last push arrived (Environment.TickCount64), 0 for never. + public long EngineAtMs => Interlocked.Read(ref _engineAtMs); + + /// A RynthCore "servermenu" push. Any thread. False when it was not usable. + public bool ApplyEngine(string? payload, long nowMs) + { + ServerVerdictView? view = ParseEngine(payload, _info.Id, out bool listed); + if (!listed) return false; + Volatile.Write(ref _engine, view); + Interlocked.Exchange(ref _engineAtMs, nowMs); + return true; + } + + /// Logout: the next character's verdict comes fresh. + public void Clear() + { + Volatile.Write(ref _engine, null); + Interlocked.Exchange(ref _engineAtMs, 0); + } + + /// + /// True when this plugin should act: RynthCore's verdict when it sent one, else the world + /// name () against the plugin's own list. + /// + public bool IsActive(string? world) + { + ServerVerdictView? v = Engine; + return v != null ? v.Active : WorldMatches(world, _info.WorldNames); + } + + /// + /// The verdict for in a "servermenu" payload. + /// is false when the payload has no server lines at all (not a push); the view is null when it has + /// some but not this server (RynthCore hasn't read this plugin's manifest yet). + /// + public static ServerVerdictView? ParseEngine(string? payload, string serverId, out bool listed) + { + listed = false; + if (string.IsNullOrEmpty(payload) || payload.Length > MaxPayload || string.IsNullOrEmpty(serverId)) return null; + ServerVerdictView? view = null; + foreach (string raw in payload.Split('\n')) + { + string[] f = raw.TrimEnd('\r').Split('\t'); + if (f[0] != "V" || f.Length < 6) continue; + listed = true; + if (!f[1].Equals(serverId, StringComparison.OrdinalIgnoreCase)) continue; + view = new ServerVerdictView(f[2], f[3] == "1", NormalizeForce(f[4]), f[5] == "1", f.Length >= 7 ? f[6] : string.Empty); + } + return view; + } + + /// "auto", "on" or "off" (anything else reads as auto). + public static string NormalizeForce(string? text) + { + string t = (text ?? string.Empty).Trim().ToLowerInvariant(); + return t is "on" or "off" ? t : "auto"; + } + + /// "/rc server {id} {mode}" for auto / on / off; "" for anything else. + public static string ForceCommand(string serverId, string mode) + { + string m = (mode ?? string.Empty).Trim().ToLowerInvariant(); + if (m is not ("auto" or "on" or "off") || !IsSafeId(serverId)) return string.Empty; + return "/rc server " + serverId + " " + m; + } + + /// True for an id RynthCore accepts in a command: 1-32 of a-z, 0-9 and '-'. + public static bool IsSafeId(string? id) + { + if (string.IsNullOrEmpty(id) || id.Length > 32) return false; + foreach (char c in id) + if (!(c is >= 'a' and <= 'z' || c is >= '0' and <= '9' || c == '-')) return false; + return true; + } + + /// Case-insensitive world-name match, '*' standing for any text (RynthCore's rules). + public static bool WorldMatches(string? world, string[] patterns) + { + if (string.IsNullOrWhiteSpace(world)) return false; + string w = world.Trim(); + foreach (string p in patterns) + if (!string.IsNullOrWhiteSpace(p) && Glob(w, p.Trim())) return true; + return false; + } + + private static bool Glob(string text, string pattern) + { + if (!pattern.Contains('*')) return text.Equals(pattern, StringComparison.OrdinalIgnoreCase); + string[] parts = pattern.Split('*'); + int pos = 0; + for (int i = 0; i < parts.Length; i++) + { + string part = parts[i]; + if (part.Length == 0) continue; + if (i == 0) + { + if (!text.StartsWith(part, StringComparison.OrdinalIgnoreCase)) return false; + pos = part.Length; + continue; + } + if (i == parts.Length - 1) + return text.Length - pos >= part.Length && text.EndsWith(part, StringComparison.OrdinalIgnoreCase); + int at = text.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase); + if (at < 0) return false; + pos = at + part.Length; + } + return true; + } + + // ── RynthPluginGetSectionsJson ──────────────────────────────────────── + + /// The Mini Remote surface of the server card. + public static string SurfaceFor(string serverId) => "section:server-" + serverId; + + /// + /// The Mini Remote section the server cards share: right after Session Stats (core order 0) and + /// before Map (100). Every server plugin declares it the same way; the first declaration wins. + /// + public const string SectionId = "server"; + public const string SectionLabel = "Server"; + public const int SectionOrder = 50; + + /// + /// The plugin's sections manifest (schema 1): its server, for RynthCore to detect, and the server + /// card in the shared "Server" section, shown only while that server is active (detected or + /// forced in RynthCore Options > Diagnostics). The card left the Char section on 2026-10-13: that + /// section is Session Stats now, session stats only. + /// (ServerPackPages, already validated) are the server's own views: + /// primary views of the same section, so each gets a sub-tab there, also only on that server. + /// + public static string BuildSectionsJson(ServerPackInfo info, string pluginName, IReadOnlyList? pages = null) + { + var sb = new StringBuilder(512); + sb.Append("{\"version\":1,\"servers\":[{\"id\":").Append(Q(info.Id)).Append(",\"name\":").Append(Q(info.Name)); + sb.Append(",\"worldNames\":["); + AppendList(sb, info.WorldNames); + sb.Append("],\"hosts\":["); + AppendList(sb, info.Hosts); + sb.Append("]}],\"sections\":[{\"id\":").Append(Q(SectionId)).Append(",\"label\":").Append(Q(SectionLabel)); + sb.Append(",\"order\":").Append(SectionOrder).Append("}],\"contributions\":[{\"section\":").Append(Q(SectionId)); + sb.Append(",\"server\":").Append(Q(info.Id)); + sb.Append(",\"label\":").Append(Q(info.Name + " server (" + pluginName + ")")); + sb.Append(",\"surface\":").Append(Q(SurfaceFor(info.Id))); + sb.Append(",\"primary\":false,\"height\":320,\"enabled\":true,\"tooltip\":"); + sb.Append(Q("What is known about " + info.Name + ": rules, account limits, botting policy, links and setup (" + + pluginName + "; also /rserver).")); + sb.Append(",\"order\":130}"); + if (pages != null) + { + for (int i = 0; i < pages.Count; i++) + { + ServerPage p = pages[i]; + sb.Append(",{\"section\":").Append(Q(SectionId)); + sb.Append(",\"server\":").Append(Q(info.Id)); + sb.Append(",\"label\":").Append(Q(p.Label)); + sb.Append(",\"surface\":").Append(Q(ServerPackPages.SurfaceFor(info.Id, p.Id))); + sb.Append(",\"primary\":true,\"width\":").Append(ServerPackPages.Width).Append(",\"height\":").Append(ServerPackPages.Height); + sb.Append(",\"enabled\":true,\"tooltip\":").Append(Q(p.Tooltip.Length > 0 ? p.Tooltip : p.Label + " (" + pluginName + ")")); + sb.Append(",\"order\":").Append(100 + i).Append('}'); + } + } + sb.Append("]}"); + return sb.ToString(); + } + + private static void AppendList(StringBuilder sb, string[] values) + { + for (int i = 0; i < values.Length; i++) sb.Append(i == 0 ? "" : ",").Append(Q(values[i])); + } + + /// A JSON string literal. + public static string Q(string? s) + { + var sb = new StringBuilder((s?.Length ?? 0) + 2).Append('"'); + foreach (char c in s ?? string.Empty) + { + 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: + if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4")); + else sb.Append(c); + break; + } + } + return sb.Append('"').ToString(); + } + + // ── The launcher side ───────────────────────────────────────────────── + + /// How to set up an account for this server in the RynthCore launcher. + public static string[] LauncherSteps(ServerPackInfo info) => new[] + { + "1. Launcher > Servers > Add: pick \"" + info.Name + "\" under Known server. It fills in " + + (info.Address.Length > 0 ? info.Address : "the host and port") + " (" + info.Emulator + ").", + "2. Launcher > Accounts > Add: choose that server, then the account and character.", + "3. Launch: RynthCore loads this plugin only for clients connecting to " + info.Name + ".", + }; +} diff --git a/Plugins/Shared/ServerPack/ServerPackPages.cs b/Plugins/Shared/ServerPack/ServerPackPages.cs new file mode 100644 index 0000000..a45f327 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackPages.cs @@ -0,0 +1,86 @@ +// ServerPackPages.cs - Pages a server plugin adds beside its server card (RynthConquest's Conquest and +// Leaderboards pages, RynthAelrynth's Leaderboards, ...). +// +// A server's own features need somewhere to show. The ServerPackPlugin.ServerPages hook lists them +// once, at construction; the shared code then +// * declares each one in the sections manifest as a primary view of the shared "Server" section, +// shown only while this plugin's server is active (contribution "server": ), so RynthCore's +// Mini Remote gives it a sub-tab next to the server card; +// * draws it through RynthPluginRenderEmbed under the surface "section:server-." +// (":popout" added in a popped-out window), into the engine's current window and context; +// * shows the same pages as tabs of the standalone "/rserver" window, after the card. +// Draw runs on the render thread: a page reads its state under its own lock and queues anything it +// sends for the plugin tick (ServerPackPlugin.RunOnTick). +// Pure (no ImGui, no host calls): RynthServerPack.Tests covers it. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.ServerPack; + +/// +/// One page a server plugin adds. is 1-16 of a-z, 0-9 and '-' (part of the +/// surface name); draws the body into the current ImGui window (render thread). +/// +internal sealed record ServerPage(string Id, string Label, string Tooltip, Action Draw); + +internal static class ServerPackPages +{ + /// At most this many pages per plugin (the Mini Remote shows them as one row of tabs). + public const int MaxPages = 6; + /// The longest page id (keeps "section:server-<32-char id>.<page>" under the engine's 64). + public const int MaxIdLength = 16; + /// The engine caps contribution labels at 48 characters. + public const int MaxLabelLength = 48; + /// Page views open at this size in the Mini Remote (it fits the window to the view). + public const int Width = 540, Height = 520; + + /// True for a page id: 1-16 of a-z, 0-9 and '-'. + public static bool IsValidId(string? id) + { + if (string.IsNullOrEmpty(id) || id.Length > MaxIdLength) return false; + foreach (char c in id) + if (!(c is >= 'a' and <= 'z' || c is >= '0' and <= '9' || c == '-')) return false; + return true; + } + + /// "section:server-conquest.bank": the page's surface. + public static string SurfaceFor(string serverId, string pageId) => ServerPackModel.SurfaceFor(serverId) + "." + pageId; + + /// + /// The page id a surface names for this server ("section:server-conquest.bank" -> "bank"), or + /// null for the card, another server's surface or anything else. ":popout" is ignored. + /// + public static string? PageIdOf(string? surface, string serverId) + { + if (string.IsNullOrEmpty(surface)) return null; + string name = surface.EndsWith(":popout", StringComparison.Ordinal) ? surface[..^":popout".Length] : surface; + string prefix = ServerPackModel.SurfaceFor(serverId) + "."; + if (!name.StartsWith(prefix, StringComparison.Ordinal)) return null; + string id = name[prefix.Length..]; + return IsValidId(id) ? id : null; + } + + /// + /// The pages kept from what a plugin listed: valid, unique ids, a label, at most + /// ; each one dropped is reported to . + /// + public static List Validate(IEnumerable? pages, Action? log = null) + { + var kept = new List(); + if (pages == null) return kept; + foreach (ServerPage p in pages) + { + if (p == null) continue; + string why = !IsValidId(p.Id) ? "its id isn't 1-16 of a-z, 0-9 and '-'" + : string.IsNullOrWhiteSpace(p.Label) ? "it has no label" + : p.Draw == null ? "it has nothing to draw" + : kept.Exists(k => k.Id == p.Id) ? "another page has its id" + : kept.Count >= MaxPages ? $"a plugin has at most {MaxPages} pages" + : string.Empty; + if (why.Length > 0) { log?.Invoke($"Page '{p.Id}' left out: {why}."); continue; } + string label = p.Label.Trim(); + kept.Add(p with { Label = label.Length <= MaxLabelLength ? label : label[..MaxLabelLength], Tooltip = p.Tooltip ?? string.Empty }); + } + return kept; + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackPlugin.cs b/Plugins/Shared/ServerPack/ServerPackPlugin.cs new file mode 100644 index 0000000..ebc342a --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackPlugin.cs @@ -0,0 +1,400 @@ +// ServerPackPlugin.cs - The shared body of every server plugin (RynthColdeve, RynthAelrynth, ...), +// built like RynthILT: one plugin per game server, so each one ships and updates on its own. +// +// What it does for its server: +// * declares the server to RynthCore (RynthPluginGetSectionsJson "servers": its hosts and world +// names), so RynthCore detects it and puts this plugin's views in the right Mini Remote spots +// (contributions with "server": show only while that server is active); +// * shows the server card (ServerPackUi): RynthCore's verdict, this character's override, what is +// known about the server, and how to set an account up for it in the launcher; +// * stays quiet anywhere else. RynthCore usually doesn't even load it there: the embedded manifest +// names the server's hosts, and the engine loads only the plugin for the host the client +// connects to (PluginManifestGate.SelectServerPlugins). +// +// Server-specific features: add files to the server's project implementing the partial hooks below +// (ServerLoginComplete, ServerTick, ServerChatCommand, ...). Unimplemented hooks compile away. +// +// What the shared code gives a server's own features (added 2026-10-20, when RynthOracle's and +// RynthInventory's Conquest and Aelrynth features moved into RynthConquest and RynthAelrynth, so a +// shared plugin carries nothing for one server): +// ServerPages(list) pages of its own (ServerPackPages.cs): sub-tabs of the Mini Remote's +// Server section, only while its server is active, and tabs of the +// /rserver window. Draw runs on the render thread. +// ServerChatText(...) every incoming chat line (pump thread), to read the server's replies +// and hide the ones answering the plugin's own requests (eat). +// ServerChatBar(text) every line sent through the chat bar (AC's thread: note it only), +// to tell the player's typed command from the plugin's own. +// Settings the plugin's own settings file (ServerPackSettings.cs), loaded before +// ServerInitialize; MigrateOnce imports a setting from its old home. +// SetProfileValue(key, n) a live number in its "RynthServer.Profile" ("values"), for other +// plugins that apply a server rule without knowing the server. +// ServerCommandVerbs(list) its own "/rserver " words, handled in ServerChatCommand. +// RunOnTick(action) work for the next tick (a page's button, on the render thread). +// Send(command) a chat command as if typed (pump thread, logged in only); +// LogTagged(text) the engine log, "[RynthConquest] ..."; ChatLine(text) the chat window. +// Resources\quests..csv (no code) the server's own quest list: embedded by ServerPlugin.props and +// offered to RynthOracle through "RynthServer.QuestPack" (ServerPackQuestPack.cs, +// added 2026-10-21 when the packs left RynthOracle). +// The tick, chat and command hooks only run while a character is logged in; each +// should check Active itself, since the plugin can be loaded for a world that isn't its server. +// +// Threads: OnTick, login/logout, chat lines and the engine's export calls run on the plugin pump. +// OnChatBarEnter runs on AC's main thread, so it only queues. The card and the pages draw on the +// render thread (OnRender, RynthPluginRenderEmbed) and queue their commands for the tick. +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using ImGuiNET; +using RynthCore.PluginCore; + +namespace RynthCore.Plugin.ServerPack; + +public sealed partial class ServerPackPlugin : RynthPluginBase +{ + internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi(RynthPluginInfo.Name); + internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi( + RynthPluginInfo.Version.Length > 0 ? RynthPluginInfo.Version : "0.1.0"); + + /// The chat command every server plugin answers ("/rserver [show|hide|toggle|info]"). + internal const string ChatCommand = "/rserver"; + + /// The card's surface in RynthCore's Mini Remote sections ("section:server-coldeve"). + internal static readonly string SettingsSurface = ServerPackModel.SurfaceFor(RynthPluginInfo.ServerId); + + private readonly ServerPackModel _model; + private readonly ServerPackUi _ui; + private readonly string _sectionsJson; + // The server's own pages (ServerPages), validated; what was left out is logged at Initialize. + private readonly List _pages; + private readonly List _pageNotes = new(); + private readonly ServerPackSettings _settings = new(ServerPackSettings.DefaultPath(RynthPluginInfo.Name)); + private readonly ServerProfileValues _profileValues = new(); + // RynthCore commands from the card (render thread), run on the next tick. + private readonly ConcurrentQueue _engineCommands = new(); + // "/rserver ..." lines from OnChatBarEnter, run on the next tick. + private readonly ConcurrentQueue _commands = new(); + // The server code's work for the tick (RunOnTick: its pages' buttons). + private readonly ConcurrentQueue _tickActions = new(); + // The server's own "/rserver" verbs (ServerCommandVerbs). + private readonly HashSet _serverVerbs = new(StringComparer.OrdinalIgnoreCase); + private volatile bool _loginComplete; + private volatile string? _world; + private bool _wasActive; + + public ServerPackPlugin() + { + ServerPackInfo info = ServerData.Create(); + _model = new ServerPackModel(info); + var pages = new List(); + ServerPages(pages); + _pages = ServerPackPages.Validate(pages, _pageNotes.Add); + var verbs = new List(); + ServerCommandVerbs(verbs); + foreach (string v in verbs) if (!string.IsNullOrWhiteSpace(v)) _serverVerbs.Add(v.Trim()); + _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages); + _sectionsJson = ServerPackModel.BuildSectionsJson(info, RynthPluginInfo.Name, _pages); + } + + internal ServerPackInfo Info => _model.Info; + + private static ServerPackInfo? _staticInfo; + + /// The server's facts before the plugin object exists ("RynthServer.Profile" asked early). + internal static ServerPackInfo StaticInfo => _staticInfo ??= ServerData.Create(); + + /// RynthCore (or the world name) says this is the plugin's server now. + internal bool Active => _loginComplete && _model.IsActive(_world); + + /// The world name the client reports ("" before login). Any thread. + internal string World => _world ?? string.Empty; + + // ── Hooks for a server's own features (implement in the server's project) ── + + partial void ServerInitialize(); + partial void ServerLoginComplete(); + partial void ServerLogout(); + partial void ServerShutdown(); + /// Every plugin tick while logged in; = this is the plugin's server. + partial void ServerTick(bool active); + /// "/rserver <verb> ..." verbs the shared code doesn't know; set handled to stop the help text. + partial void ServerChatCommand(string[] parts, ref bool handled); + /// + /// The server's own "/rserver" verbs (lower case), so "/rserver vault" reaches ServerChatCommand + /// instead of being read as another server's id. Called once, from the constructor. + /// + partial void ServerCommandVerbs(List verbs); + /// Extra lines for "/rserver info". + partial void ServerInfoLines(Action line); + /// The server's own pages (ServerPackPages.cs). Called once, from the constructor (no Host yet). + partial void ServerPages(List pages); + /// + /// An incoming chat line (pump thread, logged in only): set to keep it out of + /// the chat window (it comes in true when an earlier plugin already ate it). + /// + partial void ServerChatText(string text, int chatType, ref bool eat); + /// + /// A line sent through the chat bar, typed or another plugin's command (trimmed), before + /// "/rserver" is looked at. AC's main thread: only note it (interlocked state or a queue). + /// + partial void ServerChatBar(string text); + + // ── What the server's own code uses ────────────────────────────────── + + /// The plugin's settings file (loaded before ServerInitialize). Pump thread. + internal ServerPackSettings Settings => _settings; + + /// The live numbers of the profile ("values"). Any thread. + internal ServerProfileValues ProfileValues => _profileValues; + + /// The pages this plugin draws. + internal IReadOnlyList Pages => _pages; + + /// Publishes a live number in the "RynthServer.Profile" JSON ("values"). Any thread. + internal void SetProfileValue(string key, double value) => _profileValues.Set(key, value); + + /// Runs on the next tick while logged in (dropped at logout). Any thread. + internal void RunOnTick(Action action) + { + if (action != null) _tickActions.Enqueue(action); + } + + /// Sends a chat command as if typed; false when nothing went out. Pump thread. + internal bool Send(string command) + => _loginComplete && !string.IsNullOrWhiteSpace(command) && Host.HasInvokeChatParser && Host.InvokeChatParser(command); + + /// The plugin's log, tagged with its name. + internal void LogTagged(string message) => Host.Log($"[{RynthPluginInfo.Name}] {message}"); + + public override int Initialize() + { + Host.Log($"[{RynthPluginInfo.Name}] Plugin initialized for {Info.Name} ({Info.Id})."); + // The server card draws through the engine's cimgui (and so in its current context, a popped-out + // Mini Remote's included), never a second copy of ImGui (ImGuiNativeBinding.cs). Found and fixed + // by SilentKelpie (rynth PR #12); re-implemented here. + RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log($"[{RynthPluginInfo.Name}] {msg}")); + foreach (string note in _pageNotes) LogTagged(note); + _settings.Load(); + if (_settings.LastError.Length > 0) LogTagged($"Settings ({_settings.FilePath}) not read: {_settings.LastError}; using defaults."); + ServerInitialize(); + return 0; + } + + // Also called on a freshly (re)loaded plugin while already in game. + public override void OnLoginComplete() + { + _loginComplete = true; + _wasActive = false; + RefreshWorld(); + ServerLoginComplete(); + } + + public override void OnLogout() + { + _loginComplete = false; + _world = null; + while (_commands.TryDequeue(out _)) { } + while (_engineCommands.TryDequeue(out _)) { } + while (_tickActions.TryDequeue(out _)) { } + _model.Clear(); + _profileValues.Clear(); + ServerLogout(); + } + + public override void Shutdown() => ServerShutdown(); + + public override void OnTick() + { + if (!_loginComplete) return; + if (_world == null) RefreshWorld(); + while (_commands.TryDequeue(out string[]? parts)) RunCommand(parts); + while (_engineCommands.TryDequeue(out string? command)) + { + if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command)) + ChatLine($"[{RynthPluginInfo.Name}] RynthCore didn't take: " + command); + } + while (_tickActions.TryDequeue(out Action? action)) + { + try { action(); } + catch (Exception ex) { LogTagged($"A queued action failed: {ex.GetType().Name}: {ex.Message}"); } + } + + bool active = Active; + if (active && !_wasActive && Info.Botting == BottingPolicy.Forbidden) + ChatLine($"[{RynthPluginInfo.Name}] {Info.Name} forbids bots: don't run RynthAi's combat, navigation or looting here."); + _wasActive = active; + ServerTick(active); + } + + /// The world name the client reports (the server's own once logged in). + private void RefreshWorld() + { + if (Host.HasGetWorldName && Host.TryGetWorldName(out string w) && !string.IsNullOrWhiteSpace(w)) + _world = w.Trim(); + } + + // ── RynthCore's verdict ────────────────────────────────────────────── + + /// RynthPluginApplyRemoteCommand: "servermenu" from RynthCore. Any thread: parsed and published only. + internal void ApplyRemoteCommand(string action, string value) + { + if (action.Equals("servermenu", StringComparison.OrdinalIgnoreCase)) + _model.ApplyEngine(value, Environment.TickCount64); + } + + /// + /// RynthPluginGetSectionsJson: the server and the card's Mini Remote spot. Always declared + /// (the manifest is static): the engine only collects it once in game, and keeping it across + /// logout and character switches stops the server dropping out of Options > Diagnostics. + /// + internal string? BuildSectionsJson() => _sectionsJson; + + // ── Drawing ────────────────────────────────────────────────────────── + + /// The standalone card window. Render thread. + public override void OnRender() + { + if (!_loginComplete || !_ui.WindowOpen || Host.ImGuiContext == IntPtr.Zero) return; + IntPtr previous = ImGui.GetCurrentContext(); + ImGui.SetCurrentContext(Host.ImGuiContext); + try { _ui.RenderWindow(); } + catch (Exception ex) { Host.Log($"[{RynthPluginInfo.Name}] Server window failed: {ex.Message}"); _ui.WindowOpen = false; } + finally { ImGui.SetCurrentContext(previous); } + } + + /// + /// RynthPluginRenderEmbed "section:server-<id>": the card in RynthCore's Mini Remote, drawn + /// into the engine's current window and context (popped-out windows have their own). + /// is the height it used. False until login. Render thread. + /// + internal bool RenderEmbeddedCard(out float wantHeight) => RenderEmbedded(_ui.RenderBody, "Server card", out wantHeight); + + /// + /// RynthPluginRenderEmbed "section:server-<id>.<page>": one of the server's pages + /// (ServerPages) in RynthCore's Mini Remote. False for a page this plugin doesn't have, or before login. + /// + internal bool RenderEmbeddedPage(string pageId, out float wantHeight) + { + wantHeight = 0; + ServerPage? page = _pages.Find(p => p.Id == pageId); + return page != null && RenderEmbedded(page.Draw, "Page " + page.Label, out wantHeight); + } + + private bool RenderEmbedded(Action draw, string what, out float wantHeight) + { + wantHeight = 0; + if (!_loginComplete) return false; + IntPtr previous = ImGui.GetCurrentContext(); + IntPtr context = previous != IntPtr.Zero ? previous : Host.ImGuiContext; + if (context == IntPtr.Zero) return false; + ImGui.SetCurrentContext(context); + try + { + float startY = ImGui.GetCursorPosY(); + draw(); + wantHeight = MathF.Max(40f, ImGui.GetCursorPosY() - startY + 4f); + return true; + } + catch (Exception ex) + { + Host.Log($"[{RynthPluginInfo.Name}] {what} failed: {ex.Message}"); + return false; + } + finally { ImGui.SetCurrentContext(previous); } + } + + // ── Chat ───────────────────────────────────────────────────────────── + + /// Incoming chat (pump thread): the server's own code reads it (ServerChatText). + public override void OnChatWindowText(string? text, int chatType, ref int eat) + { + if (!_loginComplete || string.IsNullOrEmpty(text)) return; + bool eaten = eat != 0; + ServerChatText(text, chatType, ref eaten); + if (eaten) eat = 1; + } + + // ── Commands ───────────────────────────────────────────────────────── + + public override void OnChatBarEnter(string? text, ref int eat) + { + if (!_loginComplete || string.IsNullOrEmpty(text)) return; + string trimmed = text.Trim(); + ServerChatBar(trimmed); + if (!trimmed.Equals(ChatCommand, StringComparison.OrdinalIgnoreCase) + && !trimmed.StartsWith(ChatCommand + " ", StringComparison.OrdinalIgnoreCase)) + return; + string[] parts = trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries); + // "/rserver ...": only that server's plugin answers (several load when the host is unknown). + if (parts.Length >= 2 && ServerPackModel.IsSafeId(parts[1].ToLowerInvariant()) && !IsVerb(parts[1])) + { + if (!parts[1].Equals(Info.Id, StringComparison.OrdinalIgnoreCase)) return; + parts = Shift(parts); + } + eat = 1; + _commands.Enqueue(parts); + } + + private bool IsVerb(string word) => + word.ToLowerInvariant() is "show" or "hide" or "toggle" or "info" or "help" or "on" or "off" or "auto" + || _serverVerbs.Contains(word); + + /// Drops the server id: "/rserver coldeve info" -> "/rserver info". + private static string[] Shift(string[] parts) + { + var rest = new string[parts.Length - 1]; + rest[0] = parts[0]; + Array.Copy(parts, 2, rest, 1, parts.Length - 2); + return rest; + } + + private void RunCommand(string[] parts) + { + string verb = parts.Length >= 2 ? parts[1].ToLowerInvariant() : "toggle"; + switch (verb) + { + case "show": + _ui.WindowOpen = true; + return; + case "hide": + _ui.WindowOpen = false; + return; + case "toggle": + _ui.WindowOpen = !_ui.WindowOpen; + return; + case "auto": + case "on": + case "off": + _engineCommands.Enqueue(ServerPackModel.ForceCommand(Info.Id, verb)); + return; + case "info": + PrintInfo(); + return; + } + + bool handled = false; + ServerChatCommand(parts, ref handled); + if (handled) return; + ChatLine($"[{RynthPluginInfo.Name}] {ChatCommand} [show|hide|toggle] - the {Info.Name} server card (also in the Mini Remote's Char section)."); + ChatLine($"[{RynthPluginInfo.Name}] {ChatCommand} info - what is known about {Info.Name}; {ChatCommand} auto|on|off - this character's override."); + } + + private void PrintInfo() + { + string tag = $"[{RynthPluginInfo.Name}] "; + ServerVerdictView? v = _model.Engine; + string verdict = v != null + ? (v.Active ? "on for this world" : "not this world") + (v.Reason.Length > 0 ? " (" + v.Reason + ")" : "") + : (_model.IsActive(_world) ? "this world, by its name" : "not this world, by its name") + " (no RynthCore verdict yet)"; + ChatLine(tag + Info.Name + ": " + verdict); + if (Info.Address.Length > 0) ChatLine(tag + "Address " + Info.Address + " (" + Info.Emulator + ", " + Info.Ruleset + ")"); + if (Info.AccountLimit.Length > 0) ChatLine(tag + "Account limit: " + Info.AccountLimit); + ChatLine(tag + "Botting: " + Info.BottingText); + ServerInfoLines(line => ChatLine(tag + line)); + } + + internal void ChatLine(string text) + { + if (Host.HasWriteToChat) Host.WriteToChat(text, 1); + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackProfile.cs b/Plugins/Shared/ServerPack/ServerPackProfile.cs new file mode 100644 index 0000000..700c431 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackProfile.cs @@ -0,0 +1,252 @@ +// ServerPackProfile.cs - A server plugin's settings as JSON, for other plugins ("RynthServer.Profile", +// Plugins/Shared/RynthServerProfileApi.cs, served by ServerPackExports' RynthPluginQueryInterface). +// +// RynthCore's GetServerStateJson (plugin API v86) names the active server and the plugin that owns +// it; a reader (RynthOracle, RynthAi's "/ra server", ...) asks that plugin for this profile to get +// the server's rules without knowing the server: connection, rule set, botting policy, account +// limits, commands, tinkering salvage and links. Everything ServerPackInfo holds, nothing guessed. +// +// The JSON is plain ASCII (anything else is \u-escaped), so a reader can show it in the AC client. +// Pure (no host calls): RynthServerPack.Tests covers it. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace RynthCore.Plugin.ServerPack; + +/// +/// Live numbers a server plugin publishes in its profile ("values"), for other plugins that apply a +/// server rule without knowing the server: e.g. RynthConquest's "voidDotDurationScale" (how much +/// longer this character's Void damage-over-time lasts there), which RynthOracle's Void timers use. +/// Set from the server's own code (ServerPackPlugin.SetProfileValue), read by the profile interface +/// on any thread; goes up on every change, so the JSON is rebuilt only then. +/// +internal sealed class ServerProfileValues +{ + private readonly object _gate = new(); + private readonly List> _values = new(); + private volatile int _revision; + + /// Goes up whenever a value changes. + public int Revision => _revision; + + /// 1-48 of letters, digits, '.', '_' and '-'. + public static bool IsValidKey(string? key) + { + if (string.IsNullOrEmpty(key) || key.Length > 48) return false; + foreach (char c in key) + if (!(char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-')) return false; + return true; + } + + /// Sets (or adds) a value; false for a bad key or a number that isn't finite. Any thread. + public bool Set(string key, double value) + { + if (!IsValidKey(key) || !double.IsFinite(value)) return false; + lock (_gate) + { + int i = _values.FindIndex(v => v.Key == key); + if (i >= 0) + { + if (_values[i].Value.Equals(value)) return true; + _values[i] = new KeyValuePair(key, value); + } + else _values.Add(new KeyValuePair(key, value)); + _revision++; + } + return true; + } + + /// Drops one value (true when it was there). Any thread. + public bool Remove(string key) + { + lock (_gate) + { + int i = _values.FindIndex(v => v.Key == key); + if (i < 0) return false; + _values.RemoveAt(i); + _revision++; + return true; + } + } + + /// Drops every value (logout: the next character publishes its own). Any thread. + public void Clear() + { + lock (_gate) + { + if (_values.Count == 0) return; + _values.Clear(); + _revision++; + } + } + + /// A copy of the values and the revision it belongs to. Any thread. + public KeyValuePair[] Snapshot(out int revision) + { + lock (_gate) + { + revision = _revision; + return _values.ToArray(); + } + } +} + +internal static class ServerPackProfile +{ + /// The profile JSON's schema (RynthServerProfile.Schema). + public const int Schema = 1; + + /// The "botting" value for a policy. + public static string BottingName(BottingPolicy policy) => policy switch + { + BottingPolicy.Allowed => "allowed", + BottingPolicy.Restricted => "restricted", + BottingPolicy.Forbidden => "forbidden", + _ => "unknown", + }; + + /// + /// The profile for : is this plugin's verdict + /// (RynthCore's when it pushed one), the world name the client reports, + /// the live numbers the server's own code published (ServerProfileValues). + /// + public static string BuildJson(ServerPackInfo info, string pluginName, string pluginVersion, bool active, string? world, + IReadOnlyList>? values = null) + { + var sb = new StringBuilder(1024); + sb.Append("{\"schema\":").Append(Schema); + Field(sb, "id", info.Id); + Field(sb, "name", info.Name); + Field(sb, "plugin", pluginName); + Field(sb, "version", pluginVersion); + sb.Append(",\"active\":").Append(active ? "true" : "false"); + Field(sb, "world", world ?? string.Empty); + List(sb, "hosts", info.Hosts); + List(sb, "worldNames", info.WorldNames); + sb.Append(",\"port\":").Append(info.Port); + Field(sb, "emulator", info.Emulator); + Field(sb, "ruleset", info.Ruleset); + Field(sb, "status", info.Status); + Field(sb, "botting", BottingName(info.Botting)); + Field(sb, "bottingNote", info.BottingNote); + Field(sb, "accountLimit", info.AccountLimit); + Field(sb, "summary", info.Summary); + List(sb, "facts", info.Facts); + sb.Append(",\"commands\":["); + for (int i = 0; i < info.Commands.Length; i++) + { + if (i > 0) sb.Append(','); + sb.Append("{\"command\":"); + Str(sb, info.Commands[i].Command); + sb.Append(",\"what\":"); + Str(sb, info.Commands[i].What); + sb.Append('}'); + } + sb.Append(']'); + // Added within schema 1: readers that don't know "salvage" skip it. The optional row fields + // (applied, prepared, order, afterCap, stackGroup + stackCap) are written only when set. + sb.Append(",\"salvage\":["); + for (int i = 0; i < info.Salvage.Length; i++) + { + ServerSalvage s = info.Salvage[i]; + if (i > 0) sb.Append(','); + sb.Append("{\"bench\":"); + Str(sb, s.Bench); + sb.Append(",\"material\":").Append(s.Material); + sb.Append(",\"kind\":"); + Str(sb, s.Kind); + sb.Append(",\"effect\":"); + Str(sb, s.Effect); + sb.Append(",\"slot\":").Append(s.UsesTinkSlot ? "true" : "false"); + sb.Append(",\"nameMatch\":"); + Str(sb, s.NameMatch); + if (s.AppliedInt != 0) sb.Append(",\"applied\":").Append(s.AppliedInt); + if (s.Prepared) sb.Append(",\"prepared\":true"); + if (s.Order != 0) sb.Append(",\"order\":").Append(s.Order); + if (s.AfterCap) sb.Append(",\"afterCap\":true"); + if (!string.IsNullOrEmpty(s.StackGroup)) + { + sb.Append(",\"stackGroup\":"); + Str(sb, s.StackGroup); + sb.Append(",\"stackCap\":").Append(s.StackCap); + } + sb.Append('}'); + } + sb.Append(']'); + // Added within schema 1 (2026-10-20), only when the server has trinkets. + if (info.TrinketNames.Length > 0) + { + sb.Append(",\"trinkets\":{"); + sb.Append("\"names\":["); + for (int i = 0; i < info.TrinketNames.Length; i++) { if (i > 0) sb.Append(','); Str(sb, info.TrinketNames[i]); } + sb.Append("],\"except\":["); + for (int i = 0; i < info.TrinketExcept.Length; i++) { if (i > 0) sb.Append(','); Str(sb, info.TrinketExcept[i]); } + sb.Append("]}"); + } + Field(sb, "discord", info.Discord); + Field(sb, "website", info.Website); + Field(sb, "wiki", info.Wiki); + Field(sb, "source", info.Source); + // Added within schema 1: live numbers for this character on this server ({} when none). + sb.Append(",\"values\":{"); + if (values != null) + { + bool first = true; + foreach (KeyValuePair v in values) + { + if (!ServerProfileValues.IsValidKey(v.Key) || !double.IsFinite(v.Value)) continue; + if (!first) sb.Append(','); + first = false; + Str(sb, v.Key); + sb.Append(':').Append(v.Value.ToString("R", CultureInfo.InvariantCulture)); + } + } + sb.Append('}'); + sb.Append('}'); + return sb.ToString(); + } + + private static void Field(StringBuilder sb, string name, string? value) + { + sb.Append(",\"").Append(name).Append("\":"); + Str(sb, value); + } + + private static void List(StringBuilder sb, string name, string[]? values) + { + sb.Append(",\"").Append(name).Append("\":["); + if (values != null) + { + for (int i = 0; i < values.Length; i++) + { + if (i > 0) sb.Append(','); + Str(sb, values[i]); + } + } + sb.Append(']'); + } + + /// A JSON string literal in plain ASCII (control and non-ASCII characters \u-escaped). + private static void Str(StringBuilder sb, string? s) + { + sb.Append('"'); + foreach (char c in s ?? string.Empty) + { + 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: + if (c < 0x20 || c > 0x7e) sb.Append("\\u").Append(((int)c).ToString("x4")); + else sb.Append(c); + break; + } + } + sb.Append('"'); + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackQuestPack.cs b/Plugins/Shared/ServerPack/ServerPackQuestPack.cs new file mode 100644 index 0000000..c164f7d --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackQuestPack.cs @@ -0,0 +1,121 @@ +// ServerPackQuestPack.cs - A server plugin's own quest list, offered to quest readers such as RynthOracle +// through "RynthServer.QuestPack" (Plugins/Shared/RynthServerQuestPackApi.cs; the table is in +// ServerPackInterface.cs, answered by ServerPackExports' RynthPluginQueryInterface). +// +// A server plugin has a pack when its project has Resources\quests..csv: ServerPlugin.props +// embeds it as "ServerPack.quests.csv", and this file serves it. The pack is the server's data, kept +// with the server's plugin (the Conquest, Levistras and Aelrynth packs lived in RynthOracle until +// 2026-10-21); RynthOracle merges whichever pack the active server's plugin offers and names no server. +// Its "tag" is the server's display name, which is also what the master quest list's Server column +// calls it ("Conquest", "Levistras"). +// Pure apart from the embedded resource read: RynthServerPack.Tests covers it. +using System; +using System.IO; +using System.Text; + +namespace RynthCore.Plugin.ServerPack; + +internal static class ServerPackQuestPack +{ + /// The embedded pack's resource name (ServerPlugin.props). + public const string ResourceName = "ServerPack.quests.csv"; + + /// The info JSON's schema (RynthServerQuestPack.Schema). + public const int Schema = 1; + + /// The pack never changes while the plugin runs (it is embedded): one revision. + public const int Revision = 1; + + private static string? _csv; + private static bool _loaded; + + /// The embedded pack's CSV, or "" when this plugin has none. Read once. Any thread. + public static string Csv + { + get + { + if (_loaded) return _csv ?? string.Empty; + string text = string.Empty; + try + { + using Stream? s = typeof(ServerPackQuestPack).Assembly.GetManifestResourceStream(ResourceName); + if (s != null) + { + using var r = new StreamReader(s, Encoding.UTF8); + text = r.ReadToEnd(); + } + } + catch + { + text = string.Empty; // an unreadable pack is no pack: never take the plugin down + } + _csv = Usable(text) ? text : string.Empty; + _loaded = true; + return _csv; + } + } + + /// True when the text looks like a quest list: a header with a QuestFlag column and a row. + public static bool Usable(string? csv) + { + if (string.IsNullOrEmpty(csv)) return false; + int end = csv.IndexOf('\n'); + string header = (end < 0 ? csv : csv[..end]).TrimStart('').Trim(); + bool hasFlag = false; + foreach (string col in header.Split(',')) + { + string c = col.Trim().Trim('"').Replace(" ", string.Empty); + if (c.Equals("QuestFlag", StringComparison.OrdinalIgnoreCase) || c.Equals("Flag", StringComparison.OrdinalIgnoreCase)) hasFlag = true; + } + return hasFlag && CountRows(csv) > 0; + } + + /// Non-blank lines after the header (a quoted field never spans lines in these lists). + public static int CountRows(string? csv) + { + if (string.IsNullOrEmpty(csv)) return 0; + int rows = 0; + bool header = true; + foreach (string line in csv.Split('\n')) + { + if (header) { header = false; continue; } + if (line.Trim().Length > 0) rows++; + } + return rows; + } + + /// The info JSON for a pack (plain ASCII), or "" when is no pack. + public static string BuildInfoJson(ServerPackInfo info, string pluginName, string pluginVersion, string? csv) + { + if (!Usable(csv)) return string.Empty; + var sb = new StringBuilder(256); + sb.Append("{\"schema\":").Append(Schema); + Field(sb, "server", info.Id); + Field(sb, "tag", info.Name); + Field(sb, "plugin", pluginName); + Field(sb, "version", pluginVersion); + sb.Append(",\"rows\":").Append(CountRows(csv)); + sb.Append(",\"bytes\":").Append(Encoding.UTF8.GetByteCount(csv!)); + sb.Append(",\"revision\":").Append(Revision); + sb.Append('}'); + return sb.ToString(); + } + + private static void Field(StringBuilder sb, string name, string? value) + { + sb.Append(",\"").Append(name).Append("\":\""); + foreach (char c in value ?? string.Empty) + { + switch (c) + { + case '"': sb.Append("\\\""); break; + case '\\': sb.Append("\\\\"); break; + default: + if (c < 0x20 || c > 0x7e) sb.Append("\\u").Append(((int)c).ToString("x4")); + else sb.Append(c); + break; + } + } + sb.Append('"'); + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackRefresh.cs b/Plugins/Shared/ServerPack/ServerPackRefresh.cs new file mode 100644 index 0000000..3887d72 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackRefresh.cs @@ -0,0 +1,88 @@ +// ServerPackRefresh.cs - The Refresh button a server page starts with, and the status line beside it +// (as RynthOracle's pages have it): the page's own command is asked for again, refused for a few +// seconds after it went out (so the button can't spam the server), and the line waits for the reply +// ("Waiting...", then "Updated hh:mm:ss", or "No reply yet" after a while). +// Render thread: Draw runs inside the page's own lock; the page's refresh callback only decides and +// queues what to send (ServerPackPlugin.RunOnTick). +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.ServerPack; + +/// What a Refresh did, and (when it asked the server) how to tell the reply has landed. +internal sealed record ServerRefreshResult(string What, Func? Done = null); + +internal sealed class ServerRefreshRow +{ + public const long CooldownMs = 3000; + public const long ReplyWaitMs = 15_000; + public const string TooSoon = "That was just asked for; wait a few seconds before asking again."; + + private static readonly Vector4 Yellow = new(0.95f, 0.85f, 0.35f, 1f); + private static readonly Vector4 Red = new(0.95f, 0.45f, 0.40f, 1f); + + private readonly Dictionary _sent = new(); + private string _scope = string.Empty, _what = string.Empty; + private Func? _done; + private bool _doneSeen; + private long _atMs; + private DateTime _atLocal, _doneLocal; + + /// The same request (by ) twice within is refused. + public bool CoolingDown(string key, long nowMs) + { + if (_sent.TryGetValue(key, out long t) && nowMs - t < CooldownMs) return true; + _sent[key] = nowMs; + return false; + } + + /// Forgets the status line and the cooldowns (logout). + public void Reset() + { + _sent.Clear(); + _scope = _what = string.Empty; + _done = null; + } + + /// + /// The row: Refresh (tooltip ) and, for the page that last refreshed + /// (), what happened. + /// + public void Draw(string scope, string help, Func refresh) + { + long now = Environment.TickCount64; + if (ImGui.SmallButton("Refresh##refresh_" + scope)) + { + ServerRefreshResult r; + try { r = refresh(); } + catch (Exception ex) { r = new ServerRefreshResult("Couldn't refresh: " + ex.Message); } + _scope = scope; + _what = r.What; + _done = r.Done; + _doneSeen = false; + _atMs = now; + _atLocal = DateTime.Now; + } + if (help.Length > 0 && ImGui.IsItemHovered()) SafeImGui.SetTooltip(help); + if (_scope != scope || _what.Length == 0) return; + + ImGui.SameLine(); + if (_done != null && !_doneSeen && _done()) + { + _doneSeen = true; + _doneLocal = DateTime.Now; + } + if (_done != null && !_doneSeen) + { + if (now - _atMs > ReplyWaitMs) SafeImGui.TextColored(Red, "No reply yet. Press Refresh to ask again."); + else SafeImGui.TextColored(Yellow, _what + " Waiting for the reply..."); + } + else if (_done != null) + SafeImGui.TextDisabled($"Updated {_doneLocal:HH:mm:ss}. {_what}"); + else + SafeImGui.TextDisabled($"Refreshed {_atLocal:HH:mm:ss}. {_what}"); + } +} diff --git a/Plugins/Shared/ServerPack/ServerPackSettings.cs b/Plugins/Shared/ServerPack/ServerPackSettings.cs new file mode 100644 index 0000000..0b9b1ac --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackSettings.cs @@ -0,0 +1,158 @@ +// ServerPackSettings.cs - A server plugin's own settings file, %APPDATA%\RynthCore\.json +// (rynthconquest.json, ...), for the server's features (ServerPackPlugin.Settings). +// +// Flat named values (true/false, text), written by hand and read with JsonDocument: plugin types +// never go through System.Text.Json's serializer, which roots them across hot reloads. Values the +// plugin doesn't ask for are kept as they were written, so an older or newer copy of the plugin +// never drops another's. MigrateOnce imports settings that used to live elsewhere (another +// plugin's file) exactly once, and remembers that it did. +// Pure (file I/O only): RynthServerPack.Tests covers it. Pump thread only. +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.Json; + +namespace RynthCore.Plugin.ServerPack; + +internal sealed class ServerPackSettings +{ + // name -> the value's JSON text, in file order. + private readonly List> _values = new(); + + public ServerPackSettings(string path) => FilePath = path; + + /// %APPDATA%\RynthCore\<plugin name, lower case>.json. + public static string DefaultPath(string pluginName) => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", pluginName.ToLowerInvariant() + ".json"); + + public string FilePath { get; } + + /// Why the last Load or Save failed ("" when it didn't). + public string LastError { get; private set; } = string.Empty; + + /// Reads the file; a missing or broken one means defaults (the next save rewrites it). + public void Load() + { + _values.Clear(); + LastError = string.Empty; + try + { + if (!File.Exists(FilePath)) return; + using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(FilePath)); + if (doc.RootElement.ValueKind != JsonValueKind.Object) { LastError = "not a JSON object"; return; } + foreach (JsonProperty p in doc.RootElement.EnumerateObject()) + Put(p.Name, p.Value.GetRawText()); + } + catch (Exception ex) + { + _values.Clear(); + LastError = ex.Message; + } + } + + /// Writes the file (through a temporary file, so a crash never leaves half of one). False on failure. + public bool Save() + { + try + { + var sb = new StringBuilder("{\n"); + for (int i = 0; i < _values.Count; i++) + { + sb.Append(" ").Append(Quote(_values[i].Key)).Append(": ").Append(_values[i].Value); + sb.Append(i + 1 < _values.Count ? ",\n" : "\n"); + } + sb.Append("}\n"); + Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); + string tmp = FilePath + ".tmp"; + File.WriteAllText(tmp, sb.ToString()); + File.Move(tmp, FilePath, overwrite: true); + LastError = string.Empty; + return true; + } + catch (Exception ex) + { + LastError = ex.Message; + return false; + } + } + + public bool Has(string name) => Find(name) >= 0; + + public bool GetBool(string name, bool fallback) + { + int i = Find(name); + return i < 0 ? fallback : _values[i].Value switch { "true" => true, "false" => false, _ => fallback }; + } + + /// Sets a value; true when it changed (the caller saves). + public bool SetBool(string name, bool value) => Put(name, value ? "true" : "false"); + + public string GetString(string name, string fallback) + { + int i = Find(name); + if (i < 0) return fallback; + try + { + using JsonDocument doc = JsonDocument.Parse(_values[i].Value); + return doc.RootElement.ValueKind == JsonValueKind.String ? doc.RootElement.GetString() ?? fallback : fallback; + } + catch (JsonException) { return fallback; } + } + + public bool SetString(string name, string value) => Put(name, Quote(value ?? string.Empty)); + + /// + /// Runs once per settings file: unless is + /// already set, it runs, the marker is set and the file saved. True when it ran now. + /// + public bool MigrateOnce(string marker, Action migrate) + { + if (GetBool(marker, false)) return false; + migrate(this); + SetBool(marker, true); + Save(); + return true; + } + + /// + /// A true/false value from another JSON settings file (an old home of a moved setting), or null + /// when the file, the value or its type isn't there. Never throws. + /// + public static bool? ReadBoolFrom(string path, string name) + { + try + { + if (!File.Exists(path)) return null; + using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path)); + if (doc.RootElement.ValueKind != JsonValueKind.Object || !doc.RootElement.TryGetProperty(name, out JsonElement v)) return null; + return v.ValueKind switch { JsonValueKind.True => true, JsonValueKind.False => false, _ => null }; + } + catch + { + return null; + } + } + + private int Find(string name) + { + for (int i = 0; i < _values.Count; i++) + if (string.Equals(_values[i].Key, name, StringComparison.Ordinal)) return i; + return -1; + } + + private bool Put(string name, string json) + { + int i = Find(name); + if (i >= 0) + { + if (_values[i].Value == json) return false; + _values[i] = new KeyValuePair(name, json); + return true; + } + _values.Add(new KeyValuePair(name, json)); + return true; + } + + private static string Quote(string s) => "\"" + JsonEncodedText.Encode(s).ToString() + "\""; +} diff --git a/Plugins/Shared/ServerPack/ServerPackUi.cs b/Plugins/Shared/ServerPack/ServerPackUi.cs new file mode 100644 index 0000000..7db36ba --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackUi.cs @@ -0,0 +1,240 @@ +// ServerPackUi.cs - A server plugin's "server card". +// +// Drawn in two places: RynthCore's Mini Remote, the shared "Server" section, this server's area +// (the surface "section:server-" through RynthPluginRenderEmbed), and its own window ("/rserver"). +// Shows RynthCore's verdict and this character's Auto / On / Off override (read only: it is set in +// RynthCore Options > Diagnostics, 2026-10-13), what is known about the server (address, rule set, +// account limit, botting policy, its features), the commands it adds, its links, and how to set an +// account up for it in the launcher. Render thread only. +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.ServerPack; + +internal sealed class ServerPackUi +{ + private static readonly Vector4 Teal = new(0.30f, 0.85f, 0.80f, 1f); + private static readonly Vector4 Mute = new(0.60f, 0.62f, 0.66f, 1f); + private static readonly Vector4 Warn = new(0.95f, 0.55f, 0.45f, 1f); + private static readonly Vector4 Good = new(0.55f, 0.85f, 0.45f, 1f); + + private readonly ServerPackModel _model; + private readonly string _pluginLabel; + private readonly Func _world; + private readonly string _windowTitle; + private readonly IReadOnlyList _pages; + private string _status = string.Empty; + + /// The standalone window is open ("/rserver"). + public bool WindowOpen; + + /// "RynthColdeve 0.1.0", for the title and the card. + /// The world name the client reports now (null when unknown). + /// The server's own pages: tabs of the window after the card. + public ServerPackUi(ServerPackModel model, string pluginLabel, Func world, IReadOnlyList? pages = null) + { + _model = model; + _pluginLabel = pluginLabel; + _world = world; + _pages = pages ?? Array.Empty(); + _windowTitle = model.Info.Name + " server (" + pluginLabel + ")##server_" + model.Info.Id; + } + + /// The standalone window, while open: the card, and the server's pages as tabs when it has some. + public void RenderWindow() + { + if (!WindowOpen) return; + ImGui.SetNextWindowSize(new Vector2(_pages.Count > 0 ? 560 : 460, 520), ImGuiCond.FirstUseEver); + bool open = WindowOpen; + if (ImGui.Begin(_windowTitle, ref open)) + { + if (_pages.Count == 0) RenderBody(); + else if (ImGui.BeginTabBar("##server_tabs_" + _model.Info.Id)) + { + if (ImGui.BeginTabItem("Server##card")) + { + RenderBody(); + ImGui.EndTabItem(); + } + foreach (ServerPage page in _pages) + { + if (!ImGui.BeginTabItem(page.Label + "##page_" + page.Id)) continue; + if (ImGui.BeginChild("##page_body_" + page.Id)) page.Draw(); + ImGui.EndChild(); + ImGui.EndTabItem(); + } + ImGui.EndTabBar(); + } + } + ImGui.End(); + WindowOpen = open; + } + + /// The card's content, into the current window. + public void RenderBody() + { + ServerPackInfo info = _model.Info; + RenderVerdict(info); + ImGui.Separator(); + RenderFacts(info); + if (info.Commands.Length > 0) + { + ImGui.Separator(); + RenderCommands(info); + } + ImGui.Separator(); + RenderLinks(info); + ImGui.Separator(); + RenderSetup(info); + if (info.Source.Length > 0) + { + ImGui.Spacing(); + SafeImGui.TextDisabled("Server data: " + info.Source); + } + if (_status.Length > 0) + { + ImGui.Separator(); + SafeImGui.TextWrapped(_status); + } + } + + private void RenderVerdict(ServerPackInfo info) + { + ServerVerdictView? v = _model.Engine; + if (v == null) + { + bool byName = _model.IsActive(_world()); + SafeImGui.TextColored(byName ? Teal : Mute, byName + ? info.Name + ": this world (by its name)" + : info.Name + ": not this world (by its name)"); + ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGui.TextWrapped("Waiting for RynthCore's verdict and the override (RynthCore 2026.10.5.48 or later sends them)."); + ImGui.PopStyleColor(); + return; + } + + SafeImGui.TextColored(v.Active ? Teal : Mute, v.Active ? info.Name + ": on for this world" : info.Name + ": not this world"); + if (v.Reason.Length > 0) + { + ImGui.PushStyleColor(ImGuiCol.Text, Mute); + SafeImGui.TextWrapped(v.Reason); + ImGui.PopStyleColor(); + } + // Read only: a server is forced in one place, RynthCore Options > Diagnostics (2026-10-13). + SafeImGui.TextDisabled("This character: " + ForceText(ServerPackModel.NormalizeForce(v.Force)) + + " (change it in RynthCore Options > Diagnostics)"); + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("RynthCore's server selection (Options > Diagnostics) forces a server for this character,\n" + + "or /rc server " + info.Id + " auto|on|off in chat."); + } + + /// The override as words: Auto (detected), On (forced on) or Off (forced off). + private static string ForceText(string force) => force switch + { + "on" => "forced on", + "off" => "forced off", + _ => "auto (detected)", + }; + + private static void RenderFacts(ServerPackInfo info) + { + if (ImGui.BeginTable("##facts_" + info.Id, 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp)) + { + ImGui.TableSetupColumn("Item", ImGuiTableColumnFlags.WidthFixed, 110); + ImGui.TableSetupColumn("Value"); + Row("Address", info.Address.Length > 0 ? info.Address : "(not published)"); + Row("Emulator", info.Emulator); + Row("Rule set", info.Ruleset); + if (info.Status.Length > 0) Row("Status", info.Status); + Row("Account limit", info.AccountLimit.Length > 0 ? info.AccountLimit : "(not published)"); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.TextUnformatted("Botting"); + ImGui.TableNextColumn(); + Vector4 color = info.Botting switch + { + BottingPolicy.Forbidden => Warn, + BottingPolicy.Restricted => Warn, + BottingPolicy.Allowed => Good, + _ => Mute, + }; + ImGui.PushStyleColor(ImGuiCol.Text, color); + SafeImGui.TextWrapped(info.BottingText); + ImGui.PopStyleColor(); + ImGui.EndTable(); + } + + if (info.Botting == BottingPolicy.Forbidden) + SafeImGui.TextColored(Warn, "This server forbids bots: don't run RynthAi's combat, navigation or looting here."); + + if (info.Summary.Length > 0) + { + ImGui.Spacing(); + SafeImGui.TextWrapped(info.Summary); + } + foreach (string fact in info.Facts) + SafeImGui.BulletText(fact); + } + + private static void Row(string label, string value) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + SafeImGui.Text(label); + ImGui.TableNextColumn(); + SafeImGui.TextWrapped(value); + } + + private void RenderCommands(ServerPackInfo info) + { + ImGui.TextUnformatted("Server commands"); + for (int i = 0; i < info.Commands.Length; i++) + { + ServerCommand c = info.Commands[i]; + ImGui.PushID(i); + if (ImGui.SmallButton("Copy")) Copy(c.Command); + ImGui.PopID(); + ImGui.SameLine(); + SafeImGui.Text(c.Command); + ImGui.SameLine(); + SafeImGui.TextDisabled("- " + c.What); + } + } + + private void RenderLinks(ServerPackInfo info) + { + ImGui.TextUnformatted("Links"); + bool any = false; + any |= Link("Discord", info.Discord); + any |= Link("Website", info.Website); + any |= Link("Wiki", info.Wiki); + if (!any) ImGui.TextDisabled("(none published)"); + } + + private bool Link(string label, string url) + { + if (url.Length == 0) return false; + ImGui.PushID(label); + if (ImGui.SmallButton("Copy")) Copy(url); + ImGui.PopID(); + ImGui.SameLine(); + SafeImGui.Text(label + ": " + url); + return true; + } + + private static void RenderSetup(ServerPackInfo info) + { + ImGui.TextUnformatted("Account setup (RynthCore launcher)"); + foreach (string step in ServerPackModel.LauncherSteps(info)) + SafeImGui.TextWrapped(step); + } + + private void Copy(string text) + { + ImGui.SetClipboardText(text); + _status = "Copied: " + text; + } +} diff --git a/Plugins/Shared/ServerPack/ServerPlugin.props b/Plugins/Shared/ServerPack/ServerPlugin.props new file mode 100644 index 0000000..8d5adb2 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPlugin.props @@ -0,0 +1,93 @@ + + + + net10.0-windows + x86 + win-x86 + Library + true + enable + true + Shared + true + Size + false + RynthCore.Plugin.ServerPack + x86 + + 66 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..419f3c9 --- /dev/null +++ b/README.md @@ -0,0 +1,28 @@ +# RynthServers + +Plugins for particular Asheron's Call emulator servers, for [RynthCore](https://aelrynth.com/rynth.html). Each one loads only on its own server and is installed from the launcher's **Server plugins** tab. + +| Plugin | Server | +|---|---| +| RynthILT | Infinite Leaftide (pets, Vaulted Dungeons, T11, banking, Dynamic Stamps, ...) | +| RynthThreads | DreamWeave's Threads | +| RynthAelrynth, RynthConquest, RynthLevistras | their server's card, quest pack and own pages | +| RynthAChard, RynthColdeve, RynthDerptide, RynthDreamWeave, RynthEversong, RynthFrostACE, RynthFrostcull, RynthLeafDawn, RynthLeafdawning, RynthPortalStorm, RynthReefcull, RynthSundering, RynthThistlecrown | their server's card in the Mini Remote | + +The shared server-plugin build is `Plugins/Shared/ServerPack`. + +**RynthILT** is maintained by SilentKelpie: changes to it go through him. + +## Building + +RynthServers builds beside its two sibling repositories, which it compiles against: + +``` +\RynthCore engine and plugin SDK +\RynthSuite RynthAi and the other plugins; its Plugins\Shared holds the contracts server plugins use +\RynthServers this repository +``` + +`dotnet build Plugins\RynthCore.Plugin.\RynthCore.Plugin..csproj -c Release`. Tests: `Tools\RynthILT.Tests`, `Tools\RynthServerPack.Tests`, `Tools\RynthThreads.Tests` (`dotnet run -c Release`, exit 0 = pass). + +The history of these folders before 2026-10-21 is RynthSuite's. diff --git a/Tools/RynthILT.Tests/AetheriaChunkTests.cs b/Tools/RynthILT.Tests/AetheriaChunkTests.cs new file mode 100644 index 0000000..bd0ab06 --- /dev/null +++ b/Tools/RynthILT.Tests/AetheriaChunkTests.cs @@ -0,0 +1,277 @@ +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The Lugian-hammer aetheria rules (Hub/IltChunkClap.cs): Infinite Leaftide aetheria goes up to +// level 10, and aetheria carrying a C, CD or CDR rating is kept unless its keep switch is off. +// The cap covers levelled Coalesced Aetheria; an unlevelled one chunks, as in ub-IT. Corrupted +// weapons follow ub-IT's hard rules and its optional keep rules, and /clap needs a colour with its +// own trinket. +internal static class AetheriaChunkTests +{ + public static void Register(Runner r) + { + r.Add("aetheria: the chunk cap runs to one past ILT's level 10", Cap); + r.Add("aetheria: C / CD / CDR ratings are kept by default, each with its own switch", Ratings); + r.Add("aetheria: rating level - at or above keeps, below chunks (Coalesced too)", RatingLevel); + r.Add("aetheria: the level cap applies to levelled Coalesced Aetheria; unlevelled Coalesced chunks (ub-IT)", CoalescedCap); + r.Add("aetheria: a failed read is not 'unlevelled': unreadable pieces are kept, levelled Coalesced keeps its cap", UnreadableAetheria); + r.Add("aetheria: never-chunk, tinker / imbue, item XP, ratings and the cap each keep a piece", AetheriaRules); + r.Add("chunk: kind by class and name; chunks and powder are clap material", Kinds); + r.Add("corrupted: ub-IT hard rules (workmanship, cleave 1, or 2 on two-handed non-thrust)", CorruptedHardRules); + r.Add("corrupted: ub-IT keep rules, all off by default", CorruptedKeepRules); + r.Add("corrupted: a failed read is kept; two-handed cleave 2 chunks and other cleave 2 does not", UnreadableCorrupted); + r.Add("chunk: busy blocks peace mode, not combat with chunk-in-combat on (ub-IT v2.0.1059)", BusyGate); + r.Add("chunk: a target that leaves the pack counts as chunked; still carried after 10 s times out", WaitOutcome); + r.Add("clap: the server's WCIDs, each colour paired with its trinket, Coalesced only unrevealed level 1-3", ClapPairs); + } + + /// + /// Coalesced Aetheria has its level from loot (ACECustom 1-10, ratings at 6+); it used to skip + /// the cap, so a cap of 9 still chunked a level 10 Coalesced piece. + /// + private static void CoalescedCap() + { + Check.True(IltChunkClap.UnderChunkCap(8, 9), "level 8 under a cap of 9"); + Check.False(IltChunkClap.UnderChunkCap(9, 9), "level 9 is not below 9"); + Check.False(IltChunkClap.UnderChunkCap(10, 9), "a level 10 Coalesced piece is kept"); + Check.True(IltChunkClap.UnderChunkCap(10, 11), "11 chunks every level"); + Check.False(IltChunkClap.UnderChunkCap(0, 11), "revealed aetheria with no level read: never chunked"); + Check.False(IltChunkClap.UnderChunkCap(9, 9, coalesced: true), "a levelled Coalesced piece keeps the cap"); + Check.True(IltChunkClap.UnderChunkCap(0, 4, coalesced: true), "an unlevelled Coalesced piece chunks (it used to be kept forever)"); + Check.True(IltChunkClap.UnderChunkCap(0, 1, coalesced: true), "even with the lowest cap"); + } + + private static readonly IltChunkClap.AetheriaFacts PlainCoalesced = new( + Coalesced: true, MaxLevel: 0, NeverChunk: false, ItemXp: 0, Tinkers: 0, Imbue: 0, Crit: 0, CritDamage: 0, CritDamageResist: 0); + + private static void AetheriaRules() + { + var g = new IltGearState(); + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced), null, "a plain unlevelled Coalesced piece chunks"); + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 3 }), null, "level 3 under the default cap of 4"); + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 4 }), "level at or above the cap", "level 4 at the default cap"); + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { NeverChunk = true }), "never-chunk flag", "bool 9030"); + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Tinkers = 1 }), "tinkered or imbued", "tinkered"); + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Imbue = 4 }), "tinkered or imbued", "imbued"); + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { ItemXp = 100 }), "has item XP", "levelled by use"); + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Crit = 2 }), "kept for its C / CD / CDR rating", "a C 2 piece is kept by default"); + g.KeepAetheriaWithCrit = false; + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Crit = 2 }), null, "C switch off: a C 2 piece chunks"); + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Coalesced = false }), "no level read", "revealed aetheria needs a level"); + } + + /// + /// The rules read 0 for "the item has none" and for "the host could not read it". An unlevelled + /// Coalesced piece is chunked (ub-IT), but only when its level was truly read as none; a piece whose + /// properties could not be read is kept, whatever the numbers say. + /// + private static void UnreadableAetheria() + { + var g = new IltGearState(); + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced), null, "read as unlevelled: chunks"); + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Unreadable = "no appraisal" }), + "item data unreadable (no appraisal)", "the same piece with failed reads: kept"); + Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 2, Unreadable = "no item XP" }), + "item data unreadable (no item XP)", "a levelled piece with failed reads: kept"); + Check.Eq(IltChunkClap.AetheriaSkip(new IltGearState { ChunkAetheriaUnderLevel = 1 }, PlainCoalesced), null, "unlevelled chunks at the lowest cap too"); + + // Levelled Coalesced pieces keep the cap. + var cap9 = new IltGearState { ChunkAetheriaUnderLevel = 9 }; + Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 8 }), null, "levelled 8 under a cap of 9"); + Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 9 }), "level at or above the cap", "levelled 9 at a cap of 9"); + Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 10 }), "level at or above the cap", "levelled 10 over a cap of 9"); + Check.Eq(IltChunkClap.AetheriaSkip(new IltGearState { ChunkAetheriaUnderLevel = 11 }, PlainCoalesced with { MaxLevel = 10 }), null, "cap 11 chunks every level"); + } + + private static void UnreadableCorrupted() + { + var g = new IltGearState(); + Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Unreadable = "no appraisal" }), + "item data unreadable (no appraisal)", "failed reads: kept (they would read as a plain weapon)"); + var keepCb = new IltGearState { KeepCorruptedCrushingBlow = true }; + Check.Eq(IltChunkClap.CorruptedSkip(keepCb, PlainSword with { Unreadable = "float properties" }), + "item data unreadable (float properties)", "a keep rule whose float cannot be read keeps the weapon"); + var twoHanded = PlainSword with { WieldSkill = 41, Cleaving = 2 }; + Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded), null, "two-handed cleave 2 chunks"); + Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 2 }), "cleave over the limit", "other cleave 2 is kept"); + Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { WieldSkill = 0, WeaponType = 11 }), null, "WeaponType two-handed counts"); + Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { AttackType = 2 }), "cleave over the limit", "two-handed thrust keeps the 1 limit"); + } + + private static void Kinds() + { + var gem = RynthCore.Loot.AcObjectClass.Gem; + Check.Eq(IltChunkClap.KindOf(gem, "Coalesced Aetheria"), IltChunkClap.ChunkKind.Aetheria, "Coalesced"); + Check.Eq(IltChunkClap.KindOf(gem, "Blue Aetheria"), IltChunkClap.ChunkKind.Aetheria, "revealed sigil"); + Check.Eq(IltChunkClap.KindOf(gem, "Red Aetheria Chunk"), IltChunkClap.ChunkKind.None, "chunk"); + Check.Eq(IltChunkClap.KindOf(gem, "Aetheria Powder"), IltChunkClap.ChunkKind.None, "powder"); + Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MeleeWeapon, "Corrupted Greatsword"), IltChunkClap.ChunkKind.Corrupted, "melee"); + Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MissileWeapon, "Corrupted Bow"), IltChunkClap.ChunkKind.Corrupted, "missile"); + Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.WandStaffOrb, "Corrupted Orb"), IltChunkClap.ChunkKind.None, "casters are not chunked (ub-IT)"); + Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MeleeWeapon, "Greatsword"), IltChunkClap.ChunkKind.None, "not corrupted"); + } + + private static readonly IltChunkClap.CorruptedFacts PlainSword = new() { Workmanship = 6, AttackType = 4, WieldSkill = 45 }; + + private static void CorruptedHardRules() + { + var g = new IltGearState(); + Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword), null, "a plain corrupted sword chunks"); + Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Workmanship = 0 }), "no workmanship", "workmanship 0"); + Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Tinkers = 1 }), "tinkered or imbued", "tinkered"); + Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Imbue = 1 }), "tinkered or imbued", "imbued"); + Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { NeverChunk = true }), "never-chunk flag", "bool 9030"); + Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 1 }), null, "one-handed cleave 1"); + Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 2 }), "cleave over the limit", "one-handed cleave 2"); + + var twoHanded = PlainSword with { WieldSkill = 41, Cleaving = 2 }; + Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded), null, "two-handed cleave 2 chunks (it never did before)"); + Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { Cleaving = 3 }), "cleave over the limit", "two-handed cleave 3"); + Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { AttackType = 2 }), "cleave over the limit", "a two-handed thrust weapon keeps the 1 limit"); + Check.Eq(IltChunkClap.MaxChunkCleave(0, 11, 4), 2, "WeaponType TwoHanded counts too"); + Check.Eq(IltChunkClap.MaxChunkCleave(45, 0, 4), 1, "one-handed"); + } + + private static void CorruptedKeepRules() + { + var g = new IltGearState(); + var loaded = PlainSword with + { + CritFrequency = 0.1, CritMultiplier = 1.5, IgnoreArmor = 0.2, Slayer = 5, AttackType = 160, + ElementalBonus = 10, MaxDamage = 400, Spells = new[] { 2072 }, + }; + Check.Eq(IltChunkClap.CorruptedSkip(g, loaded), null, "every keep rule is off by default"); + + Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedCrushingBlow = true }, loaded), "kept: Crushing Blow", "Crushing Blow"); + Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedBitingStrike = true }, loaded), "kept: Biting Strike", "Biting Strike"); + Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedArmorCleaving = true }, loaded), "kept: Armor Cleaving", "Armor Cleaving"); + Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedAnySlayer = true }, loaded), "kept: slayer", "slayer"); + Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMultiStrike = true }, loaded), "kept: multi-strike", "multi-strike 160"); + Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMultiStrike = true }, PlainSword), null, "a single slash is not multi-strike"); + Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedElementalBonus = true }, loaded), "kept: elemental bonus", "elemental"); + Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMaxDamageAtLeast = 400 }, loaded), "kept: max damage", "max damage at the limit"); + Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMaxDamageAtLeast = 401 }, loaded), null, "max damage under the limit"); + Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedAnySpell = true }, loaded), "kept: has a spell", "any spell"); + Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedSpellIds = "100, 2072" }, loaded), "kept: listed spell", "listed spell id"); + Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedSpellIds = "100 200" }, loaded), null, "other spell ids"); + + Check.Eq(IltChunkClap.ParseSpellIds("1, 2;3 x -4 0").Count, 3, "positive ids only, any separator"); + Check.Eq(IltChunkClap.ParseSpellIds(null).Count, 0, "no list"); + } + + /// + /// Silentkelpie 2026-10-18: a Coalesced piece was chunked (Red Aetheria Chunk arrived) with no + /// result line, and it was filed as skipped after 10 s instead of counted. + /// + private static void WaitOutcome() + { + Check.Eq(IltChunkClap.WaitOutcome(500, targetStillCarried: true), IltChunkClap.ChunkWait.Waiting, "still carried, within the wait"); + Check.Eq(IltChunkClap.WaitOutcome(1_100, targetStillCarried: false), IltChunkClap.ChunkWait.Gone, "gone from the pack: chunked"); + Check.Eq(IltChunkClap.WaitOutcome(12_000, targetStillCarried: false), IltChunkClap.ChunkWait.Gone, "gone beats the timeout"); + Check.Eq(IltChunkClap.WaitOutcome(10_000, targetStillCarried: true), IltChunkClap.ChunkWait.TimedOut, "still carried at 10 s: timed out"); + } + + private static void BusyGate() + { + Check.True(IltChunkClap.AllowsChunkWhileBusy(isBusy: false, isPeace: true, chunkInCombat: false), "idle in peace"); + Check.False(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: true, chunkInCombat: true), "busy in peace waits"); + Check.True(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: false, chunkInCombat: true), "busy swinging with chunk-in-combat"); + Check.False(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: false, chunkInCombat: false), "busy in combat without it"); + } + + /// + /// ACECustom /clap: red (Coalesced 42636 at 1-3, chunk 310147, powder 42644) with Empyrean + /// Trinkets (34276); blue (42635, 310149, 300019) with Falatacot (34277). 42635/42636 were taken + /// for chunks, and one side alone counted, so auto-clap sent /clap with nothing to pair. + /// + private static void ClapPairs() + { + const string Co = "Coalesced Aetheria"; + Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 2), IltChunkClap.ClapPart.Red, "red Coalesced level 2"); + Check.Eq(IltChunkClap.ClapPartOf(42635, Co, 3), IltChunkClap.ClapPart.Blue, "blue Coalesced level 3"); + Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 0), IltChunkClap.ClapPart.Red, "level not read yet: the server decides"); + Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 4), IltChunkClap.ClapPart.None, "level 4 Coalesced is not clapped"); + Check.Eq(IltChunkClap.ClapPartOf(42636, "Aetheria", 1), IltChunkClap.ClapPart.None, "revealed aetheria is not clapped"); + Check.Eq(IltChunkClap.ClapPartOf(42637, Co, 1), IltChunkClap.ClapPart.None, "yellow has no clap use"); + Check.Eq(IltChunkClap.ClapPartOf(310147, "Red Aetheria Chunk", 0), IltChunkClap.ClapPart.Red, "red chunk"); + Check.Eq(IltChunkClap.ClapPartOf(310149, "Blue Aetheria Chunk", 0), IltChunkClap.ClapPart.Blue, "blue chunk"); + Check.Eq(IltChunkClap.ClapPartOf(310150, "Yellow Aetheria Chunk", 0), IltChunkClap.ClapPart.None, "yellow chunk"); + Check.Eq(IltChunkClap.ClapPartOf(42644, "Aetheria Powder", 0), IltChunkClap.ClapPart.Red, "red powder"); + Check.Eq(IltChunkClap.ClapPartOf(300019, "Aetheria Powder", 0), IltChunkClap.ClapPart.Blue, "blue powder"); + Check.Eq(IltChunkClap.ClapPartOf(34276, "Ancient Empyrean Trinket", 0), IltChunkClap.ClapPart.Empyrean, "Empyrean trinket"); + Check.Eq(IltChunkClap.ClapPartOf(34277, "Ancient Falatacot Trinket", 0), IltChunkClap.ClapPart.Falatacot, "Falatacot trinket"); + Check.Eq(IltChunkClap.ClapPartOf(0, "Red Aetheria Chunk", 0), IltChunkClap.ClapPart.Red, "no WCID yet: the chunk name"); + Check.Eq(IltChunkClap.ClapPartOf(0, Co, 1), IltChunkClap.ClapPart.None, "no WCID yet: a Coalesced piece's colour is unknown"); + Check.Eq(IltChunkClap.ClapPartOf(273, "Pyreal", 0), IltChunkClap.ClapPart.None, "anything else"); + + var R = IltChunkClap.ClapPart.Red; var B = IltChunkClap.ClapPart.Blue; + var E = IltChunkClap.ClapPart.Empyrean; var F = IltChunkClap.ClapPart.Falatacot; + Check.True(IltChunkClap.CanClap(new[] { R, E }), "red + Empyrean"); + Check.True(IltChunkClap.CanClap(new[] { B, F }), "blue + Falatacot"); + Check.False(IltChunkClap.CanClap(new[] { R, F }), "red needs Empyrean, not Falatacot"); + Check.False(IltChunkClap.CanClap(new[] { B, E }), "blue needs Falatacot, not Empyrean"); + Check.False(IltChunkClap.CanClap(new[] { E, F }), "trinkets alone"); + Check.False(IltChunkClap.CanClap(new[] { R, B }), "aetheria alone"); + Check.False(IltChunkClap.CanClap(System.Array.Empty()), "nothing carried"); + } + + private static void Cap() + { + Check.Eq(IltInventory.AetheriaMaxLevel, 10, "ILT max aetheria level"); + Check.Eq(IltChunkClap.ClampUnderLevel(0), 1, "below 1 clamps to 1"); + Check.Eq(IltChunkClap.ClampUnderLevel(7), 7, "7 (retail clamp was 6) is allowed"); + Check.Eq(IltChunkClap.ClampUnderLevel(11), 11, "11 chunks every level"); + Check.Eq(IltChunkClap.ClampUnderLevel(50), 11, "above 11 clamps to 11"); + Check.Eq(new IltGearState().ChunkAetheriaUnderLevel, 4, "the default cap is unchanged"); + } + + private static void Ratings() + { + var g = new IltGearState(); + Check.True(g.KeepAetheriaWithCrit && g.KeepAetheriaWithCritDamage && g.KeepAetheriaWithCritDamageResist, "all keep switches on by default"); + Check.False(IltChunkClap.KeptForRatings(g, 0, 0, 0), "no rating: chunkable"); + Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C kept"); + Check.True(IltChunkClap.KeptForRatings(g, 0, 1, 0), "CD kept"); + Check.True(IltChunkClap.KeptForRatings(g, 0, 0, 3), "CDR kept"); + + g.KeepAetheriaWithCrit = false; + Check.False(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C chunkable with its switch off"); + Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 3), "CDR still keeps a C+CDR sigil"); + g.KeepAetheriaWithCritDamage = false; + g.KeepAetheriaWithCritDamageResist = false; + Check.False(IltChunkClap.KeptForRatings(g, 3, 3, 3), "every switch off: ratings don't protect"); + } + + /// + /// The rating level: a C / CD / CDR rating at or above it keeps the piece, a lower one chunks + /// (if the level cap allows). The default of 1 keeps any rating, as before. + /// + private static void RatingLevel() + { + var g = new IltGearState(); + Check.Eq(g.KeepAetheriaRatingAtLeast, 1, "default: any rating keeps"); + Check.True(IltChunkClap.KeptForRatings(g, 1, 0, 0), "C 1 kept at the default"); + + g.KeepAetheriaRatingAtLeast = 2; + Check.False(IltChunkClap.KeptForRatings(g, 1, 0, 0), "C 1 below level 2: chunks"); + Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C 2 at level 2: kept"); + Check.True(IltChunkClap.KeptForRatings(g, 3, 0, 0), "C 3 above level 2: kept"); + Check.True(IltChunkClap.KeptForRatings(g, 1, 0, 2), "CDR 2 keeps a C 1 + CDR 2 piece"); + Check.False(IltChunkClap.KeptForRatings(g, 1, 1, 1), "every rating below the level: chunks"); + + g.KeepAetheriaWithCrit = false; + Check.False(IltChunkClap.KeptForRatings(g, 5, 0, 0), "a switch that is off ignores the level"); + + Check.Eq(IltChunkClap.ClampRatingLevel(0), 1, "below 1 clamps to 1"); + Check.Eq(IltChunkClap.ClampRatingLevel(99), IltChunkClap.MaxRatingLevel, "clamped to the maximum"); + + var coalescedC1 = PlainCoalesced with { Crit = 1 }; + var level2 = new IltGearState { KeepAetheriaRatingAtLeast = 2 }; + Check.Eq(IltChunkClap.AetheriaSkip(level2, coalescedC1), null, "an unlevelled C 1 Coalesced piece chunks at rating level 2"); + Check.Eq(IltChunkClap.AetheriaSkip(level2, PlainCoalesced with { Crit = 2 }), "kept for its C / CD / CDR rating", "a C 2 one is kept"); + Check.Eq(IltChunkClap.AetheriaSkip(level2, coalescedC1 with { MaxLevel = 6 }), "level at or above the cap", + "a low rating does not override the level cap"); + } +} diff --git a/Tools/RynthILT.Tests/AttributeRaiserTests.cs b/Tools/RynthILT.Tests/AttributeRaiserTests.cs new file mode 100644 index 0000000..01765da --- /dev/null +++ b/Tools/RynthILT.Tests/AttributeRaiserTests.cs @@ -0,0 +1,543 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// Server Features gate + the infinite-attribute raiser (2026-10-06; RynthAi's ILT Hub, in RynthILT +// since 2026-10-13). The gate decides from RynthILT's server list (world-name patterns) and the +// character's "Treat this world as ILT" whether the ILT features ask the server at all; the raiser reads "/xp all" costs and spends unassigned XP with "/attr 1" +// on the ticked stats, in the chosen order, never below the reserve. +internal static class AttributeRaiserTests +{ + private const uint Player = 0x50000C01; + + public static void Register(Runner r) + { + r.Add("server features: name patterns (exact, wildcards, case)", Patterns); + r.Add("server features: list parsing and the override", ListAndOverride); + r.Add("attr raiser: pick by mode (priority, round robin, cheapest)", PickModes); + r.Add("attr raiser: pick respects ticks, reserve and unknown costs", PickLimits); + r.Add("attr raiser: order repair and stat names from server lines", OrderAndNames); + r.Add("attr raiser: a run reads costs, raises in order, stops when nothing is affordable", FullRun); + r.Add("attr raiser: off when the world is not in the Server Features list", GatedOff); + r.Add("attr raiser: safety (stale costs, another stat's reply, gate off mid-run, held off)", Safety); + r.Add("attr raiser: by-hand +1 / +10 priced like UB, refused when unaffordable, costs read on tab open", ByHandPriced); + r.Add("aug planner: /aug pulled on tab open, totals, reset targets, copy texts", AugPlanner); + r.Add("aug refresh: banner alone does not end /aug; Current updates from level lines", AugRefreshWaitsForLevelLines); + r.Add("aug refresh: a probe that left Current empty retries /aug once; a click during the probe runs after it", AugProbeRetry); + r.Add("aug lines: separators in the level (4,300 / 4.300 / 4 300 / 4'300) and trailing notes read", AugLineValues); + r.Add("aug costs: UB's ILT model (tier starts at its S level) in closed form", AugCostModel); + r.Add("aug costs: per-server multipliers and rules, saved and reset", AugCostSettings); + } + + /// UB Augs.cs GetCumulativeCost difference, level by level (the reference the closed form must match). + private static decimal UbLoop(IltAugCostRow r, double[] m, int cur, int tgt) + { + decimal step = r.Base * (decimal)r.LinearPercent / 100m, total = 0; + for (int i = cur + 1; i <= tgt; i++) + { + decimal b = r.Base + (i - 1) * step; + double mult = i < r.S1 ? m[0] : i < r.S2 ? m[1] : i < r.S3 ? m[2] : i < r.S4 ? m[3] : m[4]; + total += b * (decimal)mult; + } + return total; + } + + private static void AugCostModel() + { + var rows = IltAugCosts.DefaultRows().ToDictionary(x => x.Key); + var m = IltAugCosts.DefaultMultipliers; + var creature = rows["creature"]; + Check.Eq(IltAugCosts.LumCost(creature, m, 2748, 2749), 750_000m + 2748 * 975_000m, "level 2749 (S1 - 1) is the last x1 level"); + Check.Eq(IltAugCosts.LumCost(creature, m, 2749, 2750), (750_000m + 2749 * 975_000m) * 4, "level 2750 (S1) is the first x4 level"); + Check.Eq(rows["specialization"].S2, 2500, "Specialization uses UB's 1750/2500/3000/3750"); + Check.Eq(rows["summon"].S1, 1750, "Summon uses UB's 1750/2500/3000/3750"); + Check.Eq(creature.Cap, 0, "no target cap by default (UB has none)"); + + foreach (var (key, cur, tgt) in new[] { ("creature", 0, 6000), ("item", 1200, 3600), ("specialization", 1700, 3800), + ("duration", 999, 1001), ("summon", 3749, 3751), ("life", 10, 10) }) + Check.Eq(IltAugCosts.LumCost(rows[key], m, cur, tgt), UbLoop(rows[key], m, cur, tgt), $"{key} {cur}->{tgt} matches UB's loop"); + var odd = new double[] { 1.5, 2, 3.25, 10, 0 }; + Check.Eq(IltAugCosts.LumCost(rows["war"], odd, 1500, 4000), UbLoop(rows["war"], odd, 1500, 4000), "custom multipliers match the loop"); + Check.Eq(IltAugCosts.LumCost(creature, m, 50, 40), 0m, "a target below current costs nothing"); + Check.True(IltAugCosts.LumCost(creature, m, 0, IltAugCosts.NoCapLimit) > 0, "the largest uncapped target is priced without overflow"); + } + + private static void AugCostSettings() + { + string file = IltAugCosts.FilePath; + if (File.Exists(file)) File.Delete(file); + var settings = new IltSettings(); + var hub = NewHub("InfiniteLeaftide", settings, "aug-costs", out _); + var prog = hub.Progression; + prog.ApplyAugLines(new List { "War: 1700" }); + hub.State.Character.AugTargets["war"] = 1800; + + string Snapshot() + { + var sb = new System.Text.StringBuilder(); + prog.AppendSnapshotJson(sb); + return "{" + sb + "}"; + } + System.Text.Json.JsonElement Aug(string json) => System.Text.Json.JsonDocument.Parse(json).RootElement.GetProperty("aug"); + + var before = Aug(Snapshot()); + Check.False(before.GetProperty("cfg").GetProperty("custom").GetBoolean(), "a world starts on the defaults"); + Check.Eq(before.GetProperty("cfg").GetProperty("mults").GetArrayLength(), 5, "five tier multipliers in the snapshot"); + string lumBefore = before.GetProperty("totLum").GetString() ?? ""; + + prog.HandleRemote(new[] { "augmult", "1", "2" }); + var after = Aug(Snapshot()); + Check.True(after.GetProperty("cfg").GetProperty("custom").GetBoolean(), "an edit gives the world its own rules"); + Check.Eq(after.GetProperty("cfg").GetProperty("mults")[1].GetDouble(), 2.0, "multiplier saved"); + Check.True((after.GetProperty("totLum").GetString() ?? "") != lumBefore, "the plan re-prices with the new multiplier"); + + prog.HandleRemote(new[] { "augcfg", "war", "s1", "1800" }); + prog.HandleRemote(new[] { "augcfg", "war", "base", "1m" }); + prog.HandleRemote(new[] { "augcfg", "war", "s2", "100" }); + var war = prog.AugCosts.For("InfiniteLeaftide").Augs.First(x => x.Key == "war"); + Check.Eq(war.S1, 1800, "S1 edited"); + Check.Eq(war.Base, 1_000_000L, "base accepts k/m/b suffixes"); + Check.Eq(war.S2, 1800, "S2 can't go below S1"); + Check.Eq(prog.AugCosts.For("Aelrynth").Multipliers[1], 4.0, "another world keeps the defaults"); + + var reloaded = new IltAugCosts(); + Check.Eq(reloaded.For("infiniteleaftide").Multipliers[1], 2.0, "rules are saved per world (name ignores case)"); + + prog.HandleRemote(new[] { "augcfgreset" }); + Check.False(prog.AugCosts.IsCustom("InfiniteLeaftide"), "reset drops the world's rules"); + Check.Eq(new IltAugCosts().For("InfiniteLeaftide").Multipliers[1], 4.0, "and the reset is saved"); + } + + private static void ByHandPriced() + { + Check.Eq(IltAttributeRaiser.ProjectCost(1_000, 1), 1_000L, "one level costs the reported cost"); + // 1000 * (1.077^10 - 1) / 0.077 = 14,281.7 (UB's EstimateMultiLevelCost). + Check.Eq(IltAttributeRaiser.ProjectCost(1_000, 10), 14_281L, "ten levels grow 7.7% each"); + Check.Eq(IltAttributeRaiser.ProjectCost(0, 10), 0L, "unknown cost projects nothing"); + Check.Eq(IltAttributeRaiser.ProjectCost(long.MaxValue / 2, 10), long.MaxValue, "saturates instead of overflowing"); + + var settings = new IltSettings(); + var hub = NewHub("InfiniteLeaftide", settings, "attr-byhand", out _); + var raiser = hub.Progression.Attributes; + FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 5_000; + // Levels already known (as after the login probe), so the tab doesn't queue /aug ahead of /xp all. + hub.Progression.ApplyAugLines(new List { "Creature: 1" }); + + // Opening the tab (a snapshot poll) reads the costs once per login. + var sb = new System.Text.StringBuilder(); + hub.Progression.AppendSnapshotJson(sb); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "the first snapshot reads the costs"); + Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 1,000", + "[XP] Your XP cost for next 1 Strength level is: 4,000"); + TickUntil(hub, () => false, 400); + int reads = FakeHost.ChatCommands.Count(x => x == "/xp all"); + hub.Progression.AppendSnapshotJson(new System.Text.StringBuilder()); + TickUntil(hub, () => false, 400); + Check.Eq(FakeHost.ChatCommands.Count(x => x == "/xp all"), reads, "later snapshots don't read again"); + + sb.Clear(); + raiser.AppendJson(sb); + string json = sb.ToString(); + System.Text.Json.JsonDocument.Parse("{" + json + "}").Dispose(); + Check.True(json.Contains("\"key\":\"coo\"") && json.Contains("\"afford1\":true") && json.Contains("\"cost10\":\"~14.3K\""), + $"Coordination: +1 affordable, +10 projected (got {json})"); + Check.True(json.Contains("\"updated\":\"") && !json.Contains("\"updated\":\"-\""), "the last-updated time is set"); + + // +10 Coordination (~14.3K of 5K) is refused; +1 Strength (4K of 5K) goes out. + raiser.RaiseManual("coo", 10); + var status = new System.Text.StringBuilder(); + raiser.AppendJson(status); + Check.True(status.ToString().Contains("Not enough unassigned XP"), "an unaffordable +10 is refused with the reason"); + raiser.RaiseManual("str", 1); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr str 1")), "an affordable +1 is sent"); + Check.False(FakeHost.ChatCommands.Contains("/attr coo 10"), "the refused +10 was never sent"); + } + + private static void AugPlanner() + { + var settings = new IltSettings(); + var hub = NewHub("InfiniteLeaftide", settings, "aug-planner", out _); + var prog = hub.Progression; + + prog.AppendSnapshotJson(new System.Text.StringBuilder()); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "opening the tab pulls /aug once"); + prog.ApplyAugLines(new List { "Creature: 100", "Specialize: 2", "Summon: 0" }); + + prog.HandleRemote(new[] { "augtarget", "creature", "110" }); + var sb = new System.Text.StringBuilder(); + prog.AppendSnapshotJson(sb); + string json = sb.ToString(); + using (var doc = System.Text.Json.JsonDocument.Parse("{" + json + "}")) + { + var aug = doc.RootElement.GetProperty("aug"); + Check.Eq(aug.GetProperty("totCur").GetInt64(), 102L, "totals: current"); + Check.Eq(aug.GetProperty("totTgt").GetInt64(), 112L, "totals: target"); + Check.Eq(aug.GetProperty("totInc").GetInt64(), 10L, "totals: increase"); + Check.Eq(aug.GetProperty("totCoins").GetInt64(), 30L, "Creature costs 3 coins a level"); + var creature = aug.GetProperty("rows").EnumerateArray().First(x => x.GetProperty("key").GetString() == "creature"); + Check.Eq(creature.GetProperty("inc").GetInt32(), 10, "row: increase"); + string discord = aug.GetProperty("copyDiscord").GetString() ?? ""; + Check.True(discord.StartsWith("```", StringComparison.Ordinal) && discord.Contains("TOTALS:") && discord.Contains("Creature"), + "Discord copy is a code-block table with totals"); + Check.True(discord.All(ch => ch < 128), "copy text is ASCII (the engine reads the snapshot as ANSI)"); + string ingame = aug.GetProperty("copyIngame").GetString() ?? ""; + Check.True(ingame.Contains("Crit: 100") && ingame.Contains("Spec: 2") && !ingame.Contains("Sum:"), + $"in-game copy lists current levels with short names (got '{ingame}')"); + } + + prog.HandleRemote(new[] { "augreset" }); + Check.Eq(hub.State.Character.AugTargets["creature"], 100, "reset targets: back to current"); + Check.Eq(hub.State.Character.AugTargets["summon"], 0, "reset targets: unloaded augs go to 0"); + Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 1, "levels loaded: no second automatic /aug"); + } + + /// + /// Refresh current must not finish on the /aug banner alone (chat-hold lag used to leave Current at 0). + /// + private static void AugRefreshWaitsForLevelLines() + { + var settings = new IltSettings(); + var hub = NewHub("InfiniteLeaftide", settings, "aug-refresh-idle", out _); + var prog = hub.Progression; + // Seed so EnsureAugs does not queue its own /aug ahead of our Refresh. + prog.ApplyAugLines(new List { "Creature: 1" }); + + prog.HandleRemote(new[] { "augload" }); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "Refresh current sends /aug"); + Reply(hub, "---------------------------", "Advanced Augmentation Levels:"); + // Longer than IdleEndMs (2s): without ArmsIdle this used to ApplyAugLines([]) and clear the status. + var until = DateTime.UtcNow.AddMilliseconds(2500); + while (DateTime.UtcNow < until) { hub.Tick(); Thread.Sleep(25); } + Check.True(FakeHost.ChatCommands.Count(x => x == "/aug") == 1, "still waiting on the same /aug (banner did not end it)"); + + Reply(hub, "Creature:4,300", "Item:100", "Specialize: 2"); + Check.True(TickUntil(hub, () => + { + var sb = new System.Text.StringBuilder(); + prog.AppendSnapshotJson(sb); + return sb.ToString().Contains("\"cur\":4300", StringComparison.Ordinal); + }), "Current updates once Creature:/Item: lines arrive"); + } + + // Silentkelpie (PR #12): the login probe could end on the banner alone (chat-hold backlog) and leave + // Current empty with nothing to retry it; a Refresh current click during the probe was dropped. + private static void AugProbeRetry() + { + var hub = NewHub("InfiniteLeaftide", new IltSettings(), "aug-probe-retry", out _); + var prog = hub.Progression; + + // Probe reply: the banner and no level lines. The tap runs ApplyAugLines then AfterExternalAugCapture. + prog.ApplyAugLines(new List { "---------------------------", "Advanced Augmentation Levels:" }); + prog.AfterExternalAugCapture(); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "Current still empty: /aug is sent again"); + prog.AfterExternalAugCapture(); // the retry is in flight, and was the one retry + prog.ApplyAugLines(new List { "Advanced Augmentation Levels:" }); + prog.AfterExternalAugCapture(); + for (int i = 0; i < 20; i++) { hub.Tick(); Thread.Sleep(25); } + Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 1, "only one retry"); + + Reply(hub, "Creature:4,300", "Item:100"); + Check.True(TickUntil(hub, () => + { + var sb = new System.Text.StringBuilder(); + prog.AppendSnapshotJson(sb); + return sb.ToString().Contains("\"cur\":4300", StringComparison.Ordinal); + }), "the retry's level lines fill Current"); + + // A probe with levels needs no retry. + var hub2 = NewHub("InfiniteLeaftide", new IltSettings(), "aug-probe-ok", out _); + hub2.Progression.ApplyAugLines(new List { "Creature: 12" }); + hub2.Progression.AfterExternalAugCapture(); + for (int i = 0; i < 20; i++) { hub2.Tick(); Thread.Sleep(25); } + Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 0, "levels present: no retry"); + } + + private static void AugLineValues() + { + Check.True(IltParse.AugLine.IsMatch("Creature:4,300") && IltParse.AugLine.IsMatch("Creature: 4.300") + && IltParse.AugLine.IsMatch("Creature: 4 300") && IltParse.AugLine.IsMatch("Creature: 4'300"), "the regex matches each grouping"); + Check.False(IltParse.AugLine.IsMatch("Creature: none") || IltParse.AugLine.IsMatch("Advanced Augmentation Levels:"), "and not a line with no number"); + Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature:4,300").Groups[2].Value), 4300L, "comma"); + Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4.300").Groups[2].Value), 4300L, "period"); + Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4 300").Groups[2].Value), 4300L, "space"); + Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4'300").Groups[2].Value), 4300L, "apostrophe"); + Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 1,234,567").Groups[2].Value), 1234567L, "two groups"); + Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Duration: 5 (adds 3)").Groups[2].Value), 5L, "a trailing note"); + Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Specialize: 2").Groups[2].Value), 2L, "plain"); + Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Item: 2750").Groups[2].Value), 2750L, "no separator"); + Check.Eq(IltParse.ParseAugValue(""), 0L, "empty"); + + var hub = NewHub("InfiniteLeaftide", new IltSettings(), "aug-values", out _); + hub.Progression.ApplyAugLines(new List { "Creature: 2 750", "Item: 1.200", "Life: 300" }); + var sb = new System.Text.StringBuilder(); + hub.Progression.AppendSnapshotJson(sb); + string snap = sb.ToString(); + Check.True(snap.Contains("\"cur\":2750", StringComparison.Ordinal) && snap.Contains("\"cur\":1200", StringComparison.Ordinal) + && snap.Contains("\"cur\":300", StringComparison.Ordinal), "the planner takes the grouped levels whole"); + } + + private static void Patterns() + { + Check.True(ServerFeatureGate.Matches("InfiniteLeaftide", "InfiniteLeaftide"), "exact"); + Check.True(ServerFeatureGate.Matches("infiniteleaftide", "InfiniteLeaftide"), "exact ignores case"); + Check.False(ServerFeatureGate.Matches("InfiniteLeaftide2", "InfiniteLeaftide"), "exact means the whole name"); + Check.True(ServerFeatureGate.Matches("Leaftide Test", "*Leaftide*"), "contains"); + Check.True(ServerFeatureGate.Matches("MyLeaftide", "*tide"), "ends with"); + Check.True(ServerFeatureGate.Matches("Leaftide-PTR", "Leaf*"), "starts with"); + Check.True(ServerFeatureGate.Matches("Aelrynth Infinite", "Ael*Inf*"), "two wildcards"); + Check.False(ServerFeatureGate.Matches("Aelrynth", "*Leaftide*"), "no match"); + Check.False(ServerFeatureGate.Matches("ab", "a*bb"), "the end part must fit after the start"); + Check.True(ServerFeatureGate.NameMatches("Aelrynth", new[] { "", "InfiniteLeaftide", "aelrynth" }, out string m) && m == "aelrynth", + "NameMatches reports the pattern that matched"); + Check.False(ServerFeatureGate.NameMatches("", ServerFeatureGate.DefaultServerNames, out _), "an unknown world never matches"); + } + + private static void ListAndOverride() + { + var list = ServerFeatureGate.ParseList(" InfiniteLeaftide , *Leaftide*;Aelrynth,,aelrynth "); + Check.Eq(string.Join("|", list), "InfiniteLeaftide|*Leaftide*|Aelrynth", "trimmed, split on , and ;, de-duplicated ignoring case"); + Check.Eq(ServerFeatureGate.FormatList(list), "InfiniteLeaftide, *Leaftide*, Aelrynth", "formatted back for the text box"); + + var s = new IltSettings(); + Check.True(s.ServerNames.Contains("InfiniteLeaftide"), "fresh settings start with the defaults"); + Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s, forceOn: false), "the default list covers InfiniteLeaftide"); + Check.False(ServerFeatureGate.IsEnabled("Aelrynth", s, forceOn: false), "another world is off by default"); + Check.True(ServerFeatureGate.IsEnabled("Aelrynth", s, forceOn: true), "the character's override turns it on anywhere"); + s.ServerNames = new List { "Aelrynth" }; + Check.True(ServerFeatureGate.IsEnabled("aelrynth", s, forceOn: false), "a world added to the list is on"); + Check.False(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s, forceOn: false), "a world removed from the list is off"); + Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", null, forceOn: false), "no settings yet: the defaults apply"); + s.ServerNames = new List(); + Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s, forceOn: false), "an emptied list falls back to the defaults"); + } + + private static readonly string[] Order = { "coo", "qui", "str", "end", "foc", "sel", "hea", "sta", "man" }; + + private static void PickModes() + { + var cost = new Dictionary { ["coo"] = 500, ["qui"] = 300, ["str"] = 100 }; + var ticked = new HashSet { "coo", "qui", "str" }; + int rr = 0; + Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, ticked, cost, 1000, ref rr), "coo", + "priority: the first affordable stat in the order"); + Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, ticked, cost, 400, ref rr), "qui", + "priority: skips a stat it can't afford"); + Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, ticked, cost, 1000, ref rr), "str", + "cheapest: the lowest next-level cost"); + var tie = new Dictionary { ["coo"] = 100, ["str"] = 100 }; + Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, ticked, tie, 1000, ref rr), "coo", + "cheapest: a tie goes to the higher-priority stat"); + + rr = 0; + var picks = new List(); + for (int i = 0; i < 4; i++) picks.Add(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 1000, ref rr)); + Check.Eq(string.Join(",", picks), "coo,qui,str,coo", "round robin: one each in order, then around again"); + rr = 0; + Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 400, ref rr), "qui", + "round robin: an unaffordable stat is passed over"); + Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 400, ref rr), "str", + "round robin: carries on from the last pick"); + } + + private static void PickLimits() + { + var cost = new Dictionary { ["coo"] = 500, ["qui"] = 300 }; + int rr = 0; + Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet(), cost, 10_000, ref rr), + "nothing ticked: nothing raised"); + Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet { "qui" }, cost, 10_000, ref rr), "qui", + "an unticked stat is never spent on, even at the top of the order"); + Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet { "coo", "qui" }, cost, 0, ref rr), + "no budget (XP at or below the reserve): nothing raised"); + Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet { "str" }, cost, 10_000, ref rr), + "a stat whose cost wasn't read is not raised blind"); + var zero = new Dictionary { ["coo"] = 0 }; + Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, new HashSet { "coo" }, zero, 10_000, ref rr), + "a zero cost (unparsed) is not raised"); + } + + private static void OrderAndNames() + { + var repaired = IltAttributeRaiser.RepairOrder(new List { "sel", "bogus", "Self", "Strength", "hea" }); + Check.Eq(string.Join(",", repaired), "sel,str,hea,coo,qui,end,foc,sta,man", + "saved order kept, duplicates/junk dropped, missing stats appended in the default order"); + Check.Eq(IltAttributeRaiser.RepairOrder(null).Count, 9, "a missing order becomes the default"); + Check.Eq(string.Join(",", IltAttributeRaiser.RepairSelection(new List { "Coordination", "coo", "x" })), "coo", + "selection: names map to abbreviations, duplicates and junk dropped"); + + Check.Eq(IltAttributeRaiser.Find("MaxHealth")?.Abbr, "hea", "cost line 'MaxHealth'"); + Check.Eq(IltAttributeRaiser.Find("Maximum Stamina")?.Abbr, "sta", "'Maximum Stamina'"); + Check.Eq(IltAttributeRaiser.Find("Self")?.Abbr, "sel", "Self"); + Check.Eq(IltAttributeRaiser.Find("qui")?.Abbr, "qui", "abbreviation"); + Check.Null(IltAttributeRaiser.Find("Luck"), "unknown names are rejected"); + + var cost = IltParse.XpCost.Match("[XP] Your XP cost for next 1 Coordination level is: 12,345,678"); + Check.True(cost.Success && cost.Groups[1].Value == "Coordination" && IltParse.ParseLeadingLong(cost.Groups[2].Value) == 12_345_678, + "the /xp all cost line parses"); + var raised = IltParse.AttrRaised.Match("[ATTR] Quickness attribute raised by 1, costing 9,876!"); + Check.True(raised.Success && raised.Groups[1].Value == "Quickness" && raised.Groups[2].Value == "1" + && IltParse.ParseLeadingLong(raised.Groups[3].Value) == 9876, "the /attr success line parses"); + } + + // ── The loop on the fake host ───────────────────────────────────────────── + + private static IltHubController NewHub(string world, IltSettings settings, string folder, out RynthCoreHost host) + { + FakeHost.Reset(); + FakeHost.WorldName = world; + host = FakeHost.Create(Player); + string dir = Path.Combine(Program.TempRoot, folder); + Directory.CreateDirectory(dir); + // No RynthAi here (the fake host has no GetPluginInterface): RynthILT runs on its own. + return new IltHubController(host, dir, settings, new RynthAiClient(host)); + } + + /// Ticks the hub until or the timeout (the chat queue spaces sends by real time). + private static bool TickUntil(IltHubController hub, Func done, int timeoutMs = 6000) + { + var until = DateTime.UtcNow.AddMilliseconds(timeoutMs); + while (DateTime.UtcNow < until) + { + hub.Tick(); + if (done()) return true; + Thread.Sleep(25); + } + return false; + } + + private static void Reply(IltHubController hub, params string[] lines) + { + foreach (string l in lines) hub.OnChat(l); + } + + private static void FullRun() + { + var settings = new IltSettings(); + var hub = NewHub("InfiniteLeaftide", settings, "attr-run", out _); + var c = hub.State.Character; + c.AttrRaiseStats = new List { "coo", "qui" }; + c.AttrRaiseMode = (int)IltAttributeRaiser.Mode.Priority; + c.AttrKeepXp = 200; + FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 2_500; + var raiser = hub.Progression.Attributes; + + Check.Null(raiser.Blocker(), "an ILT world with /xp not reported off: the raiser can run"); + raiser.Start(auto: false); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "a run starts by reading the costs"); + Reply(hub, "[XP] Your XP cost for next 1 Strength level is: 50", + "[XP] Your XP cost for next 1 Coordination level is: 1,000", + "[XP] Your XP cost for next 1 Quickness level is: 1,200"); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr coo 1")), + "priority: Coordination first (Strength is cheaper but not ticked)"); + + FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 1_500; + Reply(hub, "[ATTR] Coordination attribute raised by 1, costing 1,000!"); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Count(x => x == "/xp all") >= 2), "costs are read again after each raise"); + Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 2,000", + "[XP] Your XP cost for next 1 Quickness level is: 1,200"); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr qui 1")), + "Coordination now costs more than the spendable 1,300: Quickness next"); + + FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 300; + Reply(hub, "[ATTR] Quickness attribute raised by 1, costing 1,200!"); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Count(x => x == "/xp all") >= 3), "third cost read"); + Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 2,000", + "[XP] Your XP cost for next 1 Quickness level is: 1,500"); + Check.True(TickUntil(hub, () => !raiser.Running), "nothing affordable above the reserve: the run ends"); + Check.Eq(FakeHost.ChatCommands.Count(x => x.StartsWith("/attr", StringComparison.Ordinal)), 2, "exactly two raises sent"); + string summary = FakeHost.Chat.LastOrDefault(x => x.Contains("Attribute raise")) ?? ""; + Check.True(summary.Contains("Coordination +1") && summary.Contains("Quickness +1") && summary.Contains("2.2K"), + $"the run reports what it raised and spent (got '{summary}')"); + + var sb = new System.Text.StringBuilder(); + raiser.AppendJson(sb); + string json = sb.ToString(); + Check.True(json.StartsWith("\"attr\":{\"off\":false", StringComparison.Ordinal), "the Progression snapshot carries the raiser"); + Check.True(json.Contains("\"key\":\"coo\"") && json.Contains("\"cost\":\"2.0K\""), "rows carry the last read costs"); + System.Text.Json.JsonDocument.Parse("{" + json + "}").Dispose(); // throws if the JSON is malformed + + // Panel commands: order, ticks, mode, reserve, a manual +10. + raiser.HandleRemote("attrmove", new[] { "attrmove", "qui", "up" }); + Check.Eq(c.AttrOrder[0], "qui", "attrmove up"); + raiser.HandleRemote("attron", new[] { "attron", "str", "on" }); + Check.True(c.AttrRaiseStats.Contains("str"), "attron"); + raiser.HandleRemote("attrmode", new[] { "attrmode", "2" }); + Check.Eq(c.AttrRaiseMode, 2, "attrmode"); + raiser.HandleRemote("attrkeep", new[] { "attrkeep", "1.5b" }); + Check.Eq(c.AttrKeepXp, 1_500_000_000L, "attrkeep takes k/m/b suffixes"); + raiser.HandleRemote("attrraise", new[] { "attrraise", "foc", "10" }); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr foc 10")), "a manual +10 sends /attr foc 10"); + } + + private static void Safety() + { + var settings = new IltSettings(); + var hub = NewHub("InfiniteLeaftide", settings, "attr-safety", out _); + var c = hub.State.Character; + var raiser = hub.Progression.Attributes; + c.AttrRaiseStats = new List { "coo", "qui" }; + FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 10_000; + + // A cost seen earlier (passively, here by a hand-typed /xp all) is not trusted by a run: + // only the costs in the run's own read count. + Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 100"); + raiser.Start(auto: false); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "run reads costs"); + Reply(hub, "[XP] Your XP cost for next 1 Quickness level is: 500"); // Coordination missing this time + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Any(x => x.StartsWith("/attr", StringComparison.Ordinal))), "a raise is sent"); + Check.Eq(FakeHost.ChatCommands.First(x => x.StartsWith("/attr", StringComparison.Ordinal)), "/attr qui 1", + "Coordination's older cost is not used when this read left it out"); + + // A reply about another stat (some other /attr sender) is not taken as our success. + Reply(hub, "[ATTR] Strength attribute raised by 1, costing 50!"); + Check.True(TickUntil(hub, () => !raiser.Running), "a reply about another stat ends the run"); + Check.Eq(FakeHost.ChatCommands.Count(x => x.StartsWith("/attr", StringComparison.Ordinal)), 1, "and nothing more is raised"); + Check.False(FakeHost.Chat.Any(x => x.Contains("Attribute raise")), "and no raise is reported"); + + // The world leaves Server Features mid-run: the next step stops. + FakeHost.ChatCommands.Clear(); + raiser.Start(auto: false); + Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "second run reads costs"); + settings.ServerNames = new List { "SomewhereElse" }; + Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 100"); + Check.True(TickUntil(hub, () => !raiser.Running), "the run stops once the world is off"); + Check.False(FakeHost.ChatCommands.Any(x => x.StartsWith("/attr", StringComparison.Ordinal)), "no raise after the gate closed"); + settings.ServerNames = new List(ServerFeatureGate.DefaultServerNames); + + // Another XP spender running: neither Raise now nor +N starts. + bool spending = true; + raiser.HoldOff = () => spending; + FakeHost.ChatCommands.Clear(); + raiser.Start(auto: false); + raiser.RaiseManual("coo", 1); + TickUntil(hub, () => false, 600); + Check.False(raiser.Running, "held off: Raise now doesn't start"); + Check.False(FakeHost.ChatCommands.Any(), "held off: nothing is sent"); + } + + private static void GatedOff() + { + var settings = new IltSettings(); + var hub = NewHub("Aelrynth", settings, "attr-gated", out _); + var raiser = hub.Progression.Attributes; + hub.State.Character.AttrRaiseStats = new List { "coo" }; + Check.NotNull(raiser.Blocker(), "a world not in the list: blocked"); + raiser.Start(auto: false); + TickUntil(hub, () => false, 600); + Check.False(FakeHost.ChatCommands.Any(), "nothing is sent off a feature world"); + + settings.ServerNames.Add("Aelrynth"); + Check.Null(raiser.Blocker(), "adding the world to the server list unblocks it"); + settings.ServerNames.Remove("Aelrynth"); + hub.State.ForceLeaftideFeatures = true; + Check.Null(raiser.Blocker(), "so does the character's override"); + } +} diff --git a/Tools/RynthILT.Tests/BankCommandTests.cs b/Tools/RynthILT.Tests/BankCommandTests.cs new file mode 100644 index 0000000..0ff8a0f --- /dev/null +++ b/Tools/RynthILT.Tests/BankCommandTests.cs @@ -0,0 +1,146 @@ +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// Banking tab (IltBankCommands): the deposit / withdraw commands match ACECustom's /bank handler +// (upstream 2026-10-11), and only the bank's own reply lines count as a deposit / withdraw result. +internal static class BankCommandTests +{ + public static void Register(Runner r) + { + r.Add("bank: deposit commands (everything, one kind, luminance tokens)", Deposits); + r.Add("bank: withdraw commands, trade notes by denomination and count", Withdrawals); + r.Add("bank: withdraw input is checked before anything is sent", WithdrawRefusals); + r.Add("bank: reply lines are recognised, balance and chat lines are not", Replies); + r.Add("bank: one item table matches ACECustom's handler (deposit / withdraw / transfer)", ItemTable); + r.Add("bank: transfer commands, trade notes by denomination, quoted names", Transfers); + r.Add("bank: transfer replies (notes' equivalent, bound prestige coins) are recognised", TransferReplies); + r.Add("bank: only the balance dump is backstop-eaten, and only just after a quiet refresh", LeakedDump); + } + + private static int TransferIndex(string code) => + System.Array.FindIndex(IltBankCommands.Transfers, t => t.Code == code); + + private static void ItemTable() + { + string Codes(System.Collections.Generic.IEnumerable codes) => string.Join(",", codes); + // ACECustom HandleBank (upstream 976606695): deposit everything; withdraw all but peas and + // luminance tokens; transfer all but those and the bound prestige coins. + Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Deposits, d => d.Args)), ",p,ps,l,lum,k,mk,e,we,pc,n", "deposits"); + Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Withdrawals, w => w.Code)), "p,l,k,mk,e,we,pc,n", "withdrawals"); + Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Transfers, t => t.Code)), "p,l,k,mk,e,we,n", "transfers"); + Check.Eq(TransferIndex("pc"), -1, "prestige coins are bound: never offered for transfer"); + Check.Eq(TransferIndex("ps"), -1, "pyreal peas: deposit only"); + Check.Eq(IltBanking.Currencies.Length, IltBankCommands.Transfers.Length, "the transfer form uses the table"); + Check.Eq(IltBanking.Currencies[0].Code, "p", "saved transfer index 0 is still pyreals"); + Check.Eq(IltBanking.Currencies[5].Code, "we", "saved transfer indexes 0-5 keep their currency"); + } + + private static void Transfers() + { + int mmd = System.Array.FindIndex(IltBankCommands.NoteDenominations, n => n.Code == "mmd"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 250_000, -1, "Bob", out _), "/bank t p 250000 Bob", "pyreals"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("mk"), 3, -1, " Bob ", out _), "/bank t mk 3 Bob", "name trimmed"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("l"), 10, -1, "Some Name", out _), "/bank t l 10 \"Some Name\"", + "a name with a space is quoted (the server reads one argument)"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), 4, mmd, "Bob", out _), "/bank t n mmd 4 Bob", "four 250K notes"); + Check.True(IltBankCommands.IsNoteTransfer(TransferIndex("n")), "notes transfer by denomination"); + Check.False(IltBankCommands.IsNoteTransfer(TransferIndex("p")), "pyreals don't"); + Check.Eq(IltBankCommands.NoteValue(mmd, 4), 1_000_000L, "4 x 250K"); + + Check.Eq(IltBankCommands.Transfer(-1, 10, -1, "Bob", out string e1), "", "no currency refused"); + Check.Eq(e1, "Pick a currency.", "why"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 0, -1, "Bob", out _), "", "zero refused"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 10, -1, " ", out string e2), "", "no recipient refused"); + Check.Eq(e2, "Enter a recipient.", "why"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 10, -1, "Bob\" x", out _), "", "a quote can't break out of the name"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), 4, 99, "Bob", out _), "", "bad denomination refused"); + Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), IltBankCommands.MaxNoteCount + 1, mmd, "Bob", out _), "", "too many notes refused"); + } + + private static void TransferReplies() + { + Check.True(IltBankCommands.IsTransferReply("Transferred 1,000,000 Pyreals to Bob"), "result"); + Check.True(IltBankCommands.IsTransferReply("(Equivalent to 4x MMD notes)"), "trade-note equivalent"); + Check.True(IltBankCommands.IsTransferReply("[BANK] Prestige Coins are bound to you and cannot be transferred."), "bound coins"); + Check.True(IltBankCommands.IsTransferReply("[Transfer] This command may only be run once every 5 seconds."), "throttled"); + Check.True(IltBankCommands.IsTransferReply("Invalid denomination. Use: i(100), v(500)"), "bad denomination"); + Check.False(IltBankCommands.IsTransferReply("[BANK] Pyreals: 1,000"), "a balance line is not"); + Check.False(IltBankCommands.IsTransferReply("Bob tells you, \"Transferred 5\""), "a tell is not"); + } + + private static int DepositIndex(string args) => + System.Array.FindIndex(IltBankCommands.Deposits, d => d.Args == args); + + private static int WithdrawIndex(string code) => + System.Array.FindIndex(IltBankCommands.Withdrawals, w => w.Code == code); + + private static void Deposits() + { + Check.Eq(IltBankCommands.Deposit(0), "/b d", "Everything is a plain deposit"); + Check.Eq(IltBankCommands.Deposit(DepositIndex("p")), "/b d p", "pyreals"); + Check.Eq(IltBankCommands.Deposit(DepositIndex("pc")), "/b d pc", "prestige coins"); + Check.Eq(IltBankCommands.Deposit(DepositIndex("lum")), "/b lum", "luminance tokens use /b lum"); + Check.Eq(IltBankCommands.Deposit(-1), "", "unknown index sends nothing"); + Check.Eq(IltBankCommands.Deposit(IltBankCommands.Deposits.Length), "", "past the end sends nothing"); + } + + private static void Withdrawals() + { + Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("p"), 1_500_000, 0, out _), "/b w p 1500000", "pyreals"); + Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("pc"), 3, 0, out _), "/b w pc 3", "prestige coins"); + int mmd = System.Array.FindIndex(IltBankCommands.NoteDenominations, n => n.Code == "mmd"); + Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), 5, mmd, out _), "/b w n mmd 5", "five 250K notes"); + } + + private static void WithdrawRefusals() + { + Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("p"), 0, 0, out string e1), "", "zero refused"); + Check.True(e1.Length > 0, "zero says why"); + Check.Eq(IltBankCommands.Withdraw(-1, 10, 0, out _), "", "no currency refused"); + Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), 10, 99, out _), "", "bad denomination refused"); + Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), IltBankCommands.MaxNoteCount + 1, 0, out string e2), "", + "more notes than the server allows refused"); + Check.True(e2.Contains("50,000"), "says the limit"); + } + + private static void Replies() + { + Check.True(IltBankCommands.IsActionReply("Deposited 12,345 pyreals"), "deposit"); + Check.True(IltBankCommands.IsActionReply("No pyreal peas found to deposit"), "nothing to deposit"); + Check.True(IltBankCommands.IsActionReply("Withdrew 2 prestige coins"), "withdraw"); + Check.True(IltBankCommands.IsActionReply("Starting Banked Lum: 5B (5,000,000,000)"), "token deposit start"); + Check.True(IltBankCommands.IsActionReply("[Withdraw] This command may only be run once every 5 seconds."), "throttled"); + Check.True(IltBankCommands.IsActionReply("You don't have enough luminance banked. Need 10 but only have 5."), "short"); + Check.False(IltBankCommands.IsActionReply("[BANK] Pyreals: 1,000"), "a balance line is not an action reply"); + Check.False(IltBankCommands.IsActionReply("No one is near."), "other 'No ...' lines are not"); + Check.False(IltBankCommands.IsActionReply("Bob tells you, \"Deposited 5 pyreals\""), "a tell is not"); + Check.False(IltBankCommands.IsActionReply(""), "empty"); + } + + /// + /// SilentKelpie's backstop for a quiet refresh whose reply leaked into chat, narrowed: the dump's + /// header and "Label: N" lines only, never errors, bound-coin notes or Transferred / Received lines, + /// and never a balance read outside the window after a quiet refresh (a macro's or plugin's /bank). + /// + private static void LeakedDump() + { + Check.True(IltBanking.IsBalanceDumpLine("[BANK] Your balances are:"), "header"); + Check.True(IltBanking.IsBalanceDumpLine("[BANK] Pyreals: 1,000"), "pyreals"); + Check.True(IltBanking.IsBalanceDumpLine("[BANK] Luminance: 2,500,000"), "luminance"); + Check.True(IltBanking.IsBalanceDumpLine("[BANK] Weakly Enlightened Coins: 3"), "weakly enlightened coins"); + Check.True(IltBanking.IsBalanceDumpLine("[BANK] Prestige Coins: 2 (bound to you and cannot be traded)"), "prestige coins"); + Check.False(IltBanking.IsBalanceDumpLine("[BANK] Too many parameters"), "an error"); + Check.False(IltBanking.IsBalanceDumpLine("[BANK] Prestige Coins are bound to you and cannot be transferred."), "the bound-coin note"); + Check.False(IltBanking.IsBalanceDumpLine("Transferred 1,000,000 Pyreals to Bob"), "a transfer reply"); + Check.False(IltBanking.IsBalanceDumpLine("Received 5 Pyreals from Bob"), "a received line"); + Check.False(IltBanking.IsBalanceDumpLine("Bob tells you, \"[BANK] Pyreals: 5\""), "a tell quoting a dump"); + + const long Win = IltBanking.QuietBalanceWindowMs; + Check.True(IltBanking.EatLeakedDump(true, 1_000, 1_000 + Win), "a dump line inside the window is eaten"); + Check.False(IltBanking.EatLeakedDump(true, 1_000 + Win + 1, 1_000 + Win), "after the window it shows (a macro's /bank)"); + Check.False(IltBanking.EatLeakedDump(true, 1_000, 0), "no quiet refresh out: it shows (typed /bank, loud refresh, other plugins)"); + Check.False(IltBanking.EatLeakedDump(false, 1_000, 1_000 + Win), "a non-dump [BANK] line inside the window still shows"); + } +} diff --git a/Tools/RynthILT.Tests/BankRosterTests.cs b/Tools/RynthILT.Tests/BankRosterTests.cs new file mode 100644 index 0000000..4f7976b --- /dev/null +++ b/Tools/RynthILT.Tests/BankRosterTests.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The Banking tab's every-character table (Hub/IltBankRoster.cs): SilentKelpie's Banking tab, in +// RynthInventory's window until 2026-10-21 (its tests came with it, adapted: the roster is RynthILT's own +// characters now, without Global Inventory's "not read yet" rows) and RynthILT's own tab since. +internal static class BankRosterTests +{ + public static void Register(Runner r) + { + r.Add("bank roster: you first, then by name; the totals add every read balance", Roster); + r.Add("bank roster: the Banking tab lists every character RynthILT has run on this server", FromSavedCharacters); + } + + private static IltBankState Bank(long py, long lum, long lk, long mk, long ec, long wec, long pc, DateTime updated) => new() + { + Pyreals = py, Luminance = lum, LegendaryKeys = lk, MythicalKeys = mk, + EnlightenedCoins = ec, WeaklyEnlightenedCoins = wec, PrestigeCoins = pc, LastUpdated = updated, + }; + + private static void Roster() + { + DateTime t = new(2026, 10, 3, 11, 0, 0, DateTimeKind.Local); + var rows = new List + { + new("Willow", false, Bank(1, 1, 0, 0, 0, 0, 0, t.AddDays(-1))), + new("Buffy", true, Bank(100, 2000, 1, 0, 3, 0, 0, t)), + new("Ghost", false, Bank(50, 0, 2, 1, 0, 4, 5, t.AddDays(-2))), + new("buffy", false, Bank(999, 999, 9, 9, 9, 9, 9, t.AddDays(-9))), // a stale saved copy of you + new("Never", false, Bank(7, 7, 7, 7, 7, 7, 7, DateTime.MinValue)), // never read: not in the totals + }; + IltBankRosterRow[] roster = IltBankRoster.Build(rows); + Check.Eq(string.Join(",", roster.Select(r => r.Name)), "Buffy,Ghost,Never,Willow", "you first, then by name; your saved copy doesn't replace you"); + Check.True(roster[0].Current && roster[0].Pyreals == 100, "your live balance"); + IltBankRosterRow total = IltBankRoster.Totals(roster); + Check.True(total.Name == "Total" && total.Pyreals == 151 && total.Luminance == 2001 && total.LegendaryKeys == 3 && total.MythicalKeys == 1 + && total.EnlightenedCoins == 3 && total.WeaklyEnlightenedCoins == 4 && total.PrestigeCoins == 5, + "totals add every balance read (a never-read one isn't counted)"); + Check.Eq(string.Join(",", IltBankRoster.Others(roster)), "Ghost,Never,Willow", "the transfer form's picker: your other characters"); + Check.Eq(IltBankRoster.Build(new List()).Length, 0, "nothing: an empty roster"); + Check.Eq(IltBankRoster.Age(DateTime.MinValue, t), "-", "never read"); + Check.Eq(IltBankRoster.Age(t.AddMinutes(-5), t), "5m ago", "minutes"); + Check.Eq(IltBankRoster.Age(t.AddHours(-3), t), "3h ago", "hours"); + Check.Eq(IltBankRoster.Age(t.AddDays(-2), t), "2d ago", "days"); + } + + private static void FromSavedCharacters() + { + FakeHost.Reset(); + FakeAiHub.Reset(); + FakeHost.WorldName = "InfiniteLeaftide"; + var host = FakeHost.Create(0x50000D41); + string world = Path.Combine(Program.TempRoot, "roster-world"); + if (Directory.Exists(world)) Directory.Delete(world, recursive: true); + // Two other characters RynthILT has run here (their saved hub.json), one that never banked. + foreach ((string name, long py, bool banked) in new[] { ("Ghost", 50L, true), ("Willow", 7L, true), ("Nobank", 0L, false) }) + { + string dir = Path.Combine(world, name); + Directory.CreateDirectory(dir); + var state = new IltHubState(); + state.Bank.Pyreals = py; + if (banked) state.Bank.LastUpdated = DateTime.Now.AddHours(-2); + File.WriteAllText(Path.Combine(dir, IltHubStore.StateFile), JsonSerializer.Serialize(state, IltHubJsonContext.Default.IltHubState)); + } + string me = Path.Combine(world, "Buffy"); + Directory.CreateDirectory(me); + var hub = new IltHubController(host, me, new IltSettings(), new RynthAiClient(host)); + hub.OnLoginComplete("Buffy", forceFromMigration: false); + hub.State.Bank.Pyreals = 100; + hub.State.Bank.LastUpdated = DateTime.Now; + + hub.Tick(); + Check.Eq(hub.Banking.Roster.Length, 0, "nothing is read while the table isn't on screen"); + hub.Banking.MarkRosterWatched(); + hub.Tick(); + IltBankRosterRow[] roster = hub.Banking.Roster; + Check.Eq(string.Join(",", roster.Select(r => r.Name)), "Buffy,Ghost,Willow", "you and the characters with a saved balance"); + Check.True(roster[0].Current && roster[0].Pyreals == 100 && roster[1].Pyreals == 50, "live and saved balances"); + Check.Eq(IltBankRoster.Totals(roster).Pyreals, 157L, "the total"); + } +} diff --git a/Tools/RynthILT.Tests/BountyReviewTests.cs b/Tools/RynthILT.Tests/BountyReviewTests.cs new file mode 100644 index 0000000..2b434c8 --- /dev/null +++ b/Tools/RynthILT.Tests/BountyReviewTests.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthILT.Bounty; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The RynthILT review of SilentKelpie's tracker (2026-10-09). Two promises, checked here on a +// fake clock: +// * rate: at most one "/bounty list" per MinRefreshSeconds (5 s floor, whatever asks: kills, +// award lines every kill, Refresh spam, opening and closing the window), and none while the +// window is closed; +// * hidden chat: only the reply to the tracker's own read is eaten. A /bounty the player types +// is shown, also when it overlaps a read of ours, and our own command coming back through the +// engine's chat bar dispatcher is not mistaken for the player's. +internal static class BountyReviewTests +{ + public static void Register(Runner r) + { + r.Add("review: awards on every kill never read more than once per MinRefreshSeconds", AwardsEveryKill); + r.Add("review: Refresh spam and window open/close keep the 5 s floor", RefreshSpamAndToggling); + r.Add("review: a long mixed session: every read 5 s apart and only while the window is open", MixedSession); + r.Add("review: a /bounty list the player types is shown and stands in for the next read", TypedListShown); + r.Add("review: a /bounty the player types during our read: the rest of that read is shown", TypedDuringCapture); + r.Add("review: our own /bounty list coming back through the chat bar is not the player's", OwnEcho); + r.Add("review: command matching and long lines", Matching); + } + + private const string Header = "Bounties:"; + private const string Line = " Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills."; + private const string Footer = "Bounty: type /bounty to see the bounties where you stand."; + + private sealed class Rig + { + public long Ms = 1_000_000; + public readonly List SentAt = new(); + public readonly List SentWhileOpen = new(); + public BountyTracker T = null!; + public bool Open; + private long _lastPollMs; + + public void Step(long ms) + { + for (long e = 0; e < ms; e += 250) + { + Ms += 250; + if (Open && Ms - _lastPollMs >= 1000) { T.BuildJson(); _lastPollMs = Ms; } + T.Tick(); + } + } + + /// The server answers our read at once (header, a line, footer). + public void Reply() + { + T.OnChat(Header); + T.OnChat(Line); + T.OnChat(Footer); + } + } + + private static Rig New(int minRefreshSeconds = 5) + { + var rig = new Rig(); + rig.T = new BountyTracker(cmd => + { + if (cmd != BountyTracker.ListCommand) return; + rig.SentAt.Add(rig.Ms); + rig.SentWhileOpen.Add(rig.T.WindowOpen); + }, _ => { }, _ => { }, string.Empty, () => rig.Ms); + rig.T.Command($"set minrefreshseconds {minRefreshSeconds}"); + return rig; + } + + private static long MinGap(List at) + { + long min = long.MaxValue; + for (int i = 1; i < at.Count; i++) min = Math.Min(min, at[i] - at[i - 1]); + return min; + } + + private static void AwardsEveryKill() + { + var rig = New(minRefreshSeconds: 10); + rig.Open = true; + // A 1-kill bounty with no cooldown: every kill prints an award, for two minutes. + for (int s = 0; s < 120; s++) + { + rig.T.OnKill(); + rig.T.OnChat("Bounty complete! +1 Ascension Coin gained."); + rig.T.OnChat("Next bounty requires 1 kill."); + rig.Step(1000); + if (rig.T.Reading) rig.Reply(); + } + Check.True(rig.SentAt.Count >= 2, $"it still reads ({rig.SentAt.Count} reads)"); + Check.True(rig.SentAt.Count <= 13, $"at most one read per 10 s over 120 s ({rig.SentAt.Count} reads)"); + Check.True(MinGap(rig.SentAt) >= 10_000, $"reads at least MinRefreshSeconds apart (min gap {MinGap(rig.SentAt)} ms)"); + } + + private static void RefreshSpamAndToggling() + { + var rig = New(minRefreshSeconds: 30); + rig.Open = true; + rig.Step(500); + rig.Reply(); + Check.Eq(rig.SentAt.Count, 1, "opening reads once"); + + // Refresh clicked every half second for 20 s: manual reads keep the 5 s floor. + for (int i = 0; i < 40; i++) + { + rig.T.Command("refresh"); + rig.Step(500); + if (rig.T.Reading) rig.Reply(); + } + Check.True(rig.SentAt.Count <= 5, $"20 s of Refresh spam: at most 4 more reads ({rig.SentAt.Count} in all)"); + Check.True(MinGap(rig.SentAt) >= 5_000, $"manual reads at least 5 s apart (min gap {MinGap(rig.SentAt)} ms)"); + + // Kills while closed, then the window toggled open and shut every 4 s for a minute. + int before = rig.SentAt.Count; + for (int i = 0; i < 15; i++) + { + rig.Open = false; + rig.T.OnKill(); + rig.Step(4000); + rig.Open = true; + rig.Step(1000); + if (rig.T.Reading) rig.Reply(); + } + Check.True(rig.SentAt.Count - before <= 3, $"open/close every 5 s for 75 s with MinRefreshSeconds 30: at most 3 reads ({rig.SentAt.Count - before})"); + Check.True(MinGap(rig.SentAt) >= 5_000, "and never two within 5 s"); + Check.True(rig.SentWhileOpen.All(o => o), "every read went out with the window open"); + } + + private static void MixedSession() + { + var rig = New(minRefreshSeconds: 5); + var rnd = new Random(20261009); + for (int s = 0; s < 1800; s++) // 30 minutes + { + if (s % 120 == 0) rig.Open = !rig.Open; + int roll = rnd.Next(100); + if (roll < 30) rig.T.OnKill(); + else if (roll < 35) rig.T.OnChat("Bounty complete! +1 Ascension Coin gained."); + else if (roll < 37) rig.T.Command("refresh"); + else if (roll < 38) rig.T.OnChat("Bounty unlocked: Ascension Coin - 1 kill required."); + rig.Step(1000); + if (rig.T.Reading && rnd.Next(4) != 0) rig.Reply(); // now and then the server says nothing + } + Check.True(rig.SentAt.Count > 10, $"reads happened ({rig.SentAt.Count})"); + Check.True(MinGap(rig.SentAt) >= 5_000, $"every read at least 5 s after the last (min gap {MinGap(rig.SentAt)} ms)"); + Check.True(rig.SentWhileOpen.All(o => o), "every read went out with the window open"); + } + + private static void TypedListShown() + { + var rig = New(minRefreshSeconds: 5); + rig.Open = true; + rig.Step(500); + rig.Reply(); + Check.Eq(rig.SentAt.Count, 1, "first read"); + rig.Step(10_000); + + // The player types /bounty list: the reply is shown (nothing eaten) and still applied. + rig.T.NoteTypedCommand("/bounty list"); + Check.True(rig.T.Reading, "the typed list is captured (shown)"); + Check.False(rig.T.OnChat(Header), "typed reply: the header stays in chat"); + Check.False(rig.T.OnChat(" Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills."), "typed reply: the lines stay in chat"); + Check.False(rig.T.OnChat(Footer), "typed reply: the footer stays in chat"); + Check.False(rig.T.Reading, "and the footer ends it"); + Check.Eq(rig.T.State.Entries.Count, 1, "the typed reply fills the list"); + + // It counts as the latest read: a kill right after waits the full interval. + rig.T.OnKill(); + rig.Step(4000); + Check.Eq(rig.SentAt.Count, 1, "no read of ours on top of the player's"); + rig.Step(2000); + Check.Eq(rig.SentAt.Count, 2, "the kill's read comes MinRefreshSeconds after the typed one"); + Check.True(rig.T.OnChat(Header) && rig.T.OnChat(Line) && rig.T.OnChat(Footer), "our own read is eaten again"); + + // "/bounty" (where you stand) output is never eaten. + rig.T.NoteTypedCommand("/bounty"); + Check.False(rig.T.OnChat("Bounty: 1 Ascension Coin - 0 of 1 kills."), "a /bounty line stays in chat"); + Check.False(rig.T.OnChat("Bounty: there is no bounty here."), "'no bounty here' stays in chat"); + } + + private static void TypedDuringCapture() + { + var rig = New(minRefreshSeconds: 5); + rig.Open = true; + rig.Step(500); + Check.Eq(rig.SentAt.Count, 1, "our read went out"); + rig.T.NoteTypedCommand(BountyTracker.ListCommand); // our own echo first (consumed) + Check.True(rig.T.OnChat(Header), "our reply's header is eaten"); + + // The player types /bounty list while our reply is still coming in. + rig.Step(250); + rig.T.NoteTypedCommand("/bounty list"); + Check.False(rig.T.OnChat(Line), "after the player asked, reward lines are shown"); + Check.False(rig.T.OnChat(Footer), "and so is the footer"); + Check.False(rig.T.OnChat(Header), "the player's own reply: header shown"); + Check.False(rig.T.OnChat(Line), "the player's own reply: line shown"); + Check.False(rig.T.OnChat(Footer), "the player's own reply: footer shown"); + Check.False(rig.T.OnChat("Bounty complete! +1 Ascension Coin gained."), "award lines are never eaten"); + + // On a server without /bounty, the player's typed /bounty during our read: the refusal shows. + var rig2 = New(); + rig2.Open = true; + rig2.Step(500); + rig2.T.NoteTypedCommand("/bounty"); + Check.False(rig2.T.OnChat("Unknown command: bounty"), "the refusal of the player's own /bounty stays in chat"); + } + + private static void OwnEcho() + { + var rig = New(minRefreshSeconds: 5); + rig.Open = true; + rig.Step(500); + Check.Eq(rig.SentAt.Count, 1, "our read went out"); + rig.Step(250); + rig.T.NoteTypedCommand("/bounty list"); // the engine's dispatcher passing our own line back + Check.True(rig.T.OnChat(Header), "our echo is recognised: the reply is still eaten"); + Check.True(rig.T.OnChat(Line), "reward lines eaten"); + Check.True(rig.T.OnChat(Footer), "footer eaten"); + + // An echo that comes too late is taken for the player's: that read is shown, never eaten wrongly. + rig.Step(10_000); + Check.Eq(rig.SentAt.Count, 1, "no new read yet (nothing asked)"); + rig.T.Command("refresh"); + rig.Step(500); + Check.Eq(rig.SentAt.Count, 2, "refresh reads"); + rig.Step(3000); + rig.T.NoteTypedCommand("/bounty list"); + Check.False(rig.T.OnChat(Header), "a late echo errs on the shown side"); + } + + private static void Matching() + { + Check.True(BountyTracker.IsBountyCommand("/bounty"), "/bounty"); + Check.True(BountyTracker.IsBountyCommand("/bounty list"), "/bounty list"); + Check.True(BountyTracker.IsBountyCommand("@Bounty all"), "@bounty all"); + Check.False(BountyTracker.IsBountyCommand("/bountyhunter"), "a longer command is not /bounty"); + Check.False(BountyTracker.IsBountyCommand("/b hello"), "chat"); + Check.True(BountyTracker.IsListCommand("/bounty list") && BountyTracker.IsListCommand("/BOUNTY ALL"), "list commands"); + Check.False(BountyTracker.IsListCommand("/bounty") || BountyTracker.IsListCommand("/bounty list now"), "not list commands"); + + var rig = New(); + rig.Open = true; + rig.Step(500); + string longLine = " Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills." + new string(' ', 600) + "x"; + Check.False(rig.T.OnChat(longLine), "a line over 512 characters is never eaten or parsed"); + } +} diff --git a/Tools/RynthILT.Tests/BountyTests.cs b/Tools/RynthILT.Tests/BountyTests.cs new file mode 100644 index 0000000..1c00dc9 --- /dev/null +++ b/Tools/RynthILT.Tests/BountyTests.cs @@ -0,0 +1,388 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.RynthILT.Bounty; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// ACECustom bounty tracker (2026-10-09). The server keeps the kill counts (BountyProgress is a +// server-only property), so the engine's Bounties window has RynthILT read "/bounty list" quietly +// and parse it. The line formats below are copied from ACECustom BountyManager (ShowAllBounties / +// ShowBounty / Award / NextBountyLine). The tracker runs on a fake clock; the engine's 1 s poll +// of RynthPluginGetBountiesJson is simulated by calling BuildJson. +internal static class BountyTests +{ + public static void Register(Runner r) + { + r.Add("bounty: /bounty list lines (counting, cooldown, QB, layers, commas)", ListLines); + r.Add("bounty: /bounty lines, waits and chat events", HereLinesAndEvents); + r.Add("bounty: a full read replaces the list, a partial one updates it", ApplyListRules); + r.Add("bounty: kills and awards stamp the row; an ended cooldown shows 0 kills; state survives a relog", ChangesAndCooldown); + r.Add("bounty: /bounty updates only the one reward it can mean", HereMatching); + r.Add("bounty: an open window reads the list quietly, kills and awards re-read it", WindowReadsAndKills); + r.Add("bounty: closed window sends nothing; unknown command stops reads; no reply times out", ClosedAndUnsupported); + r.Add("bounty: the window's JSON (options, QB filter, closest first) parses in the engine", BridgeJson); + } + + // ── Parsing ──────────────────────────────────────────────────────────────── + + private static void ListLines() + { + Check.True(BountyParse.TryParseListLine(" Lugian Mines: 1 Ascension Coin every 100 kills (at most every 5 min) - you: 34 of 100 kills.", out var a), + "counting line parses (leading indentation)"); + Check.Eq(a.Where, "Lugian Mines", "area"); + Check.Eq(a.Amount, 1L, "amount"); + Check.Eq(a.Item, "Ascension Coin", "item"); + Check.Eq(a.KillsRequired, 100, "kills per award"); + Check.Eq(a.CooldownSeconds, 300, "cooldown"); + Check.Eq(a.Status.Status, BountyStatus.Counting, "status"); + Check.Eq(a.Status.Kills, 34, "kills so far"); + + Check.True(BountyParse.TryParseListLine("All zones: 3 Pyreal Nugget every 1,000 kills (at most every 2 min 30 sec) - you: unlocks in 1 hr 15 sec, then 1,000 kills required.", out var b), + "cooldown line parses"); + Check.Eq(b.Where, "All zones", "all-zones area"); + Check.Eq(b.KillsRequired, 1000, "N0 kills"); + Check.Eq(b.CooldownSeconds, 150, "2 min 30 sec"); + Check.Eq(b.Status.Status, BountyStatus.Cooldown, "cooldown status"); + Check.Eq(b.Status.WaitSeconds, 3615, "1 hr 15 sec"); + Check.Eq(b.Status.KillsRequired, 1000, "kills after the cooldown"); + + Check.True(BountyParse.TryParseListLine("Valley of Death: 1,500 Trade Note - Large every 1 kill - you: needs 5,000 QB (you have 3,210).", out var c), + "QB line with no cooldown and a hyphenated item parses"); + Check.Eq(c.Amount, 1500L, "N0 amount"); + Check.Eq(c.Item, "Trade Note - Large", "item keeps its own ' - '"); + Check.Eq(c.KillsRequired, 1, "one kill"); + Check.Eq(c.CooldownSeconds, 0, "no cooldown"); + Check.Eq(c.Status.Status, BountyStatus.NeedsQb, "QB status"); + Check.Eq(c.Status.QbRequired, 5000L, "QB needed"); + Check.Eq(c.Status.QbHave, 3210L, "QB had"); + + Check.True(BountyParse.TryParseListLine("Halls of Metos: Lower (layer 2): 2 Ascension Coin every 50 kills - you: 0 of 50 kills.", out var d), + "an area with ': ' and a layer parses"); + Check.Eq(d.Where, "Halls of Metos: Lower (layer 2)", "area keeps its colon and layer"); + + Check.False(BountyParse.TryParseListLine("Bounties:", out _), "the header is not a reward"); + Check.False(BountyParse.TryParseListLine("Bounty: type /bounty to see the bounties where you stand.", out _), "the footer is not a reward"); + Check.False(BountyParse.TryParseListLine("Bob says, \"Lugian Mines: 1 coin every 100 kills\"", out _), "chat talk is not a reward"); + Check.True(BountyParse.IsListTerminator("Bounty: type /bounty to see the bounties where you stand."), "footer ends the reply"); + Check.True(BountyParse.IsListTerminator("Bounty: there are no bounties anywhere right now."), "'none anywhere' ends the reply"); + Check.True(BountyParse.IsNoBountiesAnywhere("Bounty: there are no bounties anywhere right now."), "'none anywhere' is recognised"); + Check.False(BountyParse.IsListTerminator("Bounty: there is no bounty here."), "/bounty's 'none here' is not the list's end"); + Check.True(BountyParse.IsUnknownCommand("Unknown command: bounty"), "ACE's unknown-command reply is recognised"); + Check.False(BountyParse.IsUnknownCommand("Unknown command: bank"), "another command's reply is not ours"); + } + + private static void HereLinesAndEvents() + { + Check.True(BountyParse.TryParseHereLine("Bounty: 1 Ascension Coin - 12 of 100 kills.", out var h1), "plain /bounty line"); + Check.Eq(h1.Scope, "", "no scope"); + Check.Eq(h1.Status.Kills, 12, "kills"); + Check.True(BountyParse.TryParseHereLine("Bounty (all zones): 3 Pyreal Nugget - unlocks in 45 sec, then 1 kill required.", out var h2), "all-zones /bounty line"); + Check.Eq(h2.Scope, "all zones", "all-zones scope"); + Check.Eq(h2.Status.WaitSeconds, 45, "45 sec"); + Check.True(BountyParse.TryParseHereLine("Bounty (Thaelaryn Island): 1 Ascension Coin - needs 500 QB (you have 20).", out var h3), "region /bounty line"); + Check.Eq(h3.Scope, "Thaelaryn Island", "region scope"); + Check.False(BountyParse.TryParseHereLine("Bounty: there is no bounty here.", out _), "'none here' is not a reward"); + Check.False(BountyParse.TryParseHereLine("Bounty: +1 Ascension Coin will follow in a moment.", out _), "held notice is not a reward"); + + Check.Eq(BountyParse.ParseWaitSeconds("5 min"), 300, "5 min"); + Check.Eq(BountyParse.ParseWaitSeconds("2 hr 3 min 4 sec"), 7384, "hr min sec"); + Check.Eq(BountyParse.ParseWaitSeconds("soon"), 0, "unparseable wait"); + + Check.True(BountyParse.TryParseEvent("Bounty unlocked: Ascension Coin - 100 kills required.", out var k1, out string item1, out int n1, out _) + && k1 == BountyEventKind.Unlocked && item1 == "Ascension Coin" && n1 == 100, "unlock event"); + Check.True(BountyParse.TryParseEvent("Bounty complete! +3 Pyreal Nuggets gained.", out var k2, out string item2, out _, out _) + && k2 == BountyEventKind.Complete && item2 == "Pyreal Nuggets", "award event"); + Check.True(BountyParse.TryParseEvent("Next bounty unlocks in 2 min 30 sec - 1 kill required.", out var k3, out _, out int n3, out int w3) + && k3 == BountyEventKind.NextCooldown && n3 == 1 && w3 == 150, "next-cooldown event"); + Check.True(BountyParse.TryParseEvent("Next bounty requires 1,000 kills.", out var k4, out _, out int n4, out _) + && k4 == BountyEventKind.NextReady && n4 == 1000, "next-ready event"); + Check.True(BountyParse.TryParseEvent("Bounty: Your inventory is full. +1 Ascension Coin gained (3 total). They're safe until you make room.", out var k5, out _, out _, out _) + && k5 == BountyEventKind.Held, "held event"); + Check.False(BountyParse.TryParseEvent("Bounty: there is no bounty here.", out _, out _, out _, out _), "'none here' is not an event"); + Check.False(BountyParse.TryParseEvent("Bounty: 1 Ascension Coin - 12 of 100 kills.", out _, out _, out _, out _), "a status line is not an event"); + Check.False(BountyParse.TryParseEvent("Bounty: type /bounty to see the bounties where you stand.", out _, out _, out _, out _), "the footer is not an event"); + } + + // ── Applying reads ───────────────────────────────────────────────────────── + + private static BountyListLine L(string line) + { + Check.True(BountyParse.TryParseListLine(line, out var l), "fixture parses: " + line); + return l; + } + + private static void ApplyListRules() + { + var t = New(out _, out _, out _); + var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc); + t.ApplyList(new[] + { + L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."), + L("All zones: 3 Pyreal Nugget every 50 kills - you: 0 of 50 kills."), + }, complete: true, noneAnywhere: false, t0); + Check.Eq(t.State.Entries.Count, 2, "full read: two rewards"); + Check.Eq(t.State.ListedUtc, t0, "read time stamped"); + + // A partial reply (no footer) only updates what it names; the other rows stay. + t.ApplyList(new[] { L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 11 of 100 kills.") }, + complete: false, noneAnywhere: false, t0.AddSeconds(5)); + Check.Eq(t.State.Entries.Count, 2, "partial read keeps the other row"); + Check.Eq(t.State.Entries[0].Kills, 11, "partial read updates the named row in place"); + + // A full read drops areas that are gone and keeps the server's order. + t.ApplyList(new[] + { + L("Thaelaryn Island: 1 Ascension Coin every 20 kills - you: 4 of 20 kills."), + L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 12 of 100 kills."), + }, complete: true, noneAnywhere: false, t0.AddSeconds(10)); + Check.Eq(string.Join(",", t.State.Entries.Select(e => e.Where)), "Thaelaryn Island,Lugian Mines", "server order, removed area gone"); + + t.ApplyList(Array.Empty(), complete: true, noneAnywhere: true, t0.AddSeconds(20)); + Check.Eq(t.State.Entries.Count, 0, "'none anywhere' empties the list"); + Check.True(t.State.NoneAnywhere, "and says so"); + } + + private static void ChangesAndCooldown() + { + string file = Path.Combine(Program.TempRoot, "bounty-changes", BountyTracker.FileName); + var t = New(out _, out _, out _, file); + var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc); + const string Head = "Lugian Mines: 1 Ascension Coin every 3 kills (at most every 5 min) - you: "; + t.ApplyList(new[] { L(Head + "1 of 3 kills.") }, true, false, t0); + Check.Eq(t.State.Entries[0].ChangedUtc, default(DateTime), "first sighting is not a change"); + + t.ApplyList(new[] { L(Head + "2 of 3 kills.") }, true, false, t0.AddSeconds(10)); + Check.Eq(t.State.Entries[0].ChangedUtc, t0.AddSeconds(10), "a new kill stamps the row"); + + t.ApplyList(new[] { L(Head + "unlocks in 5 min, then 3 kills required.") }, true, false, t0.AddSeconds(20)); + var e = t.State.Entries[0]; + Check.Eq(e.ChangedUtc, t0.AddSeconds(20), "the award stamps the row"); + Check.Eq(e.UnlockAtUtc, t0.AddSeconds(320), "unlock time = read time + wait"); + Check.Eq(BountyTracker.Effective(e, t0.AddSeconds(100)).Status, BountyStatus.Cooldown, "still cooling down"); + var after = BountyTracker.Effective(e, t0.AddSeconds(321)); + Check.True(after.Status == BountyStatus.Counting && after.Kills == 0, "after the cooldown: 0 of N kills"); + Check.True(BountyTracker.Describe(e, t0.AddSeconds(100)).Contains("unlocks in 3 min 40 sec"), "chat text counts the cooldown down"); + + // The state survives a relog (the window fills right after login). + t.Command("set hideqblocked 1"); + t.Save(); + var loaded = New(out _, out _, out _, file); + Check.Eq(loaded.State.Entries.Count, 1, "entries saved per character"); + Check.Eq(loaded.State.Entries[0].UnlockAtUtc, t0.AddSeconds(320), "unlock time saved"); + Check.True(loaded.State.HideQbLocked, "options saved"); + } + + private static void HereMatching() + { + var t = New(out _, out _, out _); + var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc); + t.ApplyList(new[] + { + L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."), + L("Halls of Metos: 1 Ascension Coin every 100 kills - you: 50 of 100 kills."), + L("Thaelaryn Island: 2 Ascension Coin every 20 kills - you: 4 of 20 kills."), + L("All zones: 1 Ascension Coin every 100 kills - you: 0 of 100 kills."), + }, true, false, t0); + + Check.True(BountyParse.TryParseHereLine("Bounty (Thaelaryn Island): 2 Ascension Coin - 5 of 20 kills.", out var region), "fixture"); + Check.True(t.ApplyHere(region, t0.AddSeconds(5)), "a region line names its area"); + Check.Eq(t.State.Entries[2].Kills, 5, "region row updated"); + + Check.True(BountyParse.TryParseHereLine("Bounty (all zones): 1 Ascension Coin - 1 of 100 kills.", out var zones), "fixture"); + Check.True(t.ApplyHere(zones, t0.AddSeconds(6)), "an all-zones line names its area"); + Check.Eq(t.State.Entries[3].Kills, 1, "all-zones row updated"); + + Check.True(BountyParse.TryParseHereLine("Bounty: 1 Ascension Coin - 11 of 100 kills.", out var plain), "fixture"); + Check.False(t.ApplyHere(plain, t0.AddSeconds(7)), "two dungeons pay the same reward: left alone"); + Check.Eq(t.State.Entries[0].Kills, 10, "first dungeon untouched"); + Check.Eq(t.State.Entries[1].Kills, 50, "second dungeon untouched"); + } + + // ── The read loop ────────────────────────────────────────────────────────── + + private const string ListReplyCounting = " Lugian Mines: 1 Ascension Coin every 100 kills - you: 34 of 100 kills."; + private const string Footer = "Bounty: type /bounty to see the bounties where you stand."; + + private static void WindowReadsAndKills() + { + var t = New(out var clock, out var sent, out _); + t.Command("set minrefreshseconds 5"); + Run(t, clock, 500, windowOpen: true); + Check.Eq(Reads(sent), 1, "opening the window reads /bounty list"); + Check.True(t.Reading, "a read is in progress"); + + Check.True(t.OnChat("Bounties:"), "the header is hidden from chat"); + Check.True(t.OnChat(ListReplyCounting), "reward lines are hidden from chat"); + Check.True(t.OnChat(Footer), "the footer is hidden and ends the read"); + Check.False(t.Reading, "the read is over"); + Check.Eq(t.State.Entries.Count, 1, "the read fills the list"); + Check.Eq(t.State.Entries[0].Kills, 34, "with the player's kills"); + + // A kill re-reads after the debounce, but not sooner than MinRefreshSeconds after the last read. + t.OnKill(); + Run(t, clock, 3000, windowOpen: true); + Check.Eq(Reads(sent), 1, "no re-read inside MinRefreshSeconds"); + Run(t, clock, 3000, windowOpen: true); + Check.Eq(Reads(sent), 2, "a kill re-reads the list"); + t.OnChat("Bounties:"); + t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills - you: 35 of 100 kills."); + t.OnChat(Footer); + Check.Eq(t.State.Entries[0].Kills, 35, "the kill shows up"); + Check.True(t.State.Entries[0].ChangedUtc != default, "and the row is highlighted"); + + // Award lines are shown to the player and also trigger a read, once MinRefreshSeconds + // have passed since the last one (review 2026-10-09: awards used to skip the interval). + Check.False(t.OnChat("Bounty complete! +1 Ascension Coin gained."), "award lines stay in chat"); + Check.Eq(t.State.LastEvent, "Bounty complete! +1 Ascension Coin gained.", "the window shows the last event"); + Run(t, clock, 2000, windowOpen: true); + Check.Eq(Reads(sent), 2, "the award's re-read waits for MinRefreshSeconds"); + Run(t, clock, 3000, windowOpen: true); + Check.Eq(Reads(sent), 3, "an award re-reads the list"); + + // A reply whose footer never comes ends after a quiet moment, as a partial update. + t.OnChat("Bounties:"); + t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills (at most every 5 min) - you: unlocks in 5 min, then 100 kills required."); + Run(t, clock, 2000, windowOpen: true); + Check.False(t.Reading, "a reply without its footer still ends"); + Check.Eq(t.State.Entries[0].Status, (int)BountyStatus.Cooldown, "and is applied"); + + // Lines the player asks for themselves are not hidden but still update the list. + Check.False(t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills - you: 0 of 100 kills."), "a typed /bounty list line stays in chat"); + Check.Eq(t.State.Entries[0].Status, (int)BountyStatus.Counting, "and updates the row"); + + // Closing the window (the engine stops polling; 3 s grace) stops the reads. + Run(t, clock, 5000, windowOpen: false); + int before = Reads(sent); + t.OnKill(); + Run(t, clock, 20000, windowOpen: false); + Check.Eq(Reads(sent), before, "no reads once the window is closed"); + } + + private static void ClosedAndUnsupported() + { + var t = New(out var clock, out var sent, out var chat); + t.Command("set minrefreshseconds 5"); + t.OnKill(); + Run(t, clock, 10000, windowOpen: false); + Check.Eq(Reads(sent), 0, "closed window: kills send nothing"); + + Run(t, clock, 500, windowOpen: true); + Check.Eq(Reads(sent), 1, "opening the window reads the list"); + Check.True(t.OnChat("Unknown command: bounty"), "the unknown-command reply to our read is hidden"); + Check.True(t.Unsupported, "'Unknown command: bounty' marks the server unsupported"); + + t.OnKill(); + Run(t, clock, 10 * 60_000, windowOpen: true); + Check.Eq(Reads(sent), 1, "no automatic reads on an unsupported server, periodic included"); + + t.HandleChatCommand(new[] { "/ilt", "bountys", "refresh" }); + Check.False(t.Unsupported, "a manual refresh tries again"); + Run(t, clock, 500, windowOpen: true); + Check.Eq(Reads(sent), 2, "and reads the list"); + Check.True(chat.Any(c => c.Contains("Reading /bounty list")), "the command answers in chat"); + + Run(t, clock, 11000, windowOpen: true); + Check.False(t.Reading, "no reply: the read is abandoned"); + Check.True(t.BuildJson().Contains("no reply to /bounty list"), "and the window says so"); + + // With the window closed a manual refresh sends nothing (review 2026-10-09: reads only + // while the window is open); the next open reads. + Run(t, clock, 5000, windowOpen: false); + Check.True(t.Command("refresh").Contains("window is open"), "a closed-window refresh says why it waits"); + Check.Eq(Reads(sent), 2, "a closed-window refresh sends nothing"); + Run(t, clock, 500, windowOpen: true); + Check.Eq(Reads(sent), 3, "the next open reads"); + + chat.Clear(); + t.HandleChatCommand(new[] { "/ilt", "bounty" }); + Check.True(chat.Any(c => c.Contains("/rc bounties")), "'/ilt bounty' points at the window"); + } + + private static void BridgeJson() + { + var t = New(out _, out _, out _); + var now = DateTime.UtcNow; + t.ApplyList(new[] + { + L("Valley of Death: 1,500 Trade Note - Large every 1 kill - you: needs 5,000 QB (you have 3,210)."), + L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."), + L("Thaelaryn Island: 2 Ascension Coin every 20 kills (at most every 5 min) - you: unlocks in 2 min, then 20 kills required."), + L("Halls of Metos: 1 Ascension Coin every 10 kills - you: 9 of 10 kills."), + }, true, false, now); + + Check.Eq(t.Command("set minrefreshseconds 1"), "", "option accepted"); + Check.Eq(t.State.MinRefreshSeconds, BountyTracker.MinRefreshFloorSeconds, "MinRefreshSeconds is clamped to the floor"); + t.Command("set periodicminutes 999"); + Check.Eq(t.State.PeriodicRefreshMinutes, BountyTracker.PeriodicCeilingMinutes, "PeriodicRefreshMinutes is clamped"); + Check.True(t.Command("set nonsense 1").Contains("unknown"), "unknown option is reported"); + + using (var doc = JsonDocument.Parse(t.BuildJson())) + { + var root = doc.RootElement; + Check.Eq(root.GetProperty("rows").GetArrayLength(), 4, "all rows by default"); + Check.Eq(root.GetProperty("rows")[0].GetProperty("where").GetString(), "Valley of Death", "server order by default"); + Check.Eq(root.GetProperty("minRefreshSeconds").GetInt32(), 5, "camelCase option names"); + } + + t.Command("set hideqblocked 1"); + t.Command("set sortbyprogress on"); + string json = t.BuildJson(); + using (var doc = JsonDocument.Parse(json)) + { + var rows = doc.RootElement.GetProperty("rows"); + Check.Eq(rows.GetArrayLength(), 3, "QB-locked row hidden"); + Check.Eq(doc.RootElement.GetProperty("hiddenCount").GetInt32(), 1, "and counted"); + Check.Eq(rows[0].GetProperty("where").GetString(), "Halls of Metos", "closest first: 9 of 10"); + Check.Eq(rows[2].GetProperty("where").GetString(), "Thaelaryn Island", "cooldowns after counting rows"); + } + +#if ENGINE_BOUNTIES + var snap = RynthCore.Engine.UI.Data.BountiesSnapshot.Parse(json); + Check.NotNull(snap, "the engine parses the plugin's JSON"); + Check.True(snap!.HideQbLocked && snap.SortByProgress, "engine sees the options"); + Check.Eq(snap.MinRefreshSeconds, 5, "engine sees MinRefreshSeconds"); + Check.Eq(snap.HiddenCount, 1, "engine sees the hidden count"); + Check.Eq(snap.Rows.Count, 3, "engine sees the rows"); + var cd = snap.Rows.Single(r => r.Where == "Thaelaryn Island"); + Check.Eq(cd.Status, (int)RynthCore.Engine.UI.Data.BountyRowStatus.Cooldown, "engine status enum matches the plugin's"); + Check.True(cd.UnlockInSec > 100 && cd.UnlockInSec <= 120, $"cooldown seconds left ({cd.UnlockInSec})"); + Check.Eq(cd.CooldownSeconds, 300, "cooldown length"); + var halls = snap.Rows[0]; + Check.True(halls.Kills == 9 && halls.KillsRequired == 10 && halls.Amount == 1 && halls.Item == "Ascension Coin", "row fields"); +#endif + } + + // ── Helpers ──────────────────────────────────────────────────────────────── + + private sealed class Clock { public long Ms = 1_000_000; } + + private static BountyTracker New(out Clock clock, out List sent, out List chat, string file = "") + { + var c = new Clock(); + var s = new List(); + var ch = new List(); + if (file.Length > 0) Directory.CreateDirectory(Path.GetDirectoryName(file)!); + var t = new BountyTracker(s.Add, ch.Add, _ => { }, file, () => c.Ms); + clock = c; + sent = s; + chat = ch; + return t; + } + + private static int Reads(List sent) => sent.Count(x => x == BountyTracker.ListCommand); + + /// Advances the clock in 250 ms steps, ticking; with the window open the engine polls every second. + private static void Run(BountyTracker t, Clock clock, long ms, bool windowOpen) + { + for (long elapsed = 0; elapsed < ms; elapsed += 250) + { + clock.Ms += 250; + if (windowOpen && elapsed % 1000 == 0) t.BuildJson(); + t.Tick(); + } + } +} diff --git a/Tools/RynthILT.Tests/BreedingTests.cs b/Tools/RynthILT.Tests/BreedingTests.cs new file mode 100644 index 0000000..5501050 --- /dev/null +++ b/Tools/RynthILT.Tests/BreedingTests.cs @@ -0,0 +1,379 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.RynthILT; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The pet breeding tracker (IltBreedingRules / IltBreedingEssence / IltBreedingSupplies / IltPetBreeding): +// the server's rules and where each value came from, the parsers for ACECustom's appraisal block, +// chat and "@breed-debug" (formats copied from PetDevice_Breeding.cs / PetDevice_Maturity.cs), each +// breeding gate, the pair planner's odds, the supply refusals, and the JSON RynthOracle reads. +internal static class BreedingTests +{ + public static void Register(Runner r) + { + r.Add("breeding: tier table has one WCID per tier in every family, no repeats", TierTable); + r.Add("breeding: rules come from the server, else the ILT profile, else ACE", RuleSources); + r.Add("breeding: stat mutation odds follow ACE's decay, floor and incense cap", MutationOdds); + r.Add("breeding: appraisal text gives the stud's charges, refill window and growth", AppraisalParse); + r.Add("breeding: chat lines give charges, the guardian, growth stages and events", ChatParse); + r.Add("breeding: @breed-debug reply is captured whole or line by line and parsed", DebugParse); + r.Add("breeding: each gate (charges, rest, growth, neutered, shiny, bond, tier, ID)", Gates); + r.Add("breeding: pair planner blocks wrong sexes and ranges the inherited mutations", Planner); + r.Add("breeding: supplies are refused where the server would refuse them", Supplies); + r.Add("breeding: reader JSON round-trips through RynthOracle's view", ReaderJson); + r.Add("breeding: saved state survives the hub.json source-generated serializer", StateJson); + r.Add("breeding: RynthILT.Data v2 keeps v1 readers working", DataApiVersion); + } + + private static IltBreedingRules Rules() => new(new IltBreedingState()); + + /// A healthy adult essence's facts (tier 150, bond 120, appraised). + private static BreedEssenceFacts Facts(int id, bool male, uint wcid = 48946) => new() + { + Id = id, + Name = (male ? "Stud " : "Dam ") + id, + Wcid = wcid, + HasId = true, + Bond = 120, + MaleOverride = male, + }; + + private static void TierTable() + { + var seen = new HashSet(); + foreach (uint[] row in IltBreedingEssence.Families) + { + Check.Eq(row.Length, IltBreedingEssence.Tiers.Length, "row " + row[0]); + foreach (uint w in row) Check.True(seen.Add(w), "WCID " + w + " appears once"); + } + Check.Eq(IltBreedingEssence.Families.Length, 36, "36 combat pet families"); + Check.Eq(IltBreedingEssence.TierOf(48942), 50, "first fire skeleton is tier 50"); + Check.Eq(IltBreedingEssence.TierOf(49212), 200, "an out-of-run WCID keeps its slot (tier 200)"); + Check.Eq(IltBreedingEssence.TierOf(787801072), 300, "the last tier-300 essence"); + Check.Eq(IltBreedingEssence.TierOf(12345, 125), 125, "unknown WCID: a tier-valued level requirement"); + Check.Eq(IltBreedingEssence.TierOf(12345, 126), 0, "unknown WCID, odd level: unknown tier"); + Check.True(IltBreedingEssence.IsCombatEssence(49551), "range end is included"); + } + + private static void RuleSources() + { + IltBreedingRules r = Rules(); + Check.Eq(r.Value(IltBreedingRules.MinTier).Source, BreedRuleSource.AceDefault, "min tier: ACE default"); + Check.Eq(r.GetInt(IltBreedingRules.MinTier), 100, "min tier 100"); + Check.Eq(r.Value(IltBreedingRules.MutationDecay).Source, BreedRuleSource.IltProfile, "decay: ILT profile"); + Check.Near(r.Get(IltBreedingRules.MutationDecay), 0.1, 1e-9, "ILT decay 0.1"); + Check.Near(r.Get(IltBreedingRules.GuardianEnabled), 1, 1e-9, "ILT runs the mating guardian"); + + DateTime t = new(2026, 10, 15, 12, 0, 0, DateTimeKind.Utc); + Check.True(r.Learn(IltBreedingRules.MaleCharges, 12, t), "a new value is a change"); + Check.False(r.Learn(IltBreedingRules.MaleCharges, 12, t), "the same value again isn't"); + Check.Eq(r.Value(IltBreedingRules.MaleCharges).Source, BreedRuleSource.Server, "learned: seen on server"); + Check.Eq(r.GetInt(IltBreedingRules.MaleCharges), 12, "learned value wins"); + Check.False(r.Learn("not_a_rule", 1, t), "unknown keys are ignored"); + Check.Eq(r.RoomText(), "landblock 0x0106 variant 2", "Seedy Motel room"); + + IltBreedingRules frozen = r.Frozen(); + r.Learn(IltBreedingRules.MaleCharges, 8, t); + Check.Eq(frozen.GetInt(IltBreedingRules.MaleCharges), 12, "a frozen copy doesn't follow later learning"); + + Check.Eq(r.StageName(2), "Whelp", "default stage names"); + Check.True(r.LearnStageName(2, "Pup"), "a server's own stage name"); + Check.Eq(r.StageName(2), "Pup", "seen name wins"); + for (int i = 0; i < IltBreedingRules.MaxEvents + 5; i++) r.AddEvent("x", "e" + i, t); + Check.Eq(r.State.Log.Count, IltBreedingRules.MaxEvents, "event log is capped"); + Check.Eq(r.State.Log[^1].Text, "e" + (IltBreedingRules.MaxEvents + 4), "newest kept last"); + } + + private static void MutationOdds() + { + IltBreedingRules r = Rules(); + Check.Near(r.StatMutationChance(0, 0), 0.05, 1e-9, "base 5%"); + Check.Near(r.StatMutationChance(4, 0), 0.05 / 1.4, 1e-9, "decay 0.1 x 4 mutations"); + Check.Near(r.StatMutationChance(0, 0.10), 0.15, 1e-9, "exquisite incense adds 10%"); + Check.Near(r.CombinedIncense(0.4, 0.3), 0.5, 1e-9, "both parents' incense capped at 50%"); + r.Learn(IltBreedingRules.MutationDecay, 10, DateTime.UtcNow); + Check.Near(r.StatMutationChance(4, 0), 0.02, 1e-9, "never below the 2% floor"); + } + + private static void AppraisalParse() + { + double now = 1_800_000_000; + double lastRefill = now - (20 * 3600 + 50 * 60); + string desc = "A fire skeleton essence.\nSex: Male (9/12 breeding charges today) - refills in 3h 10m\nBond: Unbound (imprints on first summon)"; + var seen = IltBreedingRules.FromAppraisal(desc, lastRefill, now); + Check.True(seen.Contains((IltBreedingRules.MaleCharges, 12)), "max charges from the stud line"); + Check.True(seen.Contains((IltBreedingRules.MaleRefillHours, 24)), "refill window from the countdown"); + + string growth = "Sex: Female (ready to breed)\nGrowth: Whelp 2/5 - 75 kills to Juvenile, 195 to Adult"; + Check.True(IltBreedingRules.FromAppraisal(growth, 0, now).Contains((IltBreedingRules.MaturityStages, 5)), "stage count"); + Check.True(IltBreedingRules.TryParseGrowth(growth, out string name, out int stage, out int stages, out int toNext, out string next, out int toAdult), "growth line"); + Check.Eq(name, "Whelp", "stage name"); + Check.Eq(stage, 2, "stage"); + Check.Eq(stages, 5, "stages"); + Check.Eq(toNext, 75, "to next"); + Check.Eq(next, "Juvenile", "next stage"); + Check.Eq(toAdult, 195, "to adult"); + + Check.True(IltBreedingRules.TryParseGrowth("Growth: Young Adult 5/5 - 60 kills to Adult", out name, out stage, out _, out toNext, out next, out toAdult), "last stage"); + Check.Eq(name, "Young Adult", "two-word stage name"); + Check.Eq(next, "Adult", "last stage leads to Adult"); + Check.Eq(toAdult, 60, "last stage: to adult = to next"); + Check.False(IltBreedingRules.TryParseGrowth("Growth: Adult", out _, out _, out _, out _, out _, out _), "an adult has no countdown"); + } + + private static void ChatParse() + { + var a = IltBreedingRules.FromChat("[Breeding] Fire Skeleton Essence spent a breeding charge: 7/12 left today."); + Check.True(a.Contains((IltBreedingRules.MaleCharges, 12)), "charge line gives the max"); + var g = IltBreedingRules.FromChat("The union stirs something... Mating Spirit rises before A and B! Only the two parents can harm it. They have 120s to bring it down together."); + Check.True(g.Contains((IltBreedingRules.GuardianEnabled, 1)), "guardian on"); + Check.True(g.Contains((IltBreedingRules.GuardianSeconds, 120)), "guardian timer"); + var d = IltBreedingRules.FromChat("[Breeding] Your pet performs the courtship dance, waiting for a partner... (Your partner must have their pet summoned in the same room and *dance* within 5 seconds)."); + Check.True(d.Contains((IltBreedingRules.DanceWindow, 5)), "dance window"); + Check.Eq(IltBreedingRules.FromChat("You say, \"hello\"").Count, 0, "ordinary chat says nothing"); + + Check.True(IltBreedingRules.TryParseGrownInto("Pup has grown into a Whelp! Its body swells with new strength. (2/5)", out int stage, out string name), "growth line"); + Check.Eq(stage, 2, "stage number"); + Check.Eq(name, "Whelp", "stage name"); + + Check.Eq(IltPetBreeding.EventKind("The mating ritual has begun between A and B..."), "ritual", "ritual"); + Check.Eq(IltPetBreeding.EventKind("Congratulations! A baby pet has been born: Pup! Placed in Bob's inventory."), "birth", "birth"); + Check.Eq(IltPetBreeding.EventKind("A baby pet has been born: Pup! Bob's packs are full, so the baby has been tucked away"), "birth", "deferred birth"); + Check.Eq(IltPetBreeding.EventKind("Pup has reached adulthood! It stands at its full size"), "adult", "adulthood"); + Check.Eq(IltPetBreeding.EventKind("Pup has imprinted on you. It is now bound to this character"), "imprint", "imprint"); + Check.Eq(IltPetBreeding.EventKind("[Breeding] The spectral guardian dissolves back into the ether..."), "guardian", "guardian lost"); + Check.Eq(IltPetBreeding.EventKind("Bob tells you, \"breed?\""), null, "not a breeding line"); + } + + private const string DebugReply = + "=== PET BREEDING DIAGNOSTICS ===\n" + + "Breeding System Enabled: True\n" + + "Your Location: Landblock=0x0106, Cell=0x01060186, Variant=2\n" + + "Allowed Target: whole landblock 0x106, Variant=2 => Location Match: VALID (Room OK)\n" + + "Your Active Pet: Fire Skeleton (WCID 48900) | Device: Fire Skeleton Essence\n" + + " Sex: Male (9/10 charges)\n" + + "Eligible breeding partners nearby: 1\n" + + "================================\n"; + + private static void DebugParse() + { + Check.True(IltBreedingRules.IsDebugLine(DebugReply.TrimEnd('\n')), "whole message is a reply line"); + Check.True(IltBreedingRules.IsDebugEnd(DebugReply.TrimEnd('\n')), "whole message ends the reply"); + Check.True(IltBreedingRules.IsDebugEnd("================================"), "rule line alone ends it"); + Check.False(IltBreedingRules.IsDebugEnd("=== PET BREEDING DIAGNOSTICS ==="), "the header doesn't"); + Check.False(IltBreedingRules.IsDebugLine("Bob says, \"hi\""), "chat isn't"); + + BreedDebugInfo whole = IltBreedingRules.ParseDebug(new[] { DebugReply }); + BreedDebugInfo split = IltBreedingRules.ParseDebug(DebugReply.Split('\n')); + foreach (BreedDebugInfo d in new[] { whole, split }) + { + Check.Eq(d.Enabled, (bool?)true, "enabled"); + Check.Eq(d.AllowedLandblock, 0x106u, "landblock"); + Check.Eq(d.AllowedVariant, 2, "variant"); + Check.Eq(d.AllowedKind, "whole landblock", "kind"); + Check.Eq(d.LocationOk, (bool?)true, "in the room"); + Check.Eq(d.Partners, 1, "partners"); + Check.Eq(d.PetSex, "Male (9/10 charges)", "pet sex line"); + } + var rules = IltBreedingRules.FromChat(DebugReply); + Check.True(rules.Contains((IltBreedingRules.Landblock, 0x106)), "room landblock learned"); + Check.True(rules.Contains((IltBreedingRules.Variant, 2)), "room variant learned"); + } + + private static void Gates() + { + IltBreedingRules r = Rules(); + double now = 1_800_000_000; + + BreedEssence full = IltBreedingEssence.Evaluate(Facts(1, true), r, now); + Check.True(full.Ready, "a stud that never bred is full"); + Check.Eq(full.Charges, 10, "10 charges"); + Check.Eq(full.Tier, 125, "48946 is tier 125"); + + var spent = Facts(2, true); + spent.MaleCharges = 0; + spent.MaleRefreshUnix = now - 2 * 3600; + BreedEssence noCharge = IltBreedingEssence.Evaluate(spent, r, now); + Check.Eq(noCharge.Gate, BreedGate.NoCharges, "no charges"); + Check.Near(noCharge.ReadyAtUnix, now + 22 * 3600, 1, "refills 24h after the last refill"); + + spent.MaleRefreshUnix = now - 25 * 3600; + Check.True(IltBreedingEssence.Evaluate(spent, r, now).Ready, "refilled once the window passed (the server refills on read)"); + + var dam = Facts(3, false); + dam.NextBreedUnix = now + 3600 + 300; + BreedEssence resting = IltBreedingEssence.Evaluate(dam, r, now); + Check.Eq(resting.Gate, BreedGate.Resting, "resting dam"); + Check.Eq(resting.Status, "Rest 1h 05m", "rest countdown"); + + var neut = Facts(4, false); + neut.Neutered = true; + Check.Eq(IltBreedingEssence.Evaluate(neut, r, now).Gate, BreedGate.Neutered, "neutered"); + + var shiny = Facts(5, true); + shiny.LongDesc = "Sex: Male (shiny - cannot breed)"; + Check.Eq(IltBreedingEssence.Evaluate(shiny, r, now).Gate, BreedGate.Shiny, "shiny"); + + var baby = Facts(6, false); + baby.JuvenileFlag = true; + baby.MaturityKills = 130; + BreedEssence growing = IltBreedingEssence.Evaluate(baby, r, now); + Check.Eq(growing.Gate, BreedGate.Growing, "juvenile"); + Check.Eq(growing.Stage, 3, "130 kills of 300 over 5 stages: stage 3"); + Check.Eq(growing.StageName, "Juvenile", "stage 3 name"); + Check.Eq(growing.KillsToNext, 50, "50 kills to stage 4"); + + var weak = Facts(7, true); + weak.Bond = 40; + Check.Eq(IltBreedingEssence.Evaluate(weak, r, now).Gate, BreedGate.LowBond, "bond under 100"); + + BreedEssence low = IltBreedingEssence.Evaluate(Facts(8, true, 48944), r, now); + Check.Eq(low.Gate, BreedGate.LowTier, "tier 80 is under the minimum"); + + var unread = Facts(9, true); + unread.HasId = false; + Check.Eq(IltBreedingEssence.Evaluate(unread, r, now).Gate, BreedGate.NeedsId, "not appraised yet"); + + var boosted = Facts(10, false); + boosted.Incense = 0.05; + boosted.Catalyst = true; + BreedEssence b = IltBreedingEssence.Evaluate(boosted, r, now); + Check.Eq(string.Join("|", b.Boosters), "Refined incense +5%|Chromatic Catalyst", "boosters listed"); + } + + private static void Planner() + { + IltBreedingRules r = Rules(); + double now = 1_800_000_000; + var sf = Facts(1, true); + sf.MutDamage = 2; + sf.MutCrit = 1; + sf.Incense = 0.10; + var df = Facts(2, false); + df.MutDamage = 0; + df.MutCrit = 3; + BreedEssence stud = IltBreedingEssence.Evaluate(sf, r, now), dam = IltBreedingEssence.Evaluate(df, r, now); + + BreedPairPlan p = IltBreedingPlanner.Plan(stud, dam, r); + Check.True(p.CanBreed, "both ready"); + Check.Eq(p.InheritMin, 1, "lower lines: damage 0 + crit 1"); + Check.Eq(p.InheritMax, 5, "higher lines: damage 2 + crit 3"); + Check.Near(p.ChanceBest, 0.15 / 1.1, 1e-9, "best: 1 mutation, incense 10%"); + Check.Near(p.ChanceWorst, 0.15 / 1.5, 1e-9, "worst: 5 mutations"); + Check.Near(p.PotencyChance, 0.03, 1e-9, "potency 3%"); + + BreedPairPlan wrong = IltBreedingPlanner.Plan(dam, stud, r); + Check.False(wrong.CanBreed, "swapped sexes"); + Check.True(wrong.Blockers.Any(b => b.Contains("must be male")), "says the stud must be male"); + } + + private static void Supplies() + { + IltBreedingRules r = Rules(); + double now = 1_800_000_000; + BreedSupplyDef lesser = IltBreedingSupplies.Find(IltBreedingSupplies.LesserIncense)!; + BreedSupplyDef exquisite = IltBreedingSupplies.Find(IltBreedingSupplies.ExquisiteIncense)!; + BreedSupplyDef draught = IltBreedingSupplies.Find(IltBreedingSupplies.Draught)!; + BreedSupplyDef offering = IltBreedingSupplies.Find(IltBreedingSupplies.Offering)!; + BreedSupplyDef neuter = IltBreedingSupplies.Find(IltBreedingSupplies.NeuteringKit)!; + + var f = Facts(1, false); + f.Incense = 0.05; + BreedEssence primed = IltBreedingEssence.Evaluate(f, r, now); + Check.NotNull(IltBreedingSupplies.RefuseReason(lesser, primed, r), "weaker incense refused"); + Check.Null(IltBreedingSupplies.RefuseReason(exquisite, primed, r), "stronger incense taken"); + Check.True(IltBreedingSupplies.Warning(exquisite, primed).Contains("+5%"), "and warns the +5% is lost"); + + var n = Facts(2, false); + n.Neutered = true; + Check.NotNull(IltBreedingSupplies.RefuseReason(lesser, IltBreedingEssence.Evaluate(n, r, now), r), "no incense on a neutered essence"); + + BreedEssence adult = IltBreedingEssence.Evaluate(Facts(3, true), r, now); + Check.NotNull(IltBreedingSupplies.RefuseReason(draught, adult, r), "draught: juveniles only"); + var j = Facts(4, true); + j.JuvenileFlag = true; + j.MaturityKills = 0; + Check.Null(IltBreedingSupplies.RefuseReason(draught, IltBreedingEssence.Evaluate(j, r, now), r), "draught on a juvenile"); + j.MaturityXpMult = 2.0; + Check.NotNull(IltBreedingSupplies.RefuseReason(draught, IltBreedingEssence.Evaluate(j, r, now), r), "not twice"); + + Check.Null(IltBreedingSupplies.RefuseReason(offering, adult, r), "offering with the guardian on"); + r.Learn(IltBreedingRules.GuardianEnabled, 0, DateTime.UtcNow); + Check.NotNull(IltBreedingSupplies.RefuseReason(offering, adult, r), "offering refused with the guardian off"); + Check.NotNull(IltBreedingSupplies.RefuseReason(neuter, adult, r), "the neutering kit is never used from here"); + Check.Eq(IltBreedingSupplies.PriceText(1_250_000), "1.25M", "price text"); + } + + private static void ReaderJson() + { + IltBreedingRules r = Rules(); + double now = 1_800_000_000; + var stud = IltBreedingEssence.Evaluate(Facts(11, true), r, now); + var dam = IltBreedingEssence.Evaluate(Facts(12, false), r, now); + var events = new[] { new IltBreedingEvent { Utc = new DateTime(2026, 10, 15, 20, 0, 0, DateTimeKind.Utc), Kind = "birth", Text = "A \"baby\" was born" } }; + var supplies = IltBreedingSupplies.All.Select(s => (s, s.Key == IltBreedingSupplies.RefinedIncense ? 2L : 0L)).ToList(); + var snap = new BreedingSnapshot(new[] { stud, dam }, supplies, r.All(), events, + IltBreedingRules.ParseDebug(new[] { DebugReply }), DateTime.UtcNow, IltTri.On, IltTri.On, IltTri.On, + r.RoomText(), 5, "hello", now, true, r.Frozen()); + + string json = IltPetBreeding.BuildJson(snap, r, "InfiniteLeaftide"); + using (JsonDocument.Parse(json)) { } // well-formed + IltBreedingView v = IltBreedingView.Parse(json); + Check.True(v.Loaded && v.Available, "loaded"); + Check.Eq(v.Enabled, "on", "enabled"); + Check.Eq(v.Room, "landblock 0x0106 variant 2", "room"); + Check.Eq(v.FreeSlots, 5, "free slots"); + Check.Eq(v.Essences.Count, 2, "two essences"); + Check.True(v.Essences[0].Male && v.Essences[0].Ready, "stud row"); + Check.Eq(v.Pairs.Count, 1, "one ready pairing"); + Check.Near(v.Pairs[0].ChanceBest, 0.05, 1e-6, "pair odds"); + IltBreedSupplyRow refined = v.Supplies.First(s => s.Key == IltBreedingSupplies.RefinedIncense); + Check.Eq(refined.Count, 2L, "supply count"); + Check.Eq(refined.Targets.Count, 2, "both essences can take it"); + Check.Eq(v.Supplies.First(s => s.Key == IltBreedingSupplies.LesserIncense).Targets.Count, 0, "none carried: no targets"); + Check.Eq(v.Rules.Count, IltBreedingRules.Defs.Length, "every rule"); + Check.Eq(v.Events[0].Text, "A \"baby\" was born", "quotes escaped and read back"); + Check.Eq(v.Debug?.Match, "valid", "diagnostics"); + Check.Eq(IltBreedingView.ApplyVerb(" incense2 ", 12), "apply incense2 12", "apply verb"); + } + + private static void StateJson() + { + var state = new IltHubState(); + var rules = new IltBreedingRules(state.Pet.Breeding); + rules.Learn(IltBreedingRules.MaleCharges, 12, new DateTime(2026, 10, 15, 0, 0, 0, DateTimeKind.Utc)); + rules.LearnStageName(1, "Hatchling"); + rules.AddEvent("birth", "born", DateTime.UtcNow); + string json = JsonSerializer.Serialize(state, IltHubJsonContext.Default.IltHubState); + IltHubState back = JsonSerializer.Deserialize(json, IltHubJsonContext.Default.IltHubState)!; + var again = new IltBreedingRules(back.Pet.Breeding); + Check.Eq(again.GetInt(IltBreedingRules.MaleCharges), 12, "learned rule saved"); + Check.Eq(again.StageName(1), "Hatchling", "stage name saved"); + Check.Eq(back.Pet.Breeding.Log.Count, 1, "event saved"); + + IltHubState old = JsonSerializer.Deserialize("{\"Pet\":{\"PetLog\":[\"a\"]}}", IltHubJsonContext.Default.IltHubState)!; + Check.NotNull(old.Pet.Breeding, "a hub.json from before the tracker gets an empty breeding state"); + } + + private static unsafe void DataApiVersion() + { + // Version 3 (the Temple guardians) appends after the breeding pair; a v2 reader sees the same breeding layout. + Check.Eq(RynthIltDataApiV1.InterfaceVersion, 3u, "version 3"); + Check.True(RynthIltDataApiV1.V1Size < RynthIltDataApiV1.V2Size && RynthIltDataApiV1.V2Size < (uint)sizeof(RynthIltDataApiV1), + "v2 appends to v1, v3 to v2"); + Check.Eq(RynthIltDataApiV1.V1Size, (uint)(8 + 4 * sizeof(IntPtr)), "v1 = two uints and four function pointers"); + Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1) != IntPtr.Zero, "v1 readers still get the table"); + Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 2) != IntPtr.Zero, "v2 readers too"); + Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 3) != IntPtr.Zero, "v3 readers too"); + Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 4) == IntPtr.Zero, "a future version isn't claimed"); + var t = (RynthIltDataApiV1*)DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1); + Check.True(t->GetPetBreedingJson != null && t->PetBreedingCommand != null, "breeding functions filled"); + Check.Eq(RynthIltHub.SectionPetBreeding, "pets-breeding", "section id"); + } +} diff --git a/Tools/RynthILT.Tests/ChunkTargetTests.cs b/Tools/RynthILT.Tests/ChunkTargetTests.cs new file mode 100644 index 0000000..857dbc6 --- /dev/null +++ b/Tools/RynthILT.Tests/ChunkTargetTests.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The chunk rules end to end: a fake inventory with the Lugian Aetheria Hammer and one candidate, +// IltChunkClap.Tick, and whether the hammer was used on the candidate. These cover what the pure +// rule tests (AetheriaChunkTests) cannot: the properties as RynthILT reads them from the host, an +// item that is not appraised, and a host that cannot tell whether an appraisal arrived. The hammer +// destroys what it is used on, so "used on it" is the thing to get right. +internal static class ChunkTargetTests +{ + private const uint Player = 0x50000F01; + private const uint Hammer = 0x5000A001; + private const uint Item = 0x5000A002; + private const uint ItemTypeGem = 0x00000800; + private const uint ItemTypeMelee = 0x00000001; + private const uint ItemTypeMisc = 0x00000080; + + public static void Register(Runner r) + { + r.Add("chunk (live path): unlevelled Coalesced chunks only when its level was truly read as none", UnlevelledVsUnreadable); + r.Add("chunk (live path): levelled Coalesced Aetheria obeys the cap; other aetheria needs a level", LevelledCap); + r.Add("chunk (live path): corrupted two-handed cleave 2 chunks, other corrupted cleave 2 does not", CorruptedCleave); + r.Add("chunk (live path): corrupted keep rules and the rating level are off by default and protect when on", KeepRulesLive); + r.Add("chunk (live path): a busy client in combat chunks with chunk-in-combat on, not off; peace waits for idle", CombatBusy); + } + + /// One chunk pass on a fake pack. Returns the targets the hammer was used on. + private static List Pass(string folder, Action settings, Action candidate, + uint itemType = ItemTypeGem, string name = "Coalesced Aetheria", bool appraised = true, + bool hostCanSayAppraised = true, bool busy = false, int combatMode = 1) + { + FakeHost.Reset(); + FakeHost.WorldName = "InfiniteLeaftide"; + FakeHost.ContentsCalls = true; + FakeHost.UseOnCalls = true; + FakeHost.WeaponCalls = hostCanSayAppraised; // installs HasAppraisalData / RequestId / combat mode + FakeHost.BusyCalls = true; + FakeHost.BusyStateValue = busy ? 1 : 0; + FakeHost.CombatModeValue = combatMode; + FakeHost.Names[Hammer] = "Lugian Aetheria Hammer"; FakeHost.ItemTypes[Hammer] = ItemTypeMisc; FakeHost.Containers[Hammer] = Player; + FakeHost.Names[Item] = name; FakeHost.ItemTypes[Item] = itemType; FakeHost.Containers[Item] = Player; + if (appraised) FakeHost.Appraised.Add(Item); + candidate(Item); + var host = FakeHost.Create(Player); + string dir = Path.Combine(Program.TempRoot, "chunk-" + folder); + Directory.CreateDirectory(dir); + var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host)); + var g = hub.State.Gear; + g.AutoChunkAetheria = true; + g.AutoChunkCorrupted = true; + settings(g); + hub.Gear.ChunkClap.Tick(10_000); + return FakeHost.UsesOn.Where(u => u.Source == Hammer).Select(u => u.Target).ToList(); + } + + private static void Ints(uint id, params (uint Key, int Value)[] values) + { + foreach (var (k, v) in values) FakeHost.Ints[(id, k)] = v; + } + + private static void UnlevelledVsUnreadable() + { + // Truly unlevelled: the appraisal arrived and the item has no level (int 319), no XP, no tinks. + Check.Eq(Pass("coal-unlevelled", _ => { }, _ => { }).Count, 1, "appraised, no level: chunked (ub-IT)"); + // Even with the cap at its lowest. + Check.Eq(Pass("coal-unlevelled-cap1", g => g.ChunkAetheriaUnderLevel = 1, _ => { }).Count, 1, "cap 1 does not stop an unlevelled one"); + // Not appraised yet: nothing is known, so it is asked for, not hammered. + var asked = Pass("coal-unappraised", _ => { }, _ => { }, appraised: false); + Check.Eq(asked.Count, 0, "not appraised: not chunked"); + Check.True(FakeHost.IdRequests.Contains(Item), "its appraisal is requested"); + // The host cannot say whether an appraisal arrived: a level of 0 might be a failed read. + Check.Eq(Pass("coal-unreadable", _ => { }, _ => { }, hostCanSayAppraised: false).Count, 0, + "host cannot confirm the appraisal: kept, not chunked"); + // The same unconfirmable host with a read level still keeps (no half-trusted piece is hammered). + Check.Eq(Pass("coal-unreadable-lvl", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 2)), hostCanSayAppraised: false).Count, 0, + "host cannot confirm the appraisal: even a read level 2 is kept"); + // A revealed (non-Coalesced) aetheria with no level is never chunked. + Check.Eq(Pass("rev-unlevelled", _ => { }, _ => { }, name: "Blue Aetheria").Count, 0, "revealed aetheria with no level: kept"); + // Item XP, tinks or the never-chunk flag keep it. + Check.Eq(Pass("coal-xp", _ => { }, id => FakeHost.Quads[(id, IltInventory.QuadItemTotalXp)] = 500).Count, 0, "has item XP: kept"); + Check.Eq(Pass("coal-tinked", _ => { }, id => Ints(id, (IltInventory.IntNumTimesTinkered, 1))).Count, 0, "tinkered: kept"); + Check.Eq(Pass("coal-never", _ => { }, id => FakeHost.Bools[(id, IltInventory.BoolNeverChunk)] = true).Count, 0, "never-chunk flag: kept"); + } + + private static void LevelledCap() + { + Check.Eq(Pass("cap-l3", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 3))).Count, 1, "level 3 under the default cap of 4"); + Check.Eq(Pass("cap-l4", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 4))).Count, 0, "level 4 at the default cap of 4: kept"); + Check.Eq(Pass("cap9-l8", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 8))).Count, 1, "level 8 under a cap of 9"); + Check.Eq(Pass("cap9-l9", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 9))).Count, 0, "level 9 at a cap of 9: kept"); + Check.Eq(Pass("cap9-l10", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 10))).Count, 0, "level 10 over a cap of 9: kept"); + Check.Eq(Pass("cap11-l10", g => g.ChunkAetheriaUnderLevel = 11, id => Ints(id, (IltInventory.IntItemMaxLevel, 10))).Count, 1, "cap 11 chunks every level"); + Check.Eq(Pass("rev-l2", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 2)), name: "Blue Aetheria").Count, 1, "a levelled revealed piece under the cap"); + } + + private static void CorruptedCleave() + { + void Weapon(uint id, int cleave, int wieldSkill = 45, int weaponType = 0, int attackType = 4) => + Ints(id, (IltInventory.IntItemWorkmanship, 6), (IltInventory.IntCleaving, cleave), (IltInventory.IntWieldSkillType, wieldSkill), + (IltInventory.IntWeaponType, weaponType), (IltInventory.IntAttackType, attackType)); + Check.Eq(Pass("cor-1h-c1", _ => { }, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword").Count, 1, "one-handed cleave 1 chunks"); + Check.Eq(Pass("cor-1h-c2", _ => { }, id => Weapon(id, 2), ItemTypeMelee, "Corrupted Sword").Count, 0, "one-handed cleave 2 is kept"); + Check.Eq(Pass("cor-2h-c2", _ => { }, id => Weapon(id, 2, wieldSkill: 41), ItemTypeMelee, "Corrupted Greatsword").Count, 1, "two-handed cleave 2 chunks"); + Check.Eq(Pass("cor-2h-c3", _ => { }, id => Weapon(id, 3, wieldSkill: 41), ItemTypeMelee, "Corrupted Greatsword").Count, 0, "two-handed cleave 3 is kept"); + Check.Eq(Pass("cor-2h-thrust", _ => { }, id => Weapon(id, 2, wieldSkill: 41, attackType: 2), ItemTypeMelee, "Corrupted Spear").Count, 0, "two-handed thrust cleave 2 is kept"); + Check.Eq(Pass("cor-nowork", _ => { }, id => Ints(id, (IltInventory.IntCleaving, 1)), ItemTypeMelee, "Corrupted Sword").Count, 0, "no workmanship read: kept"); + Check.Eq(Pass("cor-unreadable", _ => { }, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword", hostCanSayAppraised: false).Count, 0, + "host cannot confirm the appraisal: kept"); + Check.Eq(Pass("cor-off", g => g.AutoChunkCorrupted = false, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword").Count, 0, "auto-chunk corrupted off: not touched"); + } + + private static void KeepRulesLive() + { + var def = new IltGearState(); + Check.True(!def.KeepCorruptedCrushingBlow && !def.KeepCorruptedBitingStrike && !def.KeepCorruptedArmorCleaving + && !def.KeepCorruptedAnySlayer && !def.KeepCorruptedMultiStrike && !def.KeepCorruptedElementalBonus + && !def.KeepCorruptedAnySpell && def.KeepCorruptedMaxDamageAtLeast == 0 && def.KeepCorruptedSpellIds == "", + "every corrupted keep rule is off by default"); + Check.Eq(def.KeepAetheriaRatingAtLeast, 1, "the rating level defaults to 1 (any rating keeps, as before)"); + + void Loaded(uint id) + { + Ints(id, (IltInventory.IntItemWorkmanship, 6), (IltInventory.IntCleaving, 1), (IltInventory.IntAttackType, 160), + (IltInventory.IntSlayerCreatureType, 5), (IltInventory.IntElementalDamageBonus, 10), (IltInventory.IntDamage, 400)); + FakeHost.Doubles[(id, IltInventory.FloatCriticalFrequency)] = 0.1; + FakeHost.Doubles[(id, IltInventory.FloatCriticalMultiplier)] = 1.5; + FakeHost.Doubles[(id, IltInventory.FloatIgnoreArmor)] = 0.2; + FakeHost.SpellIds[id] = new uint[] { 2072 }; + } + int Run(string tag, Action s) => Pass("keep-" + tag, s, Loaded, ItemTypeMelee, "Corrupted Sword").Count; + Check.Eq(Run("none", _ => { }), 1, "a loaded corrupted weapon chunks while every keep rule is off"); + Check.Eq(Run("crush", g => g.KeepCorruptedCrushingBlow = true), 0, "Crushing Blow on: kept"); + Check.Eq(Run("bite", g => g.KeepCorruptedBitingStrike = true), 0, "Biting Strike on: kept"); + Check.Eq(Run("armor", g => g.KeepCorruptedArmorCleaving = true), 0, "Armor Cleaving on: kept"); + Check.Eq(Run("slayer", g => g.KeepCorruptedAnySlayer = true), 0, "slayer on: kept"); + Check.Eq(Run("multi", g => g.KeepCorruptedMultiStrike = true), 0, "multi-strike on: kept"); + Check.Eq(Run("elem", g => g.KeepCorruptedElementalBonus = true), 0, "elemental bonus on: kept"); + Check.Eq(Run("maxdmg", g => g.KeepCorruptedMaxDamageAtLeast = 400), 0, "max damage 400 on: kept"); + Check.Eq(Run("maxdmg-hi", g => g.KeepCorruptedMaxDamageAtLeast = 401), 1, "max damage above the weapon's: chunks"); + Check.Eq(Run("spell", g => g.KeepCorruptedAnySpell = true), 0, "any spell on: kept"); + Check.Eq(Run("spellid", g => g.KeepCorruptedSpellIds = "2072"), 0, "a listed spell id: kept"); + Check.Eq(Run("spellid-other", g => g.KeepCorruptedSpellIds = "100"), 1, "another spell id: chunks"); + + // The rating level on a live Coalesced piece with a C 1 rating. + void C1(uint id) => Ints(id, (IltInventory.IntGearCrit, 1)); + Check.Eq(Pass("rate-default", _ => { }, C1).Count, 0, "C 1 is kept at the default rating level"); + Check.Eq(Pass("rate-2", g => g.KeepAetheriaRatingAtLeast = 2, C1).Count, 1, "C 1 chunks once the rating level is 2"); + Check.Eq(Pass("rate-2-c2", g => g.KeepAetheriaRatingAtLeast = 2, id => Ints(id, (IltInventory.IntGearCrit, 2))).Count, 0, "C 2 is kept at level 2"); + Check.Eq(Pass("rate-2-off", g => { g.KeepAetheriaRatingAtLeast = 2; g.KeepAetheriaWithCrit = false; }, id => Ints(id, (IltInventory.IntGearCrit, 5))).Count, 1, + "the C switch off ignores the rating level"); + } + + private static void CombatBusy() + { + Check.Eq(Pass("busy-combat-on", g => g.ChunkInCombat = true, _ => { }, busy: true, combatMode: 2).Count, 1, + "busy in combat mode with chunk-in-combat on: chunks"); + Check.Eq(Pass("busy-combat-off", g => g.ChunkInCombat = false, _ => { }, busy: true, combatMode: 2).Count, 0, + "busy in combat mode with chunk-in-combat off: waits"); + Check.Eq(Pass("idle-combat-on", g => g.ChunkInCombat = true, _ => { }, busy: false, combatMode: 2).Count, 1, + "idle in combat mode with chunk-in-combat on: chunks"); + Check.Eq(Pass("busy-peace", g => g.ChunkInCombat = true, _ => { }, busy: true, combatMode: 1).Count, 0, + "busy in peace mode waits for idle even with chunk-in-combat on"); + Check.Eq(Pass("idle-peace", g => g.ChunkInCombat = false, _ => { }, busy: false, combatMode: 1).Count, 1, + "idle in peace mode chunks"); + } +} diff --git a/Tools/RynthILT.Tests/ChunkTests.cs b/Tools/RynthILT.Tests/ChunkTests.cs new file mode 100644 index 0000000..0d8c931 --- /dev/null +++ b/Tools/RynthILT.Tests/ChunkTests.cs @@ -0,0 +1,36 @@ +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// Lugian-hammer chunking (Hub/IltChunkClap.cs): only the Lugian Aetheria Hammer is the tool, and +// ILT's result lines name the item and the tool. Ported from SilentKelpie's fix (2026-10-15). +internal static class ChunkTests +{ + public static void Register(Runner r) + { + r.Add("chunk: only the Lugian Aetheria Hammer is the tool, never a Lugian Hammer weapon", HammerOnly); + r.Add("chunk: ILT's result lines (item and tool named) end the wait; combat lines don't", ResultLines); + } + + /// The Flaming Lugian Hammer (a loot weapon) matched " Lugian Hammer", chunked nothing, + /// and all 9 Coalesced Aetheria timed out into the skip list. + private static void HammerOnly() + { + Check.True(IltChunkClap.IsChunkHammer("Lugian Aetheria Hammer"), "the ILT tool"); + Check.True(IltChunkClap.IsChunkHammer("lugian aetheria hammer"), "any case"); + Check.False(IltChunkClap.IsChunkHammer("Flaming Lugian Hammer"), "a loot weapon is not the tool"); + Check.False(IltChunkClap.IsChunkHammer("Lugian Hammer"), "nor the plain one"); + Check.False(IltChunkClap.IsChunkHammer("Acid Lugian Hammer"), "nor any variant"); + } + + private static void ResultLines() + { + Check.Eq(IltChunkClap.ClassifyChat("You smash the Corrupted Sword with the Lugian Aetheria Hammer."), IltChunkClap.ChunkResult.Done, "ILT corrupted line"); + Check.Eq(IltChunkClap.ClassifyChat("You smash the aetheria with the hammer."), IltChunkClap.ChunkResult.Done, "aetheria line"); + Check.Eq(IltChunkClap.ClassifyChat("The aetheria is too powerful to chunk."), IltChunkClap.ChunkResult.Refused, "refused"); + Check.Eq(IltChunkClap.ClassifyChat("You're too busy!"), IltChunkClap.ChunkResult.Busy, "busy"); + Check.Eq(IltChunkClap.ClassifyChat("You smash Corrupted Shadow for 147 points of bludgeoning damage!"), IltChunkClap.ChunkResult.None, + "a combat line naming a corrupted monster is no result"); + } +} diff --git a/Tools/RynthILT.Tests/DataApiTests.cs b/Tools/RynthILT.Tests/DataApiTests.cs new file mode 100644 index 0000000..3434c10 --- /dev/null +++ b/Tools/RynthILT.Tests/DataApiTests.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthILT; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// "RynthILT.Data" v1 (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs): the bank JSON RynthILT +// builds (Hub/IltBankExport.cs) read back by the shared reader, the bank verb lines a reader sends +// (IltBanking.RunVerb splits them), and the table itself. The charms JSON is MoveTests' +// CharmsReaderJson. No plugin in this tree reads the interface yet. +internal static class DataApiTests +{ + public static void Register(Runner r) + { + r.Add("data: the bank JSON reads back whole: characters (current first), choices, notes, log", BankRoundTrip); + r.Add("data: the bank verb lines carry their fields in RunVerb's order", BankVerbs); + r.Add("data: bad bank JSON reads as nothing", BankBadJson); + r.Add("data: the Temple guardian JSON reads back whole (switches, answer, hand-in, rows)", GuardianRoundTrip); + // Last: Release() switches the table off for the rest of the process. + r.Add("data: the RynthILT.Data table: query, functions, release", DataTable); + } + + private static void BankRoundTrip() + { + var me = new IltBankState { Pyreals = 1_500_000, Luminance = 42, PrestigeCoins = 3, + LastUpdated = new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc).ToLocalTime() }; + var alt = new IltBankState { Pyreals = 7, LegendaryKeys = 2, LastUpdated = DateTime.Now }; + var tx = new List(); + for (int i = 0; i < IltBankExport.MaxTransactions + 5; i++) + tx.Add(new IltBankTransaction { Timestamp = new DateTime(2026, 10, 1).AddMinutes(i), Type = i % 2 == 0 ? "Sent" : "Received", + Currency = "Pyreals", Amount = i, OtherPlayer = "Bob \"the\" Builder" }); + string json = IltBankExport.Build(true, 1, "InfiniteLeaftide", "Zed", + new[] { new IltBankExport.Row("Alt", false, alt), new IltBankExport.Row("Zed", true, me) }, + "Deposited 5 Pyreals", tx); + Check.True(json.All(c => c >= 0x20 && c <= 0x7E), "plain printable ASCII"); + + IltBankView v = IltBankView.Parse(json); + Check.True(v.Loaded && v.Available, "loaded, ILT"); + Check.Eq(v.Enabled, 1, "the server has /bank"); + Check.Eq(v.World, "InfiniteLeaftide", "world"); + Check.Eq(v.Character, "Zed", "character"); + Check.Eq(v.Result, "Deposited 5 Pyreals", "last result"); + Check.Eq(v.Characters.Count, 2, "both characters"); + Check.True(v.Characters[0].Current && v.Characters[0].Name == "Zed", "the current character first"); + Check.Eq(v.Characters[0].Pyreals, 1_500_000L, "pyreals"); + Check.Eq(v.Characters[0].PrestigeCoins, 3L, "prestige coins"); + Check.Eq(v.Characters[0].UpdatedUtc, new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc), "updated, in UTC"); + Check.Eq(v.Characters[1].LegendaryKeys, 2L, "the other character's keys"); + + Check.Eq(v.Deposits.Count, IltBankCommands.Deposits.Length, "every deposit choice"); + Check.Eq(v.Withdrawals.Count, IltBankCommands.Withdrawals.Length, "every withdraw choice"); + Check.Eq(v.Transfers.Count, IltBankCommands.Transfers.Length, "every transfer choice"); + Check.True(v.Transfers.Single(t => t.Notes).Label == "Trade notes", "only trade notes count notes"); + Check.Eq(v.Notes.Count, IltBankCommands.NoteDenominations.Length, "every note denomination"); + Check.Eq(v.Notes[^1].Value, 250_000L, "MMD is 250K"); + + Check.Eq(v.Transactions.Count, IltBankExport.MaxTransactions, "the log is capped"); + Check.Eq(v.Transactions[0].Amount, (long)(IltBankExport.MaxTransactions + 4), "newest first"); + Check.Eq(v.Transactions[0].Player, "Bob \"the\" Builder", "quotes in a name survive"); + } + + private static void BankVerbs() + { + Check.Eq(IltBankView.RefreshVerb(), "refresh", "refresh"); + Check.Eq(IltBankView.DepositVerb(3), "deposit 3", "deposit"); + Check.Eq(IltBankView.WithdrawVerb(7, 4, 9), "withdraw 7 4 9", "withdraw: index, amount, note"); + Check.Eq(IltBankView.TransferVerb(6, 2, 9, " Some Name "), "transfer 6 2 9 Some Name", "transfer: the name last, trimmed"); + foreach (string verb in new[] { IltBankView.RefreshVerb(), IltBankView.DepositVerb(0), IltBankView.WithdrawVerb(0, 1, -1), + IltBankView.TransferVerb(0, 1, -1, "Bob") }) + Check.True(verb.All(c => c >= 0x20 && c <= 0x7E), "ASCII verb (DataInterface refuses anything else): " + verb); + } + + private static void BankBadJson() + { + Check.True(ReferenceEquals(IltBankView.Parse(null), IltBankView.None), "null"); + Check.True(ReferenceEquals(IltBankView.Parse("{not json"), IltBankView.None), "broken"); + Check.True(ReferenceEquals(IltBankView.Parse("[1,2]"), IltBankView.None), "not an object"); + IltBankView empty = IltBankView.Parse("{}"); + Check.True(empty.Loaded && !empty.Available && empty.Enabled == -1 && empty.Characters.Count == 0, "missing fields read as nothing known"); + } + + /// + /// Version 3: the guardian JSON RynthILT builds (IltGuardian.BuildJson) read back by the reader + /// RynthOracle's Quests tab uses, quotes and all. + /// + private static void GuardianRoundTrip() + { + var rows = new[] + { + new IltTempleAttrStatus("Strength", "Fiun \"Big\" Strongarm", 3, "Ready", "", true, true), + new IltTempleAttrStatus("Focus", "Fiun Thinker", 1, "Cooldown", "in 5h 2m", false, false), + }; + string json = IltGuardian.BuildJson("InfiniteLeaftide", chat: true, auto: false, buy: true, cooldownHours: 20, + answer: "Pyreal", npc: "Guardian of Attribute Enlightenment", answerAgeSec: 42, heard: "What is \"coin\"?", + running: true, status: "handing Pyreal to Guardian...", syncedUtc: new DateTime(2026, 10, 18, 19, 5, 0, DateTimeKind.Utc), rows); + Check.True(json.All(c => c >= 0x20 && c <= 0x7E), "plain printable ASCII"); + + IltGuardianView v = IltGuardianView.Parse(json); + Check.True(v.Loaded && v.Available && v.World == "InfiniteLeaftide", "loaded, the world"); + Check.True(v.Chat && !v.Auto && v.Buy && v.CooldownHours == 20, "the switches"); + Check.True(v.Answer == "Pyreal" && v.Npc == "Guardian of Attribute Enlightenment" && v.AnswerAgeSec == 42 && v.Heard == "What is \"coin\"?", + "the last answer"); + Check.True(v.Running && v.Status.StartsWith("handing Pyreal"), "the hand-in"); + Check.Eq(v.SyncedUtc, new DateTime(2026, 10, 18, 19, 5, 0, DateTimeKind.Utc), "the /qb read time"); + Check.Eq(v.Rows.Count, 2, "both rows"); + Check.True(v.Rows[0].Npc == "Fiun \"Big\" Strongarm" && v.Rows[0].Count == 3 && v.Rows[0].Ready && v.Rows[0].Exact, "an exact, ready row"); + Check.True(v.Rows[1].Eta == "in 5h 2m" && !v.Rows[1].Ready && !v.Rows[1].Exact, "an estimated row on cooldown"); + + IltGuardianView none = IltGuardianView.Parse(IltGuardian.BuildJson("x", false, false, false, 1, "", "", -1, "", false, "idle", + DateTime.MinValue, Array.Empty())); + Check.True(none.Answer.Length == 0 && none.AnswerAgeSec == -1 && none.SyncedUtc == DateTime.MinValue && none.Rows.Count == 0, + "no answer, no /qb read, no rows"); + } + + private static unsafe void DataTable() + { + Check.Eq(DataInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not ours"); + Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 4), IntPtr.Zero, "a newer version than we have: none"); + var t = (RynthIltDataApiV1*)DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1); + Check.True(t != null, "v1 is served"); + Check.Eq(t->Version, 3u, "Version 3 (v1 and v2 readers take it: it starts with their tables)"); + Check.Eq(t->StructSize, (uint)sizeof(RynthIltDataApiV1), "StructSize"); + Check.Eq(sizeof(RynthIltDataApiV1), 8 + 8 * IntPtr.Size, "header + 8 functions (v1's 4, the breeding pair, the guardian pair)"); + Check.Eq(RynthIltDataApiV1.V1Size, (uint)(8 + 4 * IntPtr.Size), "a v1 table ends before the breeding pair"); + Check.Eq(RynthIltDataApiV1.V2Size, (uint)(8 + 6 * IntPtr.Size), "a v2 table ends before the guardian pair (readers still see breeding on it)"); + Check.True(t->GetCharmsJson != null && t->GetBankJson != null && t->ToggleCharm != null && t->BankCommand != null + && t->GetPetBreedingJson != null && t->PetBreedingCommand != null + && t->GetGuardianJson != null && t->GuardianCommand != null, "every function is filled in"); + Check.Eq((IntPtr)t, DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1), "the same table each time"); + + // No plugin instance here (not logged in): nothing to report, every action refused. + byte* buf = stackalloc byte[64]; + Check.Eq(t->GetCharmsJson(buf, 64), 0, "no charms before login"); + Check.Eq(t->GetBankJson(buf, 64), 0, "no bank before login"); + Check.Eq(t->ToggleCharm(1234), 0, "no toggle before login"); + byte* verb = stackalloc byte[] { (byte)'r', (byte)'e', (byte)'f', (byte)'r', (byte)'e', (byte)'s', (byte)'h', 0 }; + Check.Eq(t->BankCommand(verb), 0, "no bank command before login"); + Check.Eq(t->GetPetBreedingJson(buf, 64), 0, "no breeding JSON before login"); + Check.Eq(t->PetBreedingCommand(verb), 0, "no breeding command before login"); + Check.Eq(t->GetGuardianJson(buf, 64), 0, "no guardian JSON before login"); + Check.Eq(t->GuardianCommand(verb), 0, "no guardian command before login"); + + DataInterface.Release(); + Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)"); + Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1), IntPtr.Zero, "and nothing is served after shutdown"); + Check.Eq(t->GetBankJson(buf, 64), 0, "the old table stays callable and answers nothing"); + } +} diff --git a/Tools/RynthILT.Tests/FakeAiHub.cs b/Tools/RynthILT.Tests/FakeAiHub.cs new file mode 100644 index 0000000..05092c6 --- /dev/null +++ b/Tools/RynthILT.Tests/FakeAiHub.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using RynthCore.Plugin.Shared; + +namespace RynthILT.Tests; + +/// +/// A stand-in for RynthAi's "RynthAi.Hub" table (Plugins/Shared/RynthAiHubApi.cs), so the tests can +/// check what RynthILT asks of RynthAi (RynthAiClient.UseTableForTests takes it). Only the functions +/// the moved features use answer anything; the rest are absent (null), as an old RynthAi's would be. +/// Reset() before each test that uses it. +/// +internal static unsafe class FakeAiHub +{ + /// BackAwayFrom calls (object, radius, hold), and what it answers. + public static readonly List<(uint Id, float Radius, int HoldMs)> BackAways = new(); + public static int BackAwayResult = RynthAiHub.BackAwayStarted; + /// SetPlayerCounter: the last value reported per counter id. + public static readonly Dictionary Counters = new(); + /// SessionStats: the shared session's start (0 = no session: SessionStats answers 0). + public static long SessionStartTicks; + + private static RynthAiHubApiV1* _table; + + public static void Reset() + { + BackAways.Clear(); + BackAwayResult = RynthAiHub.BackAwayStarted; + Counters.Clear(); + SessionStartTicks = 0; + } + + public static IntPtr Table + { + get + { + if (_table == null) + { + var t = (RynthAiHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiHubApiV1)); + t->StructSize = (uint)sizeof(RynthAiHubApiV1); + t->BackAwayFrom = &BackAwayFrom; + t->SetPlayerCounter = &SetPlayerCounter; + t->SessionStats = &SessionStats; + t->Version = RynthAiHubApiV1.InterfaceVersion; + _table = t; + } + return (IntPtr)_table; + } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int SessionStats(SessionStatsV1* s) + { + if (SessionStartTicks == 0 || s == null) return 0; + *s = default; + s->StartUtcTicks = SessionStartTicks; + s->SessionSeconds = 60; + return 1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int SetPlayerCounter(uint id, long value) + { + Counters[id] = value; + return 1; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int BackAwayFrom(uint id, float radius, int holdMs) + { + BackAways.Add((id, radius, holdMs)); + return BackAwayResult; + } +} diff --git a/Tools/RynthILT.Tests/FeatureCatalogTests.cs b/Tools/RynthILT.Tests/FeatureCatalogTests.cs new file mode 100644 index 0000000..5e73202 --- /dev/null +++ b/Tools/RynthILT.Tests/FeatureCatalogTests.cs @@ -0,0 +1,215 @@ +using System; +using System.Text; +using System.Text.Json; +using RynthCore.Plugin.RynthILT; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// Leaftide feature list (IltFeatureCatalog): every feature the player asked RynthILT to cover is +// listed and the states follow the server bits. Also the NUL-terminated copy RynthILT's interfaces +// ("RynthServer.Profile", "RynthILT.Data") hand their JSON out with. +internal static class FeatureCatalogTests +{ + public static void Register(Runner r) + { + r.Add("features: banking, guardian, attributes, augs, paragon x3, split arrows, T11 and fellowship are listed", Listed); + r.Add("features: state follows the server bit on ILT, built-ins are on, nothing is known off ILT", States); + r.Add("features: profile JSON is valid ASCII with features and the fellowship rules", ProfileJson); + r.Add("features: the interface copies the JSON only when it fits, NUL-terminated", InterfaceWrite); + r.Add("features: the /qb list rides the profile JSON on ILT worlds only", QuestBonusJson); + r.Add("features: the RynthILT.Server table: query, filled in, release", ServerTable); + r.Add("features: the ILT profile is on with the world; a refusal in chat turns a feature off", ProfileOnWithTheWorld); + r.Add("features: probed features read checking; options ILT runs off are off until chat shows them", ProbedAndOffInIlt); + r.Add("features: charms are on with the ILT world unless refused; rows describe themselves", Charms); + } + + /// ACECustom options Infinite Leaftide runs with off (ServerConfig defaults, PROD_DEPLOY_PLAN.md). + private static readonly string[] OffInIlt = { "pet_strain", "pet_refill", "defense_scaling" }; + + /// Features the login probe (or the /myquests tracker) answers. + private static readonly string[] Probed = + { + "bank", "attributes", "augmentations", "enlightenment", "clap", "pets", "shinies", + "fellowship_blackjack", "quests", "quest_bonus", "powerball", "blackjack", + }; + + private static void ProfileOnWithTheWorld() + { + // The features the player asked about, plus the pet switches prod runs on (bond, potency). + foreach (string key in new[] { "bank_notes", "t11", "t11_craft_gate", "split_arrows", "charms", "pet_breeding", + "pet_maturity", "pet_bond", "pet_potency", "monster_capture", "universal_mastery", + "missile_power", "t11_hit_gate", "fship" }) + { + IltFeatureInfo f = IltFeatureCatalog.Find(key)!; + Check.Eq(f.Known, IltKnown.Profile, key + " is on in the ILT profile"); + Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown), IltTri.On, key + " on with the ILT world"); + Check.Eq(IltFeatureCatalog.StateOf(f, false, _ => IltTri.On), IltTri.Unknown, key + " unknown off ILT"); + } + IltFeatureInfo mastery = IltFeatureCatalog.Find("universal_mastery")!; + Check.Eq(IltFeatureCatalog.StateOf(mastery, true, k => k == IltFeature.UniversalMastery ? IltTri.Off : IltTri.Unknown), + IltTri.Off, "a refusal in chat turns a profile feature off"); + Check.Null(IltFeatureCatalog.Find("fellowship_additive"), "upstream ACE's additive fellowship option isn't an ILT feature"); + } + + private static void ProbedAndOffInIlt() + { + foreach (string key in Probed) + { + IltFeatureInfo f = IltFeatureCatalog.Find(key)!; + Check.Eq(f.Known, IltKnown.Checked, key + " is answered by the login probe"); + Check.Eq(IltFeatureCatalog.StateText(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown)), "checking", key + " reads 'checking' until then"); + } + foreach (string key in OffInIlt) + { + IltFeatureInfo f = IltFeatureCatalog.Find(key)!; + Check.Eq(f.Known, IltKnown.ProfileOff, key + " is off in the ILT profile"); + Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown), IltTri.Off, key + " off with the ILT world"); + Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.On), IltTri.On, key + " on once the server shows it"); + Check.True(IltFeatureCatalog.Describe(key).Tooltip.Contains("Off in ILT"), key + "'s tooltip says it's off in ILT"); + } + + // ACECustom's three refill messages (PetDevice.TryApplyPyrealAutoRefillBeforeSummon) prove the refill is on. + Check.True(IltServerOptions.IsPyrealRefillLine("You restore one charge on your summoning essence at no cost."), "free refill"); + Check.True(IltServerOptions.IsPyrealRefillLine("You spend 1,000 pyreals to restore one charge on your summoning essence."), "paid refill"); + Check.True(IltServerOptions.IsPyrealRefillLine("You need 1,000 pyreals to auto-replenish your summoning essence. You do not have enough pyreals."), "refill too dear"); + Check.False(IltServerOptions.IsPyrealRefillLine("Your summoning essence is empty."), "an empty essence says nothing about the refill"); + } + + private static void Charms() + { + Check.Eq(IltFeatureCatalog.CharmStateOf(true, IltTri.Unknown), IltTri.On, "a charm is on with the ILT world"); + Check.Eq(IltFeatureCatalog.CharmStateOf(true, IltTri.Off), IltTri.Off, "a refused charm is off"); + Check.Eq(IltFeatureCatalog.CharmStateOf(false, IltTri.On), IltTri.Unknown, "nothing is claimed off ILT"); + + var (label, group, tooltip) = IltFeatureCatalog.Describe(IltFeature.Charm("Mana Barrier")); + Check.Eq(label, "Mana Barrier", "a charm row shows the charm's name"); + Check.Eq(group, IltFeatureCatalog.GroupCharms, "charms have their own section"); + Check.True(tooltip.Contains("Mana absorbs"), "the tooltip carries the charm's effect"); + Check.Eq(IltFeatureCatalog.Describe("something_new").Group, IltFeatureCatalog.GroupOther, "an unknown bit goes to Other"); + } + + private static readonly string[] Requested = + { + "bank", "guardian", "attributes", "augmentations", "paragon_armor", "paragon_weapons", + "paragon_jewelry", "split_arrows", "t11", "fellowship_large", "zone_share", "fellowship_blackjack", + }; + + private static void Listed() + { + foreach (string key in Requested) + Check.NotNull(IltFeatureCatalog.Find(key), "listed: " + key); + Check.Null(IltFeatureCatalog.Find("no_such_feature"), "an unknown key is not found"); + + var seen = new System.Collections.Generic.HashSet(StringComparer.OrdinalIgnoreCase); + foreach (IltFeatureInfo f in IltFeatureCatalog.All) + { + Check.True(seen.Add(f.Key), "keys are unique: " + f.Key); + Check.True(Array.IndexOf(IltFeatureCatalog.Groups, f.Group) >= 0, $"{f.Key} is in a known section ({f.Group})"); + Check.True(f.Label.Length > 0 && f.Where.Length > 0 && f.Description.Length > 0, f.Key + " has a label, a place and a description"); + } + } + + private static void States() + { + IltFeatureInfo bank = IltFeatureCatalog.Find("bank")!; + IltFeatureInfo guardian = IltFeatureCatalog.Find("guardian")!; + Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.On), IltTri.On, "bank on when the server answers /bank"); + Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.Off), IltTri.Off, "bank off when the server says so"); + Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.Unknown), IltTri.Unknown, "bank unknown before the check"); + Check.Eq(IltFeatureCatalog.StateOf(guardian, true, _ => IltTri.Off), IltTri.On, "a built-in feature is on with the ILT world"); + Check.Eq(IltFeatureCatalog.StateOf(guardian, false, _ => IltTri.On), IltTri.Unknown, "nothing is claimed off ILT"); + Check.Eq(IltFeatureCatalog.StateText(IltTri.Unknown), "checking", "unknown reads 'checking'"); + Check.Eq(IltFeatureCatalog.FellowshipMax(true), 29, "ILT fellowships hold 29"); + Check.Eq(IltFeatureCatalog.FellowshipMax(false), 9, "retail fellowships hold 9"); + } + + private static void ProfileJson() + { + string json = IltFeatureCatalog.BuildProfileJson(true, "Infinite \"Leaftide\"", false, "probe", + new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc), + key => key == IltFeature.FBlackjack ? IltTri.Off : IltTri.On); + bool ascii = true; + foreach (char c in json) if (c < 0x20 || c > 0x7E) ascii = false; + Check.True(ascii, "plain printable ASCII"); + + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + Check.True(root.GetProperty("ilt").GetBoolean(), "ilt"); + Check.Eq(root.GetProperty("world").GetString(), "Infinite \"Leaftide\"", "quotes in the world name survive"); + Check.Eq(root.GetProperty("checked").GetString(), "2026-10-13T21:25:37Z", "checked time in UTC"); + Check.Eq(root.GetProperty("features").GetArrayLength(), IltFeatureCatalog.All.Length, "every feature in the JSON"); + JsonElement fel = root.GetProperty("fellowship"); + Check.Eq(fel.GetProperty("maxMembers").GetInt32(), 29, "fellowship size"); + Check.Eq(fel.GetProperty("zoneShare").GetInt32(), 1, "Zone Share on (built in)"); + Check.Eq(fel.GetProperty("blackjack").GetInt32(), 0, "Fellowship Blackjack off (server bit)"); + + string off = IltFeatureCatalog.BuildProfileJson(false, "", false, "", DateTime.MinValue, _ => IltTri.On); + using JsonDocument d2 = JsonDocument.Parse(off); + Check.Eq(d2.RootElement.GetProperty("fellowship").GetProperty("maxMembers").GetInt32(), 9, "off ILT: retail size"); + Check.Eq(d2.RootElement.GetProperty("checked").GetString(), "", "never checked: empty time"); + } + + private static void QuestBonusJson() + { + var qb = new IltQuestBonusInfo(false, 2, 41, "2 completed, 1 incomplete", + new[] { "flag\"one", "flagTwo" }, new[] { "flagThree" }); + string json = IltFeatureCatalog.BuildProfileJson(true, "Infinite Leaftide", false, "probe", DateTime.MinValue, _ => IltTri.On, qb); + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement q = doc.RootElement.GetProperty("questBonus"); + Check.False(q.GetProperty("disabled").GetBoolean(), "enabled"); + Check.Eq(q.GetProperty("generation").GetInt32(), 2, "generation"); + Check.Eq(q.GetProperty("count").GetInt64(), 41L, "count"); + Check.Eq(q.GetProperty("status").GetString(), "2 completed, 1 incomplete", "status"); + Check.Eq(q.GetProperty("completed").GetArrayLength(), 2, "completed flags"); + Check.Eq(q.GetProperty("completed")[0].GetString(), "flag\"one", "quotes in a flag survive"); + Check.Eq(q.GetProperty("incomplete")[0].GetString(), "flagThree", "incomplete flags"); + Check.True(doc.RootElement.TryGetProperty("fellowship", out _), "the fellowship rules are still there"); + + string off = IltFeatureCatalog.BuildProfileJson(false, "", false, "", DateTime.MinValue, _ => IltTri.On, qb); + using JsonDocument d2 = JsonDocument.Parse(off); + Check.False(d2.RootElement.TryGetProperty("questBonus", out _), "off ILT: no /qb list"); + } + + private static unsafe void ServerTable() + { + Check.Eq(ServerInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not ours"); + Check.Eq(ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none"); + var t = (RynthIltServerApiV1*)ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 1); + Check.True(t != null && t->Version == 1 && t->StructSize == (uint)sizeof(RynthIltServerApiV1) && t->GetProfileJson != null, + "v1 is served and filled in"); + + // Before login the profile is the not-ILT default; the copy is NUL-terminated and valid JSON. + byte* buf = stackalloc byte[262144]; + int n = t->GetProfileJson(buf, 262144); + Check.True(n > 0 && n < 262144 && buf[n] == 0, "the default profile fits and is NUL-terminated"); + using JsonDocument doc = JsonDocument.Parse(Encoding.UTF8.GetString(buf, n)); + Check.False(doc.RootElement.GetProperty("ilt").GetBoolean(), "not an ILT world before login"); + Check.Eq(t->GetProfileJson(buf, 8), n, "too small: the length comes back"); + + ServerInterface.Release(); + Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)"); + Check.Eq(t->GetProfileJson(buf, 64), 0, "answers 0 after release"); + Check.Eq(ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 1), IntPtr.Zero, "not served after release"); + } + + private static unsafe void InterfaceWrite() + { + const string json = "{\"ilt\":true}"; + byte* small = stackalloc byte[4]; + small[0] = 0x55; + Check.Eq(ProfileInterface.Write(json, small, 4), json.Length, "too small: the length is returned"); + Check.Eq(small[0], (byte)0x55, "too small: nothing written"); + + byte* exact = stackalloc byte[json.Length]; + Check.Eq(ProfileInterface.Write(json, exact, json.Length), json.Length, "no room for the NUL: too small"); + + byte* big = stackalloc byte[64]; + int n = ProfileInterface.Write(json, big, 64); + Check.Eq(n, json.Length, "fits: the length without the NUL"); + Check.Eq(big[n], (byte)0, "NUL-terminated"); + Check.Eq(Encoding.UTF8.GetString(big, n), json, "the JSON copied whole"); + } +} diff --git a/Tools/RynthILT.Tests/FellowshipCommandTests.cs b/Tools/RynthILT.Tests/FellowshipCommandTests.cs new file mode 100644 index 0000000..fc772e9 --- /dev/null +++ b/Tools/RynthILT.Tests/FellowshipCommandTests.cs @@ -0,0 +1,97 @@ +using System; +using System.Linq; +using RynthCore.Plugin.RynthILT.IltFellowship; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// ILT's fellowship commands (IltFellowship/IltFellowshipCommands.cs, ACECustom /fship) and the +// "servercommands" format they are kept in (Plugins/Shared/ServerCommandShare.cs), checked together. +internal static class FellowshipCommandTests +{ + public static void Register(Runner r) + { + r.Add("ilt fellowship: the /fship list round-trips through the servercommands format", RoundTrip); + r.Add("ilt fellowship: chat lines quote multi-word names and need a name for create", Compose); + r.Add("ilt fellowship: bad commands and payloads are dropped", Rejects); + r.Add("ilt fellowship: RynthCore's verdict decides, else the world name", Active); + } + + private static void RoundTrip() + { + ServerCommandSet? set = ServerCommandShare.Parse(IltFellowshipCommands.Payload(active: true)); + Check.True(set != null, "parsed"); + Check.Eq(set!.Section, "fellowship", "section"); + Check.Eq(set.ServerId, "ilt", "server id"); + Check.Eq(set.ServerName, "Infinite Leaftide", "server name"); + Check.Eq(set.Commands.Count, IltFellowshipCommands.Commands.Count, "every command survives"); + for (int i = 0; i < set.Commands.Count; i++) + Check.Eq(set.Commands[i], IltFellowshipCommands.Commands[i], "command " + i); + Check.True(set.Commands.All(c => c.Command.StartsWith("/fship", StringComparison.Ordinal)), "all /fship"); + + ServerCommandSet? off = ServerCommandShare.Parse(IltFellowshipCommands.Payload(active: false)); + Check.True(off != null, "the clear parses"); + Check.Eq(off!.Commands.Count, 0, "the clear has no commands"); + } + + private static void Compose() + { + ServerCommand create = Find("Create"), invite = Find("Invite"), dismiss = Find("Dismiss"), list = Find("List nearby"); + Check.True(ServerCommandShare.Compose(create, "") == null, "create needs a name"); + Check.True(ServerCommandShare.Compose(create, " ") == null, "blank is no name"); + Check.Eq(ServerCommandShare.Compose(create, "Leaf"), "/fship create Leaf", "one word"); + Check.Eq(ServerCommandShare.Compose(create, " Leaf Hunters "), "/fship create \"Leaf Hunters\"", "quoted, spaces collapsed"); + Check.Eq(ServerCommandShare.Compose(invite, ""), "/fship add", "no name: the selected player"); + Check.Eq(ServerCommandShare.Compose(invite, "Raw Cigam"), "/fship add \"Raw Cigam\"", "multi-word player"); + Check.Eq(ServerCommandShare.Compose(dismiss, "Bo\"b\t"), "/fship remove Bob", "quotes and control characters dropped"); + Check.Eq(ServerCommandShare.Compose(list, "ignored"), "/fship list", "no argument taken"); + Check.True(dismiss.Confirm && Find("Disband").Confirm && Find("Leave").Confirm && Find("Invite landblock").Confirm, "risky ones ask"); + Check.False(invite.Confirm || list.Confirm || create.Confirm, "the rest don't"); + string longName = new string('x', 200); + Check.Eq(ServerCommandShare.CleanArgument(longName).Length, ServerCommandShare.MaxArgument, "argument capped"); + } + + private static void Rejects() + { + Check.True(ServerCommandShare.Parse(null) == null, "null"); + Check.True(ServerCommandShare.Parse("") == null, "empty"); + Check.True(ServerCommandShare.Parse("C\tX\t/fship\t\t\n") == null, "no S line"); + Check.True(ServerCommandShare.Parse("S\t\tilt\tILT\n") == null, "no section"); + + string payload = "S\tfellowship\tilt\tILT\n" + + "C\tNo slash\tfship list\t\t\n" + + "C\tSpace\t/ fship\t\t\n" + + "C\tQuote\t/fship add \"x\"\t\t\n" + + "C\t\t/fship list\t\tno label\n" + + "C\tLong\t/" + new string('a', ServerCommandShare.MaxCommand + 5) + "\t\t\n" + + "C\tShort\t/fship\t\n" + + "C\tGood\t/fship list\tzqA\ttip\n"; + ServerCommandSet? set = ServerCommandShare.Parse(payload); + Check.True(set != null, "parsed"); + Check.Eq(set!.Commands.Count, 1, "only the good command"); + Check.Eq(set.Commands[0].Flags, "A", "unknown flags dropped"); + + var many = Enumerable.Range(0, 40).Select(i => new ServerCommand("B" + i, "/fship list", "", "")); + string built = ServerCommandShare.Build(new ServerCommandSet("fellowship", "ilt", "ILT", many.ToList())); + Check.Eq(ServerCommandShare.Parse(built)!.Commands.Count, ServerCommandShare.MaxCommands, "capped"); + + string tabbed = ServerCommandShare.Build(new ServerCommandSet("fellowship", "ilt", "ILT", + new[] { new ServerCommand("A\tB", "/fship list", "", "line one\nline two") })); + ServerCommand c = ServerCommandShare.Parse(tabbed)!.Commands[0]; + Check.Eq(c.Label, "A B", "tab in a field becomes a space"); + Check.Eq(c.Tooltip, "line one line two", "newline in a field becomes a space"); + } + + private static void Active() + { + Check.True(IltFellowshipCommands.IsActive(true, "Coldeve"), "RynthCore says ILT"); + Check.False(IltFellowshipCommands.IsActive(false, "InfiniteLeaftide"), "RynthCore says not ILT"); + Check.True(IltFellowshipCommands.IsActive(null, "InfiniteLeaftide"), "no verdict yet: the world name"); + Check.False(IltFellowshipCommands.IsActive(null, "Coldeve"), "no verdict, another world"); + Check.False(IltFellowshipCommands.IsActive(null, null), "nothing known"); + } + + private static ServerCommand Find(string label) => + IltFellowshipCommands.Commands.First(c => c.Label == label); +} diff --git a/Tools/RynthILT.Tests/IltSettingsTests.cs b/Tools/RynthILT.Tests/IltSettingsTests.cs new file mode 100644 index 0000000..49be9d8 --- /dev/null +++ b/Tools/RynthILT.Tests/IltSettingsTests.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthILT.IltSettingsView; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// RynthILT's copy of the ILT settings (IltSettingsView/IltSettingsModel.cs): RynthCore's server +// list (plugin API v86, GetServerStateJson: verdict, override, reason), the Hub's feature read, the +// engine verdict the Hub follows (IltEngineVerdict), and the RynthCore commands the view sends. +internal static class IltSettingsTests +{ + public static void Register(Runner r) + { + r.Add("ilt settings: RynthCore's server list gives the ILT verdict, override and reason", ServerList); + r.Add("ilt settings: a list without ILT, or no list at all, reads as such", NoIlt); + r.Add("ilt settings: the Hub's feature read is published whole", FeatureRead); + r.Add("ilt settings: the Hub follows RynthCore's ILT verdict once one arrives", EngineVerdict); + r.Add("ilt settings: override and world-name commands are checked before sending", Commands); + r.Add("ilt settings: logout clears the copy", ClearOnLogout); + } + + // GetServerStateJson as RynthCore writes it (UI/Sections/ServerStateJson.cs, schema 1). + private const string State = + "{\"schema\":1,\"revision\":3,\"host\":\"infiniteleaftide.online\",\"world\":\"InfiniteLeaftide\",\"pick\":\"auto\"," + + "\"active\":\"ilt\",\"activeName\":\"Infinite Leaftide\",\"activePlugin\":\"RynthILT\",\"servers\":[" + + "{\"id\":\"ilt\",\"name\":\"Infinite Leaftide\",\"active\":true,\"detected\":false,\"force\":\"on\",\"builtIn\":true," + + "\"plugin\":\"RynthILT\",\"reason\":\"forced on for this character\"}," + + "{\"id\":\"aelrynth\",\"name\":\"Aelrynth\",\"active\":false,\"detected\":false,\"force\":\"auto\",\"builtIn\":true," + + "\"plugin\":\"\",\"reason\":\"not detected\"}]}"; + + private const string NoIltState = + "{\"schema\":1,\"revision\":1,\"active\":\"\",\"servers\":[" + + "{\"id\":\"aelrynth\",\"name\":\"Aelrynth\",\"active\":true,\"detected\":true,\"force\":\"auto\"}]}"; + + private static void ServerList() + { + IltEngineView? v = IltSettingsModel.FromServerState(EngineServerState.Parse(State)); + Check.True(v?.Server != null, "the ILT server is there"); + Check.Eq(v!.Server!.Name, "Infinite Leaftide", "name"); + Check.True(v.Server.Active, "active"); + Check.False(v.Server.Detected, "not detected (forced)"); + Check.Eq(v.Server.Force, "on", "override"); + Check.Eq(v.Server.Reason, "forced on for this character", "reason"); + + IltEngineView? odd = IltSettingsModel.FromServerState(EngineServerState.Parse( + "{\"schema\":1,\"servers\":[{\"id\":\"ILT\",\"force\":\"WEIRD\"}]}")); + Check.True(odd?.Server != null, "the id ignores case"); + Check.Eq(odd!.Server!.Force, "auto", "an unknown override shows as auto"); + Check.Eq(odd.Server.Name, "Infinite Leaftide", "a missing name gets the server's"); + Check.False(odd.Server.Active, "a missing flag is off"); + } + + private static void NoIlt() + { + IltEngineView? none = IltSettingsModel.FromServerState(EngineServerState.Parse(NoIltState)); + Check.True(none != null && none.Server == null, "a list without ILT says so (not 'waiting')"); + Check.True(IltSettingsModel.FromServerState(null) == null, "no list: nothing"); + Check.True(EngineServerState.Parse("") == null && EngineServerState.Parse("{\"schema\":2}") == null, "empty or another schema: no list"); + + var model = new IltSettingsModel(); + model.ApplyServerState(EngineServerState.Parse(State)); + model.ApplyServerState(null); + Check.True(model.Engine?.Server?.Active == true, "no answer keeps the last list"); + } + + private static void FeatureRead() + { + var model = new IltSettingsModel(); + var read = new IltFeatureView("Infinite Leaftide", "probe", "12:00:00", Checking: true, IltLike: true, + new[] { new KeyValuePair("bank", 1) }); + model.PublishFeatures(read); + Check.True(ReferenceEquals(model.Features, read), "published as is"); + model.PublishFeatures(null); + Check.True(model.Features == null, "cleared while there is no Hub"); + Check.Eq(IltSettingsModel.StateText(1), "on", "1 is on"); + Check.Eq(IltSettingsModel.StateText(0), "off", "0 is off (not unknown)"); + Check.Eq(IltSettingsModel.StateText(-1), "unknown", "-1 is unknown"); + } + + private static void EngineVerdict() + { + var model = new IltSettingsModel(); + try + { + IltEngineVerdict.Attach(model); + Check.False(IltEngineVerdict.Pushed, "nothing sent yet"); + Check.True(IltEngineVerdict.Active == null, "no verdict: RynthILT's own list decides"); + model.ApplyServerState(EngineServerState.Parse(State)); + Check.True(IltEngineVerdict.Pushed, "sent"); + Check.True(IltEngineVerdict.Active == true, "RynthCore says ILT"); + model.ApplyServerState(EngineServerState.Parse(NoIltState)); + Check.True(IltEngineVerdict.Pushed && IltEngineVerdict.Active == null, "a list without ILT gives no ILT verdict"); + model.Clear(); + Check.False(IltEngineVerdict.Pushed, "logout forgets it"); + } + finally { IltEngineVerdict.Attach(null); } + Check.True(IltEngineVerdict.Active == null, "detached"); + } + + private static void Commands() + { + Check.Eq(IltSettingsModel.ForceCommand("on"), "/rc server ilt on", "on"); + Check.Eq(IltSettingsModel.ForceCommand("auto"), "/rc server ilt auto", "auto"); + Check.Eq(IltSettingsModel.ForceCommand("maybe"), "", "unknown mode sends nothing"); + Check.Eq(IltSettingsModel.NamesListCommand, "/rc server names ilt", "the names are listed by RynthCore"); + + Check.Eq(IltSettingsModel.NamesCommand(true, " *Frost* ", out _), "/rc server names ilt add *Frost*", "add, trimmed"); + Check.Eq(IltSettingsModel.NamesCommand(false, "Infinite Leaftide", out _), "/rc server names ilt remove Infinite Leaftide", "remove"); + Check.Eq(IltSettingsModel.NamesCommand(true, "", out string e1), "", "empty refused"); + Check.True(e1.Length > 0, "with a reason"); + Check.Eq(IltSettingsModel.NamesCommand(true, new string('a', IltSettingsModel.MaxPattern + 1), out _), "", "too long refused"); + Check.Eq(IltSettingsModel.NamesCommand(true, "x\n/rc reload", out _), "", "a line break can't start a second command"); + Check.Eq(IltSettingsModel.NamesCommand(true, "a/b", out _), "", "no '/'"); + } + + private static void ClearOnLogout() + { + var model = new IltSettingsModel(); + model.ApplyServerState(EngineServerState.Parse(State)); + model.PublishFeatures(new IltFeatureView("w", "", "", false, true, Array.Empty>())); + Check.True(model.Engine != null && model.Features != null, "both copies"); + model.Clear(); + Check.True(model.Engine == null && model.Features == null, "cleared"); + } +} diff --git a/Tools/RynthILT.Tests/MoveTests.cs b/Tools/RynthILT.Tests/MoveTests.cs new file mode 100644 index 0000000..b81c615 --- /dev/null +++ b/Tools/RynthILT.Tests/MoveTests.cs @@ -0,0 +1,615 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using RynthCore.Loot; +using RynthCore.Plugin.RynthILT; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The ILT Hub's move out of RynthAi into RynthILT (2026-10-13): the saved data carried over from +// RynthAi's folders (copied, never moved), the RynthILT.Hub interface table RynthAi's Mini Remote +// reads, which "/ra" verbs RynthILT takes from RynthAi, and the host-backed object view that +// replaced RynthAi's WorldObjectCache. +internal static class MoveTests +{ + public static void Register(Runner r) + { + r.Add("move: a character's RynthAi ILT Hub files are copied, the RynthAi copies left alone", MigratesCharacter); + r.Add("move: migration never overwrites RynthILT's files and runs once", MigrationIdempotent); + r.Add("move: the pre-per-server ACEmulator folder is found too", MigratesFromAceEmulatorFolder); + r.Add("move: shared Hub profiles and aug costs are copied once", MigratesShared); + r.Add("move: a migration copy that fails is reported (log + chat) and the shared ones retried", MigrationFailuresReported); + r.Add("move: a failed Hub save is reported once and retried", StoreSaveFailureReported); + r.Add("move: an unfinished copy blocks the character's Hub writes until the retry copies the original", PendingMigrationNeverShadowed); + r.Add("move: an old ilt-hub.json loads into RynthILT's state (ILT parts kept)", LegacyStateLoads); + r.Add("move: RynthAi's \"/ra\" verbs RynthILT takes (and the ones it leaves)", VerbRouting); + r.Add("move: item classes from the client's item type (the gear tools' checks)", Classification); + r.Add("move: the interface structs have the agreed layout", InterfaceLayout); + r.Add("move: server-list status lines", DescribeLines); + r.Add("move: off ILT nothing is sent, no tab or section shows; on ILT the login probe runs", DormantOffIlt); + r.Add("move: the charms JSON for RynthILT.Data readers carries the Guardian Hands", CharmsReaderJson); + r.Add("move: Character redirects to RynthOracle; Charms and Banking stay RynthILT's tabs", MovedSections); + r.Add("sections: RynthILT's manifest (rates, /fship, /qb, and the ILT tabs it shows) is valid schema-1 JSON the engine places", SectionsManifest); + // Last: Release() switches the table off for the rest of the process. + r.Add("move: the RynthILT.Hub table: query, functions, release", HubTable); + } + + private static string Root(string name) + { + string dir = Path.Combine(Program.TempRoot, "move-" + name); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + IltMigration.LegacyProfilesBase = Path.Combine(dir, "RynthAi", "SettingsProfiles"); + IltMigration.LegacySharedRoot = Path.Combine(dir, "RynthAi"); + return dir; + } + + private const string LegacyHubJson = """ + { + "SchemaVersion": 1, + "ForceLeaftideFeatures": false, + "UbSidecarsImported": true, + "Bank": { "Pyreals": 1234567, "Luminance": 89, "EnlightenedCoins": 42, "AutoRefreshSeconds": 300 }, + "Pet": { "HealingEnabled": true, "HealPetName": "Healing Buddy", "PetLog": ["Fire Banshee"], "ShinyLog": [] }, + "Character": { + "QuestFilter": "temple", "QbFilter": "wait", "QuestFavorites": ["foo"], + "AttrOrder": ["qui","coo","str","end","foc","sel","hea","sta","man"], "AttrRaiseStats": ["qui"], + "AugTargets": { "war": 1800 } + }, + "Gear": { "AutoClap": true, "LastUsdPath": "C:\\vt\\x.usd", "LastEquipProfile": "Melee" }, + "Guardian": { "AutoHandIn": true, "TurnInCounts": { "Strength": 3 } } + } + """; + + private static string MakeLegacyChar(string world, string charName, bool withProfile = true) + { + string dir = Path.Combine(IltMigration.LegacyProfilesBase, IltMigration.RynthAiSafeName(world), IltMigration.RynthAiSafeName(charName)); + Directory.CreateDirectory(Path.Combine(dir, "ilt-hub-profiles")); + File.WriteAllText(Path.Combine(dir, "ilt-hub.json"), LegacyHubJson); + File.WriteAllText(Path.Combine(dir, "ilt-hub-transactions.json"), "[{\"Type\":\"Received\",\"Currency\":\"Pyreals\",\"Amount\":5}]"); + File.WriteAllText(Path.Combine(dir, "ilt-hub-profiles", "farm.json"), "{\"SchemaVersion\":1}"); + if (withProfile) + { + File.WriteAllText(Path.Combine(dir, "active_profile.txt"), "Melee"); + File.WriteAllText(Path.Combine(dir, "Melee.json"), + "{\"MetaDebug\":false,\"FeatureServerNames\":[\"InfiniteLeaftide\",\"*Leaftide*\",\"MyShard\"],\"ForceServerFeatures\":true}"); + File.WriteAllText(Path.Combine(dir, "Default.json"), "{\"FeatureServerNames\":[\"Unused\"]}"); + } + return dir; + } + + private static void MigratesCharacter() + { + string root = Root("char"); + string legacy = MakeLegacyChar("Infinite Leaftide", "Sir Tester"); + string before = File.ReadAllText(Path.Combine(legacy, "ilt-hub.json")); + var settings = new IltSettings(); + string dest = Path.Combine(root, "RynthILT", "Infinite Leaftide", "Sir Tester"); + + var done = IltMigration.MigrateCharacter(dest, "Infinite Leaftide", "Sir Tester", settings, out bool force); + Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "ilt-hub.json -> hub.json"); + Check.Eq(File.ReadAllText(Path.Combine(dest, IltHubStore.StateFile)), before, "copied byte for byte"); + Check.True(File.Exists(Path.Combine(dest, IltHubStore.TransactionsFile)), "transactions copied"); + Check.True(File.Exists(Path.Combine(dest, IltHubStore.ProfilesFolder, "farm.json")), "per-character Hub profiles copied"); + Check.True(File.Exists(Path.Combine(legacy, "ilt-hub.json")) && File.Exists(Path.Combine(legacy, "ilt-hub-transactions.json")), + "RynthAi's files are still there (copy, not move)"); + Check.True(settings.ServerNames.Contains("MyShard"), "the active profile's server names are added"); + Check.False(settings.ServerNames.Contains("Unused"), "only the ACTIVE profile is read"); + Check.Eq(settings.ServerNames.Count(n => n.Equals("InfiniteLeaftide", StringComparison.OrdinalIgnoreCase)), 1, "no duplicates"); + Check.True(force, "\"Force enable\" carries over as Treat this world as ILT"); + Check.True(done.Count >= 4, "the log line lists what was carried over: " + string.Join(", ", done)); + } + + private static void MigrationIdempotent() + { + string root = Root("idem"); + string legacy = MakeLegacyChar("InfiniteLeaftide", "Again", withProfile: false); + string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Again"); + Directory.CreateDirectory(dest); + File.WriteAllText(Path.Combine(dest, IltHubStore.TransactionsFile), "[]"); // RynthILT already has one + var settings = new IltSettings(); + + IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Again", settings, out bool force); + Check.Eq(File.ReadAllText(Path.Combine(dest, IltHubStore.TransactionsFile)), "[]", "an existing RynthILT file is never overwritten"); + Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "the missing hub.json is still copied"); + Check.False(force, "no profile, no override"); + + File.WriteAllText(Path.Combine(legacy, "ilt-hub.json"), "{\"Bank\":{\"Pyreals\":1}}"); + var second = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Again", settings, out _); + Check.Eq(second.Count, 0, "once hub.json exists the character is never migrated again"); + Check.False(File.ReadAllText(Path.Combine(dest, IltHubStore.StateFile)).Contains("\"Pyreals\":1}"), "later RynthAi edits don't overwrite RynthILT's state"); + + var none = IltMigration.MigrateCharacter(Path.Combine(root, "RynthILT", "X", "Nobody"), "X", "Nobody", settings, out _); + Check.Eq(none.Count, 0, "a character RynthAi never saw: nothing to do"); + Check.False(Directory.Exists(Path.Combine(root, "RynthILT", "X", "Nobody")), "and no folder is made for it"); + } + + private static void MigratesFromAceEmulatorFolder() + { + string root = Root("ace"); + MakeLegacyChar("ACEmulator", "Old Timer", withProfile: false); + var settings = new IltSettings(); + string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Old Timer"); + Check.NotNull(IltMigration.FindLegacyCharFolder("InfiniteLeaftide", "Old Timer"), "the world folder is missing, ACEmulator\\ is used"); + IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Old Timer", settings, out _); + Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "copied from the ACEmulator folder"); + Check.Eq(IltMigration.RynthAiSafeName("Sir O'Neil-Smith"), "Sir_O'Neil-Smith", "RynthAi's folder names keep ' and - only"); + } + + private static void MigratesShared() + { + string root = Root("shared"); + Directory.CreateDirectory(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles")); + File.WriteAllText(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles", "team.json"), "{}"); + File.WriteAllText(Path.Combine(IltMigration.LegacySharedRoot, "ilt-aug-costs.json"), "{\"x\":1}"); + var settings = new IltSettings(); + string dest = Path.Combine(root, "RynthILT"); + + var done = IltMigration.MigrateShared(settings, dest); + Check.True(File.Exists(Path.Combine(dest, "Profiles", "team.json")), "shared profiles copied"); + Check.True(File.Exists(Path.Combine(dest, "ilt-aug-costs.json")), "aug costs copied"); + Check.True(settings.SharedFilesMigrated, "marked done in the settings"); + Check.Eq(done.Count, 2, "both reported"); + File.Delete(Path.Combine(dest, "ilt-aug-costs.json")); + Check.Eq(IltMigration.MigrateShared(settings, dest).Count, 0, "once only"); + Check.False(File.Exists(Path.Combine(dest, "ilt-aug-costs.json")), "a file deleted afterwards isn't brought back"); + } + + // A copy that fails (here: the RynthAi file held open by another program) is never silent: it + // is logged and queued for chat with the reason, the rest still copies, and the shared files + // aren't marked done so the next login tries again. + private static void MigrationFailuresReported() + { + string root = Root("fail"); + DataWriteGuard.Reset(); + string legacy = MakeLegacyChar("InfiniteLeaftide", "Locked Out"); + string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Locked Out"); + var settings = new IltSettings(); + List done; + using (new FileStream(Path.Combine(legacy, "ilt-hub-transactions.json"), FileMode.Open, FileAccess.Read, FileShare.None)) + done = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Locked Out", settings, out _); + Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "the other files are still copied"); + Check.False(File.Exists(Path.Combine(dest, IltHubStore.TransactionsFile)), "the held file isn't"); + Check.True(done.Any(l => l.Contains("NOT copied") && l.Contains(legacy)), "the log line says so and where the originals are: " + string.Join(", ", done)); + Check.Eq(DataWriteGuard.PendingCount, 1, "one chat line queued (shown on ILT)"); + var lines = new List(); + DataWriteGuard.DrainChat(lines.Add); + Check.True(lines.Count == 1 && lines[0].StartsWith("[RynthILT]", StringComparison.Ordinal) + && lines[0].Contains("ilt-hub-transactions.json") && lines[0].Contains("another program"), + "it names the file and the reason: " + string.Join(" | ", lines)); + + DataWriteGuard.Reset(); + Directory.CreateDirectory(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles")); + File.WriteAllText(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles", "team.json"), "{}"); + string aug = Path.Combine(IltMigration.LegacySharedRoot, "ilt-aug-costs.json"); + File.WriteAllText(aug, "{\"x\":1}"); + string sharedDest = Path.Combine(root, "RynthILT"); + using (new FileStream(aug, FileMode.Open, FileAccess.Read, FileShare.None)) + done = IltMigration.MigrateShared(settings, sharedDest); + Check.False(settings.SharedFilesMigrated, "a failed shared copy isn't marked done"); + Check.True(done.Any(l => l.Contains("NOT copied")), "and is reported: " + string.Join(", ", done)); + Check.True(DataWriteGuard.PendingCount >= 1, "in chat too"); + done = IltMigration.MigrateShared(settings, sharedDest); + Check.True(File.Exists(Path.Combine(sharedDest, "ilt-aug-costs.json")), "the next login copies it"); + Check.True(settings.SharedFilesMigrated, "then it is marked done"); + Check.Eq(done.Count, 1, "only the missing file is copied the second time: " + string.Join(", ", done)); + DataWriteGuard.Reset(); + } + + // A character whose ilt-hub.json couldn't be copied (held open by another program): the Hub + // runs from the RynthAi original read-only (or the defaults), writes no hub.json, bank log or + // per-character profile there, the pending mark survives a restart, and the next attempt copies + // the original byte for byte - never shadowed by a fresh file. + private static void PendingMigrationNeverShadowed() + { + string root = Root("pending"); + DataWriteGuard.Reset(); + string legacy = MakeLegacyChar("InfiniteLeaftide", "Held Open"); + string legacyHub = Path.Combine(legacy, "ilt-hub.json"); + string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Held Open"); + string hubJson = Path.Combine(dest, IltHubStore.StateFile); + var settings = new IltSettings(); + + // Held open by another program: neither copied nor readable. + using (var held = new FileStream(legacyHub, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + { + var done = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Held Open", settings, out _); + Check.False(File.Exists(hubJson), "the held ilt-hub.json isn't copied"); + Check.True(IltMigration.IsPending(settings, dest), "the character is marked pending"); + Check.True(done.Any(l => l.Contains("NOT copied")), "and the log says so: " + string.Join(", ", done)); + + var store = new IltHubStore(default, dest) + { + WritesBlocked = () => IltMigration.IsPending(settings, dest), + LegacyFolder = legacy, + }; + IltHubState state = store.LoadState(); + Check.Eq(state.Bank.Pyreals, 0L, "unreadable: the Hub runs from the defaults"); + state.Bank.Pyreals = 1; + store.SaveStateIfDirty(state); + Check.False(File.Exists(hubJson), "no hub.json is written while the copy is unfinished"); + Check.False(store.SaveProfile(state, "mine", shared: false, out string why), "nor a per-character profile"); + Check.True(why.Contains("RynthAi"), "with the reason: " + why); + Check.True(store.SaveProfile(state, "team-" + Guid.NewGuid().ToString("N"), shared: true, out _), "shared profiles still save"); + + // A second login while still held: still pending, still nothing written. + IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Held Open", settings, out _); + Check.True(IltMigration.IsPending(settings, dest) && !File.Exists(hubJson), "still pending, still no hub.json"); + } + + // Readable again but not yet retried: a Hub started now reads the original, still writes nothing. + var readOnly = new IltHubStore(default, dest) + { + WritesBlocked = () => IltMigration.IsPending(settings, dest), + LegacyFolder = legacy, + }; + IltHubState fromLegacy = readOnly.LoadState(); + Check.Eq(fromLegacy.Bank.Pyreals, 1234567L, "the Hub runs from the RynthAi original, read only"); + fromLegacy.Bank.Pyreals = 2; + readOnly.SaveStateIfDirty(fromLegacy); + Check.False(File.Exists(hubJson), "and still writes no hub.json"); + + // The mark is in settings.json, so a client restart still knows the copy is unfinished. + IltSettingsStore.Save(settings); + IltSettings reloaded = IltSettingsStore.Load(); + Check.True(IltMigration.IsPending(reloaded, dest), "pending survives a restart"); + + var finished = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Held Open", reloaded, out bool force); + Check.True(File.Exists(hubJson), "the next attempt copies it"); + Check.Eq(File.ReadAllText(hubJson), File.ReadAllText(legacyHub), "byte for byte: the original, not a fresh file"); + Check.False(IltMigration.IsPending(reloaded, dest), "no longer pending"); + Check.True(force, "the profile's Force enable still carries over on the retry"); + Check.True(finished.Any(l => l.Contains("complete")), "the log says it finished: " + string.Join(", ", finished)); + + var after = new IltHubStore(default, dest) { WritesBlocked = () => IltMigration.IsPending(reloaded, dest) }; + IltHubState loaded = after.LoadState(); + Check.Eq(loaded.Bank.Pyreals, 1234567L, "the restarted Hub loads the copied file"); + loaded.Bank.Pyreals = 7; + after.SaveStateIfDirty(loaded); + Check.True(File.ReadAllText(hubJson).Contains("\"Pyreals\": 7"), "and saves normally from then on"); + File.Delete(Path.Combine(IltSettingsStore.Folder, IltSettingsStore.FileName)); + DataWriteGuard.Reset(); + } + + // RynthILT's own saves report a failure (DataWriteGuard) and try again on the next save. + private static void StoreSaveFailureReported() + { + string root = Root("storefail"); + DataWriteGuard.Reset(); + string blocker = Path.Combine(root, "NotAFolder"); + File.WriteAllText(blocker, "a file where the character folder should be"); + var store = new IltHubStore(default, blocker); + var state = new IltHubState(); + store.SaveStateIfDirty(state); + Check.Eq(DataWriteGuard.PendingCount, 1, "the failed Hub save is queued for chat"); + store.SaveStateIfDirty(state); + Check.Eq(DataWriteGuard.PendingCount, 1, "once per folder, not every retry"); + File.Delete(blocker); + store.SaveStateIfDirty(state); + Check.True(File.Exists(Path.Combine(blocker, IltHubStore.StateFile)), "the next save retries and works"); + DataWriteGuard.Reset(); + } + + private static void LegacyStateLoads() + { + string root = Root("state"); + string dir = Path.Combine(root, "char"); + Directory.CreateDirectory(dir); + File.WriteAllText(Path.Combine(dir, IltHubStore.StateFile), LegacyHubJson); + var store = new IltHubStore(default, dir); + var s = store.LoadState(); + Check.Eq(s.Bank.Pyreals, 1234567L, "bank balances"); + Check.Eq(s.Bank.AutoRefreshSeconds, 300, "bank settings"); + Check.Eq(s.Pet.PetLog.FirstOrDefault(), "Fire Banshee", "the /pets log (an ILT part of the Pet section)"); + Check.Eq(s.Character.QbFilter, "wait", "the /qb filter"); + Check.Eq(s.Character.AttrOrder.FirstOrDefault(), "qui", "the attribute raiser's order"); + Check.Eq(s.Character.AugTargets["war"], 1800, "aug targets"); + Check.True(s.Gear.AutoClap && s.Gear.LastEquipProfile == "Melee", "gear settings"); + Check.True(s.Guardian.AutoHandIn && s.Guardian.TurnInCounts["Strength"] == 3, "guardian settings"); + Check.True(s.UbSidecarsImported, "the UB import isn't redone"); + + store.SaveStateIfDirty(s); + string saved = File.ReadAllText(Path.Combine(dir, IltHubStore.StateFile)); + Check.False(saved.Contains("HealPetName"), "the Pets tab's settings (RynthAi's now) aren't written back here"); + Check.False(saved.Contains("QuestFavorites"), "nor the Quests tab's"); + } + + private static void VerbRouting() + { + static bool Takes(string line) => RynthILTPlugin.IsIltVerb(line.Split(' ', StringSplitOptions.RemoveEmptyEntries)); + Check.True(Takes("hub bank"), "hub bank"); + Check.True(Takes("hub attr run"), "hub attr run"); + Check.True(Takes("hub refresh"), "hub refresh"); + Check.True(Takes("hub help"), "hub help (RynthILT prints the whole list)"); + Check.True(Takes("hub open banking show"), "hub open "); + Check.True(Takes("hub open guardian"), "hub open guardian (the engine panel)"); + Check.True(Takes("hub open bounties"), "hub open bounties"); + Check.False(Takes("hub open pets"), "hub open pets is RynthAi's"); + Check.False(Takes("hub open quests hide"), "hub open quests is RynthAi's"); + Check.True(Takes("hub tab gear"), "hub tab "); + Check.False(Takes("hub tab quests"), "hub tab quests is RynthAi's"); + Check.False(Takes("hub tab remote"), "the Remote tab is RynthAi's"); + Check.False(Takes("hub"), "bare /ra hub toggles RynthAi's Mini Remote"); + Check.True(Takes("guardian handin"), "guardian"); + Check.True(Takes("bounty show") && Takes("bounties") && Takes("bountys"), "bounty, bounties, bountys"); + Check.True(Takes("rates reset"), "rates reset (the Mini Remote's Reset XP)"); + Check.False(Takes("quests refresh"), "/ra quests is RynthAi's"); + Check.False(Takes("pets show"), "/ra pets is RynthAi's"); + Check.False(Takes("start"), "anything else is RynthAi's"); + // The VTank hotkey verbs (RynthAi 2026-10-13, RynthAiPlugin.VTankHotkeys.cs) stay RynthAi's. + foreach (string vt in new[] { "vtkeys", "targetlock", "recharge", "lootthis", "meleelow", "navprio", "lootprio", "navlootprio", "setmetastate Default", "testitem", "propertydump" }) + Check.False(Takes(vt), $"{vt} is RynthAi's (VTank hotkeys)"); + } + + private static void Classification() + { + Check.Eq(IltObjects.ClassifyByItemType(0x00000800), AcObjectClass.Gem, "gem (aetheria)"); + Check.Eq(IltObjects.ClassifyByItemType(0x00000001), AcObjectClass.MeleeWeapon, "melee weapon"); + Check.Eq(IltObjects.ClassifyByItemType(0x00000100), AcObjectClass.MissileWeapon, "missile weapon"); + Check.Eq(IltObjects.ClassifyByItemType(0x00008000), AcObjectClass.WandStaffOrb, "caster"); + Check.Eq(IltObjects.ClassifyByItemType(0x40000000), AcObjectClass.Salvage, "salvage (white quartz)"); + Check.Eq(IltObjects.ClassifyByItemType(0x00001000), AcObjectClass.SpellComponent, "spell component"); + Check.Eq(IltObjects.ClassifyByItemType(0x00000200), AcObjectClass.Container, "pack"); + Check.Eq(IltObjects.ClassifyByItemType(0x00000010), AcObjectClass.Monster, "creature"); + Check.Eq(IltObjects.ClassifyByItemType(0x00000002 | 0x00000004), AcObjectClass.Armor, "armor wins over clothing"); + Check.Eq(IltObjects.ClassifyByItemType(0), AcObjectClass.Unknown, "no type yet"); + } + + private static unsafe void InterfaceLayout() + { + Check.Eq(sizeof(ServerHubTabV1), 24 + 32 + 4 + 4 + 4, "ServerHubTabV1: id, label, width, height, flags"); + Check.Eq((int)Marshal.OffsetOf(nameof(ServerHubTabV1.Flags)), 64, "ServerHubTabV1.Flags offset"); + // RynthILT.Hub grew on 2026-10-20 (append-only): readers accept any table at least BaseStructSize + // long (the first release's 9 functions) and check the appended ones with Has. + Check.Eq((int)RynthServerHubApiV1.BaseStructSize, 8 + 9 * IntPtr.Size, "RynthServerHubApiV1.BaseStructSize: the first release's 9 functions"); + Check.Eq(RynthServerHubApiV1.AllowSummonOnEmptyOffset, 8 + 9 * IntPtr.Size, "AllowSummonOnEmpty right after Command"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthServerHubApiV1.AllowSummonOnEmpty)), RynthServerHubApiV1.AllowSummonOnEmptyOffset, + "AllowSummonOnEmptyOffset is where the field really is"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthServerHubApiV1.GetSubTabs)), RynthServerHubApiV1.GetSubTabsOffset, + "GetSubTabsOffset is where the field really is"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthServerHubApiV1.GetSetting)), RynthServerHubApiV1.GetSettingOffset, + "GetSettingOffset is where the field really is"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthServerHubApiV1.SetSetting)), RynthServerHubApiV1.SetSettingOffset, + "SetSettingOffset is where the field really is"); + // SessionStatsMore was appended (2026-10-13); readers accept any table at least + // BaseStructSize long, so an older RynthAi still connects. + // VaultedDungeonsEnabled was appended (2026-10-18): the Vaulted Dungeons master switch. + // BackAwayFrom was appended (2026-10-20): the generic back-away RynthILT's Handler ring evade asks for. + // SetPlayerCounter too (2026-10-20): the T11 wield counters RynthILT reads from /aug. + Check.Eq(sizeof(RynthAiHubApiV1), 8 + 14 * IntPtr.Size, "RynthAiHubApiV1: header + 14 functions"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthAiHubApiV1.SetPlayerCounter)), RynthAiHubApiV1.SetPlayerCounterOffset, + "SetPlayerCounterOffset is where the field really is"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthAiHubApiV1.BackAwayFrom)), RynthAiHubApiV1.BackAwayFromOffset, + "BackAwayFromOffset is where the field really is"); + Check.Eq((int)RynthAiHubApiV1.BaseStructSize, 8 + 10 * IntPtr.Size, "RynthAiHubApiV1.BaseStructSize: the first release's 10 functions"); + Check.Eq(RynthAiHubApiV1.SessionStatsMoreOffset, (int)RynthAiHubApiV1.BaseStructSize, "SessionStatsMore right after the base table"); + Check.Eq(RynthAiHubApiV1.VaultedDungeonsEnabledOffset, 8 + 11 * IntPtr.Size, "VaultedDungeonsEnabled right after SessionStatsMore"); + Check.Eq((int)Marshal.OffsetOf(nameof(RynthAiHubApiV1.VaultedDungeonsEnabled)), RynthAiHubApiV1.VaultedDungeonsEnabledOffset, + "VaultedDungeonsEnabledOffset is where the field really is"); + Check.Eq(sizeof(QuestFlagV1), 24, "QuestFlagV1"); + Check.Eq(sizeof(QuestStatusV1), 16, "QuestStatusV1"); + Check.Eq(RynthIltHub.InterfaceName, "RynthILT.Hub", "interface name"); + // The hub split into the neutral RynthServer.Hub (RynthServerHubApi.cs) on 2026-10-21: the ids are + // the wire format and kept their values. + Check.Eq(RynthServerHubApiV1.InterfaceName, "RynthServer.Hub", "the neutral interface name"); + Check.Eq(string.Join(",", RynthServerHub.SectionRemoteBank, RynthServerHub.SectionRemoteGuardian, RynthServerHub.SectionRemoteStats, + RynthServerHub.SectionRemoteOptions, RynthServerHub.SectionPetCharms, RynthServerHub.SectionPetCapture, + RynthServerHub.SectionPetLogs, RynthServerHub.SectionServerStatus, RynthServerHub.SectionServerMenu), + "remote-bank,remote-guardian,remote-stats,remote-options,pets-charms,pets-capture,pets-logs,ilt-status,server-menu", + "section ids unchanged"); + Check.Eq(string.Join(",", RynthServerHub.TabParentPets, RynthServerHub.TextSessionReport, RynthServerHub.TextServerId, + RynthServerHub.FeatureQuests, RynthServerHub.SettingVaultedDungeons), + "pets,session-report,server-id,quests,vaulted-dungeons", "tab, text, feature and setting ids unchanged"); + Check.Eq((RynthServerHub.TabShown, RynthServerHub.TabAvailable), (1u, 2u), "tab flags unchanged"); + Check.Eq(RynthAiHubApiV1.InterfaceName, "RynthAi.Hub", "RynthAi's interface name"); + } + + private static void DescribeLines() + { + var s = new IltSettings(); + Check.True(ServerFeatureGate.Describe("InfiniteLeaftide", s, false).Contains("ON - matches 'InfiniteLeaftide'"), "on by name"); + Check.True(ServerFeatureGate.Describe("Aelrynth", s, true).Contains("Treat this world as ILT"), "on by the override"); + Check.True(ServerFeatureGate.Describe("Aelrynth", s, false).Contains("OFF"), "off"); + Check.True(ServerFeatureGate.Describe("", s, false).Contains("not logged in"), "before login"); + } + + private static IltHubController NewHub(string world, string folder) + { + RynthCore.RynthAiHostTests.Fakes.FakeHost.Reset(); + RynthCore.RynthAiHostTests.Fakes.FakeHost.WorldName = world; + var host = RynthCore.RynthAiHostTests.Fakes.FakeHost.Create(0x50000F01); + string dir = Path.Combine(Program.TempRoot, "move-" + folder); + Directory.CreateDirectory(dir); + return new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host)); + } + + private static void TickFor(IltHubController hub, int ms) + { + var until = DateTime.UtcNow.AddMilliseconds(ms); + while (DateTime.UtcNow < until) { hub.Tick(); System.Threading.Thread.Sleep(50); } + } + + /// + /// The charms JSON behind "RynthILT.Data" is valid JSON; on ILT it has a "hands" array (empty + /// with no hand carried) that the shared reader parses, off ILT it has none and still parses. + /// + private static void CharmsReaderJson() + { + var on = NewHub("InfiniteLeaftide", "charms-on"); + string json = on.CharmsTab.BuildReaderJson(); + using (var doc = System.Text.Json.JsonDocument.Parse(json)) + Check.True(doc.RootElement.TryGetProperty("hands", out var hands) && hands.GetArrayLength() == 0, + "on ILT: an empty hands array with no Guardian Hand carried"); + Check.True(json.All(c => c < 128), "ASCII only"); + var view = IltCharmsView.Parse(json); + Check.True(view.Loaded && view.Hands.Count == 0, "the shared reader takes it"); + + var withHands = IltCharmsView.Parse("{\"available\":true,\"charms\":[],\"hands\":[" + + "{\"id\":1234,\"name\":\"Guardian Hand\",\"active\":\"on\",\"server\":\"off\"},{\"id\":0,\"name\":\"no id\"}]}"); + Check.Eq(withHands.Hands.Count, 1, "a hand without an id is skipped (nothing to toggle)"); + Check.True(withHands.Hands[0] == new IltHandRow(1234, "Guardian Hand", "on", "off"), "id, name, active, server"); + + var off = NewHub("Aeshnidae", "charms-off"); + string offJson = off.CharmsTab.BuildReaderJson(); + using (var doc = System.Text.Json.JsonDocument.Parse(offJson)) + Check.False(doc.RootElement.TryGetProperty("hands", out _), "off ILT: no hands"); + Check.True(IltCharmsView.Parse(offJson).Hands.Count == 0, "and the reader shows none"); + } + + /// The Character tab moved out (2026-10-13); every other ILT tab is still RynthILT's. + private static void MovedSections() + { + Check.Eq(IltSections.MovedCommand(IltSection.Character), IltSections.OracleCharacterCommand, "Character -> RynthOracle Character"); + foreach (var kept in new[] { IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games }) + { + Check.True(IltSections.MovedCommand(kept) == null, $"{IltSections.Label(kept)} is still RynthILT's"); + Check.True(IltSections.IsTab(kept), $"{IltSections.Label(kept)} is a Mini Remote tab"); + } + Check.True(IltSections.MovedCommand(IltSection.VaultedDungeons) == null && IltSections.IsTab(IltSection.VaultedDungeons), + "Vaulted Dungeons is a RynthILT tab (shown only with the master switch, VaultedDungeonsTests)"); + Check.True(IltSections.Tabs.SequenceEqual(new[] { IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, IltSection.VaultedDungeons }), + "the tab list is Banking, Gear, Charms, Games, Vaulted Dungeons"); + Check.False(IltSections.IsTab(IltSection.Character) || IltSections.IsTab(IltSection.Guardian), "Character and the Guardian aren't tabs"); + Check.True(IltSections.TryParse("char", out IltSection c) && c == IltSection.Character, "old Character names still parse (for the redirect)"); + Check.Eq(IltSections.OracleCharacterCommand, "/ro character", "Oracle command"); + } + + /// + /// RynthILT's RynthPluginGetSectionsJson: schema 1 (UI/Sections/SectionManifest.cs in RynthCore), + /// every view an ILT one, each surface one RenderEmbed answers. + /// + private static void SectionsManifest() + { + // No Hub (before the character's name is known): the always-there views only. + string bare = IltSectionsManifest.Build(IltSectionsManifest.TabsOf(null)); + using var doc = System.Text.Json.JsonDocument.Parse(bare); + var root = doc.RootElement; + Check.Eq(root.GetProperty("version").GetInt32(), 1, "schema 1"); + var sections = root.GetProperty("sections"); + Check.Eq(sections.GetArrayLength(), 2, "two sections of RynthILT's own"); + Check.Eq(sections[0].GetProperty("id").GetString(), "quests", "a Quests section (the /qb list)"); + Check.Eq(sections[1].GetProperty("id").GetString(), "games", "and Games (moved from RynthAi with the tabs)"); + var surfaces = new System.Collections.Generic.List(); + foreach (var c in root.GetProperty("contributions").EnumerateArray()) + { + Check.Eq(c.GetProperty("server").GetString(), "ilt", "an Infinite Leaftide view"); + surfaces.Add(c.GetProperty("surface").GetString() ?? ""); + } + Check.True(surfaces.SequenceEqual(new[] { RynthILTPlugin.RatesSurface, RynthILTPlugin.FellowshipSurface, RynthILTPlugin.QuestBonusSurface, + RynthILTPlugin.DynamicStampsSurface }), + "rates, fellowship, quest bonus, Dynamic Stamps (from RynthOracle 2026-10-21): " + string.Join(",", surfaces)); + Check.True(surfaces.All(s => s.StartsWith("section:ilt-", StringComparison.Ordinal) && s.Length <= 64), "short section:ilt-* surfaces"); + Check.True(bare.All(ch => ch < 128), "ASCII only"); + + // The Mini Remote ILT tabs the Hub shows (RynthAi listed them until 2026-10-20): Gear not reported yet, + // Games hidden, Charms and Banking shown. + var tabs = new[] + { + new IltSectionsManifest.Tab("banking", 560, 520, Shown: true, Available: true), + new IltSectionsManifest.Tab("gear", 560, 520, Shown: true, Available: false), + new IltSectionsManifest.Tab("charms", 560, 520, Shown: true, Available: true), + new IltSectionsManifest.Tab("games", 520, 440, Shown: false, Available: false), + new IltSectionsManifest.Tab("character", 520, 440, Shown: true, Available: true), + }; + string json = IltSectionsManifest.Build(tabs); + var m = RynthCore.Engine.UI.Sections.SectionManifestParser.Parse("RynthILT", json, out string error); + Check.Eq(error, string.Empty, "the engine's parser takes it"); + Check.Eq(m.Contributions.Length, 7, "rates, fellowship, /qb, Dynamic Stamps, Banking, Gear, Charms"); + var stamps = m.Contributions.Single(c => c.Surface == RynthILTPlugin.DynamicStampsSurface); + Check.True(stamps.Section == "quests" && stamps.Primary && stamps.Server == "ilt" && stamps.Label == "Dynamic Stamps", + "Dynamic Stamps: a page of RynthILT's Quests section, on ILT only"); + var gear = m.Contributions.Single(c => c.Surface == "section:gear"); + Check.True(gear.Section == "inventory" && !gear.Enabled && gear.Note.Length > 0, "Gear in Inventory, disabled with a note until reported"); + Check.True(m.Contributions.Any(c => c.Surface == "section:charms" && c.Enabled) && m.Contributions.Any(c => c.Surface == "section:banking" && c.Enabled), + "Charms and Banking stay RynthILT's tabs"); + Check.False(m.Contributions.Any(c => c.Surface == "section:games"), "a hidden tab isn't listed"); + Check.False(m.Contributions.Any(c => c.Surface == "section:character"), "Character moved out: never placed"); + var iltOn = new RynthCore.Engine.UI.Sections.ServerState("ilt", "Infinite Leaftide", true, true, RynthCore.Engine.UI.Sections.ServerForce.Auto, true, ""); + var on = RynthCore.Engine.UI.Sections.SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn }); + Check.True(on.Single(v => v.Id == "inventory").Panes.Any(p => p.Title == "Charms" && p.Contribution?.Plugin == "RynthILT"), + "on ILT the engine shows RynthILT's Charms in Inventory (drawn by RynthILT)"); + var off = RynthCore.Engine.UI.Sections.SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn with { Active = false } }); + Check.False(off.Single(v => v.Id == "inventory").Panes.Any(p => p.Title == "Charms"), "off ILT: none"); + Check.True(IltSectionsManifest.TryTabOf("section:banking", out IltSection bank) && bank == IltSection.Banking, "section:banking draws Banking"); + Check.False(IltSectionsManifest.TryTabOf("section:bank", out _), "only the tab's own id"); + Check.False(IltSectionsManifest.TryTabOf("section:pets", out _), "pets is RynthAi's"); + Check.False(IltSectionsManifest.TryTabOf("section:ilt-rates", out _), "not a tab"); + Check.True(RynthILTPlugin.IsParsedRemoteAction("servermenu") && RynthILTPlugin.IsParsedRemoteAction("ServerMenu") + && !RynthILTPlugin.IsParsedRemoteAction("prog"), "RynthCore's servermenu push is answered, never queued as a verb"); + } + + private static void DormantOffIlt() + { + var off = NewHub("Aeshnidae", "dormant"); + off.OnLoginComplete("Tester", forceFromMigration: false); + foreach (string line in new[] { "Your Pet Log:", "[BANK] Pyreals: 5", "Guardian of Strength tells you, \"x\"" }) off.OnChat(line); + TickFor(off, 6800); // past the 6 s login delay + Check.Eq(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Count, 0, "off ILT: no probe, no command at all"); + Check.False(off.Options.IsIltLikeWorld, "not an ILT world"); + foreach (var s in IltSections.Tabs) Check.False(off.TabShown(s), $"no {IltSections.Label(s)} tab"); + Check.False(off.RenderSection(RynthServerHub.SectionRemoteBank) || off.RenderSection(RynthIltHub.SectionQuestBonus) + || off.RenderSection(RynthServerHub.SectionPetLogs) || off.RenderSection(RynthServerHub.SectionRemoteGuardian) + || off.RenderSection(RynthServerHub.SectionServerMenu), "no ILT section draws (checked before any ImGui call)"); + Check.True(off.BuildProgressionJson().StartsWith("{\"available\":false"), "Progression: not available"); + off.OnLogout(); + + var on = NewHub("InfiniteLeaftide", "awake"); + on.OnLoginComplete("Tester", forceFromMigration: false); + TickFor(on, 6800); + Check.True(on.Options.IsIltLikeWorld, "InfiniteLeaftide is ILT"); + Check.True(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Count > 0, "on ILT the login probe asks the server"); + Check.False(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Any(c => c.Contains("/ilt features", StringComparison.OrdinalIgnoreCase)), + "the server is never asked for a feature list (the ILT profile is Rynth-side)"); + // Character moved out of the Mini Remote (RynthOracle's Character tab, Session Stats); + // Charms and Banking are Infinite Leaftide's own screens and stay RynthILT's tabs. + Check.False(on.TabShown(IltSection.Character), "Character is no Mini Remote tab any more"); + Check.Eq(on.TabShown(IltSection.Gear), on.Available, "Gear shows once the server features are known"); + Check.Eq(on.TabShown(IltSection.Charms), on.Available, "Charms too"); + on.OnLogout(); + + var forced = NewHub("Aeshnidae", "forced"); + forced.OnLoginComplete("Tester", forceFromMigration: true); + Check.True(forced.Options.IsIltLikeWorld, "a migrated \"Force enable\" makes the world ILT for this character"); + forced.OnLogout(); + } + + private static unsafe void HubTable() + { + Check.Eq(HubInterface.Query("RynthAi.Hub", 1), IntPtr.Zero, "another interface's name: not ours"); + Check.Eq(HubInterface.Query(RynthIltHub.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none"); + var t = (RynthServerHubApiV1*)HubInterface.Query(RynthIltHub.InterfaceName, 1); + Check.True(t != null, "v1 is served"); + Check.Eq(t->Version, 1u, "Version 1"); + Check.Eq(t->StructSize, (uint)sizeof(RynthServerHubApiV1), "StructSize"); + Check.True(t->IsServerWorld != null && t->GetFeature != null && t->GetRates != null && t->GetForceServer != null && t->SetForceServer != null + && t->GetTabs != null && t->RenderTab != null && t->RenderSection != null && t->Command != null + && t->AllowSummonOnEmpty != null && t->GetSubTabs != null && t->GetSetting != null && t->SetSetting != null, + "every function is filled in"); + Check.True(RynthServerHubApiV1.Has(t, RynthServerHubApiV1.GetSubTabsOffset), "the appended functions are inside StructSize"); + Check.Eq((IntPtr)t, HubInterface.Query(RynthIltHub.InterfaceName, 1), "the same table each time"); + Check.Eq((IntPtr)t, HubInterface.Query(RynthServerHubApiV1.InterfaceName, 1), + "and under the server-neutral name RynthAi asks the active server's owner for (RynthServer.Hub)"); + + // No plugin instance here (not logged in): every function answers "nothing". + Check.Eq(t->IsServerWorld(), 0, "not ILT before login"); + byte* key = stackalloc byte[] { (byte)'b', (byte)'a', (byte)'n', (byte)'k', 0 }; + Check.Eq(t->GetFeature(key), -1, "feature unknown before login"); + Check.Eq(t->GetTabs(null, 0), 0, "no tabs before login"); + Check.Eq(t->Command(key), 0, "no command taken before login"); + Check.Eq(t->AllowSummonOnEmpty(), 0, "no summon from empty before login"); + byte* pets = stackalloc byte[] { (byte)'p', (byte)'e', (byte)'t', (byte)'s', 0 }; + Check.Eq(t->GetSubTabs(pets, null, 0), 0, "no Pets sub-tabs before login"); + Check.Eq(t->GetSetting(pets), -1, "no setting offered before login"); + Check.Eq(t->SetSetting(pets, 1), 0, "and none taken"); + + HubInterface.Release(); + Check.Eq(t->Version, 0u, "Release zeroes Version (callers re-query)"); + Check.Eq(HubInterface.Query(RynthIltHub.InterfaceName, 1), IntPtr.Zero, "and nothing is served after shutdown"); + Check.Eq(t->IsServerWorld(), 0, "the old table stays callable and answers nothing"); + } +} diff --git a/Tools/RynthILT.Tests/PetAutomationTests.cs b/Tools/RynthILT.Tests/PetAutomationTests.cs new file mode 100644 index 0000000..659bafd --- /dev/null +++ b/Tools/RynthILT.Tests/PetAutomationTests.cs @@ -0,0 +1,189 @@ +using System; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// ACECustom's parts of RynthAi's Pets tab moved to RynthILT on 2026-10-20 (Hub/IltPetAutomation.cs): +// the pet charms, the summon-from-empty refill gate RynthAi's PetManager asks through RynthILT.Hub, +// siphon-lens auto-capture and the Breeding sub-tab offer. Their settings are copied once from the +// character's RynthAi miniremote.json (IltMigration.ImportRynthAiSettings). +internal static class PetAutomationTests +{ + private const uint Player = 0x50000A01; + private const uint Lens = 0x80000A02; + private const uint Mob = 0x80000A03; + private const uint Charm = 0x80000A04; + private const uint Lb = 0xA9B40000; + + public static void Register(Runner r) + { + r.Add("pets (RynthILT): summon from empty needs the opt-in, an active refill charm and the server's word; never off ILT", RefillGate); + r.Add("pets (RynthILT): auto-capture uses the lens on a weak creature in range only, and only when switched on", Capture); + r.Add("pets (RynthILT): the Breeding sub-tab is offered on ILT unless the server reports breeding off", BreedingSubTab); + r.Add("pets (RynthILT): off ILT the Pets sections draw nothing and nothing ticks", DormantOffIlt); + r.Add("migration: the Pets tab's ACECustom options come over from RynthAi's miniremote.json once", ImportsPetSettings); + } + + private static IltHubController NewHub(string world, string folder, Action? setup = null) + { + FakeHost.Reset(); + FakeHost.WorldName = world; + FakeHost.ContentsCalls = true; + FakeHost.WeaponCalls = true; // UseObject, RequestId, appraisal state + FakeHost.LiveObjectsCalls = true; + FakeHost.Names[Player] = "Petter"; + FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f); + setup?.Invoke(); + var host = FakeHost.Create(Player); + string dir = Path.Combine(Program.TempRoot, "pets-" + folder); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host)); + hub.OnLoginComplete("Petter", forceFromMigration: false); + return hub; + } + + private static void Carry(uint id, string name, uint wcid) + { + FakeHost.Names[id] = name; + FakeHost.ItemTypes[id] = 0x80; // misc + FakeHost.Containers[id] = Player; + FakeHost.Wcids[id] = wcid; + } + + private static void RefillGate() + { + var hub = NewHub("InfiniteLeaftide", "refill", () => FakeHost.Bools[(Player, IltInventory.BoolPyrealRefillActive)] = true); + var pets = hub.PetAutomation; + Check.False(pets.ComputeAllowSummonOnEmpty(), "not opted in: no summon from empty"); + hub.State.Pet.RefillFromEmpty = true; + Check.True(pets.ComputeAllowSummonOnEmpty(), "opted in, and the server stamped the refill bool (active and confirmed)"); + + var charmOnly = NewHub("InfiniteLeaftide", "refill-charm", () => + { + Carry(Charm, "Summon Essence Refill Charm", IltInventory.WcidSummonRefillCharm); + FakeHost.Strings[(Charm, IltInventory.StrUse)] = "Toggles the refill. Status: ON"; + }); + charmOnly.State.Pet.RefillFromEmpty = true; + Check.True(charmOnly.PetAutomation.RefillCharmActive(), "the carried charm reads ON"); + Check.False(charmOnly.PetAutomation.ComputeAllowSummonOnEmpty(), "but the server hasn't confirmed pet_refill: never spend"); + charmOnly.Options.Set(IltFeature.PetRefill, IltTri.On); + Check.True(charmOnly.PetAutomation.ComputeAllowSummonOnEmpty(), "confirmed: summon from empty"); + charmOnly.Tick(); + Check.True(charmOnly.PetAutomation.AllowSummonOnEmpty, "the tick caches it for RynthAi (RynthILT.Hub AllowSummonOnEmpty)"); + + var off = NewHub("Aeshnidae", "refill-off", () => FakeHost.Bools[(Player, IltInventory.BoolPyrealRefillActive)] = true); + off.State.Pet.RefillFromEmpty = true; + Check.False(off.PetAutomation.ComputeAllowSummonOnEmpty(), "off ILT: never"); + off.Tick(); + Check.False(off.PetAutomation.AllowSummonOnEmpty, "and nothing cached for RynthAi"); + } + + private static void Capture() + { + var hub = NewHub("InfiniteLeaftide", "capture", () => + { + Carry(Lens, "Flawed Siphon Lens", PetCaptureRules.Lenses[0].Wcid); + FakeHost.Names[Mob] = "Drudge Skulker"; + FakeHost.ItemTypes[Mob] = 0x10; // creature + FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f); // 3 m + FakeHost.TargetVitals[Mob] = (100, 100); + }); + var pets = hub.PetAutomation; + long now = Environment.TickCount64; // the chat replies time their back-off on the real clock + pets.TickCapture(now); + Check.Eq(FakeHost.Uses.Count, 0, "switched off: no lens used"); + Check.Eq(pets.CaptureStatus, "off", "status off"); + + hub.State.Pet.AutoCapture = true; + pets.TickCapture(now); + Check.Eq(FakeHost.Uses.Count, 0, "a full-health creature: no lens"); + Check.True(pets.CaptureStatus.Contains("Drudge Skulker") && pets.CaptureStatus.Contains("need"), "it says what it waits for"); + + FakeHost.TargetVitals[Mob] = (15, 100); + pets.TickCapture(now + 1000); + Check.Eq(FakeHost.Uses.Count, 1, "15%: the lens is used"); + Check.Eq(FakeHost.Uses[0], Lens, "the chosen lens"); + pets.TickCapture(now + 1500); + Check.Eq(FakeHost.Uses.Count, 1, "the cooldown holds the next use back"); + pets.OnChat("The creature is too strong to be siphoned."); + Check.True(pets.CaptureStatus.StartsWith("refused"), "a refusal is noted"); + + FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 110f, 0f); // 14 m + pets.TickCapture(now + 60_000); + Check.Eq(FakeHost.Uses.Count, 1, "out of range: no lens"); + + hub.Options.Set(RynthIltHub.FeatureMonsterCapture, IltTri.Off); + FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f); + pets.TickCapture(now + 120_000); + Check.Eq(FakeHost.Uses.Count, 1, "the server reports monster capture off: no lens"); + Check.True(pets.CaptureStatus.Contains("disabled"), "and says so"); + } + + private static void BreedingSubTab() + { + var on = NewHub("InfiniteLeaftide", "breed-on"); + var tabs = on.SubTabs(RynthServerHub.TabParentPets); + Check.Eq(tabs.Length, 1, "one Pets sub-tab on ILT"); + Check.Eq(tabs[0].Id, RynthIltHub.SectionPetBreeding, "Breeding, drawn as the pets-breeding section"); + Check.Eq(on.SubTabs("crafting").Length, 0, "nothing for another tab"); + on.Options.Set(RynthIltHub.FeaturePetBreeding, IltTri.Off); + Check.Eq(on.SubTabs(RynthServerHub.TabParentPets).Length, 0, "the server reports breeding off: none"); + + var off = NewHub("Aeshnidae", "breed-off"); + Check.Eq(off.SubTabs(RynthServerHub.TabParentPets).Length, 0, "off ILT: none"); + } + + private static void DormantOffIlt() + { + var off = NewHub("Aeshnidae", "dormant", () => + { + Carry(Lens, "Flawed Siphon Lens", PetCaptureRules.Lenses[0].Wcid); + FakeHost.Names[Mob] = "Drudge Skulker"; + FakeHost.ItemTypes[Mob] = 0x10; + FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f); + FakeHost.TargetVitals[Mob] = (1, 100); + }); + off.State.Pet.AutoCapture = true; + for (int i = 0; i < 5; i++) { off.Tick(); System.Threading.Thread.Sleep(60); } + Check.Eq(FakeHost.Uses.Count, 0, "off ILT the capture never ticks (no lens used)"); + Check.False(off.RenderSection(RynthServerHub.SectionPetCharms) || off.RenderSection(RynthServerHub.SectionPetCapture), + "the Pets sections draw nothing (checked before any ImGui call)"); + } + + private static void ImportsPetSettings() + { + string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Petter"); + Directory.CreateDirectory(legacy); + File.WriteAllText(Path.Combine(legacy, "Default.json"), "{}"); + File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyMiniRemoteFile), + "{ \"Pet\": { \"HealingEnabled\": true, \"UsePyrealRefillPath\": true, \"AutoCaptureEnabled\": true, \"CaptureLensIndex\": 3 } }"); + var state = new IltHubState(); + Check.False(state.Pet.RefillFromEmpty || state.Pet.AutoCapture, "RynthILT's defaults: both off"); + var lines = IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Petter"); + Check.True(state.RynthAiSettingsImported, "marked done"); + Check.True(state.Pet.RefillFromEmpty, "summon from empty came over"); + Check.True(state.Pet.AutoCapture, "auto-capture came over"); + Check.Eq(state.Pet.CaptureLens, 3, "the lens came over"); + Check.True(lines.Any(l => l.Contains("auto-capture on")), "and the log line says so"); + + state.Pet.AutoCapture = false; // changed in RynthILT afterwards + Check.Eq(IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Petter").Count, 0, "the second login does nothing"); + Check.False(state.Pet.AutoCapture, "RynthILT's own change stays"); + + var fresh = new IltHubState(); + IltMigration.ImportRynthAiSettings(fresh, "InfiniteLeaftide", "Nobody"); + Check.True(fresh.RynthAiSettingsImported && !fresh.Pet.AutoCapture && !fresh.Pet.RefillFromEmpty, + "a character without RynthAi files keeps the defaults (and is marked done)"); + + File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyMiniRemoteFile), "{ broken"); + var broken = new IltHubState(); + IltMigration.ImportRynthAiSettings(broken, "InfiniteLeaftide", "Petter"); + Check.True(broken.RynthAiSettingsImported && !broken.Pet.AutoCapture, "an unreadable miniremote.json: defaults, no exception"); + } +} diff --git a/Tools/RynthILT.Tests/PetCaptureRulesTests.cs b/Tools/RynthILT.Tests/PetCaptureRulesTests.cs new file mode 100644 index 0000000..3e523ce --- /dev/null +++ b/Tools/RynthILT.Tests/PetCaptureRulesTests.cs @@ -0,0 +1,109 @@ +// ACECustom MonsterCapture health / range / lens table — matches Source/ACE.Server/Entity/MonsterCapture.cs. +// Moved from RynthCore.RynthAiTests with the rules (RynthILT's IltPetCaptureRules since 2026-10-20). +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +internal static class PetCaptureRulesTests +{ + public static void Register(Runner r) + { + r.Add("pet capture: health gate matches ACECustom (≤20% or under 20 HP)", HealthGate); + r.Add("pet capture: Asheron's Lens bypasses the health gate", AsheronsBypass); + r.Add("pet capture: range is 5 m; dead creatures are never capturable", RangeAndDead); + r.Add("pet capture: lens WCIDs match PetGuideController", LensWcids); + r.Add("pet capture: a creature is left alone after 5 tries with no capture, then retried after the block", ThrottlePerTarget); + r.Add("pet capture: 15 lens uses with no capture anywhere trip the backstop; a success resets it", ThrottleBackstop); + } + + private static void HealthGate() + { + // Full health — refuse. + Check.False(PetCaptureRules.IsWeakEnough(100, 100), "100/100 too strong"); + Check.False(PetCaptureRules.IsWeakEnough(21, 100), "21% and ≥20 HP too strong"); + + // Fraction gate. + Check.True(PetCaptureRules.IsWeakEnough(20, 100), "20% exactly is allowed"); + Check.True(PetCaptureRules.IsWeakEnough(1, 100), "1% allowed"); + + // Absolute HP gate (high % but under 20 HP). + Check.True(PetCaptureRules.IsWeakEnough(15, 50), "15/50 = 30% but under 20 HP"); + Check.True(PetCaptureRules.IsWeakEnough(19, 19), "19/19 under 20 HP"); + + // Ratio-only path (no absolute HP): only the fraction half. + Check.True(PetCaptureRules.IsWeakEnoughRatio(0.20f), "ratio 0.20"); + Check.False(PetCaptureRules.IsWeakEnoughRatio(0.21f), "ratio 0.21"); + Check.False(PetCaptureRules.IsWeakEnoughRatio(0f), "ratio 0 = dead"); + Check.False(PetCaptureRules.IsWeakEnough(0, 100), "0 current = dead"); + } + + private static void AsheronsBypass() + { + var asheron = PetCaptureRules.LensAt(4); + Check.Eq(asheron.Wcid, 78780012u, "Asheron's WCID"); + Check.True(asheron.BypassesHealthGate, "bypasses health"); + Check.True(PetCaptureRules.CanAttempt(asheron, 100, 100), "full health ok for Asheron's"); + Check.False(PetCaptureRules.CanAttempt(asheron, 0, 100), "still not when dead"); + + var flawed = PetCaptureRules.LensAt(0); + Check.False(PetCaptureRules.CanAttempt(flawed, 100, 100), "Flawed refuses full health"); + Check.True(PetCaptureRules.CanAttempt(flawed, 10, 100), "Flawed at 10%"); + } + + private static void RangeAndDead() + { + Check.Eq(PetCaptureRules.CaptureRangeM, 5.0f, "5 m range"); + Check.True(PetCaptureRules.InRange(0), "at feet"); + Check.True(PetCaptureRules.InRange(5.0), "at 5 m"); + Check.False(PetCaptureRules.InRange(5.01), "past 5 m"); + Check.False(PetCaptureRules.InRange(-1), "unknown distance"); + } + + private static void LensWcids() + { + Check.Eq(PetCaptureRules.Lenses.Length, 5, "five selectable lenses"); + Check.Eq(PetCaptureRules.LensAt(0).Wcid, 78780001u, "Flawed"); + Check.Eq(PetCaptureRules.LensAt(1).Wcid, 78780002u, "Pristine"); + Check.Eq(PetCaptureRules.LensAt(2).Wcid, 78780003u, "Perfect"); + Check.Eq(PetCaptureRules.LensAt(3).Wcid, 78780010u, "Resonance"); + Check.Eq(PetCaptureRules.LensAt(4).Wcid, 78780012u, "Asheron's"); + Check.Eq(PetCaptureRules.LensNames.Length, PetCaptureRules.Lenses.Length, "combo labels match"); + } + + private static void ThrottlePerTarget() + { + var t = new PetCaptureThrottle(); + long now = 1000; + for (int i = 0; i < PetCaptureThrottle.MaxTriesPerTarget; i++) + { + Check.True(t.MayAttempt(7, now), $"try {i + 1} allowed"); + t.RecordAttempt(7, now); + now += 2500; + } + Check.False(t.MayAttempt(7, now), "5 tries used: blocked"); + Check.True(t.BlockedSecondsLeft(7, now) > 0, "block time left reported"); + Check.True(t.MayAttempt(8, now), "another creature is not blocked"); + Check.False(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs - 3000), "still blocked just before the block ends"); + Check.True(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 1), "block served: tries again"); + t.RecordAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 1); + Check.True(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 2), "a fresh set of tries after the block"); + } + + private static void ThrottleBackstop() + { + var t = new PetCaptureThrottle(); + long now = 0; + for (int i = 0; i < PetCaptureThrottle.MaxTriesWithoutSuccess; i++) + { + Check.False(t.Exhausted, $"not exhausted before use {i + 1}"); + t.RecordAttempt(100 + i, now); // a new creature each time: per-target never trips + now += 2500; + } + Check.True(t.Exhausted, "15 uses over many creatures, no capture: exhausted"); + Check.False(t.MayAttempt(999, now), "nothing more is allowed"); + t.RecordSuccess(); + Check.False(t.Exhausted, "a capture reply resets the backstop"); + Check.True(t.MayAttempt(100, now), "and the per-target blocks"); + } +} diff --git a/Tools/RynthILT.Tests/ProfileTests.cs b/Tools/RynthILT.Tests/ProfileTests.cs new file mode 100644 index 0000000..c6237e0 --- /dev/null +++ b/Tools/RynthILT.Tests/ProfileTests.cs @@ -0,0 +1,98 @@ +using System; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.RynthILT; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// RynthILT's "RynthServer.Profile" (ProfileInterface.cs): the same interface and JSON the server +// plugins serve, for "ilt", carrying Infinite Leaftide's tinkering salvage (Hub/IltSalvage.cs). +// The JSON is read back with the shared reader RynthAi's Crafting tab uses (EngineServerState.cs: +// ServerSalvageView.ParseList), so the rows it plans with are the ones checked here. 2026-10-15. +internal static unsafe class ProfileTests +{ + public static void Register(Runner r) + { + r.Add("profile: RynthILT serves RynthServer.Profile for ilt", Interface); + r.Add("profile: ILT's salvage reaches the Crafting tab's reader (Leather after the cap, jewelry stack)", Salvage); + r.Add("profile: ILT's trinkets reach the Crafting tab's reader (RynthAi's TinkerCatalog rule until 2026-10-20)", Trinkets); + } + + private static void Interface() + { + Check.Eq(ProfileInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not this table"); + Check.Eq(ProfileInterface.Query(RynthServerProfileApiV1.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none"); + var t = (RynthServerProfileApiV1*)ProfileInterface.Query(RynthServerProfileApiV1.InterfaceName, 1); + Check.True(t != null, "the table"); + Check.Eq(t->Version, RynthServerProfileApiV1.InterfaceVersion, "version"); + Check.Eq(t->StructSize, (uint)sizeof(RynthServerProfileApiV1), "struct size"); + Check.True(t->GetProfileJson != null, "GetProfileJson"); + + string json = ProfileInterface.CurrentJson(true, "InfiniteLeaftide"); + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + Check.Eq(root.GetProperty("schema").GetInt32(), RynthServerProfile.Schema, "schema"); + Check.Eq(root.GetProperty("id").GetString(), "ilt", "the engine's ILT id"); + Check.Eq(root.GetProperty("name").GetString(), "Infinite Leaftide", "name"); + Check.Eq(root.GetProperty("plugin").GetString(), "RynthILT", "plugin"); + Check.True(root.GetProperty("active").GetBoolean(), "active"); + Check.Eq(root.GetProperty("world").GetString(), "InfiniteLeaftide", "world"); + Check.Eq(root.GetProperty("hosts")[0].GetString(), "infiniteleaftide.online", "hosts from the csproj"); + Check.Eq(ProfileInterface.CurrentJson(true, "InfiniteLeaftide"), json, "unchanged state: the same JSON"); + Check.False(JsonDocument.Parse(ProfileInterface.CurrentJson(false, null)).RootElement.GetProperty("active").GetBoolean(), + "before the Hub is up: not active"); + } + + private static void Trinkets() + { + var rule = ServerTrinketRule.Parse(ProfileInterface.CurrentJson(true, "InfiniteLeaftide")); + Check.True(rule != ServerTrinketRule.None, "the profile carries a trinket rule"); + foreach (string t in new[] { "Ornate Compass", "Tinker's Goggles", "Jade Scarab", "Pocket Watch", "Puzzle Box", "Spinning Top" }) + Check.True(rule.IsTrinket(t), t + " is a trinket"); + foreach (string j in new[] { "Yellow Topaz Ring", "Gold Necklace", "Silver Bracelet" }) + Check.False(rule.IsTrinket(j), j + " is Jewelry"); + } + + private static void Salvage() + { + var rows = ServerSalvageView.ParseList(ProfileInterface.CurrentJson(true, "InfiniteLeaftide")); + Check.Eq(rows.Count, IltSalvage.Rows.Length, "every row arrives"); + for (int i = 0; i < rows.Count; i++) + { + var a = IltSalvage.Rows[i]; + var b = rows[i]; + bool same = a.Bench == b.Bench && a.Material == b.Material && a.Kind == b.Kind && a.Effect == b.Effect + && a.UsesTinkSlot == b.UsesTinkSlot && a.NameMatch == b.NameMatch && a.AppliedInt == b.AppliedInt + && a.Prepared == b.Prepared && a.Order == b.Order && a.AfterCap == b.AfterCap + && a.StackGroup == b.StackGroup && a.StackCap == b.StackCap; + Check.True(same, $"row {i} ({a.Bench} {a.Material}) round-trips"); + } + + const int Leather = 52, Steel = 64, Serpentine = 71, Silver = 63, Diamond = 20, BlackGarnet = 15; + foreach (string bench in new[] { "melee", "missile", "caster" }) + { + var leather = rows.Single(r => r.Bench == bench && r.Material == Leather); + Check.True(leather.AfterCap, bench + " Leather: after the cap"); + Check.False(leather.UsesTinkSlot, bench + " Leather: no tink slot"); + Check.Eq(leather.Kind, "once", bench + " Leather: once"); + Check.Eq(leather.Order, 995, bench + " Leather: last"); + } + Check.Eq(rows.Count(r => r.AfterCap), 3, "only the weapon Leathers wait for the cap"); + + var stack = rows.Where(r => r.StackGroup.Length > 0).ToList(); + Check.Eq(string.Join(",", stack.Select(r => r.Bench + ":" + r.Material)), $"jewelry:{Serpentine},jewelry:{Steel}", "Serpentine + Steel stack"); + Check.True(stack.All(r => r.StackGroup == "jewelry-stack" && r.StackCap == 10 && r.Kind == "tink" && !r.UsesTinkSlot), + "one group, cap 10, repeatable, no tink slot"); + + Check.Eq(rows.Single(r => r.Bench == "jewelry" && r.Material == Silver).AppliedInt, 374, "jewelry Silver flag int"); + var diamond = rows.Single(r => r.Bench == "trinkets" && r.Material == Diamond); + Check.True(diamond.Prepared && diamond.AppliedInt == 384 && diamond.Order == 10, "trinket Diamond: prepared, flag 384, first"); + Check.Eq(rows.Count(r => r.Prepared), 4, "the four trinket tiers are prepared"); + Check.True(rows.Where(r => r.Material == BlackGarnet).All(r => r.NameMatch == "Abyssal" && r.UsesTinkSlot), + "Abyssal-Touched Gems by bag name, using a tink slot"); + Check.False(rows.Any(r => r.Bench is "armor" or "items"), "no armor or item rows"); + } +} diff --git a/Tools/RynthILT.Tests/Program.cs b/Tools/RynthILT.Tests/Program.cs new file mode 100644 index 0000000..d351cc8 --- /dev/null +++ b/Tools/RynthILT.Tests/Program.cs @@ -0,0 +1,64 @@ +using System; +using System.IO; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// Offline tests for the RynthILT plugin: the ACECustom bounty tracker (parsing, merging, the +// quiet /bounty list read loop on a fake clock, persistence, the bridge JSON) and the ILT Hub +// (attribute raiser, aug costs, bank commands, sigil chain, and the move out of RynthAi: data +// migration, the RynthILT.Hub table, verb routing, the object view) and its RynthServer.Profile +// (ILT's tinkering salvage). Each test prints PASS / FAIL. +// +// Run: dotnet run -c Release (all tests) +// dotnet run -c Release -- window (tests whose name contains "window") +internal static class Program +{ + /// Scratch folder next to the exe for files tests write. Emptied at start. + public static string TempRoot { get; } = Path.Combine(AppContext.BaseDirectory, "scratch"); + + private static int Main(string[] args) + { + if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true); + Directory.CreateDirectory(TempRoot); + + // SAFETY: every file the ILT Hub would write under %APPDATA%\RynthCore\RynthILT or read from + // the RynthAi folder points at the scratch folder before any test runs. + RynthCore.Plugin.RynthILT.Hub.IltAugCosts.FilePath = Path.Combine(TempRoot, "ilt-aug-costs.json"); + RynthCore.Plugin.RynthILT.Hub.IltHubStore.SharedRoot = Path.Combine(TempRoot, "RynthILT"); + RynthCore.Plugin.RynthILT.Hub.IltSettingsStore.Folder = Path.Combine(TempRoot, "RynthILT"); + RynthCore.Plugin.RynthILT.Hub.IltMigration.LegacyProfilesBase = Path.Combine(TempRoot, "RynthAi", "SettingsProfiles"); + RynthCore.Plugin.RynthILT.Hub.IltMigration.LegacySharedRoot = Path.Combine(TempRoot, "RynthAi"); + RynthCore.Plugin.RynthILT.RynthLog.Init(default, Path.Combine(TempRoot, "Logs")); + RynthCore.Plugin.Shared.DataWriteGuard.PluginName = "RynthILT"; // as RynthILTPlugin.Initialize sets it + + var runner = new Runner(); + BountyTests.Register(runner); + BountyReviewTests.Register(runner); + AttributeRaiserTests.Register(runner); + SigilChainTests.Register(runner); + BankCommandTests.Register(runner); + MoveTests.Register(runner); + ChunkTests.Register(runner); + ProfileTests.Register(runner); + FeatureCatalogTests.Register(runner); + IltSettingsTests.Register(runner); + FellowshipCommandTests.Register(runner); + AetheriaChunkTests.Register(runner); + ChunkTargetTests.Register(runner); + RingChainTests.Register(runner); + VaultedDungeonsTests.Register(runner); + PetCaptureRulesTests.Register(runner); + PetAutomationTests.Register(runner); + RingEvadeTests.Register(runner); + VaultedSwitchTests.Register(runner); + T11Tests.Register(runner); + RemoteTabTests.Register(runner); + StampTests.Register(runner); + BankRosterTests.Register(runner); + // Before DataApiTests: its last test releases the RynthILT.Data table, which the breeding version test queries. + BreedingTests.Register(runner); + DataApiTests.Register(runner); + return runner.Run("RynthILT tests", args.Length > 0 ? args[0] : null); + } +} diff --git a/Tools/RynthILT.Tests/RemoteTabTests.cs b/Tools/RynthILT.Tests/RemoteTabTests.cs new file mode 100644 index 0000000..cd53a77 --- /dev/null +++ b/Tools/RynthILT.Tests/RemoteTabTests.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The ILT parts of RynthAi's Remote tab moved to RynthILT on 2026-10-20: the coin / pyreal lines under +// RynthAi's Stats ("remote-stats"), the session report's tail (GetText "session-report"), the Bank and +// Guardian sections' switches (RynthILT's own now, drawn in RynthAi's Options popup, "remote-options"), +// and the coin session restarting with RynthAi's shared session instead of RynthAi sending "rates reset". +internal static class RemoteTabTests +{ + public static void Register(Runner r) + { + r.Add("remote tab (RynthILT): its texts for RynthAi (server id, the session report's coins) and none off ILT", Texts); + r.Add("remote tab (RynthILT): Bank / Guardian follow RynthILT's own switches; the stats and options draw nothing off ILT", Switches); + r.Add("remote tab (RynthILT): the coins start over when RynthAi's shared session restarts", FollowsSession); + r.Add("migration: RynthAi's huds.json Bank / Guardian switches come over once", ImportsSwitches); + } + + private static IltHubController NewHub(string world, string folder) + { + FakeHost.Reset(); + FakeAiHub.Reset(); + FakeHost.WorldName = world; + var host = FakeHost.Create(0x50000D21); + var ai = new RynthAiClient(host); + ai.UseTableForTests(FakeAiHub.Table); + string dir = Path.Combine(Program.TempRoot, "remote-" + folder); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + var hub = new IltHubController(host, dir, new IltSettings(), ai); + hub.OnLoginComplete("Remoter", forceFromMigration: false); + return hub; + } + + private static void Texts() + { + var on = NewHub("InfiniteLeaftide", "texts-on"); + Check.Eq(on.GetText(RynthServerHub.TextServerId), "ilt", "its tabs belong to RynthCore's 'ilt'"); + string tail = on.GetText(RynthServerHub.TextSessionReport); + Check.True(tail.StartsWith(", Coins ") && tail.Contains("/h, Pyr "), "the session report's tail: coins and pyreals per hour"); + Check.Eq(on.GetText("no-such-text"), string.Empty, "an unknown id: nothing"); + + var off = NewHub("Aeshnidae", "texts-off"); + Check.Eq(off.GetText(RynthServerHub.TextSessionReport), string.Empty, "off ILT: no coins in RynthAi's report"); + } + + private static void Switches() + { + var on = NewHub("InfiniteLeaftide", "switches"); + Check.True(on.State.Remote.ShowBank && on.State.Remote.ShowGuardian, "both on by default"); + on.State.Remote.ShowBank = false; + on.State.Remote.ShowGuardian = false; + Check.False(on.RenderSection(RynthServerHub.SectionRemoteBank), "Bank switched off: nothing drawn"); + Check.False(on.RenderSection(RynthServerHub.SectionRemoteGuardian), "Guardian switched off: nothing drawn"); + + var off = NewHub("Aeshnidae", "switches-off"); + Check.False(off.RenderSection(RynthServerHub.SectionRemoteStats) || off.RenderSection(RynthServerHub.SectionRemoteOptions) + || off.RenderSection(RynthServerHub.SectionRemoteBank) || off.RenderSection(RynthServerHub.SectionRemoteGuardian), + "off ILT: none of the Remote tab's ILT parts draws (checked before any ImGui call)"); + } + + private static void FollowsSession() + { + var hub = NewHub("InfiniteLeaftide", "session"); + long t1 = DateTime.UtcNow.AddMinutes(-10).Ticks; + FakeAiHub.SessionStartTicks = t1; + long now = Environment.TickCount64; + hub.Rates.Tick(now); + DateTime first = hub.Rates.SessionStartUtc; + System.Threading.Thread.Sleep(30); + hub.Rates.Tick(now + 100); + Check.Eq(hub.Rates.SessionStartUtc, first, "the same shared session: no restart"); + FakeAiHub.SessionStartTicks = DateTime.UtcNow.Ticks; // RynthAi's Reset XP + hub.Rates.Tick(now + 200); + Check.True(hub.Rates.SessionStartUtc > first, "RynthAi's session restarted: the coins start over too"); + } + + private static void ImportsSwitches() + { + string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Remoter"); + Directory.CreateDirectory(legacy); + File.WriteAllText(Path.Combine(legacy, "Default.json"), "{}"); + File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyHudsFile), "{ \"ShowMiniRemote\": true, \"MiniShowBank\": false }"); + var state = new IltHubState(); + IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Remoter"); + Check.False(state.Remote.ShowBank, "Bank was hidden in RynthAi: hidden here"); + Check.True(state.Remote.ShowGuardian, "Guardian wasn't in the file: the default (shown)"); + } +} diff --git a/Tools/RynthILT.Tests/RingChainTests.cs b/Tools/RynthILT.Tests/RingChainTests.cs new file mode 100644 index 0000000..25b225f --- /dev/null +++ b/Tools/RynthILT.Tests/RingChainTests.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The Rings inscription chain's pure parts (Hub/IltRingChain.cs, SilentKelpie's RynthAi +// Crafting > Rings moved to RynthILT): ingredient names, the craft queue and the scroll pairing. +internal static class RingChainTests +{ + public static void Register(Runner r) + { + r.Add("rings: ingredients match by name, with alternates and an exclude", Ingredients); + r.Add("rings: the queue runs every Step 1, then Step 2, then the glyphs, capped per recipe", Queue); + r.Add("rings: scrolls are known by their glyph and paired with targets the UB-IT way", Scrolls); + r.Add("rings: the recipe list holds the three steps and eight glyphs", RecipeList); + } + + private static IltRingRecipe Recipe(string id) => IltRingChain.Recipes.Single(r => r.Id == id); + + private static void Ingredients() + { + var step1 = Recipe("ring2_step1_quill_trophy"); + Check.True(IltRingChain.Matches("Quill of Infliction", step1.Tool), "the quill"); + Check.True(IltRingChain.Matches("infliction quill", step1.Tool), "an alternate name, any case"); + Check.False(IltRingChain.Matches("Enlightened Quill of Infliction", step1.Tool), "the enlightened quill is Step 2's, not Step 1's"); + Check.True(IltRingChain.Matches("Empyrean Trophy", step1.Target), "a trophy"); + Check.False(IltRingChain.Matches("Trophy Scroll", step1.Target), "plain 'Trophy' isn't enough (scrolls carry the word)"); + Check.False(IltRingChain.Matches(null, step1.Tool), "no name"); + Check.False(IltRingChain.Matches("", step1.Tool), "empty name"); + + var step2 = Recipe("ring2_step2_ink"); + Check.True(IltRingChain.Matches("Enlightened Quill of Infliction", step2.Tool), "Step 2 takes Step 1's quill"); + Check.False(IltRingChain.Matches("Enlightened Infliction Quill of Partition", step2.Tool), "but not the partition quill"); + + var flame = Recipe("ring2_glyph_flame"); + Check.True(IltRingChain.Matches("Enlightened Infliction Quill of Partition", flame.Tool), "Step 3 takes the partition quill"); + Check.True(IltRingChain.Matches("Glyph of Flame", flame.Target), "the full glyph name"); + Check.False(IltRingChain.Matches("Glyph of Frost", flame.Target), "another glyph is not"); + } + + private static void Queue() + { + var runs = new Dictionary + { + ["ring2_glyph_frost"] = 1, + ["ring2_step2_ink"] = 2, + ["ring2_step1_quill_trophy"] = 2, + ["ring2_glyph_bludgeoning"] = 1, + }; + List q = IltRingChain.Expand(id => runs.TryGetValue(id, out int n) ? n : 0); + Check.Eq(string.Join(",", q.Select(r => r.Id)), + "ring2_step1_quill_trophy,ring2_step1_quill_trophy,ring2_step2_ink,ring2_step2_ink,ring2_glyph_bludgeoning,ring2_glyph_frost", + "tier order, then the definition order within a tier"); + Check.Eq(IltRingChain.Expand(_ => 0).Count, 0, "nothing queued"); + Check.Eq(IltRingChain.Expand(id => id == "ring2_step2_ink" ? -5 : 0).Count, 0, "negative runs count as none"); + Check.Eq(IltRingChain.Expand(id => id == "ring2_step2_ink" ? 500 : 0).Count, IltRingChain.MaxRuns, "capped at MaxRuns"); + } + + private static void Scrolls() + { + Check.True(IltRingChain.IsInscriptionScroll("Inscription of Halo of Frost"), "an inscription scroll"); + Check.False(IltRingChain.IsInscriptionScroll("Scroll of Frost Bolt"), "a spell scroll is not"); + Check.False(IltRingChain.IsInscriptionScroll(null), "no name"); + Check.Eq(IltRingChain.GlyphOf("Inscription of Halo of Frost")?.Id, "ring2_glyph_frost", "known by its scroll name"); + Check.Eq(IltRingChain.GlyphOf("Inscription of Cassius' Ring of Fire")?.Id, "ring2_glyph_flame", "apostrophes too"); + Check.True(IltRingChain.GlyphOf("Inscription of Something New") == null, "an unknown scroll has no glyph"); + + var scrolls = new[] + { + (Id: 50, Name: "Inscription of Something New"), + (Id: 40, Name: "Inscription of Halo of Frost"), + (Id: 30, Name: "Inscription of Tectonic Rifts"), + (Id: 20, Name: "Inscription of Halo of Frost"), + }; + var pairs = IltRingChain.PairScrolls(scrolls, new[] { 900, 700, 800, 700 }); + // Scrolls by glyph id (bludgeoning < frost; unknown last), then by id; targets by id, once each. + Check.Eq(string.Join(" ", pairs.Select(p => p.Scroll + ">" + p.Target)), "30>700 20>800 40>900", "pairing order"); + Check.Eq(IltRingChain.PairScrolls(scrolls.Take(1), new[] { 1, 2, 3 }).Count, 1, "one scroll per target, no more pairs than scrolls"); + Check.Eq(IltRingChain.PairScrolls(scrolls, Array.Empty()).Count, 0, "no targets, no pairs"); + } + + private static void RecipeList() + { + Check.Eq(IltRingChain.Recipes.Length, 10, "Step 1, Step 2 and eight glyphs"); + Check.Eq(IltRingChain.Recipes.Count(r => r.Tier == 3), 8, "eight glyphs"); + Check.True(IltRingChain.Recipes.Select(r => r.Id).Distinct().Count() == IltRingChain.Recipes.Length, "ids are unique"); + foreach (var r in IltRingChain.Recipes.Where(r => r.Tier == 3)) + Check.True(r.ScrollMarkers.Length > 0, r.Id + " knows its scroll's name"); + } +} diff --git a/Tools/RynthILT.Tests/RingEvadeTests.cs b/Tools/RynthILT.Tests/RingEvadeTests.cs new file mode 100644 index 0000000..df992a7 --- /dev/null +++ b/Tools/RynthILT.Tests/RingEvadeTests.cs @@ -0,0 +1,134 @@ +using System; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The Empyrean Handler's lethal ring (Hub/IltRingEvade.cs), RynthAi's CombatManager's until 2026-10-20 +// (Silentkelpie's PR 12). The line "The handler briefly channels infused Empyrean hatred to release a +// lethal ring." on an ILT world, with a Handler near, makes RynthILT ask RynthAi to back away from it +// (RynthAi.Hub BackAwayFrom, 12 yards, a 750 ms jump). The setting (on by default) is RynthILT's now, +// copied once from the RynthAi profile. +internal static class RingEvadeTests +{ + private const uint Player = 0x50000B01; + private const uint Handler = 0x80000B02; + private const uint Lb = 0xA9B40000; + private const string RingLine = "The handler briefly channels infused Empyrean hatred to release a lethal ring."; + + public static void Register(Runner r) + { + r.Add("ring evade (RynthILT): the Handler's line, and not a player's copy of it", ChannelLine); + r.Add("ring evade (RynthILT): on ILT with a Handler near, RynthAi is asked to back away (once per cooldown)", AsksRynthAi); + r.Add("ring evade (RynthILT): not with the setting off, no Handler near, off ILT, or without RynthAi", NotThese); + r.Add("migration: the RynthAi profile's Handler ring evade comes over once (on by default)", ImportsSetting); + } + + private static IltHubController NewHub(string world, string folder, bool handler = true, bool withAi = true, string handlerName = "Empyrean Handler") + { + FakeHost.Reset(); + FakeAiHub.Reset(); + FakeHost.WorldName = world; + FakeHost.ContentsCalls = true; + FakeHost.LiveObjectsCalls = true; + FakeHost.Names[Player] = "Evader"; + FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f); + if (handler) + { + FakeHost.Names[Handler] = handlerName; + FakeHost.ItemTypes[Handler] = 0x10; + FakeHost.Positions[Handler] = (Lb | 0x1C, 96f, 101f, 0f); + } + var host = FakeHost.Create(Player); + var ai = new RynthAiClient(host); + if (withAi) ai.UseTableForTests(FakeAiHub.Table); + string dir = Path.Combine(Program.TempRoot, "ring-" + folder); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + var hub = new IltHubController(host, dir, new IltSettings(), ai); + hub.OnLoginComplete("Evader", forceFromMigration: false); + return hub; + } + + private static void ChannelLine() + { + Check.True(IltRingEvade.IsChannelLine(RingLine, ChatSource.Emote), "the Handler's emote"); + Check.True(IltRingEvade.IsChannelLine("handler briefly channels infused Empyrean hatred to release a lethal ring.", 0x00), + "mid-line on a system line (a client that strips 'The ')"); + Check.False(IltRingEvade.IsChannelLine("Someone says, \"" + RingLine + "\"", ChatSource.Speech), "a player saying it"); + Check.False(IltRingEvade.IsChannelLine("Bob tells you, \"" + RingLine + "\"", 0x00), "a tell repeating it"); + Check.False(IltRingEvade.IsChannelLine("The handler waves.", ChatSource.Emote), "another Handler emote"); + } + + private static void AsksRynthAi() + { + var hub = NewHub("InfiniteLeaftide", "asks"); + hub.OnChat(RingLine, ChatSource.Emote); + Check.Eq(FakeAiHub.BackAways.Count, 1, "one back-away request"); + var (id, radius, hold) = FakeAiHub.BackAways[0]; + Check.Eq(id, Handler, "away from the Handler"); + Check.Eq(radius, IltRingEvade.DangerYards, "12 yards (RynthAi widens it to Ring Range)"); + Check.Eq(hold, IltRingEvade.JumpHoldMs, "a 750 ms jump"); + Check.True(hub.RingEvade.LastOutcome.Contains("backs away"), "logged"); + hub.OnChat(RingLine, ChatSource.Emote); + Check.Eq(FakeAiHub.BackAways.Count, 1, "a second line inside the cooldown asks nothing"); + + var outside = NewHub("InfiniteLeaftide", "outside"); + FakeAiHub.BackAwayResult = RynthAiHub.BackAwayOutside; + outside.OnChat(RingLine, ChatSource.Emote); + Check.Eq(FakeAiHub.BackAways.Count, 1, "RynthAi decides the radius"); + Check.True(outside.RingEvade.LastOutcome.Contains("outside"), "and its answer is logged"); + + var notFighting = NewHub("InfiniteLeaftide", "notnow"); + FakeAiHub.BackAwayResult = RynthAiHub.BackAwayNotNow; + notFighting.OnChat(RingLine, ChatSource.Emote); + Check.True(notFighting.RingEvade.LastOutcome.Contains("isn't fighting"), "RynthAi not fighting: it says so"); + } + + private static void NotThese() + { + var off = NewHub("InfiniteLeaftide", "setting-off"); + off.State.Combat.HandlerRingEvade = false; + off.OnChat(RingLine, ChatSource.Emote); + Check.Eq(FakeAiHub.BackAways.Count, 0, "setting off: nothing asked"); + + var none = NewHub("InfiniteLeaftide", "none", handlerName: "Drudge Skulker"); + none.OnChat(RingLine, ChatSource.Emote); + Check.Eq(FakeAiHub.BackAways.Count, 0, "no Empyrean Handler near: nothing asked"); + + var said = NewHub("InfiniteLeaftide", "said"); + said.OnChat("Someone says, \"" + RingLine + "\"", ChatSource.Speech); + Check.Eq(FakeAiHub.BackAways.Count, 0, "a player's copy: nothing asked"); + + var retail = NewHub("Aeshnidae", "retail"); + retail.OnChat(RingLine, ChatSource.Emote); + Check.Eq(FakeAiHub.BackAways.Count, 0, "off ILT: nothing asked"); + + var noAi = NewHub("InfiniteLeaftide", "noai", withAi: false); + noAi.OnChat(RingLine, ChatSource.Emote); + Check.True(noAi.RingEvade.LastOutcome.Contains("RynthAi"), "without RynthAi: said in the log, no crash"); + } + + private static void ImportsSetting() + { + Check.True(new IltHubState().Combat.HandlerRingEvade, "on by default"); + string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Evader"); + Directory.CreateDirectory(legacy); + File.WriteAllText(Path.Combine(legacy, "active_profile.txt"), "Farm"); + File.WriteAllText(Path.Combine(legacy, "Farm.json"), "{ \"HandlerRingEvade\": false, \"MonsterRange\": 30 }"); + var state = new IltHubState(); + IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Evader"); + Check.False(state.Combat.HandlerRingEvade, "the active profile had it off: off here too"); + + string legacy2 = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Oldie"); + Directory.CreateDirectory(legacy2); + File.WriteAllText(Path.Combine(legacy2, "Default.json"), "{ \"MonsterRange\": 30 }"); + var old = new IltHubState(); + IltMigration.ImportRynthAiSettings(old, "InfiniteLeaftide", "Oldie"); + Check.True(old.Combat.HandlerRingEvade, "a profile from before the setting: on (the default)"); + } +} diff --git a/Tools/RynthILT.Tests/RynthILT.Tests.csproj b/Tools/RynthILT.Tests/RynthILT.Tests.csproj new file mode 100644 index 0000000..177c710 --- /dev/null +++ b/Tools/RynthILT.Tests/RynthILT.Tests.csproj @@ -0,0 +1,71 @@ + + + + + Exe + net10.0-windows + x86 + win-x86 + false + enable + true + true + RynthILT.Tests + RynthILT.Tests + x86 + $(DefineConstants);RYNTHILT_TESTS + $(NoWarn);CS1591 + + + + + + + + + + + + + + + + + $(DefineConstants);ENGINE_BOUNTIES + + + + + + + + + + + + + + + + + + + + diff --git a/Tools/RynthILT.Tests/SigilChainTests.cs b/Tools/RynthILT.Tests/SigilChainTests.cs new file mode 100644 index 0000000..4641eab --- /dev/null +++ b/Tools/RynthILT.Tests/SigilChainTests.cs @@ -0,0 +1,83 @@ +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// Enlightenment 301-325 sigil craft chain (2026-10-07). Each target level T costs T - 5 sigils and +// T x 2B luminance (ACECustom tier 5). Sigil = Lifeblood Elixir + Ascension Coin; Ascension Coin = +// E-coin + Ancient Yalani Trinket; Elixir = Lifebloom Resin + Necrolytic Extract; Resin = Life +// Splitter + Plant. Stock is used from the top of the chain down. +internal static class SigilChainTests +{ + public static void Register(Runner r) + { + r.Add("sigil chain: 301-325 tier rates and sigil counts", TierRates); + r.Add("sigil chain: shortfall uses stock top-down", ShortfallTopDown); + r.Add("sigil chain: fulfillable count and shared e-coin pool", FulfillableAndCoins); + r.Add("sigil chain: item names (plural stacks, Plant exact)", Names); + } + + private static void TierRates() + { + var t301 = IltProgression.EnlStepCost(301); + Check.Eq(t301.Item, "Enlightenment Sigils", "301 takes sigils"); + Check.Eq(t301.Count, 296, "301 takes T - 5 sigils"); + Check.Eq(t301.Lum, 301 * 2_000_000_000m, "301 costs T x 2B luminance (no step multiplier yet)"); + Check.Eq(IltProgression.EnlStepCost(325).Lum, 325 * 2_000_000_000m, "325 still has no step multiplier"); + Check.Eq(IltProgression.EnlStepCost(326).Item, "Enlightenment Crests", "326 moves to crests"); + Check.Eq(IltSigilChain.SigilsForRange(300, 302), 296L + 297L, "range 300 -> 302 sums both levels"); + Check.Eq(IltSigilChain.SigilsForRange(324, 330), 320L, "range clamps at 325"); + Check.Eq(IltSigilChain.SigilsForRange(200, 300), 0L, "no sigils below 301"); + } + + private static void ShortfallTopDown() + { + var empty = IltSigilChain.Shortfall(10, new IltSigilStock()); + Check.Eq(empty.CoinsShort, 10L, "empty pack: one e-coin per sigil"); + Check.Eq(empty.PlantsShort, 10L, "empty pack: one plant per sigil"); + Check.True(!empty.Covered, "empty pack is not covered"); + + var stock = new IltSigilStock + { + Sigils = 2, AscensionCoins = 3, LifebloodElixirs = 1, LifebloomResins = 4, + EnlightenedCoins = 100, YalaniTrinkets = 1, NecrolyticExtracts = 2, LifeSplitters = 0, Plants = 5, + }; + var s = IltSigilChain.Shortfall(10, stock); + Check.Eq(s.SigilsToCraft, 8L, "2 finished sigils used first"); + Check.Eq(s.AscensionToCraft, 5L, "3 Ascension Coins on hand"); + Check.Eq(s.ElixirsToCraft, 7L, "1 Elixir on hand"); + Check.Eq(s.CoinsShort, 0L, "100 e-coins cover 5 crafts"); + Check.Eq(s.TrinketsShort, 4L, "1 trinket on hand"); + Check.Eq(s.ExtractsShort, 5L, "2 extracts on hand"); + Check.Eq(s.ResinsToCraft, 3L, "4 resins on hand"); + Check.Eq(s.SplittersShort, 3L, "no splitters"); + Check.Eq(s.PlantsShort, 0L, "5 plants cover 3 resins"); + + Check.True(IltSigilChain.Shortfall(5, new IltSigilStock { Sigils = 9 }).Covered, "finished sigils cover the demand"); + } + + private static void FulfillableAndCoins() + { + var stock = new IltSigilStock + { + Sigils = 1, AscensionCoins = 1, EnlightenedCoins = 10, YalaniTrinkets = 2, + LifebloomResins = 1, LifeSplitters = 10, Plants = 10, NecrolyticExtracts = 4, + }; + Check.Eq(IltSigilChain.Fulfillable(stock), 4L, "1 finished + min(3 coins, 4 elixirs)"); + + IltSigilChain.EcoinDemand(50, 30, 2, 20, out long fromCoins, out long still, out long need); + Check.Eq(fromCoins, 1L, "20 coins left after Ascension crafts make 1 token"); + Check.Eq(still, 1L, "one token still short"); + Check.Eq(need, 20L, "one more token's worth of coins"); + IltSigilChain.EcoinDemand(10, 25, 0, 20, out _, out _, out need); + Check.Eq(need, 15L, "Ascension crafts alone exceed the pool"); + } + + private static void Names() + { + Check.True(IltSigilChain.NameIs("Ascension Coins", IltSigilChain.AscensionCoin), "plural stack name"); + Check.True(IltSigilChain.NameIs(" plant ", IltSigilChain.Plant), "case and spaces ignored"); + Check.True(!IltSigilChain.NameIs("Plant Fiber", IltSigilChain.Plant), "Plant must be the whole name"); + Check.True(!IltSigilChain.NameIs("Lifebloom Resin", IltSigilChain.LifebloodElixir), "Lifebloom is not Lifeblood"); + } +} diff --git a/Tools/RynthILT.Tests/StampTests.cs b/Tools/RynthILT.Tests/StampTests.cs new file mode 100644 index 0000000..6824900 --- /dev/null +++ b/Tools/RynthILT.Tests/StampTests.cs @@ -0,0 +1,258 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthILT; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// Infinite Leaftide's Dynamic Stamps (Hub/IltDynamicStampList.cs, Hub/IltDynamicStamps.cs): SilentKelpie's +// (RynthSuite PR 12), rows of RynthOracle's Quests list until 2026-10-21 and RynthILT's own page since. +// The list and its matching rules (the tests that came with it from RynthOracle.Tests), the page's +// filters, where its flags come from, and what its buttons send (RynthNav, RynthAi's /ub give). +internal static class StampTests +{ + public static void Register(Runner r) + { + r.Add("stamps: the shipped list (243 stamps in 17 areas) and how a stamp is matched", ShippedList); + r.Add("stamps: the loader skips bad and repeated rows", Loader); + r.Add("stamps: the page's filters (area, missing / had, search)", Filters); + r.Add("stamps: flags come from any /myquests reply; only RynthILT's own reply is hidden", Flags); + r.Add("stamps: off ILT the page is dormant (no flags read)", Dormant); + r.Add("stamps: Go / Route / Arrow ask RynthNav; Chat prints the stamp", Nav); + r.Add("stamps: Give Parchment needs RynthAi, sends /ub give 1, then reads the flags again", Give); + r.Add("stamps: a Parchment in the packs is found while the page is on screen", Parchment); + } + + private const uint Player = 0x50000D31; + private static readonly long Yesterday = DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds(); + + private static IltHubController NewHub(string world, string folder, bool withAi = false) + { + FakeHost.Reset(); + FakeAiHub.Reset(); + FakeHost.WorldName = world; + FakeHost.PluginCommandCalls = true; + FakeHost.ContentsCalls = true; + FakeHost.Containers[0x7000A001] = Player; + FakeHost.Names[0x7000A001] = "Pyreal"; + var host = FakeHost.Create(Player); + var ai = new RynthAiClient(host); + if (withAi) ai.UseTableForTests(FakeAiHub.Table); + string dir = Path.Combine(Program.TempRoot, "stamps-" + folder); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + var hub = new IltHubController(host, dir, new IltSettings(), ai); + hub.OnLoginComplete("Stamper", forceFromMigration: false); + return hub; + } + + private static void ShippedList() + { + var all = DynamicStampList.All; + Check.Eq(all.Count, 243, "243 stamps from the ExtraDyn sheet"); + Check.True(DynamicStampList.Areas.Count == 17 && DynamicStampList.Areas[0] == "Facility Hub" && DynamicStampList.Areas[^1] == "Candeth Keep", + "areas: " + string.Join(",", DynamicStampList.Areas)); + Check.True(all.All(s => s.Stamp.StartsWith("dynamic_") && s.Stamp == s.Stamp.ToLowerInvariant()), "every stamp is a lower-case dynamic_ flag"); + Check.Eq(all.Select(s => s.Stamp).Distinct().Count(), all.Count, "no stamp listed twice"); + Check.True(all.All(s => s.Label.Length > 0), "every row names an NPC or a place"); + + DynamicStamp felscuda = all.First(s => s.Npc == "Felscuda"); + Check.True(felscuda.Stamp == "dynamic_1_&9jiytb!" && felscuda.Place == "Folthid Cellar" && felscuda.Reward == "Healing Rabbit Pie" + && felscuda.Note == "8.8S, 53.1E", $"Felscuda row: {felscuda.Place} / {felscuda.Reward} / {felscuda.Note}"); + + // /myquests keys flags as \S+ lower case, so the stamps' ! & # ^ $ survive. + var f = new QuestFlagStore(); + long t = 900_000; + f.OnChatLine($"Dynamic_1_&9jiyTB! - 1 solves ({Yesterday})\"Dynamic\" 1 0", t); + f.OnChatLine($"Dynamic_1_ANND! - 1 solves ({Yesterday})\"Dynamic\" 1 0", t + 1); // the sheet lost the closing ! + f.OnChatLine($"Dynamic_1_ZZZnewNPC! - 1 solves ({Yesterday})\"Dynamic\" 1 0", t + 2); // not on the sheet + f.OnChatLine($"rtwcompleted_1013 - 1 solves ({Yesterday})\"RTW\" -1 72000", t + 3); + f.Tick(t + 5_000); + Check.True(felscuda.Have(f), "Felscuda's stamp read from /myquests"); + DynamicStamp annd = all.First(s => s.Stamp == "dynamic_1_annd"); + Check.True(annd.Have(f) && annd.MatchedFlag(f) == "dynamic_1_annd!", "a stamp the sheet lost its ! on still matches"); + Check.False(all.First(s => s.Npc == "Raxanza Folthid").Have(f), "an NPC not done is missing"); + List extra = DynamicStampList.Unlisted(f); + Check.True(extra.Count == 1 && extra[0] == "dynamic_1_zzznewnpc!", "unlisted: only the stamp the sheet doesn't have: " + string.Join(",", extra)); + DynamicStamp shortStamp = all.First(s => s.Stamp == "dynamic_1_s"); + var sf = new QuestFlagStore(); + sf.OnChatLine($"Dynamic_1_SomethingElse! - 1 solves ({Yesterday})\"Dynamic\" 1 0", t); + sf.Tick(t + 5_000); + Check.False(shortStamp.Have(sf), "a cut-short stem under 14 characters isn't matched by prefix"); + + // RynthNav targets, best first (RynthNav takes the first on its map). + Check.Eq(string.Join(" | ", felscuda.NavCandidates()), "8.8S, 53.1E | Folthid Cellar | Felscuda | Facility Hub", "Felscuda nav"); + var gerent = new DynamicStamp { Area = "Graveyard", Place = "Gerent's Compound at 87.2S, 17.5W", Npc = "Gerent" }; + Check.Eq(string.Join(" | ", gerent.NavCandidates()), "87.2S, 17.5W | Gerent's Compound | Gerent | Graveyard", "coordinates inside the place, 'at' dropped"); + var lost = new DynamicStamp { Area = "Odd Stamps", Place = "Lost Wish Cottages (Arwic) 42.6n 62.4e", Npc = "Bob" }; + Check.Eq(string.Join(" | ", lost.NavCandidates()), "42.6N, 62.4E | Lost Wish Cottages (Arwic) | Lost Wish Cottages | Arwic", + "lower-case n/e, a bracketed town, no grouping area, a 3-letter NPC left out"); + var mhoire = new DynamicStamp { Area = "Looking Around", Place = "Mhoire Castle - Great Hall" }; + Check.Eq(string.Join(" | ", mhoire.NavCandidates()), "Mhoire Castle - Great Hall | Mhoire Castle | Great Hall", "a place's parts"); + Check.True(all.Count(s => s.NavCandidates().Count > 0) >= 200, "most stamps have somewhere to go: " + all.Count(s => s.NavCandidates().Count > 0)); + } + + private static void Loader() + { + var stamps = DynamicStampList.Parse(new StringReader( + "Area,Place,Npc,Reward,Stamp,Note\n" + + "\"A\",\"P\",\"Npc1\",\"R\",\"Dynamic_1_Abc!\",\"8.8S, 53.1E\"\n" + + "\"A\",\"P\",\"Dup\",\"R\",\"dynamic_1_abc!\",\"\"\n" // the same stamp again: skipped + + "\"A\",\"P\",\"NotDyn\",\"R\",\"something_else\",\"\"\n" // not a dynamic_ flag: skipped + + "\"A\",\"P\",\"Short\"\n" // no stamp column: skipped + + "\n" + + "\"B\",\"\",\"\",\"\",\"Dynamic_2_x\",\"\"\n")); + Check.True(stamps.Count == 2 && stamps[0].Stamp == "dynamic_1_abc!" && stamps[1].Stamp == "dynamic_2_x", + "bad and repeated rows skipped, the rest kept: " + string.Join(",", stamps.Select(s => s.Stamp))); + Check.True(stamps[0].Npc == "Npc1" && stamps[0].Note == "8.8S, 53.1E" && stamps[1].Label == "", "fields read, a missing NPC and place leave an empty label"); + Check.Eq(DynamicStampList.Parse(new StringReader("")).Count, 0, "an empty file is an empty list"); + } + + private static void Filters() + { + var f = new QuestFlagStore(); + f.OnChatLine($"Dynamic_1_&9jiyTB! - 1 solves ({Yesterday})\"Dynamic\" 1 0", 0); + f.Tick(5_000); + List rows = DynamicStampText.Rows(DynamicStampList.All, f); + Check.Eq(rows.Count, 243, "a row per listed stamp"); + Check.Eq(rows.Count(r => r.Have), 1, "one had"); + Check.Eq(DynamicStampText.Filter(rows, "", null, DynamicStampText.Show.All).Count, 243, "no filter: everything"); + Check.Eq(DynamicStampText.Filter(rows, "", null, DynamicStampText.Show.Have).Single().Stamp.Npc, "Felscuda", "Had: Felscuda's"); + Check.Eq(DynamicStampText.Filter(rows, "", null, DynamicStampText.Show.Missing).Count, 242, "Missing: the rest"); + string area = DynamicStampList.Areas[0]; + int inArea = DynamicStampList.All.Count(s => s.Area == area); + Check.Eq(DynamicStampText.Filter(rows, null, area, DynamicStampText.Show.All).Count, inArea, "the area picker narrows to " + area); + Check.Eq(DynamicStampText.Filter(rows, "felscuda rabbit", null, DynamicStampText.Show.All).Single().Stamp.Npc, "Felscuda", + "every search word, in the NPC and the reward, any case"); + Check.Eq(DynamicStampText.Filter(rows, "felscuda nothinglikethis", null, DynamicStampText.Show.All).Count, 0, "a word nowhere: nothing"); + } + + private static void Flags() + { + IltHubController hub = NewHub("InfiniteLeaftide", "flags"); + IltDynamicStamps stamps = hub.DynamicStamps; + long now = IltHubContext.NowMs; + + // A reply another plugin (or the player) asked for: read, and shown. + bool eaten = hub.OnChat($"Dynamic_1_&9jiyTB! - 1 solves ({Yesterday})\"Dynamic\" 1 0"); + Check.False(eaten, "a reply RynthILT didn't ask for shows in chat"); + stamps.Tick(now + 5_000); + Check.True(stamps.Flags.TryGet("dynamic_1_&9jiytb!", out _), "the flag is read from it"); + + // Its own request: the reply is hidden. + hub.Tick(); + stamps.RequestFlags(); + Check.True(FakeHost.ChatCommands.Contains("/myquests"), "Read quest flags sends /myquests"); + stamps.NoteTypedMyQuests(); // the engine's dispatcher hands it back through the chat bar + Check.True(stamps.Flags.AwaitingOurs, "waiting for its own reply"); + Check.True(hub.OnChat($"Dynamic_1_ANND! - 1 solves ({Yesterday})\"Dynamic\" 1 0"), "its own reply is hidden"); + stamps.Tick(IltHubContext.NowMs + 5_000); + Check.False(stamps.Flags.AwaitingOurs, "done waiting once the reply went quiet"); + Check.True(stamps.Flags.TryGet("dynamic_1_annd!", out _), "and read"); + + // The page's snapshot follows the flags while it is on screen. + stamps.MarkWatched(); + stamps.Tick(IltHubContext.NowMs); + IltDynamicStamps.Snapshot s = stamps.Current; + Check.True(s.Built && s.Rows.Count == 243, "the snapshot lists every stamp"); + Check.Eq(s.Have, 1, "one listed stamp had (the other read reply replaced the first)"); + Check.True(s.LastReadUtc != DateTime.MinValue, "when the flags were read"); + + hub.OnLogout(); + Check.False(stamps.Current.Built || stamps.Flags.Flags.Count > 0, "logout forgets the flags and the snapshot"); + } + + private static void Dormant() + { + IltHubController hub = NewHub("Aeshnidae", "dormant"); + hub.OnChat($"Dynamic_1_&9jiyTB! - 1 solves ({Yesterday})\"Dynamic\" 1 0"); + hub.DynamicStamps.Tick(IltHubContext.NowMs + 5_000); + Check.Eq(hub.DynamicStamps.Flags.Flags.Count, 0, "off ILT no chat reaches the page"); + Check.False(hub.Options.IsIltLikeWorld, "(not an ILT world)"); + } + + private static void Nav() + { + IltHubController hub = NewHub("InfiniteLeaftide", "nav"); + IltDynamicStamps stamps = hub.DynamicStamps; + DynamicStamp felscuda = DynamicStampList.All.First(s => s.Npc == "Felscuda"); + Check.Eq(DynamicStampText.NavLine("route", felscuda), "route 8.8S, 53.1E || Folthid Cellar || Felscuda || Facility Hub", "the RynthNav line"); + Check.Eq(DynamicStampText.NavLine("go", new DynamicStamp { Stamp = "dynamic_x" }), "", "nowhere to go: no line"); + + stamps.Nav("route", felscuda); + stamps.Nav("go", felscuda); + stamps.Nav("arrow", felscuda); + Check.Eq(FakeHost.PluginCommands.Count, 3, "three RynthNav commands"); + Check.True(FakeHost.PluginCommands.All(c => c.Plugin == "RynthNav" && c.Action == "rnav"), "to RynthNav's rnav"); + Check.True(FakeHost.PluginCommands[1].Value.StartsWith("go 8.8S, 53.1E || "), "go with every candidate"); + Check.True(stamps.Status.Contains("arrow"), "the status says what happened: " + stamps.Status); + FakeHost.PluginCommandDelivered = false; + stamps.Nav("go", felscuda); + Check.True(stamps.Status.Contains("RynthNav isn't loaded"), "without RynthNav: said so"); + + FakeHost.Chat.Clear(); + stamps.Print(felscuda); + Check.True(FakeHost.Chat.Count >= 2 && FakeHost.Chat[0].Contains("Felscuda") && FakeHost.Chat[0].Contains("missing") + && FakeHost.Chat[1].Contains("Folthid Cellar") && FakeHost.Chat[1].Contains("Healing Rabbit Pie"), + "Chat prints the stamp, its status, place and reward: " + string.Join(" | ", FakeHost.Chat)); + } + + private static void Give() + { + // Without RynthAi: the reason, nothing sent. + Check.True(DynamicStampText.GiveUnavailableReason(false, false)!.Contains("Needs RynthAi"), "no RynthAi: says it needs it"); + Check.True(DynamicStampText.GiveUnavailableReason(true, true)!.Contains("Unrecognized /ub command"), "rejected: says why"); + Check.Null(DynamicStampText.GiveUnavailableReason(true, false), "RynthAi there: Give works"); + Check.Eq(DynamicStampText.GiveCommand("Parchment\nof /quit", "Felscuda"), "/ub give 1 Parchmentof /quit to Felscuda", + "control characters are stripped from the command"); + Check.True(DynamicStampText.IsGiveRejection("[RynthAi] Unrecognized /ub command.") && !DynamicStampText.IsGiveRejection("[RynthAi] ok"), + "RynthAi's rejection line"); + + DynamicStamp felscuda = DynamicStampList.All.First(s => s.Npc == "Felscuda"); + IltHubController none = NewHub("InfiniteLeaftide", "give-none"); + none.DynamicStamps.Give(felscuda, "Parchment of Learning"); + Check.False(FakeHost.ChatCommands.Any(c => c.StartsWith("/ub give")), "without RynthAi nothing is sent"); + + IltHubController hub = NewHub("InfiniteLeaftide", "give", withAi: true); + IltDynamicStamps stamps = hub.DynamicStamps; + stamps.Give(felscuda, "Parchment of Learning"); + Check.True(FakeHost.ChatCommands.Contains("/ub give 1 Parchment of Learning to Felscuda"), "Give sends /ub give 1: " + string.Join("|", FakeHost.ChatCommands)); + Check.True(stamps.Status.Contains("Giving Parchment of Learning to Felscuda"), "and says so"); + + // The stamp is a quest flag: /myquests is read again once the NPC had time to answer. + stamps.Tick(IltHubContext.NowMs + 1_000); + Check.False(FakeHost.ChatCommands.Contains("/myquests"), "not straight away"); + stamps.Tick(IltHubContext.NowMs + IltDynamicStamps.HandInRefreshMs + 1_000); + Check.True(FakeHost.ChatCommands.Contains("/myquests"), "a /myquests after the hand-in"); + + // The loaded RynthAi answers "Unrecognized /ub command": Give turns itself off. + hub.OnChat("[RynthAi] Unrecognized /ub command."); + stamps.Rebuild(); + Check.True(stamps.Current.GiveReason != null && stamps.Current.GiveReason.Contains("Unrecognized"), "rejected right after the send: Give is off"); + int sends = FakeHost.ChatCommands.Count(c => c.StartsWith("/ub give")); + stamps.Give(felscuda, "Parchment of Learning"); + Check.Eq(FakeHost.ChatCommands.Count(c => c.StartsWith("/ub give")), sends, "no further /ub give goes out"); + } + + private static void Parchment() + { + IltHubController hub = NewHub("InfiniteLeaftide", "parchment", withAi: true); + IltDynamicStamps stamps = hub.DynamicStamps; + stamps.Tick(IltHubContext.NowMs); + Check.False(stamps.Current.Built, "nothing is built while the page isn't on screen"); + stamps.MarkWatched(); + stamps.Tick(IltHubContext.NowMs); + Check.True(stamps.Current.Built && stamps.Current.Parchment == null, "on screen: built; no Parchment carried"); + Check.Null(stamps.Current.GiveReason, "RynthAi is there: Give would work"); + + FakeHost.Containers[0x7000A002] = Player; + FakeHost.Names[0x7000A002] = "Parchment of Learning"; + stamps.Tick(IltHubContext.NowMs + 2_000); + Check.Eq(stamps.Current.Parchment, "Parchment of Learning", "a Parchment in the main pack is found"); + } +} diff --git a/Tools/RynthILT.Tests/T11Tests.cs b/Tools/RynthILT.Tests/T11Tests.cs new file mode 100644 index 0000000..686edda --- /dev/null +++ b/Tools/RynthILT.Tests/T11Tests.cs @@ -0,0 +1,113 @@ +using System; +using System.IO; +using System.Linq; +using RynthCore.Loot.T11; +using RynthCore.Plugin.RynthILT; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// T11 (ACECustom tier 11+ gear) moved from RynthAi on 2026-10-20 (Hub/IltT11.cs): RynthILT reads the +// "/aug" reply's wield counters, applies its item-aug override and reports them to RynthAi's loot rules +// (RynthAi.Hub SetPlayerCounter); "/ilt t11" (and RynthAi's "/ra t11", passed on) shows and sets them. +internal static class T11Tests +{ + private const uint Player = 0x50000E01; + + public static void Register(Runner r) + { + r.Add("t11 (RynthILT): the /aug reply's counters go to RynthAi, with the item-aug override applied", ReportsCounters); + r.Add("t11 (RynthILT): /ilt t11 and /ra t11 are RynthILT's verbs; augs sets the override", Commands); + r.Add("t11 (RynthILT): off ILT nothing is read or reported", DormantOffIlt); + r.Add("migration: the RynthAi profile's T11 item-aug override comes over once", ImportsOverride); + } + + private static IltHubController NewHub(string world, string folder) + { + FakeHost.Reset(); + FakeAiHub.Reset(); + FakeHost.WorldName = world; + var host = FakeHost.Create(Player); + var ai = new RynthAiClient(host); + ai.UseTableForTests(FakeAiHub.Table); + string dir = Path.Combine(Program.TempRoot, "t11-" + folder); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + var hub = new IltHubController(host, dir, new IltSettings(), ai); + hub.OnLoginComplete("Augger", forceFromMigration: false); + return hub; + } + + private static void ReportsCounters() + { + var hub = NewHub("InfiniteLeaftide", "report"); + hub.T11.Tick(Environment.TickCount64); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], -1L, "unknown before /aug (reported as -1)"); + Check.Eq(hub.T11.LastReported, T11Catalog.CounterNames.Length, "every counter is reported"); + + hub.OnChat("Advanced Augmentation Levels:"); + hub.OnChat("Item:2,400"); + hub.OnChat("Triune Weave: 5 (adds 5 to your aug counts)"); + hub.T11.Tick(Environment.TickCount64); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2400L, "Item: 2,400 reported"); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.TriuneWeave], 5L, "Triune Weave: 5 reported"); + + hub.State.T11.ItemAugsOverride = 2500; + hub.T11.Tick(Environment.TickCount64); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2500L, "the override replaces /aug's item count"); + hub.State.T11.ItemAugsOverride = -1; + hub.T11.Tick(Environment.TickCount64); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2400L, "auto again: /aug's count"); + + hub.OnLogout(); + hub.T11.Tick(Environment.TickCount64); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], -1L, "after logout: unknown again"); + } + + private static void Commands() + { + Check.True(RynthILTPlugin.IsIltVerb(new[] { "t11" }), "/ra t11 is RynthILT's (RynthAi passes it on)"); + Check.True(RynthILTPlugin.IsIltVerb(new[] { "t11", "augs", "5" }), "with its arguments"); + Check.True(RynthILTPlugin.IsIltVerb(new[] { "ub", "qblist" }) && RynthILTPlugin.IsIltVerb(new[] { "ub", "augs" }), + "ub-IT's /ub qblist and /ub augs (ACECustom commands RynthAi passes on) are RynthILT's"); + Check.False(RynthILTPlugin.IsIltVerb(new[] { "ub", "wear" }) || RynthILTPlugin.IsIltVerb(new[] { "ub" }), "no other /ub verb"); + + var hub = NewHub("InfiniteLeaftide", "cmd"); + FakeHost.Chat.Clear(); + hub.T11.HandleCommand(new[] { "augs", "3,000" }); + Check.Eq(hub.State.T11.ItemAugsOverride, 3000, "augs 3,000 fixes the override"); + Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 3000L, "and reports it at once"); + hub.T11.HandleCommand(new[] { "augs", "auto" }); + Check.Eq(hub.State.T11.ItemAugsOverride, -1, "augs auto clears it"); + FakeHost.Chat.Clear(); + hub.T11.HandleCommand(Array.Empty()); + Check.True(FakeHost.Chat.Any(l => l.Contains("=== T11 loot")), "no argument: the status"); + Check.True(FakeHost.Chat.Any(l => l.Contains("Item Augmentations") || l.Contains("unknown")), "lists the counters"); + FakeHost.Chat.Clear(); + hub.T11.HandleCommand(new[] { "augs", "-5" }); + Check.True(FakeHost.Chat.Any(l => l.Contains("Usage")), "a bad count: usage"); + } + + private static void DormantOffIlt() + { + var off = NewHub("Aeshnidae", "off"); + off.OnChat("Advanced Augmentation Levels:"); + off.OnChat("Item:2,400"); + for (int i = 0; i < 3; i++) off.Tick(); + Check.Eq(FakeAiHub.Counters.Count, 0, "off ILT: no counter is reported to RynthAi"); + Check.True(off.T11.Player.Get(T11Counter.ItemAugmentations) == null, "nor read"); + } + + private static void ImportsOverride() + { + string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Augger"); + Directory.CreateDirectory(legacy); + File.WriteAllText(Path.Combine(legacy, "Default.json"), "{ \"T11ItemAugsOverride\": 2750 }"); + var state = new IltHubState(); + Check.Eq(state.T11.ItemAugsOverride, -1, "automatic by default"); + IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Augger"); + Check.Eq(state.T11.ItemAugsOverride, 2750, "the RynthAi profile's override came over"); + } +} diff --git a/Tools/RynthILT.Tests/VaultedDungeonsTests.cs b/Tools/RynthILT.Tests/VaultedDungeonsTests.cs new file mode 100644 index 0000000..a9c9a6e --- /dev/null +++ b/Tools/RynthILT.Tests/VaultedDungeonsTests.cs @@ -0,0 +1,527 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The Vaulted Dungeons keeper (Hub/IltVaultedDungeons.cs, Silentkelpie's, taken in with the owner's +// safety rules): ILT only, a master switch (RynthAi's setting, off by default) that gates everything, +// no resume of Active from the saved file, a recall that waits out combat / buffing, /rc quit once per +// activation and never while gated, and a no-kill timer that restarts on kills and captures. +// The clock, the master switch, RynthAi's activity and the gem use are the module's test seams. +internal static class VaultedDungeonsTests +{ + private const uint Player = 0x50000C01; + private const uint Quarry = 0x01F7; // dungeon 1: Tyrant's Quarry + private const uint Elsewhere = 0x0001; + private const string Luminance = "You've banked 1,234 Luminance."; + + public static void Register(Runner r) + { + r.Add("vaulted: not an ILT world -> inert (no tick work, no recall, no quit, a 'not available' reply)", NotIlt); + r.Add("vaulted: master off -> inert even with a saved Active, Auto Start and Kill Client", MasterOff); + r.Add("vaulted: master on + explicit start -> recalls at 1 s then every 5 s outside, stops inside; a saved Active is not resumed", ExplicitStartRecalls); + r.Add("vaulted: Auto Start On Arrival is honoured only with the master on", AutoStart); + r.Add("vaulted: Kill Client fires once per activation and restarts on luminance, a killing blow and a capture", QuitOnceAndResets); + r.Add("vaulted: Kill Client is never sent once the master goes off, even between the timer and the send", QuitNeverWhenGated); + r.Add("vaulted: a busy bot (combat, buffing, server wait, client busy) defers the recall; the warning keeps its cadence", BusyDefers); + r.Add("vaulted: turning the master off mid-run stops it at once and says so once; turning it on starts Off", MasterOffMidRun); + r.Add("vaulted: the tab and /ra hub open vaulted follow ILT + the master; settings file format kept", TabAndFile); + r.Add("vaulted: capture lines are the Pets tab's own success replies", CaptureLines); + r.Add("vaulted: settings go through the source-generated JSON context (NativeAOT has no reflection serializer)", SourceGeneratedContext); + } + + // ── Rig ────────────────────────────────────────────────────────────────── + + private sealed class Rig + { + public IltHubController Hub = null!; + public IltVaultedDungeons V = null!; + public string Dir = ""; + public long T = 1_000_000; + public bool Master; + public RynthAiActivity? Act = RynthAiActivity.None; + public int MasterCalls, AllowCalls = int.MaxValue; + public readonly List GemsUsed = new(); + public bool HasGem = true; + + public int Quits => FakeHost.ChatCommands.Count(c => c == "/rc quit"); + public int ChatCount(string part) => FakeHost.Chat.Count(c => c.Contains(part, StringComparison.OrdinalIgnoreCase)); + + public void Step(long ms) { T += ms; V.Tick(T); } + public void Inside() => FakeHost.PlayerPose = ((Quarry << 16) | 0x0100u, 0, 0, 0); + public void Outside() => FakeHost.PlayerPose = ((Elsewhere << 16) | 0x0100u, 0, 0, 0); + public string SettingsFile => Path.Combine(Dir, "VaultedDungeons", "settings.json"); + public void WriteSettings(string json) + { + Directory.CreateDirectory(Path.GetDirectoryName(SettingsFile)!); + File.WriteAllText(SettingsFile, json); + } + } + + private static Rig NewRig(string world, string folder, bool master, bool busyCalls = false) + { + FakeHost.Reset(); + FakeHost.WorldName = world; + FakeHost.BusyCalls = busyCalls; + var host = FakeHost.Create(Player); + var rig = new Rig { Master = master, Dir = Path.Combine(Program.TempRoot, folder) }; + Directory.CreateDirectory(rig.Dir); + rig.Hub = new IltHubController(host, rig.Dir, new IltSettings(), new RynthAiClient(host)); + rig.V = rig.Hub.VaultedDungeons; + rig.V.Clock = () => rig.T; + rig.V.MasterEnabled = () => { rig.MasterCalls++; return rig.Master && rig.MasterCalls <= rig.AllowCalls; }; + rig.V.Activity = () => rig.Act; + rig.V.UseGem = name => { if (!rig.HasGem) return false; rig.GemsUsed.Add(name); return true; }; + rig.Outside(); + return rig; + } + + /// Dungeon 1 (Tyrant's Quarry), the primary gem, the given extras. "active": true is on disk to prove it is ignored. + private static string Settings(string extras = "") + => "{ \"active\": true, \"dungeon\": 1, \"gem\": 1" + (extras.Length > 0 ? ", " + extras : "") + " }"; + + // ── ILT only ───────────────────────────────────────────────────────────── + + private static void NotIlt() + { + var rig = NewRig("Aelrynth", "vd-notilt", master: true); + rig.WriteSettings(Settings("\"autoStart\": true, \"quit\": true, \"quitMinutes\": 1")); + string before = File.ReadAllText(rig.SettingsFile); + + rig.Outside(); + for (int i = 0; i < 20; i++) rig.Step(1000); + rig.Inside(); + for (int i = 0; i < 10; i++) rig.Step(30_000); + Check.False(rig.V.IsActive, "not running on another world, though the master is on and Auto Start was saved"); + Check.Eq(rig.GemsUsed.Count, 0, "no recall gem"); + Check.Eq(rig.Quits, 0, "no /rc quit"); + Check.Eq(FakeHost.ChatCommands.Count, 0, "no command of any kind (no /vt, /ub or /rc)"); + Check.Eq(rig.ChatCount("[Vaulted Dungeons]"), 0, "and not a word in chat"); + Check.Eq(File.ReadAllText(rig.SettingsFile), before, "the settings file wasn't even read or rewritten"); + + rig.V.HandleCommand(new[] { "on" }); + Check.False(rig.V.IsActive, "/ilt vaulted on is refused"); + Check.Eq(rig.ChatCount("Not available on this server"), 1, "with the 'not available on this server' reply"); + FakeHost.Chat.Clear(); + rig.V.HandleCommand(new[] { "status" }); + Check.Eq(rig.ChatCount("Not available on this server"), 1, "status says the same"); + Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "no tab"); + Check.False(rig.Hub.SectionAvailable(IltSection.VaultedDungeons), "not available"); + + // The controller doesn't tick it either (and the module would refuse anyway). + rig.Hub.Tick(); + Check.Eq(rig.GemsUsed.Count, 0, "the controller's tick does nothing here"); + } + + // ── Master switch ──────────────────────────────────────────────────────── + + private static void MasterOff() + { + var rig = NewRig("InfiniteLeaftide", "vd-masteroff", master: false); + rig.WriteSettings(Settings("\"autoStart\": true, \"quit\": true, \"quitMinutes\": 1, \"disableMeta\": true")); + string before = File.ReadAllText(rig.SettingsFile); + + rig.Outside(); + for (int i = 0; i < 20; i++) rig.Step(1000); + rig.Inside(); + for (int i = 0; i < 10; i++) rig.Step(30_000); // five minutes inside: a one-minute Kill Client would have fired + Check.False(rig.V.IsActive, "off: a saved Active and Auto Start start nothing"); + Check.Eq(rig.GemsUsed.Count, 0, "no recall gem"); + Check.Eq(rig.Quits, 0, "no /rc quit"); + Check.Eq(FakeHost.ChatCommands.Count, 0, "no arrival commands (/vt opt set ...) either"); + Check.Eq(rig.ChatCount("[Vaulted Dungeons]"), 0, "silent"); + Check.Eq(File.ReadAllText(rig.SettingsFile), before, "settings untouched"); + Check.True(rig.Hub.Options.IsIltLikeWorld, "(it is an ILT world: the master switch is what holds it)"); + Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "the tab is hidden"); + Check.False(rig.Hub.SectionAvailable(IltSection.VaultedDungeons), "and not available"); + + rig.V.HandleCommand(new[] { "on" }); + Check.False(rig.V.IsActive, "/ilt vaulted on is refused"); + Check.Eq(rig.ChatCount("Settings > Navigation"), 1, "and says where the switch is"); + rig.V.HandleCommand(new[] { "toggle" }); + Check.False(rig.V.IsActive, "toggle too"); + + // Through the controller, the real wiring: nothing either. + for (int i = 0; i < 5; i++) rig.Hub.Tick(); + Check.Eq(rig.GemsUsed.Count, 0, "the controller's tick does nothing while off"); + + // The lines that restart the timer are ignored too (nothing is running). + rig.V.OnChat(Luminance); + rig.V.OnKillNotification(); + Check.Eq(rig.Quits, 0, "still nothing"); + } + + // ── Recalls ────────────────────────────────────────────────────────────── + + private static void ExplicitStartRecalls() + { + var rig = NewRig("InfiniteLeaftide", "vd-recall", master: true); + rig.WriteSettings(Settings()); // "active": true on disk: ignored + rig.Outside(); + rig.Step(0); + Check.False(rig.V.IsActive, "a saved Active is not resumed after login"); + for (int i = 0; i < 10; i++) rig.Step(1000); + Check.Eq(rig.GemsUsed.Count, 0, "so nothing is recalled until the player starts it"); + + rig.V.HandleCommand(new[] { "on" }); + Check.True(rig.V.IsActive, "an explicit start"); + rig.Step(0); // first tick outside: the clock starts + rig.Step(500); + Check.Eq(rig.GemsUsed.Count, 0, "0.5 s out: too early"); + rig.Step(500); // 1 s + Check.Eq(rig.GemsUsed.Count, 1, "the first recall comes 1 s after leaving"); + Check.Eq(rig.GemsUsed[0], "Primary Portal Recall Gem", "the chosen gem"); + rig.Step(4000); + Check.Eq(rig.GemsUsed.Count, 1, "4 s later: not yet"); + rig.Step(1000); // 5 s since the last use + Check.Eq(rig.GemsUsed.Count, 2, "then every 5 s"); + rig.Step(5000); + Check.Eq(rig.GemsUsed.Count, 3, "again"); + + rig.Inside(); + rig.Step(1000); + for (int i = 0; i < 12; i++) rig.Step(1000); + Check.Eq(rig.GemsUsed.Count, 3, "inside the dungeon: no more gems"); + + FakeHost.Portaling = true; + rig.Outside(); + rig.Step(10_000); + Check.Eq(rig.GemsUsed.Count, 3, "portal space: nothing used"); + FakeHost.Portaling = false; + rig.Step(0); + rig.Step(1000); + Check.Eq(rig.GemsUsed.Count, 4, "out again: 1 s, then a recall"); + + rig.HasGem = false; + rig.Step(5000); + Check.Eq(rig.GemsUsed.Count, 4, "no gem in the pack: none used"); + Check.True(rig.ChatCount("No Primary Portal Recall Gem") >= 1, "and it says so"); + } + + private static void AutoStart() + { + // Master on: arriving in the chosen dungeon switches it on, and the arrival commands go out. + var on = NewRig("InfiniteLeaftide", "vd-auto-on", master: true); + on.WriteSettings(Settings("\"autoStart\": true, \"disableMeta\": true")); + on.Inside(); + on.Step(0); + Check.True(on.V.IsActive, "Auto Start On Arrival switches the keeper on (master on)"); + Check.True(FakeHost.ChatCommands.Contains("/vt opt set EnableMeta False"), "and runs the arrival commands"); + + // Auto Start off, master on: a relog inside does not resume a saved Active. + var manual = NewRig("InfiniteLeaftide", "vd-auto-off", master: true); + manual.WriteSettings(Settings("\"disableMeta\": true")); + manual.Inside(); + manual.Step(0); + Check.False(manual.V.IsActive, "no Auto Start: not resumed"); + Check.Eq(FakeHost.ChatCommands.Count, 0, "and the arrival commands wait for an Active keeper"); + + // Master off, Auto Start saved: nothing; then the master comes on while inside. + var gated = NewRig("InfiniteLeaftide", "vd-auto-gated", master: false); + gated.WriteSettings(Settings("\"autoStart\": true")); + gated.Inside(); + gated.Step(0); + Check.False(gated.V.IsActive, "master off: Auto Start does nothing"); + gated.Master = true; + gated.Step(1000); + Check.True(gated.V.IsActive, "with the master on, Auto Start (the player's own saved choice) applies"); + } + + // ── Kill Client ────────────────────────────────────────────────────────── + + private static Rig QuitRig(string folder, int minutes = 2) + { + var rig = NewRig("InfiniteLeaftide", folder, master: true); + rig.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": " + minutes)); + rig.Inside(); + rig.Step(0); + rig.V.HandleCommand(new[] { "on" }); + rig.Step(0); // inside: the no-kill clock starts here + return rig; + } + + private static void QuitOnceAndResets() + { + // Luminance line. + var rig = QuitRig("vd-quit-lum"); + rig.Step(119_000); + Check.Eq(rig.Quits, 0, "just under 2 minutes: no quit"); + rig.V.OnChat(Luminance); + rig.Step(119_000); + Check.Eq(rig.Quits, 0, "the luminance line restarted the timer"); + rig.Step(2_000); + Check.Eq(rig.Quits, 1, "2 minutes after the last kill: /rc quit"); + for (int i = 0; i < 10; i++) rig.Step(60_000); + Check.Eq(rig.Quits, 1, "and only once"); + // A kill after the quit went out doesn't arm a second one (once per activation). + rig.V.OnChat(Luminance); + for (int i = 0; i < 10; i++) rig.Step(60_000); + Check.Eq(rig.Quits, 1, "still once"); + + // The player's own killing blow. + rig = QuitRig("vd-quit-kill"); + rig.Step(110_000); + rig.V.OnKillNotification(); + rig.Step(110_000); + Check.Eq(rig.Quits, 0, "a killing blow restarted the timer"); + rig.Step(15_000); + Check.Eq(rig.Quits, 1, "and it fires after the next idle stretch"); + + // A pet capture. + rig = QuitRig("vd-quit-capture"); + rig.Step(110_000); + rig.V.OnChat("You have successfully siphoned the essence of the Olthoi Warrior."); + rig.Step(110_000); + Check.Eq(rig.Quits, 0, "a capture restarted the timer"); + rig.V.OnChat("The echo resonates perfectly."); + rig.Step(110_000); + Check.Eq(rig.Quits, 0, "so does the other success reply"); + rig.Step(15_000); + Check.Eq(rig.Quits, 1, "then it fires"); + + // Lines that are not kills don't restart it. + rig = QuitRig("vd-quit-noise"); + rig.Step(110_000); + rig.V.OnChat("You hit the Olthoi Warrior for 50 points of damage."); + rig.V.OnChat("The essence is not ready yet."); + rig.V.OnChat("Bob says, \"You've banked 5 Luminance.\""); // a player's chat, not the system line + rig.Step(15_000); + Check.Eq(rig.Quits, 1, "damage lines, a refused capture and someone else's chat don't count"); + + // The minutes are the player's setting: 1 minute here. + rig = QuitRig("vd-quit-1m", minutes: 1); + rig.Step(59_000); + Check.Eq(rig.Quits, 0, "1 minute setting: not yet"); + rig.Step(2_000); + Check.Eq(rig.Quits, 1, "fires at 1 minute"); + + // Off -> on again is a new activation: one more quit may be sent. + rig.V.HandleCommand(new[] { "off" }); + rig.V.HandleCommand(new[] { "on" }); + rig.Step(0); + rig.Step(61_000); + Check.Eq(rig.Quits, 2, "a new activation gets its own single quit"); + } + + private static void QuitNeverWhenGated() + { + // The master goes off, the timer would have fired: nothing is sent, and it stopped. + var rig = QuitRig("vd-quit-gated"); + rig.Step(100_000); + rig.Master = false; + rig.Step(30_000); + Check.Eq(rig.Quits, 0, "master off before the timer: no /rc quit"); + Check.False(rig.V.IsActive, "and the keeper is off"); + rig.Step(600_000); + Check.Eq(rig.Quits, 0, "ever"); + + // The master goes off between the timer firing and the send (asked again right before sending). + rig = QuitRig("vd-quit-race"); + rig.Step(100_000); + rig.AllowCalls = rig.MasterCalls + 1; // true at the top of the next tick, false when it re-checks + rig.Step(21_000); // the timer fires in this tick + Check.Eq(rig.Quits, 0, "master off between the timer firing and the send: not sent"); + Check.False(rig.V.IsActive, "the keeper stopped"); + Check.Eq(rig.ChatCount("Stopped"), 1, "said once"); + + // Not an ILT world any more (the world name changes): same. + rig = QuitRig("vd-quit-world"); + rig.Step(100_000); + FakeHost.WorldName = "Aelrynth"; + rig.Step(30_000); + Check.Eq(rig.Quits, 0, "world no longer ILT: no /rc quit"); + Check.False(rig.V.IsActive, "stopped"); + + // Not Active: the timer has nothing to do (the player turned it off). + rig = QuitRig("vd-quit-off"); + rig.V.HandleCommand(new[] { "off" }); + for (int i = 0; i < 10; i++) rig.Step(60_000); + Check.Eq(rig.Quits, 0, "Off: no quit"); + } + + // ── Combat / buff guard ────────────────────────────────────────────────── + + private static void BusyDefers() + { + var rig = NewRig("InfiniteLeaftide", "vd-busy", master: true, busyCalls: true); + rig.WriteSettings(Settings()); + rig.Outside(); + rig.Step(0); + rig.V.HandleCommand(new[] { "on" }); + rig.Act = RynthAiActivity.MacroRunning | RynthAiActivity.Combat; + rig.Step(0); + rig.Step(1000); + rig.Step(4000); + Check.Eq(rig.GemsUsed.Count, 0, "in combat: the recall is deferred"); + Check.Eq(rig.ChatCount("Waiting to use the Primary Portal Recall Gem"), 1, "and says why, once"); + rig.Step(20_000); + Check.Eq(rig.ChatCount("Waiting to use"), 1, "no repeat inside the 30 s warning cadence"); + rig.Step(10_000); + Check.Eq(rig.ChatCount("Waiting to use"), 2, "the warning comes again after 30 s"); + Check.Eq(rig.GemsUsed.Count, 0, "still nothing used"); + + rig.Act = RynthAiActivity.MacroRunning; // clear + rig.Step(100); + Check.Eq(rig.GemsUsed.Count, 1, "the first clear tick recalls (it was due all along)"); + + // Buffing, the server wait, looting, salvaging, crafting and RynthAi not answering all defer too. + foreach (RynthAiActivity? busy in new RynthAiActivity?[] + { RynthAiActivity.Buffing, RynthAiActivity.ServerAction, RynthAiActivity.Looting, RynthAiActivity.Salvaging, RynthAiActivity.Crafting, null }) + { + int before = rig.GemsUsed.Count; + rig.Act = busy; + rig.Step(6000); + Check.Eq(rig.GemsUsed.Count, before, $"busy ({(busy.HasValue ? busy.Value.ToString() : "RynthAi not ready")}): deferred"); + rig.Act = RynthAiActivity.None; + rig.Step(100); + Check.Eq(rig.GemsUsed.Count, before + 1, "and used once it is clear"); + } + + // The client's own busy hourglass. + FakeHost.BusyStateValue = 1; + int n = rig.GemsUsed.Count; + rig.Step(6000); + Check.Eq(rig.GemsUsed.Count, n, "the client is busy: deferred"); + FakeHost.BusyStateValue = 0; + rig.Step(100); + Check.Eq(rig.GemsUsed.Count, n + 1, "used when it clears"); + + // Busy never blocks the Kill Client (it is not a game action that can be lost). + var q = NewRig("InfiniteLeaftide", "vd-busy-quit", master: true); + q.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": 1")); + q.Inside(); + q.Step(0); + q.V.HandleCommand(new[] { "on" }); + q.Step(0); + q.Act = RynthAiActivity.Combat; + q.Step(61_000); + Check.Eq(q.Quits, 1, "a busy bot still gets its Kill Client"); + } + + // ── Master off mid-run ─────────────────────────────────────────────────── + + private static void MasterOffMidRun() + { + var rig = NewRig("InfiniteLeaftide", "vd-midrun", master: true); + rig.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": 1")); + rig.Outside(); + rig.Step(0); + rig.V.HandleCommand(new[] { "on" }); + rig.Step(0); + rig.Step(1000); + Check.Eq(rig.GemsUsed.Count, 1, "running: a recall went out"); + + rig.Master = false; + rig.Step(10); + Check.False(rig.V.IsActive, "the master went off: stopped on that very tick"); + Check.Eq(rig.ChatCount("Stopped"), 1, "and it said so"); + for (int i = 0; i < 20; i++) rig.Step(5000); + Check.Eq(rig.GemsUsed.Count, 1, "no more recalls"); + Check.Eq(rig.ChatCount("Stopped"), 1, "and the notice wasn't repeated"); + Check.Eq(rig.Quits, 0, "no quit"); + + rig.Master = true; + rig.Step(10); + Check.False(rig.V.IsActive, "turned back on: it starts Off, nothing resumes by itself"); + rig.Step(10_000); + Check.Eq(rig.GemsUsed.Count, 1, "nothing recalled"); + rig.V.HandleCommand(new[] { "on" }); + rig.Step(0); + rig.Step(1000); + Check.Eq(rig.GemsUsed.Count, 2, "until the player starts it again"); + + // The Mini Remote button path (posted to the pump) re-checks the switch as well. + rig.V.HandleCommand(new[] { "off" }); + rig.Master = false; + rig.Hub.Context.Post(() => rig.V.HandleCommand(new[] { "on" })); + rig.Hub.Tick(); + Check.False(rig.V.IsActive, "an On click that lands after the switch went off is refused"); + } + + // ── Tab, commands, file ────────────────────────────────────────────────── + + private static void TabAndFile() + { + var rig = NewRig("InfiniteLeaftide", "vd-tab", master: true); + Check.True(rig.Hub.TabShown(IltSection.VaultedDungeons), "ILT + master on: the tab is shown"); + Check.True(IltSections.Tabs.Contains(IltSection.VaultedDungeons), "it is one of the tab-bar tabs"); + Check.True(IltSections.IsTab(IltSection.VaultedDungeons), "a Mini Remote tab"); + Check.Eq(IltSections.TabId(IltSection.VaultedDungeons), "vaulted", "tab id"); + Check.True(IltSections.TryParse("vaulted", out var s) && s == IltSection.VaultedDungeons, "/ra hub open vaulted parses"); + Check.True(IltSections.TryParse("vaulted-dungeons", out s) && s == IltSection.VaultedDungeons, "and the long names"); + Check.True(RynthCore.Plugin.RynthILT.RynthILTPlugin.IsIltVerb(new[] { "hub", "open", "vaulted" }), "RynthILT takes '/ra hub open vaulted'"); + rig.Master = false; + Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "master off: hidden"); + + // The file: the format Silentkelpie's keeper wrote, kept. A start is saved. + rig = NewRig("InfiniteLeaftide", "vd-file", master: true); + rig.WriteSettings("""{ "dungeon": 3, "gem": 2, "quit": true, "quitMinutes": 7, "autoStart": false, "attackPower": 0.5 }"""); + rig.V.HandleCommand(new[] { "status" }); + Check.Eq(rig.ChatCount("dungeon=Wailing Cells, gem=Secondary Portal Recall Gem, kill-client=7m"), 1, "dungeon list and gem names as upstream"); + rig.V.HandleCommand(new[] { "on" }); + rig.Step(0); + string saved = File.ReadAllText(rig.SettingsFile); + Check.True(saved.Contains("\"active\": true") && saved.Contains("\"quitMinutes\": 7") && saved.Contains("\"dungeon\": 3"), + "saved in the same camelCase layout"); + + // A new session (relog) reads it back with Active Off. + var again = NewRig("InfiniteLeaftide", "vd-file", master: true); + FakeHost.Chat.Clear(); + again.V.HandleCommand(new[] { "status" }); + Check.True(again.ChatCount("Off — dungeon=Wailing Cells") == 1 && !again.V.IsActive, "the next session starts Off, with the same choices"); + } + + // The NativeAOT build (what ships) turns reflection-based System.Text.Json off, so the keeper's + // settings must use IltVaultedDungeonsJsonContext. This project runs on the normal runtime where + // reflection would still work, so assert the generated metadata exists and that the file layout + // is what the context (not an options object) produces. + private static void SourceGeneratedContext() + { + var ctx = IltVaultedDungeonsJsonContext.Default; + Check.True(ctx.Cfg != null, "the context has metadata for the settings type (IltVaultedDungeonsJsonContext.Default.Cfg)"); + Check.True(ctx.GetTypeInfo(typeof(IltVaultedDungeons.Cfg)) != null, "and resolves it by type"); + + var cfg = new IltVaultedDungeons.Cfg + { + Active = true, Dungeon = 3, Gem = 2, Quit = true, QuitMinutes = 7, ShowInDungeon = true, + AutoStart = true, DisableMeta = true, DisableNav = false, RepeatAttack = true, SetPower = true, AttackPower = 0.5f, + }; + string json = System.Text.Json.JsonSerializer.Serialize(cfg, ctx.Cfg); + Check.True(json.Contains("\"active\": true") && json.Contains("\"quitMinutes\": 7") && json.Contains("\"attackPower\": 0.5"), + "serializes indented with camelCase names"); + Check.True(json.Contains("\n"), "indented"); + + var back = System.Text.Json.JsonSerializer.Deserialize(json, ctx.Cfg); + Check.True(back != null, "round-trips"); + Check.True(back!.Active && back.Dungeon == 3 && back.Gem == 2 && back.Quit && back.QuitMinutes == 7 && back.ShowInDungeon + && back.AutoStart && back.DisableMeta && !back.DisableNav && back.RepeatAttack && back.SetPower && back.AttackPower == 0.5f, + "every field survives"); + + // The shape of the file Silentkelpie's keeper wrote (camelCase, partial) still reads. + var upstream = System.Text.Json.JsonSerializer.Deserialize( + """{ "dungeon": 2, "gem": 1, "quit": true, "quitMinutes": 5 }""", ctx.Cfg); + Check.True(upstream != null && upstream.Dungeon == 2 && upstream.Gem == 1 && upstream.Quit && upstream.QuitMinutes == 5 && !upstream.Active, + "a partial upstream file reads, missing fields keep their defaults"); + + bool threw = false; + try { System.Text.Json.JsonSerializer.Deserialize("{ not json", ctx.Cfg); } catch (System.Text.Json.JsonException) { threw = true; } + Check.True(threw, "a corrupt file still throws, which the keeper's bad-file copy relies on"); + } + + private static void CaptureLines() + { + Check.True(PetCaptureLines.IsSuccess("You have successfully siphoned the essence."), "siphoned"); + Check.True(PetCaptureLines.IsSuccess("The echo resonates perfectly."), "echo"); + Check.True(PetCaptureLines.IsSuccess("The essence is captured!"), "captured"); + Check.False(PetCaptureLines.IsSuccess("The creature is too strong to be siphoned."), "a refusal is not a success"); + Check.False(PetCaptureLines.IsSuccess("siphon failed"), "nor a failure"); + Check.False(PetCaptureLines.IsSuccess(""), "empty"); + } +} diff --git a/Tools/RynthILT.Tests/VaultedSwitchTests.cs b/Tools/RynthILT.Tests/VaultedSwitchTests.cs new file mode 100644 index 0000000..1a5124a --- /dev/null +++ b/Tools/RynthILT.Tests/VaultedSwitchTests.cs @@ -0,0 +1,64 @@ +using System; +using System.IO; +using RynthCore.Plugin.RynthILT.Hub; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The Vaulted Dungeons keeper's master switch moved from RynthAi's profile to RynthILT on 2026-10-20 +// (IltHubState.VaultedDungeonsEnabled, the ILT settings view). RynthAi mirrors it into the engine's +// Settings > Navigation row through RynthILT.Hub GetSetting / SetSetting, which offer it on ILT only. +internal static class VaultedSwitchTests +{ + public static void Register(Runner r) + { + r.Add("vaulted switch: RynthILT's own (off by default), what the keeper reads, offered to the engine row on ILT only", OwnSwitch); + r.Add("migration: the RynthAi profile's Vaulted Dungeons switch comes over once", ImportsSwitch); + } + + private static IltHubController NewHub(string world, string folder) + { + FakeHost.Reset(); + FakeHost.WorldName = world; + var host = FakeHost.Create(0x50000C01); + string dir = Path.Combine(Program.TempRoot, "vswitch-" + folder); + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + Directory.CreateDirectory(dir); + var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host)); + hub.OnLoginComplete("Vaulter", forceFromMigration: false); + return hub; + } + + private static void OwnSwitch() + { + var hub = NewHub("InfiniteLeaftide", "own"); + Check.False(hub.State.VaultedDungeonsEnabled, "off by default"); + Check.False(hub.VaultedDungeons.MasterEnabled(), "the keeper reads RynthILT's own switch (no RynthAi needed)"); + Check.False(hub.SectionAvailable(IltSection.VaultedDungeons), "no tab while off"); + Check.Eq(hub.GetSetting(RynthServerHub.SettingVaultedDungeons), 0, "offered to the engine row: off"); + Check.True(hub.SetSetting(RynthServerHub.SettingVaultedDungeons, 1), "the engine row (through RynthAi) sets it"); + Check.True(hub.State.VaultedDungeonsEnabled && hub.VaultedDungeons.MasterEnabled(), "on"); + Check.True(hub.SectionAvailable(IltSection.VaultedDungeons), "the tab shows on ILT"); + Check.Eq(hub.GetSetting("no-such-setting"), -1, "an unknown key isn't offered"); + Check.False(hub.SetSetting("no-such-setting", 1), "nor taken"); + + var off = NewHub("Aeshnidae", "off"); + Check.Eq(off.GetSetting(RynthServerHub.SettingVaultedDungeons), -1, "off ILT: not offered (the engine row hides)"); + } + + private static void ImportsSwitch() + { + string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Vaulter"); + Directory.CreateDirectory(legacy); + File.WriteAllText(Path.Combine(legacy, "Default.json"), "{ \"EnableVaultedDungeons\": true }"); + var state = new IltHubState(); + var lines = IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Vaulter"); + Check.True(state.VaultedDungeonsEnabled, "on in the RynthAi profile: on here"); + Check.True(lines.Exists(l => l.Contains("Vaulted Dungeons master switch on")), "logged"); + state.VaultedDungeonsEnabled = false; + IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Vaulter"); + Check.False(state.VaultedDungeonsEnabled, "copied once: RynthILT's later change stays"); + } +} diff --git a/Tools/RynthOracle.QuestPackGen/Program.cs b/Tools/RynthOracle.QuestPackGen/Program.cs new file mode 100644 index 0000000..b9d8fe5 --- /dev/null +++ b/Tools/RynthOracle.QuestPackGen/Program.cs @@ -0,0 +1,355 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; + +namespace RynthOracle.QuestPackGen; + +/// +/// Generates a server quest pack for RynthOracle from an ACE world-database dump. +/// +/// Every row of the world's `quest` table (the flags /myquests can show: ACE leaves out flags +/// without a row) becomes a pack row with its timer (min_Delta, seconds, before the server's +/// quest_mindelta_rate), its solve limit, its message, and who sets it (NPCs whose emotes +/// stamp, increment or update the flag; else NPCs that check it). The curated text stays +/// Advis's: for a flag in the base list the pack leaves Quest, Url and Hint empty (the plugin +/// keeps the base row's text and only fills empty fields), and a flag that only another +/// server's pack knows takes that pack's text. Base flags missing from the quest table get a +/// NotOnServer row, so the plugin hides them on this server (their status can never be read). +/// +internal static class Program +{ + // EmoteType (ACE.Entity.Enum.EmoteType) + private static readonly HashSet SetTypes = new() { 20, 22, 33, 60, 61, 70, 79, 81, 85, 86 }; + private static readonly HashSet CheckTypes = new() { 21, 30, 58, 80, 82 }; + + private static int Main(string[] args) + { + try + { + string server = Arg(args, "-server") ?? "Aelrynth"; + string resources = Arg(args, "-resources") ?? FindResources(); + // The server plugins (RynthServers\Plugins, since 2026-10-21; RynthOracle stays in RynthSuite). + string pluginsDir = Arg(args, "-plugins") ?? FindServerPlugins(); + string dump = Arg(args, "-dump") ?? NewestDump(); + // A server's pack lives in its server plugin (since 2026-10-21): Plugins\RynthCore.Plugin.Rynth\Resources. + string output = Arg(args, "-out") ?? Path.Combine(pluginsDir, + "RynthCore.Plugin.Rynth" + server, "Resources", $"quests.{server.ToLowerInvariant()}.csv"); + Console.WriteLine($"dump: {dump}"); + Console.WriteLine($"resources: {resources}"); + Console.WriteLine($"out: {output}"); + + var db = WorldDump.Read(dump); + Console.WriteLine($"read {db.Quests.Count} quests, {db.Names.Count} weenie names, {db.EmoteOwner.Count} emotes, {db.Actions.Count} quest emote actions"); + + Dictionary baseRows = Curated.Load(Path.Combine(resources, "quests.csv")); + var otherPacks = new Dictionary(StringComparer.OrdinalIgnoreCase); + // The other servers' packs, in their server plugins (Plugins\*\Resources\quests..csv). + foreach (string pack in Directory.GetDirectories(pluginsDir, "RynthCore.Plugin.Rynth*") + .Select(d => Path.Combine(d, "Resources")).Where(Directory.Exists) + .SelectMany(d => Directory.GetFiles(d, "quests.*.csv"))) + { + if (Path.GetFullPath(pack).Equals(Path.GetFullPath(output), StringComparison.OrdinalIgnoreCase)) continue; + foreach (var kv in Curated.Load(pack)) + otherPacks.TryAdd(kv.Key, kv.Value); + } + + // Who sets / checks each flag. + var setters = new Dictionary>(StringComparer.OrdinalIgnoreCase); + var checkers = new Dictionary>(StringComparer.OrdinalIgnoreCase); + foreach ((uint emoteId, int type, string message) in db.Actions) + { + var map = SetTypes.Contains(type) ? setters : CheckTypes.Contains(type) ? checkers : null; + if (map == null || !db.EmoteOwner.TryGetValue(emoteId, out uint wcid)) continue; + string flag = QuestName(message); + if (flag.Length == 0) continue; + string who = db.Names.TryGetValue(wcid, out string? n) && n.Length > 0 ? n + : db.ClassNames.TryGetValue(wcid, out string? c) ? c : $"wcid {wcid}"; + if (!map.TryGetValue(flag, out var set)) map[flag] = set = new SortedSet(StringComparer.OrdinalIgnoreCase); + set.Add(who); + } + + var sb = new StringBuilder(); + sb.Append("QuestFlag,Server,Quest,Url,Info,Hint,Repeatable,MinDelta,MaxSolves,Source,NotOnServer\n"); + int fromBase = 0, fromOther = 0, generated = 0, notOn = 0; + foreach (var q in db.Quests.OrderBy(q => q.Key, StringComparer.Ordinal)) + { + string flag = q.Key; + (uint minDelta, int maxSolves, string message) = q.Value; + string name = "", url = "", info = message, hint = ""; + if (baseRows.ContainsKey(flag)) fromBase++; + else if (otherPacks.TryGetValue(flag, out CuratedRow? o)) + { + fromOther++; + name = o.Name; url = o.Url; hint = o.Hint; + if (o.Info.Length > 0) info = o.Info; + } + else generated++; + + bool repeatable = minDelta > 0 || maxSolves == -1 || maxSolves > 1; + string source = setters.TryGetValue(flag, out var s) ? "set by " + Join(s) + : checkers.TryGetValue(flag, out var c) ? "checked by " + Join(c) : ""; + Row(sb, flag, server, name, url, info, hint, repeatable ? "TRUE" : "FALSE", + minDelta.ToString(CultureInfo.InvariantCulture), maxSolves.ToString(CultureInfo.InvariantCulture), source, ""); + } + foreach (string flag in baseRows.Keys.Where(f => !db.Quests.ContainsKey(f)).OrderBy(f => f, StringComparer.Ordinal)) + { + notOn++; + Row(sb, flag, server, "", "", "", "", "", "", "", "", "TRUE"); + } + + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))!); + File.WriteAllText(output, sb.ToString(), new UTF8Encoding(false)); + Console.WriteLine($"wrote {db.Quests.Count} quests: {fromBase} in the base list (Advis's text kept), {fromOther} named from another server's pack, {generated} new; {notOn} base flags not on {server}"); + return 0; + } + catch (Exception ex) + { + Console.Error.WriteLine("error: " + ex.Message); + return 1; + } + } + + /// ACE QuestManager.GetQuestName: everything before the first '@', lower case. + private static string QuestName(string message) + { + int at = message.IndexOf('@'); + return (at >= 0 ? message[..at] : message).Trim().ToLowerInvariant(); + } + + private static string Join(SortedSet names) => + names.Count <= 3 ? string.Join(", ", names) : string.Join(", ", names.Take(3)) + $" and {names.Count - 3} more"; + + private static void Row(StringBuilder sb, params string[] fields) + { + for (int i = 0; i < fields.Length; i++) + { + if (i > 0) sb.Append(','); + string f = fields[i].Replace("\r", " ").Replace("\n", " "); + if (f.IndexOfAny(new[] { ',', '"' }) >= 0) sb.Append('"').Append(f.Replace("\"", "\"\"")).Append('"'); + else sb.Append(f); + } + sb.Append('\n'); + } + + private static string? Arg(string[] args, string name) + { + for (int i = 0; i < args.Length - 1; i++) + if (args[i].Equals(name, StringComparison.OrdinalIgnoreCase)) return args[i + 1]; + return null; + } + + /// RynthOracle's Resources: in this tree, or the sibling RynthSuite checkout (RynthServers' layout). + private static string FindResources() => + FindUp(d => new[] { Path.Combine(d, "Plugins", "RynthCore.Plugin.RynthOracle", "Resources"), + Path.Combine(d, "RynthSuite", "Plugins", "RynthCore.Plugin.RynthOracle", "Resources") }) + ?? throw new InvalidOperationException("can't find RynthSuite's Plugins\\RynthCore.Plugin.RynthOracle\\Resources; pass -resources"); + + /// The Plugins folder that holds the server plugins (RynthAelrynth's). + private static string FindServerPlugins() => + FindUp(d => new[] { Path.Combine(d, "Plugins") }, p => Directory.Exists(Path.Combine(p, "RynthCore.Plugin.RynthAelrynth"))) + ?? throw new InvalidOperationException("can't find the server plugins (Plugins\\RynthCore.Plugin.RynthAelrynth); pass -plugins"); + + private static string? FindUp(Func candidates, Func? ok = null) + { + foreach (string start in new[] { Directory.GetCurrentDirectory(), AppContext.BaseDirectory }) + { + var dir = new DirectoryInfo(start); + while (dir != null) + { + foreach (string p in candidates(dir.FullName)) + if (Directory.Exists(p) && (ok == null || ok(p))) return p; + dir = dir.Parent; + } + } + return null; + } + + private static string NewestDump() + { + const string dir = @"C:\Aeshnidae\backups"; + string? f = Directory.Exists(dir) + ? Directory.GetFiles(dir, "aeshnidae_world-*.sql.gz").OrderByDescending(p => p, StringComparer.Ordinal).FirstOrDefault() + : null; + return f ?? throw new InvalidOperationException($"no aeshnidae_world-*.sql.gz in {dir}; pass -dump"); + } +} + +internal sealed record CuratedRow(string Name, string Url, string Info, string Hint); + +internal static class Curated +{ + public static Dictionary Load(string path) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (!File.Exists(path)) return map; + using var r = new StreamReader(path); + string? header = r.ReadLine(); + if (header == null) return map; + string[] h = CsvLine.Parse(header); + int Col(string n) => Array.FindIndex(h, x => x.Trim().Equals(n, StringComparison.OrdinalIgnoreCase)); + int flag = Col("QuestFlag"), name = Col("Quest"), url = Col("Url"), info = Col("Info"), hint = Col("Hint"); + if (flag < 0) return map; + while (r.ReadLine() is string line) + { + if (string.IsNullOrWhiteSpace(line)) continue; + string[] f = CsvLine.Parse(line); + string F(int i) => i >= 0 && i < f.Length ? f[i].Trim() : ""; + string key = F(flag).ToLowerInvariant(); + if (key.Length > 0) map.TryAdd(key, new CuratedRow(F(name), F(url), F(info), F(hint))); + } + return map; + } +} + +internal static class CsvLine +{ + public static string[] Parse(string line) + { + var fields = new List(); + var sb = new StringBuilder(); + bool q = false; + for (int i = 0; i < line.Length; i++) + { + char c = line[i]; + if (q) + { + if (c == '"') { if (i + 1 < line.Length && line[i + 1] == '"') { sb.Append('"'); i++; } else q = false; } + else sb.Append(c); + } + else if (c == '"') q = true; + else if (c == ',') { fields.Add(sb.ToString()); sb.Clear(); } + else sb.Append(c); + } + fields.Add(sb.ToString()); + return fields.ToArray(); + } +} + +/// The few world tables the pack needs, read from a mysqldump file (.sql or .sql.gz). +internal sealed class WorldDump +{ + public readonly Dictionary Quests = new(StringComparer.OrdinalIgnoreCase); + public readonly Dictionary ClassNames = new(); + public readonly Dictionary Names = new(); // PropertyString 1 (Name) + public readonly Dictionary EmoteOwner = new(); // emote id -> wcid + public readonly List<(uint EmoteId, int Type, string Message)> Actions = new(); + + public static WorldDump Read(string path) + { + var db = new WorldDump(); + using Stream file = File.OpenRead(path); + using Stream s = path.EndsWith(".gz", StringComparison.OrdinalIgnoreCase) ? new GZipStream(file, CompressionMode.Decompress) : file; + using var reader = new StreamReader(s, Encoding.UTF8); + + var columns = new Dictionary>(StringComparer.Ordinal); + string? creating = null; + string? inserting = null; + while (reader.ReadLine() is string line) + { + if (line.StartsWith("CREATE TABLE `", StringComparison.Ordinal)) + { + creating = line.Substring(14, line.IndexOf('`', 14) - 14); + columns[creating] = new List(); + continue; + } + if (creating != null) + { + string t = line.TrimStart(); + if (t.StartsWith("`", StringComparison.Ordinal)) columns[creating].Add(t.Substring(1, t.IndexOf('`', 1) - 1)); + else if (t.StartsWith(")", StringComparison.Ordinal)) creating = null; + continue; + } + if (line.StartsWith("INSERT INTO `", StringComparison.Ordinal)) + { + string table = line.Substring(13, line.IndexOf('`', 13) - 13); + inserting = IsWanted(table) ? table : null; + int v = line.IndexOf(" VALUES", StringComparison.Ordinal); + if (inserting != null && v >= 0) db.Take(inserting, columns, line[(v + 7)..]); + if (line.TrimEnd().EndsWith(";", StringComparison.Ordinal)) inserting = null; + continue; + } + if (inserting != null) + { + db.Take(inserting, columns, line); + if (line.TrimEnd().EndsWith(";", StringComparison.Ordinal)) inserting = null; + } + } + return db; + } + + private static bool IsWanted(string t) => + t is "quest" or "weenie" or "weenie_properties_string" or "weenie_properties_emote" or "weenie_properties_emote_action"; + + private void Take(string table, Dictionary> columns, string text) + { + if (!columns.TryGetValue(table, out List? cols)) return; + foreach (List row in Tuples(text)) + { + string? Get(string c) { int i = cols.IndexOf(c); return i >= 0 && i < row.Count ? row[i] : null; } + switch (table) + { + case "quest": + string name = (Get("name") ?? "").Trim().ToLowerInvariant(); + if (name.Length == 0) break; + uint.TryParse(Get("min_Delta"), NumberStyles.None, CultureInfo.InvariantCulture, out uint md); + int.TryParse(Get("max_Solves"), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int ms); + Quests[name] = (md, ms, (Get("message") ?? "").Trim()); + break; + case "weenie": + if (uint.TryParse(Get("class_Id"), out uint id)) ClassNames[id] = Get("class_Name") ?? ""; + break; + case "weenie_properties_string": + if (Get("type") == "1" && uint.TryParse(Get("object_Id"), out uint oid)) Names[oid] = Get("value") ?? ""; + break; + case "weenie_properties_emote": + if (uint.TryParse(Get("id"), out uint eid) && uint.TryParse(Get("object_Id"), out uint owner)) EmoteOwner[eid] = owner; + break; + case "weenie_properties_emote_action": + string? msg = Get("message"); + if (msg == null || !int.TryParse(Get("type"), out int type)) break; + if (uint.TryParse(Get("emote_Id"), out uint emote)) Actions.Add((emote, type, msg)); + break; + } + } + } + + /// The value tuples in a VALUES list fragment: "(1,'a\'b',NULL),(2,...);". + private static IEnumerable> Tuples(string text) + { + int i = 0; + while (true) + { + while (i < text.Length && text[i] != '(') i++; + if (i >= text.Length) yield break; + i++; + var row = new List(); + var sb = new StringBuilder(); + bool quoted = false, wasQuoted = false; + for (; i < text.Length; i++) + { + char c = text[i]; + if (quoted) + { + if (c == '\\' && i + 1 < text.Length) + { + char n = text[++i]; + sb.Append(n switch { 'n' => '\n', 'r' => '\r', 't' => '\t', '0' => '\0', _ => n }); + } + else if (c == '\'') quoted = false; + else sb.Append(c); + } + else if (c == '\'') { quoted = true; wasQuoted = true; } + else if (c == ',' || c == ')') + { + string v = sb.ToString(); + row.Add(!wasQuoted && v.Trim() == "NULL" ? null : v); + sb.Clear(); + wasQuoted = false; + if (c == ')') { i++; break; } + } + else sb.Append(c); + } + yield return row; + } + } +} diff --git a/Tools/RynthOracle.QuestPackGen/RynthOracle.QuestPackGen.csproj b/Tools/RynthOracle.QuestPackGen/RynthOracle.QuestPackGen.csproj new file mode 100644 index 0000000..11cd97e --- /dev/null +++ b/Tools/RynthOracle.QuestPackGen/RynthOracle.QuestPackGen.csproj @@ -0,0 +1,25 @@ + + + + + Exe + net10.0 + enable + enable + true + RynthOracle.QuestPackGen + + + diff --git a/Tools/RynthServerPack.Tests/AelrynthTests.cs b/Tools/RynthServerPack.Tests/AelrynthTests.cs new file mode 100644 index 0000000..0cfaaaf --- /dev/null +++ b/Tools/RynthServerPack.Tests/AelrynthTests.cs @@ -0,0 +1,170 @@ +using System; +using System.IO; +using System.Linq; +using RynthCore.Engine.UI.Sections; +using RynthCore.Plugin.RynthAelrynth; +using RynthCore.Plugin.ServerPack; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// RynthAelrynth's own features (Plugins\RynthCore.Plugin.RynthAelrynth\Aelrynth), moved out of +// RynthOracle on 2026-10-20: the /top and /trial reply parser (RynthOracle.Tests' old +// AelrynthReplies), the own-reply hiding, the setting taken over from rynthoracle.json and its page. +internal static class AelrynthTests +{ + public static void Register(Runner r) + { + r.Add("aelrynth: the replies of /top, /top me and /trial parse", Replies); + r.Add("aelrynth: replies to RynthAelrynth's own requests are hidden, typed ones show", HideOwnReplies); + r.Add("aelrynth: RynthOracle's reply-hiding choice is taken over once", Migration); + r.Add("aelrynth: its Leaderboards page is an Aelrynth-only view of the Server section", Pages); + r.Add("aelrynth: the difficulty tier (PropertyInt 9051) is published for other plugins, only on Aelrynth", DifficultyTier); + } + + private static void Replies() + { + var a = new AelrynthBoards(); + long now = 2_000_000; + a.RequestTop("", now); + Check.True(a.OnChatLine("Leaderboards - 37 characters, refreshed 4 min ago. /top for the top ten, /top me for yourself.", now, out bool ours) && ours, "overview header"); + a.OnChatLine(" kills Creature kills: Buffy, 1,234,567", now, out _); + a.OnChatLine(" pk PK kills: nobody yet", now, out _); + Check.True(a.Overview.Count == 2 && a.Overview[0].Key == "kills" && a.Overview[0].Leader == "Buffy" && a.Overview[0].Value == "1,234,567" + && a.Overview[1].Leader == "nobody yet", "overview rows"); + + a.RequestTop("kills", now); + a.OnChatLine("Creature kills - top 10 of 37:", now, out _); + a.OnChatLine(" 1. Buffy 1,234,567 <- you", now, out _); + a.OnChatLine(" 2. Dargoth 987,654", now, out _); + a.OnChatLine(" 3. Sal 500 12 kills per death", now, out _); + Check.True(a.BoardTitle == "Creature kills" && a.BoardRows.Count == 3 && a.BoardRows[0].IsYou && a.BoardRows[1].Value == "987,654" + && a.BoardRows[2].Extra == "12 kills per death", "board rows: " + string.Join(" | ", a.BoardRows.Select(r => $"{r.Rank} {r.Name} {r.Value} [{r.Extra}] {r.IsYou}"))); + + a.RequestTop("me", now); + a.OnChatLine("Buffy on the boards:", now, out _); + a.OnChatLine(" Creature kills #1 of 37, 1,234,567", now, out _); + a.OnChatLine(" PK kills -", now, out _); + Check.True(a.Standings.Count == 2 && a.Standings[0].Rank == 1 && a.Standings[1].Rank == 0, "/top me"); + + Check.False(a.OnChatLine(" 9. Nobody 12", now + 30_000, out _), "an entry long after its header is ignored"); + + a.RequestTrial("", now); + a.OnChatLine("Trials - a fresh personal copy of a listed dungeon, entered through its portal, is a timed course: ...", now, out _); + a.OnChatLine(" The Citadel Below - Trial (02F0): tier 0 12:34 by Buffy | you: tier 0 12:34 | this week: Buffy 12:34 (tier 0)", now, out _); + a.OnChatLine(" your next attempt here: in 12 min", now, out _); + a.OnChatLine("Trophy: the week's fastest clear of each dungeon, any tier - a trophy and 1,000 experience, Sunday 20:00 (2026-W40). /trial for the top 10 of one dungeon.", now, out _); + Check.True(a.Trials.Count == 1 && a.Trials[0].Landblock == "02F0" && a.TrialLines.Count == 3, $"/trial overview ({a.Trials.Count} dungeons, {a.TrialLines.Count} lines)"); + + a.RequestTrial("citadel", now); + a.OnChatLine("The Citadel Below - Trial (02F0) - top 10, best per character, any tier:", now, out _); + a.OnChatLine(" 1. 12:34 Buffy (tier 0, 105 kills, 3 Oct)", now, out _); + a.OnChatLine(" you: tier 0 12:34 (105 kills)", now, out _); + Check.True(a.TrialRows.Count == 1 && a.TrialRows[0].Name == "Buffy" && a.TrialRows[0].Value == "12:34" && a.TrialNotes.Count == 1, "/trial dungeon top 10"); + Check.False(a.OnChatLine("Bob tells you, \"hello\"", now, out _), "ordinary chat is never taken"); + } + + private static void HideOwnReplies() + { + var f = new AelrynthFeature(); + long now = 3_000_000; + f.Boards.RequestTop("", now); + Check.True(f.OnChatLine("Leaderboards - 3 characters, refreshed just now. /top ...", 0, now), "a reply to RynthAelrynth's /top is hidden"); + Check.True(f.OnChatLine(" kills Creature kills: Buffy, 12", 0, now), "and its rows"); + Check.False(f.OnChatLine("Leaderboards - 3 characters, refreshed just now. /top ...", 0, now + 60_000), "a typed /top's reply shows"); + Check.False(f.OnChatLine(" kills Creature kills: Ann, 14", 0, now + 60_000), "and its rows"); + Check.True(f.Boards.Overview.Count == 1 && f.Boards.Overview[0].Leader == "Ann", "read either way"); + f.HideOwnReplies = false; + f.Boards.RequestTrial("", now); + Check.False(f.OnChatLine("Trials - a fresh personal copy of a listed dungeon ...", 0, now), "with hiding off, own replies show too"); + Check.False(f.OnChatLine("Bob says, \"hi\"", 0, now), "ordinary chat shows"); + f.Reset(); + Check.True(f.Boards.Overview.Count == 0 && f.Boards.Trials.Count == 0, "login/logout clears the boards"); + } + + private static void Migration() + { + string dir = ServerPackHooksTests.TempDir(); + try + { + string oracle = Path.Combine(dir, "rynthoracle.json"), mine = Path.Combine(dir, "rynthaelrynth.json"); + File.WriteAllText(oracle, "{ \"hideOwnQuestReplies\": false }"); + var s = new ServerPackSettings(mine); + s.Load(); + Check.True(AelrynthFeature.Migrate(s, oracle), "taken over the first time"); + var f = new AelrynthFeature(); + f.LoadSettings(s); + Check.False(f.HideOwnReplies, "the player's choice (shown) came over"); + Check.False(AelrynthFeature.Migrate(s, oracle), "never twice"); + var fresh = new ServerPackSettings(Path.Combine(dir, "fresh.json")); + fresh.Load(); + AelrynthFeature.Migrate(fresh, Path.Combine(dir, "none.json")); + var g = new AelrynthFeature(); + g.LoadSettings(fresh); + Check.True(g.HideOwnReplies, "default: hidden"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + + private static void Pages() + { + var pages = ServerPackPages.Validate(AelrynthFeature.PageList.Select(p => new ServerPage(p.Id, p.Label, p.Tooltip, () => { }))); + Check.Eq(pages.Count, 1, "one page"); + ServerPackInfo info = new("aelrynth", "Aelrynth", new[] { "aelrynth.com" }, new[] { "Aelrynth*", "Aeshnidae*" }); + SectionManifest m = SectionManifestParser.Parse("RynthAelrynth", ServerPackModel.BuildSectionsJson(info, "RynthAelrynth", pages), out string error); + Check.Eq(error, "", "RynthCore parses the manifest"); + SectionContribution view = m.Contributions.Single(c => c.Primary); + Check.True(view.Server == "aelrynth" && view.Label == "Leaderboards" && view.Surface == "section:server-aelrynth.boards", + "Leaderboards, only while Aelrynth is active"); + } + + /// + /// AelrynthDifficulty (2026-10-21, RynthAi's AwakenedTier before): the tier the server sends as + /// PropertyInt 9051 goes into the profile's "values" with the 5% a tier, which RynthAi reads (through + /// ServerProfileView.Value) without knowing the server. + /// + private static void DifficultyTier() + { + Check.Eq(AelrynthDifficulty.TierProperty, 9051u, "PropertyInt 9051"); + Check.Eq((RynthCore.Plugin.Shared.RynthServerProfile.ValueDifficultyTier, RynthCore.Plugin.Shared.RynthServerProfile.ValueDifficultyHealthPercent), + ("difficultyTier", "difficultyHealthPercent"), "the value names RynthAi reads"); + var d = new AelrynthDifficulty(); + var values = new ServerProfileValues(); + int? property = null; + int reads = 0; + int? Read() { reads++; return property; } + ServerPackInfo info = new("aelrynth", "Aelrynth", new[] { "aelrynth.com" }, new[] { "Aelrynth*", "Aeshnidae*" }); + string Json() => ServerPackProfile.BuildJson(info, "RynthAelrynth", "0.2.0", true, "Aelrynth", values.Snapshot(out _)); + double Tier() => RynthCore.Plugin.Shared.ServerProfileView.Value(Json(), "difficultyTier", -1); + double Percent() => RynthCore.Plugin.Shared.ServerProfileView.Value(Json(), "difficultyHealthPercent", -1); + + long now = 1_000_000; + d.Tick(now, active: true, Read, values); + Check.True(d.Tier == null && values.Snapshot(out _).Length == 0, "the server hasn't sent the tier: nothing published (RynthAi stays at tier 0)"); + + property = 3; + d.Tick(now + 100, active: true, Read, values); + Check.Eq(reads, 1, "read at most every ReadMs"); + d.Tick(now + AelrynthDifficulty.ReadMs, active: true, Read, values); + Check.Eq(d.Tier, (int?)3, "tier 3 seen"); + Check.Eq((Tier(), Percent()), (3.0, 5.0), "published: tier 3, +5% health a tier"); + + property = null; + d.Tick(now + 2 * AelrynthDifficulty.ReadMs, active: true, Read, values); + Check.Eq(Tier(), 3.0, "a failed read keeps the last tier"); + property = 0; + d.Tick(now + 3 * AelrynthDifficulty.ReadMs, active: true, Read, values); + Check.Eq((Tier(), Percent()), (0.0, 5.0), "back in real Dereth: tier 0 (still a server with tiers)"); + property = -2; + d.Tick(now + 4 * AelrynthDifficulty.ReadMs, active: true, Read, values); + Check.Eq(Tier(), 0.0, "a negative tier reads as 0"); + + property = 7; + d.Tick(now + 5 * AelrynthDifficulty.ReadMs, active: false, Read, values); + Check.True(d.Tier == null && Tier() == -1 && Percent() == -1, "off Aelrynth (RynthCore's verdict): both values taken out"); + d.Tick(now + 6 * AelrynthDifficulty.ReadMs, active: true, Read, values); + Check.Eq(Tier(), 7.0, "and read again once it is Aelrynth"); + d.Reset(); + Check.True(d.Tier == null && d.Describe().Contains("not sent"), "login and logout forget the tier (logout clears the values)"); + } +} diff --git a/Tools/RynthServerPack.Tests/ConquestTests.cs b/Tools/RynthServerPack.Tests/ConquestTests.cs new file mode 100644 index 0000000..3c08bc8 --- /dev/null +++ b/Tools/RynthServerPack.Tests/ConquestTests.cs @@ -0,0 +1,216 @@ +using System; +using System.IO; +using System.Linq; +using RynthCore.Engine.UI.Sections; +using RynthCore.Plugin.RynthConquest; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.ServerPack; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// RynthConquest's own features (Plugins\RynthCore.Plugin.RynthConquest\Conquest), moved out of +// RynthOracle on 2026-10-20: the reply parser (RynthOracle.Tests' old ConquestReplies), the +// own-reply hiding, the login /augs, the auto-deposit, the settings taken over from rynthoracle.json, +// the Void DoT rule it publishes, the custom quest list and its pages. +internal static class ConquestTests +{ + public static void Register(Runner r) + { + r.Add("conquest: the replies of /b, /augs, /enl augs, /bonus, /fship list and /top parse", Replies); + r.Add("conquest: replies to RynthConquest's own requests are hidden, typed ones show", HideOwnReplies); + r.Add("conquest: /augs once after login, then never again", LoginAugs); + r.Add("conquest: the auto-deposit is off unless turned on, then once per ten-minute mark", AutoDeposit); + r.Add("conquest: RynthOracle's settings are taken over once (defaults kept without them)", Migration); + r.Add("conquest: the Void DoT rule for RynthOracle's timers", VoidRule); + r.Add("conquest: the custom quest worklist and its status", CustomQuests); + r.Add("conquest: its pages are Conquest-only views of the Server section", Pages); + } + + private static void Replies() + { + var d = new ConquestData(); + long now = 1_000_000; + d.RequestBank(now); + Check.True(d.OnChatLine("[BANK] Your balances:", now, out bool ours) && ours, "bank heading (ours)"); + d.OnChatLine("[BANK] Pyreals: 1,039,678,533", now, out _); + d.OnChatLine("[BANK] Event Tokens [Dragon Coins] (x): 12", now, out _); + Check.True(d.Bank.Any(b => b.Name == "Pyreals" && b.Value.Contains("4,158 MMDs")), "pyreals with MMDs"); + Check.True(d.Bank.Any(b => b.Name == "Dragon Coins (x)"), "event token name"); + Check.False(d.OnChatLine("Bob says, \"[BANK] Pyreals: 999\"", now, out _), "a pasted balance is ignored"); + d.OnChatLine("[BANK] Pyreals: 5", now + 60_000, out bool late); + Check.False(late, "a reply long after the request isn't ours (shows in chat)"); + + d.RequestAugs(now); + d.OnChatLine("Creature: 25", now, out _); + d.OnChatLine("Duration: 3", now, out _); + ConquestAug creature = d.Augs.First(a => a.Name == "Creature"); + Check.True(creature.Count == 25 && creature.NextLuminanceCost() == 6_229_500, $"Creature 25 next costs 6,229,500 ({creature.NextLuminanceCost()})"); + Check.True(d.DurationAugs == 3 && Math.Abs(d.VoidDurationMultiplier(5) - 2.15) < 1e-9, "void duration x(1 + 5*0.2 + 3*0.05)"); + + d.RequestEnl(now); + d.OnChatLine("Enlightenment Augmentations:", now, out _); + d.OnChatLine("Skill Credits: 2 (10 max)", now, out _); + d.OnChatLine("Damage: 5 (25 max)", now, out _); + Check.True(d.EnlAugs.Count == 2 && d.EnlAugs[0].Name == "Damage", "enlightenment augs in display order"); + + d.RequestBonus(now); + d.OnChatLine("=== XP Bonuses ===", now, out _); + d.OnChatLine("Quest Bonus: 14.18% (1,418 quests)", now, out _); + d.OnChatLine("Total Bonus (Kills): 0.16%", now, out _); + Check.True(d.Bonuses.First(b => b.Name == "Quest").Value == "14.18% (1,418 quests)" && d.Bonuses.First(b => b.Name == "Total (Kills)").Value == "0.16%", "bonuses"); + + d.RequestFships(now); + d.OnChatLine("Fellowships looking for members:", now, out _); + d.OnChatLine("- Heroes (Leader: Bob) [3/14] @ Bur", now, out _); + d.OnChatLine("- Quiet (Leader: Ann) [1/14]", now, out _); + Check.True(d.Fellowships.Count == 2 && d.Fellowships[0].Location == "Bur" && d.Fellowships[1].MemberCount == 1, "fellowship list"); + + ConquestBoard lvl = d.Boards.First(b => b.Key == "level"); + d.RequestBoard(lvl, now); + d.OnChatLine("Top 2 Players by Level:", now, out _); + d.OnChatLine("1: 300 - Alpha", now, out _); + d.OnChatLine("2: 299 - Beta", now, out _); + d.OnChatLine("57: 250 - Me (You)", now, out _); + Check.True(lvl.Rows.Count == 2 && lvl.You != null && lvl.You.Rank == 57 && lvl.You.Name == "Me", "Conquest /top board"); + + Check.Eq(ConquestData.WithdrawCommand(ConquestData.Withdrawable[ConquestData.DefaultWithdraw], "10"), "/bank withdraw n 10", "withdraw MMDs"); + Check.Null(ConquestData.WithdrawCommand(ConquestData.Withdrawable[0], "-3"), "withdraw refuses a bad amount"); + Check.Eq(ConquestData.TransferCommand(ConquestData.Transferable[2], "4", "Some One"), "/bank transfer p 1000000 \"Some One\"", "transfer MMD notes as pyreals"); + Check.Null(ConquestData.TransferCommand(ConquestData.Transferable[2], "1001", "X"), "transfer cap"); + } + + private static void HideOwnReplies() + { + var f = new ConquestFeature(); + f.Login(0); + long now = 100_000; + f.Data.RequestBank(now); + Check.True(f.OnChatLine("[BANK] Pyreals: 1,000", now), "a reply to RynthConquest's /b is hidden"); + Check.False(f.OnChatLine("[BANK] Pyreals: 1,000", now + 60_000), "the same reply long after (typed /b) shows"); + Check.False(f.OnChatLine("Bob says, \"hello\"", now), "ordinary chat shows"); + f.HideOwnReplies = false; + f.Data.RequestBank(now); + Check.False(f.OnChatLine("[BANK] Pyreals: 1,000", now), "with hiding off, own replies show too"); + f.HideOwnReplies = true; + + // /myquests: only RynthConquest's own request's reply is hidden; the flags are read either way. + Check.True(f.Flags.Request(_ => true, now), "own /myquests sent"); + Check.True(f.OnChatLine("assaultonaimaru - 1 solves (1719432000)\"x\" -1 0", now), "its reply is hidden"); + f.Flags.Tick(now + 2000); + Check.True(f.Flags.TryGet("assaultonaimaru", out _), "and read"); + Check.False(f.OnChatLine("ghostdencompleted - 1 solves (1719432000)\"x\" -1 0", now + 3000), "a reply nobody here asked for shows"); + Check.True(f.Data.AutoDeposit(now).Length > 0 && f.OnChatLine("Deposited 12 items.", now), "the auto-deposit's reply is hidden"); + } + + private static void LoginAugs() + { + var f = new ConquestFeature(); + f.Login(1000); + Check.Null(f.LoginAugsDue(1000 + ConquestFeature.AugsReadDelayMs), "not before the delay"); + Check.Eq(f.LoginAugsDue(1001 + ConquestFeature.AugsReadDelayMs), "/augs", "/augs after it"); + Check.Null(f.LoginAugsDue(5_000_000), "only once"); + f.Login(9_000_000); + Check.Eq(f.LoginAugsDue(9_000_001 + ConquestFeature.AugsReadDelayMs), "/augs", "again for the next login"); + } + + private static void AutoDeposit() + { + var f = new ConquestFeature(); + f.Login(0); + var at = new DateTime(2026, 10, 20, 14, 0, 5, DateTimeKind.Local); + Check.False(f.AutoDeposit, "off by default (as it was in RynthOracle)"); + Check.Null(f.AutoDepositDue(at, 0), "off: no deposit at :00"); + f.AutoDeposit = true; + Check.Eq(f.AutoDepositDue(at, 0), "/bank deposit", "on: /bank deposit at :00"); + Check.Null(f.AutoDepositDue(at.AddSeconds(30), 0), "once per mark"); + Check.Null(f.AutoDepositDue(at.AddMinutes(5), 0), "not at :05"); + Check.Eq(f.AutoDepositDue(at.AddMinutes(10), 0), "/bank deposit", "again at :10"); + long block = -1; + Check.True(ConquestFeature.DepositDue(new DateTime(2026, 1, 1, 0, 20, 0), ref block), "the schedule: :20"); + Check.False(ConquestFeature.DepositDue(new DateTime(2026, 1, 1, 0, 21, 0), ref block), "the schedule: not :21"); + } + + private static void Migration() + { + string dir = ServerPackHooksTests.TempDir(); + try + { + string oracle = Path.Combine(dir, "rynthoracle.json"), mine = Path.Combine(dir, "rynthconquest.json"); + File.WriteAllText(oracle, "{ \"hideOwnQuestReplies\": false, \"conquestAutoDeposit\": true, \"tabName\": \"Conquest\" }"); + var s = new ServerPackSettings(mine); + s.Load(); + Check.True(ConquestFeature.Migrate(s, oracle), "taken over the first time"); + var f = new ConquestFeature(); + f.LoadSettings(s); + Check.True(f.AutoDeposit, "auto-deposit came over (on)"); + Check.False(f.HideOwnReplies, "hiding came over (off)"); + + // Turned off here later: a newer rynthoracle.json never turns it back on. + f.AutoDeposit = false; + f.SaveSettings(s); + var again = new ServerPackSettings(mine); + again.Load(); + Check.False(ConquestFeature.Migrate(again, oracle), "never taken over twice"); + var g = new ConquestFeature(); + g.LoadSettings(again); + Check.False(g.AutoDeposit, "the player's choice here stands"); + + // A new player (no RynthOracle settings): the defaults. + string fresh = Path.Combine(dir, "fresh.json"); + var n = new ServerPackSettings(fresh); + n.Load(); + Check.True(ConquestFeature.Migrate(n, Path.Combine(dir, "missing.json")), "runs (nothing to take)"); + var h = new ConquestFeature(); + h.LoadSettings(n); + Check.True(!h.AutoDeposit && h.HideOwnReplies, "defaults: auto-deposit off, own replies hidden"); + Check.True(new ServerPackSettings(fresh) is var reread && Reload(reread) && reread.GetBool(ConquestFeature.MigrationMarker, false), + "the marker is saved"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + + private static bool Reload(ServerPackSettings s) { s.Load(); return true; } + + private static void VoidRule() + { + var f = new ConquestFeature(); + f.Login(0); + Check.Eq(f.VoidScale, 1.0, "no augs, no Archmage's Endurance: x1"); + f.ArchmagesEndurance = 5; + f.Data.RequestAugs(0); + f.Data.OnChatLine("Duration: 3", 0, out _); + Check.Near(f.VoidScale, 2.15, 1e-9, "x(1 + 5*0.2 + 3*0.05)"); + Check.Eq(ConquestFeature.VoidScaleKey, "voidDotDurationScale", "the profile value RynthOracle reads"); + } + + private static void CustomQuests() + { + Check.Eq(CustomQuestList.All.Count, 6, "six custom quests (customquests.csv, embedded)"); + Check.True(CustomQuestList.All.All(q => q.Server == "Conquest" && q.Flag.Length > 0 && q.Flag == q.Flag.ToLowerInvariant()), "Conquest rows, flags in lower case"); + var flags = new QuestFlagStore(); + CustomQuest darsh = CustomQuestList.All.First(q => q.Flag == "assaultonaimaru"); + DateTime now = DateTime.UtcNow; + Check.False(darsh.IsComplete(flags, now), "not done without the flag"); + Check.Eq(darsh.Status(flags, now), "ready", "ready without the flag"); + long done = DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 60; + flags.OnChatLine($"assaultonaimaru - 1 solves ({done})\"x\" -1 3600", 0); + flags.Tick(5000); + Check.True(darsh.IsComplete(flags, now), "a repeatable on cooldown counts as done"); + Check.True(darsh.Status(flags, now) is not ("ready" or "completed") && darsh.Status(flags, now).Contains('m'), "its status is the time left: " + darsh.Status(flags, now)); + } + + private static void Pages() + { + var pages = ServerPackPages.Validate(ConquestFeature.PageList.Select(p => new ServerPage(p.Id, p.Label, p.Tooltip, () => { }))); + Check.Eq(pages.Count, ConquestFeature.PageList.Length, "every page is valid"); + Check.True(pages.Select(p => p.Label).SequenceEqual(new[] { "Conquest", "Leaderboards" }), "the Conquest and Leaderboards pages"); + ServerPackInfo info = new("conquest", "Conquest", new[] { "acconquest.ddns.net" }, new[] { "Conquest", "ConquestAC" }); + SectionManifest m = SectionManifestParser.Parse("RynthConquest", ServerPackModel.BuildSectionsJson(info, "RynthConquest", pages), out string error); + Check.Eq(error, "", "RynthCore parses the manifest"); + SectionContribution[] views = m.Contributions.Where(c => c.Primary).ToArray(); + Check.Eq(views.Length, 2, "two pages in the Mini Remote"); + Check.True(views.All(c => c.Server == "conquest"), "shown only while Conquest is active"); + Check.True(views.Select(c => c.Surface).SequenceEqual(new[] { "section:server-conquest.main", "section:server-conquest.boards" }), "their surfaces"); + } +} diff --git a/Tools/RynthServerPack.Tests/LevistrasTests.cs b/Tools/RynthServerPack.Tests/LevistrasTests.cs new file mode 100644 index 0000000..08c7f5b --- /dev/null +++ b/Tools/RynthServerPack.Tests/LevistrasTests.cs @@ -0,0 +1,122 @@ +using System; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Xml.Linq; +using RynthCore.App; +using RynthCore.PluginSdk.Manifest; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// RynthLevistras (2026-10-21): the Levistras server plugin, and the launcher's server list +// (RynthCore.App\KnownServerCatalog.cs), which names a server plugin for every server it offers. +internal static class LevistrasTests +{ + public static void Register(Runner r) + { + r.Add("levistras: the plugin's detection data matches the launcher's Levistras entry", Detection); + r.Add("levistras: its card says bots are forbidden and two accounts", Card); + r.Add("levistras: its quest pack is the 464 Levistras rows RynthOracle had", Pack); + r.Add("launcher catalog: every server names a plugin that claims its host, port and emulator", Catalog); + } + + private static string PluginsDir() + { + string? dir = AppContext.BaseDirectory; + while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) + dir = Path.GetDirectoryName(dir); + if (dir == null) throw new DirectoryNotFoundException("RynthSuite\\Plugins not found above " + AppContext.BaseDirectory); + return Path.Combine(dir, "Plugins"); + } + + private sealed record Plugin(string Dir, string Id, string Name, string[] Hosts, string[] Worlds, string ServerData); + + /// The server plugin project named Rynth<name>, or null. + private static Plugin? Load(string pluginName) + { + string dir = Path.Combine(PluginsDir(), "RynthCore.Plugin." + pluginName); + string csproj = Path.Combine(dir, "RynthCore.Plugin." + pluginName + ".csproj"); + if (!File.Exists(csproj)) return null; + XDocument doc = XDocument.Load(csproj); + string Prop(string name) => doc.Descendants(name).FirstOrDefault()?.Value.Trim() ?? ""; + string[] Split(string v) => v.Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + string data = Path.Combine(dir, "ServerData.cs"); + return new Plugin(dir, Prop("RynthPluginServerId"), Prop("RynthPluginServerName"), Split(Prop("RynthPluginServerHosts")), + Split(Prop("RynthPluginServerWorldNames")), File.Exists(data) ? File.ReadAllText(data) : ""); + } + + /// The port ServerData.cs sets (9000 when it doesn't say). + private static int PortOf(Plugin p) + { + Match m = Regex.Match(p.ServerData, @"\bPort\s*=\s*(\d+)"); + return m.Success ? int.Parse(m.Groups[1].Value) : 9000; + } + + private static string EmulatorOf(Plugin p) + { + Match m = Regex.Match(p.ServerData, @"\bEmulator\s*=\s*""([^""]*)"""); + return m.Success ? m.Groups[1].Value : "ACE"; + } + + private static void Detection() + { + Plugin? p = Load("RynthLevistras"); + Check.NotNull(p, "RynthLevistras exists"); + if (p == null) return; + Check.Eq(p.Id, "levistras", "id"); + Check.Eq(p.Name, "Levistras", "name (also its quest pack's tag)"); + Check.True(p.Hosts.SequenceEqual(new[] { "levistras.acportalstorm.com" }), "host: " + string.Join("|", p.Hosts)); + Check.True(p.Worlds.Contains("Levistras"), "world name Levistras (the name RynthOracle matched before the move)"); + + KnownServer? k = KnownServerCatalog.FindById("levistras"); + Check.NotNull(k, "the launcher lists Levistras"); + if (k == null) return; + Check.Eq(k.PluginName, "RynthLevistras", "the launcher's entry names RynthLevistras"); + var server = new RynthPluginServer { Id = p.Id, Hosts = p.Hosts.ToList() }; + Check.True(server.MatchesHost(k.Host, out _), "the plugin claims the launcher's host " + k.Host); + Check.Eq(PortOf(p), k.Port, "port"); + Check.Eq(EmulatorOf(p), "ACE", "emulator"); + Check.Eq(k.Emulator, AcEmulatorKind.Ace, "the launcher connects with ACE"); + } + + private static void Card() + { + Plugin? p = Load("RynthLevistras"); + if (p == null) { Check.True(false, "RynthLevistras exists"); return; } + Check.True(p.ServerData.Contains("Botting = BottingPolicy.Forbidden"), "botting forbidden (the server card warns, RynthAi's combat isn't for here)"); + Check.True(p.ServerData.Contains("AccountLimit = \"2 accounts\""), "two accounts"); + Check.True(p.ServerData.Contains("Ruleset = \"PvE\""), "PvE"); + } + + private static void Pack() + { + Plugin? p = Load("RynthLevistras"); + if (p == null) { Check.True(false, "RynthLevistras exists"); return; } + string file = Path.Combine(p.Dir, "Resources", "quests.levistras.csv"); + Check.True(File.Exists(file), "Resources\\quests.levistras.csv (ServerPlugin.props embeds it as the served pack)"); + if (!File.Exists(file)) return; + string csv = File.ReadAllText(file); + Check.Eq(RynthCore.Plugin.ServerPack.ServerPackQuestPack.CountRows(csv), 464, "464 quests"); + var info = new RynthCore.Plugin.ServerPack.ServerPackInfo(p.Id, p.Name, p.Hosts, p.Worlds); + string json = RynthCore.Plugin.ServerPack.ServerPackQuestPack.BuildInfoJson(info, "RynthLevistras", "0.1.0", csv); + Check.True(json.Contains("\"server\":\"levistras\"") && json.Contains("\"tag\":\"Levistras\"") && json.Contains("\"rows\":464"), + "offered as levistras / Levistras, 464 rows: " + json); + Check.True(File.Exists(Path.Combine(p.Dir, "THIRD_PARTY_NOTICES.md")), "the pack's MIT notice (Advis Eveldan's rows) comes with it"); + } + + private static void Catalog() + { + foreach (KnownServer k in KnownServerCatalog.All) + { + Plugin? p = Load(k.PluginName); + Check.NotNull(p, $"{k.Id}: the launcher's plugin {k.PluginName} exists"); + if (p == null) continue; + Check.Eq(p.Id, k.Id, $"{k.PluginName}: the same server id as the launcher"); + var server = new RynthPluginServer { Id = p.Id, Hosts = p.Hosts.ToList() }; + Check.True(server.MatchesHost(k.Host, out _), $"{k.PluginName} claims the launcher's host {k.Host}"); + Check.Eq(PortOf(p), k.Port, $"{k.PluginName}: port"); + Check.Eq(EmulatorOf(p).Equals("GDLE", StringComparison.OrdinalIgnoreCase), k.Emulator == AcEmulatorKind.Gdle, $"{k.PluginName}: emulator"); + } + } +} diff --git a/Tools/RynthServerPack.Tests/Program.cs b/Tools/RynthServerPack.Tests/Program.cs new file mode 100644 index 0000000..60fae99 --- /dev/null +++ b/Tools/RynthServerPack.Tests/Program.cs @@ -0,0 +1,24 @@ +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// Offline tests for the server plugins: the shared model and every server plugin's detection data. +// +// Run: dotnet run -c Release (all tests) +// dotnet run -c Release -- host (tests whose name contains "host") +internal static class Program +{ + private static int Main(string[] args) + { + var runner = new Runner(); + ServerPackModelTests.Register(runner); + ServerProjectsTests.Register(runner); + ServerPackHooksTests.Register(runner); + ConquestTests.Register(runner); + AelrynthTests.Register(runner); + VaultTests.Register(runner); + QuestPackTests.Register(runner); + LevistrasTests.Register(runner); + return runner.Run("RynthServerPack tests", args.Length > 0 ? args[0] : null); + } +} diff --git a/Tools/RynthServerPack.Tests/QuestPackTests.cs b/Tools/RynthServerPack.Tests/QuestPackTests.cs new file mode 100644 index 0000000..9eafc5e --- /dev/null +++ b/Tools/RynthServerPack.Tests/QuestPackTests.cs @@ -0,0 +1,154 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.ServerPack; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// "RynthServer.QuestPack" (Plugins\Shared\ServerPack\ServerPackQuestPack.cs): a server plugin's own quest +// list for RynthOracle. The info JSON says whose pack it is and how big; junk is no pack at all. +internal static class QuestPackTests +{ + public static void Register(Runner r) + { + r.Add("quest pack: the info JSON names the server, its tag and the pack's size", InfoJson); + r.Add("quest pack: no pack, junk or a header alone is no pack", NoPack); + r.Add("quest pack: the info JSON is plain ASCII and escaped", InfoAscii); + r.Add("quest pack: the embedded pack is served as it is (RynthConquest's)", Embedded); + r.Add("quest packs: Conquest's, Levistras's and Aelrynth's are their own plugins' (none left in RynthOracle)", Projects); + } + + private static string PluginsDir() + { + string? dir = AppContext.BaseDirectory; + while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) + dir = Path.GetDirectoryName(dir); + if (dir == null) throw new DirectoryNotFoundException("RynthSuite\\Plugins not found above " + AppContext.BaseDirectory); + return Path.Combine(dir, "Plugins"); + } + + /// RynthSuite's Plugins: the sibling checkout this repo builds against (RynthOracle lives there). + private static string SuitePluginsDir() + { + string? dir = AppContext.BaseDirectory; + while (dir != null && !Directory.Exists(Path.Combine(dir, "RynthSuite", "Plugins", "RynthCore.Plugin.RynthOracle"))) + dir = Path.GetDirectoryName(dir); + if (dir == null) throw new DirectoryNotFoundException("the sibling RynthSuite\\Plugins not found above " + AppContext.BaseDirectory); + return Path.Combine(dir, "RynthSuite", "Plugins"); + } + + private static void Embedded() + { + string csv = ServerPackQuestPack.Csv; + Check.Eq(ServerPackQuestPack.CountRows(csv), 546, "RynthConquest's 546 quests are served"); + var conquest = new ServerPackInfo("conquest", "Conquest", new[] { "acconquest.ddns.net" }, new[] { "Conquest" }); + using JsonDocument doc = JsonDocument.Parse(ServerPackQuestPack.BuildInfoJson(conquest, "RynthConquest", "0.2.0", csv)); + Check.Eq(doc.RootElement.GetProperty("rows").GetInt32(), 546, "the info says so"); + Check.Eq(doc.RootElement.GetProperty("tag").GetString(), "Conquest", "under the tag the master list uses"); + Check.True(ReferenceEquals(csv, ServerPackQuestPack.Csv), "read once"); + } + + /// + /// The packs that were RynthOracle's (2026-10-21): each in its server's plugin, as + /// Resources\quests.<server id>.csv (ServerPlugin.props embeds it), naming only that server; the + /// same rows as before; none left in RynthOracle, which keeps only the retail list. + /// + private static void Projects() + { + string plugins = PluginsDir(); + var expected = new Dictionary + { + ["conquest"] = ("RynthCore.Plugin.RynthConquest", "Conquest", 546), + ["levistras"] = ("RynthCore.Plugin.RynthLevistras", "Levistras", 464), + ["aelrynth"] = ("RynthCore.Plugin.RynthAelrynth", "Aelrynth", 4277), + }; + foreach (var kv in expected) + { + string file = Path.Combine(plugins, kv.Value.Dir, "Resources", $"quests.{kv.Key}.csv"); + Check.True(File.Exists(file), kv.Value.Dir + " has its pack " + Path.GetFileName(file)); + if (!File.Exists(file)) continue; + string csv = File.ReadAllText(file); + Check.True(ServerPackQuestPack.Usable(csv), kv.Key + ": a quest list (QuestFlag header and rows)"); + Check.Eq(ServerPackQuestPack.CountRows(csv), kv.Value.Rows, kv.Key + ": the same rows as before the move"); + string[] lines = csv.Replace("\r", "").Split('\n', StringSplitOptions.RemoveEmptyEntries); + string[] header = lines[0].Split(','); + int server = Array.FindIndex(header, h => h.Trim().Equals("Server", StringComparison.OrdinalIgnoreCase)); + Check.True(server >= 0, kv.Key + ": has a Server column"); + int other = lines.Skip(1).Count(l => l.Split(',')[server].Trim() != kv.Value.Name); + Check.Eq(other, 0, $"{kv.Key}: every row's Server is {kv.Value.Name} (the pack's tag, the plugin's server name)"); + string csproj = File.ReadAllText(Path.Combine(plugins, kv.Value.Dir, kv.Value.Dir + ".csproj")); + Check.True(csproj.Contains("" + kv.Key + "") + && csproj.Contains("" + kv.Value.Name + ""), + kv.Value.Dir + ": the pack's file name is its server id, the rows' Server its server name"); + } + + // No other server plugin carries a pack, and none carries another server's. + foreach (string dir in Directory.GetDirectories(plugins, "RynthCore.Plugin.Rynth*")) + { + string res = Path.Combine(dir, "Resources"); + if (!Directory.Exists(res)) continue; + foreach (string f in Directory.GetFiles(res, "quests.*.csv")) + { + string id = Path.GetFileNameWithoutExtension(f).Substring("quests.".Length); + Check.True(expected.TryGetValue(id, out var e) && Path.GetFileName(dir) == e.Dir, $"{Path.GetFileName(dir)}/{Path.GetFileName(f)} is in its own server's plugin"); + } + } + string oracle = Path.Combine(SuitePluginsDir(), "RynthCore.Plugin.RynthOracle"); + string[] left = Directory.GetFiles(Path.Combine(oracle, "Resources"), "quests*.csv").Select(Path.GetFileName).ToArray()!; + Check.True(left.SequenceEqual(new[] { "quests.csv" }), "RynthOracle keeps only the retail list: " + string.Join(",", left)); + Check.False(File.ReadAllText(Path.Combine(oracle, "RynthCore.Plugin.RynthOracle.csproj")).Contains("quests.conquest", StringComparison.OrdinalIgnoreCase), + "and embeds no server's pack"); + string props = File.ReadAllText(Path.Combine(plugins, "Shared", "ServerPack", "ServerPlugin.props")); + Check.True(props.Contains("quests.$(RynthPluginServerId).csv") && props.Contains("LogicalName=\"" + ServerPackQuestPack.ResourceName + "\""), + "ServerPlugin.props embeds Resources\\quests..csv as the served pack"); + } + + private const string Sample = + "QuestFlag,Server,Quest,Url,Info,Hint,Repeatable\n" + + "aaaflag,Example,A quest,,,,FALSE\n" + + "\n" + + "bbbflag,Example,\"Another, with a comma\",,,,TRUE\n"; + + private static ServerPackInfo Example() => new("Example", "Example", new[] { "play.example.test" }, new[] { "Example" }); + + private static void InfoJson() + { + string json = ServerPackQuestPack.BuildInfoJson(Example(), "RynthExample", "0.1.0", Sample); + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + Check.Eq(root.GetProperty("schema").GetInt32(), ServerPackQuestPack.Schema, "schema"); + Check.Eq(root.GetProperty("server").GetString(), "example", "server: the RynthCore id (lower case)"); + Check.Eq(root.GetProperty("tag").GetString(), "Example", "tag: the server's name (the master list's Server column)"); + Check.Eq(root.GetProperty("plugin").GetString(), "RynthExample", "plugin"); + Check.Eq(root.GetProperty("version").GetString(), "0.1.0", "version"); + Check.Eq(root.GetProperty("rows").GetInt32(), 2, "rows: data lines, blank ones skipped"); + Check.Eq(root.GetProperty("bytes").GetInt32(), System.Text.Encoding.UTF8.GetByteCount(Sample), "bytes: the CSV's UTF-8 length"); + Check.Eq(root.GetProperty("revision").GetInt32(), ServerPackQuestPack.Revision, "revision"); + Check.Eq(ServerPackQuestPack.CountRows(Sample), 2, "CountRows"); + Check.True(ServerPackQuestPack.Usable("QuestFlag,Server\nx,Example\n"), "a BOM before the header is fine"); + Check.True(ServerPackQuestPack.Usable("Flag,Quest\r\nx,y\r\n"), "Flag works as the column name too (CRLF lines)"); + } + + private static void NoPack() + { + ServerPackInfo info = Example(); + Check.Eq(ServerPackQuestPack.BuildInfoJson(info, "RynthExample", "0.1.0", null), "", "null: no pack"); + Check.Eq(ServerPackQuestPack.BuildInfoJson(info, "RynthExample", "0.1.0", ""), "", "empty: no pack"); + Check.Eq(ServerPackQuestPack.BuildInfoJson(info, "RynthExample", "0.1.0", "QuestFlag,Server\n"), "", "a header alone: no pack"); + Check.Eq(ServerPackQuestPack.BuildInfoJson(info, "RynthExample", "0.1.0", "Name,Notes\na,b\n"), "", "no QuestFlag column: no pack"); + Check.False(ServerPackQuestPack.Usable("404"), "junk is not usable"); + } + + private static void InfoAscii() + { + var odd = new ServerPackInfo("odd", "Odd \"Name\" é", new[] { "a" }, Array.Empty()); + string json = ServerPackQuestPack.BuildInfoJson(odd, "Rynth\\Odd", "1", Sample); + foreach (char c in json) Check.True(c >= 0x20 && c <= 0x7e, "plain ASCII: " + (int)c); + using JsonDocument doc = JsonDocument.Parse(json); + Check.Eq(doc.RootElement.GetProperty("tag").GetString(), "Odd \"Name\" é", "quotes and accents survive"); + Check.Eq(doc.RootElement.GetProperty("plugin").GetString(), "Rynth\\Odd", "backslash survives"); + } +} diff --git a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj new file mode 100644 index 0000000..e8aca60 --- /dev/null +++ b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj @@ -0,0 +1,67 @@ + + + + + Exe + net10.0 + enable + true + + true + RynthServerPack.Tests + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs new file mode 100644 index 0000000..f6d75e2 --- /dev/null +++ b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using RynthCore.Engine.UI.Sections; +using RynthCore.Plugin.ServerPack; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// The shared hooks a server plugin's own features use (2026-10-20, when RynthOracle's and +// RynthInventory's Conquest and Aelrynth features moved into RynthConquest and RynthAelrynth): +// pages beside the server card, the plugin's own settings file (with a one-time migration), live +// numbers in the "RynthServer.Profile" JSON, and the own-reply window. +internal static class ServerPackHooksTests +{ + public static void Register(Runner r) + { + r.Add("hooks: page ids, surfaces and the surface a page is drawn under", PageNames); + r.Add("hooks: bad, duplicate and surplus pages are left out", PageValidation); + r.Add("hooks: pages are server-only primary views of the Server section, accepted by RynthCore's parser", PagesInManifest); + r.Add("hooks: settings round-trip and keep values the plugin doesn't know", SettingsRoundTrip); + r.Add("hooks: settings migration runs once, and a broken file means defaults", SettingsMigration); + r.Add("hooks: profile values are published, validated and read back", ProfileValues); + r.Add("hooks: the own-reply window opens, stretches and closes", ReplyWindow); + } + + internal static string TempDir() + { + string dir = Path.Combine(Path.GetTempPath(), "RynthServerPack.Tests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + return dir; + } + + private static void PageNames() + { + Check.True(ServerPackPages.IsValidId("bank") && ServerPackPages.IsValidId("top-10"), "plain ids"); + Check.False(ServerPackPages.IsValidId("") || ServerPackPages.IsValidId("Bank") || ServerPackPages.IsValidId("a.b") + || ServerPackPages.IsValidId(new string('a', 17)), "empty, capitals, dots and long ids are refused"); + Check.Eq(ServerPackPages.SurfaceFor("conquest", "bank"), "section:server-conquest.bank", "surface"); + Check.Eq(ServerPackPages.PageIdOf("section:server-conquest.bank", "conquest"), "bank", "page from its surface"); + Check.Eq(ServerPackPages.PageIdOf("section:server-conquest.bank:popout", "conquest"), "bank", "popped out"); + Check.Null(ServerPackPages.PageIdOf("section:server-conquest", "conquest"), "the card is not a page"); + Check.Null(ServerPackPages.PageIdOf("section:server-aelrynth.top", "conquest"), "another server's page"); + Check.Null(ServerPackPages.PageIdOf("section:server-conquest.Bad!", "conquest"), "a malformed page id"); + Check.Null(ServerPackPages.PageIdOf(null, "conquest"), "null"); + string longest = ServerPackPages.SurfaceFor(new string('a', 32), new string('b', ServerPackPages.MaxIdLength)); + Check.True(longest.Length <= SectionManifestParser.MaxSurfaceLength, "the longest surface fits RynthCore's cap: " + longest.Length); + } + + private static void PageValidation() + { + Action draw = () => { }; + var notes = new List(); + var pages = new List + { + new("one", "One", "", draw), new("one", "Again", "", draw), new("Two", "Two", "", draw), + new("three", " ", "", draw), new("four", "Four", "tip", null!), + }; + for (int i = 0; i < 8; i++) pages.Add(new ServerPage("p" + i, "Page " + i, "", draw)); + List kept = ServerPackPages.Validate(pages, notes.Add); + Check.Eq(kept.Count, ServerPackPages.MaxPages, "capped"); + Check.Eq(kept[0].Id, "one", "first kept"); + Check.Eq(kept.Count(p => p.Id == "one"), 1, "a duplicate id is dropped"); + Check.False(kept.Any(p => p.Id is "Two" or "three" or "four"), "bad id, no label, nothing to draw"); + Check.True(notes.Count == pages.Count - kept.Count, "every dropped page is reported: " + string.Join(" | ", notes)); + Check.Eq(ServerPackPages.Validate(null).Count, 0, "no pages"); + string label = new string('x', 60); + Check.Eq(ServerPackPages.Validate(new[] { new ServerPage("x", label, "", draw) })[0].Label.Length, ServerPackPages.MaxLabelLength, "label capped"); + } + + private static void PagesInManifest() + { + ServerPackInfo info = new("conquest", "Conquest", new[] { "acconquest.ddns.net" }, new[] { "Conquest" }); + var pages = ServerPackPages.Validate(new[] + { + new ServerPage("main", "Conquest", "Bank, augs and more", () => { }), + new ServerPage("boards", "Leaderboards", "", () => { }), + }); + string json = ServerPackModel.BuildSectionsJson(info, "RynthConquest", pages); + SectionManifest m = SectionManifestParser.Parse("RynthConquest", json, out string error); + Check.Eq(error, "", "RynthCore parses it"); + Check.Eq(m.Contributions.Length, 3, "the card and two pages"); + SectionContribution card = m.Contributions.Single(c => !c.Primary); + Check.Eq(card.Surface, "section:server-conquest", "the card keeps its surface"); + SectionContribution[] views = m.Contributions.Where(c => c.Primary).ToArray(); + Check.True(views.All(c => c.Section == ServerPackModel.SectionId && c.Server == "conquest" && c.IsSurface), + "pages: primary views of the Server section, only on Conquest"); + Check.Eq(views[0].Surface, "section:server-conquest.main", "page surface"); + Check.Eq(views[0].Label, "Conquest", "page label"); + Check.Eq(views[0].Tooltip, "Bank, augs and more", "page tooltip"); + Check.Eq(views[1].Tooltip, "Leaderboards (RynthConquest)", "a default tooltip"); + Check.True(views[0].Order < views[1].Order, "pages keep their order"); + Check.True(views[0].Width > 0 && views[0].Height > 0, "pages say their size"); + + // Without pages the manifest is byte for byte what it was. + Check.Eq(ServerPackModel.BuildSectionsJson(info, "RynthConquest", null), ServerPackModel.BuildSectionsJson(info, "RynthConquest"), + "no pages: the old manifest"); + Check.Eq(SectionManifestParser.Parse("x", ServerPackModel.BuildSectionsJson(info, "RynthConquest"), out _).Contributions.Length, 1, + "no pages: only the card"); + } + + private static void SettingsRoundTrip() + { + string dir = TempDir(); + try + { + string path = Path.Combine(dir, "rynthtest.json"); + File.WriteAllText(path, "{ \"future\": {\"a\":[1,2]}, \"flag\": false, \"name\": \"x\" }"); + var s = new ServerPackSettings(path); + s.Load(); + Check.Eq(s.LastError, "", "read"); + Check.False(s.GetBool("flag", true), "a stored false"); + Check.True(s.GetBool("missing", true), "a missing value falls back"); + Check.True(s.GetBool("name", true), "a value of another type falls back"); + Check.Eq(s.GetString("name", "?"), "x", "text"); + Check.True(s.SetBool("flag", true), "a change says so"); + Check.False(s.SetBool("flag", true), "the same value is no change"); + s.SetString("quote", "a \"b\" \\ c"); + Check.True(s.Save(), "saved"); + + var again = new ServerPackSettings(path); + again.Load(); + Check.True(again.GetBool("flag", false), "the change was kept"); + Check.Eq(again.GetString("quote", ""), "a \"b\" \\ c", "text escaped and read back"); + using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path)); + Check.Eq(doc.RootElement.GetProperty("future").GetProperty("a").GetArrayLength(), 2, "an unknown value is written back as it was"); + Check.False(File.Exists(path + ".tmp"), "no temporary file left"); + Check.True(ServerPackSettings.DefaultPath("RynthConquest").EndsWith(Path.Combine("RynthCore", "rynthconquest.json"), StringComparison.Ordinal), + "%APPDATA%\\RynthCore\\.json"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + + private static void SettingsMigration() + { + string dir = TempDir(); + try + { + string old = Path.Combine(dir, "old.json"), mine = Path.Combine(dir, "mine.json"); + File.WriteAllText(old, "{ \"moved\": true, \"text\": \"t\" }"); + Check.Eq(ServerPackSettings.ReadBoolFrom(old, "moved"), (bool?)true, "the old home's value"); + Check.Null(ServerPackSettings.ReadBoolFrom(old, "text"), "not a true/false value"); + Check.Null(ServerPackSettings.ReadBoolFrom(old, "absent"), "missing value"); + Check.Null(ServerPackSettings.ReadBoolFrom(Path.Combine(dir, "nope.json"), "moved"), "missing file"); + + var s = new ServerPackSettings(mine); + s.Load(); + int runs = 0; + Action migrate = t => { runs++; if (ServerPackSettings.ReadBoolFrom(old, "moved") is bool b) t.SetBool("moved", b); }; + Check.True(s.MigrateOnce("migratedFromOld", migrate), "runs the first time"); + Check.True(s.GetBool("moved", false), "imported"); + File.WriteAllText(old, "{ \"moved\": false }"); + var later = new ServerPackSettings(mine); + later.Load(); + Check.False(later.MigrateOnce("migratedFromOld", migrate), "never again (the marker was saved)"); + Check.True(later.GetBool("moved", false), "later changes to the old home don't come over"); + Check.Eq(runs, 1, "ran once"); + + File.WriteAllText(mine, "{ not json"); + var broken = new ServerPackSettings(mine); + broken.Load(); + Check.True(broken.LastError.Length > 0 && broken.GetBool("moved", true), "a broken file reads as defaults"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + + private static void ProfileValues() + { + var v = new ServerProfileValues(); + int r0 = v.Revision; + Check.True(v.Set("voidDotDurationScale", 1.35), "set"); + Check.True(v.Revision > r0, "a change bumps the revision"); + int r1 = v.Revision; + Check.True(v.Set("voidDotDurationScale", 1.35) && v.Revision == r1, "the same value is no change"); + Check.False(v.Set("bad key", 1) || v.Set("", 1) || v.Set("x", double.NaN) || v.Set("y", double.PositiveInfinity), "bad keys and numbers"); + + ServerPackInfo info = new("conquest", "Conquest", new[] { "h" }, new[] { "Conquest" }); + string json = ServerPackProfile.BuildJson(info, "RynthConquest", "0.2.0", true, "Conquest", v.Snapshot(out int rev)); + Check.Eq(rev, v.Revision, "the snapshot's revision"); + Check.Near(RynthCore.Plugin.Shared.ServerProfileView.Value(json, "voidDotDurationScale", 1), 1.35, 1e-12, "a reader gets the value"); + Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value(json, "other", 7), 7.0, "a missing value falls back"); + Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("", "voidDotDurationScale", 1), 1.0, "no profile falls back"); + Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("{\"values\":{\"k\":\"2\"}}", "k", 1), 1.0, "text is not a number"); + Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("{broken", "k", 3), 3.0, "broken JSON falls back"); + using (JsonDocument doc = JsonDocument.Parse(ServerPackProfile.BuildJson(info, "RynthConquest", "0.2.0", true, "Conquest"))) + Check.Eq(doc.RootElement.GetProperty("values").EnumerateObject().Count(), 0, "no values: an empty object"); + + Check.True(v.Remove("voidDotDurationScale") && !v.Remove("voidDotDurationScale"), "remove"); + v.Set("a", 1); + int r2 = v.Revision; + v.Clear(); + Check.True(v.Revision > r2 && v.Snapshot(out _).Length == 0, "clear (logout)"); + } + + private static void ReplyWindow() + { + var req = new ServerChatRequest(); + Check.False(req.Awaiting(0), "nothing asked"); + req.Sent(1000); + Check.True(req.Awaiting(1000 + ServerChatRequest.WindowMs - 1), "inside the window"); + Check.False(req.Awaiting(1000 + ServerChatRequest.WindowMs), "the window closes"); + req.Sent(1000); + req.Extend(5500); + Check.True(req.Awaiting(7000), "a reply line stretches it"); + req.Clear(); + Check.False(req.Awaiting(1001), "cleared"); + } +} diff --git a/Tools/RynthServerPack.Tests/ServerPackModelTests.cs b/Tools/RynthServerPack.Tests/ServerPackModelTests.cs new file mode 100644 index 0000000..f77ac4c --- /dev/null +++ b/Tools/RynthServerPack.Tests/ServerPackModelTests.cs @@ -0,0 +1,243 @@ +using System; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.ServerPack; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// The shared server-plugin model (Plugins\Shared\ServerPack\ServerPackModel.cs): RynthCore's +// "servermenu" verdict for the plugin's own server, the world-name fallback before one arrives, +// the override commands the card sends, and the sections manifest RynthCore reads. +internal static class ServerPackModelTests +{ + public static void Register(Runner r) + { + r.Add("server pack: RynthCore's push gives this server's verdict, override and reason", EnginePush); + r.Add("server pack: a push without this server, or not a push, changes nothing", ForeignPush); + r.Add("server pack: before any push the world name decides", WorldFallback); + r.Add("server pack: override commands are checked before sending", ForceCommands); + r.Add("server pack: the sections manifest declares the server and a server-only card", SectionsJson); + r.Add("server pack: logout clears the verdict", ClearOnLogout); + r.Add("server pack: the card's botting line and address", InfoText); + r.Add("server pack: the RynthServer.Profile JSON carries the server's settings", ProfileJson); + r.Add("server pack: the profile JSON is plain ASCII and escaped", ProfileJsonAscii); + } + + private static void ProfileJson() + { + ServerPackInfo info = new("Coldeve", "Coldeve", new[] { "play.coldeve.ac" }, new[] { "Coldeve" }) + { + Port = 9050, Ruleset = "PvP", Status = "Stable", Botting = BottingPolicy.Restricted, BottingNote = "attended only", + AccountLimit = "3 accounts", Facts = new[] { "fact one" }, Commands = new[] { new ServerCommand("/x", "does x") }, + Discord = "https://discord.gg/x", + }; + string json = ServerPackProfile.BuildJson(info, "RynthColdeve", "0.1.2", true, "Coldeve"); + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + Check.Eq(root.GetProperty("schema").GetInt32(), ServerPackProfile.Schema, "schema"); + Check.Eq(root.GetProperty("id").GetString(), "coldeve", "id (lower-cased)"); + Check.Eq(root.GetProperty("plugin").GetString(), "RynthColdeve", "plugin"); + Check.Eq(root.GetProperty("version").GetString(), "0.1.2", "version"); + Check.True(root.GetProperty("active").GetBoolean(), "active"); + Check.Eq(root.GetProperty("world").GetString(), "Coldeve", "world"); + Check.Eq(root.GetProperty("hosts")[0].GetString(), "play.coldeve.ac", "hosts"); + Check.Eq(root.GetProperty("port").GetInt32(), 9050, "port"); + Check.Eq(root.GetProperty("ruleset").GetString(), "PvP", "ruleset"); + Check.Eq(root.GetProperty("botting").GetString(), "restricted", "botting"); + Check.Eq(root.GetProperty("bottingNote").GetString(), "attended only", "botting note"); + Check.Eq(root.GetProperty("facts")[0].GetString(), "fact one", "facts"); + Check.Eq(root.GetProperty("commands")[0].GetProperty("what").GetString(), "does x", "commands"); + Check.Eq(root.GetProperty("discord").GetString(), "https://discord.gg/x", "links"); + + // What a reader (RynthOracle, RynthAi's /ra server) makes of it. + var view = RynthCore.Plugin.Shared.ServerProfileView.Parse(json); + Check.True(view != null, "the shared reader parses it"); + Check.Eq(view!.Summary(), "PvP, ACE; botting restricted - attended only; accounts: 3 accounts", "the reader's summary"); + + // No salvage defined: an empty list, which the Crafting tab reads as "none defined". + Check.Eq(root.GetProperty("salvage").GetArrayLength(), 0, "no salvage: empty list"); + Check.Eq(RynthCore.Plugin.Shared.ServerSalvageView.ParseList(json).Count, 0, "the reader sees none"); + + // Salvage defined: each row round-trips through the shared reader. + ServerPackInfo withSalvage = new("x", "X", new[] { "x.example" }, new[] { "X" }) + { + Salvage = new[] + { + new ServerSalvage("melee", 52, "+1 tink past the cap", "once", UsesTinkSlot: false), + new ServerSalvage("Armor", 64, "+30 armor level"), + new ServerSalvage("", 64, "no bench: skipped"), + }, + }; + var salvage = RynthCore.Plugin.Shared.ServerSalvageView.ParseList( + ServerPackProfile.BuildJson(withSalvage, "RynthX", "1", true, "X")); + Check.Eq(salvage.Count, 2, "rows without a bench are skipped"); + Check.Eq(salvage[0].Bench, "melee", "bench"); + Check.Eq(salvage[0].Material, 52, "material id"); + Check.Eq(salvage[0].Kind, "once", "kind"); + Check.False(salvage[0].UsesTinkSlot, "no tink slot"); + Check.Eq(salvage[1].Bench, "armor", "bench lower-cased"); + Check.Eq(salvage[1].Kind, "tink", "default kind"); + Check.True(salvage[1].UsesTinkSlot, "slot by default"); + Check.Eq(RynthCore.Plugin.Shared.ServerSalvageView.ParseList("{\"id\":\"x\"}").Count, 0, "a profile without the list (older plugins)"); + + // The optional row fields: absent = off / the default, and the writer leaves them out then. + Check.True(salvage.All(v => v.AppliedInt == 0 && !v.Prepared && v.Order == 0 && !v.AfterCap + && v.StackGroup.Length == 0 && v.StackCap == 0), "optional fields default when absent"); + string plain = ServerPackProfile.BuildJson(withSalvage, "RynthX", "1", true, "X"); + Check.True(!plain.Contains("\"applied\"") && !plain.Contains("\"prepared\"") && !plain.Contains("\"order\"") + && !plain.Contains("\"afterCap\"") && !plain.Contains("\"stackGroup\""), "unset fields are not written"); + + ServerPackInfo withRules = new("x", "X", new[] { "x.example" }, new[] { "X" }) + { + Salvage = new[] + { + new ServerSalvage("melee", 52, "post-cap", "once", UsesTinkSlot: false, Order: 995, AfterCap: true), + new ServerSalvage("jewelry", 71, "stack", UsesTinkSlot: false, Order: 50, StackGroup: "jewelry-stack", StackCap: 10), + new ServerSalvage("trinkets", 20, "tier", "once", UsesTinkSlot: false, AppliedInt: 384, Prepared: true, Order: 10), + }, + }; + var rules = RynthCore.Plugin.Shared.ServerSalvageView.ParseList( + ServerPackProfile.BuildJson(withRules, "RynthX", "1", true, "X")); + Check.Eq(rules.Count, 3, "rows with rules"); + Check.True(rules[0].AfterCap && rules[0].Order == 995 && !rules[0].Prepared && rules[0].StackGroup.Length == 0, "after cap + order"); + Check.Eq(rules[1].StackGroup, "jewelry-stack", "stack group"); + Check.Eq(rules[1].StackCap, 10, "stack cap"); + Check.True(rules[2].Prepared && rules[2].AppliedInt == 384 && rules[2].Order == 10 && !rules[2].AfterCap, "prepared + applied + order"); + Check.Eq(RynthCore.Plugin.Shared.ServerSalvageView.ParseList( + "{\"salvage\":[{\"bench\":\"jewelry\",\"material\":64,\"stackGroup\":\"g\"},{\"bench\":\"jewelry\",\"material\":71,\"stackGroup\":\"g\",\"stackCap\":0}]}") + .Count(v => v.StackGroup.Length > 0), 0, "a stack group without a positive cap is no group"); + var odd = RynthCore.Plugin.Shared.ServerSalvageView.ParseList( + "{\"salvage\":[{\"bench\":\"melee\",\"material\":52,\"applied\":\"x\",\"prepared\":1,\"order\":null,\"afterCap\":\"yes\"}]}"); + Check.True(odd.Count == 1 && odd[0].AppliedInt == 0 && !odd[0].Prepared && odd[0].Order == 0 && !odd[0].AfterCap, + "fields of the wrong type read as absent"); + + string idle = ServerPackProfile.BuildJson(info, "RynthColdeve", "0.1.2", false, null); + using JsonDocument idleDoc = JsonDocument.Parse(idle); + Check.False(idleDoc.RootElement.GetProperty("active").GetBoolean(), "not active"); + Check.Eq(idleDoc.RootElement.GetProperty("world").GetString(), "", "no world before login"); + Check.Eq(ServerPackProfile.BottingName(BottingPolicy.Unknown), "unknown", "unknown botting"); + } + + private static void ProfileJsonAscii() + { + ServerPackInfo info = new("x", "Caf\u00e9 \"Q\"\n", Array.Empty(), Array.Empty()) { Summary = "a\\b\tc \u2014 d" }; + string json = ServerPackProfile.BuildJson(info, "RynthX", "1", false, ""); + bool ascii = true; + foreach (char c in json) if (c > 0x7e || c < 0x20) ascii = false; + Check.True(ascii, "only printable ASCII: " + json); + using JsonDocument doc = JsonDocument.Parse(json); + Check.Eq(doc.RootElement.GetProperty("name").GetString(), "Caf\u00e9 \"Q\"", "name round-trips (trimmed)"); + Check.Eq(doc.RootElement.GetProperty("summary").GetString(), "a\\b\tc \u2014 d", "summary round-trips"); + } + + private static ServerPackInfo Coldeve() => + new("Coldeve", "Coldeve", new[] { "play.coldeve.ac" }, new[] { "Coldeve" }) { Discord = "https://discord.gg/x" }; + + private const string Push = + "V\tcoldeve\tColdeve\t1\ton\t0\tforced on for this character\n" + + "V\tilt\tInfinite Leaftide\t0\tauto\t0\tnot Infinite Leaftide\n" + + "X\tchar\tChar\n" + + "S\tcoldeve\tColdeve\t1\t/rc server coldeve on\n" + + "I\tColdeve server (RynthColdeve)\t/rc miniremote section char\tWhat is known.\tsection:char\n"; + + private static void EnginePush() + { + var model = new ServerPackModel(Coldeve()); + Check.True(model.ApplyEngine(Push, 1234), "taken"); + ServerVerdictView? v = model.Engine; + Check.True(v != null, "this server's verdict"); + Check.True(v!.Active, "active"); + Check.Eq(v.Force, "on", "override"); + Check.False(v.Detected, "forced, not detected"); + Check.Eq(v.Reason, "forced on for this character", "reason"); + Check.Eq(model.EngineAtMs, 1234L, "when"); + Check.True(model.IsActive("SomewhereElse"), "RynthCore's verdict beats the world name"); + } + + private static void ForeignPush() + { + var model = new ServerPackModel(Coldeve()); + Check.False(model.ApplyEngine("X\tchar\tChar\n", 1), "no server lines: not a push"); + Check.False(model.ApplyEngine(null, 1), "null"); + Check.False(model.ApplyEngine(new string('V', ServerPackModel.MaxPayload + 1), 1), "too long"); + Check.True(model.Engine == null, "nothing published"); + + // A push that lists other servers but not this one yet (RynthCore hasn't read the manifest). + Check.True(model.ApplyEngine("V\tilt\tInfinite Leaftide\t1\tauto\t1\thost matches\n", 2), "a push"); + Check.True(model.Engine == null, "no verdict for this server"); + ServerPackModel.ParseEngine("V\tCOLDEVE\tColdeve\t0\tweird\t1\n", "coldeve", out bool listed); + Check.True(listed, "listed"); + Check.Eq(ServerPackModel.ParseEngine("V\tCOLDEVE\tColdeve\t0\tweird\t1\n", "coldeve", out _)!.Force, "auto", + "id case ignored; an unknown override reads as auto; no reason field is fine"); + } + + private static void WorldFallback() + { + var model = new ServerPackModel(Coldeve()); + Check.True(model.IsActive("Coldeve"), "exact world name"); + Check.True(model.IsActive(" coldeve "), "case and spaces"); + Check.False(model.IsActive("ColdeveTwo"), "no partial match without '*'"); + Check.False(model.IsActive(null), "unknown world"); + Check.True(ServerPackModel.WorldMatches("Aeshnidae Live", new[] { "Aelrynth*", "Aeshnidae*" }), "wildcard"); + Check.False(ServerPackModel.WorldMatches("LeafDawn", new[] { "Leafdawning" }), "LeafDawn is not Leafdawning"); + Check.True(ServerPackModel.WorldMatches("Infinite Leaftide", new[] { "*Leaftide*" }), "both ends"); + } + + private static void ForceCommands() + { + Check.Eq(ServerPackModel.ForceCommand("coldeve", "On"), "/rc server coldeve on", "on"); + Check.Eq(ServerPackModel.ForceCommand("coldeve", "auto"), "/rc server coldeve auto", "auto"); + Check.Eq(ServerPackModel.ForceCommand("coldeve", "maybe"), "", "unknown mode"); + Check.Eq(ServerPackModel.ForceCommand("cold eve", "on"), "", "an id with a space"); + Check.Eq(ServerPackModel.ForceCommand("coldeve; /quit", "on"), "", "no command injection through the id"); + Check.False(ServerPackModel.IsSafeId(new string('a', 33)), "too long"); + } + + private static void SectionsJson() + { + string json = ServerPackModel.BuildSectionsJson(Coldeve(), "RynthColdeve"); + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + Check.Eq(root.GetProperty("version").GetInt32(), 1, "schema 1"); + JsonElement server = root.GetProperty("servers")[0]; + Check.Eq(server.GetProperty("id").GetString(), "coldeve", "server id lower-cased"); + Check.Eq(server.GetProperty("hosts")[0].GetString(), "play.coldeve.ac", "hosts"); + Check.Eq(server.GetProperty("worldNames")[0].GetString(), "Coldeve", "world names"); + JsonElement card = root.GetProperty("contributions")[0]; + Check.Eq(card.GetProperty("section").GetString(), "server", "in the Server section (not Session Stats)"); + JsonElement section = root.GetProperty("sections")[0]; + Check.Eq(section.GetProperty("id").GetString(), "server", "the Server section is declared"); + Check.Eq(section.GetProperty("label").GetString(), "Server", "its label"); + Check.Eq(section.GetProperty("order").GetInt32(), 50, "after Session Stats, before Map"); + Check.Eq(card.GetProperty("server").GetString(), "coldeve", "only while Coldeve is active"); + Check.Eq(card.GetProperty("surface").GetString(), "section:server-coldeve", "the card's surface"); + + var quoted = new ServerPackInfo("odd", "Odd \"Name\"\n", new[] { "a\\b" }, Array.Empty()); + using JsonDocument odd = JsonDocument.Parse(ServerPackModel.BuildSectionsJson(quoted, "RynthOdd")); + Check.Eq(odd.RootElement.GetProperty("servers")[0].GetProperty("hosts")[0].GetString(), "a\\b", "escaped"); + } + + private static void ClearOnLogout() + { + var model = new ServerPackModel(Coldeve()); + model.ApplyEngine(Push, 5); + model.Clear(); + Check.True(model.Engine == null, "verdict cleared"); + Check.Eq(model.EngineAtMs, 0L, "time cleared"); + Check.False(model.IsActive("Elsewhere"), "back to the world name"); + } + + private static void InfoText() + { + ServerPackInfo c = Coldeve(); + Check.Eq(c.Address, "play.coldeve.ac:9000", "address"); + Check.True(c.BottingText.StartsWith("Not published"), "unknown policy says so"); + Check.True(c.BottingText.Contains("Discord"), "and points at the Discord"); + var lev = new ServerPackInfo("example", "Example", new[] { "play.example.test" }, new[] { "Example" }) + { Botting = BottingPolicy.Forbidden, BottingNote = "no automation" }; + Check.Eq(lev.BottingText, "Forbidden - no automation", "forbidden"); + Check.Eq(new ServerPackInfo("x", "", Array.Empty(), Array.Empty()).Address, "", "no host, no address"); + Check.True(ServerPackModel.LauncherSteps(c)[0].Contains("play.coldeve.ac:9000"), "setup names the address"); + } +} diff --git a/Tools/RynthServerPack.Tests/ServerProjectsTests.cs b/Tools/RynthServerPack.Tests/ServerProjectsTests.cs new file mode 100644 index 0000000..621b92c --- /dev/null +++ b/Tools/RynthServerPack.Tests/ServerProjectsTests.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Xml.Linq; +using RynthCore.PluginSdk.Manifest; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// Every server plugin's csproj (Plugins\RynthCore.Plugin.Rynth*\ with RynthPluginServerId), read as +// XML: the detection data RynthCore's loader and sections use must be unique and must not overlap, +// or a client would load (or show) the wrong server's plugin. +internal static class ServerProjectsTests +{ + public static void Register(Runner r) + { + r.Add("server projects: every listed server has a plugin", AllServersPresent); + r.Add("server projects: ids, plugin names and hosts are unique", Unique); + r.Add("server projects: no server's host is claimed by another server's list", NoHostOverlap); + r.Add("server projects: each new server plugin has ServerData.cs and imports the shared props", Layout); + } + + // The shared plugins' own check (they name no server, send no server's commands) is RynthSuite's + // (Tools/RynthSuite.BoundaryTests) since the server plugins moved to RynthServers (2026-10-21). + + private sealed record Project(string Dir, string PluginName, string Id, string Name, string[] Hosts, string[] Worlds, bool Shared); + + /// The servers in the request (the server list's busiest, plus Aelrynth) and their plugins. + private static readonly string[] Expected = + { + "coldeve", "ilt", "frostace", "reefcull", "conquest", "dreamweave", "portalstorm", "sundering", + "achard", "leafdawn", "derptide", "frostcull", "thistlecrown", "eversong", "leafdawning", "aelrynth", + // Added 2026-10-21 with its quest pack (it was RynthOracle's). + "levistras", + }; + + private static string PluginsDir() + { + string? dir = AppContext.BaseDirectory; + while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) + dir = Path.GetDirectoryName(dir); + if (dir == null) throw new DirectoryNotFoundException("RynthSuite\\Plugins not found above " + AppContext.BaseDirectory); + return Path.Combine(dir, "Plugins"); + } + + private static List Load() + { + var list = new List(); + foreach (string dir in Directory.GetDirectories(PluginsDir(), "RynthCore.Plugin.Rynth*")) + { + string csproj = Path.Combine(dir, Path.GetFileName(dir) + ".csproj"); + if (!File.Exists(csproj)) continue; + XDocument doc = XDocument.Load(csproj); + string Prop(string name) => doc.Descendants(name).FirstOrDefault()?.Value.Trim() ?? ""; + string id = Prop("RynthPluginServerId"); + if (id.Length == 0) continue; + string[] Split(string v) => v.Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + bool shared = doc.Descendants("Import").Any(i => (i.Attribute("Project")?.Value ?? "").EndsWith("ServerPlugin.props")); + string asm = Prop("AssemblyName"); + list.Add(new Project(dir, asm.Replace("RynthCore.Plugin.", ""), id, Prop("RynthPluginServerName"), + Split(Prop("RynthPluginServerHosts")), Split(Prop("RynthPluginServerWorldNames")), shared)); + } + return list; + } + + private static void AllServersPresent() + { + List projects = Load(); + foreach (string id in Expected) + Check.True(projects.Any(p => p.Id == id), "a server plugin for " + id); + Check.Eq(projects.Count, Expected.Length, "no unexpected server plugins"); + } + + private static void Unique() + { + List projects = Load(); + Check.Eq(projects.Select(p => p.Id).Distinct().Count(), projects.Count, "ids unique"); + Check.Eq(projects.Select(p => p.PluginName.ToLowerInvariant()).Distinct().Count(), projects.Count, "plugin names unique"); + var hosts = projects.SelectMany(p => p.Hosts).Select(h => h.ToLowerInvariant()).ToList(); + Check.Eq(hosts.Distinct().Count(), hosts.Count, "hosts unique"); + foreach (Project p in projects) + { + Check.True(p.Hosts.Length > 0, p.PluginName + " lists a host (the loader picks plugins by host)"); + Check.True(p.Worlds.Length > 0, p.PluginName + " lists a world name"); + Check.True(p.Name.Length > 0, p.PluginName + " has a display name"); + } + } + + private static void NoHostOverlap() + { + List projects = Load(); + foreach (Project owner in projects) + foreach (string host in owner.Hosts.Where(h => !h.Contains('*'))) + foreach (Project other in projects.Where(o => o != owner)) + { + var server = new RynthPluginServer { Id = other.Id, Hosts = other.Hosts.ToList() }; + Check.False(server.MatchesHost(host, out string hit), + $"{owner.PluginName}'s host {host} is not claimed by {other.PluginName} ({hit})"); + } + } + + private static void Layout() + { + foreach (Project p in Load().Where(p => p.Id != "ilt")) + { + Check.True(p.Shared, p.PluginName + " imports Shared\\ServerPack\\ServerPlugin.props"); + Check.True(File.Exists(Path.Combine(p.Dir, "ServerData.cs")), p.PluginName + " has ServerData.cs"); + } + } + +} diff --git a/Tools/RynthServerPack.Tests/VaultTests.cs b/Tools/RynthServerPack.Tests/VaultTests.cs new file mode 100644 index 0000000..59ad0e8 --- /dev/null +++ b/Tools/RynthServerPack.Tests/VaultTests.cs @@ -0,0 +1,229 @@ +using System.Collections.Generic; +using RynthCore.Plugin.RynthAelrynth; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// The Aelrynth account vault: /mule-data answers, one "~ael1" line a page (Aeshnidae.Mule MuleData.cs). +// Moved with the feed from RynthInventory.Tests on 2026-10-20: RynthAelrynth reads the vault now and +// hands it to RynthInventory through the storage feed (Plugins/Shared/StorageFeed.cs). +internal static class VaultTests +{ + public static void Register(Runner r) + { + r.Add("vault: pages are asked one after the other and filed as one record", Pages); + r.Add("vault: other plugins' lines and players' imitations are left alone", Imitations); + r.Add("vault: a server without the command is asked once", Unsupported); + r.Add("vault: loading, changed and silent vaults are never filed half or empty", Retries); + r.Add("vault: RynthAelrynth asks after login, every ten minutes and on /rserver vault", Schedule); + r.Add("vault: the record reaches RynthInventory's format intact (plain ASCII)", HandOff); + } + + private const string A = "{\"o\":2147483649,\"w\":100,\"n\":\"Acid Assagai\",\"i\":100667000,\"u\":100667001,\"v\":100667002,\"s\":3,\"m\":100,\"y\":1,\"e\":1}"; + private const string B = "{\"o\":2147483650,\"w\":101,\"n\":\"Pyreal\",\"i\":100667003,\"y\":8192}"; + + private static string VaultPage(int page, int pages, int count, string items, bool ready = true, string why = "") => + ready + ? "~ael1 {\"t\":\"mule\",\"ready\":true,\"page\":" + page + ",\"pages\":" + pages + ",\"count\":" + count + ",\"max\":1000,\"items\":[" + items + "]}" + : "~ael1 {\"t\":\"mule\",\"ready\":false,\"why\":\"" + why + "\"}"; + + private static (VaultFeed Feed, List Sent) NewVault() + { + var sent = new List(); + return (new VaultFeed(t => { sent.Add(t); return true; }), sent); + } + + private static void Pages() + { + (VaultFeed v, List sent) = NewVault(); + Check.True(v.Ask(1000), "ask starts"); + Check.Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "page 1 asked first"); + Check.True(v.ShouldEat(VaultPage(1, 2, 2, A)), "page 1 is eaten"); + v.Tick(1100, "Tom"); + Check.Eq(sent.Count == 2 ? sent[1] : "?", "/mule-data 2", "page 2 asked when page 1 came"); + Check.Null(v.Record, "nothing filed before the last page"); + Check.True(v.ShouldEat(VaultPage(2, 2, 2, B)), "page 2 is eaten"); + v.Tick(1200, "Tom"); + StorageFeedRecord? r = v.Record; + Check.True(r != null && v.TakeChanged() && !v.TakeChanged(), "filed once"); + Check.Eq(r?.Items.Count ?? -1, 2, "both pages' items"); + Check.Eq(r?.Id ?? 0, VaultFeed.VaultId("tom"), "id follows the account, case-blind"); + Check.True(StorageFeed.IsStandInId(r?.Id ?? 0), "id is a stand-in, far from real objects"); + Check.Eq(r?.Label ?? "", "Account vault", "label"); + Check.Eq(r?.Name ?? "", "Aelrynth vault", "name"); + StorageFeedItem a = r!.Items[0]; + Check.Eq(a.Name, "Acid Assagai", "name"); Check.Eq(a.Icon, 100667000u, "icon"); Check.Eq(a.Underlay, 100667001u, "underlay"); + Check.Eq(a.Overlay, 100667002u, "overlay"); Check.Eq(a.Stack, 3, "stack"); Check.Eq(a.MaxStack, 100, "max stack"); + Check.Eq(a.ItemType, 1u, "item type"); + Check.Eq(r.Items[1].Stack, 1, "no stack field is a stack of 1"); + Check.Eq(v.Status, VaultFeed.State.Idle, "idle again"); + Check.Eq(VaultFeed.VaultId("Tom"), 0xFF000000u | (FnvOf("tom") & 0x00FFFFFFu), "the id RynthInventory used before the move (no second vault)"); + } + + private static uint FnvOf(string s) + { + uint h = 2166136261u; + foreach (char c in s) { h ^= c; h *= 16777619u; } + return h; + } + + private static void Imitations() + { + { + (VaultFeed v, _) = NewVault(); + v.Ask(0); + Check.False(v.ShouldEat("~ael1 {\"t\":\"inspect\",\"ok\":true}"), "the Companion's line stays visible"); + Check.False(v.ShouldEat("Welcome to Aelrynth"), "ordinary chat stays visible"); + Check.False(v.ShouldEat(null), "null is fine"); + } + { + (VaultFeed v, _) = NewVault(); + v.Ask(0); + Check.False(v.ShouldEat("Bob says, \"" + VaultPage(1, 1, 1, A) + "\"", 2), "spoken data line is not ours"); + Check.False(v.ShouldEat("Bob " + VaultPage(1, 1, 1, A), 12), "an emoted data line is not ours"); + Check.False(v.ShouldEat("Bob " + VaultPage(1, 1, 1, A)), "a data line not at the start is not ours, type unknown"); + Check.False(v.ShouldEat(VaultPage(1, 1, 1, A), 3), "a data line in a tell is not ours"); + Check.False(v.ShouldEat("Bob tells you, \"Unknown command: mule-data\"", 3), "a told unknown-command line is not ours"); + Check.False(v.ShouldEat("Unknown command: mule-data", 2), "unknown-command in speech is not ours"); + Check.False(v.ShouldEat("Unknown command: mule-data-ish"), "another command's refusal is not ours"); + Check.True(v.ShouldEat("Unknown command: mule-data", 15), "ACE's real reply (Help) is ours"); + } + { + (VaultFeed v, _) = NewVault(); + v.Ask(0); + Check.True(v.ShouldEat(" " + VaultPage(1, 1, 1, A), 0), "the server's line (Broadcast), leading space allowed"); + } + { + (VaultFeed v, _) = NewVault(); + Check.True(v.ShouldEat(VaultPage(1, 1, 1, A)), "a line typed by hand while we are not asking is eaten"); + v.Tick(0, "tom"); + Check.Null(v.Record, "but ignored when we did not ask"); + } + } + + private static void Unsupported() + { + { + (VaultFeed v, List sent) = NewVault(); + v.Ask(0); + Check.True(v.ShouldEat("Unknown command: /mule-data"), "the unknown-command reply is eaten while we wait"); + v.Tick(100, "tom"); + Check.Eq(v.Status, VaultFeed.State.Unsupported, "unsupported"); + Check.False(v.Ask(200), "not asked again"); + Check.Eq(sent.Count, 1, "one probe, no more"); + Check.True(v.Ask(300, force: true), "/rserver vault asks anyway"); + } + { + (VaultFeed v, _) = NewVault(); + Check.False(v.ShouldEat("Unknown command: /mule-data"), "an unknown-command line we did not provoke is left alone"); + } + } + + private static void Retries() + { + // A vault the server is still loading is asked again, and never recorded as empty. + { + (VaultFeed v, List sent) = NewVault(); + v.Ask(0); + v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading")); + v.Tick(10, "tom"); + Check.Eq(v.Status, VaultFeed.State.Waiting, "waiting"); + v.Tick(2000, "tom"); + Check.Eq(sent.Count, 1, "not before the retry delay"); + v.Tick(3500, "tom"); + Check.Eq(sent.Count, 2, "asked again after it"); + Check.Null(v.Record, "never recorded"); + for (int i = 0; i < 10; i++) + { + v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading")); + v.Tick(4000 + i * 4000, "tom"); + } + Check.True(v.Status != VaultFeed.State.Asking || sent.Count < 12, "it gives up after a few tries"); + Check.Null(v.Record, "still never recorded"); + } + // A vault that changed between pages is read again, not filed half and half. + { + (VaultFeed v, _) = NewVault(); + v.Ask(0); + v.ShouldEat(VaultPage(1, 2, 3, A)); + v.Tick(10, "tom"); + v.ShouldEat(VaultPage(2, 2, 3, B)); // 2 read, the server says 3 + v.Tick(20, "tom"); + Check.Null(v.Record, "a mismatched read is not filed"); + Check.Eq(v.Status, VaultFeed.State.Waiting, "and is retried"); + } + // Silence is an idle feed, not a stuck one. + { + (VaultFeed v, _) = NewVault(); + v.Ask(0); + v.Tick(20_000, "tom"); + Check.Eq(v.Status, VaultFeed.State.Idle, "no answer in time"); + Check.True(v.Ask(21_000), "can ask again"); + } + // Garbage inside a mule line does not throw. + { + (VaultFeed v, _) = NewVault(); + v.Ask(0); + v.ShouldEat("~ael1 {\"t\":\"mule\",\"ready\":tru"); + v.Tick(5, "tom"); + Check.True(v.Record == null && v.Status == VaultFeed.State.Idle, "bad JSON drops the read"); + } + } + + private static void Schedule() + { + var sent = new List(); + var f = new AelrynthFeature { SendCommand = t => { sent.Add(t); return true; } }; + f.Reset(); + long login = 50_000; + Check.Null(f.VaultTick(login, "tom"), "nothing at login"); + Check.Eq(sent.Count, 0, "not asked at once"); + f.VaultTick(login + VaultFeed.FirstAskMs - 1, "tom"); + Check.Eq(sent.Count, 0, "not before the first delay"); + f.VaultTick(login + VaultFeed.FirstAskMs, "tom"); + Check.Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "asked after the first delay"); + Check.True(f.OnChatLine(VaultPage(1, 1, 1, A), 0, login + VaultFeed.FirstAskMs + 10), "its reply is always hidden"); + StorageFeedRecord? read = f.VaultTick(login + VaultFeed.FirstAskMs + 20, "tom"); + Check.True(read != null && read.Items.Count == 1, "the finished read is handed back once"); + Check.Null(f.VaultTick(login + VaultFeed.FirstAskMs + 30, "tom"), "and only once"); + f.VaultTick(login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs, "tom"); + Check.Eq(sent.Count, 2, "read again ten minutes later"); + f.OnChatLine(VaultPage(1, 1, 1, A), 0, login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs + 1); + f.VaultTick(login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs + 2, "tom"); + Check.True(f.VaultAskNow(login + 700_000) && sent.Count == 3, "/rserver vault reads it now"); + + // A server without the command: one probe per login, then quiet. + var g = new AelrynthFeature { SendCommand = t => { sent.Add(t); return true; } }; + g.Reset(); + int before = sent.Count; + g.VaultTick(0, "tom"); + g.VaultTick(VaultFeed.FirstAskMs, "tom"); + g.OnChatLine("Unknown command: mule-data", 0, VaultFeed.FirstAskMs + 1); + g.VaultTick(VaultFeed.FirstAskMs + 2, "tom"); + g.VaultTick(VaultFeed.FirstAskMs + 3 * VaultFeed.RefreshMs, "tom"); + Check.Eq(sent.Count - before, 1, "no vault on the server: asked once, then never on a timer"); + g.Reset(); + Check.Eq(g.Vault.Status, VaultFeed.State.Idle, "the next login asks again"); + } + + private static void HandOff() + { + var items = new List + { + new(2147483649u, 100, "Acid \"Assagai\" \\ é", 100667000, 100667001, 100667002, 3, 100, 1), + new(2147483650u, 101, "Pyreal", 100667003, 0, 0, 1, 0, 8192), + }; + var rec = new StorageFeedRecord(VaultFeed.VaultId("tom"), VaultFeed.VaultName, VaultFeed.Label, items); + string json = StorageFeed.ToJson(rec); + bool ascii = true; + foreach (char c in json) if (c > 0x7e || c < 0x20) ascii = false; + Check.True(ascii, "plain ASCII (the broker carries ANSI)"); + StorageFeedRecord? back = StorageFeed.Parse(json, out string error); + Check.Eq(error, "", "parsed"); + Check.True(back != null && back.Id == rec.Id && back.Name == rec.Name && back.Label == rec.Label && back.Items.Count == 2, "the record"); + Check.Eq(back!.Items[0], items[0], "an item, name escapes included"); + Check.Eq(back.Items[1], items[1], "another"); + Check.Eq(StorageFeed.TargetPlugin + "/" + StorageFeed.Action, "RynthInventory/storage", "sent to RynthInventory's \"storage\" command"); + } +} diff --git a/Tools/RynthThreads.Tests/InferenceTests.cs b/Tools/RynthThreads.Tests/InferenceTests.cs new file mode 100644 index 0000000..ce49350 --- /dev/null +++ b/Tools/RynthThreads.Tests/InferenceTests.cs @@ -0,0 +1,297 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthThreads.Threads; +using RynthCore.RynthAiTests.Harness; + +namespace RynthThreads.Tests; + +// The odds (Threads/PressInference.cs): rates, intervals and comparisons, on the first real presses +// and on made-up ones. +internal static class InferenceTests +{ + public static void Register(Runner r) + { + r.Add("infer: the 4 real Lead Scarab presses (old JSON lines): rates, intervals, Affinity group", RealPresses); + r.Add("infer: with/without a component; 'more likely' only when clear; 'always' only at 10+", WithWithout); + r.Add("infer: Wilson intervals and the Fisher test", Statistics); + r.Add("infer: exact combinations of components", Combinations); + r.Add("infer: No components and All presses rows; incomplete presses left out", NoComponentsAndAll); + r.Add("infer: Affinity grouping and the split by material", AffinityGroup); + r.Add("infer: per-modifier view: overall, no components, each component (0% too)", ModifierView); + r.Add("infer: values by level, tags, results and modifiers per press", ReportDetails); + r.Add("infer: the sample press runs through the whole report", SampleReport); + } + + /// The first 4 presses from presses.jsonl (2026-10-12, all Lead Scarab), exactly as written. + internal static readonly string[] RealLines = + { + """{"v":1,"id":"ccbf1dd788704e08","time":"2026-10-12T23:44:32.8501639Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Radiant","description":"kills pay x1.84 luminance","numbers":[{"value":1.84,"kind":"mult","text":"x1.84"}]},{"name":"Amethyst Affinity","description":"10% of kills leave amethyst to salvage","numbers":[{"value":10,"kind":"pct","text":"10%"}]},{"name":"Precise","description":"monsters have \u002B27 critical strike rating, landing more critical hits","numbers":[{"value":27,"kind":"plus","text":"\u002B27"}]},{"name":"Guarded","description":"the boss has x1.91 health","numbers":[{"value":1.91,"kind":"mult","text":"x1.91"}]},{"name":"Savage","description":"monsters attack with \u002B35 damage rating, hitting harder","numbers":[{"value":35,"kind":"plus","text":"\u002B35"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Radiant - kills pay x1.84 luminance"," Amethyst Affinity - 10% of kills leave amethyst to salvage"," Precise - monsters have \u002B27 critical strike rating, landing more critical hits"," Guarded - the boss has x1.91 health"," Savage - monsters attack with \u002B35 damage rating, hitting harder","Level 175, 3 entries."],"extra":[]}""", + """{"v":1,"id":"6613196a36424f8c","time":"2026-10-12T23:50:31.1229501Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Radiant","description":"kills pay x1.75 luminance","numbers":[{"value":1.75,"kind":"mult","text":"x1.75"}]},{"name":"Iron Affinity","description":"8% of kills leave iron to salvage","numbers":[{"value":8,"kind":"pct","text":"8%"}]},{"name":"Teeming","description":"67% more monsters","numbers":[{"value":67,"kind":"pct","text":"67%"}]},{"name":"Guarded","description":"the boss has x1.83 health","numbers":[{"value":1.83,"kind":"mult","text":"x1.83"}]},{"name":"Swift","description":"monsters move at x1.21 speed","numbers":[{"value":1.21,"kind":"mult","text":"x1.21"}]},{"name":"Shieldbreaker","description":"monsters ignore 54% of your shield","numbers":[{"value":54,"kind":"pct","text":"54%"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Radiant - kills pay x1.75 luminance"," Iron Affinity - 8% of kills leave iron to salvage"," Teeming - 67% more monsters"," Guarded - the boss has x1.83 health"," Swift - monsters move at x1.21 speed"," Shieldbreaker - monsters ignore 54% of your shield","Level 175, 3 entries."],"extra":[]}""", + """{"v":1,"id":"1e960ea87fa64343","time":"2026-10-13T00:22:04.7703741Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Bounteous","description":"kills drop x1.51 loot","numbers":[{"value":1.51,"kind":"mult","text":"x1.51"}]},{"name":"Serpentine Affinity","description":"22% of kills leave serpentine to salvage","numbers":[{"value":22,"kind":"pct","text":"22%"}]},{"name":"Champions","description":"30% of the run\u0027s monsters are elites","numbers":[{"value":30,"kind":"pct","text":"30%"}]},{"name":"Guarded","description":"the boss has x2.18 health","numbers":[{"value":2.18,"kind":"mult","text":"x2.18"}]},{"name":"Enraged","description":"the boss attacks with \u002B54 damage rating, hitting harder","numbers":[{"value":54,"kind":"plus","text":"\u002B54"}]},{"name":"Precise","description":"monsters have \u002B19 critical strike rating, landing more critical hits","numbers":[{"value":19,"kind":"plus","text":"\u002B19"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Bounteous - kills drop x1.51 loot"," Serpentine Affinity - 22% of kills leave serpentine to salvage"," Champions - 30% of the run\u0027s monsters are elites"," Guarded - the boss has x2.18 health"," Enraged - the boss attacks with \u002B54 damage rating, hitting harder"," Precise - monsters have \u002B19 critical strike rating, landing more critical hits","Level 175, 3 entries."],"extra":[]}""", + """{"v":1,"id":"f0bf2c2811904c52","time":"2026-10-13T00:34:08.9352276Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Enlightened","description":"kills pay x1.43 experience","numbers":[{"value":1.43,"kind":"mult","text":"x1.43"}]},{"name":"Obsidian Affinity","description":"7% of kills leave obsidian to salvage","numbers":[{"value":7,"kind":"pct","text":"7%"}]},{"name":"Shieldbreaker","description":"monsters ignore 51% of your shield","numbers":[{"value":51,"kind":"pct","text":"51%"}]},{"name":"Savage","description":"monsters attack with \u002B33 damage rating, hitting harder","numbers":[{"value":33,"kind":"plus","text":"\u002B33"}]},{"name":"Stalwart","description":"monsters have \u002B20 damage resist rating, taking less damage from you","numbers":[{"value":20,"kind":"plus","text":"\u002B20"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Enlightened - kills pay x1.43 experience"," Obsidian Affinity - 7% of kills leave obsidian to salvage"," Shieldbreaker - monsters ignore 51% of your shield"," Savage - monsters attack with \u002B33 damage rating, hitting harder"," Stalwart - monsters have \u002B20 damage resist rating, taking less damage from you","Level 175, 3 entries."],"extra":["[BANK] Debited 1 Trade Notes (250,000) (250,000 pyreals) from your bank."]}""", + }; + + internal static List Real() => RealLines.Select(l => PressStore.FromJson(l)!).ToList(); + + private static int _n; + + /// A complete press with these components and modifiers ("Name" or "Name=x1.5 text"). + internal static Press P(string components, string modifiers, int level = 100, bool complete = true, int? result = null, int? entries = null) + { + var p = new Press + { + Id = "t" + (++_n), + TimeUtc = new DateTime(2026, 10, 12, 19, 0, 0, DateTimeKind.Utc).AddSeconds(_n), + Character = "Tester", + Server = "DreamWeave", + Fragment = "Raw Fragment", + FragmentLevel = level, + Outcome = "Pressed. It holds.", + ComponentsSeen = true, + Components = PressParser.SplitComponents(components), + Complete = complete, + End = complete ? "done" : "timeout", + ResultLevel = result, + Entries = entries, + }; + foreach (string m in modifiers.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + string[] parts = m.Split('=', 2); + string desc = parts.Length > 1 ? parts[1] : "something"; + p.Modifiers.Add(new GemModifier { Name = parts[0], Description = desc, Numbers = PressParser.Numbers(desc) }); + } + return p; + } + + private static List Many(int count, string components, string modifiers) => + Enumerable.Range(0, count).Select(_ => P(components, modifiers)).ToList(); + + private static Odds? Odd(GroupReport? g, string mod) => g?.Find(mod); + + private static void RealPresses() + { + List presses = Real(); + Check.True(presses.All(p => p != null && p.Usable), "all 4 old lines load as complete presses"); + Check.Eq(string.Join(",", presses.Select(p => p.ComponentsText).Distinct()), "Lead Scarab", "all Lead Scarab"); + ThreadsReport r = PressInference.Build(presses); + GroupReport? ls = r.Component("Lead Scarab"); + Check.NotNull(ls, "Lead Scarab row"); + if (ls == null) return; + Check.Eq(ls.Presses, 4, "4 presses"); + + Odds g = Odd(ls, "Guarded")!; + Check.Eq((g.Hits, g.N), (3, 4), "Guarded 3/4"); + Check.Eq(PressInference.OddsText(g), "75% (3/4, 30-95%)", "Guarded text"); + Check.Eq(g.Values, "x1.83 to x2.18", "Guarded values"); + Odds rad = Odd(ls, "Radiant")!; + Check.Eq(PressInference.OddsText(rad), "50% (2/4, 15-85%)", "Radiant 2/4"); + Check.Eq(PressInference.OddsText(Odd(ls, "Champions")!), "25% (1/4, 5-70%)", "Champions 1/4"); + + Odds aff = Odd(ls, PressInference.AffinityGroup)!; + Check.Eq((aff.Hits, aff.N), (4, 4), "Affinity group 4/4"); + Check.Eq(PressInference.OddsText(aff), "100% (4/4, 51-100%)", "Affinity text"); + Check.Eq(PressInference.SplitText(aff), "Amethyst 1, Iron 1, Obsidian 1, Serpentine 1", "split 1 each"); + Check.Eq(aff.Values, "7% to 22%", "affinity values across materials"); + Check.Null(Odd(ls, "Amethyst Affinity"), "materials are not rows of their own"); + Check.Eq(ls.Odds[0].Modifier, PressInference.AffinityGroup, "sorted by rate: Affinity first"); + Check.Eq(ls.Odds[1].Modifier, "Guarded", "then Guarded"); + + Check.Eq(PressInference.OtherText(g, ls.OtherLabel), "without: no data", "nothing without Lead Scarab"); + Check.False(ls.Odds.Any(o => o.MoreLikely), "no 'more likely' with nothing to compare"); + Check.Eq(r.All?.Presses, 4, "All presses row"); + Check.Eq(r.Combinations.Count, 0, "no combinations"); + Check.Null(r.NoComponents, "no No components row"); + Check.Eq(PressInference.ModifiersText(ls), "5.5 modifiers per press (5-6)", "modifiers per press"); + Check.Eq(PressInference.ResultsText(ls), "L185 -> 175, 3 entries: 4", "results"); + Check.Eq(r.Modifier("Affinity")?.Overall.Hits, 4, "modifier view: Affinity 4/4"); + Check.Null(r.Modifier("Iron Affinity"), "no Iron Affinity modifier entry"); + Check.Eq(r.Modifiers.Count, 13, "13 modifiers (affinities as one)"); + } + + private static void WithWithout() + { + var presses = Many(5, "Red Taper", "Bounteous, Hardy"); + presses.Add(P("Red Taper", "Teeming, Hardy")); + presses.AddRange(Many(3, "", "Hardy, Teeming")); + presses.AddRange(Many(3, "", "Savage, Teeming")); + ThreadsReport r = PressInference.Build(presses); + GroupReport red = r.Component("Red Taper")!; + Odds b = Odd(red, "Bounteous")!; + Check.Eq((b.Hits, b.N, b.OtherHits, b.OtherN), (5, 6, 0, 6), "Bounteous 5/6 with, 0/6 without"); + Check.True(b.MoreLikely, "Bounteous more likely with Red Taper"); + Check.Eq(PressInference.LikelyText(b, red), "more likely with Red Taper", "wording"); + Check.Eq(PressInference.OtherText(b, red.OtherLabel), "without: 0% (0/6)", "without text"); + Odds h = Odd(red, "Hardy")!; + Check.Eq((h.Hits, h.OtherHits), (6, 3), "Hardy 6/6 with, 3/6 without"); + Check.False(h.MoreLikely, "Hardy 6/6 vs 3/6: not clear (p ~ 0.09)"); + Check.Eq(red.Odds[0].Modifier, "Hardy", "sorted by rate: Hardy (100%) first"); + + // Few presses: nothing claimed. + r = PressInference.Build(Many(2, "Blue Taper", "Bounteous").Concat(Many(2, "", "Hardy")).ToList()); + Check.False(Odd(r.Component("Blue Taper"), "Bounteous")!.MoreLikely, "2/2 vs 0/2: not claimed"); + + // 'always' only at 100% over 10 or more. + r = PressInference.Build(Many(9, "Green Taper", "Teeming").Concat(Many(9, "", "Hardy")).ToList()); + GroupReport green = r.Component("Green Taper")!; + Check.Eq(PressInference.LikelyText(Odd(green, "Teeming")!, green), "more likely with Green Taper", "9/9: more likely, not always"); + r = PressInference.Build(Many(10, "Green Taper", "Teeming").Concat(Many(10, "", "Hardy")).ToList()); + green = r.Component("Green Taper")!; + Check.Eq(PressInference.LikelyText(Odd(green, "Teeming")!, green), "always with Green Taper so far", "10/10: always so far"); + + // The No components row is compared with presses that had components. + r = PressInference.Build(Many(6, "Red Taper", "Hardy").Concat(Many(6, "", "Teeming")).ToList()); + Odds t = Odd(r.NoComponents, "Teeming")!; + Check.True(t.MoreLikely, "Teeming 6/6 plain vs 0/6 with components"); + Check.Eq(PressInference.LikelyText(t, r.NoComponents!), "more likely with no components", "no-components wording"); + } + + private static void Statistics() + { + var (lo, hi) = PressInference.Wilson(3, 4); + Check.True(Math.Abs(lo - 0.3006) < 0.001 && Math.Abs(hi - 0.9544) < 0.001, $"3/4: 30.1-95.4% ({lo:0.0000}-{hi:0.0000})"); + (lo, hi) = PressInference.Wilson(0, 5); + Check.True(lo == 0 && Math.Abs(hi - 0.4345) < 0.001, $"0/5: 0-43% ({hi:0.0000})"); + (lo, hi) = PressInference.Wilson(0, 0); + Check.True(lo == 0 && hi == 1, "0/0: anything"); + Check.True(Math.Abs(PressInference.FisherGreater(3, 3, 0, 3) - 0.05) < 1e-9, "3/3 vs 0/3: p = 1/20"); + Check.True(Math.Abs(PressInference.FisherGreater(5, 6, 0, 6) - 7.0 / 924) < 1e-9, "5/6 vs 0/6: p = 7/924"); + Check.True(Math.Abs(PressInference.FisherGreater(0, 4, 4, 4) - 1) < 1e-9, "0 hits: p = 1"); + Check.Eq(PressInference.OddsText(new Odds { Hits = 30, N = 60 }), "50% (30/60)", "no interval from 50 presses"); + Check.Eq(PressInference.OddsText(new Odds { Hits = 0, N = 0 }), "no data", "empty"); + } + + private static void Combinations() + { + var presses = Many(3, "Red Taper, Blue Taper", "Bounteous, Savage"); + presses.AddRange(Many(2, "Red Taper", "Bounteous, Hardy")); + presses.Add(P("Blue Taper", "Savage, Hardy")); + presses.AddRange(Many(2, "", "Hardy, Teeming")); + ThreadsReport r = PressInference.Build(presses); + Check.Eq(r.Combinations.Count, 1, "one combination"); + GroupReport? combo = r.Combination("Blue Taper + Red Taper"); + Check.NotNull(combo, "named by its sorted components"); + if (combo == null) return; + Check.Eq(combo.Presses, 3, "3 presses with exactly both"); + Check.Eq(combo.Members.Count, 2, "two members"); + Check.Eq(r.Component("Red Taper")!.Presses, 5, "component row counts every press with it"); + Check.Eq(r.Component("Blue Taper")!.Presses, 4, "Blue Taper 4"); + Odds s = Odd(combo, "Savage")!; + Check.Eq((s.Hits, s.N, s.OtherHits, s.OtherN), (3, 3, 1, 5), "Savage 3/3 in the combination, 1/5 in other presses"); + Check.Eq(PressInference.OtherText(s, combo.OtherLabel), "other presses: 20% (1/5)", "comparison label"); + Check.Eq(PressInference.Build(Many(2, "Blue Taper, Red Taper", "Hardy").Concat(Many(1, "Red Taper, Blue Taper", "Hardy")).ToList()) + .Combination("Blue Taper + Red Taper")?.Presses, 3, "order of components doesn't matter"); + } + + private static void NoComponentsAndAll() + { + var presses = Many(4, "Red Taper", "Bounteous, Hardy"); + presses.AddRange(Many(2, "", "Hardy, Teeming")); + presses.Add(P("", "Teeming")); + presses.Add(P("Red Taper", "Savage", complete: false)); + presses.Add(P("", "")); // finished but no gem block: not usable + ThreadsReport r = PressInference.Build(presses); + Check.Eq((r.Total, r.Usable, r.Incomplete), (9, 7, 1), "totals"); + Check.Eq(r.Component("Red Taper")!.Presses, 4, "incomplete press left out"); + + GroupReport? nc = r.NoComponents; + Check.NotNull(nc, "No components row"); + if (nc == null) return; + Check.Eq((nc.Presses, nc.Kind), (3, GroupKind.NoComponents), "3 plain presses"); + Odds t = Odd(nc, "Teeming")!; + Check.Eq((t.Hits, t.N, t.OtherHits, t.OtherN), (3, 3, 0, 4), "Teeming 3/3 plain, 0/4 with components"); + Check.Eq(PressInference.OtherText(t, nc.OtherLabel), "with components: 0% (0/4)", "comparison label"); + Check.Eq(nc.Odds[0].Modifier, "Teeming", "most common plain draw first"); + + GroupReport all = r.All!; + Check.Eq((all.Presses, all.Kind), (7, GroupKind.All), "All presses: every usable press"); + Odds h = Odd(all, "Hardy")!; + Check.Eq((h.Hits, h.N), (6, 7), "Hardy 6/7 overall"); + Check.False(h.Compared, "the baseline isn't compared"); + Check.Eq(PressInference.OtherText(h, all.OtherLabel), "", "no comparison text"); + Check.False(all.Odds.Any(o => o.MoreLikely), "never flagged"); + } + + private static void AffinityGroup() + { + Check.Eq(PressInference.Material("Green Garnet Affinity"), "Green Garnet", "two-word material"); + Check.Eq(PressInference.Key("Tourmaline Affinity"), PressInference.AffinityGroup, "grouped"); + Check.Null(PressInference.Material("Affinity"), "bare 'Affinity' is not a material"); + Check.Eq(PressInference.Key("Guarded"), "Guarded", "others keep their name"); + Check.Eq(PressInference.Display(PressInference.AffinityGroup), "Affinity (any)", "display name"); + + var presses = new List + { + P("Red Taper", "Iron Affinity=8% of kills leave iron to salvage, Hardy"), + P("Red Taper", "Iron Affinity=10% of kills leave iron to salvage, Teeming"), + P("Red Taper", "Amethyst Affinity=12% of kills leave amethyst to salvage, Gold Affinity=5% of kills leave gold to salvage"), + P("", "Hardy"), + }; + ThreadsReport r = PressInference.Build(presses); + Odds a = Odd(r.Component("Red Taper"), PressInference.AffinityGroup)!; + Check.Eq((a.Hits, a.N, a.OtherHits, a.OtherN), (3, 3, 0, 1), "a press with two affinities counts once"); + Check.Eq(PressInference.SplitText(a), "Iron 2, Amethyst 1, Gold 1", "split counts both, most first"); + ModifierReport m = r.Modifier("Affinity")!; + Check.True(m.IsGroup, "modifier view: the group"); + Check.Eq(m.Tag, "reward", "salvage: reward"); + Check.Eq(m.Values, "8% to 12%", "values over every material (first affinity per press)"); + } + + private static void ModifierView() + { + var presses = Many(3, "Red Taper", "Bounteous, Hardy"); + presses.AddRange(Many(2, "Blue Taper", "Hardy")); + presses.Add(P("Blue Taper, Red Taper", "Bounteous")); + presses.AddRange(Many(2, "", "Teeming, Bounteous")); + ThreadsReport r = PressInference.Build(presses); + ModifierReport b = r.Modifier("Bounteous")!; + Check.Eq((b.Overall.Hits, b.Overall.N), (6, 8), "overall 6/8"); + Check.Eq((b.NoComponents?.Hits, b.NoComponents?.N, b.NoComponents?.OtherHits, b.NoComponents?.OtherN), ((int?)2, (int?)2, (int?)4, (int?)6), "no components 2/2 vs 4/6"); + Check.Eq(string.Join(", ", b.ByGroup.Select(x => $"{x.Group.Name} {x.Odds.Hits}/{x.Odds.N}")), + "Red Taper 4/4, Blue Taper + Red Taper 1/1, Blue Taper 1/3", "each component and combination, likeliest first"); + Odds teemingBlue = r.Modifier("Teeming")!.ByGroup.First(x => x.Group.Name == "Blue Taper").Odds; + Check.Eq((teemingBlue.Hits, teemingBlue.N, teemingBlue.OtherHits, teemingBlue.OtherN), (0, 3, 2, 5), "0% rows are kept, with their comparison"); + } + + private static void ReportDetails() + { + var presses = new List + { + P("Red Taper", "Bounteous=kills drop x1.38 loot, Hardy=monsters have x1.5 health", level: 185, result: 175, entries: 3), + P("Red Taper", "Bounteous=kills drop x1.52 loot", level: 185, result: 175, entries: 3), + P("Red Taper", "Bounteous=kills drop x1.20 loot", level: 120, result: 110, entries: 2), + P("Red Taper", "Hardy=monsters have x2 health", complete: false), + P("", "Hardy=monsters have x1.81 health, Teeming=75% more monsters", level: 120), + P("", "Teeming=60% more monsters", level: 120), + }; + ThreadsReport r = PressInference.Build(presses); + GroupReport red = r.Component("Red Taper")!; + Check.Eq(PressInference.ResultsText(red), "L185 -> 175, 3 entries: 2; L120 -> 110, 2 entries: 1", "results, most common first"); + Check.Eq(PressInference.ModifiersText(red), "1.33 modifiers per press (1-2)", "modifiers per press"); + Check.Eq(Odd(red, "Bounteous")!.Values, "x1.2 to x1.52", "values with the component"); + + ModifierReport b = r.Modifier("Bounteous")!; + Check.Eq(b.Values, "x1.2 to x1.52", "value range"); + Check.Eq(b.ByLevel.Count, 2, "two fragment levels"); + Check.Eq(b.ByLevel[0].Level, 120, "lowest level first"); + Check.Eq(b.ByLevel[1].Values, "x1.38 to x1.52", "level 185 range"); + Check.Eq(b.Tag, "reward", "loot is a reward"); + Check.Eq(r.Modifier("Hardy")!.Tag, "harder", "monster health is harder"); + Check.Eq(PressInference.Tag("something odd"), "", "no tag when the text doesn't say"); + + ThreadsReport empty = PressInference.Build(new List()); + Check.True(empty.Usable == 0 && empty.All == null && empty.Modifiers.Count == 0, "empty input"); + } + + private static void SampleReport() + { + Press p = new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0]; + ThreadsReport r = PressInference.Build(new[] { p }); + Check.Eq(r.Component("Red Taper")?.Presses, 1, "Red Taper counted"); + Check.Eq(r.Modifiers.Count, 6, "six modifiers in the report"); + Check.Eq(r.Modifier("Affinity")?.Tag, "reward", "salvage is a reward"); + Check.Eq(PressInference.SplitText(r.Modifier("Affinity")!.Overall), "Tourmaline 1", "Tourmaline"); + Check.Eq(r.Modifier("Enraged")?.Tag, "harder", "boss damage is harder"); + Check.Eq(PressInference.OddsText(r.Component("Red Taper")!.Find("Hardy")!), "100% (1/1, 21-100%)", "one press: wide range"); + } +} diff --git a/Tools/RynthThreads.Tests/ParserTests.cs b/Tools/RynthThreads.Tests/ParserTests.cs new file mode 100644 index 0000000..1c749e9 --- /dev/null +++ b/Tools/RynthThreads.Tests/ParserTests.cs @@ -0,0 +1,258 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthThreads.Threads; +using RynthCore.RynthAiTests.Harness; + +namespace RynthThreads.Tests; + +// The chat parser (Threads/PressParser.cs). The sample is real DreamWeave chat from 2026-10-12 +// (timestamps removed: the plugin sees the text without them), with another player's line in it. +internal static class ParserTests +{ + public static readonly string[] Sample = + { + "Using the Raw Fragment (Level 185) with the Fragment Press", + "Yorick is recalling to the marketplace.", + "Pressed. It holds.", + "Components selected: Red Taper", + "Remaining slots drawn at random.", + "The gem carries:", + " Bounteous - kills drop x1.38 loot", + " Tourmaline Affinity - 12% of kills leave tourmaline to salvage", + " Hardy - monsters have x1.81 health", + " Enraged - the boss attacks with +29 damage rating, hitting harder", + " Teeming - 75% more monsters", + " Savage - monsters attack with +20 damage rating, hitting harder", + "Level 190, 4 entries.", + }; + + public static void Register(Runner r) + { + r.Add("parse: the real sample, line by line, with another player's line in it", SampleLineByLine); + r.Add("parse: the sample as one message with newlines", SampleOneMessage); + r.Add("parse: several components (commas, 'and'), sorted", SeveralComponents); + r.Add("parse: no components (no line, 'none', 'No components ...')", NoComponents); + r.Add("parse: incomplete presses (timeout, next press, other Using line, logout)", Incomplete); + r.Add("parse: unknown and odd lines never throw and never become modifiers", UnknownLines); + r.Add("parse: numbers and their forms", NumberForms); + } + + private static List FeedAll(PressParser parser, IEnumerable lines, long now = 1000) + { + var done = new List(); + foreach (string line in lines) + if (parser.Feed(line, now) is { } d) done.AddRange(d); + return done; + } + + private static void SampleLineByLine() + { + var parser = new PressParser(); + List done = FeedAll(parser, Sample); + Check.Eq(done.Count, 1, "one press"); + if (done.Count != 1) return; + CheckSample(done[0]); + Check.False(parser.Busy, "parser idle after the Level line"); + } + + private static void SampleOneMessage() + { + var parser = new PressParser(); + List? done = parser.Feed(string.Join("\n", Sample) + "\n", 1000); + Check.Eq(done?.Count ?? 0, 1, "one press from one message"); + if (done is { Count: 1 }) CheckSample(done[0]); + // CRLF too. + done = new PressParser().Feed(string.Join("\r\n", Sample), 1000); + Check.Eq(done?[0].Modifiers.Count ?? -1, 6, "CRLF lines: 6 modifiers"); + } + + internal static void CheckSample(Press p) + { + Check.Eq(p.Fragment, "Raw Fragment", "fragment name"); + Check.Eq(p.FragmentLevel, 185, "fragment level"); + Check.Eq(p.Tool, "Fragment Press", "tool"); + Check.Eq(p.Outcome, "Pressed. It holds.", "outcome"); + Check.True(p.Held, "held"); + Check.True(p.ComponentsSeen, "components line seen"); + Check.Eq(string.Join("|", p.Components), "Red Taper", "components"); + Check.Eq(p.RandomNote, "Remaining slots drawn at random.", "random note"); + Check.Eq(p.ResultLevel, 190, "result level"); + Check.Eq(p.Entries, 4, "entries (raw, not the modifier count)"); + Check.True(p.Complete, "complete"); + Check.Eq(p.End, "done", "end reason"); + Check.Eq(p.Modifiers.Count, 6, "six modifiers"); + Check.Eq(p.Raw.Count, 12, "12 own raw lines"); + Check.Eq(string.Join("|", p.Extra), "Yorick is recalling to the marketplace.", "the foreign line is kept apart"); + Check.False(p.Raw.Any(l => l.Contains("Yorick")), "no foreign line in Raw"); + Check.Eq(p.Raw[5], " Bounteous - kills drop x1.38 loot", "raw lines kept as is (indent too)"); + if (p.Modifiers.Count != 6) return; + + (string Name, string Kinds, string Values, string Desc)[] want = + { + ("Bounteous", "mult", "1.38", "kills drop x1.38 loot"), + ("Tourmaline Affinity", "pct", "12", "12% of kills leave tourmaline to salvage"), + ("Hardy", "mult", "1.81", "monsters have x1.81 health"), + ("Enraged", "plus", "29", "the boss attacks with +29 damage rating, hitting harder"), + ("Teeming", "pct", "75", "75% more monsters"), + ("Savage", "plus", "20", "monsters attack with +20 damage rating, hitting harder"), + }; + for (int i = 0; i < want.Length; i++) + { + GemModifier m = p.Modifiers[i]; + Check.Eq(m.Name, want[i].Name, $"modifier {i} name"); + Check.Eq(m.Description, want[i].Desc, $"{want[i].Name} description"); + Check.Eq(string.Join(",", m.Numbers.Select(n => n.Kind)), want[i].Kinds, $"{want[i].Name} number kinds"); + Check.Eq(string.Join(",", m.Numbers.Select(n => n.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))), want[i].Values, $"{want[i].Name} values"); + } + Check.Eq(p.Modifiers[0].Numbers[0].Text, "x1.38", "text as written"); + Check.Eq(p.Modifiers[3].Numbers[0].Text, "+29", "rating text"); + } + + private static string[] Press(string components, params string[] mods) + { + var lines = new List { "Using the Raw Fragment (Level 100) with the Fragment Press", "Pressed. It holds." }; + if (components != null) lines.Add(components); + lines.Add("Remaining slots drawn at random."); + lines.Add("The gem carries:"); + lines.AddRange(mods.Select(m => " " + m)); + lines.Add("Level 104, 2 entries."); + return lines.ToArray(); + } + + private static void SeveralComponents() + { + Press p = FeedAll(new PressParser(), Press("Components selected: Red Taper, Blue Taper, Pyreal", "Hardy - monsters have x1.5 health")).Single(); + Check.Eq(string.Join("|", p.Components), "Blue Taper|Pyreal|Red Taper", "three, sorted"); + p = FeedAll(new PressParser(), Press("Components selected: Red Taper and Yellow Taper.", "Hardy - x")).Single(); + Check.Eq(string.Join("|", p.Components), "Red Taper|Yellow Taper", "'and' splits, trailing dot dropped"); + p = FeedAll(new PressParser(), Press("Components selected: Red Taper, red taper", "Hardy - x")).Single(); + Check.Eq(p.Components.Count, 1, "the same component twice counts once"); + } + + private static void NoComponents() + { + Press p = FeedAll(new PressParser(), Press(null!, "Teeming - 75% more monsters")).Single(); + Check.False(p.ComponentsSeen, "no line: not seen"); + Check.Eq(p.Components.Count, 0, "no line: none"); + Check.True(p.Complete && p.Usable, "still complete and usable"); + + p = FeedAll(new PressParser(), Press("Components selected: none", "Teeming - 75% more monsters")).Single(); + Check.True(p.ComponentsSeen && p.Components.Count == 0, "'none'"); + p = FeedAll(new PressParser(), Press("No components selected.", "Teeming - 75% more monsters")).Single(); + Check.True(p.ComponentsSeen && p.Components.Count == 0, "'No components selected.'"); + Check.Eq(p.ComponentsText, "no components", "shown as 'no components'"); + } + + private static void Incomplete() + { + // Timeout: the Level line never comes. + var parser = new PressParser(); + string[] lines = Sample.Take(Sample.Length - 1).ToArray(); + Check.Eq(FeedAll(parser, lines, 1000).Count, 0, "nothing finished yet"); + Check.Null(parser.Tick(1000 + PressParser.TimeoutMs - 1), "not before the timeout"); + // Other chat doesn't keep it open. + parser.Feed("Someone says, \"hello\"", 1000 + PressParser.TimeoutMs - 1); + Press? t = parser.Tick(1000 + PressParser.TimeoutMs); + Check.NotNull(t, "timed out"); + if (t != null) + { + Check.False(t.Complete, "incomplete"); + Check.Eq(t.End, "timeout", "reason"); + Check.Eq(t.Modifiers.Count, 6, "what was gathered is kept"); + Check.Null(t.ResultLevel, "no result level"); + Check.False(t.Usable, "not used by the inference"); + } + + // The next press starts before this one's Level line. + parser = new PressParser(); + var done = FeedAll(parser, Sample.Take(4).Concat(Sample)); + Check.Eq(done.Count, 2, "two presses"); + if (done.Count == 2) + { + Check.True(!done[0].Complete && done[0].End == "next use", "first: incomplete, next use"); + Check.Eq(done[0].Outcome, "Pressed. It holds.", "first kept its outcome"); + Check.True(done[1].Complete && done[1].Modifiers.Count == 6, "second complete"); + } + + // Some other "Using ..." line ends it and starts nothing. + parser = new PressParser(); + done = FeedAll(parser, Sample.Take(3).Append("Using the Mana Stone on the Robe of Ages")); + Check.Eq(done.Count, 1, "ended by another Using line"); + Check.False(parser.Busy, "no new press from an unrelated Using line"); + Check.Eq(done.Count == 1 ? done[0].End : "", "next use", "reason"); + + // Logout. + parser = new PressParser(); + FeedAll(parser, Sample.Take(2)); + Press? f = parser.Flush("logout"); + Check.True(f != null && f.End == "logout" && !f.Complete, "flush at logout"); + Check.Null(parser.Flush("logout"), "nothing left to flush"); + } + + private static void UnknownLines() + { + var parser = new PressParser(); + string[] junk = + { + "", " ", "\n\n", "Level 190, 4 entries.", "Pressed. It holds.", " Hardy - monsters have x1.81 health", + new string('x', 5000), "Components selected:", "The gem carries:", "☃ éè ???", "Using", "Using the", + "with the Fragment Press", "1234567890123456789012345678901234567890", " - just a dash", "x%+", + }; + int finished = 0; + foreach (string j in junk) + finished += parser.Feed(j, 1000)?.Count ?? 0; + Check.Eq(finished, 0, "nothing comes out of junk while idle"); + Check.False(parser.Busy, "still idle"); + Check.Null(parser.Feed(null, 1000), "null text"); + + // Inside a press: junk goes to Extra, chat-like dash lines don't become modifiers, a failed outcome is kept. + var lines = new List + { + "Using the Woven Shard (Level 12) with the Fragment Press", + "Pressed. It cracks.", + "The gem carries:", + "Bob says, \"Hardy - is that good?\"", + "[Trade] Alice - selling tapers", + "☃☃☃", + " Strange Sigil - something we've never seen, 3 times", + " not a modifier line", + new string('y', 2000), + "Level 12, 1 entry.", + }; + List done = FeedAll(parser, lines); + Check.Eq(done.Count, 1, "one press"); + if (done.Count != 1) return; + Press p = done[0]; + Check.Eq(p.Fragment, "Woven Shard", "other fragment name"); + Check.Eq(p.FragmentLevel, 12, "its level"); + Check.Eq(p.Outcome, "Pressed. It cracks.", "a failed outcome is kept as said"); + Check.False(p.Held, "not held"); + Check.Eq(p.Modifiers.Count, 1, "only the real modifier line"); + Check.Eq(p.Modifiers.Count == 1 ? p.Modifiers[0].Name : "", "Strange Sigil", "unknown modifier name kept"); + Check.Eq(p.Entries, 1, "'1 entry' singular"); + Check.True(p.Extra.Count >= 4, "unfitting lines kept in Extra"); + Check.True(p.Extra.All(l => l.Length <= 400), "long lines cut"); + + // A fragment without a level, and a press that isn't the Fragment Press. + done = FeedAll(new PressParser(), new[] { "Using the Odd Shard with the Fragment Press", "Level 3, 0 entries." }); + Check.True(done.Count == 1 && done[0].FragmentLevel == null && done[0].Fragment == "Odd Shard", "no level in the name"); + Check.True(done.Count == 1 && done[0].Complete && !done[0].Usable, "complete, but no modifiers: not usable"); + done = FeedAll(new PressParser(), new[] { "Using the Pyreal Ingot with the Forge", "Level 3, 0 entries." }); + Check.Eq(done.Count, 0, "not a Press: ignored"); + } + + private static void NumberForms() + { + string Forms(string s) => string.Join(" ", PressParser.Numbers(s).Select(n => n.Kind + ":" + n.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); + Check.Eq(Forms("kills drop x1.38 loot"), "mult:1.38", "multiplier"); + Check.Eq(Forms("12% of kills"), "pct:12", "percent"); + Check.Eq(Forms("+29 damage rating"), "plus:29", "rating"); + Check.Eq(Forms("attacks with +29."), "plus:29", "rating before a full stop"); + Check.Eq(Forms("-5 damage rating"), "plus:-5", "negative rating"); + Check.Eq(Forms("+12% more"), "pct:12", "signed percent is a percent"); + Check.Eq(Forms("spawns 3 bosses in 10.5 seconds"), "num:3 num:10.5", "plain numbers"); + Check.Eq(Forms("max5 and box2"), "", "digits glued to words aren't numbers"); + Check.Eq(Forms("no numbers here"), "", "none"); + } +} diff --git a/Tools/RynthThreads.Tests/Program.cs b/Tools/RynthThreads.Tests/Program.cs new file mode 100644 index 0000000..4723f05 --- /dev/null +++ b/Tools/RynthThreads.Tests/Program.cs @@ -0,0 +1,51 @@ +using System; +using System.IO; +using RynthCore.RynthAiTests.Harness; + +// The engine parser's only outside dependency: the registry's limits (the engine's values). +namespace RynthCore.Engine.UI.ScriptWindows +{ + internal static class ScriptWindowRegistry + { + public const int MaxOpsPerWindow = 1500; + public const int MaxBytesPerWindow = 64 * 1024; + public const int MaxWindowsPerOwner = 32; + public const int MaxBytesPerSubmit = 256 * 1024; + } +} + +namespace RynthThreads.Tests +{ + // Offline tests for RynthThreads. Each test prints PASS / FAIL. + // + // Run: dotnet run -c Release (all tests) + // dotnet run -c Release -- infer (tests whose name contains "infer") + internal static class Program + { + /// Scratch folder next to the exe for files tests write. Emptied at start. + public static string TempRoot { get; } = Path.Combine(AppContext.BaseDirectory, "scratch"); + + private static int Main(string[] args) + { + if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true); + Directory.CreateDirectory(TempRoot); + + var runner = new Runner(); + ParserTests.Register(runner); + InferenceTests.Register(runner); + StoreTests.Register(runner); + WindowTests.Register(runner); + int rc = runner.Run("RynthThreads tests", args.Length > 0 ? args[0] : null); + try { Directory.Delete(TempRoot, recursive: true); } catch { } + return rc; + } + + /// A fresh empty folder under the scratch root. + public static string NewFolder(string name) + { + string path = Path.Combine(TempRoot, name + "-" + Guid.NewGuid().ToString("N").Substring(0, 6)); + Directory.CreateDirectory(path); + return path; + } + } +} diff --git a/Tools/RynthThreads.Tests/RynthThreads.Tests.csproj b/Tools/RynthThreads.Tests/RynthThreads.Tests.csproj new file mode 100644 index 0000000..746a661 --- /dev/null +++ b/Tools/RynthThreads.Tests/RynthThreads.Tests.csproj @@ -0,0 +1,39 @@ + + + + + Exe + net10.0-windows + enable + true + true + RynthThreads.Tests + + + + + + + + + + + + + + + + + + diff --git a/Tools/RynthThreads.Tests/StoreTests.cs b/Tools/RynthThreads.Tests/StoreTests.cs new file mode 100644 index 0000000..78cd25f --- /dev/null +++ b/Tools/RynthThreads.Tests/StoreTests.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using RynthCore.Plugin.RynthThreads.Threads; +using RynthCore.RynthAiTests.Harness; + +namespace RynthThreads.Tests; + +// The shared presses.jsonl (Threads/PressStore.cs). +internal static class StoreTests +{ + public static void Register(Runner r) + { + r.Add("store: a press survives the JSON round trip", RoundTrip); + r.Add("store: another client's presses are read as the file grows; no doubles", FollowsGrowth); + r.Add("store: odd lines are skipped, a half-written line waits", OddLines); + r.Add("store: two writers appending at once lose nothing", ConcurrentAppends); + r.Add("store: CSV export", CsvExport); + } + + private static Press Sample() => new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0]; + + private static void RoundTrip() + { + Press p = Sample(); + p.Server = "DreamWeave"; + p.Character = "Tester \"Quote\""; + string json = PressStore.ToJson(p); + Check.False(json.Contains('\n'), "one line"); + Press? back = PressStore.FromJson(json); + Check.NotNull(back, "reads back"); + if (back == null) return; + ParserTests.CheckSample(back); + Check.Eq(back.Id, p.Id, "id"); + Check.Eq(back.Character, "Tester \"Quote\"", "character (escaped quotes)"); + Check.Eq(back.Server, "DreamWeave", "server"); + Check.Eq(back.TimeUtc, p.TimeUtc, "time"); + Check.Eq(back.Modifiers[3].Numbers[0].Text, "+29", "number text"); + + // Missing fields and unknown ones (a later version) are fine. + Press? minimal = PressStore.FromJson("{\"id\":\"x1\",\"future\":[1,2],\"modifiers\":[{\"name\":\"Hardy\"},{\"description\":\"no name\"}]}"); + Check.True(minimal != null && minimal.Id == "x1" && minimal.Modifiers.Count == 1 && minimal.FragmentLevel == null, + "minimal line reads, nameless modifier dropped"); + Check.Null(PressStore.FromJson("not json"), "garbage"); + Check.Null(PressStore.FromJson("[1,2]"), "not an object"); + } + + private static void FollowsGrowth() + { + string folder = Program.NewFolder("growth"); + var a = new PressStore(folder); + var b = new PressStore(folder); + Check.Eq(b.Poll(), 0, "no file yet"); + + Check.Null(a.Record(Sample()), "client A writes"); + Check.Eq(a.Poll(), 0, "A reading its own press back adds nothing"); + Check.Eq(a.Presses.Count, 1, "A has it once"); + Check.Eq(b.Poll(), 1, "client B sees it"); + Check.Eq(b.Poll(), 0, "and only once"); + + Press second = Sample(); + second.Components = new List { "Blue Taper" }; + a.Record(second); + b.Record(Sample()); + Check.Eq(b.Poll(), 1, "B gets A's second press (its own is already there)"); + Check.Eq(a.Poll(), 1, "A gets B's press"); + Check.Eq(a.Presses.Count, 3, "A: 3"); + Check.Eq(b.Presses.Count, 3, "B: 3"); + + // A fresh client reads them all. + var c = new PressStore(folder); + Check.Eq(c.Poll(), 3, "a new client loads everything"); + int v = c.Version; + c.Poll(); + Check.Eq(c.Version, v, "nothing new: unchanged"); + } + + private static void OddLines() + { + string folder = Program.NewFolder("odd"); + var s = new PressStore(folder); + Directory.CreateDirectory(folder); + string good = PressStore.ToJson(Sample()); + File.WriteAllText(s.FilePath, good + "\n\nnot json at all\n{\"broken\":\n" + good.Substring(0, 20)); + Check.Eq(s.Poll(), 1, "the good line"); + Check.Eq(s.BadLines, 2, "two bad lines counted"); + // The half line gets finished (with a different id: a new press). + Press other = Sample(); + string rest = PressStore.ToJson(other); + File.WriteAllText(s.FilePath, good + "\n\nnot json at all\n{\"broken\":\n" + rest + "\n"); + Check.Eq(s.Poll(), 1, "the finished line is read"); + Check.Eq(s.Presses.Count, 2, "two presses"); + } + + private static void ConcurrentAppends() + { + string folder = Program.NewFolder("concurrent"); + const int perWriter = 250; + var writers = new[] { new PressStore(folder), new PressStore(folder) }; + var errors = new int[2]; + using var stop = new CancellationTokenSource(); + + // A third party holding the file now and then, as another client mid-write would. + var holder = new Thread(() => + { + while (!stop.IsCancellationRequested) + { + try + { + using var fs = new FileStream(Path.Combine(folder, PressStore.FileName), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + Thread.Sleep(3); + } + catch (IOException) { } + Thread.Sleep(2); + } + }); + holder.Start(); + + var threads = Enumerable.Range(0, 2).Select(w => new Thread(() => + { + for (int i = 0; i < perWriter; i++) + { + Press p = Sample(); + p.Character = "Writer" + w; + p.Components = new List { "C" + i }; + if (writers[w].Record(p) != null) errors[w]++; + } + })).ToList(); + threads.ForEach(t => t.Start()); + threads.ForEach(t => t.Join()); + stop.Cancel(); + holder.Join(); + + // Whatever found the file busy every time is written now. + foreach (PressStore w in writers) + for (int i = 0; i < 50 && w.FlushPending() > 0; i++) Thread.Sleep(10); + Check.Eq(writers[0].PendingCount + writers[1].PendingCount, 0, "nothing left pending"); + + string[] lines = File.ReadAllLines(Path.Combine(folder, PressStore.FileName), Encoding.UTF8) + .Where(l => l.Length > 0).ToArray(); + Check.Eq(lines.Length, 2 * perWriter, "every press is one line"); + List read = lines.Select(PressStore.FromJson).ToList(); + Check.True(read.All(p => p != null && p.Modifiers.Count == 6), "every line is a whole press"); + Check.Eq(read.Select(p => p!.Id).Distinct().Count(), 2 * perWriter, "all ids distinct"); + Check.Eq(read.Count(p => p!.Character == "Writer0"), perWriter, "writer 0's presses all there"); + Check.Eq(read.Count(p => p!.Character == "Writer1"), perWriter, "writer 1's presses all there"); + + var reader = new PressStore(folder); + Check.Eq(reader.Poll(), 2 * perWriter, "a reader loads them all"); + Check.Eq(reader.BadLines, 0, "no bad lines"); + Console.WriteLine($" (appends that found the file busy every try and waited: {errors[0] + errors[1]})"); + } + + private static void CsvExport() + { + string folder = Program.NewFolder("csv"); + var s = new PressStore(folder); + Press p = Sample(); + p.Character = "Tester, Jr."; + s.Record(p); + Press q = Sample(); + q.Components = new List { "=cmd", "Red Taper" }; + q.Complete = false; + q.End = "timeout"; + s.Record(q); + string path = s.ExportCsv(new DateTime(2026, 10, 12, 19, 30, 0)); + Check.True(File.Exists(path) && Path.GetDirectoryName(path) == folder, "written next to presses.jsonl"); + Check.Eq(Path.GetFileName(path), "presses-20261012-193000.csv", "file name"); + string[] rows = File.ReadAllLines(path); + Check.Eq(rows.Length, 3, "header + 2 rows"); + Check.True(rows[0].StartsWith("time_utc,server,character,fragment,fragment_level"), "header"); + Check.True(rows[1].Contains("\"Tester, Jr.\""), "comma value quoted"); + Check.True(rows[1].Contains(",Raw Fragment,185,Pressed. It holds.,Red Taper,190,4,yes,6,"), "columns"); + Check.True(rows[1].Contains("Bounteous: kills drop x1.38 loot | Tourmaline Affinity"), "modifiers joined"); + Check.True(rows[2].Contains("'=cmd; Red Taper"), "a formula-looking cell is defused"); + Check.True(rows[2].Contains("no (timeout)"), "incomplete marked"); + } +} diff --git a/Tools/RynthThreads.Tests/WindowTests.cs b/Tools/RynthThreads.Tests/WindowTests.cs new file mode 100644 index 0000000..b2ff2be --- /dev/null +++ b/Tools/RynthThreads.Tests/WindowTests.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using RynthCore.Engine.UI.ScriptWindows; +using RynthCore.Plugin.RynthThreads; +using RynthCore.Plugin.RynthThreads.Threads; +using RynthCore.Plugin.RynthThreads.Ui; +using RynthCore.Plugin.RynthThreads.Views; +using RynthCore.RynthAiTests.Harness; + +namespace RynthThreads.Tests; + +// The window's display list against the engine's own parser, the server check and /rthreads stats. +internal static class WindowTests +{ + [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Write")] + private static extern int Write(UiHost h); + + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_submit")] + private static extern ref byte[] SubmitBuffer(UiHost h); + + public static void Register(Runner r) + { + r.Add("window: every tab, headers open, parses in the engine (bar button set)", EveryTab); + r.Add("window: DreamWeave check and /rthreads stats lines", ServerAndStats); + r.Add("window: Components and Modifiers tab text for the 4 real presses", RealText); + } + + private static List Data() + { + var presses = new List(); + for (int i = 0; i < 3; i++) presses.Add(InferenceTests.P("Red Taper", "Bounteous=kills drop x1.38 loot, Hardy=monsters have x1.5 health", level: 185)); + for (int i = 0; i < 4; i++) presses.Add(InferenceTests.P("", "Hardy=monsters have x1.81 health, Teeming=75% more monsters", level: 185)); + presses.Add(InferenceTests.P("Blue Taper, Red Taper", "Bounteous=kills drop x1.4 loot", level: 120)); + Press raw = new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0]; + presses.Add(raw); + presses.Add(InferenceTests.P("Red Taper", "Hardy", complete: false)); + return presses; + } + + private static unsafe void EveryTab() + { + List presses = Data(); + ThreadsReport report = PressInference.Build(presses); + var panel = new ThreadsPanel { Report = () => report, Presses = () => presses }; + var host = new UiHost(); + UiWindow w = host.Add(new UiWindow("RynthThreads/Main", "RynthThreads") { DefaultWidth = 440f, DefaultHeight = 480f, MinWidth = 320f, MinHeight = 220f }); + + void Pass() + { + w.Begin(); + panel.Draw(w); + w.End(); + } + void OpenAll(IEnumerable ids) + { + foreach (string id in ids) w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvOpen, b: true)); + } + void Click(string id) => w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvClicked)); + + string[] tabs = { "tab.c", "tab.m", "tab.p" }; + foreach (string tab in tabs) + { + Pass(); + Click(tab); + Pass(); + OpenAll(report.Components.Select(c => "c:" + c.Name).Append("c:(none)").Append("c:(all)") + .Concat(report.Combinations.Select(c => "k:" + c.Name)) + .Concat(report.Modifiers.Select(m => "m:" + m.Name)) + .Concat(presses.Select(p => "p:" + p.Id))); + Pass(); + + int n = Write(host); + byte[] buf = SubmitBuffer(host); + int rc; + List windows; + string error; + fixed (byte* p = buf) rc = DisplayListParser.Parse(p, n, 4000f, out _, out windows, out error); + Check.Eq(rc, 0, $"{tab}: the engine accepts the list ({error})"); + if (rc != 0 || windows.Count != 1) continue; + Check.Eq(windows[0].Title, "RynthThreads", "title (the bar button's tooltip)"); + Check.True((windows[0].Flags & WindowFlags.ShowInBar) != 0 && (windows[0].Flags & WindowFlags.BarButton) != 0, "bar button"); + Check.True(windows[0].List!.OpCount > 20, $"{tab}: something drawn ({windows[0].List!.OpCount} ops)"); + } + string body = System.Text.Encoding.UTF8.GetString(w.Body); + Check.True(body.Contains("Level 190, 4 entries."), "presses tab shows raw lines"); + Check.True(body.Contains("Yorick is recalling"), "and the other lines kept beside them"); + + // Empty data still draws. + var empty = new ThreadsPanel(); + w.Begin(); + empty.Draw(w); + w.End(); + Check.True(System.Text.Encoding.UTF8.GetString(w.Body).Contains("No presses yet"), "empty window explains itself"); + } + + private static void ServerAndStats() + { + Check.True(RynthThreadsPlugin.IsDreamWeave("DreamWeave"), "DreamWeave"); + Check.True(RynthThreadsPlugin.IsDreamWeave("dreamweave PvE"), "any case, extra words"); + Check.False(RynthThreadsPlugin.IsDreamWeave("Aelrynth"), "Aelrynth"); + Check.False(RynthThreadsPlugin.IsDreamWeave(""), "empty"); + Check.False(RynthThreadsPlugin.IsDreamWeave(null), "null"); + + List lines = RynthThreadsPlugin.StatsLines(PressInference.Build(Data()), @"C:\x\presses.jsonl"); + Check.True(lines[0].StartsWith("10 presses (9 complete, 1 incomplete)"), "totals line: " + lines[0]); + Check.True(lines.Any(l => l.StartsWith("Red Taper (5): Bounteous 100%+, Hardy 80%")), "Red Taper line"); + Check.True(lines.Any(l => l == "Blue Taper (1): Bounteous 100%"), "Blue Taper line"); + Check.True(lines.Any(l => l.StartsWith("No components (4): Hardy 100%")), "No components line"); + Check.False(lines.Any(l => l.Contains("Affinity")), "the Affinity group is left out"); + Check.True(lines.Contains("+ = more likely with it than without."), "legend"); + Check.Eq(lines[^1], @"File: C:\x\presses.jsonl", "file named last"); + Check.True(lines.Count <= 9, "short"); + } + + /// The window's text ops in order (headers as "== label", indented by Indent ops). + internal static List TextOf(ReadOnlySpan b) + { + var lines = new List(); + int i = 0, indent = 0; + string Str(ReadOnlySpan s, int at) => + System.Text.Encoding.UTF8.GetString(s.Slice(at + 2, s[at] | (s[at + 1] << 8))); + while (i + 4 <= b.Length) + { + byte code = b[i], flags = b[i + 1]; + int len = b[i + 2] | (b[i + 3] << 8), at = i + 4; + if (code == UiFormat.OpEnd && len == 0) break; + string pad = new string(' ', indent * 2); + switch (code) + { + case UiFormat.OpText: case UiFormat.OpTextWrapped: case UiFormat.OpTextDisabled: case UiFormat.OpSeparatorText: + lines.Add(pad + Str(b, at)); break; + case UiFormat.OpBulletText: lines.Add(pad + "- " + Str(b, at)); break; + case UiFormat.OpTextColored: lines.Add(pad + Str(b, at + 4)); break; + case UiFormat.OpCollapsingHeader: + string h = Str(b, at + 4); + int cut = h.IndexOf("###", StringComparison.Ordinal); + lines.Add(pad + "== " + (cut >= 0 ? h.Substring(0, cut) : h)); break; + case UiFormat.OpIndent: indent++; break; + case UiFormat.OpUnindent: indent = Math.Max(0, indent - 1); break; + } + i = at + len + ((flags & UiFormat.OpHasBlock) != 0 ? 4 : 0); + } + return lines; + } + + private static void RealText() + { + List presses = InferenceTests.Real(); + ThreadsReport report = PressInference.Build(presses); + var panel = new ThreadsPanel { Report = () => report, Presses = () => presses }; + var w = new UiWindow("RynthThreads/Main", "RynthThreads"); + void Pass() { w.Begin(); panel.Draw(w); w.End(); } + void Open(string id) => w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvOpen, b: true)); + + Pass(); + Open("c:(all)"); + Open("c:Lead Scarab"); + Pass(); + List comp = TextOf(w.Body); + Check.True(comp.Contains("== Lead Scarab (4 presses)"), "Lead Scarab header"); + Check.True(comp.Any(l => l.Trim() == "- Guarded 75% (3/4, 30-95%); without: no data; x1.83 to x2.18"), "Guarded line"); + Check.True(comp.Any(l => l.Trim() == "- Affinity (any) 100% (4/4, 51-100%); without: no data; 7% to 22%"), "Affinity line"); + Check.True(comp.Any(l => l.Trim() == "Amethyst 1, Iron 1, Obsidian 1, Serpentine 1"), "split line"); + Check.True(comp.Any(l => l.Trim() == "- Guarded 75% (3/4, 30-95%); x1.83 to x2.18"), "All presses: no comparison"); + + w.Dispatch(w.KeyOf("tab.m"), new UiEvent(UiFormat.EvClicked)); + Pass(); + Open("m:Affinity"); + Open("m:Guarded"); + Pass(); + List mods = TextOf(w.Body); + Check.True(mods.Contains("== Guarded 75% (3/4, 30-95%) [harder]") || mods.Contains("== Guarded 75% (3/4, 30-95%)"), "Guarded header"); + Check.True(mods.Any(l => l.Trim() == "- Lead Scarab 75% (3/4, 30-95%); without: no data; x1.83 to x2.18"), "Guarded with Lead Scarab"); + Check.True(mods.Any(l => l.Trim() == "- Amethyst: 25% (1/4, 5-70%)"), "Affinity by material"); + + if (Environment.GetEnvironmentVariable("RYNTHTHREADS_DUMP") == "1") + { + Console.WriteLine("---- Components tab ----"); + foreach (string l in comp) Console.WriteLine(l); + Console.WriteLine("---- Modifiers tab ----"); + foreach (string l in mods) Console.WriteLine(l); + } + } +}