SK fork: RynthAi 0.5.14 / SK-local features through release 2026.10.5.12 #1

Closed
Silentkelpie wants to merge 2 commits from Silentkelpie/SK-RynthSuite:main into main
100 changed files with 20816 additions and 75 deletions

View file

@ -3594,13 +3594,23 @@ public partial class CombatManager : IDisposable
return any ? CreatureWeakness.FromAppraisal(m) : null;
}
/// <summary>
/// Optional UtilityBelt damage seed lookup (wcid, name) → damage types best first, or null.
/// Set by the plugin when the seed store loads; null (default) leaves the ranking as before.
/// Called on the combat thread.
/// </summary>
internal Func<uint, string, IReadOnlyList<string>?>? MobSeedLookup { get; set; }
/// <summary>The same by wcid and name; <paramref name="objectId"/> (optional) reads a live creature type.</summary>
internal CreatureWeakness.Ranking? WeaknessFor(uint wcid, string? name, int objectId = 0)
{
name ??= "";
int ctype = CreatureTypeOf(wcid, name, objectId);
string learned = wcid != 0 ? _damageStore?.GetBestElement(wcid) ?? "" : "";
return CreatureWeakness.Rank(wcid, name, ctype, learned);
IReadOnlyList<string>? seeded = null;
try { seeded = MobSeedLookup?.Invoke(wcid, name); }
catch { seeded = null; } // a bad seed file must never stop element choice
return CreatureWeakness.Rank(wcid, name, ctype, learned, seeded);
}
// Server replies seen when the last combat wield was sent (UseDone / WeenieError sequence).

View file

@ -60,6 +60,14 @@ internal sealed class PetManager
// get parked so we advance to the next configured essence instead of looping.
private readonly Dictionary<int, long> _deviceCooldownUntil = new();
// Essences the server just confirmed full ("You add the spirit…" / "…already full"). Until a
// summon reports "not enough charges", their Structure read is not trusted: the cached value
// can still be the empty 0 from the last appraisal, which re-issued the refill in a loop
// (spirit use → peace mode → clap) on 2026-10-04.
private readonly Dictionary<int, long> _confirmedFullUntil = new();
// Refills issued per essence inside RefillLoopWindowMs; a third one parks the essence.
private readonly Dictionary<int, (int Count, long WindowStart)> _refillAttempts = new();
// Encapsulated Spirit — the fixed retail recharge item (WCID 49485). Detected
// by name; it is never itself a summon device.
private const string EncapsulatedSpiritName = "Encapsulated Spirit";
@ -69,12 +77,36 @@ internal sealed class PetManager
private const long AssumeActiveAfterSummonMs = 10_000;
private const long DeviceFailCooldownMs = 30_000;
private const long DeviceNoSpiritCooldownMs = 15_000;
private const long ConfirmedFullTrustMs = 30 * 60_000;
private const long RefillLoopWindowMs = 120_000;
private const int RefillLoopMaxAttempts = 2;
private const long RefillLoopParkMs = 300_000;
private string _playerName = string.Empty;
private long _playerNameAt;
private static long NowMs => Environment.TickCount64;
/// <summary>
/// Optional ILT Hub hook: when it returns true an EMPTY essence is used anyway, because
/// the server's Summon Essence Refill Charm refills it from banked pyreals on use.
/// Null (default) keeps the retail behaviour (spirit refill or park).
/// </summary>
public Func<bool>? AllowSummonOnEmpty { get; set; }
/// <summary>
/// Optional ILT Hub hook: while it returns true no combat summon is started (e.g. the
/// healing-pet helper has its heal pet out). Null (default) never holds.
/// </summary>
public Func<bool>? HoldSummons { get; set; }
/// <summary>
/// Optional ILT Hub hook, called when a pet already holds the slot and monsters are near.
/// Returns true after dismissing a non-combat (cosmetic) pet so a combat pet can follow.
/// Null (default) leaves whatever pet is out alone.
/// </summary>
public Func<bool>? YieldPetForCombat { get; set; }
public PetManager(RynthCoreHost host, LegacyUiSettings settings,
WorldObjectCache objectCache, CombatManager? combat,
CharacterSkills? skills)
@ -113,7 +145,7 @@ internal sealed class PetManager
bool spiritGone = _activeSpiritId != 0 && _objectCache[_activeSpiritId] == null;
if (spiritGone || DeviceHasCharges(_activeDeviceId))
{
_host.Log($"[RynthAi] Pet: refill complete (essence 0x{(uint)_activeDeviceId:X8}).");
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: refill complete (essence 0x{(uint)_activeDeviceId:X8}).");
GoIdle();
}
}
@ -122,7 +154,7 @@ internal sealed class PetManager
// decrement that never lands), and waiting on it would wedge the subsystem.
if (_state != PetState.Idle && now - _actionIssuedAt > ActionTimeoutMs)
{
_host.Log($"[RynthAi] Pet: action timeout in {_state} after {now - _actionIssuedAt}ms (essence 0x{(uint)_activeDeviceId:X8}); cooling down.");
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: action timeout in {_state} after {now - _actionIssuedAt}ms (essence 0x{(uint)_activeDeviceId:X8}); cooling down.");
if (_activeDeviceId != 0)
_deviceCooldownUntil[_activeDeviceId] = now + DeviceFailCooldownMs;
// A summon that we simply couldn't confirm very likely DID work — assume
@ -158,7 +190,12 @@ internal sealed class PetManager
// Drop to Idle; the next think tick reads Structure==0 and refills it.
if (text.Contains("enough charges", StringComparison.OrdinalIgnoreCase))
{
_host.Log($"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill.");
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill.");
_confirmedFullUntil.Remove(_activeDeviceId); // really empty now — a refill is due
// The server-side pyreal refill didn't happen (charm off / no pyreals):
// park the essence so the empty-summon path can't spin on it.
if (AllowSummonOnEmpty?.Invoke() == true && _activeDeviceId != 0)
_deviceCooldownUntil[_activeDeviceId] = NowMs + DeviceNoSpiritCooldownMs;
GoIdle();
return;
}
@ -169,9 +206,20 @@ internal sealed class PetManager
{
// "You add the spirit to the essence." (success) / "This essence is
// already full." (our Structure read was stale — also done).
if (text.Contains("add the spirit to the essence", StringComparison.OrdinalIgnoreCase)
|| text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase))
bool added = text.Contains("add the spirit to the essence", StringComparison.OrdinalIgnoreCase);
bool full = text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase);
if (added || full)
{
int device = _activeDeviceId;
if (device != 0)
{
_confirmedFullUntil[device] = NowMs + ConfirmedFullTrustMs;
// Refresh the cached Structure so the roster / HUD and later reads agree.
if (_host.HasRequestId) _host.RequestId(unchecked((uint)device));
}
RynthLog.Write(LogCat.Pets, added
? $"[RynthAi] Pet: refill complete (essence 0x{(uint)device:X8}, server confirmed)."
: $"[RynthAi] Pet: essence 0x{(uint)device:X8} is already full; charge read was stale.");
GoIdle();
}
}
@ -183,7 +231,14 @@ internal sealed class PetManager
{
// A pet is already up (just summoned, or detected in the world) — done.
if (now < _assumePetActiveUntil) return;
if (IsPetActive()) return;
if (IsPetActive())
{
// A cosmetic pet in the slot steps aside for the fight; wait for the dismiss to land.
if (YieldPetForCombat != null && MonstersNearby() && YieldPetForCombat())
_assumePetActiveUntil = now + 3000;
return;
}
if (HoldSummons?.Invoke() == true) return;
// Only summon when mobs are near (the user's trigger).
if (!MonstersNearby()) return;
@ -203,6 +258,13 @@ internal sealed class PetManager
int charges = ReadCharges(deviceId); // -1 = unreadable
// The server said this essence is full since the read went stale — summon from it.
if (charges == 0 && _confirmedFullUntil.TryGetValue(deviceId, out long trustUntil))
{
if (now < trustUntil) charges = -1;
else _confirmedFullUntil.Remove(deviceId);
}
if (charges != 0)
{
// Has charges (or unreadable → attempt; an empty one is rejected
@ -211,12 +273,22 @@ internal sealed class PetManager
return;
}
// charges == 0 → empty. Auto-refill from an Encapsulated Spirit.
// charges == 0 → empty. ILT shards with an active pyreal-refill charm refill
// the essence server-side on use, so summon straight away.
if (AllowSummonOnEmpty?.Invoke() == true)
{
IssueSummon(deviceId, charges);
return;
}
// Otherwise auto-refill from an Encapsulated Spirit.
if (_settings.PetAutoRefill)
{
int spiritId = FindEncapsulatedSpirit();
if (spiritId != 0)
{
if (RefillLoopDetected(deviceId, now))
continue;
IssueRefill(deviceId, spiritId);
return;
}
@ -239,7 +311,7 @@ internal sealed class PetManager
_activeSpiritId = 0;
_preActionCharges = charges;
_actionIssuedAt = NowMs;
_host.Log($"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}).");
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}).");
_host.UseFor(unchecked((uint)deviceId), "Pet", "summon a pet from the essence");
}
@ -251,10 +323,37 @@ internal sealed class PetManager
_activeDeviceId = deviceId;
_activeSpiritId = spiritId;
_actionIssuedAt = NowMs;
_host.Log($"[RynthAi] Pet: refilling essence 0x{(uint)deviceId:X8} with spirit 0x{(uint)spiritId:X8}.");
RecordRefillAttempt(deviceId, _actionIssuedAt);
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: refilling essence 0x{(uint)deviceId:X8} with spirit 0x{(uint)spiritId:X8}.");
_host.UseOnFor(unchecked((uint)spiritId), unchecked((uint)deviceId), "Pet", "refill the essence with a spirit");
}
/// <summary>Counts refills per essence inside <see cref="RefillLoopWindowMs"/>.</summary>
private void RecordRefillAttempt(int deviceId, long now)
{
if (_refillAttempts.TryGetValue(deviceId, out var a) && now - a.WindowStart < RefillLoopWindowMs)
_refillAttempts[deviceId] = (a.Count + 1, a.WindowStart);
else
_refillAttempts[deviceId] = (1, now);
}
/// <summary>
/// True (and the essence parked) when it was already refilled <see cref="RefillLoopMaxAttempts"/>
/// times in the window without becoming usable — the charge read is stale or the refill is
/// failing, and repeating it only burns spirits and forces peace mode.
/// </summary>
private bool RefillLoopDetected(int deviceId, long now)
{
if (!_refillAttempts.TryGetValue(deviceId, out var a) || now - a.WindowStart >= RefillLoopWindowMs)
return false;
if (a.Count < RefillLoopMaxAttempts)
return false;
_deviceCooldownUntil[deviceId] = now + RefillLoopParkMs;
_refillAttempts.Remove(deviceId);
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} refilled {a.Count}x in {(now - a.WindowStart) / 1000}s and still reads empty; parking it for {RefillLoopParkMs / 60_000} min.");
return true;
}
private void GoIdle()
{
_state = PetState.Idle;

View file

@ -8,6 +8,9 @@ namespace RynthCore.Plugin.RynthAi;
public static class SpellDatabase
{
private static readonly Dictionary<int, string> _spellNames = new();
// Family + difficulty (power) per spell id, from SpellData.txt columns 3 and 7.
// Used by the Mag-style item info spell filter (cantrip / aura tiers).
private static readonly Dictionary<int, (int Family, int Difficulty)> _spellMeta = new();
private static bool _loaded = false;
private static readonly Dictionary<int, string> _builtinSpells = new Dictionary<int, string>
@ -38,6 +41,7 @@ public static class SpellDatabase
public static void Load(Action<string>? log = null)
{
_spellNames.Clear();
_spellMeta.Clear();
_loaded = false;
try
@ -59,7 +63,13 @@ public static class SpellDatabase
if (string.IsNullOrWhiteSpace(line)) continue;
string[] columns = line.Split('\t');
if (columns.Length >= 2 && int.TryParse(columns[0].Trim(), out int spellId))
{
_spellNames[spellId] = columns[1].Trim();
if (columns.Length >= 7
&& int.TryParse(columns[2].Trim(), out int family)
&& int.TryParse(columns[6].Trim(), out int difficulty))
_spellMeta[spellId] = (family, difficulty);
}
}
_loaded = _spellNames.Count > 0;
@ -77,6 +87,24 @@ public static class SpellDatabase
return $"Unknown Spell ({spellId})";
}
/// <summary>Spell family and difficulty (power). False when the spell isn't in SpellData.txt.</summary>
public static bool TryGetSpellMeta(int spellId, out int family, out int difficulty)
{
if (_spellMeta.TryGetValue(spellId, out var meta))
{
family = meta.Family;
difficulty = meta.Difficulty;
return true;
}
family = 0;
difficulty = 0;
return false;
}
/// <summary>True when the spell id is in the embedded table or the built-in recall list.</summary>
public static bool HasSpell(int spellId) =>
_spellNames.ContainsKey(spellId) || _builtinSpells.ContainsKey(spellId);
public static string GetSpellNameOrId(int spellId)
{
if (_spellNames.TryGetValue(spellId, out string? name)) return name;

View file

@ -601,17 +601,14 @@ public class WorldObjectCache
return;
}
// Non-creature with a position — could be equipped item on 0x8000 range
// or static world object; classify by type flags
if ((typeFlags & (ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer)) != 0)
{
// Item with a world position = equipped or ground-dropped
cls = ClassifyItem(uid, typeFlags);
_inventory.Add(id);
_landscape.Remove(id);
_byId[id] = Make(id, name, cls);
// Non-creature with a known type: classify it by its ItemType flags and place it
// by ownership. Only weapons/armor/casters/containers were accepted here before,
// so keys, gems, spell components, food and misc fell through to Unknown
// landscape (never inventory) and ReclassifyUnknownDynamics re-probed them
// every 2 s forever.
AcObjectClass typedCls = ClassifyItem(uid, typeFlags);
if (typedCls != AcObjectClass.Unknown && PlaceTypedObject(uid, id, name, typedCls, typeFlags))
return;
}
}
else if (uid >= 0x80000000u)
{
@ -660,6 +657,83 @@ public class WorldObjectCache
}
}
/// <summary>
/// Places a positioned, non-creature object whose ItemType resolved to a real class.
/// Must be called under <see cref="_gate"/>.
/// <list type="bullet">
/// <item>Portals / lifestones → landscape with their real class.</item>
/// <item>Dynamic objects owned by the player (wielded, in the main pack, or in a side pack) → inventory.</item>
/// <item>Other dynamic objects (ground drops, corpse / chest contents) → landscape with the item class.</item>
/// <item>Ownership unreadable → gear-like types go to inventory, the rest to landscape.</item>
/// <item>Static non-fixture, non-container objects (doors, signs) → returns false; the caller keeps them Unknown scenery.</item>
/// </list>
/// Returns true when the object was placed and recorded in <see cref="_byId"/>.
/// </summary>
private bool PlaceTypedObject(uint uid, int id, string name, AcObjectClass cls, uint typeFlags)
{
bool isFixture = cls is AcObjectClass.Portal or AcObjectClass.Lifestone;
bool isDynamic = uid >= 0x80000000u;
bool toInventory;
if (isFixture)
{
toInventory = false;
}
else if (!isDynamic)
{
// Chests are static containers; other static objects stay Unknown scenery.
if ((typeFlags & ItemTypeContainer) == 0)
return false;
toInventory = false;
}
else
{
bool owned = IsOwnedByPlayer(id, out bool ownershipKnown);
toInventory = ownershipKnown
? owned
: (typeFlags & (ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer)) != 0;
}
_classifyRetry.Remove(uid);
_reclassifySkipState.Remove(uid);
if (toInventory)
{
if (_inventory.Add(id)) _inventoryDirty = true;
_landscape.Remove(id);
}
else
{
if (_inventory.Remove(id)) _inventoryDirty = true;
_landscape.Add(id);
}
_byId[id] = Make(id, name, cls);
TraceClassify(uid, name.Length > 0, true, true, typeFlags, toInventory ? $"typed->{cls}(inv)" : $"typed->{cls}(land)");
return true;
}
/// <summary>
/// True when the object is wielded by the player, sits in the player's main pack, or sits in
/// a side pack whose container is the player. <paramref name="known"/> is false when the
/// player id isn't set yet or the ownership read failed.
/// </summary>
private bool IsOwnedByPlayer(int id, out bool known)
{
known = false;
if (_playerId == 0 || !TryGetOwnership(id, out int containerId, out int wielderId, out _))
return false;
known = true;
uint container = unchecked((uint)containerId);
uint wielder = unchecked((uint)wielderId);
if (wielder == _playerId || container == _playerId)
return true;
// One level of nesting covers side packs (AC doesn't allow packs inside packs).
return container != 0
&& TryGetOwnership(containerId, out int outer, out _, out _)
&& unchecked((uint)outer) == _playerId;
}
// PublicWeenieDesc._bitfield BF_CORPSE (ObjectDescriptionFlag.Corpse).
private const uint BfCorpse = 0x2000;
@ -725,6 +799,7 @@ public class WorldObjectCache
List<int>? toPromote = null;
List<int>? toCorpse = null;
List<(int id, string name, AcObjectClass cls)>? statics = null;
List<(int Id, uint Flags)>? toType = null; // Unknowns whose ItemType is now a real item class
foreach (int id in _landscape)
{
uint uid = unchecked((uint)id);
@ -771,14 +846,21 @@ public class WorldObjectCache
// immediate signal that doesn't wait on qualities/appraisal). This
// second path is what rescues a login mob within 2s if it slipped
// to Unknown before its weenie/combat-state was readable.
bool isCreature = _host.TryGetItemType(uid, out uint typeFlags)
&& (typeFlags & ItemTypeCreature) != 0;
bool gotType = _host.TryGetItemType(uid, out uint typeFlags);
bool isCreature = gotType && (typeFlags & ItemTypeCreature) != 0;
if (!isCreature
&& _host.HasObjectIsAttackable
&& _host.ObjectIsAttackable(uid))
isCreature = true;
if (!isCreature)
{
// Type known now (or arrived late): place it as a real item instead of
// re-probing it every pass. Applied after the loop: placing mutates _landscape.
if (gotType && typeFlags != 0 && ClassifyByItemType(typeFlags) != AcObjectClass.Unknown)
{
(toType ??= new()).Add((id, typeFlags));
continue;
}
DiagLogReclassifySkip(uid, wo.Name);
continue;
}
@ -832,10 +914,27 @@ public class WorldObjectCache
_host.Log($"[RynthAi] ReclassifyUnknownDynamics: rescued {toCorpse.Count} stale corpse(s) → Corpse");
}
if (toType != null)
{
int placed = 0, toInv = 0;
foreach (var (id, flags) in toType)
{
if (!_byId.TryGetValue(id, out var wo)) continue;
uint uid = unchecked((uint)id);
// An Unknown result would be re-queued every pass, so leave it to the skip diag.
AcObjectClass cls = ClassifyItem(uid, flags);
if (cls == AcObjectClass.Unknown || !PlaceTypedObject(uid, id, wo.Name ?? string.Empty, cls, flags)) continue;
placed++;
if (_inventory.Contains(id)) toInv++;
}
_host.Log($"[RynthAi] ReclassifyUnknownDynamics: typed {placed} Unknown object(s) as items ({toInv} into inventory)");
}
// DIAG: heartbeat — Unknown landscape candidates checked but nothing promoted
// this pass. Confirms ReclassifyUnknownDynamics is running and engine signals
// keep failing for the stuck uids (vs. them never reaching _landscape at all).
if (toPromote == null
&& toType == null
&& _reclassifySkipState.Count > 0
&& _reclassifyDiagSummaryCount < MaxReclassifyDiagSummaries)
{
@ -1035,6 +1134,13 @@ public class WorldObjectCache
: defaultValue;
}
/// <summary>
/// True when ownership is readable and the object has neither a container nor a wielder,
/// so it lies loose in the world. Unreadable ownership is false (a pack item is never a ground drop).
/// </summary>
public bool IsOnGround(int id)
=> TryGetOwnership(id, out int containerId, out int wielderId, out _) && containerId == 0 && wielderId == 0;
public int GetContainerId(int id)
{
if (!TryGetOwnership(id, out int containerId, out _, out _))

View file

@ -530,16 +530,25 @@ public sealed partial class RynthAiPlugin
if (IsLootingBlockedByPack(settings) && !OwnCorpseBypassesPackGate(settings, maxMeters))
return;
if (!TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out _))
// A ground pickup already sent finishes before a corpse is claimed.
if (GroundPickupInFlight)
{
// No corpses in range. STEP 4: nothing to release. The "Looting"
// string used to be held here from a just-completed corpse and
// had to be handed back so nav could resume; now HasLootWork
// simply stops returning true and the arbiter moves on by itself
// on the next tick.
TickGroundLoot(settings, maxMeters);
return;
}
if (!TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out _))
{
// No corpses in range. Loose ground items that match the loot profile
// get their turn here; HasLootWork keeps Looting while any remain.
TickGroundLoot(settings, maxMeters);
return;
}
// A corpse outranks an unsent ground claim.
if (_groundTargetId != 0)
ResetGroundLoot(clearCaches: false);
if (corpse == null)
return;
@ -1571,7 +1580,7 @@ public sealed partial class RynthAiPlugin
if (maxMeters <= 0.25)
return false;
return HasUnlootedCorpsesInRange(maxMeters);
return HasUnlootedCorpsesInRange(maxMeters) || HasGroundLootWork(settings);
}
/// <summary>

View file

@ -58,10 +58,19 @@ internal static class CreatureWeakness
/// <summary>
/// The elements that hurt this monster most, or null when nothing is known. Order of
/// sources: the server table (wcid + name), then what the Damage tab learned
/// (<paramref name="learnedBest"/>) ahead of the creature-type ranking, then the type
/// ranking alone. <paramref name="creatureType"/> 0 = unknown (the name keywords decide).
/// (<paramref name="learnedBest"/>) ahead of the creature-type ranking, then the
/// UtilityBelt damage seed (<paramref name="seeded"/>, best first) ahead of the type
/// ranking, then the type ranking alone. <paramref name="creatureType"/> 0 = unknown
/// (the name keywords decide).
/// </summary>
public static Ranking? Rank(uint wcid, string? name, int creatureType, string? learnedBest)
/// <param name="seeded">
/// Damage types other players landed best on this monster (Monster Editor "Import UB
/// damage insights"), best first; null or empty = no seed. It reflects what players
/// owned as much as the monster's weakness, so it never outranks the server table or
/// this character's learned element; it only beats the generic creature-type average.
/// </param>
public static Ranking? Rank(uint wcid, string? name, int creatureType, string? learnedBest,
IReadOnlyList<string>? seeded = null)
{
EnsureLoaded();
name ??= "";
@ -86,11 +95,36 @@ internal static class CreatureWeakness
if (!e.Element.Equals(learned, StringComparison.OrdinalIgnoreCase)) r.Order.Add(e);
return r;
}
Ranking? seed = SeedRanking(seeded, type);
if (seed != null)
return seed;
if (type != null)
return new Ranking { Source = Pretty(type.Name) + " type", Order = new(type.Order) };
return null;
}
/// <summary>
/// The seed's elements (normalised, de-duplicated, no multiplier: only the order is known),
/// then the creature type's remaining elements. Null when the seed names no element.
/// </summary>
private static Ranking? SeedRanking(IReadOnlyList<string>? seeded, TypeInfo? type)
{
if (seeded == null || seeded.Count == 0) return null;
var r = new Ranking();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string raw in seeded)
{
string e = Normalize(raw);
if (e.Length > 0 && seen.Add(e)) r.Order.Add((e, double.NaN));
}
if (r.Order.Count == 0) return null;
r.Source = type != null ? $"UB seed, then {Pretty(type.Name)} type" : "UB seed";
if (type != null)
foreach (var e in type.Order)
if (seen.Add(e.Element)) r.Order.Add(e);
return r;
}
/// <summary>
/// The creature type the world-database table gives this monster (0 = not in it). Same match
/// as <see cref="Rank"/>: the wcid's row when its name agrees (or no name is given); no wcid,

View file

@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using RynthCore.CreatureSeed;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi.CreatureData;
/// <summary>
/// Read-only view of the UtilityBelt damage-type seed (<see cref="UbMobSeedFile"/>),
/// produced by the Monster Editor's "Import UB damage insights".
/// File: <c>&lt;SuiteDir&gt;\RynthAi\CreatureData\ub-mob-seed.json</c>.
/// <para>
/// Used only as a fallback for the "Auto" damage type when a monster has no appraised
/// resists: it ranks damage types by what players actually landed on that monster, which
/// reflects what they owned as much as the monster's weakness. Never written by the plugin
/// and never fed into the per-character <see cref="MonsterDamageStore"/>.
/// </para>
/// Lookups are made from the combat thread only; the lock guards the occasional reload.
/// </summary>
internal sealed class UbMobSeedStore
{
/// <summary>Minimum time between file-change checks (the editor may rewrite the seed while playing).</summary>
private static readonly TimeSpan ReloadCheckInterval = TimeSpan.FromSeconds(15);
private readonly object _lock = new();
private readonly Dictionary<uint, UbMobSeedEntry> _byWcid = new();
private readonly Dictionary<string, UbMobSeedEntry> _byName = new(StringComparer.OrdinalIgnoreCase);
private DateTime _loadedWriteUtc = DateTime.MinValue;
private DateTime _nextCheckUtc = DateTime.MinValue;
private static string FilePath =>
Path.Combine(RynthInstallPaths.RynthAiDir, "CreatureData", UbMobSeedFile.FileName);
/// <summary>Number of seeded monsters currently loaded (wcid + name-only).</summary>
public int Count { get { lock (_lock) return _byWcid.Count + CountNameOnly(); } }
/// <summary>Loads (or reloads) the seed when the file changed. Safe to call often.</summary>
public void Load()
{
lock (_lock)
{
_nextCheckUtc = DateTime.UtcNow + ReloadCheckInterval;
string path = FilePath;
if (!File.Exists(path))
{
Clear();
return;
}
DateTime writeUtc;
try { writeUtc = File.GetLastWriteTimeUtc(path); }
catch { return; }
if (writeUtc == _loadedWriteUtc) return;
try
{
var seed = JsonSerializer.Deserialize(File.ReadAllText(path), RynthAiJsonContext.Default.UbMobSeedFile);
Clear();
_loadedWriteUtc = writeUtc;
if (seed == null || seed.Version > UbMobSeedFile.CurrentVersion) return;
foreach (var e in seed.Entries)
{
if (e.Elements == null || e.Elements.Count < 2) continue;
if (e.Wcid != 0) _byWcid[e.Wcid] = e;
IndexName(e);
}
}
catch
{
// Corrupt or mid-write file: keep whatever was loaded before and retry on the next check.
}
}
}
/// <summary>
/// Ranked damage types (best first) for a monster: exact wcid first, then name.
/// Returns false when the seed has nothing comparable for it.
/// </summary>
public bool TryGetRanked(uint wcid, string? name, out IReadOnlyList<UbMobSeedElement> ranked)
{
lock (_lock)
{
// Checked under the lock: DateTime reads are not atomic on x86. Monitor is re-entrant.
if (DateTime.UtcNow >= _nextCheckUtc) Load();
UbMobSeedEntry? entry = null;
if (wcid != 0) _byWcid.TryGetValue(wcid, out entry);
if (entry == null && !string.IsNullOrWhiteSpace(name)) _byName.TryGetValue(name.Trim(), out entry);
ranked = entry?.Elements ?? (IReadOnlyList<UbMobSeedElement>)Array.Empty<UbMobSeedElement>();
return entry != null;
}
}
/// <summary>
/// Name index: a wcid entry beats a name-only one; among equals the most-hit entry wins
/// (tier variants share a name, so the busiest variant is the best guess).
/// </summary>
private void IndexName(UbMobSeedEntry e)
{
if (string.IsNullOrWhiteSpace(e.Name)) return;
string key = e.Name.Trim();
if (_byName.TryGetValue(key, out var existing))
{
bool existingHasWcid = existing.Wcid != 0, newHasWcid = e.Wcid != 0;
if (existingHasWcid && !newHasWcid) return;
if (existingHasWcid == newHasWcid && existing.TotalHits >= e.TotalHits) return;
}
_byName[key] = e;
}
private int CountNameOnly()
{
int n = 0;
foreach (var e in _byName.Values) if (e.Wcid == 0) n++;
return n;
}
private void Clear()
{
_byWcid.Clear();
_byName.Clear();
_loadedWriteUtc = DateTime.MinValue;
}
}

File diff suppressed because it is too large Load diff

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi;
@ -23,7 +24,7 @@ namespace RynthCore.Plugin.RynthAi;
internal static class DungeonHazardStore
{
// Sibling of the existing NavProfiles folder (see LegacyDashboardRenderer._navFolder).
private static readonly string Folder = @"C:\Games\RynthSuite\RynthAi\DungeonHazards";
private static readonly string Folder = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"DungeonHazards");
private static string PathFor(uint landblockKey)
=> System.IO.Path.Combine(Folder, $"{landblockKey:X4}.txt");

View file

@ -30,13 +30,14 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi;
internal static class DungeonHazardSurfaces
{
// Sibling of NavProfiles / DungeonHazards (LegacyDashboardRenderer._navFolder family).
private static readonly string Folder = @"C:\Games\RynthSuite\RynthAi";
private static readonly string Folder = RynthInstallPaths.RynthAiDir;
private static readonly string SetPath = System.IO.Path.Combine(Folder, "HazardTextures.txt");
private static readonly object _gate = new();

View file

@ -0,0 +1,355 @@
// GroundLootController.cs — picks up loose ground items that match the active loot profile
// (UB-IT AutoGroundLoot, driven by RynthAi's own loot rules and corpse range).
//
// * Scan: every GroundScanIntervalMs, objects lying in the world (readable ownership with
// no container / wielder, finite distance) within the corpse max range, minus scenery /
// creatures / doors / corpses, are classified with the same ClassifyItemAgainstProfile
// the corpse looter uses. Stat-gated rules get a server appraisal first (a few per scan),
// then a best-effort classify once GroundAppraiseWaitMs passes.
// * Pickup: only once the activity arbiter has handed the tick to Looting (HasLootWork sees
// the matches, so navigation is already stopped). MoveItemExternal(item → player); ACE
// walks the character to the item and picks it up. Confirmed when the item leaves the
// ground, retried up to GroundMaxPickupAttempts, then put on a long cooldown.
// * Corpses always win: ground loot only runs when no corpse is claimed or open.
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
private const long GroundScanIntervalMs = 300;
/// <summary>Classify best-effort after waiting this long for an item's appraisal.</summary>
private const long GroundAppraiseWaitMs = 3_000;
/// <summary>Server move-to plus pickup animation must finish inside this window before a retry.</summary>
private const long GroundPickupVerifyMs = 5_000;
/// <summary>A claimed item whose pickup could never be sent (client stayed busy) is dropped after this.</summary>
private const long GroundClaimStallMs = 10_000;
/// <summary>Items that matched no rule are re-checked after this (profile edits, late appraisal).</summary>
private const long GroundLeaveCooldownMs = 60_000;
private const long GroundFailCooldownMs = 300_000;
private const int GroundMaxPickupAttempts = 3;
private const int GroundAppraisalsPerScan = 2;
private long _groundLastScanAt;
private int _groundMatchesInRange;
private int _groundTargetId;
private long _groundTargetSince;
private long _groundPickupRequestedAt;
private int _groundPickupAttempts;
private string _groundTargetName = string.Empty;
private string _groundTargetAction = string.Empty;
private string _groundTargetRule = string.Empty;
private bool _groundTargetIsSalvage;
/// <summary>id → ms before which the item is not re-evaluated (left, failed or gone).</summary>
private readonly Dictionary<int, long> _groundSkipUntil = new();
/// <summary>id → ms of the first appraisal request (bounds the wait for stat data).</summary>
private readonly Dictionary<int, long> _groundAppraiseAt = new();
/// <summary>A pickup request is out and not yet confirmed — corpse claims wait for it.</summary>
private bool GroundPickupInFlight => _groundTargetId != 0 && _groundPickupRequestedAt != 0;
/// <summary>Arbiter input: a claimed ground item, or matching ground items seen by the last scan.</summary>
private bool HasGroundLootWork(LegacyUiSettings settings)
=> settings.EnableGroundLoot && (_groundTargetId != 0 || _groundMatchesInRange > 0);
/// <summary>
/// One ground-loot step (pump thread, called from TickCorpseOpening when no corpse is
/// claimed or open). Gating for macro / looting / buffing / combat is done by the caller.
/// </summary>
private void TickGroundLoot(LegacyUiSettings settings, double maxMeters)
{
if (!settings.EnableGroundLoot || _objectCache == null || _playerId == 0)
{
ResetGroundLoot(clearCaches: false);
return;
}
long now = CorpseNowMs;
if (_groundTargetId != 0)
{
TickGroundTarget(maxMeters, now);
return;
}
if (now - _groundLastScanAt < GroundScanIntervalMs)
return;
_groundLastScanAt = now;
PruneGroundCollections(now);
WorldObject? best = ScanGroundLoot(settings, maxMeters, now, out double bestDist,
out string action, out string rule, out bool salvage);
if (best == null)
return;
// HasLootWork reports the match; wait until the arbiter actually gives Looting the tick.
if (_activity != BotActivity.Looting)
return;
_groundTargetId = best.Id;
_groundTargetSince = now;
_groundPickupRequestedAt = 0;
_groundPickupAttempts = 0;
_groundTargetName = best.Name ?? string.Empty;
_groundTargetAction = action;
_groundTargetRule = rule;
_groundTargetIsSalvage = salvage;
if (!(_navStopIssued && _navStoppedFor == BotActivity.Looting))
StopNavFor(BotActivity.Looting);
LootDiag($"[RynthAi] Ground loot: claimed 0x{(uint)best.Id:X8} '{_groundTargetName}' dist={bestDist:F1}m [{action}] rule='{rule}'.");
TryRequestGroundPickup(now);
}
/// <summary>
/// Finds the nearest ground item that matches the loot profile and counts all matches
/// in range (for <see cref="HasGroundLootWork"/>). Requests appraisal for stat-gated items.
/// </summary>
private WorldObject? ScanGroundLoot(LegacyUiSettings settings, double maxMeters, long now,
out double bestDist, out string bestAction, out string bestRule, out bool bestSalvage)
{
bestDist = double.MaxValue;
bestAction = bestRule = string.Empty;
bestSalvage = false;
_groundMatchesInRange = 0;
if (_objectCache == null || maxMeters <= 0.25)
return null;
// The profile loaders chat on every failed load; a 300 ms scan must not trigger that.
string profilePath = (settings.CurrentLootPath ?? string.Empty).Trim().Trim('"');
if (profilePath.Length == 0 || !System.IO.File.Exists(profilePath))
return null;
int playerId = unchecked((int)_playerId);
int appraisalsSent = 0;
WorldObject? best = null;
foreach (WorldObject wo in _objectCache.AllKnownObjects())
{
if (wo.Id == playerId || IsGroundLootExcludedClass(wo.ObjectClass))
continue;
if (_groundSkipUntil.TryGetValue(wo.Id, out long until))
{
if (until > now) continue;
_groundSkipUntil.Remove(wo.Id);
}
if (string.IsNullOrWhiteSpace(wo.Name))
continue;
// Carried / contained items have no world position, so Distance is MaxValue for them.
double dist = _objectCache.Distance(playerId, wo.Id);
if (dist > maxMeters)
continue;
if (!_objectCache.IsOnGround(wo.Id))
continue;
uint uid = unchecked((uint)wo.Id);
bool appraised = Host.HasHasAppraisalData && Host.HasAppraisalData(uid);
if (!appraised && ItemNeedsAppraisalForLoot(wo))
{
if (!_groundAppraiseAt.TryGetValue(wo.Id, out long firstAsk))
{
if (appraisalsSent < GroundAppraisalsPerScan && _busyCount == 0 && Host.RequestId(uid))
{
_groundAppraiseAt[wo.Id] = now;
appraisalsSent++;
}
continue;
}
if (now - firstAsk < GroundAppraiseWaitMs)
continue;
// Appraisal never arrived — classify best-effort, like the corpse assess window.
}
bool keep = ClassifyItemAgainstProfile(wo, settings, out string action, out bool salvage, out string rule);
LootDiag($"[LootEval] ground '{wo.Name}' cls={wo.ObjectClass} dist={dist:F1}m appraised={appraised} -> " +
(keep ? $"KEEP [{action}] rule='{rule}'" : "leave"));
if (!keep)
{
_groundSkipUntil[wo.Id] = now + GroundLeaveCooldownMs;
continue;
}
_groundMatchesInRange++;
if (dist < bestDist)
{
best = wo;
bestDist = dist;
bestAction = action;
bestRule = rule;
bestSalvage = salvage;
}
}
return best;
}
/// <summary>Follows a claimed item: confirm pickup, retry, or give up.</summary>
private void TickGroundTarget(double maxMeters, long now)
{
if (_objectCache == null)
return;
int id = _groundTargetId;
WorldObject? item = _objectCache[id];
if (item == null)
{
// Deleted from the world: decayed or another player took it.
LootDiag($"[RynthAi] Ground loot: 0x{(uint)id:X8} '{_groundTargetName}' is gone.");
FinishGroundTarget(now, GroundFailCooldownMs);
return;
}
if (!_objectCache.IsOnGround(id) && _objectCache.GetContainerId(id) != 0)
{
LootDiag($"[RynthAi] Ground loot: pickup confirmed for 0x{(uint)id:X8} '{_groundTargetName}'.");
ChatLine($"[RynthAi] Looted [{_groundTargetAction}] {_groundTargetName} (ground)");
if (_groundTargetIsSalvage)
_salvageManager?.EnqueueItem(unchecked((uint)id));
FinishGroundTarget(now, GroundFailCooldownMs);
return;
}
int playerId = unchecked((int)_playerId);
double dist = _objectCache.Distance(playerId, id);
if (dist > Math.Max(maxMeters * 1.5, maxMeters + 2.0))
{
LootDiag($"[RynthAi] Ground loot: 0x{(uint)id:X8} '{_groundTargetName}' drifted out of range ({dist:F1}m); releasing.");
FinishGroundTarget(now, GroundLeaveCooldownMs);
return;
}
if (_groundPickupRequestedAt == 0)
{
if (now - _groundTargetSince > GroundClaimStallMs)
{
LootDiag($"[RynthAi] Ground loot: could not send pickup for 0x{(uint)id:X8} (client busy); releasing.");
FinishGroundTarget(now, GroundLeaveCooldownMs);
return;
}
TryRequestGroundPickup(now);
return;
}
if (now - _groundPickupRequestedAt < GroundPickupVerifyMs)
return;
if (_groundPickupAttempts >= GroundMaxPickupAttempts)
{
LootDiag($"[RynthAi] Ground loot: pickup failed for 0x{(uint)id:X8} '{_groundTargetName}' after {_groundPickupAttempts} attempt(s).");
FinishGroundTarget(now, GroundFailCooldownMs);
return;
}
TryRequestGroundPickup(now);
}
/// <summary>Sends the pickup (item → player's main pack) when the client isn't busy.</summary>
private void TryRequestGroundPickup(long now)
{
if (_busyCount > 0 || _groundTargetId == 0)
return;
uint uid = unchecked((uint)_groundTargetId);
Host.SelectItem(uid);
bool sent = Host.HasMoveItemExternal
? Host.MoveItemExternal(uid, _playerId, 0)
: Host.UseObject(uid);
_groundPickupAttempts++;
_groundPickupRequestedAt = now;
LootDiag($"[RynthAi] Ground loot: pickup {(sent ? "sent" : "rejected")} for 0x{uid:X8} attempt {_groundPickupAttempts}.");
}
/// <summary>Releases the claimed item and parks it for <paramref name="cooldownMs"/>.</summary>
private void FinishGroundTarget(long now, long cooldownMs)
{
if (_groundTargetId != 0)
{
_groundSkipUntil[_groundTargetId] = now + cooldownMs;
_groundAppraiseAt.Remove(_groundTargetId);
}
_groundTargetId = 0;
_groundTargetSince = 0;
_groundPickupRequestedAt = 0;
_groundPickupAttempts = 0;
_groundTargetName = _groundTargetAction = _groundTargetRule = string.Empty;
_groundTargetIsSalvage = false;
_groundLastScanAt = 0; // rescan straight away for the next item
}
/// <summary>Drops the claim (and optionally the per-item caches, e.g. on logout or /ra groundloot scan).</summary>
private void ResetGroundLoot(bool clearCaches)
{
_groundTargetId = 0;
_groundTargetSince = 0;
_groundPickupRequestedAt = 0;
_groundPickupAttempts = 0;
_groundTargetName = _groundTargetAction = _groundTargetRule = string.Empty;
_groundTargetIsSalvage = false;
_groundMatchesInRange = 0;
if (!clearCaches)
return;
_groundSkipUntil.Clear();
_groundAppraiseAt.Clear();
_groundLastScanAt = 0;
}
/// <summary>Keeps the per-item maps bounded.</summary>
private void PruneGroundCollections(long now)
{
if (_groundSkipUntil.Count > 512)
{
var expired = new List<int>();
foreach (var kv in _groundSkipUntil)
if (kv.Value <= now) expired.Add(kv.Key);
foreach (int k in expired) _groundSkipUntil.Remove(k);
}
if (_groundAppraiseAt.Count > 256)
{
var stale = new List<int>();
foreach (var kv in _groundAppraiseAt)
if (now - kv.Value > GroundLeaveCooldownMs) stale.Add(kv.Key);
foreach (int k in stale) _groundAppraiseAt.Remove(k);
}
}
/// <summary>Scenery, creatures, fixtures and containers are never picked up from the ground.</summary>
private static bool IsGroundLootExcludedClass(AcObjectClass cls) => cls is
AcObjectClass.Unknown or AcObjectClass.Monster or AcObjectClass.Player or AcObjectClass.Npc
or AcObjectClass.Vendor or AcObjectClass.Portal or AcObjectClass.Door or AcObjectClass.Corpse
or AcObjectClass.Lifestone or AcObjectClass.Sign or AcObjectClass.Housing or AcObjectClass.Container
or AcObjectClass.CombatPet or AcObjectClass.Services;
/// <summary>/ra groundloot [on|off|status|scan]</summary>
private void HandleGroundLootCommand(string[] parts)
{
var settings = _dashboard?.Settings;
if (settings == null) { ChatLine("[RynthAi] Not logged in."); return; }
string verb = parts.Length >= 3 ? parts[2].Trim().ToLowerInvariant() : "status";
switch (verb)
{
case "on":
settings.EnableGroundLoot = true;
_dashboard?.SaveSettings();
ChatLine("[RynthAi] Ground loot ON (uses the loot profile and the corpse max range).");
break;
case "off":
settings.EnableGroundLoot = false;
ResetGroundLoot(clearCaches: true);
_dashboard?.SaveSettings();
ChatLine("[RynthAi] Ground loot OFF.");
break;
case "scan":
ResetGroundLoot(clearCaches: true);
ChatLine("[RynthAi] Ground loot: cleared skip list; rescanning.");
break;
default:
double yards = settings.CorpseApproachRangeMax;
string target = _groundTargetId != 0 ? $" | target '{_groundTargetName}' attempts={_groundPickupAttempts}" : string.Empty;
ChatLine($"[RynthAi] Ground loot {(settings.EnableGroundLoot ? "ON" : "OFF")} | range {yards:0.#} yd | " +
$"looting {(settings.EnableLooting ? "on" : "off")} | matches in range {_groundMatchesInRange} | " +
$"skipped {_groundSkipUntil.Count}{target}");
break;
}
}
}

View file

@ -0,0 +1,223 @@
// CombatHudTracker.cs — Pump-thread feed for the Mini Remote's Target and Summon rows.
//
// Target the creature combat is attacking (CombatManager.activeTargetId): name, health
// ratio from the object cache, distance.
// Summon the player's pet ("<Player>'s <Pet>" in the landscape): health ratio (polled with
// QueryHealth) and time left (RemainingLifespan from one appraisal, then counted
// down locally).
//
// The render thread only reads the published immutable snapshot.
using System;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Huds;
/// <summary>Immutable view of the attack target and the active summon (render thread safe).</summary>
internal sealed record CombatHudSnapshot(
int TargetId,
string TargetName,
float TargetHealth, // 0..1, -1 = no health received yet
double TargetDistance, // yards, < 0 = unknown
int PetId,
string PetName,
float PetHealth, // 0..1, -1 = no health received yet
long PetExpiresAtMs, // Environment.TickCount64 deadline, 0 = lifespan unknown
int PetLifespanSec, // total lifespan, 0 = unknown
long PetSeenAtMs) // when this pet first appeared
{
public static readonly CombatHudSnapshot Empty = new(0, string.Empty, -1f, -1, 0, string.Empty, -1f, 0, 0, 0);
}
internal sealed class CombatHudTracker
{
private const uint StypeLifespan = 267;
private const uint StypeRemainingLifespan = 268;
private const long ThinkIntervalMs = 250;
// QueryHealth makes the server stream that creature's health to us instead of the previous
// query's, so each pet poll is followed by a re-query of the combat / selected target.
private const long PetHealthPollMs = 3000;
private const long AppraiseRetryMs = 5000;
private const int AppraiseMaxAttempts = 3;
private const long PlayerNameRefreshMs = 30_000;
private readonly RynthCoreHost _host;
private readonly Func<WorldObjectCache?> _cache;
private readonly Func<int> _attackTargetId;
private volatile CombatHudSnapshot _snapshot = CombatHudSnapshot.Empty;
private long _lastThinkAt;
private string _playerName = string.Empty;
private long _playerNameAt;
// Current pet bookkeeping.
private int _petId;
private long _petSeenAt;
private long _petExpiresAt;
private int _petLifespanSec;
private int _appraiseAttempts;
private long _lastAppraiseAt;
private long _lastPetHealthAt;
public CombatHudTracker(RynthCoreHost host, Func<WorldObjectCache?> cache, Func<int> attackTargetId)
{
_host = host;
_cache = cache;
_attackTargetId = attackTargetId;
}
/// <summary>Latest target / summon view.</summary>
public CombatHudSnapshot Snapshot => _snapshot;
private static long NowMs => Environment.TickCount64;
/// <summary>Refreshes the snapshot (pump thread). Cheap when called every tick.</summary>
public void Tick()
{
long now = NowMs;
if (now - _lastThinkAt < ThinkIntervalMs) return;
_lastThinkAt = now;
var cache = _cache();
if (cache == null) { _snapshot = CombatHudSnapshot.Empty; return; }
int playerId = unchecked((int)_host.GetPlayerId());
int targetId = _attackTargetId();
// ── Attack target ──
string targetName = string.Empty;
float targetHealth = -1f;
double targetDist = -1;
if (targetId != 0)
{
targetName = cache[targetId]?.Name ?? string.Empty;
if (targetName.Length == 0 && _host.TryGetObjectName(unchecked((uint)targetId), out string n)) targetName = n;
if (targetName.Length == 0) targetName = $"0x{(uint)targetId:X8}";
targetHealth = cache.GetHealthRatio(targetId);
if (playerId != 0)
{
double d = cache.Distance(playerId, targetId);
targetDist = d < double.MaxValue ? d : -1;
}
}
// ── Summon ──
var pet = FindOwnPet(cache);
string petName = string.Empty;
float petHealth = -1f;
if (pet == null)
{
ForgetPet();
}
else
{
if (pet.Id != _petId) StartTrackingPet(pet.Id, now);
petName = StripOwner(pet.Name);
TickPetLifespan(now);
TickPetHealth(now, targetId);
petHealth = cache.GetHealthRatio(_petId);
}
_snapshot = new CombatHudSnapshot(targetId, targetName, targetHealth, targetDist,
_petId, petName, petHealth, _petExpiresAt, _petLifespanSec, _petSeenAt);
}
public void OnLogout()
{
ForgetPet();
_playerName = string.Empty;
_snapshot = CombatHudSnapshot.Empty;
}
// ── Pet ─────────────────────────────────────────────────────────────────
private WorldObject? FindOwnPet(WorldObjectCache cache)
{
string me = PlayerName();
if (me.Length == 0) return null;
string prefix = me + "'s ";
foreach (var wo in cache.GetLandscape())
if (wo != null && !string.IsNullOrEmpty(wo.Name) && wo.Name.StartsWith(prefix, StringComparison.Ordinal))
return wo;
return null;
}
private string PlayerName()
{
long now = NowMs;
if (_playerName.Length > 0 && now - _playerNameAt < PlayerNameRefreshMs) return _playerName;
uint pid = _host.GetPlayerId();
if (pid != 0 && _host.TryGetObjectName(pid, out string n) && !string.IsNullOrEmpty(n))
{
_playerName = n;
_playerNameAt = now;
}
return _playerName;
}
/// <summary>"Silent's Fire Banshee" → "Fire Banshee".</summary>
private string StripOwner(string name)
{
string prefix = _playerName + "'s ";
return _playerName.Length > 0 && name.StartsWith(prefix, StringComparison.Ordinal) ? name[prefix.Length..] : name;
}
private void StartTrackingPet(int id, long now)
{
_petId = id;
_petSeenAt = now;
_petExpiresAt = 0;
_petLifespanSec = 0;
_appraiseAttempts = 0;
_lastAppraiseAt = 0;
_lastPetHealthAt = 0;
RynthLog.Trace(LogCat.Huds, $"summon tracked 0x{(uint)id:X8}");
}
private void ForgetPet()
{
_petId = 0;
_petSeenAt = 0;
_petExpiresAt = 0;
_petLifespanSec = 0;
_appraiseAttempts = 0;
}
/// <summary>
/// Appraises the new pet (at most <see cref="AppraiseMaxAttempts"/> times) and anchors the
/// countdown on the first RemainingLifespan the server returns. The pet's guid is new, so
/// any cached value belongs to this pet.
/// </summary>
private void TickPetLifespan(long now)
{
if (_petExpiresAt != 0) return;
uint uid = unchecked((uint)_petId);
if (_host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(uid, StypeRemainingLifespan, out int remaining) && remaining > 0)
{
_petExpiresAt = now + remaining * 1000L;
if (_host.TryGetObjectIntProperty(uid, StypeLifespan, out int total) && total > 0)
_petLifespanSec = Math.Max(total, remaining);
RynthLog.Trace(LogCat.Huds, $"summon 0x{uid:X8}: {remaining}s left of {_petLifespanSec}s");
return;
}
if (_appraiseAttempts >= AppraiseMaxAttempts || !_host.HasRequestId) return;
if (_lastAppraiseAt != 0 && now - _lastAppraiseAt < AppraiseRetryMs) return;
_appraiseAttempts++;
_lastAppraiseAt = now;
_host.RequestId(uid);
}
/// <summary>Polls the pet's health, then hands the server's health stream back to the fight target.</summary>
private void TickPetHealth(long now, int combatTargetId)
{
if (!_host.HasQueryHealth || now - _lastPetHealthAt < PetHealthPollMs) return;
_lastPetHealthAt = now;
_host.QueryHealth(unchecked((uint)_petId));
uint restore = combatTargetId != 0 ? unchecked((uint)combatTargetId) : 0;
if (restore == 0 && _host.HasGetSelectedItemId) restore = _host.GetSelectedItemId();
if (restore != 0 && restore != unchecked((uint)_petId)) _host.QueryHealth(restore);
}
}

View file

@ -0,0 +1,442 @@
// #region License
// /*
// Microsoft Public License (Ms-PL)
// MonoGame - Copyright © 2009 The MonoGame Team
//
// All rights reserved.
//
// This license governs use of the accompanying software. If you use the software, you accept this license. If you do not
// accept the license, do not use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under
// U.S. copyright law.
//
// A "contribution" is the original software, or any additions or changes to the software.
// A "contributor" is any person that distributes its contribution under this license.
// "Licensed patents" are a contributor's patent claims that read directly on its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
// each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
// each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software,
// your patent license from such contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution
// notices that are present in the software.
// (D) If you distribute any portion of the software in source code form, you may do so only under this license by including
// a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object
// code form, you may only do so under a license that complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees
// or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent
// permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular
// purpose and non-infringement.
// */
// #endregion License
//
namespace RynthCore.Plugin.RynthAi.Huds
{
using System.IO;
internal static class DxtUtil
{
internal static byte[] DecompressDxt1(byte[] imageData, int width, int height)
{
using (MemoryStream imageStream = new MemoryStream(imageData))
return DecompressDxt1(imageStream, width, height);
}
internal static byte[] DecompressDxt1(Stream imageStream, int width, int height)
{
byte[] imageData = new byte[width * height * 4];
using (BinaryReader imageReader = new BinaryReader(imageStream))
{
int blockCountX = (width + 3) / 4;
int blockCountY = (height + 3) / 4;
for (int y = 0; y < blockCountY; y++)
{
for (int x = 0; x < blockCountX; x++)
{
DecompressDxt1Block(imageReader, x, y, blockCountX, width, height, imageData);
}
}
}
return imageData;
}
private static void DecompressDxt1Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
{
ushort c0 = imageReader.ReadUInt16();
ushort c1 = imageReader.ReadUInt16();
byte r0, g0, b0;
byte r1, g1, b1;
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
uint lookupTable = imageReader.ReadUInt32();
for (int blockY = 0; blockY < 4; blockY++)
{
for (int blockX = 0; blockX < 4; blockX++)
{
byte r = 0, g = 0, b = 0, a = 255;
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
if (c0 > c1)
{
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((2 * r0 + r1) / 3);
g = (byte)((2 * g0 + g1) / 3);
b = (byte)((2 * b0 + b1) / 3);
break;
case 3:
r = (byte)((r0 + 2 * r1) / 3);
g = (byte)((g0 + 2 * g1) / 3);
b = (byte)((b0 + 2 * b1) / 3);
break;
}
}
else
{
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((r0 + r1) / 2);
g = (byte)((g0 + g1) / 2);
b = (byte)((b0 + b1) / 2);
break;
case 3:
r = 0;
g = 0;
b = 0;
a = 0;
break;
}
}
int px = (x << 2) + blockX;
int py = (y << 2) + blockY;
if ((px < width) && (py < height))
{
int offset = ((py * width) + px) << 2;
imageData[offset] = r;
imageData[offset + 1] = g;
imageData[offset + 2] = b;
imageData[offset + 3] = a;
}
}
}
}
internal static byte[] DecompressDxt3(byte[] imageData, int width, int height)
{
using (MemoryStream imageStream = new MemoryStream(imageData))
return DecompressDxt3(imageStream, width, height);
}
internal static byte[] DecompressDxt3(Stream imageStream, int width, int height)
{
byte[] imageData = new byte[width * height * 4];
using (BinaryReader imageReader = new BinaryReader(imageStream))
{
int blockCountX = (width + 3) / 4;
int blockCountY = (height + 3) / 4;
for (int y = 0; y < blockCountY; y++)
{
for (int x = 0; x < blockCountX; x++)
{
DecompressDxt3Block(imageReader, x, y, blockCountX, width, height, imageData);
}
}
}
return imageData;
}
private static void DecompressDxt3Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
{
byte a0 = imageReader.ReadByte();
byte a1 = imageReader.ReadByte();
byte a2 = imageReader.ReadByte();
byte a3 = imageReader.ReadByte();
byte a4 = imageReader.ReadByte();
byte a5 = imageReader.ReadByte();
byte a6 = imageReader.ReadByte();
byte a7 = imageReader.ReadByte();
ushort c0 = imageReader.ReadUInt16();
ushort c1 = imageReader.ReadUInt16();
byte r0, g0, b0;
byte r1, g1, b1;
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
uint lookupTable = imageReader.ReadUInt32();
int alphaIndex = 0;
for (int blockY = 0; blockY < 4; blockY++)
{
for (int blockX = 0; blockX < 4; blockX++)
{
byte r = 0, g = 0, b = 0, a = 0;
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
switch (alphaIndex)
{
case 0:
a = (byte)((a0 & 0x0F) | ((a0 & 0x0F) << 4));
break;
case 1:
a = (byte)((a0 & 0xF0) | ((a0 & 0xF0) >> 4));
break;
case 2:
a = (byte)((a1 & 0x0F) | ((a1 & 0x0F) << 4));
break;
case 3:
a = (byte)((a1 & 0xF0) | ((a1 & 0xF0) >> 4));
break;
case 4:
a = (byte)((a2 & 0x0F) | ((a2 & 0x0F) << 4));
break;
case 5:
a = (byte)((a2 & 0xF0) | ((a2 & 0xF0) >> 4));
break;
case 6:
a = (byte)((a3 & 0x0F) | ((a3 & 0x0F) << 4));
break;
case 7:
a = (byte)((a3 & 0xF0) | ((a3 & 0xF0) >> 4));
break;
case 8:
a = (byte)((a4 & 0x0F) | ((a4 & 0x0F) << 4));
break;
case 9:
a = (byte)((a4 & 0xF0) | ((a4 & 0xF0) >> 4));
break;
case 10:
a = (byte)((a5 & 0x0F) | ((a5 & 0x0F) << 4));
break;
case 11:
a = (byte)((a5 & 0xF0) | ((a5 & 0xF0) >> 4));
break;
case 12:
a = (byte)((a6 & 0x0F) | ((a6 & 0x0F) << 4));
break;
case 13:
a = (byte)((a6 & 0xF0) | ((a6 & 0xF0) >> 4));
break;
case 14:
a = (byte)((a7 & 0x0F) | ((a7 & 0x0F) << 4));
break;
case 15:
a = (byte)((a7 & 0xF0) | ((a7 & 0xF0) >> 4));
break;
}
++alphaIndex;
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((2 * r0 + r1) / 3);
g = (byte)((2 * g0 + g1) / 3);
b = (byte)((2 * b0 + b1) / 3);
break;
case 3:
r = (byte)((r0 + 2 * r1) / 3);
g = (byte)((g0 + 2 * g1) / 3);
b = (byte)((b0 + 2 * b1) / 3);
break;
}
int px = (x << 2) + blockX;
int py = (y << 2) + blockY;
if ((px < width) && (py < height))
{
int offset = ((py * width) + px) << 2;
imageData[offset] = r;
imageData[offset + 1] = g;
imageData[offset + 2] = b;
imageData[offset + 3] = a;
}
}
}
}
internal static byte[] DecompressDxt5(byte[] imageData, int width, int height)
{
using (MemoryStream imageStream = new MemoryStream(imageData))
return DecompressDxt5(imageStream, width, height);
}
internal static byte[] DecompressDxt5(Stream imageStream, int width, int height)
{
byte[] imageData = new byte[width * height * 4];
using (BinaryReader imageReader = new BinaryReader(imageStream))
{
int blockCountX = (width + 3) / 4;
int blockCountY = (height + 3) / 4;
for (int y = 0; y < blockCountY; y++)
{
for (int x = 0; x < blockCountX; x++)
{
DecompressDxt5Block(imageReader, x, y, blockCountX, width, height, imageData);
}
}
}
return imageData;
}
private static void DecompressDxt5Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
{
byte alpha0 = imageReader.ReadByte();
byte alpha1 = imageReader.ReadByte();
ulong alphaMask = (ulong)imageReader.ReadByte();
alphaMask += (ulong)imageReader.ReadByte() << 8;
alphaMask += (ulong)imageReader.ReadByte() << 16;
alphaMask += (ulong)imageReader.ReadByte() << 24;
alphaMask += (ulong)imageReader.ReadByte() << 32;
alphaMask += (ulong)imageReader.ReadByte() << 40;
ushort c0 = imageReader.ReadUInt16();
ushort c1 = imageReader.ReadUInt16();
byte r0, g0, b0;
byte r1, g1, b1;
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
uint lookupTable = imageReader.ReadUInt32();
for (int blockY = 0; blockY < 4; blockY++)
{
for (int blockX = 0; blockX < 4; blockX++)
{
byte r = 0, g = 0, b = 0, a = 255;
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
uint alphaIndex = (uint)((alphaMask >> 3 * (4 * blockY + blockX)) & 0x07);
if (alphaIndex == 0)
{
a = alpha0;
}
else if (alphaIndex == 1)
{
a = alpha1;
}
else if (alpha0 > alpha1)
{
a = (byte)(((8 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 7);
}
else if (alphaIndex == 6)
{
a = 0;
}
else if (alphaIndex == 7)
{
a = 0xff;
}
else
{
a = (byte)(((6 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 5);
}
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((2 * r0 + r1) / 3);
g = (byte)((2 * g0 + g1) / 3);
b = (byte)((2 * b0 + b1) / 3);
break;
case 3:
r = (byte)((r0 + 2 * r1) / 3);
g = (byte)((g0 + 2 * g1) / 3);
b = (byte)((b0 + 2 * b1) / 3);
break;
}
int px = (x << 2) + blockX;
int py = (y << 2) + blockY;
if ((px < width) && (py < height))
{
int offset = ((py * width) + px) << 2;
imageData[offset] = r;
imageData[offset + 1] = g;
imageData[offset + 2] = b;
imageData[offset + 3] = a;
}
}
}
}
private static void ConvertRgb565ToRgb888(ushort color, out byte r, out byte g, out byte b)
{
int temp;
temp = (color >> 11) * 255 + 16;
r = (byte)((temp / 32 + temp) / 32);
temp = ((color & 0x07E0) >> 5) * 255 + 32;
g = (byte)((temp / 64 + temp) / 64);
temp = (color & 0x001F) * 255 + 16;
b = (byte)((temp / 32 + temp) / 32);
}
}
}

View file

@ -0,0 +1,480 @@
// HudController.cs — Owner of RynthAi's floating HUD windows.
//
// * Pack item count HUD (ItemCountHud): icon + carried count for pinned items.
// * Mini Remote (MiniRemoteHud): session stats, attack target, summon (health / time
// left, fed by CombatHudTracker), 30 quick-use item slots, macro toggles, bank balances
// and rebuff buttons.
// * Inventory HUDs setup window (HudSetupUi): picks what the two HUDs show. Opened from
// the Inventory Management settings (ImGui Advanced Settings, the Avalonia Settings
// panel) or "/ra huds".
// Every HUD is an ordinary ImGui window, so it can be docked into / undocked from other
// ImGui windows and dragged outside the game window (multi-viewport).
//
// Threading: host reads and every game action run on the pump thread (Tick / posted
// actions). The render thread only reads the published pack snapshot and toggles simple
// flags; list edits are posted so the pump thread is the only writer.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.IltHub;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Huds;
/// <summary>One carried item name, aggregated over every stack in the pack.</summary>
internal sealed record HudPackRow(string Name, uint Wcid, uint IconDid, long Count, int FirstId);
/// <summary>Immutable pack view published by the pump thread.</summary>
internal sealed class HudPackSnapshot
{
public static readonly HudPackSnapshot Empty = new(Array.Empty<HudPackRow>());
public HudPackRow[] Rows { get; }
public Dictionary<string, HudPackRow> ByName { get; }
public HudPackSnapshot(HudPackRow[] rows)
{
Rows = rows;
ByName = new Dictionary<string, HudPackRow>(StringComparer.OrdinalIgnoreCase);
foreach (var r in rows) ByName[r.Name] = r;
}
public long CountOf(string name) => ByName.TryGetValue(name, out var r) ? r.Count : 0;
}
internal sealed class HudController
{
private const uint StypeIcon = 8; // DataID Icon → PWD _iconID
private const int StypeStackSize = 12;
private const long PackScanIntervalMs = 1000;
private const long SaveIntervalMs = 5000;
private readonly RynthCoreHost _host;
private readonly Func<WorldObjectCache?> _cache;
private readonly HudStore _store;
private readonly ConcurrentQueue<Action> _posted = new();
private readonly Dictionary<int, uint> _iconById = new();
private readonly ItemCountHud _itemHud;
private readonly MiniRemoteHud _miniRemote;
private readonly HudSetupUi _setup;
private readonly CombatHudTracker _combat;
private volatile HudPackSnapshot _pack = HudPackSnapshot.Empty;
private long _lastScanAt;
private long _lastSaveAt;
private bool _scanRequested;
/// <summary>
/// How long a pack item the player selected stays assignable after the game selection moves
/// on (the combat bot re-selects monsters, so "the selected item" is often gone by the time
/// the player clicks a slot).
/// </summary>
private const long RememberSelectionMs = 120_000;
private uint _lastSeenSelection;
private int _lastPackSelId;
private long _lastPackSelAt;
private volatile string _assignCandidate = string.Empty;
public HudController(RynthCoreHost host, string charFolder, Func<WorldObjectCache?> cache,
LegacyDashboardRenderer dashboard, Func<IltHubController?> hub, HudIconCache icons, Func<int> attackTargetId)
{
_host = host;
_cache = cache;
_store = new HudStore(charFolder);
State = _store.Load();
Icons = icons;
Dashboard = dashboard;
Hub = hub;
_itemHud = new ItemCountHud(this);
_miniRemote = new MiniRemoteHud(this);
_setup = new HudSetupUi(this);
_combat = new CombatHudTracker(host, cache, attackTargetId);
}
public HudState State { get; }
public HudIconCache Icons { get; }
public LegacyDashboardRenderer Dashboard { get; }
public Func<IltHubController?> Hub { get; }
public RynthCoreHost Host => _host;
/// <summary>Latest pack view (render thread safe).</summary>
public HudPackSnapshot Pack => _pack;
/// <summary>Latest attack target / summon view (render thread safe).</summary>
public CombatHudSnapshot Combat => _combat.Snapshot;
/// <summary>
/// Name of the pack item a slot click would assign (current or remembered selection); empty
/// when there is none. Render thread safe.
/// </summary>
public string AssignCandidate => _assignCandidate;
/// <summary>Chat translator views for the Mini Remote row; null until the translator exists.</summary>
public RynthCore.Plugin.RynthAi.Translate.TranslateUi? Translate { get; set; }
/// <summary>Queues work for the next pump tick (safe from the render thread).</summary>
public void Post(Action action) => _posted.Enqueue(action);
private static long NowMs => Environment.TickCount64;
// ── Pump thread ─────────────────────────────────────────────────────────
public void Tick()
{
int guard = 0;
while (guard++ < 64 && _posted.TryDequeue(out var a))
{
try { a(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "posted HUD action"); }
}
long now = NowMs;
// The pack is only scanned while something shows it.
bool needPack = State.ShowItemHud || State.ShowMiniRemote || State.ShowSetup;
if (needPack && (_scanRequested || now - _lastScanAt >= PackScanIntervalMs))
{
_scanRequested = false;
_lastScanAt = now;
RebuildPack();
}
Icons.Tick();
if (State.ShowMiniRemote || State.ShowSetup || State.ShowItemHud) TrackPackSelection(now);
// Target / summon polling sends health queries and appraisals, so it only runs while shown.
if (State.ShowMiniRemote && (State.MiniShowTarget || State.MiniShowPet))
_combat.Tick();
if (now - _lastSaveAt >= SaveIntervalMs)
{
_lastSaveAt = now;
_store.SaveIfDirty(State);
}
}
public void OnLogout()
{
_store.SaveIfDirty(State);
_pack = HudPackSnapshot.Empty;
_iconById.Clear();
_combat.OnLogout();
}
/// <summary>Aggregates the pack by item name and refreshes pinned entries' icon / WCID.</summary>
private void RebuildPack()
{
var cache = _cache();
if (cache == null) return;
var byName = new Dictionary<string, HudPackRow>(StringComparer.OrdinalIgnoreCase);
var seen = new HashSet<int>();
foreach (var wo in cache.GetInventory())
{
if (wo == null || string.IsNullOrWhiteSpace(wo.Name)) continue;
seen.Add(wo.Id);
long count = Math.Max(1, wo.Values(StypeStackSize, 1));
if (byName.TryGetValue(wo.Name, out var row))
{
byName[wo.Name] = row with { Count = row.Count + count };
continue;
}
byName[wo.Name] = new HudPackRow(wo.Name, Wcid(wo), IconOf(wo), count, wo.Id);
}
// Forget icon lookups for items that left the pack.
if (_iconById.Count > seen.Count + 64)
foreach (int id in _iconById.Keys.Where(k => !seen.Contains(k)).ToList()) _iconById.Remove(id);
var snap = new HudPackSnapshot(byName.Values.OrderBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray());
_pack = snap;
// Remember icon / WCID on pinned entries so they still draw while none are carried.
foreach (var e in State.ItemHudItems.Concat(State.MiniRemoteSlots))
{
if (e.IsEmpty || !snap.ByName.TryGetValue(e.Name, out var r)) continue;
if (r.IconDid != 0) e.IconDid = r.IconDid;
if (r.Wcid != 0) e.Wcid = r.Wcid;
}
}
private uint IconOf(WorldObject wo)
{
if (_iconById.TryGetValue(wo.Id, out uint icon) && icon != 0) return icon;
if (_host.HasGetObjectDataIdProperty && _host.TryGetObjectDataIdProperty(unchecked((uint)wo.Id), StypeIcon, out icon))
_iconById[wo.Id] = icon;
return icon;
}
private uint Wcid(WorldObject wo)
=> _host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)wo.Id), out uint w) ? w : 0;
// ── Actions (pump thread; post them from the render thread) ──────────────
/// <summary>Rescans the pack on the next tick.</summary>
public void RequestScan() => _scanRequested = true;
/// <summary>Uses one carried item by name (falls back to WCID when the name changed).</summary>
public void UseItem(HudItemEntry entry)
{
if (entry.IsEmpty) return;
var cache = _cache();
if (cache == null || !_host.HasUseObject) return;
var inv = cache.GetInventory().Where(w => w != null).ToList();
var wo = inv.FirstOrDefault(w => w.Name.Equals(entry.Name, StringComparison.OrdinalIgnoreCase))
?? (entry.Wcid != 0 ? inv.FirstOrDefault(w => Wcid(w) == entry.Wcid) : null);
if (wo == null) { Chat($"[RynthAi] No {entry.Name} in your pack."); return; }
_host.UseObject(unchecked((uint)wo.Id));
RynthLog.Trace(LogCat.Huds, $"use {wo.Name} (0x{wo.Id:X8})");
}
/// <summary>Carried item by object id, or null.</summary>
private WorldObject? PackItem(int id)
=> id == 0 ? null : _cache()?.GetInventory().FirstOrDefault(w => w != null && w.Id == id);
/// <summary>
/// Remembers the last pack item selected in the game (native inventory, or the RynthCore
/// Inventory window, which mirrors its clicks to the game selection). Only re-checks the
/// pack when the selection changes.
/// </summary>
private void TrackPackSelection(long now)
{
if (!_host.HasGetSelectedItemId) return;
uint sel = _host.GetSelectedItemId();
if (sel != _lastSeenSelection)
{
_lastSeenSelection = sel;
var wo = PackItem(unchecked((int)sel));
if (wo != null)
{
_lastPackSelId = wo.Id;
_lastPackSelAt = now;
}
}
// The candidate label only feeds tooltips / menus: refresh it a few times a second.
if (now - _lastCandidateAt < 250) return;
_lastCandidateAt = now;
var candidate = AssignablePackItem(quiet: true);
_assignCandidate = candidate?.Name ?? string.Empty;
}
private long _lastCandidateAt;
/// <summary>
/// The pack item to assign: the current game selection when it is carried, otherwise the
/// last carried item the player selected within <see cref="RememberSelectionMs"/>.
/// </summary>
private WorldObject? AssignablePackItem(bool quiet = false)
{
if (!_host.HasGetSelectedItemId)
{
if (!quiet) Chat("[RynthAi] This client build can't read the selected item.");
return null;
}
uint selected = _host.GetSelectedItemId();
var wo = PackItem(unchecked((int)selected));
bool fellBack = false;
long rememberedAge = NowMs - _lastPackSelAt;
if (wo == null && _lastPackSelId != 0 && rememberedAge <= RememberSelectionMs)
{
wo = PackItem(_lastPackSelId);
fellBack = wo != null;
}
// Quiet calls feed tooltips several times a second: only real assignments are traced.
if (!quiet)
{
string selInfo = selected == 0 ? "none" : $"0x{selected:X8} ({(fellBack || wo == null ? DescribeCacheEntry(unchecked((int)selected)) : "in inventory")})";
string result = wo == null ? "nothing to assign"
: fellBack ? $"fell back to remembered 0x{_lastPackSelId:X8} '{wo.Name}' ({rememberedAge / 1000.0:0.0} s old)"
: $"selected '{wo.Name}'";
RynthLog.Trace(LogCat.Huds, $"assign candidate: selected={selInfo}; {result}");
}
if (wo == null && !quiet)
Chat("[RynthAi] Click an item in your pack (game inventory or RynthCore Inventory) first, "
+ "or drag it from the RynthCore Inventory onto the slot.");
return wo;
}
/// <summary>The item to act on for "use the selected item" HUD actions.</summary>
private WorldObject? SelectedPackItem() => AssignablePackItem();
public void AddSelectedToItemHud()
{
var wo = SelectedPackItem();
if (wo != null) AddToItemHud(wo.Name);
}
public void AddToItemHud(string name)
{
if (string.IsNullOrWhiteSpace(name) || State.ItemHudItems.Any(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase))) return;
var row = _pack.ByName.TryGetValue(name, out var r) ? r : null;
State.ItemHudItems.Add(new HudItemEntry { Name = name, Wcid = row?.Wcid ?? 0, IconDid = row?.IconDid ?? 0 });
RynthLog.Trace(LogCat.Huds, $"item HUD += '{name}' (first id 0x{(uint)(row?.FirstId ?? 0):X8}, wcid {row?.Wcid ?? 0}, in pack scan: {(row != null ? "yes" : "no")})");
}
/// <summary>
/// Adds <paramref name="name"/> to the item count HUD (if missing) and shows the HUD.
/// Icon and WCID fill in on the next pack scan. Returns the chat confirmation.
/// </summary>
public string AddToItemHudAndShow(string name)
{
name = name.Trim();
bool already = State.ItemHudItems.Any(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (!already) AddToItemHud(name);
State.ShowItemHud = true;
RequestScan();
return already ? $"{name} is already on the item count HUD." : $"Added {name} to the item count HUD.";
}
public void RemoveFromItemHud(string name)
=> State.ItemHudItems.RemoveAll(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
/// <summary>Moves a HUD entry up (-1) or down (+1) in display order.</summary>
public void MoveItemHudEntry(string name, int delta)
{
var list = State.ItemHudItems;
int i = list.FindIndex(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
int j = i + delta;
if (i < 0 || j < 0 || j >= list.Count) return;
(list[i], list[j]) = (list[j], list[i]);
}
/// <summary>Removes HUD entries for items no longer carried.</summary>
public void DropMissingFromItemHud()
{
var pack = _pack;
int n = State.ItemHudItems.RemoveAll(e => pack.CountOf(e.Name) == 0);
Chat(n > 0 ? $"[RynthAi] Removed {n} item(s) you no longer carry from the HUD." : "[RynthAi] Every HUD item is still in your pack.");
}
/// <summary>Puts the selected (or last selected) pack item into Mini Remote slot <paramref name="slot"/>.</summary>
public void SetSlotFromSelection(int slot)
{
if (slot < 0 || slot >= State.MiniRemoteSlots.Count) return;
var wo = AssignablePackItem();
if (wo != null) AssignSlot(slot, wo);
}
/// <summary>
/// Puts carried item <paramref name="objectId"/> into <paramref name="slot"/> (-1 = first empty
/// slot). Used by drag-and-drop from the RynthCore Inventory and its "Add to Mini Remote" menu.
/// </summary>
public void SetSlotFromItemId(int slot, uint objectId)
{
var wo = PackItem(unchecked((int)objectId));
if (wo == null)
{
// The cache's view of the id shows a classification miss (item filed outside inventory).
int invCount = _cache()?.GetInventory().Count() ?? -1;
RynthLog.Trace(LogCat.Huds, $"slot-from-id: 0x{objectId:X8} not in inventory ({invCount} items); {DescribeCacheEntry(unchecked((int)objectId))}");
Chat("[RynthAi] That item is no longer in your pack.");
return;
}
RynthLog.Trace(LogCat.Huds, $"slot-from-id: 0x{objectId:X8} = '{wo.Name}' ({wo.ObjectClass}), requested slot {(slot < 0 ? "first empty" : (slot + 1).ToString("00"))}");
if (slot < 0) slot = State.MiniRemoteSlots.FindIndex(e => e.IsEmpty);
if (slot < 0) { Chat("[RynthAi] Every Mini Remote slot is in use. Clear one first (right-click it)."); return; }
if (slot >= State.MiniRemoteSlots.Count) return;
AssignSlot(slot, wo);
}
private void AssignSlot(int slot, WorldObject wo)
{
var row = _pack.ByName.TryGetValue(wo.Name, out var r) ? r : null;
var entry = new HudItemEntry { Name = wo.Name, Wcid = row?.Wcid ?? Wcid(wo), IconDid = row?.IconDid ?? IconOf(wo) };
State.MiniRemoteSlots[slot] = entry;
RynthLog.Trace(LogCat.Huds, $"assign slot {slot + 1:00} = '{wo.Name}' 0x{(uint)wo.Id:X8} (wcid {entry.Wcid}, icon 0x{entry.IconDid:X8})");
Chat($"[RynthAi] Mini Remote slot {slot + 1:00} = {wo.Name}.");
}
/// <summary>How the world cache knows <paramref name="id"/> (for traces): name and class, or that it doesn't.</summary>
private string DescribeCacheEntry(int id)
{
var cache = _cache();
if (cache == null) return "no world cache";
var wo = cache[id];
return wo == null ? "unknown to the world cache" : $"world cache has '{wo.Name}' as {wo.ObjectClass}";
}
/// <summary>
/// Remote command "remoteslot &lt;slot|first&gt; &lt;objectId&gt;" (RynthCore Inventory menu).
/// Slot is 1-based. Returns false when the value can't be parsed.
/// </summary>
public bool HandleRemoteSlot(string value)
{
var parts = (value ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
int slot = 0;
bool ok = parts.Length == 2 && uint.TryParse(parts[1], out _);
if (ok)
{
if (parts[0].Equals("first", StringComparison.OrdinalIgnoreCase)) slot = -1;
else if (int.TryParse(parts[0], out int n) && n >= 1) slot = n - 1;
else ok = false;
}
if (!ok)
{
RynthLog.Trace(LogCat.Huds, $"remoteslot '{value}': can't parse (expected '<slot|first> <objectId>')");
return false;
}
uint id = uint.Parse(parts[1]);
RynthLog.Trace(LogCat.Huds, $"remoteslot '{value}': slot {(slot < 0 ? "first empty" : (slot + 1).ToString("00"))}, id 0x{id:X8}");
SetSlotFromItemId(slot, id);
return true;
}
public void ClearSlot(int slot)
{
if (slot >= 0 && slot < State.MiniRemoteSlots.Count) State.MiniRemoteSlots[slot] = new HudItemEntry();
}
public void Chat(string text)
{
// Every message the player sees also lands in the Huds trace.
RynthLog.Trace(LogCat.Huds, "chat: " + text);
if (_host.HasWriteToChat) _host.WriteToChat(text, 1);
}
/// <summary>
/// "/ra huds|itemhud|remote [show|hide|toggle]" and the matching remote command.
/// Returns the chat confirmation.
/// </summary>
public string HandleCommand(string which, string mode)
{
static bool Resolve(string m, bool current) => m.ToLowerInvariant() switch
{
"show" or "on" or "true" or "1" => true,
"hide" or "off" or "false" or "0" => false,
_ => !current,
};
switch (which)
{
case "itemhud":
State.ShowItemHud = Resolve(mode, State.ShowItemHud);
return State.ShowItemHud ? "Pack item count HUD shown." : "Pack item count HUD hidden.";
case "remote":
case "miniremote":
State.ShowMiniRemote = Resolve(mode, State.ShowMiniRemote);
return State.ShowMiniRemote ? "Mini Remote shown." : "Mini Remote hidden.";
default:
State.ShowSetup = Resolve(mode, State.ShowSetup);
return State.ShowSetup ? "Inventory HUDs window shown." : "Inventory HUDs window hidden.";
}
}
// ── Render thread ───────────────────────────────────────────────────────
public void Render()
{
int pushed = LegacyDashboardRenderer.PushDashboardStyle();
try
{
if (State.ShowSetup) _setup.Render();
if (State.ShowItemHud) _itemHud.Render(); else _itemHud.OnHidden();
if (State.ShowMiniRemote) _miniRemote.Render(); else _miniRemote.OnHidden();
}
finally
{
ImGuiNET.ImGui.PopStyleColor(pushed);
}
}
}

View file

@ -0,0 +1,56 @@
// HudDraw.cs — Small ImGui drawing helpers shared by the HUD windows (render thread only).
using System;
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi.Huds;
internal static class HudDraw
{
private static readonly Vector4 Opaque = new(1f, 1f, 1f, 1f);
private static readonly Vector4 Faded = new(1f, 1f, 1f, 0.35f);
private static readonly Vector4 NoBorder = Vector4.Zero;
/// <summary>
/// Draws an item icon of <paramref name="size"/> pixels. While the texture is still
/// loading (or the item has no icon) a framed box with the name's first letter stands in.
/// <paramref name="dim"/> fades it (e.g. none carried).
/// </summary>
public static void Icon(HudIconCache icons, uint iconDid, string name, float size, bool dim)
{
IntPtr tex = icons.GetTexture(iconDid);
var sz = new Vector2(size, size);
if (tex != IntPtr.Zero)
{
ImGui.Image(tex, sz, Vector2.Zero, Vector2.One, dim ? Faded : Opaque, NoBorder);
return;
}
Placeholder(name, sz, dim);
}
/// <summary>Framed stand-in with the item's first letter, same footprint as an icon.</summary>
public static void Placeholder(string name, Vector2 size, bool dim)
{
Vector2 p = ImGui.GetCursorScreenPos();
ImGui.Dummy(size);
var dl = ImGui.GetWindowDrawList();
uint frame = ImGui.GetColorU32(new Vector4(0.45f, 0.55f, 0.65f, dim ? 0.35f : 0.8f));
uint fill = ImGui.GetColorU32(new Vector4(0.12f, 0.16f, 0.22f, dim ? 0.35f : 0.8f));
dl.AddRectFilled(p, p + size, fill, 3f);
dl.AddRect(p, p + size, frame, 3f);
if (string.IsNullOrEmpty(name)) return;
string letter = name.Substring(0, 1).ToUpperInvariant();
Vector2 ts = ImGui.CalcTextSize(letter);
dl.AddText(p + (size - ts) * 0.5f, ImGui.GetColorU32(new Vector4(0.9f, 0.9f, 0.9f, dim ? 0.4f : 1f)), letter);
}
/// <summary>"1468", "12.3k", "4.5m", "1.2b" — compact counts for tight HUD rows.</summary>
public 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");
}
}

View file

@ -0,0 +1,266 @@
// HudIconCache.cs — Item icons for the RynthAi HUD windows.
//
// An item's icon DID (PWD _iconID, 0x06xxxxxx) points at a Texture file in portal.dat.
// Decoding (dat read + pixel conversion) runs on the pump thread; the D3D9 texture is
// created lazily on the render thread, a few per frame, so a full pack never stalls a frame.
// Textures are POOL_MANAGED (they survive device resets) and are never released: plugin
// unload can run off the render thread, where touching the device is unsafe, and the
// whole set is a few hundred 32×32 icons.
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Huds;
internal sealed class HudIconCache
{
// IDirect3DDevice9 / IDirect3DTexture9 vtable slots.
private const int VtCreateTexture = 23;
private const int VtLockRect = 19;
private const int VtUnlockRect = 20;
private const int VtRelease = 2;
private const uint D3DFMT_A8R8G8B8 = 21;
private const uint D3DPOOL_MANAGED = 1;
/// <summary>Texture uploads allowed per rendered frame.</summary>
private const int UploadsPerFrame = 6;
/// <summary>Icons decoded per pump tick.</summary>
private const int DecodesPerTick = 12;
/// <summary>Runaway guard; a full character's icons are a few hundred.</summary>
private const int MaxIcons = 4000;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage, uint fmt, uint pool, out IntPtr tex, IntPtr shared);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int LockRectD(IntPtr tex, uint level, ref D3DLockedRect locked, IntPtr rect, uint flags);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int UnlockRectD(IntPtr tex, uint level);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseD(IntPtr obj);
[StructLayout(LayoutKind.Sequential)]
private struct D3DLockedRect { public int Pitch; public IntPtr Bits; }
/// <summary>Decoded icon in D3D A8R8G8B8 order (A&lt;&lt;24 | R&lt;&lt;16 | G&lt;&lt;8 | B).</summary>
private sealed class Decoded
{
public int Width;
public int Height;
public uint[] Pixels = Array.Empty<uint>();
}
private readonly RynthCoreHost _host;
private readonly Func<DatDatabase?> _portal;
// DID → decoded pixels (null value = decode failed, don't retry).
private readonly ConcurrentDictionary<uint, Decoded?> _decoded = new();
// DIDs the render thread asked for that the pump thread hasn't decoded yet.
private readonly ConcurrentQueue<uint> _pending = new();
private readonly ConcurrentDictionary<uint, byte> _queued = new();
// Render thread only.
private readonly System.Collections.Generic.Dictionary<uint, IntPtr> _textures = new();
private IntPtr _textureDevice;
private int _uploadFrame = -1;
private int _uploadsThisFrame;
public HudIconCache(RynthCoreHost host, Func<DatDatabase?> portal)
{
_host = host;
_portal = portal;
}
// ── Render thread ───────────────────────────────────────────────────────
/// <summary>
/// ImGui texture id for <paramref name="iconDid"/>, or IntPtr.Zero while it is still
/// being decoded / uploaded (callers draw a placeholder).
/// </summary>
public IntPtr GetTexture(uint iconDid)
{
if (iconDid == 0) return IntPtr.Zero;
IntPtr device = _host.D3DDevice;
if (device == IntPtr.Zero) return IntPtr.Zero;
// A new device means the old textures belong to a dead device; forget them (not
// Release — the owning device may already be gone).
if (device != _textureDevice)
{
_textures.Clear();
_textureDevice = device;
}
if (_textures.TryGetValue(iconDid, out IntPtr tex)) return tex;
if (!_decoded.TryGetValue(iconDid, out Decoded? d))
{
if (_queued.TryAdd(iconDid, 0)) _pending.Enqueue(iconDid);
return IntPtr.Zero;
}
if (d == null) return IntPtr.Zero;
int frame = ImGuiNET.ImGui.GetFrameCount();
if (frame != _uploadFrame) { _uploadFrame = frame; _uploadsThisFrame = 0; }
if (_uploadsThisFrame >= UploadsPerFrame) return IntPtr.Zero;
_uploadsThisFrame++;
tex = Upload(device, d);
// Failed uploads are remembered as Zero so they aren't retried every frame.
_textures[iconDid] = tex;
return tex;
}
// ── Pump thread ─────────────────────────────────────────────────────────
/// <summary>Decodes a batch of requested icons (dat reads stay off the render thread).</summary>
public void Tick()
{
var portal = _portal();
if (portal == null || !portal.IsLoaded) return;
for (int i = 0; i < DecodesPerTick && _pending.TryDequeue(out uint did); i++)
{
_queued.TryRemove(did, out _);
if (_decoded.Count >= MaxIcons) { _decoded.TryAdd(did, null); continue; }
Decoded? d = null;
try { d = Decode(portal, did); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, $"icon decode 0x{did:X8}"); }
_decoded[did] = d;
}
}
// ── Decoding (Texture 0x06 → ARGB) ──────────────────────────────────────
// Texture layout: Id(u32) Unknown(i32) Width(i32) Height(i32) Format(u32) Length(i32)
// Source[Length], then DefaultPaletteId(u32) for INDEX16 / P8.
private static Decoded? Decode(DatDatabase portal, uint textureId)
{
byte[]? data = portal.GetFileData(textureId);
if (data == null || data.Length < 24) return null;
using var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); r.ReadInt32();
int w = r.ReadInt32(), h = r.ReadInt32();
uint fmt = r.ReadUInt32();
int len = r.ReadInt32();
if (w <= 0 || h <= 0 || w > 1024 || h > 1024 || len < 0 || ms.Position + len > ms.Length) return null;
byte[] src = r.ReadBytes(len);
uint palId = 0;
if ((fmt == 101 || fmt == 41) && ms.Position + 4 <= ms.Length) palId = r.ReadUInt32();
var px = new uint[w * h];
static uint Argb(int a, int rr, int g, int b) => ((uint)a << 24) | ((uint)rr << 16) | ((uint)g << 8) | (uint)b;
switch (fmt)
{
case 827611204: return FromRgba(DxtUtil.DecompressDxt1(src, w, h), w, h); // DXT1
case 861165636: return FromRgba(DxtUtil.DecompressDxt3(src, w, h), w, h); // DXT3
case 894720068: return FromRgba(DxtUtil.DecompressDxt5(src, w, h), w, h); // DXT5
case 20: // R8G8B8, stored B,G,R
for (int i = 0; i < px.Length && i * 3 + 2 < src.Length; i++) px[i] = Argb(255, src[i * 3 + 2], src[i * 3 + 1], src[i * 3]);
break;
case 21: // A8R8G8B8, stored B,G,R,A
case 22: // X8R8G8B8
for (int i = 0; i < px.Length && i * 4 + 3 < src.Length; i++)
px[i] = Argb(fmt == 22 ? 255 : src[i * 4 + 3], src[i * 4 + 2], src[i * 4 + 1], src[i * 4]);
break;
case 23: // R5G6B5
for (int i = 0; i < px.Length && i * 2 + 1 < src.Length; i++)
{
int v = src[i * 2] | (src[i * 2 + 1] << 8);
px[i] = Argb(255, ((v >> 11) & 0x1F) << 3, ((v >> 5) & 0x3F) << 2, (v & 0x1F) << 3);
}
break;
case 26: // A4R4G4B4
for (int i = 0; i < px.Length && i * 2 + 1 < src.Length; i++)
{
int v = src[i * 2] | (src[i * 2 + 1] << 8);
px[i] = Argb(((v >> 12) & 0xF) * 17, ((v >> 8) & 0xF) * 17, ((v >> 4) & 0xF) * 17, (v & 0xF) * 17);
}
break;
case 28: // A8 greyscale
for (int i = 0; i < px.Length && i < src.Length; i++) px[i] = Argb(255, src[i], src[i], src[i]);
break;
case 101: // INDEX16
case 41: // P8
{
uint[]? pal = LoadPalette(portal, palId);
if (pal == null || pal.Length == 0) return null;
bool p8 = fmt == 41;
for (int i = 0; i < px.Length; i++)
{
int idx;
if (p8) { if (i >= src.Length) break; idx = src[i]; }
else { if (i * 2 + 1 >= src.Length) break; idx = src[i * 2] | (src[i * 2 + 1] << 8); }
px[i] = pal[idx % pal.Length]; // palette entries are already ARGB
}
break;
}
default:
return null;
}
return new Decoded { Width = w, Height = h, Pixels = px };
}
/// <summary>Palette (0x04): Id(u32), Count(i32), Count × ARGB(u32).</summary>
private static uint[]? LoadPalette(DatDatabase portal, uint paletteId)
{
byte[]? data = portal.GetFileData(paletteId);
if (data == null || data.Length < 8) return null;
int n = BitConverter.ToInt32(data, 4);
if (n <= 0 || n > 65536) return null;
n = Math.Min(n, (data.Length - 8) / 4);
var pal = new uint[n];
for (int i = 0; i < n; i++) pal[i] = BitConverter.ToUInt32(data, 8 + i * 4);
return pal;
}
/// <summary>DxtUtil output (R,G,B,A bytes) → ARGB.</summary>
private static Decoded FromRgba(byte[] rgba, int w, int h)
{
var px = new uint[w * h];
for (int i = 0; i < px.Length && i * 4 + 3 < rgba.Length; i++)
px[i] = ((uint)rgba[i * 4 + 3] << 24) | ((uint)rgba[i * 4] << 16) | ((uint)rgba[i * 4 + 1] << 8) | rgba[i * 4 + 2];
return new Decoded { Width = w, Height = h, Pixels = px };
}
// ── D3D9 upload (render thread) ─────────────────────────────────────────
private static unsafe IntPtr Upload(IntPtr device, Decoded d)
{
try
{
int hr = Vt<CreateTextureD>(device, VtCreateTexture)(device, (uint)d.Width, (uint)d.Height, 1, 0,
D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out IntPtr tex, IntPtr.Zero);
if (hr < 0 || tex == IntPtr.Zero) return IntPtr.Zero;
var locked = new D3DLockedRect();
if (Vt<LockRectD>(tex, VtLockRect)(tex, 0, ref locked, IntPtr.Zero, 0) < 0)
{
Vt<ReleaseD>(tex, VtRelease)(tex);
return IntPtr.Zero;
}
// Row by row: the locked pitch can be wider than Width * 4.
for (int row = 0; row < d.Height; row++)
{
fixed (uint* src = &d.Pixels[row * d.Width])
Buffer.MemoryCopy(src, (void*)IntPtr.Add(locked.Bits, row * locked.Pitch), d.Width * 4, d.Width * 4);
}
Vt<UnlockRectD>(tex, VtUnlockRect)(tex, 0);
return tex;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.Huds, ex, "icon upload");
return IntPtr.Zero;
}
}
private static unsafe T Vt<T>(IntPtr obj, int index) where T : Delegate
{
void** vt = *(void***)obj;
return Marshal.GetDelegateForFunctionPointer<T>((IntPtr)vt[index]);
}
}

View file

@ -0,0 +1,183 @@
// HudSetupUi.cs — "Inventory HUDs" setup window (UtilityBelt Item Hud tab equivalent).
//
// * Show / hide the pack item count HUD and the Mini Remote.
// * Two lists: items on the HUD (left) and carried items not on it (right).
// "<" pins the highlighted right row, ">" unpins the highlighted left row,
// Up / Down reorder the HUD. "Add from inventory" pins the item selected in the game.
// * Mini Remote slots: pick a slot, then Set (selected game item) or Clear.
// Render thread only; list edits are posted to the pump thread.
using System;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.Huds;
internal sealed class HudSetupUi
{
private const float ListIcon = 18f;
private readonly HudController _hud;
private string _selOnHud = string.Empty;
private string _selInPack = string.Empty;
private string _packFilter = string.Empty;
private int _slot;
public HudSetupUi(HudController hud) => _hud = hud;
public void Render()
{
var s = _hud.State;
ImGui.SetNextWindowSize(new Vector2(640, 520), ImGuiCond.FirstUseEver);
bool open = true;
bool visible = ImGui.Begin("Inventory HUDs##rynthhudsetup", ref open);
if (!open) s.ShowSetup = false;
if (!visible) { ImGui.End(); return; }
RenderHudToggles(s);
ImGui.Separator();
RenderItemLists(s);
ImGui.Separator();
RenderSlotPicker(s);
ImGui.End();
}
private static void RenderHudToggles(HudState s)
{
bool itemHud = s.ShowItemHud;
if (ImGui.Checkbox("Show pack item count HUD", ref itemHud)) s.ShowItemHud = itemHud;
ImGui.SameLine();
bool names = s.ItemHudShowNames;
if (ImGui.Checkbox("with names", ref names)) s.ItemHudShowNames = names;
ImGui.SameLine();
bool remote = s.ShowMiniRemote;
if (ImGui.Checkbox("Show Mini Remote", ref remote)) s.ShowMiniRemote = remote;
ImGui.TextDisabled("Both are separate windows: drag them anywhere, dock them into other RynthAi windows,");
ImGui.TextDisabled("or pull them outside the game window. Right-click a HUD for its options.");
}
private void RenderItemLists(HudState s)
{
ImGui.TextWrapped("Left = shown on the HUD. Right = in your pack but not on the HUD. "
+ "< pins the highlighted right row; > removes the highlighted left row. "
+ "Add from inventory uses the item selected in the game.");
if (ImGui.Button("Scan pack")) _hud.Post(_hud.RequestScan);
ImGui.SameLine();
if (ImGui.Button("Add from inventory")) _hud.Post(_hud.AddSelectedToItemHud);
ImGui.SameLine();
if (ImGui.Button("Drop missing")) _hud.Post(_hud.DropMissingFromItemHud);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Remove HUD items you no longer carry.");
var entries = s.ItemHudItems.ToArray();
var pack = _hud.Pack;
float listH = 230f;
float colW = Math.Max(180f, (ImGui.GetContentRegionAvail().X - 50f) * 0.5f);
// ── Left: on the HUD ──
ImGui.BeginGroup();
ImGui.TextUnformatted($"On HUD ({entries.Length})");
if (ImGui.BeginChild("##hudon", new Vector2(colW, listH), ImGuiChildFlags.Borders))
{
foreach (var e in entries)
{
long count = pack.CountOf(e.Name);
if (Row(e.Name, e.IconDid, $"{e.Name} | {count:N0}", _selOnHud == e.Name, count == 0))
_selOnHud = e.Name;
}
}
ImGui.EndChild();
bool haveLeft = entries.Any(e => e.Name == _selOnHud);
ImGui.BeginDisabled(!haveLeft);
string upName = _selOnHud;
if (ImGui.SmallButton("Up")) _hud.Post(() => _hud.MoveItemHudEntry(upName, -1));
ImGui.SameLine();
if (ImGui.SmallButton("Down")) _hud.Post(() => _hud.MoveItemHudEntry(upName, +1));
ImGui.EndDisabled();
ImGui.EndGroup();
// ── Middle: move buttons ──
ImGui.SameLine();
ImGui.BeginGroup();
ImGui.Dummy(new Vector2(1, listH * 0.35f));
ImGui.BeginDisabled(string.IsNullOrEmpty(_selInPack));
string add = _selInPack;
if (ImGui.Button("<", new Vector2(36, 0))) { _hud.Post(() => _hud.AddToItemHud(add)); _selInPack = string.Empty; }
ImGui.EndDisabled();
ImGui.BeginDisabled(!haveLeft);
string remove = _selOnHud;
if (ImGui.Button(">", new Vector2(36, 0))) { _hud.Post(() => _hud.RemoveFromItemHud(remove)); _selOnHud = string.Empty; }
ImGui.EndDisabled();
ImGui.EndGroup();
// ── Right: in pack, not on the HUD ──
ImGui.SameLine();
ImGui.BeginGroup();
ImGui.TextUnformatted("Not on HUD");
ImGui.SameLine();
ImGui.SetNextItemWidth(Math.Max(80f, colW - 90f));
ImGui.InputTextWithHint("##hudpackfilter", "filter", ref _packFilter, 64u);
if (ImGui.BeginChild("##hudoff", new Vector2(colW, listH), ImGuiChildFlags.Borders))
{
var pinned = entries.Select(e => e.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var r in pack.Rows)
{
if (pinned.Contains(r.Name)) continue;
if (_packFilter.Length > 0 && !r.Name.Contains(_packFilter, StringComparison.OrdinalIgnoreCase)) continue;
if (Row(r.Name, r.IconDid, $"{r.Name} | {r.Count:N0}", _selInPack == r.Name, false))
_selInPack = r.Name;
// Double-click pins straight away.
if (ImGui.IsItemHovered() && ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left))
{
string name = r.Name;
_hud.Post(() => _hud.AddToItemHud(name));
}
}
if (pack.Rows.Length == 0) ImGui.TextDisabled("Scanning your pack...");
}
ImGui.EndChild();
ImGui.EndGroup();
}
/// <summary>Icon + label selectable row; returns true when clicked.</summary>
private bool Row(string name, uint iconDid, string label, bool selected, bool dim)
{
Vector2 start = ImGui.GetCursorPos();
bool clicked = ImGui.Selectable($"##row{name}", selected, ImGuiSelectableFlags.AllowOverlap, new Vector2(0, ListIcon));
ImGui.SetCursorPos(start);
HudDraw.Icon(_hud.Icons, iconDid, name, ListIcon, dim);
ImGui.SameLine();
if (dim) ImGui.TextDisabled(label);
else ImGui.TextUnformatted(label);
return clicked;
}
private void RenderSlotPicker(HudState s)
{
var slots = s.MiniRemoteSlots.ToArray();
if (slots.Length == 0) return;
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Mini Remote slots");
ImGui.TextDisabled($"Slot 01 = top-left of the Mini Remote grid ({HudState.MiniRemoteColumns} per row). "
+ "Select an item in your pack, pick the slot, then Set.");
_slot = Math.Clamp(_slot, 0, slots.Length - 1);
string Label(int i) => $"{i + 1:00} - {(slots[i].IsEmpty ? "(empty)" : slots[i].Name)}";
ImGui.SetNextItemWidth(320);
if (ImGui.BeginCombo("##mrslot", Label(_slot)))
{
for (int i = 0; i < slots.Length; i++)
if (ImGui.Selectable(Label(i), i == _slot)) _slot = i;
ImGui.EndCombo();
}
int slot = _slot;
ImGui.SameLine();
if (ImGui.Button("Set")) _hud.Post(() => _hud.SetSlotFromSelection(slot));
ImGui.SameLine();
ImGui.BeginDisabled(slots[slot].IsEmpty);
if (ImGui.Button("Clear")) _hud.Post(() => _hud.ClearSlot(slot));
ImGui.EndDisabled();
ImGui.SameLine();
if (ImGui.Button("Refresh")) _hud.Post(_hud.RequestScan);
}
}

View file

@ -0,0 +1,119 @@
// HudState.cs — Persisted per-character settings for the floating HUD windows
// (<charFolder>\huds.json). Fields, not properties, so the source-generated
// RynthAiJsonContext (IncludeFields) round-trips them under NativeAOT.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.Plugin.RynthAi.Huds;
public sealed class HudState
{
/// <summary>Mini Remote gem grid size (UB layout: 5 columns × 6 rows).</summary>
public const int MiniRemoteColumns = 5;
public const int MiniRemoteSlotCount = 30;
/// <summary>The "Inventory HUDs" setup window is open.</summary>
public bool ShowSetup;
// ── Pack item count HUD ──
public bool ShowItemHud;
public bool ItemHudShowNames;
public bool ItemHudLocked;
public float ItemHudIconSize = 20f;
/// <summary>Items shown on the HUD, in display order (matched by name).</summary>
public List<HudItemEntry> ItemHudItems = new();
// ── Mini Remote ──
public bool ShowMiniRemote;
public bool MiniRemoteLocked;
/// <summary>Sections laid out side by side in columns (the V/H button) instead of stacked.</summary>
public bool MiniRemoteHorizontal;
public bool MiniShowStats = true;
/// <summary>Attack target row: name, health bar, distance.</summary>
public bool MiniShowTarget = true;
/// <summary>Pet row: the summon that is out (health, time left), else the next combat essence.</summary>
public bool MiniShowPet = true;
public bool MiniShowGems = true;
public bool MiniShowToggles = true;
public bool MiniShowBank = true;
public bool MiniShowRebuff = true;
/// <summary>Chat translator row: on/off, receive / send language swap.</summary>
public bool MiniShowTranslate = true;
/// <summary>Temple guardian row: the last riddle answer with a Give button (only while one is recent).</summary>
public bool MiniShowGuardian = true;
/// <summary>Gem grid slots, row-major from the top-left (empty Name = unassigned).</summary>
public List<HudItemEntry> MiniRemoteSlots = new();
}
/// <summary>An item pinned to a HUD. Matched by name; Wcid / IconDid are remembered so the
/// entry still shows its icon while none are carried.</summary>
public sealed class HudItemEntry
{
public string Name = string.Empty;
public uint Wcid;
public uint IconDid;
[JsonIgnore] public bool IsEmpty => string.IsNullOrWhiteSpace(Name);
}
/// <summary>Loads / dirty-checked saves of <see cref="HudState"/>.</summary>
internal sealed class HudStore
{
private readonly string _charFolder;
private string _lastJson = string.Empty;
public HudStore(string charFolder) => _charFolder = charFolder ?? string.Empty;
private string StatePath => Path.Combine(_charFolder, "huds.json");
public HudState Load()
{
HudState? s = null;
try
{
if (_charFolder.Length > 0 && File.Exists(StatePath))
{
string json = File.ReadAllText(StatePath);
s = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.HudState);
if (s != null) _lastJson = json;
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, $"load {StatePath}"); }
s ??= new HudState();
Normalize(s);
return s;
}
/// <summary>Writes the state only when its JSON differs from the last write.</summary>
public void SaveIfDirty(HudState state)
{
if (_charFolder.Length == 0) return;
try
{
string json = JsonSerializer.Serialize(state, RynthAiJsonContext.Default.HudState);
if (json == _lastJson) return;
Directory.CreateDirectory(_charFolder);
string tmp = StatePath + ".tmp";
File.WriteAllText(tmp, json);
File.Move(tmp, StatePath, overwrite: true);
_lastJson = json;
}
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, $"save {StatePath}"); }
}
/// <summary>Repairs null lists / out-of-range values after deserialization.</summary>
private static void Normalize(HudState s)
{
s.ItemHudItems ??= new();
s.ItemHudItems.RemoveAll(e => e == null || e.IsEmpty);
s.ItemHudIconSize = Math.Clamp(s.ItemHudIconSize, 12f, 48f);
s.MiniRemoteSlots ??= new();
for (int i = 0; i < s.MiniRemoteSlots.Count; i++) s.MiniRemoteSlots[i] ??= new HudItemEntry();
while (s.MiniRemoteSlots.Count < HudState.MiniRemoteSlotCount) s.MiniRemoteSlots.Add(new HudItemEntry());
if (s.MiniRemoteSlots.Count > HudState.MiniRemoteSlotCount)
s.MiniRemoteSlots.RemoveRange(HudState.MiniRemoteSlotCount, s.MiniRemoteSlots.Count - HudState.MiniRemoteSlotCount);
}
}

View file

@ -0,0 +1,89 @@
// ItemCountHud.cs — Floating "pack item count" HUD: one row per pinned item with its
// icon, carried count and (optionally) name. Right-click for options. Render thread only.
using System.Linq;
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi.Huds;
internal sealed class ItemCountHud
{
private const string OptionsPopup = "##itemhudopts";
private static readonly Vector4 ColCount = new(0.95f, 0.95f, 0.95f, 1f);
private static readonly Vector4 ColNone = new(0.95f, 0.45f, 0.40f, 1f);
private static readonly Vector4 ColName = new(0.70f, 0.75f, 0.80f, 1f);
private readonly HudController _hud;
private bool _rescueChecked; // off-screen check done for the current show
public ItemCountHud(HudController hud) => _hud = hud;
/// <summary>The HUD was not drawn this frame: check its position again on the next show.</summary>
public void OnHidden() => _rescueChecked = false;
public void Render()
{
var s = _hud.State;
var entries = s.ItemHudItems.ToArray();
var pack = _hud.Pack;
var flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoScrollbar
| ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav;
if (s.ItemHudLocked) flags |= ImGuiWindowFlags.NoMove;
// Right of and above centre, clear of the character in the middle of the view.
UiPlacement.CenterFirstUse(new Vector2(220, -160));
ImGui.SetNextWindowBgAlpha(0.55f);
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 4));
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 2));
bool visible = ImGui.Begin("Item HUD##rynthitemhud", flags);
ImGui.PopStyleVar(2);
if (!visible) { ImGui.End(); return; }
UiPlacement.RescueOncePerShow(ref _rescueChecked);
if (entries.Length == 0)
{
ImGui.TextDisabled("Item HUD is empty.");
ImGui.TextDisabled("Right-click > Edit items...");
}
float size = s.ItemHudIconSize;
foreach (var e in entries)
{
long count = pack.CountOf(e.Name);
HudDraw.Icon(_hud.Icons, e.IconDid, e.Name, size, count == 0);
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"{e.Name}\n{count:N0} carried");
ImGui.SameLine();
// Vertically centre the text on the icon.
float pad = (size - ImGui.GetTextLineHeight()) * 0.5f;
if (pad > 0) ImGui.SetCursorPosY(ImGui.GetCursorPosY() + pad);
ImGui.TextColored(count == 0 ? ColNone : ColCount, count.ToString("N0"));
if (s.ItemHudShowNames)
{
ImGui.SameLine();
ImGui.TextColored(ColName, e.Name);
}
}
if (ImGui.IsWindowHovered() && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) ImGui.OpenPopup(OptionsPopup);
RenderOptions(s);
ImGui.End();
}
private void RenderOptions(HudState s)
{
if (!ImGui.BeginPopup(OptionsPopup)) return;
ImGui.TextDisabled("Item HUD");
bool names = s.ItemHudShowNames;
if (ImGui.Checkbox("Show names", ref names)) s.ItemHudShowNames = names;
bool locked = s.ItemHudLocked;
if (ImGui.Checkbox("Lock position", ref locked)) s.ItemHudLocked = locked;
float size = s.ItemHudIconSize;
ImGui.SetNextItemWidth(120);
if (ImGui.SliderFloat("Icon size", ref size, 12f, 48f, "%.0f")) s.ItemHudIconSize = size;
ImGui.Separator();
if (ImGui.MenuItem("Edit items...")) s.ShowSetup = true;
if (ImGui.MenuItem("Hide HUD")) s.ShowItemHud = false;
ImGui.EndPopup();
}
}

View file

@ -0,0 +1,525 @@
// MiniRemoteHud.cs — Floating Mini Remote (UtilityBelt-style) for RynthAi. Render thread only.
//
// The Mini Remote is the ILT Hub's main window: its Options menu (the Options button or a
// right-click) opens the Hub's section windows (Character, Quests, Pets, Banking, Gear, Games,
// Guardian).
// The V/H button stacks the sections (vertical) or lays them out in three columns (horizontal).
//
// Sections (each can be hidden from the Options menu):
// Stats session time and per-hour XP / luminance / kills / coins / pyreals (ILT Hub rates)
// Target the creature combat is attacking: name, health bar, distance
// Pet the summon that is out (health bar, time left), else the next combat essence and
// whether it is ready
// Slots 5 × 6 quick-use item grid; click uses the item (an empty slot takes the selected
// pack item), right-click assigns / clears, and items dragged from the game's
// inventory or the RynthCore Inventory window drop straight into a slot
// Toggles macro and subsystem switches (same as the dashboard buttons)
// Bank ILT bank balances (pyreals, luminance, keys, coins)
// Rebuff force rebuff / cancel rebuff
// Translate chat translator on/off and the receive <-> send language swap
// Guardian the last Temple guardian answer with a Give button (only while it is recent)
// All game actions are posted to the pump thread.
using System;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.IltHub;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.Huds;
internal sealed class MiniRemoteHud
{
private const string OptionsPopup = "##miniremoteopts";
private const string SlotPopup = "##miniremoteslot";
private const float SlotSize = 28f;
/// <summary>Slot button edge including its 1 px frame padding on each side.</summary>
private const float SlotButtonSize = SlotSize + 2f;
/// <summary>Narrowest horizontal-layout column (fits the stat lines and the translate row).</summary>
private const float MinColumnWidth = 190f;
private const float HeaderButtonWidth = 80f;
private static readonly Vector4 ColLabel = new(0.80f, 0.84f, 0.90f, 1f);
private static readonly Vector4 ColReady = new(0.40f, 0.95f, 0.45f, 1f);
private static readonly Vector4 ColOut = new(0.45f, 0.85f, 0.95f, 1f);
private static readonly Vector4 ColEmpty = new(0.95f, 0.45f, 0.40f, 1f);
private static readonly Vector4 ColBusy = new(0.95f, 0.80f, 0.35f, 1f);
private readonly HudController _hud;
private int _slotMenuIndex = -1;
private bool _rescueChecked; // off-screen check done for the current show
private bool _columnOpen; // horizontal layout: a column was already started this frame (next one goes SameLine)
public MiniRemoteHud(HudController hud) => _hud = hud;
/// <summary>The remote was not drawn this frame: check its position again on the next show.</summary>
public void OnHidden() => _rescueChecked = false;
public void Render()
{
var s = _hud.State;
var flags = ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoScrollbar
| ImGuiWindowFlags.NoFocusOnAppearing;
if (s.MiniRemoteLocked) flags |= ImGuiWindowFlags.NoMove;
// Left of and above centre, mirroring the Item HUD's first spot.
UiPlacement.CenterFirstUse(new Vector2(-220, -160));
ImGui.SetNextWindowBgAlpha(0.70f);
bool open = true;
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 3));
bool visible = ImGui.Begin("Mini Remote##rynthminiremote", ref open, flags);
ImGui.PopStyleVar();
if (!open) s.ShowMiniRemote = false;
if (!visible) { ImGui.End(); return; }
UiPlacement.RescueOncePerShow(ref _rescueChecked);
var hub = _hud.Hub();
RenderHeaderRow(s);
if (s.MiniRemoteHorizontal) RenderHorizontal(s, hub);
else RenderVertical(s, hub);
// Right-click on the window body opens the options, unless a slot's own menu is open.
if (_slotMenuIndex < 0 && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
ImGui.OpenPopup(OptionsPopup);
RenderOptions(s);
_slotMenuIndex = -1;
ImGui.End();
}
// ── Layout ──────────────────────────────────────────────────────────────
/// <summary>[V/H] and [Options] buttons. Fixed widths so the auto-resizing window can't grow from them.</summary>
private static void RenderHeaderRow(HudState s)
{
if (ImGui.Button((s.MiniRemoteHorizontal ? "H" : "V") + "##mrlayout", new Vector2(HeaderButtonWidth, 0)))
s.MiniRemoteHorizontal = !s.MiniRemoteHorizontal;
if (ImGui.IsItemHovered())
ImGui.SetTooltip(s.MiniRemoteHorizontal ? "Horizontal: sections in columns. Click to stack them." : "Vertical: sections stacked. Click to lay them out in columns.");
ImGui.SameLine();
if (ImGui.Button("Options##mropts", new Vector2(HeaderButtonWidth, 0))) ImGui.OpenPopup(OptionsPopup);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("ILT Hub windows and Mini Remote settings (or right-click the remote).");
}
private void RenderVertical(HudState s, IltHubController? hub)
{
RenderStatusSections(s, hub);
RenderActionSections(s);
RenderEconomySections(s, hub);
}
/// <summary>
/// Three side-by-side columns: status (stats, target, pet), actions (slots, toggles) and
/// economy (bank, rebuff, translate). Each column is a fixed-width child that grows only in
/// height; widgets sized from the available width would otherwise make the auto-resizing
/// window grow every frame.
/// </summary>
private void RenderHorizontal(HudState s, IltHubController? hub)
{
float colW = ColumnWidth();
_columnOpen = false;
if (s.MiniShowStats || s.MiniShowTarget || s.MiniShowPet)
{
BeginColumn("##mrcolstatus", colW);
RenderStatusSections(s, hub);
ImGui.EndChild();
}
if (s.MiniShowGems || s.MiniShowToggles)
{
BeginColumn("##mrcolactions", colW);
RenderActionSections(s);
ImGui.EndChild();
}
if (s.MiniShowBank || s.MiniShowRebuff || s.MiniShowTranslate || s.MiniShowGuardian)
{
BeginColumn("##mrcoleconomy", colW);
RenderEconomySections(s, hub);
ImGui.EndChild();
}
}
/// <summary>Starts a column child (caller always calls EndChild, whatever BeginChild returned).</summary>
private void BeginColumn(string id, float width)
{
if (_columnOpen) ImGui.SameLine();
_columnOpen = true;
ImGui.BeginChild(id, new Vector2(width, 0), ImGuiChildFlags.AutoResizeY, ImGuiWindowFlags.NoScrollbar);
}
/// <summary>Wide enough for the slot grid, and never narrower than MinColumnWidth.</summary>
private static float ColumnWidth()
{
int cols = HudState.MiniRemoteColumns;
float grid = cols * SlotButtonSize + (cols - 1) * ImGui.GetStyle().ItemSpacing.X;
return Math.Max(MinColumnWidth, grid);
}
private void RenderStatusSections(HudState s, IltHubController? hub)
{
var combat = _hud.Combat;
if (s.MiniShowStats) RenderStats(hub);
if (s.MiniShowTarget) RenderTarget(combat);
if (s.MiniShowPet) RenderPet(hub, combat);
if (s.MiniShowStats) RenderStatButtons(hub);
}
private void RenderActionSections(HudState s)
{
if (s.MiniShowGems) RenderSlots(s);
if (s.MiniShowToggles) RenderToggles(_hud.Dashboard.Settings);
}
private void RenderEconomySections(HudState s, IltHubController? hub)
{
if (s.MiniShowBank) RenderBank(hub);
if (s.MiniShowRebuff) RenderRebuff();
if (s.MiniShowTranslate && _hud.Translate is { } translate) translate.RenderHubSection();
if (s.MiniShowGuardian && IltActive(hub)) hub!.Guardian.RenderRemoteLine();
}
// ── Sections ────────────────────────────────────────────────────────────
private static bool IltActive(IltHubController? hub) => hub != null && hub.Options.IsIltLikeWorld;
private static void Stat(string label, string value)
{
ImGui.TextColored(ColLabel, label);
ImGui.SameLine();
ImGui.TextUnformatted(value);
}
private static void RenderStats(IltHubController? hub)
{
if (!IltActive(hub)) { ImGui.TextDisabled("Session stats: ILT worlds only"); return; }
var r = hub!.Rates.Summary;
Stat("Time:", IltParse.Duration(DateTime.UtcNow - hub.Rates.SessionStartUtc));
Stat("XP:", HudDraw.Compact(r.XpPerHour) + "/h");
Stat("Lum:", HudDraw.Compact(r.LumPerHour) + "/h");
Stat("Kills:", HudDraw.Compact(r.KillsPerHour) + "/h");
Stat("Coins:", HudDraw.Compact(r.CoinsPerHour) + "/h");
Stat("Pyr:", HudDraw.Compact(r.PyrealsPerHour) + "/h");
}
private static void RenderTarget(CombatHudSnapshot c)
{
if (c.TargetId == 0) { ImGui.TextDisabled("Target: none"); return; }
ImGui.TextColored(ColLabel, "Target:");
ImGui.SameLine();
ImGui.TextUnformatted(c.TargetName);
if (c.TargetDistance >= 0)
{
ImGui.SameLine();
ImGui.TextDisabled($"{c.TargetDistance:F0}yd");
}
HealthBar("##mrtargethp", c.TargetHealth);
}
/// <summary>The live summon when one is out, else the ILT Hub's next-essence line.</summary>
private static void RenderPet(IltHubController? hub, CombatHudSnapshot c)
{
if (c.PetId != 0)
{
RenderSummon(hub, c);
return;
}
if (!IltActive(hub)) { ImGui.TextDisabled("Summon: none"); return; }
string name = hub!.Pets.HudPetName;
string status = hub.Pets.HudPetStatus;
if (name.Length == 0) { ImGui.TextDisabled("No combat pet set"); return; }
ImGui.TextUnformatted(name);
var col = status switch { "Ready" => ColReady, "Out" => ColOut, "Healing" => ColBusy, _ => ColEmpty };
ImGui.TextColored(col, status);
}
private static void RenderSummon(IltHubController? hub, CombatHudSnapshot c)
{
ImGui.TextColored(ColLabel, "Summon:");
ImGui.SameLine();
ImGui.TextUnformatted(c.PetName);
if (IltActive(hub) && hub!.Pets.HudPetStatus == "Healing")
{
ImGui.SameLine();
ImGui.TextColored(ColBusy, "Healing");
}
HealthBar("##mrpethp", c.PetHealth);
long now = Environment.TickCount64;
if (c.PetExpiresAtMs != 0)
{
long leftMs = Math.Max(0, c.PetExpiresAtMs - now);
var left = TimeSpan.FromMilliseconds(leftMs);
string text = $"{FormatClock(left)} left";
if (c.PetLifespanSec > 0)
{
float frac = Math.Clamp(leftMs / (c.PetLifespanSec * 1000f), 0f, 1f);
var col = left.TotalSeconds <= 30 ? ColEmpty : left.TotalSeconds <= 90 ? ColBusy : ColOut;
Bar("##mrpettime", frac, text, col);
}
else
{
ImGui.TextColored(left.TotalSeconds <= 30 ? ColEmpty : ColOut, text);
}
}
else
{
// No RemainingLifespan from the server: show how long it has been out instead.
var up = TimeSpan.FromMilliseconds(Math.Max(0, now - c.PetSeenAtMs));
ImGui.TextDisabled($"Out {FormatClock(up)}");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("The server hasn't reported this summon's lifespan yet.");
}
}
private static string FormatClock(TimeSpan t)
=> t.TotalHours >= 1 ? $"{(int)t.TotalHours}:{t.Minutes:00}:{t.Seconds:00}" : $"{t.Minutes}:{t.Seconds:00}";
/// <summary>Health ratio bar coloured green / yellow / red; "--" until the first health update.</summary>
private static void HealthBar(string id, float ratio)
{
if (ratio < 0f) { Bar(id, 0f, "HP --", ColLabel); return; }
var col = ratio > 0.6f ? ColReady : ratio > 0.3f ? ColBusy : ColEmpty;
Bar(id, ratio, $"HP {ratio * 100f:F0}%", col);
}
private static void Bar(string id, float fraction, string overlay, Vector4 color)
{
float w = Math.Max(ImGui.GetContentRegionAvail().X, 140f);
ImGui.PushStyleColor(ImGuiCol.PlotHistogram, color with { W = 0.85f });
ImGui.PushID(id);
ImGui.ProgressBar(fraction, new Vector2(w, 14f), overlay);
ImGui.PopID();
ImGui.PopStyleColor();
}
private void RenderStatButtons(IltHubController? hub)
{
if (!IltActive(hub)) return;
float w = (ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) * 0.5f;
w = Math.Max(w, 70f);
if (ImGui.Button("Reset XP", new Vector2(w, 0))) _hud.Post(() => _hud.Hub()?.Rates.Reset());
ImGui.SameLine();
if (ImGui.Button("Report", new Vector2(w, 0))) _hud.Post(ReportToChat);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Print the session rates in your chat window (local only).");
}
/// <summary>One-line session summary written to local chat (pump thread).</summary>
private void ReportToChat()
{
var hub = _hud.Hub();
if (hub == null) return;
var r = hub.Rates.Summary;
string time = IltParse.Duration(DateTime.UtcNow - hub.Rates.SessionStartUtc);
_hud.Chat($"[RynthAi] Session {time}: XP {HudDraw.Compact(r.XpPerHour)}/h, Lum {HudDraw.Compact(r.LumPerHour)}/h, "
+ $"Kills {HudDraw.Compact(r.KillsPerHour)}/h ({r.Kills:N0}), Coins {HudDraw.Compact(r.CoinsPerHour)}/h, "
+ $"Pyr {HudDraw.Compact(r.PyrealsPerHour)}/h");
}
private void RenderSlots(HudState s)
{
var slots = s.MiniRemoteSlots.ToArray();
var pack = _hud.Pack;
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(1, 1));
for (int i = 0; i < slots.Length; i++)
{
if (i % HudState.MiniRemoteColumns != 0) ImGui.SameLine();
var e = slots[i];
long count = e.IsEmpty ? 0 : pack.CountOf(e.Name);
ImGui.PushID(i);
bool clicked;
IntPtr tex = e.IsEmpty ? IntPtr.Zero : _hud.Icons.GetTexture(e.IconDid);
if (tex != IntPtr.Zero)
{
var tint = count == 0 ? new Vector4(1, 1, 1, 0.35f) : Vector4.One;
clicked = ImGui.ImageButton("##slot", tex, new Vector2(SlotSize, SlotSize), Vector2.Zero, Vector2.One, Vector4.Zero, tint);
}
else
{
string label = e.IsEmpty ? string.Empty : e.Name.Substring(0, 1).ToUpperInvariant();
if (e.IsEmpty) ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.10f, 0.13f, 0.18f, 0.6f));
clicked = ImGui.Button(label + "##slot", new Vector2(SlotSize + 2, SlotSize + 2));
if (e.IsEmpty) ImGui.PopStyleColor();
}
if (ImGui.IsItemHovered())
ImGui.SetTooltip(e.IsEmpty ? EmptySlotTip(i) : $"{e.Name}\n{count:N0} carried\nClick to use, right-click for options.");
int slotIndex = i;
if (clicked)
{
// Empty slot: click assigns the selected (or last selected) pack item.
if (e.IsEmpty) _hud.Post(() => _hud.SetSlotFromSelection(slotIndex));
else
{
var entry = e;
_hud.Post(() => _hud.UseItem(entry));
}
}
AcceptItemDrop(slotIndex, e.IsEmpty);
if (ImGui.IsItemClicked(ImGuiMouseButton.Right))
{
_slotMenuIndex = i;
ImGui.OpenPopup(SlotPopup);
}
RenderSlotMenu(i, e);
ImGui.PopID();
}
ImGui.PopStyleVar();
}
/// <summary>
/// ImGui drag-and-drop payload type for one inventory item (uint object id). Must match
/// InventoryFace.ItemPayloadType in RynthCore.Engine, which publishes it while dragging.
/// </summary>
private const string ItemPayloadType = "RYNTH_INV_ITEM";
/// <summary>
/// Payload type for an AC-inventory drag whose item the engine guessed from the game selection
/// (uint object id); engines that hook AC's drag start send the real item as ItemPayloadType
/// instead. Must match ItemDragBridge.NativePayloadType in RynthCore.Engine. A guess can be the
/// wrong item, so it is taken by empty slots only and never replaces an assigned one.
/// </summary>
private const string GameItemPayloadType = "RYNTH_GAME_ITEM";
/// <summary>
/// Makes the last slot button a drop target: RynthCore Inventory drags on any slot, game
/// inventory drags on <paramref name="empty"/> slots.
/// </summary>
private unsafe void AcceptItemDrop(int slot, bool empty)
{
if (!ImGui.BeginDragDropTarget()) return;
ImGuiPayloadPtr payload = ImGui.AcceptDragDropPayload(ItemPayloadType);
if (payload.NativePtr == null && empty) payload = ImGui.AcceptDragDropPayload(GameItemPayloadType);
if (payload.NativePtr != null && payload.Data != IntPtr.Zero && payload.DataSize >= sizeof(uint))
{
uint objectId = *(uint*)payload.Data;
_hud.Post(() => _hud.SetSlotFromItemId(slot, objectId));
}
ImGui.EndDragDropTarget();
}
private string EmptySlotTip(int index)
{
string candidate = _hud.AssignCandidate;
return candidate.Length > 0
? $"Slot {index + 1:00}: empty\nClick to assign {candidate}.\nOr drag an item here from the game inventory or the RynthCore Inventory."
: $"Slot {index + 1:00}: empty\nClick an item in your pack, then click here to assign it.\nOr drag an item here from the game inventory or the RynthCore Inventory.";
}
/// <summary>Per-slot right-click menu (opened inside the slot's ID scope).</summary>
private void RenderSlotMenu(int index, HudItemEntry e)
{
if (!ImGui.BeginPopup(SlotPopup)) return;
_slotMenuIndex = index;
ImGui.TextDisabled(e.IsEmpty ? $"Slot {index + 1:00}" : $"Slot {index + 1:00}: {e.Name}");
string candidate = _hud.AssignCandidate;
if (ImGui.MenuItem(candidate.Length > 0 ? $"Assign {candidate}" : "Assign selected item"))
_hud.Post(() => _hud.SetSlotFromSelection(index));
if (!e.IsEmpty && ImGui.MenuItem("Clear slot")) _hud.Post(() => _hud.ClearSlot(index));
ImGui.EndPopup();
}
private void RenderToggles(LegacyUiSettings settings)
{
var dash = _hud.Dashboard;
if (!ImGui.BeginTable("##mrtoggles", 3, ImGuiTableFlags.SizingStretchSame)) return;
Toggle("Macro", settings.IsMacroRunning, _ => dash.TogglePanelMacro());
Toggle("Combat", settings.EnableCombat, on => dash.SetSubsystemEnabled(0, on));
Toggle("Buff", settings.EnableBuffing, on => dash.SetSubsystemEnabled(1, on));
Toggle("Nav", settings.EnableNavigation, on => dash.SetSubsystemEnabled(2, on));
Toggle("Loot", settings.EnableLooting, on => dash.SetSubsystemEnabled(3, on));
Toggle("Meta", settings.EnableMeta, on => dash.SetSubsystemEnabled(4, on));
Toggle("Pet", settings.SummonPets, on => { settings.SummonPets = on; dash.SaveSettings(); });
ImGui.EndTable();
}
/// <summary>A checkbox in the next table cell whose change is applied on the pump thread.</summary>
private void Toggle(string label, bool current, Action<bool> apply)
{
ImGui.TableNextColumn();
bool v = current;
if (ImGui.Checkbox(label + "##mrt", ref v)) _hud.Post(() => apply(v));
}
private static void RenderBank(IltHubController? hub)
{
if (!IltActive(hub) || hub!.Options.IsOff(IltFeature.Bank)) return;
var b = hub.State.Bank;
if (b.LastUpdated == DateTime.MinValue) { ImGui.TextDisabled("Bank: not loaded (Options > Banking)"); return; }
Stat("P:", HudDraw.Compact(b.Pyreals));
Stat("Lum:", HudDraw.Compact(b.Luminance));
if (!ImGui.BeginTable("##mrbank", 2, ImGuiTableFlags.SizingStretchSame)) return;
ImGui.TableNextColumn(); Stat("LK:", HudDraw.Compact(b.LegendaryKeys));
ImGui.TableNextColumn(); Stat("MK:", HudDraw.Compact(b.MythicalKeys));
ImGui.TableNextColumn(); Stat("EC:", HudDraw.Compact(b.EnlightenedCoins));
ImGui.TableNextColumn(); Stat("WE:", HudDraw.Compact(b.WeaklyEnlightenedCoins));
ImGui.EndTable();
}
private void RenderRebuff()
{
var dash = _hud.Dashboard;
ImGui.TextColored(ColLabel, "Rebuff:");
float w = (ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) * 0.5f;
w = Math.Max(w, 70f);
if (ImGui.Button("FB", new Vector2(w, 0))) _hud.Post(dash.RequestForceRebuff);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Force rebuff: recast every buff now.");
ImGui.SameLine();
if (ImGui.Button("CFB", new Vector2(w, 0))) _hud.Post(dash.RequestCancelForceRebuff);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Cancel the running rebuff.");
}
private void RenderOptions(HudState s)
{
if (!ImGui.BeginPopup(OptionsPopup)) return;
RenderHubMenu(_hud.Hub());
ImGui.Separator();
ImGui.TextDisabled("Mini Remote sections");
Flag("Session stats", ref s.MiniShowStats);
Flag("Attack target", ref s.MiniShowTarget);
Flag("Pet / summon", ref s.MiniShowPet);
Flag("Item slots", ref s.MiniShowGems);
Flag("Toggles", ref s.MiniShowToggles);
Flag("Bank", ref s.MiniShowBank);
Flag("Rebuff", ref s.MiniShowRebuff);
Flag("Translate", ref s.MiniShowTranslate);
Flag("Guardian answer", ref s.MiniShowGuardian);
ImGui.Separator();
Flag("Horizontal layout", ref s.MiniRemoteHorizontal);
Flag("Lock position", ref s.MiniRemoteLocked);
if (ImGui.MenuItem("Inventory HUDs setup...")) s.ShowSetup = true;
if (ImGui.MenuItem("Hide Mini Remote")) s.ShowMiniRemote = false;
ImGui.EndPopup();
}
/// <summary>
/// ILT Hub group of the Options menu: one item per section window (checked when open, greyed
/// out until the server reports the feature). Off ILT worlds it also offers the Force-ILT
/// override and a server-options refresh.
/// </summary>
private static void RenderHubMenu(IltHubController? hub)
{
ImGui.TextDisabled("ILT Hub");
if (hub == null) { ImGui.TextDisabled("Available after login."); return; }
foreach (IltSection section in IltSections.All)
{
bool open = hub.IsSectionOpen(section);
if (ImGui.MenuItem(IltSections.Label(section) + "##mrsec", string.Empty, open, hub.SectionAvailable(section)))
hub.SetSectionOpen(section, !open);
}
ImGui.TextDisabled("Progression: Skills panel (Char right-click)");
if (hub.Available) return;
var o = hub.Options;
ImGui.TextDisabled(!o.IsIltLikeWorld ? "Not an ILT world."
: o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue ? "Checking server features..."
: "No ILT features reported.");
bool force = hub.ForceIltWorld;
if (ImGui.Checkbox("Treat this world as ILT##mrforce", ref force)) hub.ForceIltWorld = force;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("World-identity override only: the Hub asks the server which features exist.\nIt never turns a feature on by itself.");
if (ImGui.MenuItem("Refresh server features##mrrefresh")) hub.RequestOptionsRefresh();
}
private static void Flag(string label, ref bool value)
{
bool v = value;
if (ImGui.Checkbox(label, ref v)) value = v;
}
}

View file

@ -0,0 +1,427 @@
// IltBanking.cs — ILT Hub "Banking" tab: /bank balances, confirmed transfers, transaction log.
//
// Server contract (ACECustom PlayerCommands bank handler):
// /bank → "[BANK] Your balances are:" then "[BANK] Pyreals: N", "Luminance:",
// "Legendary Keys:", "Mythical Keys:", "Enlightened Coins:",
// "Weakly Enlightened Coins:".
// /bank t <c> <n> <who> → "Transferred {N0} {Currency} to {Name}[ (offline)]" or an error;
// the recipient sees "Received {N0} {currency} from {Name}".
// Codes: p pyreals, l luminance, k legendary keys, mk mythical keys, e enl coins, we weak coins.
// 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).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltBanking : IIltFeature
{
/// <summary>Transfer currency table: display name, /bank t code.</summary>
public static readonly (string Name, string Code)[] Currencies =
{
("Pyreals", "p"),
("Luminance", "l"),
("Legendary Keys", "k"),
("Mythical Keys", "mk"),
("Enlightened Coins", "e"),
("Weakly Enlightened Coins", "we"),
};
private static readonly string[] CurrencyNames = Currencies.Select(c => c.Name).ToArray();
/// <summary>Server throttle for bank commands (bank_command_limit).</summary>
private const long BankCommandSpacingMs = 5000;
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 _lastAutoRefreshAt;
// Render-thread form state.
private string _amountText = string.Empty;
private string _txFilter = string.Empty;
private string _lastResult = string.Empty;
/// <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>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 - _lastBankCommandAt < BankCommandSpacingMs) return;
_lastBankCommandAt = now;
_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. Pump thread.
/// Returns an error message, or empty when the command was queued.
/// </summary>
public string SendTransfer(int currencyIndex, long amount, string target)
{
RynthLog.Trace(LogCat.IltBanking, $"SendTransfer(currency={currencyIndex}, amount={amount}, target='{target}')");
if (!Enabled) return "Bank is not available on this server.";
if (currencyIndex < 0 || currencyIndex >= Currencies.Length) return "Pick a currency.";
if (amount <= 0) return "Amount must be positive.";
target = (target ?? string.Empty).Trim();
if (target.Length == 0) return "Enter a recipient.";
// The recipient is spliced into a chat command, so only character-name characters are
// allowed: no '/', control characters or line breaks that could start a second command.
if (!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.";
long now = IltHubContext.NowMs;
if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds.";
_lastBankCommandAt = now;
string cmd = $"/bank t {Currencies[currencyIndex].Code} {amount} {target}";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = cmd,
IsResponseLine = t => t.StartsWith("Transferred ", StringComparison.Ordinal)
|| t.StartsWith("Character '", StringComparison.Ordinal)
|| t.StartsWith("You cannot transfer", StringComparison.Ordinal)
|| t.StartsWith("You don't have enough", StringComparison.Ordinal)
|| t.StartsWith("[Transfer]", StringComparison.Ordinal),
IdleEndMs = 500,
FirstLineTimeoutMs = 8000,
Eat = false,
OnComplete = r =>
{
_lastResult = r.Lines.Count > 0 ? r.Lines[^1] : (r.TimedOut ? "No reply from server." : string.Empty);
// Balances changed — refresh quietly once the server throttle allows.
_lastAutoRefreshAt = 0;
},
});
return string.Empty;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
// Periodic quiet refresh only while the Hub is open and the server has /bank.
int every = Bank.AutoRefreshSeconds;
if (Enabled && _ctx.WindowOpen && every > 0 && nowMs - _lastAutoRefreshAt >= every * 1000L
&& nowMs - _lastBankCommandAt >= BankCommandSpacingMs)
{
_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))
{
ParseBalanceLine(text);
return false; // eating is decided by the capture queue
}
TryLogTransaction(text);
return false;
}
public void OnLogout()
{
lock (_txLock) _ctx.Store.SaveTransactionsIfDirty(_transactions);
}
// ── Parsing ─────────────────────────────────────────────────────────────
private void ParseBalanceLine(string text)
{
string body = text.Substring("[BANK]".Length).Trim();
int colon = body.IndexOf(':');
if (colon <= 0) return;
string label = body.Substring(0, colon).Trim();
long value = IltParse.ParseLeadingLong(body.Substring(colon + 1));
if (body.Substring(colon + 1).Trim().Length == 0) return; // header "Your balances are:"
// Order matters: "Weakly Enlightened Coins" also contains "Enlightened Coins".
if (label.Contains("Weakly", StringComparison.OrdinalIgnoreCase)) Apply("WeaklyEnlightenedCoins", ref Bank.WeaklyEnlightenedCoins, value);
else if (label.Contains("Enlightened", StringComparison.OrdinalIgnoreCase)) Apply("EnlightenedCoins", ref Bank.EnlightenedCoins, value);
else if (label.Contains("Mythical", StringComparison.OrdinalIgnoreCase)) Apply("MythicalKeys", ref Bank.MythicalKeys, value);
else if (label.Contains("Legendary", StringComparison.OrdinalIgnoreCase)) Apply("LegendaryKeys", ref Bank.LegendaryKeys, value);
else if (label.Contains("Luminance", StringComparison.OrdinalIgnoreCase)) Apply("Luminance", ref Bank.Luminance, value);
else if (label.Contains("Pyreal", StringComparison.OrdinalIgnoreCase)) Apply("Pyreals", ref Bank.Pyreals, value);
else return;
Bank.LastUpdated = DateTime.Now;
_ctx.Options.Set(IltFeature.Bank, IltTri.On);
}
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)
{
ImGui.TextColored(LegacyDashboardRenderer.ColTextMute,
_ctx.Options.IsOff(IltFeature.Bank) ? "The server reports /bank is not available." : "Waiting for the server options check...");
return;
}
// Balances
ImGui.TextColored(LegacyDashboardRenderer.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();
ImGui.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);
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();
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)})");
}
private void RenderTransferForm()
{
ImGui.TextColored(LegacyDashboardRenderer.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;
ImGui.SetNextItemWidth(200);
ImGui.InputTextWithHint("Amount##xfer", "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.TextDisabled("= " + IltParse.N0(amount));
else ImGui.TextColored(LegacyDashboardRenderer.ColHp, "invalid amount");
}
ImGui.BeginDisabled(!amountOk || string.IsNullOrWhiteSpace(Bank.TransferTarget));
if (ImGui.Button("Send transfer..."))
{
int cur = idx;
long amt = amount;
string who = Bank.TransferTarget.Trim();
_ctx.Confirm("Confirm bank transfer",
$"Send {IltParse.N0(amt)} {Currencies[cur].Name} to {who}?\n\nThis cannot be undone.",
() =>
{
string err = SendTransfer(cur, amt, who);
_lastResult = err.Length > 0 ? err : "Transfer sent...";
},
"Send");
}
ImGui.EndDisabled();
if (_lastResult.Length > 0) ImGui.TextWrapped(_lastResult);
}
private void RenderTransactionLog()
{
var snap = _txSnapshot;
ImGui.TextColored(LegacyDashboardRenderer.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();
ImGui.TextColored(t.Type == "Sent" ? LegacyDashboardRenderer.ColAmber : LegacyDashboardRenderer.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)} | "
+ $"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();
}
}

View file

@ -0,0 +1,254 @@
// IltBuffKeepers.cs — Rune-of-Dispel auto-dispel and Surging Strength keeper (Gear tab).
//
// Both read the player's enchantment list once a second (one shared read).
// Dispel: classifies active spells by NAME (SpellDatabase 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.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
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]);
string name = SpellDatabase.GetSpellName(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(LegacyDashboardRenderer.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);
ImGui.TextDisabled("Status: " + _dispelStatus);
var harm = _harmfulNow;
if (harm.Length > 0) ImGui.TextColored(LegacyDashboardRenderer.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(LegacyDashboardRenderer.ColTeal, "Surging Strength");
bool ss = G.SurgingStrength;
if (ImGui.Checkbox("Keep Surging Strength up (Empowered Volcanic Ember)", ref ss)) G.SurgingStrength = ss;
ImGui.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++)
{
ImGui.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;
}
}
}

View file

@ -0,0 +1,137 @@
// IltCharmTracker.cs — Snapshot of every ACECustom registry charm for the engine Settings
// panel's "Charms Tracking" tab (RynthPluginGetCharmsJson).
//
// 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.RynthAi.IltHub;
internal sealed class IltCharmTracker
{
private readonly IltHubContext _ctx;
public IltCharmTracker(IltHubContext ctx) => _ctx = ctx;
/// <summary>One charm's tracked state.</summary>
internal readonly record struct CharmState(
IltCharmDef Def, string Acquired, int Count, int Tier, int MaxTier,
IltTri Active, IltTri Server, DateTime LastSeenUtc);
/// <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;
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;
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;
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));
}
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(RynthAiPlugin.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(RynthAiPlugin.JsonEscape(r.Def.Name)).Append('"');
sb.Append(",\"effect\":\"").Append(RynthAiPlugin.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("\"}");
}
sb.Append("]}");
return sb.ToString();
}
private static string TriText(IltTri t) => t switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" };
}

View file

@ -0,0 +1,199 @@
// IltChatCapture.cs — Shared "send a server command and collect its reply" helper.
//
// Every ILT Hub feature that talks to ACECustom (/bank, /aug, /qb, /pets, /xp, /pb,
// /ilt features, the login probe, ...) 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.RynthAi.IltHub;
/// <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: 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>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;
if (gotAny && now - _lastLineAt >= _active.IdleEndMs)
Finish();
else if (!gotAny && 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);
_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;
_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;
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}'"); }
}
}

View file

@ -0,0 +1,282 @@
// IltChunkClap.cs — Lugian-hammer chunking and /clap automation (Gear tab).
//
// Chunk: uses a Lugian (Aetheria) Hammer on eligible items, one at a time:
// Aetheria — "Aetheria"/"Coalesced Aetheria" gems, not equipped, appraised, not flagged
// never-chunk (bool 9030), never levelled (ItemTotalXp quad 4 == 0), and
// max level (int 319) under the configured cap (Coalesced always qualifies).
// Corrupted — "Corrupted" melee/missile weapons with no tinks (171), no imbue (179),
// not equipped, not never-chunk, cleave (292) <= 1.
// Peace mode only unless ChunkInCombat; waits for the result line (10 s max).
// Clap: "/clap all" converts aetheria chunks + trinkets into coins server-side. 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.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
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;
// 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 ───────────────────────────────────────────────────────────────
private WorldObject? FindHammer()
=> _ctx.Inventory.FindByName(n => n.Equals("Lugian Aetheria Hammer", StringComparison.OrdinalIgnoreCase)
|| n.Equals("Lugian Hammer", StringComparison.OrdinalIgnoreCase)
|| n.EndsWith(" Lugian Hammer", StringComparison.OrdinalIgnoreCase));
/// <summary>True/false when decidable; null when appraisal is still needed.</summary>
private bool? IsChunkableAetheria(WorldObject wo)
{
if (wo.ObjectClass != AcObjectClass.Gem) return false;
bool coalesced = wo.Name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase);
if (!coalesced && (!wo.Name.Contains("Aetheria", StringComparison.OrdinalIgnoreCase) || wo.Name.Contains("Chunk", StringComparison.OrdinalIgnoreCase)))
return false;
var inv = _ctx.Inventory;
if (inv.IsEquipped(wo)) return false;
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return null; }
if (inv.Bool(wo, IltInventory.BoolNeverChunk)) return false;
if (inv.Quad(wo, IltInventory.QuadItemTotalXp) != 0) return false;
return coalesced || inv.Int(wo, IltInventory.IntItemMaxLevel) < Math.Max(1, G.ChunkAetheriaUnderLevel);
}
private bool? IsChunkableCorrupted(WorldObject wo)
{
if (wo.ObjectClass is not (AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon)) return false;
if (!wo.Name.Contains("Corrupted", StringComparison.OrdinalIgnoreCase)) return false;
var inv = _ctx.Inventory;
if (inv.IsEquipped(wo)) return false;
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return null; }
if (inv.Bool(wo, IltInventory.BoolNeverChunk)) return false;
if (inv.Int(wo, IltInventory.IntNumTimesTinkered) != 0 || inv.Int(wo, IltInventory.IntImbuedEffect) != 0) return false;
return inv.Int(wo, IltInventory.IntCleaving) <= 1;
}
private WorldObject? NextChunkTarget()
{
foreach (var wo in _ctx.Inventory.Items())
{
if (_skip.Contains(wo.Id)) continue;
if ((G.AutoChunkAetheria || _manualPass) && IsChunkableAetheria(wo) == true) return wo;
if ((G.AutoChunkCorrupted || _manualPass) && IsChunkableCorrupted(wo) == true) return wo;
}
return null;
}
/// <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;
_chunkStatus = "manual pass started";
}
private void TickChunk(long now)
{
if (!G.AutoChunkAetheria && !G.AutoChunkCorrupted && !_manualPass) return;
if (_waitingOn != 0)
{
if (now - _waitStartedAt < ChunkResultWaitMs) return;
_skip.Add(_waitingOn); // no result line — don't hammer the same item forever
_waitingOn = 0;
}
if (now - _lastChunkAt < Math.Max(500, G.ChunkIntervalMs)) return;
_lastChunkAt = now;
if (!G.ChunkInCombat && !_ctx.Inventory.InPeaceMode) { _chunkStatus = "waiting for peace mode"; return; }
if (_ctx.Inventory.IsBusy) return;
var hammer = FindHammer();
if (hammer == null) { _chunkStatus = "no Lugian Hammer carried"; _manualPass = false; return; }
var target = NextChunkTarget();
if (target == null)
{
_chunkStatus = _chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible";
_manualPass = false;
return;
}
if (_ctx.Inventory.UseOn(hammer, unchecked((uint)target.Id)))
{
_waitingOn = target.Id;
_waitStartedAt = now;
_chunkStatus = "chunking " + target.Name;
}
}
// ── Clap ────────────────────────────────────────────────────────────────
private bool HasClapMaterials()
{
var inv = _ctx.Inventory;
foreach (var wo in inv.Items())
{
uint w = inv.Wcid(wo);
if ((w == IltInventory.WcidRedAetheriaChunk || w == IltInventory.WcidBlueAetheriaChunk)
&& inv.Int(wo, IltInventory.IntItemMaxLevel) <= 3)
return true;
string n = wo.Name;
if (n.Equals("Red Aetheria Chunk", StringComparison.OrdinalIgnoreCase) || n.Equals("Blue Aetheria Chunk", StringComparison.OrdinalIgnoreCase)
|| n.Equals("Ancient Empyrean Trinket", StringComparison.OrdinalIgnoreCase) || n.Equals("Ancient Falatacot Trinket", StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <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 materials carried"; 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);
}
public bool OnChat(string text)
{
if (_waitingOn == 0) return false;
if (text.StartsWith("You're too busy", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You are too busy", StringComparison.OrdinalIgnoreCase))
{
_waitingOn = 0; // retry the same item next interval
return false;
}
if (ChunkDoneLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase)))
{
_chunked++;
_waitingOn = 0;
}
else if (ChunkRefusedLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase)))
{
_skip.Add(_waitingOn);
_waitingOn = 0;
}
return false;
}
public void OnLogout()
{
_waitingOn = 0;
_skip.Clear();
_manualPass = false;
_clapWasEnabled = false;
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Chunking (Lugian Hammer)");
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 = Math.Clamp(under, 1, 6);
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");
ImGui.TextDisabled("Status: " + _chunkStatus);
ImGui.Separator();
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Clap (/clap all)");
if (_ctx.Options.IsOff(IltFeature.Clap))
{
ImGui.TextColored(LegacyDashboardRenderer.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();
ImGui.TextDisabled(_clapStatus);
}
}

View file

@ -0,0 +1,264 @@
// 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
// (WorldObjectCache.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.
// Search order: RynthAi EquipProfiles\<char>, EquipProfiles, then UB's equip folders.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi.IltHub;
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()
{
string root = Path.Combine(IltHubStore.SharedRoot, "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).</summary>
private List<WorldObject>? SuitItems(string path, out string error)
{
error = string.Empty;
VTankLootProfile profile;
try { profile = VTankLootParser.Load(path); }
catch (Exception ex) { error = "could not read profile: " + ex.Message; return null; }
var lootCtx = new VTankLootContext(_ctx.Host, _ctx.Inventory.PlayerId) { Cache = _ctx.Inventory.Cache };
var list = 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;
VTankLootRule? match = null;
foreach (var rule in profile.Rules)
if (VTankLootEvaluator.Match(rule, wo, lootCtx)) { match = rule; break; }
if (match != null && match.Action == VTankLootAction.Keep) list.Add(wo);
}
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 = WorldObjectCache.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(LegacyDashboardRenderer.ColTeal, "Equipment suits (.utl)");
if (ImGui.SmallButton("Rescan profiles")) _ctx.Post(RefreshProfileList);
var profiles = _profiles;
if (profiles.Length == 0)
{
ImGui.TextDisabled($"No .utl files found ({System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, "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("[ILT Hub] " + Load(pick)), "Load");
if (_running)
{
ImGui.SameLine();
if (ImGui.SmallButton("Cancel")) _ctx.Post(() => Cancel("cancelled by player"));
}
}
ImGui.TextDisabled("Status: " + _status);
foreach (string l in _preview) ImGui.BulletText(l);
}
}

View file

@ -0,0 +1,254 @@
// IltGames.cs — ILT Hub "Games" tab + hand HUD (P2): Blackjack, Fellowship Blackjack, Powerball.
//
// 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.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
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(LegacyDashboardRenderer.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();
ImGui.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) ImGui.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) ImGui.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) ImGui.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))
{
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, _fellowshipHand ? "Fellowship Blackjack" : "Blackjack");
RenderHandButtons("hud");
}
ImGui.End();
if (!open) _ctx.State.GamesHudVisible = false;
}
}

View file

@ -0,0 +1,155 @@
// IltGear.cs — ILT Hub "Gear" tab: charm strip (incl. Guardian Hand) plus the gear tools.
//
// Charm strip: every carried ACECustom charm with its ON/OFF state (from the appraisal
// Use text) and a toggle (using a charm flips it). Charms the server reports disabled are
// shown greyed out. Guardian Hand has no published WCID yet, so it is matched by name
// ("guardian" + "hand") unless a WCID is configured in the Hub.
// The remaining sections are separate modules (buff keepers, chunk/clap, split arrows,
// equipment suits, VTank import) that this tab just lays out.
using System;
using System.Collections.Generic;
using System.Linq;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltGear : IIltFeature
{
private readonly IltHubContext _ctx;
public IltBuffKeepers Keepers { get; }
public IltChunkClap ChunkClap { get; }
public IltSplitArrows Split { get; }
public IltEquipSuits Suits { get; }
public IltUsdImporter Usd { get; }
private sealed record CharmRow(int Id, string Name, IltTri Status, bool ServerDisabled, bool IsGuardianHand);
private volatile CharmRow[] _charms = Array.Empty<CharmRow>();
private long _lastCharmScan;
public IltGear(IltHubContext ctx)
{
_ctx = ctx;
Keepers = new IltBuffKeepers(ctx);
ChunkClap = new IltChunkClap(ctx);
Split = new IltSplitArrows(ctx);
Suits = new IltEquipSuits(ctx);
Usd = new IltUsdImporter(ctx);
}
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));
}
private void ScanCharms()
{
var inv = _ctx.Inventory;
var rows = new List<CharmRow>();
var seen = new HashSet<int>();
foreach (var wo in inv.CarriedCharms().Concat(inv.Items().Where(IsGuardianHand)))
{
if (!seen.Add(wo.Id)) continue;
bool gh = IsGuardianHand(wo);
string defName = gh ? "Guardian Hand" : inv.CharmDefFor(wo)?.Name ?? wo.Name;
rows.Add(new CharmRow(wo.Id, wo.Name, inv.CharmStatus(wo), _ctx.Options.IsOff(IltFeature.Charm(defName)), gh));
}
_charms = rows.OrderBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray();
}
/// <summary>Uses (toggles) a charm (pump thread).</summary>
private void ToggleCharm(int id)
{
var wo = _ctx.Inventory.Cache?[id];
if (wo == null) return;
if (_ctx.Inventory.IsBusy) { _ctx.Chat("[ILT Hub] Busy - try the charm again in a moment."); return; }
_ctx.Inventory.Use(wo);
_lastCharmScan = 0; // re-read status soon (appraisal refresh is throttled per item)
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (_ctx.WindowOpen && nowMs - _lastCharmScan >= 3000)
{
_lastCharmScan = nowMs;
ScanCharms();
}
Keepers.Tick(nowMs);
ChunkClap.Tick(nowMs);
Split.Tick(nowMs);
Suits.Tick(nowMs);
}
public bool OnChat(string text)
{
bool eat = Keepers.OnChat(text);
eat |= ChunkClap.OnChat(text);
eat |= Split.OnChat(text);
eat |= Suits.OnChat(text);
return eat;
}
public void OnLogout()
{
Keepers.OnLogout();
ChunkClap.OnLogout();
Split.OnLogout();
Suits.OnLogout();
_charms = Array.Empty<CharmRow>();
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
if (ImGui.CollapsingHeader("Charms", ImGuiTreeNodeFlags.DefaultOpen)) RenderCharms();
if (ImGui.CollapsingHeader("Dispel / Surging Strength")) 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("VirindiTank import")) Usd.Render();
}
private void RenderCharms()
{
var rows = _charms;
if (rows.Length == 0) ImGui.TextDisabled("No charms carried.");
foreach (var r in rows)
{
ImGui.PushID(r.Id);
if (r.ServerDisabled)
{
ImGui.TextDisabled($"{r.Name} - disabled on this server");
ImGui.PopID();
continue;
}
var col = r.Status == IltTri.On ? LegacyDashboardRenderer.ColGreen
: r.Status == IltTri.Off ? LegacyDashboardRenderer.ColTextMute : LegacyDashboardRenderer.ColAmber;
ImGui.TextColored(col, r.Status == IltTri.On ? "ON " : r.Status == IltTri.Off ? "OFF" : " ? ");
ImGui.SameLine();
ImGui.TextUnformatted(r.Name);
ImGui.SameLine();
int id = r.Id;
if (ImGui.SmallButton("Toggle")) _ctx.Post(() => ToggleCharm(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();
}
}
}

View file

@ -0,0 +1,571 @@
// IltGuardian.cs - Temple of Enlightenment guardians (ILT Hub "Guardian" window).
//
// * 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.
//
// 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.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
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, Func<QuestTracker?> tracker, IltQuests quests)
{
_ctx = ctx;
Attributes = new IltTempleAttributes(ctx, tracker, 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 &lt;text&gt;|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;
}
}
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);
ImGui.TextDisabled(IltGuardianPhrasebook.MessageOf(line));
ImGui.PopTextWrapPos();
}
string answer = _lastAnswer, npc = _lastNpc;
if (answer.Length > 0)
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, answer);
ImGui.SameLine();
ImGui.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.");
ImGui.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;
ImGui.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 ? LegacyDashboardRenderer.ColGreen
: r.Status == "Unknown" ? LegacyDashboardRenderer.ColTextMute
: LegacyDashboardRenderer.ColAmber;
ImGui.TextColored(col, r.Status);
if (ImGui.IsItemHovered())
ImGui.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(LegacyDashboardRenderer.ColTextMute, "Guardian:");
ImGui.SameLine();
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, answer);
if (ImGui.IsItemHovered()) ImGui.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));
}
}
}

View file

@ -0,0 +1,220 @@
// IltGuardianPhrasebook.cs - Temple of Enlightenment spell words and Guardian of Attribute
// 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.RynthAi.IltHub;
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();
}
}

View file

@ -0,0 +1,105 @@
// IltHubContext.cs — Shared services handed to every ILT Hub feature.
//
// 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). This mirrors the existing
// DrainMetaCommands pattern in RynthAiPlugin.
using System;
using System.Collections.Concurrent;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>A yes/no question waiting for the player in the Hub window.</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();
private readonly Func<LegacyUiSettings?> _settings;
public IltHubContext(RynthCoreHost host, IltHubState state, IltHubStore store, IltChatCapture capture,
IltServerOptions options, IltInventory inventory, Func<LegacyUiSettings?> settings)
{
Host = host;
State = state;
Store = store;
Capture = capture;
Options = options;
Inventory = inventory;
_settings = settings;
}
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>The live combat settings (rule lists the Pet picker / USD importer edit). Null before login.</summary>
public LegacyUiSettings? Settings => _settings();
/// <summary>Set by the controller when combat settings were edited and must be saved.</summary>
public Action? SaveCombatSettings;
/// <summary>Logged-in character name (resolved at login).</summary>
public string CharName = string.Empty;
/// <summary>True when the Hub window is open (features use it to gate auto-refreshes).</summary>
public bool WindowOpen => State.WindowVisible;
/// <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();
}

View file

@ -0,0 +1,499 @@
// IltHubController.cs — Owns the ILT Hub: state, services, feature modules, commands.
//
// RynthAiPlugin creates one controller per login session and forwards:
// OnTick → Tick() (pump thread)
// OnChatWindowText → OnChat() (pump thread; returns true to eat the line)
// OnKillNotification → RecordKill()
// OnRender → Render() (render thread)
// /ra hub ..., /ra quests ... → HandleCommand()
// OnLogout / teardown → OnLogout()
// The Hub only appears on ACECustom/ILT worlds where at least one server feature is on;
// on every other world it stays dormant (no probes, no chat, no window).
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltHubController
{
private const long SaveIntervalMs = 5000;
private readonly IltHubContext _ctx;
private readonly IltHubUi _ui;
private readonly Func<QuestTracker?> _quests;
private readonly List<IIltFeature> _features = new();
private long _lastSaveAt;
private bool _questOutcomeHooked;
private bool _availabilityAnnounced; // "/ra hub to open" hint printed this session
public IltBanking Banking { get; }
public IltPets Pets { get; }
public IltSessionRates Rates { get; }
public IltQuests Quests { get; }
public IltProgression Progression { get; }
public IltGear Gear { get; }
public IltGames Games { get; }
/// <summary>Registry charm acquired / active / server state (Charms Tracking tab).</summary>
public IltCharmTracker Charms { get; }
/// <summary>Temple guardians: riddle translator, hand-in, attribute turn-in tracker.</summary>
public IltGuardian Guardian { get; }
public IltHubController(RynthCoreHost host, string charFolder, Func<WorldObjectCache?> cache,
Func<LegacyUiSettings?> settings, Func<QuestTracker?> quests, Action saveCombatSettings)
{
var store = new IltHubStore(host, charFolder);
var state = store.LoadState();
var capture = new IltChatCapture(host);
var inventory = new IltInventory(host, cache);
IltHubContext? ctxRef = null;
var options = new IltServerOptions(host, capture, state, text => ctxRef?.Chat(text));
_ctx = new IltHubContext(host, state, store, capture, options, inventory, settings) { SaveCombatSettings = saveCombatSettings };
ctxRef = _ctx;
_quests = quests;
Banking = new IltBanking(_ctx);
Pets = new IltPets(_ctx);
Rates = new IltSessionRates(_ctx);
Quests = new IltQuests(_ctx, quests);
Progression = new IltProgression(_ctx);
Gear = new IltGear(_ctx);
Games = new IltGames(_ctx);
Charms = new IltCharmTracker(_ctx);
Guardian = new IltGuardian(_ctx, quests, Quests);
_features.AddRange(new IIltFeature[] { Banking, Pets, Rates, Quests, Progression, Gear, Games, Guardian });
Banking.BalanceChanged += Rates.OnBankBalanceChanged;
options.ProbeReplyTap = OnProbeReply;
_ui = new IltHubUi(this, _ctx);
}
public IltHubState State => _ctx.State;
public IltServerOptions Options => _ctx.Options;
/// <summary>
/// Shows / hides / toggles the Mini Remote, which is the Hub's main window ("show", "hide",
/// "toggle"). Set by RynthAiPlugin; returns the chat reply. Pump thread.
/// </summary>
public Func<string, string>? MiniRemoteCommand { get; set; }
/// <summary>True while the Mini Remote is on screen (set by RynthAiPlugin).</summary>
public Func<bool>? MiniRemoteVisible { get; set; }
/// <summary>World is ILT-like and the server has at least one Hub feature on.</summary>
public bool Available => _ctx.Options.IsIltLikeWorld && _ctx.Options.AnyFeatureOn;
/// <summary>
/// Whether a section window can be shown now. Character always can (it explains why the Hub is
/// idle and holds the Force-ILT override); the rest need server features.
/// </summary>
public bool SectionAvailable(IltSection section) => section switch
{
IltSection.Character => true,
IltSection.Banking => Available && !_ctx.Options.IsOff(IltFeature.Bank),
IltSection.Games => Available && Games.AnyGameAvailable,
_ => Available,
};
public bool IsSectionOpen(IltSection section) => IltSections.IsOpen(_ctx.State.Character, section);
/// <summary>Opens / closes a section window (render or pump thread; a plain bool write).</summary>
public void SetSectionOpen(IltSection section, bool open) => IltSections.SetOpen(_ctx.State.Character, section, open);
/// <summary>The Force-ILT world override (world identity only; features still come from the server).</summary>
public bool ForceIltWorld
{
get => _ctx.State.ForceLeaftideFeatures;
set => _ctx.State.ForceLeaftideFeatures = value;
}
/// <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));
/// <summary>True when the cached options already say /myquests is off (skip the login refresh).</summary>
public bool SkipLoginQuestRefresh => _ctx.Options.IsIltLikeWorld && _ctx.Options.IsOff(IltFeature.Quests);
// ── Lifecycle ───────────────────────────────────────────────────────────
/// <summary>Login: remember the character, hook PetManager, schedule the options check, import UB data once.</summary>
public void OnLoginComplete(string charName, PetManager? petManager)
{
_ctx.CharName = charName ?? string.Empty;
RynthLog.Event(LogEvents.IltLogin, $"login: char='{_ctx.CharName}' world='{_ctx.Options.WorldName}'");
_ctx.Options.OnLoginComplete();
_ctx.Inventory.Reset();
Rates.Reset();
if (petManager != null)
{
petManager.AllowSummonOnEmpty = Pets.AllowSummonOnEmpty;
petManager.HoldSummons = Pets.HoldCombatSummons;
petManager.YieldPetForCombat = Pets.YieldPetForCombat;
}
HookQuestOutcome();
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));
}
}
private void HookQuestOutcome()
{
if (_questOutcomeHooked) return;
var t = _quests();
if (t == null) return;
t.RefreshCompleted += () => _ctx.Options.NoteQuestTrackerOutcome(t.Disabled, t.Count);
_questOutcomeHooked = true;
}
/// <summary>Pump-thread tick.</summary>
public void Tick()
{
long now = IltHubContext.NowMs;
_ctx.DrainPosted();
_ctx.Capture.Tick();
_ctx.Options.Tick();
HookQuestOutcome();
// "Hub UI on screen" gates bank auto-refresh and the gear / split-arrow scans.
_ctx.State.WindowVisible = (MiniRemoteVisible?.Invoke() ?? false) || IltSections.AnyOpen(_ctx.State.Character);
// One hint per session once the server confirms Hub 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("[ILT Hub] ILT server features detected. Type /ra hub to open the Mini Remote (Options lists the Hub windows).");
}
// Features run only on ILT-like worlds; elsewhere the Hub is fully dormant.
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($"[ILT Hub] Confirmation for '{_pendingLabel}' expired.");
ClearPending();
}
if (now - _lastSaveAt >= SaveIntervalMs)
{
_lastSaveAt = now;
_ctx.Store.SaveStateIfDirty(_ctx.State);
}
}
/// <summary>Pump-thread chat line. Returns true when the line should be hidden.</summary>
public bool OnChat(string text)
{
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;
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,
IltPets => LogCat.IltPets,
IltSessionRates => LogCat.IltRates,
IltQuests => LogCat.IltQuests,
IltProgression => LogCat.IltProgression,
IltGear => LogCat.IltGear,
IltGames => LogCat.IltGames,
_ => LogCat.IltHub,
};
public void RecordKill() => Rates.RecordKill();
/// <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 (RynthPluginGetProgressionJson).
/// "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(RynthAiPlugin.JsonEscape(_ctx.Options.WorldName ?? string.Empty)).Append("\",");
Progression.AppendSnapshotJson(sb);
sb.Append('}');
return sb.ToString();
}
/// <summary>JSON for the engine Settings panel's Charms Tracking tab (RynthPluginGetCharmsJson). Pump thread.</summary>
public string BuildCharmsJson() => Charms.BuildJson();
/// <summary>Render thread: section windows, confirm popups, games HUD.</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); break;
case IltFeature.Pets: Pets.ApplyRoster(false, r.Lines); break;
case IltFeature.Shinies: Pets.ApplyRoster(true, r.Lines); break;
case IltFeature.Qb: Quests.ApplyQbProbe(r.Lines); break;
// Bank lines are parsed passively by IltBanking.OnChat as they arrive.
}
}
// ── Commands ────────────────────────────────────────────────────────────
/// <summary>
/// "/ra hub [show|hide|toggle|open &lt;section&gt; [show|hide|toggle]|refresh|bank|status|force on|off|
/// profile save|load|list ...|suit list|test|load ...]" (show/hide/toggle drive the Mini Remote),
/// "/ra quests [refresh|check &lt;regex&gt;|window|favhud]", "/ra pets [show|hide|toggle]" and
/// "/ra guardian ..." (see IltGuardian.HandleCommand).
/// 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("quests", StringComparison.OrdinalIgnoreCase))
{
string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "refresh";
string mode = args.Length > 1 ? args[1].ToLowerInvariant() : "toggle";
var cs = _ctx.State.Character;
switch (sub)
{
case "check" when args.Length > 1:
Quests.CheckCommand(string.Join(" ", args.Skip(1)));
break;
case "window":
OpenSection(IltSection.Quests, mode);
break;
case "favhud":
case "favorites":
cs.ShowQuestFavoritesHud = ResolveToggle(mode, cs.ShowQuestFavoritesHud);
_ctx.Chat(cs.ShowQuestFavoritesHud ? "[ILT Hub] Quest favorites HUD shown." : "[ILT Hub] Quest favorites HUD hidden.");
break;
default:
_ctx.Chat("[ILT Hub] " + Quests.RefreshQuests());
break;
}
return true;
}
if (verb.Equals("pets", StringComparison.OrdinalIgnoreCase))
{
// "/ra pets [show|hide|toggle]": same as "/ra hub open pets".
OpenSection(IltSection.Pet, args.Length > 0 ? args[0] : "toggle");
return true;
}
if (verb.Equals("guardian", StringComparison.OrdinalIgnoreCase))
{
// "/ra guardian window [show|hide|toggle]" opens the window; everything else is the Guardian's.
if (args.Length > 0 && args[0].Equals("window", StringComparison.OrdinalIgnoreCase))
OpenSection(IltSection.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() : "toggle";
string rest = args.Length > 1 ? string.Join(" ", args.Skip(1)) : string.Empty;
switch (cmd)
{
case "show":
case "hide":
case "toggle":
// The Mini Remote is the Hub's main window.
if (MiniRemoteCommand != null) _ctx.Chat(MiniRemoteCommand(cmd));
else _ctx.Chat("[ILT Hub] The Mini Remote is not available yet.");
break;
case "open":
if (args.Length < 2 || !IltSections.TryParse(args[1], out IltSection section))
{
_ctx.Chat("[ILT Hub] Usage: /ra hub open character|quests|pets|banking|gear|games|guardian [show|hide|toggle]");
break;
}
OpenSection(section, args.Length > 2 ? args[2] : "toggle");
break;
case "refresh": _ctx.Options.Refresh(manual: true); break;
case "bank": Banking.RequestRefresh(quiet: false); break;
case "status": PrintStatus(); break;
case "force":
_ctx.State.ForceLeaftideFeatures = !rest.Equals("off", StringComparison.OrdinalIgnoreCase);
_ctx.Chat($"[ILT Hub] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")}. Use /ra hub refresh to re-check the server.");
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 "confirm": RunPending(); break;
case "cancel":
_ctx.Chat(_pendingAction != null ? $"[ILT Hub] Cancelled '{_pendingLabel}'." : "[ILT Hub] Nothing to cancel.");
ClearPending();
break;
default:
_ctx.Chat("[ILT Hub] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|force on|off|clap|confirm|cancel");
_ctx.Chat("[ILT Hub] /ra hub open character|quests|pets|banking|gear|games|guardian [show|hide|toggle]");
_ctx.Chat("[ILT Hub] /ra hub profile list|save <name> [shared]|load <name> /ra hub suit list|test|load [name]");
_ctx.Chat("[ILT Hub] /ra quests [refresh|check <regex>|window [show|hide]|favhud [show|hide]] /ra pets [show|hide]");
_ctx.Chat("[ILT Hub] /ra guardian [window|translate <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status]");
break;
}
return true;
}
/// <summary>Applies show / hide / toggle to a section window and says what happened.</summary>
private void OpenSection(IltSection section, string mode)
{
bool open = IltSections.Resolve(mode, IsSectionOpen(section));
SetSectionOpen(section, open);
string label = IltSections.Label(section);
_ctx.Chat(!open ? $"[ILT Hub] {label} window hidden."
: SectionAvailable(section) ? $"[ILT Hub] {label} window shown."
: $"[ILT Hub] {label} window will show once the server reports that feature on.");
}
/// <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($"[ILT Hub] 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("[ILT Hub] on: " + (on.Length > 0 ? on : "-"));
_ctx.Chat("[ILT Hub] 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("[ILT Hub] Profiles: " + (names.Count > 0 ? string.Join(", ", names) : "(none)"));
return;
}
if (a.Length < 2) { _ctx.Chat("[ILT Hub] 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)
? $"[ILT Hub] Saved {(shared ? "shared " : "")}profile '{a[1]}'." : "[ILT Hub] 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)
? $"[ILT Hub] Loaded profile '{profile}'." : "[ILT Hub] 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($"[ILT Hub] 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("[ILT Hub] 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("[ILT Hub] 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("[ILT Hub] " + l);
break;
case "load":
// Equipping a suit swaps gear mid-session, so it needs an explicit confirm.
RequestConfirm($"equip suit '{name ?? "(auto)"}'", () => _ctx.Chat("[ILT Hub] " + Gear.Suits.Load(name)));
break;
default:
_ctx.Chat("[ILT Hub] Usage: /ra hub suit list|test [name]|load [name]");
break;
}
}
}

View file

@ -0,0 +1,285 @@
// IltHubState.cs — Persisted per-character state for the ILT Hub (Infinite Leaftide tools).
//
// Lives in <charFolder>\ilt-hub.json, deliberately separate from the combat settings
// profile (Default.json / /ra settings) so ILT data never leaks into combat profiles and
// non-ILT characters stay untouched. Serialized with the NativeAOT source-generated
// RynthAiJsonContext (IncludeFields = true), so plain public fields are used throughout.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <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>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>Cached result of the server-options check (see IltServerOptions).</summary>
public sealed class IltServerOptionsSnapshot
{
public string WorldName = string.Empty;
/// <summary>"ilt-features" (structured dump), "probe" (command probing) 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;
public DateTime LastUpdated = DateTime.MinValue;
/// <summary>Last transfer recipient typed into the transfer form.</summary>
public string TransferTarget = string.Empty;
public int TransferCurrencyIndex;
/// <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
{
// Healing-pet automation (UB "HealingBuddy" subset).
public bool HealingEnabled;
/// <summary>Exact name of the heal-pet essence to use; empty = auto-detect (Healing Buddy / Dule box).</summary>
public string HealPetName = string.Empty;
public int HealthThresholdPercent = 80;
/// <summary>Do not summon when current HP is below this (summoning mid-death wastes the use). 0 = off.</summary>
public int MinHealthPoints = 100;
public bool AutoDespawnAfterHeal = true;
public int RespawnDelaySeconds = 2;
public int PetTimeoutSeconds = 30;
/// <summary>
/// Allow a combat summon from an EMPTY essence when the Summon Essence Refill Charm is
/// active (server refills from banked pyreals). Still requires the server flag to be on.
/// </summary>
public bool UsePyrealRefillPath;
/// <summary>Last captured /pets and /shinies rosters (display only).</summary>
public List<string> PetLog = new();
public List<string> ShinyLog = new();
// ── Pet roster (UB Pets-tab style) ──
/// <summary>Roster type shown in the Pet tab (IltPetKind: 0 Combat, 1 Healing, 2 Cosmetic).</summary>
public int RosterKind;
/// <summary>Roster sort (IltPetSort: 0 Priority, 1 Bond, 2 Potency, 3 Breed ready, 4 Level, 5 Uses, 6 Name).</summary>
public int RosterSort;
/// <summary>User type overrides by essence name; essences not listed are auto-classified.</summary>
public List<IltPetAssignment> Assignments = new();
/// <summary>Essence name of the chosen cosmetic (display) pet; empty = none.</summary>
public string CosmeticPetName = string.Empty;
/// <summary>Keep the cosmetic pet summoned while in peace mode; it is dismissed when a combat pet is needed.</summary>
public bool KeepCosmeticOut;
/// <summary>Seconds to wait before re-summoning the cosmetic pet after it despawns.</summary>
public int CosmeticRespawnSeconds = 15;
}
/// <summary>A user's choice of summon type for one essence (matched by name, case-insensitive).</summary>
public sealed class IltPetAssignment
{
public string Name = string.Empty;
/// <summary>IltPetKind as int (0 Combat, 1 Healing, 2 Cosmetic).</summary>
public int Kind;
}
// ── 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;
/// <summary>Quest Tracker search box contents.</summary>
public string QuestFilter = string.Empty;
public string QbFilter = string.Empty;
/// <summary>Starred quest flag keys (lowercase), shown on the floating favorites HUD.</summary>
public List<string> QuestFavorites = new();
/// <summary>Quest tracker lists starred quests only.</summary>
public bool QuestFavoritesOnly;
/// <summary>Floating quest favorites HUD is shown.</summary>
public bool ShowQuestFavoritesHud;
public bool QuestFavoritesHudLocked;
// ILT section windows, opened from the Mini Remote's Options (IltSections).
/// <summary>The "Quests" window (tracker + quest bonus) is open.</summary>
public bool QuestTrackerPoppedOut;
/// <summary>The "Pets" window is open.</summary>
public bool PetsWindowOpen;
/// <summary>The "ILT Character" window (world status, session rates) is open.</summary>
public bool CharacterWindowOpen;
/// <summary>The "Banking" window is open.</summary>
public bool BankingWindowOpen;
/// <summary>The "Gear" window is open.</summary>
public bool GearWindowOpen;
/// <summary>The "Games" window is open.</summary>
public bool GamesWindowOpen;
/// <summary>The "Guardian" window (riddle translator, attribute tracker) is open.</summary>
public bool GuardianWindowOpen;
/// <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 always chunks).</summary>
public int ChunkAetheriaUnderLevel = 4;
// 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) and VTank .usd import
public string LastEquipProfile = string.Empty;
public string LastUsdPath = string.Empty;
}
// ── 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);
}

View file

@ -0,0 +1,404 @@
// IltHubStore.cs — Disk persistence for the ILT Hub.
//
// Files (all under the per-character settings folder the dashboard already uses):
// <charFolder>\ilt-hub.json live Hub state (IltHubState)
// <charFolder>\ilt-hub-transactions.json bank transaction log (capped)
// <charFolder>\ilt-hub-profiles\<n>.json named per-character Hub profiles
// <root>\IltHubProfiles\<n>.json named profiles shared by every character
// 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.PluginSdk;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltHubStore
{
/// <summary>Maximum bank transactions kept on disk (oldest dropped first).</summary>
public const int MaxTransactions = 1000;
/// <summary>Shared root (<SuiteDir>\RynthAi) for profiles usable by every character.</summary>
public static readonly string SharedRoot = RynthInstallPaths.RynthAiDir;
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;
}
public string CharFolder => _charFolder;
private string StatePath => Path.Combine(_charFolder, "ilt-hub.json");
private string TxPath => Path.Combine(_charFolder, "ilt-hub-transactions.json");
private string CharProfileDir => Path.Combine(_charFolder, "ilt-hub-profiles");
private static string SharedProfileDir => Path.Combine(SharedRoot, "IltHubProfiles");
// ── 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, RynthAiJsonContext.Default.IltHubState);
if (s != null)
{
Normalize(s);
_lastStateJson = json;
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, RynthAiJsonContext.Default.IltHubState);
if (json == _lastStateJson) return;
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.Assignments ??= new();
s.Pet.Assignments.RemoveAll(a => a == null || string.IsNullOrWhiteSpace(a.Name));
s.Pet.CosmeticPetName ??= string.Empty;
s.Pet.RosterKind = Math.Clamp(s.Pet.RosterKind, 0, 2);
s.Pet.RosterSort = Math.Clamp(s.Pet.RosterSort, 0, 6);
s.Pet.CosmeticRespawnSeconds = Math.Clamp(s.Pet.CosmeticRespawnSeconds, 5, 600);
s.Character ??= new IltCharacterState();
s.Character.ItemConversions ??= new();
s.Character.QuestFavorites ??= new();
s.Character.QuestFavorites.RemoveAll(string.IsNullOrWhiteSpace);
s.Character.AugTargets = new Dictionary<string, int>(s.Character.AugTargets ?? new(), StringComparer.OrdinalIgnoreCase);
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.Games ??= new IltGamesState();
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, RynthAiJsonContext.Default.IltBankTransactionList);
if (list != null) { _lastTxJson = json; 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, RynthAiJsonContext.Default.IltBankTransactionList);
if (json == _lastTxJson) return;
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; }
try
{
string dir = shared ? SharedProfileDir : CharProfileDir;
Directory.CreateDirectory(dir);
var copy = Clone(state);
StripRuntime(copy);
WriteAtomic(Path.Combine(dir, safe + ".json"), JsonSerializer.Serialize(copy, RynthAiJsonContext.Default.IltHubState));
return 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), RynthAiJsonContext.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;
return incoming;
}
private static IltHubState Clone(IltHubState s)
=> JsonSerializer.Deserialize(JsonSerializer.Serialize(s, RynthAiJsonContext.Default.IltHubState),
RynthAiJsonContext.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.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\&lt;world&gt;\&lt;char&gt;; 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);
}
}

View file

@ -0,0 +1,242 @@
// IltHubUi.cs — The ILT Hub's ImGui windows (render thread only).
//
// The Mini Remote is the Hub. Each former tab is its own window, opened from the Mini Remote's
// Options or "/ra hub open <section>": ILT Character (world status, Force-ILT, profiles, session
// rates), Quests (IltQuests), Pets, Banking, Gear, Games and Guardian (IltGuardian: Temple riddle
// translator, hand-in, attribute turn-in tracker). A section window draws only while the
// server reports its feature on. 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.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltHubUi
{
private const string ConfirmPopupId = "Confirm##iltconfirm";
private static readonly int SectionCount = IltSections.All.Length;
private readonly IltHubController _hub;
private readonly IltHubContext _ctx;
private IltConfirmRequest? _confirm;
private bool _confirmOpened;
private string _profileName = string.Empty;
private bool _profileShared;
private string[] _profileList = Array.Empty<string>();
private int _profileIdx;
// Per section (indexed by IltSection): drawn last frame (for shown/hidden log events) and
// whether the off-screen check already ran for the current show.
private readonly bool[] _wasDrawn = new bool[SectionCount];
private readonly bool[] _rescueChecked = new bool[SectionCount];
// Cached so the per-frame window calls don't allocate a delegate each time.
private readonly Action _characterBody, _petsBody, _bankingBody, _gearBody, _gamesBody, _guardianBody;
public IltHubUi(IltHubController hub, IltHubContext ctx)
{
_hub = hub;
_ctx = ctx;
_characterBody = RenderCharacterBody;
_petsBody = () => _hub.Pets.Render();
_bankingBody = () => _hub.Banking.Render();
_gearBody = () => _hub.Gear.Render();
_gamesBody = () => _hub.Games.Render();
_guardianBody = () => _hub.Guardian.Render();
}
public void Render()
{
// Distinct first-use offsets so sections opened together don't stack exactly.
RenderSectionWindow(IltSection.Character, "ILT Character##iltcharwin", new Vector2(520, 480), Vector2.Zero, _characterBody);
RenderSectionWindow(IltSection.Pet, "Pets##iltpetswin", new Vector2(560, 620), Vector2.Zero, _petsBody);
RenderSectionWindow(IltSection.Banking, "Banking##iltbankwin", new Vector2(560, 560), new Vector2(80, 80), _bankingBody);
RenderSectionWindow(IltSection.Gear, "Gear##iltgearwin", new Vector2(560, 560), new Vector2(120, 120), _gearBody);
RenderSectionWindow(IltSection.Games, "Games##iltgameswin", new Vector2(520, 480), new Vector2(160, 160), _gamesBody);
RenderSectionWindow(IltSection.Guardian, "Guardian##iltguardianwin", new Vector2(540, 520), new Vector2(200, 120), _guardianBody);
LogSectionTransition(IltSection.Quests, _ctx.State.Character.QuestTrackerPoppedOut && _hub.SectionAvailable(IltSection.Quests));
_hub.Games.RenderHud();
_hub.Quests.RenderFloatingWindows();
RenderConfirm();
}
/// <summary>
/// One section window: drawn while its open flag is set and the section is available, centred
/// on first use and moved back on screen once per show if a saved spot left it off-screen.
/// Closing it with the title-bar X clears the open flag.
/// </summary>
private void RenderSectionWindow(IltSection section, string title, Vector2 size, Vector2 offset, Action body)
{
var cs = _ctx.State.Character;
int i = (int)section;
bool drawn = IltSections.IsOpen(cs, section) && _hub.SectionAvailable(section);
LogSectionTransition(section, drawn);
if (!drawn) { _rescueChecked[i] = false; return; }
UiPlacement.CenterFirstUse(offset);
ImGui.SetNextWindowSize(size, ImGuiCond.FirstUseEver);
bool open = true;
if (ImGui.Begin(title, ref open))
{
if (UiPlacement.RescueOncePerShow(ref _rescueChecked[i]))
{
Vector2 moved = ImGui.GetWindowPos();
RynthLog.Write(LogCat.IltHub, $"[IltHub] {IltSections.Label(section)} window was off-screen - moved to ({moved.X:0},{moved.Y:0}).");
}
body();
}
ImGui.End();
if (!open) IltSections.SetOpen(cs, section, false);
}
/// <summary>Logs the first frame a section window is (or stops being) drawn, proving the overlay renders it.</summary>
private void LogSectionTransition(IltSection section, bool drawn)
{
int i = (int)section;
if (drawn == _wasDrawn[i]) return;
_wasDrawn[i] = drawn;
string label = IltSections.Label(section);
if (drawn)
RynthLog.Event(LogEvents.IltWindowShown, $"{label} window shown (world='{_ctx.Options.WorldName}', available={_hub.Available})");
else
RynthLog.Event(LogEvents.IltWindowHidden, $"{label} window hidden");
}
/// <summary>ILT Character window: world / options header, then session rates (or why the Hub is idle).</summary>
private void RenderCharacterBody()
{
RenderHeader();
ImGui.Separator();
if (!_hub.Available) { RenderUnavailable(); return; }
if (ImGui.CollapsingHeader("Session rates", ImGuiTreeNodeFlags.DefaultOpen)) _hub.Rates.Render();
ImGui.Spacing();
ImGui.TextDisabled("XP planner, Augmentations and Enlightenment are on the Skills panel's Progression tab");
ImGui.TextDisabled("(right-click the dashboard's Char button > Progression).");
}
private void RenderHeader()
{
var o = _ctx.Options;
string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world";
ImGui.TextColored(o.IsIltLikeWorld ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextMute, world);
ImGui.SameLine();
ImGui.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));
bool force = _ctx.State.ForceLeaftideFeatures;
if (ImGui.Checkbox("Treat this world as ILT", ref force)) _ctx.State.ForceLeaftideFeatures = force;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("World-identity override only: the Hub asks the server which features exist.\nIt never turns a feature on by itself.");
ImGui.SameLine();
if (ImGui.SmallButton("Profiles...")) { ImGui.OpenPopup("##iltprofiles"); _ctx.Post(() => _profileList = _ctx.Store.ListProfiles().ToArray()); }
RenderProfilesPopup();
}
private void RenderProfilesPopup()
{
if (!ImGui.BeginPopup("##iltprofiles")) return;
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Hub profiles (settings only; no balances)");
ImGui.SetNextItemWidth(180);
ImGui.InputTextWithHint("##profname", "profile name", ref _profileName, 64u);
ImGui.SameLine();
ImGui.Checkbox("shared", ref _profileShared);
ImGui.SameLine();
if (ImGui.SmallButton("Save"))
{
string n = _profileName; bool sh = _profileShared;
_ctx.Post(() =>
{
_ctx.Chat(_ctx.Store.SaveProfile(_ctx.State, n, sh, out string err) ? $"[ILT Hub] Saved profile '{n}'." : "[ILT Hub] Save failed: " + err);
_profileList = _ctx.Store.ListProfiles().ToArray();
});
}
var list = _profileList;
if (list.Length > 0)
{
_profileIdx = Math.Clamp(_profileIdx, 0, list.Length - 1);
ImGui.SetNextItemWidth(180);
ImGui.Combo("##proflist", ref _profileIdx, list, list.Length);
ImGui.SameLine();
if (ImGui.SmallButton("Load"))
{
string n = list[_profileIdx];
_ctx.Confirm("Load Hub profile", $"Replace the current Hub settings with profile '{n}'?",
() => _ctx.Chat(_ctx.Store.LoadProfile(_ctx.State, n, out string err) ? $"[ILT Hub] Loaded profile '{n}'." : "[ILT Hub] Load failed: " + err),
"Load");
}
}
else ImGui.TextDisabled("No saved profiles.");
ImGui.EndPopup();
}
private void RenderUnavailable()
{
var o = _ctx.Options;
if (!o.IsIltLikeWorld)
{
ImGui.TextWrapped("This is not an Infinite Leaftide / ACECustom world, so the ILT Hub is idle. "
+ "If this shard runs ACECustom under another name, tick 'Treat this world as ILT' and press Refresh.");
}
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 Hub features as enabled. Press Refresh to check again.");
}
}
// ── 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))
{
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, _confirm.Title);
ImGui.Separator();
ImGui.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;
}
}

View file

@ -0,0 +1,309 @@
// IltInventory.cs — Shared item / player-property helper for every ILT Hub feature.
//
// 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.RynthAi.IltHub;
/// <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 };
public const uint WcidRedAetheriaChunk = 42636;
public const uint WcidBlueAetheriaChunk = 42635;
// ── 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;
public const uint IntItemMaxLevel = 319;
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;
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 Func<WorldObjectCache?> _cache;
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, Func<WorldObjectCache?> cache)
{
_host = host;
_cache = cache;
}
public RynthCoreHost Host => _host;
public WorldObjectCache? 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() == CombatMode.NonCombat;
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() ?? Enumerable.Empty<WorldObject>();
/// <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;
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>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>
/// 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();
if (cache == null) return -1;
int player = unchecked((int)PlayerId);
int capacity = PlayerInt((uint)LongValueKey.ItemsCapacity, 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();
}
}

View file

@ -0,0 +1,112 @@
// IltParse.cs — Shared parsing / formatting helpers for ILT Hub server output.
//
// 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.RynthAi.IltHub;
internal static class IltParse
{
private const RegexOptions Opt = RegexOptions.Compiled | RegexOptions.CultureInvariant;
/// <summary>"/aug" level line: "Creature: 1,234".</summary>
public static readonly Regex AugLine = new(@"^(\w+):\s*([\d,]+)$", 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>"You've banked 1,234 Luminance" (session rates).</summary>
public static readonly Regex LumBanked = new(@"You've banked (?<amt>[\d,]+)\s+Luminance", Opt | RegexOptions.IgnoreCase);
/// <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);
/// <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 "&lt;Tell:…&gt;" style markup the chat window sometimes leaves on names.</summary>
public static string StripMarkup(string text)
=> Regex.Replace(text ?? string.Empty, @"<[^>]*>", string.Empty).Trim();
}

View file

@ -0,0 +1,323 @@
// IltPetStats.cs — Mag-Tools / UtilityBelt-style stats for one carried pet essence.
//
// Line 1: Name, Bond N, Lvl N, Craft N
// Line 2: Sex, Growth, Mut N, Potency S (A act +P%), Mastery, DamageType
// Line 3: [D, DR, C, CD, CR, CDR] Uses cur/max Breed Ready|n/m|Rec 4h|Juv|Neut
//
// Property ids are ACECustom (ILT) pet-device qualities, the same ones UtilityBelt's Pets
// tab reads (UB Lib\IltPetAceConstants.cs). Bond, level, craft and ratings are appraisal
// data: they read 0 until the essence has been ID'd, which HasId reports.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>Pet summon category (UB Pets "Type"). Persisted as int in <see cref="IltPetAssignment.Kind"/>.</summary>
internal enum IltPetKind { Combat = 0, Healing = 1, Cosmetic = 2 }
/// <summary>Roster sort modes (persisted as int in <see cref="IltPetState.RosterSort"/>).</summary>
internal enum IltPetSort { Priority = 0, Bond = 1, Potency = 2, BreedReady = 3, Level = 4, Uses = 5, Name = 6 }
/// <summary>One carried essence with its decoded stats. Built on the pump thread, read by the UI.</summary>
internal sealed class IltPetStats
{
public int Id;
public string Name = string.Empty;
public uint Wcid;
public IltPetKind Kind;
/// <summary>Kind came from a user assignment rather than auto-detection.</summary>
public bool KindAssigned;
public bool HasId;
public int Bond;
public int Level;
public int Craft;
public string Sex = "?";
public string Growth = string.Empty;
public int Mutations;
public int StoredPotency;
public int ActivePotency;
public int DamageBonusPercent;
public string Mastery = string.Empty;
public string DamageType = string.Empty;
public int D, DR, C, CD, CR, CDR;
public int UsesCur;
public int UsesMax;
public string Breed = "-";
public bool BreedReady;
/// <summary>Chosen for its kind: in the combat summon list, the heal pet, or the cosmetic pet.</summary>
public bool Selected;
/// <summary>Combat summon priority (list index), or int.MaxValue when not in the list.</summary>
public int Priority = int.MaxValue;
public string Line1 = string.Empty;
public string Line2 = string.Empty;
public string Line3 = string.Empty;
}
/// <summary>Reads and formats <see cref="IltPetStats"/>. Pump thread only (host reads).</summary>
internal static class IltPetStatsReader
{
// ── ACECustom / ACE property ids (UB IltPetAceConstants, PetEssenceItemInfoFormatter) ──
private const uint IntDamageType = 45;
private const uint IntMaxStructure = 91;
private const uint IntStructure = 92;
private const uint IntWorkmanship = 105;
private const uint IntSummoningMastery = 362;
private const uint IntUseLevelRequirement = 364;
private const uint IntUseRequiresLevel = 369;
private const uint IntGearDamage = 370;
private const uint IntGearDamageResist = 371;
private const uint IntGearCrit = 372;
private const uint IntGearCritResist = 373;
private const uint IntGearCritDamage = 374;
private const uint IntGearCritDamageResist = 375;
private const uint IntDamageRating = 307;
private const uint IntDamageResistRating = 308;
private const uint IntCritRating = 313;
private const uint IntCritDamageRating = 314;
private const uint IntCritResistRating = 315;
private const uint IntCritDamageResistRating = 316;
private const uint IntBondLevel = 9053;
private const uint IntCapturedDamageType = 9054;
private const uint IntPotencyStored = 9056;
private const uint IntMaleBreedingCharges = 9057;
private const uint IntMutDamage = 9070;
private const uint IntMutDamageResist = 9071;
private const uint IntMutCrit = 9072;
private const uint IntMutVitality = 9073;
private const uint IntMutPotency = 9074;
private const uint IntMutationCount = 9075;
private const uint IntMaturityKills = 9077;
private const uint FloatNextBreedingTime = 9056;
private const uint BoolNeutered = 9051;
private const uint BoolMaleOverride = 50053;
private const uint BoolJuvenile = 50054;
// ACE PetPotencyMath defaults (UB PetEssencePotencyMath).
private const int PotencyActiveCap = 150;
private const int PotencyBondDivisor = 10;
private const double PotencyDamagePerLevelPercent = 2.0;
/// <summary>ACE pet_breeding_male_max_charges default.</summary>
private const int MaleMaxBreedingCharges = 10;
/// <summary>Decodes every stat for <paramref name="wo"/> and fills the three display lines.</summary>
public static IltPetStats Read(RynthCoreHost host, IltInventory inv, WorldObject wo, long unixNow)
{
uint id = unchecked((uint)wo.Id);
var s = new IltPetStats
{
Id = wo.Id,
Name = wo.Name,
Wcid = inv.Wcid(wo),
HasId = inv.HasAppraisal(wo),
UsesCur = inv.Int(wo, IntStructure),
UsesMax = inv.Int(wo, IntMaxStructure),
};
s.Bond = inv.Int(wo, IntBondLevel);
s.Level = inv.Int(wo, IntUseRequiresLevel);
if (s.Level <= 0) s.Level = inv.Int(wo, IntUseLevelRequirement);
s.Craft = inv.Int(wo, IntWorkmanship);
// Sex: explicit override when the server set one, else ACE PetDevice.IsMale's GUID hash.
bool isMale = TryBool(host, id, BoolMaleOverride, out bool male) ? male : DeriveIsMale(wo.Id);
bool neutered = TryBool(host, id, BoolNeutered, out bool n) && n;
bool juvenile = TryBool(host, id, BoolJuvenile, out bool j) && j;
s.Sex = (isMale ? "M" : "F") + (neutered ? "n" : juvenile ? "j" : string.Empty);
// Growth only exists on bred essences (9077 present, even when 0).
if (TryInt(host, id, IntMaturityKills, out int kills))
s.Growth = !juvenile ? "Adult" : kills > 0 ? "Juv " + kills.ToString(CultureInfo.InvariantCulture) : "Juv";
int total = inv.Int(wo, IntMutationCount);
s.Mutations = total > 0 ? total
: inv.Int(wo, IntMutDamage) + inv.Int(wo, IntMutDamageResist) + inv.Int(wo, IntMutCrit)
+ inv.Int(wo, IntMutVitality) + inv.Int(wo, IntMutPotency);
s.StoredPotency = Math.Max(0, inv.Int(wo, IntPotencyStored));
s.ActivePotency = ActivePotency(s.StoredPotency, s.Bond);
s.DamageBonusPercent = (int)Math.Round(s.ActivePotency * PotencyDamagePerLevelPercent);
s.Mastery = inv.Int(wo, IntSummoningMastery) switch
{
1 => "Primalist",
2 => "Necromancer",
3 => "Naturalist",
_ => string.Empty,
};
int dmg = inv.Int(wo, IntCapturedDamageType);
if (dmg <= 0) dmg = inv.Int(wo, IntDamageType);
s.DamageType = DamageTypeName(dmg);
// Gear ratings first (what Mag ItemInfo shows), else the base rating ids.
s.D = inv.Int(wo, IntGearDamage);
s.DR = inv.Int(wo, IntGearDamageResist);
s.C = inv.Int(wo, IntGearCrit);
s.CR = inv.Int(wo, IntGearCritResist);
s.CD = inv.Int(wo, IntGearCritDamage);
s.CDR = inv.Int(wo, IntGearCritDamageResist);
if (s.D <= 0 && s.DR <= 0 && s.C <= 0 && s.CR <= 0 && s.CD <= 0 && s.CDR <= 0)
{
s.D = inv.Int(wo, IntDamageRating);
s.DR = inv.Int(wo, IntDamageResistRating);
s.C = inv.Int(wo, IntCritRating);
s.CD = inv.Int(wo, IntCritDamageRating);
s.CR = inv.Int(wo, IntCritResistRating);
s.CDR = inv.Int(wo, IntCritDamageResistRating);
}
int charges = inv.Int(wo, IntMaleBreedingCharges);
double nextBreed = TryDouble(host, id, FloatNextBreedingTime, out double nb) ? nb : 0;
(s.Breed, s.BreedReady) = FormatBreed(isMale, neutered, juvenile, charges, nextBreed, unixNow);
FormatLines(s);
return s;
}
/// <summary>Builds Line1..Line3 from the decoded fields (Kind/Selected don't affect the text).</summary>
public static void FormatLines(IltPetStats s)
{
var l1 = new StringBuilder(s.Name);
if (s.Bond > 0) l1.Append(", Bond ").Append(s.Bond.ToString(CultureInfo.InvariantCulture));
if (s.Level > 0) l1.Append(", Lvl ").Append(s.Level.ToString(CultureInfo.InvariantCulture));
if (s.Craft > 0) l1.Append(", Craft ").Append(s.Craft.ToString(CultureInfo.InvariantCulture));
s.Line1 = l1.ToString();
var l2 = new StringBuilder(s.Sex);
if (s.Growth.Length > 0) l2.Append(", Growth ").Append(s.Growth);
l2.Append(", Mut ").Append(s.Mutations.ToString(CultureInfo.InvariantCulture));
l2.Append(", Potency ").Append(s.StoredPotency.ToString(CultureInfo.InvariantCulture));
if (s.StoredPotency > 0)
l2.Append(" (").Append(s.ActivePotency.ToString(CultureInfo.InvariantCulture))
.Append(" act +").Append(s.DamageBonusPercent.ToString(CultureInfo.InvariantCulture)).Append("%)");
if (s.Mastery.Length > 0) l2.Append(", ").Append(s.Mastery);
if (s.DamageType.Length > 0) l2.Append(", ").Append(s.DamageType);
s.Line2 = l2.ToString();
var parts = new List<string>(4);
string ratings = RatingsBracket(s);
if (ratings.Length > 0) parts.Add(ratings);
if (s.UsesMax > 0) parts.Add($"Uses {s.UsesCur}/{s.UsesMax}");
else if (s.UsesCur > 0) parts.Add($"Uses {s.UsesCur}");
if (s.Breed != "-") parts.Add("Breed " + s.Breed);
if (!s.HasId) parts.Add("ID pending");
s.Line3 = parts.Count > 0 ? string.Join(" ", parts) : "-";
}
/// <summary>Orders rows for display; ties keep a stable name order.</summary>
public static IltPetStats[] Sort(IEnumerable<IltPetStats> rows, IltPetSort mode)
{
var list = new List<IltPetStats>(rows);
Comparison<IltPetStats> byName = (a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
Comparison<IltPetStats> cmp = mode switch
{
// Selected first, then combat priority, then name.
IltPetSort.Priority => (a, b) => Chain(b.Selected.CompareTo(a.Selected), a.Priority.CompareTo(b.Priority), byName(a, b)),
IltPetSort.Bond => (a, b) => Chain(b.Bond.CompareTo(a.Bond), byName(a, b)),
IltPetSort.Potency => (a, b) => Chain(b.StoredPotency.CompareTo(a.StoredPotency), b.ActivePotency.CompareTo(a.ActivePotency), byName(a, b)),
IltPetSort.BreedReady => (a, b) => Chain(b.BreedReady.CompareTo(a.BreedReady), b.Bond.CompareTo(a.Bond), byName(a, b)),
IltPetSort.Level => (a, b) => Chain(b.Level.CompareTo(a.Level), byName(a, b)),
IltPetSort.Uses => (a, b) => Chain(b.UsesCur.CompareTo(a.UsesCur), byName(a, b)),
_ => byName,
};
list.Sort(cmp);
return list.ToArray();
}
private static int Chain(params int[] results)
{
foreach (int r in results) if (r != 0) return r;
return 0;
}
/// <summary>ACE PetPotencyMath: min(stored, ceil(bond / 10)), at least 1 with any bond, capped at 150.</summary>
private static int ActivePotency(int stored, int bond)
{
if (stored <= 0 || bond <= 0) return 0;
int cap = Math.Max(1, (bond + PotencyBondDivisor - 1) / PotencyBondDivisor);
return Math.Min(stored, Math.Min(cap, PotencyActiveCap));
}
/// <summary>ACE PetDevice.IsMale when no override is set (murmur3 fmix32 on the object GUID).</summary>
private 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>Breeding cell: Neut / Juv / male charges n/max / female "Rec Nh" or "Ready".</summary>
private static (string Text, bool Ready) FormatBreed(bool isMale, bool neutered, bool juvenile,
int maleCharges, double nextBreedingUnix, long unixNow)
{
if (neutered) return ("Neut", false);
if (juvenile) return ("Juv", false);
if (isMale)
{
int ch = Math.Max(0, maleCharges);
return ($"{ch}/{MaleMaxBreedingCharges}", ch > 0);
}
if (nextBreedingUnix > 0 && unixNow < (long)nextBreedingUnix)
{
long remain = (long)nextBreedingUnix - unixNow;
int hours = (int)(remain / 3600);
return (hours > 0 ? $"Rec {hours}h" : $"Rec {(int)(remain % 3600 / 60)}m", false);
}
return ("Ready", true);
}
private static string RatingsBracket(IltPetStats s)
{
var sb = new StringBuilder();
void Add(string label, int v)
{
if (v <= 0) return;
if (sb.Length > 0) sb.Append(", ");
sb.Append(label).Append(' ').Append(v.ToString(CultureInfo.InvariantCulture));
}
Add("D", s.D); Add("DR", s.DR); Add("C", s.C); Add("CD", s.CD); Add("CR", s.CR); Add("CDR", s.CDR);
return sb.Length > 0 ? "[" + sb + "]" : string.Empty;
}
/// <summary>Single AC DamageType flag → name (combined flags return empty).</summary>
private static string DamageTypeName(int flags) => flags switch
{
1 => "Slash",
2 => "Pierce",
4 => "Bludgeon",
8 => "Cold",
16 => "Fire",
32 => "Acid",
64 => "Lightning",
1024 => "Nether",
_ => string.Empty,
};
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 bool TryDouble(RynthCoreHost host, uint id, uint stype, out double v)
{
v = 0;
return host.HasGetObjectDoubleProperty && host.TryGetObjectDoubleProperty(id, stype, out v);
}
}

View file

@ -0,0 +1,974 @@
// IltPets.cs — ILT Hub "Pet" tab.
//
// * Pet roster (UtilityBelt Pets-tab style): every carried pet essence with three stat
// lines (bond / level / craft · sex / mutations / potency / mastery · ratings / uses /
// breeding), filtered by summon type (Combat / Healing / Cosmetic) and sortable.
// Pets are detected by type (essence WCID block, summoning-gem icon underlay,
// Summoning use requirement, ACECustom bond/potency) — a pet-like name only nominates
// an item for appraisal. Healing Buddy / Dule box and cosmetic naming pick the type,
// else Combat; any essence can be re-typed ("Add sel." or right-click a row).
// - Combat: the tick list is the existing ConsumableRules Type=="Pet" list that
// PetManager summons from (list order = summon priority) — no second summoner.
// - Healing: the tick picks the heal pet the healing state machine uses.
// - Cosmetic: the tick picks a display pet; "Keep cosmetic pet out" summons it in
// peace mode and dismisses it when PetManager needs the slot for a fight.
// Summon / Despawn act on the highlighted row (or the type's chosen pet).
// * Pet charms: Summon Essence Refill (server refills an empty essence from banked
// pyreals) and Universal Summoning Mastery, read from the charm appraisal text and the
// player bools the server stamps. Feeds PetManager.AllowSummonOnEmpty.
// * Healing pet (UB HealingBuddy subset): summons a heal pet when HP drops, dismisses it
// after the heal lands, holds PetManager's combat summons while it is out.
// * /pets and /shinies roster capture (read-only display).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltPets : IIltFeature
{
private static readonly string[] KindNames = { "Combat", "Healing", "Cosmetic" };
private static readonly string[] SortNames = { "Priority", "Bond", "Potency", "Breed ready", "Level", "Uses", "Name" };
/// <summary>Un-ID'd essences auto-appraised per 2 s scan (keeps the server request rate low).</summary>
private const int AutoAppraisePerScan = 2;
private readonly IltHubContext _ctx;
// Healing-pet state machine.
private enum HealState { Idle, Summoning, Despawning }
private HealState _heal = HealState.Idle;
private long _healStartedAt;
private long _despawnAt;
private long _healCooldownUntil;
private int _healEssenceId;
private long _lastHealThink;
private string _healStatus = "idle";
// Roster snapshot (rebuilt on the pump thread, read by the render thread).
private volatile IltPetStats[] _pets = Array.Empty<IltPetStats>();
private long _lastPetScan;
// Active-pet / cosmetic bookkeeping (pump thread; the ui* copies are for the render thread).
private long _lastPresenceThink;
private int _lastSummonEssenceId;
private int _cosmeticOutEssenceId;
private long _cosmeticNextAt;
private volatile string _uiActivePet = string.Empty;
private volatile string _cosmeticStatus = "off";
private volatile string _hudPetName = string.Empty;
private volatile string _hudPetStatus = string.Empty;
/// <summary>Mini Remote pet line: the pet that is out, else the first combat essence in priority order.</summary>
public string HudPetName => _hudPetName;
/// <summary>Mini Remote pet status: "Out", "Ready", "Empty" or "Healing" (empty when there is no pet).</summary>
public string HudPetStatus => _hudPetStatus;
// Charm / supply status cached for the render thread.
private volatile bool _uiRefillActive;
private volatile bool _uiMasteryActive;
private volatile bool _uiHasCasting = true;
// Render-thread only: highlighted row and the sorted view cache.
private int _highlightId;
private IltPetStats[]? _viewSource;
private int _viewKind = -1;
private int _viewSort = -1;
private IltPetStats[] _view = Array.Empty<IltPetStats>();
public IltPets(IltHubContext ctx) => _ctx = ctx;
private IltPetState S => _ctx.State.Pet;
// ── Classification ──────────────────────────────────────────────────────
// Pet-device type signals (client-visible assessment properties).
private const uint IntMaxStructure = 91;
private const uint IntUseRequiresSkill = 366;
private const uint IntUseRequiresSkillSpec = 368;
private const uint IntBondLevel = 9053; // ACECustom pet essence
private const uint IntPotencyStored = 9056; // ACECustom pet essence
private const int SkillSummoning = 54;
private const uint DidIconUnderlay = 52;
/// <summary>Low 24 bits of the summoning-gem icon underlay (0x06007420) every pet device carries.</summary>
private const uint SummonGemUnderlay = 0x007420;
/// <summary>Icon-underlay verdict per object id (the DID never changes; only successful reads are cached).</summary>
private readonly Dictionary<int, bool> _underlayCache = new();
/// <summary>
/// True when the item is a pet device by type, not by name: the ACECustom combat
/// essence WCID block, the summoning-gem icon underlay, a Summoning-skill use
/// requirement, or ACECustom bond/potency properties. Names (" Essence", heal /
/// stamina / cosmetic pet naming) only make an item a candidate, which must then show
/// charges (MaxStructure) — so augmentation gems like "Jibril's Essence" stay out.
/// Spirits, charms, capture devices and summoned pet creatures are never pets.
/// </summary>
public bool IsPetDevice(WorldObject wo)
{
uint w = _ctx.Inventory.Wcid(wo);
if (w == IltInventory.WcidEncapsulatedSpirit) return false;
if (w is >= 78780030 and <= 78780089) return false; // charm block
if (w is >= 78780001 and <= 78780012) return false; // capture devices
if (w is >= 787802001 and <= 787802072) return false; // summoned combat pet creatures
if (w is >= 787801001 and <= 787801072) return true; // combat essence block
if (HasSummonGemUnderlay(wo)) return true;
if (RequiresSummoning(wo)) return true;
if (_ctx.Inventory.Int(wo, IntBondLevel) > 0 || _ctx.Inventory.Int(wo, IntPotencyStored, -1) >= 0) return true;
return IsPetNameCandidate(wo.Name) && _ctx.Inventory.Int(wo, IntMaxStructure) > 0;
}
/// <summary>Name hints UB's pet scan uses; never sufficient on their own (see <see cref="IsPetDevice"/>).</summary>
private static bool IsPetNameCandidate(string n)
=> n.EndsWith(" Essence", StringComparison.OrdinalIgnoreCase)
|| LooksLikeHealPet(n) || LooksLikeStaminaPet(n) || LooksLikeCosmeticPet(n);
/// <summary>UseRequiresSkill / UseRequiresSkillSpec is Summoning (appraisal data).</summary>
private bool RequiresSummoning(WorldObject wo)
=> _ctx.Inventory.Int(wo, IntUseRequiresSkill) == SkillSummoning
|| _ctx.Inventory.Int(wo, IntUseRequiresSkillSpec) == SkillSummoning;
/// <summary>Icon underlay is the summoning gem (network-populated, no appraisal needed; engine 2026.10.4.19+).</summary>
private bool HasSummonGemUnderlay(WorldObject wo)
{
if (_underlayCache.TryGetValue(wo.Id, out bool known)) return known;
var host = _ctx.Host;
if (!host.HasGetObjectDataIdProperty
|| !host.TryGetObjectDataIdProperty(unchecked((uint)wo.Id), DidIconUnderlay, out uint did))
return false;
bool match = (did & 0x00FFFFFF) == SummonGemUnderlay;
_underlayCache[wo.Id] = match;
return match;
}
/// <summary>"Healing Buddy" / "Dule box" naming used by the server's heal pets.</summary>
private static bool LooksLikeHealPet(string n)
=> (n.Contains("healing", StringComparison.OrdinalIgnoreCase) && n.Contains("buddy", StringComparison.OrdinalIgnoreCase))
|| (n.Contains("dule", StringComparison.OrdinalIgnoreCase) && n.Contains("box", StringComparison.OrdinalIgnoreCase));
/// <summary>Stamina buddy / crate / pet naming.</summary>
private static bool LooksLikeStaminaPet(string n)
=> n.Contains("stamina", StringComparison.OrdinalIgnoreCase)
&& (n.Contains("buddy", StringComparison.OrdinalIgnoreCase) || n.Contains("crate", StringComparison.OrdinalIgnoreCase)
|| n.Contains("pet", StringComparison.OrdinalIgnoreCase));
/// <summary>Cosmetic / plush / display pet naming.</summary>
private static bool LooksLikeCosmeticPet(string n)
=> n.Contains("cosmetic", StringComparison.OrdinalIgnoreCase) || n.Contains("plush", StringComparison.OrdinalIgnoreCase)
|| n.Contains("display pet", StringComparison.OrdinalIgnoreCase);
/// <summary>Name candidate that hasn't been appraised yet, so its type can't be confirmed.</summary>
private bool IsUnconfirmedCandidate(WorldObject wo)
=> IsPetNameCandidate(wo.Name) && !IsPetDevice(wo)
&& _ctx.Host.HasHasAppraisalData && !_ctx.Inventory.HasAppraisal(wo);
private IltPetAssignment? FindAssignment(string name)
=> S.Assignments.FirstOrDefault(a => a.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
/// <summary>
/// Summon type for a carried item: the user's override wins, then the configured heal
/// pet. Anything else must be a pet device by type (<see cref="IsPetDevice"/>); its
/// naming then picks Healing / Cosmetic, defaulting to Combat. Null = not a pet.
/// </summary>
private IltPetKind? ClassifyKind(WorldObject wo, out bool assigned)
{
var a = FindAssignment(wo.Name);
if (a != null)
{
assigned = true;
return (IltPetKind)Math.Clamp(a.Kind, 0, 2);
}
assigned = false;
if (NameIs(wo, S.HealPetName)) return IltPetKind.Healing;
if (!IsPetDevice(wo)) return null;
if (LooksLikeHealPet(wo.Name)) return IltPetKind.Healing;
if (LooksLikeCosmeticPet(wo.Name)) return IltPetKind.Cosmetic;
return IltPetKind.Combat;
}
private static bool NameIs(WorldObject wo, string name)
=> !string.IsNullOrWhiteSpace(name) && wo.Name.Equals(name.Trim(), StringComparison.OrdinalIgnoreCase);
private WorldObject? FindCarried(string name)
=> string.IsNullOrWhiteSpace(name) ? null : _ctx.Inventory.Items().FirstOrDefault(wo => NameIs(wo, name));
/// <summary>Heal-pet essence: the ticked heal pet, else the first Healing-typed essence.</summary>
private WorldObject? FindHealEssence()
{
if (!string.IsNullOrWhiteSpace(S.HealPetName)) return FindCarried(S.HealPetName);
return _ctx.Inventory.Items().FirstOrDefault(wo => ClassifyKind(wo, out _) == IltPetKind.Healing);
}
// ── Charms / gates ──────────────────────────────────────────────────────
/// <summary>Summon Essence Refill charm is carried and switched on (or the server stamped the player bool).</summary>
public bool RefillCharmActive()
{
if (_ctx.Inventory.PlayerBool(IltInventory.BoolPyrealRefillActive)) return true;
var charm = _ctx.Inventory.FindByWcid(IltInventory.WcidSummonRefillCharm);
return charm != null && _ctx.Inventory.CharmStatus(charm) == IltTri.On;
}
public bool MasteryCharmActive()
{
if (_ctx.Options.IsOff(IltFeature.UniversalMastery)) return false;
if (_ctx.Inventory.PlayerBool(IltInventory.BoolUniversalMasteryActive)) return true;
var charm = _ctx.Inventory.FindByWcid(IltInventory.WcidUniversalMasteryCharm);
return charm != null && _ctx.Inventory.CharmStatus(charm) == IltTri.On;
}
/// <summary>
/// PetManager hook: 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 /ilt features reported pet_refill on, or the server stamped the
/// player's refill bool. An unknown feature state never spends.
/// </summary>
public bool AllowSummonOnEmpty()
{
if (!S.UsePyrealRefillPath || !_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;
}
/// <summary>PetManager hook: hold combat summons while the heal pet cycle is running.</summary>
public bool HoldCombatSummons() => _heal != HealState.Idle;
/// <summary>
/// PetManager hook (pump thread): a pet already holds the slot and monsters are near.
/// When that pet is the cosmetic pet, dismiss it so a combat pet can be summoned.
/// Returns true when a dismiss was issued.
/// </summary>
public bool YieldPetForCombat()
{
if (_heal != HealState.Idle || string.IsNullOrWhiteSpace(S.CosmeticPetName)) return false;
var pet = FindOwnPet();
var essence = FindCarried(S.CosmeticPetName);
if (pet == null || essence == null) return false;
if (!PetMatchesEssence(pet, essence) && _cosmeticOutEssenceId != essence.Id) return false;
if (_ctx.Inventory.IsBusy || !_ctx.Inventory.Use(essence)) return false;
long now = IltHubContext.NowMs;
_cosmeticOutEssenceId = 0;
_cosmeticNextAt = now + Math.Max(5, S.CosmeticRespawnSeconds) * 1000L;
_cosmeticStatus = "dismissed for combat";
RynthLog.Trace(LogCat.IltPets, $"cosmetic pet '{pet.Name}' dismissed so a combat pet can be summoned");
return true;
}
// ── Rosters ─────────────────────────────────────────────────────────────
/// <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)
{
if (nowMs - _lastPetScan >= 2000)
{
_lastPetScan = nowMs;
RebuildPetSnapshot(autoAppraise: true);
// Host reads (and appraisal requests) happen here, never on the render thread.
_uiRefillActive = RefillCharmActive();
_uiMasteryActive = MasteryCharmActive();
_uiHasCasting = _ctx.Inventory.HasCastingSupplies();
}
if (nowMs - _lastHealThink >= 250)
{
_lastHealThink = nowMs;
TickHealing(nowMs);
}
if (nowMs - _lastPresenceThink >= 1000)
{
_lastPresenceThink = nowMs;
var pet = FindOwnPet();
_uiActivePet = pet?.Name ?? string.Empty;
TickCosmetic(nowMs, pet);
UpdateHudPetLine(pet);
}
}
/// <summary>Refreshes the Mini Remote's pet name / status pair (pump thread).</summary>
private void UpdateHudPetLine(WorldObject? pet)
{
if (pet != null)
{
_hudPetName = ResolveActiveEssence(pet)?.Name ?? pet.Name;
_hudPetStatus = _heal != HealState.Idle ? "Healing" : "Out";
return;
}
var next = ChosenEssence(IltPetKind.Combat);
if (next == null) { _hudPetName = string.Empty; _hudPetStatus = string.Empty; return; }
_hudPetName = next.Name;
_hudPetStatus = _ctx.Inventory.Uses(next) == 0 && !AllowSummonOnEmpty() ? "Empty" : "Ready";
}
public bool OnChat(string text)
{
// "<pet> casts Heal Other ... and restores N points of your health."
if (_heal == HealState.Summoning
&& text.Contains("casts", StringComparison.OrdinalIgnoreCase)
&& text.Contains("heal other", StringComparison.OrdinalIgnoreCase)
&& text.Contains("restores", StringComparison.OrdinalIgnoreCase)
&& text.Contains("points of your health", StringComparison.OrdinalIgnoreCase))
{
if (S.AutoDespawnAfterHeal)
{
_heal = HealState.Despawning;
_despawnAt = IltHubContext.NowMs + 1000;
_healStatus = "heal landed, dismissing";
}
else
{
EndHealCycle(IltHubContext.NowMs, "heal landed");
}
}
return false;
}
public void OnLogout()
{
_heal = HealState.Idle;
_pets = Array.Empty<IltPetStats>();
_uiActivePet = string.Empty;
_lastSummonEssenceId = 0;
_cosmeticOutEssenceId = 0;
_cosmeticNextAt = 0;
}
// ── Healing pet ─────────────────────────────────────────────────────────
private void TickHealing(long now)
{
if (!S.HealingEnabled)
{
if (_heal != HealState.Idle) { _heal = HealState.Idle; _healStatus = "off"; }
return;
}
switch (_heal)
{
case HealState.Idle:
{
if (now < _healCooldownUntil) return;
var (cur, max) = _ctx.Inventory.PlayerHealth();
if (max == 0) return;
int pct = (int)(cur * 100 / max);
if (pct >= Math.Clamp(S.HealthThresholdPercent, 1, 99)) { _healStatus = $"HP {pct}% ok"; return; }
if (S.MinHealthPoints > 0 && cur < S.MinHealthPoints) { _healStatus = "HP below minimum, not summoning"; return; }
if (_ctx.Inventory.IsBusy) return;
if (AnyOwnPetPresent()) { _healStatus = "another pet is out"; return; }
var essence = FindHealEssence();
if (essence == null) { _healStatus = "no heal-pet essence found"; return; }
if (_ctx.Inventory.Uses(essence) == 0 && !AllowSummonOnEmpty()) { _healStatus = "heal-pet essence is empty"; return; }
if (!_ctx.Inventory.Use(essence)) return;
_healEssenceId = essence.Id;
_lastSummonEssenceId = essence.Id;
_healStartedAt = now;
_heal = HealState.Summoning;
_healStatus = $"summoning heal pet (HP {pct}%)";
break;
}
case HealState.Summoning:
{
long timeout = Math.Max(5, S.PetTimeoutSeconds) * 1000L;
if (now - _healStartedAt < timeout) return;
// No heal seen in time: dismiss only if the pet is actually up.
if (AnyOwnPetPresent()) UseHealEssence();
EndHealCycle(now, "timed out waiting for heal");
break;
}
case HealState.Despawning:
{
if (now < _despawnAt || _ctx.Inventory.IsBusy) return;
if (AnyOwnPetPresent()) UseHealEssence();
EndHealCycle(now, "dismissed");
break;
}
}
}
private void EndHealCycle(long now, string why)
{
_heal = HealState.Idle;
_healCooldownUntil = now + Math.Max(1, S.RespawnDelaySeconds) * 1000L;
_healStatus = why;
}
private void UseHealEssence()
{
var cache = _ctx.Inventory.Cache;
var essence = cache?[_healEssenceId];
if (essence != null) _ctx.Inventory.Use(essence);
}
// ── Active pet ──────────────────────────────────────────────────────────
/// <summary>The live "&lt;Me&gt;'s …" creature (server pet naming), or null.</summary>
private WorldObject? FindOwnPet()
{
var cache = _ctx.Inventory.Cache;
if (cache == null || _ctx.CharName.Length == 0) return null;
string prefix = _ctx.CharName + "'s ";
return cache.GetLandscape().FirstOrDefault(wo => wo != null && wo.Name.StartsWith(prefix, StringComparison.Ordinal));
}
private bool AnyOwnPetPresent() => FindOwnPet() != null;
/// <summary>"Fire Banshee Essence (250)" → "Fire Banshee": the part the summoned creature is named after.</summary>
private static string EssenceBaseName(string essenceName)
{
int i = essenceName.IndexOf(" Essence", StringComparison.OrdinalIgnoreCase);
return (i > 0 ? essenceName[..i] : essenceName).Trim();
}
private static bool PetMatchesEssence(WorldObject pet, WorldObject essence) => PetMatchesEssence(pet, essence.Name);
private static bool PetMatchesEssence(WorldObject pet, string essenceName)
{
string b = EssenceBaseName(essenceName);
return b.Length > 0 && pet.Name.Contains(b, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Essence that summoned <paramref name="pet"/>: the longest essence base name contained
/// in the creature's name, else the last essence this tab / the heal cycle used.
/// </summary>
private WorldObject? ResolveActiveEssence(WorldObject pet)
{
WorldObject? best = null;
int bestLen = 0;
WorldObject? last = null;
foreach (var wo in _ctx.Inventory.Items())
{
if (wo.Id == _lastSummonEssenceId) last = wo;
if (ClassifyKind(wo, out _) == null) continue;
string b = EssenceBaseName(wo.Name);
if (b.Length > bestLen && pet.Name.Contains(b, StringComparison.OrdinalIgnoreCase))
{
best = wo;
bestLen = b.Length;
}
}
return best ?? last;
}
// ── Cosmetic pet ────────────────────────────────────────────────────────
/// <summary>Keeps the chosen cosmetic pet summoned while nothing else needs the pet slot.</summary>
private void TickCosmetic(long now, WorldObject? pet)
{
if (!S.KeepCosmeticOut) { _cosmeticStatus = "off"; return; }
if (string.IsNullOrWhiteSpace(S.CosmeticPetName)) { _cosmeticStatus = "no cosmetic pet ticked"; return; }
if (pet != null)
{
_cosmeticStatus = PetMatchesEssence(pet, S.CosmeticPetName) ? "out" : "another pet is out";
return;
}
if (now < _cosmeticNextAt || _heal != HealState.Idle || _ctx.Inventory.IsBusy) return;
if (!_ctx.Inventory.InPeaceMode) { _cosmeticStatus = "waiting for peace mode"; return; }
var settings = _ctx.Settings;
if (settings != null && settings.IsMacroRunning && settings.SummonPets) { _cosmeticStatus = "combat summoner is active"; return; }
var essence = FindCarried(S.CosmeticPetName);
if (essence == null) { _cosmeticStatus = "essence not carried"; return; }
if (_ctx.Inventory.Uses(essence) == 0 && !AllowSummonOnEmpty())
{
_cosmeticStatus = "essence is empty";
_cosmeticNextAt = now + 30_000;
return;
}
if (!_ctx.Inventory.Use(essence)) return;
_cosmeticOutEssenceId = essence.Id;
_lastSummonEssenceId = essence.Id;
// Covers the summon round-trip so the pet isn't re-summoned before it appears.
_cosmeticNextAt = now + Math.Max(5, S.CosmeticRespawnSeconds) * 1000L;
_cosmeticStatus = "summoning";
RynthLog.Trace(LogCat.IltPets, $"cosmetic pet summon: {essence.Name}");
}
// ── Manual actions (pump thread) ────────────────────────────────────────
/// <summary>Summons from <paramref name="essenceId"/>, or the current type's chosen pet when 0.</summary>
private void SummonPet(int essenceId, IltPetKind kind)
{
if (FindOwnPet() is { } outPet) { _ctx.Chat($"[ILT Hub] {outPet.Name} is already out — Despawn it first."); return; }
if (_heal != HealState.Idle) { _ctx.Chat("[ILT Hub] The heal-pet cycle is running."); return; }
if (_ctx.Inventory.IsBusy) { _ctx.Chat("[ILT Hub] Busy — try again in a moment."); return; }
WorldObject? essence = essenceId != 0 ? _ctx.Inventory.Items().FirstOrDefault(w => w.Id == essenceId) : ChosenEssence(kind);
if (essence == null) { _ctx.Chat($"[ILT Hub] No {KindNames[(int)kind].ToLowerInvariant()} pet selected."); return; }
if (_ctx.Inventory.Uses(essence) == 0 && !AllowSummonOnEmpty()) { _ctx.Chat($"[ILT Hub] {essence.Name} has no uses left."); return; }
if (!_ctx.Inventory.Use(essence)) return;
_lastSummonEssenceId = essence.Id;
if (NameIs(essence, S.CosmeticPetName)) _cosmeticOutEssenceId = essence.Id;
RynthLog.Trace(LogCat.IltPets, $"manual summon: {essence.Name}");
}
/// <summary>Dismisses the pet that is out by using the essence that summoned it again.</summary>
private void DespawnPet()
{
var pet = FindOwnPet();
if (pet == null) { _ctx.Chat("[ILT Hub] No pet is out."); return; }
if (_ctx.Inventory.IsBusy) { _ctx.Chat("[ILT Hub] Busy — try again in a moment."); return; }
var essence = ResolveActiveEssence(pet);
if (essence == null) { _ctx.Chat($"[ILT Hub] Couldn't find the essence for {pet.Name}."); return; }
if (!_ctx.Inventory.Use(essence)) return;
// A manual dismiss shouldn't be undone straight away by "Keep cosmetic pet out".
_cosmeticNextAt = IltHubContext.NowMs + Math.Max(5, S.CosmeticRespawnSeconds) * 1000L;
if (essence.Id == _cosmeticOutEssenceId) _cosmeticOutEssenceId = 0;
RynthLog.Trace(LogCat.IltPets, $"manual despawn: {pet.Name} via {essence.Name}");
}
/// <summary>The pet the type's tick selects: first combat priority, the heal pet, or the cosmetic pet.</summary>
private WorldObject? ChosenEssence(IltPetKind kind)
{
switch (kind)
{
case IltPetKind.Healing:
return FindHealEssence();
case IltPetKind.Cosmetic:
return FindCarried(S.CosmeticPetName);
default:
var rules = PetRules();
foreach (var r in rules)
{
var wo = _ctx.Inventory.Items().FirstOrDefault(w => w.Id == r.Id || NameIs(w, r.Name));
if (wo != null) return wo;
}
return null;
}
}
/// <summary>
/// Requests appraisal for every carried pet (refreshes bond / potency after fights) and
/// for un-appraised pet-named items, whose type is only known once the appraisal lands.
/// </summary>
private void ScanPack()
{
int pets = 0, candidates = 0;
foreach (var wo in _ctx.Inventory.Items())
{
if (ClassifyKind(wo, out _) != null)
{
if (_ctx.Inventory.RequestAppraisal(wo)) pets++;
}
else if (IsUnconfirmedCandidate(wo) && _ctx.Inventory.RequestAppraisal(wo))
{
candidates++;
}
}
if (pets == 0 && candidates == 0)
_ctx.Chat("[ILT Hub] Pets were appraised recently.");
else
_ctx.Chat(candidates > 0
? $"[ILT Hub] Appraising {pets} pet(s) and checking {candidates} pet-named item(s)…"
: $"[ILT Hub] Appraising {pets} pet(s)…");
RebuildPetSnapshot(autoAppraise: false);
}
/// <summary>Gives the item selected in the game a summon type (pump thread).</summary>
private void AddSelectedAs(IltPetKind kind)
{
if (!_ctx.Host.HasGetSelectedItemId) { _ctx.Chat("[ILT Hub] This client build can't read the selected item."); return; }
int id = unchecked((int)_ctx.Host.GetSelectedItemId());
var wo = _ctx.Inventory.Items().FirstOrDefault(w => w.Id == id);
if (wo == null) { _ctx.Chat("[ILT Hub] Select a pet essence in your pack first."); return; }
SetKind(wo.Id, wo.Name, kind);
_ctx.Chat($"[ILT Hub] {wo.Name} added as a {KindNames[(int)kind].ToLowerInvariant()} pet.");
}
/// <summary>
/// Re-types an essence (null = back to auto classification) and drops it from the other
/// types' selections so a pet is only ever chosen under one type.
/// </summary>
private void SetKind(int id, string name, IltPetKind? kind)
{
S.Assignments.RemoveAll(a => a.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (kind is { } k) S.Assignments.Add(new IltPetAssignment { Name = name, Kind = (int)k });
if (kind != IltPetKind.Combat && PetRules().Any(r => r.Id == id || r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
SetCombatSelected(id, name, false);
if (kind != IltPetKind.Healing && S.HealPetName.Trim().Equals(name, StringComparison.OrdinalIgnoreCase))
S.HealPetName = string.Empty;
if (kind != IltPetKind.Cosmetic && S.CosmeticPetName.Trim().Equals(name, StringComparison.OrdinalIgnoreCase))
S.CosmeticPetName = string.Empty;
RebuildPetSnapshot(autoAppraise: false);
}
/// <summary>Applies a roster tick for the row's type (pump thread).</summary>
private void SetSelected(int id, string name, IltPetKind kind, bool on)
{
switch (kind)
{
case IltPetKind.Healing: S.HealPetName = on ? name : string.Empty; break;
case IltPetKind.Cosmetic: S.CosmeticPetName = on ? name : string.Empty; break;
default: SetCombatSelected(id, name, on); break;
}
RebuildPetSnapshot(autoAppraise: false);
}
// ── Combat summon list (ConsumableRules Type=="Pet") ────────────────────
private List<ConsumableRule> PetRules()
=> _ctx.Settings?.ConsumableRules.Where(r => r.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)).ToList()
?? new List<ConsumableRule>();
/// <summary>Adds or removes an essence from the PetManager list (pump thread).</summary>
private void SetCombatSelected(int id, string name, bool on)
{
var settings = _ctx.Settings;
if (settings == null) return;
settings.ConsumableRules.RemoveAll(r => r.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)
&& (r.Id == id || r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
if (on) settings.ConsumableRules.Add(new ConsumableRule { Id = id, Name = name, Type = "Pet" });
_ctx.SaveCombatSettings?.Invoke();
}
/// <summary>Moves a configured essence up (-1) or down (+1) in summon priority (pump thread).</summary>
private void MovePriority(int id, int delta)
{
var settings = _ctx.Settings;
if (settings == null) return;
var list = settings.ConsumableRules;
int idx = list.FindIndex(r => r.Id == id && r.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase));
if (idx < 0) return;
// Find the neighbouring Pet rule in the requested direction.
int j = idx + delta;
while (j >= 0 && j < list.Count && !list[j].Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)) j += delta;
if (j < 0 || j >= list.Count) return;
(list[idx], list[j]) = (list[j], list[idx]);
_ctx.SaveCombatSettings?.Invoke();
RebuildPetSnapshot(autoAppraise: false);
}
// ── Roster snapshot (pump thread) ───────────────────────────────────────
private void RebuildPetSnapshot(bool autoAppraise)
{
var rules = PetRules();
long unixNow = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var rows = new List<IltPetStats>();
int appraised = 0;
foreach (var wo in _ctx.Inventory.Items())
{
var kind = ClassifyKind(wo, out bool assigned);
if (kind == null)
{
// Pet-named but unconfirmed: its appraisal decides whether it is a pet device.
if (autoAppraise && appraised < AutoAppraisePerScan && IsUnconfirmedCandidate(wo)
&& _ctx.Inventory.RequestAppraisal(wo))
appraised++;
continue;
}
var s = IltPetStatsReader.Read(_ctx.Host, _ctx.Inventory, wo, unixNow);
s.Kind = kind.Value;
s.KindAssigned = assigned;
int pri = rules.FindIndex(r => r.Id == wo.Id || r.Name.Equals(wo.Name, StringComparison.OrdinalIgnoreCase));
s.Priority = pri >= 0 ? pri : int.MaxValue;
s.Selected = s.Kind switch
{
IltPetKind.Healing => NameIs(wo, S.HealPetName),
IltPetKind.Cosmetic => NameIs(wo, S.CosmeticPetName),
_ => pri >= 0,
};
rows.Add(s);
// Stats beyond uses need an appraisal; trickle the requests for un-ID'd essences.
if (autoAppraise && !s.HasId && appraised < AutoAppraisePerScan && _ctx.Inventory.RequestAppraisal(wo))
appraised++;
}
_pets = rows.ToArray();
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
var settings = _ctx.Settings;
if (settings == null) { ImGui.TextDisabled("Not logged in."); return; }
RenderRosterHeader(settings);
RenderRosterTable();
ImGui.Separator();
RenderCharms();
ImGui.Separator();
RenderHealing();
ImGui.Separator();
RenderRosters();
}
/// <summary>Type / Sort combos, action buttons, the active-summon line and per-type options.</summary>
private void RenderRosterHeader(LegacyUiSettings settings)
{
var kind = (IltPetKind)Math.Clamp(S.RosterKind, 0, 2);
ImGui.TextUnformatted("Type");
ImGui.SameLine();
ImGui.SetNextItemWidth(100);
int k = (int)kind;
if (ImGui.Combo("##iltpetkind", ref k, KindNames, KindNames.Length)) { S.RosterKind = k; kind = (IltPetKind)k; _highlightId = 0; }
ImGui.SameLine();
ImGui.TextUnformatted("Sort");
ImGui.SameLine();
ImGui.SetNextItemWidth(110);
int sort = Math.Clamp(S.RosterSort, 0, SortNames.Length - 1);
if (ImGui.Combo("##iltpetsort", ref sort, SortNames, SortNames.Length)) S.RosterSort = sort;
int target = _highlightId;
var summonKind = kind;
if (ImGui.Button("Summon")) _ctx.Post(() => SummonPet(target, summonKind));
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Summon the highlighted pet (or this type's ticked pet).");
ImGui.SameLine();
if (ImGui.Button("Despawn")) _ctx.Post(DespawnPet);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Dismiss the pet that is out.");
ImGui.SameLine();
if (ImGui.Button("Scan pack")) _ctx.Post(ScanPack);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Appraise every pet to refresh bond, potency and breeding, and check pet-named items\n(an \"... Essence\" name alone isn't enough — the item must be a summoning pet device).");
ImGui.SameLine();
if (ImGui.Button("Add sel.")) _ctx.Post(() => AddSelectedAs(summonKind));
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Make the item selected in your pack a {KindNames[(int)kind].ToLowerInvariant()} pet.");
string active = _uiActivePet;
if (active.Length > 0) ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Active summon: " + active);
else ImGui.TextDisabled("Active summon: none");
switch (kind)
{
case IltPetKind.Combat:
{
bool summon = settings.SummonPets;
if (ImGui.Checkbox("Summon when monsters are near", ref summon)) _ctx.Post(() => { settings.SummonPets = summon; _ctx.SaveCombatSettings?.Invoke(); });
ImGui.SameLine();
int minMobs = settings.PetMinMonsters;
ImGui.SetNextItemWidth(90);
if (ImGui.InputInt("Min monsters", ref minMobs)) _ctx.Post(() => { settings.PetMinMonsters = Math.Max(1, minMobs); _ctx.SaveCombatSettings?.Invoke(); });
bool refill = settings.PetAutoRefill;
if (ImGui.Checkbox("Refill empty essences with Encapsulated Spirit", ref refill)) _ctx.Post(() => { settings.PetAutoRefill = refill; _ctx.SaveCombatSettings?.Invoke(); });
ImGui.TextDisabled("Tick pets to add them to the summon list; with Sort = Priority the arrows set the order.");
break;
}
case IltPetKind.Healing:
ImGui.TextDisabled("Tick one heal pet (none ticked = first Healing Buddy / Dule box). Settings are below.");
break;
case IltPetKind.Cosmetic:
{
bool keep = S.KeepCosmeticOut;
if (ImGui.Checkbox("Keep cosmetic pet out", ref keep)) S.KeepCosmeticOut = keep;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Peace mode only. Dismissed automatically when the combat summoner needs the pet slot.");
ImGui.SameLine();
int resp = S.CosmeticRespawnSeconds;
ImGui.SetNextItemWidth(90);
if (ImGui.InputInt("Respawn (s)", ref resp)) S.CosmeticRespawnSeconds = Math.Clamp(resp, 5, 600);
ImGui.TextDisabled("Tick one cosmetic pet. Status: " + _cosmeticStatus);
break;
}
}
}
/// <summary>Sorted rows of the current type, cached until the snapshot / type / sort changes.</summary>
private IltPetStats[] CurrentView()
{
var src = _pets;
int kind = Math.Clamp(S.RosterKind, 0, 2);
int sort = Math.Clamp(S.RosterSort, 0, SortNames.Length - 1);
if (!ReferenceEquals(src, _viewSource) || kind != _viewKind || sort != _viewSort)
{
_view = IltPetStatsReader.Sort(src.Where(p => (int)p.Kind == kind), (IltPetSort)sort);
_viewSource = src;
_viewKind = kind;
_viewSort = sort;
}
return _view;
}
/// <summary>One table row per pet: tick · three stat lines (highlight / right-click menu) · priority arrows.</summary>
private void RenderRosterTable()
{
var rows = CurrentView();
var kind = (IltPetKind)Math.Clamp(S.RosterKind, 0, 2);
bool showArrows = kind == IltPetKind.Combat && S.RosterSort == (int)IltPetSort.Priority;
if (rows.Length == 0)
{
ImGui.TextDisabled(kind == IltPetKind.Cosmetic
? "No cosmetic pets yet — select an essence in your pack and press Add sel., or right-click a pet in another type."
: $"No {KindNames[(int)kind].ToLowerInvariant()} pet essences carried.");
return;
}
float lineH = ImGui.GetTextLineHeightWithSpacing();
float tableH = Math.Min(320f, rows.Length * (lineH * 3 + 6) + 8);
if (!ImGui.BeginTable("##iltpets", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.ScrollY, new Vector2(0, tableH)))
return;
ImGui.TableSetupColumn("##sel", ImGuiTableColumnFlags.WidthFixed, 26);
ImGui.TableSetupColumn("##pet");
ImGui.TableSetupColumn("##ord", ImGuiTableColumnFlags.WidthFixed, showArrows ? 52 : 1);
foreach (var r in rows)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool on = r.Selected;
if (ImGui.Checkbox($"##psel{r.Id}", ref on))
{
var row = r;
_ctx.Post(() => SetSelected(row.Id, row.Name, row.Kind, on));
}
ImGui.TableNextColumn();
Vector2 start = ImGui.GetCursorPos();
if (ImGui.Selectable($"##prow{r.Id}", _highlightId == r.Id, ImGuiSelectableFlags.AllowOverlap, new Vector2(0, lineH * 3 - ImGui.GetStyle().ItemSpacing.Y)))
_highlightId = _highlightId == r.Id ? 0 : r.Id;
RenderRowContextMenu(r);
ImGui.SetCursorPos(start);
ImGui.TextColored(DamageColor(r.DamageType), r.Line1);
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, " " + r.Line2);
if (r.UsesMax > 0 && r.UsesCur == 0) ImGui.TextColored(LegacyDashboardRenderer.ColHp, " " + r.Line3);
else ImGui.TextDisabled(" " + r.Line3);
ImGui.TableNextColumn();
if (showArrows && r.Selected)
{
int id = r.Id;
if (ImGui.ArrowButton($"##pup{r.Id}", ImGuiDir.Up)) _ctx.Post(() => MovePriority(id, -1));
ImGui.SameLine();
if (ImGui.ArrowButton($"##pdn{r.Id}", ImGuiDir.Down)) _ctx.Post(() => MovePriority(id, +1));
}
}
ImGui.EndTable();
}
/// <summary>Right-click menu on a roster row: summon / move to another type / clear override.</summary>
private void RenderRowContextMenu(IltPetStats r)
{
if (!ImGui.BeginPopupContextItem($"##pctx{r.Id}")) return;
var row = r;
if (ImGui.MenuItem("Summon")) _ctx.Post(() => SummonPet(row.Id, row.Kind));
ImGui.Separator();
for (int i = 0; i < KindNames.Length; i++)
{
if (i == (int)r.Kind) continue;
var to = (IltPetKind)i;
if (ImGui.MenuItem("Move to " + KindNames[i])) _ctx.Post(() => SetKind(row.Id, row.Name, to));
}
if (r.KindAssigned && ImGui.MenuItem("Clear type override"))
_ctx.Post(() => SetKind(row.Id, row.Name, null));
ImGui.EndPopup();
}
/// <summary>Line-1 colour by the pet's damage type (white when unknown / not appraised).</summary>
private static Vector4 DamageColor(string damageType) => damageType switch
{
"Fire" => new Vector4(1.00f, 0.55f, 0.30f, 1f),
"Cold" => new Vector4(0.55f, 0.80f, 1.00f, 1f),
"Acid" => new Vector4(0.55f, 0.95f, 0.45f, 1f),
"Lightning" => new Vector4(0.85f, 0.70f, 1.00f, 1f),
"Nether" => new Vector4(0.75f, 0.50f, 0.90f, 1f),
_ => new Vector4(0.95f, 0.95f, 0.95f, 1f),
};
private void RenderCharms()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Pet charms");
bool refillOff = _ctx.Options.IsOff(IltFeature.PetRefill);
ImGui.TextUnformatted("Summon Essence Refill: " + (refillOff ? "disabled on this server" : _uiRefillActive ? "ON" : "off / not carried"));
ImGui.BeginDisabled(refillOff);
bool usePath = S.UsePyrealRefillPath;
if (ImGui.Checkbox("Summon from empty essences while the refill charm is ON (spends banked pyreals)", ref usePath))
S.UsePyrealRefillPath = usePath;
ImGui.EndDisabled();
ImGui.TextUnformatted("Universal Summoning Mastery: "
+ (_ctx.Options.IsOff(IltFeature.UniversalMastery) ? "disabled on this server" : _uiMasteryActive ? "ON" : "off / not carried"));
if (!_ctx.Options.IsOff(IltFeature.RequireComps) && !_uiHasCasting)
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "No spell components or Infinite Casting Stone carried.");
}
private void RenderHealing()
{
if (!ImGui.CollapsingHeader("Healing pet settings")) return;
bool en = S.HealingEnabled;
if (ImGui.Checkbox("Summon heal pet when health is low", ref en)) S.HealingEnabled = en;
string healPet = S.HealPetName;
ImGui.TextDisabled("Heal pet: " + (string.IsNullOrWhiteSpace(healPet) ? "auto (Healing Buddy / Dule box)" : healPet)
+ " — tick one under Type = Healing.");
int thr = S.HealthThresholdPercent;
ImGui.SetNextItemWidth(160);
if (ImGui.SliderInt("Health % trigger", ref thr, 10, 99)) S.HealthThresholdPercent = thr;
int minHp = S.MinHealthPoints;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Don't summon below HP", ref minHp, 10)) S.MinHealthPoints = Math.Max(0, minHp);
bool desp = S.AutoDespawnAfterHeal;
if (ImGui.Checkbox("Dismiss after the heal", ref desp)) S.AutoDespawnAfterHeal = desp;
int resp = S.RespawnDelaySeconds;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Respawn delay (s)", ref resp)) S.RespawnDelaySeconds = Math.Max(1, resp);
int to = S.PetTimeoutSeconds;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Heal timeout (s)", ref to)) S.PetTimeoutSeconds = Math.Max(5, to);
ImGui.TextDisabled("Status: " + _healStatus);
}
private void RenderRosters()
{
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) ImGui.BulletText(s);
ImGui.TreePop();
}
}
}

View file

@ -0,0 +1,459 @@
// IltProgression.cs — Augmentation and Enlightenment planners, drawn by the engine's
// Skills panel (Progression tab) from AppendSnapshotJson; edits arrive via HandleRemote.
//
// Augs : "/aug" levels + the SERVER cost formula (per level n: base + n*(base*LP/100),
// times a soft-cap multiplier 1/4/8/16/24 at thresholds 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 only spends unassigned XP ("/attr") before an auto-enlighten.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltProgression : IIltFeature
{
// ── Augmentation table (server values) ──────────────────────────────────
private sealed record AugDef(string Key, string Label, long Base, int LinearPercent, int CoinsPerLevel,
int S1, int S2, int S3, int S4, int Cap);
private static readonly AugDef[] Augs =
{
new("creature", "Creature", 750_000, 130, 3, 2750, 4000, 4750, 5250, 6000),
new("item", "Item", 1_000_000, 165, 18, 1250, 2000, 3000, 3500, 4000),
new("life", "Life", 975_000, 195, 12, 1000, 2000, 3000, 3750, 4000),
new("war", "War", 750_000, 140, 5, 1750, 2500, 3000, 3750, 4000),
new("void", "Void", 800_000, 160, 5, 1750, 2500, 3000, 3750, 4000),
new("duration", "Duration", 400_000, 120, 5, 1000, 2000, 2500, 3000, 4000),
new("melee", "Melee", 750_000, 140, 5, 1750, 2500, 3000, 3750, 4000),
new("missile", "Missile", 750_000, 140, 5, 1750, 2500, 3000, 3750, 4000),
new("specialization", "Specialization", 3_000_000, 200, 50, 1750, 2000, 2250, 2750, 266),
new("summon", "Summon", 500_000, 125, 36, 1250, 2000, 3000, 3500, 4000),
};
/// <summary>Luminance for raising one aug from <paramref name="cur"/> to <paramref name="tgt"/>.</summary>
private static decimal AugLumCost(AugDef a, int cur, int tgt)
{
decimal total = 0;
decimal step = a.Base * (decimal)a.LinearPercent / 100m;
for (int n = Math.Max(0, cur); n < tgt; n++)
{
int mult = n >= a.S4 ? 24 : n >= a.S3 ? 16 : n >= a.S2 ? 8 : n >= a.S1 ? 4 : 1;
total += (a.Base + n * step) * mult;
}
return total;
}
// ── 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";
// 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
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;
public IltProgression(IltHubContext ctx) => _ctx = ctx;
private IltCharacterState C => _ctx.State.Character;
// ── Commands ────────────────────────────────────────────────────────────
public void RequestAugs()
{
RynthLog.Trace(LogCat.IltProgression, $"RequestAugs()");
if (_ctx.Options.IsOff(IltFeature.Aug) || _ctx.Capture.IsPending("/aug")) return;
_augStatus = "loading...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/aug",
IsResponseLine = t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) || IltParse.AugLine.IsMatch(t),
IdleEndMs = 2000,
FirstLineTimeoutMs = 15000,
Eat = true,
OnComplete = r =>
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Aug, IltTri.Off); _augStatus = "/aug not available"; return; }
ApplyAugLines(r.Lines);
},
});
}
/// <summary>Parses "/aug" output (also fed from the login probe).</summary>
public void ApplyAugLines(List<string> lines)
{
RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines(lines={lines.Count})");
int n = 0;
foreach (string l in lines)
{
var m = IltParse.AugLine.Match(l.Trim());
if (!m.Success) continue;
string key = m.Groups[1].Value.ToLowerInvariant();
if (key == "specialize") key = "specialization";
lock (_augLevels) _augLevels[key] = (int)IltParse.ParseLeadingLong(m.Groups[2].Value);
n++;
}
_augStatus = n > 0 ? $"{n} aug types @ {DateTime.Now:t}" : "no aug lines in reply";
}
/// <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("[ILT Hub] " + _enlStatus);
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (nowMs - _lastFactsAt >= 2000)
{
_lastFactsAt = nowMs;
RefreshFacts();
}
TickSpend(nowMs);
if (_autoArmed && C.AutoEnlightenEnabled && !_spending
&& nowMs - _lastAutoCheck >= Math.Max(10, C.AutoEnlightenCheckSeconds) * 1000L)
{
_lastAutoCheck = nowMs;
TryAutoEnlighten(nowMs);
}
}
public bool OnChat(string text)
{
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;
lock (_augLevels) _augLevels.Clear();
}
// ── 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);
_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) list.Add($"Need {cost.Count} {cost.Item} (have {HaveFor(cost.Wcid)}).");
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 (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":{...}</c> to <paramref name="sb"/>. Pump thread.</summary>
public void AppendSnapshotJson(StringBuilder sb)
{
AppendAugJson(sb);
sb.Append(',');
AppendEnlJson(sb);
}
private void AppendAugJson(StringBuilder sb)
{
Dictionary<string, int> levels;
lock (_augLevels) levels = new Dictionary<string, int>(_augLevels, StringComparer.OrdinalIgnoreCase);
sb.Append("\"aug\":{\"off\":").Append(Bool(_ctx.Options.IsOff(IltFeature.Aug)));
Str(sb, "status", _augStatus);
sb.Append(",\"lumPerCoin\":").Append(C.LumPerEnlightenedCoin).Append(",\"rows\":[");
decimal totalLum = 0;
long totalCoins = 0;
for (int i = 0; i < Augs.Length; i++)
{
var a = Augs[i];
int cur = levels.TryGetValue(a.Key, out int c) ? c : 0;
int ceiling = Math.Max(cur, a.Cap);
int tgt = Math.Clamp(C.AugTargets.TryGetValue(a.Key, out int t) ? t : cur, cur, ceiling);
decimal lum = AugLumCost(a, cur, tgt);
long coins = (long)(tgt - cur) * a.CoinsPerLevel;
totalLum += lum;
totalCoins += coins;
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "key", a.Key, first: true);
Str(sb, "label", a.Label);
sb.Append(",\"cur\":").Append(cur).Append(",\"tgt\":").Append(tgt).Append(",\"cap\":").Append(ceiling);
Str(sb, "lum", lum > 0 ? IltParse.Compact((double)lum) : "-");
sb.Append(",\"coins\":").Append(coins).Append('}');
}
sb.Append(']');
Str(sb, "total", $"Total: {IltParse.Compact((double)totalLum)} luminance, {IltParse.N0(totalCoins)} coins");
long bankCoins = _ctx.State.Bank.EnlightenedCoins;
long lumPerCoin = C.LumPerEnlightenedCoin;
string shortText = totalCoins > bankCoins
? $"Coins short: {IltParse.N0(totalCoins - bankCoins)}"
+ (lumPerCoin > 0 ? $" (~{IltParse.Compact((double)(totalCoins - bankCoins) * lumPerCoin)} luminance to buy)" : "")
: string.Empty;
Str(sb, "short", shortText);
Str(sb, "banked", $"Banked luminance: {IltParse.Compact(_ctx.State.Bank.Luminance)}");
sb.Append('}');
}
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);
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('}');
}
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(RynthAiPlugin.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(RynthAiPlugin.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);
switch (a[0].ToLowerInvariant())
{
case "augload": RequestAugs(); break;
case "augtarget" when a.Length > 2:
foreach (var def in 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, Math.Max(cur, def.Cap));
break;
}
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("[ILT Hub] 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;
}
}
}

View file

@ -0,0 +1,474 @@
// IltQuests.cs — Quest Tracker UI and Quest Bonus (/qb) list for the ILT Hub Character tab.
//
// Quest Tracker reuses the meta QuestTracker (the same /myquests cache the meta
// expression engine reads) — it never runs a second parser. Friendly names come from:
// 1. an optional user-supplied quests.xml (<SuiteDir>\RynthAi\quests.xml),
// 2. the description the server prints in /myquests,
// 3. the raw flag key.
// UB's bundled quests.xml is NOT embedded (no license on UB content).
//
// QB: "/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.IO;
using System.Linq;
using System.Numerics;
using System.Text.RegularExpressions;
using System.Xml;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltQuests : IIltFeature
{
/// <summary>Optional user quest-name file (UB-style or simple key/name XML).</summary>
public static readonly string QuestsXmlPath = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"quests.xml");
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 QuestRefreshCooldownMs = 60_000;
private const long QbCooldownMs = 60_000;
private readonly IltHubContext _ctx;
private readonly Func<QuestTracker?> _tracker;
private Dictionary<string, string> _friendlyNames = new(StringComparer.OrdinalIgnoreCase);
private long _lastQuestRefreshAt = -QuestRefreshCooldownMs;
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
private bool _questsRescueChecked; // popped-out window's off-screen check done for the current show
// Render-thread UI state.
private int _questView; // 0 timed, 1 kill tasks, 2 once, 3 all
public IltQuests(IltHubContext ctx, Func<QuestTracker?> tracker)
{
_ctx = ctx;
_tracker = tracker;
LoadFriendlyNames();
}
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;
}
public string FriendlyName(QuestRecord r)
{
if (_friendlyNames.TryGetValue(r.Key, out string? n) && !string.IsNullOrWhiteSpace(n)) return n;
if (!string.IsNullOrWhiteSpace(r.Description)) return r.Description;
return r.Key;
}
// ── quests.xml (optional) ───────────────────────────────────────────────
/// <summary>Reads any element carrying a key/flag attribute plus a name/description.</summary>
public void LoadFriendlyNames()
{
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
try
{
if (File.Exists(QuestsXmlPath))
{
using var reader = XmlReader.Create(QuestsXmlPath, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, IgnoreComments = true });
while (reader.Read())
{
if (reader.NodeType != XmlNodeType.Element || !reader.HasAttributes) continue;
string? key = null, name = null;
while (reader.MoveToNextAttribute())
{
string a = reader.Name.ToLowerInvariant();
if (a is "key" or "flag" or "questflag" or "id") key = reader.Value;
else if (a is "name" or "description" or "title" or "friendlyname") name ??= reader.Value;
}
reader.MoveToElement();
if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(name))
map[key.Trim().ToLowerInvariant()] = name.Trim();
}
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltQuests, ex, "quests.xml load"); }
_friendlyNames = map;
}
// ── Commands ────────────────────────────────────────────────────────────
/// <summary>Quiet /myquests refresh with a 60 s client-side cooldown (server throttle).</summary>
public string RefreshQuests()
{
RynthLog.Trace(LogCat.IltQuests, $"RefreshQuests()");
var t = _tracker();
if (t == null) return "Quest tracker not ready.";
if (_ctx.Options.IsOff(IltFeature.Quests) || t.Disabled) return "/myquests is disabled on this server.";
long now = IltHubContext.NowMs;
if (now - _lastQuestRefreshAt < QuestRefreshCooldownMs)
return $"Wait {(QuestRefreshCooldownMs - (now - _lastQuestRefreshAt)) / 1000}s (server allows one /myquests per minute).";
_lastQuestRefreshAt = now;
t.Refresh(quiet: true);
return "Refreshing quests...";
}
/// <summary>"/ra quests check &lt;regex&gt;" — lists up to 5 matching flags in chat.</summary>
public void CheckCommand(string pattern)
{
var t = _tracker();
if (t == null) { _ctx.Chat("[ILT Hub] Quest tracker not ready."); return; }
Regex rx;
try { rx = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(200)); }
catch (ArgumentException ex) { _ctx.Chat("[ILT Hub] Bad pattern: " + ex.Message); return; }
var hits = t.Snapshot().Where(r => rx.IsMatch(r.Key) || rx.IsMatch(FriendlyName(r))).OrderBy(r => r.Key).ToList();
if (hits.Count == 0) { _ctx.Chat($"[ILT Hub] No quest flags match '{pattern}' ({t.Count} cached)."); return; }
foreach (var r in hits.Take(5))
_ctx.Chat($"[ILT Hub] {FriendlyName(r)} [{r.Key}] solves {r.Solves}{(r.MaxSolves > 0 ? "/" + r.MaxSolves : "")} - {IltParse.Duration(r.TimeUntilReady())}");
if (hits.Count > 5) _ctx.Chat($"[ILT Hub] ...and {hits.Count - 5} more.");
}
/// <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>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>Quest tracker body, filling the "Quests" window (the table uses the remaining height).</summary>
public void RenderQuestTracker()
{
var t = _tracker();
if (t == null) { ImGui.TextDisabled("Quest tracker not ready."); return; }
if (_ctx.Options.IsOff(IltFeature.Quests) || t.Disabled)
{
ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "/myquests is disabled on this server.");
return;
}
var cs = _ctx.State.Character;
if (ImGui.SmallButton("Refresh##quests")) _ctx.Post(() => _ctx.Chat("[ILT Hub] " + RefreshQuests()));
ImGui.SameLine();
if (ImGui.SmallButton("Reload quests.xml")) _ctx.Post(LoadFriendlyNames);
ImGui.SameLine();
ImGui.TextDisabled(t.IsRefreshing ? "refreshing..." : t.LastStatus
+ (t.LastRefreshUtc == DateTime.MinValue ? "" : " @ " + t.LastRefreshUtc.ToLocalTime().ToString("t")));
string filter = cs.QuestFilter;
ImGui.SetNextItemWidth(220);
if (ImGui.InputTextWithHint("##qfilter", "filter by name or key", ref filter, 64u))
cs.QuestFilter = filter;
ImGui.SameLine();
ImGui.RadioButton("Timed", ref _questView, 0); ImGui.SameLine();
ImGui.RadioButton("Kill tasks", ref _questView, 1); ImGui.SameLine();
ImGui.RadioButton("Once", ref _questView, 2); ImGui.SameLine();
ImGui.RadioButton("All", ref _questView, 3);
bool favOnly = cs.QuestFavoritesOnly;
if (ImGui.Checkbox("Favorites only", ref favOnly)) cs.QuestFavoritesOnly = favOnly;
ImGui.SameLine();
bool favHud = cs.ShowQuestFavoritesHud;
if (ImGui.Checkbox("Show floating favorites HUD", ref favHud)) cs.ShowQuestFavoritesHud = favHud;
ImGui.SameLine();
ImGui.TextDisabled("(click * to star a quest)");
var favorites = FavoriteSet();
var rows = t.Snapshot()
.Where(r => favOnly ? favorites.Contains(r.Key) : _questView == 3 || (int)Classify(r) == ViewToKind(_questView))
.Where(r => filter.Length == 0 || r.Key.Contains(filter, StringComparison.OrdinalIgnoreCase)
|| FriendlyName(r).Contains(filter, StringComparison.OrdinalIgnoreCase))
.OrderBy(r => r.TimeUntilReady())
.ThenBy(r => FriendlyName(r), StringComparer.OrdinalIgnoreCase)
.ToArray();
if (ImGui.BeginTable("##iltquests", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.Resizable,
new Vector2(0, -1)))
{
ImGui.TableSetupScrollFreeze(0, 1);
ImGui.TableSetupColumn("*", ImGuiTableColumnFlags.WidthFixed, 18);
ImGui.TableSetupColumn("Quest");
ImGui.TableSetupColumn("Solves", ImGuiTableColumnFlags.WidthFixed, 70);
ImGui.TableSetupColumn("Ready", ImGuiTableColumnFlags.WidthFixed, 110);
ImGui.TableSetupColumn("Key");
ImGui.TableHeadersRow();
foreach (var r in rows)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool starred = favorites.Contains(r.Key);
ImGui.PushStyleColor(ImGuiCol.Text, starred ? FavStarOn : FavStarOff);
if (ImGui.Selectable($"*##fav{r.Key}", false))
{
string key = r.Key;
_ctx.Post(() => ToggleFavorite(key));
}
ImGui.PopStyleColor();
if (ImGui.IsItemHovered()) ImGui.SetTooltip(starred ? "Remove from favorites" : "Add to favorites");
ImGui.TableNextColumn(); ImGui.TextUnformatted(FriendlyName(r));
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.MaxSolves > 0 ? $"{r.Solves}/{r.MaxSolves}" : r.Solves.ToString());
ImGui.TableNextColumn();
var left = r.TimeUntilReady();
if (Classify(r) == QuestKind.Once) ImGui.TextDisabled("done");
else if (left <= TimeSpan.Zero) ImGui.TextColored(LegacyDashboardRenderer.ColGreen, "ready");
else ImGui.TextUnformatted(IltParse.Duration(left));
ImGui.TableNextColumn(); ImGui.TextDisabled(r.Key);
}
ImGui.EndTable();
}
}
private static int ViewToKind(int view) => view switch { 0 => (int)QuestKind.Timed, 1 => (int)QuestKind.KillTask, _ => (int)QuestKind.Once };
// ── Favorites / floating windows ────────────────────────────────────────
private static readonly Vector4 FavStarOn = new(1.00f, 0.82f, 0.25f, 1f);
private static readonly Vector4 FavStarOff = new(0.45f, 0.48f, 0.52f, 1f);
private const string FavHudPopup = "##questfavhudopts";
/// <summary>Starred keys as a set (render thread; the list itself is only edited on the pump thread).</summary>
private HashSet<string> FavoriteSet()
=> new(_ctx.State.Character.QuestFavorites.ToArray(), StringComparer.OrdinalIgnoreCase);
/// <summary>Stars / unstars a quest flag (pump thread).</summary>
private void ToggleFavorite(string key)
{
var list = _ctx.State.Character.QuestFavorites;
if (list.RemoveAll(k => k.Equals(key, StringComparison.OrdinalIgnoreCase)) == 0)
list.Add(key.ToLowerInvariant());
}
/// <summary>
/// The "Quests" window (opened from the Mini Remote's Options or "/ra hub open quests"; drawn
/// only while the Hub is available, matching IltHubController.SectionAvailable) and the
/// floating favorites HUD. Called every frame.
/// </summary>
public void RenderFloatingWindows()
{
var cs = _ctx.State.Character;
bool hubAvailable = _ctx.Options.IsIltLikeWorld && _ctx.Options.AnyFeatureOn;
if (cs.QuestTrackerPoppedOut && hubAvailable) RenderPoppedOutTracker(cs);
else _questsRescueChecked = false;
if (cs.ShowQuestFavoritesHud) RenderFavoritesHud(cs);
}
private void RenderPoppedOutTracker(IltCharacterState cs)
{
// Offset from the Pets window's first spot so the two don't open exactly stacked.
UiPlacement.CenterFirstUse(new Vector2(40, 40));
ImGui.SetNextWindowSize(new Vector2(700, 520), ImGuiCond.FirstUseEver);
bool open = true;
if (ImGui.Begin("Quests##iltquestswin", ref open))
{
UiPlacement.RescueOncePerShow(ref _questsRescueChecked);
// Quest bonus first (collapsed by default) so the tracker table can fill the rest.
if (ImGui.CollapsingHeader("Quest bonus (/qb)##qbwin")) RenderQb();
RenderQuestTracker();
}
ImGui.End();
if (!open) cs.QuestTrackerPoppedOut = false;
}
/// <summary>Compact always-on list of starred quests and when each is ready.</summary>
private void RenderFavoritesHud(IltCharacterState cs)
{
var flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoScrollbar
| ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav;
if (cs.QuestFavoritesHudLocked) flags |= ImGuiWindowFlags.NoMove;
ImGui.SetNextWindowPos(new Vector2(260, 120), ImGuiCond.FirstUseEver);
ImGui.SetNextWindowBgAlpha(0.55f);
if (!ImGui.Begin("Quest favorites##iltquestfavhud", flags)) { ImGui.End(); return; }
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Quest favorites");
var t = _tracker();
var favorites = FavoriteSet();
if (t == null || favorites.Count == 0)
{
ImGui.TextDisabled(t == null ? "Quest tracker not ready." : "No favorites yet - star quests in the tracker.");
}
else
{
var rows = t.Snapshot().Where(r => favorites.Contains(r.Key))
.OrderBy(r => r.TimeUntilReady()).ThenBy(r => FriendlyName(r), StringComparer.OrdinalIgnoreCase).ToArray();
if (rows.Length == 0) ImGui.TextDisabled("Starred quests not in /myquests yet.");
if (ImGui.BeginTable("##questfavrows", 2, ImGuiTableFlags.SizingFixedFit))
{
foreach (var r in rows)
{
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.TextUnformatted(FriendlyName(r));
ImGui.TableNextColumn();
var left = r.TimeUntilReady();
if (Classify(r) == QuestKind.Once) ImGui.TextDisabled("done");
else if (left <= TimeSpan.Zero) ImGui.TextColored(LegacyDashboardRenderer.ColGreen, "ready");
else ImGui.TextUnformatted(IltParse.Duration(left));
}
ImGui.EndTable();
}
}
if (ImGui.IsWindowHovered() && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) ImGui.OpenPopup(FavHudPopup);
if (ImGui.BeginPopup(FavHudPopup))
{
bool locked = cs.QuestFavoritesHudLocked;
if (ImGui.Checkbox("Lock position", ref locked)) cs.QuestFavoritesHudLocked = locked;
if (ImGui.MenuItem("Open quest tracker")) cs.QuestTrackerPoppedOut = true;
if (ImGui.MenuItem("Refresh /myquests")) _ctx.Post(() => _ctx.Chat("[ILT Hub] " + RefreshQuests()));
if (ImGui.MenuItem("Hide favorites HUD")) cs.ShowQuestFavoritesHud = false;
ImGui.EndPopup();
}
ImGui.End();
}
public void RenderQb()
{
if (_ctx.Options.IsOff(IltFeature.Qb))
{
ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "/qb is disabled on this server.");
return;
}
if (ImGui.SmallButton("Load /qb list")) _ctx.Post(() => _ctx.Chat("[ILT Hub] " + RefreshQb()));
ImGui.SameLine();
long count = _qbCount;
ImGui.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, LegacyDashboardRenderer.ColAmber);
RenderQbList("Completed", _qbCompleted, filter, LegacyDashboardRenderer.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) ImGui.TextColored(color, s);
ImGui.TreePop();
}
}
}

View file

@ -0,0 +1,97 @@
// IltSections.cs - The ILT Hub's sections, each its own window, opened from the Mini Remote's
// Options or "/ra hub open <section>". Open flags live in IltCharacterState (per character).
using System;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>Section windows. Values index per-section arrays, so new sections go at the end.</summary>
internal enum IltSection
{
Character,
Quests,
Pet,
Banking,
Gear,
Games,
Guardian,
}
internal static class IltSections
{
/// <summary>Menu order (the old Hub's tab order, then the Guardian window).</summary>
public static readonly IltSection[] All =
{
IltSection.Character, IltSection.Quests, IltSection.Pet,
IltSection.Banking, IltSection.Gear, IltSection.Games, IltSection.Guardian,
};
public static string Label(IltSection s) => s switch
{
IltSection.Character => "Character",
IltSection.Quests => "Quests",
IltSection.Pet => "Pets",
IltSection.Banking => "Banking",
IltSection.Gear => "Gear",
IltSection.Games => "Games",
IltSection.Guardian => "Guardian",
_ => s.ToString(),
};
/// <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 "quests": case "quest": section = IltSection.Quests; return true;
case "pets": case "pet": section = IltSection.Pet; 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 "guardian": case "temple": case "riddle": section = IltSection.Guardian; return true;
default: section = IltSection.Character; return false;
}
}
public static bool IsOpen(IltCharacterState cs, IltSection s) => s switch
{
IltSection.Character => cs.CharacterWindowOpen,
IltSection.Quests => cs.QuestTrackerPoppedOut,
IltSection.Pet => cs.PetsWindowOpen,
IltSection.Banking => cs.BankingWindowOpen,
IltSection.Gear => cs.GearWindowOpen,
IltSection.Games => cs.GamesWindowOpen,
IltSection.Guardian => cs.GuardianWindowOpen,
_ => false,
};
public static void SetOpen(IltCharacterState cs, IltSection s, bool open)
{
switch (s)
{
case IltSection.Character: cs.CharacterWindowOpen = open; break;
case IltSection.Quests: cs.QuestTrackerPoppedOut = open; break;
case IltSection.Pet: cs.PetsWindowOpen = open; break;
case IltSection.Banking: cs.BankingWindowOpen = open; break;
case IltSection.Gear: cs.GearWindowOpen = open; break;
case IltSection.Games: cs.GamesWindowOpen = open; break;
case IltSection.Guardian: cs.GuardianWindowOpen = open; break;
}
}
/// <summary>True when any section window is open.</summary>
public static bool AnyOpen(IltCharacterState cs)
{
foreach (IltSection s in All)
if (IsOpen(cs, s)) return true;
return false;
}
/// <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,
};
}

View file

@ -0,0 +1,401 @@
// IltServerOptions.cs — Per-feature enable bits for the ILT Hub, read from the server.
//
// 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: Host.TryGetWorldName (or ForceLeaftideFeatures) decides whether we
// even ASK — it never switches a feature on by itself.
// * Preferred source: a structured "/ilt features" dump (ILTFEATURE key=0|1 lines) once
// ACECustom ships it. Today the server prints "Coming Soon", so:
// * Fallback: a one-shot login probe 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", ...).
// 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.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <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;
/// <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)
{
_host = host;
_capture = capture;
_state = state;
_chat = chat;
}
// ── 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>True when the world is (or is declared to be) an ACECustom/ILT shard.</summary>
public bool IsIltLikeWorld
{
get
{
if (_state.ForceLeaftideFeatures) return true;
string w = WorldName;
return w.Equals("InfiniteLeaftide", StringComparison.OrdinalIgnoreCase)
|| w.Contains("leaftide", StringComparison.OrdinalIgnoreCase);
}
}
/// <summary>True while a refresh (dump or 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".
if (string.IsNullOrEmpty(WorldName) && 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 dump-then-probe refresh. Manual refreshes report progress in chat; the
/// login refresh is silent.
/// </summary>
public void Refresh(bool manual)
{
if (_refreshInFlight)
{
if (manual) _chat("[ILT Hub] Server options refresh already running.");
return;
}
if (!IsIltLikeWorld)
{
if (manual) _chat("[ILT Hub] This world is not an ILT/ACECustom shard (enable Force in the Hub to override).");
return;
}
_refreshInFlight = true;
_state.ServerOptions.WorldName = WorldName;
RynthLog.Event(LogEvents.IltOptionsRefreshStart, $"refresh start (manual={manual}, world='{WorldName}')");
if (manual) _chat("[ILT Hub] Refreshing server options...");
// Step 1: structured dump. Lines start with "=== ILT Custom Features ===".
_capture.Enqueue(new IltChatRequest
{
Command = "/ilt features",
IsResponseLine = t => t.StartsWith("ILTFEATURE", StringComparison.OrdinalIgnoreCase)
|| t.Contains("ILT Custom Features", StringComparison.OrdinalIgnoreCase)
|| t.Equals("Coming Soon", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 1200,
FirstLineTimeoutMs = 8000,
Eat = true,
OnComplete = r => OnFeatureDump(r, manual),
});
}
private void OnFeatureDump(IltChatResult r, bool manual)
{
var fromDump = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string line in r.Lines)
{
if (!line.StartsWith("ILTFEATURE", StringComparison.OrdinalIgnoreCase)) continue;
foreach (var kv in ParseFeatureLine(line))
{
Set(kv.Key, kv.Value);
fromDump.Add(kv.Key);
}
}
_state.ServerOptions.Source = fromDump.Count > 0 ? "ilt-features" : "probe";
RynthLog.Trace(LogCat.IltOptions, $"feature dump: {fromDump.Count} key(s) (timedOut={r.TimedOut}, unknown={r.UnknownCommand}) → source={_state.ServerOptions.Source}");
RunProbes(fromDump, manual);
}
/// <summary>
/// Parses "ILTFEATURE bank=1 powerball=0 charms=infinitecasting:1,guardianhand:0".
/// ServerConfig-style names ("powerball_enabled") are mapped onto Hub keys.
/// </summary>
internal static IEnumerable<KeyValuePair<string, IltTri>> ParseFeatureLine(string line)
{
string body = line.Substring("ILTFEATURE".Length).Trim();
foreach (string token in body.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
int eq = token.IndexOf('=');
if (eq <= 0) continue;
string key = token.Substring(0, eq).Trim();
string val = token.Substring(eq + 1).Trim();
if (key.Equals("charms", StringComparison.OrdinalIgnoreCase))
{
foreach (string pair in val.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
int c = pair.IndexOf(':');
if (c <= 0) continue;
yield return new(IltFeature.Charm(pair.Substring(0, c)), ParseTri(pair.Substring(c + 1)));
}
continue;
}
yield return new(MapServerKey(key), ParseTri(val));
}
}
private static IltTri ParseTri(string v)
{
v = v.Trim().ToLowerInvariant();
return v is "1" or "on" or "true" or "yes" ? IltTri.On
: v is "0" or "off" or "false" or "no" ? IltTri.Off
: IltTri.Unknown;
}
private static string MapServerKey(string key)
{
string k = key.Trim().ToLowerInvariant();
return k switch
{
"powerball_enabled" => IltFeature.Powerball,
"quest_info_enabled" => IltFeature.Quests,
"pet_device_pyreal_auto_refill_enabled" => IltFeature.PetRefill,
"pet_charm_universal_summoning_mastery_enabled" => IltFeature.UniversalMastery,
"pet_bond_enabled" => IltFeature.PetBond,
"pet_potency_enabled" => IltFeature.PetPotency,
_ => k.EndsWith("_enabled", StringComparison.Ordinal) ? k.Substring(0, k.Length - "_enabled".Length) : k,
};
}
// ── 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(HashSet<string> alreadyKnown, bool manual)
{
var todo = Probes.Where(p => !alreadyKnown.Contains(p.Key)).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 unless the
// dump said otherwise.
if (!alreadyKnown.Contains(IltFeature.Enl))
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,
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($"[ILT Hub] Server options refreshed via {Source}: {on} on, {off} off.");
}
// ── Passive refusals ────────────────────────────────────────────────────
/// <summary>
/// Watches every chat line for explicit server refusals and flips the matching bit Off.
/// 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);
}
/// <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);
}
}

View file

@ -0,0 +1,240 @@
// IltSessionRates.cs — Session earnings / per-hour rates for the ILT Hub Character tab.
//
// Sources (all passive — nothing is sent to the server except the optional bank refresh
// the Banking tab already does):
// XP player quad 1 (TotalExperience) delta since session start.
// Luminance "You've banked N Luminance" chat lines (ILT overflow-to-bank message).
// 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.
// Kills RynthAiPlugin.OnKillNotification.
using System;
using System.Collections.Generic;
using System.Linq;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltSessionRates : IIltFeature
{
private const long PyrealsPerMmd = 250_000;
private const long SampleIntervalMs = 5000;
private readonly IltHubContext _ctx;
private DateTime _start = DateTime.UtcNow;
private long _startXp = -1;
private long _xp;
private long _lum;
private long _coins;
private long _pyreals;
private int _kills;
// 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;
// Render snapshot.
private volatile RateRow[] _rows = Array.Empty<RateRow>();
private sealed record RateRow(string Label, string Total, string PerHour);
/// <summary>Per-hour figures for the Mini Remote HUD (rebuilt every sample).</summary>
public sealed record RateSummary(double XpPerHour, double LumPerHour, double KillsPerHour,
double CoinsPerHour, double PyrealsPerHour, long Xp, int Kills);
private static readonly RateSummary EmptySummary = new(0, 0, 0, 0, 0, 0, 0);
private volatile RateSummary _summary = EmptySummary;
/// <summary>Latest per-hour summary (safe from the render thread).</summary>
public RateSummary Summary => _summary;
/// <summary>When the current session (or the last Reset) started.</summary>
public DateTime SessionStartUtc => _start;
public IltSessionRates(IltHubContext ctx) => _ctx = ctx;
/// <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;
long delta = newValue - oldValue;
if (delta <= 0) return; // spending / sending isn't income
if (key == "EnlightenedCoins") _coins += delta;
else if (key == "Pyreals") _pyreals += delta;
}
public void RecordKill() => _kills++;
public void Reset()
{
RynthLog.Trace(LogCat.IltRates, $"Reset()");
_start = DateTime.UtcNow;
_startXp = -1;
_xp = _lum = _coins = _pyreals = 0;
_kills = 0;
_lastInvCoins = _lastInvPyreals = -1;
_lastItemCounts.Clear();
_itemGains.Clear();
_lastSampleAt = 0;
_summary = EmptySummary;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (nowMs - _lastSampleAt < SampleIntervalMs) return;
_lastSampleAt = nowMs;
var inv = _ctx.Inventory;
long totalXp = inv.PlayerQuad(IltInventory.QuadTotalXp);
if (totalXp > 0)
{
if (_startXp < 0) _startXp = totalXp;
_xp = Math.Max(0, totalXp - _startXp);
}
_coins += Gain(ref _lastInvCoins, inv.CountByWcid(IltInventory.WcidEnlightenedCoin));
_pyreals += Gain(ref _lastInvPyreals, inv.CountByWcid(IltInventory.WcidPyreal));
// 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();
}
/// <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;
}
public bool OnChat(string text)
{
var m = IltParse.LumBanked.Match(text);
if (m.Success) _lum += IltParse.ParseLeadingLong(m.Groups["amt"].Value);
return false;
}
public void OnLogout() => Reset();
// ── Rows ────────────────────────────────────────────────────────────────
private void BuildRows()
{
double hours = Math.Max((DateTime.UtcNow - _start).TotalHours, 1.0 / 3600);
_summary = new RateSummary(_xp / hours, _lum / hours, _kills / hours, _coins / hours, _pyreals / hours, _xp, _kills);
var rows = new List<RateRow>
{
Row("XP", _xp, hours),
Row("Luminance banked", _lum, hours),
Row("Enlightened Coins", _coins, hours),
Row("Pyreals", _pyreals, hours),
new(" as MMD", (_pyreals / (double)PyrealsPerMmd).ToString("0.0"), (_pyreals / (double)PyrealsPerMmd / hours).ToString("0.0")),
new("Kills", _kills.ToString(), (_kills / hours).ToString("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();
}
private static RateRow Row(string label, long total, double hours)
=> new(label, IltParse.Compact(total), IltParse.Compact(total / hours));
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
var elapsed = DateTime.UtcNow - _start;
ImGui.TextDisabled($"Session {IltParse.Duration(elapsed)}");
ImGui.SameLine();
if (ImGui.SmallButton("Reset##rates")) _ctx.Post(Reset);
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)
{
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Label);
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Total);
ImGui.TableNextColumn(); ImGui.TextColored(LegacyDashboardRenderer.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;
}
}
}

View file

@ -0,0 +1,205 @@
// IltSplitArrows.cs — Split-arrow imbuer (Gear tab, P2).
//
// 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.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
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;
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 (_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(LegacyDashboardRenderer.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;
ImGui.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"));
ImGui.TextDisabled("Status: " + _status);
}
}

View file

@ -0,0 +1,298 @@
// IltTempleAttributes.cs - Temple of Enlightenment attribute turn-in tracker (Guardian window).
//
// 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;
using RynthCore.Plugin.RynthAi.Meta;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <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 Func<QuestTracker?> _tracker;
private readonly IltQuests _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, Func<QuestTracker?> tracker, IltQuests quests)
{
_ctx = ctx;
_tracker = tracker;
_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 the RynthAi folder, else UB's Documents location; built-in rows otherwise.</summary>
private static IltTempleAttrRow[] LoadRows(out string source)
{
string[] candidates =
{
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() => $"{_quests.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!;
var t = _tracker();
if (t == null) return false;
foreach (string key in row.MyQuestsKeys)
if (t.TryGetFlag(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 (IltQuests.Classify(rec))
{
case IltQuests.QuestKind.KillTask:
return new(row.Attribute, row.Npc, rec.Solves, "Kill task", $"{rec.Solves}/{rec.MaxSolves}", false, true);
case IltQuests.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),
};
}

View file

@ -0,0 +1,351 @@
// IltUsdImporter.cs — VirindiTank .usd settings → RynthAi monster / weapon / consumable rules (Gear tab, P2).
//
// .usd is VTank's line-based table dump. Each table is:
// <table name>
// <column count 1..32>
// <column name> x count
// <column type token> x count
// <row count>
// per cell: <tag line s|i|b|d|...> then <value line>
// Tables we read: MyMonsters (monster rules), weapons/wands/shields/combatitems (weapon
// rules), pets (pet essences), items/itemlist/buffeditems/AssistItems (consumables).
// Object ids are resolved against the current inventory (id first, then name). The
// import is previewed first and only applied after a confirm; existing rules with the
// same name / id are replaced, everything else is kept.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltUsdImporter
{
/// <summary>Default VTank profile folder when the Decal registry value is unavailable.</summary>
public const string DefaultVtProfileDir = @"C:\Games\VirindiPlugins\VirindiTank\";
private static readonly string[] Elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
private static readonly HashSet<string> WeaponTables = new(StringComparer.OrdinalIgnoreCase) { "weapons", "wands", "shields", "combatitems" };
private static readonly HashSet<string> ConsumableTables = new(StringComparer.OrdinalIgnoreCase) { "items", "itemlist", "buffeditems", "assistitems" };
/// <summary>One parsed table: column names and rows of raw cell strings.</summary>
private sealed class UsdTable
{
public string Name = string.Empty;
public string[] Columns = Array.Empty<string>();
public List<string[]> Rows = new();
public string Get(string[] row, params string[] names)
{
foreach (string n in names)
{
int i = Array.FindIndex(Columns, c => c.Equals(n, StringComparison.OrdinalIgnoreCase));
if (i >= 0 && i < row.Length) return row[i] ?? string.Empty;
}
return string.Empty;
}
}
/// <summary>Result of a preview: the rules that would be written.</summary>
private sealed class ImportPlan
{
public string Path = string.Empty;
public List<MonsterRule> Monsters = new();
public List<ItemRule> Weapons = new();
public List<ConsumableRule> Consumables = new();
public List<string> Notes = new();
}
private readonly IltHubContext _ctx;
private volatile ImportPlan? _plan;
private volatile string _status = string.Empty;
private string _pathInput = string.Empty;
public IltUsdImporter(IltHubContext ctx)
{
_ctx = ctx;
_pathInput = ctx.State.Gear.LastUsdPath;
}
/// <summary>VTank's profile folder from Decal's registry entry, else the default install path.</summary>
public static string VtProfileDir()
{
try
{
using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"Software\Decal\Plugins\{642F1F48-16BE-48BF-B1D4-286652C4533E}");
if (key?.GetValue("ProfilePath") is string p && p.Length > 0 && Directory.Exists(p)) return p;
}
catch { /* registry unavailable: fall back */ }
return DefaultVtProfileDir;
}
// ── Parsing ─────────────────────────────────────────────────────────────
private static List<UsdTable> Parse(string[] lines)
{
var tables = new List<UsdTable>();
int i = 0;
while (i < lines.Length - 1)
{
string name = lines[i].Trim();
if (name.Length == 0 || !int.TryParse(lines[i + 1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int cols)
|| cols < 1 || cols > 32 || name.Any(char.IsWhiteSpace))
{
i++;
continue;
}
int p = i + 2;
if (p + cols * 2 >= lines.Length) { i++; continue; }
var t = new UsdTable { Name = name, Columns = new string[cols] };
for (int c = 0; c < cols; c++) t.Columns[c] = lines[p++].Trim();
p += cols; // type tokens
if (p >= lines.Length || !int.TryParse(lines[p].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int rows) || rows < 0 || rows > 100_000)
{
i++;
continue;
}
p++;
bool ok = true;
for (int r = 0; r < rows && ok; r++)
{
var row = new string[cols];
for (int c = 0; c < cols; c++)
{
if (p + 1 >= lines.Length) { ok = false; break; }
// Every cell is a tag line plus a value line; unknown tags are still two lines.
row[c] = lines[p + 1].Trim();
p += 2;
}
if (ok) t.Rows.Add(row);
}
tables.Add(t);
i = p;
}
return tables;
}
private static int ParseId(string s)
{
s = s.Trim();
if (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
&& int.TryParse(s.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int hex)) return hex;
if (long.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out long l)) return unchecked((int)l);
return 0;
}
private static bool ValidId(int id) => id != 0 && id != -1 && id != -5;
private static bool ParseBool(string s)
=> s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1" || s.Equals("yes", StringComparison.OrdinalIgnoreCase);
/// <summary>VTank damage value (name or AC damage-type bitmask) → RynthAi element, or null.</summary>
private static string? MapElement(string v)
{
v = v.Trim();
if (v.Length == 0) return null;
foreach (string e in Elements) if (v.Equals(e, StringComparison.OrdinalIgnoreCase)) return e;
if (v.StartsWith("Bludg", StringComparison.OrdinalIgnoreCase)) return "Bludgeon";
if (v.StartsWith("Pierc", StringComparison.OrdinalIgnoreCase)) return "Pierce";
if (v.StartsWith("Electric", StringComparison.OrdinalIgnoreCase)) return "Lightning";
if (v.StartsWith("Void", StringComparison.OrdinalIgnoreCase)) return "Nether";
if (!int.TryParse(v, NumberStyles.Integer, CultureInfo.InvariantCulture, out int dt) || dt <= 0) return null;
return BitsToElement(dt);
}
private static string? BitsToElement(int dt)
{
if ((dt & 1024) != 0) return "Nether";
if ((dt & 16) != 0) return "Fire";
if ((dt & 8) != 0) return "Cold";
if ((dt & 64) != 0) return "Lightning";
if ((dt & 32) != 0) return "Acid";
if ((dt & 4) != 0) return "Bludgeon";
if ((dt & 2) != 0) return "Pierce";
if ((dt & 1) != 0) return "Slash";
return null;
}
/// <summary>Resolves a USD object (id, name) to a carried item.</summary>
private WorldObject? Resolve(int id, string name)
{
var cache = _ctx.Inventory.Cache;
if (cache == null) return null;
if (ValidId(id))
{
var byId = cache[id];
if (byId != null) return byId;
}
if (string.IsNullOrWhiteSpace(name)) return null;
return _ctx.Inventory.Items().FirstOrDefault(w => w.Name.Equals(name.Trim(), StringComparison.OrdinalIgnoreCase));
}
private static string ConsumableType(string name)
{
string n = name.ToLowerInvariant();
if (n.Contains("essence")) return "Pet";
if (n.Contains("kit")) return "HealthKit";
if (n.Contains("mana stone") || n.Contains("mana charge")) return "ManaStone";
if (n.Contains("stamina")) return "Stamina";
if (n.Contains("lockpick")) return "Lockpick";
return "General";
}
// ── Preview / apply (pump thread) ───────────────────────────────────────
public void Preview(string path)
{
path = (path ?? string.Empty).Trim().Trim('"');
if (path.Length > 0 && !Path.IsPathRooted(path)) path = Path.Combine(VtProfileDir(), path);
if (!File.Exists(path)) { _status = "File not found: " + path; _plan = null; return; }
string[] lines;
try { lines = File.ReadAllLines(path); }
catch (Exception ex) { _status = "Read failed: " + ex.Message; _plan = null; return; }
var plan = new ImportPlan { Path = path };
foreach (var t in Parse(lines))
{
if (t.Name.Equals("MyMonsters", StringComparison.OrdinalIgnoreCase)) PlanMonsters(t, plan);
else if (WeaponTables.Contains(t.Name)) PlanWeapons(t, plan);
else if (t.Name.Equals("pets", StringComparison.OrdinalIgnoreCase)) PlanConsumables(t, plan, forceType: "Pet");
else if (ConsumableTables.Contains(t.Name)) PlanConsumables(t, plan, forceType: null);
}
_ctx.State.Gear.LastUsdPath = path;
_plan = plan;
_status = $"Preview: {plan.Monsters.Count} monsters, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables.";
}
private void PlanMonsters(UsdTable t, ImportPlan plan)
{
foreach (var row in t.Rows)
{
string name = t.Get(row, "MonsterName", "Name").Trim();
if (name.Length == 0) continue;
var rule = new MonsterRule
{
Name = name,
Priority = int.TryParse(t.Get(row, "AttackPriority", "Priority"), out int pri) ? Math.Max(0, pri) : 1,
DamageType = MapElement(t.Get(row, "DamageType")) ?? "Auto",
ExVuln = MapElement(t.Get(row, "SecondaryVuln", "ExtraVuln")) ?? "None",
PetDamage = MapElement(t.Get(row, "PetDamage")) ?? "PAuto",
UseRing = ParseBool(t.Get(row, "Ring")),
UseStreak = ParseBool(t.Get(row, "Streak")),
UseArc = ParseBool(t.Get(row, "Arc")),
Fester = ParseBool(t.Get(row, "Fester")),
Broadside = ParseBool(t.Get(row, "Broadside")),
GravityWell = ParseBool(t.Get(row, "GravityW", "GravityWell")),
Imperil = ParseBool(t.Get(row, "Imperil")),
Yield = ParseBool(t.Get(row, "Yield")),
Vuln = ParseBool(t.Get(row, "Vuln")),
};
var weapon = Resolve(ParseId(t.Get(row, "WeaponToUse", "Weapon")), t.Get(row, "WeaponName"));
if (weapon != null) rule.WeaponId = weapon.Id;
else if (t.Get(row, "WeaponName").Length > 0) plan.Notes.Add($"{name}: weapon '{t.Get(row, "WeaponName")}' not carried");
var off = Resolve(ParseId(t.Get(row, "SecondaryEquip", "Offhand")), t.Get(row, "OffhandName"));
if (off != null) rule.OffhandId = off.Id;
plan.Monsters.Add(rule);
}
}
private void PlanWeapons(UsdTable t, ImportPlan plan)
{
// The VT "shields" table (or any row whose item wields into the shield slot)
// becomes an off-hand Shield entry, never a main-hand weapon.
bool shieldTable = t.Name.Equals("shields", StringComparison.OrdinalIgnoreCase);
foreach (var row in t.Rows)
{
int id = ParseId(t.Get(row, "Object", "ObjectId", "Id"));
string name = t.Get(row, "Name").Trim();
var wo = Resolve(id, name);
if (wo == null) { if (name.Length > 0) plan.Notes.Add($"weapon '{name}' not carried"); continue; }
if (plan.Weapons.Any(w => w.Id == wo.Id)) continue;
bool isShield = shieldTable || RynthCore.Plugin.RynthAi.CombatManager.IsShieldItem(wo);
string element = BitsToElement(wo.Values(LongValueKey.DamageType, 0)) ?? "Slash";
plan.Weapons.Add(new ItemRule
{
Id = wo.Id,
Name = wo.Name,
Action = isShield ? ItemRule.ShieldAction : ItemRule.WeaponAction,
Element = element,
});
}
}
private void PlanConsumables(UsdTable t, ImportPlan plan, string? forceType)
{
foreach (var row in t.Rows)
{
int id = ParseId(t.Get(row, "Object", "ObjectId", "Id"));
string name = t.Get(row, "Name").Trim();
var wo = Resolve(id, name);
if (wo == null) { if (name.Length > 0) plan.Notes.Add($"item '{name}' not carried"); continue; }
if (wo.ObjectClass is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.WandStaffOrb) continue;
if (plan.Consumables.Any(c => c.Id == wo.Id)) continue;
plan.Consumables.Add(new ConsumableRule { Id = wo.Id, Name = wo.Name, Type = forceType ?? ConsumableType(wo.Name) });
}
}
/// <summary>Writes the previewed rules into the live settings and saves them.</summary>
public void Apply()
{
var plan = _plan;
var s = _ctx.Settings;
if (plan == null || s == null) { _status = "Nothing to apply."; return; }
foreach (var m in plan.Monsters)
{
s.MonsterRules.RemoveAll(r => r.Name.Equals(m.Name, StringComparison.OrdinalIgnoreCase));
s.MonsterRules.Add(m);
}
foreach (var w in plan.Weapons)
{
s.ItemRules.RemoveAll(r => r.Id == w.Id);
s.ItemRules.Add(w);
}
foreach (var c in plan.Consumables)
{
s.ConsumableRules.RemoveAll(r => r.Id == c.Id);
s.ConsumableRules.Add(c);
}
_ctx.SaveCombatSettings?.Invoke();
_status = $"Imported {plan.Monsters.Count} monsters, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables.";
_ctx.Chat("[ILT Hub] " + _status);
_plan = null;
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Import VirindiTank settings (.usd)");
ImGui.SetNextItemWidth(320);
ImGui.InputTextWithHint("##usdpath", @"full path or file name in C:\Games\VirindiPlugins\VirindiTank", ref _pathInput, 260u);
ImGui.SameLine();
string p = _pathInput;
if (ImGui.SmallButton("Preview")) _ctx.Post(() => Preview(p));
var plan = _plan;
if (plan != null)
{
ImGui.TextUnformatted($"{plan.Monsters.Count} monster rules, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables");
if (ImGui.TreeNode("Preview details"))
{
foreach (var m in plan.Monsters.Take(50)) ImGui.BulletText($"Monster {m.Name} [{m.DamageType}] pri {m.Priority}");
foreach (var w in plan.Weapons) ImGui.BulletText($"Weapon {w.Name} [{w.Element}]");
foreach (var c in plan.Consumables) ImGui.BulletText($"{c.Type}: {c.Name}");
foreach (var n in plan.Notes.Take(30)) ImGui.TextColored(LegacyDashboardRenderer.ColAmber, n);
ImGui.TreePop();
}
if (ImGui.Button("Apply import..."))
_ctx.Confirm("Import VTank settings",
$"Write these rules into the current RynthAi profile?\nRules with the same monster name / item id are replaced.",
Apply, "Import");
}
if (_status.Length > 0) ImGui.TextWrapped(_status);
}
}

View file

@ -0,0 +1,69 @@
// ImGuiNativeBinding.cs - Binds ImGui.NET's "cimgui" P/Invokes to the cimgui module the
// engine already loaded.
//
// The engine ships its own build as RynthCore.cimgui.dll. Without this resolver, Windows
// resolves "cimgui" to a separate cimgui.dll: a second ImGui instance whose windows (ILT Hub,
// Pets, Quests, Mini Remote, Item HUD) are built but never reach the engine's draw data.
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi;
internal static class ImGuiNativeBinding
{
private const string EngineModule = "RynthCore.cimgui.dll";
private const string LegacyModule = "cimgui.dll";
private static int _configured; // 1 once the resolver is registered (survives DLL-copy reuse)
private static int _resolvedLogged;
/// <summary>
/// Registers the resolver. Call before the first ImGui call (Initialize). The resolver can be
/// set only once per assembly, so later calls (a reused plugin DLL copy) are no-ops.
/// </summary>
public static void Ensure()
{
if (Interlocked.Exchange(ref _configured, 1) != 0) return;
try
{
NativeLibrary.SetDllImportResolver(typeof(ImGui).Assembly, Resolve);
RynthLog.Write(LogCat.UI, "[ImGui] native resolver registered (prefers the engine's " + EngineModule + ").");
}
catch (InvalidOperationException)
{
// Already registered by an earlier instance in this process.
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.UI, ex, "ImGuiNativeBinding.Ensure");
}
}
/// <summary>Runs on the first cimgui P/Invoke: the engine's module, else whatever cimgui.dll is loaded.</summary>
private static IntPtr Resolve(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
if (!string.Equals(libraryName, "cimgui", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(libraryName, LegacyModule, StringComparison.OrdinalIgnoreCase))
return IntPtr.Zero;
string bound = EngineModule;
IntPtr module = GetModuleHandleA(EngineModule);
if (module == IntPtr.Zero)
{
bound = LegacyModule;
module = GetModuleHandleA(LegacyModule);
}
if (Interlocked.Exchange(ref _resolvedLogged, 1) == 0)
RynthLog.Write(LogCat.UI, module != IntPtr.Zero
? $"[ImGui] cimgui bound to loaded {bound} (0x{module.ToInt64():X})."
: "[ImGui] no loaded cimgui module found; falling back to the default DLL search.");
return module; // IntPtr.Zero = default resolution
}
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr GetModuleHandleA(string lpModuleName);
}

View file

@ -0,0 +1,673 @@
// MagItemDescriber.cs — one-line "Mag-style" item info (Mag-Tools ItemInfo / UtilityBelt ub-IT ItemInfo).
//
// Gold Ornate Long Sword (Slash Sword), Noble Relic Set, CS, Undead Slayer, Tinks 4,
// Applied: Steel x2, 152.48-236, 0.35v, +18%a, 12%md, Legendary Blood Thirst, Wield Lvl 180,
// Heavy Weapons 375, Diff 270, Craft 8, [D 3, CD 2]
//
// The same fields can also print as the pet-roster layout (IltPetStats: identity line, stats
// line, ratings/requirements line), plus a spells line:
//
// Gold Ornate Long Sword (Slash Sword), Noble Relic Set, Tinks 4, Applied: Steel x2, Craft 8
// CS, Undead Slayer, 152.48-236, 0.35v, 18%a, 12%md
// [D 3, CD 2] Wield Lvl 180, Heavy Weapons 375, Diff 270
// Spells: Legendary Blood Thirst
//
// Field order and per-class gating follow ub-IT (Tools/ItemInfo.cs ItemDescriptions.ToString,
// Lib/ItemDescribeMagShorthand.cs, Lib/ItemInfoHelper/ItemIdentifyFieldSet.cs); labels and the
// spell filter follow Mag-Tools. All ids are raw ACE properties (RynthCore reads CBaseQualities by
// STypeInt/STypeFloat/STypeString id — not Decal's remapped LongValueKey/DoubleValueKey numbers).
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using RynthCore.Loot;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
/// <summary>Property reads for one item. Implemented over the live object cache (see
/// <see cref="CacheItemPropertySource"/>); a missing property returns false / empty.</summary>
internal interface IItemPropertySource
{
string Name { get; }
AcObjectClass ObjectClass { get; }
bool TryGetInt(uint stype, out int value);
bool TryGetDouble(uint stype, out double value);
string GetString(uint stype);
/// <summary>Spell ids on the item (inscribed + cantrips), unsorted.</summary>
IReadOnlyList<int> SpellIds { get; }
}
/// <summary>Per-call output options, snapshotted from <see cref="MagItemInfoSettings"/>.</summary>
internal readonly record struct MagItemInfoOptions(
MagItemInfoField Hidden, int HiddenRatings, bool ShowValueAndBurden, bool AllSpells, int MaxListedSpells)
{
/// <summary>Everything shown, Mag spell filter — used when no settings are loaded yet.</summary>
public static readonly MagItemInfoOptions Default = new(MagItemInfoField.None, 0, false, false, 26);
public static MagItemInfoOptions From(MagItemInfoSettings? s) => s == null
? Default
: new((MagItemInfoField)s.HiddenFields, s.HiddenRatings, s.ShowValueAndBurden,
s.SpellMode == MagItemInfoSettings.SpellModeAll, s.MaxListedSpells);
public bool Shows(MagItemInfoField f) => (Hidden & f) == 0;
}
/// <summary>Which pet-style line a field lands on (<see cref="MagItemDescription.ToPetLines"/>).</summary>
internal enum MagItemSection
{
/// <summary>Line 1 after the name: set, AL, tinks, applied, craft, keyring.</summary>
Identity,
/// <summary>Line 2: imbues, slayer, damage, attack/defense/mana-conversion, protections.</summary>
Combat,
/// <summary>Line 3 lead: the "[D 3, CD 2]" cluster.</summary>
Ratings,
/// <summary>Line 3 tail: wield / activation / difficulty, value and burden.</summary>
Requirements,
/// <summary>Line 4: spell names.</summary>
Spells,
}
/// <summary>
/// One described item: the title plus fields tagged with their section, kept in Mag print order
/// so <see cref="ToOneLine"/> reproduces the classic line exactly.
/// </summary>
internal sealed class MagItemDescription
{
/// <summary>"[Material ]Name[ (DamageType Mastery)]".</summary>
public string Title = string.Empty;
public readonly List<(MagItemSection Section, string Text)> Segments = new();
public void Add(MagItemSection section, string text)
{
if (!string.IsNullOrEmpty(text)) Segments.Add((section, text));
}
/// <summary>Classic Mag one-liner: title, then every field comma-separated.</summary>
public string ToOneLine()
{
var sb = new StringBuilder(Title, 256);
foreach (var (_, text) in Segments) sb.Append(", ").Append(text);
return sb.ToString();
}
/// <summary>
/// Pet-roster layout: line 1 is always present; empty stat / requirement / spell lines are
/// dropped so plain armor stays short.
/// </summary>
public List<string> ToPetLines()
{
var lines = new List<string>(4);
var identity = new StringBuilder(Title);
foreach (string t in Section(MagItemSection.Identity)) identity.Append(", ").Append(t);
lines.Add(identity.ToString());
string combat = string.Join(", ", Section(MagItemSection.Combat));
if (combat.Length > 0) lines.Add(combat);
// Like the pet roster's third line: ratings first, then the rest two-space separated.
var tail = new List<string>(2);
string ratings = string.Join(", ", Section(MagItemSection.Ratings));
if (ratings.Length > 0) tail.Add(ratings);
string reqs = string.Join(", ", Section(MagItemSection.Requirements));
if (reqs.Length > 0) tail.Add(reqs);
if (tail.Count > 0) lines.Add(string.Join(" ", tail));
var spells = Section(MagItemSection.Spells);
if (spells.Count > 0)
{
// The verbose list is a single pre-labelled "Spells: a; b" segment.
lines.Add(spells.Count == 1 && spells[0].StartsWith("Spells:", StringComparison.Ordinal)
? spells[0]
: "Spells: " + string.Join(", ", spells));
}
return lines;
}
private List<string> Section(MagItemSection section)
{
var list = new List<string>();
foreach (var (s, text) in Segments)
if (s == section) list.Add(text);
return list;
}
}
/// <summary>Builds the Mag-style item info line.</summary>
internal static class MagItemDescriber
{
// ── ACE PropertyInt ids ──────────────────────────────────────────────────
private const uint IntBurden = 5; // EncumbranceVal
private const uint IntValue = 19;
private const uint IntArmorLevel = 28;
private const uint IntResistMagic = 36; // >= 9999 = unenchantable
private const uint IntMaxDamage = 44; // Damage
private const uint IntDamageType = 45;
private const uint IntAttackType = 47;
private const uint IntStructure = 92; // keyring uses remaining
private const uint IntWorkmanship = 105;
private const uint IntItemDifficulty = 109; // arcane lore requirement ("Diff")
private const uint IntActivationLevel = 115; // ItemSkillLevelLimit
private const uint IntMaterial = 131;
private const uint IntWieldReq = 158;
private const uint IntWieldSkill = 159;
private const uint IntWieldValue = 160;
private const uint IntSlayerCreature = 166;
private const uint IntNumItemsInMaterial = 170; // salvage: workmanship = 105 / 170
private const uint IntTinks = 171;
private const uint IntActivationSkill = 176; // AppraisalItemSkill
private const uint IntImbued = 179; // ImbuedEffect (+ 303..306 for 2..5)
private const uint IntNumKeys = 193;
private const uint IntElementalBonus = 204;
private const uint IntEquipmentSet = 265;
private const uint IntWieldReq2 = 270;
private const uint IntWieldSkill2 = 271;
private const uint IntWieldValue2 = 272;
private const uint IntWeaponType = 353; // mastery
private const uint IntUseRequiresSkill = 366;
private const uint IntUseRequiresSkillLvl = 367;
private const uint IntUseRequiresSpec = 368;
private const uint IntUseRequiresLevel = 369;
private const uint IntSplitArrows = 9031; // ACECustom SplitArrowCount
// ── ACE PropertyFloat ids ────────────────────────────────────────────────
private const uint FloatArmorVsSlash = 13; // 13..19 = Slash/Pierce/Bludgeon/Cold/Fire/Acid/Electric
private const uint FloatVariance = 22;
private const uint FloatMaxVelocity = 26;
private const uint FloatMeleeDefense = 29; // WeaponDefense
private const uint FloatAttack = 62; // WeaponOffense
private const uint FloatDamageMod = 63;
private const uint FloatCritMultiplier = 136;
private const uint FloatManaConversion = 144;
private const uint FloatCritFrequency = 147;
private const uint FloatMissileDefense = 149;
private const uint FloatMagicDefense = 150;
private const uint FloatVsMonsters = 152; // ElementalDamageMod
private const uint FloatIgnoreArmor = 155; // armor cleaving
// ── ACE PropertyString ids ───────────────────────────────────────────────
private const uint StringTinkerLog = 9007; // ACECustom: CSV of applied material ids
/// <summary>Gear ratings are small (1..~50). Anything above is a wrong key leaking through.</summary>
private const int MaxPlausibleRating = 200;
/// <summary>Class-specific fields (ub-IT ItemIdentifyFieldSet). Generic fields print for every class.</summary>
[Flags]
private enum Field
{
None = 0,
DamageType = 1 << 0,
CritStats = 1 << 1,
Splits = 1 << 2,
Cleaves = 1 << 3,
Slayer = 1 << 4,
Range = 1 << 5,
Damage = 1 << 6,
AttackBonus = 1 << 7,
MeleeDefense = 1 << 8,
MissileDefense = 1 << 9,
MagicDefense = 1 << 10,
ManaConversion = 1 << 11,
ArmorCleave = 1 << 12,
WeaponDefenses = MeleeDefense | MissileDefense | MagicDefense,
}
private static Field FieldsFor(AcObjectClass cls) => cls switch
{
AcObjectClass.MissileWeapon => Field.DamageType | Field.CritStats | Field.Splits | Field.Cleaves
| Field.Slayer | Field.Range | Field.Damage | Field.WeaponDefenses
| Field.ArmorCleave,
AcObjectClass.MeleeWeapon => Field.DamageType | Field.CritStats | Field.Cleaves | Field.Slayer
| Field.Damage | Field.AttackBonus | Field.WeaponDefenses
| Field.ArmorCleave,
AcObjectClass.WandStaffOrb => Field.DamageType | Field.CritStats | Field.Slayer | Field.Damage
| Field.WeaponDefenses | Field.ManaConversion,
AcObjectClass.Jewelry => Field.None,
// Armor / clothing / misc: keep Mag's generic bonus lines (shields roll %md etc.).
_ => Field.AttackBonus | Field.WeaponDefenses | Field.ManaConversion,
};
/// <summary>Full Mag-style line for one item (name first, comma-separated fields).</summary>
public static string Describe(IItemPropertySource item, MagItemInfoOptions options)
=> Build(item, options).ToOneLine();
/// <summary>Reads every enabled field once, tagged by section (one-line or pet-style output).</summary>
public static MagItemDescription Build(IItemPropertySource item, MagItemInfoOptions options)
{
var d = new MagItemDescription();
var sb = new StringBuilder(128); // title only
AcObjectClass cls = item.ObjectClass;
Field fields = FieldsFor(cls);
bool Has(Field f) => (fields & f) == f;
bool Show(MagItemInfoField f) => options.Shows(f);
int Int(uint id) => item.TryGetInt(id, out int v) ? v : 0;
double Dbl(uint id, double fallback) => item.TryGetDouble(id, out double v) ? v : fallback;
// ── Name: "[Material ]Name (DamageType Mastery)" ────────────────────────
int material = Int(IntMaterial);
if (material > 0 && Show(MagItemInfoField.Material))
{
string matName = MagItemInfoTables.Materials.TryGetValue(material, out string? m) ? m : $"material {material}";
// Loot names usually omit the material; don't double it when the name already starts with it.
if (!item.Name.StartsWith(matName, StringComparison.OrdinalIgnoreCase))
sb.Append(matName).Append(' ');
}
sb.Append(item.Name);
if (Has(Field.DamageType) && Show(MagItemInfoField.TypeMastery))
{
string dmgType = MagItemInfoTables.DamageTypeName(Int(IntDamageType));
int mastery = Int(IntWeaponType);
string masteryName = mastery > 0
? (MagItemInfoTables.Masteries.TryGetValue(mastery, out string? mn) ? mn : $"Unknown mastery {mastery}")
: string.Empty;
string inner = $"{dmgType} {masteryName}".Trim();
if (inner.Length > 0) sb.Append(" (").Append(inner).Append(')');
}
d.Title = sb.ToString();
const MagItemSection Id = MagItemSection.Identity, Cbt = MagItemSection.Combat, Req = MagItemSection.Requirements;
string I(int v) => v.ToString(CultureInfo.InvariantCulture);
// ── Set ─────────────────────────────────────────────────────────────────
int set = Int(IntEquipmentSet);
if (set > 0 && Show(MagItemInfoField.Set))
d.Add(Id, MagItemInfoTables.EquipmentSets.TryGetValue(set, out string? setName) ? setName : $"Unknown set {set}");
// ── Armor level ─────────────────────────────────────────────────────────
int al = Int(IntArmorLevel);
if (al > 0 && Show(MagItemInfoField.ArmorLevel)) d.Add(Id, "AL " + I(al));
// ── Imbues (ImbuedEffect 179 plus ImbuedEffect2..5 = 303..306) ─────────
if (Show(MagItemInfoField.Imbues))
d.Add(Cbt, ImbueLabels(Int(IntImbued) | Int(303) | Int(304) | Int(305) | Int(306)));
if (Has(Field.ArmorCleave) && Show(MagItemInfoField.ArmorCleave) && Dbl(FloatIgnoreArmor, 0) != 0)
d.Add(Cbt, "AC");
if (Has(Field.CritStats) && Show(MagItemInfoField.CritStats))
{
double critMult = Dbl(FloatCritMultiplier, 0);
if (critMult > 0) d.Add(Cbt, $"CritMult ({Fmt(critMult)})");
double critFreq = Dbl(FloatCritFrequency, 0);
if (critFreq > 0) d.Add(Cbt, $"CritFreq ({Fmt(critFreq)})");
}
if (Has(Field.Splits) && Show(MagItemInfoField.Splits))
{
int splits = Int(IntSplitArrows);
if (splits > 0) d.Add(Cbt, $"Splits ({I(splits)})");
}
if (Has(Field.Range) && Show(MagItemInfoField.Range))
{
int yards = MissileRangeYards(Dbl(FloatMaxVelocity, 0));
if (yards > 0) d.Add(Cbt, $"Range {I(yards)}yd");
}
if (Has(Field.Cleaves) && Show(MagItemInfoField.CleaveMultiStrike))
{
int attackType = Int(IntAttackType);
int mastery = Int(IntWeaponType);
bool cleaving = (attackType == 4 && mastery == 11) || (attackType == 1 && mastery != 11 && mastery != 0);
if (cleaving) d.Add(Cbt, "Cleaving");
else if (attackType is 160 or 166) d.Add(Cbt, "Multi-Strike");
else if (attackType == 486) d.Add(Cbt, "Multi-Strike (3)");
}
// ── Slayer ──────────────────────────────────────────────────────────────
if (Has(Field.Slayer) && Show(MagItemInfoField.Slayer))
{
string? slayer = MagItemInfoTables.CreatureTypeName(Int(IntSlayerCreature));
if (slayer != null) d.Add(Cbt, slayer + " Slayer");
}
// ── Tinks + applied materials (TinkerLog) ──────────────────────────────
int tinks = Int(IntTinks);
if (tinks > 0 && Show(MagItemInfoField.Tinks)) d.Add(Id, "Tinks " + I(tinks));
if (Show(MagItemInfoField.Applied))
{
string applied = FormatTinkerLog(item.GetString(StringTinkerLog));
if (applied.Length > 0) d.Add(Id, "Applied: " + applied);
}
// ── Damage ──────────────────────────────────────────────────────────────
if (Has(Field.Damage) && Show(MagItemInfoField.Damage))
AddDamage(d, cls, Int(IntMaxDamage), Dbl(FloatVariance, 0), Int(IntElementalBonus),
Dbl(FloatDamageMod, 1), Dbl(FloatVsMonsters, 1));
// ── Attack / defense / mana conversion percents ───────────────────────
bool defenses = Show(MagItemInfoField.Defenses);
if (Has(Field.AttackBonus) && Show(MagItemInfoField.Attack)) AddPercent(d, Dbl(FloatAttack, 1), "%a", 0);
if (Has(Field.MeleeDefense) && defenses) AddPercent(d, Dbl(FloatMeleeDefense, 1), "%md", 0);
if (Has(Field.MagicDefense) && defenses) AddPercent(d, Dbl(FloatMagicDefense, 1), "%mgc.d", 1);
if (Has(Field.MissileDefense) && defenses) AddPercent(d, Dbl(FloatMissileDefense, 1), "%msl.d", 1);
if (Has(Field.ManaConversion) && Show(MagItemInfoField.ManaConversion))
{
double mc = Dbl(FloatManaConversion, 0);
if (mc != 0) d.Add(Cbt, Math.Round(mc * 100).ToString(CultureInfo.InvariantCulture) + "%mc");
}
// ── Spells ──────────────────────────────────────────────────────────────
bool unenchantable = Int(IntResistMagic) >= 9999;
if (Show(MagItemInfoField.Spells))
AddSpells(d, item.SpellIds, unenchantable, options.AllSpells, options.MaxListedSpells);
// ── Requirements ────────────────────────────────────────────────────────
if (Show(MagItemInfoField.Wield))
{
AddWieldRequirement(d, Int(IntWieldReq), Int(IntWieldSkill), Int(IntWieldValue));
AddWieldRequirement(d, Int(IntWieldReq2), Int(IntWieldSkill2), Int(IntWieldValue2));
}
if (Show(MagItemInfoField.Activation))
{
int useLevel = Int(IntUseRequiresLevel);
if (useLevel > 0) d.Add(Req, "Lvl " + I(useLevel));
// "Melee Defense 300 to Activate" — hidden when the wield requirement already covers it.
int actSkill = Int(IntActivationSkill), actLevel = Int(IntActivationLevel);
if (actLevel > 0 && (Int(IntWieldSkill) != actSkill || Int(IntWieldValue) < actLevel))
d.Add(Req, $"{SkillName(actSkill)} {I(actLevel)} to Activate");
// Summoning essences / gems.
int useSkill = Int(IntUseRequiresSkill), useSkillLvl = Int(IntUseRequiresSkillLvl), useSpec = Int(IntUseRequiresSpec);
if (useSkill > 0 && useSkillLvl > 0) d.Add(Req, $"{SkillName(useSkill)} {I(useSkillLvl)}");
if (useSpec > 0 && useSkillLvl > 0) d.Add(Req, $"Spec {SkillName(useSpec)} {I(useSkillLvl)}");
}
int diff = Int(IntItemDifficulty);
if (diff > 0 && Show(MagItemInfoField.Difficulty)) d.Add(Req, "Diff " + I(diff));
// ── Workmanship ─────────────────────────────────────────────────────────
int work = Show(MagItemInfoField.Craft) ? Int(IntWorkmanship) : 0;
if (cls == AcObjectClass.Salvage)
{
int items = Int(IntNumItemsInMaterial);
if (work > 0)
{
double avg = items > 0 ? (double)work / items : work;
d.Add(Id, "Work " + avg.ToString("N2", CultureInfo.InvariantCulture));
}
}
else if (work > 0 && tinks != 10) // Mag: hide craft once fully tinked
{
d.Add(Id, "Craft " + I(work));
}
// ── Unenchantable armor: base protections [S/P/B/C/F/A/L] ─────────────
if (cls == AcObjectClass.Armor && unenchantable && Show(MagItemInfoField.Protections))
{
var prot = new StringBuilder("[");
for (uint i = 0; i < 7; i++)
{
if (i > 0) prot.Append('/');
prot.Append(Dbl(FloatArmorVsSlash + i, 0).ToString("N1", CultureInfo.InvariantCulture));
}
d.Add(Cbt, prot.Append(']').ToString());
}
if (options.ShowValueAndBurden)
{
int value = Int(IntValue);
if (value > 0) d.Add(Req, "Value " + value.ToString("N0", CultureInfo.InvariantCulture));
int burden = Int(IntBurden);
if (burden > 0) d.Add(Req, "BU " + I(burden));
}
// ── Ratings ─────────────────────────────────────────────────────────────
if (Show(MagItemInfoField.Ratings))
d.Add(MagItemSection.Ratings, RatingsCluster(item, options.HiddenRatings));
if (cls == AcObjectClass.Misc && Show(MagItemInfoField.Keyring)
&& item.Name.Contains("Keyring", StringComparison.OrdinalIgnoreCase))
{
d.Add(Id, "Keys: " + I(Int(IntNumKeys)));
d.Add(Id, "Uses: " + I(Int(IntStructure)));
}
return d;
}
/// <summary>Mag imbue labels ("CS AR"), plus the ACE flags Mag predates (missile imbue, nether
/// rend); empty when no known bit is set.</summary>
private static string ImbueLabels(int mask)
{
if (mask == 0) return string.Empty;
var sb = new StringBuilder();
void Flag(int bit, string label)
{
if ((mask & bit) == 0) return;
if (sb.Length > 0) sb.Append(' ');
sb.Append(label);
}
Flag(0x0001, "CS");
Flag(0x0002, "CB");
Flag(0x0004, "AR");
Flag(0x0008, "SlashRend");
Flag(0x0010, "PierceRend");
Flag(0x0020, "BludgeRend");
Flag(0x0040, "AcidRend");
Flag(0x0080, "FrostRend");
Flag(0x0100, "LightRend");
Flag(0x0200, "FireRend");
Flag(0x4000, "NetherRend");
Flag(0x0400, "MeleeImbue");
Flag(0x0800, "MissileImbue");
Flag(0x1000, "MagicImbue");
Flag(0x2000, "Hematited");
Flag(0x20000000, "MagicAbsorb");
return sb.ToString(); // only unknown bits → empty → field skipped
}
/// <summary>Melee "min-max", variance, "+elem", "+mod%", wand "+N% vs. Monsters" (combat line).</summary>
private static void AddDamage(MagItemDescription d, AcObjectClass cls, int maxDmg, double variance,
int elemBonus, double dmgMod, double vsMonsters)
{
const MagItemSection Cbt = MagItemSection.Combat;
if (cls != AcObjectClass.MissileWeapon && maxDmg > 0)
{
string max = maxDmg.ToString(CultureInfo.InvariantCulture);
d.Add(Cbt, variance > 0
? (maxDmg - maxDmg * variance).ToString("N2", CultureInfo.InvariantCulture) + "-" + max
: max);
}
if (variance > 0)
d.Add(Cbt, Math.Round(variance, 2).ToString(CultureInfo.InvariantCulture) + "v");
if (elemBonus != 0)
d.Add(Cbt, "+" + elemBonus.ToString(CultureInfo.InvariantCulture));
// A missing/zero multiplier means "no bonus" (0 would print as -100%).
if (dmgMod > 0 && dmgMod != 1)
d.Add(Cbt, "+" + Math.Round((dmgMod - 1) * 100).ToString(CultureInfo.InvariantCulture) + "%");
if (vsMonsters > 0 && vsMonsters != 1)
d.Add(Cbt, "+" + Math.Round((vsMonsters - 1) * 100).ToString(CultureInfo.InvariantCulture) + "% vs. Monsters");
}
/// <summary>Mag "18%a" from a 1.0-based multiplier; skips missing (≤0) and neutral 1.0.</summary>
private static void AddPercent(MagItemDescription d, double multiplier, string suffix, int decimals)
{
if (multiplier <= 0 || multiplier == 1) return;
double pct = Math.Round((multiplier - 1) * 100, decimals);
d.Add(MagItemSection.Combat, pct.ToString(CultureInfo.InvariantCulture) + suffix);
}
/// <summary>"Wield Lvl 180" for a level requirement, else "Heavy Weapons 375".</summary>
private static void AddWieldRequirement(MagItemDescription d, int reqType, int skillOrAttr, int value)
{
if (value <= 0) return;
string v = value.ToString(CultureInfo.InvariantCulture);
d.Add(MagItemSection.Requirements, reqType == 7 // WieldRequirement.Level
? "Wield Lvl " + v
: SkillName(skillOrAttr) + " " + v);
}
private static string SkillName(int skill) =>
MagItemInfoTables.Skills.TryGetValue(skill, out string? name) ? name : $"Skill {skill}";
/// <summary>
/// Mag-Tools spell filter (ub-IT applies it to every item): keep cantrip Impen, Augmented
/// (trinket) spells, banes/Impen only on unenchantable gear, level 7+ weapon auras, and
/// named high-tier spells (cantrips); drop I–VI, level-7 lore buffs and Incantations.
/// Verbose lists every spell (capped) for troubleshooting.
/// </summary>
private static void AddSpells(MagItemDescription d, IReadOnlyList<int> spellIds, bool unenchantable,
bool verbose, int maxVerbose)
{
if (spellIds.Count == 0) return;
var ids = new List<int>(spellIds);
ids.Sort();
ids.Reverse(); // Mag lists highest spell id first
var seen = new HashSet<int>();
var verboseList = verbose ? new StringBuilder() : null;
int shown = 0, skippedVerbose = 0;
foreach (int id in ids)
{
if (!seen.Add(id)) continue;
bool known = SpellDatabase.HasSpell(id);
if (verboseList != null)
{
// Verbose is the troubleshooting view: list ids SpellData.txt doesn't know too.
if (shown >= maxVerbose) { skippedVerbose++; continue; }
verboseList.Append(shown == 0 ? "Spells: " : "; ")
.Append(known ? SpellDatabase.GetSpellName(id) : $"Spell {id}");
shown++;
continue;
}
if (!known) continue;
string name = SpellDatabase.GetSpellName(id);
SpellDatabase.TryGetSpellMeta(id, out int family, out int difficulty);
if (ShouldShowSpell(name, family, difficulty, unenchantable))
d.Add(MagItemSection.Spells, name);
}
if (verboseList == null || verboseList.Length == 0) return;
if (skippedVerbose > 0) verboseList.Append("; (+").Append(skippedVerbose).Append(" more spells)");
d.Add(MagItemSection.Spells, verboseList.ToString());
}
private static bool ShouldShowSpell(string name, int family, int difficulty, bool unenchantable)
{
if (name.Contains("Minor Impenetrability") || name.Contains("Major Impenetrability")
|| name.Contains("Epic Impenetrability") || name.Contains("Legendary Impenetrability"))
return true;
if (name.Contains("Augmented"))
return true;
// Banes / Impen / Brogard's: only meaningful on unenchantable gear (loot armor
// already reflects them in AL and protections).
bool baneLike = name.Contains(" Bane") || name.Contains("Impen") || name.StartsWith("Brogard", StringComparison.Ordinal);
if (baneLike) return unenchantable;
// Weapon auras (Elysa's Sight .. Swift Killer, Hermetic Link, Vision of the Hunter):
// level 7 (300) and 8+ (400+) only.
if ((family >= 152 && family <= 158) || family == 195 || family == 325)
return difficulty == 300 || difficulty >= 400;
if (name.EndsWith(" I") || name.EndsWith(" II") || name.EndsWith(" III")
|| name.EndsWith(" IV") || name.EndsWith(" V") || name.EndsWith(" VI"))
return false;
if (difficulty == 300) return false; // level-7 lore buffs (Might of the Lugians …)
if (name.Contains("Incantation")) return false;
return true; // cantrips: Legendary Strength, Epic Defender …
}
/// <summary>Rating cluster "[D 11, C 8, CD 4]" from ACE Gear* ratings 370–389
/// (<see cref="MagItemInfoCatalog.Ratings"/>); bit i of <paramref name="hiddenMask"/> skips rating i.</summary>
private static string RatingsCluster(IItemPropertySource item, int hiddenMask)
{
var sb = new StringBuilder();
var ratings = MagItemInfoCatalog.Ratings;
for (int i = 0; i < ratings.Length; i++)
{
if ((hiddenMask & (1 << i)) != 0) continue;
if (!item.TryGetInt(ratings[i].StatId, out int v) || v <= 0 || v > MaxPlausibleRating) continue;
sb.Append(sb.Length == 0 ? "[" : ", ").Append(ratings[i].Tag).Append(' ')
.Append(v.ToString(CultureInfo.InvariantCulture));
}
return sb.Length > 0 ? sb.Append(']').ToString() : string.Empty;
}
/// <summary>ACECustom TinkerLog CSV ("64,64,46") → "Steel x2, White Quartz".</summary>
private static string FormatTinkerLog(string csv)
{
if (string.IsNullOrWhiteSpace(csv)) return string.Empty;
var order = new List<int>();
var counts = new Dictionary<int, int>();
foreach (string raw in csv.Split(','))
{
if (!int.TryParse(raw.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int id) || id <= 0)
continue;
if (counts.TryGetValue(id, out int c)) counts[id] = c + 1;
else { counts[id] = 1; order.Add(id); }
}
var sb = new StringBuilder();
foreach (int id in order)
{
if (sb.Length > 0) sb.Append(", ");
sb.Append(MagItemInfoTables.Materials.TryGetValue(id, out string? name) ? name : $"material {id}");
if (counts[id] > 1) sb.Append(" x").Append(counts[id]);
}
return sb.ToString();
}
/// <summary>Max ballistic range (45° arc, v²/g) in yards; 0 when velocity is missing.</summary>
private static int MissileRangeYards(double velocity)
{
if (double.IsNaN(velocity) || velocity <= 0) return 0;
double meters = velocity * velocity / 9.8;
return (int)Math.Round(meters * 1.0936133);
}
private static string Fmt(double v) => Math.Round(v, 2).ToString(CultureInfo.InvariantCulture);
}
/// <summary><see cref="IItemPropertySource"/> over the live client object (RynthCore host reads).</summary>
internal sealed class CacheItemPropertySource : IItemPropertySource
{
private readonly RynthCore.PluginSdk.RynthCoreHost _host;
private readonly uint _id;
private IReadOnlyList<int>? _spells;
public CacheItemPropertySource(RynthCore.PluginSdk.RynthCoreHost host, WorldObject wo)
{
_host = host;
_id = unchecked((uint)wo.Id);
Name = wo.Name;
ObjectClass = wo.ObjectClass;
}
public string Name { get; }
public AcObjectClass ObjectClass { get; }
public bool TryGetInt(uint stype, out int value)
{
value = 0;
return _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(_id, stype, out value);
}
public bool TryGetDouble(uint stype, out double value)
{
value = 0;
return _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(_id, stype, out value);
}
public string GetString(uint stype) =>
_host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(_id, stype, out string? v) && v != null
? v
: string.Empty;
public IReadOnlyList<int> SpellIds => _spells ??= ReadSpells();
private IReadOnlyList<int> ReadSpells()
{
if (!_host.HasGetObjectSpellIds) return Array.Empty<int>();
uint[] buf = new uint[128];
int n = _host.GetObjectSpellIds(_id, buf, buf.Length);
if (n <= 0) return Array.Empty<int>();
int take = Math.Min(n, buf.Length);
var list = new List<int>(take);
for (int i = 0; i < take; i++) list.Add(unchecked((int)buf[i]));
return list;
}
}

View file

@ -0,0 +1,251 @@
// MagItemInfoSettings.cs — user options for the Mag-style item info line (/ra iteminfo).
//
// Stored per character inside LegacyUiSettings.ItemInfoSettings. Field visibility is kept as a
// *hidden* bitmask so any field added in a later release shows by default for existing profiles.
using System;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
/// <summary>Toggleable sections of the item info line (bit set in HiddenFields = not printed).</summary>
[Flags]
public enum MagItemInfoField
{
None = 0,
Material = 1 << 0,
TypeMastery = 1 << 1,
Set = 1 << 2,
ArmorLevel = 1 << 3,
Imbues = 1 << 4,
ArmorCleave = 1 << 5,
CritStats = 1 << 6,
Splits = 1 << 7,
Range = 1 << 8,
CleaveMultiStrike = 1 << 9,
Slayer = 1 << 10,
Tinks = 1 << 11,
Applied = 1 << 12,
Damage = 1 << 13,
Attack = 1 << 14,
Defenses = 1 << 15,
ManaConversion = 1 << 16,
Spells = 1 << 17,
Wield = 1 << 18,
Activation = 1 << 19,
Difficulty = 1 << 20,
Craft = 1 << 21,
Protections = 1 << 22,
Ratings = 1 << 23,
Keyring = 1 << 24,
}
/// <summary>Persisted item-info options (JSON fields; see RynthAiJsonContext IncludeFields).</summary>
public sealed class MagItemInfoSettings
{
/// <summary>Spell list modes for <see cref="SpellMode"/>.</summary>
public const int SpellModeMag = 0, SpellModeAll = 1;
/// <summary>Mouse triggers for <see cref="ClickTrigger"/>.</summary>
public const int ClickOff = 0, ClickLeft = 1, ClickRight = 2;
/// <summary>Output layouts for <see cref="Layout"/>.</summary>
public const int LayoutOneLine = 0, LayoutPetLines = 1;
/// <summary><see cref="DetailChatType"/> value meaning "use <see cref="ChatType"/>".</summary>
public const int SameAsHeader = -1;
// ── When to print ────────────────────────────────────────────────────────
/// <summary>Print automatically when an item is selected.</summary>
public bool OnSelect;
/// <summary>
/// Print the selected item after a left (<see cref="ClickLeft"/>) or right (<see cref="ClickRight"/>)
/// click in the game world / inventory — also re-prints an item that was already selected.
/// </summary>
public int ClickTrigger = ClickOff;
/// <summary>On-select class filters (manual /ra iteminfo ignores them).</summary>
public bool OnSelectWeapons = true;
public bool OnSelectArmor = true;
public bool OnSelectJewelry = true;
public bool OnSelectOther = true;
/// <summary>Seconds to wait for an ID before printing partial data.</summary>
public float IdTimeoutSec = 3f;
// ── What to print ────────────────────────────────────────────────────────
/// <summary><see cref="MagItemInfoField"/> bits that are NOT printed.</summary>
public int HiddenFields;
/// <summary>Bit i set = <see cref="MagItemInfoCatalog.Ratings"/>[i] not printed.</summary>
public int HiddenRatings;
/// <summary>Append ", Value N, BU N".</summary>
public bool ShowValueAndBurden;
/// <summary><see cref="SpellModeMag"/> (Mag filter) or <see cref="SpellModeAll"/>.</summary>
public int SpellMode = SpellModeMag;
/// <summary>Cap for the "all spells" list.</summary>
public int MaxListedSpells = 26;
// ── How to print ─────────────────────────────────────────────────────────
/// <summary><see cref="LayoutPetLines"/> (pet-roster style lines) or <see cref="LayoutOneLine"/> (Mag one-liner).</summary>
public int Layout = LayoutPetLines;
/// <summary>AC chat type passed to WriteToChat (selects the chat colour / window).</summary>
public int ChatType = 1;
/// <summary>Chat type for pet-style lines 2+, or <see cref="SameAsHeader"/>.</summary>
public int DetailChatType = SameAsHeader;
/// <summary>Text put in front of every line.</summary>
public string Prefix = "[RynthAi] ";
/// <summary>Item Info settings window open.</summary>
public bool ShowWindow;
public bool IsHidden(MagItemInfoField f) => (HiddenFields & (int)f) != 0;
public void SetHidden(MagItemInfoField f, bool hidden) =>
HiddenFields = hidden ? HiddenFields | (int)f : HiddenFields & ~(int)f;
public bool IsRatingHidden(int index) => (HiddenRatings & (1 << index)) != 0;
public void SetRatingHidden(int index, bool hidden) =>
HiddenRatings = hidden ? HiddenRatings | (1 << index) : HiddenRatings & ~(1 << index);
/// <summary>Clamp values a hand-edited or older profile could carry out of range.</summary>
public void Sanitize()
{
if (float.IsNaN(IdTimeoutSec) || IdTimeoutSec < 0.5f) IdTimeoutSec = 0.5f;
if (IdTimeoutSec > 15f) IdTimeoutSec = 15f;
if (SpellMode is not (SpellModeMag or SpellModeAll)) SpellMode = SpellModeMag;
MaxListedSpells = Math.Clamp(MaxListedSpells, 1, 64);
if (ChatType < 0 || ChatType > 31) ChatType = 1;
if (DetailChatType < SameAsHeader || DetailChatType > 31) DetailChatType = SameAsHeader;
if (ClickTrigger is not (ClickOff or ClickLeft or ClickRight)) ClickTrigger = ClickOff;
if (Layout is not (LayoutOneLine or LayoutPetLines)) Layout = LayoutPetLines;
Prefix ??= string.Empty;
if (Prefix.Length > 32) Prefix = Prefix[..32];
}
/// <summary>Back to first-run defaults (window stays open).</summary>
public void ResetToDefaults()
{
var d = new MagItemInfoSettings();
OnSelect = d.OnSelect;
ClickTrigger = d.ClickTrigger;
Layout = d.Layout;
DetailChatType = d.DetailChatType;
OnSelectWeapons = d.OnSelectWeapons; OnSelectArmor = d.OnSelectArmor;
OnSelectJewelry = d.OnSelectJewelry; OnSelectOther = d.OnSelectOther;
IdTimeoutSec = d.IdTimeoutSec;
HiddenFields = d.HiddenFields; HiddenRatings = d.HiddenRatings;
ShowValueAndBurden = d.ShowValueAndBurden;
SpellMode = d.SpellMode; MaxListedSpells = d.MaxListedSpells;
ChatType = d.ChatType; Prefix = d.Prefix;
}
}
/// <summary>Labels for the settings window and the /ra iteminfo field|rating commands.</summary>
public static class MagItemInfoCatalog
{
public readonly record struct FieldInfo(MagItemInfoField Field, string Label, string Example);
public readonly record struct RatingInfo(uint StatId, string Tag, string Name);
/// <summary>In print order.</summary>
public static readonly FieldInfo[] Fields =
{
new(MagItemInfoField.Material, "Material", "Gold Ornate Long Sword"),
new(MagItemInfoField.TypeMastery, "Damage type / mastery","(Slash Sword)"),
new(MagItemInfoField.Set, "Equipment set", "Noble Relic Set"),
new(MagItemInfoField.ArmorLevel, "Armor level", "AL 650"),
new(MagItemInfoField.Imbues, "Imbues", "CS, AR, FireRend"),
new(MagItemInfoField.ArmorCleave, "Armor cleaving", "AC"),
new(MagItemInfoField.CritStats, "Crit mult / freq", "CritMult (1.5), CritFreq (0.15)"),
new(MagItemInfoField.Splits, "Split arrows", "Splits (2)"),
new(MagItemInfoField.Range, "Missile range", "Range 120yd"),
new(MagItemInfoField.CleaveMultiStrike, "Cleaving / Multi-Strike", "Cleaving"),
new(MagItemInfoField.Slayer, "Slayer", "Undead Slayer"),
new(MagItemInfoField.Tinks, "Tinks", "Tinks 4"),
new(MagItemInfoField.Applied, "Applied materials", "Applied: Steel x2"),
new(MagItemInfoField.Damage, "Damage", "152.48-236, 0.35v, +18, +10%"),
new(MagItemInfoField.Attack, "Attack bonus", "+18%a"),
new(MagItemInfoField.Defenses, "Defense bonuses", "12%md, 1.5%mgc.d, 1%msl.d"),
new(MagItemInfoField.ManaConversion, "Mana conversion", "6%mc"),
new(MagItemInfoField.Spells, "Spells", "Legendary Blood Thirst"),
new(MagItemInfoField.Wield, "Wield requirements", "Wield Lvl 180, Heavy Weapons 375"),
new(MagItemInfoField.Activation, "Activation / use reqs","Lvl 50, Melee Defense 300 to Activate"),
new(MagItemInfoField.Difficulty, "Arcane difficulty", "Diff 270"),
new(MagItemInfoField.Craft, "Craft / salvage work", "Craft 8"),
new(MagItemInfoField.Protections, "Protections (unenchantable armor)", "[1.0/0.8/1.2/...]"),
new(MagItemInfoField.Ratings, "Ratings", "[D 3, CD 2]"),
new(MagItemInfoField.Keyring, "Keyring keys / uses", "Keys: 3, Uses: 25"),
};
/// <summary>ACE gear ratings (PropertyInt 370–389) in Mag print order.</summary>
public static readonly RatingInfo[] Ratings =
{
new(370, "D", "Damage"),
new(371, "DR", "Damage Resist"),
new(372, "C", "Crit"),
new(374, "CD", "Crit Damage"),
new(373, "CR", "Crit Resist"),
new(375, "CDR", "Crit Damage Resist"),
new(376, "HB", "Healing Boost"),
new(379, "V", "Vitality"),
new(377, "NR", "Nether Resist"),
new(378, "LR", "Life Resist"),
new(383, "PKD", "PK Damage"),
new(384, "PKDR", "PK Damage Resist"),
new(388, "OP", "Overpower"),
new(389, "OPR", "Overpower Resist"),
};
/// <summary>Labels for <see cref="MagItemInfoSettings.ClickTrigger"/>, indexed by value.</summary>
public static readonly string[] ClickTriggers = { "Off", "Left mouse click", "Right mouse click" };
/// <summary>Labels for <see cref="MagItemInfoSettings.Layout"/>, indexed by value.</summary>
public static readonly string[] Layouts = { "One line (Mag-Tools)", "Pet-style lines" };
/// <summary>Common AC chat types for the colour picker (value passed to WriteToChat).</summary>
public static readonly (int Type, string Label)[] ChatTypes =
{
(0, "0 - Broadcast"),
(1, "1 - RynthAi default"),
(2, "2 - Speech"),
(3, "3 - Tell"),
(4, "4 - Outgoing tell"),
(5, "5 - System"),
(6, "6 - Combat"),
(7, "7 - Magic"),
(8, "8 - Channels"),
(10, "10 - Social"),
(12, "12 - Emote"),
(13, "13 - Advancement"),
(15, "15 - Help"),
(16, "16 - Appraisal"),
(17, "17 - Spellcasting"),
(18, "18 - Allegiance"),
(19, "19 - Fellowship"),
(21, "21 - Combat (enemy)"),
(22, "22 - Combat (self)"),
(24, "24 - Craft"),
(25, "25 - Salvaging"),
};
/// <summary>Field by enum name or label word, case-insensitive ("ratings", "slayer", "typemastery").</summary>
public static bool TryFindField(string key, out MagItemInfoField field)
{
foreach (var f in Fields)
{
if (f.Field.ToString().Equals(key, StringComparison.OrdinalIgnoreCase)
|| f.Label.Replace(" ", string.Empty).StartsWith(key, StringComparison.OrdinalIgnoreCase))
{
field = f.Field;
return true;
}
}
field = MagItemInfoField.None;
return false;
}
/// <summary>Rating index by tag ("CD") or name ("critdamage"), case-insensitive.</summary>
public static int FindRating(string key)
{
for (int i = 0; i < Ratings.Length; i++)
{
if (Ratings[i].Tag.Equals(key, StringComparison.OrdinalIgnoreCase)
|| Ratings[i].Name.Replace(" ", string.Empty).Equals(key, StringComparison.OrdinalIgnoreCase))
return i;
}
return -1;
}
}

View file

@ -0,0 +1,159 @@
// MagItemInfoTables.cs — name tables for the Mag-style item info line (MagItemDescriber).
// Skill / mastery / set / material names follow UtilityBelt ub-IT (Lib/ItemInfoHelper/Dictionaries.cs,
// itself from Mag-Tools / Alinco / VTank). Slayer names use the full ACE CreatureType enum instead of
// ub-IT's 17-entry subset so every slayer resolves.
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
internal static class MagItemInfoTables
{
/// <summary>Skill id → name (wield / activation / summoning requirements).</summary>
public static readonly Dictionary<int, string> Skills = new()
{
{ 0x01, "Axe" }, { 0x02, "Bow" }, { 0x03, "Crossbow" }, { 0x04, "Dagger" }, { 0x05, "Mace" },
{ 0x06, "Melee Defense" }, { 0x07, "Missile Defense" }, { 0x08, "Sling" }, { 0x09, "Spear" },
{ 0x0A, "Staff" }, { 0x0B, "Sword" }, { 0x0C, "Thrown Weapons" }, { 0x0D, "Unarmed Combat" },
{ 0x0E, "Arcane Lore" }, { 0x0F, "Magic Defense" }, { 0x10, "Mana Conversion" },
{ 0x12, "Item Tinkering" }, { 0x13, "Assess Person" }, { 0x14, "Deception" }, { 0x15, "Healing" },
{ 0x16, "Jump" }, { 0x17, "Lockpick" }, { 0x18, "Run" }, { 0x1B, "Assess Creature" },
{ 0x1C, "Weapon Tinkering" }, { 0x1D, "Armor Tinkering" }, { 0x1E, "Magic Item Tinkering" },
{ 0x1F, "Creature Enchantment" }, { 0x20, "Item Enchantment" }, { 0x21, "Life Magic" },
{ 0x22, "War Magic" }, { 0x23, "Leadership" }, { 0x24, "Loyalty" }, { 0x25, "Fletching" },
{ 0x26, "Alchemy" }, { 0x27, "Cooking" }, { 0x28, "Salvaging" }, { 0x29, "Two Handed Combat" },
{ 0x2A, "Gearcraft" }, { 0x2B, "Void" }, { 0x2C, "Heavy Weapons" }, { 0x2D, "Light Weapons" },
{ 0x2E, "Finesse Weapons" }, { 0x2F, "Missile Weapons" }, { 0x30, "Shield" }, { 0x31, "Dual Wield" },
{ 0x32, "Recklessness" }, { 0x33, "Sneak Attack" }, { 0x34, "Dirty Fighting" }, { 0x35, "Challenge" },
{ 0x36, "Summoning" },
};
/// <summary>ACE PropertyInt.WeaponType (353) → mastery name.</summary>
public static readonly Dictionary<int, string> Masteries = new()
{
{ 1, "Unarmed Weapon" }, { 2, "Sword" }, { 3, "Axe" }, { 4, "Mace" }, { 5, "Spear" }, { 6, "Dagger" },
{ 7, "Staff" }, { 8, "Bow" }, { 9, "Crossbow" }, { 10, "Thrown" }, { 11, "Two Handed Combat" }, { 12, "Wand" },
};
/// <summary>ACE PropertyInt.MaterialType (131) → material name.</summary>
public static readonly Dictionary<int, string> Materials = new()
{
{ 1, "Ceramic" }, { 2, "Porcelain" }, { 4, "Linen" }, { 5, "Satin" }, { 6, "Silk" }, { 7, "Velvet" },
{ 8, "Wool" }, { 10, "Agate" }, { 11, "Amber" }, { 12, "Amethyst" }, { 13, "Aquamarine" },
{ 14, "Azurite" }, { 15, "Bag of Abyssal-Touched" }, { 16, "Black Opal" }, { 17, "Bloodstone" },
{ 18, "Carnelian" }, { 19, "Citrine" }, { 20, "Diamond" }, { 21, "Emerald" }, { 22, "Fire Opal" },
{ 23, "Green Garnet" }, { 24, "Green Jade" }, { 25, "Hematite" }, { 26, "Imperial Topaz" }, { 27, "Jet" },
{ 28, "Lapis Lazuli" }, { 29, "Lavender Jade" }, { 30, "Malachite" }, { 31, "Moonstone" }, { 32, "Onyx" },
{ 33, "Opal" }, { 34, "Peridot" }, { 35, "Red Garnet" }, { 36, "Red Jade" }, { 37, "Rose Quartz" },
{ 38, "Ruby" }, { 39, "Sapphire" }, { 40, "Smokey Quartz" }, { 41, "Sunstone" }, { 42, "Tiger Eye" },
{ 43, "Tourmaline" }, { 44, "Turquoise" }, { 45, "White Jade" }, { 46, "White Quartz" },
{ 47, "White Sapphire" }, { 48, "Yellow Garnet" }, { 49, "Yellow Topaz" }, { 50, "Zircon" },
{ 51, "Ivory" }, { 52, "Leather" }, { 53, "Armoredillo Hide" }, { 54, "Gromnie Hide" },
{ 55, "Reed Shark Hide" }, { 57, "Brass" }, { 58, "Bronze" }, { 59, "Copper" }, { 60, "Gold" },
{ 61, "Iron" }, { 62, "Pyreal" }, { 63, "Silver" }, { 64, "Steel" }, { 66, "Alabaster" },
{ 67, "Granite" }, { 68, "Marble" }, { 69, "Obsidian" }, { 70, "Sandstone" }, { 71, "Serpentine" },
{ 73, "Ebony" }, { 74, "Mahogany" }, { 75, "Oak" }, { 76, "Pine" }, { 77, "Teak" },
};
/// <summary>ACE PropertyInt.EquipmentSetId (265) → set name.</summary>
public static readonly Dictionary<int, string> EquipmentSets = BuildSets();
/// <summary>ACE CreatureType enum, index = value (0..101). Used for SlayerCreatureType (166).</summary>
private static readonly string[] CreatureTypes =
{
"Invalid", "Olthoi", "Banderling", "Drudge", "Mosswart", "Lugian", "Tumerok", "Mite", "Tusker",
"Phyntos Wasp", "Rat", "Auroch", "Cow", "Golem", "Undead", "Gromnie", "Reedshark", "Armoredillo",
"Fae", "Virindi", "Wisp", "Knathtead", "Shadow", "Mattekar", "Mumiyah", "Rabbit", "Sclavus",
"Shallows Shark", "Monouga", "Zefir", "Skeleton", "Human", "Shreth", "Chittick", "Moarsman",
"Olthoi Larvae", "Slithis", "Deru", "Fire Elemental", "Snowman", "Unknown", "Bunny",
"Lightning Elemental", "Rockslide", "Grievver", "Niffis", "Ursuin", "Crystal", "Hollow Minion",
"Scarecrow", "Idol", "Empyrean", "Hopeslayer", "Doll", "Marionette", "Carenzi", "Siraluun",
"Aun Tumerok", "Hea Tumerok", "Simulacrum", "Acid Elemental", "Frost Elemental", "Elemental",
"Statue", "Wall", "Altered Human", "Device", "Harbinger", "Dark Sarcophagus", "Chicken",
"Gotrok Lugian", "Margul", "Bleached Rabbit", "Nasty Rabbit", "Grimacing Rabbit", "Burun", "Target",
"Ghost", "Fiun", "Eater", "Penguin", "Ruschk", "Thrungus", "Viamontian Knight", "Remoran", "Swarm",
"Moar", "Enchanted Arms", "Sleech", "Mukkir", "Merwart", "Food", "Paradox Olthoi", "Harvest",
"Energy", "Apparition", "Aerbax", "Touched", "Blighted Moarsman", "Gear Knight", "Gurog", "A'nekshay",
};
/// <summary>Slayer creature name, or null for 0 / unknown values.</summary>
public static string? CreatureTypeName(int value) =>
value > 0 && value < CreatureTypes.Length ? CreatureTypes[value] : null;
/// <summary>
/// ACE DamageType flags (45) → "Slash", "Slash/Pierce", "Lightning" … Empty when no known bit is set.
/// </summary>
public static string DamageTypeName(int flags)
{
if (flags <= 0) return string.Empty;
var sb = new StringBuilder();
void Add(int bit, string name)
{
if ((flags & bit) == 0) return;
if (sb.Length > 0) sb.Append('/');
sb.Append(name);
}
Add(0x001, "Slash");
Add(0x002, "Pierce");
Add(0x004, "Bludgeon");
Add(0x008, "Cold");
Add(0x010, "Fire");
Add(0x020, "Acid");
Add(0x040, "Lightning");
Add(0x400, "Nether");
return sb.ToString();
}
private static Dictionary<int, string> BuildSets()
{
var d = new Dictionary<int, string>
{
{ 2, "Test" }, { 4, "Carraida's Benediction" }, { 5, "Noble Relic Set" }, { 6, "Ancient Relic Set" },
{ 7, "Relic Alduressa Set" }, { 8, "Shou-jen Set" }, { 9, "Empyrean Rings Set" },
{ 10, "Arm, Mind, Heart Set" }, { 11, "Coat of the Perfect Light Set" },
{ 12, "Leggings of Perfect Light Set" }, { 13, "Soldier's Set" }, { 14, "Adept's Set" },
{ 15, "Archer's Set" }, { 16, "Defender's Set" }, { 17, "Tinker's Set" }, { 18, "Crafter's Set" },
{ 19, "Hearty Set" }, { 20, "Dexterous Set" }, { 21, "Wise Set" }, { 22, "Swift Set" },
{ 23, "Hardened Set" }, { 24, "Reinforced Set" }, { 25, "Interlocking Set" },
{ 26, "Flame Proof Set" }, { 27, "Acid Proof Set" }, { 28, "Cold Proof Set" },
{ 29, "Lightning Proof Set" }, { 30, "Dedication Set" }, { 31, "Gladiatorial Clothing Set" },
{ 32, "Ceremonial Clothing" }, { 33, "Protective Clothing" }, { 34, "Noobie Armor" },
{ 35, "Sigil of Defense" }, { 36, "Sigil of Destruction" }, { 37, "Sigil of Fury" },
{ 38, "Sigil of Growth" }, { 39, "Sigil of Vigor" }, { 40, "Heroic Protector Set" },
{ 41, "Heroic Destroyer Set" }, { 42, "Olthoi Armor D Red" }, { 43, "Olthoi Armor C Rat" },
{ 44, "Olthoi Armor C Red" }, { 45, "Olthoi Armor D Rat" }, { 46, "Upgraded Relic Alduressa Set" },
{ 47, "Upgraded Ancient Relic Set" }, { 48, "Upgraded Noble Relic Set" },
{ 49, "Weave of Alchemy" }, { 50, "Weave of Arcane Lore" }, { 51, "Weave of Armor Tinkering" },
{ 52, "Weave of Assess Person" }, { 53, "Weave of Light Weapons" }, { 54, "Weave of Missile Weapons" },
{ 55, "Weave of Cooking" }, { 56, "Weave of Creature Enchantment" }, { 57, "Weave of Missile Weapons" },
{ 58, "Weave of Finesse" }, { 59, "Weave of Deception" }, { 60, "Weave of Fletching" },
{ 61, "Weave of Healing" }, { 62, "Weave of Item Enchantment" }, { 63, "Weave of Item Tinkering" },
{ 64, "Weave of Leadership" }, { 65, "Weave of Life Magic" }, { 66, "Weave of Loyalty" },
{ 67, "Weave of Light Weapons" }, { 68, "Weave of Magic Defense" },
{ 69, "Weave of Magic Item Tinkering" }, { 70, "Weave of Mana Conversion" },
{ 71, "Weave of Melee Defense" }, { 72, "Weave of Missile Defense" }, { 73, "Weave of Salvaging" },
{ 74, "Weave of Light Weapons" }, { 75, "Weave of Light Weapons" }, { 76, "Weave of Heavy Weapons" },
{ 77, "Weave of Missile Weapons" }, { 78, "Weave of Two Handed Combat" }, { 79, "Weave of Light Weapons" },
{ 80, "Weave of Void Magic" }, { 81, "Weave of War Magic" }, { 82, "Weave of Weapon Tinkering" },
{ 83, "Weave of Assess Creature" }, { 84, "Weave of Dirty Fighting" }, { 85, "Weave of Dual Wield" },
{ 86, "Weave of Recklessness" }, { 87, "Weave of Shield" }, { 88, "Weave of Sneak Attack" },
{ 89, "Ninja_New" }, { 90, "Weave of Summoning" }, { 91, "Shrouded Soul" }, { 92, "Darkened Mind" },
{ 93, "Clouded Spirit" }, { 130, "Shimmering Shadows" }, { 131, "Brown Society Locket" },
{ 132, "Yellow Society Locket" }, { 133, "Red Society Band" }, { 134, "Green Society Band" },
{ 135, "Purple Society Band" }, { 136, "Blue Society Band" }, { 137, "Gauntlet Garb" },
{ 138, "Paragon" }, { 139, "Paragon" }, { 140, "Paragon" },
};
// 94..129: Minor / Major / Blackfire × Stinging / Sparking / Smoldering / Shivering ×
// Shrouded Soul / Darkened Mind / Clouded Spirit (same order as the VTank set list).
string[] tiers = { "Minor", "Major", "Blackfire" };
string[] souls = { "Shrouded Soul", "Darkened Mind", "Clouded Spirit" };
string[] elements = { "Stinging", "Sparking", "Smoldering", "Shivering" };
int id = 94;
foreach (string tier in tiers)
foreach (string soul in souls)
foreach (string element in elements)
d[id++] = $"{tier} {element} {soul}";
return d;
}
}

View file

@ -89,11 +89,11 @@ internal sealed class Jumper
_turningStartedAt = DateTime.UtcNow;
if (_host.HasTurnToHeading)
_host.TurnToHeadingBy("Jump", _targetHeading);
_host.Log($"[Jumper] Start turn->{_targetHeading:F0} letters='{directionLetters}' hold={_msToHoldDown}ms");
RynthLog.Write(LogCat.Jumper, $"[Jumper] Start turn->{_targetHeading:F0} letters='{directionLetters}' hold={_msToHoldDown}ms");
}
else
{
_host.Log($"[Jumper] Start jump (no turn) letters='{directionLetters}' hold={_msToHoldDown}ms");
RynthLog.Write(LogCat.Jumper, $"[Jumper] Start jump (no turn) letters='{directionLetters}' hold={_msToHoldDown}ms");
}
return true;
}
@ -118,7 +118,7 @@ internal sealed class Jumper
{
_isTurning = false;
if (_host.TryGetPlayerHeading(out float current))
_host.Log($"[Jumper] Turn done heading={current:F1}");
RynthLog.Write(LogCat.Jumper, $"[Jumper] Turn done heading={current:F1}");
}
if (_needToJump && !_isTurning)
@ -141,12 +141,12 @@ internal sealed class Jumper
RestoreNav();
_waitingForJump = false;
_addW = _addX = _addZ = _addC = _addShift = false;
_host.Log("[Jumper] Settle complete -> idle");
RynthLog.Write(LogCat.Jumper, "[Jumper] Settle complete -> idle");
}
}
catch (Exception ex)
{
_host.Log($"[Jumper] Tick exception: {ex.GetType().Name}: {ex.Message}");
RynthLog.Write(LogCat.Jumper, $"[Jumper] Tick exception: {ex.GetType().Name}: {ex.Message}");
Cancel();
}
}
@ -166,7 +166,7 @@ internal sealed class Jumper
started = _host.CommenceJump();
_charging = started;
_chargeStartedAt = DateTime.UtcNow;
_host.Log($"[Jumper] CommenceJump ok={started} hold={_msToHoldDown}ms " +
RynthLog.Write(LogCat.Jumper, $"[Jumper] CommenceJump ok={started} hold={_msToHoldDown}ms " +
$"w={_addW} x={_addX} z={_addZ} c={_addC} shift={_addShift}");
}
else
@ -174,7 +174,7 @@ internal sealed class Jumper
started = _host.HasTapJump && _host.TapJump();
_waitingForJump = started;
_jumpStartedAt = DateTime.UtcNow;
_host.Log($"[Jumper] TapJump fallback ok={started} " +
RynthLog.Write(LogCat.Jumper, $"[Jumper] TapJump fallback ok={started} " +
$"w={_addW} x={_addX} z={_addZ} c={_addC} shift={_addShift}");
}
@ -200,13 +200,13 @@ internal sealed class Jumper
if (_host.HasLaunchJumpWithMotion)
{
released = _host.LaunchJumpWithMotion(_addShift, _addW, _addX, _addZ, _addC);
_host.Log($"[Jumper] LaunchJumpWithMotion ok={released} charged={_msToHoldDown}ms " +
RynthLog.Write(LogCat.Jumper, $"[Jumper] LaunchJumpWithMotion ok={released} charged={_msToHoldDown}ms " +
$"w={_addW} x={_addX} z={_addZ} c={_addC} shift={_addShift}");
}
else
{
released = _host.HasDoJump && _host.DoJump(true);
_host.Log($"[Jumper] DoJump fallback ok={released} charged={_msToHoldDown}ms");
RynthLog.Write(LogCat.Jumper, $"[Jumper] DoJump fallback ok={released} charged={_msToHoldDown}ms");
}
}

View file

@ -0,0 +1,27 @@
// LegacyDashboardRenderer.LocalFeatures.cs — style shared with the plugin's own ImGui windows
// (ILT Hub, floating HUDs, chat translator).
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed partial class LegacyDashboardRenderer
{
/// <summary>Pushes RynthAi's window colours; returns the count for PopStyleColor.</summary>
internal static int PushDashboardStyle()
{
// Muted slate-blue accents. TitleBgActive replaces ImGui's default yellow on detached windows.
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;
}
}

View file

@ -0,0 +1,224 @@
// LegacyDashboardRenderer.NavEdit.cs — route editor commands from the engine Nav panel:
// multi-select move / duplicate / delete, set active, move a step to the player, nearest,
// reverse, snap to path, pause / portal / point-at-selection steps, simplify, recording and
// trail -> route.
//
// Commands arrive with indices into the route the panel last saw. Structural edits go
// through NavRouteEditing.Apply (copy-on-write) so the nav engine never sees a half-edited list.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed partial class LegacyDashboardRenderer
{
/// <summary>How long an edit's result stays in the Nav panel's status line.</summary>
private const long NavEditStatusMs = 8_000;
/// <summary>Spot closer than this to an existing waypoint is refused by "Snap to path", yards.</summary>
private const double SnapMinGapYards = 0.5;
/// <summary>Decal ObjectClass.Portal, as VTank writes it in Portal steps.</summary>
private const int PortalObjectClass = 14;
private string _navEditStatus = string.Empty;
private long _navEditStatusAt;
/// <summary>Breadcrumb trail (set by the plugin once the nav overlay exists; null before login).</summary>
internal NavBreadcrumbTracker? NavBreadcrumbs { get; set; }
private List<NavPoint> RoutePoints => _settings.CurrentRoute.Points;
/// <summary>The last edit's result while it is fresh, else empty.</summary>
private string CurrentNavEditStatus() =>
_navEditStatus.Length > 0 && Environment.TickCount64 - _navEditStatusAt < NavEditStatusMs ? _navEditStatus : string.Empty;
private void SetNavEditStatus(string text)
{
_navEditStatus = text;
_navEditStatusAt = Environment.TickCount64;
RynthLog.Trace(LogCat.Navigation, "[NavEdit] " + text);
}
private void HandleNavEditCommand(NavCommand cmd)
{
switch (cmd.Cmd)
{
case "movePoints":
{
var sel = PointsAt(cmd.Indices);
if (sel.Count == 0 || cmd.Delta == 0) return;
EditRoute(l => NavRouteEditing.Move(l, sel, Math.Sign(cmd.Delta)));
break;
}
case "duplicatePoints":
{
var sel = PointsAt(cmd.Indices);
if (sel.Count == 0) return;
var copies = new List<NavPoint>();
EditRoute(l => NavRouteEditing.Duplicate(l, sel, copies));
SetNavEditStatus($"Duplicated {copies.Count} step(s).");
break;
}
case "deletePoints":
{
var sel = PointsAt(cmd.Indices);
if (sel.Count == 0) return;
EditRoute(l => NavRouteEditing.Remove(l, sel));
SetNavEditStatus($"Deleted {sel.Count} step(s).");
break;
}
case "setActive":
if (cmd.Index < 0 || cmd.Index >= RoutePoints.Count) return;
_settings.ActiveNavIndex = cmd.Index;
SaveSettings();
SetNavEditStatus($"Active waypoint: {cmd.Index}.");
break;
case "movePointHere":
{
if (cmd.Index < 0 || cmd.Index >= RoutePoints.Count || !TryNavHere(out NavPoint here)) return;
NavPoint p = RoutePoints[cmd.Index];
p.NS = here.NS; p.EW = here.EW; p.Z = here.Z;
_navigationUi.TryAutoSaveNav();
SetNavEditStatus($"Step {cmd.Index} moved to your position.");
break;
}
case "nearestActive":
{
int i = FindNearestWaypoint(_settings.CurrentRoute);
if (RoutePoints.Count == 0) return;
_settings.ActiveNavIndex = i;
SaveSettings();
SetNavEditStatus($"Active waypoint: {i} (nearest).");
break;
}
case "reverseRoute":
if (RoutePoints.Count < 2) return;
EditRoute(NavRouteEditing.Reverse);
SetNavEditStatus("Route reversed.");
break;
case "snapToPath":
{
if (!TryNavHere(out NavPoint here)) return;
NavPoint? inserted = null;
string error = string.Empty;
EditRoute(l => { NavRouteEditing.TrySnapInsert(l, here.NS, here.EW, SnapMinGapYards, out inserted, out error); return l; });
SetNavEditStatus(inserted != null ? $"Inserted a point on the path at step {RoutePoints.IndexOf(inserted)}." : error);
break;
}
case "addPause":
{
if (!TryNavHere(out NavPoint p)) return;
p.Type = NavPointType.Pause;
p.PauseTimeMs = (int)(Math.Clamp(cmd.Seconds, 0.1, 600.0) * 1000);
InsertNavPoint(p, cmd.AddMode, cmd.InsertAt);
SetNavEditStatus($"Added a {p.PauseTimeMs / 1000.0:0.#} s pause.");
break;
}
case "addPortal":
{
if (!TryDescribeNavSelection(out string name, out double ons, out double oew, out double oz) || !TryNavHere(out NavPoint p)) return;
p.Type = NavPointType.PortalNPC;
p.TargetName = name;
p.ObjectClass = PortalObjectClass;
p.PortalExitNS = ons; p.PortalExitEW = oew; p.PortalExitZ = oz;
InsertNavPoint(p, cmd.AddMode, cmd.InsertAt);
SetNavEditStatus($"Added Portal step '{name}'.");
break;
}
case "addPointAtSelected":
{
if (!TryDescribeNavSelection(out string name, out double ns, out double ew, out double z)) return;
InsertNavPoint(new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = z }, cmd.AddMode, cmd.InsertAt);
SetNavEditStatus($"Added a point at '{name}'.");
break;
}
case "simplifyRoute":
{
double tol = Math.Clamp(cmd.Yards, 0.2, 10.0);
int ai = _settings.ActiveNavIndex;
NavPoint? keep = ai >= 0 && ai < RoutePoints.Count ? RoutePoints[ai] : null;
int removed = 0;
EditRoute(l => { removed = NavRouteEditing.Simplify(l, tol, keep); return l; });
SetNavEditStatus($"Simplify ({tol:0.#} yd) removed {removed} point(s).");
break;
}
case "setRecording":
_settings.IsRecordingNav = cmd.On;
SetNavEditStatus(cmd.On ? "Recording: walk the route; points are added for you." : "Recording stopped.");
break;
case "trailToRoute":
{
NavCrumb[] trail = NavBreadcrumbs?.Trail ?? Array.Empty<NavCrumb>();
List<NavPoint> pts = NavBreadcrumbTracker.TrailToPoints(trail, _settings.NavOverlay.RecordSpacingYards, cmd.Reverse);
if (pts.Count < 2) { SetNavEditStatus("The trail is too short to make a route."); return; }
_settings.IsRecordingNav = false;
// A new unsaved route: the loaded file on disk is not changed (Save As keeps it).
_settings.CurrentRoute = new NavRouteParser { RouteType = NavRouteType.Once, Points = pts };
_settings.CurrentNavPath = string.Empty;
_settings.ActiveNavIndex = 0;
RefreshNavFiles();
SaveSettings();
SetNavEditStatus($"{(cmd.Reverse ? "Backtrack" : "Trail")} route created: {pts.Count} points (unsaved).");
break;
}
}
}
/// <summary>Copy-on-write route edit, then the route file autosave.</summary>
private void EditRoute(Func<List<NavPoint>, List<NavPoint>> edit)
{
NavRouteEditing.Apply(_settings, edit);
_navigationUi.TryAutoSaveNav();
}
/// <summary>The route's points at <paramref name="indices"/>; out-of-range indices are skipped.</summary>
private HashSet<NavPoint> PointsAt(List<int>? indices)
{
var sel = new HashSet<NavPoint>();
if (indices == null) return sel;
var pts = RoutePoints;
foreach (int i in indices)
if (i >= 0 && i < pts.Count) sel.Add(pts[i]);
return sel;
}
/// <summary>A Point at the player's position (Z in nav units), or false when the position is unknown.</summary>
private bool TryNavHere(out NavPoint p)
{
p = new NavPoint();
if (!NavCoordinateHelper.TryGetNavPosition(_host, out double ns, out double ew, out double z))
{
SetNavEditStatus("Position unavailable.");
return false;
}
p.NS = ns; p.EW = ew; p.Z = z;
return true;
}
/// <summary>Name and nav position of the selected world object.</summary>
private bool TryDescribeNavSelection(out string name, out double ns, out double ew, out double navZ)
{
name = string.Empty; ns = ew = navZ = 0;
if (!_host.HasGetSelectedItemId) { SetNavEditStatus("Selection unavailable."); return false; }
uint sel = _host.GetSelectedItemId();
if (sel == 0) { SetNavEditStatus("Select an object first."); return false; }
if (!_host.HasGetObjectName || !_host.TryGetObjectName(sel, out name) || string.IsNullOrWhiteSpace(name))
{
SetNavEditStatus("The selected object has no name yet.");
return false;
}
if (_host.HasGetObjectPosition
&& _host.TryGetObjectPosition(sel, out uint cell, out float x, out float y, out float z)
&& NavCoordinateHelper.TryConvertPoseToCoords(cell, x, y, out ns, out ew))
{
navZ = z / NavCoordinateHelper.NavZScale;
return true;
}
SetNavEditStatus($"Could not read the position of '{name}'.");
return false;
}
}

View file

@ -12,7 +12,7 @@ using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal sealed class LegacyDashboardRenderer
internal sealed partial class LegacyDashboardRenderer
{
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);
@ -1087,6 +1087,13 @@ internal sealed class LegacyDashboardRenderer
AutoVendorTriesTime = s.AutoVendorTriesTime,
OffhandDefault = s.OffhandDefault,
PreferDualWield = s.PreferDualWield,
EnableGroundLoot = s.EnableGroundLoot,
ItemInfoOnSelect = s.ItemInfoSettings.OnSelect,
// Diagnostics (per PC, RynthLog)
DiagDebugToChat = RynthLog.DebugToChat,
DiagFileLogAll = RynthLog.FileLogAll,
DiagCategories = RynthLog.FormatCategoryLevels(),
DiagFolder = RynthLog.Directory,
};
return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.SettingsBridgePayload);
}
@ -1288,6 +1295,12 @@ internal sealed class LegacyDashboardRenderer
// Off hand: only fields the sender actually included (the engine face doesn't draw them yet)
if (p.OffhandDefault is string od && OffhandRules.TryParse(od, out var odMode)) s.OffhandDefault = OffhandRules.SettingValue(odMode);
if (p.PreferDualWield is bool pdw) s.PreferDualWield = pdw;
s.EnableGroundLoot = p.EnableGroundLoot;
s.ItemInfoSettings.OnSelect = p.ItemInfoOnSelect;
// Diagnostics: each setter rewrites diagnostics.json, so only touch what changed.
if (p.DiagDebugToChat != RynthLog.DebugToChat) RynthLog.DebugToChat = p.DiagDebugToChat;
if (p.DiagFileLogAll != RynthLog.FileLogAll) RynthLog.FileLogAll = p.DiagFileLogAll;
RynthLog.ApplyCategoryLevels(p.DiagCategories);
SaveSettings();
}
catch { }
@ -2300,6 +2313,12 @@ internal sealed class LegacyDashboardRenderer
ActiveNavIndex = _settings.ActiveNavIndex,
NavFiles = new List<string>(_navFiles),
Points = points,
TrackBreadcrumbs = _settings.NavOverlay.TrackBreadcrumbs,
ShowRouteOverlay = _settings.NavOverlay.ShowRouteMarkers,
IsRecording = _settings.IsRecordingNav,
TrailPoints = NavBreadcrumbs?.Trail.Length ?? 0,
TrailYards = NavBreadcrumbs?.TrailYards ?? 0,
EditStatus = CurrentNavEditStatus(),
};
return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.NavBridgePayload);
}
@ -2329,6 +2348,18 @@ internal sealed class LegacyDashboardRenderer
SaveSettings();
break;
case "setBreadcrumbs":
// Nav panel "Breadcrumbs": record (and draw) the walked trail.
_settings.NavOverlay.TrackBreadcrumbs = cmd.On;
SaveSettings();
break;
case "setRouteOverlay":
// Nav panel "Route overlay": route rings / lines, waypoint labels, guide line.
_settings.NavOverlay.ShowRouteMarkers = cmd.On;
SaveSettings();
break;
case "addWaypoint":
_host.SetMotionBy("UI", 0x6500000D, false); // stop TurnRight
_host.SetMotionBy("UI", 0x6500000E, false); // stop TurnLeft
@ -2405,6 +2436,11 @@ internal sealed class LegacyDashboardRenderer
int ni = _navFiles.IndexOf(cmd.NavName);
if (ni >= 0) { _selectedNavIdx = ni; LoadSelectedNav(); SaveSettings(); }
break;
default:
// Route editor commands (multi-select edits, pause / portal steps, trail -> route).
HandleNavEditCommand(cmd);
break;
}
}
catch { }

View file

@ -0,0 +1,295 @@
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.ItemInfo;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// <summary>
/// "RynthAi Item Info" window: every option of the Mag-style item info line (/ra iteminfo) with
/// a live preview of the selected item. Edits go straight into
/// <see cref="LegacyUiSettings.ItemInfoSettings"/> and are saved by the dashboard autosave.
/// Opened from Advanced Settings → Display or with /ra iteminfo settings.
/// </summary>
internal sealed class LegacyItemInfoUi
{
private readonly LegacyUiSettings _settings;
// Supplied by RynthAiPlugin (it owns the host + object cache).
private Func<string?>? _describeSelected; // selected item's line (no prefix) or null when nothing is selected
private Action? _printSelected; // same path as /ra iteminfo (requests an ID when needed)
private Action<int>? _testChatType; // prints a sample line with the given chat type
// Preview is rebuilt on a timer or when an output option changes, not every frame.
private const long PreviewRefreshMs = 500;
private string? _previewText;
private long _previewAt;
private MagItemInfoOptions _previewOptions;
private static readonly Vector4 ExampleColor = new(0.60f, 0.66f, 0.74f, 1f);
public LegacyItemInfoUi(LegacyUiSettings settings) => _settings = settings;
public void SetHooks(Func<string?> describeSelected, Action printSelected, Action<int> testChatType)
{
_describeSelected = describeSelected;
_printSelected = printSelected;
_testChatType = testChatType;
}
public void Render()
{
// Re-read every frame: loading a character profile replaces the settings object.
MagItemInfoSettings s = _settings.ItemInfoSettings;
if (!s.ShowWindow) return;
ImGui.SetNextWindowSize(new Vector2(560, 600), ImGuiCond.FirstUseEver);
if (ImGui.Begin("RynthAi Item Info##ItemInfoSettings", ref s.ShowWindow))
{
RenderPreview(s);
RenderWhen(s);
RenderFields(s);
RenderSpellsAndRatings(s);
RenderChat(s);
ImGui.Spacing();
ImGui.Separator();
if (ImGui.Button("Reset all to defaults##ii"))
{
s.ResetToDefaults();
_previewAt = 0;
}
ImGui.SameLine();
if (ImGui.Button("Close##ii")) s.ShowWindow = false;
}
ImGui.End();
}
// ── Preview ──────────────────────────────────────────────────────────────
private void RenderPreview(MagItemInfoSettings s)
{
if (!ImGui.CollapsingHeader("Preview (selected item)##ii", ImGuiTreeNodeFlags.DefaultOpen)) return;
var options = MagItemInfoOptions.From(s);
long now = Environment.TickCount64;
if (_describeSelected != null && (now - _previewAt >= PreviewRefreshMs || options != _previewOptions))
{
try { _previewText = _describeSelected(); }
catch (Exception ex) { _previewText = "Preview failed: " + ex.Message; }
_previewAt = now;
_previewOptions = options;
}
// Pet-style output is up to four lines plus wrapping.
float previewHeight = s.Layout == MagItemInfoSettings.LayoutPetLines ? 110 : 70;
ImGui.BeginChild("iiPreview", new Vector2(0, previewHeight), ImGuiChildFlags.Borders);
if (string.IsNullOrEmpty(_previewText))
ImGui.TextDisabled("Select an item to preview its info line.");
else
ImGui.TextWrapped(s.Prefix + _previewText);
ImGui.EndChild();
if (ImGui.Button("Print to chat##iiPrint")) _printSelected?.Invoke();
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Same as /ra iteminfo: IDs the selected item first when needed.");
ImGui.SameLine();
if (ImGui.Button("Refresh##iiRefresh")) _previewAt = 0;
}
// ── When to print ────────────────────────────────────────────────────────
private static void RenderWhen(MagItemInfoSettings s)
{
if (!ImGui.CollapsingHeader("When to print##ii", ImGuiTreeNodeFlags.DefaultOpen)) return;
ImGui.Checkbox("Describe items when selected##iiOnSel", ref s.OnSelect);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Print the info every time the selection changes to an item.\n/ra iteminfo always works, whatever is set here.");
RenderClickTrigger(s, "##iiClick");
ImGui.Text("Item types:");
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Which items the select / click triggers describe.\n/ra iteminfo and Print to chat ignore these.");
ImGui.Indent();
ImGui.BeginDisabled(!s.OnSelect && s.ClickTrigger == MagItemInfoSettings.ClickOff);
ImGui.Checkbox("Weapons##iiSelW", ref s.OnSelectWeapons); ImGui.SameLine();
ImGui.Checkbox("Armor & clothing##iiSelA", ref s.OnSelectArmor); ImGui.SameLine();
ImGui.Checkbox("Jewelry##iiSelJ", ref s.OnSelectJewelry); ImGui.SameLine();
ImGui.Checkbox("Other items##iiSelO", ref s.OnSelectOther);
ImGui.EndDisabled();
ImGui.Unindent();
ImGui.SetNextItemWidth(200);
if (ImGui.SliderFloat("ID wait (seconds)##iiTimeout", ref s.IdTimeoutSec, 0.5f, 15f, "%.1f s"))
s.Sanitize();
if (ImGui.IsItemHovered())
ImGui.SetTooltip("How long to wait for an unidentified item's appraisal\nbefore printing what is already known.");
}
/// <summary>
/// "ID on click" combo (Off / Left / Right). Shared with Advanced Settings → Display, so
/// <paramref name="idSuffix"/> keeps the ImGui ids unique per window.
/// </summary>
public static void RenderClickTrigger(MagItemInfoSettings s, string idSuffix)
{
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("ID + print on click" + idSuffix, ref s.ClickTrigger,
MagItemInfoCatalog.ClickTriggers, MagItemInfoCatalog.ClickTriggers.Length))
s.Sanitize();
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Clicking an item in the world or your packs IDs it and prints its info,\n" +
"even when it was already selected. Clicks on RynthCore windows, drags and\n" +
"held-button camera turns are ignored.\n" +
"Right click prints whatever item is selected after the click: if your client\n" +
"doesn't select on right click, left-click to select, then right-click to print.\n" +
"Needs the ImGui overlay enabled.");
}
/// <summary>Layout combo (pet-style lines / one line). Shared with Advanced Settings → Display.</summary>
public static void RenderLayout(MagItemInfoSettings s, string idSuffix)
{
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("Layout" + idSuffix, ref s.Layout, MagItemInfoCatalog.Layouts, MagItemInfoCatalog.Layouts.Length))
s.Sanitize();
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Pet-style lines (like the ILT Hub pet roster):\n" +
" 1 Name (type mastery), set, AL, tinks, applied, craft\n" +
" 2 imbues, slayer, damage, variance, %a / %md / %mc\n" +
" 3 [ratings] wield / activation / diff, value\n" +
" 4 Spells: …\n" +
"One line: the classic Mag-Tools single line.");
}
// ── Field toggles ────────────────────────────────────────────────────────
private void RenderFields(MagItemInfoSettings s)
{
if (!ImGui.CollapsingHeader("Fields##ii", ImGuiTreeNodeFlags.DefaultOpen)) return;
if (ImGui.SmallButton("All on##iiFields")) s.HiddenFields = 0;
ImGui.SameLine();
if (ImGui.SmallButton("All off##iiFields"))
{
foreach (var f in MagItemInfoCatalog.Fields) s.SetHidden(f.Field, true);
}
ImGui.SameLine();
ImGui.TextDisabled("(the item name is always printed)");
if (ImGui.BeginTable("iiFieldTable", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp))
{
ImGui.TableSetupColumn("Field", ImGuiTableColumnFlags.WidthStretch, 0.45f);
ImGui.TableSetupColumn("Example", ImGuiTableColumnFlags.WidthStretch, 0.55f);
foreach (var f in MagItemInfoCatalog.Fields)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool shown = !s.IsHidden(f.Field);
if (ImGui.Checkbox($"{f.Label}##iiF{(int)f.Field}", ref shown))
s.SetHidden(f.Field, !shown);
ImGui.TableNextColumn();
ImGui.TextColored(ExampleColor, f.Example);
}
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.Checkbox("Value & burden##iiValBu", ref s.ShowValueAndBurden);
ImGui.TableNextColumn();
ImGui.TextColored(ExampleColor, "Value 12,500, BU 220");
ImGui.EndTable();
}
}
// ── Spells + per-rating toggles ──────────────────────────────────────────
private static void RenderSpellsAndRatings(MagItemInfoSettings s)
{
if (!ImGui.CollapsingHeader("Spells & ratings##ii")) return;
ImGui.BeginDisabled(s.IsHidden(MagItemInfoField.Spells));
ImGui.Text("Spell list:");
ImGui.SameLine();
ImGui.RadioButton("Mag filter##iiSpMag", ref s.SpellMode, MagItemInfoSettings.SpellModeMag);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Cantrips, level 7+ weapon auras, Augmented spells,\nand Impen/banes only on unenchantable gear.");
ImGui.SameLine();
ImGui.RadioButton("All spells##iiSpAll", ref s.SpellMode, MagItemInfoSettings.SpellModeAll);
if (s.SpellMode == MagItemInfoSettings.SpellModeAll)
{
ImGui.SetNextItemWidth(200);
if (ImGui.SliderInt("Max spells listed##iiSpMax", ref s.MaxListedSpells, 1, 64))
s.Sanitize();
}
ImGui.EndDisabled();
ImGui.Spacing();
ImGui.BeginDisabled(s.IsHidden(MagItemInfoField.Ratings));
ImGui.Text("Ratings shown:");
ImGui.SameLine();
if (ImGui.SmallButton("All##iiRat")) s.HiddenRatings = 0;
ImGui.SameLine();
if (ImGui.SmallButton("None##iiRat")) s.HiddenRatings = (1 << MagItemInfoCatalog.Ratings.Length) - 1;
if (ImGui.BeginTable("iiRatingTable", 3))
{
var ratings = MagItemInfoCatalog.Ratings;
for (int i = 0; i < ratings.Length; i++)
{
ImGui.TableNextColumn();
bool shown = !s.IsRatingHidden(i);
if (ImGui.Checkbox($"{ratings[i].Tag} - {ratings[i].Name}##iiR{i}", ref shown))
s.SetRatingHidden(i, !shown);
}
ImGui.EndTable();
}
ImGui.EndDisabled();
}
// ── Chat output ──────────────────────────────────────────────────────────
private void RenderChat(MagItemInfoSettings s)
{
if (!ImGui.CollapsingHeader("Chat output##ii", ImGuiTreeNodeFlags.DefaultOpen)) return;
RenderLayout(s, "##iiLayout");
ChatTypeCombo("Chat type / colour##iiChat", ref s.ChatType, allowSameAsHeader: false);
ImGui.SameLine();
if (ImGui.Button("Test##iiChatTest")) _testChatType?.Invoke(s.ChatType);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Print a sample line with this chat type to see its colour.");
// Pet-style only: the roster draws its detail lines in a second colour.
ImGui.BeginDisabled(s.Layout != MagItemInfoSettings.LayoutPetLines);
ChatTypeCombo("Detail lines colour##iiChatDetail", ref s.DetailChatType, allowSameAsHeader: true);
ImGui.SameLine();
if (ImGui.Button("Test##iiChatDetailTest"))
_testChatType?.Invoke(s.DetailChatType == MagItemInfoSettings.SameAsHeader ? s.ChatType : s.DetailChatType);
ImGui.EndDisabled();
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
ImGui.SetTooltip("Chat type for lines 2-4 of the pet-style layout\n(the name line uses the colour above).");
ImGui.SetNextItemWidth(220);
ImGui.InputText("Line prefix##iiPrefix", ref s.Prefix, 32);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Text put in front of every item info line (may be empty).");
}
/// <summary>Chat type picker; <paramref name="allowSameAsHeader"/> adds the "same as name line" entry (-1).</summary>
private static void ChatTypeCombo(string label, ref int chatType, bool allowSameAsHeader)
{
const string SameLabel = "Same as name line";
string current = chatType == MagItemInfoSettings.SameAsHeader ? SameLabel : $"{chatType}";
foreach (var (type, name) in MagItemInfoCatalog.ChatTypes)
if (type == chatType) { current = name; break; }
ImGui.SetNextItemWidth(220);
if (!ImGui.BeginCombo(label, current)) return;
if (allowSameAsHeader && ImGui.Selectable(SameLabel, chatType == MagItemInfoSettings.SameAsHeader))
chatType = MagItemInfoSettings.SameAsHeader;
foreach (var (type, name) in MagItemInfoCatalog.ChatTypes)
if (ImGui.Selectable(name, type == chatType)) chatType = type;
ImGui.EndCombo();
}
}

View file

@ -5,6 +5,7 @@ using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
@ -46,7 +47,7 @@ internal sealed class LegacyMetaUi
private string _statusMessage = "";
private DateTime _statusTime = DateTime.MinValue;
private static readonly string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles";
private static readonly string MetaFolder = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"MetaFiles");
/// <summary>Warnings from the most recent LoadMacroFile, so the Avalonia
/// bridge can surface them too (it doesn't see the LoadedMeta).</summary>

View file

@ -13,6 +13,8 @@ public static class DashWindows
public static bool ShowWeapons;
public static bool ShowLua;
public static bool ShowDungeonMap;
/// <summary>ILT Hub window (persisted in ilt-hub.json, not in the combat profile).</summary>
public static bool ShowIltHub;
}
public sealed class LegacyUiSettings
@ -80,6 +82,10 @@ public sealed class LegacyUiSettings
public bool ShowTargetStaminaMana;
/// <summary>Mag-style item info (/ra iteminfo): on-select, per-field visibility, chat type, prefix.
/// Edited in the "RynthAi Item Info" window.</summary>
public RynthCore.Plugin.RynthAi.ItemInfo.MagItemInfoSettings ItemInfoSettings = new();
public bool EnableMissileCrafting = true;
public int MissileCraftAmmoThreshold = 1000;
@ -162,6 +168,8 @@ public sealed class LegacyUiSettings
public const float FollowNavMinLowest = 0.5f, FollowNavMinHighest = 20f;
public static float ClampFollowNavMin(float yards) =>
float.IsNaN(yards) ? 1.5f : Math.Clamp(yards, FollowNavMinLowest, FollowNavMinHighest);
/// <summary>Marker colours, waypoint HUD / labels, breadcrumb trail and recording options.</summary>
public NavOverlaySettings NavOverlay = new();
public float NavRingThickness = 6.0f;
public float NavLineThickness = 6.0f;
public float NavHeightOffset = 0.05f;
@ -197,6 +205,8 @@ public sealed class LegacyUiSettings
/// </summary>
public bool TravelToOwnCorpse;
public bool LootOnlyRareCorpses;
/// <summary>Also pick up loose ground items that match the loot profile, within the corpse max range.</summary>
public bool EnableGroundLoot;
public bool PeaceModeWhenIdle = true;
public bool RebuffWhenIdle;
/// <summary>
@ -411,6 +421,8 @@ public sealed class LegacyUiSettings
public List<MonsterRule> MonsterRules { get; set; } = new();
public List<ItemRule> ItemRules { get; set; } = new();
/// <summary>Loose ammo the monster rules can prefer. Edited by the local monsters window.</summary>
public List<AmmoRule> AmmoRules { get; set; } = new();
public List<ConsumableRule> ConsumableRules { get; set; } = new();
public List<BuffRule> BuffRules { get; set; } = new();
public List<MetaRule> MetaRules { get; set; } = new();
@ -614,6 +626,8 @@ public sealed class MonsterRule
/// 2 Shield, 3 Offhand weapon, 4 None (OffhandRules.Rule*); any other value is a listed
/// item to wield there (the old per-rule picker).</summary>
public int OffhandId { get; set; }
/// <summary>Optional loose ammo stack id for missile combat while this rule matches (0 = auto).</summary>
public int PreferredAmmoItemId { get; set; }
public string PetDamage { get; set; } = "PAuto";
/// <summary>Debuffs the player typed in (Damage panel), comma separated: a spell's base
/// name ("Corrosion Vulnerability Other") casts its best known tier; a full name casts as is.</summary>
@ -629,6 +643,11 @@ public sealed class BuffRule
public sealed class ItemRule
{
/// <summary>Action string for a listed weapon (VirindiTank import and the ILT gear importer).</summary>
public const string WeaponAction = "Weapon";
/// <summary>Action string for a listed shield.</summary>
public const string ShieldAction = "Shield";
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Action { get; set; } = "Loot";
@ -638,6 +657,18 @@ public sealed class ItemRule
/// (not known, or an entry from before sources were kept).</summary>
public string ElementSource { get; set; } = "";
public bool KeepBuffed { get; set; } = true;
/// <summary>True when this row is a shield (off hand), not a main-hand weapon.</summary>
public bool IsShield() => string.Equals(Action, ShieldAction, StringComparison.OrdinalIgnoreCase);
}
/// <summary>Loose ammo the monster rules can prefer (bow, crossbow, atlatl, or Auto).</summary>
public sealed class AmmoRule
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
/// <summary>Bow, Crossbow, Atlatl, or Auto (match any launcher).</summary>
public string Category { get; set; } = "Auto";
}
/// <summary>JSON wire-format types used by the engine-side Avalonia MonstersPanel.</summary>
@ -707,6 +738,17 @@ public sealed class NavBridgePayload
public int ActiveNavIndex { get; set; }
public List<string> NavFiles { get; set; } = new();
public List<NavBridgePoint> Points { get; set; } = new();
/// <summary>NavOverlaySettings.TrackBreadcrumbs (Nav panel "Breadcrumbs" toggle).</summary>
public bool TrackBreadcrumbs { get; set; }
/// <summary>NavOverlaySettings.ShowRouteMarkers (Nav panel "Route overlay" toggle).</summary>
public bool ShowRouteOverlay { get; set; }
/// <summary>Route recording is on (/ra navrec).</summary>
public bool IsRecording { get; set; }
/// <summary>Breadcrumb trail since the last teleport: point count and walked yards.</summary>
public int TrailPoints { get; set; }
public double TrailYards { get; set; }
/// <summary>Result of the last route edit ("Route reversed."), empty once it is a few seconds old.</summary>
public string EditStatus { get; set; } = string.Empty;
}
/// <summary>One-shot command sent from the Avalonia NavPanel to the plugin.</summary>
@ -720,6 +762,12 @@ public sealed class NavCommand
public int InsertAt { get; set; } = -1;
public string NavName { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty; // addChat: the command or text
public bool On { get; set; } // setBreadcrumbs / setRouteOverlay / setRecording
public List<int> Indices { get; set; } = new(); // movePoints / duplicatePoints / deletePoints
public int Delta { get; set; } // movePoints: -1 up, +1 down
public double Seconds { get; set; } // addPause
public double Yards { get; set; } // simplifyRoute tolerance
public bool Reverse { get; set; } // trailToRoute: backtrack (walk the trail in reverse)
}
/// <summary>Bridge payload for the engine-side Avalonia SettingsPanel.</summary>
@ -915,6 +963,21 @@ public sealed class SettingsBridgePayload
// The off hand (only when the sender includes them; today's engine Settings face doesn't).
public string? OffhandDefault { get; set; }
public bool? PreferDualWield { get; set; }
// Ground loot (GroundLootController; also /ra groundloot on|off).
public bool EnableGroundLoot { get; set; }
// Item info: describe an item in chat when it is selected (/ra iteminfo onselect).
public bool ItemInfoOnSelect { get; set; }
// Diagnostics. Stored per PC in Logs\Diagnostics\diagnostics.json (RynthLog), not in
// the character profile; applied only when a value differs, so a save of other
// settings doesn't rewrite that file.
public bool DiagDebugToChat { get; set; }
public bool DiagFileLogAll { get; set; } = true;
/// <summary>Every trace category as "Name=Level" joined by ','; Level 0 = Off, 1 = Trace, 2 = Info.</summary>
public string DiagCategories { get; set; } = string.Empty;
/// <summary>Read-only: the diagnostics folder, shown under the switches.</summary>
public string DiagFolder { get; set; } = string.Empty;
}
public enum MetaConditionType

View file

@ -5,6 +5,9 @@ namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal static class NavCoordinateHelper
{
/// <summary>World Z from the player pose is divided by this to match nav-file height.</summary>
public const double NavZScale = 240.0;
public static bool TryGetNavCoords(RynthCoreHost host, out double northSouth, out double eastWest)
{
northSouth = 0;
@ -19,6 +22,17 @@ internal static class NavCoordinateHelper
return false;
}
/// <summary>Current position as a waypoint would store it (NS/EW map coords + Z in nav units).</summary>
public static bool TryGetNavPosition(RynthCoreHost host, out double northSouth, out double eastWest, out double navZ)
{
navZ = 0;
if (!TryGetNavCoords(host, out northSouth, out eastWest))
return false;
if (host.HasGetPlayerPose && host.TryGetPlayerPose(out _, out _, out _, out float z, out _, out _, out _, out _))
navZ = z / NavZScale;
return true;
}
internal static bool TryConvertPoseToCoords(uint objCellId, float x, float y, out double northSouth, out double eastWest)
{
northSouth = 0;

View file

@ -0,0 +1,109 @@
// NavOverlaySettings.cs — display + recording options for the Navigation window:
// route marker colours, the on-screen waypoint HUD / labels, the guide line to the
// active waypoint, the breadcrumb trail and route recording.
//
// Stored per character inside LegacyUiSettings.NavOverlay (public fields, serialized via
// RynthAiJsonContext IncludeFields). Colours are D3D9 ARGB (0xAARRGGBB).
using System;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// <summary>Persisted Navigation display / breadcrumb / recording options.</summary>
public sealed class NavOverlaySettings
{
// ── Route markers (3D rings + lines) ─────────────────────────────────────
/// <summary>
/// Route overlay master switch (Nav panel "Route overlay"): the route's rings and connecting
/// lines, the waypoint labels and the guide line. The waypoint HUD window has its own switch.
/// </summary>
public bool ShowRouteMarkers = true;
/// <summary>Upper bound on route points drawn around the active waypoint.</summary>
public int MaxRouteMarkers = 128;
public uint ColorRing = 0xFF00FFFF; // cyan
public uint ColorActiveRing = 0xFFFF4444; // red
public uint ColorLine = 0xFF0088FF; // blue
// ── Waypoint HUD + on-screen labels ──────────────────────────────────────
/// <summary>Small movable window: active waypoint, distance, direction arrow, next step.</summary>
public bool ShowHud = true;
/// <summary>Only show the HUD while navigation is enabled (otherwise whenever a route is loaded).</summary>
public bool HudOnlyWhileNavigating;
/// <summary>"#12 · 34yd" text drawn over the upcoming waypoints in the 3D view.</summary>
public bool ShowWaypointLabels = true;
/// <summary>How many upcoming waypoints get a label (active included).</summary>
public int LabelsAhead = 3;
/// <summary>Line from the player to the active waypoint (UB "breadcrumb" line).</summary>
public bool ShowGuideLine = true;
public uint ColorGuide = 0xFFFFDC28; // yellow
// ── Breadcrumb trail ─────────────────────────────────────────────────────
/// <summary>
/// Record where the character walks, independent of any route (Nav panel "Breadcrumbs").
/// While off, the trail is neither extended nor drawn.
/// </summary>
public bool TrackBreadcrumbs = true;
/// <summary>Draw the recorded trail on the ground.</summary>
public bool ShowBreadcrumbs = true;
/// <summary>Minimum distance between trail samples, yards.</summary>
public float BreadcrumbSpacingYards = 3f;
/// <summary>Trail length cap (oldest samples drop off).</summary>
public int BreadcrumbMaxPoints = 400;
/// <summary>Trail segments farther than this from the player are not drawn, yards.</summary>
public float BreadcrumbDrawRangeYards = 150f;
/// <summary>Older trail segments fade out.</summary>
public bool BreadcrumbFade = true;
public uint ColorBreadcrumb = 0xFFFF9A2E; // orange
// ── Route recording ──────────────────────────────────────────────────────
/// <summary>Distance between auto-added Point waypoints while recording, yards.</summary>
public float RecordSpacingYards = 5f;
/// <summary>On a teleport while recording, add a Portal step for the portal used just before it.</summary>
public bool RecordPortals = true;
/// <summary>Pause added after an auto-recorded portal step, ms (0 = none).</summary>
public int RecordPauseAfterPortalMs = 1500;
// Effective visibility (methods, not properties, so the settings JSON doesn't gain fields).
/// <summary>Breadcrumb trail is drawn: tracking on and the trail display on.</summary>
public bool TrailVisible() => TrackBreadcrumbs && ShowBreadcrumbs;
/// <summary>Guide line to the active waypoint is drawn (part of the route overlay).</summary>
public bool GuideLineVisible() => ShowRouteMarkers && ShowGuideLine;
/// <summary>Waypoint labels are drawn (part of the route overlay).</summary>
public bool LabelsVisible() => ShowRouteMarkers && ShowWaypointLabels;
/// <summary>Clamp values a hand-edited or older profile could carry out of range.</summary>
public void Sanitize()
{
MaxRouteMarkers = Math.Clamp(MaxRouteMarkers, 8, 128);
LabelsAhead = Math.Clamp(LabelsAhead, 1, 10);
BreadcrumbSpacingYards = Clamp(BreadcrumbSpacingYards, 0.5f, 50f, 3f);
BreadcrumbMaxPoints = Math.Clamp(BreadcrumbMaxPoints, 20, 2000);
BreadcrumbDrawRangeYards = Clamp(BreadcrumbDrawRangeYards, 20f, 500f, 150f);
RecordSpacingYards = Clamp(RecordSpacingYards, 1f, 50f, 5f);
RecordPauseAfterPortalMs = Math.Clamp(RecordPauseAfterPortalMs, 0, 30000);
}
/// <summary>Display defaults (recording / trail options keep their values).</summary>
public void ResetColors()
{
var d = new NavOverlaySettings();
ColorRing = d.ColorRing; ColorActiveRing = d.ColorActiveRing; ColorLine = d.ColorLine;
ColorGuide = d.ColorGuide; ColorBreadcrumb = d.ColorBreadcrumb;
}
private static float Clamp(float v, float min, float max, float fallback)
=> float.IsNaN(v) ? fallback : Math.Clamp(v, min, max);
/// <summary>D3D9 ARGB → ImGui ABGR (swap red and blue).</summary>
public static uint ArgbToImGui(uint argb)
=> (argb & 0xFF00FF00) | ((argb & 0x00FF0000) >> 16) | ((argb & 0x000000FF) << 16);
/// <summary>Same colour with its alpha scaled by <paramref name="factor"/> (0..1).</summary>
public static uint ScaleAlpha(uint argb, float factor)
{
uint a = (uint)Math.Clamp((argb >> 24) * factor, 0f, 255f);
return (a << 24) | (argb & 0x00FFFFFF);
}
}

View file

@ -0,0 +1,229 @@
// NavRouteEditing.cs — route edit operations for the Navigation window (UB-IT nav builder
// parity plus a few extras): remove / duplicate / move selected, reverse, snap-insert on the
// path, simplify, nearest waypoint, trail → route.
//
// The nav engine reads CurrentRoute.Points on the plugin tick thread while the window edits
// on the render thread, so structural edits never mutate the live list: they build a new
// list and swap the reference (atomic), keeping the active waypoint on the same NavPoint.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
internal static class NavRouteEditing
{
/// <summary>Nav map units → yards (the engine's distance scale).</summary>
public const double NavToYards = 240.0;
public static double DistanceYards(double ns1, double ew1, double ns2, double ew2)
{
double dn = ns2 - ns1, de = ew2 - ew1;
return Math.Sqrt(dn * dn + de * de) * NavToYards;
}
/// <summary>
/// Copy-on-write edit of the current route. <paramref name="edit"/> receives a private copy
/// and returns the new list; the active waypoint follows its NavPoint (or is clamped when
/// that point was removed).
/// </summary>
public static void Apply(LegacyUiSettings s, Func<List<NavPoint>, List<NavPoint>> edit)
{
var route = s.CurrentRoute;
var old = route.Points;
int oldActive = s.ActiveNavIndex;
NavPoint? active = oldActive >= 0 && oldActive < old.Count ? old[oldActive] : null;
var next = edit(new List<NavPoint>(old));
route.Points = next;
int ai = active != null ? next.IndexOf(active) : -1;
s.ActiveNavIndex = ai >= 0 ? ai : Math.Clamp(oldActive, 0, Math.Max(0, next.Count - 1));
}
/// <summary>Field-for-field copy (NavPoint is a plain DTO).</summary>
public static NavPoint Clone(NavPoint p) => new()
{
Type = p.Type, NS = p.NS, EW = p.EW, Z = p.Z,
SpellId = p.SpellId, PauseTimeMs = p.PauseTimeMs, ChatCommand = p.ChatCommand,
TargetName = p.TargetName, ObjectClass = p.ObjectClass, IsTie = p.IsTie, VendorId = p.VendorId,
PortalExitNS = p.PortalExitNS, PortalExitEW = p.PortalExitEW, PortalExitZ = p.PortalExitZ,
};
public static List<NavPoint> Remove(List<NavPoint> list, HashSet<NavPoint> sel)
{
list.RemoveAll(sel.Contains);
return list;
}
/// <summary>Each selected point gets a copy right after it; returns the copies via <paramref name="copies"/>.</summary>
public static List<NavPoint> Duplicate(List<NavPoint> list, HashSet<NavPoint> sel, List<NavPoint> copies)
{
var result = new List<NavPoint>(list.Count + sel.Count);
foreach (var p in list)
{
result.Add(p);
if (!sel.Contains(p)) continue;
var c = Clone(p);
result.Add(c);
copies.Add(c);
}
return result;
}
/// <summary>Moves every selected point one slot up (delta -1) or down (+1), keeping their order;
/// a selected point already at the edge (or blocked by another selected one there) stays put.</summary>
public static List<NavPoint> Move(List<NavPoint> list, HashSet<NavPoint> sel, int delta)
{
if (delta < 0)
{
for (int i = 1; i < list.Count; i++)
if (sel.Contains(list[i]) && !sel.Contains(list[i - 1]))
(list[i - 1], list[i]) = (list[i], list[i - 1]);
}
else
{
for (int i = list.Count - 2; i >= 0; i--)
if (sel.Contains(list[i]) && !sel.Contains(list[i + 1]))
(list[i + 1], list[i]) = (list[i], list[i + 1]);
}
return list;
}
public static List<NavPoint> Reverse(List<NavPoint> list)
{
list.Reverse();
return list;
}
/// <summary>Nearest travel Point to the given position, or -1 when the route has none.</summary>
public static int NearestPointIndex(IReadOnlyList<NavPoint> list, double ns, double ew)
{
int best = -1;
double bestD = double.MaxValue;
for (int i = 0; i < list.Count; i++)
{
var p = list[i];
if (p.Type != NavPointType.Point) continue;
double d = DistanceYards(ns, ew, p.NS, p.EW);
if (d < bestD) { bestD = d; best = i; }
}
return best;
}
/// <summary>
/// UB-IT "snap to path": projects the position onto every Point→Point leg (NS/EW plane),
/// and inserts a Point at the closest spot (Z interpolated) before the leg's far end.
/// Refuses when the spot lands within <paramref name="minGapYards"/> of an existing point.
/// </summary>
public static bool TrySnapInsert(List<NavPoint> list, double ns, double ew, double minGapYards,
out NavPoint? inserted, out string error)
{
inserted = null;
error = string.Empty;
int bestLeg = -1;
double bestDist = double.MaxValue, bestT = 0;
for (int i = 0; i + 1 < list.Count; i++)
{
NavPoint a = list[i], b = list[i + 1];
if (a.Type != NavPointType.Point || b.Type != NavPointType.Point) continue;
double vn = b.NS - a.NS, ve = b.EW - a.EW;
double len2 = vn * vn + ve * ve;
double t = len2 < 1e-12 ? 0 : Math.Clamp(((ns - a.NS) * vn + (ew - a.EW) * ve) / len2, 0, 1);
double d = DistanceYards(ns, ew, a.NS + vn * t, a.EW + ve * t);
if (d < bestDist) { bestDist = d; bestLeg = i; bestT = t; }
}
if (bestLeg < 0) { error = "The route has no Point→Point leg to snap onto."; return false; }
NavPoint pa = list[bestLeg], pb = list[bestLeg + 1];
var p = new NavPoint
{
Type = NavPointType.Point,
NS = pa.NS + (pb.NS - pa.NS) * bestT,
EW = pa.EW + (pb.EW - pa.EW) * bestT,
Z = pa.Z + (pb.Z - pa.Z) * bestT,
};
if (DistanceYards(p.NS, p.EW, pa.NS, pa.EW) < minGapYards || DistanceYards(p.NS, p.EW, pb.NS, pb.EW) < minGapYards)
{
error = $"Closest path spot is on waypoint {(bestT < 0.5 ? bestLeg : bestLeg + 1)} already.";
return false;
}
list.Insert(bestLeg + 1, p);
inserted = p;
return true;
}
/// <summary>
/// Douglas–Peucker over each run of consecutive Points (action steps split runs and are
/// never touched; run endpoints are kept). Removes Points that deviate less than
/// <paramref name="toleranceYards"/> from the simplified line. Returns the removed count.
/// </summary>
public static int Simplify(List<NavPoint> list, double toleranceYards, NavPoint? keep)
{
var drop = new HashSet<NavPoint>();
int runStart = -1;
for (int i = 0; i <= list.Count; i++)
{
bool isPoint = i < list.Count && list[i].Type == NavPointType.Point;
if (isPoint && runStart < 0) runStart = i;
if (!isPoint && runStart >= 0)
{
if (i - 1 - runStart >= 2)
DouglasPeucker(list, runStart, i - 1, toleranceYards, drop);
runStart = -1;
}
}
if (keep != null) drop.Remove(keep); // never remove the active waypoint
list.RemoveAll(drop.Contains);
return drop.Count;
}
private static void DouglasPeucker(List<NavPoint> list, int first, int last, double tol, HashSet<NavPoint> drop)
{
// Iterative stack so long recorded runs can't overflow the stack.
var stack = new Stack<(int, int)>();
stack.Push((first, last));
while (stack.Count > 0)
{
var (a, b) = stack.Pop();
if (b - a < 2) continue;
double maxD = -1;
int maxI = -1;
for (int i = a + 1; i < b; i++)
{
double d = SegmentDistanceYards(list[i], list[a], list[b]);
if (d > maxD) { maxD = d; maxI = i; }
}
if (maxD > tol)
{
stack.Push((a, maxI));
stack.Push((maxI, b));
}
else
{
for (int i = a + 1; i < b; i++) drop.Add(list[i]);
}
}
}
/// <summary>Horizontal distance from <paramref name="p"/> to segment a–b, yards.</summary>
private static double SegmentDistanceYards(NavPoint p, NavPoint a, NavPoint b)
{
double vn = b.NS - a.NS, ve = b.EW - a.EW;
double len2 = vn * vn + ve * ve;
double t = len2 < 1e-12 ? 0 : Math.Clamp(((p.NS - a.NS) * vn + (p.EW - a.EW) * ve) / len2, 0, 1);
return DistanceYards(p.NS, p.EW, a.NS + vn * t, a.EW + ve * t);
}
/// <summary>Total walking length of the route's Point→Point legs, yards.</summary>
public static double PathLengthYards(IReadOnlyList<NavPoint> list)
{
double total = 0;
for (int i = 0; i + 1 < list.Count; i++)
{
NavPoint a = list[i], b = list[i + 1];
if (a.Type == NavPointType.Point && b.Type == NavPointType.Point)
total += DistanceYards(a.NS, a.EW, b.NS, b.EW);
}
return total;
}
}

View file

@ -17,6 +17,14 @@ namespace RynthCore.Plugin.RynthAi;
[JsonSerializable(typeof(MetaRuleDto))]
[JsonSerializable(typeof(MetaCommand))]
[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Meta.MetaScheduleConfig))]
// UB seed, translation, diagnostics, ILT Hub, HUD and item info files persist through this
// context (NativeAOT cannot reflect).
[JsonSerializable(typeof(RynthCore.CreatureSeed.UbMobSeedFile))]
[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Translate.TranslateSettings))]
[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.RynthLogConfig))]
[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Huds.HudState))]
[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.IltHub.IltHubState))]
[JsonSerializable(typeof(System.Collections.Generic.List<RynthCore.Plugin.RynthAi.IltHub.IltBankTransaction>), TypeInfoPropertyName = "IltBankTransactionList")]
[JsonSourceGenerationOptions(
WriteIndented = true,
IncludeFields = true,

View file

@ -1379,7 +1379,7 @@ public sealed class SalvageManager
return name.Contains("Salvage (", StringComparison.OrdinalIgnoreCase);
}
private void Log(string message) => _host.Log(message);
private void Log(string message) => RynthLog.Write(LogCat.Salvage, message);
private void NoteError(string what)
{

View file

@ -0,0 +1,237 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi.Maps;
/// <summary>
/// One D3D9 POOL_MANAGED A8R8G8B8 texture baked from a single Z-layer's floor cells.
/// Each texel covers one GridCell (0.5 AC units). Edge cells (cells bordering empty space)
/// use the bright wall colour; interior cells use the semi-transparent fill colour;
/// empty cells are fully transparent (alpha=0).
///
/// Displayed via dl.AddImageQuad — O(1) vertices per layer vs O(strips + edges) otherwise.
/// Disk-cached to <SuiteDir>\RynthAi\Maps\{landblock:X8}_{layerIdx}.bin so
/// re-entering a dungeon skips the rasterise step.
/// </summary>
internal sealed class DungeonMapTexture : IDisposable
{
private const float GridCell = 0.5f;
private static readonly string CacheDir = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"Maps");
private const uint Magic = 0x524D5458u; // "XTMR"
// D3D9 vtable indices on IDirect3DDevice9 / IDirect3DTexture9
private const int VtCreateTexture = 23;
private const int VtLockRect = 19;
private const int VtUnlockRect = 20;
private const int VtRelease = 2;
private const uint D3DFMT_A8R8G8B8 = 21;
private const uint D3DPOOL_MANAGED = 1;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage, uint fmt, uint pool, out IntPtr ppTex, IntPtr shared);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int LockRectD(IntPtr tex, uint level, ref D3DLockedRect locked, IntPtr pRect, uint flags);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int UnlockRectD(IntPtr tex, uint level);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseD(IntPtr obj);
[StructLayout(LayoutKind.Sequential)]
private struct D3DLockedRect { public int Pitch; public IntPtr pBits; }
// ── D3D9 A8R8G8B8 colour helpers (ARGB uint: A<<24|R<<16|G<<8|B) ─────
private static uint Argb(float r, float g, float b, float a) =>
((uint)(a * 255f) << 24) | ((uint)(r * 255f) << 16) | ((uint)(g * 255f) << 8) | (uint)(b * 255f);
// Match DungeonMapUi colour definitions
private static readonly uint FillFlat = Argb(0.18f, 0.55f, 0.22f, 0.40f);
private static readonly uint FillSlopeUp = Argb(0.55f, 0.12f, 0.08f, 0.40f);
private static readonly uint FillSlopeDown = Argb(0.10f, 0.50f, 0.15f, 0.40f);
private static readonly uint EdgeFlat = Argb(0.55f, 0.80f, 1.00f, 1.00f);
private static readonly uint EdgeSlopeUp = Argb(1.00f, 0.35f, 0.25f, 1.00f);
private static readonly uint EdgeSlopeDown = Argb(0.25f, 1.00f, 0.35f, 1.00f);
// World bounds of the baked area
public float WorldX0, WorldY0, WorldX1, WorldY1;
public IntPtr TexId => _tex;
private IntPtr _tex;
private DungeonMapTexture() {}
/// <summary>
/// Returns a texture for the given floor-cell grid. Checks the disk cache first;
/// if absent, rasterises, uploads to D3D9, and saves to disk.
/// Returns null if device is invalid or texture upload fails.
/// </summary>
public static DungeonMapTexture? GetOrBuild(
IntPtr device,
Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells,
uint landblock, int layerIdx)
{
if (device == IntPtr.Zero || cells.Count == 0) return null;
// Bounding box
int xMin = int.MaxValue, xMax = int.MinValue;
int yMin = int.MaxValue, yMax = int.MinValue;
foreach (var (gx, gy) in cells.Keys)
{
if (gx < xMin) xMin = gx; if (gx > xMax) xMax = gx;
if (gy < yMin) yMin = gy; if (gy > yMax) yMax = gy;
}
int w = xMax - xMin + 1, h = yMax - yMin + 1;
if (w <= 0 || h <= 0 || w > 8192 || h > 8192) return null;
// Try disk cache first (only valid when dimensions match the dat-computed bounds)
var cached = TryLoadFromDisk(device, landblock, layerIdx, xMin, yMin, w, h);
if (cached != null) return cached;
// Rasterise → upload → cache
var pixels = Rasterise(cells, xMin, yMax, w, h);
IntPtr tex = Upload(device, w, h, pixels);
if (tex == IntPtr.Zero) return null;
SaveToDisk(landblock, layerIdx, xMin, yMin, w, h, pixels);
return new DungeonMapTexture
{
_tex = tex,
WorldX0 = xMin * GridCell,
WorldY0 = yMin * GridCell,
WorldX1 = (xMax + 1) * GridCell,
WorldY1 = (yMax + 1) * GridCell,
};
}
public void Dispose()
{
if (_tex == IntPtr.Zero) return;
try { GetVtFunc<ReleaseD>(_tex, VtRelease)(_tex); } catch { }
_tex = IntPtr.Zero;
}
// ── Rasterisation ─────────────────────────────────────────────────────
private static uint[] Rasterise(
Dictionary<(int gx, int gy), DungeonMapUi.CellType> cells,
int xMin, int yMax, int w, int h)
{
var pixels = new uint[w * h]; // 0 = transparent
foreach (var ((gx, gy), ctype) in cells)
{
bool isEdge = !cells.ContainsKey((gx + 1, gy))
|| !cells.ContainsKey((gx - 1, gy))
|| !cells.ContainsKey((gx, gy + 1))
|| !cells.ContainsKey((gx, gy - 1));
uint col = isEdge
? ctype switch
{
DungeonMapUi.CellType.SlopeUp => EdgeSlopeUp,
DungeonMapUi.CellType.SlopeDown => EdgeSlopeDown,
_ => EdgeFlat,
}
: ctype switch
{
DungeonMapUi.CellType.SlopeUp => FillSlopeUp,
DungeonMapUi.CellType.SlopeDown => FillSlopeDown,
_ => FillFlat,
};
// Row 0 = northernmost cells (highest gy), so flip Y
pixels[(yMax - gy) * w + (gx - xMin)] = col;
}
return pixels;
}
// ── D3D9 upload ───────────────────────────────────────────────────────
private static unsafe IntPtr Upload(IntPtr device, int w, int h, uint[] pixels)
{
try
{
int hr = GetVtFunc<CreateTextureD>(device, VtCreateTexture)(
device, (uint)w, (uint)h, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out IntPtr tex, IntPtr.Zero);
if (hr < 0 || tex == IntPtr.Zero) return IntPtr.Zero;
var locked = new D3DLockedRect();
hr = GetVtFunc<LockRectD>(tex, VtLockRect)(tex, 0, ref locked, IntPtr.Zero, 0);
if (hr < 0) { GetVtFunc<ReleaseD>(tex, VtRelease)(tex); return IntPtr.Zero; }
// Copy row by row — pitch may be wider than w*4
for (int row = 0; row < h; row++)
{
IntPtr dst = IntPtr.Add(locked.pBits, row * locked.Pitch);
fixed (uint* src = &pixels[row * w])
Buffer.MemoryCopy(src, (void*)dst, (nuint)(w * 4), (nuint)(w * 4));
}
GetVtFunc<UnlockRectD>(tex, VtUnlockRect)(tex, 0);
return tex;
}
catch { return IntPtr.Zero; }
}
// ── Disk cache ────────────────────────────────────────────────────────
private static DungeonMapTexture? TryLoadFromDisk(
IntPtr device, uint lb, int layerIdx,
int expXMin, int expYMin, int expW, int expH)
{
try
{
string path = Path.Combine(CacheDir, $"{lb:X8}_{layerIdx}.bin");
if (!File.Exists(path)) return null;
using var br = new BinaryReader(File.OpenRead(path));
if (br.ReadUInt32() != Magic) return null;
int xMin = br.ReadInt32(), yMin = br.ReadInt32();
int w = br.ReadInt32(), h = br.ReadInt32();
// Invalidate if bounds no longer match the dat
if (w != expW || h != expH || xMin != expXMin || yMin != expYMin) return null;
if (br.BaseStream.Length < 20L + (long)w * h * 4) return null;
var pixels = new uint[w * h];
for (int i = 0; i < pixels.Length; i++) pixels[i] = br.ReadUInt32();
IntPtr tex = Upload(device, w, h, pixels);
if (tex == IntPtr.Zero) return null;
return new DungeonMapTexture
{
_tex = tex,
WorldX0 = xMin * GridCell,
WorldY0 = yMin * GridCell,
WorldX1 = (xMin + w) * GridCell,
WorldY1 = (yMin + h) * GridCell,
};
}
catch { return null; }
}
private static void SaveToDisk(uint lb, int layerIdx, int xMin, int yMin, int w, int h, uint[] pixels)
{
try
{
Directory.CreateDirectory(CacheDir);
string path = Path.Combine(CacheDir, $"{lb:X8}_{layerIdx}.bin");
using var bw = new BinaryWriter(File.Open(path, FileMode.Create));
bw.Write(Magic); bw.Write(xMin); bw.Write(yMin); bw.Write(w); bw.Write(h);
foreach (uint px in pixels) bw.Write(px);
}
catch { }
}
// ── VTable helper ─────────────────────────────────────────────────────
private static unsafe TDelegate GetVtFunc<TDelegate>(IntPtr obj, int idx) where TDelegate : Delegate
{
void** vt = *(void***)obj;
return Marshal.GetDelegateForFunctionPointer<TDelegate>((IntPtr)vt[idx]);
}
}

View file

@ -7,6 +7,7 @@ using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.CreatureData;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi.Meta;
@ -111,7 +112,7 @@ internal sealed class MetaManager
// §3.3: surface schema/enum drift once per session instead of letting a
// mid-enum insert silently corrupt every saved meta + the JSON bridge.
if (MetaSchema.DriftError != null)
_host.Log($"[Meta] SCHEMA DRIFT — fix MetaSchema/enum alignment: {MetaSchema.DriftError}");
RynthLog.Write(LogCat.Meta, $"[Meta] SCHEMA DRIFT — fix MetaSchema/enum alignment: {MetaSchema.DriftError}");
}
public void SetMtCommandHandler(Func<string, bool> handler) => _mtCommandHandler = handler;
@ -389,7 +390,7 @@ internal sealed class MetaManager
// A condition/action threw. Localise it to this tick instead of
// letting partial state (half-applied SetState, pushed call stack)
// persist. ForceStateReset recomputes HasFired cleanly next tick.
_host.Log($"[Meta] Think crashed in '{_settings.CurrentState}': {ex.GetType().Name}: {ex.Message}");
RynthLog.Write(LogCat.Meta, $"[Meta] Think crashed in '{_settings.CurrentState}': {ex.GetType().Name}: {ex.Message}");
if (_settings.MetaDebug)
_host.WriteToChat($"[Meta] Think exception: {ex.Message}", 1);
_lastExprError = $"Think: {ex.GetType().Name}: {Truncate(ex.Message, 100)}";
@ -850,7 +851,7 @@ internal sealed class MetaManager
{
if (string.IsNullOrWhiteSpace(rule.ActionData))
{
_host.Log("[Meta] EmbedNav: empty ActionData, ignored");
RynthLog.Write(LogCat.Meta, "[Meta] EmbedNav: empty ActionData, ignored");
break;
}
string routeName = rule.ActionData.Split(';')[0];
@ -886,13 +887,13 @@ internal sealed class MetaManager
_settings.CurrentRoute = newRoute;
_settings.ActiveNavIndex = StartIndexForRoute(newRoute);
_settings.EnableNavigation = true;
_host.Log($"[Meta] EmbedNav: loaded '{routeName}' ({newRoute.Points.Count} pts, was {priorPoints})");
RynthLog.Write(LogCat.Meta, $"[Meta] EmbedNav: loaded '{routeName}' ({newRoute.Points.Count} pts, was {priorPoints})");
_host.WriteToChat($"[RynthAi Meta] Route \u2192 {routeName} ({newRoute.Points.Count} pts)", 1);
break;
}
// Fallback: a standalone .nav file in NavProfiles.
string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
string navFolder = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"NavProfiles");
string fullPath = Path.Combine(navFolder, routeName + ".nav");
if (File.Exists(fullPath))
{
@ -901,19 +902,19 @@ internal sealed class MetaManager
_settings.CurrentRoute = newRoute;
_settings.ActiveNavIndex = StartIndexForRoute(newRoute);
_settings.EnableNavigation = true;
_host.Log($"[Meta] EmbedNav: loaded file '{routeName}' ({newRoute.Points.Count} pts, was {priorPoints})");
RynthLog.Write(LogCat.Meta, $"[Meta] EmbedNav: loaded file '{routeName}' ({newRoute.Points.Count} pts, was {priorPoints})");
_host.WriteToChat($"[RynthAi Meta] Route \u2192 {routeName} ({newRoute.Points.Count} pts)", 1);
}
else
{
string keys = string.Join(", ", _settings.EmbeddedNavs.Keys);
_host.Log($"[Meta] EmbedNav: route '{routeName}' not found. Embedded keys: [{keys}]");
RynthLog.Write(LogCat.Meta, $"[Meta] EmbedNav: route '{routeName}' not found. Embedded keys: [{keys}]");
_host.WriteToChat($"[RynthAi Meta] Route missing: {routeName}", 1);
}
}
catch (Exception ex)
{
_host.Log($"[Meta] EmbedNav error: {ex.Message}");
RynthLog.Write(LogCat.Meta, $"[Meta] EmbedNav error: {ex.Message}");
_host.WriteToChat($"[RynthAi Meta] Load Error: {ex.Message}", 1);
}
break;
@ -1023,7 +1024,7 @@ internal sealed class MetaManager
_lastExprError = $"{rule.Action} ignored — VTank Views are not supported in RynthAi";
_lastExprErrorAt = Clock();
_host.WriteToChat("[RynthAi] Meta uses VTank Views (CreateView/DestroyView) — not supported; those actions are ignored.", 1);
_host.Log($"[Meta] {rule.Action} ignored — VTank Views unsupported");
RynthLog.Write(LogCat.Meta, $"[Meta] {rule.Action} ignored — VTank Views unsupported");
}
break;
}
@ -1091,7 +1092,7 @@ internal sealed class MetaManager
parts[2].Equals("load", StringComparison.OrdinalIgnoreCase))
{
string name = string.Join(" ", parts, 3, parts.Length - 3);
string metaDir = @"C:\Games\RynthSuite\RynthAi\MetaFiles";
string metaDir = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"MetaFiles");
string afPath = Path.Combine(metaDir, name + ".af");
string metPath = Path.Combine(metaDir, name + ".met");

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using RynthCore.PluginSdk;
@ -8,6 +9,8 @@ namespace RynthCore.Plugin.RynthAi.Meta;
internal sealed class QuestRecord
{
public string Key = "";
/// <summary>Server-supplied description from /myquests (may be empty).</summary>
public string Description = "";
public int Solves;
public int MaxSolves;
public DateTime CompletedOn = DateTime.MinValue;
@ -24,6 +27,13 @@ internal sealed class QuestRecord
return false;
return !(MaxSolves == 1 && Solves <= 1);
}
/// <summary>Time until the flag can be solved again (zero when ready).</summary>
public TimeSpan TimeUntilReady()
{
var left = (CompletedOn + RepeatTime) - DateTime.UtcNow;
return left > TimeSpan.Zero ? left : TimeSpan.Zero;
}
}
/// <summary>
@ -44,21 +54,44 @@ internal sealed class QuestTracker
private bool _refreshing;
private bool _gotFirstQuest;
private bool _quietRefresh;
private DateTime _lastLineTime;
private DateTime _refreshStarted;
public bool IsRefreshing => _refreshing;
/// <summary>The server answered that /myquests is not enabled.</summary>
public bool Disabled { get; private set; }
/// <summary>UTC time the last refresh finished with data (MinValue = never).</summary>
public DateTime LastRefreshUtc { get; private set; } = DateTime.MinValue;
/// <summary>Last refresh outcome text for the ILT Hub ("12 flags", "rate limited", ...).</summary>
public string LastStatus { get; private set; } = "not refreshed";
/// <summary>Number of cached flags.</summary>
public int Count => _flags.Count;
/// <summary>Raised on the pump thread when a refresh ends. The ILT Hub reads Disabled and Count.</summary>
public event Action? RefreshCompleted;
public QuestTracker(RynthCoreHost host) => _host = host;
/// <summary>
/// Issues /myquests to the server to populate the quest flag cache.
/// No-ops if already refreshing or InvokeChatParser is not available.
/// </summary>
public void Refresh()
public void Refresh() => Refresh(quiet: false);
/// <summary>
/// Issues /myquests. <paramref name="quiet"/> asks <see cref="OnChatLine"/> to report
/// those lines as eatable so the ILT Hub can hide its own poll.
/// </summary>
public void Refresh(bool quiet)
{
if (_refreshing || !_host.HasInvokeChatParser)
return;
_quietRefresh = quiet;
ExpectReply();
RefreshSent?.Invoke();
_host.InvokeChatParser("/myquests");
@ -83,33 +116,43 @@ internal sealed class QuestTracker
/// Feed every incoming chat line here. Quest lines are parsed and cached;
/// terminal lines (empty list, rate limit, etc.) end the refresh early.
/// </summary>
public void OnChatLine(string text)
public bool OnChatLine(string text)
{
if (!_refreshing)
return;
return false;
if (text.Contains("Quest list is empty") ||
text.Contains("The command \"myquests\" is not currently enabled"))
if (text.Contains("Quest list is empty"))
{
_refreshing = false;
return;
bool quiet = _quietRefresh;
Finish("quest list is empty", gotData: true);
return quiet;
}
if (text.Contains("The command \"myquests\" is not currently enabled"))
{
Disabled = true;
bool quiet = _quietRefresh;
Finish("/myquests is disabled on this server", gotData: false);
return quiet;
}
if (text.Contains("This command may only be run once every"))
{
_refreshing = false;
return;
bool quiet = _quietRefresh;
Finish("rate limited by the server (try again in a minute)", gotData: false);
return quiet;
}
var m = QuestLineRegex.Match(text);
if (!m.Success)
return;
return false;
_gotFirstQuest = true;
_lastLineTime = DateTime.UtcNow;
var rec = new QuestRecord();
rec.Key = m.Groups["key"].Value.ToLowerInvariant();
rec.Description = m.Groups["description"].Value.Trim().Trim('"');
int.TryParse(m.Groups["solves"].Value, out rec.Solves);
int.TryParse(m.Groups["maxSolves"].Value, out rec.MaxSolves);
@ -126,6 +169,7 @@ internal sealed class QuestTracker
rec.RepeatTime = TimeSpan.FromSeconds(rt);
_flags[rec.Key] = rec;
return _quietRefresh;
}
/// <summary>
@ -142,15 +186,32 @@ internal sealed class QuestTracker
if (_gotFirstQuest)
{
if ((now - _lastLineTime).TotalSeconds >= 1.0)
_refreshing = false;
Finish($"{Count} flags", gotData: true);
}
else
{
if ((now - _refreshStarted).TotalSeconds >= 15.0)
_refreshing = false;
Finish("no reply from server", gotData: false);
}
}
private void Finish(string status, bool gotData)
{
_refreshing = false;
_quietRefresh = false;
LastStatus = status;
if (gotData)
{
Disabled = false;
LastRefreshUtc = DateTime.UtcNow;
}
try { RefreshCompleted?.Invoke(); }
catch (Exception ex) { _host.Log($"[RynthAi] QuestTracker RefreshCompleted threw: {ex.Message}"); }
}
/// <summary>Copy of every cached record for the ILT Hub quest list.</summary>
public QuestRecord[] Snapshot() => _flags.Values.ToArray();
/// <summary>Returns true if the key exists in the cached quest flag list.</summary>
public bool HasFlag(string key) => _flags.ContainsKey(key.ToLowerInvariant());

View file

@ -0,0 +1,286 @@
// NavBreadcrumbTracker.cs — position sampling for the Navigation window:
//
// * Breadcrumb trail: where the character has walked (spacing / max points / teleport
// breaks), drawn by NavOverlayRenderer and exportable as a route ("backtrack").
// * Route recording (UB-IT KeyStoreRecorder style): while LegacyUiSettings.IsRecordingNav
// is on, appends Point waypoints every RecordSpacingYards and, on a teleport, a Portal
// step for the portal selected just before it (plus an optional pause).
//
// Runs on the plugin tick thread. The render thread only reads the published trail array
// (copy-on-write), so no locks are needed.
using System;
using System.Collections.Generic;
using System.Threading;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>One trail sample. Z is the raw world height (marker frame = Z, not Z/240).</summary>
internal readonly record struct NavCrumb(double NS, double EW, float Z, bool SegmentStart);
internal sealed class NavBreadcrumbTracker
{
/// <summary>A position jump larger than this between ticks is a teleport (engine uses the same 50 yd).</summary>
private const double TeleportYards = 50.0;
/// <summary>A portal selected longer ago than this isn't credited for a recorded teleport.</summary>
private const long PortalCreditMs = 20_000;
/// <summary>Recording autosaves to the route file every this many added waypoints.</summary>
private const int RecordAutosaveEvery = 10;
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
/// <summary>Object id → (name, Decal object class) when it is a portal, else null.</summary>
private readonly Func<uint, (string Name, int ObjectClass)?> _describePortal;
private readonly Action<string> _chat;
// ── Trail (tick thread owns _crumbs; _snapshot is what the renderer reads) ──
private readonly List<NavCrumb> _crumbs = new();
private NavCrumb[] _snapshot = Array.Empty<NavCrumb>();
private bool _breakNext = true;
private double _trailYards;
// ── Teleport detection ──
private double _lastNS = double.NaN, _lastEW, _lastZ;
private bool _wasPortaling;
// ── Recording ──
private bool _recordingActive;
private double _recNS = double.NaN, _recEW;
private int _recAdded, _recSinceSave;
private (string Name, int Cls, double NS, double EW, double NavZ, long At)? _portalCandidate;
public NavBreadcrumbTracker(RynthCoreHost host, LegacyUiSettings settings,
Func<uint, (string Name, int ObjectClass)?> describePortal, Action<string> chat)
{
_host = host;
_settings = settings;
_describePortal = describePortal;
_chat = chat;
}
/// <summary>Current trail, oldest first (safe to read from the render thread).</summary>
public NavCrumb[] Trail => Volatile.Read(ref _snapshot);
/// <summary>Walked length of the trail (teleport jumps excluded), yards.</summary>
public double TrailYards => Volatile.Read(ref _trailYards);
/// <summary>Waypoints added by the current recording session.</summary>
public int RecordedCount => Volatile.Read(ref _recAdded);
/// <summary>Clear request from the UI thread; applied on the next tick.</summary>
public void RequestClear() => Interlocked.Exchange(ref _clearRequested, 1);
private int _clearRequested;
public void Tick()
{
var o = _settings.NavOverlay;
if (Interlocked.Exchange(ref _clearRequested, 0) == 1) ClearTrail();
// Portal space: no position worth recording, but remember we passed through it.
if (_host.HasIsPortaling && _host.IsPortaling())
{
_wasPortaling = true;
return;
}
if (!NavCoordinateHelper.TryGetNavCoords(_host, out double ns, out double ew)) return;
if (!_host.TryGetPlayerPose(out uint cell, out _, out _, out float z, out _, out _, out _, out _)) return;
if ((cell >> 16) == 0) return;
bool hadLast = !double.IsNaN(_lastNS);
bool teleported = _wasPortaling
|| (hadLast && NavRouteEditing.DistanceYards(_lastNS, _lastEW, ns, ew) > TeleportYards);
_wasPortaling = false;
double preNS = _lastNS, preEW = _lastEW, preZ = _lastZ;
_lastNS = ns; _lastEW = ew; _lastZ = z;
if (teleported) _breakNext = true;
// While tracking is off, keep a break pending so the trail resumes as a new segment
// instead of joining across the untracked stretch.
if (o.TrackBreadcrumbs) SampleCrumb(ns, ew, z, o);
else _breakNext = true;
TickRecording(ns, ew, z, o, teleported && hadLast, preNS, preEW, preZ);
}
// ═══════════════════════════════════════════════════════════════════
// Breadcrumb trail
// ═══════════════════════════════════════════════════════════════════
private void SampleCrumb(double ns, double ew, float z, NavOverlaySettings o)
{
if (_crumbs.Count > 0 && !_breakNext)
{
var last = _crumbs[^1];
double d = NavRouteEditing.DistanceYards(last.NS, last.EW, ns, ew);
if (d < o.BreadcrumbSpacingYards) return;
_trailYards += d;
}
_crumbs.Add(new NavCrumb(ns, ew, z, _breakNext || _crumbs.Count == 0));
_breakNext = false;
int over = _crumbs.Count - o.BreadcrumbMaxPoints;
if (over > 0)
{
_crumbs.RemoveRange(0, over);
if (_crumbs.Count > 0 && !_crumbs[0].SegmentStart)
_crumbs[0] = _crumbs[0] with { SegmentStart = true };
_trailYards = MeasureTrail(_crumbs);
}
Volatile.Write(ref _snapshot, _crumbs.ToArray());
}
private void ClearTrail()
{
_crumbs.Clear();
_trailYards = 0;
_breakNext = true;
Volatile.Write(ref _snapshot, Array.Empty<NavCrumb>());
}
private static double MeasureTrail(List<NavCrumb> crumbs)
{
double total = 0;
for (int i = 1; i < crumbs.Count; i++)
if (!crumbs[i].SegmentStart)
total += NavRouteEditing.DistanceYards(crumbs[i - 1].NS, crumbs[i - 1].EW, crumbs[i].NS, crumbs[i].EW);
return total;
}
/// <summary>
/// Trail → waypoints (Z converted to nav units), thinned to <paramref name="spacingYards"/>.
/// <paramref name="reverse"/> builds a backtrack (newest first). Teleport breaks end the
/// export so the route never asks the bot to walk across a portal jump.
/// </summary>
public static List<NavPoint> TrailToPoints(NavCrumb[] trail, double spacingYards, bool reverse)
{
var pts = new List<NavPoint>();
if (trail.Length == 0) return pts;
// Newest unbroken segment only: from the last segment start to the end.
int start = 0;
for (int i = trail.Length - 1; i >= 0; i--)
if (trail[i].SegmentStart) { start = i; break; }
NavCrumb? lastKept = null;
for (int i = start; i < trail.Length; i++)
{
var c = trail[i];
bool isLast = i == trail.Length - 1;
if (lastKept is NavCrumb k && !isLast
&& NavRouteEditing.DistanceYards(k.NS, k.EW, c.NS, c.EW) < spacingYards)
continue;
pts.Add(new NavPoint { Type = NavPointType.Point, NS = c.NS, EW = c.EW, Z = c.Z / NavCoordinateHelper.NavZScale });
lastKept = c;
}
if (reverse) pts.Reverse();
return pts;
}
// ═══════════════════════════════════════════════════════════════════
// Route recording
// ═══════════════════════════════════════════════════════════════════
private void TickRecording(double ns, double ew, float z, NavOverlaySettings o,
bool teleported, double preNS, double preEW, double preZ)
{
if (!_settings.IsRecordingNav)
{
if (_recordingActive) StopRecordingSession();
return;
}
if (!_recordingActive)
{
_recordingActive = true;
_recNS = double.NaN;
_recAdded = 0;
_recSinceSave = 0;
_portalCandidate = null;
RynthLog.Write(LogCat.Navigation, "[NavRecord] recording started.");
}
TrackPortalSelection();
if (teleported)
{
// Portal used just before the jump → Portal step (+ pause); the arrival point
// then records immediately because _recNS is reset.
if (o.RecordPortals && _portalCandidate is { } pc && Environment.TickCount64 - pc.At <= PortalCreditMs)
{
AddRecorded(new NavPoint
{
Type = NavPointType.PortalNPC,
NS = preNS, EW = preEW, Z = preZ / NavCoordinateHelper.NavZScale,
TargetName = pc.Name, ObjectClass = pc.Cls,
PortalExitNS = pc.NS, PortalExitEW = pc.EW, PortalExitZ = pc.NavZ,
});
if (o.RecordPauseAfterPortalMs > 0)
AddRecorded(new NavPoint { Type = NavPointType.Pause, NS = ns, EW = ew, Z = z / NavCoordinateHelper.NavZScale, PauseTimeMs = o.RecordPauseAfterPortalMs });
_chat($"[RynthAi] Nav record: added Portal step '{pc.Name}'.");
}
else
{
_chat("[RynthAi] Nav record: teleport detected — add a Portal or Recall step for it if the route needs one.");
}
_portalCandidate = null;
_recNS = double.NaN;
}
if (!double.IsNaN(_recNS) && NavRouteEditing.DistanceYards(_recNS, _recEW, ns, ew) < o.RecordSpacingYards)
return;
AddRecorded(new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = z / NavCoordinateHelper.NavZScale });
_recNS = ns;
_recEW = ew;
}
/// <summary>Remembers the last selected portal (name, class, position) for the teleport step.</summary>
private void TrackPortalSelection()
{
if (!_host.HasGetSelectedItemId) return;
uint sel = _host.GetSelectedItemId();
if (sel == 0) return;
if (_portalCandidate is { } cur && Environment.TickCount64 - cur.At < 1000) return; // refresh ~1/s
if (_describePortal(sel) is not { } info) return;
double pns = 0, pew = 0, pz = 0;
if (_host.HasGetObjectPosition
&& _host.TryGetObjectPosition(sel, out uint pcell, out float ox, out float oy, out float oz)
&& NavCoordinateHelper.TryConvertPoseToCoords(pcell, ox, oy, out pns, out pew))
pz = oz / NavCoordinateHelper.NavZScale;
_portalCandidate = (info.Name, info.ObjectClass, pns, pew, pz, Environment.TickCount64);
}
private void AddRecorded(NavPoint p)
{
NavRouteEditing.Apply(_settings, list => { list.Add(p); return list; });
Interlocked.Increment(ref _recAdded);
if (++_recSinceSave >= RecordAutosaveEvery)
{
_recSinceSave = 0;
SaveRouteFile();
}
}
/// <summary>Session teardown: saves a recording in progress (no chat — the session is ending).</summary>
public void Shutdown()
{
if (_recordingActive) StopRecordingSession(announce: false);
}
private void StopRecordingSession(bool announce = true)
{
_recordingActive = false;
_portalCandidate = null;
SaveRouteFile();
RynthLog.Write(LogCat.Navigation, $"[NavRecord] recording stopped ({_recAdded} waypoints added).");
if (announce)
_chat($"[RynthAi] Nav record stopped: {_recAdded} waypoints added" +
(string.IsNullOrEmpty(_settings.CurrentNavPath) ? " (route not saved yet — use Save As)." : " and saved."));
}
private void SaveRouteFile()
{
if (string.IsNullOrEmpty(_settings.CurrentNavPath)) return;
try { _settings.CurrentRoute.Save(_settings.CurrentNavPath); }
catch (Exception ex) { RynthLog.Write(LogCat.Navigation, $"[NavRecord] save failed: {ex.Message}"); }
}
}

View file

@ -123,6 +123,10 @@ internal sealed class NavMarkerRenderer
playerNS = playerEW = 0.0;
ringRadius = 0f; heightOffset = 0f;
// Route overlay switched off (Nav panel / "/ra navoverlay off"): no rings or lines.
if (!_settings.NavOverlay.ShowRouteMarkers)
return false;
var r = _settings.CurrentRoute;
if (r?.Points == null || r.Points.Count == 0)
return false;

View file

@ -0,0 +1,354 @@
// NavOverlayRenderer.cs — on-screen navigation aids on top of NavMarkerRenderer's route rings:
//
// * Waypoint HUD: small movable window with the active waypoint, distance, a direction
// arrow relative to the character's facing, the next step, remaining route length,
// breadcrumb / recording status.
// * Waypoint labels: "#12 34yd" over the next N travel points in the 3D view.
// * Guide line: player → active waypoint (UB-IT world-overlay "breadcrumb" line).
// * Breadcrumb trail: NavBreadcrumbTracker samples drawn on the ground, fading with age.
//
// 3D geometry (guide line, trail) is submitted from OnTick through the engine's Nav3D buffer
// (shared budget: 512 lines across all plugins), with an ImGui projected fallback when the
// engine has no Nav3D API. HUD and labels are ImGui and need the overlay.
using System;
using System.IO;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
internal sealed class NavOverlayRenderer
{
/// <summary>Most trail segments submitted per frame (route markers use up to 128 lines).</summary>
private const int MaxTrailLines = 200;
/// <summary>Label text sits this far above the waypoint ring, world units.</summary>
private const float LabelLift = 1.2f;
private readonly RynthCoreHost _host;
private readonly LegacyUiSettings _settings;
private readonly NavBreadcrumbTracker _trail;
public NavOverlayRenderer(RynthCoreHost host, LegacyUiSettings settings, NavBreadcrumbTracker trail)
{
_host = host;
_settings = settings;
_trail = trail;
}
/// <summary>Player frame shared by every pass (marker world frame: X=EW, Y=up, Z=NS).</summary>
private readonly record struct Frame(double NS, double EW, float Px, float Py, float Pz, float HeadingDeg);
private bool TryGetFrame(out Frame f)
{
f = default;
if (_host.HasIsPortaling && _host.IsPortaling()) return false;
if (!NavCoordinateHelper.TryGetNavCoords(_host, out double ns, out double ew)) return false;
if (!_host.TryGetPlayerPose(out uint cell, out float px, out float py, out float pz,
out float qw, out _, out _, out float qz)) return false;
if ((cell >> 16) == 0) return false;
// Physics yaw (CCW from north) → compass heading (0 = north, clockwise), as NavigationEngine.
double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
f = new Frame(ns, ew, px, py, pz, (float)((-yaw + 720.0) % 360.0));
return true;
}
private Vector3 ToWorld(in Frame f, double ns, double ew, float worldY)
=> new(f.Px + (float)((ew - f.EW) * NavRouteEditing.NavToYards), worldY,
f.Py + (float)((ns - f.NS) * NavRouteEditing.NavToYards));
private float WaypointWorldY(NavPoint p) => (float)(p.Z * NavCoordinateHelper.NavZScale) + _settings.NavHeightOffset;
/// <summary>Active waypoint when it is a travel Point, else null.</summary>
private NavPoint? ActivePoint(out int index)
{
var pts = _settings.CurrentRoute?.Points;
index = _settings.ActiveNavIndex;
if (pts == null || index < 0 || index >= pts.Count) return null;
return pts[index];
}
// ═══════════════════════════════════════════════════════════════════
// 3D (tick thread)
// ═══════════════════════════════════════════════════════════════════
/// <summary>Guide line + breadcrumb trail into the Nav3D buffer. Call from OnTick.</summary>
public void SubmitNav3D()
{
if (!_host.HasNav3D) return;
try
{
if (!TryGetFrame(out var f)) return;
var o = _settings.NavOverlay;
float lineThick = _settings.NavLineThickness * 0.01f;
if (o.TrailVisible())
ForEachTrailSegment(f, o, (a, b, fade) =>
_host.Nav3DAddLine(a.X, a.Y, a.Z, b.X, b.Y, b.Z, lineThick * 0.7f,
NavOverlaySettings.ScaleAlpha(o.ColorBreadcrumb, fade)));
if (o.GuideLineVisible() && ActivePoint(out _) is { Type: NavPointType.Point } ap)
{
Vector3 me = new(f.Px, f.Pz + _settings.NavHeightOffset, f.Py);
Vector3 to = ToWorld(f, ap.NS, ap.EW, WaypointWorldY(ap));
_host.Nav3DAddLine(me.X, me.Y, me.Z, to.X, to.Y, to.Z, lineThick * 0.8f, o.ColorGuide);
}
}
catch (Exception ex) { RynthLog.Write(LogCat.Navigation, $"NavOverlay(3D): {ex.Message}"); }
}
/// <summary>
/// Newest-first walk of the trail within draw range, capped at <see cref="MaxTrailLines"/>;
/// no segment crosses a teleport break. <c>fade</c> is 1 for the newest segment.
/// </summary>
private void ForEachTrailSegment(in Frame f, NavOverlaySettings o, Action<Vector3, Vector3, float> draw)
{
NavCrumb[] trail = _trail.Trail;
if (trail.Length < 2) return;
float lift = _settings.NavHeightOffset + 0.03f;
int drawn = 0, total = Math.Min(trail.Length - 1, MaxTrailLines);
for (int i = trail.Length - 1; i >= 1 && drawn < MaxTrailLines; i--)
{
NavCrumb b = trail[i], a = trail[i - 1];
if (b.SegmentStart) continue;
if (NavRouteEditing.DistanceYards(f.NS, f.EW, b.NS, b.EW) > o.BreadcrumbDrawRangeYards) continue;
float fade = o.BreadcrumbFade ? 1f - 0.8f * drawn / Math.Max(1, total) : 1f;
draw(ToWorld(f, a.NS, a.EW, a.Z + lift), ToWorld(f, b.NS, b.EW, b.Z + lift), fade);
drawn++;
}
}
// ═══════════════════════════════════════════════════════════════════
// ImGui (render thread)
// ═══════════════════════════════════════════════════════════════════
/// <summary>HUD window, waypoint labels, and the projected fallback for trail/guide. Call inside an ImGui frame.</summary>
public void Render()
{
try
{
var o = _settings.NavOverlay;
var route = _settings.CurrentRoute;
bool hasRoute = route?.Points is { Count: > 0 };
bool navigating = _settings.IsMacroRunning && _settings.EnableNavigation;
bool wantFallback3D = !_host.HasNav3D && (o.TrailVisible() || o.GuideLineVisible());
bool wantLabels = o.LabelsVisible() && hasRoute;
bool wantHud = o.ShowHud && (hasRoute || _settings.IsRecordingNav) && (!o.HudOnlyWhileNavigating || navigating);
if (!wantFallback3D && !wantLabels && !wantHud) return;
if (!TryGetFrame(out var f)) return;
if (wantFallback3D || wantLabels) RenderWorldOverlay(f, o, wantLabels, wantFallback3D);
if (wantHud) RenderHud(f, o);
}
catch (Exception ex) { RynthLog.Write(LogCat.Navigation, $"NavOverlay(ImGui): {ex.Message}"); }
}
private void RenderWorldOverlay(in Frame f, NavOverlaySettings o, bool labels, bool fallback3D)
{
if (!_host.HasWorldToScreen || !_host.HasGetViewportSize) return;
if (!_host.TryGetViewportSize(out uint vpW, out uint vpH) || vpW == 0 || vpH == 0) return;
ImGui.SetNextWindowPos(Vector2.Zero);
ImGui.SetNextWindowSize(new Vector2(vpW, vpH));
ImGui.PushStyleColor(ImGuiCol.WindowBg, 0u);
ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f);
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
bool open = true;
bool visible = ImGui.Begin("##NavWaypointOverlay", ref open,
ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove |
ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoCollapse |
ImGuiWindowFlags.NoInputs | ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoBringToFrontOnFocus |
ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav | ImGuiWindowFlags.NoSavedSettings);
try
{
if (!visible) return;
var dl = ImGui.GetWindowDrawList();
float thick = Math.Max(1f, _settings.NavLineThickness * 0.5f);
var frame = f;
if (fallback3D && o.TrailVisible())
{
ForEachTrailSegment(f, o, (a, b, fade) =>
{
if (Project(a, out var sa) && Project(b, out var sb))
dl.AddLine(sa, sb, NavOverlaySettings.ArgbToImGui(NavOverlaySettings.ScaleAlpha(o.ColorBreadcrumb, fade)), thick);
});
}
if (fallback3D && o.GuideLineVisible() && ActivePoint(out _) is { Type: NavPointType.Point } ap
&& Project(new Vector3(f.Px, f.Pz + _settings.NavHeightOffset, f.Py), out var sMe)
&& Project(ToWorld(frame, ap.NS, ap.EW, WaypointWorldY(ap)), out var sTo))
dl.AddLine(sMe, sTo, NavOverlaySettings.ArgbToImGui(o.ColorGuide), thick);
if (labels) DrawWaypointLabels(dl, f, o);
}
finally
{
ImGui.End();
ImGui.PopStyleVar(2);
ImGui.PopStyleColor();
}
}
private bool Project(Vector3 w, out Vector2 s)
{
bool ok = _host.WorldToScreen(w.X, w.Y, w.Z, out float sx, out float sy);
s = new Vector2(sx, sy);
return ok;
}
/// <summary>"#12 34yd" over the active travel point and the next ones in route order.</summary>
private void DrawWaypointLabels(ImDrawListPtr dl, in Frame f, NavOverlaySettings o)
{
var route = _settings.CurrentRoute;
var pts = route.Points;
int n = pts.Count;
int idx = Math.Clamp(_settings.ActiveNavIndex, 0, n - 1);
bool circular = route.RouteType == NavRouteType.Circular;
uint activeCol = NavOverlaySettings.ArgbToImGui(o.ColorActiveRing);
uint nextCol = NavOverlaySettings.ArgbToImGui(o.ColorRing);
uint bg = 0xB0000000;
int labelled = 0;
for (int step = 0; step < n && labelled < o.LabelsAhead; step++)
{
int i = circular ? (idx + step) % n : idx + step;
if (i >= n) break;
var p = pts[i];
if (p.Type != NavPointType.Point) continue;
Vector3 w = ToWorld(f, p.NS, p.EW, WaypointWorldY(p) + LabelLift);
if (!Project(w, out var s)) { labelled++; continue; }
double yd = NavRouteEditing.DistanceYards(f.NS, f.EW, p.NS, p.EW);
string text = $"#{i} {yd:F0}yd";
Vector2 size = ImGui.CalcTextSize(text);
Vector2 tl = s - new Vector2(size.X * 0.5f + 4, size.Y + 2);
dl.AddRectFilled(tl, tl + size + new Vector2(8, 4), bg, 3f);
dl.AddText(tl + new Vector2(4, 2), i == _settings.ActiveNavIndex ? activeCol : nextCol, text);
labelled++;
}
}
private void RenderHud(in Frame f, NavOverlaySettings o)
{
ImGui.SetNextWindowPos(new Vector2(20, 220), ImGuiCond.FirstUseEver);
ImGui.SetNextWindowBgAlpha(0.65f);
if (!ImGui.Begin("Nav HUD##RynthAiNavHud", ref o.ShowHud,
ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse |
ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav))
{
ImGui.End();
return;
}
var route = _settings.CurrentRoute;
var pts = route.Points;
string name = string.IsNullOrEmpty(_settings.CurrentNavPath) ? "(unsaved)" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath);
ImGui.TextColored(new Vector4(1f, 0.85f, 0.3f, 1f), $"{name} [{route.RouteType}]");
if (_settings.IsRecordingNav)
{
ImGui.SameLine();
ImGui.TextColored(new Vector4(1f, 0.3f, 0.3f, 1f), $"REC +{_trail.RecordedCount}");
}
int idx = _settings.ActiveNavIndex;
if (pts.Count > 0 && idx >= 0 && idx < pts.Count)
{
var p = pts[idx];
bool travel = p.Type == NavPointType.Point;
ImGui.BeginGroup();
ImGui.Text($"WP {idx}/{pts.Count - 1} {TypeLabel(p)}");
if (travel)
{
double yd = NavRouteEditing.DistanceYards(f.NS, f.EW, p.NS, p.EW);
double dz = (p.Z * NavCoordinateHelper.NavZScale) - f.Pz;
ImGui.Text(Math.Abs(dz) >= 3 ? $"{yd:F1} yd ({(dz > 0 ? "up" : "down")} {Math.Abs(dz):F0})" : $"{yd:F1} yd");
}
else
{
ImGui.TextDisabled(p.ToString());
}
int ni = NextIndex(route, idx);
if (ni >= 0) ImGui.TextDisabled($"Next: [{ni}] {pts[ni]}");
double remain = RemainingYards(route, idx, f);
if (remain > 0) ImGui.TextDisabled(route.RouteType == NavRouteType.Circular ? $"Loop: {remain:F0} yd" : $"Remaining: ~{remain:F0} yd");
ImGui.EndGroup();
if (travel)
{
ImGui.SameLine();
double bearing = Math.Atan2(p.EW - f.EW, p.NS - f.NS) * (180.0 / Math.PI);
DrawArrow((float)(bearing - f.HeadingDeg), NavOverlaySettings.ArgbToImGui(o.ColorGuide));
}
}
else if (pts.Count == 0)
{
ImGui.TextDisabled("Route is empty.");
}
if (!string.IsNullOrEmpty(_settings.NavStatusLine))
ImGui.TextColored(_settings.NavIsStuck ? new Vector4(0.91f, 0.70f, 0.20f, 1f) : new Vector4(0.6f, 0.75f, 0.6f, 1f),
_settings.NavStatusLine);
if (o.TrackBreadcrumbs)
ImGui.TextDisabled($"Trail: {_trail.Trail.Length} pts, {_trail.TrailYards:F0} yd");
ImGui.End();
}
/// <summary>Direction arrow in a 36 px box; <paramref name="relDeg"/> 0 = straight ahead, clockwise.</summary>
private static void DrawArrow(float relDeg, uint color)
{
const float Box = 36f;
Vector2 tl = ImGui.GetCursorScreenPos();
ImGui.Dummy(new Vector2(Box, Box));
var dl = ImGui.GetWindowDrawList();
Vector2 c = tl + new Vector2(Box * 0.5f, Box * 0.5f);
dl.AddCircle(c, Box * 0.48f, 0x60FFFFFF, 24, 1.5f);
double a = relDeg * Math.PI / 180.0;
var dir = new Vector2((float)Math.Sin(a), -(float)Math.Cos(a));
var perp = new Vector2(-dir.Y, dir.X);
dl.AddTriangleFilled(c + dir * 14f, c - dir * 8f + perp * 7f, c - dir * 8f - perp * 7f, color);
}
private static string TypeLabel(NavPoint p) => p.Type switch
{
NavPointType.Point => "Point",
NavPointType.Recall => "Recall",
NavPointType.Pause => "Pause",
NavPointType.Chat => "Chat",
NavPointType.OpenVendor => "Vendor",
NavPointType.PortalNPC => "Portal",
NavPointType.Npc => "NPC",
_ => p.Type.ToString(),
};
/// <summary>Following waypoint in route order (wraps on circular), or -1 at the end.</summary>
private static int NextIndex(NavRouteParser route, int idx)
{
int n = route.Points.Count;
if (idx + 1 < n) return idx + 1;
return route.RouteType == NavRouteType.Circular && n > 1 ? 0 : -1;
}
/// <summary>Player → active point → … end of route (one lap for circular), walking legs only.</summary>
private static double RemainingYards(NavRouteParser route, int idx, in Frame f)
{
var pts = route.Points;
int n = pts.Count;
if (idx < 0 || idx >= n) return 0;
double total = 0;
NavPoint? prev = null;
int steps = route.RouteType == NavRouteType.Circular ? n : n - idx;
for (int s = 0; s < steps; s++)
{
var p = pts[(idx + s) % n];
if (p.Type != NavPointType.Point) { prev = null; continue; }
total += prev == null
? (s == 0 ? NavRouteEditing.DistanceYards(f.NS, f.EW, p.NS, p.EW) : 0)
: NavRouteEditing.DistanceYards(prev.NS, prev.EW, p.NS, p.EW);
prev = p;
}
return total;
}
}

View file

@ -65,6 +65,19 @@ public static unsafe class PluginExports
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
// Local ImGui windows (ILT Hub, HUDs, translator, item info, nav overlay). The engine
// calls this when the export exists; the main panels stay on the engine side.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Render() => Runtime.OnRender();
/// <summary>Engine calls this instead of RynthPluginRender while its ImGui shell is off.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderOverlay", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void RenderOverlay()
{
try { Runtime.Plugin?.OnRenderOverlay(); }
catch { /* an exception crossing UnmanagedCallersOnly would fail-fast the client */ }
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
@ -626,6 +639,56 @@ public static unsafe class PluginExports
}
}
private static IntPtr _progressionPtr = IntPtr.Zero;
/// <summary>
/// Skills panel Progression tab (ILT augmentations / enlightenment). Same contract as
/// RynthPluginGetPatrolInfoJson: one static buffer, valid until the next call; the engine
/// polls it from its pump thread only.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetProgressionJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetProgressionJson()
{
try
{
string json = Runtime.Plugin?.BuildProgressionJson() ?? "{\"available\":false}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _progressionPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
private static IntPtr _charmsPtr = IntPtr.Zero;
/// <summary>
/// Settings panel Charms Tracking tab (ACECustom registry charms: acquired / active / server
/// state). Same contract as RynthPluginGetProgressionJson: one static buffer, valid until the
/// next call; the engine polls it from its pump thread only.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetCharmsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetCharmsJson()
{
try
{
string json = Runtime.Plugin?.BuildCharmsJson() ?? "{\"available\":false}";
IntPtr newPtr = Marshal.StringToHGlobalAnsi(json);
IntPtr oldPtr = Interlocked.Exchange(ref _charmsPtr, newPtr);
if (oldPtr != IntPtr.Zero)
Marshal.FreeHGlobal(oldPtr);
return newPtr;
}
catch
{
return IntPtr.Zero;
}
}
// ── Items bridge (engine-side Avalonia ItemsPanel) ──────────────────────
private static IntPtr _itemsPtr = IntPtr.Zero;

View file

@ -0,0 +1,329 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.ProfileImport;
/// <summary>
/// Copies VirindiTank-style loot files (.utl) and merges Rynth-format monster JSON found under common VT install paths.
/// </summary>
public static class VirindiTankProfileImporter
{
/// <summary>Standard VirindiTank install locations (wiki / community bundles).</summary>
public static IReadOnlyList<string> DefaultVirindiTankRoots()
{
var list = new List<string>
{
@"C:\Games\VirindiPlugins\VirindiTank",
};
try
{
string docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (!string.IsNullOrEmpty(docs))
{
list.Add(Path.Combine(docs, "VirindiPlugins", "VirindiTank"));
list.Add(Path.Combine(docs, "Decal", "VirindiPlugins", "VirindiTank"));
}
}
catch { }
try
{
string loc = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (!string.IsNullOrEmpty(loc))
list.Add(Path.Combine(loc, "VirindiPlugins", "VirindiTank"));
}
catch { }
return list.Distinct(StringComparer.OrdinalIgnoreCase).Where(Directory.Exists).ToList();
}
public sealed class Result
{
public int LootFilesCopied;
public int MonsterRulesAdded;
/// <summary>Full paths of .utl files copied into the Rynth loot folder this run (for activating loot).</summary>
public List<string> CopiedLootDestPaths { get; } = new();
public List<string> LogLines { get; } = new();
}
/// <param name="lootDestDir">RynthAi LootProfiles folder.</param>
/// <param name="mergeMonsterRules">When true, deserialized rules are merged into <paramref name="settings"/>.</param>
public static Result Import(string lootDestDir, LegacyUiSettings settings, bool mergeMonsterRules)
{
var result = new Result();
if (string.IsNullOrEmpty(lootDestDir))
{
result.LogLines.Add("Loot destination folder is empty.");
return result;
}
try { Directory.CreateDirectory(lootDestDir); }
catch (Exception ex)
{
result.LogLines.Add($"Cannot create loot folder: {ex.Message}");
return result;
}
var seenSrc = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string root in DefaultVirindiTankRoots())
{
foreach (string utl in EnumerateFilesRecursive(root, "*.utl", maxDepth: 6))
{
if (!seenSrc.Add(utl)) continue;
string baseName = Path.GetFileName(utl);
string dest = Path.Combine(lootDestDir, baseName);
int suffix = 0;
while (File.Exists(dest))
{
suffix++;
dest = Path.Combine(lootDestDir, $"VT_{suffix}_{baseName}");
}
try
{
File.Copy(utl, dest, overwrite: false);
result.LootFilesCopied++;
result.CopiedLootDestPaths.Add(dest);
result.LogLines.Add($"Loot: {baseName} -> {Path.GetFileName(dest)}");
}
catch (Exception ex)
{
result.LogLines.Add($"Loot skip {baseName}: {ex.Message}");
}
}
if (mergeMonsterRules)
{
foreach (string jsonPath in EnumerateFilesRecursive(root, "monsters.json", maxDepth: 8))
TryMergeMonsterFile(jsonPath, settings, result);
foreach (string usdPath in EnumerateFilesRecursive(root, "*.usd", maxDepth: 6))
TryMergeUsdMyMonstersScf(usdPath, settings, result);
}
}
if (result.LootFilesCopied == 0 && result.MonsterRulesAdded == 0)
result.LogLines.Add("No .utl loot files, Rynth monsters.json, or text MyMonsters .usd found under VirindiTank paths.");
return result;
}
/// <summary>SQLite-backed VT profiles are skipped here; use Monster Editor import for those.</summary>
private static bool LooksLikeSqliteFile(string path)
{
try
{
using var fs = File.OpenRead(path);
var hdr = new byte[16];
int n = fs.Read(hdr, 0, hdr.Length);
const string sig = "SQLite format 3\0";
if (n < sig.Length)
return false;
for (int i = 0; i < sig.Length; i++)
{
if (hdr[i] != sig[i])
return false;
}
return true;
}
catch
{
return false;
}
}
/// <summary>Text SCF .usd with MyMonsters — same subset as Monster Editor import for the current character merge.</summary>
private static void TryMergeUsdMyMonstersScf(string usdPath, LegacyUiSettings settings, Result result)
{
if (string.IsNullOrWhiteSpace(usdPath) || !File.Exists(usdPath))
return;
if (LooksLikeSqliteFile(usdPath))
{
result.LogLines.Add($"Monsters: skip SQLite .usd (use Monster Editor): {Path.GetFileName(usdPath)}");
return;
}
string allText;
try
{
allText = File.ReadAllText(usdPath, Encoding.UTF8);
}
catch (Exception ex)
{
result.LogLines.Add($"Monsters: skip .usd read {Path.GetFileName(usdPath)}: {ex.Message}");
return;
}
var tmp = new List<MonsterRule>();
if (!VirindiTankUsdMyMonstersScfParser.TryParseMyMonsters(allText, tmp, out string? note) || tmp.Count == 0)
return;
int addedBefore = result.MonsterRulesAdded;
MergeVtMonsterRows(tmp, settings, result);
int newNamed = result.MonsterRulesAdded - addedBefore;
result.LogLines.Add(
$"Monsters: VT MyMonsters from {Path.GetFileName(usdPath)} — parsed {tmp.Count} row(s), +{newNamed} new rule(s).{(string.IsNullOrEmpty(note) ? "" : " " + note)}");
}
/// <summary>Merges VT-style rows into <paramref name="settings"/> like Monster Editor external import.</summary>
private static void MergeVtMonsterRows(IReadOnlyList<MonsterRule> src, LegacyUiSettings settings, Result result)
{
settings.EnsureDefaultRule();
List<MonsterRule> rules = settings.MonsterRules;
MonsterRule? srcDefault = src.FirstOrDefault(x => x.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
if (srcDefault != null && rules.Count > 0 && rules[0].Name.Equals("Default", StringComparison.OrdinalIgnoreCase))
CopyCombatOntoDefault(rules[0], srcDefault);
var nameSet = new HashSet<string>(rules.Select(x => x.Name), StringComparer.OrdinalIgnoreCase);
var exprSet = new HashSet<string>(
rules.Where(x => !string.IsNullOrWhiteSpace(x.MatchExpression)).Select(x => x.MatchExpression),
StringComparer.Ordinal);
foreach (MonsterRule row in src)
{
if (row.Name.Equals("Default", StringComparison.OrdinalIgnoreCase))
continue;
if (!string.IsNullOrEmpty(row.Name))
{
if (nameSet.Contains(row.Name))
continue;
}
else if (!string.IsNullOrEmpty(row.MatchExpression))
{
if (exprSet.Contains(row.MatchExpression))
continue;
}
else
{
continue;
}
var c = CloneMonsterRule(row);
if (!string.IsNullOrEmpty(c.Name))
{
if (!nameSet.Add(c.Name))
continue;
}
if (!string.IsNullOrEmpty(c.MatchExpression))
exprSet.Add(c.MatchExpression);
rules.Add(c);
result.MonsterRulesAdded++;
}
}
private static void CopyCombatOntoDefault(MonsterRule dst, MonsterRule src)
{
dst.Category = src.Category;
dst.MatchExpression = src.MatchExpression;
dst.Priority = src.Priority;
dst.DamageType = src.DamageType;
dst.WeaponId = src.WeaponId;
dst.Fester = src.Fester;
dst.Broadside = src.Broadside;
dst.GravityWell = src.GravityWell;
dst.Imperil = src.Imperil;
dst.Yield = src.Yield;
dst.Vuln = src.Vuln;
dst.UseArc = src.UseArc;
dst.UseBolt = src.UseBolt;
dst.UseRing = src.UseRing;
dst.UseStreak = src.UseStreak;
dst.ExVuln = src.ExVuln;
dst.OffhandId = src.OffhandId;
dst.PreferredAmmoItemId = src.PreferredAmmoItemId;
dst.PetDamage = src.PetDamage;
}
private static MonsterRule CloneMonsterRule(MonsterRule row) =>
new()
{
Name = row.Name,
Category = row.Category,
MatchExpression = row.MatchExpression,
Priority = row.Priority,
DamageType = row.DamageType,
WeaponId = row.WeaponId,
Fester = row.Fester,
Broadside = row.Broadside,
GravityWell = row.GravityWell,
Imperil = row.Imperil,
Yield = row.Yield,
Vuln = row.Vuln,
UseArc = row.UseArc,
UseBolt = row.UseBolt,
UseRing = row.UseRing,
UseStreak = row.UseStreak,
ExVuln = row.ExVuln,
OffhandId = row.OffhandId,
PreferredAmmoItemId = row.PreferredAmmoItemId,
PetDamage = row.PetDamage,
};
private static void TryMergeMonsterFile(string jsonPath, LegacyUiSettings settings, Result result)
{
try
{
string json = File.ReadAllText(jsonPath);
var imported = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.MonsterRuleList);
if (imported == null || imported.Count == 0) return;
int added = 0;
foreach (var rule in imported)
{
if (string.IsNullOrWhiteSpace(rule.Name)) continue;
if (rule.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)) continue;
if (settings.MonsterRules.Any(m => m.Name.Equals(rule.Name, StringComparison.OrdinalIgnoreCase)))
continue;
settings.MonsterRules.Add(rule);
added++;
}
if (added > 0)
{
result.MonsterRulesAdded += added;
result.LogLines.Add($"Monsters: merged {added} rule(s) from {Path.GetFileName(jsonPath)}");
}
}
catch (Exception ex)
{
result.LogLines.Add($"Monsters skip {jsonPath}: {ex.Message}");
}
}
private static IEnumerable<string> EnumerateFilesRecursive(string root, string pattern, int maxDepth)
{
if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) yield break;
var stack = new Stack<(string Path, int Depth)>();
stack.Push((root, 0));
while (stack.Count > 0)
{
var (dir, depth) = stack.Pop();
IEnumerable<string> files;
try { files = Directory.EnumerateFiles(dir, pattern); }
catch { continue; }
foreach (string f in files)
yield return f;
if (depth >= maxDepth) continue;
IEnumerable<string> subdirs;
try { subdirs = Directory.EnumerateDirectories(dir); }
catch { continue; }
foreach (string sub in subdirs)
stack.Push((sub, depth + 1));
}
}
}

View file

@ -0,0 +1,339 @@
// Line-oriented uTank2 SCF .usd MyMonsters table — logic mirrors Tools/RynthCore.MonsterEditor/VirindiTankUsdTextScfParser.cs
// for LegacyUi.MonsterRule. If VT changes the SCF layout, update both files together.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.ProfileImport;
/// <summary>Parses VirindiTank text-format <c>.usd</c> files that contain a <c>MyMonsters</c> SCF block.</summary>
internal static class VirindiTankUsdMyMonstersScfParser
{
/// <summary>Returns false if the file is not SCF MyMonsters (e.g. SQLite binary profile).</summary>
public static bool TryParseMyMonsters(string allText, List<MonsterRule> outList, out string? note)
{
outList.Clear();
note = null;
if (string.IsNullOrWhiteSpace(allText) || allText.IndexOf("MyMonsters", StringComparison.Ordinal) < 0)
return false;
string[] L = allText
.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None)
.Select(s => s.Trim())
.ToArray();
if (L.Length < 8)
{
note = "File too short.";
return false;
}
int idx = 0;
for (; idx < L.Length; idx++)
if (L[idx] == "MyMonsters")
break;
if (idx >= L.Length)
{
note = "MyMonsters not found.";
return false;
}
idx++;
if (!int.TryParse(L[idx], out int colCount) || colCount < 1)
{
note = "MyMonsters: bad column count.";
return false;
}
idx += 1 + colCount * 2;
if (idx >= L.Length)
{
note = "MyMonsters: truncated after header.";
return false;
}
if (!int.TryParse(L[idx], out int rowCount) || rowCount < 0)
{
note = "MyMonsters: bad row count.";
return false;
}
idx++;
if (rowCount == 0)
{
note = "MyMonsters has no rows.";
return false;
}
if (colCount < 4 + 3)
{
note = "MyMonsters: column count too small.";
return false;
}
int nBool = colCount - 4 - 3;
for (int r = 0; r < rowCount; r++)
{
if (idx + 1 >= L.Length)
{
note = $"No data for row {r + 1} (early EOF).";
return outList.Count > 0;
}
if (!T(L, "s", ref idx))
{
note = RowErr(r, "s");
return outList.Count > 0;
}
if (!ValStr(L, ref idx, out string raw))
{
note = RowErr(r, "name");
return outList.Count > 0;
}
if (!T(L, "i", ref idx))
{
note = RowErr(r, "i ap");
return outList.Count > 0;
}
if (!ValInt(L, ref idx, out int ap, out int err) || err != 0)
{
note = RowErr(r, "ap int");
return outList.Count > 0;
}
if (!T(L, "i", ref idx))
{
note = RowErr(r, "i dt");
return outList.Count > 0;
}
if (!ValInt(L, ref idx, out int vtDmg, out err) || err != 0)
{
note = RowErr(r, "dt int");
return outList.Count > 0;
}
if (!T(L, "i", ref idx))
{
note = RowErr(r, "i wep");
return outList.Count > 0;
}
if (!ValInt(L, ref idx, out int wep, out err) || err != 0)
{
note = RowErr(r, "wep int");
return outList.Count > 0;
}
if (nBool < 14)
{
note = "Expected at least 14 bool columns in mob row.";
return outList.Count > 0;
}
if (nBool < 1)
{
note = "nBool<1.";
return false;
}
var b = new bool[nBool];
for (int k = 0; k < nBool; k++)
{
if (!T(L, "b", ref idx) || !ValBool(L, ref idx, out b[k]))
{
note = RowErr(r, $"b{k}");
return outList.Count > 0;
}
}
if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int sev, out err) || err != 0)
{
note = RowErr(r, "sec vuln int");
return outList.Count > 0;
}
if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int ofh, out err) || err != 0)
{
note = RowErr(r, "offh int");
return outList.Count > 0;
}
if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int pet, out err) || err != 0)
{
note = RowErr(r, "pet int");
return outList.Count > 0;
}
outList.Add(MakeRule(raw, ap, vtDmg, wep, b, sev, ofh, pet));
}
if (outList.Count == 0)
{
note = "No rows were parsed from MyMonsters.";
return false;
}
return true;
}
private static string RowErr(int r, string what) => $"MyMonsters row {r + 1} ({what}).";
private static bool T(string[] L, string t, ref int i)
{
if (i >= L.Length || L[i] != t)
return false;
i++;
return true;
}
private static bool ValStr(string[] L, ref int i, out string s)
{
s = "";
if (i >= L.Length)
return false;
s = L[i++];
return true;
}
private static bool ValInt(string[] L, ref int i, out int v, out int err)
{
err = 0;
v = 0;
if (i >= L.Length)
{
err = 1;
return false;
}
if (!int.TryParse(L[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out v) &&
!int.TryParse(L[i], out v))
{
err = 1;
return false;
}
i++;
return true;
}
private static bool ValBool(string[] L, ref int i, out bool b)
{
b = false;
if (i >= L.Length)
return false;
string t = L[i++];
if (string.Equals(t, "True", StringComparison.OrdinalIgnoreCase))
{
b = true;
return true;
}
if (string.Equals(t, "False", StringComparison.OrdinalIgnoreCase))
{
b = false;
return true;
}
return false;
}
private static MonsterRule MakeRule(string raw, int ap, int vtDmg, int wep, bool[] b, int sev, int ofh, int pet)
{
string n = Nm(raw);
if (b.Length < 14)
b = Pad(b, 14);
bool i = b[0], v = b[1], y = b[2], gW = b[3];
bool useBolt = b[4], useRing = b[5], broad = b[6], fest = b[7];
bool strk = b[13];
return new MonsterRule
{
Name = n,
Priority = ap,
DamageType = MapDmg(vtDmg),
WeaponId = WepId(wep),
Imperil = i,
Vuln = v,
Yield = y,
GravityWell = gW,
UseBolt = useBolt,
UseRing = useRing,
Broadside = broad,
Fester = fest,
UseStreak = strk,
ExVuln = "None",
OffhandId = WepId(ofh),
PetDamage = MapPet(pet, sev),
};
}
private static bool[] Pad(bool[] b, int min)
{
if (b.Length >= min)
return b;
var r = new bool[min];
for (int i = 0; i < b.Length; i++)
r[i] = b[i];
return r;
}
private static string Nm(string s)
{
s = s.Trim();
if (s.Length > 1 && s[0] == '<' && s[^1] == '>')
{
string t = s.Substring(1, s.Length - 2);
if (t.Equals("DEFAULT", StringComparison.OrdinalIgnoreCase))
return "Default";
return t;
}
return s;
}
private static int WepId(int w) => w;
private static string MapDmg(int c) => c switch
{
8 => "Auto",
1 => "Slash",
2 => "Pierce",
3 => "Bludgeon",
4 => "Acid",
5 => "Fire",
6 => "Cold",
7 => "Lightning",
0 => "Nether",
_ => "Auto",
};
private static string MapPet(int pdt, int _)
{
if (pdt is 0 or 101)
return "PAuto";
if (pdt is >= 1 and <= 8)
{
return pdt switch
{
1 => "Slash",
2 => "Pierce",
3 => "Bludgeon",
4 => "Fire",
5 => "Cold",
6 => "Lightning",
7 => "Acid",
8 => "Nether",
_ => "PAuto",
};
}
return "PAuto";
}
}

View file

@ -7,6 +7,7 @@ using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.PluginSdk;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi;
@ -17,7 +18,7 @@ namespace RynthCore.Plugin.RynthAi;
/// dungeons stack would be unreadable otherwise.
///
/// Explored state is per-EnvCell and persisted per-landblock under
/// C:\Games\RynthSuite\RynthAi\ExploredDungeons\XXYY0000.json.
/// <SuiteDir>\RynthAi\ExploredDungeons\XXYY0000.json.
/// </summary>
internal sealed class RadarWallRenderer
{
@ -49,7 +50,7 @@ internal sealed class RadarWallRenderer
private readonly bool[] _inside = new bool[MaxPolyVerts];
private static readonly string ExploredDir =
@"C:\Games\RynthSuite\RynthAi\ExploredDungeons";
System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"ExploredDungeons");
public RadarWallRenderer(RynthCoreHost host, LegacyUiSettings settings)
{
@ -62,7 +63,7 @@ internal sealed class RadarWallRenderer
public void Render()
{
try { RenderCore(); }
catch (Exception ex) { _host.Log($"RadarWalls: {ex.Message}"); }
catch (Exception ex) { RynthLog.Write(LogCat.Radar, $"RadarWalls: {ex.Message}"); }
}
private void RenderCore()
@ -288,7 +289,7 @@ internal sealed class RadarWallRenderer
}
catch (Exception ex)
{
_host.Log($"RadarWalls: load {path} failed: {ex.Message}");
RynthLog.Write(LogCat.Radar, $"RadarWalls: load {path} failed: {ex.Message}");
}
}
@ -309,7 +310,7 @@ internal sealed class RadarWallRenderer
}
catch (Exception ex)
{
_host.Log($"RadarWalls: save failed: {ex.Message}");
RynthLog.Write(LogCat.Radar, $"RadarWalls: save failed: {ex.Message}");
}
}

View file

@ -1072,6 +1072,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[DungeonLOS] {msg}");
RynthLog.Trace(LogCat.Raycast, $"[DungeonLOS] {msg}"); // visible via /ra trace raycast
}
}

View file

@ -1788,6 +1788,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
{
string line = $"[GeoLoader] {msg}";
System.Diagnostics.Debug.WriteLine(line);
RynthLog.Trace(LogCat.Raycast, line); // visible via /ra trace raycast
if (DiagLog.Count < 200) DiagLog.Add(msg);
}
}

View file

@ -164,6 +164,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[LandblockInfo] {msg}");
RynthLog.Trace(LogCat.Raycast, $"[LandblockInfo] {msg}"); // visible via /ra trace raycast
}
}
@ -282,6 +283,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[EnvCell] {msg}");
RynthLog.Trace(LogCat.Raycast, $"[EnvCell] {msg}"); // visible via /ra trace raycast
}
}
@ -585,6 +587,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[Setup] {msg}");
RynthLog.Trace(LogCat.Raycast, $"[Setup] {msg}"); // visible via /ra trace raycast
}
}
@ -755,6 +758,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
private static void Log(string msg)
{
System.Diagnostics.Debug.WriteLine($"[GfxObj] {msg}");
RynthLog.Trace(LogCat.Raycast, $"[GfxObj] {msg}"); // visible via /ra trace raycast
}
}

View file

@ -1027,6 +1027,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
{
string line = $"[Scatter] {msg}";
System.Diagnostics.Debug.WriteLine(line);
RynthLog.Trace(LogCat.Raycast, line); // visible via /ra trace raycast
if (DiagLog.Count < 100) DiagLog.Add(msg);
}
}

View file

@ -2993,8 +2993,8 @@ public sealed partial class RynthAiPlugin
return sb.ToString();
}
// Minimal JSON string escaper for route names (which can contain user-chosen chars).
private static string JsonEscape(string s)
// Minimal JSON string escaper for hand-built export JSON (route names, ILT Hub text).
internal static string JsonEscape(string s)
{
var sb = new System.Text.StringBuilder(s.Length + 8);
foreach (char c in s)

View file

@ -0,0 +1,381 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
using System.Threading;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.ItemInfo;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// /ra iteminfo — Mag-style item info (ratings, damage, spells, slayer, imbues …) as one line or
/// as pet-roster style lines, printed on demand, on select or on a left/right mouse click;
/// ported from UtilityBelt ub-IT / Mag-Tools ItemInfo. Partial class of RynthAiPlugin.
///
/// /ra iteminfo describe the selected item (IDs it first when needed)
/// /ra iteminfo on|off describe every item you select
/// /ra iteminfo settings open/close the Item Info settings window
/// /ra iteminfo fields list fields and ratings with their on/off state
/// /ra iteminfo field &lt;name&gt; on|off show/hide one field (ratings, slayer, spells, …)
/// /ra iteminfo rating &lt;tag&gt; on|off show/hide one rating (D, CD, CDR, …)
/// /ra iteminfo value on|off append value + burden
/// /ra iteminfo verbose on|off list every spell instead of Mag's filter
/// /ra iteminfo click left|right|off print the selected item after a mouse click
/// /ra iteminfo layout pet|line pet-roster style lines or the Mag one-liner
/// /ra iteminfo reset restore defaults
/// Every option is also editable in the "RynthAi Item Info" window (LegacyItemInfoUi).
/// </summary>
public sealed partial class RynthAiPlugin
{
// One pending describe at a time: the newest request replaces the previous one.
private int _itemInfoPendingId;
private long _itemInfoPendingSince;
// Automatic triggers (select + click) can both fire for one click; the same item inside
// this window prints once.
private const long AutoDedupeMs = 1500;
private int _itemInfoLastAutoId;
private long _itemInfoLastAutoAt;
// Click trigger. A press counts as a click only if it started outside every overlay window,
// was released within ClickMaxHoldMs and moved at most ClickMaxMovePx — so item drags and
// right-button mouse-look never print. The client updates the selection after it handles
// the click, so the selection is read ClickSettleMs after the release, on the tick thread.
private const long ClickMaxHoldMs = 600;
private const float ClickMaxMovePx = 6f;
private const long ClickSettleMs = 150;
private bool _iiClickPrevDown;
private bool _iiClickArmed;
private long _iiClickPressAt;
private Vector2 _iiClickPressPos;
private long _iiClickResolveAt; // TickCount64 to read the selection at; 0 = none (Interlocked)
/// <summary>Character settings when loaded, else null (commands then use defaults / refuse edits).</summary>
private MagItemInfoSettings? ItemInfoSettings => _dashboard?.Settings.ItemInfoSettings;
private void HandleItemInfoCommand(string[] parts)
{
var s = ItemInfoSettings;
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty;
string arg3 = parts.Length >= 4 ? parts[3] : string.Empty;
string arg4 = parts.Length >= 5 ? parts[4] : string.Empty;
if (sub.Length == 0)
{
PrintSelectedItemInfo();
return;
}
if (s == null) { ChatLine("[RynthAi] Settings not ready (log in first)."); return; }
switch (sub)
{
case "settings":
case "gui":
case "window":
s.ShowWindow = !s.ShowWindow;
ChatLine($"[RynthAi] Item info window {(s.ShowWindow ? "opened" : "closed")}.");
return;
case "value":
if (ParseOnOff(arg3) is bool v) s.ShowValueAndBurden = v;
ChatLine($"[RynthAi] Item info value/burden: {OnOff(s.ShowValueAndBurden)}");
return;
case "verbose":
if (ParseOnOff(arg3) is bool all)
s.SpellMode = all ? MagItemInfoSettings.SpellModeAll : MagItemInfoSettings.SpellModeMag;
ChatLine($"[RynthAi] Item info all spells: {OnOff(s.SpellMode == MagItemInfoSettings.SpellModeAll)}");
return;
case "field":
if (!MagItemInfoCatalog.TryFindField(arg3, out MagItemInfoField field))
{
ChatLine($"[RynthAi] Unknown field '{arg3}'. /ra iteminfo fields lists them.");
return;
}
if (ParseOnOff(arg4) is bool fieldOn) s.SetHidden(field, !fieldOn);
ChatLine($"[RynthAi] Item info field {field}: {OnOff(!s.IsHidden(field))}");
return;
case "rating":
int r = MagItemInfoCatalog.FindRating(arg3);
if (r < 0)
{
ChatLine($"[RynthAi] Unknown rating '{arg3}'. /ra iteminfo fields lists them.");
return;
}
if (ParseOnOff(arg4) is bool ratingOn) s.SetRatingHidden(r, !ratingOn);
var rating = MagItemInfoCatalog.Ratings[r];
ChatLine($"[RynthAi] Item info rating {rating.Tag} ({rating.Name}): {OnOff(!s.IsRatingHidden(r))}");
return;
case "fields":
ListItemInfoFields(s);
return;
case "click":
switch (arg3.ToLowerInvariant())
{
case "left": case "l": s.ClickTrigger = MagItemInfoSettings.ClickLeft; break;
case "right": case "r": s.ClickTrigger = MagItemInfoSettings.ClickRight; break;
case "off": case "none": s.ClickTrigger = MagItemInfoSettings.ClickOff; break;
case "": break;
default:
ChatLine("[RynthAi] Usage: /ra iteminfo click left|right|off");
return;
}
ChatLine($"[RynthAi] Item info on click: {MagItemInfoCatalog.ClickTriggers[s.ClickTrigger]}");
return;
case "layout":
switch (arg3.ToLowerInvariant())
{
case "pet": case "pets": case "lines": s.Layout = MagItemInfoSettings.LayoutPetLines; break;
case "line": case "mag": case "one": s.Layout = MagItemInfoSettings.LayoutOneLine; break;
case "": break;
default:
ChatLine("[RynthAi] Usage: /ra iteminfo layout pet|line");
return;
}
ChatLine($"[RynthAi] Item info layout: {MagItemInfoCatalog.Layouts[s.Layout]}");
return;
case "reset":
s.ResetToDefaults();
ChatLine("[RynthAi] Item info settings reset to defaults.");
return;
}
if (ParseOnOff(sub) is bool onSelect)
{
s.OnSelect = onSelect;
ChatLine($"[RynthAi] Item info on select: {OnOff(onSelect)}");
return;
}
ChatLine("[RynthAi] Usage: /ra iteminfo [on|off|settings|fields|field <name> on|off|rating <tag> on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|reset]");
}
private static string OnOff(bool on) => on ? "ON" : "OFF";
/// <summary>"/ra iteminfo fields" — current state of every field and rating.</summary>
private void ListItemInfoFields(MagItemInfoSettings s)
{
var sb = new StringBuilder("[RynthAi] Fields: ");
bool first = true;
foreach (var f in MagItemInfoCatalog.Fields)
{
if (!first) sb.Append(", ");
sb.Append(f.Field).Append(s.IsHidden(f.Field) ? " off" : " on");
first = false;
}
ChatLine(sb.ToString());
sb.Clear().Append("[RynthAi] Ratings: ");
var ratings = MagItemInfoCatalog.Ratings;
for (int i = 0; i < ratings.Length; i++)
{
if (i > 0) sb.Append(", ");
sb.Append(ratings[i].Tag).Append(s.IsRatingHidden(i) ? " off" : " on");
}
ChatLine(sb.ToString());
}
/// <summary>/ra iteminfo and the window's "Print to chat" button.</summary>
private void PrintSelectedItemInfo()
{
if (!Host.HasGetSelectedItemId) { ChatLine("[RynthAi] Host does not expose the selected item."); return; }
uint selected = Host.GetSelectedItemId();
if (selected == 0) { ChatLine("[RynthAi] No item selected. Click an item first."); return; }
QueueItemInfo(unchecked((int)selected), requestId: true);
}
/// <summary>On-select class filters from the Item Info window.</summary>
private static bool ItemInfoWantsClass(MagItemInfoSettings s, AcObjectClass cls) => cls switch
{
AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.WandStaffOrb => s.OnSelectWeapons,
AcObjectClass.Armor or AcObjectClass.Clothing => s.OnSelectArmor,
AcObjectClass.Jewelry => s.OnSelectJewelry,
_ => s.OnSelectOther,
};
/// <summary>
/// Describe <paramref name="itemId"/> now if its appraisal is cached, otherwise (optionally)
/// request an ID and print from <see cref="TickItemInfo"/> once it lands or times out.
/// </summary>
internal void QueueItemInfo(int itemId, bool requestId)
{
if (itemId == 0) return;
uint uid = unchecked((uint)itemId);
if (!Host.HasHasAppraisalData || Host.HasAppraisalData(uid))
{
_itemInfoPendingId = 0;
PrintItemInfo(itemId, identified: true);
return;
}
if (requestId && Host.HasRequestId) Host.RequestId(uid);
_itemInfoPendingId = itemId;
_itemInfoPendingSince = Environment.TickCount64;
}
/// <summary>
/// Select / click triggers: <see cref="QueueItemInfo"/> unless the same item was queued
/// automatically within <see cref="AutoDedupeMs"/> (one click can raise both triggers).
/// </summary>
internal void QueueAutoItemInfo(int itemId, bool requestId)
{
long now = Environment.TickCount64;
if (itemId == _itemInfoLastAutoId && now - _itemInfoLastAutoAt < AutoDedupeMs) return;
_itemInfoLastAutoId = itemId;
_itemInfoLastAutoAt = now;
QueueItemInfo(itemId, requestId);
}
/// <summary>
/// Render-thread click watcher (OnRender / OnRenderOverlay, ImGui context current). The ImGui
/// backend sees every mouse message on the game window, including the ones the game handles,
/// so the raw button state is edge-detected here; the selection is resolved in
/// <see cref="TickItemInfo"/>.
/// </summary>
private void DetectItemInfoClick()
{
int trigger = ItemInfoSettings?.ClickTrigger ?? MagItemInfoSettings.ClickOff;
int button = trigger switch
{
MagItemInfoSettings.ClickLeft => 0,
MagItemInfoSettings.ClickRight => 1,
_ => -1,
};
if (button < 0)
{
_iiClickPrevDown = false;
_iiClickArmed = false;
return;
}
ImGuiIOPtr io = ImGui.GetIO();
bool down = io.MouseDown[button];
long now = Environment.TickCount64;
if (down && !_iiClickPrevDown)
{
// A press on an overlay window belongs to the overlay, not to an item in the game.
_iiClickArmed = !io.WantCaptureMouse;
_iiClickPressAt = now;
_iiClickPressPos = io.MousePos;
}
else if (down && _iiClickArmed)
{
bool held = now - _iiClickPressAt > ClickMaxHoldMs;
bool moved = Vector2.DistanceSquared(io.MousePos, _iiClickPressPos) > ClickMaxMovePx * ClickMaxMovePx;
if (held || moved) _iiClickArmed = false; // drag or mouse-look, not a click
}
else if (!down && _iiClickPrevDown && _iiClickArmed)
{
_iiClickArmed = false;
Interlocked.Exchange(ref _iiClickResolveAt, now + ClickSettleMs);
}
_iiClickPrevDown = down;
}
/// <summary>Tick-thread half of the click trigger: describe whatever item the click selected.</summary>
private void ResolveItemInfoClick()
{
long at = Interlocked.Read(ref _iiClickResolveAt);
if (at == 0 || Environment.TickCount64 < at) return;
if (Interlocked.CompareExchange(ref _iiClickResolveAt, 0, at) != at) return;
var s = ItemInfoSettings;
if (s == null || s.ClickTrigger == MagItemInfoSettings.ClickOff || !Host.HasGetSelectedItemId) return;
uint selected = Host.GetSelectedItemId();
if (selected == 0) return;
int id = unchecked((int)selected);
WorldObject? obj = _objectCache?[id];
if (obj == null || !IsLootableClass(obj.ObjectClass) || !ItemInfoWantsClass(s, obj.ObjectClass)) return;
QueueAutoItemInfo(id, requestId: true);
}
/// <summary>Plugin-tick poll for a pending describe (no appraisal-arrived event in the SDK).</summary>
private void TickItemInfo()
{
ResolveItemInfoClick();
int id = _itemInfoPendingId;
if (id == 0) return;
bool ready = Host.HasAppraisalData(unchecked((uint)id));
long timeoutMs = (long)((ItemInfoSettings?.IdTimeoutSec ?? 3f) * 1000f);
bool timedOut = Environment.TickCount64 - _itemInfoPendingSince > timeoutMs;
if (!ready && !timedOut) return;
_itemInfoPendingId = 0;
PrintItemInfo(id, identified: ready);
}
/// <summary>
/// Builds the output lines (no prefix / indent) in the configured layout, or returns null
/// with <paramref name="error"/> set. The one-line layout returns a single line.
/// </summary>
private List<string>? BuildItemInfoLines(int itemId, out string? error)
{
error = null;
WorldObject? wo = _objectCache?[itemId];
if (wo == null) { error = $"Item 0x{(uint)itemId:X8} is not in the object cache."; return null; }
try
{
var s = ItemInfoSettings;
MagItemDescription d = MagItemDescriber.Build(new CacheItemPropertySource(Host, wo), MagItemInfoOptions.From(s));
return (s?.Layout ?? MagItemInfoSettings.LayoutPetLines) == MagItemInfoSettings.LayoutOneLine
? new List<string> { d.ToOneLine() }
: d.ToPetLines();
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.General, ex, $"item info 0x{(uint)itemId:X8}");
error = $"Item info failed for {wo.Name}: {ex.Message}";
return null;
}
}
/// <summary>
/// Chat output. Pet-style: line 1 carries the prefix in <see cref="MagItemInfoSettings.ChatType"/>,
/// later lines are indented like the pet roster and use <see cref="MagItemInfoSettings.DetailChatType"/>.
/// </summary>
private void PrintItemInfo(int itemId, bool identified)
{
List<string>? lines = BuildItemInfoLines(itemId, out string? error);
if (lines == null || lines.Count == 0) { ChatLine("[RynthAi] " + error); return; }
if (!identified) lines[0] += " (not identified — stats may be incomplete)";
var s = ItemInfoSettings;
string prefix = s?.Prefix ?? "[RynthAi] ";
int headerType = s?.ChatType ?? 1;
int detailType = s == null || s.DetailChatType == MagItemInfoSettings.SameAsHeader ? headerType : s.DetailChatType;
Host.WriteToChat(prefix + lines[0], headerType);
for (int i = 1; i < lines.Count; i++)
Host.WriteToChat(prefix + " " + lines[i], detailType);
}
/// <summary>Item Info window preview: the selected item's lines, or null when nothing is selected.</summary>
private string? DescribeSelectedItemForPreview()
{
if (!Host.HasGetSelectedItemId) return null;
uint selected = Host.GetSelectedItemId();
if (selected == 0) return null;
int id = unchecked((int)selected);
List<string>? lines = BuildItemInfoLines(id, out string? error);
if (lines == null || lines.Count == 0) return error;
if (Host.HasHasAppraisalData && !Host.HasAppraisalData(selected))
lines[0] += " (not identified yet — Print to chat IDs it)";
// The window adds the prefix to the first line; indent the rest like chat.
return string.Join("\n ", lines);
}
/// <summary>Item Info window "Test" button: sample line in the chosen chat type.</summary>
private void TestItemInfoChatType(int chatType)
{
string prefix = ItemInfoSettings?.Prefix ?? "[RynthAi] ";
Host.WriteToChat($"{prefix}Item info chat test (type {chatType})", chatType);
}
}

View file

@ -0,0 +1,467 @@
// RynthAiPlugin.LocalFeatures.cs — ILT Hub, floating HUDs, chat translation, item info, the nav
// overlay and the UB damage seed.
//
// The engine draws the main panels. These features draw their own ImGui windows from
// RynthPluginRender / RynthPluginRenderOverlay. Lifecycle methods on RynthAiPlugin call into
// this file; they add to combat, loot and navigation and never replace them.
using System;
using System.Collections.Generic;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
private NavBreadcrumbTracker? _navBreadcrumbs;
private NavOverlayRenderer? _navOverlay;
private IltHub.IltHubController? _iltHub;
private Huds.HudController? _huds;
private Huds.HudIconCache? _hudIcons;
private Translate.ChatTranslator? _translator;
private Translate.TranslateUi? _translateUi;
private LegacyItemInfoUi? _itemInfoUi;
private CreatureData.UbMobSeedStore? _mobSeedStore;
// One-time overlay diagnostics (render thread only).
private string? _overlaySkipReasonLogged;
private bool _overlayEnteredLogged;
/// <summary>Daily diagnostics log. Feature code writes through <see cref="RynthLog"/>.</summary>
private void InitLocalDiagnostics()
{
try { RynthLog.Init(Host); }
catch (Exception ex) { Host.Log($"[RynthAi] diagnostics init failed: {ex.Message}"); }
try { _mobSeedStore = new CreatureData.UbMobSeedStore(); }
catch (Exception ex) { Host.Log($"[RynthAi] mob seed store failed: {ex.Message}"); }
}
/// <summary>
/// CombatManager.MobSeedLookup: the seed's damage types for a monster, best first (highest
/// Score), or null when the seed has nothing for it. Feeds the Auto element ranking only
/// after the server table and the learned element (see CreatureWeakness.Rank).
/// </summary>
private IReadOnlyList<string>? LookupMobSeed(uint wcid, string name)
{
var store = _mobSeedStore;
if (store == null || !store.TryGetRanked(wcid, name, out var ranked) || ranked.Count == 0)
return null;
var ordered = new List<RynthCore.CreatureSeed.UbMobSeedElement>(ranked);
ordered.Sort((a, b) => b.Score.CompareTo(a.Score));
var elements = new List<string>(ordered.Count);
foreach (var e in ordered) elements.Add(e.Element);
return elements;
}
/// <summary>Chat translator survives logout; session language resets on each login.</summary>
private void EnsureTranslator()
{
try
{
if (_translator == null)
{
_translator = new Translate.ChatTranslator(Host, CurrentCharacterName);
_translateUi = new Translate.TranslateUi(_translator);
}
_translator.ResetSession();
if (_huds != null) _huds.Translate = _translateUi;
}
catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, "translator init"); }
}
/// <summary>The logged-in character's name, or empty before login.</summary>
private string CurrentCharacterName()
=> _playerId != 0 && Host.HasGetObjectName && Host.TryGetObjectName(_playerId, out string name) ? name ?? string.Empty : string.Empty;
/// <summary>Waypoint HUD, labels, guide line, and the breadcrumb recorder.</summary>
private void CreateNavOverlay()
{
if (_dashboard == null) return;
_navBreadcrumbs = new NavBreadcrumbTracker(Host, _dashboard.Settings, DescribeNavPortal, ChatLine);
_navOverlay = new NavOverlayRenderer(Host, _dashboard.Settings, _navBreadcrumbs);
_dashboard.NavBreadcrumbs = _navBreadcrumbs; // Nav panel: trail -> route, trail stats
}
/// <summary>Nav recorder hook: (name, object class) when <paramref name="id"/> is a portal.</summary>
private (string Name, int ObjectClass)? DescribeNavPortal(uint id)
{
WorldObject? wo = _objectCache?[unchecked((int)id)];
if (wo == null || wo.ObjectClass != AcObjectClass.Portal || string.IsNullOrEmpty(wo.Name)) return null;
return (wo.Name, (int)AcObjectClass.Portal);
}
/// <summary>
/// ILT Hub and floating HUDs for the loaded character. No-op until the per-character
/// folder exists, so login and the deferred settings load in OnTick both call this.
/// </summary>
private void CreateIltHub()
{
if (_dashboard == null || string.IsNullOrEmpty(_dashboard.CharFolder) || _iltHub != null)
return;
var dash = _dashboard;
_iltHub = new IltHub.IltHubController(Host, dash.CharFolder,
() => _objectCache, () => dash.Settings, () => _questTracker,
() => dash.SaveSettings());
_hudIcons ??= new Huds.HudIconCache(Host, () => _raycast?.GeometryLoader?.PortalDat);
_huds = new Huds.HudController(Host, dash.CharFolder, () => _objectCache, dash, () => _iltHub, _hudIcons,
() => _combatManager?.activeTargetId ?? 0);
if (_translateUi != null) _huds.Translate = _translateUi;
// The Mini Remote is the Hub's main window: "/ra hub [show|hide|toggle]" drives it, and
// while it is up the Hub keeps its bank / gear data fresh.
var huds = _huds;
_iltHub.MiniRemoteCommand = mode => "[ILT Hub] " + huds.HandleCommand("remote", mode);
_iltHub.MiniRemoteVisible = () => huds.State.ShowMiniRemote;
EnsureItemInfoUi();
}
/// <summary>Item Info window, created once settings exist.</summary>
private void EnsureItemInfoUi()
{
if (_dashboard == null || _itemInfoUi != null) return;
_itemInfoUi = new LegacyItemInfoUi(_dashboard.Settings);
_itemInfoUi.SetHooks(DescribeSelectedItemForPreview, PrintSelectedItemInfo, TestItemInfoChatType);
}
/// <summary>Pump-thread work for the ported features. Safe before login (each call is null-checked).</summary>
private void TickLocalFeatures()
{
try { RynthLog.Pump(); }
catch (Exception ex) { Host.Log($"[RynthAi] diagnostics pump: {ex.Message}"); }
try { _iltHub?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "Tick"); }
try { _huds?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "Tick"); }
try { _translator?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, "translator Tick"); }
try { TickItemInfo(); }
catch (Exception ex) { RynthLog.Exception(LogCat.General, ex, "item info tick"); }
try { _navBreadcrumbs?.Tick(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Navigation, ex, "nav breadcrumbs tick"); }
}
/// <summary>Drop per-character feature objects. The translator is disposed only on plugin shutdown.</summary>
private void TeardownLocalFeatures(bool disposeTranslator)
{
try { _navBreadcrumbs?.Shutdown(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Navigation, ex, "nav recorder shutdown"); }
_navBreadcrumbs = null;
if (_dashboard != null) _dashboard.NavBreadcrumbs = null;
_navOverlay = null;
try { _iltHub?.OnLogout(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "logout"); }
_iltHub = null;
try { _huds?.OnLogout(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "logout"); }
_huds = null;
_itemInfoUi = null;
ResetGroundLoot(clearCaches: true);
if (!disposeTranslator) return;
try { _translator?.Dispose(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, "translator dispose"); }
_translator = null;
_translateUi = null;
}
/// <summary>ILT Hub may eat a server reply; the translator records the line either way.</summary>
private void OnChatLocalFeatures(string text, int chatType, ref int eat)
{
try
{
if (_iltHub?.OnChat(text) == true) eat = 1;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnChat"); }
try { _translator?.OnChatWindowText(text, chatType); }
catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, "translator inbound"); }
}
/// <summary>True when the translator swallowed an outbound chat line (it will resend the translation).</summary>
private bool TryEatOutboundTranslation(string trimmed)
{
try
{
return _translator != null && _translator.TryInterceptOutbound(trimmed);
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.Chat, ex, "translator outbound");
return false;
}
}
/// <summary>ImGui windows the engine panels do not draw.</summary>
public override void OnRender()
{
if (!_initialized || !_loginComplete || Host.ImGuiContext == IntPtr.Zero)
return;
IntPtr previousContext = ImGui.GetCurrentContext();
ImGui.SetCurrentContext(Host.ImGuiContext);
try
{
DetectItemInfoClick();
_navOverlay?.Render();
_itemInfoUi?.Render();
_iltHub?.Render();
_huds?.Render();
RenderTranslateWindow();
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.UI, ex, "OnRender");
}
finally
{
ImGui.SetCurrentContext(previousContext);
}
}
/// <summary>
/// Called when the engine's ImGui shell is off. Same local windows as <see cref="OnRender"/>;
/// the engine panels are absent in that mode, so these windows are the only UI for them.
/// </summary>
public void OnRenderOverlay()
{
if (!_initialized || !_loginComplete || Host.ImGuiContext == IntPtr.Zero)
{
string reason = !_initialized ? "not initialized" : !_loginComplete ? "login not complete" : "no ImGui context";
if (reason != _overlaySkipReasonLogged)
{
_overlaySkipReasonLogged = reason;
RynthLog.Write(LogCat.UI, $"[Overlay] OnRenderOverlay skipped: {reason}.");
}
return;
}
if (!_overlayEnteredLogged)
{
_overlayEnteredLogged = true;
RynthLog.Write(LogCat.UI, $"[Overlay] OnRenderOverlay drawing (iltHub={(_iltHub != null ? "ready" : "null")}).");
}
IntPtr previousContext = ImGui.GetCurrentContext();
ImGui.SetCurrentContext(Host.ImGuiContext);
try
{
DetectItemInfoClick();
int pushedColors = LegacyDashboardRenderer.PushDashboardStyle();
try { _iltHub?.Render(); }
finally { ImGui.PopStyleColor(pushedColors); }
_huds?.Render();
RenderTranslateWindow();
_navOverlay?.Render();
_itemInfoUi?.Render();
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.UI, ex, "OnRenderOverlay");
}
finally
{
ImGui.SetCurrentContext(previousContext);
}
}
/// <summary>Chat Translate window in the dashboard colours (no-op while hidden).</summary>
private void RenderTranslateWindow()
{
var ui = _translateUi;
if (ui == null || _translator?.Settings.ShowWindow != true) return;
int pushedColors = LegacyDashboardRenderer.PushDashboardStyle();
try { ui.RenderWindow(); }
finally { ImGui.PopStyleColor(pushedColors); }
}
/// <summary>"/ra huds|itemhud|remote|miniremote [show|hide|toggle]".</summary>
private void HandleHudCommand(string which, string mode)
{
if (_huds == null) { ChatLine("[RynthAi] HUDs not ready (log in first)."); return; }
ChatLine("[RynthAi] " + _huds.HandleCommand(which, mode));
}
/// <summary>Skills panel Progression tab snapshot (RynthPluginGetProgressionJson). Pump thread.</summary>
internal string BuildProgressionJson() => _iltHub?.BuildProgressionJson() ?? "{\"available\":false}";
/// <summary>Settings panel Charms Tracking tab snapshot (RynthPluginGetCharmsJson). Pump thread.</summary>
internal string BuildCharmsJson() => _iltHub?.BuildCharmsJson() ?? "{\"available\":false}";
/// <summary>"prog ..." remote command from the Skills panel's Progression tab. Pump thread.</summary>
private void HandleProgressionRemote(string value)
{
if (_iltHub == null) { ChatLine("[RynthAi] ILT Hub not ready (log in first)."); return; }
_iltHub.Progression.HandleRemote(value.Split(' ', StringSplitOptions.RemoveEmptyEntries));
}
/// <summary>"/ra itemhud add &lt;name&gt;" and the inventory panel's "Add to item count HUD". Pump thread.</summary>
private void HandleItemHudAdd(string name)
{
if (_huds == null) { ChatLine("[RynthAi] HUDs not ready (log in first)."); return; }
if (string.IsNullOrWhiteSpace(name)) { ChatLine("[RynthAi] Usage: /ra itemhud add <item name>"); return; }
ChatLine("[RynthAi] " + _huds.AddToItemHudAndShow(name));
}
/// <summary>/ra translate ... — forwards to the chat translator.</summary>
private void HandleTranslateCommand(string[] parts)
{
if (_translator == null) { ChatLine("[RynthAi] Chat translator not ready (log in first)."); return; }
_translator.HandleCommand(parts.Length > 2 ? parts[2..] : Array.Empty<string>(), ChatLine);
}
/// <summary>Parses an on/off word; returns null for anything else (caller treats it as status).</summary>
private static bool? ParseOnOff(string? word) => word?.ToLowerInvariant() switch
{
"on" or "true" or "1" or "enable" => true,
"off" or "false" or "0" or "disable" => false,
_ => null,
};
/// <summary>"/ra debug [on|off|status]" — echoes trace and exception lines to chat.</summary>
private void HandleDebugCommand(string[] parts)
{
string arg = parts.Length > 2 ? parts[2] : "status";
bool? state = arg.Equals("toggle", StringComparison.OrdinalIgnoreCase) ? !RynthLog.DebugToChat : ParseOnOff(arg);
if (state.HasValue) RynthLog.DebugToChat = state.Value;
ChatLine($"[RynthAi] Debug-to-chat is {(RynthLog.DebugToChat ? "ON" : "off")}."
+ (RynthLog.DebugToChat && RynthLog.TracedCategories().Count == 0 ? " (no categories traced — see /ra trace list)" : ""));
}
/// <summary>"/ra trace &lt;cat|all|ilt|list&gt; [on|off|status]".</summary>
private void HandleTraceCommand(string[] parts)
{
string target = parts.Length > 2 ? parts[2] : "status";
string? action = parts.Length > 3 ? parts[3] : null;
if (target.Equals("status", StringComparison.OrdinalIgnoreCase))
{
foreach (string l in RynthLog.StatusLines()) ChatLine(l);
return;
}
if (target.Equals("list", StringComparison.OrdinalIgnoreCase))
{
var names = new System.Collections.Generic.List<string>();
foreach (LogCat c in Enum.GetValues<LogCat>())
names.Add(RynthLog.IsTracing(c) ? c + "*" : c.ToString());
ChatLine("[RynthAi] Trace categories (* = on): " + string.Join(", ", names));
return;
}
bool? state = ParseOnOff(action);
bool isAll = target.Equals("all", StringComparison.OrdinalIgnoreCase);
bool isIlt = target.Equals("ilt", StringComparison.OrdinalIgnoreCase);
if (isAll || isIlt)
{
if (!state.HasValue) { foreach (string l in RynthLog.StatusLines()) ChatLine(l); return; }
int n = RynthLog.SetTracingByPrefix(isIlt ? "Ilt" : string.Empty, state.Value);
ChatLine($"[RynthAi] Tracing {(state.Value ? "enabled" : "disabled")} for {n} {(isIlt ? "ILT Hub " : "")}categories.");
return;
}
if (!RynthLog.TryParseCategory(target, out LogCat cat))
{
ChatLine($"[RynthAi] Unknown trace category '{target}'. Use /ra trace list.");
return;
}
if (action != null && action.Equals("status", StringComparison.OrdinalIgnoreCase))
{
ChatLine($"[RynthAi] Trace {cat}: {(RynthLog.IsTracing(cat) ? "ON" : "off")}");
return;
}
bool enable = state ?? !RynthLog.IsTracing(cat);
RynthLog.SetTracing(cat, enable);
ChatLine($"[RynthAi] Trace {cat}: {(enable ? "ON" : "off")} → {RynthLog.TraceDirectory}");
}
/// <summary>"/ra logs [open|prune|flush|file on|off]".</summary>
private void HandleLogsCommand(string[] parts)
{
string sub = parts.Length > 2 ? parts[2].ToLowerInvariant() : "status";
switch (sub)
{
case "open":
try
{
RynthLog.Flush();
System.IO.Directory.CreateDirectory(RynthLog.Directory);
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("explorer.exe", $"\"{RynthLog.Directory}\"") { UseShellExecute = true });
}
catch (Exception ex) { RynthLog.Exception(LogCat.Commands, ex, "logs open"); ChatLine($"[RynthAi] Could not open {RynthLog.Directory}: {ex.Message}"); }
break;
case "prune":
ChatLine($"[RynthAi] Pruned {RynthLog.Prune()} old diagnostics file(s).");
break;
case "flush":
RynthLog.Flush();
ChatLine("[RynthAi] Diagnostics flushed to disk.");
break;
case "file":
bool? state = ParseOnOff(parts.Length > 3 ? parts[3] : null);
if (state.HasValue) RynthLog.FileLogAll = state.Value;
ChatLine($"[RynthAi] Daily RynthAi log file is {(RynthLog.FileLogAll ? "ON" : "off")}.");
break;
default:
foreach (string l in RynthLog.StatusLines()) ChatLine(l);
break;
}
}
/// <summary>/ra navrec [on|off] — toggles route recording.</summary>
private void HandleNavRecordCommand(string[] parts)
{
if (_dashboard == null) return;
var s = _dashboard.Settings;
string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : "";
s.IsRecordingNav = arg switch { "on" => true, "off" => false, _ => !s.IsRecordingNav };
ChatLine($"[RynthAi] Nav recording {(s.IsRecordingNav ? "ON — walk the route; portals are captured" : "OFF")}.");
}
/// <summary>/ra navhud [on|off] — shows or hides the navigation HUD window.</summary>
private void HandleNavHudCommand(string[] parts)
{
if (_dashboard == null) return;
var o = _dashboard.Settings.NavOverlay;
string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : "";
o.ShowHud = arg switch { "on" => true, "off" => false, _ => !o.ShowHud };
ChatLine($"[RynthAi] Nav HUD {(o.ShowHud ? "shown" : "hidden")}.");
}
/// <summary>/ra navtrail [on|off|toggle|clear] — breadcrumb tracking switch, wipe, or a status report.</summary>
private void HandleNavTrailCommand(string[] parts)
{
string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : "";
if (arg == "clear")
{
_navBreadcrumbs?.RequestClear();
ChatLine("[RynthAi] Breadcrumb trail cleared.");
return;
}
if (arg is "on" or "off" or "toggle")
{
if (_dashboard == null) return;
var o = _dashboard.Settings.NavOverlay;
o.TrackBreadcrumbs = arg switch { "on" => true, "off" => false, _ => !o.TrackBreadcrumbs };
_dashboard.SaveSettings();
ChatLine($"[RynthAi] Breadcrumb tracking {(o.TrackBreadcrumbs ? "on" : "off")}.");
return;
}
bool tracking = _dashboard?.Settings.NavOverlay.TrackBreadcrumbs ?? false;
int n = _navBreadcrumbs?.Trail.Length ?? 0;
double yd = _navBreadcrumbs?.TrailYards ?? 0;
ChatLine($"[RynthAi] Breadcrumbs {(tracking ? "on" : "off")}: {n} points, {yd:F0} yd. Use /ra navtrail on|off|clear.");
}
/// <summary>/ra navoverlay [on|off] — route overlay (rings / lines, waypoint labels, guide line); no argument toggles.</summary>
private void HandleNavOverlayCommand(string[] parts)
{
if (_dashboard == null) return;
var o = _dashboard.Settings.NavOverlay;
string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : "";
o.ShowRouteMarkers = arg switch { "on" => true, "off" => false, _ => !o.ShowRouteMarkers };
_dashboard.SaveSettings();
ChatLine($"[RynthAi] Route overlay {(o.ShowRouteMarkers ? "on" : "off")}.");
}
}

View file

@ -164,6 +164,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// constructor does no ImGui work. (RynthAi no longer exports RynthPluginRender
// and never reads Host.ImGuiContext.)
ComponentDatabase.SetLog(msg => Log(msg));
InitLocalDiagnostics();
// The overlay windows (OnRenderOverlay) must draw through the engine's cimgui module.
ImGuiNativeBinding.Ensure();
_dashboard = new LegacyDashboardRenderer(Host);
// Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line
// each, and no automatic door/corpse use while the macro is off.
@ -232,6 +235,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
}
catch { }
long tAfterGc = Environment.TickCount64;
try { _translator?.Dispose(); } catch { }
_translator = null;
_translateUi = null;
try { RynthLog.Shutdown(); } catch { }
Log($"RynthAi: Shutdown done — SaveSettings={tAfterSettings - t0} ms, TeardownSession={tAfterTeardown - tAfterSettings} ms, SaveCreatureStore={tAfterStore - tAfterTeardown} ms, GC={tAfterGc - tGc} ms (heap now {GC.GetGCMemoryInfo().HeapSizeBytes / (1024 * 1024)} MB), total={tAfterGc - t0} ms");
}
@ -390,6 +397,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_autoVendor = null;
_autoTrade?.Reset();
_autoTrade = null;
TeardownLocalFeatures(disposeTranslator: false);
_playerId = 0;
_loginComplete = false;
_pendingGives.Clear();
@ -454,6 +462,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_loginComplete = true;
_dashboard.OnLoginComplete();
_dashboard.ChatSubmitHandler = HandleRynthChatSubmit;
EnsureTranslator();
EnsureItemInfoUi();
_navigationEngine = new NavigationEngine(Host, _dashboard.Settings)
{
ChatSubmit = HandleRynthChatSubmit,
@ -480,6 +490,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
GeometrySource = () => _raycast is { IsInitialized: true } rc ? rc.GeometryLoader : null,
};
CreateNavOverlay();
_radarWallRenderer = new RadarWallRenderer(Host, _dashboard.Settings);
_terrainOverlay = new TerrainPassabilityOverlay(Host);
Log($"RynthAi: NavMarkerRenderer created, HasNav3D={Host.HasNav3D}, version={Host.Version}");
@ -614,6 +625,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager.SetCharacterSkills(_charSkills);
_combatManager.SetPlayerId(_playerId);
_combatManager.SetDamageStores(_creatureStore, _damageStore);
_combatManager.MobSeedLookup = LookupMobSeed;
_combatManager.SetAwakenedTier(_tier);
// The raycast init thread may already have finished (warm dats): hand it over now.
WireRaycastIntoCombat();
@ -658,6 +670,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager.SummonOut = () => _petManager?.CurrentSummon();
}
CreateIltHub();
if (_iltHub?.SkipLoginQuestRefresh == true)
Log("RynthAi: ILT Hub says /myquests is off on this server; login quest refresh already ran.");
try
{
string hubChar = CurrentCharacterName();
_iltHub?.OnLoginComplete(hubChar, _petManager);
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "login"); }
_salvageManager = new SalvageManager(Host, _dashboard.Settings, _objectCache);
// Hand the salvage manager a live accessor for the loot profile's
// SalvageCombine config so combining respects per-material workmanship
@ -814,15 +836,64 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "hideui": _hideUi = on; dash.SetUiHidden(on); break; // applied each tick in OnTick
case "sendchat": if (!string.IsNullOrEmpty(value)) HandleRynthChatSubmit(value); break;
case "setsetting": ApplyRemoteSetting(value); break; // one advanced setting from the phone (clamped + persisted)
case "hub":
case "quests":
case "pets":
case "guardian":
// Dashboard Char launcher (hub=show opens the Mini Remote) and its right-click menu
// (hub=open <section> toggle); value carries the "/ra hub|quests|pets" arguments.
if (_iltHub == null) { ChatLine("[RynthAi] ILT Hub not ready (log in first)."); break; }
_iltHub.HandleCommand(action.ToLowerInvariant(), value.Split(' ', StringSplitOptions.RemoveEmptyEntries));
break;
case "huds":
case "itemhud":
case "remote":
case "miniremote":
// Dashboard Hub launcher: left-click remote=toggle, right-click huds=show.
HandleHudCommand(action.ToLowerInvariant(), value);
break;
case "itemhudadd":
// Inventory panel "Add to item count HUD"; value is the item name.
HandleItemHudAdd(value);
break;
case "remoteslot":
// Inventory panel "Add to Mini Remote"; value is "<slot 1-30|first> <objectId>".
if (_huds == null) { ChatLine("[RynthAi] HUDs not ready (log in first)."); break; }
if (!_huds.HandleRemoteSlot(value)) Host.Log($"[RynthAi] bad remoteslot value: {value}");
break;
case "prog":
// Skills panel Progression tab (augmentations / enlightenment edits).
HandleProgressionRemote(value);
break;
case "trace":
case "logs":
case "iteminfo":
// Settings panel buttons (Diagnostics tab, Item Info options); value carries the
// same arguments as "/ra trace|logs|iteminfo ...".
{
var args = new List<string> { "/ra", action.ToLowerInvariant() };
args.AddRange(value.Split(' ', StringSplitOptions.RemoveEmptyEntries));
string[] parts = args.ToArray();
switch (parts[1])
{
case "trace": HandleTraceCommand(parts); break;
case "logs": HandleLogsCommand(parts); break;
case "iteminfo": HandleItemInfoCommand(parts); break;
}
}
break;
// movestart/movestop are applied DIRECTLY by the RynthRemote plugin (pure Host.SetAutoRun/
// SetMotion + its own dead-man watchdog) and are never forwarded here.
default:
Host.Log($"[RynthAi] ignored unknown remote command: {action}={value}");
return;
}
Host.Log($"[RynthAi] applied remote command: {action}={value}");
}
// Settings the phone must never write (engine-populated read-only status).
private static readonly HashSet<string> ReadOnlySettingKeys = new(StringComparer.OrdinalIgnoreCase)
{ "MissileCraftingState", "MissileCraftingActive", "MissileCraftingStatus" };
{ "MissileCraftingState", "MissileCraftingActive", "MissileCraftingStatus", "DiagFolder" };
// Authoritative server-side clamp (min,max) per numeric setting — a bad/garbage phone value can never
// push a setting out of range and brick a client. Ranges mirror the in-AC SettingsPanel rows. Booleans
@ -1332,6 +1403,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_buffManager?.SetTimerPath(_dashboard.CharFolder);
_damageStore?.SetCharacter(_dashboard.CharFolder);
_patrolOnLoginPending = _dashboard.Settings.PatrolOnLogin;
if (_iltHub == null)
{
CreateIltHub();
try { _iltHub?.OnLoginComplete(lateName, _petManager); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "late login"); }
}
Log($"RynthAi: per-character settings established late for '{lateName}' (early OnLoginComplete read had failed).");
}
}
@ -1359,6 +1436,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// longer calls, so edits waited for the next login. A flag check when idle.
_dashboard?.TickMonsterReload();
_questTracker?.Tick();
TickLocalFeatures();
if (diag) Host.Log("[RynthAi] OnTick: after quest tracker");
DrainGiveQueue();
if (diag) Host.Log("[RynthAi] OnTick: after drain give queue");
@ -1926,7 +2004,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// this fires even when an early return short-circuits the body
// (Buffing / missile-crafting / BoostNavPriority branches).
if (Host.HasNav3D)
{
_navMarkerRenderer?.SubmitNav3D();
_navOverlay?.SubmitNav3D();
}
}
}
}
@ -1966,7 +2047,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
WorldObject? obj = _objectCache?[sid];
// Skip non-items (monsters, players, NPCs, doors, corpses, portals, etc.)
if (obj != null && IsLootableClass(obj.ObjectClass))
{
InspectLootRuleForItem(sid, quiet: true);
var itemInfo = _dashboard?.Settings.ItemInfoSettings;
if (itemInfo != null && ItemInfoWantsClass(itemInfo, obj.ObjectClass))
QueueAutoItemInfo(sid, requestId: false);
}
}
}
@ -1991,6 +2077,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
try { mmEat = MetaScheduleChat(text); } catch { }
if (mmEat) eat = 1;
else _dashboard?.PushChatLine(text, chatType);
OnChatLocalFeatures(text, chatType, ref eat);
_buffManager?.OnChatWindowText(text, chatType);
_manaStoneManager?.OnChatWindowText(text);
_petManager?.OnChatWindowText(text);
@ -2013,6 +2100,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (string.IsNullOrEmpty(deathMessage)) return;
_combatManager?.OnKillNotification(deathMessage);
_dashboard?.RecordKill(); // feeds the kills/hour session stat
try { _iltHub?.RecordKill(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "kill"); }
}
public override void OnCreateObject(uint objectId)
@ -2868,6 +2957,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
return;
string trimmed = text.Trim();
if (TryEatOutboundTranslation(trimmed))
{
eat = 1;
return;
}
NoteChatBarLineForMetaSchedule(trimmed);
// Mag-Tools /mt command compatibility
@ -3031,6 +3125,32 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "scan": HandleScanCommand(); break;
case "buildinfo": HandleBuildInfoCommand(); break;
case "navdebug": HandleNavDebugCommand(); break;
case "navrec": HandleNavRecordCommand(parts); break;
case "navhud": HandleNavHudCommand(parts); break;
case "navtrail": HandleNavTrailCommand(parts); break;
case "navoverlay": HandleNavOverlayCommand(parts); break;
case "debug": HandleDebugCommand(parts); break;
case "trace": HandleTraceCommand(parts); break;
case "logs": HandleLogsCommand(parts); break;
case "hub":
case "quests":
case "pets":
case "guardian":
if (_iltHub == null) { ChatLine("[RynthAi] ILT Hub not ready (log in first)."); break; }
_iltHub.HandleCommand(cmd, parts.Length > 2 ? parts[2..] : Array.Empty<string>());
break;
case "itemhud" when parts.Length > 2 && parts[2].Equals("add", StringComparison.OrdinalIgnoreCase):
HandleItemHudAdd(string.Join(" ", parts, 3, parts.Length - 3));
break;
case "huds":
case "itemhud":
case "remote":
case "miniremote": HandleHudCommand(cmd, parts.Length > 2 ? parts[2] : string.Empty); break;
case "translate":
case "tr": HandleTranslateCommand(parts); break;
case "iteminfo":
case "ii": HandleItemInfoCommand(parts); break;
case "groundloot": HandleGroundLootCommand(parts); break;
case "addnavpt": HandleAddNavPointCommand(); break;
case "nav": HandleNavCommand(parts); break;
case "lua": ForwardLuaCommand(parts); break;

View file

@ -29,6 +29,10 @@
</ItemGroup>
<ItemGroup>
<!-- Install-folder resolver used by the ILT Hub, diagnostics, and chat translator. -->
<Compile Include="..\..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- UB damage-insights seed schema, shared with the Monster Editor importer. -->
<Compile Include="..\..\Shared\UbMobSeed.cs" Link="Shared\UbMobSeed.cs" />
<!-- Interfaces shared with other RynthSuite plugins (RynthLua uses RynthAi.Script, RynthNet RynthAi.Status). -->
<Compile Include="..\Shared\RynthAiScriptApi.cs" Link="Shared\RynthAiScriptApi.cs" />
<!-- RynthNet reads the bot state through RynthAi.Status. -->

View file

@ -0,0 +1,49 @@
// AcChatEscapes.cs — AC chat text helpers for the translator.
//
// AC carries characters above Latin-1 (Hangul, CJK, Cyrillic, ...) in chat as "<hhhh>" UTF-16 escapes,
// and the outbound chat path converts each char to one byte, so anything above U+00FF must be escaped
// before sending. Latin-1 letters (ä ö ü ñ é) stay literal; escaping them shows "<00e4>" in chat.
// Speaker names arrive wrapped in "<Tell:IIDString:id:Name>Name<\Tell>" link markup.
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthAi.Translate;
internal static class AcChatEscapes
{
private static readonly Regex RxEscape = new(@"<([0-9a-fA-F]{4})>", RegexOptions.CultureInvariant);
private static readonly Regex RxTellLink = new(@"<Tell:[^>]*>(?<n>[^<]*)<\\Tell>", RegexOptions.CultureInvariant);
/// <summary>Expands "&lt;c2dc&gt;" escapes into the characters they stand for.</summary>
public static string Decode(string text)
{
if (string.IsNullOrEmpty(text) || text.IndexOf('<') < 0) return text ?? string.Empty;
return RxEscape.Replace(text, m =>
{
int cp = int.Parse(m.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
return cp is > 0 and <= 0xFFFF ? ((char)cp).ToString() : m.Value;
});
}
/// <summary>Escapes characters above U+00FF as "&lt;hhhh&gt;"; drops other control characters.</summary>
public static string EncodeForSend(string text)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
var sb = new StringBuilder(text.Length + 16);
foreach (char c in text)
{
if (c == '\r' || c == '\n' || c == '\t') { sb.Append(' '); continue; }
if (c < 0x20) continue;
if (c <= 0xFF) { sb.Append(c); continue; }
sb.Append('<').Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)).Append('>');
}
return sb.ToString().Trim();
}
/// <summary>Replaces tell-link markup with the plain name it wraps.</summary>
public static string StripLinks(string text)
=> string.IsNullOrEmpty(text) || text.IndexOf("<Tell:", System.StringComparison.Ordinal) < 0
? text ?? string.Empty
: RxTellLink.Replace(text, "${n}");
}

View file

@ -0,0 +1,600 @@
// ChatTranslator.cs — Auto-translation of AC chat (UB-IT ChatTranslateTool port, multi-provider).
//
// Inbound chat lines on the ticked channels are translated into the receive language and written
// back to chat as "[Translate] [Channel] Name (es): text". Host.WriteToChat output passes the
// engine's chat hook, so it shows in AC's chat window and in RynthChat.
// Outbound typed lines on the ticked channels are swallowed, translated into the send language and
// resent with the same command prefix ("/f ", "/t Bob, ", ...).
//
// Threads OnChatWindowText / TryInterceptOutbound / UI calls only enqueue (any thread). Tick runs on
// the plugin pump thread: it owns the queues, starts one HTTP request at a time (spaced by
// MinIntervalMs) and applies results. The window reads the log through a lock.
//
// Host.WriteToChat off AC's main thread drops calls made within 100 ms of the previous one, so echoes
// go through a queue drained at EchoSpacingMs and retried when the host reports a drop.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Translate;
internal enum TranslateDirection { In, Out, Test }
/// <summary>One line in the Translate window log (immutable once added).</summary>
internal sealed record TranslateLogEntry(
DateTime Time,
TranslateDirection Direction,
TranslateChannel? Channel,
string Speaker,
string Original,
string Translated,
string From,
string To,
string Error);
internal sealed class ChatTranslator : IDisposable
{
/// <summary>Prefix of every line the translator writes, so its own echoes are never re-translated.</summary>
public const string EchoPrefix = "[Translate]";
private const int EchoSpacingMs = 150;
private const int EchoMaxAttempts = 20;
private const int MaxInboundQueue = 40;
private const int DedupWindowMs = 5000;
private const int ResendGuardMs = 15000;
private const int SaveEveryMs = 2000;
private const int ErrorChatEveryMs = 30000;
private const int ChatTypeSystem = 1;
private const int ChatTypeSpellcasting = 0x11;
private enum JobKind { Inbound, Outbound, SendRaw, Test }
private sealed record Job(JobKind Kind, TranslateChannel? Channel, string Speaker, string Text,
string Source, string Target, string Prefix);
private readonly RynthCoreHost _host;
private readonly Func<string> _myName;
private readonly TranslateStore _store;
private readonly CancellationTokenSource _cts = new();
// Any thread → pump.
private readonly ConcurrentQueue<Job> _incoming = new();
private readonly ConcurrentQueue<(Job Job, TranslateResult Result)> _done = new();
// Translated bodies we are about to resend; OnChatBarEnter lets these through untouched.
private readonly ConcurrentDictionary<string, long> _resend = new(StringComparer.Ordinal);
// Pump thread only.
private readonly Queue<Job> _outQueue = new();
private readonly LinkedList<Job> _inQueue = new();
private readonly Dictionary<string, long> _recent = new(StringComparer.Ordinal);
private readonly Queue<(string Text, int ChatType, int Attempts)> _echo = new();
private long _lastEchoMs;
private long _lastStartMs;
private long _lastSaveMs;
private long _lastErrorChatMs = -ErrorChatEveryMs;
private int _inFlight;
private readonly object _logLock = new();
private readonly List<TranslateLogEntry> _log = new();
private TranslateLogEntry[] _logSnapshot = Array.Empty<TranslateLogEntry>();
public TranslateSettings Settings { get; }
/// <summary>Last provider error (empty after a success). Read by the UI.</summary>
public string LastError { get; private set; } = string.Empty;
/// <summary>Characters sent to the provider this session (most plans bill per character).</summary>
public long CharsSent => Interlocked.Read(ref _charsSent);
private long _charsSent;
public int Translated => Volatile.Read(ref _translated);
private int _translated;
/// <summary>Requests waiting or in flight (approximate when read off the pump thread).</summary>
public int Pending => _inQueue.Count + _outQueue.Count + _incoming.Count + Volatile.Read(ref _inFlight);
public ChatTranslator(RynthCoreHost host, Func<string> myName, TranslateStore? store = null)
{
_host = host;
_myName = myName;
_store = store ?? new TranslateStore();
Settings = _store.Load();
}
/// <summary>Per-login reset: send language back to the default, queues cleared.</summary>
public void ResetSession()
{
Settings.CurrentSendLanguage = Settings.DefaultSendLanguage;
while (_incoming.TryDequeue(out _)) { }
_outQueue.Clear();
_inQueue.Clear();
_echo.Clear();
_recent.Clear();
_resend.Clear();
}
// ── Entry points (any thread) ──────────────────────────────────────────
/// <summary>Inbound chat line from the AC chat window.</summary>
public void OnChatWindowText(string text, int chatType)
{
var s = Settings;
if (!s.Enabled || !s.EnableInbound || string.IsNullOrEmpty(text)) return;
if (chatType == ChatTypeSpellcasting || text.StartsWith(EchoPrefix, StringComparison.Ordinal)) return;
if (!TryParseInbound(text, chatType, out var ch, out string speaker, out string msg, out bool own)) return;
if (!s.ListensTo(ch) || (own && s.SkipOwn)) return;
if (IsOwnName(speaker) && s.SkipOwn) return;
msg = AcChatEscapes.Decode(msg).Trim();
if (msg.Length == 0) return;
_incoming.Enqueue(new Job(JobKind.Inbound, ch, speaker, msg, s.InboundSource, s.MyLanguage, string.Empty));
}
/// <summary>
/// Typed chat line (OnChatBarEnter). Returns true when the translator took it over and the caller
/// must swallow the original.
/// </summary>
public bool TryInterceptOutbound(string text)
{
var s = Settings;
if (!TranslateChannels.TryParseOutbound(text, out var line)) return false;
string body = line.Body.Trim();
if (_resend.TryRemove(body, out _)) return false;
if (!s.Enabled || !s.EnableOutbound || !s.SendsOn(line.Channel) || body.Length == 0) return false;
if (s.RawPrefix.Length > 0 && body.StartsWith(s.RawPrefix, StringComparison.Ordinal))
{
string raw = body.Substring(s.RawPrefix.Length).TrimStart();
if (raw.Length == 0) return false;
_incoming.Enqueue(new Job(JobKind.SendRaw, line.Channel, string.Empty, raw, string.Empty, string.Empty, line.Prefix));
return true;
}
string target = s.CurrentSendLanguage;
if (TranslateLanguages.BaseOf(target) == TranslateLanguages.BaseOf(s.MyLanguage)) return false;
_incoming.Enqueue(new Job(JobKind.Outbound, line.Channel, string.Empty, body, TranslateLanguages.Auto, target, line.Prefix));
return true;
}
/// <summary>Translate window compose box: translate into the send language and send on <paramref name="ch"/>.</summary>
public void Compose(TranslateChannel ch, string tellTarget, string text)
{
text = (text ?? string.Empty).Trim();
if (text.Length == 0) return;
var s = Settings;
string prefix = TranslateChannels.SendPrefix(ch, tellTarget);
bool same = TranslateLanguages.BaseOf(s.CurrentSendLanguage) == TranslateLanguages.BaseOf(s.MyLanguage);
_incoming.Enqueue(same
? new Job(JobKind.SendRaw, ch, string.Empty, text, string.Empty, string.Empty, prefix)
: new Job(JobKind.Outbound, ch, string.Empty, text, TranslateLanguages.Auto, s.CurrentSendLanguage, prefix));
}
/// <summary>Translates <paramref name="text"/> into <paramref name="target"/> (send language when null) without sending.</summary>
public void Test(string text, string? target = null)
{
text = (text ?? string.Empty).Trim();
if (text.Length == 0) return;
_incoming.Enqueue(new Job(JobKind.Test, null, string.Empty, text, TranslateLanguages.Auto,
target ?? Settings.CurrentSendLanguage, string.Empty));
}
// ── Pump thread ────────────────────────────────────────────────────────
public void Tick()
{
long now = Environment.TickCount64;
DrainIncoming(now);
while (_done.TryDequeue(out var d)) ApplyResult(d.Job, d.Result);
StartNextRequest(now);
DrainEcho(now);
if (now - _lastSaveMs >= SaveEveryMs)
{
_lastSaveMs = now;
PruneGuards(now);
_store.SaveIfDirty(Settings);
}
}
private void DrainIncoming(long now)
{
while (_incoming.TryDequeue(out var job))
{
switch (job.Kind)
{
case JobKind.SendRaw:
Send(job.Prefix, job.Text);
AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.Out, job.Channel, string.Empty,
job.Text, job.Text, string.Empty, string.Empty, "sent untranslated"));
break;
case JobKind.Inbound:
string key = $"{job.Channel}|{job.Speaker}|{job.Text}";
if (_recent.TryGetValue(key, out long seen) && now - seen < DedupWindowMs) break;
_recent[key] = now;
while (_inQueue.Count >= MaxInboundQueue) _inQueue.RemoveFirst();
_inQueue.AddLast(job);
break;
default:
_outQueue.Enqueue(job);
break;
}
}
}
private void StartNextRequest(long now)
{
if (Volatile.Read(ref _inFlight) != 0) return;
if (now - _lastStartMs < Settings.MinIntervalMs) return;
Job? job = null;
if (_outQueue.Count > 0) job = _outQueue.Dequeue();
else if (_inQueue.Count > 0) { job = _inQueue.First!.Value; _inQueue.RemoveFirst(); }
if (job == null) return;
var s = Settings;
if (!s.Enabled && job.Kind == JobKind.Inbound) return;
_lastStartMs = now;
Volatile.Write(ref _inFlight, 1);
Interlocked.Add(ref _charsSent, job.Text.Length);
string provider = s.Provider, key = s.ApiKey, url = s.ApiUrl;
var ct = _cts.Token;
_ = Task.Run(async () =>
{
TranslateResult r;
try { r = await TranslateClient.TranslateAsync(provider, key, url, job.Text, job.Source, job.Target, ct).ConfigureAwait(false); }
catch (Exception ex) { r = TranslateResult.Fail(ex.Message); }
_done.Enqueue((job, r));
Volatile.Write(ref _inFlight, 0);
});
}
private void ApplyResult(Job job, TranslateResult r)
{
if (r.Ok) LastError = string.Empty;
else
{
LastError = r.Error;
RynthLog.Write(LogCat.Chat, $"[Translate] {job.Kind} failed: {r.Error}");
}
switch (job.Kind)
{
case JobKind.Inbound: ApplyInbound(job, r); break;
case JobKind.Outbound: ApplyOutbound(job, r); break;
case JobKind.Test: ApplyTest(job, r); break;
}
}
private void ApplyInbound(Job job, TranslateResult r)
{
if (!r.Ok)
{
AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.In, job.Channel, job.Speaker, job.Text,
string.Empty, job.Source, job.Target, r.Error));
ChatErrorThrottled(r.Error);
return;
}
string translated = r.Text.Trim();
// Already in the receive language, or nothing changed: stay quiet.
if (TranslateLanguages.BaseOf(r.DetectedSource) == TranslateLanguages.BaseOf(job.Target)) return;
if (translated.Length == 0 || string.Equals(translated, job.Text, StringComparison.OrdinalIgnoreCase)) return;
Interlocked.Increment(ref _translated);
AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.In, job.Channel, job.Speaker, job.Text,
translated, r.DetectedSource, job.Target, string.Empty));
if (Settings.EchoToChat && job.Channel is { } ch)
{
string from = r.DetectedSource.Length > 0 ? $" ({r.DetectedSource})" : string.Empty;
QueueEcho($"{EchoPrefix} [{TranslateChannels.Name(ch)}] {job.Speaker}{from}: {translated}", TranslateChannels.ChatType(ch));
}
}
private void ApplyOutbound(Job job, TranslateResult r)
{
string body;
if (r.Ok && r.Text.Trim().Length > 0)
{
body = r.Text.Trim();
Interlocked.Increment(ref _translated);
}
else if (Settings.SendOriginalOnError)
{
body = job.Text;
QueueEcho($"{EchoPrefix} Couldn't translate ({(r.Ok ? "empty result" : r.Error)}); sent the original.", ChatTypeSystem);
}
else
{
QueueEcho($"{EchoPrefix} Couldn't translate ({(r.Ok ? "empty result" : r.Error)}); message not sent.", ChatTypeSystem);
AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.Out, job.Channel, string.Empty, job.Text,
string.Empty, r.DetectedSource, job.Target, r.Ok ? "empty result" : r.Error));
return;
}
string sent = Send(job.Prefix, body);
AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.Out, job.Channel, string.Empty, job.Text,
sent, r.DetectedSource, job.Target, r.Ok ? string.Empty : r.Error));
if (r.Ok && Settings.EchoOutbound && job.Channel is { } ch)
QueueEcho($"{EchoPrefix} [{TranslateChannels.Name(ch)} -> {job.Target}] you typed: {job.Text}", TranslateChannels.ChatType(ch));
}
private void ApplyTest(Job job, TranslateResult r)
{
AddLog(new TranslateLogEntry(DateTime.Now, TranslateDirection.Test, null, string.Empty, job.Text,
r.Ok ? r.Text : string.Empty, r.DetectedSource, job.Target, r.Error));
QueueEcho(r.Ok
? $"{EchoPrefix} Test ({(r.DetectedSource.Length > 0 ? r.DetectedSource : "?")} -> {job.Target}): {r.Text}"
: $"{EchoPrefix} Test failed: {r.Error}", ChatTypeSystem);
}
/// <summary>Sends <paramref name="prefix"/> + body through the chat parser; returns the body as sent.</summary>
private string Send(string prefix, string body)
{
string encoded = AcChatEscapes.EncodeForSend(body);
if (encoded.Length == 0) return string.Empty;
_resend[encoded] = Environment.TickCount64;
bool ok = _host.HasInvokeChatParser && _host.InvokeChatParser(prefix + encoded);
if (!ok)
{
_resend.TryRemove(encoded, out _);
QueueEcho($"{EchoPrefix} The client refused to send: {prefix}{encoded}", ChatTypeSystem);
}
return encoded;
}
private void QueueEcho(string text, int chatType) => _echo.Enqueue((text, chatType, 0));
private void DrainEcho(long now)
{
if (_echo.Count == 0 || now - _lastEchoMs < EchoSpacingMs) return;
var (text, type, attempts) = _echo.Peek();
_lastEchoMs = now;
if (_host.WriteToChat(text, type) || attempts + 1 >= EchoMaxAttempts)
{
_echo.Dequeue();
return;
}
// Dropped by the host's rate limit: retry the same line next time.
_echo.Dequeue();
var rest = _echo.ToArray();
_echo.Clear();
_echo.Enqueue((text, type, attempts + 1));
foreach (var e in rest) _echo.Enqueue(e);
}
private void ChatErrorThrottled(string error)
{
long now = Environment.TickCount64;
if (now - _lastErrorChatMs < ErrorChatEveryMs) return;
_lastErrorChatMs = now;
QueueEcho($"{EchoPrefix} Translation error: {error}", ChatTypeSystem);
}
private void PruneGuards(long now)
{
foreach (var kv in _resend)
if (now - kv.Value > ResendGuardMs) _resend.TryRemove(kv.Key, out _);
if (_recent.Count > 256)
{
var stale = new List<string>();
foreach (var kv in _recent) if (now - kv.Value > DedupWindowMs) stale.Add(kv.Key);
foreach (var k in stale) _recent.Remove(k);
}
}
// ── Log (pump writes, render reads) ────────────────────────────────────
private void AddLog(TranslateLogEntry e)
{
lock (_logLock)
{
_log.Add(e);
int max = Settings.MaxLog;
if (_log.Count > max) _log.RemoveRange(0, _log.Count - max);
_logSnapshot = _log.ToArray();
}
}
public TranslateLogEntry[] LogSnapshot()
{
lock (_logLock) return _logSnapshot;
}
public void ClearLog()
{
lock (_logLock)
{
_log.Clear();
_logSnapshot = Array.Empty<TranslateLogEntry>();
}
}
// ── Inbound parsing ────────────────────────────────────────────────────
// "[General] " style tab prefix some servers / chat options put in front of channel lines.
private static readonly Regex RxBracket = new(@"^\[(?<b>[A-Za-z ]{1,24})\]\s*", RegexOptions.CultureInvariant);
// "You say ...", "You tell Bob, ..." — the server echo of your own lines.
private static readonly Regex RxOwn = new(@"^You\s+(?:say|tell)\b(?<mid>[^""]*)""(?<msg>.*)""\s*$",
RegexOptions.Singleline | RegexOptions.CultureInvariant);
// "Bob says, "..."" / "Bob says on the General channel, "..."" / "Bob tells you, "...""
private static readonly Regex RxSpeech = new(@"^(?<name>.+?)\s+(?<verb>says|tells)\b(?<mid>[^""]*)""(?<msg>.*)""\s*$",
RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex RxOnChannel = new(@"on the (?<ch>[A-Za-z ]+?) channel", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// <summary>
/// Splits a chat line into channel, speaker and message. Channel comes from (in order) a "[Name]"
/// prefix, "on the X channel", "tells you", the chat colour, then words like "patron" / "vassal".
/// </summary>
internal static bool TryParseInbound(string raw, int chatType, out TranslateChannel channel,
out string speaker, out string message, out bool own)
{
channel = TranslateChannel.Local;
speaker = message = string.Empty;
own = false;
string t = AcChatEscapes.StripLinks(raw).Trim();
if (t.Length < 6 || t.IndexOf('"') < 0) return false;
TranslateChannel? hint = null;
var b = RxBracket.Match(t);
if (b.Success && TranslateChannels.TryParse(b.Groups["b"].Value, out var bc))
{
hint = bc;
t = t.Substring(b.Length);
}
string mid;
bool tellsYou;
var mo = RxOwn.Match(t);
if (mo.Success)
{
own = true;
speaker = "You";
mid = mo.Groups["mid"].Value;
message = mo.Groups["msg"].Value;
tellsYou = t.StartsWith("You tell", StringComparison.OrdinalIgnoreCase);
}
else
{
var m = RxSpeech.Match(t);
if (!m.Success) return false;
speaker = m.Groups["name"].Value.Trim().TrimStart('+');
mid = m.Groups["mid"].Value;
message = m.Groups["msg"].Value;
tellsYou = m.Groups["verb"].Value == "tells" && mid.TrimStart().StartsWith("you", StringComparison.OrdinalIgnoreCase);
if (speaker.Length == 0 || speaker.Length > 40) return false;
}
TranslateChannel? ch = hint;
if (ch == null)
{
var oc = RxOnChannel.Match(mid);
if (oc.Success && TranslateChannels.TryParse(oc.Groups["ch"].Value, out var named)) ch = named;
}
if (ch == null && tellsYou) ch = TranslateChannel.Tell;
ch ??= TranslateChannels.FromChatType(chatType);
ch ??= FromWords(mid);
if (ch == null) return false;
channel = ch.Value;
return message.Trim().Length > 0;
}
private static TranslateChannel? FromWords(string mid)
{
string m = mid.ToLowerInvariant();
if (m.Contains("covassal")) return TranslateChannel.Covassals;
if (m.Contains("vassal")) return TranslateChannel.Vassals;
if (m.Contains("patron")) return TranslateChannel.Patron;
if (m.Contains("monarch")) return TranslateChannel.Monarch;
if (m.Contains("fellowship")) return TranslateChannel.Fellowship;
if (m.Contains("allegiance")) return TranslateChannel.Allegiance;
return null;
}
private bool IsOwnName(string speaker)
{
string me;
try { me = _myName() ?? string.Empty; }
catch { return false; }
return me.Length > 0 && string.Equals(me.TrimStart('+'), speaker, StringComparison.OrdinalIgnoreCase);
}
// ── Language helpers (UI + commands) ───────────────────────────────────
/// <summary>Swaps the receive and send languages for this session.</summary>
public void SwapLanguages()
{
var s = Settings;
string recv = s.MyLanguage;
s.MyLanguage = s.CurrentSendLanguage;
s.CurrentSendLanguage = recv;
}
// ── /ra translate ──────────────────────────────────────────────────────
/// <summary>
/// /ra translate [on|off|in on|off|out on|off|window|send &lt;lang&gt;|recv &lt;lang&gt;|default &lt;lang&gt;|swap|reset|test &lt;text&gt;|status]
/// </summary>
public void HandleCommand(string[] args, Action<string> chat)
{
var s = Settings;
string verb = args.Length > 0 ? args[0].ToLowerInvariant() : "status";
string arg = args.Length > 1 ? args[1] : string.Empty;
switch (verb)
{
case "on": s.Enabled = true; chat($"{EchoPrefix} On. {StatusLine()}"); break;
case "off": s.Enabled = false; chat($"{EchoPrefix} Off."); break;
case "in":
case "out":
bool? v = arg.Equals("on", StringComparison.OrdinalIgnoreCase) ? true
: arg.Equals("off", StringComparison.OrdinalIgnoreCase) ? false : null;
if (verb == "in") s.EnableInbound = v ?? !s.EnableInbound;
else s.EnableOutbound = v ?? !s.EnableOutbound;
chat($"{EchoPrefix} Inbound {(s.EnableInbound ? "on" : "off")}, outbound {(s.EnableOutbound ? "on" : "off")}.");
break;
case "window":
case "show":
s.ShowWindow = !s.ShowWindow;
break;
case "send":
case "recv":
case "receive":
case "default":
string? code = TranslateLanguages.Normalize(arg);
if (code == null || code == TranslateLanguages.Auto)
{
chat($"{EchoPrefix} Unknown language '{arg}'. Codes: {string.Join(", ", TranslateLanguages.Codes, 1, TranslateLanguages.Codes.Length - 1)}");
break;
}
if (verb == "send") s.CurrentSendLanguage = code;
else if (verb == "default") s.DefaultSendLanguage = code;
else s.MyLanguage = code;
chat($"{EchoPrefix} {StatusLine()}");
break;
case "swap":
SwapLanguages();
chat($"{EchoPrefix} {StatusLine()}");
break;
case "reset":
s.CurrentSendLanguage = s.DefaultSendLanguage;
chat($"{EchoPrefix} {StatusLine()}");
break;
case "test":
string text = string.Join(" ", args, 1, Math.Max(0, args.Length - 1));
if (text.Length == 0) { chat($"{EchoPrefix} Usage: /ra translate test <text>"); break; }
Test(text);
break;
default:
chat($"{EchoPrefix} {(s.Enabled ? "On" : "Off")}. {StatusLine()}"
+ (LastError.Length > 0 ? $" Last error: {LastError}" : string.Empty));
chat($"{EchoPrefix} /ra translate on|off | in|out [on|off] | window | send|recv|default <lang> | swap | reset | test <text>");
break;
}
}
public string StatusLine()
{
var s = Settings;
return $"Receive {s.MyLanguage}, send {s.CurrentSendLanguage} (default {s.DefaultSendLanguage}), "
+ $"inbound {(s.EnableInbound ? "on" : "off")}, outbound {(s.EnableOutbound ? "on" : "off")}, provider {s.Provider}"
+ (s.ApiKey.Length == 0 && s.Provider != TranslateSettings.ProviderLibre ? " (no API key set)" : string.Empty) + ".";
}
public void Dispose()
{
try { _cts.Cancel(); } catch { }
_store.SaveIfDirty(Settings);
_cts.Dispose();
}
}

View file

@ -0,0 +1,186 @@
// TranslateChannels.cs — AC chat channels the translator can listen to (inbound) or send on (outbound),
// plus parsing of typed slash commands and the chat colour used for local echoes.
using System;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthAi.Translate;
/// <summary>Values are bit positions in <see cref="TranslateSettings.InboundMask"/> / OutboundMask; do not reorder.</summary>
internal enum TranslateChannel
{
Local = 0,
Tell,
Fellowship,
Allegiance,
Patron,
Vassals,
Covassals,
Monarch,
General,
Trade,
Lfg,
Roleplay,
Society,
Olthoi,
}
/// <summary>A typed chat line split into its channel, the text to keep verbatim, and the message body.</summary>
internal readonly record struct OutboundLine(TranslateChannel Channel, string Prefix, string Body, string TellTarget);
internal static class TranslateChannels
{
public static readonly TranslateChannel[] All = Enum.GetValues<TranslateChannel>();
public static uint Bit(TranslateChannel ch) => 1u << (int)ch;
public static string Name(TranslateChannel ch) => ch switch
{
TranslateChannel.Lfg => "LFG",
_ => ch.ToString(),
};
/// <summary>Accepts channel names and the usual short forms (case-insensitive).</summary>
public static bool TryParse(string? text, out TranslateChannel ch)
{
ch = TranslateChannel.Local;
if (string.IsNullOrWhiteSpace(text)) return false;
switch (text.Trim().ToLowerInvariant())
{
case "local": case "say": case "area": ch = TranslateChannel.Local; return true;
case "tell": case "tells": case "t": ch = TranslateChannel.Tell; return true;
case "fellowship": case "fellow": case "f": ch = TranslateChannel.Fellowship; return true;
case "allegiance": case "alleg": case "a": ch = TranslateChannel.Allegiance; return true;
case "patron": case "p": ch = TranslateChannel.Patron; return true;
case "vassals": case "vassal": case "v": ch = TranslateChannel.Vassals; return true;
case "covassals": case "covassal": case "c": ch = TranslateChannel.Covassals; return true;
case "monarch": case "m": ch = TranslateChannel.Monarch; return true;
case "general": case "cg": case "g": ch = TranslateChannel.General; return true;
case "trade": case "ct": ch = TranslateChannel.Trade; return true;
case "lfg": case "looking for group": case "clfg": ch = TranslateChannel.Lfg; return true;
case "roleplay": case "rp": case "crp": ch = TranslateChannel.Roleplay; return true;
case "society": case "cs": ch = TranslateChannel.Society; return true;
case "olthoi": case "co": ch = TranslateChannel.Olthoi; return true;
default: return false;
}
}
/// <summary>Chat colour for local echoes, so they land in the same chat tab as the source channel.</summary>
public static int ChatType(TranslateChannel ch) => ch switch
{
TranslateChannel.Local => 0x02,
TranslateChannel.Tell => 0x03,
TranslateChannel.Fellowship => 0x13,
TranslateChannel.Allegiance or TranslateChannel.Patron or TranslateChannel.Vassals
or TranslateChannel.Covassals or TranslateChannel.Monarch => 0x12,
TranslateChannel.General => 0x1B,
TranslateChannel.Trade => 0x1C,
TranslateChannel.Lfg => 0x1D,
TranslateChannel.Roleplay => 0x1E,
TranslateChannel.Olthoi => 0x20,
TranslateChannel.Society => 0x21,
_ => 0x01,
};
/// <summary>Channel implied by an inbound chat colour; null for generic colours (Channels / Social).</summary>
public static TranslateChannel? FromChatType(int chatType) => chatType switch
{
0x02 => TranslateChannel.Local,
0x03 => TranslateChannel.Tell,
0x12 => TranslateChannel.Allegiance,
0x13 => TranslateChannel.Fellowship,
0x1B => TranslateChannel.General,
0x1C => TranslateChannel.Trade,
0x1D => TranslateChannel.Lfg,
0x1E => TranslateChannel.Roleplay,
0x20 => TranslateChannel.Olthoi,
0x21 => TranslateChannel.Society,
_ => null,
};
/// <summary>
/// Command prefix used when the translator composes a line itself (Translate window).
/// A tell needs <paramref name="tellTarget"/>; an empty target replies to the last tell.
/// </summary>
public static string SendPrefix(TranslateChannel ch, string? tellTarget) => ch switch
{
TranslateChannel.Local => string.Empty,
TranslateChannel.Tell => string.IsNullOrWhiteSpace(tellTarget) ? "/r " : $"/t {tellTarget.Trim()}, ",
TranslateChannel.Fellowship => "/f ",
TranslateChannel.Allegiance => "/a ",
TranslateChannel.Patron => "/p ",
TranslateChannel.Vassals => "/v ",
TranslateChannel.Covassals => "/c ",
TranslateChannel.Monarch => "/m ",
TranslateChannel.General => "/cg ",
TranslateChannel.Trade => "/ct ",
TranslateChannel.Lfg => "/clfg ",
TranslateChannel.Roleplay => "/crp ",
TranslateChannel.Society => "/cs ",
TranslateChannel.Olthoi => "/co ",
_ => string.Empty,
};
// "/cmd rest" or "@cmd rest"; the body keeps everything after the first run of whitespace.
private static readonly Regex RxSlash = new(@"^(?<cmd>[/@][A-Za-z]+)(?<sp>\s+)(?<rest>.+)$",
RegexOptions.Singleline | RegexOptions.CultureInvariant);
// Tell target and body: "Name, message".
private static readonly Regex RxTellArgs = new(@"^(?<name>[^,]+?)\s*,\s*(?<msg>.+)$",
RegexOptions.Singleline | RegexOptions.CultureInvariant);
/// <summary>
/// Splits a typed chat line into channel + verbatim prefix + body. Plain text is Local speech.
/// Returns false for slash commands that are not chat (emotes, /ra, /loc, ...).
/// </summary>
public static bool TryParseOutbound(string text, out OutboundLine line)
{
line = default;
if (string.IsNullOrWhiteSpace(text)) return false;
string t = text.Trim();
if (t[0] != '/' && t[0] != '@')
{
line = new OutboundLine(TranslateChannel.Local, string.Empty, t, string.Empty);
return true;
}
var m = RxSlash.Match(t);
if (!m.Success) return false;
string cmd = m.Groups["cmd"].Value.Substring(1).ToLowerInvariant();
string rest = m.Groups["rest"].Value;
string head = m.Groups["cmd"].Value + m.Groups["sp"].Value;
TranslateChannel ch;
switch (cmd)
{
case "s": case "say": ch = TranslateChannel.Local; break;
case "f": case "fellowship": ch = TranslateChannel.Fellowship; break;
case "a": case "allegiance": ch = TranslateChannel.Allegiance; break;
case "p": case "patron": ch = TranslateChannel.Patron; break;
case "v": case "vassals": ch = TranslateChannel.Vassals; break;
case "c": case "covassals": ch = TranslateChannel.Covassals; break;
case "m": case "monarch": ch = TranslateChannel.Monarch; break;
case "cg": ch = TranslateChannel.General; break;
case "ct": ch = TranslateChannel.Trade; break;
case "clfg": ch = TranslateChannel.Lfg; break;
case "crp": case "rp": ch = TranslateChannel.Roleplay; break;
case "cs": ch = TranslateChannel.Society; break;
case "co": ch = TranslateChannel.Olthoi; break;
case "r": case "reply":
line = new OutboundLine(TranslateChannel.Tell, head, rest, string.Empty);
return true;
case "t": case "tell":
var tm = RxTellArgs.Match(rest);
if (!tm.Success) return false;
string msg = tm.Groups["msg"].Value;
string prefix = t.Substring(0, t.Length - msg.Length);
line = new OutboundLine(TranslateChannel.Tell, prefix, msg, tm.Groups["name"].Value.Trim());
return true;
default:
return false;
}
line = new OutboundLine(ch, head, rest, string.Empty);
return true;
}
}

View file

@ -0,0 +1,286 @@
// TranslateClient.cs — HTTP calls to the translation providers. NativeAOT-safe: request JSON is written
// with Utf8JsonWriter and responses are read with JsonDocument (no reflection serialization).
//
// google Cloud Translation Basic v2 POST .../language/translate/v2?key=KEY {q,target,format,source?}
// deepl DeepL API v2 POST .../v2/translate Authorization: DeepL-Auth-Key KEY
// (keys ending ":fx" are Free-plan keys and must use api-free.deepl.com)
// libre LibreTranslate POST {server}/translate {q,source,target,format,api_key?}
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.Plugin.RynthAi.Translate;
/// <summary>Outcome of one request. <see cref="DetectedSource"/> is empty when the provider didn't report it.</summary>
internal readonly record struct TranslateResult(bool Ok, string Text, string DetectedSource, string Error)
{
public static TranslateResult Fail(string error) => new(false, string.Empty, string.Empty, error);
}
internal static class TranslateClient
{
public const string GoogleUrl = "https://translation.googleapis.com/language/translate/v2";
public const string DeepLProUrl = "https://api.deepl.com/v2/translate";
public const string DeepLFreeUrl = "https://api-free.deepl.com/v2/translate";
public const string LibreUrl = "https://libretranslate.com";
private static readonly HttpClient Http = CreateHttp();
private static HttpClient CreateHttp()
{
var handler = new SocketsHttpHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
};
var http = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15) };
http.DefaultRequestHeaders.UserAgent.ParseAdd("RynthAi-Translate/1.0");
http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return http;
}
/// <summary>Endpoint shown in the UI when the URL box is blank.</summary>
public static string DefaultUrl(string provider, string apiKey) => provider switch
{
TranslateSettings.ProviderDeepL => IsDeepLFreeKey(apiKey) ? DeepLFreeUrl : DeepLProUrl,
TranslateSettings.ProviderLibre => LibreUrl,
_ => GoogleUrl,
};
private static bool IsDeepLFreeKey(string apiKey)
=> apiKey.Trim().EndsWith(":fx", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Translates <paramref name="text"/> from <paramref name="source"/> ("auto" = detect) into
/// <paramref name="target"/>. Never throws; failures come back as <see cref="TranslateResult.Fail"/>.
/// </summary>
public static async Task<TranslateResult> TranslateAsync(string provider, string apiKey, string apiUrl,
string text, string source, string target, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(text)) return TranslateResult.Fail("nothing to translate");
apiKey = (apiKey ?? string.Empty).Trim();
apiUrl = (apiUrl ?? string.Empty).Trim();
bool auto = string.IsNullOrWhiteSpace(source) || source.Equals(TranslateLanguages.Auto, StringComparison.OrdinalIgnoreCase);
try
{
return provider switch
{
TranslateSettings.ProviderDeepL => await DeepLAsync(apiKey, apiUrl, text, auto ? null : source, target, ct).ConfigureAwait(false),
TranslateSettings.ProviderLibre => await LibreAsync(apiKey, apiUrl, text, auto ? null : source, target, ct).ConfigureAwait(false),
_ => await GoogleAsync(apiKey, apiUrl, text, auto ? null : source, target, ct).ConfigureAwait(false),
};
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return TranslateResult.Fail("request timed out");
}
catch (OperationCanceledException)
{
return TranslateResult.Fail("cancelled");
}
catch (HttpRequestException ex)
{
return TranslateResult.Fail("network error: " + ex.Message);
}
catch (Exception ex)
{
return TranslateResult.Fail($"{ex.GetType().Name}: {ex.Message}");
}
}
// ── Google Cloud Translation Basic v2 ──────────────────────────────────
private static async Task<TranslateResult> GoogleAsync(string key, string url, string text, string? source, string target, CancellationToken ct)
{
if (key.Length == 0) return TranslateResult.Fail("Google needs an API key (Cloud Translation API).");
string baseUrl = url.Length == 0 ? GoogleUrl : url;
int q = baseUrl.IndexOf('?');
if (q >= 0) baseUrl = baseUrl.Substring(0, q);
string body = BuildJson(w =>
{
w.WriteString("q", text);
w.WriteString("target", target);
w.WriteString("format", "text");
if (source != null) w.WriteString("source", source);
});
using var req = new HttpRequestMessage(HttpMethod.Post, baseUrl + "?key=" + Uri.EscapeDataString(key))
{
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
var (status, json) = await SendAsync(req, ct).ConfigureAwait(false);
if (status != HttpStatusCode.OK) return TranslateResult.Fail(ErrorText(status, json));
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("data", out var data)
&& data.TryGetProperty("translations", out var arr)
&& arr.ValueKind == JsonValueKind.Array && arr.GetArrayLength() > 0)
{
var first = arr[0];
string translated = first.TryGetProperty("translatedText", out var t) ? t.GetString() ?? string.Empty : string.Empty;
string detected = first.TryGetProperty("detectedSourceLanguage", out var d) ? d.GetString() ?? string.Empty : source ?? string.Empty;
return new TranslateResult(true, WebUtility.HtmlDecode(translated), detected, string.Empty);
}
return TranslateResult.Fail("unexpected Google response: " + Truncate(json, 160));
}
// ── DeepL v2 ───────────────────────────────────────────────────────────
private static async Task<TranslateResult> DeepLAsync(string key, string url, string text, string? source, string target, CancellationToken ct)
{
if (key.Length == 0) return TranslateResult.Fail("DeepL needs an API key (Free keys end in :fx).");
string endpoint = url.Length == 0 ? (IsDeepLFreeKey(key) ? DeepLFreeUrl : DeepLProUrl) : url;
string body = BuildJson(w =>
{
w.WriteStartArray("text");
w.WriteStringValue(text);
w.WriteEndArray();
w.WriteString("target_lang", DeepLTarget(target));
if (source != null) w.WriteString("source_lang", DeepLSource(source));
});
using var req = new HttpRequestMessage(HttpMethod.Post, endpoint)
{
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
req.Headers.TryAddWithoutValidation("Authorization", "DeepL-Auth-Key " + key);
var (status, json) = await SendAsync(req, ct).ConfigureAwait(false);
if (status != HttpStatusCode.OK) return TranslateResult.Fail(ErrorText(status, json));
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("translations", out var arr)
&& arr.ValueKind == JsonValueKind.Array && arr.GetArrayLength() > 0)
{
var first = arr[0];
string translated = first.TryGetProperty("text", out var t) ? t.GetString() ?? string.Empty : string.Empty;
string detected = first.TryGetProperty("detected_source_language", out var d) ? (d.GetString() ?? string.Empty).ToLowerInvariant() : string.Empty;
return new TranslateResult(true, translated, detected, string.Empty);
}
return TranslateResult.Fail("unexpected DeepL response: " + Truncate(json, 160));
}
/// <summary>DeepL target codes: upper-case, English / Portuguese need a regional variant.</summary>
private static string DeepLTarget(string code) => code.ToLowerInvariant() switch
{
"en" => "EN-US",
"pt" => "PT-BR",
"zh-cn" => "ZH-HANS",
"zh-tw" => "ZH-HANT",
"no" => "NB",
var c => c.ToUpperInvariant(),
};
/// <summary>DeepL source codes: base language only.</summary>
private static string DeepLSource(string code)
{
string b = TranslateLanguages.BaseOf(code);
return (b == "no" ? "nb" : b).ToUpperInvariant();
}
// ── LibreTranslate ─────────────────────────────────────────────────────
private static async Task<TranslateResult> LibreAsync(string key, string url, string text, string? source, string target, CancellationToken ct)
{
string server = (url.Length == 0 ? LibreUrl : url).TrimEnd('/');
string endpoint = server.EndsWith("/translate", StringComparison.OrdinalIgnoreCase) ? server : server + "/translate";
string body = BuildJson(w =>
{
w.WriteString("q", text);
w.WriteString("source", source == null ? "auto" : LibreCode(source));
w.WriteString("target", LibreCode(target));
w.WriteString("format", "text");
if (key.Length > 0) w.WriteString("api_key", key);
});
using var req = new HttpRequestMessage(HttpMethod.Post, endpoint)
{
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
var (status, json) = await SendAsync(req, ct).ConfigureAwait(false);
if (status != HttpStatusCode.OK) return TranslateResult.Fail(ErrorText(status, json));
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (root.TryGetProperty("translatedText", out var t))
{
string detected = root.TryGetProperty("detectedLanguage", out var d) && d.ValueKind == JsonValueKind.Object
&& d.TryGetProperty("language", out var lang)
? lang.GetString() ?? string.Empty
: source ?? string.Empty;
return new TranslateResult(true, t.GetString() ?? string.Empty, detected, string.Empty);
}
return TranslateResult.Fail("unexpected LibreTranslate response: " + Truncate(json, 160));
}
/// <summary>LibreTranslate uses "zh" for Simplified and "zt" for Traditional Chinese.</summary>
private static string LibreCode(string code) => code.ToLowerInvariant() switch
{
"zh-cn" => "zh",
"zh-tw" => "zt",
"no" => "nb",
var c => c,
};
// ── Shared helpers ─────────────────────────────────────────────────────
private static async Task<(HttpStatusCode Status, string Body)> SendAsync(HttpRequestMessage req, CancellationToken ct)
{
using var resp = await Http.SendAsync(req, ct).ConfigureAwait(false);
string body = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
return (resp.StatusCode, body);
}
private static string BuildJson(Action<Utf8JsonWriter> writeProperties)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
writeProperties(w);
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
/// <summary>Pulls the provider's error message (Google error.message, DeepL message, Libre error).</summary>
private static string ErrorText(HttpStatusCode status, string json)
{
string detail = string.Empty;
try
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (root.ValueKind == JsonValueKind.Object)
{
if (root.TryGetProperty("error", out var err))
detail = err.ValueKind == JsonValueKind.Object && err.TryGetProperty("message", out var m)
? m.GetString() ?? string.Empty
: err.ValueKind == JsonValueKind.String ? err.GetString() ?? string.Empty : string.Empty;
else if (root.TryGetProperty("message", out var msg))
detail = msg.GetString() ?? string.Empty;
}
}
catch (JsonException) { detail = Truncate(json, 160); }
string hint = status switch
{
HttpStatusCode.Forbidden or HttpStatusCode.Unauthorized => " (check the API key)",
(HttpStatusCode)429 => " (rate limited, slow down)",
(HttpStatusCode)456 => " (DeepL quota used up)",
_ => string.Empty,
};
return $"HTTP {(int)status}{hint}" + (detail.Length > 0 ? ": " + Truncate(detail, 200) : string.Empty);
}
internal static string Truncate(string s, int max)
=> string.IsNullOrEmpty(s) || s.Length <= max ? s ?? string.Empty : s.Substring(0, max) + "...";
}

View file

@ -0,0 +1,92 @@
// TranslateLanguages.cs — Language codes offered by the chat translator (ISO 639-1 / Google style).
// Providers that use other codes (DeepL upper-case, LibreTranslate "zh") are mapped in TranslateClient.
using System;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi.Translate;
internal static class TranslateLanguages
{
/// <summary>Pseudo-code meaning "let the provider detect the source language".</summary>
public const string Auto = "auto";
/// <summary>Codes in display order; index-aligned with <see cref="Names"/>.</summary>
public static readonly string[] Codes =
{
Auto, "en", "es", "fr", "de", "it", "pt", "nl", "sv", "no", "da", "fi", "pl", "cs", "hu",
"ro", "el", "tr", "ru", "uk", "ar", "he", "hi", "th", "vi", "id", "ja", "ko", "zh-CN", "zh-TW",
};
public static readonly string[] Names =
{
"Auto-detect", "English", "Spanish", "French", "German", "Italian", "Portuguese", "Dutch", "Swedish",
"Norwegian", "Danish", "Finnish", "Polish", "Czech", "Hungarian", "Romanian", "Greek", "Turkish",
"Russian", "Ukrainian", "Arabic", "Hebrew", "Hindi", "Thai", "Vietnamese", "Indonesian", "Japanese",
"Korean", "Chinese (Simplified)", "Chinese (Traditional)",
};
public static int IndexOf(string? code)
{
if (string.IsNullOrWhiteSpace(code)) return -1;
for (int i = 0; i < Codes.Length; i++)
if (string.Equals(Codes[i], code.Trim(), StringComparison.OrdinalIgnoreCase)) return i;
return -1;
}
/// <summary>True when the code is in the list (auto only counts when <paramref name="allowAuto"/>).</summary>
public static bool IsKnown(string? code, bool allowAuto)
{
int i = IndexOf(code);
return i > 0 || (i == 0 && allowAuto);
}
/// <summary>Canonical spelling of a known code (e.g. "ZH-cn" → "zh-CN"); null when unknown.</summary>
public static string? Normalize(string? code)
{
int i = IndexOf(code);
return i < 0 ? null : Codes[i];
}
/// <summary>"Spanish (es)" for UI and chat feedback; unknown codes are shown as-is.</summary>
public static string Label(string? code)
{
int i = IndexOf(code);
return i < 0 ? (code ?? string.Empty) : i == 0 ? Names[0] : $"{Names[i]} ({Codes[i]})";
}
/// <summary>Base language of a code ("zh-CN" → "zh"), lower-case, for same-language checks.</summary>
public static string BaseOf(string? code)
{
if (string.IsNullOrWhiteSpace(code)) return string.Empty;
string c = code.Trim().ToLowerInvariant();
int dash = c.IndexOf('-');
return dash > 0 ? c.Substring(0, dash) : c;
}
/// <summary>
/// ImGui language picker. Returns true when the selection changed. Render thread only.
/// </summary>
public static bool Combo(string label, ref string code, bool allowAuto, float width = 0f)
{
bool changed = false;
if (width > 0f) ImGui.SetNextItemWidth(width);
int current = IndexOf(code);
string preview = current < 0 ? code : current == 0 ? Names[0] : Codes[current];
if (ImGui.BeginCombo(label, preview, ImGuiComboFlags.HeightLarge))
{
for (int i = allowAuto ? 0 : 1; i < Codes.Length; i++)
{
bool selected = i == current;
if (ImGui.Selectable(i == 0 ? Names[0] : $"{Codes[i]} {Names[i]}", selected))
{
code = Codes[i];
changed = true;
}
if (selected) ImGui.SetItemDefaultFocus();
}
ImGui.EndCombo();
}
if (ImGui.IsItemHovered() && current > 0) ImGui.SetTooltip(Names[current]);
return changed;
}
}

View file

@ -0,0 +1,180 @@
// TranslateSettings.cs — Chat translator settings, shared by every character (RynthAi\translate.json).
// Fields are written by the render thread (UI) and read by the pump thread; each one is a single
// reference / 32-bit value so reads never tear. The JSON keeps channels as names; the masks are the
// runtime form.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi.Translate;
internal sealed class TranslateSettings
{
public const string ProviderGoogle = "google";
public const string ProviderDeepL = "deepl";
public const string ProviderLibre = "libre";
public static readonly string[] Providers = { ProviderGoogle, ProviderDeepL, ProviderLibre };
public static readonly string[] ProviderNames = { "Google Cloud Translation", "DeepL", "LibreTranslate" };
/// <summary>Master switch; off means no API calls and no chat interception.</summary>
public bool Enabled;
public string Provider = ProviderGoogle;
/// <summary>Stored in plain text in translate.json.</summary>
public string ApiKey = string.Empty;
/// <summary>Blank uses the provider's default endpoint (LibreTranslate needs a server URL).</summary>
public string ApiUrl = string.Empty;
/// <summary>"Receive" language: inbound chat is translated into this.</summary>
public string MyLanguage = "en";
/// <summary>Source language of inbound chat; "auto" lets the provider detect it.</summary>
public string InboundSource = TranslateLanguages.Auto;
/// <summary>Send language each session starts with (Advanced Settings > Translate).</summary>
public string DefaultSendLanguage = "es";
public bool EnableInbound = true;
public bool EnableOutbound;
public List<string>? InboundChannels;
public List<string>? OutboundChannels;
/// <summary>Skip your own lines inbound (the server echoes what you send).</summary>
public bool SkipOwn = true;
/// <summary>Write inbound translations into chat (AC chat window and RynthChat).</summary>
public bool EchoToChat = true;
/// <summary>After an outbound translation, show what you typed locally next to what was sent.</summary>
public bool EchoOutbound = true;
/// <summary>When an outbound translation fails, send the original text instead of dropping it.</summary>
public bool SendOriginalOnError = true;
/// <summary>Lines starting with this go out untranslated (the prefix is removed).</summary>
public string RawPrefix = "\\";
/// <summary>Minimum spacing between API requests.</summary>
public int MinIntervalMs = 750;
/// <summary>Entries kept in the Translate window log.</summary>
public int MaxLog = 200;
public bool ShowWindow;
// ── Runtime only ────────────────────────────────────────────────────────
/// <summary>Send language for this session; starts as <see cref="DefaultSendLanguage"/>.</summary>
[JsonIgnore] public string CurrentSendLanguage = "es";
[JsonIgnore] public uint InboundMask;
[JsonIgnore] public uint OutboundMask;
public bool ListensTo(TranslateChannel ch) => (InboundMask & TranslateChannels.Bit(ch)) != 0;
public bool SendsOn(TranslateChannel ch) => (OutboundMask & TranslateChannels.Bit(ch)) != 0;
public static uint DefaultInboundMask()
=> Mask(TranslateChannel.Tell, TranslateChannel.Fellowship, TranslateChannel.Allegiance, TranslateChannel.Patron,
TranslateChannel.Vassals, TranslateChannel.Covassals, TranslateChannel.Monarch, TranslateChannel.General,
TranslateChannel.Trade, TranslateChannel.Lfg, TranslateChannel.Roleplay, TranslateChannel.Society,
TranslateChannel.Olthoi);
public static uint DefaultOutboundMask()
=> Mask(TranslateChannel.Tell, TranslateChannel.Fellowship, TranslateChannel.Allegiance,
TranslateChannel.General, TranslateChannel.Roleplay);
private static uint Mask(params TranslateChannel[] channels)
{
uint m = 0;
foreach (var ch in channels) m |= TranslateChannels.Bit(ch);
return m;
}
internal static uint MaskFromNames(List<string>? names, uint fallback)
{
if (names == null) return fallback;
uint m = 0;
foreach (var n in names)
if (TranslateChannels.TryParse(n, out var ch)) m |= TranslateChannels.Bit(ch);
return m;
}
internal static List<string> NamesFromMask(uint mask)
{
var list = new List<string>();
foreach (var ch in TranslateChannels.All)
if ((mask & TranslateChannels.Bit(ch)) != 0) list.Add(TranslateChannels.Name(ch));
return list;
}
}
/// <summary>Loads / saves <see cref="TranslateSettings"/>; writes only when the JSON changed.</summary>
internal sealed class TranslateStore
{
private readonly string _path;
private string _lastJson = string.Empty;
public TranslateStore(string? path = null)
=> _path = path ?? Path.Combine(RynthInstallPaths.RynthAiDir, "translate.json");
public string FilePath => _path;
public TranslateSettings Load()
{
TranslateSettings? s = null;
try
{
if (File.Exists(_path))
{
string json = File.ReadAllText(_path);
s = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.TranslateSettings);
if (s != null) _lastJson = json;
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, $"translate load {_path}"); }
s ??= new TranslateSettings();
Normalize(s);
return s;
}
public void SaveIfDirty(TranslateSettings s)
{
try
{
s.InboundChannels = TranslateSettings.NamesFromMask(s.InboundMask);
s.OutboundChannels = TranslateSettings.NamesFromMask(s.OutboundMask);
string json = JsonSerializer.Serialize(s, RynthAiJsonContext.Default.TranslateSettings);
if (json == _lastJson) return;
string? dir = Path.GetDirectoryName(_path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
string tmp = _path + ".tmp";
File.WriteAllText(tmp, json);
File.Move(tmp, _path, overwrite: true);
_lastJson = json;
}
catch (Exception ex) { RynthLog.Exception(LogCat.Chat, ex, $"translate save {_path}"); }
}
/// <summary>Repairs unknown codes / out-of-range numbers and builds the runtime masks.</summary>
private static void Normalize(TranslateSettings s)
{
if (Array.IndexOf(TranslateSettings.Providers, s.Provider ?? string.Empty) < 0) s.Provider = TranslateSettings.ProviderGoogle;
s.ApiKey ??= string.Empty;
s.ApiUrl ??= string.Empty;
s.RawPrefix ??= string.Empty;
s.MyLanguage = TranslateLanguages.Normalize(s.MyLanguage) is { } my && my != TranslateLanguages.Auto ? my : "en";
s.InboundSource = TranslateLanguages.Normalize(s.InboundSource) ?? TranslateLanguages.Auto;
s.DefaultSendLanguage = TranslateLanguages.Normalize(s.DefaultSendLanguage) is { } send && send != TranslateLanguages.Auto ? send : "es";
s.CurrentSendLanguage = s.DefaultSendLanguage;
s.MinIntervalMs = Math.Clamp(s.MinIntervalMs, 250, 10000);
s.MaxLog = Math.Clamp(s.MaxLog, 20, 2000);
s.InboundMask = TranslateSettings.MaskFromNames(s.InboundChannels, TranslateSettings.DefaultInboundMask());
s.OutboundMask = TranslateSettings.MaskFromNames(s.OutboundChannels, TranslateSettings.DefaultOutboundMask());
}
}

View file

@ -0,0 +1,348 @@
// TranslateUi.cs — ImGui views for the chat translator. Render thread only.
//
// RenderWindow "Chat Translate" window: language row, log, compose box, channels, settings
// RenderSettings provider / key / languages / options (also the Advanced Settings > Translate page)
// RenderHubSection compact on/off + receive/send swap row for the Mini Remote
//
// Settings fields are edited in place (single-value writes the pump thread tolerates); anything that
// needs the pump thread goes through ChatTranslator's thread-safe enqueue methods.
using System;
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi.Translate;
internal sealed class TranslateUi
{
private static readonly Vector4 ColIn = new(0.45f, 0.85f, 0.95f, 1f);
private static readonly Vector4 ColOut = new(0.40f, 0.95f, 0.45f, 1f);
private static readonly Vector4 ColTest = new(0.95f, 0.80f, 0.35f, 1f);
private static readonly Vector4 ColError = new(0.95f, 0.45f, 0.40f, 1f);
private static readonly Vector4 ColDim = new(0.60f, 0.64f, 0.70f, 1f);
private readonly ChatTranslator _tr;
private string _composeText = string.Empty;
private string _tellTarget = string.Empty;
private string _testText = string.Empty;
private TranslateChannel _composeChannel = TranslateChannel.Fellowship;
private bool _showKey;
private bool _refocusCompose;
private int _lastLogCount;
public TranslateUi(ChatTranslator translator) => _tr = translator;
private TranslateSettings S => _tr.Settings;
// ── Window ─────────────────────────────────────────────────────────────
public void RenderWindow()
{
var s = S;
if (!s.ShowWindow) return;
ImGui.SetNextWindowSize(new Vector2(520, 420), ImGuiCond.FirstUseEver);
bool open = true;
bool visible = ImGui.Begin("Chat Translate##rynthtranslate", ref open, ImGuiWindowFlags.NoCollapse);
if (!open) s.ShowWindow = false;
if (!visible) { ImGui.End(); return; }
RenderHeader();
RenderLanguageRow("##win", 110f);
ImGui.Separator();
if (ImGui.BeginTabBar("##translatetabs"))
{
if (ImGui.BeginTabItem("Log")) { RenderLog(); ImGui.EndTabItem(); }
if (ImGui.BeginTabItem("Compose")) { RenderCompose(); ImGui.EndTabItem(); }
if (ImGui.BeginTabItem("Channels")) { RenderChannels(); ImGui.EndTabItem(); }
if (ImGui.BeginTabItem("Settings")) { RenderSettings("##win"); ImGui.EndTabItem(); }
ImGui.EndTabBar();
}
ImGui.End();
}
private void RenderHeader()
{
var s = S;
ImGui.Checkbox("Enabled##trenabled", ref s.Enabled);
ImGui.SameLine();
ImGui.Checkbox("Incoming##trin", ref s.EnableInbound);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Translate chat you receive into your receive language.");
ImGui.SameLine();
ImGui.Checkbox("Outgoing##trout", ref s.EnableOutbound);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Translate what you type on the ticked Send channels before it goes out.\n"
+ $"Start a line with '{s.RawPrefix}' to send it untranslated.");
ImGui.SameLine();
ImGui.TextColored(ColDim, $"| {_tr.Translated} done, {_tr.CharsSent:N0} chars, {_tr.Pending} queued");
if (s.ApiKey.Length == 0 && s.Provider != TranslateSettings.ProviderLibre)
ImGui.TextColored(ColError, "No API key: open the Settings tab to add one.");
else if (_tr.LastError.Length > 0)
ImGui.TextColored(ColError, "Last error: " + _tr.LastError);
}
/// <summary>Receive / swap / send / reset-to-default row (window and Advanced page).</summary>
public void RenderLanguageRow(string id, float comboWidth)
{
var s = S;
ImGui.AlignTextToFramePadding();
ImGui.TextUnformatted("Receive");
ImGui.SameLine();
string recv = s.MyLanguage;
if (TranslateLanguages.Combo("##recv" + id, ref recv, allowAuto: false, comboWidth)) s.MyLanguage = recv;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Incoming chat is translated into this language.");
ImGui.SameLine();
if (ImGui.Button("<->##swap" + id)) _tr.SwapLanguages();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Swap the receive and send languages.");
ImGui.SameLine();
ImGui.TextUnformatted("Send");
ImGui.SameLine();
string send = s.CurrentSendLanguage;
if (TranslateLanguages.Combo("##send" + id, ref send, allowAuto: false, comboWidth)) s.CurrentSendLanguage = send;
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"What you type is translated into this language.\nDefault: {TranslateLanguages.Label(s.DefaultSendLanguage)}");
ImGui.SameLine();
bool atDefault = s.CurrentSendLanguage == s.DefaultSendLanguage;
if (atDefault) ImGui.BeginDisabled();
if (ImGui.Button("Default##senddef" + id)) s.CurrentSendLanguage = s.DefaultSendLanguage;
if (atDefault) ImGui.EndDisabled();
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
ImGui.SetTooltip($"Reset the send language to the default ({s.DefaultSendLanguage}).");
}
private void RenderLog()
{
var log = _tr.LogSnapshot();
if (ImGui.SmallButton("Clear")) _tr.ClearLog();
ImGui.SameLine();
ImGui.TextColored(ColDim, $"{log.Length} entries (hover a line for the original)");
if (!ImGui.BeginChild("##trlog", new Vector2(0, 0), ImGuiChildFlags.Borders)) { ImGui.EndChild(); return; }
foreach (var e in log)
{
var (tag, col) = e.Direction switch
{
TranslateDirection.In => ("IN ", ColIn),
TranslateDirection.Out => ("OUT", ColOut),
_ => ("TST", ColTest),
};
ImGui.TextColored(ColDim, e.Time.ToString("HH:mm:ss"));
ImGui.SameLine();
ImGui.TextColored(e.Error.Length > 0 && e.Translated.Length == 0 ? ColError : col, tag);
ImGui.SameLine();
string ch = e.Channel is { } c ? $"[{TranslateChannels.Name(c)}] " : string.Empty;
string who = e.Speaker.Length > 0 ? e.Speaker + ": " : string.Empty;
string body = e.Translated.Length > 0 ? e.Translated : e.Original;
ImGui.TextWrapped($"{ch}{who}{body}");
if (ImGui.IsItemHovered())
{
string langs = e.From.Length > 0 || e.To.Length > 0 ? $"\n{(e.From.Length > 0 ? e.From : "?")} -> {e.To}" : string.Empty;
ImGui.SetTooltip($"Original: {e.Original}{langs}{(e.Error.Length > 0 ? "\n" + e.Error : string.Empty)}");
}
}
// Follow new lines unless the user scrolled up.
if (log.Length != _lastLogCount && ImGui.GetScrollY() >= ImGui.GetScrollMaxY() - 20f)
ImGui.SetScrollHereY(1f);
_lastLogCount = log.Length;
ImGui.EndChild();
}
private void RenderCompose()
{
var s = S;
ImGui.TextWrapped($"Type in any language; it is translated into {TranslateLanguages.Label(s.CurrentSendLanguage)} and sent on the chosen channel.");
ImGui.Spacing();
ImGui.SetNextItemWidth(140f);
if (ImGui.BeginCombo("Channel##trcompose", TranslateChannels.Name(_composeChannel)))
{
foreach (var ch in TranslateChannels.All)
if (ImGui.Selectable(TranslateChannels.Name(ch), ch == _composeChannel)) _composeChannel = ch;
ImGui.EndCombo();
}
if (_composeChannel == TranslateChannel.Tell)
{
ImGui.SameLine();
ImGui.SetNextItemWidth(160f);
ImGui.InputTextWithHint("##trtell", "name (blank = reply)", ref _tellTarget, 64u);
}
ImGui.SetNextItemWidth(-1f);
if (_refocusCompose)
{
ImGui.SetKeyboardFocusHere();
_refocusCompose = false;
}
bool enter = ImGui.InputTextWithHint("##trcomposetext", "message", ref _composeText, 400u, ImGuiInputTextFlags.EnterReturnsTrue);
if (ImGui.Button("Translate && send") || enter)
{
if (_composeText.Trim().Length > 0)
{
_tr.Compose(_composeChannel, _tellTarget, _composeText);
_composeText = string.Empty;
_refocusCompose = enter;
}
}
ImGui.SameLine();
if (ImGui.Button("Preview only")) _tr.Test(_composeText);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Translate without sending; the result appears in the Log tab and chat.");
if (!s.Enabled) ImGui.TextColored(ColDim, "The compose box works even while auto-translate is off.");
}
private void RenderChannels()
{
var s = S;
ImGui.TextWrapped("Listen: incoming lines on these channels are translated into your receive language. "
+ "Send: lines you type on these channels are translated into your send language.");
if (ImGui.SmallButton("Listen all")) s.InboundMask = AllMask();
ImGui.SameLine();
if (ImGui.SmallButton("Listen none")) s.InboundMask = 0;
ImGui.SameLine();
if (ImGui.SmallButton("Send all")) s.OutboundMask = AllMask();
ImGui.SameLine();
if (ImGui.SmallButton("Send none")) s.OutboundMask = 0;
ImGui.SameLine();
if (ImGui.SmallButton("Defaults"))
{
s.InboundMask = TranslateSettings.DefaultInboundMask();
s.OutboundMask = TranslateSettings.DefaultOutboundMask();
}
if (!ImGui.BeginTable("##trchannels", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingStretchProp))
return;
ImGui.TableSetupColumn("Channel", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Listen", ImGuiTableColumnFlags.WidthFixed, 60f);
ImGui.TableSetupColumn("Send", ImGuiTableColumnFlags.WidthFixed, 60f);
ImGui.TableHeadersRow();
foreach (var ch in TranslateChannels.All)
{
uint bit = TranslateChannels.Bit(ch);
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.AlignTextToFramePadding();
ImGui.TextUnformatted(TranslateChannels.Name(ch));
if (ch == TranslateChannel.Local && ImGui.IsItemHovered())
ImGui.SetTooltip("Local speech includes NPCs; listening here uses more of your API quota.");
ImGui.TableNextColumn();
bool inOn = (s.InboundMask & bit) != 0;
if (ImGui.Checkbox("##in" + (int)ch, ref inOn)) s.InboundMask = inOn ? s.InboundMask | bit : s.InboundMask & ~bit;
ImGui.TableNextColumn();
bool outOn = (s.OutboundMask & bit) != 0;
if (ImGui.Checkbox("##out" + (int)ch, ref outOn)) s.OutboundMask = outOn ? s.OutboundMask | bit : s.OutboundMask & ~bit;
}
ImGui.EndTable();
}
private static uint AllMask()
{
uint m = 0;
foreach (var ch in TranslateChannels.All) m |= TranslateChannels.Bit(ch);
return m;
}
// ── Settings (window tab + Advanced Settings page) ─────────────────────
public void RenderSettings(string id)
{
var s = S;
ImGui.TextColored(ColIn, "Service");
int provider = Math.Max(0, Array.IndexOf(TranslateSettings.Providers, s.Provider));
ImGui.SetNextItemWidth(220f);
if (ImGui.Combo("Provider" + id, ref provider, TranslateSettings.ProviderNames, TranslateSettings.ProviderNames.Length))
s.Provider = TranslateSettings.Providers[provider];
ImGui.TextColored(ColDim, ProviderHint(s.Provider));
var keyFlags = _showKey ? ImGuiInputTextFlags.None : ImGuiInputTextFlags.Password;
ImGui.SetNextItemWidth(300f);
ImGui.InputTextWithHint("API key" + id, s.Provider == TranslateSettings.ProviderLibre ? "optional" : "required",
ref s.ApiKey, 256u, keyFlags);
ImGui.SameLine();
ImGui.Checkbox("Show" + id + "key", ref _showKey);
ImGui.SetNextItemWidth(300f);
ImGui.InputTextWithHint("Endpoint" + id, TranslateClient.DefaultUrl(s.Provider, s.ApiKey), ref s.ApiUrl, 256u);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Leave blank for the provider's default.\nLibreTranslate: your server URL, e.g. http://localhost:5000");
ImGui.Spacing();
ImGui.TextColored(ColIn, "Languages");
string my = s.MyLanguage;
if (TranslateLanguages.Combo("Receive (my language)" + id, ref my, allowAuto: false, 180f)) s.MyLanguage = my;
string src = s.InboundSource;
if (TranslateLanguages.Combo("Incoming chat is in" + id, ref src, allowAuto: true, 180f)) s.InboundSource = src;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Auto-detect works for mixed channels; pick a language to force it.");
string def = s.DefaultSendLanguage;
if (TranslateLanguages.Combo("Default send language" + id, ref def, allowAuto: false, 180f))
{
// Following the default keeps the hub in step unless the user picked something else this session.
if (s.CurrentSendLanguage == s.DefaultSendLanguage) s.CurrentSendLanguage = def;
s.DefaultSendLanguage = def;
}
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Each login starts with this send language; swap it any time from the Mini Remote.");
ImGui.Spacing();
ImGui.TextColored(ColIn, "Behaviour");
ImGui.Checkbox("Skip my own lines" + id, ref s.SkipOwn);
ImGui.Checkbox("Write incoming translations to chat" + id, ref s.EchoToChat);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Shown as \"[Translate] [Channel] Name (lang): text\" in AC chat and RynthChat,\nin the same tab as the original. Always kept in the Translate log.");
ImGui.Checkbox("Show what I typed after sending a translation" + id, ref s.EchoOutbound);
ImGui.Checkbox("Send the original if translation fails" + id, ref s.SendOriginalOnError);
ImGui.SetNextItemWidth(60f);
ImGui.InputText("Send-untranslated prefix" + id, ref s.RawPrefix, 4u);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("A typed line starting with this goes out as-is (prefix removed).");
ImGui.SetNextItemWidth(180f);
if (ImGui.SliderInt("Min ms between requests" + id, ref s.MinIntervalMs, 250, 5000)) s.MinIntervalMs = Math.Clamp(s.MinIntervalMs, 250, 10000);
ImGui.SetNextItemWidth(180f);
if (ImGui.SliderInt("Log size" + id, ref s.MaxLog, 20, 1000)) s.MaxLog = Math.Clamp(s.MaxLog, 20, 2000);
ImGui.Spacing();
ImGui.TextColored(ColIn, "Test");
ImGui.SetNextItemWidth(260f);
bool go = ImGui.InputTextWithHint("##trtest" + id, "text to translate", ref _testText, 400u, ImGuiInputTextFlags.EnterReturnsTrue);
ImGui.SameLine();
if ((ImGui.Button("Test" + id) || go) && _testText.Trim().Length > 0) _tr.Test(_testText);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Translates into the current send language and prints the result in chat.");
ImGui.Spacing();
ImGui.TextColored(ColDim, "Shared by all characters. The API key is stored in plain text in RynthAi\\translate.json.");
ImGui.TextColored(ColDim, "AC's chat font can't draw CJK / Thai / Arabic script; those show as boxes.");
}
private static string ProviderHint(string provider) => provider switch
{
TranslateSettings.ProviderDeepL => "DeepL API key (deepl.com/pro-api). Free plan keys end in :fx, 500k chars/month.",
TranslateSettings.ProviderLibre => "Self-hosted or public LibreTranslate server; libretranslate.com needs a key.",
_ => "Cloud Translation API key (console.cloud.google.com), 500k chars/month free.",
};
// ── Mini Remote section ────────────────────────────────────────────────
public void RenderHubSection()
{
var s = S;
ImGui.PushID("##mrtranslate");
ImGui.Checkbox("Translate", ref s.Enabled);
if (ImGui.IsItemHovered()) ImGui.SetTooltip(_tr.StatusLine() + (_tr.LastError.Length > 0 ? "\nLast error: " + _tr.LastError : string.Empty));
ImGui.SameLine();
if (ImGui.SmallButton("Window")) s.ShowWindow = !s.ShowWindow;
string recv = s.MyLanguage;
if (TranslateLanguages.Combo("##mrrecv", ref recv, allowAuto: false, 62f)) s.MyLanguage = recv;
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Receive: {TranslateLanguages.Label(s.MyLanguage)}");
ImGui.SameLine();
if (ImGui.Button("<->")) _tr.SwapLanguages();
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Swap receive and send languages.");
ImGui.SameLine();
string send = s.CurrentSendLanguage;
if (TranslateLanguages.Combo("##mrsend", ref send, allowAuto: false, 62f)) s.CurrentSendLanguage = send;
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Send: {TranslateLanguages.Label(s.CurrentSendLanguage)}");
// Right-click belongs to the Mini Remote options menu, so the reset is a button.
if (s.CurrentSendLanguage != s.DefaultSendLanguage)
{
ImGui.SameLine();
if (ImGui.SmallButton("def")) s.CurrentSendLanguage = s.DefaultSendLanguage;
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Reset the send language to the default ({s.DefaultSendLanguage}).");
}
ImGui.PopID();
}
}

View file

@ -0,0 +1,54 @@
// UiPlacement.cs - Shared first-use placement and off-screen rescue for RynthAi's floating
// ImGui windows (render thread only).
//
// Windows with no imgui.ini entry open near the middle of the game view instead of ImGui's
// default (60,60), where a popped-out panel above the game frame would hide them. A window
// whose saved position leaves it (almost) off the game view is moved back to the middle.
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi;
internal static class UiPlacement
{
/// <summary>Pixels of a window that must stay inside the game view to count as on-screen.</summary>
private const float MinVisible = 40f;
private static readonly Vector2 CenterPivot = new(0.5f, 0.5f);
/// <summary>
/// Before Begin: if the window has no saved position, centre it in the game view, shifted by
/// <paramref name="offset"/> so windows opened together don't stack exactly.
/// </summary>
public static void CenterFirstUse(Vector2 offset = default)
{
Vector2 display = ImGui.GetIO().DisplaySize;
if (display.X <= 1 || display.Y <= 1) return; // no display size yet: ImGui's default spot
ImGui.SetNextWindowPos(display * 0.5f + offset, ImGuiCond.FirstUseEver, CenterPivot);
}
/// <summary>
/// Between Begin and End, once per show (<paramref name="checkedThisShow"/> is cleared by the
/// caller while the window is hidden): moves the window to the middle of the game view if
/// less than 40 px of it is on screen. Returns true when it moved the window.
/// </summary>
public static bool RescueOncePerShow(ref bool checkedThisShow)
{
if (checkedThisShow) return false;
checkedThisShow = true;
Vector2 pos = ImGui.GetWindowPos();
Vector2 size = ImGui.GetWindowSize();
Vector2 display = ImGui.GetIO().DisplaySize;
if (display.X <= MinVisible * 2 || display.Y <= MinVisible * 2) return false;
if (IsOnScreen(pos, size, display)) return false;
ImGui.SetWindowPos(Vector2.Max(Vector2.Zero, (display - size) * 0.5f));
return true;
}
/// <summary>True when at least 40 px of the window overlaps the game view on each axis.</summary>
public static bool IsOnScreen(Vector2 pos, Vector2 size, Vector2 display) =>
pos.X + size.X >= MinVisible && pos.Y + size.Y >= MinVisible
&& pos.X <= display.X - MinVisible && pos.Y <= display.Y - MinVisible;
}

128
Shared/RynthInstallPaths.cs Normal file
View file

@ -0,0 +1,128 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace RynthCore.Install;
/// <summary>
/// Resolves where RynthCore and RynthSuite are installed. The installer lets the user pick
/// both folders and records them under <c>Software\Rynth</c> (HKCU for a per-user install,
/// HKLM for an all-users install), so nothing may assume <c>C:\Games\...</c> any more.
/// <para>
/// Resolution order per folder: environment override (<c>RYNTHCORE_DIR</c> /
/// <c>RYNTHSUITE_DIR</c>, for dev setups) → HKCU → HKLM (32-bit view, where the 32-bit
/// installer writes) → the historical default under <c>C:\Games</c>. Results are cached
/// for the life of the process.
/// </para>
/// Linked into the RynthAi plugin and the Loot / Monster editors. RynthCore keeps an identical copy in
/// <c>src/RynthCore.App/RynthInstallPaths.cs</c> (engine, launcher, injector) — change both together.
/// Registry access is a direct RegGetValueW P/Invoke so it works under NativeAOT and trimming
/// without pulling in Microsoft.Win32.Registry.
/// </summary>
internal static class RynthInstallPaths
{
/// <summary>Default RynthCore folder (pre-2026.10.4.2 installs always used this).</summary>
public const string DefaultCoreDir = @"C:\Games\RynthCore";
/// <summary>Default RynthSuite folder (pre-2026.10.4.2 installs always used this).</summary>
public const string DefaultSuiteDir = @"C:\Games\RynthSuite";
/// <summary>Registry key (under HKCU or HKLM) written by the installer.</summary>
public const string RegistryKey = @"Software\Rynth";
private static string? _coreDir;
private static string? _suiteDir;
/// <summary>RynthCore install folder (launcher, <c>Runtime\</c>, <c>Logs\</c>, <c>Tools\</c>).</summary>
public static string CoreDir => _coreDir ??= Resolve("RYNTHCORE_DIR", "CoreDir", DefaultCoreDir);
/// <summary>RynthSuite folder (plugins and their data, e.g. <c>RynthAi\</c>).</summary>
public static string SuiteDir => _suiteDir ??= Resolve("RYNTHSUITE_DIR", "SuiteDir", DefaultSuiteDir);
/// <summary>Unified RynthCore log folder (<c>&lt;CoreDir&gt;\Logs</c>).</summary>
public static string CoreLogsDir => Path.Combine(CoreDir, "Logs");
/// <summary>RynthAi plugin home and data root (<c>&lt;SuiteDir&gt;\RynthAi</c>).</summary>
public static string RynthAiDir => Path.Combine(SuiteDir, "RynthAi");
/// <summary>Reads a string value from <c>Software\Rynth</c> (HKCU first, then HKLM 32-bit view); null when absent.</summary>
public static string? ReadSetting(string valueName)
=> ReadRegistryString(HKEY_CURRENT_USER, valueName, 0)
?? ReadRegistryString(HKEY_LOCAL_MACHINE, valueName, RRF_SUBKEY_WOW6432KEY);
/// <summary>Deletes a value from HKCU <c>Software\Rynth</c> (used for one-shot installer hand-offs). Best effort.</summary>
public static void DeleteUserSetting(string valueName)
{
try { RegDeleteKeyValueW(HKEY_CURRENT_USER, RegistryKey, valueName); } catch { }
}
private static string Resolve(string envVar, string valueName, string fallback)
{
string? fromEnv = null;
try { fromEnv = Environment.GetEnvironmentVariable(envVar); } catch { }
foreach (string? candidate in new[] { fromEnv, ReadSetting(valueName) })
{
string? normalized = Normalize(candidate);
if (normalized != null) return normalized;
}
return fallback;
}
/// <summary>Accepts only absolute paths; trims whitespace, quotes and trailing separators.</summary>
private static string? Normalize(string? path)
{
if (string.IsNullOrWhiteSpace(path)) return null;
string p = path.Trim().Trim('"').TrimEnd('\\', '/');
if (p.Length == 2 && p[1] == ':') p += "\\"; // keep "D:" as the drive root "D:\"
try
{
if (!Path.IsPathFullyQualified(p)) return null;
string full = Path.GetFullPath(p);
return full.Length > 3 ? full.TrimEnd('\\') : full; // "D:\" stays a root
}
catch
{
return null;
}
}
// ── Win32 registry (advapi32) ───────────────────────────────────────────
private static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001));
private static readonly IntPtr HKEY_LOCAL_MACHINE = new(unchecked((int)0x80000002));
private const uint RRF_RT_REG_SZ = 0x00000002;
private const uint RRF_RT_REG_EXPAND_SZ = 0x00000004;
private const uint RRF_SUBKEY_WOW6432KEY = 0x00020000;
private const int ERROR_SUCCESS = 0;
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int RegGetValueW(IntPtr hkey, string lpSubKey, string lpValue, uint dwFlags,
IntPtr pdwType, char[]? pvData, ref uint pcbData);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int RegDeleteKeyValueW(IntPtr hkey, string lpSubKey, string lpValueName);
private static string? ReadRegistryString(IntPtr root, string valueName, uint viewFlags)
{
try
{
uint flags = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | viewFlags;
uint bytes = 0;
if (RegGetValueW(root, RegistryKey, valueName, flags, IntPtr.Zero, null, ref bytes) != ERROR_SUCCESS || bytes < 2)
return null;
var buffer = new char[(bytes + 1) / 2];
if (RegGetValueW(root, RegistryKey, valueName, flags, IntPtr.Zero, buffer, ref bytes) != ERROR_SUCCESS)
return null;
int len = Array.IndexOf(buffer, '\0');
return new string(buffer, 0, len >= 0 ? len : buffer.Length);
}
catch
{
// Missing advapi32 entry point or access denied — fall back to the defaults.
return null;
}
}
}

77
Shared/UbMobSeed.cs Normal file
View file

@ -0,0 +1,77 @@
using System.Collections.Generic;
namespace RynthCore.CreatureSeed;
/// <summary>
/// Monster damage-type seed derived from UtilityBelt's <c>mob_damage_insights.ldb</c>.
/// Written by the Monster Editor ("Import UB damage insights"); read (never written)
/// by the RynthAi plugin as a fallback for the "Auto" damage type when a monster
/// has no appraised resists yet.
/// File: <c>&lt;SuiteDir&gt;\RynthAi\CreatureData\ub-mob-seed.json</c>.
/// Compiled into both projects so the schema cannot drift; plain properties with
/// defaults keep it source-generator (NativeAOT) friendly.
/// </summary>
public sealed class UbMobSeedFile
{
/// <summary>Current schema version written by the importer.</summary>
public const int CurrentVersion = 1;
/// <summary>File name inside <c>RynthAi\CreatureData</c>.</summary>
public const string FileName = "ub-mob-seed.json";
/// <summary>Schema version of this file; readers ignore files with a newer major version.</summary>
public int Version { get; set; } = CurrentVersion;
/// <summary>UTC time the importer produced the file (ISO-8601).</summary>
public string GeneratedUtc { get; set; } = string.Empty;
/// <summary>Most common UB world name across the imported rows (e.g. "InfiniteLeaftide").</summary>
public string World { get; set; } = string.Empty;
/// <summary>Hits a damage type needs before it is ranked at all.</summary>
public int MinHitsPerType { get; set; }
/// <summary>Source databases that contributed rows (full paths, for traceability).</summary>
public List<string> Sources { get; set; } = new();
/// <summary>One entry per monster with at least two comparable damage types.</summary>
public List<UbMobSeedEntry> Entries { get; set; } = new();
}
/// <summary>Seeded damage-type ranking for one monster.</summary>
public sealed class UbMobSeedEntry
{
/// <summary>Weenie class id; 0 for name-only rows imported from Mag-Tools.</summary>
public uint Wcid { get; set; }
/// <summary>Last display name UB saw for this monster.</summary>
public string Name { get; set; } = string.Empty;
/// <summary>"ub" (live UB wcid rows) or "magtools" (name-keyed Mag-Tools XML imports).</summary>
public string Source { get; set; } = string.Empty;
/// <summary>All hits UB recorded against this monster (every type, including unranked ones).</summary>
public long TotalHits { get; set; }
/// <summary>Ranked damage types, best first. Only types meeting the hit threshold are listed.</summary>
public List<UbMobSeedElement> Elements { get; set; } = new();
}
/// <summary>Observed outgoing-damage statistics for one damage type against one monster.</summary>
public sealed class UbMobSeedElement
{
/// <summary>RynthAi element name: Slash, Pierce, Bludgeon, Fire, Cold, Lightning, Acid or Nether.</summary>
public string Element { get; set; } = string.Empty;
/// <summary>Hits recorded with this damage type.</summary>
public int Hits { get; set; }
/// <summary>Average damage per hit with this damage type.</summary>
public double AvgDamage { get; set; }
/// <summary>Largest single hit (0 for Mag-Tools rows, which do not record it).</summary>
public long MaxHit { get; set; }
/// <summary>Relative effectiveness 0..1 (1 = best type for this monster); used for the ranking.</summary>
public double Score { get; set; }
}

View file

@ -5,5 +5,7 @@ namespace RynthCore.MonsterEditor;
[JsonSerializable(typeof(List<MonsterRule>))]
[JsonSerializable(typeof(EditorSettings))]
// UB damage-insights seed written for the RynthAi plugin (see UbMobSeedImport).
[JsonSerializable(typeof(RynthCore.CreatureSeed.UbMobSeedFile))]
[JsonSourceGenerationOptions(WriteIndented = true, IncludeFields = true)]
internal partial class EditorJsonContext : JsonSerializerContext { }

View file

@ -15,10 +15,22 @@ public class MonsterRule : INotifyPropertyChanged
private bool _useArc, _useBolt = true, _useRing, _useStreak, _useBlast;
private string _exVuln = "None";
private int _offhandId;
private int _preferredAmmoItemId;
private string _petDamage = "PAuto";
/// <summary>Dashboard-only label; optional (empty shows as "Default" in the game UI).</summary>
private string _category = string.Empty;
/// <summary>vTank-style match expression. Empty = for named rules, match on Name substring; for the Default row, it is the global fallback when nothing else matches.</summary>
private string _matchExpression = string.Empty;
public string Name { get => _name; set { _name = value; OnPropertyChanged(); } }
public int Priority { get => _priority; set { _priority = value; OnPropertyChanged(); } }
public string Category { get => _category; set { _category = value ?? string.Empty; OnPropertyChanged(); } }
/// <summary>vTank-style match expression. Empty matches on the rule name.</summary>
public string MatchExpression
{
get => _matchExpression;
set { _matchExpression = value ?? string.Empty; OnPropertyChanged(); }
}
public string DamageType { get => _damageType; set { _damageType = value; OnPropertyChanged(); } }
public int WeaponId { get => _weaponId; set { _weaponId = value; OnPropertyChanged(); } }
public bool Fester { get => _fester; set { _fester = value; OnPropertyChanged(); } }
@ -34,11 +46,70 @@ public class MonsterRule : INotifyPropertyChanged
public bool UseBlast { get => _useBlast; set { _useBlast = value; OnPropertyChanged(); } }
public string ExVuln { get => _exVuln; set { _exVuln = value; OnPropertyChanged(); } }
public int OffhandId { get => _offhandId; set { _offhandId = value; OnPropertyChanged(); } }
/// <summary>Optional loose ammo stack id for missile combat while this rule matches (0 = auto).</summary>
public int PreferredAmmoItemId { get => _preferredAmmoItemId; set { _preferredAmmoItemId = value; OnPropertyChanged(); } }
public string PetDamage { get => _petDamage; set { _petDamage = value; OnPropertyChanged(); } }
[JsonIgnore]
/// <summary>True for the special row named "Default" — the catch-all when no other rule matches.</summary>
public bool IsDefault => string.Equals(_name, "Default", System.StringComparison.OrdinalIgnoreCase);
/// <summary>Full copy (for import merge). Copies every rule field, UseBlast included.</summary>
public MonsterRule Clone()
{
return new MonsterRule
{
Name = _name,
Category = _category,
MatchExpression = _matchExpression,
Priority = _priority,
DamageType = _damageType,
WeaponId = _weaponId,
Fester = _fester,
Broadside = _broadside,
GravityWell = _gravityWell,
Imperil = _imperil,
Yield = _yield,
Vuln = _vuln,
UseArc = _useArc,
UseBolt = _useBolt,
UseRing = _useRing,
UseStreak = _useStreak,
UseBlast = _useBlast,
ExVuln = _exVuln,
OffhandId = _offhandId,
PreferredAmmoItemId = _preferredAmmoItemId,
PetDamage = _petDamage,
};
}
/// <summary>Overwrites combat fields (used to merge a VT Default row into the Rynth Default row).</summary>
public void CopyCombatSettingsFrom(MonsterRule? src)
{
if (src == null) return;
// Keep Name: must stay "Default". Use public setters so the grid updates.
Category = src.Category;
MatchExpression = src.MatchExpression;
Priority = src.Priority;
DamageType = src.DamageType;
WeaponId = src.WeaponId;
Fester = src.Fester;
Broadside = src.Broadside;
GravityWell = src.GravityWell;
Imperil = src.Imperil;
Yield = src.Yield;
Vuln = src.Vuln;
UseArc = src.UseArc;
UseBolt = src.UseBolt;
UseRing = src.UseRing;
UseStreak = src.UseStreak;
UseBlast = src.UseBlast;
ExVuln = src.ExVuln;
OffhandId = src.OffhandId;
PreferredAmmoItemId = src.PreferredAmmoItemId;
PetDamage = src.PetDamage;
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string? name = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

View file

@ -16,6 +16,18 @@
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" />
<PackageReference Include="Avalonia.Controls.DataGrid" Version="11.2.3" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.0" />
<!-- Reads UtilityBelt's mob_damage_insights.ldb (same LiteDB version UB writes with). -->
<PackageReference Include="LiteDB" Version="5.0.21" />
<!-- Direct reference overrides Avalonia's transitive 0.20.x (NU1903 / GHSA-xrw6-gwf8-vvr9). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
</ItemGroup>
<ItemGroup>
<!-- Install-location resolver (installer-chosen RynthCore / RynthSuite folders). -->
<Compile Include="..\..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- UB damage-insights seed schema, shared with the RynthAi plugin. -->
<Compile Include="..\..\Shared\UbMobSeed.cs" Link="Shared\UbMobSeed.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,318 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using LiteDB;
using RynthCore.CreatureSeed;
// LiteDB ships its own JsonSerializer; the seed is written with System.Text.Json (source-generated).
using StjSerializer = System.Text.Json.JsonSerializer;
namespace RynthCore.MonsterEditor;
/// <summary>
/// Converts UtilityBelt's <c>mob_damage_insights.ldb</c> (LiteDB 5) into the RynthAi
/// damage-type seed (<see cref="UbMobSeedFile"/>). Runs here rather than in the plugin
/// because LiteDB is reflection-heavy and the RynthAi plugin is NativeAOT.
/// <para>
/// UB rows record damage players dealt TO each monster, per damage type. The
/// per-character databases are pushed into the shared server database every 12 hours,
/// so they are mostly a subset of it: for each monster the single row with the most hits
/// wins (summing would double-count).
/// </para>
/// </summary>
internal static class UbMobSeedImport
{
/// <summary>Hits a damage type needs before it is ranked.</summary>
public const int DefaultMinHitsPerType = 20;
private const string DbFileName = "mob_damage_insights.ldb";
private const string WcidCollection = "mob_damage_agg";
private const string MagCollection = "mob_mag_name_agg";
/// <summary>UB damage-type flags (ACE <c>DamageType</c>) mapped to RynthAi element names.
/// Normal (0) and combined flags are not castable choices and are skipped.</summary>
private static readonly Dictionary<string, string> FlagToElement = new()
{
["1"] = "Slash",
["2"] = "Pierce",
["4"] = "Bludgeon",
["8"] = "Cold",
["16"] = "Fire",
["32"] = "Acid",
["64"] = "Lightning",
["1024"] = "Nether",
};
/// <summary>Outcome of an import run.</summary>
public sealed record Result(bool Ok, string Message, UbMobSeedFile? Seed);
/// <summary>UB's per-world folder for InfiniteLeaftide (holds the shared server database).</summary>
public static string DefaultServerFolder => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"Decal Plugins", "UtilityBelt", "InfiniteLeaftide");
/// <summary>Where the plugin reads the seed: <c>&lt;SuiteDir&gt;\RynthAi\CreatureData\ub-mob-seed.json</c>.</summary>
public static string DefaultOutputPath => Path.Combine(
RynthCore.Install.RynthInstallPaths.RynthAiDir, "CreatureData", UbMobSeedFile.FileName);
/// <summary>
/// Lists the shared server database (first) and every per-character database
/// one level below it.
/// </summary>
public static List<string> FindDatabases(string serverFolder)
{
var list = new List<string>();
if (!Directory.Exists(serverFolder)) return list;
string shared = Path.Combine(serverFolder, DbFileName);
if (File.Exists(shared)) list.Add(shared);
foreach (string dir in Directory.GetDirectories(serverFolder).OrderBy(d => d, StringComparer.OrdinalIgnoreCase))
{
string perChar = Path.Combine(dir, DbFileName);
if (File.Exists(perChar)) list.Add(perChar);
}
return list;
}
/// <summary>
/// Reads every database under <paramref name="serverFolder"/>, ranks damage types per
/// monster and writes the seed to <paramref name="outputPath"/> atomically.
/// </summary>
public static Result Run(string serverFolder, string outputPath, int minHitsPerType = DefaultMinHitsPerType)
{
List<string> dbs = FindDatabases(serverFolder);
if (dbs.Count == 0)
return new Result(false, $"No {DbFileName} found in {serverFolder}.", null);
// Best row per wcid / per normalized Mag-Tools name, across all sources.
var bestWcid = new Dictionary<uint, BsonDocument>();
var bestMag = new Dictionary<string, BsonDocument>(StringComparer.OrdinalIgnoreCase);
var used = new List<string>();
var errors = new List<string>();
foreach (string db in dbs)
{
try
{
ReadDatabase(db, bestWcid, bestMag);
used.Add(db);
}
catch (Exception ex)
{
errors.Add($"{Path.GetFileName(Path.GetDirectoryName(db))}: {ex.Message}");
}
}
if (used.Count == 0)
return new Result(false, "Could not read any UB database: " + string.Join("; ", errors), null);
var seed = new UbMobSeedFile
{
GeneratedUtc = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture),
MinHitsPerType = minHitsPerType,
Sources = used,
World = MostCommonWorld(bestWcid.Values),
};
// Live UB rows keyed by wcid.
var wcidNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var (wcid, doc) in bestWcid.OrderBy(kv => kv.Key))
{
string name = Str(doc, "LastSeenName");
if (name.Length > 0) wcidNames.Add(name);
var elements = RankElements(doc, minHitsPerType, hasPeaks: true);
if (elements.Count < 2) continue; // one type alone says nothing about weakness
seed.Entries.Add(new UbMobSeedEntry
{
Wcid = wcid,
Name = name,
Source = "ub",
TotalHits = Num(doc, "TotalHits"),
Elements = elements,
});
}
// Mag-Tools name-only rows, skipped when a wcid row already covers the name.
foreach (var doc in bestMag.Values)
{
string name = Str(doc, "LastSeenDisplayName");
if (name.Length == 0) name = Str(doc, "NormalizedMobName");
if (name.Length == 0 || wcidNames.Contains(name)) continue;
var elements = RankElements(doc, minHitsPerType, hasPeaks: false);
if (elements.Count < 2) continue;
seed.Entries.Add(new UbMobSeedEntry
{
Wcid = 0,
Name = name,
Source = "magtools",
TotalHits = elements.Sum(e => (long)e.Hits),
Elements = elements,
});
}
WriteAtomic(outputPath, StjSerializer.Serialize(seed, EditorJsonContext.Default.UbMobSeedFile));
int ub = seed.Entries.Count(e => e.Source == "ub");
int mag = seed.Entries.Count - ub;
string msg = $"UB seed written: {ub} monster(s) by wcid + {mag} by name (Mag-Tools) from {used.Count} database(s) → {outputPath}";
if (errors.Count > 0) msg += $" Skipped: {string.Join("; ", errors)}";
return new Result(true, msg, seed);
}
/// <summary>
/// Opens a snapshot copy of <paramref name="dbPath"/> (UB may have the live file open)
/// and folds its rows into the best-row maps.
/// </summary>
private static void ReadDatabase(string dbPath, Dictionary<uint, BsonDocument> bestWcid,
Dictionary<string, BsonDocument> bestMag)
{
string tempDir = Path.Combine(Path.GetTempPath(), "RynthUbSeed-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
try
{
string copy = Path.Combine(tempDir, DbFileName);
CopyShared(dbPath, copy);
// LiteDB 5 keeps uncommitted pages in "<name>-log.ldb"; copy it so recent hits are included.
string log = Path.Combine(Path.GetDirectoryName(dbPath)!, Path.GetFileNameWithoutExtension(dbPath) + "-log.ldb");
if (File.Exists(log))
CopyShared(log, Path.Combine(tempDir, Path.GetFileNameWithoutExtension(DbFileName) + "-log.ldb"));
// Writable connection on the private copy so LiteDB can replay the log; the original is untouched.
using var db = new LiteDatabase(new ConnectionString { Filename = copy, Connection = ConnectionType.Direct });
if (db.CollectionExists(WcidCollection))
{
foreach (var doc in db.GetCollection(WcidCollection).FindAll())
{
long wcid = Num(doc, "Wcid");
// wcid 1 is the player weenie (self/PvP lines), not a monster.
if (wcid <= 1 || wcid > uint.MaxValue) continue;
KeepBest(bestWcid, (uint)wcid, doc, Num(doc, "TotalHits"));
}
}
if (db.CollectionExists(MagCollection))
{
foreach (var doc in db.GetCollection(MagCollection).FindAll())
{
string key = Str(doc, "NormalizedMobName");
if (key.Length == 0) continue;
KeepBest(bestMag, key, doc, SumValues(doc, "HitsByType"));
}
}
}
finally
{
try { Directory.Delete(tempDir, recursive: true); } catch { /* temp cleanup is best-effort */ }
}
}
/// <summary>Keeps the row with the most hits per key (sources overlap; see class remarks).</summary>
private static void KeepBest<TKey>(Dictionary<TKey, BsonDocument> map, TKey key, BsonDocument doc, long hits)
where TKey : notnull
{
if (!map.TryGetValue(key, out var existing) || hits > HitsOf(existing))
map[key] = doc;
}
/// <summary>Total hits of a row in either collection's shape.</summary>
private static long HitsOf(BsonDocument doc)
{
long total = Num(doc, "TotalHits");
return total > 0 ? total : SumValues(doc, "HitsByType");
}
/// <summary>
/// Ranks the castable damage types with at least <paramref name="minHits"/> hits.
/// Score blends average damage (vs the best average) with UB's own effectiveness
/// measure, peak hit vs the best peak, when peaks are recorded.
/// </summary>
private static List<UbMobSeedElement> RankElements(BsonDocument doc, int minHits, bool hasPeaks)
{
var hits = Doc(doc, "HitsByType");
var sums = Doc(doc, "SumDamageByType");
var peaks = hasPeaks ? Doc(doc, "MaxDamageByType") : null;
if (hits == null || sums == null) return new List<UbMobSeedElement>();
var list = new List<UbMobSeedElement>();
foreach (string flag in hits.Keys)
{
if (!FlagToElement.TryGetValue(flag, out string? element)) continue;
int n = (int)Math.Min(int.MaxValue, Num(hits, flag));
if (n < minHits || !sums.ContainsKey(flag)) continue;
list.Add(new UbMobSeedElement
{
Element = element,
Hits = n,
AvgDamage = Math.Round(Num(sums, flag) / (double)n, 2),
MaxHit = peaks != null && peaks.ContainsKey(flag) ? Num(peaks, flag) : 0,
});
}
if (list.Count == 0) return list;
double bestAvg = list.Max(e => e.AvgDamage);
long bestPeak = list.Max(e => e.MaxHit);
foreach (var e in list)
{
double avgRatio = bestAvg > 0 ? e.AvgDamage / bestAvg : 0;
double score = bestPeak > 0
? 0.5 * avgRatio + 0.5 * (e.MaxHit / (double)bestPeak)
: avgRatio;
e.Score = Math.Round(score, 4);
}
return list.OrderByDescending(e => e.Score).ThenByDescending(e => e.Hits).ToList();
}
/// <summary>Most frequent <c>WorldName</c> among the rows (empty when none recorded).</summary>
private static string MostCommonWorld(IEnumerable<BsonDocument> rows) =>
rows.Select(r => Str(r, "WorldName"))
.Where(w => w.Length > 0)
.GroupBy(w => w, StringComparer.OrdinalIgnoreCase)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.FirstOrDefault() ?? string.Empty;
/// <summary>Copies a file another process may hold open for writing.</summary>
private static void CopyShared(string source, string dest)
{
using var src = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
using var dst = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None);
src.CopyTo(dst);
}
/// <summary>Writes via a temp file so the plugin never reads a half-written seed.</summary>
private static void WriteAtomic(string path, string contents)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
File.WriteAllText(tmp, contents);
File.Move(tmp, path, overwrite: true);
}
// ── BSON helpers (schema-tolerant: UB may store numbers as Int32, Int64 or Double) ──
private static BsonDocument? Doc(BsonDocument doc, string field) =>
doc.TryGetValue(field, out var v) && v.IsDocument ? v.AsDocument : null;
private static string Str(BsonDocument doc, string field) =>
doc.TryGetValue(field, out var v) && v.IsString ? v.AsString.Trim() : string.Empty;
private static long Num(BsonDocument doc, string field) =>
doc.TryGetValue(field, out var v) && v.IsNumber ? Convert.ToInt64(v.RawValue, CultureInfo.InvariantCulture) : 0;
private static long SumValues(BsonDocument doc, string field)
{
var d = Doc(doc, field);
if (d == null) return 0;
long total = 0;
foreach (string k in d.Keys) total += Num(d, k);
return total;
}
}

View file

@ -0,0 +1,548 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Data.Sqlite;
namespace RynthCore.MonsterEditor;
/// <summary>
/// Best-effort import of VirindiTank "user" macro profiles (typically <c>.usd</c>) into RynthAi
/// <see cref="MonsterRule"/> rows. Tries, in order: (1) line-oriented SCF <c>MyMonsters</c> (classic
/// uTank2 <c>*.usd</c> in <c>VirindiPlugins\VirindiTank</c>); (2) SQLite; (3) binary scan for
/// vTank-style match expressions.
/// </summary>
public static class VirindiTankUsdImport
{
public sealed class Result
{
public bool Ok { get; set; }
public List<MonsterRule> Rules { get; } = new();
/// <summary>Human-readable summary: counts, method used, warnings.</summary>
public string Message { get; set; } = string.Empty;
}
public static Result TryImport(string filePath)
{
var r = new Result();
if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath))
{
r.Message = "File not found.";
return r;
}
string? allText;
try
{
// VT text profiles are UTF-8; invalid sequences become replacement chars, still OK for SCF.
allText = File.ReadAllText(filePath, Encoding.UTF8);
}
catch (Exception ex)
{
r.Message = $"Read failed: {ex.Message}";
return r;
}
// Primary path: SCF <c>MyMonsters</c> block (see VirindiPlugins\VirindiTank\*.usd, format 8+).
if (VirindiTankUsdTextScfParser.TryParseMyMonsters(allText, r.Rules, out string? scfNote) && r.Rules.Count > 0)
{
r.Ok = true;
r.Message = BuildMessage("MyMonsters (VT SCF / line format)", r.Rules.Count, scfNote);
return r;
}
r.Rules.Clear();
byte[] bytes;
try
{
bytes = File.ReadAllBytes(filePath);
}
catch (Exception ex2)
{
r.Message = $"Read as bytes failed: {ex2.Message}";
return r;
}
if (IsSqliteDatabase(bytes))
{
try
{
if (TryImportFromSqlite(filePath, r.Rules, out int count, out string? sqlNote))
{
r.Ok = true;
r.Message = BuildMessage("SQLite (Virindi uTank settings database)", count, sqlNote);
return r;
}
}
catch (Exception ex)
{
const string pfx = "SQLite read error: ";
string errMsg = pfx + ex.Message;
if (TryImportFromStringScan(bytes, r.Rules, out int exprCount, out string? scanNote))
{
r.Ok = exprCount > 0;
r.Message = BuildMessage("Text scan (after SQLite exception)", exprCount, errMsg + " " + scanNote);
}
else
r.Message = errMsg;
return r;
}
}
string? fallNote;
if (TryImportFromStringScan(bytes, r.Rules, out int n, out fallNote))
{
r.Ok = n > 0;
r.Message = n > 0
? BuildMessage("Expression scan (non-SQLite or unreadable table)", n, fallNote)
: "Could not import: no vTank-style match expressions in file. " + (fallNote ?? string.Empty) +
" If this is a Virindi Tank user profile, ensure the file is a .usd from your VirindiPlugins\\VirindiTank folder (SQLite based).";
}
else
{
r.Message = fallNote ?? "Import failed.";
}
return r;
}
private static string BuildMessage(string method, int count, string? extra)
{
var sb = new StringBuilder();
sb.Append(CultureInfo.InvariantCulture, $"Imported {count} rule(s) using {method}.");
if (!string.IsNullOrWhiteSpace(extra))
{
sb.Append(' ');
sb.Append(extra);
}
return sb.ToString();
}
private static bool IsSqliteDatabase(byte[] header)
{
const string sig = "SQLite format 3\0";
if (header.Length < sig.Length) return false;
for (int i = 0; i < sig.Length; i++)
{
if (header[i] != sig[i]) return false;
}
return true;
}
private static bool TryImportFromSqlite(string filePath, List<MonsterRule> outList, out int count, out string? note)
{
count = 0;
note = null;
outList.Clear();
var csb = new SqliteConnectionStringBuilder
{
DataSource = filePath,
Mode = SqliteOpenMode.ReadOnly,
};
using var con = new SqliteConnection(csb.ToString());
con.Open();
// Discover tables and their columns; pick the best "monster list" table.
var tableScores = new List<(string name, int score)>();
using (var listCmd = con.CreateCommand())
{
listCmd.CommandText = "SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'";
using var r = listCmd.ExecuteReader();
while (r.Read())
{
string t = r.GetString(0);
if (!IsSafeTableName(t)) continue;
int s = ScoreTableIntent(con, t);
if (s > 0) tableScores.Add((t, s));
}
}
if (tableScores.Count == 0)
{
// Unknown schema — try every user table; ReadMonsterTable skips unsuitable ones.
using (var listCmd2 = con.CreateCommand())
{
listCmd2.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'";
using var r2 = listCmd2.ExecuteReader();
while (r2.Read())
{
string t = r2.GetString(0);
if (IsSafeTableName(t)) tableScores.Add((t, 1));
}
}
}
if (tableScores.Count == 0)
{
note = "No user tables in SQLite file.";
return false;
}
tableScores.Sort((a, b) => b.score.CompareTo(a.score));
var best = tableScores[0].name;
if (!ReadMonsterTable(con, best, outList, out int readCount, out string? readErr))
{
note = readErr;
return false;
}
count = readCount;
note = $"Table \"{best}\" (score {tableScores[0].score}). {readErr ?? string.Empty}".Trim();
return count > 0;
}
private static bool IsSafeTableName(string t)
{
foreach (char c in t)
{
if (char.IsLetterOrDigit(c) || c is '_' or '-') continue;
return false;
}
return t.Length is > 0 and < 200;
}
private static int ScoreTableIntent(SqliteConnection con, string table)
{
int s = 0;
if (table.IndexOf("monster", StringComparison.OrdinalIgnoreCase) >= 0) s += 15;
if (table.IndexOf("mob", StringComparison.OrdinalIgnoreCase) >= 0) s += 8;
if (table.IndexOf("attack", StringComparison.OrdinalIgnoreCase) >= 0) s += 4;
using var c = con.CreateCommand();
c.CommandText = $"PRAGMA table_info(\"{table}\")";
using var r = c.ExecuteReader();
while (r.Read())
{
string col = r.GetString(1);
s += ColumnScore(col);
}
return s;
}
private static int ColumnScore(string col)
{
string c = col.ToLowerInvariant();
if (c.Contains("fester", StringComparison.Ordinal) || c is "f") return 4;
if (c.Contains("broad", StringComparison.Ordinal) || c is "b" or "broadside") return 4;
if (c.Contains("gravity", StringComparison.Ordinal) || c is "g") return 2;
if (c.Contains("imperil", StringComparison.Ordinal) || c is "i") return 2;
if (c.Contains("yield", StringComparison.Ordinal) || c is "y") return 2;
if (c.Contains("vuln", StringComparison.Ordinal) && c.Contains("ex", StringComparison.Ordinal) == false) return 2;
if (c is "v") return 2;
if (c.Contains("expression", StringComparison.Ordinal) || c is "matchexpr" or "matchexpression" or "match" or "expr" or "e")
return 8;
if (c is "name" or "mname" or "monstername" or "n")
return 6;
if (c.Contains("damag", StringComparison.Ordinal) || c.Contains("element", StringComparison.Ordinal) || c is "dmg" or "dt")
return 4;
if (c.Contains("priority", StringComparison.Ordinal) || c is "p" or "pri" or "sort" or "idx" or "ordinal")
return 2;
if (c.Contains("weapon", StringComparison.Ordinal) || c.Contains("wand", StringComparison.Ordinal)) return 2;
if (c is "a" or "r" or "s" or "w" or "u") return 1; // A/R/S are ambiguous; low weight
return 0;
}
private static bool ReadMonsterTable(SqliteConnection con, string table, List<MonsterRule> outList, out int count, out string? err)
{
count = 0;
err = null;
// Prefer stable ordering when a dedicated column exists (ROWID is the SQLite insert order for many VT exports).
string orderBy = "ROWID";
if (TableHasColumn(con, table, "Order")) orderBy = "CAST([Order] AS INTEGER)";
else if (TableHasColumn(con, table, "SortIndex")) orderBy = "SortIndex";
else if (TableHasColumn(con, table, "Index")) orderBy = "[Index]";
using var cmd = con.CreateCommand();
cmd.CommandText = $"SELECT * FROM \"{table}\" ORDER BY {orderBy} ASC";
using var r = cmd.ExecuteReader();
int ordName = FindOrdinalByHints(r, "name", "monstername", "mname", "entry", "n", "text0");
int ordExpr = FindOrdinalByHints(r, "matchexpression", "match", "expression", "expr", "e", "ed");
if (ordExpr < 0) ordExpr = FindExpressionColumn(r);
int ordDmg = FindOrdinalByHints(r, "damagetype", "element", "dmg", "de", "delement");
int ordPri = FindOrdinalByHints(r, "priority", "p", "pri", "importance", "ipriority");
int ordEx = FindOrdinalByHints(r, "exvuln", "exvul", "extravuln", "vulnextra");
int ordWep = FindOrdinalByHints(r, "weaponid", "weapon", "windex", "weaponindex");
int ordOff = FindOrdinalByHints(r, "offhand", "offhandid", "shield");
int ordF = FindOrdinalByHints(r, "fester", "f", "b_fester", "bisfester", "festerb");
int ordB = FindOrdinalByHints(r, "broadside", "b", "broad", "broadb");
int ordG = FindOrdinalByHints(r, "gravity", "g", "grav");
int ordI = FindOrdinalByHints(r, "imperil", "i", "imprl");
int ordY = FindOrdinalByHints(r, "yield", "y", "yld");
int ordV = FindOrdinalByHints(r, "vulnerability", "v", "vuln", "b_vuln", "bisfestervuln", "bisfesterv"); // be careful: skip ex vuln
// VT often: UseArc, UseRing, Streak, Bolt
int ordA = FindOrdinalByHints(r, "usearc", "arc", "a");
int ordR = FindOrdinalByHints(r, "usering", "ring", "r", "b_ring");
int ordS = FindOrdinalByHints(r, "streak", "s", "usestreak", "b_streak", "bisfeststreak", "bisfstreak", "bisfstreak2");
int ordBl= FindOrdinalByHints(r, "usebolt", "bolt", "bl", "b_bolt", "bisfstreakbolt", "bisfstreakbol", "bisfb");
if (ordName < 0 && ordExpr < 0)
{
err = "Table has no recognizable name/expression column.";
return false;
}
while (r.Read())
{
var m = new MonsterRule();
string? name = GetStr(r, ordName);
string? expr = GetStr(r, ordExpr);
if (!string.IsNullOrWhiteSpace(name) && name.Trim().Equals("default", StringComparison.OrdinalIgnoreCase))
{
m.Name = "Default";
m.MatchExpression = string.Empty;
}
else
{
m.Name = name?.Trim() ?? string.Empty;
m.MatchExpression = expr?.Trim() ?? string.Empty;
}
m.Priority = 1;
if (ordPri >= 0) m.Priority = Math.Clamp(ToInt32(r, ordPri, 1), -100, 10000);
m.DamageType = string.IsNullOrEmpty(GetStr(r, ordDmg)) ? "Auto" : MapDamageType(GetStr(r, ordDmg) ?? "Auto");
m.ExVuln = string.IsNullOrEmpty(GetStr(r, ordEx)) ? "None" : (GetStr(r, ordEx) ?? "None");
m.WeaponId = ordWep >= 0 ? Math.Max(0, ToInt32(r, ordWep, 0)) : 0;
m.OffhandId = ordOff >= 0 ? Math.Max(0, ToInt32(r, ordOff, 0)) : 0;
m.Fester = GetBoolish(r, ordF);
m.Broadside = GetBoolish(r, ordB);
m.GravityWell= GetBoolish(r, ordG);
m.Imperil = GetBoolish(r, ordI);
m.Yield = GetBoolish(r, ordY);
m.Vuln = GetBoolish(r, ordV);
m.UseArc = GetBoolish(r, ordA);
m.UseRing = GetBoolish(r, ordR);
m.UseStreak = GetBoolish(r, ordS);
m.UseBolt = ordBl >= 0 ? GetBoolish(r, ordBl) : m.UseBolt;
// If row is empty, skip
if (string.IsNullOrEmpty(m.Name) && string.IsNullOrEmpty(m.MatchExpression))
{
bool anyToggle = m.Fester || m.Broadside || m.GravityWell || m.Imperil || m.Yield || m.Vuln
|| m.UseArc || m.UseRing || m.UseStreak;
if (!anyToggle) continue;
}
if (m.Name.Length == 0 && m.MatchExpression.Length == 0)
continue;
outList.Add(m);
}
count = outList.Count;
if (count == 0) err = "No mappable rows.";
return true;
}
private static bool TableHasColumn(SqliteConnection con, string table, string col)
{
using var c = con.CreateCommand();
c.CommandText = $"PRAGMA table_info(\"{table}\")";
using var r = c.ExecuteReader();
while (r.Read())
{
if (r.GetString(1).Equals(col, StringComparison.OrdinalIgnoreCase)) return true;
}
return false;
}
/// <summary>Column whose name is exactly <paramref name="hints"/> (lowercase) or a short exact code (P, V, etc.).</summary>
private static int FindOrdinalByHints(SqliteDataReader r, params string[] hints)
{
for (int i = 0; i < r.FieldCount; i++)
{
string n = r.GetName(i);
string nl = n.ToLowerInvariant();
foreach (string h in hints)
{
if (h.Equals("p", StringComparison.Ordinal) && nl is "p" or "ipriority")
return i;
if (h.Equals("v", StringComparison.Ordinal) && (nl is "v" or "b_v" or "b_vuln" or "vuln")
&& !nl.Contains("exvul", StringComparison.Ordinal) && !nl.Contains("ex_vul", StringComparison.Ordinal))
return i;
if (nl == h.ToLowerInvariant()) return i;
}
}
return -1;
}
private static int FindExpressionColumn(SqliteDataReader r)
{
for (int i = 0; i < r.FieldCount; i++)
{
string nl = r.GetName(i).ToLowerInvariant();
if (nl.Contains("matchexpr", StringComparison.Ordinal)
|| (nl.Contains("match", StringComparison.Ordinal) && nl.Contains("exp", StringComparison.Ordinal)))
return i;
}
return -1;
}
private static string? GetStr(SqliteDataReader r, int ord) => ord < 0 || r.IsDBNull(ord) ? null : r.GetValue(ord)?.ToString();
private static int ToInt32(SqliteDataReader r, int ord, int dft)
{
try
{
if (r.IsDBNull(ord)) return dft;
return Convert.ToInt32(r.GetValue(ord), CultureInfo.InvariantCulture);
}
catch
{
if (int.TryParse(r.GetValue(ord)?.ToString(), out int p)) return p;
return dft;
}
}
private static bool GetBoolish(SqliteDataReader r, int ord)
{
if (ord < 0 || r.IsDBNull(ord)) return false;
var v = r.GetValue(ord);
if (v is long l) return l != 0;
if (v is int i) return i != 0;
if (v is bool b) return b;
string? s = v?.ToString()?.Trim();
if (string.IsNullOrEmpty(s)) return false;
if (s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1" || s.Equals("yes", StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
private static string MapDamageType(string raw)
{
string t = raw.Trim();
if (t.Length == 0) return "Auto";
if (t.Contains('<', StringComparison.Ordinal) && t.Contains('>', StringComparison.Ordinal)) // <auto>
{
if (t.Contains("auto", StringComparison.OrdinalIgnoreCase)) return "Auto";
}
// VT uses words like "Slash" — normalize first letter
if (t.Equals("Auto", StringComparison.OrdinalIgnoreCase)) return "Auto";
foreach (string s in new[] { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" })
{
if (s.Equals(t, StringComparison.OrdinalIgnoreCase)) return s;
}
// Unknown — keep for display, Rynth will treat oddly if not in list; still better than Data loss
return t;
}
// ── Binary / UTF-16 / UTF-8 string scan: expression fallbacks ────────────
private static bool TryImportFromStringScan(byte[] data, List<MonsterRule> outList, out int count, out string? note)
{
count = 0;
note = null;
outList.Clear();
var strs = new HashSet<string>(StringComparer.Ordinal);
foreach (string s in ExtractAllStrings(data, minLen: 8, maxLen: 480))
{
if (LooksLikeVtExpression(s))
strs.Add(s.Trim());
}
if (strs.Count == 0)
{
count = 0;
return false;
}
// Prefer longer expressions (often more specific)
foreach (string s in strs.OrderByDescending(x => x.Length))
{
outList.Add(new MonsterRule
{
Name = string.Empty,
MatchExpression = s,
DamageType = "Auto",
UseBolt = true,
});
}
count = outList.Count;
note = "Binary mode only recovers vTank **match expression** rows (name-only entries must be added by hand, or re-export from a SQLite .usd).";
return true;
}
/// <summary>Pull printable ASCII/UTF-8 (single-byte) and UTF-16-LE "wide string" runs from a blob.</summary>
private static IEnumerable<string> ExtractAllStrings(byte[] data, int minLen, int maxLen)
{
// 7-bit runs (covers most human-readable .usd contents outside SQLite BLOBs)
int start = -1;
for (int i = 0; i < data.Length; i++)
{
byte b = data[i];
if ((b >= 0x20 && b <= 0x7E) || b == 0x09) // printables + tab
{
if (start < 0) start = i;
}
else
{
if (start >= 0)
{
int len = i - start;
if (len >= minLen)
yield return Encoding.UTF8.GetString(data, start, len > maxLen ? maxLen : len);
}
start = -1;
}
}
if (start >= 0)
{
int len2 = data.Length - start;
if (len2 >= minLen)
yield return Encoding.UTF8.GetString(data, start, len2 > maxLen ? maxLen : len2);
}
// UTF-16-LE ASCII: [char][0][char][0] (common in Windows/.NET-originated data)
for (int i = 0; i < data.Length - 1;)
{
if (data[i + 1] != 0) { i++; continue; }
if (data[i] < 0x20) { i++; continue; }
{
char ch = (char)data[i];
if (!char.IsLetter(ch) && !char.IsDigit(ch) && ch is not ( '<' or '=' or '(' or '!' or 'f' or 't')) { i++; continue; }
}
int p = i;
var sb = new StringBuilder();
while (p + 1 < data.Length)
{
if (data[p + 1] != 0) break;
int c = data[p];
if (c < 0x20) break;
if (c > 0x7E) break;
sb.Append((char)c);
p += 2;
if (sb.Length >= maxLen) break;
}
if (sb.Length >= minLen) yield return sb.ToString();
if (p > i) { i = p; }
else { i++; }
}
}
private static bool LooksLikeVtExpression(string s)
{
s = s.Trim();
if (s.Length < 6) return false;
if (s.Equals("DEFAULT", StringComparison.OrdinalIgnoreCase)) return false;
if (s.Contains("SQLite format", StringComparison.Ordinal)) return false;
if (s.Contains("&&", StringComparison.Ordinal) || s.Contains("||", StringComparison.Ordinal)) return true;
if (s.Contains("==", StringComparison.Ordinal) && (
s.Contains("range", StringComparison.Ordinal)
|| s.Contains("species", StringComparison.Ordinal)
|| s.Contains("typeid", StringComparison.Ordinal)
|| s.Contains("name", StringComparison.Ordinal)
|| s.Contains("maxhp", StringComparison.Ordinal)
|| s.Contains("hasshield", StringComparison.Ordinal)
|| s.Contains("metastate", StringComparison.Ordinal)))
return true;
// e.g. range>5 && !foo
if (Regex.IsMatch(s, @"(?i)range\s*[<>=!]+")) return true;
return false;
}
}

View file

@ -0,0 +1,189 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace RynthCore.MonsterEditor;
// In-game VirindiTank import uses the same MyMonsters layout in Plugins/RynthCore.Plugin.RynthAi/ProfileImport/VirindiTankUsdMyMonstersScfParser.cs — keep in sync.
/// <summary>
/// Line-oriented uTank2 SCF <c>.usd</c> (e.g. format 8) — the common format under
/// <c>C:\Games\VirindiPlugins\VirindiTank\*.usd</c>, with a <c>MyMonsters</c> table using <c>s</c>/<c>i</c>/<c>b</c> value lines.
/// Reference: <c>--Silentkelpie_InfiniteLeaftide.usd</c> (MyMonsters 21 columns, 110+ rows in sample file).
/// </summary>
public static class VirindiTankUsdTextScfParser
{
public static bool TryParseMyMonsters(string allText, List<MonsterRule> outList, out string? note)
{
outList.Clear();
note = null;
if (string.IsNullOrWhiteSpace(allText) || allText.IndexOf("MyMonsters", StringComparison.Ordinal) < 0)
return false;
string[] L = allText
.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None)
.Select(s => s.Trim())
.ToArray();
if (L.Length < 8) { note = "File too short."; return false; }
int idx = 0;
for (; idx < L.Length; idx++) if (L[idx] == "MyMonsters") break;
if (idx >= L.Length) { note = "MyMonsters not found."; return false; }
idx++;
if (!int.TryParse(L[idx], out int colCount) || colCount < 1) { note = "MyMonsters: bad column count."; return false; }
idx += 1 + colCount * 2; // names + y/n
if (idx >= L.Length) { note = "MyMonsters: truncated after header."; return false; }
if (!int.TryParse(L[idx], out int rowCount) || rowCount < 0) { note = "MyMonsters: bad row count."; return false; }
idx++;
// Empty table: treat as "no data" so the importer can fall back to SQLite / byte scan.
if (rowCount == 0) { note = "MyMonsters has no rows."; return false; }
if (colCount < 4 + 3) { note = "MyMonsters: column count too small."; return false; }
int nBool = colCount - 4 - 3;
for (int r = 0; r < rowCount; r++)
{
if (idx + 1 >= L.Length) { note = $"No data for row {r + 1} (early EOF)."; return outList.Count > 0; }
if (!T(L, "s", ref idx)) { note = RowErr(r, "s"); return outList.Count > 0; }
if (!ValStr(L, ref idx, out string raw)) { note = RowErr(r, "name"); return outList.Count > 0; }
if (!T(L, "i", ref idx)) { note = RowErr(r, "i ap"); return outList.Count > 0; }
if (!ValInt(L, ref idx, out int ap, out int err) || err != 0) { note = RowErr(r, "ap int"); return outList.Count > 0; }
if (!T(L, "i", ref idx)) { note = RowErr(r, "i dt"); return outList.Count > 0; }
if (!ValInt(L, ref idx, out int vtDmg, out err) || err != 0) { note = RowErr(r, "dt int"); return outList.Count > 0; }
if (!T(L, "i", ref idx)) { note = RowErr(r, "i wep"); return outList.Count > 0; }
if (!ValInt(L, ref idx, out int wep, out err) || err != 0) { note = RowErr(r, "wep int"); return outList.Count > 0; }
if (nBool < 14) { note = "Expected at least 14 bool columns in mob row."; return outList.Count > 0; }
if (nBool < 1) { note = "nBool<1."; return false; }
var b = new bool[nBool];
for (int k = 0; k < nBool; k++)
{
if (!T(L, "b", ref idx) || !ValBool(L, ref idx, out b[k])) { note = RowErr(r, $"b{k}"); return outList.Count > 0; }
}
if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int sev, out err) || err != 0) { note = RowErr(r, "sec vuln int"); return outList.Count > 0; }
if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int ofh, out err) || err != 0) { note = RowErr(r, "offh int"); return outList.Count > 0; }
if (!T(L, "i", ref idx) || !ValInt(L, ref idx, out int pet, out err) || err != 0) { note = RowErr(r, "pet int"); return outList.Count > 0; }
outList.Add(MakeRule(raw, ap, vtDmg, wep, b, sev, ofh, pet));
}
if (outList.Count == 0) { note = "No rows were parsed from MyMonsters."; return false; }
return true;
}
private static string RowErr(int r, string what) => $"MyMonsters row {r + 1} ({what}).";
private static bool T(string[] L, string t, ref int i)
{
if (i >= L.Length || L[i] != t) return false;
i++;
return true;
}
private static bool ValStr(string[] L, ref int i, out string s)
{
s = "";
if (i >= L.Length) return false;
s = L[i++]; return true;
}
private static bool ValInt(string[] L, ref int i, out int v, out int err)
{
err = 0;
v = 0;
if (i >= L.Length) { err = 1; return false; }
if (!int.TryParse(L[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out v) &&
!int.TryParse(L[i], out v))
{
err = 1; return false;
}
i++;
return true;
}
private static bool ValBool(string[] L, ref int i, out bool b)
{
b = false;
if (i >= L.Length) return false;
string t = L[i++];
if (string.Equals(t, "True", StringComparison.OrdinalIgnoreCase)) { b = true; return true; }
if (string.Equals(t, "False", StringComparison.OrdinalIgnoreCase)) { b = false; return true; }
return false;
}
/// b[0] Imperil, [1] Vuln, [2] Yield, [3] GravityW, [4] Attack, [5] Ring, [6] Broad, [7] Fester, [8..12] WC/FC/Cp/DC/Cs, [13] Streak.
private static MonsterRule MakeRule(
string raw, int ap, int vtDmg, int wep, bool[] b, int sev, int ofh, int pet)
{
string n = Nm(raw);
if (b.Length < 14) b = Pad(b, 14);
bool i = b[0], v = b[1], y = b[2], gW = b[3];
bool useBolt = b[4], useRing = b[5], broad = b[6], fest = b[7];
bool strk = b[13];
return new MonsterRule
{
Name = n,
Priority = ap,
DamageType = MapDmg(vtDmg),
WeaponId = WepId(wep),
Imperil = i,
Vuln = v,
Yield = y,
GravityWell = gW,
UseBolt = useBolt,
UseRing = useRing,
Broadside = broad,
Fester = fest,
UseStreak = strk,
// VT extra curses (b[8]..b[12]) — no Rynth match
ExVuln = "None", // sev = spell/element code; Rynth list is by name; leave None; user can tune
OffhandId = WepId(ofh),
PetDamage = MapPet(pet, sev),
};
}
private static bool[] Pad(bool[] b, int min)
{
if (b.Length >= min) return b;
var r = new bool[min];
for (int i = 0; i < b.Length; i++) r[i] = b[i];
return r;
}
private static string Nm(string s)
{
s = s.Trim();
if (s.Length > 1 && s[0] == '<' && s[^1] == '>')
{
string t = s.Substring(1, s.Length - 2);
if (t.Equals("DEFAULT", StringComparison.OrdinalIgnoreCase)) return "Default";
return t;
}
return s;
}
private static int WepId(int w) => w; // Rynth keeps AC-style ids (often large negatives); editor shows &lt;ID:…&gt; if not in list
/// <summary>uTank2 damage int — 8 and negatives typically mean "Auto" in exports.</summary>
private static string MapDmg(int c) => c switch
{
8 => "Auto",
1 => "Slash", 2 => "Pierce", 3 => "Bludgeon", 4 => "Acid", 5 => "Fire", 6 => "Cold", 7 => "Lightning", 0 => "Nether",
_ => "Auto",
};
private static string MapPet(int pdt, int _ /* secondary vuln int from VT; ExVuln string not derived */)
{
if (pdt is 0 or 101) return "PAuto";
if (pdt is >= 1 and <= 8)
{
// Narrowed 1..8: pet damage type codes in VT SCF.
return pdt switch
{
1 => "Slash", 2 => "Pierce", 3 => "Bludgeon", 4 => "Fire", 5 => "Cold", 6 => "Lightning", 7 => "Acid", 8 => "Nether",
_ => "PAuto",
};
}
return "PAuto";
}
}

View file

@ -28,6 +28,8 @@ internal static class LootSalvageTests
private const uint ItemBase = 0x80000B00;
private const uint UstWcid = 20646;
private const uint ItemTypeJewelry = 0x8, ItemTypeGem = 0x800, ItemTypeContainer = 0x200, ItemTypeArmor = 0x2;
private static readonly string TestLogDirectory =
System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthAiHostTests", "Diagnostics");
public static void Register(Runner r)
{
@ -143,6 +145,10 @@ internal static class LootSalvageTests
}
beforeCreate?.Invoke();
Host = FakeHost.Create(Player);
// SalvageManager logs through RynthLog (LogCat.Salvage), which forwards to the host it
// is bound to; bind it to this fake so FakeHost.Logs sees the [Salvage] lines. A temp
// folder keeps the test's diagnostics.json and log files out of the real install.
RynthLog.Init(Host, TestLogDirectory);
Cache = FakeHost.MakeCache(Host, Player, ids);
Settings.EnableCombineSalvage = false; // bag merging has its own tests in game
Settings.SalvageOpenDelayFirstMs = 400; Settings.SalvageOpenDelayFastMs = 50;

View file

@ -25,6 +25,7 @@ internal static class CreatureWeaknessTests
r.Add("weakness: server table ranks most damage first", ServerTable);
r.Add("weakness: type keyword is a whole word", TypeKeyword);
r.Add("weakness: learned element goes first, then the type order", LearnedFirst);
r.Add("weakness: UB seed ranks after server data and learned, before the type", SeedBeforeType);
}
private static void Normalize()
@ -130,4 +131,34 @@ internal static class CreatureWeaknessTests
Check.Eq(alone?.Order.Count, 1, "only the learned element");
Check.Eq(alone?.Describe(), "Fire", "describe without a multiplier");
}
private static void SeedBeforeType()
{
var type = CreatureWeakness.Rank(0, OlthoiByKeyword, 0, null);
var r = CreatureWeakness.Rank(0, OlthoiByKeyword, 0, null, new[] { "Electric", "fire", "Holy", "Fire" });
Check.NotNull(r, "ranking with a seed");
if (r == null || type == null) return;
Check.Eq(r.Source, "UB seed, then Olthoi type", "source");
Check.Eq(r.Order[0].Element, "Lightning", "seed order first (normalised)");
Check.Eq(r.Order[1].Element, "Fire", "second seed element");
Check.True(double.IsNaN(r.Order[1].Mult), "seed elements have no multiplier");
Check.Eq(r.Order.Count, 8, "unknown names dropped, no element listed twice");
var rest = new List<string>();
foreach (var (e, _) in type.Order) if (e != "Lightning" && e != "Fire") rest.Add(e);
for (int i = 0; i < rest.Count; i++)
Check.Eq(r.Order[i + 2].Element, rest[i], $"then the type order at {i + 2}");
var learned = CreatureWeakness.Rank(0, OlthoiByKeyword, 0, "Cold", new[] { "Fire" });
Check.Eq(learned?.Source, "learned, then Olthoi type", "learned element beats the seed");
Check.Eq(learned?.Order[0].Element, "Cold", "learned element first");
var row = FirstServerRow();
if (row is { } sr)
Check.Eq(CreatureWeakness.Rank(sr.Wcid, sr.Name, 0, null, new[] { "Nether" })?.Source, "server data", "server table beats the seed");
var alone = CreatureWeakness.Rank(0, Unknown, 0, null, new[] { "Acid" });
Check.Eq(alone?.Source, "UB seed", "seed with no type");
Check.Eq(alone?.Order.Count, 1, "only the seed element");
Check.True(CreatureWeakness.Rank(0, Unknown, 0, null, new[] { "Holy" }) == null, "a seed with no element is ignored");
}
}