Snapshot for release 2026.10.28.3 (internal db7f094)

This commit is contained in:
Tom Bohar 2026-10-28 23:23:42 -04:00
commit e6642d0e10
102 changed files with 4821 additions and 782 deletions

View file

@ -0,0 +1,326 @@
// ============================================================================
// RynthDefective - Corpses/CorpseBook.cs
// Where a character's corpses are (Tom 2026-10-23: "a small panel somewhere
// that tells you where all your corpses are"). Pure: the plugin feeds it what
// it sees (RynthDefectivePlugin.Corpses.cs), tests feed it directly.
//
// What tells it:
// the death health 0: where the player stands is where the corpse lies
// (ACE puts it at the player's position).
// the server "Your corpse is located at (12.3N, 45.6E)." (ACE, outdoor deaths
// that dropped something) confirms it; "You have retained all your
// items. You do not need to recover your corpse!" means there is
// nothing to go back for, so that death is dropped. Either line
// may come before or after the health reaches 0.
// the corpse an object named "Corpse of <name>" in view: its id and exact
// place, matched to a death nearby or added as a corpse found.
// it's gone it left view (the server deletes it from the client) and
// VanishMeansGone says so: you had opened it (an emptied corpse
// rots 15 s later), or it was due to rot, or it went from right
// beside you. Otherwise it only left view (in a dungeon, around a
// corner: ACE drops what you can't see after about 25 s) and stays.
// not there you stand where it should be and it isn't (10 s, not in the
// first 2 minutes after the death, while the corpse appears).
//
// How long one lasts (ACE's Corpse.RecalculateDecayTime): a player's corpse rots
// after the player's level times 5 minutes, at least an hour; an emptied one 15
// seconds after. Other servers may differ, so the time is an estimate and a
// corpse is only dropped 10 minutes after it.
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthDefective.Corpses;
/// <summary>One corpse: where, when the character died (or the corpse was found), when it rots.</summary>
internal sealed class CorpseRecord
{
/// <summary>When the character died; MinValue for a corpse found in the world with no death seen.</summary>
public DateTime DiedUtc;
/// <summary>When it should rot (an estimate); MinValue when unknown.</summary>
public DateTime RotsUtc;
/// <summary>The landcell and the position in it; Cell 0 when only the server's map coordinates are known.</summary>
public uint Cell;
public float X, Y, Z;
/// <summary>The server's map coordinates (outdoor deaths); otherwise worked out from Cell.</summary>
public double Ns, Ew;
public bool ServerCoords;
/// <summary>The corpse object, once seen (0 before).</summary>
public uint ObjectId;
public DateTime SeenUtc;
/// <summary>When the player last opened it (not saved: only the minutes after matter).</summary>
public DateTime OpenedUtc;
/// <summary>Since when the player has stood at its place without it there (not saved).</summary>
public DateTime AbsentSinceUtc;
public bool Indoors => Cell != 0 && (Cell & 0xFFFF) >= 0x100;
public uint Landblock => Cell >> 16;
/// <summary>The map coordinates: the server's, else from the landcell (meaningless in a dungeon).</summary>
public bool TryCoords(out double ns, out double ew)
{
if (ServerCoords) { ns = Ns; ew = Ew; return true; }
return CorpseBook.MapCoords(Cell, X, Y, out ns, out ew);
}
}
internal sealed class CorpseBook
{
public const int MaxCorpses = 20;
/// <summary>A death and the server's lines about it arrive within this of each other.</summary>
public static readonly TimeSpan DeathWindow = TimeSpan.FromMinutes(2);
/// <summary>A corpse is dropped this long after its estimated rot time.</summary>
public static readonly TimeSpan RotGrace = TimeSpan.FromMinutes(10);
/// <summary>A corpse with no rot estimate is dropped this long after it was last known.</summary>
public static readonly TimeSpan UnknownKeep = TimeSpan.FromHours(48);
private readonly List<CorpseRecord> _list = new();
private DateTime _nothingDroppedUtc = DateTime.MinValue;
public IReadOnlyList<CorpseRecord> Corpses => _list;
/// <summary>Bumped on every change (the plugin saves and redraws on it).</summary>
public int Revision { get; private set; }
public void Load(IEnumerable<CorpseRecord> records)
{
_list.Clear();
_list.AddRange(records);
Trim();
Revision++;
}
/// <summary>ACE's rot time for a player's corpse: level x 5 minutes, at least an hour (level 0: unknown).</summary>
public static DateTime RotTime(DateTime diedUtc, int level) =>
level <= 0 ? DateTime.MinValue : diedUtc + TimeSpan.FromSeconds(Math.Max(3600, level * 300));
/// <summary>
/// The character's health reached 0 at this place. The server's corpse line may already have come
/// (then this fills in the exact place), or "nothing to recover" (then there's no corpse to note).
/// </summary>
public void Died(DateTime now, uint cell, float x, float y, float z, int level)
{
if (now - _nothingDroppedUtc < DeathWindow) return;
CorpseRecord? recent = Recent(now);
if (recent != null && recent.Cell == 0)
{
recent.Cell = cell; recent.X = x; recent.Y = y; recent.Z = z;
Changed();
return;
}
Add(new CorpseRecord { DiedUtc = now, RotsUtc = RotTime(now, level), Cell = cell, X = x, Y = y, Z = z });
}
/// <summary>"Your corpse is located at (ns, ew)." The latest death, or a death the health didn't show.</summary>
public void ServerLine(DateTime now, double ns, double ew, int level)
{
CorpseRecord? recent = Recent(now);
if (recent != null)
{
recent.Ns = ns; recent.Ew = ew; recent.ServerCoords = true;
Changed();
return;
}
Add(new CorpseRecord { DiedUtc = now, RotsUtc = RotTime(now, level), Ns = ns, Ew = ew, ServerCoords = true });
}
/// <summary>"You do not need to recover your corpse": that death left nothing behind.</summary>
public void NothingDropped(DateTime now)
{
_nothingDroppedUtc = now;
CorpseRecord? recent = Recent(now);
if (recent != null && recent.ObjectId == 0)
{
_list.Remove(recent);
Changed();
}
}
/// <summary>
/// "Corpse of &lt;name&gt;" is in view: the corpse it is (by id, else the nearest death in the same
/// place), or one found. Returns the record.
/// </summary>
public CorpseRecord Seen(DateTime now, uint objectId, uint cell, float x, float y, float z)
{
CorpseRecord? hit = null;
foreach (CorpseRecord c in _list)
if (c.ObjectId == objectId) { hit = c; break; }
if (hit == null)
{
double best = double.MaxValue;
foreach (CorpseRecord c in _list)
{
if (c.ObjectId != 0) continue;
double d = Distance(c, cell, x, y, z);
if (d <= (c.Cell != 0 ? MatchDistance : MatchDistanceCoords) && d < best) { best = d; hit = c; }
}
}
if (hit == null)
{
hit = new CorpseRecord
{
DiedUtc = DateTime.MinValue, RotsUtc = DateTime.MinValue,
ObjectId = objectId, Cell = cell, X = x, Y = y, Z = z, SeenUtc = now,
};
Add(hit);
return hit;
}
bool moved = hit.ObjectId != objectId || hit.Cell != cell || MathF.Abs(hit.X - x) > 0.5f || MathF.Abs(hit.Y - y) > 0.5f;
hit.ObjectId = objectId;
hit.Cell = cell; hit.X = x; hit.Y = y; hit.Z = z;
hit.SeenUtc = now;
if (moved) Changed();
return hit;
}
/// <summary>The player opened a corpse (its contents came): if it's one of these, noted.</summary>
public void Opened(uint objectId, DateTime now)
{
foreach (CorpseRecord c in _list)
if (c.ObjectId == objectId) { c.OpenedUtc = now; return; }
}
/// <summary>Opened this recently, its vanishing is the looting (an emptied corpse rots 15 s later).</summary>
public static readonly TimeSpan LootedWindow = TimeSpan.FromMinutes(15);
/// <summary>Vanishing this close to the player can't be leaving view.</summary>
public const double BesideYou = 10.0;
/// <summary>
/// The corpse left view while the player was <paramref name="distance"/> metres off: gone for good
/// (looted, rotted), or only out of sight? Pure.
/// </summary>
public static bool VanishMeansGone(CorpseRecord c, double distance, DateTime now)
{
if (c.OpenedUtc != DateTime.MinValue && now - c.OpenedUtc < LootedWindow) return true;
if (c.RotsUtc != DateTime.MinValue && now >= c.RotsUtc - TimeSpan.FromMinutes(5)) return true;
return distance <= BesideYou;
}
/// <summary>Standing at its place without it there this long: it's gone.</summary>
public static readonly TimeSpan AbsentFor = TimeSpan.FromSeconds(10);
/// <summary>
/// The player is <paramref name="distance"/> metres from it and it is (or isn't) in view: true when
/// it has been missing from its place long enough to drop. Not in the first <see cref="DeathWindow"/>
/// after the death (the corpse appears a moment after it). Pure but for the record's timer.
/// </summary>
public static bool NotThere(CorpseRecord c, double distance, bool inView, DateTime now)
{
if (inView || distance > BesideYou || (c.DiedUtc != DateTime.MinValue && now - c.DiedUtc < DeathWindow))
{
c.AbsentSinceUtc = DateTime.MinValue;
return false;
}
if (c.AbsentSinceUtc == DateTime.MinValue) c.AbsentSinceUtc = now;
return now - c.AbsentSinceUtc >= AbsentFor;
}
/// <summary>The corpse object is gone for good (looted and rotted, or rotted).</summary>
public bool Gone(uint objectId)
{
int i = _list.FindIndex(c => c.ObjectId == objectId);
if (i < 0) return false;
_list.RemoveAt(i);
Changed();
return true;
}
public bool Forget(CorpseRecord record)
{
if (!_list.Remove(record)) return false;
Changed();
return true;
}
public void Clear()
{
if (_list.Count == 0) return;
_list.Clear();
Changed();
}
/// <summary>Drops the corpses that should have rotted by now. True when any went.</summary>
public bool Expire(DateTime now)
{
int n = _list.RemoveAll(c => Expired(c, now));
if (n > 0) Changed();
return n > 0;
}
public static bool Expired(CorpseRecord c, DateTime now)
{
if (c.RotsUtc != DateTime.MinValue) return now > c.RotsUtc + RotGrace;
DateTime known = c.DiedUtc > c.SeenUtc ? c.DiedUtc : c.SeenUtc;
return known != DateTime.MinValue && now > known + UnknownKeep;
}
/// <summary>
/// Within this (metres) a corpse seen is the death noted there: ACE drops it where the player
/// stood, so only a knockback in the dying moment separates them. With only the server's map
/// coordinates (rounded to a tenth, 24 m) the second, wider one.
/// </summary>
public const double MatchDistance = 15.0, MatchDistanceCoords = 25.0;
/// <summary>Metres between a corpse and a place; +inf when they can't be compared (another dungeon).</summary>
public static double Distance(CorpseRecord c, uint cell, float x, float y, float z)
{
if (c.Cell != 0)
{
bool aIn = c.Indoors, bIn = (cell & 0xFFFF) >= 0x100;
// Two dungeon places compare only in the same landblock (dungeons share no space).
if ((aIn || bIn) && c.Landblock != (cell >> 16)) return double.PositiveInfinity;
double dx = Global(c.Cell, c.X, true) - Global(cell, x, true);
double dy = Global(c.Cell, c.Y, false) - Global(cell, y, false);
double dz = c.Z - z;
return Math.Sqrt(dx * dx + dy * dy + dz * dz);
}
if (!c.ServerCoords || (cell & 0xFFFF) >= 0x100 || !MapCoords(cell, x, y, out double ns, out double ew))
return double.PositiveInfinity;
// Map coordinates: a tenth of a unit is 24 metres.
double dn = (c.Ns - ns) * 240.0, de = (c.Ew - ew) * 240.0;
return Math.Sqrt(dn * dn + de * de);
}
/// <summary>A landcell coordinate as a world one: 192 metres a landblock (the cell's high bytes).</summary>
public static double Global(uint cell, float local, bool x) =>
((x ? cell >> 24 : cell >> 16) & 0xFF) * 192.0 + local;
/// <summary>The map coordinates of a landcell position (the radar's formula: 0.1 = 24 metres).</summary>
public static bool MapCoords(uint cell, float x, float y, out double ns, out double ew)
{
ns = ew = 0;
if ((cell >> 16) == 0) return false;
ew = (((cell >> 24) & 0xFF) * 8.0 + x / 24.0 - 1019.5) / 10.0;
ns = (((cell >> 16) & 0xFF) * 8.0 + y / 24.0 - 1019.5) / 10.0;
return true;
}
/// <summary>The last death, if it was just now (the server's lines belong to it).</summary>
private CorpseRecord? Recent(DateTime now)
{
CorpseRecord? last = null;
foreach (CorpseRecord c in _list)
if (c.DiedUtc != DateTime.MinValue && now - c.DiedUtc < DeathWindow && (last == null || c.DiedUtc > last.DiedUtc))
last = c;
return last;
}
private void Add(CorpseRecord c)
{
_list.Add(c);
Trim();
Changed();
}
/// <summary>The newest first (by the death, or when a found one was first seen); at most <see cref="MaxCorpses"/>.</summary>
private void Trim()
{
_list.Sort((a, b) => When(b).CompareTo(When(a)));
if (_list.Count > MaxCorpses) _list.RemoveRange(MaxCorpses, _list.Count - MaxCorpses);
}
private static DateTime When(CorpseRecord c) => c.DiedUtc != DateTime.MinValue ? c.DiedUtc : c.SeenUtc;
private void Changed() => Revision++;
}

View file

@ -0,0 +1,35 @@
// ============================================================================
// RynthDefective - Corpses/CorpseLines.cs
// The server's two lines about a death's corpse (ACE, Creature_Death):
// "Your corpse is located at (12.3N, 45.6E)." outdoor deaths that dropped something
// "You have retained all your items. You do not need to recover your corpse!"
// Pure.
// ============================================================================
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthDefective.Corpses;
internal static class CorpseLines
{
private static readonly Regex Located = new(
@"Your corpse is located at \(\s*(\d+(?:\.\d+)?)\s*([NS])\s*,\s*(\d+(?:\.\d+)?)\s*([EW])\s*\)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
public static bool IsCorpseLine(string text) => Located.IsMatch(text) || IsNothingDropped(text);
public static bool IsNothingDropped(string text) =>
text.IndexOf("You do not need to recover your corpse", StringComparison.OrdinalIgnoreCase) >= 0;
public static bool TryLocated(string text, out double ns, out double ew)
{
ns = ew = 0;
Match m = Located.Match(text);
if (!m.Success) return false;
ns = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture) * (m.Groups[2].Value.Equals("S", StringComparison.OrdinalIgnoreCase) ? -1 : 1);
ew = double.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture) * (m.Groups[4].Value.Equals("W", StringComparison.OrdinalIgnoreCase) ? -1 : 1);
return true;
}
}

View file

@ -0,0 +1,173 @@
// ============================================================================
// RynthDefective - Corpses/CorpseRows.cs
// The Corpses window's rows, built on the plugin tick from the book, the other
// characters' files and where the player stands. Pure (tests build rows).
//
// A row: the place (the dungeon's name, or the map coordinates outdoors), then
// how long ago, the rot estimate and, when the player can be measured against
// it (outdoors, or in the same dungeon), how far and which way, with an arrow
// from where the player faces.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Plugin.RynthDefective.Corpses;
internal sealed record CorpseRow(
string Place,
string Detail,
string Tip,
float Relative, // degrees from where the player faces (0 ahead, + to the right); NaN = no arrow
CorpseRecord? Record, // this character's corpse (click: select it; X: forget it); null for another character's
uint ObjectId);
internal sealed record CorpsesView(bool Ready, IReadOnlyList<CorpseRow> Mine, IReadOnlyList<CorpseRow> Others)
{
public static readonly CorpsesView NotReady = new(false, Array.Empty<CorpseRow>(), Array.Empty<CorpseRow>());
}
/// <summary>Where the player is, for distances and the arrow (Cell 0 = unknown).</summary>
internal readonly record struct PlayerSpot(uint Cell, float X, float Y, float Z, double FacingDeg);
internal static class CorpseRows
{
/// <summary>Beyond this (metres) a corpse gets no distance: the map coordinates say it better.</summary>
public const double MaxShownDistance = 5000;
public static CorpsesView Build(IReadOnlyList<CorpseRecord> mine, IReadOnlyList<OtherCorpses> others, PlayerSpot me, DateTime now)
{
var rows = new List<CorpseRow>(mine.Count);
foreach (CorpseRecord c in mine)
{
float rel = float.NaN;
var detail = new List<string>(3) { Age(c, now) };
string rot = Rot(c, now);
if (rot.Length > 0) detail.Add(rot);
if (Offset(c, me, out double dist, out double bearing))
{
detail.Add(Distance(dist) + " " + Compass(bearing));
if (dist >= 1.0)
{
double r = bearing - me.FacingDeg;
while (r > 180) r -= 360;
while (r < -180) r += 360;
rel = (float)r;
}
}
rows.Add(new CorpseRow(Place(c), string.Join(" · ", detail), Tip(c, null, now), rel, c, c.ObjectId));
}
var other = new List<CorpseRow>();
foreach (OtherCorpses o in others)
foreach (CorpseRecord c in o.Corpses)
{
string rot = Rot(c, now);
string detail = o.Character + " · " + Age(c, now) + (rot.Length > 0 ? " · " + rot : "");
other.Add(new CorpseRow(Place(c), detail, Tip(c, o, now), float.NaN, null, 0));
}
return new CorpsesView(true, rows, other);
}
/// <summary>"Matron Hive East", "41.2N, 33.6E", "41.2N, 33.6E (indoors)", "Dungeon 6146".</summary>
public static string Place(CorpseRecord c)
{
if (c.Indoors)
{
PlaceNames.Dungeon? d = PlaceNames.DungeonAt(c.Landblock);
if (d != null) return d.Name;
if (PlaceNames.IsMapLandblock(c.Landblock) && c.TryCoords(out double bns, out double bew)) return Coords(bns, bew) + " (indoors)";
return "Dungeon " + c.Landblock.ToString("X4", CultureInfo.InvariantCulture);
}
return c.TryCoords(out double ns, out double ew) ? Coords(ns, ew) : "Somewhere";
}
public static string Coords(double ns, double ew) =>
Math.Abs(ns).ToString("0.0", CultureInfo.InvariantCulture) + (ns >= 0 ? "N" : "S") + ", "
+ Math.Abs(ew).ToString("0.0", CultureInfo.InvariantCulture) + (ew >= 0 ? "E" : "W");
/// <summary>"died 25m ago", "found 3m ago" (a corpse seen with no death seen).</summary>
public static string Age(CorpseRecord c, DateTime now) =>
c.DiedUtc != DateTime.MinValue ? "died " + Span(now - c.DiedUtc) + " ago"
: c.SeenUtc != DateTime.MinValue ? "seen " + Span(now - c.SeenUtc) + " ago" : "";
/// <summary>"rots in ~2h 5m", "may have rotted", or "" when unknown.</summary>
public static string Rot(CorpseRecord c, DateTime now)
{
if (c.RotsUtc == DateTime.MinValue) return "";
TimeSpan left = c.RotsUtc - now;
return left > TimeSpan.Zero ? "rots in ~" + Span(left) : "may have rotted";
}
/// <summary>"40s", "25m", "3h 10m", "2d 4h".</summary>
public static string Span(TimeSpan t)
{
if (t < TimeSpan.Zero) t = TimeSpan.Zero;
if (t.TotalMinutes < 1) return ((int)t.TotalSeconds).ToString(CultureInfo.InvariantCulture) + "s";
if (t.TotalHours < 1) return ((int)t.TotalMinutes).ToString(CultureInfo.InvariantCulture) + "m";
if (t.TotalDays < 1) return ((int)t.TotalHours).ToString(CultureInfo.InvariantCulture) + "h " + t.Minutes.ToString(CultureInfo.InvariantCulture) + "m";
return ((int)t.TotalDays).ToString(CultureInfo.InvariantCulture) + "d " + t.Hours.ToString(CultureInfo.InvariantCulture) + "h";
}
public static string Distance(double metres) =>
metres < 10 ? metres.ToString("0.0", CultureInfo.InvariantCulture) + " yd"
: metres.ToString("N0", CultureInfo.InvariantCulture) + " yd";
private static readonly string[] Points = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" };
public static string Compass(double bearing) => Points[(int)Math.Round(((bearing % 360) + 360) % 360 / 45.0) % 8];
/// <summary>How far and which way (degrees clockwise from north) the corpse is from the player, when they can be compared.</summary>
public static bool Offset(CorpseRecord c, PlayerSpot me, out double dist, out double bearing)
{
dist = bearing = 0;
if (me.Cell == 0) return false;
double dx, dy, dz = 0;
if (c.Cell != 0)
{
bool aIn = c.Indoors, bIn = (me.Cell & 0xFFFF) >= 0x100;
if ((aIn || bIn) && c.Landblock != (me.Cell >> 16)) return false;
dx = CorpseBook.Global(c.Cell, c.X, true) - CorpseBook.Global(me.Cell, me.X, true);
dy = CorpseBook.Global(c.Cell, c.Y, false) - CorpseBook.Global(me.Cell, me.Y, false);
dz = c.Z - me.Z;
}
else
{
if (!c.ServerCoords || (me.Cell & 0xFFFF) >= 0x100 || !CorpseBook.MapCoords(me.Cell, me.X, me.Y, out double ns, out double ew))
return false;
dx = (c.Ew - ew) * 240.0;
dy = (c.Ns - ns) * 240.0;
}
dist = Math.Sqrt(dx * dx + dy * dy + dz * dz);
if (dist > MaxShownDistance) return false;
bearing = Math.Atan2(dx, dy) * 180.0 / Math.PI;
if (bearing < 0) bearing += 360.0;
return true;
}
private static string Tip(CorpseRecord c, OtherCorpses? owner, DateTime now)
{
var sb = new StringBuilder();
if (owner != null) sb.Append(owner.Character).Append(owner.Server.Length > 0 ? " on " + owner.Server : "").Append('\n');
if (c.DiedUtc != DateTime.MinValue)
sb.Append("Died ").Append(c.DiedUtc.ToLocalTime().ToString("MMM d, h:mm tt", CultureInfo.InvariantCulture))
.Append(" (").Append(Span(now - c.DiedUtc)).Append(" ago)").Append('\n');
else if (c.SeenUtc != DateTime.MinValue)
sb.Append("Found in the world (no death seen); last seen ").Append(Span(now - c.SeenUtc)).Append(" ago").Append('\n');
if (c.RotsUtc != DateTime.MinValue)
sb.Append(c.RotsUtc > now ? "Should rot in about " + Span(c.RotsUtc - now) : "Should have rotted by now")
.Append(" (level x 5 min, at least an hour; emptied, 15 s)").Append('\n');
PlaceNames.Dungeon? d = c.Indoors ? PlaceNames.DungeonAt(c.Landblock) : null;
sb.Append("Where: ").Append(Place(c));
if (c.Cell != 0)
sb.Append(" - landblock ").Append((c.Cell >> 16).ToString("X4", CultureInfo.InvariantCulture))
.Append(", cell ").Append((c.Cell & 0xFFFF).ToString("X4", CultureInfo.InvariantCulture))
.Append(" (").Append(c.X.ToString("0.0", CultureInfo.InvariantCulture)).Append(", ")
.Append(c.Y.ToString("0.0", CultureInfo.InvariantCulture)).Append(", ")
.Append(c.Z.ToString("0.0", CultureInfo.InvariantCulture)).Append(')');
if (d != null && d.HasEntrance) sb.Append("\nEntrance: ").Append(Coords(d.Ns, d.Ew));
if (owner == null)
sb.Append(c.ObjectId != 0 ? "\nClick: select it (when it's in view). X: forget it." : "\nX: forget it.");
return sb.ToString();
}
}

View file

@ -0,0 +1,165 @@
// ============================================================================
// RynthDefective - Corpses/CorpseStore.cs
// The corpses, one file per character: <SuiteDir>\RynthDefective\corpses\
// <server_character>.json. Each client writes only its own character's file
// and reads the others' (the window lists every character's corpses on this
// PC), so clients never write the same file. Written by hand and read with
// JsonDocument, as DefStore does; a broken file reads as no corpses.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.RynthDefective.Model;
namespace RynthCore.Plugin.RynthDefective.Corpses;
/// <summary>Another character's corpses, as its file has them.</summary>
internal sealed record OtherCorpses(string Server, string Character, IReadOnlyList<CorpseRecord> Corpses);
internal sealed class CorpseStore
{
public string Root;
public CorpseStore(string defectiveRoot) => Root = Path.Combine(defectiveRoot, "corpses");
public string PathFor(string server, string character) => Path.Combine(Root, DefStore.FileStem(server, character) + ".json");
public List<CorpseRecord> Load(string server, string character, out string? problem)
{
problem = null;
string path = PathFor(server, character);
if (!File.Exists(path)) return new List<CorpseRecord>();
try
{
return Parse(File.ReadAllBytes(path), out _, out _);
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException or InvalidOperationException or FormatException)
{
problem = $"{Path.GetFileName(path)}: {ex.Message}";
return new List<CorpseRecord>();
}
}
public string? Save(string server, string character, IReadOnlyList<CorpseRecord> corpses)
{
string path = PathFor(server, character);
try
{
Directory.CreateDirectory(Root);
string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
File.WriteAllText(tmp, ToJson(server, character, corpses), new UTF8Encoding(false));
File.Move(tmp, path, overwrite: true);
return null;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>Every other character's corpses that haven't rotted (files that can't be read are skipped).</summary>
public List<OtherCorpses> LoadOthers(string server, string character, DateTime now)
{
var result = new List<OtherCorpses>();
if (!Directory.Exists(Root)) return result;
string own = Path.GetFullPath(PathFor(server, character));
foreach (string path in Directory.EnumerateFiles(Root, "*.json"))
{
if (string.Equals(Path.GetFullPath(path), own, StringComparison.OrdinalIgnoreCase)) continue;
try
{
List<CorpseRecord> list = Parse(File.ReadAllBytes(path), out string sv, out string ch);
list.RemoveAll(c => CorpseBook.Expired(c, now));
if (list.Count > 0 && ch.Length > 0) result.Add(new OtherCorpses(sv, ch, list));
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException or InvalidOperationException or FormatException)
{
}
}
result.Sort((a, b) => string.Compare(a.Character, b.Character, StringComparison.OrdinalIgnoreCase));
return result;
}
internal static string ToJson(string server, string character, IReadOnlyList<CorpseRecord> corpses)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
w.WriteString("server", server);
w.WriteString("character", character);
w.WriteStartArray("corpses");
foreach (CorpseRecord c in corpses)
{
w.WriteStartObject();
if (c.DiedUtc != DateTime.MinValue) w.WriteString("died", c.DiedUtc.ToString("o", CultureInfo.InvariantCulture));
if (c.RotsUtc != DateTime.MinValue) w.WriteString("rots", c.RotsUtc.ToString("o", CultureInfo.InvariantCulture));
if (c.SeenUtc != DateTime.MinValue) w.WriteString("seen", c.SeenUtc.ToString("o", CultureInfo.InvariantCulture));
if (c.Cell != 0)
{
w.WriteString("cell", c.Cell.ToString("X8", CultureInfo.InvariantCulture));
w.WriteNumber("x", Math.Round(c.X, 2));
w.WriteNumber("y", Math.Round(c.Y, 2));
w.WriteNumber("z", Math.Round(c.Z, 2));
}
if (c.ServerCoords)
{
w.WriteNumber("ns", c.Ns);
w.WriteNumber("ew", c.Ew);
}
if (c.ObjectId != 0) w.WriteString("id", c.ObjectId.ToString("X8", CultureInfo.InvariantCulture));
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
internal static List<CorpseRecord> Parse(byte[] json, out string server, out string character)
{
using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) throw new JsonException("the file isn't a JSON object");
server = Str(root, "server");
character = Str(root, "character");
var list = new List<CorpseRecord>();
if (!root.TryGetProperty("corpses", out JsonElement arr) || arr.ValueKind != JsonValueKind.Array) return list;
foreach (JsonElement e in arr.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
var c = new CorpseRecord
{
DiedUtc = Time(e, "died"), RotsUtc = Time(e, "rots"), SeenUtc = Time(e, "seen"),
Cell = Hex(e, "cell"), X = (float)Num(e, "x"), Y = (float)Num(e, "y"), Z = (float)Num(e, "z"),
ObjectId = Hex(e, "id"),
};
if (e.TryGetProperty("ns", out JsonElement ns) && ns.ValueKind == JsonValueKind.Number
&& e.TryGetProperty("ew", out JsonElement ew) && ew.ValueKind == JsonValueKind.Number)
{
c.Ns = ns.GetDouble(); c.Ew = ew.GetDouble(); c.ServerCoords = true;
}
if (c.Cell == 0 && !c.ServerCoords) continue; // nowhere
list.Add(c);
}
return list;
}
private static string Str(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
private static double Num(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number ? v.GetDouble() : 0;
private static uint Hex(JsonElement e, string name) =>
uint.TryParse(Str(e, name), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint v) ? v : 0;
private static DateTime Time(JsonElement e, string name) =>
DateTime.TryParse(Str(e, name), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime t)
? t.ToUniversalTime() : DateTime.MinValue;
}

View file

@ -0,0 +1,200 @@
// ============================================================================
// RynthDefective - Corpses/CorpsesWindow.cs
// Where your corpses are (Tom 2026-10-23): this character's, newest first,
// then your other characters' on this PC. A small frameless window in the
// Selection window's look (RynthCore hosts it, plugin API v90).
//
// the title row drag to move; Ctrl+wheel: bigger or smaller (30-250%);
// right-click: hide it (/rdef corpses, the bar button).
// a row the place, then how long ago, when it rots and, near it,
// how far and which way (the arrow is from where you face).
// Click: select the corpse when it's in view; X: forget it.
//
// AC's render thread; reads the view the tick built (CorpsesView).
// ============================================================================
using System;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthDefective.ShortcutBar;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthDefective.Corpses;
internal sealed class CorpsesWindow
{
public const string Title = "Corpses";
private readonly RynthCoreHost _host;
private readonly Action<CorpseRow> _select, _forget;
private float _k = 1f, _r = 1f;
public CorpsesWindow(RynthCoreHost host, Action<CorpseRow> select, Action<CorpseRow> forget)
{
_host = host;
_select = select;
_forget = forget;
}
private float Px(float v) => v * _k;
private float Fs(ImFontPtr f) => f.FontSize * _r;
private void Scale()
{
float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
int pct = _host.PanelScale(Title);
_k = pct > 0 ? pct / 100f : fontK;
_r = _k / fontK;
}
private const float Pad = 6, HeadH = 18, RowH = 30, Radius = 4, Mark = 14, XW = 16;
private uint _bg, _key, _inset, _line, _text, _dim, _faint, _accent;
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
/// <summary>Draws the corpses into the host's window; returns the height it needs (pixels). Render thread.</summary>
public float Draw(CorpsesView v)
{
Scale();
_bg = Color(RynthUiColor.Background);
_key = Color(RynthUiColor.KeyFace);
_inset = Color(RynthUiColor.Inset);
_line = Color(RynthUiColor.Hairline);
_text = Color(RynthUiColor.Text);
_dim = Color(RynthUiColor.Muted);
_faint = Color(RynthUiColor.Faint);
_accent = Color(RynthUiColor.Accent);
Vector2 origin = ImGui.GetCursorScreenPos();
origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y));
float width = MathF.Floor(ImGui.GetContentRegionAvail().X);
if (width < 40) return Px(40);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
float pad = Px(Pad), rowH = Px(RowH), headH = Px(HeadH);
int empty = v.Mine.Count == 0 && v.Others.Count == 0 ? 1 : 0;
float height = MathF.Ceiling(pad + headH + (v.Mine.Count + empty) * rowH
+ (v.Others.Count > 0 ? headH + v.Others.Count * rowH : 0) + pad * 0.5f);
Vector2 max = origin + new Vector2(width, height);
dl.AddRectFilled(origin, max, A(_bg, 0.94f), Px(Radius));
dl.AddRect(origin, max, _line, Px(Radius));
// The title row: the drag surface.
float y = origin.Y + pad * 0.5f;
ImGui.SetCursorScreenPos(new Vector2(origin.X, origin.Y));
ImGui.InvisibleButton("##corpses_drag", new Vector2(width, headH + pad * 0.5f));
_host.PanelDragWithLastItem();
if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _host.SetPanelOpen(Title, RynthPanelOpen.Close);
SafeImGui.SetItemTooltip("Where your corpses are: this character's, then your other characters' on this PC.\n"
+ "Drag to move; Ctrl+wheel: bigger or smaller; right-click: hide (/rdef corpses).");
PanelButtonsWindow.DrawIcon(dl, RynthIcons.Skull, new Vector2(origin.X + pad, y), new Vector2(Px(Mark), headH), Px(12), _dim);
ImFontPtr hf = Font(RynthUiFont.NarrowBold11), sf = Font(RynthUiFont.Narrow9), nf = Font(RynthUiFont.Narrow10);
float tx = origin.X + pad + Px(Mark) + Px(4);
dl.AddText(hf, Fs(hf), new Vector2(tx, MathF.Round(y + (headH - Fs(hf)) * 0.5f)), _dim, "CORPSES");
if (v.Ready)
{
string count = v.Mine.Count.ToString(CultureInfo.InvariantCulture);
float cw = sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, count).X;
dl.AddText(sf, Fs(sf), new Vector2(origin.X + width - pad - cw, MathF.Round(y + (headH - Fs(sf)) * 0.5f)), _faint, count);
}
y += headH;
if (empty == 1)
{
dl.AddLine(new Vector2(origin.X + pad, y), new Vector2(origin.X + width - pad, y), _line);
string msg = v.Ready ? "No corpses. Where you die shows here." : "Corpses";
Clip(dl, sf, Fs(sf), new Vector2(origin.X + pad, MathF.Round(y + (rowH - Fs(sf)) * 0.5f)), _faint, msg, width - 2 * pad);
}
for (int i = 0; i < v.Mine.Count; i++)
{
Row(dl, v.Mine[i], i, new Vector2(origin.X, y), width, rowH, nf, sf, mine: true);
y += rowH;
}
if (v.Others.Count > 0)
{
dl.AddLine(new Vector2(origin.X + pad, y + 0.5f), new Vector2(origin.X + width - pad, y + 0.5f), _line);
dl.AddText(sf, Fs(sf), new Vector2(origin.X + pad, MathF.Round(y + (headH - Fs(sf)) * 0.5f)), _faint, "OTHER CHARACTERS");
y += headH;
for (int i = 0; i < v.Others.Count; i++)
{
Row(dl, v.Others[i], 1000 + i, new Vector2(origin.X, y), width, rowH, nf, sf, mine: false);
y += rowH;
}
}
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
return height;
}
private void Row(ImDrawListPtr dl, CorpseRow row, int n, Vector2 at, float width, float h, ImFontPtr nf, ImFontPtr sf, bool mine)
{
float pad = Px(Pad), xw = mine ? Px(XW) : 0f;
dl.AddLine(new Vector2(at.X + pad, at.Y + 0.5f), new Vector2(at.X + width - pad, at.Y + 0.5f), A(_line, 0.6f));
// The row: click selects the corpse (yours, while it's in view).
ImGui.SetCursorScreenPos(at);
bool click = ImGui.InvisibleButton(Id("##corpse", n), new Vector2(Math.Max(1, width - xw - pad), h));
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(row.Tip);
if (hot && mine) dl.AddRectFilled(at + new Vector2(1, 1), at + new Vector2(width - 1, h), A(_key, 0.55f), Px(3));
if (click && mine) _select(row);
// The arrow toward it, or a pin.
Vector2 mc = new(at.X + pad + Px(Mark) * 0.5f, at.Y + h * 0.5f);
if (!float.IsNaN(row.Relative)) Arrow(dl, mc, Px(Mark) * 0.42f, row.Relative, _accent);
else PanelButtonsWindow.DrawIcon(dl, RynthIcons.MapPin, new Vector2(at.X + pad, at.Y), new Vector2(Px(Mark), h), Px(12), mine ? _dim : _faint);
float tx = at.X + pad + Px(Mark) + Px(5), room = at.X + width - pad - xw - tx;
float top = MathF.Round(at.Y + (h - Fs(nf) - Fs(sf) - Px(1)) * 0.5f);
Clip(dl, nf, Fs(nf), new Vector2(tx, top), mine ? _text : _dim, row.Place, room);
Clip(dl, sf, Fs(sf), new Vector2(tx, top + Fs(nf) + Px(1)), mine ? _dim : _faint, row.Detail, room);
if (!mine) return;
// X: forget it (shown on the row's hover, always clickable).
Vector2 xp = new(at.X + width - pad - xw, at.Y + (h - xw) * 0.5f);
ImGui.SetCursorScreenPos(xp);
bool forget = ImGui.InvisibleButton(Id("##corpse_x", n), new Vector2(xw, xw));
bool xhot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip("Forget this corpse (it's recovered, or not worth going back for).");
if (hot || xhot) PanelButtonsWindow.DrawIcon(dl, RynthIcons.X, xp, new Vector2(xw, xw), Px(10), xhot ? _text : _faint);
if (forget) _forget(row);
}
// ImGui ids with a number, made once each: no strings built every frame.
private static readonly System.Collections.Generic.Dictionary<(string, int), string> Ids = new();
private static string Id(string prefix, int n)
{
if (!Ids.TryGetValue((prefix, n), out string? id)) Ids[(prefix, n)] = id = prefix + n;
return id;
}
/// <summary>Text cut with "..." to <paramref name="room"/> pixels.</summary>
private static void Clip(ImDrawListPtr dl, ImFontPtr f, float size, Vector2 pos, uint color, string text, float room)
{
if (text.Length == 0 || room <= 4) return;
float w = f.CalcTextSizeA(size, float.MaxValue, 0f, text).X;
if (w > room)
{
int n = text.Length;
while (n > 1 && f.CalcTextSizeA(size, float.MaxValue, 0f, text[..n] + "...").X > room) n--;
text = text[..n] + "...";
}
dl.AddText(f, size, new Vector2(MathF.Round(pos.X), MathF.Round(pos.Y)), color, text);
}
/// <summary>A small arrow pointing <paramref name="degrees"/> from straight up (where the player faces), clockwise.</summary>
private static void Arrow(ImDrawListPtr dl, Vector2 c, float r, float degrees, uint color)
{
float a = degrees * MathF.PI / 180f;
Vector2 Dir(float t) => new(MathF.Sin(t), -MathF.Cos(t));
Vector2 tip = c + Dir(a) * r;
Vector2 left = c + Dir(a + 2.45f) * r * 0.85f, rightP = c + Dir(a - 2.45f) * r * 0.85f;
dl.AddTriangleFilled(tip, left, rightP, color);
}
}

View file

@ -0,0 +1,84 @@
// ============================================================================
// RynthDefective - Corpses/PlaceNames.cs
// What the Corpses window needs from RynthNav's Atlas (<CoreDir>\NavData\
// locations.json, the file RynthCore's own readers and RynthNet's Characters
// window use): the dungeons' names and entrances by landblock, and the
// landblocks with a place on the surface map (their indoor cells are buildings
// in the overworld, not a dungeon). Read once, in the background, the first
// time it's asked; until then (or with no Atlas) a dungeon is named by its
// landblock number. Any thread.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
namespace RynthCore.Plugin.RynthDefective.Corpses;
internal static class PlaceNames
{
internal sealed record Dungeon(string Name, double Ns, double Ew, bool HasEntrance);
private sealed record Data(HashSet<uint> MapLandblocks, Dictionary<uint, Dungeon> Dungeons);
private static volatile Data _data = new(new HashSet<uint>(), new Dictionary<uint, Dungeon>());
private static int _started;
/// <summary>Starts the one background read (later calls do nothing).</summary>
public static void EnsureLoading()
{
if (System.Threading.Interlocked.Exchange(ref _started, 1) != 0) return;
string path = Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "NavData", "locations.json");
Task.Run(() =>
{
try { if (File.Exists(path)) _data = Parse(File.ReadAllText(path)); }
catch { }
});
}
/// <summary>A surface building's landblock (a cell's top 16 bits).</summary>
public static bool IsMapLandblock(uint landblock) => _data.MapLandblocks.Contains(landblock & 0xFFFF);
/// <summary>The dungeon in this landblock, or null when the Atlas doesn't name it.</summary>
public static Dungeon? DungeonAt(uint landblock) => _data.Dungeons.TryGetValue(landblock & 0xFFFF, out Dungeon? d) ? d : null;
/// <summary>For tests: the Atlas from text, at once.</summary>
internal static void LoadForTests(string json)
{
_data = Parse(json);
_started = 1;
}
/// <summary>The Atlas's surface landblocks and dungeons (RynthCore's RynthNavAtlas rules, as RynthNet reads them). Pure.</summary>
private static Data Parse(string json)
{
var lbs = new HashSet<uint>();
var dungeons = new Dictionary<uint, Dungeon>();
using JsonDocument doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("locations", out JsonElement arr) && arr.ValueKind == JsonValueKind.Array)
foreach (JsonElement e in arr.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
string cell = Str(e, "cell"), type = Str(e, "type"), name = Str(e, "name"), lb = Str(e, "lb");
bool onMap = TryNum(e, "ns", out double ns) & TryNum(e, "ew", out double ew);
if (onMap && cell.Length == 8 && uint.TryParse(cell.AsSpan(0, 4), NumberStyles.HexNumber, null, out uint l))
lbs.Add(l);
if (type == "Dungeon" && name.Length > 0 && uint.TryParse(lb, NumberStyles.HexNumber, null, out uint d))
dungeons.TryAdd(d, new Dungeon(name, ns, ew, onMap));
}
return new Data(lbs, dungeons);
}
private static string Str(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
private static bool TryNum(JsonElement e, string name, out double value)
{
bool ok = e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number;
value = ok ? v.GetDouble() : 0;
return ok;
}
}

View file

@ -2,7 +2,7 @@ using System;
namespace RynthCore.Plugin.RynthDefective.Model;
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell }
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell, Corpses }
/// <summary>A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).</summary>
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "");
@ -11,7 +11,7 @@ internal static class DefCommandParser
{
public const string Usage =
"/rdef [use <slot or item name> | set <slot> [item name] | spell <slot> <spell name> | clear <slot> | bind <slot> <key> | unbind <slot> | "
+ "weapons [search] | fav | slots <count> | list | status | settings | panels (the game panel buttons) | selection]";
+ "weapons [search] | fav | slots <count> | list | status | settings | panels (the game panel buttons) | selection | corpses [clear]]";
/// <summary>Parses the arguments after "/rdef" (blank = show or hide the bar).</summary>
public static DefCommand Parse(string? args)
@ -29,6 +29,7 @@ internal static class DefCommandParser
case "status": return new DefCommand(DefVerb.Status);
case "panels": case "panel": return new DefCommand(DefVerb.Panels);
case "settings": case "options": case "setup": return new DefCommand(DefVerb.Settings);
case "corpses": case "corpse": return new DefCommand(DefVerb.Corpses, Text: rest);
case "selection": case "target":
// "/rdef selection 0x80001234": select that object (a test hook for the Selection window).
return new DefCommand(DefVerb.Selection, Text: rest);

View file

@ -0,0 +1,55 @@
using System.Globalization;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>
/// The line /rdef answers with for the commands that used to say nothing (2026-10-28: every command
/// answers, Plugins/Shared/CommandReply.cs): a window shown or hidden, a use started, a test
/// selection. Pure, so RynthDefective.Tests checks every verb's line.
/// </summary>
internal static class DefReplies
{
/// <summary>A window after a show / hide / toggle: <paramref name="state"/> 1 shown, 0 hidden, -1 the engine can't say.</summary>
public static (bool Ok, string Text) Window(string title, int state) => state switch
{
1 => (true, CommandReply.Shown(title, true)),
0 => (true, CommandReply.Shown(title, false)),
_ => (false, $"This RynthCore has no {title} window (it needs plugin API v90)."),
};
/// <summary>A slot's use started (the result shows on the bar; a problem is said in chat).</summary>
public static string UseSlot(DefSlot slot, int number) => slot.IsSpell
? $"Casting {slot.SpellLabel} (slot {number})."
: $"Using {slot.Label} (slot {number}).";
/// <summary>"/rdef use &lt;name&gt;" started: the item is looked up when the use runs.</summary>
public static string UseName(string name) => $"Using {name.Trim()}.";
/// <summary>The weapon picker after /rdef weapons [search].</summary>
public static string Weapons(bool shown, string search) =>
!shown ? "Weapon picker hidden."
: search.Trim().Length > 0 ? $"Weapon picker shown, searching '{search.Trim()}'."
: "Weapon picker shown.";
/// <summary>
/// "/rdef selection &lt;0xId&gt;" (the Selection window's test hook): the object id (hex, "0x" optional),
/// or false with the usage in <paramref name="why"/>.
/// </summary>
public static bool TryParseSelection(string text, out uint id, out string why)
{
why = string.Empty;
string t = text.Trim();
if (uint.TryParse(t.Replace("0x", "", System.StringComparison.OrdinalIgnoreCase), NumberStyles.HexNumber, null, out id)) return true;
why = $"'{t}' isn't an object id. Usage: /rdef selection [0x80001234 | stack]";
return false;
}
/// <summary>"/rdef selection stack" with no stack in the pack.</summary>
public const string NoStack = "No stack in your pack to select.";
/// <summary>What a test selection did.</summary>
public static (bool Ok, string Text) Selected(uint id, bool selected, string? name) =>
selected ? (true, $"Selected 0x{id:X8}{(string.IsNullOrEmpty(name) ? "" : " (" + name + ")")}.")
: (false, $"The game didn't select 0x{id:X8}.");
}

View file

@ -45,6 +45,19 @@ public static unsafe class PluginExports
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) =>
Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
// The Corpses window (RynthDefectivePlugin.Corpses.cs): the server's corpse lines, corpses coming into view and leaving it.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnViewObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnViewObjectContents(uint objectId) => Runtime.OnViewObjectContents(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
@ -92,6 +105,7 @@ public static unsafe class PluginExports
if (name == RynthDefectivePlugin.BarSurface) result = plugin.RenderBar(popped, out wantH);
else if (name == RynthDefectivePlugin.PanelsSurface) result = plugin.RenderPanels(out wantH);
else if (name == RynthDefectivePlugin.SelectionSurface) result = plugin.RenderSelection(out wantH);
else if (name == RynthDefectivePlugin.CorpsesSurface) result = plugin.RenderCorpses(out wantH);
else return 0;
if (result != 1) return result;
if (wantWidth != null) *wantWidth = width;

View file

@ -41,6 +41,8 @@
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- How a chat command answers (2026-10-28): the shared reply queue and colours. -->
<Compile Include="..\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>
<ItemGroup>
<!-- Spell slots (2026-10-28): spell names and whom a spell is cast on, from RynthAi's spell table

View file

@ -64,7 +64,12 @@ public sealed partial class RynthDefectivePlugin : IBarActions
"\",\"icon\":\"\\u" + ((int)RynthIcons.Crosshair[0]).ToString("X4", CultureInfo.InvariantCulture) +
"\",\"width\":280,\"height\":46,\"minWidth\":120,\"minHeight\":24,\"bar\":false,\"edgeToEdge\":true," +
"\"chrome\":\"none\",\"fitHeight\":true,\"corner\":\"top\",\"scale\":\"draw\"}";
return "{\"version\":1,\"windows\":[" + bar + panels + selection + "]}";
// Where your corpses are (a bar button of its own).
string corpses = ",{\"id\":\"corpses\",\"title\":\"" + Corpses.CorpsesWindow.Title + "\",\"surface\":\"" + CorpsesSurface +
"\",\"icon\":\"\\u" + ((int)RynthIcons.Skull[0]).ToString("X4", CultureInfo.InvariantCulture) +
"\",\"width\":290,\"height\":80,\"minWidth\":140,\"minHeight\":30,\"bar\":true,\"edgeToEdge\":true," +
"\"chrome\":\"none\",\"fitHeight\":true,\"scale\":\"draw\"}";
return "{\"version\":1,\"windows\":[" + bar + panels + selection + corpses + "]}";
}
/// <summary>RynthPluginRenderEmbed "window:panels". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>

View file

@ -0,0 +1,313 @@
// ============================================================================
// RynthDefective - RynthDefectivePlugin.Corpses.cs
// The Corpses window (2026-10-23): where your corpses are (Corpses/CorpseBook.cs
// has the rules, Corpses/CorpsesWindow.cs draws it).
//
// Always on while logged in (a death has to be noted whether the window shows
// or not), and cheap: the health is read 10 times a second, the server's two
// corpse lines are picked out of the chat, and each object that comes into
// view is checked once for the name "Corpse of <you>". A corpse leaving view
// counts as gone (CorpseBook.VanishMeansGone) when you had opened it, it was due
// to rot, or it went from beside you, and not while portalling; otherwise you
// only walked away from it or lost sight of it.
//
// This character's corpses are saved in their own file, the other characters'
// read from theirs every 10 s while the window shows.
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Corpses;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective;
public sealed partial class RynthDefectivePlugin
{
internal const string CorpsesSurface = "window:corpses";
private const string CorpsePrefix = "Corpse of ";
private const uint LevelProperty = 25; // PropertyInt.Level
private readonly CorpseBook _corpseBook = new();
private CorpseStore? _corpseStore;
private CorpsesWindow? _corpsesWindow; // render thread
private volatile CorpsesView _corpsesView = CorpsesView.NotReady; // tick writes, render reads
private readonly ConcurrentQueue<uint> _createdIds = new(), _deletedIds = new(), _openedIds = new();
private readonly ConcurrentQueue<string> _corpseLines = new();
private readonly ConcurrentQueue<Action> _corpseActions = new();
private readonly List<(uint Id, long AtMs)> _corpsePending = new(); // seen, no position yet
private readonly List<(uint Id, long AtMs)> _corpseDeletes = new(); // left view: gone?
private List<OtherCorpses> _otherCorpses = new();
private bool _corpsesStarted, _deadSeen;
private string? _corpseAlias; // test hook: another name's corpses count as yours
private long _corpsesDrawnMs = long.MinValue / 2, _nextCorpseViewMs, _nextDeathCheckMs, _nextCorpseExpireMs, _nextOthersMs, _corpseSaveDueMs, _nextAbsentCheckMs;
private int _corpseRevisionSaved, _corpseRevisionShown = -1, _corpsesFailures;
/// <summary>RynthPluginRenderEmbed "window:corpses". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
internal int RenderCorpses(out float wantHeight)
{
wantHeight = 0;
if (!UsesShortcutBar) return 0;
System.Threading.Volatile.Write(ref _corpsesDrawnMs, Environment.TickCount64);
try
{
_corpsesWindow ??= new CorpsesWindow(Host,
row => _corpseActions.Enqueue(() => SelectCorpse(row)),
row => _corpseActions.Enqueue(() => { if (row.Record != null) _corpseBook.Forget(row.Record); }));
wantHeight = _corpsesWindow.Draw(_corpsesView);
_corpsesFailures = 0;
return 1;
}
catch (Exception ex)
{
Host.Log($"[RynthDefective] corpses draw failed: {ex.GetType().Name}: {ex.Message}");
return ++_corpsesFailures >= 3 ? -2 : 0;
}
}
public override void OnCreateObject(uint objectId)
{
if (_createdIds.Count < 4096) _createdIds.Enqueue(objectId);
}
public override void OnDeleteObject(uint objectId)
{
if (_deletedIds.Count < 4096) _deletedIds.Enqueue(objectId);
}
public override void OnViewObjectContents(uint objectId)
{
if (_openedIds.Count < 256) _openedIds.Enqueue(objectId);
}
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
if (text == null || text.IndexOf("corpse", StringComparison.OrdinalIgnoreCase) < 0) return;
if (CorpseLines.IsCorpseLine(text) && _corpseLines.Count < 64) _corpseLines.Enqueue(text);
}
/// <summary>The character is known: its corpses from its file, and any of them already in view.</summary>
private void StartCorpses()
{
_corpseStore ??= new CorpseStore(_store.Root);
PlaceNames.EnsureLoading();
_corpseBook.Load(_corpseStore.Load(_server, _character, out string? problem));
if (problem != null) Host.Log($"[RynthDefective] couldn't read the corpses ({problem}); starting empty.");
_corpseRevisionSaved = _corpseBook.Revision;
_corpseRevisionShown = -1;
_corpsePending.Clear();
_corpseDeletes.Clear();
_deadSeen = false;
_nextOthersMs = 0;
_corpsesStarted = true;
if (Host.HasGetLiveObjectIds)
foreach (uint id in Host.GetLiveObjectIds()) CheckCreated(id, Environment.TickCount64);
}
private void StopCorpses()
{
SaveCorpsesNow();
_corpsesStarted = false;
_corpsesView = CorpsesView.NotReady;
while (_createdIds.TryDequeue(out _)) { }
while (_deletedIds.TryDequeue(out _)) { }
while (_openedIds.TryDequeue(out _)) { }
while (_corpseLines.TryDequeue(out _)) { }
_corpsePending.Clear();
_corpseDeletes.Clear();
}
/// <summary>Plugin tick: the death, the server's lines, corpses coming and going, the save and the window's view.</summary>
private void TickCorpses(long now)
{
if (!_corpsesStarted)
{
while (_createdIds.TryDequeue(out _)) { } // nothing to match them to yet
while (_deletedIds.TryDequeue(out _)) { }
while (_openedIds.TryDequeue(out _)) { }
return;
}
DateTime utc = DateTime.UtcNow;
while (_corpseActions.TryDequeue(out Action? act))
{
try { act(); } catch (Exception ex) { Host.Log($"[RynthDefective] corpses: {ex.Message}"); }
}
if (now >= _nextDeathCheckMs)
{
_nextDeathCheckMs = now + 100;
CheckDeath(utc);
}
while (_corpseLines.TryDequeue(out string? line))
{
if (CorpseLines.TryLocated(line, out double ns, out double ew)) _corpseBook.ServerLine(utc, ns, ew, PlayerLevel());
else if (CorpseLines.IsNothingDropped(line)) _corpseBook.NothingDropped(utc);
}
// A portal into town brings hundreds at once: a few hundred a tick, the rest on the next.
for (int n = 0; n < 256 && _createdIds.TryDequeue(out uint id); n++) CheckCreated(id, now);
while (_openedIds.TryDequeue(out uint opened)) _corpseBook.Opened(opened, utc);
for (int i = _corpsePending.Count - 1; i >= 0; i--)
{
(uint id, long until) = _corpsePending[i];
if (TrySeen(id, utc) || now > until) _corpsePending.RemoveAt(i);
}
while (_deletedIds.TryDequeue(out uint id))
foreach (CorpseRecord c in _corpseBook.Corpses)
if (c.ObjectId == id) { _corpseDeletes.Add((id, now + 2500)); break; }
for (int i = _corpseDeletes.Count - 1; i >= 0; i--)
{
if (now < _corpseDeletes[i].AtMs) continue;
uint id = _corpseDeletes[i].Id;
_corpseDeletes.RemoveAt(i);
CheckGone(id);
}
if (now >= _nextAbsentCheckMs)
{
_nextAbsentCheckMs = now + 1000;
CheckNotThere(utc);
}
if (now >= _nextCorpseExpireMs)
{
_nextCorpseExpireMs = now + 60_000;
_corpseBook.Expire(utc);
}
if (_corpseBook.Revision != _corpseRevisionSaved && _corpseSaveDueMs == 0) _corpseSaveDueMs = now + 1000;
if (_corpseSaveDueMs != 0 && now >= _corpseSaveDueMs) SaveCorpsesNow();
bool shown = now - System.Threading.Volatile.Read(ref _corpsesDrawnMs) < 2000;
if (!shown) return;
if (now >= _nextOthersMs && _corpseStore != null)
{
_nextOthersMs = now + 10_000;
_otherCorpses = _corpseStore.LoadOthers(_server, _character, utc);
_corpseRevisionShown = -1;
}
if (now >= _nextCorpseViewMs || _corpseBook.Revision != _corpseRevisionShown)
{
_nextCorpseViewMs = now + 250;
_corpseRevisionShown = _corpseBook.Revision;
_corpsesView = CorpseRows.Build(_corpseBook.Corpses, _otherCorpses, PlayerSpotNow(), utc);
}
}
/// <summary>Health 0 (the edge): where the player stands is where the corpse will lie.</summary>
private void CheckDeath(DateTime utc)
{
if (!Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out _, out _, out _, out _) || maxHp == 0) return;
bool dead = hp == 0;
if (dead && !_deadSeen)
{
_deadSeen = true;
if (Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _) && cell != 0)
{
_corpseBook.Died(utc, cell, x, y, z, PlayerLevel());
Host.Log($"[RynthDefective] died at 0x{cell:X8} ({x:0.0}, {y:0.0}, {z:0.0}): noted for the Corpses window.");
}
}
else if (!dead) _deadSeen = false;
}
private int PlayerLevel()
{
uint player = Host.GetPlayerId();
return player != 0 && Host.TryGetObjectIntProperty(player, LevelProperty, out int level) ? level : 0;
}
/// <summary>An object came into view: one of this character's corpses?</summary>
private void CheckCreated(uint id, long now)
{
if (id == 0 || !Host.TryGetObjectName(id, out string name) || !name.StartsWith(CorpsePrefix, StringComparison.Ordinal)) return;
string of = name.Substring(CorpsePrefix.Length);
if (of != _character && (_corpseAlias == null || of != _corpseAlias)) return;
if (!TrySeen(id, DateTime.UtcNow)) _corpsePending.Add((id, now + 5000));
}
private bool TrySeen(uint id, DateTime utc)
{
if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out float z) || cell == 0) return false;
_corpseBook.Seen(utc, id, cell, x, y, z);
return true;
}
/// <summary>A corpse left view 2.5 s ago: gone for good, or only out of sight (CorpseBook.VanishMeansGone)?</summary>
private void CheckGone(uint id)
{
if (Host.HasIsPortaling && Host.IsPortaling()) return;
if (Host.TryGetObjectPosition(id, out uint back, out _, out _, out _) && back != 0) return; // in view again
CorpseRecord? c = null;
foreach (CorpseRecord r in _corpseBook.Corpses) if (r.ObjectId == id) { c = r; break; }
if (c == null) return;
PlayerSpot me = PlayerSpotNow();
if (me.Cell == 0) return;
double d = CorpseBook.Distance(c, me.Cell, me.X, me.Y, me.Z);
bool opened = c.OpenedUtc != DateTime.MinValue;
if (CorpseBook.VanishMeansGone(c, d, DateTime.UtcNow) && _corpseBook.Gone(id))
Host.Log($"[RynthDefective] your corpse 0x{id:X8} is gone ({d:0} m away{(opened ? ", opened" : "")}).");
else
Host.Log($"[RynthDefective] your corpse 0x{id:X8} left view ({d:0} m away); kept.");
}
/// <summary>Standing where a corpse should be without it in view: after 10 s it's dropped.</summary>
private void CheckNotThere(DateTime utc)
{
if (_corpseBook.Corpses.Count == 0 || (Host.HasIsPortaling && Host.IsPortaling())) return;
PlayerSpot me = PlayerSpotNow();
if (me.Cell == 0) return;
CorpseRecord? drop = null;
double dropAt = 0;
foreach (CorpseRecord c in _corpseBook.Corpses)
{
double d = CorpseBook.Distance(c, me.Cell, me.X, me.Y, me.Z);
bool inView = c.ObjectId != 0 && Host.TryGetObjectPosition(c.ObjectId, out uint oc, out _, out _, out _) && oc != 0;
if (CorpseBook.NotThere(c, d, inView, utc)) { drop = c; dropAt = d; }
}
if (drop != null && _corpseBook.Forget(drop))
Host.Log($"[RynthDefective] a corpse isn't where it was ({dropAt:0} m from its place for {CorpseBook.AbsentFor.TotalSeconds:0} s): dropped.");
}
private PlayerSpot PlayerSpotNow()
{
if (!Host.TryGetPlayerPose(out uint pc, out float px, out float py, out float pz, out float qw, out _, out _, out float qz) || pc == 0)
return default;
double facing = ((-2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI) % 360.0 + 720.0) % 360.0;
return new PlayerSpot(pc, px, py, pz, facing);
}
private void SelectCorpse(CorpseRow row)
{
if (row.ObjectId != 0 && Host.TryGetObjectName(row.ObjectId, out _) && Host.SelectItem(row.ObjectId)) return;
Print($"That corpse isn't in view. It's at {row.Place}.");
}
/// <summary>"/rdef corpses die" and "/rdef corpses as &lt;name&gt;" (tests on a server where dying is slow).</summary>
private string CorpseTestHook(string arg)
{
if (!_corpsesStarted) return "Log in first.";
if (arg.Equals("die", StringComparison.OrdinalIgnoreCase))
{
if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _) || cell == 0)
return "No position.";
_corpseBook.Died(DateTime.UtcNow, cell, x, y, z, PlayerLevel());
return $"Test: a death noted at 0x{cell:X8} ({x:0.0}, {y:0.0}, {z:0.0}).";
}
if (arg.StartsWith("as ", StringComparison.OrdinalIgnoreCase))
{
_corpseAlias = arg.Substring(3).Trim();
if (Host.HasGetLiveObjectIds)
foreach (uint id in Host.GetLiveObjectIds()) CheckCreated(id, Environment.TickCount64);
return $"Test: \"{CorpsePrefix}{_corpseAlias}\" counts as yours until the plugin reloads.";
}
return "Usage: /rdef corpses [clear]";
}
private void SaveCorpsesNow()
{
_corpseSaveDueMs = 0;
if (!_corpsesStarted || _corpseStore == null || _corpseBook.Revision == _corpseRevisionSaved) return;
_corpseRevisionSaved = _corpseBook.Revision;
string? error = _corpseStore.Save(_server, _character, _corpseBook.Corpses);
if (error != null) Host.Log("[RynthDefective] corpses save failed: " + error);
}
}

View file

@ -7,6 +7,7 @@ using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
using RynthCore.Plugin.RynthDefective.Use;
using RynthCore.Plugin.RynthDefective.Views;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
@ -61,6 +62,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
public override int Initialize()
{
_reply = new CommandReply("[RynthDefective]", (t, c) => Host.WriteToChat(t, c), t => Host.Log(t));
_ui.Log = msg => Host.Log(msg);
// The shortcut bar (plugin API v90) draws with ImGui.NET bound to the engine's cimgui, in its look.
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log("[RynthDefective] " + msg));
@ -77,7 +79,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_session.BindOwnKey = (own, key) => Host.HasKeyBinding && BindOwnSlotKey(own, key, out _);
_session.Use.Say = text => { _session.SetStatus(text); Host.Log("[RynthDefective] " + text); };
_session.Use.Warn = text => { _session.SetStatus(text, warning: true); Print(text); };
_session.Use.Warn = text => { _session.SetStatus(text, warning: true); PrintFail(text); };
_session.Use.Log = line => Host.Log(line);
_session.Use.Wielded = OnWielded;
@ -106,6 +108,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
// The engine calls this on a real login and on a freshly (re)loaded plugin already in game.
public override void OnLoginComplete()
{
if (_corpsesStarted) StopCorpses();
_inWorld = true;
_identityKnown = false;
_nextIdentityTryMs = Environment.TickCount64;
@ -116,6 +119,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
public override void OnLogout()
{
SaveNow();
StopCorpses();
_inWorld = false;
_identityKnown = false;
_session.LoggedIn = false;
@ -131,6 +135,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
public override void Shutdown()
{
SaveNow();
SaveCorpsesNow();
_session.Use.ResetSession();
_ui.SubmitEmpty(Host);
}
@ -158,54 +163,88 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
}
if (c.Verb == DefVerb.Error)
{
Print(c.Error);
PrintFail(c.Error);
return;
}
if (!_identityKnown)
{
Print("Log in first.");
PrintFail("Log in first.");
return;
}
// Every command answers (2026-10-28, Plugins/Shared/CommandReply.cs). RynthDefective can't tell a
// typed /rdef from a hotkey's or a meta's (the engine sends them all the same way), so each one does.
switch (c.Verb)
{
case DefVerb.Toggle:
if (UsesShortcutBar)
Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.ShortcutBarWindow.Title, RynthPanelOpen.Toggle);
else if (_barWindow != null) { _barWindow.Visible = !_barWindow.Visible; _barWindow.NeedsPass = true; NoteNoUi(_barWindow.Visible); }
Answer(DefReplies.Window("Shortcuts bar", Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.ShortcutBarWindow.Title, RynthPanelOpen.Toggle)));
else if (_barWindow != null)
{
_barWindow.Visible = !_barWindow.Visible; _barWindow.NeedsPass = true; NoteNoUi(_barWindow.Visible);
Print(CommandReply.Shown("Item bar", _barWindow.Visible));
}
break;
case DefVerb.Selection when c.Text.Length > 0:
// Test hooks: "/rdef selection 0x80001234" selects that object; "stack" the first stack in the pack.
if (c.Text.Equals("stack", StringComparison.OrdinalIgnoreCase))
{
CarriedItem? stack = null;
foreach (var it in _session.Items())
if (it.Stack > 1 && !it.Wielded) { Host.SelectItem(it.Id); break; }
if (it.Stack > 1 && !it.Wielded) { stack = it; break; }
if (stack == null) PrintFail(DefReplies.NoStack);
else Answer(DefReplies.Selected(stack.Id, Host.SelectItem(stack.Id), _session.ObjectName(stack.Id)));
}
else if (uint.TryParse(c.Text.Replace("0x", "", StringComparison.OrdinalIgnoreCase), System.Globalization.NumberStyles.HexNumber, null, out uint pick))
Host.SelectItem(pick);
else if (DefReplies.TryParseSelection(c.Text, out uint pick, out string why))
Answer(DefReplies.Selected(pick, Host.SelectItem(pick), _session.ObjectName(pick)));
else PrintFail(why);
break;
case DefVerb.Selection:
if (UsesShortcutBar) Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.SelectionWindow.Title, RynthPanelOpen.Toggle);
else Print("This RynthCore can't show the selection window (it needs plugin API v90).");
if (UsesShortcutBar) Answer(DefReplies.Window("Selection window", Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.SelectionWindow.Title, RynthPanelOpen.Toggle)));
else PrintFail("This RynthCore can't show the selection window (it needs plugin API v90).");
break;
case DefVerb.Settings:
ShowSettingsWindow(true);
Print("Settings shown.");
break;
case DefVerb.Corpses when c.Text.Equals("clear", StringComparison.OrdinalIgnoreCase):
_corpseBook.Clear();
Print("This character's corpses are forgotten.");
break;
case DefVerb.Corpses when c.Text.Length > 0:
// Test hooks: "die" notes a death where you stand; "as Olthoi Slayer" counts that name's corpses as yours.
Print(CorpseTestHook(c.Text));
break;
case DefVerb.Corpses:
if (UsesShortcutBar) Answer(DefReplies.Window("Corpses window", Host.SetPanelOpen(Corpses.CorpsesWindow.Title, RynthPanelOpen.Toggle)));
else PrintFail("This RynthCore can't show the corpses window (it needs plugin API v90).");
break;
case DefVerb.Panels:
if (UsesPanelButtons) Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.PanelButtonsWindow.Title, RynthPanelOpen.Toggle);
else Print("This RynthCore can't open the game's panels from buttons (it needs plugin API v90).");
if (UsesPanelButtons) Answer(DefReplies.Window("Game Panels buttons", Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.PanelButtonsWindow.Title, RynthPanelOpen.Toggle)));
else PrintFail("This RynthCore can't open the game's panels from buttons (it needs plugin API v90).");
break;
case DefVerb.Weapons:
{
if (c.Text.Length > 0 && _picker != null) _picker.Search = c.Text;
ShowPicker(c.Text.Length > 0 || _pickerWindow?.Visible != true);
bool show = c.Text.Length > 0 || _pickerWindow?.Visible != true;
ShowPicker(show);
Print(DefReplies.Weapons(show, c.Text));
break;
}
case DefVerb.Use:
if (c.Slot > 0)
{
string? problem = _session.UseSlot(c.Slot);
if (problem != null) { _session.SetStatus(problem, warning: true); Print(problem); }
// A use that goes is quiet (logged): slot hotkeys send /rdef use N on every press, and
// the use itself is the feedback (Tom 2026-10-28). Failures still answer.
if (problem != null) { _session.SetStatus(problem, warning: true); PrintFail(problem); }
else Reply.Ok(DefReplies.UseSlot(_session.Data.Slots[c.Slot - 1], c.Slot), quiet: true);
}
else
{
_session.UseByName(c.Text);
Reply.Ok(DefReplies.UseName(c.Text), quiet: true);
}
else _session.UseByName(c.Text);
break;
case DefVerb.Set:
Print(c.Text.Length > 0 ? _session.SetFromName(c.Slot, c.Text) : _session.SetFromSelected(c.Slot));
@ -280,11 +319,16 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
+ $"{(_session.Use.InFlight ? "an action is in flight" : _session.Use.HasPending ? "an action is waiting" : "idle")}; file {_store.PathFor(_server, _character)}");
}
private void Print(string text)
{
if (!Host.WriteToChat("[RynthDefective] " + text, 1))
Host.Log("[RynthDefective] " + text);
}
// Chat lines wait in the shared reply queue (the host drops a line written within 100 ms of
// another plugin's); the tick writes them.
private CommandReply? _reply;
private CommandReply Reply => _reply ??= new CommandReply("[RynthDefective]", (t, c) => Host.WriteToChat(t, c), t => Host.Log(t));
private void Print(string text) => Reply.Ok(text);
private void PrintFail(string text) => Reply.Fail(text);
private void Answer((bool Ok, string Text) reply) => Reply.Say(reply.Ok, reply.Text);
private void NoteNoUi(bool shown)
{
@ -367,8 +411,13 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
while (_commands.TryDequeue(out string? cmd))
{
try { RunCommand(cmd); }
catch (Exception ex) { Host.Log($"[RynthDefective] /rdef {cmd} failed: {ex.GetType().Name}: {ex.Message}"); }
catch (Exception ex)
{
Host.Log($"[RynthDefective] /rdef {cmd} failed: {ex.GetType().Name}: {ex.Message}");
PrintFail($"/rdef {cmd} failed: {ex.Message}");
}
}
Reply.Flush();
_ui.Poll(Host);
if (_inWorld)
@ -390,6 +439,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
if (_saveDueMs != 0 && now >= _saveDueMs) SaveNow();
TickBar(now);
TickSelection(now);
TickCorpses(now);
// With the shortcut bar the old script-window bar stays shut (the weapon picker is still one), and
// has no RynthBar button (one that opened a window shut again at once). Its settings have their
@ -451,6 +501,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_identityKnown = true;
_revisionSeen = -1;
RefreshIconSupport();
StartCorpses();
if (_barWindow != null && _bar != null)
{
_barWindow.Visible = data.Settings.BarOpen;

View file

@ -137,7 +137,7 @@ internal sealed class PanelButtonsWindow
}
/// <summary>A Phosphor glyph centred in the box, <paramref name="px"/> across its em (from Ui18's bake).</summary>
private static unsafe void DrawIcon(ImDrawListPtr dl, string glyph, Vector2 min, Vector2 size, float px, uint color)
internal static unsafe void DrawIcon(ImDrawListPtr dl, string glyph, Vector2 min, Vector2 size, float px, uint color)
{
if (string.IsNullOrEmpty(glyph)) return;
ImFontPtr font = Font(RynthUiFont.Ui18);