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;
///
/// /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 <name> on|off show/hide one field (ratings, slayer, spells, …)
/// /ra iteminfo rating <tag> 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).
///
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)
/// Character settings when loaded, else null (commands then use defaults / refuse edits).
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 on|off|rating 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";
/// "/ra iteminfo fields" — current state of every field and rating.
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());
}
/// /ra iteminfo and the window's "Print to chat" button.
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);
}
/// On-select class filters from the Item Info window.
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,
};
///
/// Describe now if its appraisal is cached, otherwise (optionally)
/// request an ID and print from once it lands or times out.
///
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);
ItemInfoLog($"0x{uid:X8}: waiting for ID data (requested={requestId && Host.HasRequestId})");
_itemInfoPendingId = itemId;
_itemInfoPendingSince = Environment.TickCount64;
}
/// One "[ItemInfo]" line in the engine log and the daily RynthAi file per trigger decision.
private static void ItemInfoLog(string message) => RynthLog.Write(LogCat.UI, "[ItemInfo] " + message);
///
/// Select / click triggers: unless the same item was queued
/// automatically within (one click can raise both triggers).
///
internal void QueueAutoItemInfo(int itemId, bool requestId)
{
long now = Environment.TickCount64;
if (itemId == _itemInfoLastAutoId && now - _itemInfoLastAutoAt < AutoDedupeMs)
{
ItemInfoLog($"0x{(uint)itemId:X8}: already queued by the other trigger");
return;
}
_itemInfoLastAutoId = itemId;
_itemInfoLastAutoAt = now;
QueueItemInfo(itemId, requestId);
}
///
/// 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
/// .
///
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;
}
/// Tick-thread half of the click trigger: describe whatever item the click selected.
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;
string button = MagItemInfoCatalog.ClickTriggers[s.ClickTrigger];
uint selected = Host.GetSelectedItemId();
if (selected == 0) { ItemInfoLog($"{button}: nothing selected"); return; }
int id = unchecked((int)selected);
WorldObject? obj = _objectCache?[id];
if (obj == null) { ItemInfoLog($"{button}: 0x{selected:X8} not in the object cache"); return; }
if (!IsLootableClass(obj.ObjectClass) || !ItemInfoWantsClass(s, obj.ObjectClass))
{
ItemInfoLog($"{button}: '{obj.Name}' ({obj.ObjectClass}) skipped by the class filters");
return;
}
ItemInfoLog($"{button}: 0x{selected:X8} '{obj.Name}': click queue");
QueueAutoItemInfo(id, requestId: true);
}
/// Plugin-tick poll for a pending describe (no appraisal-arrived event in the SDK).
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);
}
///
/// Builds the output lines (no prefix / indent) in the configured layout, or returns null
/// with set. The one-line layout returns a single line.
///
private List? 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 { 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;
}
}
///
/// Chat output. Pet-style: line 1 carries the prefix in ,
/// later lines are indented like the pet roster and use .
///
private void PrintItemInfo(int itemId, bool identified)
{
List? lines = BuildItemInfoLines(itemId, out string? error);
if (lines == null || lines.Count == 0)
{
ItemInfoLog($"0x{(uint)itemId:X8}: not printed: {error}");
ChatLine("[RynthAi] " + error);
return;
}
if (!identified) lines[0] += " (not identified — stats may be incomplete)";
ItemInfoLog($"0x{(uint)itemId:X8}: printed {lines.Count} line(s), identified={identified}: {lines[0]}");
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);
}
/// Item Info window preview: the selected item's lines, or null when nothing is selected.
private string? DescribeSelectedItemForPreview()
{
if (!Host.HasGetSelectedItemId) return null;
uint selected = Host.GetSelectedItemId();
if (selected == 0) return null;
int id = unchecked((int)selected);
List? 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);
}
/// Item Info window "Test" button: sample line in the chosen chat type.
private void TestItemInfoChatType(int chatType)
{
string prefix = ItemInfoSettings?.Prefix ?? "[RynthAi] ";
Host.WriteToChat($"{prefix}Item info chat test (type {chatType})", chatType);
}
}