// SkillsReader.cs - Reads the character for the Skills panel and spends XP for it, on the plugin tick.
//
// Reading: while the panel is drawn it asks for a read about four times a second (RequestRead, render
// thread); the tick then reads the engine's training numbers (GetTrainingInfo, v79: the engine refreshes
// them every 2 s while asked, and at once after a raise) and the header's properties, and publishes one
// SkillsSheet. Nothing is read while the panel is closed.
//
// Spending: the panel's raise arrow and "+10" queue a Raise (or a train, for an untrained skill) with the
// cost the player saw; the engine refuses it when the cost changed meanwhile (RaiseResult.CostChanged),
// so a click never spends more than the footer said. Like retail's arrow there is no confirm.
using System;
using System.Threading;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDreamWeave;
internal sealed class SkillsReader
{
private const uint IntGender = 113, IntHeritage = 188, IntPkStatus = 134, IntAllegianceRank = 30, IntCharacterTitleId = 261;
private const uint QuadAvailableLuminance = 6, QuadMaximumLuminance = 7;
private const long ReadEveryMs = 250;
private readonly TrainingEntryNative[] _entries = new TrainingEntryNative[128];
private SkillsSheet _sheet = SkillsSheet.Empty;
private long _lastAsk;
private int _readQueued;
private string _message = "";
/// The newest snapshot (any thread).
public SkillsSheet Sheet => Volatile.Read(ref _sheet);
/// The last raise's refusal, for the footer ("" when none). Any thread.
public string Message => Volatile.Read(ref _message);
///
/// Render thread, each frame the panel draws: true when a read is due (the caller queues
/// for the tick). At most four a second, one in flight.
///
public bool ReadDue()
{
long now = Environment.TickCount64;
if (now - Volatile.Read(ref _lastAsk) < ReadEveryMs) return false;
if (Interlocked.Exchange(ref _readQueued, 1) == 1) return false;
Volatile.Write(ref _lastAsk, now);
return true;
}
/// Logout: forget the character.
public void Clear()
{
Volatile.Write(ref _sheet, SkillsSheet.Empty);
Volatile.Write(ref _message, "");
}
/// Plugin tick: reads the numbers and publishes a new sheet when they are in.
public void Read(RynthCoreHost host)
{
try
{
if (!host.HasTraining) { Volatile.Write(ref _message, "This RynthCore is too old for the Skills panel (needs plugin API v79)."); return; }
if (!host.TryGetTrainingInfo(out TrainingInfoNative info, _entries, out int count)) return;
var skills = new System.Collections.Generic.List(64);
var attrs = new AttributeLine?[AttributesPage.Rows.Length];
uint health = 0, stam = 0, mana = 0;
bool haveVitals = host.TryGetPlayerVitals(out health, out _, out stam, out _, out mana, out _);
for (int i = 0; i < Math.Min(count, _entries.Length); i++)
{
TrainingEntryNative e = _entries[i];
if (e.Kind is TrainingKind.Attribute or TrainingKind.Vital)
{
int kind = e.Kind == TrainingKind.Attribute ? 1 : 2;
int row = AttributesPage.RowIndex(kind, e.Stype);
if (row < 0) continue;
var r = AttributesPage.Rows[row];
int current = kind == 2 && haveVitals ? (int)(e.Stype switch { 1 => health, 3 => stam, _ => mana }) : -1;
attrs[row] = new AttributeLine(kind, e.Stype, r.Name, r.Icon, e.Base, e.Buffed, e.CostOne, e.CostTen,
e.Raisable, e.AtTop, e.Ranks, e.XpSpent, current);
continue;
}
if (e.Kind != TrainingKind.Skill || e.Class is < 1 or > 3) continue;
RetailSkill? table = RetailData.Skill(e.Stype);
if (table == null) continue; // a skill the retail table doesn't list (retired): retail doesn't show it either
bool usable = (e.Flags & TrainingEntryFlags.UsableUntrained) != 0 || e.Class >= 2 || table.UsableUntrained;
skills.Add(new SkillLine(e.Stype, table.Name, table.Icon, (SkillClass)e.Class, usable,
e.Base, e.Buffed, e.CostOne, e.CostTen, e.TrainCredits, e.Raisable, e.Trainable, e.AtTop,
e.Ranks, e.XpSpent));
}
uint me = host.GetPlayerId();
string name = me != 0 && host.HasGetObjectName && host.TryGetObjectName(me, out string n) ? n : "";
int gender = Int(host, me, IntGender), heritage = Int(host, me, IntHeritage), pk = Int(host, me, IntPkStatus);
// Retail's header: the allegiance rank's title before the name ("Yeoman Drakkon"), and the
// character title chosen in the Titles tab ("Obviously Bored") after sex and heritage.
name = SkillsLayout.NameLine(name, gender, heritage, Int(host, me, IntAllegianceRank));
int titleId = Int(host, me, IntCharacterTitleId);
string title = SkillsLayout.Title(titleId);
long? lumMax = Quad(host, me, QuadMaximumLuminance);
long? lumAvail = Quad(host, me, QuadAvailableLuminance);
TitleList titles = TitlesFor(me).WithDisplayed((uint)Math.Max(0, titleId));
var attrList = new System.Collections.Generic.List(attrs.Length);
foreach (AttributeLine? a in attrs) if (a != null) attrList.Add(a);
var sheet = new SkillsSheet(name, SkillsLayout.Identity(gender, heritage, title), SkillsLayout.PkStatus(pk),
info.Level, info.TotalXp, info.UnassignedXp, info.SkillCredits,
lumMax is > 0 ? lumAvail ?? 0 : null, lumMax is > 0 ? lumMax : null,
skills, info.Busy, info.SnapshotVersion, attrList, titles);
Volatile.Write(ref _sheet, sheet);
}
finally
{
Volatile.Write(ref _readQueued, 0);
}
}
///
/// Plugin tick: the raise arrow ( false: one rank, or train an untrained skill
/// with credits) or "+10", at the cost the footer showed. The answer comes back in the numbers;
/// a refusal is said in the footer and chat.
///
public void Raise(RynthCoreHost host, SkillLine skill, bool ten, Action chat)
{
RaiseResult r;
if (skill.Class < SkillClass.Trained)
r = host.TrainSkill(skill.Id, skill.TrainCredits);
else
r = host.Raise(TrainingKind.Skill, skill.Id, ten ? 10u : 1u, ten ? skill.CostTen : skill.CostOne, out _);
string why = r switch
{
RaiseResult.Sent => "",
RaiseResult.CostChanged or RaiseResult.Stale or RaiseResult.NotReady or RaiseResult.Busy
=> "The numbers changed; look again and press once more.",
RaiseResult.NotEnough => skill.Class < SkillClass.Trained ? "Not enough skill credits." : "Not enough unassigned experience.",
RaiseResult.NotRaisable => $"{skill.Name} can't be raised any further.",
RaiseResult.Unavailable => "This client can't raise skills from a plugin.",
RaiseResult.EngineTooOld => "This RynthCore is too old to raise skills (needs plugin API v79).",
_ => $"{skill.Name} wasn't raised ({r}).",
};
Volatile.Write(ref _message, why);
Volatile.Write(ref _lastAsk, 0); // read again at once
if (why.Length > 0) chat(why);
}
// ── Titles (the server's list, kept per character: AttributesTitles.cs) ──
private readonly object _titlesGate = new();
private readonly System.Collections.Generic.Dictionary _titles = new();
private Func? _loadTitles;
private Action? _saveTitles;
/// Where the titles are kept between sessions (the plugin's settings, by character id).
public void SetTitleStore(Func load, Action save)
{
_loadTitles = load;
_saveTitles = save;
}
private TitleList TitlesFor(uint me)
{
if (me == 0) return TitleList.Empty;
lock (_titlesGate)
{
if (_titles.TryGetValue(me, out TitleList? t)) return t;
t = TitleList.Load(_loadTitles?.Invoke(me));
_titles[me] = t;
return t;
}
}
/// Pump thread: game event 0x0029 (the whole list, at login) or 0x002B (one title) for .
public void OnTitleEvent(uint me, uint eventType, ReadOnlySpan body)
{
if (me == 0) return;
TitleList next;
lock (_titlesGate)
{
TitleList now = _titles.TryGetValue(me, out TitleList? t) ? t : TitleList.Load(_loadTitles?.Invoke(me));
if (eventType == 0x0029) { if (!TitleList.TryParseTable(body, out next)) return; }
else next = now.WithUpdate(body);
_titles[me] = next;
}
_saveTitles?.Invoke(me, next.Save());
Volatile.Write(ref _lastAsk, 0); // show it at once
}
/// Plugin tick: show as the character's title (retail's "Set as Display Title").
public void SetDisplayTitle(RynthCoreHost host, uint titleId, Action chat)
{
if (titleId == 0) return;
if (!host.HasInvokeChatParser || !host.InvokeChatParser("/rc title " + titleId.ToString(System.Globalization.CultureInfo.InvariantCulture)))
chat("Couldn't set the title: this RynthCore can't send it (needs the engine from 2026-11-07).");
Volatile.Write(ref _lastAsk, 0);
}
///
/// Plugin tick: raises an attribute (Kind 1) or vital maximum (Kind 2) one or ten ranks at the cost the
/// footer showed, as the skills' arrows do.
///
public void Raise(RynthCoreHost host, AttributeLine a, bool ten, Action chat)
{
RaiseResult r = host.Raise(a.IsVital ? TrainingKind.Vital : TrainingKind.Attribute, a.Stype, ten ? 10u : 1u,
ten ? a.CostTen : a.CostOne, out _);
string why = r switch
{
RaiseResult.Sent => "",
RaiseResult.CostChanged or RaiseResult.Stale or RaiseResult.NotReady or RaiseResult.Busy
=> "The numbers changed; look again and press once more.",
RaiseResult.NotEnough => "Not enough unassigned experience.",
RaiseResult.NotRaisable => $"{a.Name} can't be raised any further.",
RaiseResult.Unavailable => "This client can't raise attributes from a plugin.",
RaiseResult.EngineTooOld => "This RynthCore is too old to raise attributes (needs plugin API v79).",
_ => $"{a.Name} wasn't raised ({r}).",
};
Volatile.Write(ref _message, why);
Volatile.Write(ref _lastAsk, 0);
if (why.Length > 0) chat(why);
}
private static int Int(RynthCoreHost host, uint id, uint stype)
=> id != 0 && host.HasGetObjectIntProperty && host.TryGetObjectIntProperty(id, stype, out int v) ? v : 0;
private static long? Quad(RynthCoreHost host, uint id, uint stype)
=> id != 0 && host.TryGetObjectQuadProperty(id, stype, out long v) ? v : null;
}