Snapshot for release 2026.10.21.1 (internal 7a4c0dd)
This commit is contained in:
parent
bfcd48950d
commit
d0c95956a0
263 changed files with 4185 additions and 39583 deletions
20
CONTRIBUTING.md
Normal file
20
CONTRIBUTING.md
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
# Contributing to RynthSuite
|
||||
|
||||
RynthCore is the hook layer: it injects into the client, reads the game, runs plugins and hosts their windows. RynthSuite is the plugins. RynthAi is one plugin among them, built on RynthCore the same way any other plugin is.
|
||||
|
||||
## Where a change goes
|
||||
|
||||
| It is... | It goes in |
|
||||
|---|---|
|
||||
| A hook into the client, game state, the plugin API, the window host, a service every plugin can use | **RynthCore** |
|
||||
| A plugin's behaviour or its own screens | **That plugin** (`Plugins/RynthCore.Plugin.<Name>`), drawn by the plugin with the engine's ImGui |
|
||||
| A feature for one game server | **That server's plugin**, in the **RynthServers** repository |
|
||||
|
||||
A shared plugin (RynthAi, RynthOracle, RynthInventory, RynthNav, ...) never names a server. When a server plugin needs a place in one of them, add a generic hook the server plugin fills (the ServerPack hooks, the server tab host, the storage and chat feeds) and keep the server's own code in the server plugin.
|
||||
|
||||
## Pull requests
|
||||
|
||||
- One purpose per pull request. A change that touches several layers comes as one pull request per layer, the RynthCore hook first.
|
||||
- Plugin API numbers and plugin versions are assigned when a change is merged.
|
||||
- Add or update tests where the project has them (`Tools/`, each plugin's `*.Tests`).
|
||||
- Say in the description what you tested in game and on which server.
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- RynthAChard: the AChard server plugin (PvP). The build is shared (..\Shared\ServerPack\ServerPlugin.props);
|
||||
ServerData.cs holds what is known about the server. -->
|
||||
<PropertyGroup>
|
||||
<AssemblyName>RynthCore.Plugin.RynthAChard</AssemblyName>
|
||||
<Version>0.1.0</Version>
|
||||
<RynthPluginServerId>achard</RynthPluginServerId>
|
||||
<RynthPluginServerName>AChard</RynthPluginServerName>
|
||||
<RynthPluginServerHosts>a-chard.ddns.net</RynthPluginServerHosts>
|
||||
<RynthPluginServerWorldNames>AChard|A-Chard</RynthPluginServerWorldNames>
|
||||
<RynthPluginDescription>AChard only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="..\Shared\ServerPack\ServerPlugin.props" />
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
// 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",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,277 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>A row of a leaderboard.</summary>
|
||||
internal sealed class BoardRow
|
||||
{
|
||||
public int Rank;
|
||||
public string Name = "";
|
||||
public string Value = "";
|
||||
public string Extra = "";
|
||||
public bool IsYou;
|
||||
}
|
||||
|
||||
/// <summary>A board in Aelrynth's /top overview.</summary>
|
||||
internal sealed class AelrynthBoardSummary
|
||||
{
|
||||
public string Key = "", Title = "", Leader = "", Value = "";
|
||||
}
|
||||
|
||||
/// <summary>Your standing on one board ("/top me").</summary>
|
||||
internal sealed class AelrynthStanding
|
||||
{
|
||||
public string Title = "";
|
||||
public int Rank;
|
||||
public int Of;
|
||||
public string Value = "";
|
||||
}
|
||||
|
||||
/// <summary>A line of the "/trial" overview: a dungeon's record, yours and this week's best.</summary>
|
||||
internal sealed class TrialDungeon
|
||||
{
|
||||
public string Name = "", Landblock = "", Record = "", You = "", Week = "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<AelrynthBoardSummary> Overview = new();
|
||||
public string OverviewNote = "";
|
||||
public string BoardTitle = "", BoardNote = "";
|
||||
public readonly List<BoardRow> BoardRows = new();
|
||||
public string BoardYou = "";
|
||||
public readonly List<AelrynthStanding> Standings = new();
|
||||
public readonly List<TrialDungeon> Trials = new();
|
||||
public readonly List<string> TrialLines = new();
|
||||
public string TrialBoardTitle = "";
|
||||
public readonly List<BoardRow> TrialRows = new();
|
||||
public readonly List<string> 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; }
|
||||
|
||||
/// <summary>A chat line: true when it was a leaderboard reply; <paramref name="ours"/> = it answers RynthAelrynth's request.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
// 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";
|
||||
/// <summary>Set once rynthoracle.json's setting was taken over (it's never read again).</summary>
|
||||
public const string MigrationMarker = "migratedFromRynthOracle";
|
||||
|
||||
/// <summary>RynthAelrynth's pages (AelrynthPages draws them): id, label, tooltip.</summary>
|
||||
public static readonly (string Id, string Label, string Tooltip)[] PageList =
|
||||
{
|
||||
("boards", "Leaderboards", "Aelrynth's /top leaderboards and /trial dungeon records (RynthAelrynth)."),
|
||||
};
|
||||
|
||||
/// <summary>Held for everything below (pump and render thread).</summary>
|
||||
public readonly object Gate = new();
|
||||
public readonly AelrynthBoards Boards = new();
|
||||
|
||||
/// <summary>Hide the replies to RynthAelrynth's own requests (a command typed by hand always shows).</summary>
|
||||
public bool HideOwnReplies = true;
|
||||
|
||||
/// <summary>Sends a chat command as if typed (the vault's /mule-data); the plugin sets it (AelrynthPlugin).</summary>
|
||||
public Func<string, bool> SendCommand = _ => false;
|
||||
|
||||
/// <summary>The account vault reader.</summary>
|
||||
public readonly VaultFeed Vault;
|
||||
private long _nextVaultAskMs;
|
||||
|
||||
/// <summary>What happened to the last vault read on its way to RynthInventory ("" before one).</summary>
|
||||
public string VaultHandOff = string.Empty;
|
||||
|
||||
public AelrynthFeature() => Vault = new VaultFeed(cmd => SendCommand(cmd));
|
||||
|
||||
/// <summary>Takes over RynthOracle's reply-hiding choice once (default: hidden, as it was there).</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Login and logout: the boards and the vault are read fresh.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
Boards.Clear();
|
||||
Vault.Reset();
|
||||
_nextVaultAskMs = 0;
|
||||
VaultHandOff = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The vault's timing (plugin tick, on Aelrynth): the first read <see cref="VaultFeed.FirstAskMs"/>
|
||||
/// after login, then every <see cref="VaultFeed.RefreshMs"/> unless the server has no vault.
|
||||
/// Returns the record to hand to RynthInventory when a read just finished, else null.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>"/rserver vault": a read now (even on a server that said it has none); the next timed one in ten minutes.</summary>
|
||||
public bool VaultAskNow(long nowMs)
|
||||
{
|
||||
_nextVaultAskMs = nowMs + VaultFeed.RefreshMs;
|
||||
return Vault.Ask(nowMs, force: true);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,252 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<bool> _active;
|
||||
private readonly Action<Action> _runOnTick;
|
||||
private readonly Func<string, bool> _send;
|
||||
private readonly Action<string> _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<bool> active, Action<Action> runOnTick, Func<string, bool> send,
|
||||
Action<string> 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) };
|
||||
}
|
||||
|
||||
/// <summary>Logout: the next character's status lines start empty.</summary>
|
||||
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.",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// "/top [arg]" or "/trial [arg]" on the next tick, marked as RynthAelrynth's own (its reply can
|
||||
/// be hidden); returns the command.
|
||||
/// </summary>
|
||||
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)) + "...";
|
||||
}
|
||||
|
|
@ -1,239 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>
|
||||
/// 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: <see cref="ShouldEat"/> only queues; everything else runs on the plugin tick.
|
||||
/// Pure: RynthServerPack.Tests covers it.
|
||||
/// </summary>
|
||||
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";
|
||||
/// <summary>After login, before the first /mule-data; then every <see cref="RefreshMs"/>.</summary>
|
||||
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<string, bool> _send;
|
||||
private readonly ConcurrentQueue<string> _lines = new();
|
||||
|
||||
private long _sentAtMs;
|
||||
private volatile bool _expecting;
|
||||
private int _readyTries;
|
||||
private long _retryAtMs;
|
||||
private readonly List<StorageFeedItem> _pages = new();
|
||||
private bool _changed;
|
||||
|
||||
public VaultFeed(Func<string, bool> send) => _send = send;
|
||||
|
||||
public State Status { get; private set; } = State.Idle;
|
||||
/// <summary>The vault once a full read finished (null until then).</summary>
|
||||
public StorageFeedRecord? Record { get; private set; }
|
||||
public int Max { get; private set; }
|
||||
|
||||
/// <summary>For /rserver info.</summary>
|
||||
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}" : ""),
|
||||
};
|
||||
|
||||
/// <summary>True once after <see cref="Record"/> was replaced.</summary>
|
||||
public bool TakeChanged() { bool c = _changed; _changed = false; return c; }
|
||||
|
||||
/// <summary>Login and logout: a fresh read (the record from before is forgotten).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
Status = State.Idle;
|
||||
_expecting = false;
|
||||
_pages.Clear();
|
||||
_readyTries = 0;
|
||||
Record = null;
|
||||
_changed = false;
|
||||
Max = 0;
|
||||
while (_lines.TryDequeue(out _)) { }
|
||||
}
|
||||
|
||||
/// <summary>Starts a read from page 1, unless one is under way or the server has no vault (<paramref name="force"/> asks anyway).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True for a line this feed answers, so the caller keeps it out of the chat window. Cheap; any thread.
|
||||
/// <paramref name="chatType"/> 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".
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>ACE's "Unknown command: mule-data" (GameActionTalk names the bare command; a leading / or @ is allowed).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Applies what arrived and decides what to send next. Plugin tick.</summary>
|
||||
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<StorageFeedItem>(_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"));
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
|
@ -1,127 +0,0 @@
|
|||
// 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.
|
||||
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 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;
|
||||
|
||||
/// <summary>Where RynthOracle kept the reply-hiding choice before it moved here (read once).</summary>
|
||||
internal static string OracleSettingsPath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json");
|
||||
|
||||
partial void ServerPages(System.Collections.Generic.List<ServerPage> 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<string> 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()
|
||||
{
|
||||
lock (_aelrynth.Gate) _aelrynth.Reset();
|
||||
_vaultToHandOff = null;
|
||||
_aelrynthPages?.Reset();
|
||||
}
|
||||
|
||||
partial void ServerLogout()
|
||||
{
|
||||
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)
|
||||
{
|
||||
if (!active || !Host.HasInvokeChatParser) return;
|
||||
long now = Environment.TickCount64;
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<string> line)
|
||||
{
|
||||
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") + ".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- RynthAelrynth: the Aelrynth server plugin. "aelrynth" is one of RynthCore's built-in server ids, so the
|
||||
engine's own Aelrynth detection decides when it is active (the hosts here only pick it at load).
|
||||
The build is shared (..\Shared\ServerPack\ServerPlugin.props); ServerData.cs holds what is known.
|
||||
Aelrynth's own features (AelrynthPlugin.cs, Aelrynth\) came from RynthOracle and RynthInventory on
|
||||
2026-10-20: the /top leaderboards and /trial records (a page of the Mini Remote's Server section),
|
||||
and the account vault (/mule-data), handed to RynthInventory's Global Inventory. -->
|
||||
<PropertyGroup>
|
||||
<AssemblyName>RynthCore.Plugin.RynthAelrynth</AssemblyName>
|
||||
<Version>0.2.0</Version>
|
||||
<RynthPluginServerId>aelrynth</RynthPluginServerId>
|
||||
<RynthPluginServerName>Aelrynth</RynthPluginServerName>
|
||||
<RynthPluginServerHosts>aelrynth.com</RynthPluginServerHosts>
|
||||
<RynthPluginServerWorldNames>Aelrynth*|Aeshnidae*</RynthPluginServerWorldNames>
|
||||
<RynthPluginDescription>Aelrynth only: the server card (its mods, links, account setup), Aelrynth's leaderboards and Trials records in the Mini Remote, and the account vault in Global Inventory.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="..\Shared\ServerPack\ServerPlugin.props" />
|
||||
|
||||
<ItemGroup>
|
||||
<!-- The vault's server lines vs a player's copy of them, and the storage feed RynthInventory reads. -->
|
||||
<Compile Include="..\Shared\ChatSource.cs" Link="Shared\ChatSource.cs" />
|
||||
<Compile Include="..\Shared\StorageFeed.cs" Link="Shared\StorageFeed.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
// 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).",
|
||||
"RynthOracle has an Aelrynth quest pack (quests.aelrynth.csv).",
|
||||
"RynthAelrynth's Leaderboards page (Server section, or /rserver): the /top boards and /trial dungeon records.",
|
||||
"The world was named Aeshnidae before; both names count.",
|
||||
},
|
||||
Website = "https://aelrynth.com",
|
||||
Source = "RynthCore's Aelrynth support and RynthOracle, 2026-10-13",
|
||||
};
|
||||
}
|
||||
|
|
@ -507,7 +507,7 @@ public partial class CombatManager : IDisposable
|
|||
private int _fightCastCount; // offensive casts fired this fight (for casts-to-kill learning)
|
||||
private bool _fightAppraiseRequested; // one appraisal attempt per fight to fill unknown HP
|
||||
private bool _fightHpEstimated; // _fightTargetMaxHp is tier 0's scaled by the tier, not measured
|
||||
private AwakenedTier? _awakenedTier; // Aelrynth's difficulty tier where we stand (0 elsewhere)
|
||||
private DifficultyTier? _difficultyTier; // the server plugin's difficulty tier where we stand (0 without one)
|
||||
|
||||
// Predicted one-shots are swapped away BEFORE their own KillerNotification
|
||||
// arrives, so OnKillNotification (which keys off the CURRENT target) can't
|
||||
|
|
@ -589,10 +589,10 @@ public partial class CombatManager : IDisposable
|
|||
_damageStore = damage;
|
||||
}
|
||||
|
||||
internal void SetAwakenedTier(AwakenedTier? tier) => _awakenedTier = tier;
|
||||
internal void SetDifficultyTier(DifficultyTier? tier) => _difficultyTier = tier;
|
||||
|
||||
/// <summary>Aelrynth's difficulty tier where we stand; always 0 on other servers.</summary>
|
||||
private int Difficulty => _awakenedTier?.Current ?? 0;
|
||||
/// <summary>The difficulty tier where we stand, as the server plugin reports it; always 0 without one.</summary>
|
||||
private int Difficulty => _difficultyTier?.Current ?? 0;
|
||||
|
||||
public int RaycastBlockCount { get; private set; }
|
||||
public int RaycastCheckCount { get; private set; }
|
||||
|
|
@ -2762,10 +2762,10 @@ public partial class CombatManager : IDisposable
|
|||
|
||||
if (_fightTargetMaxHp > 0 && !_fightHpEstimated) return;
|
||||
|
||||
// Aelrynth's awakened worlds and scaled copies: the same wcid, +5% health a tier.
|
||||
// 0 everywhere else, and then this is the old resolution exactly.
|
||||
// A server's scaled worlds and copies: the same wcid, its health percent a tier (the server
|
||||
// plugin's numbers, DifficultyTier). 0 everywhere else, and then this is the old resolution exactly.
|
||||
int difficulty = Difficulty;
|
||||
double scale = AwakenedTier.HealthScale(difficulty);
|
||||
double scale = _difficultyTier?.HealthScale(difficulty) ?? 1.0;
|
||||
|
||||
// User-entered HP override (set in the Damage panel) is authoritative —
|
||||
// it's the manual fix for ACE's skill-gated appraisal reading low.
|
||||
|
|
|
|||
|
|
@ -152,7 +152,9 @@ internal static class OffhandRules
|
|||
/// adds none).
|
||||
/// * An explicit item (the Damage tab's per-monster offhand, else the rule's old item pick):
|
||||
/// used when it is listed and allowed (a weapon needs the Dual Wield skill and the
|
||||
/// slot-wield call), else the mode decides.
|
||||
/// slot-wield call), else the mode decides. An explicit weapon that is the main weapon this
|
||||
/// fight (picked for the monster's weakness) gives its place to the other listed one-handed
|
||||
/// weapon, so the character keeps dual wielding.
|
||||
/// * Shield: the best listed shield. Weapon: a second listed one-handed melee weapon when
|
||||
/// the Dual Wield skill is trained, else the best shield. Auto: the best shield; a second
|
||||
/// listed one-handed weapon instead only when <paramref name="preferDualWield"/> is on and
|
||||
|
|
@ -180,12 +182,21 @@ internal static class OffhandPlanner
|
|||
else if (weapon == null || (c.InOffhand && !weapon.InOffhand)) weapon = c;
|
||||
}
|
||||
|
||||
if (explicitId != 0 && explicitId != mainId)
|
||||
if (explicitId != 0)
|
||||
{
|
||||
foreach (var c in listed)
|
||||
{
|
||||
if (c.Id != explicitId) continue;
|
||||
if (c.IsShield || dualOk) return new OffhandPlan(c.Id, explicitSource);
|
||||
if (explicitId != mainId)
|
||||
{
|
||||
if (c.IsShield || dualOk) return new OffhandPlan(c.Id, explicitSource);
|
||||
}
|
||||
// The off-hand weapon picked is the main weapon this fight (chosen for the monster's
|
||||
// weakness): the other listed one-handed weapon goes in the off hand, so the
|
||||
// character still dual wields. It used to fall to the mode, and Auto with no shield
|
||||
// listed left the off hand empty (Drakkon, 2026-10-21).
|
||||
else if (!c.IsShield && dualOk && weapon != null)
|
||||
return new OffhandPlan(weapon.Id, explicitSource + "; it is in the main hand, so the other weapon");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,120 +0,0 @@
|
|||
using System;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.CreatureData;
|
||||
|
||||
/// <summary>
|
||||
/// Aelrynth's difficulty tier where the player stands, and which server this is (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.
|
||||
///
|
||||
/// The rule: on any server other than Aelrynth this is inert - <see cref="Current"/> is 0 and
|
||||
/// <see cref="Active"/> false - so every store keyed by tier behaves exactly as before. On
|
||||
/// Aelrynth it also stays inert until the property has been seen this login (an older server
|
||||
/// build that does not send it changes nothing either).
|
||||
///
|
||||
/// Server detection matches RynthOracle's (Data/ServerIdentity.cs) older-engine path: the world
|
||||
/// name the server announced (Aelrynth's live world is still named "Aeshnidae"; both names, and
|
||||
/// the staging world, count), else the Bank mod's player properties 9101-9103, which only
|
||||
/// Aelrynth sends. Engine API v75 adds GetServerInfo (the engine's own verdict); when the SDK
|
||||
/// this builds against has it, it should be asked first, as RynthOracle does.
|
||||
/// </summary>
|
||||
internal sealed class AwakenedTier
|
||||
{
|
||||
/// <summary>PropertyInt 9051 on the player: the difficulty tier where they stand.</summary>
|
||||
public const uint TierProperty = 9051;
|
||||
|
||||
/// <summary>The server's scaling per tier (InstancesNoDat DifficultyPercentPerEnlightenment, 5.0).</summary>
|
||||
public const double PercentPerTier = 5.0;
|
||||
|
||||
private const uint QuadRadianceEarned = 9101, QuadLuminanceBanked = 9102, QuadLuminanceDrawn = 9103;
|
||||
|
||||
private volatile bool _aelrynth;
|
||||
private volatile bool _seen;
|
||||
private volatile int _tier;
|
||||
private string _serverKey = "";
|
||||
private long _nextRefreshMs;
|
||||
|
||||
/// <summary>On Aelrynth (live or staging), by the world name or the Bank properties.</summary>
|
||||
public bool OnAelrynth => _aelrynth;
|
||||
|
||||
/// <summary>The tier property has been seen this login.</summary>
|
||||
public bool Seen => _seen;
|
||||
|
||||
/// <summary>The tier feature is in force: on Aelrynth and the property seen. Off everywhere else.</summary>
|
||||
public bool Active => _aelrynth && _seen;
|
||||
|
||||
/// <summary>The tier where the player stands; 0 whenever <see cref="Active"/> is false.</summary>
|
||||
public int Current => Active ? _tier : 0;
|
||||
|
||||
/// <summary>
|
||||
/// The server's key for per-server data (creatures.json): "Aelrynth" for every Aelrynth
|
||||
/// world name (live "Aeshnidae", "Aelrynth", "Aeshnidae Staging"), else the world name made
|
||||
/// safe for a folder name; "" while unknown.
|
||||
/// </summary>
|
||||
public string ServerKey => _serverKey;
|
||||
|
||||
/// <summary>The multiplier a tier puts on a monster's health: 1 + 5% per tier.</summary>
|
||||
public static double HealthScale(int tier) => tier <= 0 ? 1.0 : 1.0 + PercentPerTier / 100.0 * tier;
|
||||
|
||||
/// <summary>Logout: nothing carries to the next login (it may be another server).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
_aelrynth = false;
|
||||
_seen = false;
|
||||
_tier = 0;
|
||||
_serverKey = "";
|
||||
_nextRefreshMs = 0;
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the server and the tier, at most once a second. Pump thread.</summary>
|
||||
public void Refresh(RynthCoreHost host, uint playerId, bool force = false)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (!force && now < _nextRefreshMs) return;
|
||||
_nextRefreshMs = now + 1000;
|
||||
|
||||
try
|
||||
{
|
||||
string world = host.HasGetWorldName && host.TryGetWorldName(out string w) ? (w ?? "").Trim() : "";
|
||||
bool aelrynth = IsAelrynthWorld(world)
|
||||
|| (playerId != 0 && host.HasGetObjectQuadProperty
|
||||
&& (host.TryGetObjectQuadProperty(playerId, QuadRadianceEarned, out _)
|
||||
|| host.TryGetObjectQuadProperty(playerId, QuadLuminanceBanked, out _)
|
||||
|| host.TryGetObjectQuadProperty(playerId, QuadLuminanceDrawn, out _)));
|
||||
_aelrynth = aelrynth;
|
||||
_serverKey = aelrynth ? "Aelrynth" : SafeKey(world);
|
||||
|
||||
if (aelrynth && playerId != 0 && host.HasGetObjectIntProperty
|
||||
&& host.TryGetObjectIntProperty(playerId, TierProperty, out int tier))
|
||||
{
|
||||
_tier = Math.Max(0, tier);
|
||||
_seen = true;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>Aelrynth's world names: "Aelrynth...", or "Aeshnidae..." (its earlier name, still the live config's).</summary>
|
||||
public static bool IsAelrynthWorld(string? world)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(world)) return false;
|
||||
string w = world.Trim();
|
||||
return w.StartsWith("Aelrynth", StringComparison.OrdinalIgnoreCase)
|
||||
|| w.StartsWith("Aeshnidae", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>A world name as a folder name (the SettingsProfiles rule); "" for none.</summary>
|
||||
public static string SafeKey(string? world)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(world)) return "";
|
||||
var sb = new System.Text.StringBuilder(world.Length);
|
||||
foreach (char c in world.Trim())
|
||||
sb.Append(char.IsLetterOrDigit(c) || c == '\'' || c == '-' ? c : '_');
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
|
@ -17,13 +17,13 @@ public sealed class CreatureProfile
|
|||
|
||||
public int CreatureType { get; set; }
|
||||
|
||||
/// <summary>Max health at Aelrynth difficulty tier 0 (real Dereth; every tier on other servers).</summary>
|
||||
/// <summary>Max health at difficulty tier 0 (the unscaled world; every tier on servers without tiers).</summary>
|
||||
public uint MaxHealth { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Max health at Aelrynth difficulty tiers above 0 (awakened worlds, scaled copies: +5% a
|
||||
/// tier), tier -> highest seen. Null until one is seen, and then left out of the file
|
||||
/// on every other server. Resists, armour, spells and type are the same at every tier.
|
||||
/// Max health at difficulty tiers above 0 (a server plugin's tiers, DifficultyTier: scaled
|
||||
/// worlds or copies), tier -> highest seen. Null until one is seen, and then left out of the
|
||||
/// file on every server without tiers. Resists, armour, spells and type are the same at every tier.
|
||||
/// </summary>
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public Dictionary<int, uint>? TierMaxHealth { get; set; }
|
||||
|
|
|
|||
|
|
@ -11,18 +11,19 @@ namespace RynthCore.Plugin.RynthAi.CreatureData;
|
|||
/// Keyed by composite "name|wcid" so tier variants don't collide.
|
||||
///
|
||||
/// Per server (2026-10-03): wcids are only unique within one server's world database, and
|
||||
/// custom content (Aelrynth's 3000001+, ConquestAC's own) reuses numbers, so each server keeps
|
||||
/// its own file:
|
||||
/// servers' custom content reuses numbers, so each server keeps its own file:
|
||||
/// C:\Games\RynthSuite\RynthAi\CreatureData\<server>\creatures.json
|
||||
/// <server> is <see cref="AwakenedTier.ServerKey"/>: "Aelrynth" for every Aelrynth world name,
|
||||
/// else the world name the server announced, made safe for a folder (the SettingsProfiles rule).
|
||||
/// <server> is <see cref="DifficultyTier.ServerKey"/>: the folder that already holds this
|
||||
/// server's data (by RynthCore's server id, its name or the world name), else the server's id,
|
||||
/// else (no server known) the world name the server announced, made safe for a folder (the
|
||||
/// SettingsProfiles rule). Folders made before 2026-10-21 are read where they are; nothing moves.
|
||||
/// The shared file from before, CreatureData\creatures.json, is the legacy store: COPIED (not
|
||||
/// moved) into a server's folder the first time that server is played, so every server starts
|
||||
/// from exactly what it had - the same precedent as the per-server SettingsProfiles
|
||||
/// (MigrateToServerFolder). It is only read and written while no server is known (before the
|
||||
/// first tick of a login, or a server that announces no name), as before.
|
||||
///
|
||||
/// Aelrynth difficulty tiers: appraised max health above tier 0 goes to
|
||||
/// Difficulty tiers (a server plugin's, DifficultyTier): appraised max health above tier 0 goes to
|
||||
/// <see cref="CreatureProfile.TierMaxHealth"/>; MaxHealth stays the tier-0 value. Everything
|
||||
/// else in a profile is the same at every tier.
|
||||
/// </summary>
|
||||
|
|
@ -47,6 +48,27 @@ internal sealed class CreatureProfileStore
|
|||
/// <summary>The server whose file is loaded ("" = the legacy shared file).</summary>
|
||||
public string ServerKey { get { lock (_lock) return _serverKey; } }
|
||||
|
||||
/// <summary>
|
||||
/// The name, as on disk, of the per-server folder matching <paramref name="serverKey"/> (any case)
|
||||
/// that holds a creatures.json; null when there is none. Never throws.
|
||||
/// </summary>
|
||||
public static string? ExistingServerFolder(string serverKey)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(serverKey)) return null;
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(Folder)) return null;
|
||||
foreach (string dir in Directory.EnumerateDirectories(Folder))
|
||||
{
|
||||
string name = Path.GetFileName(dir);
|
||||
if (name.Equals(serverKey.Trim(), StringComparison.OrdinalIgnoreCase) && File.Exists(Path.Combine(dir, FileName)))
|
||||
return name;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Switch to <paramref name="serverKey"/>'s file (saving the current one first). The first
|
||||
/// time a server is seen its file is a copy of the legacy shared file. "" or the same server
|
||||
|
|
@ -198,8 +220,8 @@ internal sealed class CreatureProfileStore
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// A profile's appraised max health at an Aelrynth difficulty tier (0 = real Dereth, and
|
||||
/// every tier on other servers); 0 when that tier hasn't been seen.
|
||||
/// A profile's appraised max health at a difficulty tier (0 = the unscaled world, and every
|
||||
/// tier on servers without tiers); 0 when that tier hasn't been seen.
|
||||
/// </summary>
|
||||
public uint MaxHealthAt(CreatureProfile? profile, int difficulty)
|
||||
{
|
||||
|
|
@ -212,7 +234,7 @@ internal sealed class CreatureProfileStore
|
|||
/// <summary>
|
||||
/// Merge a new observation into the store. Fields with value 0 / empty are
|
||||
/// ignored so partial samples don't clobber better data. <paramref name="difficulty"/>
|
||||
/// above 0 (an Aelrynth awakened world or scaled copy) files the max health under that tier
|
||||
/// above 0 (a server's scaled world or copy, DifficultyTier) files the max health under that tier
|
||||
/// and leaves the tier-0 vitals alone; the rest merges as always.
|
||||
/// </summary>
|
||||
public void Upsert(CreatureProfile sample, int difficulty = 0)
|
||||
|
|
|
|||
169
Plugins/RynthCore.Plugin.RynthAi/CreatureData/DifficultyTier.cs
Normal file
169
Plugins/RynthCore.Plugin.RynthAi/CreatureData/DifficultyTier.cs
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.CreatureData;
|
||||
|
||||
/// <summary>
|
||||
/// The difficulty tier where the player stands and the monster health a tier adds, as the active
|
||||
/// server's plugin reports them, and which server this is for per-server data (2026-10-03 as one
|
||||
/// server's AwakenedTier; server-neutral since 2026-10-21).
|
||||
///
|
||||
/// Some servers hold the same monsters (same names, same wcids) at several difficulty tiers, with
|
||||
/// health, skills and damage scaled per tier. A server plugin that knows its server's tiers says so
|
||||
/// in its "RynthServer.Profile" values (Plugins/Shared/RynthServerProfileApi.cs):
|
||||
/// "difficultyTier" the tier where the player stands (0 = the unscaled world);
|
||||
/// "difficultyHealthPercent" the health one tier adds, in percent of tier 0's (absent: 0).
|
||||
/// They are read from the plugin that owns RynthCore's active server (ServerStateClient, plugin API
|
||||
/// v86), about once a second. RynthAi knows nothing else about the server.
|
||||
///
|
||||
/// The rule: while no server plugin reports a tier this is inert - <see cref="Current"/> is 0,
|
||||
/// <see cref="Active"/> false and every health scale 1 - so every store keyed by tier behaves
|
||||
/// exactly as before. A reported tier 0 is Active (the Damage panel shows the picker) and still
|
||||
/// changes nothing about the numbers.
|
||||
///
|
||||
/// <see cref="ServerKey"/>: the folder of the per-server creature data (CreatureProfileStore), see
|
||||
/// <see cref="ResolveServerKey"/>.
|
||||
/// </summary>
|
||||
internal sealed class DifficultyTier
|
||||
{
|
||||
/// <summary>The largest tier taken as reported (anything above is read as this).</summary>
|
||||
public const int MaxTier = 10_000;
|
||||
|
||||
/// <summary>The largest health percent per tier taken (anything else, or below 0, reads as 0).</summary>
|
||||
public const double MaxHealthPercent = 1000;
|
||||
|
||||
/// <summary>One reading of the server plugin's values: replaced whole (render and pump threads read it).</summary>
|
||||
internal sealed record Reading(bool Active, int Tier, double HealthPercent, string Plugin)
|
||||
{
|
||||
public static readonly Reading None = new(false, 0, 0, string.Empty);
|
||||
}
|
||||
|
||||
private readonly ServerStateClient _server = new();
|
||||
private volatile Reading _reading = Reading.None;
|
||||
private volatile string _serverKey = string.Empty;
|
||||
private long _nextRefreshMs;
|
||||
private int _appliedRevision = -1;
|
||||
private string _appliedWorld = string.Empty;
|
||||
|
||||
/// <summary>The active server's plugin reports a difficulty tier. False everywhere else.</summary>
|
||||
public bool Active => _reading.Active;
|
||||
|
||||
/// <summary>The tier where the player stands; 0 whenever <see cref="Active"/> is false.</summary>
|
||||
public int Current => _reading.Active ? _reading.Tier : 0;
|
||||
|
||||
/// <summary>The monster health one tier adds, in percent of tier 0's; 0 whenever <see cref="Active"/> is false.</summary>
|
||||
public double HealthPercentPerTier => _reading.Active ? _reading.HealthPercent : 0;
|
||||
|
||||
/// <summary>The plugin the tier comes from ("" while none reports one).</summary>
|
||||
public string Source => _reading.Plugin;
|
||||
|
||||
/// <summary>
|
||||
/// The server's key for per-server data (creatures.json): see <see cref="ResolveServerKey"/>;
|
||||
/// "" while unknown.
|
||||
/// </summary>
|
||||
public string ServerKey => _serverKey;
|
||||
|
||||
/// <summary>The multiplier this server's tier <paramref name="tier"/> puts on a monster's health (1 without tiers).</summary>
|
||||
public double HealthScale(int tier) => HealthScale(tier, HealthPercentPerTier);
|
||||
|
||||
/// <summary>The multiplier a tier puts on a monster's health: 1 + <paramref name="percentPerTier"/>% per tier.</summary>
|
||||
public static double HealthScale(int tier, double percentPerTier)
|
||||
=> tier <= 0 || percentPerTier <= 0 ? 1.0 : 1.0 + percentPerTier / 100.0 * tier;
|
||||
|
||||
/// <summary>Logout: nothing carries to the next login (it may be another server).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
_server.Clear();
|
||||
_reading = Reading.None;
|
||||
_serverKey = string.Empty;
|
||||
_nextRefreshMs = 0;
|
||||
_appliedRevision = -1;
|
||||
_appliedWorld = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the server and its tier, at most once a second (<paramref name="force"/>: now). Pump thread.</summary>
|
||||
public void Refresh(RynthCoreHost host, bool force = false)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (!force && now < _nextRefreshMs) return;
|
||||
_nextRefreshMs = now + 1000;
|
||||
try
|
||||
{
|
||||
_server.Poll(host, now, force: true); // throttled here, not by the client's own 2 s
|
||||
string world = host.HasGetWorldName && host.TryGetWorldName(out string w) ? (w ?? string.Empty).Trim() : string.Empty;
|
||||
if (_server.Revision == _appliedRevision && world == _appliedWorld) return;
|
||||
_appliedRevision = _server.Revision;
|
||||
_appliedWorld = world;
|
||||
Apply(_server.State, _server.ProfileJson, _server.ProfilePlugin, world, CreatureProfileStore.ExistingServerFolder);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What RynthCore's server list, the active server owner's profile JSON and the world name mean:
|
||||
/// the tier reading and the creature data key. <paramref name="existingFolder"/> answers whether a
|
||||
/// per-server creature data folder exists (its name as on disk, or null). Pure apart from it.
|
||||
/// </summary>
|
||||
internal void Apply(EngineServerState? state, string? profileJson, string? plugin, string? world,
|
||||
Func<string, string?> existingFolder)
|
||||
{
|
||||
_reading = Read(profileJson, plugin);
|
||||
_serverKey = ResolveServerKey(state, world, existingFolder);
|
||||
}
|
||||
|
||||
/// <summary>The tier values of a profile JSON; <see cref="Reading.None"/> without a "difficultyTier". Pure.</summary>
|
||||
internal static Reading Read(string? profileJson, string? plugin)
|
||||
{
|
||||
double tier = ServerProfileView.Value(profileJson, RynthServerProfile.ValueDifficultyTier, double.NaN);
|
||||
if (double.IsNaN(tier)) return Reading.None;
|
||||
double percent = ServerProfileView.Value(profileJson, RynthServerProfile.ValueDifficultyHealthPercent, 0);
|
||||
if (!(percent >= 0 && percent <= MaxHealthPercent)) percent = 0;
|
||||
return new Reading(true, (int)Math.Clamp(Math.Round(tier), 0, MaxTier), percent, plugin ?? string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The folder name of this server's creature data. Pure apart from <paramref name="existingFolder"/>.
|
||||
/// * RynthCore names the server (the active one, else one its detection found and this character
|
||||
/// turned off): a folder that already holds data is kept, looked for under the server's id, then
|
||||
/// its name, then the world name (RynthAi before 2026-10-21 used the world name, and "Aelrynth"
|
||||
/// for that server's worlds, which its name finds); with none, the server's id.
|
||||
/// * Otherwise (no server, an engine before v86): the world name, as before.
|
||||
/// Every key is made safe for a folder name (the SettingsProfiles rule); "" while nothing is known.
|
||||
/// </summary>
|
||||
internal static string ResolveServerKey(EngineServerState? state, string? world, Func<string, string?> existingFolder)
|
||||
{
|
||||
string legacy = SafeKey(world);
|
||||
EngineServer? server = ServerOf(state);
|
||||
if (server == null) return legacy;
|
||||
string id = SafeKey(server.Id);
|
||||
foreach (string candidate in new[] { id, SafeKey(server.Name), legacy })
|
||||
{
|
||||
if (candidate.Length == 0) continue;
|
||||
string? found = existingFolder(candidate);
|
||||
if (!string.IsNullOrEmpty(found)) return found;
|
||||
}
|
||||
return id.Length > 0 ? id : legacy;
|
||||
}
|
||||
|
||||
/// <summary>RynthCore's active server, else the first one its detection found (turned off by an override); null for none.</summary>
|
||||
private static EngineServer? ServerOf(EngineServerState? state)
|
||||
{
|
||||
if (state == null) return null;
|
||||
if (state.HasActive)
|
||||
return state.Find(state.Active) ?? new EngineServer(state.Active, state.ActiveName, true, true, "auto", false, state.ActivePlugin, "");
|
||||
foreach (EngineServer s in state.Servers)
|
||||
if (s.Detected) return s;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A world or server name as a folder name (the SettingsProfiles rule); "" for none.</summary>
|
||||
public static string SafeKey(string? name)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name)) return string.Empty;
|
||||
var sb = new System.Text.StringBuilder(name.Length);
|
||||
foreach (char c in name.Trim())
|
||||
sb.Append(char.IsLetterOrDigit(c) || c == '\'' || c == '-' ? c : '_');
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
|
@ -32,13 +32,13 @@ namespace RynthCore.Plugin.RynthAi.CreatureData;
|
|||
/// D|<wcid>|<name>|<weaponId>|<element>|<tier>|<avgDamage>|<dmgSamples>|<avgCastsToKill>|<killSamples>|<critAvg>|<critSamples>|<nonCritAvg>|<nonCritSamples>
|
||||
/// (The loader also accepts the older 9/10-field name-less / crit-less D rows so existing data carries over.)
|
||||
///
|
||||
/// Aelrynth difficulty tiers (2026-10-03, <see cref="AwakenedTier"/>): Aelrynth's awakened worlds
|
||||
/// and scaled copies hold the same monsters (same wcids) with health, skills and damage scaled 5%
|
||||
/// a tier. What a tier changes is kept per (wcid, tier): the HP pool, casts-to-kill, hits and
|
||||
/// Difficulty tiers (2026-10-03, <see cref="DifficultyTier"/>: the active server plugin reports
|
||||
/// them): a server's scaled worlds and copies hold the same monsters (same wcids) with health,
|
||||
/// skills and damage scaled by the tier. What a tier changes is kept per (wcid, tier): the HP pool, casts-to-kill, hits and
|
||||
/// misses, seconds per kill (per weapon and per summon) and the damage the monster does to us.
|
||||
/// What it does not change stays shared: per-cast damage (resistances and armour don't scale)
|
||||
/// and every rule (weapon, offhand, pet, manual HP). Tier 0 - real Dereth, and every other
|
||||
/// server, where the tier is always 0 - is today's data in today's rows, untouched. Tiers above 0
|
||||
/// and every rule (weapon, offhand, pet, manual HP). Tier 0 - the unscaled world, and every
|
||||
/// server without tiers, where the tier is always 0 - is today's data in today's rows, untouched. Tiers above 0
|
||||
/// are extra rows an older loader skips:
|
||||
/// AH|<tier>|<wcid>|<name>|<hpToKill>|<samples>
|
||||
/// AD|<tier>|<wcid>|<name>|<weaponId>|<element>|<spellTier>|<avgCastsToKill>|<killSamples>
|
||||
|
|
@ -115,7 +115,7 @@ internal sealed class MonsterDamageStore
|
|||
public int KillSamples;
|
||||
}
|
||||
|
||||
/// <summary>What one Aelrynth difficulty tier above 0 changes about one monster (see the class comment).</summary>
|
||||
/// <summary>What one difficulty tier above 0 changes about one monster (see the class comment).</summary>
|
||||
private sealed class TierProfile
|
||||
{
|
||||
public double HpPool;
|
||||
|
|
@ -134,9 +134,9 @@ internal sealed class MonsterDamageStore
|
|||
private volatile int _difficulty;
|
||||
|
||||
/// <summary>
|
||||
/// The Aelrynth difficulty tier new observations are recorded under, and the one the
|
||||
/// tier-less readers answer for: the tier where the player stands (AwakenedTier.Current,
|
||||
/// set every tick). Always 0 off Aelrynth.
|
||||
/// The difficulty tier new observations are recorded under, and the one the tier-less
|
||||
/// readers answer for: the tier where the player stands (DifficultyTier.Current, set every
|
||||
/// tick). Always 0 on a server without tiers.
|
||||
/// </summary>
|
||||
public int Difficulty
|
||||
{
|
||||
|
|
@ -425,7 +425,7 @@ internal sealed class MonsterDamageStore
|
|||
private void AppendTierRows(StringBuilder sb)
|
||||
{
|
||||
if (_byTier.Count == 0) return;
|
||||
sb.Append("# Aelrynth difficulty tiers above 0 (awakened worlds, scaled copies); tier 0 is the rows above:\n");
|
||||
sb.Append("# Above tier 0: the server's difficulty tiers (scaled worlds, copies); tier 0 is the rows above:\n");
|
||||
sb.Append("# AH|tier|wcid|name|hpToKill|samples\n");
|
||||
sb.Append("# AD|tier|wcid|name|weaponId|element|spellTier|avgCastsToKill|killSamples\n");
|
||||
sb.Append("# AU|tier|wcid|name|weaponId|hits|misses|secToKillAvg|secSamples\n");
|
||||
|
|
@ -764,7 +764,7 @@ internal sealed class MonsterDamageStore
|
|||
return tp;
|
||||
}
|
||||
|
||||
/// <summary>The difficulty tiers above 0 with anything learned, ascending (empty off Aelrynth).</summary>
|
||||
/// <summary>The difficulty tiers above 0 with anything learned, ascending (empty on a server without tiers).</summary>
|
||||
public List<int> KnownDifficulties()
|
||||
{
|
||||
var set = new SortedSet<int>();
|
||||
|
|
|
|||
|
|
@ -453,10 +453,10 @@ internal sealed class MiniRemoteHud
|
|||
{
|
||||
// The server plugin's Remote sections (RynthILT: Bank, Guardian answer) decide themselves whether
|
||||
// they show (their switches are the plugin's); nothing is drawn without one.
|
||||
bool drawn = remote?.ServerHub.RenderSection(RynthIltHub.SectionRemoteBank) == true;
|
||||
bool drawn = remote?.ServerHub.RenderSection(RynthServerHub.SectionRemoteBank) == true;
|
||||
if (s.MiniShowRebuff) RenderRebuff();
|
||||
if (s.MiniShowTranslate && _hud.Translate is { } translate) translate.RenderHubSection();
|
||||
drawn |= remote?.ServerHub.RenderSection(RynthIltHub.SectionRemoteGuardian) == true;
|
||||
drawn |= remote?.ServerHub.RenderSection(RynthServerHub.SectionRemoteGuardian) == true;
|
||||
_serverEconomyDrawn = drawn;
|
||||
}
|
||||
|
||||
|
|
@ -490,7 +490,7 @@ internal sealed class MiniRemoteHud
|
|||
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"{v.LumPassUp:N0} this session.\n{PassUpTooltip}");
|
||||
}
|
||||
Stat("Kills:", HudDraw.Compact(v.KillsPerHour) + "/h");
|
||||
remote?.ServerHub.RenderSection(RynthIltHub.SectionRemoteStats);
|
||||
remote?.ServerHub.RenderSection(RynthServerHub.SectionRemoteStats);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -660,7 +660,7 @@ internal sealed class MiniRemoteHud
|
|||
+ $"({HudDraw.Compact(v.LumLast5Min)} last 5m)";
|
||||
if (v.PassUpTracked) line += $", Pass-up {HudDraw.Compact(v.PassUpPerHour)}/h";
|
||||
line += $", Kills {HudDraw.Compact(v.KillsPerHour)}/h ({v.Kills:N0})";
|
||||
line += _hud.Remote()?.ServerHub.Text(RynthIltHub.TextSessionReport) ?? string.Empty; // the server plugin's rates
|
||||
line += _hud.Remote()?.ServerHub.Text(RynthServerHub.TextSessionReport) ?? string.Empty; // the server plugin's rates
|
||||
_hud.Chat(line);
|
||||
}
|
||||
|
||||
|
|
@ -832,7 +832,7 @@ internal sealed class MiniRemoteHud
|
|||
Flag("Rebuff", ref s.MiniShowRebuff);
|
||||
Flag("Translate", ref s.MiniShowTranslate);
|
||||
// The server plugin's Remote sections (RynthILT: Bank, Guardian answer): its own switches.
|
||||
_hud.Remote()?.ServerHub.RenderSection(RynthIltHub.SectionRemoteOptions);
|
||||
_hud.Remote()?.ServerHub.RenderSection(RynthServerHub.SectionRemoteOptions);
|
||||
ImGui.Separator();
|
||||
Flag("Horizontal layout", ref s.MiniRemoteHorizontal);
|
||||
RenderSlotSizeSlider(s);
|
||||
|
|
@ -937,13 +937,13 @@ internal sealed class MiniRemoteHud
|
|||
ServerMenuGroup[]? groups = ServerMenuModel.Groups;
|
||||
if (groups == null)
|
||||
{
|
||||
remote?.ServerHub.RenderSection(RynthIltHub.SectionServerMenu);
|
||||
remote?.ServerHub.RenderSection(RynthServerHub.SectionServerMenu);
|
||||
return;
|
||||
}
|
||||
if (groups.Length == 0) return; // no server plugin installed
|
||||
|
||||
// The server the active server plugin's tabs and status belong to (RynthILT: "ilt"); "" without one.
|
||||
string pluginServer = remote?.ServerHub.Text(RynthIltHub.TextServerId) ?? string.Empty;
|
||||
string pluginServer = remote?.ServerHub.Text(RynthServerHub.TextServerId) ?? string.Empty;
|
||||
bool any = false;
|
||||
foreach (ServerMenuGroup g in groups)
|
||||
{
|
||||
|
|
@ -969,7 +969,7 @@ internal sealed class MiniRemoteHud
|
|||
SafeImGui.SetTooltip(enabled ? item.Tooltip : item.Tooltip + "\nShows once the server reports this feature on.");
|
||||
}
|
||||
// The plugin's status under its server (RynthILT: why no ILT feature is on, Refresh).
|
||||
if (ours) remote?.ServerHub.RenderSection(RynthIltHub.SectionIltStatus);
|
||||
if (ours) remote?.ServerHub.RenderSection(RynthServerHub.SectionServerStatus);
|
||||
}
|
||||
if (any) return;
|
||||
|
||||
|
|
|
|||
|
|
@ -1101,7 +1101,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
// ── Settings bridge (engine-side Avalonia SettingsPanel) ─────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The active server plugin's mirrored settings (RynthILT.Hub GetSetting / SetSetting, through the
|
||||
/// The active server plugin's mirrored settings (RynthServer.Hub GetSetting / SetSetting, through the
|
||||
/// Mini Remote's server client): the value, or -1 when none is offered. Set by RynthAiPlugin.
|
||||
/// </summary>
|
||||
public Func<string, int>? ServerSettingGet { get; set; }
|
||||
|
|
@ -1238,7 +1238,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
CorpseApproachRangeMin = s.CorpseApproachRangeMin,
|
||||
// Navigation
|
||||
BoostNavPriority = s.BoostNavPriority,
|
||||
EnableVaultedDungeons = ServerSettingBool(RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons), // RynthILT's (null: the row hides)
|
||||
EnableVaultedDungeons = ServerSettingBool(RynthCore.Plugin.Shared.RynthServerHub.SettingVaultedDungeons), // the server plugin's (null: the row hides)
|
||||
FollowNavMin = s.FollowNavMin,
|
||||
NavRingThickness = s.NavRingThickness,
|
||||
NavLineThickness = s.NavLineThickness,
|
||||
|
|
@ -1499,7 +1499,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
// Navigation
|
||||
s.BoostNavPriority = p.BoostNavPriority;
|
||||
if (p.EnableVaultedDungeons is bool vaulted) // absent = unchanged
|
||||
ServerSettingSet?.Invoke(RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons, vaulted ? 1 : 0); // RynthILT's switch
|
||||
ServerSettingSet?.Invoke(RynthCore.Plugin.Shared.RynthServerHub.SettingVaultedDungeons, vaulted ? 1 : 0); // the server plugin's switch
|
||||
s.FollowNavMin = p.FollowNavMin;
|
||||
s.NavRingThickness = p.NavRingThickness;
|
||||
s.NavLineThickness = p.NavLineThickness;
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.RynthLogConfig))]
|
||||
[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Huds.HudState))]
|
||||
[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.MiniRemote.MiniRemoteState))]
|
||||
[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.MiniRemote.LegacyIltHubFile))]
|
||||
[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.MiniRemote.LegacyHubFile))]
|
||||
[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.BuffProfile))]
|
||||
[JsonSourceGenerationOptions(
|
||||
WriteIndented = true,
|
||||
|
|
|
|||
|
|
@ -78,7 +78,7 @@ internal sealed class MiniRemoteController
|
|||
public Func<string, string, string>? MiniRemoteTabCommand { get; set; }
|
||||
|
||||
/// <summary>True when the server plugin already says /myquests is off on its server (skip the login refresh).</summary>
|
||||
public bool SkipLoginQuestRefresh => _ctx.ServerHub.ServerActive && _ctx.ServerHub.IsOff(RynthIltHub.FeatureQuests);
|
||||
public bool SkipLoginQuestRefresh => _ctx.ServerHub.ServerActive && _ctx.ServerHub.IsOff(RynthServerHub.FeatureQuests);
|
||||
|
||||
// ── Lifecycle ───────────────────────────────────────────────────────────
|
||||
|
||||
|
|
@ -144,7 +144,7 @@ internal sealed class MiniRemoteController
|
|||
RynthLog.Trace(LogCat.Quests, "RefreshQuests()");
|
||||
QuestTracker? t = _quests();
|
||||
if (t == null) return "Quest tracker not ready.";
|
||||
if (_ctx.ServerHub.IsOff(RynthIltHub.FeatureQuests) || t.Disabled) return "/myquests is disabled on this server.";
|
||||
if (_ctx.ServerHub.IsOff(RynthServerHub.FeatureQuests) || t.Disabled) return "/myquests is disabled on this server.";
|
||||
long now = MiniRemoteContext.NowMs;
|
||||
if (now - _lastQuestRefreshAt < QuestRefreshCooldownMs)
|
||||
return $"Wait {(QuestRefreshCooldownMs - (now - _lastQuestRefreshAt)) / 1000}s (server allows one /myquests per minute).";
|
||||
|
|
|
|||
|
|
@ -155,17 +155,17 @@ public sealed class QuestsTabState
|
|||
}
|
||||
|
||||
/// <summary>The parts of an old ilt-hub.json the universal tabs take over (first load only).</summary>
|
||||
public sealed class LegacyIltHubFile
|
||||
public sealed class LegacyHubFile
|
||||
{
|
||||
public PetTabState? Pet;
|
||||
/// <summary>The ILT Hub's IltCharacterState: its quest fields have QuestsTabState's names.</summary>
|
||||
public QuestsTabState? Character;
|
||||
public LegacyIltGear? Gear;
|
||||
public LegacyHubGear? Gear;
|
||||
/// <summary>The ILT Hub's Crafting tab (build-comp-10-11 hosted it in RynthAi): same field names.</summary>
|
||||
public CraftingTabState? Crafting;
|
||||
}
|
||||
|
||||
public sealed class LegacyIltGear
|
||||
public sealed class LegacyHubGear
|
||||
{
|
||||
public string? LastUsdPath;
|
||||
}
|
||||
|
|
@ -202,7 +202,7 @@ internal sealed class MiniRemoteStore
|
|||
string legacy = Path.Combine(_charFolder, LegacyFileName);
|
||||
if (_charFolder.Length > 0 && File.Exists(legacy))
|
||||
{
|
||||
var old = JsonSerializer.Deserialize(File.ReadAllText(legacy), RynthAiJsonContext.Default.LegacyIltHubFile);
|
||||
var old = JsonSerializer.Deserialize(File.ReadAllText(legacy), RynthAiJsonContext.Default.LegacyHubFile);
|
||||
if (old != null)
|
||||
{
|
||||
var s = FromLegacy(old);
|
||||
|
|
@ -216,7 +216,7 @@ internal sealed class MiniRemoteStore
|
|||
}
|
||||
|
||||
/// <summary>The universal parts of an old ilt-hub.json as a fresh state.</summary>
|
||||
internal static MiniRemoteState FromLegacy(LegacyIltHubFile old)
|
||||
internal static MiniRemoteState FromLegacy(LegacyHubFile old)
|
||||
{
|
||||
var s = new MiniRemoteState
|
||||
{
|
||||
|
|
|
|||
|
|
@ -676,7 +676,7 @@ internal sealed class PetsTab
|
|||
internal string? PendingSubTab => _selectSubTab;
|
||||
|
||||
/// <summary>The sub-tabs the server plugin adds to this tab now (RynthILT's Breeding); empty without one.</summary>
|
||||
public IReadOnlyList<ServerTabInfo> SubTabs() => _ctx.ServerHub.SubTabs(RynthIltHub.TabParentPets);
|
||||
public IReadOnlyList<ServerTabInfo> SubTabs() => _ctx.ServerHub.SubTabs(RynthServerHub.TabParentPets);
|
||||
|
||||
/// <summary>
|
||||
/// The shown sub-tab a "/ra hub open|tab <name>" names: its label ("Breeding"), its id, or its id
|
||||
|
|
@ -699,7 +699,7 @@ internal sealed class PetsTab
|
|||
return null;
|
||||
}
|
||||
|
||||
private const string SubTabPrefix = RynthIltHub.TabParentPets + "-";
|
||||
private const string SubTabPrefix = RynthServerHub.TabParentPets + "-";
|
||||
|
||||
/// <summary>
|
||||
/// The Pets tab: the universal roster, and Roster | ... sub-tabs when the server plugin adds some
|
||||
|
|
@ -770,11 +770,11 @@ internal sealed class PetsTab
|
|||
RenderRosterTable();
|
||||
// The server plugin's own pet features (RynthILT: ACECustom's charms and siphon capture);
|
||||
// each draws its own separator, and nothing off its server.
|
||||
_ctx.ServerHub.RenderSection(RynthIltHub.SectionPetCharms);
|
||||
_ctx.ServerHub.RenderSection(RynthIltHub.SectionPetCapture);
|
||||
_ctx.ServerHub.RenderSection(RynthServerHub.SectionPetCharms);
|
||||
_ctx.ServerHub.RenderSection(RynthServerHub.SectionPetCapture);
|
||||
ImGui.Separator();
|
||||
RenderHealing();
|
||||
_ctx.ServerHub.RenderSection(RynthIltHub.SectionPetLogs);
|
||||
_ctx.ServerHub.RenderSection(RynthServerHub.SectionPetLogs);
|
||||
}
|
||||
|
||||
/// <summary>Type / Sort combos, action buttons, the active-summon line and per-type options.</summary>
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
// ServerHubClient.cs - RynthAi's side of a server plugin's hub (the "RynthILT.Hub" table layout,
|
||||
// Plugins/Shared/RynthIltHubApi.cs; was IltClient until 2026-10-20): the tabs, sub-tabs and sections
|
||||
// ServerHubClient.cs - RynthAi's side of a server plugin's hub ("RynthServer.Hub",
|
||||
// Plugins/Shared/RynthServerHubApi.cs; was IltClient until 2026-10-20): the tabs, sub-tabs and sections
|
||||
// the Mini Remote hosts for the server you're on, its feature bits (the Quests tab's /myquests bit),
|
||||
// its texts and settings, its "/ra" verbs, and its pet gate. RynthAi knows no server's content: it
|
||||
// shows what the plugin offers.
|
||||
//
|
||||
// The plugin is found by the engine's server list first (the active server's owner plugin, under the
|
||||
// neutral name "RynthServer.Hub"), then RynthILT under "RynthILT.Hub" (every RynthILT answers that;
|
||||
// older ones only that). Without one (not installed, too old, not loaded yet: any retail-like world)
|
||||
// The plugin is found through RynthCore's server list (plugin API v86, GetServerStateJson): the
|
||||
// active server's owner plugin first, else the owners of the other servers it lists (a server plugin
|
||||
// may follow its own world check or override), preferring one that says this world is its server.
|
||||
// Without one (not installed, too old, not loaded yet, an engine before v86: any retail-like world)
|
||||
// every call answers "nothing": no tab, no section, unknown feature bits, no verbs. The table is
|
||||
// looked up on the pump thread (Tick) at most every RecheckMs and kept in a volatile field for the
|
||||
// render thread; the plugin never frees it (Version goes to 0 on its shutdown), so reading a stale
|
||||
|
|
@ -32,7 +33,7 @@ internal sealed unsafe class ServerHubClient
|
|||
private IntPtr _table; // volatile reads/writes: the render thread uses what the pump found
|
||||
private long _checkedAt;
|
||||
private bool _checkedOnce; // false: look now (a sentinel time would overflow "now - _checkedAt")
|
||||
private readonly IltTabV1[] _tabBuf = new IltTabV1[MaxTabs];
|
||||
private readonly ServerHubTabV1[] _tabBuf = new ServerHubTabV1[MaxTabs];
|
||||
private readonly List<ServerTabInfo> _tabs = new();
|
||||
|
||||
private bool _pinned; // tests: a table handed in, never looked up
|
||||
|
|
@ -52,39 +53,69 @@ internal sealed unsafe class ServerHubClient
|
|||
{
|
||||
if (_pinned) return;
|
||||
long now = Environment.TickCount64;
|
||||
var t = (RynthIltHubApiV1*)System.Threading.Volatile.Read(ref _table);
|
||||
var t = (RynthServerHubApiV1*)System.Threading.Volatile.Read(ref _table);
|
||||
if (!LookupDue(_checkedOnce, _checkedAt, now, haveTable: t != null, tableLive: t != null && t->Version >= 1)) return;
|
||||
_checkedOnce = true;
|
||||
_checkedAt = now;
|
||||
IntPtr found = IntPtr.Zero;
|
||||
if (_host.HasGetPluginInterface)
|
||||
{
|
||||
// The active server's own plugin (the engine's server list), under the neutral name ...
|
||||
string owner = ActiveServerPlugin();
|
||||
if (owner.Length > 0) found = Look(owner, RynthIltHubApiV1.NeutralInterfaceName);
|
||||
// ... else RynthILT under its own name (every RynthILT; it also follows its own world check).
|
||||
if (found == IntPtr.Zero) found = Look(RynthIltHub.PluginName, RynthIltHubApiV1.InterfaceName);
|
||||
EngineServerState? st = EngineState();
|
||||
IReadOnlyList<string> owners = OwnerOrder(st);
|
||||
bool activeFirst = st != null && st.ActivePlugin.Length > 0;
|
||||
IntPtr first = IntPtr.Zero;
|
||||
for (int i = 0; i < owners.Count && found == IntPtr.Zero; i++)
|
||||
{
|
||||
IntPtr p = Look(owners[i]);
|
||||
if (p == IntPtr.Zero) continue;
|
||||
// The active server's own plugin is the one; another server's only when it claims this world.
|
||||
var hub = (RynthServerHubApiV1*)p;
|
||||
if ((i == 0 && activeFirst) || (hub->IsServerWorld != null && hub->IsServerWorld() != 0)) found = p;
|
||||
else if (first == IntPtr.Zero) first = p;
|
||||
}
|
||||
// None claims this world: the first that serves a hub (its tabs say they're hidden).
|
||||
if (found == IntPtr.Zero) found = first;
|
||||
}
|
||||
System.Threading.Volatile.Write(ref _table, found);
|
||||
}
|
||||
|
||||
/// <summary>A hub table <paramref name="plugin"/> serves as <paramref name="iface"/>, or 0.</summary>
|
||||
private IntPtr Look(string plugin, string iface)
|
||||
/// <summary>A hub table <paramref name="plugin"/> serves, or 0.</summary>
|
||||
private IntPtr Look(string plugin)
|
||||
{
|
||||
var p = (RynthIltHubApiV1*)_host.GetPluginInterface(plugin, iface, RynthIltHubApiV1.InterfaceVersion);
|
||||
var p = (RynthServerHubApiV1*)_host.GetPluginInterface(plugin, RynthServerHubApiV1.InterfaceName, RynthServerHubApiV1.InterfaceVersion);
|
||||
// Any table at least as big as the first release's: newer functions are checked with Has.
|
||||
return p != null && p->Version >= 1 && p->StructSize >= RynthIltHubApiV1.BaseStructSize ? (IntPtr)p : IntPtr.Zero;
|
||||
return p != null && p->Version >= 1 && p->StructSize >= RynthServerHubApiV1.BaseStructSize ? (IntPtr)p : IntPtr.Zero;
|
||||
}
|
||||
|
||||
/// <summary>The plugin that owns the engine's active server ("" when none, or the engine is pre-v86). Pump thread.</summary>
|
||||
private string ActiveServerPlugin()
|
||||
/// <summary>RynthCore's server list (null when none, or the engine is pre-v86). Pump thread.</summary>
|
||||
private EngineServerState? EngineState()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_host.HasGetServerStateJson || !_host.TryGetServerStateJson(out string json)) return string.Empty;
|
||||
return EngineServerState.Parse(json)?.ActivePlugin ?? string.Empty;
|
||||
if (!_host.HasGetServerStateJson || !_host.TryGetServerStateJson(out string json)) return null;
|
||||
return EngineServerState.Parse(json);
|
||||
}
|
||||
catch { return string.Empty; }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plugins to ask for a hub, in order: the active server's owner, then every other server's
|
||||
/// owner RynthCore lists (each once). Empty without a server list. Pure.
|
||||
/// </summary>
|
||||
internal static IReadOnlyList<string> OwnerOrder(EngineServerState? st)
|
||||
{
|
||||
var list = new List<string>();
|
||||
if (st == null) return list;
|
||||
if (st.ActivePlugin.Length > 0) list.Add(st.ActivePlugin);
|
||||
foreach (EngineServer s in st.Servers)
|
||||
{
|
||||
if (s.Plugin.Length == 0) continue;
|
||||
bool seen = false;
|
||||
foreach (string p in list)
|
||||
if (p.Equals(s.Plugin, StringComparison.OrdinalIgnoreCase)) { seen = true; break; }
|
||||
if (!seen) list.Add(s.Plugin);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Forget the table (login, logout); the next Tick looks again.</summary>
|
||||
|
|
@ -97,7 +128,7 @@ internal sealed unsafe class ServerHubClient
|
|||
|
||||
/// <summary>
|
||||
/// Whether Tick looks the table up again. Pure. Always on the first call (and after Reset), at
|
||||
/// once when the table RynthILT gave is shut down (Version 0), else every <see cref="RecheckMs"/>.
|
||||
/// once when the table the plugin gave is shut down (Version 0), else every <see cref="RecheckMs"/>.
|
||||
/// </summary>
|
||||
internal static bool LookupDue(bool checkedOnce, long checkedAt, long now, bool haveTable, bool tableLive)
|
||||
{
|
||||
|
|
@ -106,11 +137,11 @@ internal sealed unsafe class ServerHubClient
|
|||
return now - checkedAt >= RecheckMs;
|
||||
}
|
||||
|
||||
private RynthIltHubApiV1* T
|
||||
private RynthServerHubApiV1* T
|
||||
{
|
||||
get
|
||||
{
|
||||
var t = (RynthIltHubApiV1*)System.Threading.Volatile.Read(ref _table);
|
||||
var t = (RynthServerHubApiV1*)System.Threading.Volatile.Read(ref _table);
|
||||
return t != null && t->Version >= 1 ? t : null;
|
||||
}
|
||||
}
|
||||
|
|
@ -118,13 +149,13 @@ internal sealed unsafe class ServerHubClient
|
|||
/// <summary>A server plugin answers (any thread).</summary>
|
||||
public bool Loaded => T != null;
|
||||
|
||||
/// <summary>This world is the plugin's server (or forced there), as it sees it (RynthILT: Infinite Leaftide). Any thread.</summary>
|
||||
/// <summary>This world is the plugin's server (or forced there), as it sees it. Any thread.</summary>
|
||||
public bool ServerActive
|
||||
{
|
||||
get
|
||||
{
|
||||
var t = T;
|
||||
return t != null && t->IsIltWorld != null && t->IsIltWorld() != 0;
|
||||
return t != null && t->IsServerWorld != null && t->IsServerWorld() != 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -144,13 +175,13 @@ internal sealed unsafe class ServerHubClient
|
|||
public bool IsOn(string key) => Feature(key) == 1;
|
||||
|
||||
/// <summary>
|
||||
/// A short text from the server plugin (RynthIltHub.Text*: the session report's tail, its server id);
|
||||
/// A short text from the server plugin (RynthServerHub.Text*: the session report's tail, its server id);
|
||||
/// "" without one, from an older one, or for nothing. Any thread.
|
||||
/// </summary>
|
||||
public string Text(string id)
|
||||
{
|
||||
var t = T;
|
||||
if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetTextOffset) || t->GetText == null) return string.Empty;
|
||||
if (t == null || !RynthServerHubApiV1.Has(t, RynthServerHubApiV1.GetTextOffset) || t->GetText == null) return string.Empty;
|
||||
byte* buf = stackalloc byte[256];
|
||||
buf[0] = 0;
|
||||
int n;
|
||||
|
|
@ -161,7 +192,7 @@ internal sealed unsafe class ServerHubClient
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// This character forces the plugin's server (RynthILT: "Treat this world as ILT"; set there or in
|
||||
/// This character forces the plugin's server (its own override; set there or in
|
||||
/// RynthCore's Options > Diagnostics, never by RynthAi). Any thread.
|
||||
/// </summary>
|
||||
public bool ServerForced
|
||||
|
|
@ -169,7 +200,7 @@ internal sealed unsafe class ServerHubClient
|
|||
get
|
||||
{
|
||||
var t = T;
|
||||
return t != null && t->GetForceIlt != null && t->GetForceIlt() != 0;
|
||||
return t != null && t->GetForceServer != null && t->GetForceServer() != 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -180,22 +211,22 @@ internal sealed unsafe class ServerHubClient
|
|||
var t = T;
|
||||
if (t == null || t->GetTabs == null) return _tabs;
|
||||
int n;
|
||||
fixed (IltTabV1* buf = _tabBuf) n = t->GetTabs(buf, MaxTabs);
|
||||
fixed (ServerHubTabV1* buf = _tabBuf) n = t->GetTabs(buf, MaxTabs);
|
||||
n = Math.Min(n, MaxTabs);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
ref IltTabV1 tab = ref _tabBuf[i];
|
||||
ref ServerHubTabV1 tab = ref _tabBuf[i];
|
||||
string id, label;
|
||||
fixed (byte* pid = tab.Id) id = Marshal.PtrToStringUTF8((IntPtr)pid) ?? string.Empty;
|
||||
fixed (byte* plabel = tab.Label) label = Marshal.PtrToStringUTF8((IntPtr)plabel) ?? string.Empty;
|
||||
if (id.Length == 0) continue;
|
||||
_tabs.Add(new ServerTabInfo(id, label.Length > 0 ? label : id, tab.Width, tab.Height,
|
||||
(tab.Flags & RynthIltHub.TabShown) != 0, (tab.Flags & RynthIltHub.TabAvailable) != 0));
|
||||
(tab.Flags & RynthServerHub.TabShown) != 0, (tab.Flags & RynthServerHub.TabAvailable) != 0));
|
||||
}
|
||||
return _tabs;
|
||||
}
|
||||
|
||||
/// <summary>Render thread: one ILT tab's body into the current child window; false = nothing drawn.</summary>
|
||||
/// <summary>Render thread: one of the plugin's tabs into the current child window; false = nothing drawn.</summary>
|
||||
public bool RenderTab(string id)
|
||||
{
|
||||
var t = T;
|
||||
|
|
@ -204,7 +235,7 @@ internal sealed unsafe class ServerHubClient
|
|||
return t->RenderTab(s.P) != 0;
|
||||
}
|
||||
|
||||
/// <summary>Render thread: an ILT section (RynthIltHub.Section*); false = nothing drawn (not ILT, or no RynthILT).</summary>
|
||||
/// <summary>Render thread: a server section (RynthServerHub.Section*); false = nothing drawn (not its server, or no plugin).</summary>
|
||||
public bool RenderSection(string id)
|
||||
{
|
||||
var t = T;
|
||||
|
|
@ -213,7 +244,7 @@ internal sealed unsafe class ServerHubClient
|
|||
return t->RenderSection(s.P) != 0;
|
||||
}
|
||||
|
||||
/// <summary>An ILT "/ra" verb ("hub bank", "guardian handin", ...); false when RynthILT doesn't take it.</summary>
|
||||
/// <summary>One of the plugin's "/ra" verbs ("hub bank", ...); false when it doesn't take it.</summary>
|
||||
public bool Command(string text)
|
||||
{
|
||||
var t = T;
|
||||
|
|
@ -224,21 +255,21 @@ internal sealed unsafe class ServerHubClient
|
|||
|
||||
/// <summary>
|
||||
/// The server plugin's answer to "may an EMPTY pet essence be summoned?" (the server refills it;
|
||||
/// RynthILT: ACECustom's Summon Essence Refill charm). False without one, or from an older one
|
||||
/// e.g. a refill charm). False without one, or from an older one
|
||||
/// that doesn't answer: an empty essence is then never used. Any thread.
|
||||
/// </summary>
|
||||
public bool AllowSummonOnEmpty()
|
||||
{
|
||||
var t = T;
|
||||
return t != null && RynthIltHubApiV1.Has(t, RynthIltHubApiV1.AllowSummonOnEmptyOffset)
|
||||
return t != null && RynthServerHubApiV1.Has(t, RynthServerHubApiV1.AllowSummonOnEmptyOffset)
|
||||
&& t->AllowSummonOnEmpty != null && t->AllowSummonOnEmpty() != 0;
|
||||
}
|
||||
|
||||
/// <summary>One of the server plugin's mirrored settings (RynthIltHub.Setting*): its value, -1 when not offered. Any thread.</summary>
|
||||
/// <summary>One of the server plugin's mirrored settings (RynthServerHub.Setting*): its value, -1 when not offered. Any thread.</summary>
|
||||
public int Setting(string key)
|
||||
{
|
||||
var t = T;
|
||||
if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetSettingOffset) || t->GetSetting == null) return -1;
|
||||
if (t == null || !RynthServerHubApiV1.Has(t, RynthServerHubApiV1.GetSettingOffset) || t->GetSetting == null) return -1;
|
||||
using var k = new Utf8(key);
|
||||
return t->GetSetting(k.P);
|
||||
}
|
||||
|
|
@ -247,7 +278,7 @@ internal sealed unsafe class ServerHubClient
|
|||
public bool SetSetting(string key, int value)
|
||||
{
|
||||
var t = T;
|
||||
if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.SetSettingOffset) || t->SetSetting == null) return false;
|
||||
if (t == null || !RynthServerHubApiV1.Has(t, RynthServerHubApiV1.SetSettingOffset) || t->SetSetting == null) return false;
|
||||
using var k = new Utf8(key);
|
||||
return t->SetSetting(k.P, value) != 0;
|
||||
}
|
||||
|
|
@ -256,15 +287,15 @@ internal sealed unsafe class ServerHubClient
|
|||
|
||||
/// <summary>
|
||||
/// The sub-tabs the server plugin adds to one of the Mini Remote's tabs (<paramref name="parent"/>
|
||||
/// "pets": RynthILT's Breeding). Each id is a RenderSection id. Empty without one. A new list each
|
||||
/// "pets": e.g. a Breeding sub-tab). Each id is a RenderSection id. Empty without one. A new list each
|
||||
/// call (the render thread draws them, a command looks one up). Any thread.
|
||||
/// </summary>
|
||||
public IReadOnlyList<ServerTabInfo> SubTabs(string parent)
|
||||
{
|
||||
var t = T;
|
||||
if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetSubTabsOffset) || t->GetSubTabs == null)
|
||||
if (t == null || !RynthServerHubApiV1.Has(t, RynthServerHubApiV1.GetSubTabsOffset) || t->GetSubTabs == null)
|
||||
return Array.Empty<ServerTabInfo>();
|
||||
IltTabV1* buf = stackalloc IltTabV1[MaxSubTabs];
|
||||
ServerHubTabV1* buf = stackalloc ServerHubTabV1[MaxSubTabs];
|
||||
int n;
|
||||
using (var p = new Utf8(parent)) n = t->GetSubTabs(p.P, buf, MaxSubTabs);
|
||||
n = Math.Min(n, MaxSubTabs);
|
||||
|
|
@ -272,14 +303,14 @@ internal sealed unsafe class ServerHubClient
|
|||
var list = new List<ServerTabInfo>(n);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
IltTabV1* tab = &buf[i];
|
||||
ServerHubTabV1* tab = &buf[i];
|
||||
tab->Id[23] = 0; // never read past a buffer the other side filled to the brim
|
||||
tab->Label[31] = 0;
|
||||
string id = Marshal.PtrToStringUTF8((IntPtr)tab->Id) ?? string.Empty;
|
||||
string label = Marshal.PtrToStringUTF8((IntPtr)tab->Label) ?? string.Empty;
|
||||
if (id.Length == 0) continue;
|
||||
list.Add(new ServerTabInfo(id, label.Length > 0 ? label : id, tab->Width, tab->Height,
|
||||
(tab->Flags & RynthIltHub.TabShown) != 0, (tab->Flags & RynthIltHub.TabAvailable) != 0));
|
||||
(tab->Flags & RynthServerHub.TabShown) != 0, (tab->Flags & RynthServerHub.TabAvailable) != 0));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -481,20 +481,21 @@ public static unsafe class PluginExports
|
|||
}
|
||||
|
||||
// Manual HP override from the Damage panel (hp <= 0 clears it).
|
||||
private static IntPtr _awakenedTierJsonPtr = IntPtr.Zero;
|
||||
private static IntPtr _difficultyTierJsonPtr = IntPtr.Zero;
|
||||
|
||||
// Aelrynth difficulty tiers (2026-10-03): the Damage panel's tier label and picker.
|
||||
// {"show":false} off Aelrynth or until the server has sent a tier; else
|
||||
// {"show":true,"current":N,"view":M,"following":bool,"percent":5,"tiers":[0,...]}.
|
||||
// Difficulty tiers (2026-10-03; a server plugin's values since 2026-10-21, CreatureData/DifficultyTier.cs):
|
||||
// the Damage panel's tier label and picker. {"show":false} while no server plugin reports a tier; else
|
||||
// {"show":true,"current":N,"view":M,"following":bool,"percent":P,"tiers":[0,...]} (P: health % a tier).
|
||||
// The export keeps the name the engine binds ("...AwakenedTierJson", its first server's word).
|
||||
// An engine without the picker never calls this; the damage JSON then shows the current tier.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetAwakenedTierJson", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetAwakenedTierJson()
|
||||
public static IntPtr GetDifficultyTierJson()
|
||||
{
|
||||
try
|
||||
{
|
||||
string json = Runtime.Plugin?.BuildAwakenedTierJson() ?? "{\"show\":false}";
|
||||
string json = Runtime.Plugin?.BuildDifficultyTierJson() ?? "{\"show\":false}";
|
||||
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
|
||||
IntPtr oldPtr = Interlocked.Exchange(ref _awakenedTierJsonPtr, newPtr);
|
||||
IntPtr oldPtr = Interlocked.Exchange(ref _difficultyTierJsonPtr, newPtr);
|
||||
if (oldPtr != IntPtr.Zero)
|
||||
Marshal.FreeHGlobal(oldPtr);
|
||||
return newPtr;
|
||||
|
|
|
|||
|
|
@ -192,10 +192,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// Per-character learned combat damage (avg damage by wcid/element/tier +
|
||||
// learned HP-to-kill), used by CombatManager for kill-shot prediction.
|
||||
private CreatureData.MonsterDamageStore? _damageStore;
|
||||
// Aelrynth's difficulty tier where the player stands (and which server this is): keys the
|
||||
// tier-scaled learned numbers. Inert (tier 0) on every other server.
|
||||
private readonly CreatureData.AwakenedTier _tier = new();
|
||||
internal CreatureData.AwakenedTier AwakenedTier => _tier;
|
||||
// The difficulty tier where the player stands, as the active server's plugin reports it (and
|
||||
// which server this is): keys the tier-scaled learned numbers. Inert (tier 0) on every server
|
||||
// whose plugin reports none.
|
||||
private readonly CreatureData.DifficultyTier _tier = new();
|
||||
internal CreatureData.DifficultyTier DifficultyTier => _tier;
|
||||
// The tier the Damage panel shows: -1 = the current one (the default).
|
||||
private volatile int _damageViewTier = -1;
|
||||
// wcids appraised this session (AutoId of nearby mobs). Surfaced as bare rows in the
|
||||
|
|
@ -755,7 +756,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_combatManager.SetPlayerId(_playerId);
|
||||
_combatManager.SetDamageStores(_creatureStore, _damageStore);
|
||||
_combatManager.MobSeedLookup = LookupMobSeed;
|
||||
_combatManager.SetAwakenedTier(_tier);
|
||||
_combatManager.SetDifficultyTier(_tier);
|
||||
// The raycast init thread may already have finished (warm dats): hand it over now.
|
||||
WireRaycastIntoCombat();
|
||||
_navigationEngine?.SetCombatManager(_combatManager);
|
||||
|
|
@ -1534,7 +1535,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_objectCache?.Tick();
|
||||
if (diag) Host.Log("[RynthAi] OnTick: after cache tick");
|
||||
|
||||
if (_loginComplete) TickAwakenedTier();
|
||||
if (_loginComplete) TickDifficultyTier();
|
||||
|
||||
// A stop the action pacing held (nothing of ours moving, a server action unanswered)
|
||||
// goes out as soon as the server has answered: a stop is never dropped (2026-10-12).
|
||||
|
|
@ -2585,7 +2586,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
{
|
||||
var store = _damageStore;
|
||||
if (store == null) return "[]";
|
||||
// The Aelrynth difficulty tier shown (0 off Aelrynth): HP, kills, casts to kill, seconds
|
||||
// The difficulty tier shown (0 without a server plugin's tiers): HP, kills, casts to kill, seconds
|
||||
// per kill and hit rate are that tier's; damage per cast and every rule are shared.
|
||||
int vt = DamageViewDifficulty;
|
||||
_jsonViewTier = vt;
|
||||
|
|
@ -2961,17 +2962,18 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
{
|
||||
if (_damageStore == null) return;
|
||||
// The Damage panel shows (and so edits) the HP of the difficulty tier it shows; the
|
||||
// override is kept as the real-Dereth value, which every tier scales by 5% a tier.
|
||||
// Off Aelrynth the tier is 0 and this is the value as typed, as before.
|
||||
// override is kept as the real-Dereth value, which every tier scales by the server's
|
||||
// percent a tier. Without a server plugin's tiers the tier is 0 and this is the value as
|
||||
// typed, as before.
|
||||
int vt = DamageViewDifficulty;
|
||||
double value = hp > 0 && vt > 0 ? hp / CreatureData.AwakenedTier.HealthScale(vt) : hp;
|
||||
double value = hp > 0 && vt > 0 ? hp / _tier.HealthScale(vt) : hp;
|
||||
foreach (uint w in DamageGroupOf(wcid)) _damageStore.SetManualHp(w, value); // every kind of the row
|
||||
_damageStore.SaveIfDirty();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Aelrynth difficulty tier the Damage panel shows: the one picked there, else the one
|
||||
/// where the player stands. Always 0 off Aelrynth (or before the server has sent a tier).
|
||||
/// The difficulty tier the Damage panel shows: the one picked there, else the one where the
|
||||
/// player stands. Always 0 while no server plugin reports a tier.
|
||||
/// </summary>
|
||||
internal int DamageViewDifficulty
|
||||
{
|
||||
|
|
@ -2987,10 +2989,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
public void SetDamageViewTier(int tier) => _damageViewTier = tier < 0 ? -1 : tier;
|
||||
|
||||
/// <summary>
|
||||
/// The tier picker's state for the Damage panel: {"show":false} off Aelrynth or until the
|
||||
/// server has sent a tier this login - the panel then shows nothing of it.
|
||||
/// The tier picker's state for the Damage panel (RynthPluginGetAwakenedTierJson): {"show":false}
|
||||
/// while no server plugin reports a tier - the panel then shows nothing of it.
|
||||
/// </summary>
|
||||
public string BuildAwakenedTierJson()
|
||||
public string BuildDifficultyTierJson()
|
||||
{
|
||||
if (!_tier.Active) return "{\"show\":false}";
|
||||
var tiers = new SortedSet<int> { 0, _tier.Current };
|
||||
|
|
@ -3001,7 +3003,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
sb.Append("{\"show\":true,\"current\":").Append(_tier.Current)
|
||||
.Append(",\"view\":").Append(view)
|
||||
.Append(",\"following\":").Append(_damageViewTier < 0 ? "true" : "false")
|
||||
.Append(",\"percent\":").Append(JsonNum(CreatureData.AwakenedTier.PercentPerTier))
|
||||
.Append(",\"percent\":").Append(JsonNum(_tier.HealthPercentPerTier))
|
||||
.Append(",\"tiers\":[").Append(string.Join(",", tiers)).Append("]}");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
|
@ -3009,15 +3011,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
/// <summary>
|
||||
/// A monster's HP at a difficulty tier, for the Damage panel: the manual override (a
|
||||
/// real-Dereth value, scaled), else that tier's appraisal, else that tier's learned pool
|
||||
/// (<paramref name="learned"/>), else - above tier 0 only - tier 0's scaled by 5% a tier,
|
||||
/// (<paramref name="learned"/>), else - above tier 0 only - tier 0's scaled by the tier,
|
||||
/// flagged as an estimate. At tier 0 this is the panel's old order exactly.
|
||||
/// </summary>
|
||||
private (double Hp, bool Manual, bool Estimated, string Source) HpAt(uint wcid, int difficulty, bool learned = true)
|
||||
{
|
||||
var store = _damageStore;
|
||||
if (store == null || wcid == 0) return (0, false, false, "");
|
||||
double scale = CreatureData.AwakenedTier.HealthScale(difficulty);
|
||||
double pct = difficulty * CreatureData.AwakenedTier.PercentPerTier;
|
||||
double scale = _tier.HealthScale(difficulty);
|
||||
double pct = difficulty * _tier.HealthPercentPerTier;
|
||||
double manual = store.GetManualHp(wcid);
|
||||
if (manual > 0)
|
||||
return (manual * scale, true, false, difficulty > 0 ? $"set by you (real Dereth {manual:0}, +{pct:0}%)" : "set by you");
|
||||
|
|
@ -3251,18 +3253,18 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
private const uint PROP_FLOAT_RESIST_ELECTRIC = 70;
|
||||
|
||||
/// <summary>
|
||||
/// Once a second (AwakenedTier throttles): which server, and Aelrynth's tier where the player
|
||||
/// stands. The creature store follows the server; the damage store records under the tier.
|
||||
/// Off Aelrynth the tier stays 0, so nothing below changes there.
|
||||
/// Once a second (DifficultyTier throttles): which server, and the difficulty tier where the
|
||||
/// player stands as the server's plugin reports it. The creature store follows the server; the
|
||||
/// damage store records under the tier. Without a server plugin's tiers the tier stays 0, so
|
||||
/// nothing below changes there.
|
||||
/// </summary>
|
||||
private void TickAwakenedTier()
|
||||
private void TickDifficultyTier()
|
||||
{
|
||||
try
|
||||
{
|
||||
uint pid = _playerId != 0 ? _playerId : Host.GetPlayerId();
|
||||
bool wasActive = _tier.Active;
|
||||
int was = _tier.Current;
|
||||
_tier.Refresh(Host, pid);
|
||||
_tier.Refresh(Host);
|
||||
if (_damageStore != null) _damageStore.Difficulty = _tier.Current;
|
||||
|
||||
if (_creatureStore != null && _tier.ServerKey.Length > 0
|
||||
|
|
@ -3273,11 +3275,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
}
|
||||
|
||||
if (_tier.Active && (!wasActive || was != _tier.Current))
|
||||
Log($"RynthAi: Aelrynth difficulty tier {_tier.Current} - learned HP, casts to kill, accuracy and fight times are kept for this tier.");
|
||||
Log($"RynthAi: difficulty tier {_tier.Current} (+{_tier.HealthPercentPerTier:0.##}% monster health a tier, from {_tier.Source})"
|
||||
+ " - learned HP, casts to kill, accuracy and fight times are kept for this tier.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Host.Log($"[RynthAi] TickAwakenedTier: {ex.Message}");
|
||||
Host.Log($"[RynthAi] TickDifficultyTier: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -3332,7 +3335,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
}
|
||||
}
|
||||
|
||||
TickAwakenedTier(); // the right server's file and tier before the first write (throttled)
|
||||
TickDifficultyTier(); // the right server's file and tier before the first write (throttled)
|
||||
_creatureStore.Upsert(sample, _tier.Current);
|
||||
|
||||
// Remember this monster type so the Damage table shows it (as a bare row with
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] Mini Remote server tabs: no server plugin hub connected (none loaded for this world).");
|
||||
else
|
||||
{
|
||||
string id = hub.Text(RynthIltHub.TextServerId);
|
||||
string id = hub.Text(RynthServerHub.TextServerId);
|
||||
ChatLine($"[RynthAi] Mini Remote server tabs: connected{(id.Length > 0 ? " (server '" + id + "')" : string.Empty)}, "
|
||||
+ (hub.ServerActive ? "its server is this world." : "its server is not this world (nothing shown)."));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -67,8 +67,8 @@
|
|||
<Compile Include="..\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
|
||||
<!-- ImGui text calls for non-literal text ('%' escaped; RynthILT links the same file). -->
|
||||
<Compile Include="..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
|
||||
<!-- Infinite Leaftide: RynthILT.Hub (its tabs in the Mini Remote) and RynthAi.Hub (what RynthILT borrows). -->
|
||||
<Compile Include="..\Shared\RynthIltHubApi.cs" Link="Shared\RynthIltHubApi.cs" />
|
||||
<!-- A server plugin's part of the Mini Remote (RynthServer.Hub) and RynthAi.Hub (what server plugins borrow). -->
|
||||
<Compile Include="..\Shared\RynthServerHubApi.cs" Link="Shared\RynthServerHubApi.cs" />
|
||||
<Compile Include="..\Shared\RynthAiHubApi.cs" Link="Shared\RynthAiHubApi.cs" />
|
||||
<!-- Save failures said in chat with the reason and the fix (2026-10-13; RynthILT links it too). -->
|
||||
<Compile Include="..\Shared\DataWriteGuard.cs" Link="Shared\DataWriteGuard.cs" />
|
||||
|
|
|
|||
|
|
@ -140,11 +140,11 @@ public sealed partial class RynthAiPlugin
|
|||
UbNoEquivalent(cmd, "RynthSort reads its rules itself");
|
||||
return true;
|
||||
|
||||
// ── A server's own commands (ub-IT's ACECustom verbs): the server plugin's (RynthILT) ──
|
||||
// ── A server's own commands (ub-IT's server verbs): the active server plugin's, if it takes them ──
|
||||
case "qblist":
|
||||
case "augs":
|
||||
if (!TryForwardToServerPlugin(new[] { "/ra", "ub", cmd }))
|
||||
UbNoEquivalent(cmd, "it is a server plugin's command (Infinite Leaftide: RynthILT), and none is loaded");
|
||||
UbNoEquivalent(cmd, "it is a server plugin's command, and no loaded server plugin takes it");
|
||||
return true;
|
||||
|
||||
// ── RynthCore's window placement ────────────────────────────────────
|
||||
|
|
|
|||
|
|
@ -1,17 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- RynthColdeve: the Coldeve server plugin. The build is shared (..\Shared\ServerPack\ServerPlugin.props);
|
||||
ServerData.cs holds what is known about the server. -->
|
||||
<PropertyGroup>
|
||||
<AssemblyName>RynthCore.Plugin.RynthColdeve</AssemblyName>
|
||||
<Version>0.1.0</Version>
|
||||
<RynthPluginServerId>coldeve</RynthPluginServerId>
|
||||
<RynthPluginServerName>Coldeve</RynthPluginServerName>
|
||||
<RynthPluginServerHosts>play.coldeve.ac</RynthPluginServerHosts>
|
||||
<RynthPluginServerWorldNames>Coldeve</RynthPluginServerWorldNames>
|
||||
<RynthPluginDescription>Coldeve only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="..\Shared\ServerPack\ServerPlugin.props" />
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
// 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",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,428 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>A labelled value from a server reply ("Pyreals" = "1,039,678,533 (4,158 MMDs)").</summary>
|
||||
internal sealed class NamedValue
|
||||
{
|
||||
public string Name = "";
|
||||
public string Value = "";
|
||||
}
|
||||
|
||||
/// <summary>One of ConquestAC's advanced augmentations (counts from "/augs").</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The next purchase's luminance (Conquest-ACE's tiered cost, as upstream mirrors it).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The effect at the current count (upstream's reading of the Conquest-ACE source).</summary>
|
||||
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})",
|
||||
_ => "",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A fellowship from "/fship list".</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A row of a leaderboard.</summary>
|
||||
internal sealed class BoardRow
|
||||
{
|
||||
public int Rank;
|
||||
public string Name = "";
|
||||
public string Value = "";
|
||||
public string Extra = "";
|
||||
public bool IsYou;
|
||||
}
|
||||
|
||||
/// <summary>One of ConquestAC's /top boards.</summary>
|
||||
internal sealed class ConquestBoard
|
||||
{
|
||||
public readonly string Key, Label, Header;
|
||||
public readonly List<BoardRow> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<string, string> 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<NamedValue> Bank = new();
|
||||
public readonly List<ConquestAug> 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<NamedValue> EnlAugs { get; private set; } = new();
|
||||
public readonly List<NamedValue> 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<ConquestFellowship> Fellowships = new();
|
||||
public readonly List<ConquestBoard> 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<NamedValue>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>An automatic deposit: its reply is ours to hide.</summary>
|
||||
public string AutoDeposit(long now) { _depositReq.Sent(now); return "/bank deposit"; }
|
||||
|
||||
/// <summary>
|
||||
/// A chat line: true when it was a reply this module reads; <paramref name="ours"/> = it
|
||||
/// answers a request RynthConquest sent (eligible to be hidden).
|
||||
/// </summary>
|
||||
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<NamedValue>();
|
||||
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<NamedValue>(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
|
||||
|
||||
/// <summary>"/bank withdraw <token> <n>", or null when the amount isn't a whole number above 0.</summary>
|
||||
public static string? WithdrawCommand(Currency c, string amount) =>
|
||||
long.TryParse((amount ?? "").Replace(",", "").Trim(), out long n) && n > 0 ? $"/bank withdraw {c.Token} {n}" : null;
|
||||
|
||||
/// <summary>"/bank transfer <token> <n> "name"", or null when the amount or name isn't usable.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Total XP to reach a level 276-300 (0 otherwise).</summary>
|
||||
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));
|
||||
|
||||
/// <summary>Void DoT duration on ConquestAC: × (1 + Archmage's Endurance × 0.2 + Duration augs × 0.05).</summary>
|
||||
public double VoidDurationMultiplier(int archmagesEndurance) => 1.0 + archmagesEndurance * 0.2 + DurationAugs * 0.05;
|
||||
}
|
||||
|
|
@ -1,143 +0,0 @@
|
|||
// 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";
|
||||
/// <summary>Set once rynthoracle.json's Conquest settings were taken over (they're never read again).</summary>
|
||||
public const string MigrationMarker = "migratedFromRynthOracle";
|
||||
/// <summary>The profile value RynthOracle's Void timers apply ("RynthServer.Profile" values).</summary>
|
||||
public const string VoidScaleKey = "voidDotDurationScale";
|
||||
/// <summary>After login, before the hidden /augs (RynthOracle's old timing: its quest read plus 4 s).</summary>
|
||||
public const long AugsReadDelayMs = 10_000;
|
||||
/// <summary>The character's level, XP and augmentation are read this often.</summary>
|
||||
public const long CharacterReadMs = 1000;
|
||||
|
||||
/// <summary>RynthConquest's pages (ConquestPages draws them): id, label, tooltip.</summary>
|
||||
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)."),
|
||||
};
|
||||
|
||||
/// <summary>Held for everything below (pump and render thread).</summary>
|
||||
public readonly object Gate = new();
|
||||
public readonly ConquestData Data = new();
|
||||
public readonly QuestFlagStore Flags = new();
|
||||
|
||||
/// <summary>"/bank deposit" at every ten-minute mark (upstream's auto-deposit). Off by default.</summary>
|
||||
public bool AutoDeposit;
|
||||
/// <summary>Hide the replies to RynthConquest's own requests (a command typed by hand always shows).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Takes over the settings RynthOracle had for Conquest (rynthoracle.json at <paramref name="oraclePath"/>),
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>A character logged in (or the plugin loaded in game): everything is read fresh.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An incoming chat line on Conquest. True when it should be hidden: a reply to one of
|
||||
/// RynthConquest's own requests, with HideOwnReplies on.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The once-after-login /augs: the command to send now, or null.</summary>
|
||||
public string? LoginAugsDue(long nowMs)
|
||||
{
|
||||
if (_augsAsked || nowMs - _loginMs <= AugsReadDelayMs) return null;
|
||||
_augsAsked = true;
|
||||
return Data.RequestAugs(nowMs);
|
||||
}
|
||||
|
||||
/// <summary>The automatic deposit: "/bank deposit" when one is due now, else null.</summary>
|
||||
public string? AutoDepositDue(DateTime local, long nowMs)
|
||||
=> AutoDeposit && DepositDue(local, ref _lastDepositBlock) ? Data.AutoDeposit(nowMs) : null;
|
||||
|
||||
/// <summary>
|
||||
/// True once in each ten-minute block, at its first minute (:00, :10, :20 ... local time), as
|
||||
/// upstream does; <paramref name="lastBlock"/> remembers the block already done.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>This character's Void DoT duration multiplier on Conquest (Archmage's Endurance and the Duration augs).</summary>
|
||||
public double VoidScale => Data.VoidDurationMultiplier(ArchmagesEndurance);
|
||||
}
|
||||
|
|
@ -1,417 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<bool> _active;
|
||||
private readonly Action<Action> _runOnTick;
|
||||
private readonly Func<string, bool> _send;
|
||||
private readonly Action<string> _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;
|
||||
|
||||
/// <param name="active">RynthConquest's server is this world.</param>
|
||||
/// <param name="runOnTick">Queues work for the plugin tick (ServerPackPlugin.RunOnTick).</param>
|
||||
/// <param name="send">Sends a chat command as if typed (pump thread).</param>
|
||||
/// <param name="print">A line in the chat window (pump thread).</param>
|
||||
/// <param name="saveSettings">Writes the feature's settings (pump thread).</param>
|
||||
public ConquestPages(ConquestFeature feature, Func<bool> active, Action<Action> runOnTick, Func<string, bool> send,
|
||||
Action<string> 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),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Logout: the next character's status lines start empty.</summary>
|
||||
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.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when the page has something to show; otherwise says why.</summary>
|
||||
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<ConquestFellowship> 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.");
|
||||
}
|
||||
|
||||
/// <summary>An entry's name, status, hint and link in chat (upstream "thinks" them).</summary>
|
||||
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.",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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 <paramref name="state"/> to change.
|
||||
/// </summary>
|
||||
private ServerRefreshResult Ask(string key, Func<long> state, string command, Action<long> 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 ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A command from a button, sent on the next tick.</summary>
|
||||
private void Queue(string command) => _runOnTick(() => _send(command));
|
||||
|
||||
/// <summary>A line in chat, written on the next tick.</summary>
|
||||
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);
|
||||
}
|
||||
|
|
@ -1,63 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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
|
||||
{
|
||||
/// <summary>The embedded list's logical name (RynthCore.Plugin.RynthConquest.csproj).</summary>
|
||||
public const string ResourceName = "RynthConquest.customquests.csv";
|
||||
|
||||
public static List<CustomQuest> All { get; } = Load();
|
||||
|
||||
private static List<CustomQuest> Load()
|
||||
{
|
||||
var list = new List<CustomQuest>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,118 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>Where RynthOracle kept the Conquest settings before they moved here (read once).</summary>
|
||||
internal static string OracleSettingsPath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json");
|
||||
|
||||
partial void ServerPages(System.Collections.Generic.List<ServerPage> 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();
|
||||
}
|
||||
|
||||
/// <summary>Level, XP, enlightenment and Archmage's Endurance (the Void DoT rule), then the rule for RynthOracle.</summary>
|
||||
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<string> 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).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
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
|
||||
|
|
|
@ -1,37 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- RynthConquest: the Conquest (ConquestAC) server plugin. The build is shared
|
||||
(..\Shared\ServerPack\ServerPlugin.props); ServerData.cs holds what is known about the server.
|
||||
Conquest's own features (ConquestPlugin.cs, Conquest\) came from RynthOracle on 2026-10-20: the
|
||||
bank and its auto-deposit, augmentations, levels past 275, fellowships, custom quests and the
|
||||
/top boards, as pages of the Mini Remote's Server section. -->
|
||||
<PropertyGroup>
|
||||
<AssemblyName>RynthCore.Plugin.RynthConquest</AssemblyName>
|
||||
<Version>0.2.0</Version>
|
||||
<RynthPluginServerId>conquest</RynthPluginServerId>
|
||||
<RynthPluginServerName>Conquest</RynthPluginServerName>
|
||||
<RynthPluginServerHosts>acconquest.ddns.net</RynthPluginServerHosts>
|
||||
<RynthPluginServerWorldNames>Conquest|ConquestAC</RynthPluginServerWorldNames>
|
||||
<RynthPluginDescription>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.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="..\Shared\ServerPack\ServerPlugin.props" />
|
||||
|
||||
<ItemGroup>
|
||||
<!-- RynthOracle's /myquests parser and its helpers (linked source, so both read the flags alike):
|
||||
the custom quest worklist's status. -->
|
||||
<Compile Include="..\RynthCore.Plugin.RynthOracle\Data\QuestFlags.cs" Link="Shared\QuestFlags.cs" />
|
||||
<Compile Include="..\RynthCore.Plugin.RynthOracle\Data\TimeText.cs" Link="Shared\TimeText.cs" />
|
||||
<Compile Include="..\RynthCore.Plugin.RynthOracle\Data\Csv.cs" Link="Shared\Csv.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Oracle of Dereth's Conquest custom quest list (MIT, by Advis Eveldan / advis61). -->
|
||||
<EmbeddedResource Include="Resources\customquests.csv" LogicalName="RynthConquest.customquests.csv" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="THIRD_PARTY_NOTICES.md" CopyToPublishDirectory="PreserveNewest" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
// 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.",
|
||||
"RynthOracle has a Conquest quest pack (quests.conquest.csv).",
|
||||
"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",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
# 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), 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.
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- RynthDerptide: the Derptide server plugin. The build is shared (..\Shared\ServerPack\ServerPlugin.props);
|
||||
ServerData.cs holds what is known about the server. -->
|
||||
<PropertyGroup>
|
||||
<AssemblyName>RynthCore.Plugin.RynthDerptide</AssemblyName>
|
||||
<Version>0.1.0</Version>
|
||||
<RynthPluginServerId>derptide</RynthPluginServerId>
|
||||
<RynthPluginServerName>Derptide</RynthPluginServerName>
|
||||
<RynthPluginServerHosts>ac.derptide.net</RynthPluginServerHosts>
|
||||
<RynthPluginServerWorldNames>Derptide</RynthPluginServerWorldNames>
|
||||
<RynthPluginDescription>Derptide only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="..\Shared\ServerPack\ServerPlugin.props" />
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
// 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",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- RynthDreamWeave: the DreamWeave server plugin. The build is shared (..\Shared\ServerPack\ServerPlugin.props);
|
||||
ServerData.cs holds what is known about the server. -->
|
||||
<PropertyGroup>
|
||||
<AssemblyName>RynthCore.Plugin.RynthDreamWeave</AssemblyName>
|
||||
<Version>0.1.0</Version>
|
||||
<RynthPluginServerId>dreamweave</RynthPluginServerId>
|
||||
<RynthPluginServerName>DreamWeave</RynthPluginServerName>
|
||||
<RynthPluginServerHosts>play.acdreamweave.com</RynthPluginServerHosts>
|
||||
<RynthPluginServerWorldNames>DreamWeave|Dream Weave</RynthPluginServerWorldNames>
|
||||
<RynthPluginDescription>DreamWeave only: the server card (rules, server features, player commands, links, account setup) in the Mini Remote.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="..\Shared\ServerPack\ServerPlugin.props" />
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
// 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 <N> 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",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- RynthEversong: the Eversong server plugin. The build is shared (..\Shared\ServerPack\ServerPlugin.props);
|
||||
ServerData.cs holds what is known about the server. -->
|
||||
<PropertyGroup>
|
||||
<AssemblyName>RynthCore.Plugin.RynthEversong</AssemblyName>
|
||||
<Version>0.1.0</Version>
|
||||
<RynthPluginServerId>eversong</RynthPluginServerId>
|
||||
<RynthPluginServerName>Eversong</RynthPluginServerName>
|
||||
<RynthPluginServerHosts>eversong.abrdns.com</RynthPluginServerHosts>
|
||||
<RynthPluginServerWorldNames>Eversong</RynthPluginServerWorldNames>
|
||||
<RynthPluginDescription>Eversong only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="..\Shared\ServerPack\ServerPlugin.props" />
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
// 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",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- RynthFrostACE: the FrostACE server plugin (listed as "FrostfACE" in the public server list). The build
|
||||
is shared (..\Shared\ServerPack\ServerPlugin.props); ServerData.cs holds what is known about the server. -->
|
||||
<PropertyGroup>
|
||||
<AssemblyName>RynthCore.Plugin.RynthFrostACE</AssemblyName>
|
||||
<Version>0.1.0</Version>
|
||||
<RynthPluginServerId>frostace</RynthPluginServerId>
|
||||
<RynthPluginServerName>FrostACE</RynthPluginServerName>
|
||||
<RynthPluginServerHosts>172.111.230.127</RynthPluginServerHosts>
|
||||
<RynthPluginServerWorldNames>FrostACE|FrostfACE</RynthPluginServerWorldNames>
|
||||
<RynthPluginDescription>FrostACE only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="..\Shared\ServerPack\ServerPlugin.props" />
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
// 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",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- RynthFrostcull: the Frostcull server plugin. The build is shared (..\Shared\ServerPack\ServerPlugin.props);
|
||||
ServerData.cs holds what is known about the server. -->
|
||||
<PropertyGroup>
|
||||
<AssemblyName>RynthCore.Plugin.RynthFrostcull</AssemblyName>
|
||||
<Version>0.1.0</Version>
|
||||
<RynthPluginServerId>frostcull</RynthPluginServerId>
|
||||
<RynthPluginServerName>Frostcull</RynthPluginServerName>
|
||||
<RynthPluginServerHosts>frostcull.ddns.net</RynthPluginServerHosts>
|
||||
<RynthPluginServerWorldNames>Frostcull</RynthPluginServerWorldNames>
|
||||
<RynthPluginDescription>Frostcull only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import Project="..\Shared\ServerPack\ServerPlugin.props" />
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
// 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",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,229 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>Where the player stands on one bounty reward.</summary>
|
||||
internal enum BountyStatus
|
||||
{
|
||||
/// <summary>Kills are counting: Kills of KillsRequired.</summary>
|
||||
Counting = 0,
|
||||
/// <summary>The cooldown after the last award runs; kills do not count until UnlockAtUtc.</summary>
|
||||
Cooldown = 1,
|
||||
/// <summary>The player's QB is below the reward's minimum; kills do not count.</summary>
|
||||
NeedsQb = 2,
|
||||
}
|
||||
|
||||
/// <summary>One parsed status phrase.</summary>
|
||||
internal readonly record struct BountyStatusInfo(BountyStatus Status, int Kills, int KillsRequired,
|
||||
int WaitSeconds, long QbRequired, long QbHave);
|
||||
|
||||
/// <summary>One "/bounty list" line.</summary>
|
||||
internal readonly record struct BountyListLine(string Where, long Amount, string Item, int KillsRequired,
|
||||
int CooldownSeconds, BountyStatusInfo Status);
|
||||
|
||||
/// <summary>One "/bounty" (where you stand) line. Scope is "" (this dungeon/zone), "all zones" or a region name.</summary>
|
||||
internal readonly record struct BountyHereLine(string Scope, long Amount, string Item, BountyStatusInfo Status);
|
||||
|
||||
/// <summary>Kind of a bounty chat event.</summary>
|
||||
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 =
|
||||
@"(?<status>" + Num + @" of " + Num + @" kills?|unlocks in .+?, then " + Num + @" kills? required|needs "
|
||||
+ Num + @" QB \(you have " + Num + @"\))";
|
||||
|
||||
/// <summary>"/bounty list" reward line (leading indentation already trimmed).</summary>
|
||||
private static readonly Regex ListLine = new(
|
||||
@"^(?<where>.+?): (?<amount>" + Num + @") (?<item>.+?) every (?<kills>" + Num + @") kills?"
|
||||
+ @"(?: \(at most every (?<cd>[^)]+)\))? - you: " + StatusPattern + @"\.$", Opt);
|
||||
|
||||
/// <summary>"/bounty" reward line.</summary>
|
||||
private static readonly Regex HereLine = new(
|
||||
@"^Bounty(?: \((?<scope>[^)]+)\))?: (?<amount>" + Num + @") (?<item>.+?) - " + StatusPattern + @"\.$", Opt);
|
||||
|
||||
private static readonly Regex Counting = new(@"^(?<k>" + Num + @") of (?<n>" + Num + @") kills?$", Opt);
|
||||
private static readonly Regex Cooldown = new(@"^unlocks in (?<wait>.+?), then (?<n>" + Num + @") kills? required$", Opt);
|
||||
private static readonly Regex Qb = new(@"^needs (?<qb>" + Num + @") QB \(you have (?<have>" + Num + @")\)$", Opt);
|
||||
private static readonly Regex WaitPart = new(@"(?<v>\d+)\s*(?<u>hr|min|sec)\b", Opt);
|
||||
|
||||
private static readonly Regex EvUnlocked = new(@"^Bounty unlocked: (?<item>.+) - (?<n>" + Num + @") kills? required\.$", Opt);
|
||||
private static readonly Regex EvComplete = new(@"^Bounty complete! \+(?<n>" + Num + @") (?<item>.+) gained\.$", Opt);
|
||||
private static readonly Regex EvNextWait = new(@"^Next bounty unlocks in (?<wait>.+?) - (?<n>" + Num + @") kills? required\.$", Opt);
|
||||
private static readonly Regex EvNextReady = new(@"^Next bounty requires (?<n>" + Num + @") kills?\.$", Opt);
|
||||
|
||||
/// <summary>"/bounty list" header line.</summary>
|
||||
public const string ListHeader = "Bounties:";
|
||||
|
||||
/// <summary>True for the line that ends a "/bounty list" reply (footer or "no bounties anywhere").</summary>
|
||||
public static bool IsListTerminator(string text)
|
||||
=> text.StartsWith("Bounty: type /bounty", StringComparison.OrdinalIgnoreCase)
|
||||
|| text.StartsWith("Bounty: there are no bounties anywhere", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>True when the terminator says no bounty is active anywhere.</summary>
|
||||
public static bool IsNoBountiesAnywhere(string text)
|
||||
=> text.StartsWith("Bounty: there are no bounties anywhere", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>ACE's reply to a command the server doesn't register.</summary>
|
||||
public static bool IsUnknownCommand(string text)
|
||||
=> text.StartsWith("Unknown command: bounty", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Parses a "/bounty list" reward line.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Parses a "/bounty" (where you stand) reward line.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Parses one status phrase (without the trailing period).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>"2 min 30 sec" → 150, "1 hr 15 sec" → 3615. 0 when nothing parses.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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".
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Key that identifies one reward of one area across refreshes.</summary>
|
||||
public static string Key(string where, long amount, string item, int killsRequired)
|
||||
=> $"{where}|{amount}|{item}|{killsRequired}".ToLowerInvariant();
|
||||
|
||||
/// <summary>"1 hr 5 min", "45 sec", "2 days 3 hr". Negative spans read as 0 sec.</summary>
|
||||
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";
|
||||
}
|
||||
|
||||
/// <summary>Digits with "," grouping removed; 0 when nothing parses.</summary>
|
||||
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);
|
||||
}
|
||||
|
|
@ -1,714 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>Persisted per character (bounties.json): the window's options and the last list read.</summary>
|
||||
internal sealed class BountyState
|
||||
{
|
||||
public bool RefreshOnKills = true;
|
||||
public int MinRefreshSeconds = 10;
|
||||
public int PeriodicRefreshMinutes = 5;
|
||||
public bool HideQbLocked;
|
||||
public bool SortByProgress;
|
||||
public List<BountyEntry> Entries = new();
|
||||
public DateTime ListedUtc;
|
||||
public bool NoneAnywhere;
|
||||
public string LastEvent = string.Empty;
|
||||
public DateTime LastEventUtc;
|
||||
}
|
||||
|
||||
/// <summary>One reward of one bounty area and where this character stands on it.</summary>
|
||||
internal sealed class BountyEntry
|
||||
{
|
||||
public string Where = string.Empty;
|
||||
public long Amount;
|
||||
public string Item = string.Empty;
|
||||
public int KillsRequired;
|
||||
public int CooldownSeconds;
|
||||
/// <summary>A <see cref="BountyStatus"/> value.</summary>
|
||||
public int Status;
|
||||
public int Kills;
|
||||
public DateTime UnlockAtUtc;
|
||||
public long QbRequired;
|
||||
public long QbHave;
|
||||
/// <summary>Last time the kills went up or an award reset them (row highlight).</summary>
|
||||
public DateTime ChangedUtc;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// RynthPluginGetBountiesJson payload. Mirrored by RynthCore.Engine UI/Data/BountiesSnapshotJson.cs;
|
||||
/// either side may add fields (unknown ones are skipped, missing ones keep their defaults).
|
||||
/// </summary>
|
||||
internal sealed class BountyBridgePayload
|
||||
{
|
||||
[JsonPropertyName("unsupported")] public bool Unsupported;
|
||||
[JsonPropertyName("reading")] public bool Reading;
|
||||
[JsonPropertyName("status")] public string Status = string.Empty;
|
||||
/// <summary>Seconds since the last list read; -1 = never.</summary>
|
||||
[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;
|
||||
/// <summary>Rows not shown because of HideQbLocked.</summary>
|
||||
[JsonPropertyName("hiddenCount")] public int HiddenCount;
|
||||
[JsonPropertyName("rows")] public List<BountyRow> Rows = new();
|
||||
}
|
||||
|
||||
/// <summary>One row of <see cref="BountyBridgePayload"/>, with the status as of the poll.</summary>
|
||||
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;
|
||||
/// <summary>A <see cref="BountyStatus"/> value; an ended cooldown is already Counting.</summary>
|
||||
[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;
|
||||
/// <summary>Kills went up (or an award reset them) in the last 15 seconds.</summary>
|
||||
[JsonPropertyName("changed")] public bool Changed;
|
||||
}
|
||||
|
||||
internal sealed class BountyTracker
|
||||
{
|
||||
/// <summary>The capture command; "/bounty all" is the same list.</summary>
|
||||
public const string ListCommand = "/bounty list";
|
||||
/// <summary>Lowest allowed MinRefreshSeconds (the server is asked at most this often after kills).</summary>
|
||||
public const int MinRefreshFloorSeconds = 5;
|
||||
public const int MinRefreshCeilingSeconds = 300;
|
||||
public const int PeriodicCeilingMinutes = 60;
|
||||
public const string FileName = "bounties.json";
|
||||
|
||||
/// <summary>Wait after a kill so a burst of kills (and the server's own award lines) lands in one read.</summary>
|
||||
private const long KillDebounceMs = 2000;
|
||||
/// <summary>Wait after a bounty chat event before re-reading.</summary>
|
||||
private const long EventDebounceMs = 1500;
|
||||
/// <summary>The window counts as open while the engine polled the export this recently (it polls every second).</summary>
|
||||
private const long WindowPollWindowMs = 3000;
|
||||
/// <summary>A capture with no reply line by then is abandoned.</summary>
|
||||
private const long FirstLineTimeoutMs = 10000;
|
||||
/// <summary>A capture whose footer never came ends this long after its last line.</summary>
|
||||
private const long IdleEndMs = 1500;
|
||||
/// <summary>The engine may pass our own /bounty list back through the chat bar hook this soon after sending it.</summary>
|
||||
private const long OwnEchoMs = 2000;
|
||||
/// <summary>Longer chat lines are never parsed (no bounty line is near this; bounds the regex work).</summary>
|
||||
private const int MaxLineLength = 512;
|
||||
private const long SaveDebounceMs = 5000;
|
||||
/// <summary>A list older than this is re-read when the window opens.</summary>
|
||||
private static readonly TimeSpan OpenRefreshAge = TimeSpan.FromSeconds(30);
|
||||
/// <summary>How long a row stays highlighted after its kills went up.</summary>
|
||||
private static readonly TimeSpan ChangedHighlight = TimeSpan.FromSeconds(15);
|
||||
|
||||
private readonly Action<string> _send;
|
||||
private readonly Action<string> _chat;
|
||||
private readonly Action<string> _log;
|
||||
private readonly string _filePath;
|
||||
private readonly Func<long> _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<BountyListLine> _capLines = new();
|
||||
|
||||
private bool _unsupported;
|
||||
private string _status = string.Empty;
|
||||
private bool _dirty;
|
||||
private long _lastSaveMs;
|
||||
|
||||
/// <param name="send">Sends a chat command to the server (Host.InvokeChatParser).</param>
|
||||
/// <param name="chat">Prints a line to the player's chat window.</param>
|
||||
/// <param name="log">Writes to the RynthCore log.</param>
|
||||
/// <param name="filePath">bounties.json in the character folder; empty = not persisted.</param>
|
||||
/// <param name="clock">Milliseconds clock; Environment.TickCount64 unless a test supplies one.</param>
|
||||
public BountyTracker(Action<string> send, Action<string> chat, Action<string> log, string filePath, Func<long>? clock = null)
|
||||
{
|
||||
_send = send;
|
||||
_chat = chat;
|
||||
_log = log;
|
||||
_filePath = filePath ?? string.Empty;
|
||||
_clock = clock ?? (() => Environment.TickCount64);
|
||||
_s = Load();
|
||||
}
|
||||
|
||||
private long NowMs => _clock();
|
||||
|
||||
/// <summary>The persisted state (host tests).</summary>
|
||||
internal BountyState State => _s;
|
||||
|
||||
/// <summary>True once the server answered "Unknown command: bounty" (no bounty system on this server).</summary>
|
||||
public bool Unsupported => _unsupported;
|
||||
|
||||
/// <summary>True while a "/bounty list" reply is being captured.</summary>
|
||||
public bool Reading => _capActive;
|
||||
|
||||
/// <summary>True while the engine's Bounties window is polling the export.</summary>
|
||||
public bool WindowOpen => _lastPollMs != 0 && NowMs - _lastPollMs < WindowPollWindowMs;
|
||||
|
||||
// ── Scheduling ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Schedules a "/bounty list" read; the earliest pending request wins. Every read waits for
|
||||
/// MinRefreshSeconds since the last one; <paramref name="respectMinInterval"/> false (a manual
|
||||
/// refresh) waits only for the MinRefreshFloorSeconds floor.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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...";
|
||||
}
|
||||
|
||||
/// <summary>One of this character's kills (RynthILTPlugin.OnKillNotification).</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>"/bounty list" or "/bounty all" (or with ACE's '@' command prefix).</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>True for a chat-bar line that is a /bounty command (what the plugin passes to NoteTypedCommand).</summary>
|
||||
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 ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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) ────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal void ApplyList(IReadOnlyList<BountyListLine> lines, bool complete, bool noneAnywhere, DateTime nowUtc)
|
||||
{
|
||||
var old = new Dictionary<string, BountyEntry>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var e in _s.Entries)
|
||||
old[BountyParse.Key(e.Where, e.Amount, e.Item, e.KillsRequired)] = e;
|
||||
|
||||
var fresh = new List<BountyEntry>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Copies a parsed status onto <paramref name="e"/> and stamps ChangedUtc when kills went up or an award reset them.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The status to show now: a cooldown that has ended is "0 of N kills".</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>"Closest first" order: counting by fraction left, then cooldowns by time left, then QB-locked.</summary>
|
||||
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 ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>RynthPluginGetBountiesJson. Each call also marks the window open for the read schedule.</summary>
|
||||
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<BountyEntry> 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);
|
||||
|
||||
/// <summary>
|
||||
/// RynthPluginBountyCommand: "refresh", or "set {option} {value}" with option one of
|
||||
/// refreshonkills, minrefreshseconds, periodicminutes, hideqblocked, sortbyprogress.
|
||||
/// </summary>
|
||||
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 ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>"/ilt bounty [refresh|list]".</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One-line chat text for an entry.</summary>
|
||||
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}",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>"/ilt bounty list": the tracked bounties in chat.</summary>
|
||||
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<BountyEntry>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Writes bounties.json when something changed (also called at logout).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,172 +0,0 @@
|
|||
// 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's Quests tab).
|
||||
//
|
||||
// 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
|
||||
{
|
||||
/// <summary>Longest bank / breeding verb line taken (a transfer with a long character name fits easily).</summary>
|
||||
private const int MaxVerbBytes = 256;
|
||||
|
||||
private static RynthIltDataApiV1* _table;
|
||||
private static volatile bool _released;
|
||||
|
||||
/// <summary>The table for (<paramref name="iface"/>, <paramref name="version"/>), or 0 when it isn't ours.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Plugin shutdown: readers see Version 0 and re-query; every function answers 0.</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>A reader's verb line, or null when it is empty, too long or not plain ASCII (no control characters reach a chat command).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,638 +0,0 @@
|
|||
// 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 <abbr> <n>" → "[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 <abbr> 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 <abbr> 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
|
||||
{
|
||||
/// <summary>Raise modes (IltCharacterState.AttrRaiseMode).</summary>
|
||||
public enum Mode { Priority = 0, RoundRobin = 1, Cheapest = 2 }
|
||||
|
||||
/// <summary>/attr abbreviation, display name, vital?</summary>
|
||||
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),
|
||||
};
|
||||
|
||||
/// <summary>UB's default priority (Coordination, Quickness, Strength, Endurance, Focus, Self, vitals).</summary>
|
||||
public static readonly string[] DefaultOrder = { "coo", "qui", "str", "end", "foc", "sel", "hea", "sta", "man" };
|
||||
|
||||
public const int MaxRaisesPerRun = 200;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
/// <summary>A run with no reply/step for this long is ended (a lost callback must not wedge it).</summary>
|
||||
private const long StallMs = 45_000;
|
||||
|
||||
/// <summary>"Your base Strength is now 250!" / "Your base Maximum Health is now 900!" (older servers / UB wording).</summary>
|
||||
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<string, long> _cost = new(StringComparer.OrdinalIgnoreCase);
|
||||
private Dictionary<string, long> _runCosts = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, int> _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<string, int> _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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public Func<bool>? 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;
|
||||
}
|
||||
|
||||
/// <summary>All nine abbreviations exactly once: saved order first, missing ones appended, junk dropped.</summary>
|
||||
public static List<string> RepairOrder(List<string>? order)
|
||||
{
|
||||
var result = new List<string>();
|
||||
foreach (string k in order ?? new List<string>())
|
||||
{
|
||||
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<string> RepairSelection(List<string>? selection)
|
||||
{
|
||||
var result = new List<string>();
|
||||
foreach (string k in selection ?? new List<string>())
|
||||
{
|
||||
Stat? s = Find(k);
|
||||
if (s != null && !result.Contains(s.Abbr)) result.Add(s.Abbr);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Picks the next stat to raise. Pure (unit-testable): <paramref name="order"/> is the
|
||||
/// priority order, <paramref name="ticked"/> the stats allowed, <paramref name="cost"/> the
|
||||
/// known next-level costs, <paramref name="budget"/> what may be spent. Round robin starts at
|
||||
/// <paramref name="rrNext"/> and returns the index after the pick there.
|
||||
/// </summary>
|
||||
public static string? Pick(Mode mode, IReadOnlyList<string> order, ICollection<string> ticked,
|
||||
IReadOnlyDictionary<string, long> 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 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Why the raiser can't run here, or null when it can.</summary>
|
||||
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 ─────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Tick. <paramref name="holdOff"/>: another XP spender (auto-enlighten's loop) is running.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Passive: keeps costs / base values current when the player runs the commands by hand.</summary>
|
||||
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 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Starts a spend run (manual "Raise now" or the auto timer).</summary>
|
||||
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<string, long>(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);
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the costs only (the panel's Refresh button).</summary>
|
||||
public void RefreshCosts()
|
||||
{
|
||||
if (Running || Blocker() != null) return;
|
||||
ReadCosts(_runId, thenStep: false);
|
||||
}
|
||||
|
||||
/// <summary>Reads the costs once per login when the Progression tab is first shown. Pump thread.</summary>
|
||||
public void EnsureCosts()
|
||||
{
|
||||
if (_autoCostsTried || _costsAtMs != 0 || Running || Blocker() != null) return;
|
||||
_autoCostsTried = true;
|
||||
ReadCosts(_runId, thenStep: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// XP for <paramref name="levels"/> raises when the next one costs <paramref name="nextCost"/>,
|
||||
/// each level <see cref="ProjectedLevelGrowth"/> dearer than the last. Saturates at long.MaxValue.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "+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.
|
||||
/// </summary>
|
||||
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<string, long>(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<string>(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);
|
||||
}
|
||||
|
||||
/// <summary>Runs a capture callback; an exception ends the run instead of leaving it Running.</summary>
|
||||
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 ────────────────────────────────────────────
|
||||
|
||||
/// <summary>Appends <c>"attr":{...}</c> for the Progression tab.</summary>
|
||||
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<string>(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('"');
|
||||
}
|
||||
|
||||
/// <summary>"prog attr…" commands from the Skills panel. Returns false when the verb isn't ours.</summary>
|
||||
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<string>(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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,228 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>The saved file: one cost profile per world that was changed from the defaults.</summary>
|
||||
public sealed class IltAugCostFile
|
||||
{
|
||||
public Dictionary<string, IltAugCostProfile> Servers = new(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>A world's cost rules: the five tier multipliers and one row per aug.</summary>
|
||||
public sealed class IltAugCostProfile
|
||||
{
|
||||
public double[] Multipliers = (double[])IltAugCosts.DefaultMultipliers.Clone();
|
||||
public List<IltAugCostRow> Augs = new();
|
||||
}
|
||||
|
||||
/// <summary>One aug's cost rule. Thresholds are 1-based levels; Cap 0 = no target limit.</summary>
|
||||
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
|
||||
{
|
||||
/// <summary>UB's tier multipliers: below S1, from S1, from S2, from S3, from S4.</summary>
|
||||
public static readonly double[] DefaultMultipliers = { 1, 4, 8, 16, 24 };
|
||||
|
||||
/// <summary>Highest target the planner accepts when an aug has no cap (keeps the plan sane).</summary>
|
||||
public const int NoCapLimit = 100_000;
|
||||
|
||||
/// <summary>Display order and labels; also the only keys a profile may hold.</summary>
|
||||
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"),
|
||||
};
|
||||
|
||||
/// <summary>UB Augs.cs (ILT): cost models, coins per level and soft caps S1..S4; no target cap.</summary>
|
||||
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 };
|
||||
|
||||
/// <summary>The shared settings file. Tests point it at a scratch folder before first use.</summary>
|
||||
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<string, IltAugCostProfile>(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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<string, IltAugCostRow>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var r in p.Augs ?? new()) if (r != null && !string.IsNullOrEmpty(r.Key)) byKey[r.Key] = r;
|
||||
var rows = new List<IltAugCostRow>(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;
|
||||
}
|
||||
|
||||
/// <summary>The rules for <paramref name="world"/>: its saved profile, or the UB defaults.</summary>
|
||||
public IltAugCostProfile For(string world)
|
||||
=> File_.Servers.TryGetValue(world ?? string.Empty, out var p) ? p : Defaults;
|
||||
|
||||
/// <summary>True when <paramref name="world"/> has its own saved rules.</summary>
|
||||
public bool IsCustom(string world) => File_.Servers.ContainsKey(world ?? string.Empty);
|
||||
|
||||
/// <summary>Applies an edit to <paramref name="world"/>'s rules (copying the defaults first) and saves.</summary>
|
||||
public void Edit(string world, Action<IltAugCostProfile> 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();
|
||||
}
|
||||
|
||||
/// <summary>Drops <paramref name="world"/>'s saved rules: it goes back to the UB defaults.</summary>
|
||||
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}"); }
|
||||
}
|
||||
|
||||
/// <summary>Highest target the planner allows for <paramref name="r"/> at current level <paramref name="cur"/>.</summary>
|
||||
public static int Ceiling(IltAugCostRow r, int cur) => Math.Max(cur, r.Cap > 0 ? r.Cap : NoCapLimit);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,188 +0,0 @@
|
|||
// 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 <kind>",
|
||||
// "No <kind> found to deposit", "Deposited all <kind>!".
|
||||
// /b lum bank luminance tokens: "Starting Banked Lum", one "Deposited N x <token>"
|
||||
// a kind, "Ending Banked Lum"; "No luminance tokens found to deposit".
|
||||
// /b w <code> <amount> withdraw: "Withdrew ...", "You don't have enough ...", "Failed to create ...".
|
||||
// /b w n <denom> [n] trade notes by denomination (i v x l c d m md mm mmd).
|
||||
// /b t <code> <n> <who> transfer; "Transferred {N0} {Currency} to {Name}[ (offline)]".
|
||||
// /b t n <denom> <n> <who> 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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed record BankItem(string Label, string Code, bool Deposit, bool Withdraw, bool Transfer);
|
||||
|
||||
/// <summary>The trade-notes code: withdrawn and transferred by denomination.</summary>
|
||||
public const string NotesCode = "n";
|
||||
|
||||
/// <summary>The luminance-tokens deposit: its own command, "/b lum".</summary>
|
||||
public const string LuminanceTokensCode = "lum";
|
||||
|
||||
/// <summary>Everything the bank holds, in the server's order, with what it allows.</summary>
|
||||
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),
|
||||
};
|
||||
|
||||
/// <summary>A deposit choice: label, and the command's argument after "/b d" ("" = all).</summary>
|
||||
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();
|
||||
|
||||
/// <summary>A withdraw choice: label and the server code; "n" is trade notes (by denomination).</summary>
|
||||
public static readonly (string Label, string Code)[] Withdrawals =
|
||||
Items.Where(i => i.Withdraw).Select(i => (i.Label, i.Code)).ToArray();
|
||||
|
||||
/// <summary>A transfer choice: label and the server code; "n" moves trade notes' pyreal value.</summary>
|
||||
public static readonly (string Label, string Code)[] Transfers =
|
||||
Items.Where(i => i.Transfer).Select(i => (i.Label, i.Code)).ToArray();
|
||||
|
||||
/// <summary>Trade note denominations: label and code, in the server's order.</summary>
|
||||
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),
|
||||
};
|
||||
|
||||
/// <summary>The server refuses a trade-note withdrawal of more than this many notes; transfers use the same cap.</summary>
|
||||
public const int MaxNoteCount = 50_000;
|
||||
|
||||
/// <summary>"/b d", "/b d p", or "/b lum" for the luminance tokens; empty for an unknown index.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "/b w p 1000000", or "/b w n mmd 5" for trade notes (<paramref name="amount"/> is then the
|
||||
/// note count). Empty (with <paramref name="error"/>) when the input can't be sent.
|
||||
/// </summary>
|
||||
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}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "/bank t p 250000 Bob", "/bank t n mmd 4 \"Some Name\"" for trade notes (<paramref name="amount"/>
|
||||
/// is then the note count). <paramref name="target"/> must already be a checked character name
|
||||
/// (IltParse.CharacterName); a name with a space is quoted, as the server reads one argument.
|
||||
/// Empty (with <paramref name="error"/>) when the input can't be sent.
|
||||
/// </summary>
|
||||
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}";
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="index"/> is the trade-notes transfer (denomination and count).</summary>
|
||||
public static bool IsNoteTransfer(int index) => index >= 0 && index < Transfers.Length && Transfers[index].Code == NotesCode;
|
||||
|
||||
/// <summary>The pyreal value of <paramref name="count"/> notes of <paramref name="denomination"/> (0 if unknown).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,151 +0,0 @@
|
|||
// 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
|
||||
// (<RynthILT folder>\<world>\<character>\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
|
||||
{
|
||||
/// <summary>How many recent transfers the JSON carries (newest first).</summary>
|
||||
public const int MaxTransactions = 50;
|
||||
|
||||
/// <summary>One character's balances as exported.</summary>
|
||||
internal sealed record Row(string Name, bool Current, IltBankState Bank);
|
||||
|
||||
/// <summary>
|
||||
/// The bank JSON. <paramref name="enabled"/>: 1 the server has /bank, 0 not, -1 not known yet.
|
||||
/// Rows are listed current character first, then by name. Plain ASCII.
|
||||
/// </summary>
|
||||
public static string Build(bool available, int enabled, string world, string character, IReadOnlyList<Row> rows,
|
||||
string result, IReadOnlyList<IltBankTransaction> 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<Row>(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(']');
|
||||
}
|
||||
|
||||
/// <summary>A local DateTime as ISO UTC ("" = never).</summary>
|
||||
private static string Utc(DateTime local) => local == DateTime.MinValue || local == default
|
||||
? ""
|
||||
: local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>
|
||||
/// The other characters' saved balances: every <c><world folder>\*\hub.json</c> except
|
||||
/// <paramref name="currentFolder"/>. A file that can't be read is skipped (its character just
|
||||
/// isn't listed). Characters never banked (no LastUpdated) are left out.
|
||||
/// </summary>
|
||||
public static List<Row> ReadSiblings(string currentFolder)
|
||||
{
|
||||
var rows = new List<Row>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,676 +0,0 @@
|
|||
// 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. 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 <c> <n> <who> → "Transferred {N0} {Currency} to {Name}[ (offline)]" or an error;
|
||||
// the recipient sees "Received {N0} {currency} from {Name}".
|
||||
// /bank t n <d> <n> <who> → 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
|
||||
{
|
||||
/// <summary>Transfer currencies: display name, /bank t code (IltBankCommands.Transfers).</summary>
|
||||
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();
|
||||
|
||||
/// <summary>Server throttle for deposit / withdraw / transfer (bank_command_limit).</summary>
|
||||
private const long BankCommandSpacingMs = 5000;
|
||||
/// <summary>Client spacing for balance refreshes (the server doesn't throttle a plain /bank).</summary>
|
||||
private const long BalanceSpacingMs = 5000;
|
||||
/// <summary>After a deposit or withdrawal, the balances are re-read this long after the reply.</summary>
|
||||
private const long RefreshAfterActionMs = 1500;
|
||||
|
||||
private readonly IltHubContext _ctx;
|
||||
private readonly object _txLock = new();
|
||||
private readonly List<IltBankTransaction> _transactions;
|
||||
private IltBankTransaction[] _txSnapshot = Array.Empty<IltBankTransaction>();
|
||||
private bool _txDirty;
|
||||
|
||||
private long _lastBankCommandAt;
|
||||
private long _lastBalanceAt;
|
||||
private long _lastAutoRefreshAt;
|
||||
/// <summary>When a quiet balance refresh is due after an action (0 = none). Pump thread.</summary>
|
||||
private long _refreshDueAt;
|
||||
/// <summary>Until then, money is moving between pack and bank (MovingMoney). Pump thread.</summary>
|
||||
private long _moveUntil;
|
||||
/// <summary>How long after a deposit / withdrawal reply the moved amounts are not income (covers the balance re-read).</summary>
|
||||
private const long MoveWindowMs = 12_000;
|
||||
/// <summary>Until this tick, a balance dump that reaches chat is the reply to a quiet Hub refresh (0 = no quiet refresh out).</summary>
|
||||
private long _quietBalanceUntil;
|
||||
/// <summary>How long after a quiet refresh is queued its leaked dump lines are still eaten here.</summary>
|
||||
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;
|
||||
/// <summary>The newest action reply or error (deposit, withdrawal or transfer), for the bank export.</summary>
|
||||
private volatile string _latestResult = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public bool ReaderWatching;
|
||||
|
||||
/// <summary>The newest action reply or error (any thread).</summary>
|
||||
public string LatestResult => _latestResult;
|
||||
|
||||
/// <summary>The transaction log as last published (any thread; oldest first).</summary>
|
||||
public IReadOnlyList<IltBankTransaction> Transactions => _txSnapshot;
|
||||
|
||||
/// <summary>The bank state (pump thread).</summary>
|
||||
public IltBankState State => Bank;
|
||||
|
||||
/// <summary>Raised (pump thread) after a balance line updates the state; Character rates use the deltas.</summary>
|
||||
public event Action<string, long, long>? 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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public bool MovingMoney => IltHubContext.NowMs < _moveUntil;
|
||||
|
||||
/// <summary>Exposed for the one-time UB import (mutated under the lock).</summary>
|
||||
public void ImportUb(Func<List<IltBankTransaction>, string> importer)
|
||||
{
|
||||
string summary;
|
||||
lock (_txLock)
|
||||
{
|
||||
summary = importer(_transactions);
|
||||
_txDirty = true;
|
||||
}
|
||||
PublishSnapshot();
|
||||
RynthLog.Write(LogCat.IltBanking, $"[IltHub] UB sidecar import: {summary}");
|
||||
}
|
||||
|
||||
// ── Commands ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Queues a /bank balance refresh (eaten when <paramref name="quiet"/>).</summary>
|
||||
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);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates and (after the UI confirm) sends a transfer. For trade notes
|
||||
/// <paramref name="amount"/> is the note count of <paramref name="denomination"/>. Pump thread.
|
||||
/// Returns an error message, or empty when the command was queued.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a deposit (<see cref="IltBankCommands.Deposits"/> index). Pump thread. Returns an
|
||||
/// error message, or empty when the command was queued; the reply lands in the tab.
|
||||
/// </summary>
|
||||
public string SendDeposit(int index)
|
||||
{
|
||||
string cmd = IltBankCommands.Deposit(index);
|
||||
if (cmd.Length == 0) return "Pick what to deposit.";
|
||||
return SendAction(cmd, "Deposit");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a withdrawal (<see cref="IltBankCommands.Withdrawals"/> index; for trade notes
|
||||
/// <paramref name="amount"/> is the note count). Pump thread; same result as SendDeposit.
|
||||
/// </summary>
|
||||
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");
|
||||
}
|
||||
|
||||
/// <summary>A deposit or withdrawal through the capture queue (shown, not eaten), then a quiet balance read.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="LatestResult"/>.
|
||||
/// </summary>
|
||||
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 ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// True when a quiet refresh's dump line that reached chat should be eaten here: it is a balance
|
||||
/// line (see <see cref="ParseBalanceLine"/>) and a quiet refresh was queued within the window.
|
||||
/// </summary>
|
||||
internal static bool EatLeakedDump(bool isBalanceLine, long nowMs, long quietUntilMs)
|
||||
=> isBalanceLine && quietUntilMs != 0 && nowMs < quietUntilMs;
|
||||
|
||||
/// <summary>The balance key a dump label belongs to ("Weakly Enlightened Coins" -> WeaklyEnlightenedCoins), or null.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Reads a "[BANK] ..." line into the balances. Returns <see cref="IsBalanceDumpLine"/>.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True for chat another player could have written (tells, says, channel or emote markup).</summary>
|
||||
private static bool IsPlayerAuthoredLine(string text)
|
||||
=> text.Contains("<Tell:", StringComparison.Ordinal)
|
||||
|| text.Contains(" tells you", StringComparison.Ordinal)
|
||||
|| text.Contains(" says, \"", StringComparison.Ordinal)
|
||||
|| text.Contains("[Allegiance]", StringComparison.Ordinal)
|
||||
|| text.Contains("[Fellowship]", StringComparison.Ordinal)
|
||||
|| text.Contains("[General]", StringComparison.Ordinal)
|
||||
|| text.Contains("[Trade]", StringComparison.Ordinal)
|
||||
|| text.Contains("[LFG]", StringComparison.Ordinal)
|
||||
|| text.Contains("[Roleplay]", StringComparison.Ordinal)
|
||||
|| text.Contains("[Society]", StringComparison.Ordinal)
|
||||
|| text.Contains("[Olthoi]", StringComparison.Ordinal)
|
||||
|| text.Contains("[Patron]", StringComparison.Ordinal)
|
||||
|| text.Contains("[Vassals]", StringComparison.Ordinal)
|
||||
|| text.Contains("[Covassals]", StringComparison.Ordinal)
|
||||
|| text.Contains("[Monarch]", StringComparison.Ordinal);
|
||||
|
||||
private void PublishSnapshot()
|
||||
{
|
||||
lock (_txLock) _txSnapshot = _transactions.ToArray();
|
||||
}
|
||||
|
||||
// ── UI (render thread) ──────────────────────────────────────────────────
|
||||
|
||||
public void Render()
|
||||
{
|
||||
if (!Enabled)
|
||||
{
|
||||
SafeImGui.TextColored(IltStyle.ColTextMute,
|
||||
_ctx.Options.IsOff(IltFeature.Bank) ? "The server reports /bank is not available." : "Waiting for the server options check...");
|
||||
return;
|
||||
}
|
||||
|
||||
// Balances
|
||||
ImGui.TextColored(IltStyle.ColTeal, "Balances");
|
||||
ImGui.SameLine();
|
||||
if (ImGui.SmallButton("Refresh##bank")) _ctx.Post(() => 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);
|
||||
|
||||
ImGui.Separator();
|
||||
RenderDepositWithdraw();
|
||||
ImGui.Separator();
|
||||
RenderTransferForm();
|
||||
ImGui.Separator();
|
||||
RenderTransactionLog();
|
||||
}
|
||||
|
||||
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)})");
|
||||
}
|
||||
|
||||
/// <summary>Deposit (one kind or everything, luminance tokens included) and withdraw (an amount, or trade notes).</summary>
|
||||
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 <denomination> <count> <name>).");
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One-line summary in UB's chat-paste format.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,316 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>A gate's outcome for one essence.</summary>
|
||||
internal enum BreedGate { Ready, Resting, NoCharges, Growing, Neutered, Shiny, LowBond, LowTier, NeedsId }
|
||||
|
||||
/// <summary>What was read for one essence (host values; pump thread fills it).</summary>
|
||||
internal sealed class BreedEssenceFacts
|
||||
{
|
||||
public int Id;
|
||||
public string Name = string.Empty;
|
||||
public uint Wcid;
|
||||
public bool HasId;
|
||||
/// <summary>The essence's level requirement (a tier fallback for WCIDs outside the table).</summary>
|
||||
public int UseLevel;
|
||||
public int Bond;
|
||||
/// <summary>The server's explicit sex (Tailoring Kit), or null to derive it from the object id.</summary>
|
||||
public bool? MaleOverride;
|
||||
public bool Neutered;
|
||||
public bool JuvenileFlag;
|
||||
/// <summary>PetMaturityKills: -1 when absent (the essence was never bred).</summary>
|
||||
public int MaturityKills = -1;
|
||||
/// <summary>PetMaleBreedingCharges: -1 when absent (a full stud).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>One essence evaluated for breeding. Immutable; the UI and the reader JSON read it.</summary>
|
||||
internal sealed record BreedEssence(
|
||||
int Id, string Name, uint Wcid, bool HasId, int Tier, int Bond, bool Male, BreedGate Gate, string Status,
|
||||
IReadOnlyList<string> 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<string> Boosters,
|
||||
int MutD, int MutDR, int MutC, int MutV, int MutP, bool Shiny, bool Unbound, int Potency)
|
||||
{
|
||||
/// <summary>Every gate passes now.</summary>
|
||||
public bool Ready => Gate == BreedGate.Ready;
|
||||
/// <summary>The stat mutation lines (damage, damage resist, crit, vitality) summed.</summary>
|
||||
public int StatMutations => MutD + MutDR + MutC + MutV;
|
||||
/// <summary>"Stud" or "Dam".</summary>
|
||||
public string Role => Male ? "Stud" : "Dam";
|
||||
}
|
||||
|
||||
internal static class IltBreedingEssence
|
||||
{
|
||||
/// <summary>Essence tiers, in the order of each family row below (ACE PetDeviceWcids petLevelIndexes).</summary>
|
||||
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",
|
||||
};
|
||||
|
||||
/// <summary>Each family row expanded (tests check every row has one WCID per tier).</summary>
|
||||
internal static readonly uint[][] Families = Array.ConvertAll(FamilyRows, ExpandRow);
|
||||
|
||||
private static readonly Dictionary<uint, int> TierByWcid = BuildTiers();
|
||||
|
||||
private static uint[] ExpandRow(string row)
|
||||
{
|
||||
var list = new List<uint>(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<uint, int> BuildTiers()
|
||||
{
|
||||
var d = new Dictionary<uint, int>();
|
||||
foreach (uint[] row in Families)
|
||||
for (int i = 0; i < row.Length && i < Tiers.Length; i++)
|
||||
d[row[i]] = Tiers[i];
|
||||
return d;
|
||||
}
|
||||
|
||||
/// <summary>True for a combat pet essence WCID (the only kind that breeds).</summary>
|
||||
public static bool IsCombatEssence(uint wcid) => TierByWcid.ContainsKey(wcid);
|
||||
|
||||
/// <summary>The essence tier for a WCID, else the level requirement when it is a tier, else 0.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>ACE PetDevice.IsMale without an override: murmur3 fmix32 on the object id, even = male.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>"3h 05m", "42m", "20s" (0 or less = "now").</summary>
|
||||
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";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates one essence: role, every failing gate (the first is the headline), the ready time,
|
||||
/// growth and boosters. <paramref name="nowUnix"/> is unix seconds.
|
||||
/// </summary>
|
||||
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<string>();
|
||||
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<string>(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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a stud + dam pairing would do: the gates both must pass, and the baby's odds.</summary>
|
||||
internal sealed record BreedPairPlan(bool CanBreed, IReadOnlyList<string> Blockers, double Incense, double ChanceBest, double ChanceWorst,
|
||||
double PotencyChance, int InheritMin, int InheritMax, IReadOnlyList<string> Notes);
|
||||
|
||||
internal static class IltBreedingPlanner
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static BreedPairPlan Plan(BreedEssence stud, BreedEssence dam, IltBreedingRules r)
|
||||
{
|
||||
var blockers = new List<string>();
|
||||
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<string>
|
||||
{
|
||||
"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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,445 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>Where a breeding rule's value came from (later = more trusted).</summary>
|
||||
internal enum BreedRuleSource { AceDefault = 0, IltProfile = 1, Server = 2 }
|
||||
|
||||
/// <summary>One rule: stable key, label, unit, the ACE default and the ILT profile value (null = same as ACE).</summary>
|
||||
internal sealed record BreedRuleDef(string Key, string Label, string Unit, double AceDefault, double? IltProfile, string Help);
|
||||
|
||||
/// <summary>A rule's effective value and where it came from.</summary>
|
||||
internal readonly record struct BreedRuleValue(BreedRuleDef Def, double Value, BreedRuleSource Source, DateTime SeenUtc);
|
||||
|
||||
/// <summary>A value this server showed, saved with the character.</summary>
|
||||
public sealed class IltLearnedRule
|
||||
{
|
||||
public string Key = string.Empty;
|
||||
public double Value;
|
||||
public DateTime SeenUtc;
|
||||
}
|
||||
|
||||
/// <summary>One breeding event from chat (ritual, birth, growth, ...), newest last.</summary>
|
||||
public sealed class IltBreedingEvent
|
||||
{
|
||||
public DateTime Utc;
|
||||
/// <summary>ritual, charge, birth, mutation, guardian, growth, adult, imprint, dance, debug.</summary>
|
||||
public string Kind = string.Empty;
|
||||
public string Text = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The breeding tracker's saved part (IltPetState.Breeding).</summary>
|
||||
public sealed class IltBreedingState
|
||||
{
|
||||
/// <summary>Rules read back from this server (see IltBreedingRules).</summary>
|
||||
public List<IltLearnedRule> Rules = new();
|
||||
/// <summary>Growth stage names this server uses, by stage (index 0 = stage 1); "" = not seen yet.</summary>
|
||||
public List<string> StageNames = new();
|
||||
/// <summary>Recent breeding events (capped at IltBreedingRules.MaxEvents).</summary>
|
||||
public List<IltBreedingEvent> Log = new();
|
||||
/// <summary>The last "@breed-debug" reply's lines and when it came.</summary>
|
||||
public List<string> LastDebug = new();
|
||||
public DateTime LastDebugUtc;
|
||||
}
|
||||
|
||||
/// <summary>What one "@breed-debug" reply said.</summary>
|
||||
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";
|
||||
|
||||
/// <summary>Breeding events kept with the character.</summary>
|
||||
public const int MaxEvents = 60;
|
||||
|
||||
/// <summary>ACECustom's default growth stage names (pet_maturity_stage_names).</summary>
|
||||
public static readonly string[] DefaultStageNames = { "Newborn", "Whelp", "Juvenile", "Adolescent", "Young Adult" };
|
||||
|
||||
/// <summary>Every rule shown, in display order. Values copied from ACECustom ServerConfig and the ILT deploy plan.</summary>
|
||||
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<string, BreedRuleDef> DefByKey = BuildIndex();
|
||||
|
||||
private static Dictionary<string, BreedRuleDef> BuildIndex()
|
||||
{
|
||||
var d = new Dictionary<string, BreedRuleDef>(StringComparer.Ordinal);
|
||||
foreach (BreedRuleDef def in Defs) d[def.Key] = def;
|
||||
return d;
|
||||
}
|
||||
|
||||
private readonly IltBreedingState _state;
|
||||
|
||||
/// <param name="state">The saved breeding state; learned values are read from and written to it.</param>
|
||||
public IltBreedingRules(IltBreedingState state) => _state = state;
|
||||
|
||||
/// <summary>The saved state these rules read and update.</summary>
|
||||
public IltBreedingState State => _state;
|
||||
|
||||
/// <summary>A copy that never changes (the render thread reads it while the pump learns).</summary>
|
||||
public IltBreedingRules Frozen()
|
||||
{
|
||||
var copy = new IltBreedingState { StageNames = new List<string>(_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);
|
||||
}
|
||||
|
||||
/// <summary>The effective value of rule <paramref name="key"/> (0 for an unknown key).</summary>
|
||||
public double Get(string key) => Value(key).Value;
|
||||
|
||||
/// <summary>A whole-number rule (charges, kills, tiers).</summary>
|
||||
public int GetInt(string key) => (int)Math.Round(Get(key));
|
||||
|
||||
/// <summary>The effective value and its source.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Every rule's effective value, in display order.</summary>
|
||||
public List<BreedRuleValue> All()
|
||||
{
|
||||
var list = new List<BreedRuleValue>(Defs.Length);
|
||||
foreach (BreedRuleDef d in Defs) list.Add(Value(d.Key));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Records a value the server showed. True when it changed what RynthILT knew.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Applies every (key, value) an observer returned. True when anything changed.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Records a growth stage's name (1-based) as the server spelled it.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The name of growth stage <paramref name="stage"/> (1-based): seen on the server, else ACE's default, else "Stage N".</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Appends an event, dropping the oldest past <see cref="MaxEvents"/>.</summary>
|
||||
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) ──────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The chance of a stat mutation for a baby that inherits <paramref name="babyStatMutations"/>
|
||||
/// stat mutations, with <paramref name="incense"/> from both parents (already capped):
|
||||
/// clamp(max(floor, (base + incense) / (1 + decay x mutations)), 0, 1).
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Both parents' incense together, capped at the incense cap.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="longDesc">The appraisal LongDesc (string 16).</param>
|
||||
/// <param name="maleRefreshUnix">The essence's PetMaleChargesRefreshTime (0 = not sent).</param>
|
||||
/// <param name="nowUnix">Now, unix seconds.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>What one chat line says about the rules (a line can say nothing).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The stage name a "has grown into a Whelp! ... (2/5)" line gives, with its stage number; false for any other line.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>True for any line of an "@breed-debug" reply (one multi-line message, or its lines one by one).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The reply's closing rule of '=' (alone, or ending the whole message).</summary>
|
||||
public static bool IsDebugEnd(string text)
|
||||
=> !string.IsNullOrEmpty(text) && text.TrimEnd().EndsWith("================================", StringComparison.Ordinal);
|
||||
|
||||
/// <summary>Parses an "@breed-debug" reply (any mix of whole messages and single lines).</summary>
|
||||
public static BreedDebugInfo ParseDebug(IEnumerable<string> 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);
|
||||
}
|
||||
|
||||
/// <summary>"0x0106 variant 2" (or "anywhere") for the rules list.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A rule value for display: "5%", "24h", "0x0106", "on", "10".</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"ACE default", "ILT profile" or "seen on server".</summary>
|
||||
public static string SourceText(BreedRuleSource s) => s switch
|
||||
{
|
||||
BreedRuleSource.Server => "seen on server",
|
||||
BreedRuleSource.IltProfile => "ILT profile",
|
||||
_ => "ACE default",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,112 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>One supply: key, WCID, name, what it does, Ivo's price, and whether the tracker can apply it.</summary>
|
||||
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";
|
||||
|
||||
/// <summary>Every supply, boosters first.</summary>
|
||||
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),
|
||||
};
|
||||
|
||||
/// <summary>The supply with this key, or null.</summary>
|
||||
public static BreedSupplyDef? Find(string key) => Array.Find(All, s => s.Key == key);
|
||||
|
||||
/// <summary>The incense bonus a supply gives (0 for anything else).</summary>
|
||||
public static double IncenseBonus(string key) => key switch
|
||||
{
|
||||
LesserIncense => 0.025,
|
||||
RefinedIncense => 0.05,
|
||||
ExquisiteIncense => 0.10,
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
/// <summary>"Refined incense +5%" for an applied bonus.</summary>
|
||||
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)}%";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why the server would refuse <paramref name="s"/> on <paramref name="e"/> (the server's own
|
||||
/// checks, so nothing is spent on a refusal), or null when it would take it.
|
||||
/// </summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A warning to show in the confirmation (a weaker incense being replaced), or "".</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>"1.25M", "125M", "-" for a price.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,256 +0,0 @@
|
|||
// 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<string> 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<string> BuildHarmfulExact()
|
||||
{
|
||||
var set = new HashSet<string>(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<string>();
|
||||
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;
|
||||
|
||||
/// <summary>True when this spell should be dispelled (precedence documented above).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>"Vulnerability Other VII" → "vulnerability other" (roman numeral suffix removed).</summary>
|
||||
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<string>();
|
||||
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<string>();
|
||||
}
|
||||
|
||||
// ── 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<string> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,144 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>
|
||||
/// One charm's tracked state. <paramref name="ToggleId"/> is the carried copy a toggle uses
|
||||
/// (the active one when one is on), 0 when none is carried.
|
||||
/// </summary>
|
||||
internal readonly record struct CharmState(
|
||||
IltCharmDef Def, string Acquired, int Count, int Tier, int MaxTier,
|
||||
IltTri Active, IltTri Server, DateTime LastSeenUtc, int ToggleId = 0);
|
||||
|
||||
/// <summary>Evaluates every registry charm and refreshes the "seen" memory for carried ones.</summary>
|
||||
public List<CharmState> Evaluate()
|
||||
{
|
||||
var inv = _ctx.Inventory;
|
||||
var seenMap = _ctx.State.Character.CharmsSeen;
|
||||
var result = new List<CharmState>(IltInventory.Charms.Length);
|
||||
// One inventory pass, grouped by charm definition, instead of a WCID scan per charm.
|
||||
var carried = new Dictionary<IltCharmDef, List<WorldObject>>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Server-side enabled state as far as the client has learned it.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>JSON for RynthPluginGetCharmsJson. "available" is false off ILT-like worlds.</summary>
|
||||
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" };
|
||||
}
|
||||
|
|
@ -1,266 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>A Guardian Hand carried now (name or WCID match).</summary>
|
||||
private sealed record HandRow(int Id, string Name, IltTri Status, bool ServerDisabled);
|
||||
|
||||
private volatile IltCharmTracker.CharmState[] _rows = Array.Empty<IltCharmTracker.CharmState>();
|
||||
private volatile HandRow[] _hands = Array.Empty<HandRow>();
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>Pump thread: the registry table and the carried Guardian Hands.</summary>
|
||||
private void Scan()
|
||||
{
|
||||
_rows = _tracker.Evaluate().ToArray();
|
||||
var inv = _ctx.Inventory;
|
||||
var hands = new List<HandRow>();
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Uses (toggles) a charm (pump thread).</summary>
|
||||
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)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<IltCharmTracker.CharmState>();
|
||||
_hands = Array.Empty<HandRow>();
|
||||
_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();
|
||||
}
|
||||
|
||||
/// <summary>The Guardian Hand (not a registry charm): each carried one with a Toggle, and how it is matched.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,217 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>Describes one command whose reply should be captured.</summary>
|
||||
internal sealed class IltChatRequest
|
||||
{
|
||||
/// <summary>Text handed to InvokeChatParser, e.g. "/bank".</summary>
|
||||
public string Command = string.Empty;
|
||||
/// <summary>True for lines that belong to this reply (captured, refresh the idle timer).</summary>
|
||||
public Func<string, bool> IsResponseLine = _ => false;
|
||||
/// <summary>
|
||||
/// 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:).
|
||||
/// </summary>
|
||||
public Func<string, bool>? ArmsIdle;
|
||||
/// <summary>Optional: a line that ends the reply immediately (it is captured too).</summary>
|
||||
public Func<string, bool>? IsTerminator;
|
||||
/// <summary>The reply is complete after this long with no new response line.</summary>
|
||||
public int IdleEndMs = 2000;
|
||||
/// <summary>Give up if no response line arrives within this long.</summary>
|
||||
public int FirstLineTimeoutMs = 15000;
|
||||
/// <summary>Hide captured lines from the chat window.</summary>
|
||||
public bool Eat = true;
|
||||
/// <summary>Invoked once on the pump thread when the capture finishes for any reason.</summary>
|
||||
public Action<IltChatResult>? OnComplete;
|
||||
}
|
||||
|
||||
/// <summary>What a capture produced.</summary>
|
||||
internal sealed class IltChatResult
|
||||
{
|
||||
public readonly List<string> Lines = new();
|
||||
/// <summary>No response line ever arrived.</summary>
|
||||
public bool TimedOut;
|
||||
/// <summary>The server answered "Unknown command: …" for this command.</summary>
|
||||
public bool UnknownCommand;
|
||||
/// <summary>The engine had no InvokeChatParser, so nothing was sent.</summary>
|
||||
public bool NotSent;
|
||||
public string? TerminatorLine;
|
||||
}
|
||||
|
||||
internal sealed class IltChatCapture
|
||||
{
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly Queue<IltChatRequest> _queue = new();
|
||||
|
||||
private IltChatRequest? _active;
|
||||
private IltChatResult? _activeResult;
|
||||
private long _sentAt;
|
||||
private long _lastLineAt;
|
||||
/// <summary>True once a response line that arms idle has arrived (always true when <see cref="IltChatRequest.ArmsIdle"/> is null).</summary>
|
||||
private bool _idleArmed;
|
||||
|
||||
/// <summary>Minimum spacing between two sends so the server's own command throttles aren't tripped.</summary>
|
||||
private const long SendSpacingMs = 400;
|
||||
private long _lastSendAt;
|
||||
|
||||
private static long NowMs => Environment.TickCount64;
|
||||
|
||||
public IltChatCapture(RynthCoreHost host) => _host = host;
|
||||
|
||||
/// <summary>True while a capture is in flight or queued.</summary>
|
||||
public bool IsBusy => _active != null || _queue.Count > 0;
|
||||
|
||||
/// <summary>True if a request with this exact command is queued or in flight (avoids duplicate refreshes).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Queues a capture. It is sent from <see cref="Tick"/> once earlier captures finish.</summary>
|
||||
public void Enqueue(IltChatRequest request)
|
||||
{
|
||||
_queue.Enqueue(request);
|
||||
RynthLog.Trace(LogCat.IltChat, $"enqueue '{request.Command}' (queue={_queue.Count}, busy={_active != null})");
|
||||
}
|
||||
|
||||
/// <summary>Drops everything (logout / teardown). Pending callbacks are not invoked.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Starts queued captures and finishes the active one on idle/timeout.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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}'"); }
|
||||
}
|
||||
}
|
||||
|
|
@ -1,672 +0,0 @@
|
|||
// 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<int> _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<int, string> _lastSkip = new();
|
||||
// Skip reasons of the current pass (reason -> items), shown in the status line.
|
||||
private readonly Dictionary<string, int> _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 ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Infinite Leaftide's chunking tool.</summary>
|
||||
internal const string HammerName = "Lugian Aetheria Hammer";
|
||||
|
||||
/// <summary>True for the chunking tool only, never a Lugian Hammer weapon. Pure: the tests drive it.</summary>
|
||||
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));
|
||||
|
||||
/// <summary>Item kinds the hammer works on (the name and class gate, before any appraisal).</summary>
|
||||
internal enum ChunkKind { None, Aetheria, Corrupted }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>An aetheria piece's chunk facts, read after appraisal.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// <para>
|
||||
/// <see cref="AetheriaFacts.Unreadable"/> 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.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Why an aetheria item is kept (null = chunk it); "appraising" while its data is missing.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The chunk cap in range: 1 (chunk nothing by level) to one past the ILT maximum (every level).</summary>
|
||||
internal static int ClampUnderLevel(int under) => Math.Clamp(under, 1, IltInventory.AetheriaMaxLevel + 1);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static bool UnderChunkCap(int maxLevel, int under, bool coalesced = false)
|
||||
=> maxLevel > 0 ? maxLevel < ClampUnderLevel(under) : coalesced && maxLevel == 0;
|
||||
|
||||
/// <summary>Highest rating level the keep threshold accepts.</summary>
|
||||
internal const int MaxRatingLevel = 50;
|
||||
|
||||
/// <summary>The rating keep threshold in range: 1 (any rating keeps) to <see cref="MaxRatingLevel"/>.</summary>
|
||||
internal static int ClampRatingLevel(int level) => Math.Clamp(level, 1, MaxRatingLevel);
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="IltGearState.KeepAetheriaRatingAtLeast"/>).
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>A corrupted weapon's chunk facts, read after appraisal.</summary>
|
||||
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<int> Spells { get; init; } = Array.Empty<int>();
|
||||
/// <summary>What could not be read (null = everything the rules need was); see AetheriaFacts.Unreadable.</summary>
|
||||
public string? Unreadable { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static int MaxChunkCleave(int wieldSkill, int weaponType, int attackType)
|
||||
=> (wieldSkill == SkillTwoHandedCombat || weaponType == WeaponTypeTwoHanded) && attackType != AttackTypeThrust ? 2 : 1;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Positive spell ids from a comma / semicolon / whitespace separated list. Pure: the tests drive it.</summary>
|
||||
internal static HashSet<int> ParseSpellIds(string? csv)
|
||||
{
|
||||
var ids = new HashSet<int>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Why a corrupted weapon is kept (null = chunk it); "appraising" while its data is missing.</summary>
|
||||
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<int>(),
|
||||
};
|
||||
return CorruptedSkip(G, f);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Tallies a skip for the status line and logs it once per item and reason.</summary>
|
||||
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}");
|
||||
}
|
||||
|
||||
/// <summary>"3 kept for its C / CD / CDR rating, 1 appraising" — the current pass's skips.</summary>
|
||||
private string PassSkipSummary()
|
||||
=> string.Join(", ", _passSkips.OrderByDescending(kv => kv.Value).Select(kv => $"{kv.Value} {kv.Key}"));
|
||||
|
||||
/// <summary>Runs one chunk pass now (both item kinds) regardless of the auto toggles.</summary>
|
||||
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 }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static bool CanClap(IEnumerable<ClapPart> 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))));
|
||||
}
|
||||
|
||||
/// <summary>Sends "/clap all" through the capture queue (reply stays visible).</summary>
|
||||
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 }
|
||||
|
||||
/// <summary>Where a chunk in flight stands when no chat line has ended the wait.</summary>
|
||||
internal enum ChunkWait { Waiting, Gone, TimedOut }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static ChunkWait WaitOutcome(long elapsedMs, bool targetStillCarried)
|
||||
=> !targetStillCarried ? ChunkWait.Gone
|
||||
: elapsedMs >= ChunkResultWaitMs ? ChunkWait.TimedOut
|
||||
: ChunkWait.Waiting;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,265 +0,0 @@
|
|||
// 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\<char>, 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<int> _dequip = new();
|
||||
private readonly Queue<int> _equip = new();
|
||||
private readonly Dictionary<int, int> _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<string>();
|
||||
private volatile string[] _preview = Array.Empty<string>();
|
||||
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<string> 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");
|
||||
}
|
||||
|
||||
/// <summary>All .utl profiles, first directory wins for duplicate names.</summary>
|
||||
public List<(string Name, string Path)> ListProfiles()
|
||||
{
|
||||
var seen = new Dictionary<string, string>(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;
|
||||
}
|
||||
|
||||
/// <summary>Items the suit wants worn (first matching rule is Keep; RynthAi evaluates the profile).</summary>
|
||||
private List<WorldObject>? SuitItems(string path, out string error)
|
||||
{
|
||||
error = string.Empty;
|
||||
var candidates = new List<WorldObject>();
|
||||
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<WorldObject>();
|
||||
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();
|
||||
|
||||
/// <summary>Lists what a load would do without doing it. Returns lines (also shown in the UI).</summary>
|
||||
public List<string> Test(string? name)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Starts loading a suit.</summary>
|
||||
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)";
|
||||
}
|
||||
|
||||
/// <summary>Counts an attempt; false once the item has used up its attempts.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,362 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>One Leaftide feature: id, display text, where it lives, and the server bit that says whether it's on.</summary>
|
||||
/// <param name="Key">Stable id.</param>
|
||||
/// <param name="Label">Display name.</param>
|
||||
/// <param name="Group">Character, Items, Fellowship or Activities (the list's sections).</param>
|
||||
/// <param name="Where">Where the Rynth tools handle it.</param>
|
||||
/// <param name="Description">One line on what the server does.</param>
|
||||
/// <param name="ServerBit">The IltServerOptions key probes and chat refusals set; null = content built into ACECustom (on with the world).</param>
|
||||
/// <param name="Known">How the state is known while the bit hasn't been set (see <see cref="IltKnown"/>).</param>
|
||||
internal sealed record IltFeatureInfo(string Key, string Label, string Group, string Where, string Description, string? ServerBit,
|
||||
IltKnown Known = IltKnown.Profile);
|
||||
|
||||
/// <summary>How a feature's state is known on an ILT world before (or without) a server answer.</summary>
|
||||
internal enum IltKnown
|
||||
{
|
||||
/// <summary>On in ILT: on with the ILT world unless chat shows it off.</summary>
|
||||
Profile,
|
||||
/// <summary>The login probe answers it: "checking" until the reply arrives.</summary>
|
||||
Checked,
|
||||
/// <summary>Off in ILT: off with the ILT world unless chat shows it on.</summary>
|
||||
ProfileOff,
|
||||
}
|
||||
|
||||
/// <summary>The quest bonus list as the profile JSON carries it ("questBonus"), for RynthOracle's Quests tab.</summary>
|
||||
/// <param name="Disabled">The server has /qb turned off.</param>
|
||||
/// <param name="Generation">Bumped per parsed "/qb list"; 0 = not loaded this session.</param>
|
||||
/// <param name="Count">The server's quest bonus count; -1 = unknown.</param>
|
||||
/// <param name="Status">One line on the last request ("loading...", "12 completed, 3 incomplete", ...).</param>
|
||||
/// <param name="Completed">Completed bonus flags, sorted.</param>
|
||||
/// <param name="Incomplete">Incomplete bonus flags, sorted.</param>
|
||||
internal sealed record IltQuestBonusInfo(bool Disabled, int Generation, long Count, string Status,
|
||||
IReadOnlyList<string> Completed, IReadOnlyList<string> 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";
|
||||
|
||||
/// <summary>The section order of the list (ACECustom's "/ilt features" uses the same).</summary>
|
||||
public static readonly string[] Groups = { GroupCharacter, GroupItems, GroupPets, GroupFellowship, GroupCombat, GroupActivities };
|
||||
|
||||
/// <summary>ACECustom's fellowship member limit (Fellowship.MaxFellows); retail is 9.</summary>
|
||||
public const int IltFellowshipMax = 29;
|
||||
|
||||
/// <summary>A retail fellowship's member limit.</summary>
|
||||
public const int RetailFellowshipMax = 9;
|
||||
|
||||
/// <summary>Every Leaftide feature RynthILT supports, in display order.</summary>
|
||||
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"),
|
||||
};
|
||||
|
||||
/// <summary>The entry with <paramref name="key"/>, or null.</summary>
|
||||
public static IltFeatureInfo? Find(string key)
|
||||
{
|
||||
foreach (IltFeatureInfo f in All)
|
||||
if (f.Key.Equals(key, StringComparison.OrdinalIgnoreCase)) return f;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="IltKnown.Profile"/>,
|
||||
/// Off for <see cref="IltKnown.ProfileOff"/>, Unknown ("checking") for probed features.
|
||||
/// Off ILT nothing is claimed: Unknown.
|
||||
/// </summary>
|
||||
public static IltTri StateOf(IltFeatureInfo f, bool iltWorld, Func<string, IltTri> 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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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").
|
||||
/// </summary>
|
||||
public static IltTri CharmStateOf(bool iltWorld, IltTri reported)
|
||||
=> !iltWorld ? IltTri.Unknown : reported != IltTri.Unknown ? reported : IltTri.On;
|
||||
|
||||
/// <summary>Prefix of a charm's server key (IltFeature.Charm): "charm:manabarrier".</summary>
|
||||
public const string CharmKeyPrefix = "charm:";
|
||||
|
||||
/// <summary>
|
||||
/// 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".
|
||||
/// </summary>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>One line on where a feature's state comes from (tooltips).</summary>
|
||||
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.",
|
||||
};
|
||||
|
||||
/// <summary>The settings view's extra sections after <see cref="Groups"/>.</summary>
|
||||
public const string GroupCharms = "Charms";
|
||||
public const string GroupOther = "Other";
|
||||
|
||||
/// <summary>Short state text for the list and chat: "on", "off" or "checking".</summary>
|
||||
public static string StateText(IltTri state) => state switch
|
||||
{
|
||||
IltTri.On => "on",
|
||||
IltTri.Off => "off",
|
||||
_ => "checking",
|
||||
};
|
||||
|
||||
/// <summary>The fellowship member limit: ACECustom's 29 on an ILT world, retail's 9 elsewhere.</summary>
|
||||
public static int FellowshipMax(bool iltWorld) => iltWorld ? IltFellowshipMax : RetailFellowshipMax;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static string BuildProfileJson(bool iltWorld, string world, bool forced, string source, DateTime checkedUtc,
|
||||
Func<string, IltTri> 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<string> 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(']');
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>JSON string body: quotes, backslashes and control characters escaped, anything non-ASCII as \uXXXX.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>The chat listing for "/ra hub features": one line per feature, ASCII only.</summary>
|
||||
public static List<string> BuildChatLines(bool iltWorld, Func<string, IltTri> bit)
|
||||
{
|
||||
var lines = new List<string>(All.Length + Groups.Length);
|
||||
foreach (string g in Groups)
|
||||
{
|
||||
var parts = new List<string>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,255 +0,0 @@
|
|||
// 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 <bet>, /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 )?(?<card>.+?)\.$", RegexOptions.Compiled);
|
||||
private static readonly Regex MyValue = new(@"Your (?:initial )?hand value is (?:now )?(?<v>\d+)", RegexOptions.Compiled);
|
||||
private static readonly Regex DealerValue = new(@"Rand's (?:current )?hand value is (?<v>\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<string>();
|
||||
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<string>();
|
||||
_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<string>(_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<string>();
|
||||
}
|
||||
|
||||
// ── 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);
|
||||
}
|
||||
|
||||
/// <summary>Small HUD with the current hand; called every frame by the Hub UI.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
// 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.");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,656 +0,0 @@
|
|||
// 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
|
||||
{
|
||||
/// <summary>The same guardian + answer from chat within this window is one prompt (tells repeat lines).</summary>
|
||||
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;
|
||||
/// <summary>How far (meters) to look for the guardian and a vendor.</summary>
|
||||
private const double SearchRangeMeters = 60.0;
|
||||
/// <summary>
|
||||
/// PublicWeenieDesc BF_VENDOR. The world cache files vendors as creatures (Monster / Npc), never
|
||||
/// AcObjectClass.Vendor, so vendors are recognised by this weenie flag.
|
||||
/// </summary>
|
||||
private const uint BfVendor = 0x200;
|
||||
/// <summary>The Mini Remote shows the last answer for this long.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Last answer item ("" until a guardian prompt was translated).</summary>
|
||||
public string LastAnswer => _lastAnswer;
|
||||
/// <summary>Guardian the last answer goes to.</summary>
|
||||
public string LastNpc => _lastNpc;
|
||||
/// <summary>The hand-in sequence is running.</summary>
|
||||
public bool HandInRunning => _step != Step.Idle;
|
||||
public string HandInStatus => _handInStatus;
|
||||
|
||||
/// <summary>Time since the last answer (MaxValue when there is none).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Translates pasted text; a real answer becomes the current answer. Pump thread.</summary>
|
||||
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 ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Starts giving <paramref name="item"/> to <paramref name="npc"/>. Pump thread.</summary>
|
||||
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}...");
|
||||
}
|
||||
|
||||
/// <summary>Stops a running hand-in.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private WorldObject? FindHandInItem()
|
||||
{
|
||||
string want = NormalizeName(_item);
|
||||
return CarriedItems().FirstOrDefault(wo => NormalizeName(wo.Name) == want && !_ctx.Inventory.IsEquipped(wo));
|
||||
}
|
||||
|
||||
/// <summary>Live walk of the player's pack and side packs (falls back to the cache without the engine call).</summary>
|
||||
private System.Collections.Generic.IReadOnlyList<WorldObject> CarriedItems()
|
||||
=> _ctx.Inventory.Cache?.GetDirectInventory(forceRefresh: true) ?? Array.Empty<WorldObject>();
|
||||
|
||||
/// <summary>Lower-case, trimmed, single-spaced name for comparisons.</summary>
|
||||
private static string NormalizeName(string name)
|
||||
=> string.Join(' ', (name ?? string.Empty).Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant();
|
||||
|
||||
/// <summary>Logs carried items sharing a word with the answer, so a name mismatch shows in the log.</summary>
|
||||
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")}");
|
||||
}
|
||||
|
||||
/// <summary>A vendor (weenie BF_VENDOR flag, or a cache entry already classed Vendor).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Logs every vendor the cache sees with its distance (vendor search found none in range).</summary>
|
||||
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")}");
|
||||
}
|
||||
|
||||
/// <summary>Nearest landscape object matching <paramref name="match"/> within SearchRangeMeters.</summary>
|
||||
private WorldObject? Nearest(Func<WorldObject, bool> 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 ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// "/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.
|
||||
/// </summary>
|
||||
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 <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status]");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Reader ("RynthILT.Data" GetGuardianJson / GuardianCommand; RynthOracle's Quests tab) ──
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The reader JSON from its parts. Pure: the tests drive it.</summary>
|
||||
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<IltTempleAttrStatus> 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('"');
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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) ──────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Guardian window body.</summary>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mini Remote line: the last answer (for AnswerShownFor) with a Give / Stop button.
|
||||
/// Draws nothing when there is no recent answer. Render thread.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,221 +0,0 @@
|
|||
// 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";
|
||||
|
||||
/// <summary>Chat prefixes of an incoming guardian line ("tells you" or ACE's environmental "says").</summary>
|
||||
private static readonly string[] IncomingPrefixes =
|
||||
{
|
||||
TempleGuardian + " tells you",
|
||||
AttributeGuardian + " tells you",
|
||||
TempleGuardian + " says",
|
||||
AttributeGuardian + " says",
|
||||
};
|
||||
|
||||
/// <summary>Help text returned when nothing was pasted.</summary>
|
||||
public const string PasteHint = "Paste a spell word or riddle text, then Translate.";
|
||||
|
||||
/// <summary>Help text returned when the text didn't match any spell word or riddle.</summary>
|
||||
public const string NoMatchHint = "No match: paste more lines from the guardian (especially the question line ending with ?).";
|
||||
|
||||
private static readonly Dictionary<string, string> 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" },
|
||||
};
|
||||
|
||||
/// <summary>Spell words longest first so a short word never shadows a longer one.</summary>
|
||||
private static readonly KeyValuePair<string, string>[] TempleSpellsByLength =
|
||||
TempleSpells.OrderByDescending(p => p.Key.Length).ToArray();
|
||||
|
||||
/// <summary>Normalized riddle phrases (longest first) and the item each answers.</summary>
|
||||
private static readonly (string Needle, string Item)[] AttributeClues = BuildAttributeClues();
|
||||
|
||||
/// <summary>The same riddles split into meaningful words for the fuzzy fallback.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Lowercase, curly apostrophes folded, punctuation collapsed to single spaces.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Words of 3+ letters minus question / filler words.</summary>
|
||||
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();
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static string? TryFuzzyAttributeMatch(string blob)
|
||||
{
|
||||
var inputWords = TokenizeMeaningfulWords(blob);
|
||||
if (inputWords.Length == 0) return null;
|
||||
var inputSet = new HashSet<string>(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;
|
||||
}
|
||||
|
||||
/// <summary>Resolves guardian text to an item name, or one of the help strings.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>False for the help strings Translate returns when nothing matched.</summary>
|
||||
public static bool IsAnswer(string translation) =>
|
||||
!string.IsNullOrWhiteSpace(translation) && translation != PasteHint && translation != NoMatchHint;
|
||||
|
||||
/// <summary>True when the line starts like an incoming guardian tell / say.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The guardian to give the item to, read from an incoming line (Attribute when unclear).</summary>
|
||||
public static string TurnInNpcFromLine(string raw)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(raw) && raw.Contains(TempleGuardian, StringComparison.OrdinalIgnoreCase))
|
||||
return TempleGuardian;
|
||||
return AttributeGuardian;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The quoted message of a guardian line ("... tells you, \"text\"" → text); the line itself otherwise.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,114 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>A yes/no question waiting for the player (a modal over the Mini Remote).</summary>
|
||||
internal sealed class IltConfirmRequest
|
||||
{
|
||||
public string Title = "Confirm";
|
||||
public string Message = string.Empty;
|
||||
public string YesLabel = "Yes";
|
||||
/// <summary>Runs on the pump thread after the player clicks Yes.</summary>
|
||||
public Action? OnYes;
|
||||
}
|
||||
|
||||
internal sealed class IltHubContext
|
||||
{
|
||||
private readonly ConcurrentQueue<Action> _posted = new();
|
||||
private readonly ConcurrentQueue<IltConfirmRequest> _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; }
|
||||
|
||||
/// <summary>RynthILT's settings (the server list). Edits are saved through <see cref="SaveSettings"/>.</summary>
|
||||
public IltSettings Settings { get; }
|
||||
|
||||
/// <summary>Saves <see cref="Settings"/> (pump thread).</summary>
|
||||
public void SaveSettings() => IltSettingsStore.Save(Settings);
|
||||
|
||||
/// <summary>RynthAi's services (the Mini Remote, /myquests, spell names, loot matching); each says when RynthAi is missing.</summary>
|
||||
public RynthAiClient Ai { get; }
|
||||
|
||||
/// <summary>Logged-in character name (resolved at login).</summary>
|
||||
public string CharName = string.Empty;
|
||||
|
||||
/// <summary>True when the Mini Remote is on screen (features use it to gate auto-refreshes).</summary>
|
||||
public bool WindowOpen => State.WindowVisible;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public Action<IltSection>? ShowTab;
|
||||
|
||||
/// <summary>Writes a local chat line (never sent to the server).</summary>
|
||||
public void Chat(string text)
|
||||
{
|
||||
if (Host.HasWriteToChat) Host.WriteToChat(text, 1);
|
||||
}
|
||||
|
||||
/// <summary>Queues work for the next pump tick (safe from the render thread).</summary>
|
||||
public void Post(Action action) => _posted.Enqueue(action);
|
||||
|
||||
/// <summary>Asks the player to confirm before <paramref name="onYes"/> runs on the pump thread.</summary>
|
||||
public void Confirm(string title, string message, Action onYes, string yesLabel = "Yes")
|
||||
=> _confirms.Enqueue(new IltConfirmRequest { Title = title, Message = message, OnYes = onYes, YesLabel = yesLabel });
|
||||
|
||||
/// <summary>Render thread: takes the next pending confirmation, if any.</summary>
|
||||
public bool TryTakeConfirm(out IltConfirmRequest request) => _confirms.TryDequeue(out request!);
|
||||
|
||||
/// <summary>Pump thread: runs everything posted since the last tick.</summary>
|
||||
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"); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Elapsed-ms clock used for every Hub timer.</summary>
|
||||
public static long NowMs => Environment.TickCount64;
|
||||
}
|
||||
|
||||
/// <summary>Contract every Hub feature module implements.</summary>
|
||||
internal interface IIltFeature
|
||||
{
|
||||
/// <summary>Pump-thread tick (~every plugin tick).</summary>
|
||||
void Tick(long nowMs);
|
||||
|
||||
/// <summary>Pump-thread chat line. Return true to hide the line from the chat window.</summary>
|
||||
bool OnChat(string text);
|
||||
|
||||
/// <summary>Logout / teardown: stop automation, drop transient state.</summary>
|
||||
void OnLogout();
|
||||
}
|
||||
|
|
@ -1,870 +0,0 @@
|
|||
// 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<IIltFeature> _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;
|
||||
/// <summary>How often the other characters' saved balances are re-read for the bank export.</summary>
|
||||
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<IltBankExport.Row> _siblings = new();
|
||||
|
||||
public IltBanking Banking { get; }
|
||||
public IltSessionRates Rates { get; }
|
||||
/// <summary>The quest bonus list (/qb): the Quests tab's section and the Temple tracker's stamps.</summary>
|
||||
public IltQuestBonus QuestBonus { get; }
|
||||
/// <summary>The /pets and /shinies logs (the Pets tab's section).</summary>
|
||||
public IltPetLogs PetLogs { get; }
|
||||
/// <summary>The pet breeding tracker (the Pets tab's Breeding sub-tab, and the "RynthILT.Data" breeding JSON).</summary>
|
||||
public IltPetBreeding Breeding { get; }
|
||||
/// <summary>The Pets tab's ACECustom sections: pet charms, the summon-from-empty refill path, siphon auto-capture.</summary>
|
||||
public IltPetAutomation PetAutomation { get; }
|
||||
public IltProgression Progression { get; }
|
||||
public IltGear Gear { get; }
|
||||
public IltGames Games { get; }
|
||||
/// <summary>Registry charm acquired / active / server state (the Charms tab and RynthILTGetCharmsJson).</summary>
|
||||
public IltCharmTracker Charms { get; }
|
||||
/// <summary>The Mini Remote's Charms tab (registry charms with toggles, the Guardian Hand).</summary>
|
||||
public IltCharms CharmsTab { get; }
|
||||
/// <summary>Temple guardians: riddle translator, hand-in, attribute turn-in tracker.</summary>
|
||||
public IltGuardian Guardian { get; }
|
||||
/// <summary>Vaulted Dungeons keeper (Mini Remote tab). ILT-only and behind its master switch (State.VaultedDungeonsEnabled), off by default.</summary>
|
||||
public IltVaultedDungeons VaultedDungeons { get; }
|
||||
/// <summary>The Empyrean Handler's lethal ring: asks RynthAi to back away (RynthAi.Hub BackAwayFrom).</summary>
|
||||
public IltRingEvade RingEvade { get; }
|
||||
/// <summary>T11 gear: the "/aug" wield counters for RynthAi's loot rules, "/ilt t11".</summary>
|
||||
public IltT11 T11 { get; }
|
||||
|
||||
/// <param name="writesBlocked">True while this character's copy from RynthAi is unfinished (IltHubStore.WritesBlocked).</param>
|
||||
/// <param name="legacyFolder">The character's RynthAi folder while that copy is unfinished (read-only fallback).</param>
|
||||
public IltHubController(RynthCoreHost host, string charFolder, IltSettings settings, RynthAiClient ai,
|
||||
Func<bool>? 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);
|
||||
_features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, PetAutomation, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, VaultedDungeons, Guardian, RingEvade, T11 });
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public string ProfileJson => _profileJson;
|
||||
|
||||
/// <summary>Rebuilds <see cref="ProfileJson"/> from the current server options. Pump thread.</summary>
|
||||
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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public string CharmsJson
|
||||
{
|
||||
get { System.Threading.Interlocked.Exchange(ref _charmsReadAt, IltHubContext.NowMs); return _charmsJson; }
|
||||
}
|
||||
|
||||
/// <summary>The bank JSON ("RynthILT.Data" GetBankJson), as <see cref="CharmsJson"/>.</summary>
|
||||
public string BankJson
|
||||
{
|
||||
get { System.Threading.Interlocked.Exchange(ref _bankReadAt, IltHubContext.NowMs); return _bankJson; }
|
||||
}
|
||||
|
||||
/// <summary>A reader's charm Toggle, posted to the pump (IltCharms checks the id). Any thread.</summary>
|
||||
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
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// The pet breeding JSON ("RynthILT.Data" GetPetBreedingJson).
|
||||
/// Reading it keeps the tracker scanning; "" off an ILT world or before its first scan. Any thread.
|
||||
/// </summary>
|
||||
public string PetBreedingJson => _ctx.Options.IsIltLikeWorld ? Breeding.ReaderJson : string.Empty;
|
||||
|
||||
/// <summary>A reader's breeding verb line, posted to the pump (IltPetBreeding.RunVerb). Any thread.</summary>
|
||||
public void RequestBreedingVerb(string line)
|
||||
=> _ctx.Post(() =>
|
||||
{
|
||||
if (!_ctx.Options.IsIltLikeWorld) return;
|
||||
Breeding.RunVerb(line);
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// The Temple guardian JSON ("RynthILT.Data" GetGuardianJson): switches, last answer, hand-in
|
||||
/// status and attribute turn-ins. "" off an ILT world. Any thread.
|
||||
/// </summary>
|
||||
public string GuardianJson => _ctx.Options.IsIltLikeWorld ? Guardian.ReaderJson(_ctx.Options.WorldName) : string.Empty;
|
||||
|
||||
/// <summary>A reader's guardian verb line, posted to the pump (IltGuardian.RunVerb). Any thread.</summary>
|
||||
public void RequestGuardianVerb(string line)
|
||||
=> _ctx.Post(() =>
|
||||
{
|
||||
if (!_ctx.Options.IsIltLikeWorld) return;
|
||||
Guardian.RunVerb(line);
|
||||
});
|
||||
|
||||
/// <summary>A reader's bank verb line, posted to the pump (IltBanking.RunVerb). Any thread.</summary>
|
||||
public void RequestBankVerb(string line)
|
||||
=> _ctx.Post(() =>
|
||||
{
|
||||
if (!_ctx.Options.IsIltLikeWorld) return;
|
||||
Banking.RunVerb(line);
|
||||
_bankBuiltAt = 0;
|
||||
});
|
||||
|
||||
/// <summary>Pump: rebuilds the charms / bank snapshots a reader is watching.</summary>
|
||||
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;
|
||||
if (!bankWatched || 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<IltBankExport.Row>(_siblings.Count + 1) { new(me, true, _ctx.State.Bank) };
|
||||
rows.AddRange(_siblings);
|
||||
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;
|
||||
|
||||
/// <summary>World is ILT-like and the server has at least one ILT feature on.</summary>
|
||||
public bool Available => _ctx.Options.IsIltLikeWorld && _ctx.Options.AnyFeatureOn;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="SectionAvailable"/>.
|
||||
/// </summary>
|
||||
public bool OffersTabs => _ctx.Options.IsIltLikeWorld;
|
||||
|
||||
/// <summary>Whether the Mini Remote's tab bar shows <paramref name="section"/>.</summary>
|
||||
public bool TabShown(IltSection section) => OffersTabs && IltSections.IsTab(section) && SectionAvailable(section);
|
||||
|
||||
/// <summary>Render thread: one Mini Remote ILT tab's body (RynthAi's MiniRemoteHud draws the tab bar).</summary>
|
||||
public void RenderTab(IltSection section) => _ui.RenderTab(section);
|
||||
|
||||
/// <summary>Render thread: a tab was just drawn as RynthCore's section view (it counts as the Mini Remote on screen).</summary>
|
||||
public void NoteTabDrawn() => System.Threading.Interlocked.Exchange(ref _tabDrawnAt, IltHubContext.NowMs);
|
||||
|
||||
/// <summary>
|
||||
/// 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").
|
||||
/// </summary>
|
||||
public void RenderRatesSection() => _ui.RenderRatesSection();
|
||||
|
||||
/// <summary>Render thread: the /qb list in RynthILT's own Quests section (surface "section:ilt-questbonus").</summary>
|
||||
public void RenderQuestBonusSection() => _ui.RenderQuestBonusSection();
|
||||
|
||||
/// <summary>Render thread: the Guardian panel's body (RynthPluginRenderEmbed "guardian").</summary>
|
||||
public void RenderGuardianPanel() => _ui.RenderGuardianPanel();
|
||||
|
||||
/// <summary>Render thread: one of the sections RynthAi draws (RynthILT.Hub RenderSection); false = nothing drawn.</summary>
|
||||
public bool RenderSection(string id) => _ui.RenderSection(id);
|
||||
|
||||
/// <summary>The Force-ILT world override (world identity only; features still come from the server). Set from any thread.</summary>
|
||||
public bool ForceIltWorld
|
||||
{
|
||||
get => _ctx.State.ForceLeaftideFeatures;
|
||||
set => _forceRequest = value ? 1 : 0;
|
||||
}
|
||||
|
||||
/// <summary>Re-asks the server which features are on (safe from the render thread: posted to the pump).</summary>
|
||||
public void RequestOptionsRefresh() => _ctx.Post(() => _ctx.Options.Refresh(manual: true));
|
||||
|
||||
// ── Lifecycle ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Login: remember the character, schedule the options check, import UB data once.
|
||||
/// <paramref name="forceFromMigration"/>: the character's RynthAi profile had "Force enable" ticked.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A RynthAi /myquests refresh ended since the last look: tell the options (the "quests" bit).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Pump-thread tick.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A creature's health update from the server (RynthPluginOnUpdateHealth): auto-capture's fallback health read.</summary>
|
||||
public void OnUpdateHealth(uint objectId, float healthRatio)
|
||||
{
|
||||
if (!_ctx.Options.IsIltLikeWorld) return;
|
||||
PetAutomation.NoteHealth(objectId, healthRatio);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public (string Id, string Label)[] SubTabs(string parent)
|
||||
{
|
||||
if (!string.Equals(parent, RynthCore.Plugin.Shared.RynthIltHub.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") };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// RynthILT.Hub GetSetting: a setting another plugin mirrors (RynthIltHub.Setting*), -1 when not offered
|
||||
/// (unknown key, or off an ILT world: the engine row then hides). Any thread.
|
||||
/// </summary>
|
||||
public int GetSetting(string key) => key switch
|
||||
{
|
||||
RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons when _ctx.Options.IsIltLikeWorld
|
||||
=> _ctx.State.VaultedDungeonsEnabled ? 1 : 0,
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// RynthILT.Hub GetText: a short text RynthAi shows (RynthIltHub.Text*); "" for an unknown id, and
|
||||
/// the session tail off ILT. Any thread.
|
||||
/// </summary>
|
||||
public string GetText(string id) => id switch
|
||||
{
|
||||
RynthCore.Plugin.Shared.RynthIltHub.TextServerId => IltSectionsManifest.Server,
|
||||
RynthCore.Plugin.Shared.RynthIltHub.TextSessionReport when _ctx.Options.IsIltLikeWorld => _ui.SessionReportTail(),
|
||||
_ => string.Empty,
|
||||
};
|
||||
|
||||
/// <summary>RynthILT.Hub SetSetting: false for an unknown key. Saved with the state (next periodic save). Any thread.</summary>
|
||||
public bool SetSetting(string key, int value)
|
||||
{
|
||||
if (key != RynthCore.Plugin.Shared.RynthIltHub.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;
|
||||
}
|
||||
|
||||
/// <summary>The server's killer notification (pump thread): restarts the Vaulted Dungeons no-kill timer, on ILT only.</summary>
|
||||
public void OnKillNotification()
|
||||
{
|
||||
if (!_ctx.Options.IsIltLikeWorld) return;
|
||||
try { VaultedDungeons.OnKillNotification(); }
|
||||
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "VaultedDungeons.OnKillNotification"); }
|
||||
}
|
||||
|
||||
/// <summary>Pump-thread chat line. Returns true when the line should be hidden.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Maps a feature module to its diagnostics category so its trace/exception lines land in its own file.</summary>
|
||||
private static LogCat CategoryOf(IIltFeature f) => f switch
|
||||
{
|
||||
IltBanking => LogCat.IltBanking,
|
||||
IltPetLogs or IltPetBreeding or IltPetAutomation => LogCat.IltPets,
|
||||
IltSessionRates => LogCat.IltRates,
|
||||
IltQuestBonus => LogCat.IltQuests,
|
||||
IltProgression => LogCat.IltProgression,
|
||||
IltGear or IltCharms => LogCat.IltGear,
|
||||
IltGames => LogCat.IltGames,
|
||||
IltVaultedDungeons => LogCat.IltHub,
|
||||
_ => LogCat.IltHub,
|
||||
};
|
||||
|
||||
/// <summary>Logout / teardown: stop automation and flush to disk.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>JSON for RynthILTGetCharmsJson / RynthPluginGetCharmsJson (an older engine's Settings "Charms Tracking" tab). Pump thread.</summary>
|
||||
public string BuildCharmsJson() => Charms.BuildJson();
|
||||
|
||||
/// <summary>Render thread: Games HUD and confirmation popups.</summary>
|
||||
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 ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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 <name> [shared]|load <name> /ra hub suit list|test|load [name]");
|
||||
_ctx.Chat("[Mini Remote] /ra hub attr run|stop|costs|status|auto on|off|every <min>|raise <stat> <n> (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 <text>|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;
|
||||
}
|
||||
|
||||
/// <summary>"/ra hub features": every Leaftide feature RynthILT supports, with the server's state for each.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>"/ra hub servers [list | <names, comma separated> | default]": which world names count as Infinite Leaftide.</summary>
|
||||
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<string>(ServerFeatureGate.DefaultServerNames)
|
||||
: ServerFeatureGate.ParseList(arg);
|
||||
if (list.Count == 0) { _ctx.Chat("[Mini Remote] Usage: /ra hub servers <name, *pattern*, ...> | 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));
|
||||
}
|
||||
|
||||
/// <summary>"/ra hub attr ...": the attribute raiser from chat (same verbs as the Progression tab).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"/ra bounty", "/ra bounties" and the "/ra bountys" spelling all reach the Bounties panel.</summary>
|
||||
public static bool IsBountyVerb(string verb)
|
||||
=> verb.Equals("bounty", StringComparison.OrdinalIgnoreCase)
|
||||
|| verb.Equals("bounties", StringComparison.OrdinalIgnoreCase)
|
||||
|| verb.Equals("bountys", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Applies show / hide / toggle to a section: a Mini Remote tab, or for the Guardian
|
||||
/// RynthCore's ILT panel. Says what happened.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens / closes one of RynthCore's ILT panels ("/rc bounties|guardian [show|hide|toggle]")
|
||||
/// through the engine's chat dispatcher. Pump thread.
|
||||
/// </summary>
|
||||
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}.");
|
||||
}
|
||||
|
||||
/// <summary>"show"/"on" → true, "hide"/"off" → false, anything else flips <paramref name="current"/>.</summary>
|
||||
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 <name> [shared] | load <name>"); 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 ─────────────────────────
|
||||
|
||||
/// <summary>How long a "/ra hub confirm" stays valid after the prompt.</summary>
|
||||
private const long ConfirmWindowMs = 20000;
|
||||
|
||||
private string? _pendingLabel;
|
||||
private Action? _pendingAction;
|
||||
private long _pendingAt;
|
||||
|
||||
/// <summary>Arms a single pending action; a newer request replaces an older one.</summary>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>Runs the pending action if one is armed and still inside its window.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,364 +0,0 @@
|
|||
// 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\<world>\<char>\hub.json (IltHubStore). The first
|
||||
// login with RynthILT copies RynthAi's <charFolder>\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;
|
||||
|
||||
/// <summary>Root of everything the Hub remembers between sessions.</summary>
|
||||
public sealed class IltHubState
|
||||
{
|
||||
/// <summary>Bumped when the shape changes in a way that needs a migration.</summary>
|
||||
public int SchemaVersion = 1;
|
||||
|
||||
// ── Window / shell ──────────────────────────────────────────────────────
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public bool WindowVisible;
|
||||
/// <summary>Unused since the tabbed Hub window was retired; kept so old files still load.</summary>
|
||||
public int SelectedTab;
|
||||
public bool GamesHudVisible = true;
|
||||
|
||||
/// <summary>
|
||||
/// "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.
|
||||
/// </summary>
|
||||
public bool ForceLeaftideFeatures;
|
||||
|
||||
/// <summary>True once the one-time UtilityBelt sidecar import has run for this character.</summary>
|
||||
public bool UbSidecarsImported;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public bool RynthAiSettingsImported;
|
||||
|
||||
/// <summary>Last-seen server feature bits. Cache only — overwritten by every login refresh.</summary>
|
||||
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();
|
||||
/// <summary>Infinite Leaftide combat helpers (moved from RynthAi's profile 2026-10-20).</summary>
|
||||
public IltCombatState Combat = new();
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public bool VaultedDungeonsEnabled;
|
||||
|
||||
/// <summary>ACECustom T11 gear (IltT11): the item-aug override (moved from RynthAi's profile 2026-10-20).</summary>
|
||||
public IltT11State T11 = new();
|
||||
|
||||
/// <summary>The ILT sections of RynthAi's Remote tab (moved from RynthAi's huds.json 2026-10-20).</summary>
|
||||
public IltRemoteState Remote = new();
|
||||
}
|
||||
|
||||
// ── RynthAi's Remote tab ────────────────────────────────────────────────────
|
||||
|
||||
public sealed class IltRemoteState
|
||||
{
|
||||
/// <summary>The Remote tab's Bank section (ILT bank balances). Was RynthAi's MiniShowBank.</summary>
|
||||
public bool ShowBank = true;
|
||||
/// <summary>The Remote tab's Guardian line (the last Temple guardian answer). Was RynthAi's MiniShowGuardian.</summary>
|
||||
public bool ShowGuardian = true;
|
||||
}
|
||||
|
||||
// ── T11 ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
public sealed class IltT11State
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public int ItemAugsOverride = -1;
|
||||
}
|
||||
|
||||
// ── Combat ──────────────────────────────────────────────────────────────────
|
||||
|
||||
public sealed class IltCombatState
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public bool HandlerRingEvade = true;
|
||||
}
|
||||
|
||||
/// <summary>Cached result of the server-options check (see IltServerOptions).</summary>
|
||||
public sealed class IltServerOptionsSnapshot
|
||||
{
|
||||
public string WorldName = string.Empty;
|
||||
/// <summary>"probe" (the login probe) or "" (never refreshed).</summary>
|
||||
public string Source = string.Empty;
|
||||
public DateTime LastRefreshUtc = DateTime.MinValue;
|
||||
/// <summary>Feature key → -1 unknown, 0 off, 1 on.</summary>
|
||||
public Dictionary<string, int> 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;
|
||||
/// <summary>Bound to the character: deposit and withdraw only, never transferred.</summary>
|
||||
public long PrestigeCoins;
|
||||
public DateTime LastUpdated = DateTime.MinValue;
|
||||
|
||||
/// <summary>Last transfer recipient typed into the transfer form.</summary>
|
||||
public string TransferTarget = string.Empty;
|
||||
public int TransferCurrencyIndex;
|
||||
/// <summary>Transfer form's trade-note denomination (IltBankCommands.NoteDenominations; 9 = MMD).</summary>
|
||||
public int TransferNoteIndex = 9;
|
||||
|
||||
/// <summary>Deposit / withdraw form choices (IltBankCommands.Deposits / Withdrawals / NoteDenominations).</summary>
|
||||
public int DepositIndex;
|
||||
public int WithdrawIndex;
|
||||
public int WithdrawNoteIndex = 9;
|
||||
|
||||
/// <summary>Re-issue /bank every N seconds while the Hub is open (0 = manual only).</summary>
|
||||
public int AutoRefreshSeconds = 120;
|
||||
}
|
||||
|
||||
/// <summary>One "Transferred …" / "Received …" bank line seen in chat.</summary>
|
||||
public sealed class IltBankTransaction
|
||||
{
|
||||
public DateTime Timestamp;
|
||||
/// <summary>"Sent" or "Received".</summary>
|
||||
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
|
||||
{
|
||||
/// <summary>Last captured /pets and /shinies rosters (display only; the Pets tab's logs).</summary>
|
||||
public List<string> PetLog = new();
|
||||
public List<string> ShinyLog = new();
|
||||
/// <summary>The breeding tracker: rules this server showed, growth stage names, recent events (IltPetBreeding).</summary>
|
||||
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.
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public bool RefillFromEmpty;
|
||||
/// <summary>Use the chosen siphon lens on the nearest creature once it is weak enough (off by default).</summary>
|
||||
public bool AutoCapture;
|
||||
/// <summary>Index into PetCaptureRules.Lenses (Flawed to Asheron's).</summary>
|
||||
public int CaptureLens;
|
||||
// The Pets tab's own settings (roster, healing / cosmetic pets) are RynthAi's (its miniremote.json).
|
||||
}
|
||||
|
||||
// ── Character ───────────────────────────────────────────────────────────────
|
||||
|
||||
public sealed class IltCharacterState
|
||||
{
|
||||
/// <summary>Item → coin conversion table used by the session-rates strip.</summary>
|
||||
public List<IltItemConversion> ItemConversions = new()
|
||||
{
|
||||
new IltItemConversion { ItemName = "Strawberry Jam Jar", ItemsPerConversion = 100, CoinsPerConversion = 10 },
|
||||
new IltItemConversion { ItemName = "Ancient Pyreal", ItemsPerConversion = 100, CoinsPerConversion = 37 },
|
||||
};
|
||||
|
||||
/// <summary>Augmentation planner targets, keyed by aug type (lowercase).</summary>
|
||||
public Dictionary<string, int> AugTargets = new(StringComparer.OrdinalIgnoreCase);
|
||||
/// <summary>Luminance price of one Enlightened Coin (planner math only; 0 = don't price coins).</summary>
|
||||
public long LumPerEnlightenedCoin;
|
||||
|
||||
/// <summary>Enlightenment planner target level (0 = current + 5).</summary>
|
||||
public int EnlTargetLevel;
|
||||
public int EnlightenedCoinsPerToken = 20;
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public bool AutoEnlightenEnabled;
|
||||
public int AutoEnlightenCheckSeconds = 30;
|
||||
/// <summary>Spend unassigned XP with /attr before sending /enl (enlightening wipes unspent XP).</summary>
|
||||
public bool AutoEnlightenSpendXpFirst;
|
||||
|
||||
// ── Attribute raiser (IltAttributeRaiser; Skills panel > Progression) ──
|
||||
/// <summary>Spend unassigned XP on the ticked attributes/vitals every AttrAutoRaiseMinutes.</summary>
|
||||
public bool AttrAutoRaise;
|
||||
public int AttrAutoRaiseMinutes = 5;
|
||||
/// <summary>IltAttributeRaiser.Mode: 0 priority (top of the order first), 1 round robin, 2 cheapest first.</summary>
|
||||
public int AttrRaiseMode;
|
||||
/// <summary>Unassigned XP the raiser never spends.</summary>
|
||||
public long AttrKeepXp;
|
||||
/// <summary>/attr abbreviations in raise-priority order (all nine; repaired on load).</summary>
|
||||
public List<string> AttrOrder = new(IltAttributeRaiser.DefaultOrder);
|
||||
/// <summary>/attr abbreviations the raiser may spend on ("Raise now" and auto-raise).</summary>
|
||||
public List<string> AttrRaiseStats = new();
|
||||
|
||||
/// <summary>Quest bonus (/qb) list filter. (The /myquests tracker's filter and favorites are RynthAi's.)</summary>
|
||||
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.
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public Dictionary<string, IltCharmSeen> CharmsSeen = new(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>Last time a charm was seen in the character's possession, with its best tier.</summary>
|
||||
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;
|
||||
/// <summary>Spell-name substrings that are ALWAYS dispelled.</summary>
|
||||
public List<string> DispelInclusions = new();
|
||||
/// <summary>Spell-name substrings that are NEVER dispelled.</summary>
|
||||
public List<string> 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;
|
||||
/// <summary>
|
||||
/// Only chunk aetheria whose max level is below this (Coalesced Aetheria too). Infinite Leaftide
|
||||
/// aetheria goes up to level <see cref="IltInventory.AetheriaMaxLevel"/>, so the cap runs to one past it.
|
||||
/// </summary>
|
||||
public int ChunkAetheriaUnderLevel = 4;
|
||||
/// <summary>Never chunk aetheria carrying a Crit rating (C, GearCrit 372; ILT tier-10 sigils of level 6+).</summary>
|
||||
public bool KeepAetheriaWithCrit = true;
|
||||
/// <summary>Never chunk aetheria carrying a Crit Damage rating (CD, GearCritDamage 374).</summary>
|
||||
public bool KeepAetheriaWithCritDamage = true;
|
||||
/// <summary>Never chunk aetheria carrying a Crit Damage Resist rating (CDR, GearCritDamageResist 375).</summary>
|
||||
public bool KeepAetheriaWithCritDamageResist = true;
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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.
|
||||
/// <summary>Never chunk a corrupted weapon with Crushing Blow (CriticalFrequency float 147 > 0).</summary>
|
||||
public bool KeepCorruptedCrushingBlow;
|
||||
/// <summary>Never chunk a corrupted weapon with Biting Strike (CriticalMultiplier float 136 > 0).</summary>
|
||||
public bool KeepCorruptedBitingStrike;
|
||||
/// <summary>Never chunk a corrupted weapon with Armor Cleaving (IgnoreArmor float 155 > 0).</summary>
|
||||
public bool KeepCorruptedArmorCleaving;
|
||||
/// <summary>Never chunk a corrupted weapon with any slayer (SlayerCreatureType int 166 > 0).</summary>
|
||||
public bool KeepCorruptedAnySlayer;
|
||||
/// <summary>Never chunk a multi-strike corrupted weapon (AttackType int 47 = 160 / 166 / 486).</summary>
|
||||
public bool KeepCorruptedMultiStrike;
|
||||
/// <summary>Never chunk a corrupted weapon with an elemental damage bonus (int 204 > 0).</summary>
|
||||
public bool KeepCorruptedElementalBonus;
|
||||
/// <summary>Never chunk a corrupted weapon with any spell on it.</summary>
|
||||
public bool KeepCorruptedAnySpell;
|
||||
/// <summary>Never chunk a corrupted weapon whose max damage (int 44) is at least this. 0 = off.</summary>
|
||||
public int KeepCorruptedMaxDamageAtLeast;
|
||||
/// <summary>Spell ids (comma / space separated): never chunk a corrupted weapon carrying any of them.</summary>
|
||||
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)
|
||||
/// <summary>Recipe id (IltRingChain.Recipes) to how many times to craft it. Pump thread only.</summary>
|
||||
public Dictionary<string, int> RingRuns = new(StringComparer.OrdinalIgnoreCase);
|
||||
/// <summary>Answer the server's craft dialog Yes for the queued combines (engine API v85).</summary>
|
||||
public bool RingAnswerCraftDialog = true;
|
||||
/// <summary>Craft and inscribe in combat mode too (servers with combat-mode crafting).</summary>
|
||||
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
|
||||
{
|
||||
/// <summary>Translate incoming guardian tells and show the answer (Guardian window + Mini Remote).</summary>
|
||||
public bool AutoDetectFromChat = true;
|
||||
/// <summary>After a chat answer, give the item to the guardian automatically.</summary>
|
||||
public bool AutoHandIn;
|
||||
/// <summary>Temple guardian only: buy one of the item from the nearest vendor when none is carried.</summary>
|
||||
public bool BuyMissingFromVendor = true;
|
||||
|
||||
/// <summary>Assumed attribute turn-in cooldown when only /qb wait stamps are known (hours).</summary>
|
||||
public int CooldownHoursAssumed = 20;
|
||||
/// <summary>Turn-ins counted from /qb wait-stamp transitions, keyed by attribute (fallback when /myquests lacks the flag).</summary>
|
||||
public Dictionary<string, int> TurnInCounts = new(StringComparer.OrdinalIgnoreCase);
|
||||
/// <summary>Estimated end of each attribute's cooldown (UTC), keyed by attribute (same fallback).</summary>
|
||||
public Dictionary<string, DateTime> CooldownUntilUtc = new(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
|
@ -1,494 +0,0 @@
|
|||
// 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; <char> = <world>\<character>):
|
||||
// <char>\hub.json live Hub state (IltHubState)
|
||||
// <char>\bank-transactions.json bank transaction log (capped)
|
||||
// <char>\profiles\<n>.json named per-character Hub profiles
|
||||
// Profiles\<n>.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
|
||||
{
|
||||
/// <summary>Maximum bank transactions kept on disk (oldest dropped first).</summary>
|
||||
public const int MaxTransactions = 1000;
|
||||
|
||||
/// <summary>RynthILT's folder: shared profiles, aug costs and equipment suits (overridable for the tests).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public Func<bool> WritesBlocked = static () => false;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public string? LegacyFolder;
|
||||
|
||||
private bool Blocked()
|
||||
{
|
||||
try { return WritesBlocked(); }
|
||||
catch { return true; }
|
||||
}
|
||||
|
||||
/// <summary>A RynthAi original read without locking it (it may be held open elsewhere). Null when it can't be.</summary>
|
||||
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 ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Loads the live state, returning defaults when the file is missing or unreadable.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Writes the state only when its JSON differs from the last write.</summary>
|
||||
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}"); }
|
||||
}
|
||||
|
||||
/// <summary>Repairs null collections / out-of-range values after deserialization.</summary>
|
||||
private static void Normalize(IltHubState s)
|
||||
{
|
||||
s.ServerOptions ??= new IltServerOptionsSnapshot();
|
||||
s.ServerOptions.Bits = new Dictionary<string, int>(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<string, int>(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<string, IltCharmSeen>(s.Character.CharmsSeen ?? new(), StringComparer.OrdinalIgnoreCase);
|
||||
s.Gear ??= new IltGearState();
|
||||
s.Gear.DispelInclusions ??= new();
|
||||
s.Gear.DispelExclusions ??= new();
|
||||
s.Gear.RingRuns = new Dictionary<string, int>(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<string, int>(s.Guardian.TurnInCounts ?? new(), StringComparer.OrdinalIgnoreCase);
|
||||
s.Guardian.CooldownUntilUtc = new Dictionary<string, DateTime>(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<IltBankTransaction> 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<IltBankTransaction>();
|
||||
}
|
||||
|
||||
public void SaveTransactionsIfDirty(List<IltBankTransaction> 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 ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Lists profile names. Shared ones are prefixed "shared:".</summary>
|
||||
public List<string> ListProfiles()
|
||||
{
|
||||
var names = new List<string>();
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(CharProfileDir))
|
||||
names.AddRange(Directory.GetFiles(CharProfileDir, "*.json").Select(Path.GetFileNameWithoutExtension).OfType<string>());
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Saves the preference parts of <paramref name="state"/> as a named profile.</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads a profile onto <paramref name="target"/>, keeping runtime data (balances,
|
||||
/// server bits, rosters, import flag) from the current state.
|
||||
/// </summary>
|
||||
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();
|
||||
|
||||
/// <summary>Removes character-specific runtime data before a profile is written.</summary>
|
||||
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 ──────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public string ImportUbSidecars(IltHubState state, List<IltBankTransaction> 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<string>();
|
||||
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<IltBankTransaction> 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<IltItemConversion> 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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Write-then-rename so a crash mid-write never leaves a truncated file.</summary>
|
||||
private static void WriteAtomic(string path, string contents)
|
||||
{
|
||||
string tmp = path + ".tmp";
|
||||
File.WriteAllText(tmp, contents);
|
||||
File.Move(tmp, path, overwrite: true);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,401 +0,0 @@
|
|||
// 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);
|
||||
|
||||
/// <summary>Where a server is forced now (the only place: RynthCore's Options window).</summary>
|
||||
private const string ForceHint = "To force a server, use RynthCore Options > Diagnostics > server selection (/rc diagnostics).";
|
||||
|
||||
/// <summary>RynthCore's command that opens Options > Diagnostics (RynthCore 2026.10.5.54+).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The floating extras: Games HUD and the confirmation modal.</summary>
|
||||
public void Render()
|
||||
{
|
||||
_hub.Games.RenderHud();
|
||||
RenderConfirm();
|
||||
}
|
||||
|
||||
/// <summary>Draws one Mini Remote ILT tab's body into the current (child) window.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public void RenderRatesSection()
|
||||
{
|
||||
if (!_hub.Available)
|
||||
{
|
||||
RenderHeader();
|
||||
RenderUnavailable();
|
||||
return;
|
||||
}
|
||||
_hub.Rates.Render(extrasOnly: true);
|
||||
ImGui.TextDisabled("XP planner, Augmentations and Enlightenment: Skills panel > Progression.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public void RenderQuestBonusSection()
|
||||
{
|
||||
if (!_ctx.Options.IsIltLikeWorld)
|
||||
{
|
||||
RenderHeader();
|
||||
RenderUnavailable();
|
||||
return;
|
||||
}
|
||||
_hub.QuestBonus.RenderQb();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One of the ILT pieces RynthAi draws in its own surfaces (RynthIltHub.Section*). False when
|
||||
/// there is nothing to draw (unknown id, or not an ILT world).
|
||||
/// </summary>
|
||||
public bool RenderSection(string id)
|
||||
{
|
||||
var o = _ctx.Options;
|
||||
switch (id)
|
||||
{
|
||||
case RynthIltHub.SectionRemoteBank:
|
||||
if (!o.IsIltLikeWorld || o.IsOff(IltFeature.Bank) || !_ctx.State.Remote.ShowBank) return false;
|
||||
RenderRemoteBank();
|
||||
return true;
|
||||
case RynthIltHub.SectionRemoteGuardian:
|
||||
if (!o.IsIltLikeWorld || !_ctx.State.Remote.ShowGuardian) return false;
|
||||
_hub.Guardian.RenderRemoteLine();
|
||||
return true;
|
||||
case RynthIltHub.SectionRemoteStats:
|
||||
if (!o.IsIltLikeWorld) return false;
|
||||
RenderRemoteStats();
|
||||
return true;
|
||||
case RynthIltHub.SectionRemoteOptions:
|
||||
if (!o.IsIltLikeWorld) return false;
|
||||
RenderRemoteOptions();
|
||||
return true;
|
||||
case RynthIltHub.SectionQuestBonus:
|
||||
if (!o.IsIltLikeWorld) return false;
|
||||
_hub.QuestBonus.RenderSection();
|
||||
return true;
|
||||
case RynthIltHub.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 RynthIltHub.SectionPetCharms:
|
||||
if (!o.IsIltLikeWorld) return false;
|
||||
_hub.PetAutomation.RenderCharms();
|
||||
return true;
|
||||
case RynthIltHub.SectionPetCapture:
|
||||
if (!o.IsIltLikeWorld) return false;
|
||||
_hub.PetAutomation.RenderCapture();
|
||||
return true;
|
||||
case RynthIltHub.SectionIltStatus:
|
||||
return RenderIltStatus();
|
||||
case RynthIltHub.SectionServerMenu:
|
||||
return RenderLocalMenu();
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public void RenderGuardianPanel()
|
||||
{
|
||||
if (!_hub.SectionAvailable(IltSection.Guardian))
|
||||
{
|
||||
RenderHeader();
|
||||
ImGui.Separator();
|
||||
RenderUnavailable();
|
||||
return;
|
||||
}
|
||||
_hub.Guardian.Render();
|
||||
}
|
||||
|
||||
/// <summary>A button that opens a moved section's new home (posted: the command runs on the pump).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The world and when the server's ILT features were last read, with a Refresh.</summary>
|
||||
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 ──
|
||||
|
||||
/// <summary>Coins and pyreals per hour under RynthAi's per-hour lines (the Remote tab's Stats).</summary>
|
||||
private void RenderRemoteStats()
|
||||
{
|
||||
var r = _hub.Rates.Summary;
|
||||
Stat("Coins:", Compact(r.CoinsPerHour) + "/h");
|
||||
Stat("Pyr:", Compact(r.PyrealsPerHour) + "/h");
|
||||
}
|
||||
|
||||
/// <summary>The Remote tab's ILT sections' switches, in RynthAi's Options popup.</summary>
|
||||
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).");
|
||||
}
|
||||
|
||||
/// <summary>The tail of RynthAi's one-line session report: the coin / pyreal rates (RynthIltHub.TextSessionReport).</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>The Bank line's link to RynthILT's own Banking tab (Infinite Leaftide's bank stays RynthILT's).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The Mini Remote's compact numbers (RynthAi's HudDraw.Compact): 12.3k, 4.5m, 1.2b.</summary>
|
||||
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 ──────────
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,391 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </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).
|
||||
/// <summary>ACE PropertyInt.Damage — a weapon's max damage.</summary>
|
||||
public const uint IntDamage = 44;
|
||||
/// <summary>ACE PropertyInt.AttackType — 2 = thrust; 160 / 166 / 486 are the multi-strike masks.</summary>
|
||||
public const uint IntAttackType = 47;
|
||||
/// <summary>ACE PropertyInt.ItemWorkmanship — loot-gen Craft (salvage-bag workmanship is not on weapons).</summary>
|
||||
public const uint IntItemWorkmanship = 105;
|
||||
/// <summary>ACE PropertyInt.WieldSkillType — 41 (Two Handed Combat) for two-handed weapons.</summary>
|
||||
public const uint IntWieldSkillType = 159;
|
||||
/// <summary>ACE PropertyInt.SlayerCreatureType.</summary>
|
||||
public const uint IntSlayerCreatureType = 166;
|
||||
/// <summary>ACE PropertyInt.ElementalDamageBonus.</summary>
|
||||
public const uint IntElementalDamageBonus = 204;
|
||||
/// <summary>ACE PropertyInt.WeaponType — 11 = TwoHanded.</summary>
|
||||
public const uint IntWeaponType = 353;
|
||||
/// <summary>ACE PropertyFloat.CriticalMultiplier — Biting Strike.</summary>
|
||||
public const uint FloatCriticalMultiplier = 136;
|
||||
/// <summary>ACE PropertyFloat.CriticalFrequency — Crushing Blow.</summary>
|
||||
public const uint FloatCriticalFrequency = 147;
|
||||
/// <summary>ACE PropertyFloat.IgnoreArmor — Armor Cleaving.</summary>
|
||||
public const uint FloatIgnoreArmor = 155;
|
||||
public const uint IntItemMaxLevel = 319;
|
||||
/// <summary>Highest aetheria level on Infinite Leaftide (ACECustom AetheriaChance rolls up to 10; retail stops at 5).</summary>
|
||||
public const int AetheriaMaxLevel = 10;
|
||||
/// <summary>Gear ratings ILT aetheria can carry: C, CD and CDR (PropertyInt GearCrit / GearCritDamage / GearCritDamageResist).</summary>
|
||||
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;
|
||||
/// <summary>ACECustom charm item: current tier (PropertyInt.CharmLevel).</summary>
|
||||
public const uint IntCharmLevel = 50005;
|
||||
/// <summary>ACECustom charm item: highest tier for this charm line (PropertyInt.CharmMaxLevel).</summary>
|
||||
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;
|
||||
/// <summary>ACECustom PropertyInt64.BankedLuminance (sent with each XP batch).</summary>
|
||||
public const uint QuadBankedLuminance = 9005;
|
||||
public const uint BoolNeverChunk = 9030;
|
||||
public const uint BoolPyrealRefillActive = 9049;
|
||||
public const uint BoolUniversalMasteryActive = 50038;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
/// <summary>AC's CM_Combat value for peace mode (RynthAi's CombatMode.NonCombat).</summary>
|
||||
private const int CombatModeNonCombat = 1;
|
||||
private readonly Dictionary<int, uint> _wcidCache = new();
|
||||
private readonly Dictionary<int, long> _lastIdRequest = new();
|
||||
|
||||
/// <summary>Don't re-request appraisal for the same object more often than this.</summary>
|
||||
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 ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The client busy hourglass is up (an action is in progress).</summary>
|
||||
public bool IsBusy => _host.HasGetBusyState && _host.GetBusyState() != 0;
|
||||
|
||||
/// <summary>Player is in peace mode (combat mode NonCombat). True when the engine can't tell.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Current/max health from the engine vitals read (0/0 when unavailable).</summary>
|
||||
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 ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>All items the player carries or wears (snapshot).</summary>
|
||||
public IEnumerable<WorldObject> Items() => _cache.GetInventory();
|
||||
|
||||
/// <summary>Weenie class id, cached per object (0 when unknown).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>A float (PropertyFloat) value; 0 when the host cannot read it or the item has none.</summary>
|
||||
public double Double(WorldObject wo, uint stype)
|
||||
=> _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(unchecked((uint)wo.Id), stype, out double v) ? v : 0;
|
||||
|
||||
/// <summary>The spell ids on an item (empty when none or the host cannot read them).</summary>
|
||||
public IReadOnlyList<int> SpellIds(WorldObject wo)
|
||||
{
|
||||
if (!_host.HasGetObjectSpellIds) return Array.Empty<int>();
|
||||
var buf = new uint[64];
|
||||
int n = _host.GetObjectSpellIds(unchecked((uint)wo.Id), buf, buf.Length);
|
||||
if (n <= 0) return Array.Empty<int>();
|
||||
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;
|
||||
|
||||
/// <summary>Stack size (1 for non-stackables).</summary>
|
||||
public int StackSize(WorldObject wo) => Math.Max(1, Int(wo, IntStackSize, 1));
|
||||
|
||||
/// <summary>Remaining uses on a structure item (essences, kits, salvage bags).</summary>
|
||||
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));
|
||||
|
||||
/// <summary>
|
||||
/// 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. <paramref name="quads"/> adds the 64-bit reads
|
||||
/// (item XP), <paramref name="doubles"/> the float reads and <paramref name="spells"/> the
|
||||
/// spell list, for the rules that use them.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Requests appraisal data, throttled per object. Returns true if a request was sent.</summary>
|
||||
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<WorldObject> AllByWcid(params uint[] wcids)
|
||||
=> Items().Where(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0);
|
||||
|
||||
public WorldObject? FindByName(Func<string, bool> predicate)
|
||||
=> Items().FirstOrDefault(wo => predicate(wo.Name));
|
||||
|
||||
/// <summary>Total stack count of items with any of the given WCIDs.</summary>
|
||||
public long CountByWcid(params uint[] wcids)
|
||||
=> AllByWcid(wcids).Sum(wo => (long)StackSize(wo));
|
||||
|
||||
/// <summary>Total stack count of items whose name matches exactly (case-insensitive).</summary>
|
||||
public long CountByName(string name)
|
||||
=> Items().Where(wo => wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Sum(wo => (long)StackSize(wo));
|
||||
|
||||
/// <summary>Total stack count of a sigil-chain item (singular or plural stack name; see IltSigilChain.NameIs).</summary>
|
||||
public long CountByChainName(string chainName)
|
||||
=> Items().Where(wo => IltSigilChain.NameIs(wo.Name, chainName)).Sum(wo => (long)StackSize(wo));
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public bool HasCastingSupplies()
|
||||
=> AllByWcid(WcidInfiniteCastingStone).Any(stone => CharmStatus(stone) != IltTri.Off)
|
||||
|| Items().Any(wo => wo.ObjectClass == AcObjectClass.SpellComponent);
|
||||
|
||||
/// <summary>Free main-pack slots (best effort: capacity minus direct children; -1 when unknown).</summary>
|
||||
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 ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// ON/OFF/Unknown from the appraisal Use text ("... Status: ON"). Requests appraisal
|
||||
/// (throttled) when the text isn't loaded yet.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>Charm definition for an item (by WCID), or null.</summary>
|
||||
public IltCharmDef? CharmDefFor(WorldObject wo)
|
||||
{
|
||||
uint w = Wcid(wo);
|
||||
if (w == 0) return null;
|
||||
return Charms.FirstOrDefault(c => Array.IndexOf(c.Wcids, w) >= 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every charm the player carries: registered WCIDs plus anything whose Use text starts
|
||||
/// with "Charm [Tier" (generic ACECustom charm format, catches charms added later).
|
||||
/// </summary>
|
||||
public List<WorldObject> CarriedCharms()
|
||||
{
|
||||
var list = new List<WorldObject>();
|
||||
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);
|
||||
|
||||
/// <summary>Forgets cached WCIDs / appraisal throttles (logout).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
_wcidCache.Clear();
|
||||
_lastIdRequest.Clear();
|
||||
_cache.Clear();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,196 +0,0 @@
|
|||
// 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 <cat|all> 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;
|
||||
|
||||
/// <summary>One trace category per ILT feature (the names RynthAi's ILT Hub used).</summary>
|
||||
internal enum LogCat
|
||||
{
|
||||
IltHub,
|
||||
IltOptions,
|
||||
IltChat,
|
||||
IltStore,
|
||||
IltBanking,
|
||||
IltPets,
|
||||
IltQuests,
|
||||
IltProgression,
|
||||
IltRates,
|
||||
IltGear,
|
||||
IltGames,
|
||||
}
|
||||
|
||||
/// <summary>Named key events (the ILT Hub's catalogue in RynthAi's RynthLog).</summary>
|
||||
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";
|
||||
/// <summary>/aug ApplyAugLines outcome (Progress Refresh current / login probe).</summary>
|
||||
public const string IltAugLoad = "IltHub.AugLoad";
|
||||
|
||||
/// <summary>Events written as a normal log line; the rest only while their category is traced.</summary>
|
||||
internal static readonly Dictionary<string, (LogCat Cat, bool Info)> 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<string> Pending = new();
|
||||
private static readonly ConcurrentQueue<string> PendingChat = new();
|
||||
private static readonly bool[] Traced = new bool[Enum.GetValues<LogCat>().Length];
|
||||
private static RynthCoreHost _host;
|
||||
private static bool _hasHost;
|
||||
private static string _directory = string.Empty;
|
||||
|
||||
/// <summary>Echo trace and exception lines to the chat window ("/ilt debug on").</summary>
|
||||
public static volatile bool DebugToChat;
|
||||
|
||||
/// <summary>Where the daily files go (tests point it at a scratch folder).</summary>
|
||||
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");
|
||||
}
|
||||
|
||||
/// <summary>Drops the host (plugin shutdown): nothing is written to it afterwards.</summary>
|
||||
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}");
|
||||
}
|
||||
|
||||
/// <summary>True when <see cref="Event"/> would record the event (an Info event, or a traced Trace one).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Every category on or off; returns how many.</summary>
|
||||
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<string>();
|
||||
foreach (LogCat c in Enum.GetValues<LogCat>()) if (IsTracing(c)) on.Add(c.ToString());
|
||||
return on.Count == 0 ? "none" : string.Join(", ", on);
|
||||
}
|
||||
|
||||
/// <summary>Writes the queued lines (plugin pump).</summary>
|
||||
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 { }
|
||||
}
|
||||
|
||||
/// <summary>Queued for the pump (trace lines can come from the render thread).</summary>
|
||||
private static void Chat(string text)
|
||||
{
|
||||
if (PendingChat.Count < 200) PendingChat.Enqueue(text);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,344 +0,0 @@
|
|||
// 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
|
||||
// (<RynthAi>\SettingsProfiles\<world or ACEmulator>\<character>\: 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;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public sealed class IltLegacyProfileFlags
|
||||
{
|
||||
public List<string>? FeatureServerNames;
|
||||
public bool ForceServerFeatures;
|
||||
/// <summary>RynthAi's Empyrean Handler ring evade (on by default there too).</summary>
|
||||
public bool? HandlerRingEvade;
|
||||
/// <summary>RynthAi's Vaulted Dungeons master switch (off by default).</summary>
|
||||
public bool? EnableVaultedDungeons;
|
||||
/// <summary>RynthAi's T11 item-aug override (-1 = automatic).</summary>
|
||||
public int? T11ItemAugsOverride;
|
||||
}
|
||||
|
||||
/// <summary>The Remote tab switches of RynthAi's huds.json that moved to RynthILT (2026-10-20).</summary>
|
||||
public sealed class IltLegacyHuds
|
||||
{
|
||||
public bool? MiniShowBank;
|
||||
public bool? MiniShowGuardian;
|
||||
}
|
||||
|
||||
/// <summary>The Pets tab fields of RynthAi's miniremote.json that moved to RynthILT (2026-10-20).</summary>
|
||||
public sealed class IltLegacyMiniRemote
|
||||
{
|
||||
public IltLegacyPetTab? Pet;
|
||||
}
|
||||
|
||||
public sealed class IltLegacyPetTab
|
||||
{
|
||||
public bool? UsePyrealRefillPath;
|
||||
public bool? AutoCaptureEnabled;
|
||||
public int? CaptureLensIndex;
|
||||
}
|
||||
|
||||
internal static class IltMigration
|
||||
{
|
||||
/// <summary>RynthAi's per-server profile folders (overridable for the tests).</summary>
|
||||
public static string LegacyProfilesBase = Path.Combine(RynthInstallPaths.RynthAiDir, "SettingsProfiles");
|
||||
|
||||
/// <summary>RynthAi's folder (shared profiles, aug costs; overridable for the tests).</summary>
|
||||
public static string LegacySharedRoot = RynthInstallPaths.RynthAiDir;
|
||||
|
||||
/// <summary>RynthAi's folder for profiles saved before they went per server.</summary>
|
||||
private const string LegacyServerFolder = "ACEmulator";
|
||||
|
||||
/// <summary>RynthAi's file-name sanitizer (LegacyDashboardRenderer.SanitizeFileName).</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>RynthAi's settings folder for this character: the world's, else the pre-per-server one. Null when neither exists.</summary>
|
||||
public static string? FindLegacyCharFolder(string world, string charName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(charName)) return null;
|
||||
string safeChar = RynthAiSafeName(charName.Trim());
|
||||
var candidates = new List<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Whether <paramref name="charFolder"/>'s copy from RynthAi failed and hasn't been finished yet.</summary>
|
||||
public static bool IsPending(IltSettings settings, string charFolder)
|
||||
{
|
||||
if (string.IsNullOrEmpty(charFolder)) return false;
|
||||
foreach (string f in settings.PendingCharacterMigrations ?? new List<string>())
|
||||
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<string>();
|
||||
settings.PendingCharacterMigrations.RemoveAll(f => string.Equals(f, charFolder, StringComparison.OrdinalIgnoreCase));
|
||||
if (pending) settings.PendingCharacterMigrations.Add(charFolder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// First login of a character with RynthILT: copies its RynthAi ILT Hub files into
|
||||
/// <paramref name="newFolder"/> (only when it has no hub.json yet, or an earlier copy failed
|
||||
/// part-way) and folds its RynthAi Server Features into <paramref name="settings"/>.
|
||||
/// <paramref name="forceIlt"/> 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 <paramref name="settings"/> (save them): the Hub then writes nothing there and the
|
||||
/// next call copies what is still missing (never overwriting).
|
||||
/// </summary>
|
||||
public static List<string> MigrateCharacter(string newFolder, string world, string charName, IltSettings settings, out bool forceIlt)
|
||||
{
|
||||
forceIlt = false;
|
||||
var done = new List<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Once for every character: RynthAi's shared Hub profiles and aug-cost table into
|
||||
/// <paramref name="newRoot"/> (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.
|
||||
/// </summary>
|
||||
public static List<string> MigrateShared(IltSettings settings, string newRoot)
|
||||
{
|
||||
var done = new List<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>RynthAi's per-character Mini Remote file (the Pets tab's settings).</summary>
|
||||
public const string LegacyMiniRemoteFile = "miniremote.json";
|
||||
|
||||
/// <summary>RynthAi's per-character HUD file (the Remote tab's section switches).</summary>
|
||||
public const string LegacyHudsFile = "huds.json";
|
||||
|
||||
/// <summary>
|
||||
/// 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 <paramref name="state"/>:
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static List<string> ImportRynthAiSettings(IltHubState state, string world, string charName)
|
||||
{
|
||||
var done = new List<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A JSON file read with <paramref name="info"/>, or null (missing or unreadable: logged).</summary>
|
||||
private static T? ReadJson<T>(string path, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The character's active RynthAi profile's Server Features fields.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Adds the names the list doesn't have yet (case-insensitive); returns how many.</summary>
|
||||
internal static int MergeServerNames(IltSettings settings, IEnumerable<string>? 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies <paramref name="from"/> to <paramref name="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 <paramref name="failed"/>.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,129 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>
|
||||
/// "/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.
|
||||
/// </summary>
|
||||
public static readonly Regex AugLine = new(@"^(\w+)\s*:\s*(\d[\d,.\s']*)", Opt);
|
||||
|
||||
/// <summary>"/pets" / "/shinies" roster entry: "12. Shiny Drudge Ravener".</summary>
|
||||
public static readonly Regex RosterLine = new(@"^\s*(\d+)\.\s+(.+)$", Opt);
|
||||
|
||||
/// <summary>Bank-command amount entry: "1.5m", "250,000", "2b".</summary>
|
||||
public static readonly Regex AmountInput = new(@"^([\d,.]+)\s*([kmbt]?)$", Opt | RegexOptions.IgnoreCase);
|
||||
|
||||
/// <summary>AC character name: starts with a letter, then letters, spaces, apostrophes or hyphens (max 32).</summary>
|
||||
public static readonly Regex CharacterName = new(@"^[A-Za-z][A-Za-z '\-]{0,31}$", Opt);
|
||||
|
||||
/// <summary>A comma-grouped or plain integer as printed by ACE's N0 format.</summary>
|
||||
public const string AmountPattern = @"(?:\d{1,3}(?:,\d{3})+|\d+)";
|
||||
|
||||
/// <summary>"Transferred 5,000 Pyreals to Bob" (optional " (offline)" / trailing "--- note").</summary>
|
||||
public static readonly Regex BankSent = new(
|
||||
@"^Transferred (" + AmountPattern + @") ([^']+?) to ([^-]+?)(?:\s*---.*)?$", Opt);
|
||||
|
||||
/// <summary>"Received 5,000 Pyreals from Bob".</summary>
|
||||
public static readonly Regex BankReceived = new(
|
||||
@"^Received (" + AmountPattern + @") ([^']+?) from (.+?)(?:\s*---.*)?$", Opt);
|
||||
|
||||
/// <summary>"/xp all" cost line: "[XP] Your XP cost for next 1 Strength level is: 1,234".</summary>
|
||||
public static readonly Regex XpCost = new(@"\[XP\] Your XP cost for next 1 (\w+) level is: ([\d,]+)", Opt);
|
||||
|
||||
/// <summary>"/attr" success: "[ATTR] Strength attribute raised by 10, costing 1,234!".</summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Strips commas and parses the leading integer; 0 when absent.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Compact display: 950 → "950", 12_300 → "12.3K", 4_500_000 → "4.50M", 2e9 → "2.00B".</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Full grouped display: 1234567 → "1,234,567".</summary>
|
||||
public static string N0(long value) => value.ToString("N0", CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>"3d 4h 12m 5s" style duration; "ready" when zero or negative.</summary>
|
||||
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";
|
||||
}
|
||||
|
||||
/// <summary>Strips "<Tell:…>" style markup the chat window sometimes leaves on names.</summary>
|
||||
public static string StripMarkup(string text)
|
||||
=> Regex.Replace(text ?? string.Empty, @"<[^>]*>", string.Empty).Trim();
|
||||
}
|
||||
|
|
@ -1,394 +0,0 @@
|
|||
// 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<int, float> _healthRatios = new();
|
||||
|
||||
public IltPetAutomation(IltHubContext ctx) => _ctx = ctx;
|
||||
|
||||
private IltPetState S => _ctx.State.Pet;
|
||||
|
||||
/// <summary>The auto-capture line under the switch (render thread).</summary>
|
||||
public string CaptureStatus => _captureStatus;
|
||||
|
||||
/// <summary>
|
||||
/// RynthILT.Hub AllowSummonOnEmpty: the last tick's answer, false off an ILT world. Any thread.
|
||||
/// </summary>
|
||||
public bool AllowSummonOnEmpty => _ctx.Options.IsIltLikeWorld && _allowSummonOnEmpty;
|
||||
|
||||
// ── Charms / gates ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Summon Essence Refill charm is carried and switched on (or the server stamped the player bool).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>ACECustom MonsterCapture replies: back off after a refuse so lenses aren't burned. Never eats.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A creature's health ratio from the server (RynthPluginOnUpdateHealth; any thread).</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The last health ratio the server sent for a creature, -1 when none.</summary>
|
||||
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) ───────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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 ────────────────
|
||||
|
||||
/// <summary>The pet charms and the refill opt-in (section "pets-charms").</summary>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>Siphon-lens auto-capture: enable + which lens to use (section "pets-capture").</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,790 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>Everything the breeding UI and reader JSON show, rebuilt whole on the pump.</summary>
|
||||
/// <remarks><see cref="RulesView"/> is a frozen copy of the rules: the render thread plans with it while the pump learns.</remarks>
|
||||
internal sealed record BreedingSnapshot(
|
||||
IReadOnlyList<BreedEssence> Essences, IReadOnlyList<(BreedSupplyDef Def, long Count)> Supplies,
|
||||
IReadOnlyList<BreedRuleValue> Rules, IReadOnlyList<IltBreedingEvent> 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<BreedEssence>(), Array.Empty<(BreedSupplyDef, long)>(),
|
||||
Array.Empty<BreedRuleValue>(), Array.Empty<IltBreedingEvent>(), null, default, IltTri.Unknown, IltTri.Unknown,
|
||||
IltTri.Unknown, string.Empty, -1, string.Empty, 0, false, new IltBreedingRules(new IltBreedingState()));
|
||||
}
|
||||
|
||||
internal sealed class IltPetBreeding : IIltFeature
|
||||
{
|
||||
/// <summary>Feature bits this tracker reports (IltFeatureCatalog's pet_breeding / pet_maturity rows).</summary>
|
||||
public const string BitBreeding = RynthIltHub.FeaturePetBreeding;
|
||||
public const string BitMaturity = "pet_maturity";
|
||||
|
||||
/// <summary>ACE commands: the diagnostics reply, and the courtship dance.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>The tracker reads essences while it was looked at within this long.</summary>
|
||||
private const long WatchMs = 6000;
|
||||
/// <summary>How often a watched tracker re-reads the essences.</summary>
|
||||
private const long ScanMs = 2000;
|
||||
/// <summary>Appraisal requests per scan for essences not yet appraised.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The rules (tests and the controller).</summary>
|
||||
internal IltBreedingRules Rules => _rules;
|
||||
|
||||
/// <summary>The latest snapshot (any thread).</summary>
|
||||
public BreedingSnapshot Snapshot => _snap;
|
||||
|
||||
/// <summary>Someone is looking: keep the essences fresh for a while (any thread).</summary>
|
||||
public void MarkWatched() => System.Threading.Interlocked.Exchange(ref _watchedAt, IltHubContext.NowMs);
|
||||
|
||||
/// <summary>The reader JSON ("RynthILT.Data" GetPetBreedingJson); reading it marks the tracker watched. Any thread.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The event kind of a breeding chat line, or null for any other line.</summary>
|
||||
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) ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Reads every carried combat essence and the supplies, then rebuilds the snapshot and reader JSON.</summary>
|
||||
private void Scan()
|
||||
{
|
||||
IltInventory inv = _ctx.Inventory;
|
||||
RynthCoreHost host = _ctx.Host;
|
||||
double now = UnixNow;
|
||||
DateTime utc = DateTime.UtcNow;
|
||||
var essences = new List<BreedEssence>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The pet_breeding state the Leaftide profile shows (reported, else the ILT profile's "on").</summary>
|
||||
private IltTri EnabledState()
|
||||
{
|
||||
IltTri t = _ctx.Options.Get(BitBreeding);
|
||||
return t != IltTri.Unknown ? t : _ctx.Options.IsIltLikeWorld ? IltTri.On : IltTri.Unknown;
|
||||
}
|
||||
|
||||
/// <summary>An essence outside the WCID table (a new family) that the server gave a breeding block.</summary>
|
||||
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) ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Re-appraises every essence and rescans.</summary>
|
||||
public void RefreshAll()
|
||||
{
|
||||
_refreshAll = true;
|
||||
_scannedAt = 0;
|
||||
MarkWatched();
|
||||
}
|
||||
|
||||
/// <summary>Runs "@breed-debug" quietly and keeps its reply (the room check, partners nearby).</summary>
|
||||
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<string>(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;
|
||||
}
|
||||
|
||||
/// <summary>Starts the courtship dance ("@dance"); the breed happens when a partner dances in time.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A reader's verb line ("RynthILT.Data" PetBreedingCommand): refresh, debug, dance,
|
||||
/// or "apply <supplyKey> <essenceId>" (the reader confirmed it with the player). Pump thread.
|
||||
/// </summary>
|
||||
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 ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The reader JSON (Plugins/Shared/RynthIltDataApi.cs header has the shape).</summary>
|
||||
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<int>();
|
||||
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<string> 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 ───────────────────
|
||||
|
||||
/// <summary>The Breeding tab's body (RynthIltHub.SectionPetBreeding).</summary>
|
||||
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<BreedEssence> list, BreedEssence? current, Action<int> 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) + "%";
|
||||
|
||||
/// <summary>Item names go into ImGui labels, where "##" would start the hidden id.</summary>
|
||||
private static string SafeText(string s) => (s ?? string.Empty).Replace("#", "");
|
||||
}
|
||||
|
|
@ -1,166 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>One siphon lens the Pets tab can auto-use (name, WCID, whether health is gated).</summary>
|
||||
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; }
|
||||
/// <summary>Asheron's (and Debug) lenses skip the 20% / 20 HP gate.</summary>
|
||||
public bool BypassesHealthGate { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static class PetCaptureRules
|
||||
{
|
||||
/// <summary>A lens targets the nearest attackable creature within this many meters.</summary>
|
||||
public const float CaptureRangeM = 5.0f;
|
||||
|
||||
/// <summary>Siphon once at or below this fraction of max health…</summary>
|
||||
public const float CaptureMaxHealthFraction = 0.20f;
|
||||
|
||||
/// <summary>…or below this many hit points (the gate is OR with the fraction).</summary>
|
||||
public const int CaptureMaxHealthPoints = 20;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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),
|
||||
};
|
||||
|
||||
/// <summary>Combo labels for the Pets tab (same order as <see cref="Lenses"/>).</summary>
|
||||
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];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Same gate from a 0–1 health ratio only (no absolute HP). Dead / unknown = false.</summary>
|
||||
public static bool IsWeakEnoughRatio(float healthRatio)
|
||||
{
|
||||
if (healthRatio <= 0f || healthRatio > 1f) return false;
|
||||
return healthRatio <= CaptureMaxHealthFraction;
|
||||
}
|
||||
|
||||
/// <summary>True when this lens may be used given the creature's vitals (bypass lenses always, if alive).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Distance gate: ACECustom CaptureRangeM.</summary>
|
||||
public static bool InRange(double distanceM) => distanceM >= 0 && distanceM <= CaptureRangeM;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class PetCaptureThrottle
|
||||
{
|
||||
/// <summary>Lens uses on one creature, with no success in between, before it is left alone.</summary>
|
||||
public const int MaxTriesPerTarget = 5;
|
||||
|
||||
/// <summary>How long a creature that used up its tries is left alone (ms).</summary>
|
||||
public const long TargetBlockMs = 120_000;
|
||||
|
||||
/// <summary>Lens uses over all creatures with no success before auto-capture switches itself off.</summary>
|
||||
public const int MaxTriesWithoutSuccess = 15;
|
||||
|
||||
private readonly Dictionary<int, int> _tries = new();
|
||||
private readonly Dictionary<int, long> _blockedUntil = new();
|
||||
private int _sinceSuccess;
|
||||
|
||||
/// <summary>Consecutive lens uses with no recognized success (all targets).</summary>
|
||||
public int TriesWithoutSuccess => _sinceSuccess;
|
||||
|
||||
/// <summary>True when the backstop was hit: the caller should switch auto-capture off.</summary>
|
||||
public bool Exhausted => _sinceSuccess >= MaxTriesWithoutSuccess;
|
||||
|
||||
/// <summary>False while this target is blocked (it used its tries) or the backstop is hit.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Seconds left on this target's block, 0 when it is not blocked.</summary>
|
||||
public long BlockedSecondsLeft(int targetId, long nowMs)
|
||||
=> _blockedUntil.TryGetValue(targetId, out long until) && nowMs < until ? (until - nowMs + 999) / 1000 : 0;
|
||||
|
||||
/// <summary>Count a lens use on this target; blocks it once it reaches <see cref="MaxTriesPerTarget"/>.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A recognized success reply: everything starts over.</summary>
|
||||
public void RecordSuccess() => Reset();
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_tries.Clear();
|
||||
_blockedUntil.Clear();
|
||||
_sinceSuccess = 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>Captures /pets or /shinies into the state (quiet).</summary>
|
||||
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);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Also used by the login probe tap so the roster fills without a second command.</summary>
|
||||
public void ApplyRoster(bool shinies, List<string> lines)
|
||||
{
|
||||
RynthLog.Trace(LogCat.IltPets, $"ApplyRoster(shinies={shinies}, lines={lines.Count})");
|
||||
var list = new List<string>();
|
||||
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<string> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,882 +0,0 @@
|
|||
// 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 ─────────────────────────────────────────────
|
||||
|
||||
/// <summary>Per-server aug cost rules (UB's ILT model unless this world was changed).</summary>
|
||||
public IltAugCosts AugCosts { get; } = new();
|
||||
|
||||
/// <summary>The rules for the world we're on.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Materials for reaching enlightenment level <paramref name="t"/> (one step).</summary>
|
||||
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 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>/attr abbreviation, display name, attribute stype (0 = vital), vital stype.</summary>
|
||||
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<string, int> _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;
|
||||
/// <summary>Second Refresh current while /aug is already queued or in flight (UB coalesces the same way).</summary>
|
||||
private bool _augRefreshAgain;
|
||||
/// <summary>One silent retry after the login probe left Current empty (chat-hold / ArmsIdle race).</summary>
|
||||
private bool _augProbeRetryDone;
|
||||
/// <summary>Passive /aug window: accept AugLine chat until this tick (like T11's report parser).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Infinite-attribute raiser (Progression tab "Attribute raiser" section).</summary>
|
||||
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();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Runs a coalesced Refresh current if one was queued. Returns true when it did.</summary>
|
||||
private bool DrainAugRefreshAgain()
|
||||
{
|
||||
if (!_augRefreshAgain) return false;
|
||||
_augRefreshAgain = false;
|
||||
RequestAugs();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Parses "/aug" output (also fed from the login probe and passive chat).</summary>
|
||||
public void ApplyAugLines(List<string> 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})");
|
||||
}
|
||||
|
||||
/// <summary>Applies one "/aug" Type: N line. Returns true when a known planner key was updated.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Sends "/enl" (server shows the confirmation dialog). Pump thread.</summary>
|
||||
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,
|
||||
};
|
||||
|
||||
/// <summary>Checks the client-visible requirements for the next enlightenment. Empty = ready.</summary>
|
||||
private List<string> NextEnlBlockers()
|
||||
{
|
||||
var list = new List<string>();
|
||||
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 <abbr> 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.
|
||||
|
||||
/// <summary>Appends <c>"aug":{...},"enl":{...},"attr":{...}</c> to <paramref name="sb"/>. Pump thread.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Pulls "/aug" once per login when the levels haven't been loaded (login probe or by hand).</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>One aug's plan line: current level, clamped target, luminance and coins to get there.</summary>
|
||||
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<AugPlan> BuildAugPlan()
|
||||
{
|
||||
Dictionary<string, int> levels;
|
||||
lock (_augLevels) levels = new Dictionary<string, int>(_augLevels, StringComparer.OrdinalIgnoreCase);
|
||||
var profile = AugProfile;
|
||||
var plan = new List<AugPlan>(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('}');
|
||||
}
|
||||
|
||||
/// <summary><c>"cfg":{...}</c>: this world's cost rules for the "Cost settings" editor.</summary>
|
||||
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("]}");
|
||||
}
|
||||
|
||||
/// <summary>"augcfg <aug> <field> <value>": one cost-rule edit for this world.</summary>
|
||||
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;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UB's "Copy Discord" table in a code block. ASCII only: the engine reads the snapshot as ANSI.
|
||||
/// </summary>
|
||||
private string AugDiscordText(List<AugPlan> 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();
|
||||
}
|
||||
|
||||
/// <summary>UB's "Copy In-Game": one line of current levels with short names, for pasting into chat.</summary>
|
||||
private string AugIngameText(List<AugPlan> 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<string, long>();
|
||||
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('}');
|
||||
}
|
||||
|
||||
/// <summary>Per-level rows the calculator lists at most (a bigger range is summarised in the totals).</summary>
|
||||
private const int EnlLevelRowsMax = 100;
|
||||
|
||||
/// <summary>
|
||||
/// 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".
|
||||
/// </summary>
|
||||
private void AppendEnlCalculatorJson(StringBuilder sb, int enl, int target, Dictionary<string, long> 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)");
|
||||
}
|
||||
|
||||
/// <summary>Short label for the per-level table's item column.</summary>
|
||||
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('"');
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "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.
|
||||
/// </summary>
|
||||
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-4> <multiplier>": 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,209 +0,0 @@
|
|||
// 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<string>();
|
||||
private volatile string[] _qbIncomplete = Array.Empty<string>();
|
||||
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;
|
||||
|
||||
/// <summary>The /myquests flag kinds (RynthAi's QuestsTab.Classify, which the Temple tracker reads by).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Captures "/qb list" (quiet).</summary>
|
||||
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<string>();
|
||||
var todo = new List<string>();
|
||||
List<string>? 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++;
|
||||
}
|
||||
|
||||
/// <summary>Increments each time a "/qb list" reply is parsed (0 = not loaded this session).</summary>
|
||||
public int QbGeneration => _qbGeneration;
|
||||
|
||||
/// <summary>
|
||||
/// Snapshot for the "RynthILT.Server" profile JSON (Oracle Quests / Fellowship). Pump thread.
|
||||
/// </summary>
|
||||
public IltQuestBonusInfo Snapshot() =>
|
||||
new(_ctx.Options.IsOff(IltFeature.Qb), _qbGeneration, _qbCount, _qbStatus, _qbCompleted, _qbIncomplete);
|
||||
|
||||
/// <summary>True when the last "/qb list" (completed or incomplete) contains the flag.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Login probe tap: "/qb" (no args) prints the count line.</summary>
|
||||
public void ApplyQbProbe(List<string> 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<string>();
|
||||
_qbIncomplete = Array.Empty<string>();
|
||||
_qbCount = -1;
|
||||
_qbStatus = "not loaded";
|
||||
_qbGeneration = 0;
|
||||
}
|
||||
|
||||
// ── UI (render thread) ──────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The Quests tab's "Quest bonus (/qb)" section (collapsed header; ILT worlds only).</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,130 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>One ingredient: the first of <see cref="Names"/> found in an item's name, unless it also has <see cref="Exclude"/>.</summary>
|
||||
internal sealed record IltRingIngredient(string Label, string[] Names, string Exclude = "");
|
||||
|
||||
/// <summary>One combine: <see cref="Tool"/> is used on <see cref="Target"/>.</summary>
|
||||
/// <param name="Tier">1 quill + trophy, 2 + ink, 3 + glyph: the queue runs every tier-1 run first.</param>
|
||||
/// <param name="ScrollMarkers">Step 3: the words the resulting inscription scroll's name carries.</param>
|
||||
internal sealed record IltRingRecipe(string Id, int Tier, string Name, string Notes,
|
||||
IltRingIngredient Tool, IltRingIngredient Target, string[] ScrollMarkers);
|
||||
|
||||
internal static class IltRingChain
|
||||
{
|
||||
/// <summary>Every inscription scroll's name has this.</summary>
|
||||
public const string InscriptionMarker = "Inscription of";
|
||||
/// <summary>Most runs of one recipe the tab queues.</summary>
|
||||
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 });
|
||||
|
||||
/// <summary>The chain, in UB-IT's order.</summary>
|
||||
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<string>()),
|
||||
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<string>()),
|
||||
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"),
|
||||
};
|
||||
|
||||
/// <summary>True when an item's name is this ingredient.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public static List<IltRingRecipe> Expand(Func<string, int> runs)
|
||||
{
|
||||
var queue = new List<IltRingRecipe>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The glyph recipe a scroll came from (null when its name has no known marker).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>The order scrolls are listed and used in: by glyph recipe id, unknown ones last by name.</summary>
|
||||
public static string ScrollOrderKey(string? scrollName) => GlyphOf(scrollName)?.Id ?? "zzz_" + scrollName;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static List<(int Scroll, int Target)> PairScrolls(IEnumerable<(int Id, string Name)> scrolls, IEnumerable<int> 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,557 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>One line of the Rings scan: a recipe header (Found null) or an ingredient.</summary>
|
||||
/// <param name="State">0 found, 1 comes from an earlier step, 2 missing.</param>
|
||||
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;
|
||||
/// <summary>The player answers AC's own dialog: give them time.</summary>
|
||||
private const long ManualTimeoutMs = 60_000;
|
||||
private const long StepGapMs = 700;
|
||||
private const long RetryDelayMs = 1_500;
|
||||
private const int MaxBusyRetries = 3;
|
||||
/// <summary>A missing ingredient is looked for this often and this many times (~10 s).</summary>
|
||||
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;
|
||||
/// <summary>True while another ILT job (the split-arrow imbuer) is using the pack.</summary>
|
||||
private readonly Func<bool> _blocked;
|
||||
|
||||
// Job (pump thread)
|
||||
private Mode _mode;
|
||||
private List<IltRingRecipe> _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<IltRingScanLine>();
|
||||
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<bool> blocked)
|
||||
{
|
||||
_ctx = ctx;
|
||||
_blocked = blocked;
|
||||
}
|
||||
|
||||
public bool Running => _running;
|
||||
public string Status => _status;
|
||||
public IltRingScanLine[] ScanLines => _scan;
|
||||
/// <summary>The inscription scrolls the last scan found.</summary>
|
||||
public (int Id, string Name)[] Scrolls => _scrolls;
|
||||
|
||||
private RynthCoreHost Host => _ctx.Host;
|
||||
private IltInventory Inv => _ctx.Inventory;
|
||||
private IltGearState G => _ctx.State.Gear;
|
||||
|
||||
/// <summary>Pump thread: the saved run count for a recipe.</summary>
|
||||
private int Runs(string id) => G.RingRuns.TryGetValue(id, out int n) ? n : 0;
|
||||
|
||||
/// <summary>Pump thread: sets a recipe's run count (0 removes it) and the render copy.</summary>
|
||||
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<WorldObject> 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));
|
||||
|
||||
/// <summary>What a recipe makes, counted: Step 1 the enlightened quill, Step 2 the partition quill, Step 3 a scroll.</summary>
|
||||
private long OutputCount(IltRingRecipe r) => r.Tier switch
|
||||
{
|
||||
1 => Count(IltRingChain.Recipes[1].Tool),
|
||||
2 => Count(IltRingChain.Recipes[2].Tool),
|
||||
_ => ScrollCount(),
|
||||
};
|
||||
|
||||
// ── Scan ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public void Scan()
|
||||
{
|
||||
var lines = new List<IltRingScanLine>();
|
||||
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) ───────────────────────────────────────────
|
||||
|
||||
/// <summary>Crafts the queued recipes (after the tab's confirm).</summary>
|
||||
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)");
|
||||
}
|
||||
|
||||
/// <summary>Uses one scroll on the item selected in AC.</summary>
|
||||
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)) });
|
||||
}
|
||||
|
||||
/// <summary>Pairs the carried scrolls with these items (the carried jewelry) and uses them.</summary>
|
||||
public void ApplyToItems(IReadOnlyList<int> 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<IltRingRecipe>();
|
||||
_pairs = new List<(int, int)>();
|
||||
_status = why;
|
||||
}
|
||||
|
||||
// ── IIltFeature ─────────────────────────────────────────────────────────
|
||||
|
||||
public void OnLogout()
|
||||
{
|
||||
Stop("idle");
|
||||
_scan = Array.Empty<IltRingScanLine>();
|
||||
_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}";
|
||||
}
|
||||
|
||||
/// <summary>Arms the dialog answer (Yes: the player asked for this) and uses source on target.</summary>
|
||||
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)");
|
||||
}
|
||||
|
||||
/// <summary>The current combine or inscription went through.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>"cannot be used on" ends the job: the names didn't match what the server expects. Never eaten.</summary>
|
||||
public bool OnChat(string text)
|
||||
{
|
||||
if (!_waiting || string.IsNullOrEmpty(text)) return false;
|
||||
if (CannotUse.IsMatch(text)) Stop(text);
|
||||
return false;
|
||||
}
|
||||
|
||||
// ── UI (render thread) ──────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The ring inscription chain: runs per recipe, Scan / Create / Stop, then the scrolls.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The carried inscription scrolls: one to the selected item, or all to the carried jewelry.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,121 +0,0 @@
|
|||
// 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";
|
||||
/// <summary>Yards: the Handler's lethal ring is treated as at least this wide (RynthAi widens it to Ring Range).</summary>
|
||||
internal const float DangerYards = 12f;
|
||||
/// <summary>Back-jump charge (ms): run-back + jump must clear about the ring's radius.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>What the last ring line did (for the log and the tests).</summary>
|
||||
public string LastOutcome { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="text"/> 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The nearest Empyrean Handler the client knows (a creature with that in its name).</summary>
|
||||
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) { }
|
||||
|
||||
/// <summary>Unused: the controller passes the chat type (OnChatLine).</summary>
|
||||
public bool OnChat(string text) => false;
|
||||
|
||||
public void OnLogout() => _lastRequestAt = long.MinValue;
|
||||
}
|
||||
|
|
@ -1,81 +0,0 @@
|
|||
// 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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
internal static readonly string[] TrinketNames = { "compass", "goggles", "scarab", "watch", "puzzle box", "top" };
|
||||
/// <summary>"top" but not "topaz".</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Steel and Serpentine stack on ILT jewelry, at most this many combined.</summary>
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
|
@ -1,144 +0,0 @@
|
|||
// 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 <section>" picks one, and with RynthCore's sections rail
|
||||
// RynthAi lists them as "section:<tab>" 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;
|
||||
|
||||
/// <summary>ILT sections: the Mini Remote's ILT tabs, the one that moved out, then the Guardian panel.</summary>
|
||||
internal enum IltSection
|
||||
{
|
||||
/// <summary>Moved out (2026-10-13): RynthOracle's Character tab and the Session Stats section.</summary>
|
||||
Character,
|
||||
Banking,
|
||||
Gear,
|
||||
Games,
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
VaultedDungeons,
|
||||
/// <summary>Registry charms (acquired / status / tier / server) and the Guardian Hand.</summary>
|
||||
Charms,
|
||||
// Keep Guardian last.
|
||||
Guardian,
|
||||
}
|
||||
|
||||
internal static class IltSections
|
||||
{
|
||||
/// <summary>The ILT tabs, in tab-bar order (RynthAi puts them after its own tabs).</summary>
|
||||
public static readonly IltSection[] Tabs =
|
||||
{
|
||||
IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, IltSection.VaultedDungeons,
|
||||
};
|
||||
|
||||
/// <summary>The Mini Remote's own tab (the remote itself): its tab id.</summary>
|
||||
public const string RemoteTab = "";
|
||||
|
||||
/// <summary>RynthOracle's Character tab: the character overview and this session.</summary>
|
||||
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(),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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(),
|
||||
};
|
||||
|
||||
/// <summary>True for the sections drawn as Mini Remote tabs (Banking, Gear, Charms, Games, Vaulted Dungeons).</summary>
|
||||
public static bool IsTab(IltSection s) => s is IltSection.Banking or IltSection.Gear or IltSection.Charms or IltSection.Games
|
||||
or IltSection.VaultedDungeons;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public static string? MovedCommand(IltSection s) => s switch
|
||||
{
|
||||
IltSection.Character => OracleCharacterCommand,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>"quests" / "pets" (and their aliases): not ILT sections (RynthAi's Pets tab, RynthOracle's quests).</summary>
|
||||
public static bool IsUniversalTabName(string text) => (text ?? string.Empty).Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"quests" or "quest" or "pets" or "pet" => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>Parses a "/ra hub open" section name (a few aliases accepted).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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),
|
||||
};
|
||||
|
||||
/// <summary>"show" / "hide" / "toggle" (anything else toggles) applied to the current state.</summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,376 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>Feature keys used by the gate table.</summary>
|
||||
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";
|
||||
|
||||
/// <summary>Key for a per-charm "enabled" bit, e.g. Charm("Guardian Hand") → "charm:guardianhand".</summary>
|
||||
public static string Charm(string charmName)
|
||||
{
|
||||
var chars = (charmName ?? string.Empty).Where(char.IsLetterOrDigit).Select(char.ToLowerInvariant).ToArray();
|
||||
return "charm:" + new string(chars);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tri-state feature value.</summary>
|
||||
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<string> _chat;
|
||||
private readonly Func<IltSettings?> _settings;
|
||||
|
||||
/// <summary>Feeds probe replies to features that can reuse them (e.g. /bank → Banking balances).</summary>
|
||||
public Action<string, IltChatResult>? ProbeReplyTap;
|
||||
|
||||
private bool _refreshInFlight;
|
||||
private int _probesOutstanding;
|
||||
private long _loginAt;
|
||||
private bool _loginRefreshDone;
|
||||
|
||||
/// <summary>Wait this long after login before the one-shot refresh so chat/world are settled.</summary>
|
||||
private const long LoginRefreshDelayMs = 6000;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private const long WorldNameWaitMs = 60000;
|
||||
|
||||
public IltServerOptions(RynthCoreHost host, IltChatCapture capture, IltHubState state, Action<string> chat,
|
||||
Func<IltSettings?>? settings = null)
|
||||
{
|
||||
_host = host;
|
||||
_capture = capture;
|
||||
_state = state;
|
||||
_chat = chat;
|
||||
_settings = settings ?? (() => null);
|
||||
}
|
||||
|
||||
// ── Identity ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>World name as reported by the engine login hook (empty if unknown).</summary>
|
||||
public string WorldName
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_host.HasGetWorldName && _host.TryGetWorldName(out string n) && !string.IsNullOrWhiteSpace(n))
|
||||
return n.Trim();
|
||||
return _state.ServerOptions.WorldName ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>RynthCore's id for Infinite Leaftide in its server verdicts.</summary>
|
||||
public const string EngineServerId = "ilt";
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public static bool EngineDecides => IltEngineVerdict.Active.HasValue;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public bool IsIltLikeWorldLocal
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_state.ForceLeaftideFeatures) return true;
|
||||
IltSettings? s;
|
||||
try { s = _settings(); } catch { s = null; }
|
||||
return ServerFeatureGate.IsEnabled(WorldName, s, _state.ForceLeaftideFeatures);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public bool IsIltLikeWorld
|
||||
{
|
||||
get
|
||||
{
|
||||
bool? engine = IltEngineVerdict.Active;
|
||||
return engine ?? IsIltLikeWorldLocal;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True while the login probe is running.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>True only when the server positively reported the feature as available.</summary>
|
||||
public bool IsOn(string key) => Get(key) == IltTri.On;
|
||||
|
||||
/// <summary>True when the server positively reported the feature as unavailable.</summary>
|
||||
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}");
|
||||
}
|
||||
|
||||
/// <summary>At least one feature bit is On (Hub window shows only then, unless Force is on).</summary>
|
||||
public bool AnyFeatureOn => _state.ServerOptions.Bits.Values.Any(v => v == 1);
|
||||
|
||||
/// <summary>All known bits for the status display.</summary>
|
||||
public IReadOnlyList<KeyValuePair<string, int>> SnapshotBits()
|
||||
=> _state.ServerOptions.Bits.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase).ToList();
|
||||
|
||||
// ── Lifecycle ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Called at login: schedules the one-shot refresh (never a recurring timer).</summary>
|
||||
public void OnLoginComplete()
|
||||
{
|
||||
_loginAt = Environment.TickCount64;
|
||||
_loginRefreshDone = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the probe refresh. Manual refreshes report progress in chat; the login refresh is
|
||||
/// silent.
|
||||
/// </summary>
|
||||
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 <name> 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 ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>One read-only probe: command, reply recogniser, feature key.</summary>
|
||||
private readonly record struct Probe(string Key, string Command, Func<string, bool> 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")),
|
||||
};
|
||||
|
||||
/// <summary>Recognises ACE's wrong-parameter-count reply (command exists) or a keyword reply.</summary>
|
||||
private static Func<string, bool> 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("<Tell", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private void RunProbes(bool manual)
|
||||
{
|
||||
var todo = Probes.ToList();
|
||||
|
||||
// /enl is never probed (it pops the enlightenment confirmation). On an ILT-like
|
||||
// world the command is part of ACECustom, so it is assumed present.
|
||||
Set(IltFeature.Enl, IltTri.On);
|
||||
|
||||
_probesOutstanding = todo.Count;
|
||||
if (_probesOutstanding == 0) { CompleteRefresh(manual); return; }
|
||||
|
||||
foreach (var p in todo)
|
||||
{
|
||||
var probe = p;
|
||||
_capture.Enqueue(new IltChatRequest
|
||||
{
|
||||
Command = probe.Command,
|
||||
IsResponseLine = probe.IsReply,
|
||||
// /aug: banner alone must not end the probe before Creature:/Item: lines arrive.
|
||||
ArmsIdle = probe.Key == IltFeature.Aug ? t => 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 ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>Records what the login /myquests refresh learned (called by the Hub after the Meta tracker finishes).</summary>
|
||||
public void NoteQuestTrackerOutcome(bool disabled, int recordCount)
|
||||
{
|
||||
if (disabled) Set(IltFeature.Quests, IltTri.Off);
|
||||
else if (recordCount > 0) Set(IltFeature.Quests, IltTri.On);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,291 +0,0 @@
|
|||
// 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<string, long> _lastItemCounts = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, long> _itemGains = new(StringComparer.OrdinalIgnoreCase);
|
||||
private long _lastSampleAt;
|
||||
private long _lastRowsAt;
|
||||
|
||||
// Render snapshot.
|
||||
private volatile RateRow[] _rows = Array.Empty<RateRow>();
|
||||
// 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);
|
||||
|
||||
/// <summary>Coin and pyreal per-hour figures for the Mini Remote HUD (rebuilt every sample).</summary>
|
||||
public sealed record RateSummary(double CoinsPerHour, double PyrealsPerHour);
|
||||
private static readonly RateSummary EmptySummary = new(0, 0);
|
||||
private volatile RateSummary _summary = EmptySummary;
|
||||
|
||||
/// <summary>Latest coin / pyreal summary (safe from the render thread).</summary>
|
||||
public RateSummary Summary => _summary;
|
||||
/// <summary>When the coin / pyreal session (or the last Reset) started.</summary>
|
||||
public DateTime SessionStartUtc => _start;
|
||||
|
||||
public IltSessionRates(IltHubContext ctx) => _ctx = ctx;
|
||||
|
||||
/// <summary>True while money moves between pack and bank (set by the controller from Banking). Pump thread.</summary>
|
||||
public Func<bool>? MovingMoney { get; set; }
|
||||
|
||||
private bool Moving => MovingMoney?.Invoke() ?? false;
|
||||
|
||||
/// <summary>Banking hook: bank balance changed (pump thread).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Coins, pyreals and item gains start over (login, or with <see cref="ResetAll"/>).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The player's reset (this tab, the Mini Remote): coins here and the shared session stats together. Pump thread.</summary>
|
||||
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)
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Positive change since the last sample; the first sample only sets the baseline.</summary>
|
||||
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<RateRow>();
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>What the pass-up figure is (shared with the Mini Remote's Stats).</summary>
|
||||
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) ──────────────────────────────────────────────────
|
||||
|
||||
/// <param name="extrasOnly">
|
||||
/// 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.
|
||||
/// </param>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
// 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 <list>" (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;
|
||||
|
||||
/// <summary>World-name patterns that count as Infinite Leaftide ('*' wildcard, case-insensitive).</summary>
|
||||
public List<string> ServerNames = new(ServerFeatureGate.DefaultServerNames);
|
||||
|
||||
/// <summary>The shared RynthAi files (Hub profiles, aug costs) were copied over once.</summary>
|
||||
public bool SharedFilesMigrated;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public List<string> PendingCharacterMigrations = new();
|
||||
}
|
||||
|
||||
/// <summary>Loads and saves <see cref="IltSettings"/>; a broken or missing file reads as the defaults.</summary>
|
||||
internal static class IltSettingsStore
|
||||
{
|
||||
public const string FileName = "settings.json";
|
||||
|
||||
/// <summary>Overridable for the tests.</summary>
|
||||
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<string>()));
|
||||
if (s.ServerNames.Count == 0) s.ServerNames = new List<string>(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<IltBankTransaction>), 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 { }
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>Stack counts of every item in the sigil chain.</summary>
|
||||
internal sealed class IltSigilStock
|
||||
{
|
||||
public long Sigils, AscensionCoins, LifebloodElixirs, LifebloomResins;
|
||||
public long EnlightenedCoins, YalaniTrinkets, NecrolyticExtracts, LifeSplitters, Plants;
|
||||
|
||||
public IltSigilStock Clone() => (IltSigilStock)MemberwiseClone();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class IltSigilShortfall
|
||||
{
|
||||
public long SigilsNeeded, SigilsToCraft, AscensionToCraft, ElixirsToCraft, ResinsToCraft;
|
||||
/// <summary>E-coins the Ascension Coin crafts use (before stock).</summary>
|
||||
public long CoinsForCraft;
|
||||
public long CoinsShort, TrinketsShort, ExtractsShort, SplittersShort, PlantsShort;
|
||||
|
||||
/// <summary>Stock (with the whole chain) covers every sigil.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Sigils for target levels current+1 .. target that fall inside 301-325 (T - 5 each).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Shortfall for <paramref name="sigilsNeeded"/>: sigils first, then coins / elixirs, then resins, then raws.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Sigils the stock can make: finished sigils plus the scarcer of the two craft paths.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits the e-coin pool between Ascension Coin crafts (served first) and token conversion.
|
||||
/// <paramref name="coinsNeeded"/> is what is still to get for both.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>True for a chain item name (stack names may be plural; "Plant" must be the whole name).</summary>
|
||||
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));
|
||||
}
|
||||
|
|
@ -1,210 +0,0 @@
|
|||
// 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(
|
||||
@"^(?<character>[\w\s]+) successfully applies the (?<salvage>[\w\s\-]+?)(\sSalvage.*)(\s?\(100\))?\s\(workmanship (?<workmanship>\d+\.\d+)\) to the (?<item>[\w\s\'\-]+)\.$",
|
||||
RegexOptions.Compiled | RegexOptions.CultureInvariant);
|
||||
private static readonly Regex Failed = new(
|
||||
@"^(?<character>[\w\s]+) fails to apply the (?<salvage>[\w\s\-]+?)(\sSalvage.*)(\s?\(100\))?\s\(workmanship (?<workmanship>\d+\.\d+)\) to the (?<item>[\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<WeaponRow>();
|
||||
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;
|
||||
|
||||
/// <summary>True while another ILT pack job (the Rings chain) is running: no imbue starts then.</summary>
|
||||
public Func<bool>? 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)));
|
||||
}
|
||||
|
||||
/// <summary>Full White Quartz bags, lowest workmanship first.</summary>
|
||||
private List<WorldObject> 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;
|
||||
}
|
||||
|
||||
/// <summary>Starts imbuing one weapon (pump thread, after the UI confirm).</summary>
|
||||
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<WeaponRow>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
// 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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Minimal JSON string escaper for hand-built export JSON.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,213 +0,0 @@
|
|||
// 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 <n|auto>") 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 <n|auto> | 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;
|
||||
|
||||
/// <summary>The counters this character's "/aug" reply gave, with the override applied.</summary>
|
||||
public T11PlayerAugs Player { get; } = new();
|
||||
|
||||
/// <summary>How many counters the last report to RynthAi carried (for the tests).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The "/aug" reply's counter lines. Never eats (the login probe's capture decides that).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Every counter to RynthAi (-1 for an unknown one). Pump thread.</summary>
|
||||
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 ..." ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>"/ilt t11 [status | augs <n|auto> | refresh | item [0xId]]" (args after "t11"). Pump thread.</summary>
|
||||
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 <n|auto> | refresh | item [0xId]] (also /ra t11)");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The counters the "T11: Can Wield" loot key compares wield gates against.</summary>
|
||||
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 <n>.");
|
||||
if (!_ctx.Ai.Available)
|
||||
_ctx.Chat("[RynthILT] (The loot rules are RynthAi's; it isn't loaded, so nothing uses these yet.)");
|
||||
}
|
||||
|
||||
/// <summary>"/ilt t11 augs <n|auto>": the item-aug override (-1 = read from /aug), saved with the Hub's state.</summary>
|
||||
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|auto> (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.");
|
||||
}
|
||||
|
||||
/// <summary>"/ilt t11 item [0xId]": the parsed T11 text of an item (the selected item by default).</summary>
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,296 +0,0 @@
|
|||
// 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;
|
||||
|
||||
/// <summary>One tracked turn-in: the NPC, its attribute, the /qb wait flag and the /myquests keys to try.</summary>
|
||||
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<string>();
|
||||
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; }
|
||||
/// <summary>/qb flag name (e.g. TempleAttributeStrengthWait).</summary>
|
||||
public string QbWaitFlag { get; }
|
||||
/// <summary>Lowercase /myquests keys in lookup order: CSV override, the wait flag, the flag without "Wait".</summary>
|
||||
public string[] MyQuestsKeys { get; }
|
||||
|
||||
/// <summary>"You've stamped X!" → "X"; a bare flag name is returned trimmed.</summary>
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the Guardian window shows for one row.</summary>
|
||||
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<string, bool> _lastHadWait = new(StringComparer.OrdinalIgnoreCase);
|
||||
private int _seenQbGeneration;
|
||||
private long _lastRebuildAt = -RebuildIntervalMs;
|
||||
|
||||
private volatile IltTempleAttrStatus[] _snapshot = Array.Empty<IltTempleAttrStatus>();
|
||||
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}");
|
||||
}
|
||||
|
||||
/// <summary>Rows as last computed (render thread reads this).</summary>
|
||||
public IltTempleAttrStatus[] Snapshot => _snapshot;
|
||||
|
||||
/// <summary>When the quest data behind the rows last changed (MinValue = never this session).</summary>
|
||||
public DateTime SyncedUtc => _syncedUtc;
|
||||
|
||||
private IltGuardianState S => _ctx.State.Guardian;
|
||||
|
||||
// ── Rows file ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The CSV in RynthILT's folder, the RynthAi folder (where it lived), else UB's Documents location; built-in rows otherwise.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>npc, attribute, stamp [, myQuestsKey]; a header row and blank lines are skipped.</summary>
|
||||
private static List<IltTempleAttrRow> ParseCsv(string[] lines)
|
||||
{
|
||||
var rows = new List<IltTempleAttrRow>();
|
||||
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<IltTempleAttrRow> loaded)
|
||||
{
|
||||
var seen = new HashSet<string>(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();
|
||||
}
|
||||
|
||||
/// <summary>Re-asks the server for /myquests and "/qb list" (each limited to once a minute).</summary>
|
||||
public string Refresh() => $"{_ctx.Ai.RefreshQuests()} {_quests.RefreshQb()}";
|
||||
|
||||
/// <summary>Forgets the counted turn-ins and estimated cooldowns (the /qb fallback only).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A new "/qb list" arrived: count wait stamps that appeared since the previous list.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A row backed by its /myquests flag: exact solves and cooldown.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stored times may load as Unspecified; they were written as UTC.</summary>
|
||||
private static DateTime AsUtc(DateTime dt) => dt.Kind switch
|
||||
{
|
||||
DateTimeKind.Utc => dt,
|
||||
DateTimeKind.Local => dt.ToUniversalTime(),
|
||||
_ => DateTime.SpecifyKind(dt, DateTimeKind.Utc),
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue