RynthSuite as of 2026-11-26 (internal 1db112e): release 2026.11.26.1
This commit is contained in:
parent
90e76a6561
commit
25552fa794
175 changed files with 23428 additions and 494 deletions
243
Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapCalibration.cs
Normal file
243
Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapCalibration.cs
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
// ============================================================================
|
||||
// RynthAi - AcMaps/AcMapCalibration.cs
|
||||
// Where you are on an ACMAPS map: the dungeon position (the /loc x, y, z in
|
||||
// the landblock) to a pixel on the image, set by the player once per map.
|
||||
//
|
||||
// ACMAPS maps carry no coordinates. GoArrow had the player drag the map until
|
||||
// its arrow sat on the entrance, then moved the map 3 pixels per unit walked
|
||||
// (DungeonHud.cs: dX = (old - new) * 3, north up). Here the player does the
|
||||
// same once and it is saved: stand somewhere you can find on the map, press
|
||||
// "Place me here" and click that spot. One spot per floor places the floor
|
||||
// with the map's scale (GoArrow's 3 pixels per unit until it is measured);
|
||||
// a second spot on a floor, some way from the first, measures the scale.
|
||||
// ACMAPS draws each floor in its own part of the image, so every floor
|
||||
// (spots within FloorTolerance of each other's height) gets its own spots.
|
||||
// The maps are north up: x east is right, y north is up (the image's -y).
|
||||
//
|
||||
// Pure: tests drive it.
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.AcMaps;
|
||||
|
||||
/// <summary>A spot the player set: where they stood (landblock x, y, z) and the pixel on the map they clicked.</summary>
|
||||
internal readonly record struct MapSpot(float X, float Y, float Z, float Px, float Py);
|
||||
|
||||
/// <summary>What a Place did, for the window's status line.</summary>
|
||||
internal enum PlaceResult
|
||||
{
|
||||
/// <summary>The first spot on this floor: placed with the map's scale.</summary>
|
||||
FloorPlaced,
|
||||
/// <summary>A spot near the floor's only one: it moved there.</summary>
|
||||
Moved,
|
||||
/// <summary>The second spot on the floor: the scale was measured.</summary>
|
||||
ScaleMeasured,
|
||||
/// <summary>The two spots disagree with a north-up map (the map would be mirrored or the scale absurd): kept as the floor's only spot.</summary>
|
||||
ScaleRefused,
|
||||
}
|
||||
|
||||
internal sealed class AcMapCalibration
|
||||
{
|
||||
/// <summary>GoArrow's scale: map pixels per landblock unit walked.</summary>
|
||||
public const float DefaultScale = 3f;
|
||||
public const float MinScale = 0.2f, MaxScale = 50f;
|
||||
/// <summary>Spots this close in height are one floor (AC dungeon floors are about 6 units apart).</summary>
|
||||
public const float FloorTolerance = 3f;
|
||||
/// <summary>Two spots must be this far apart (landblock units) to measure the scale.</summary>
|
||||
public const float MinSpotDistance = 8f;
|
||||
/// <summary>The most spots a map keeps (two a floor; a dungeon has a handful of floors).</summary>
|
||||
public const int MaxSpots = 64;
|
||||
|
||||
private readonly List<MapSpot> _spots = new();
|
||||
|
||||
/// <summary>Map pixels per landblock unit, shared by every floor.</summary>
|
||||
public float Scale { get; private set; } = DefaultScale;
|
||||
/// <summary>The scale was measured from two spots (or set by hand), not GoArrow's default.</summary>
|
||||
public bool ScaleMeasuredOrSet { get; private set; }
|
||||
|
||||
public IReadOnlyList<MapSpot> Spots => _spots;
|
||||
public bool IsEmpty => _spots.Count == 0;
|
||||
|
||||
public AcMapCalibration() { }
|
||||
|
||||
/// <summary>A saved calibration (AcMapSettings); bad values fall back to the defaults.</summary>
|
||||
public AcMapCalibration(float scale, bool scaleSet, IEnumerable<MapSpot> spots)
|
||||
{
|
||||
if (float.IsFinite(scale) && scale >= MinScale && scale <= MaxScale) { Scale = scale; ScaleMeasuredOrSet = scaleSet; }
|
||||
foreach (MapSpot s in spots)
|
||||
{
|
||||
if (_spots.Count >= MaxSpots) break;
|
||||
if (float.IsFinite(s.X) && float.IsFinite(s.Y) && float.IsFinite(s.Z) && float.IsFinite(s.Px) && float.IsFinite(s.Py))
|
||||
_spots.Add(s);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The spots on the floor at height <paramref name="z"/>, nearest in height first.</summary>
|
||||
public List<MapSpot> FloorSpots(float z)
|
||||
{
|
||||
var list = new List<MapSpot>();
|
||||
foreach (MapSpot s in _spots)
|
||||
if (MathF.Abs(s.Z - z) <= FloorTolerance) list.Add(s);
|
||||
list.Sort((a, b) => MathF.Abs(a.Z - z).CompareTo(MathF.Abs(b.Z - z)));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>This floor has a spot: a position on it has a pixel.</summary>
|
||||
public bool FloorPlaced(float z) => FloorSpots(z).Count > 0;
|
||||
|
||||
/// <summary>
|
||||
/// The pixel for a landblock position, through the floor's spots (one: that spot and the map's scale; two:
|
||||
/// their mean). False when the floor has no spot.
|
||||
/// </summary>
|
||||
public bool TryToImage(float x, float y, float z, out Vector2 pixel)
|
||||
{
|
||||
pixel = default;
|
||||
if (!TryFloorOrigin(z, out Vector2 origin)) return false;
|
||||
pixel = new Vector2(origin.X + Scale * x, origin.Y - Scale * y);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The landblock x, y for a pixel on the floor at <paramref name="z"/> (the inverse of TryToImage).</summary>
|
||||
public bool TryToWorld(Vector2 pixel, float z, out float x, out float y)
|
||||
{
|
||||
x = y = 0;
|
||||
if (!TryFloorOrigin(z, out Vector2 origin)) return false;
|
||||
x = (pixel.X - origin.X) / Scale;
|
||||
y = -(pixel.Y - origin.Y) / Scale;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Where landblock (0, 0) falls on the image for this floor: each spot's pixel less its position, averaged.</summary>
|
||||
private bool TryFloorOrigin(float z, out Vector2 origin)
|
||||
{
|
||||
origin = default;
|
||||
List<MapSpot> floor = FloorSpots(z);
|
||||
if (floor.Count == 0) return false;
|
||||
int n = Math.Min(floor.Count, 2);
|
||||
for (int i = 0; i < n; i++)
|
||||
origin += new Vector2(floor[i].Px - Scale * floor[i].X, floor[i].Py + Scale * floor[i].Y);
|
||||
origin /= n;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Place me here": the player stands at (x, y, z) and clicked pixel (px, py). The floor's first spot places it;
|
||||
/// a second one at least <see cref="MinSpotDistance"/> away measures the map's scale; one closer than that
|
||||
/// moves the nearer spot. A floor keeps two spots: a third replaces the nearer.
|
||||
/// </summary>
|
||||
public PlaceResult Place(float x, float y, float z, float px, float py)
|
||||
{
|
||||
var spot = new MapSpot(x, y, z, px, py);
|
||||
List<MapSpot> floor = FloorSpots(z);
|
||||
if (floor.Count == 0)
|
||||
{
|
||||
if (_spots.Count >= MaxSpots) _spots.RemoveAt(0);
|
||||
_spots.Add(spot);
|
||||
return PlaceResult.FloorPlaced;
|
||||
}
|
||||
// The spot nearest the new one (in the dungeon) is the one replaced or kept beside it.
|
||||
MapSpot nearer = floor[0];
|
||||
float nearD = Dist(floor[0], spot);
|
||||
for (int i = 1; i < floor.Count; i++)
|
||||
{
|
||||
float d = Dist(floor[i], spot);
|
||||
if (d < nearD) { nearD = d; nearer = floor[i]; }
|
||||
}
|
||||
if (nearD < MinSpotDistance)
|
||||
{
|
||||
// Too near to measure anything: it moves (a better click on the same place).
|
||||
Replace(nearer, spot);
|
||||
return PlaceResult.Moved;
|
||||
}
|
||||
// The other spot on this floor (the one kept): with the new one they measure the scale.
|
||||
MapSpot other = nearer;
|
||||
if (floor.Count >= 2)
|
||||
{
|
||||
// Two already: the nearer one goes, the farther one stays with the new.
|
||||
MapSpot farther = floor[0].Equals(nearer) ? floor[1] : floor[0];
|
||||
_spots.Remove(nearer);
|
||||
for (int i = 2; i < floor.Count; i++) _spots.Remove(floor[i]);
|
||||
other = farther;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 1; i < floor.Count; i++) _spots.Remove(floor[i]);
|
||||
}
|
||||
if (!TrySolveScale(other, spot, out float scale))
|
||||
{
|
||||
// A mirrored or absurd answer: the click was off. The new spot alone places the floor.
|
||||
_spots.Remove(other);
|
||||
_spots.Add(spot);
|
||||
return PlaceResult.ScaleRefused;
|
||||
}
|
||||
_spots.Add(spot);
|
||||
Scale = scale;
|
||||
ScaleMeasuredOrSet = true;
|
||||
return PlaceResult.ScaleMeasured;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The scale two spots give on a north-up map: the least-squares fit of pixel steps to (dx, -dy) steps.
|
||||
/// False when the spots are too close, or the fit is mirrored, out of range, or far from a plain scale
|
||||
/// (the pixel steps and the walked steps point more than 30 degrees apart).
|
||||
/// </summary>
|
||||
internal static bool TrySolveScale(MapSpot a, MapSpot b, out float scale)
|
||||
{
|
||||
scale = 0;
|
||||
float wx = b.X - a.X, wy = -(b.Y - a.Y);
|
||||
float ix = b.Px - a.Px, iy = b.Py - a.Py;
|
||||
float w2 = wx * wx + wy * wy;
|
||||
if (w2 < MinSpotDistance * MinSpotDistance) return false;
|
||||
float s = (ix * wx + iy * wy) / w2;
|
||||
if (!float.IsFinite(s) || s < MinScale || s > MaxScale) return false;
|
||||
float i2 = ix * ix + iy * iy;
|
||||
if (i2 <= 0) return false;
|
||||
float cos = (ix * wx + iy * wy) / MathF.Sqrt(i2 * w2);
|
||||
if (cos < MathF.Cos(30f * MathF.PI / 180f)) return false;
|
||||
scale = s;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The scale nudged by hand (the window's - and +), kept in range.</summary>
|
||||
public void NudgeScale(float factor)
|
||||
{
|
||||
if (!float.IsFinite(factor) || factor <= 0) return;
|
||||
Scale = Math.Clamp(Scale * factor, MinScale, MaxScale);
|
||||
ScaleMeasuredOrSet = true;
|
||||
}
|
||||
|
||||
/// <summary>The floor at <paramref name="z"/> forgets its spots. True when it had some.</summary>
|
||||
public bool ClearFloor(float z) => _spots.RemoveAll(s => MathF.Abs(s.Z - z) <= FloorTolerance) > 0;
|
||||
|
||||
/// <summary>Every spot and the scale back to the start.</summary>
|
||||
public void ClearAll()
|
||||
{
|
||||
_spots.Clear();
|
||||
Scale = DefaultScale;
|
||||
ScaleMeasuredOrSet = false;
|
||||
}
|
||||
|
||||
/// <summary>How many floors have a spot (spots grouped by height).</summary>
|
||||
public int FloorCount()
|
||||
{
|
||||
var zs = new List<float>();
|
||||
foreach (MapSpot s in _spots)
|
||||
if (!zs.Exists(z => MathF.Abs(z - s.Z) <= FloorTolerance)) zs.Add(s.Z);
|
||||
return zs.Count;
|
||||
}
|
||||
|
||||
private void Replace(MapSpot old, MapSpot now)
|
||||
{
|
||||
int i = _spots.IndexOf(old);
|
||||
if (i >= 0) _spots[i] = now;
|
||||
else _spots.Add(now);
|
||||
}
|
||||
|
||||
private static float Dist(MapSpot a, MapSpot b)
|
||||
{
|
||||
float dx = a.X - b.X, dy = a.Y - b.Y;
|
||||
return MathF.Sqrt(dx * dx + dy * dy);
|
||||
}
|
||||
}
|
||||
377
Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapIndex.cs
Normal file
377
Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapIndex.cs
Normal file
|
|
@ -0,0 +1,377 @@
|
|||
// ============================================================================
|
||||
// RynthAi - AcMaps/AcMapIndex.cs
|
||||
// The player's own ACMAPS dungeon map pack, indexed (2026-11-26, a player's
|
||||
// request: show the ACMAPS maps in game, as GoArrow did). Nothing here ships
|
||||
// a map: the player points RynthAi at the folder they already have.
|
||||
//
|
||||
// What a pack looks like (GoArrow's "Dungeon Map Cache" folder, read from
|
||||
// GoArrow's MIT-licensed source, Huds/DungeonHud.cs):
|
||||
// - one image per dungeon, named by the dungeon's four-hex landblock, the
|
||||
// top half of the /loc cell id: "02CA.gif" (GoArrow fetched
|
||||
// www.acmaps.com/maps/{0:X4}.gif). PNG and JPG are taken too, and names
|
||||
// like "0x02CA.png", "02CA - Mosswart Maze.gif" or "02CA0100.gif";
|
||||
// - "dungeons.txt" (ACMAPS' dungeon_ids.csv): "02CA;Mosswart Maze", one
|
||||
// dungeon a line, the landblock in hex then the name;
|
||||
// - optionally a GoArrow locations database (data_cod.xml, GAlocations.xml):
|
||||
// <location> records whose <type>Dungeon</type> ones carry <dungeon_id>
|
||||
// (the same landblock), <name>, <restrictions>, <description> and the
|
||||
// entrance's <latitude>/<longitude> (north and west negative).
|
||||
// An image whose name has no landblock is matched to a name from those files.
|
||||
//
|
||||
// Pure apart from Scan (the disk listing); tests feed Build file names and text.
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.AcMaps;
|
||||
|
||||
/// <summary>One map image: its dungeon's landblock (0 = not known), name and the file, relative to the folder.</summary>
|
||||
internal sealed record AcMapEntry(ushort Landblock, string Name, string RelativePath, string Notes)
|
||||
{
|
||||
/// <summary>"Mosswart Maze (02CA)", or the file name when nothing names it.</summary>
|
||||
public string Label => Landblock != 0
|
||||
? (Name.Length > 0 ? $"{Name} ({Landblock:X4})" : $"Dungeon {Landblock:X4}")
|
||||
: (Name.Length > 0 ? Name : Path.GetFileName(RelativePath));
|
||||
}
|
||||
|
||||
internal sealed class AcMapIndex
|
||||
{
|
||||
/// <summary>The image types WIC decodes that map packs use.</summary>
|
||||
internal static readonly string[] ImageExtensions = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
|
||||
|
||||
/// <summary>The index files read (a dungeon list or a locations database).</summary>
|
||||
internal static readonly string[] IndexExtensions = { ".txt", ".csv", ".xml" };
|
||||
|
||||
/// <summary>Scan limits: a pack is a few hundred images; a wrong folder (C:\) must not stall.</summary>
|
||||
internal const int MaxFiles = 20000, MaxDepth = 4;
|
||||
internal const long MaxIndexFileBytes = 16L * 1024 * 1024;
|
||||
|
||||
public static readonly AcMapIndex Empty = new(string.Empty, new List<AcMapEntry>(), new Dictionary<ushort, string>(),
|
||||
new List<string>(), new List<string>());
|
||||
|
||||
public string Folder { get; }
|
||||
/// <summary>Every map, by label.</summary>
|
||||
public IReadOnlyList<AcMapEntry> Maps { get; }
|
||||
/// <summary>Dungeon names by landblock, from the index files.</summary>
|
||||
public IReadOnlyDictionary<ushort, string> Names { get; }
|
||||
/// <summary>The index files that named at least one dungeon (relative paths).</summary>
|
||||
public IReadOnlyList<string> IndexFiles { get; }
|
||||
/// <summary>What went wrong reading the folder (shown in the window).</summary>
|
||||
public IReadOnlyList<string> Problems { get; }
|
||||
|
||||
private readonly Dictionary<ushort, List<AcMapEntry>> _byLandblock = new();
|
||||
|
||||
private AcMapIndex(string folder, List<AcMapEntry> maps, Dictionary<ushort, string> names, List<string> indexFiles, List<string> problems)
|
||||
{
|
||||
Folder = folder;
|
||||
Maps = maps;
|
||||
Names = names;
|
||||
IndexFiles = indexFiles;
|
||||
Problems = problems;
|
||||
foreach (AcMapEntry e in maps)
|
||||
{
|
||||
if (e.Landblock == 0) continue;
|
||||
if (!_byLandblock.TryGetValue(e.Landblock, out var list)) _byLandblock[e.Landblock] = list = new List<AcMapEntry>();
|
||||
list.Add(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The maps of a dungeon (most packs have one; a few have extra parts), first by file name.</summary>
|
||||
public IReadOnlyList<AcMapEntry> ForLandblock(ushort landblock) =>
|
||||
_byLandblock.TryGetValue(landblock, out var list) ? list : (IReadOnlyList<AcMapEntry>)Array.Empty<AcMapEntry>();
|
||||
|
||||
public bool Has(ushort landblock) => _byLandblock.ContainsKey(landblock);
|
||||
|
||||
/// <summary>The dungeon's name from the index files, or "".</summary>
|
||||
public string NameOf(ushort landblock) => Names.TryGetValue(landblock, out string? n) ? n : string.Empty;
|
||||
|
||||
/// <summary>"123 maps, 456 dungeon names (dungeons.txt)".</summary>
|
||||
public string Summary()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(Maps.Count == 1 ? "1 map" : $"{Maps.Count} maps");
|
||||
sb.Append(", ").Append(Names.Count == 1 ? "1 dungeon name" : $"{Names.Count} dungeon names");
|
||||
if (IndexFiles.Count > 0) sb.Append(" (").Append(string.Join(", ", IndexFiles)).Append(')');
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
// ── Building ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The index of <paramref name="folder"/> from its files (<paramref name="relativeFiles"/>, relative paths)
|
||||
/// and <paramref name="readText"/> (an index file's text by relative path, null when it can't be read).
|
||||
/// </summary>
|
||||
public static AcMapIndex Build(string folder, IEnumerable<string> relativeFiles, Func<string, string?> readText)
|
||||
{
|
||||
var problems = new List<string>();
|
||||
var names = new Dictionary<ushort, string>();
|
||||
var notes = new Dictionary<ushort, string>();
|
||||
var indexFiles = new List<string>();
|
||||
var images = new List<string>();
|
||||
foreach (string rel in relativeFiles)
|
||||
{
|
||||
string ext = Path.GetExtension(rel).ToLowerInvariant();
|
||||
if (ImageExtensions.Contains(ext)) images.Add(rel);
|
||||
else if (IndexExtensions.Contains(ext))
|
||||
{
|
||||
string? text = readText(rel);
|
||||
if (text == null) { problems.Add($"Couldn't read {rel}."); continue; }
|
||||
int n = ext == ".xml" || text.Contains("<location", StringComparison.OrdinalIgnoreCase)
|
||||
? ParseLocationsXml(text, names, notes)
|
||||
: ParseDungeonList(text, names);
|
||||
if (n > 0) indexFiles.Add(rel);
|
||||
}
|
||||
}
|
||||
|
||||
// Names without a landblock in their file name: matched by dungeon name.
|
||||
var byName = new Dictionary<string, ushort>(StringComparer.Ordinal);
|
||||
foreach (var (lb, name) in names)
|
||||
{
|
||||
string key = NameKey(name);
|
||||
if (key.Length > 0 && !byName.ContainsKey(key)) byName[key] = lb;
|
||||
}
|
||||
|
||||
var maps = new List<AcMapEntry>(images.Count);
|
||||
foreach (string rel in images.OrderBy(r => r, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
string file = Path.GetFileNameWithoutExtension(rel);
|
||||
ushort lb;
|
||||
string name;
|
||||
// A whole file name that is a listed dungeon wins ("Dead End.png" is a name, not landblock DEAD).
|
||||
if (byName.TryGetValue(NameKey(file), out ushort named) && ParseLandblock(file) == 0)
|
||||
{
|
||||
lb = named;
|
||||
name = names[named];
|
||||
}
|
||||
else if (TryLandblockFromFileName(file, out lb, out string rest))
|
||||
name = names.TryGetValue(lb, out string? n) ? n : rest;
|
||||
else
|
||||
{
|
||||
name = file.Trim();
|
||||
lb = byName.TryGetValue(NameKey(name), out ushort found) ? found : (ushort)0;
|
||||
if (lb != 0 && names.TryGetValue(lb, out string? listed)) name = listed;
|
||||
}
|
||||
maps.Add(new AcMapEntry(lb, name, rel, lb != 0 && notes.TryGetValue(lb, out string? note) ? note : string.Empty));
|
||||
}
|
||||
maps.Sort((a, b) => string.Compare(a.Label, b.Label, StringComparison.OrdinalIgnoreCase));
|
||||
if (images.Count == 0) problems.Add("No map images (GIF, PNG or JPG) in this folder or the folders in it.");
|
||||
else if (names.Count == 0) problems.Add("No dungeon list (dungeons.txt) found: maps are shown by their landblock.");
|
||||
return new AcMapIndex(folder, maps, names, indexFiles, problems);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lists <paramref name="folder"/> (and the folders in it, <see cref="MaxDepth"/> deep, <see cref="MaxFiles"/>
|
||||
/// files at most) and builds the index. Any thread; never throws.
|
||||
/// </summary>
|
||||
public static AcMapIndex Scan(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(folder) || !Directory.Exists(folder))
|
||||
return new AcMapIndex(folder ?? string.Empty, new List<AcMapEntry>(), new Dictionary<ushort, string>(),
|
||||
new List<string>(), new List<string> { "The folder isn't there." });
|
||||
string root = Path.GetFullPath(folder);
|
||||
var files = new List<string>();
|
||||
bool truncated = false;
|
||||
Walk(root, root, 0, files, ref truncated);
|
||||
AcMapIndex index = Build(root, files, rel =>
|
||||
{
|
||||
try
|
||||
{
|
||||
string full = Path.Combine(root, rel);
|
||||
if (new FileInfo(full).Length > MaxIndexFileBytes) return null;
|
||||
return File.ReadAllText(full, Encoding.UTF8);
|
||||
}
|
||||
catch { return null; }
|
||||
});
|
||||
if (truncated) ((List<string>)index.Problems).Add($"Stopped after {MaxFiles} files: is this the map folder?");
|
||||
return index;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new AcMapIndex(folder ?? string.Empty, new List<AcMapEntry>(), new Dictionary<ushort, string>(),
|
||||
new List<string>(), new List<string> { "Couldn't read the folder: " + ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
private static void Walk(string root, string dir, int depth, List<string> files, ref bool truncated)
|
||||
{
|
||||
IEnumerable<string> here;
|
||||
try { here = Directory.EnumerateFiles(dir); }
|
||||
catch { return; }
|
||||
foreach (string f in here)
|
||||
{
|
||||
if (files.Count >= MaxFiles) { truncated = true; return; }
|
||||
string ext = Path.GetExtension(f).ToLowerInvariant();
|
||||
if (ImageExtensions.Contains(ext) || IndexExtensions.Contains(ext)) files.Add(Path.GetRelativePath(root, f));
|
||||
}
|
||||
if (depth >= MaxDepth) return;
|
||||
IEnumerable<string> subs;
|
||||
try { subs = Directory.EnumerateDirectories(dir); }
|
||||
catch { return; }
|
||||
foreach (string d in subs)
|
||||
{
|
||||
if (files.Count >= MaxFiles) { truncated = true; return; }
|
||||
Walk(root, d, depth + 1, files, ref truncated);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Parsing ──────────────────────────────────────────────────────────
|
||||
|
||||
private static readonly Regex FileNameRx = new(@"^(?:0x)?([0-9A-Fa-f]{4})(?:[0-9A-Fa-f]{4})?(?![0-9A-Za-z])(.*)$",
|
||||
RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>
|
||||
/// "02CA", "0x02CA", "02CA0100", "02CA - Mosswart Maze": the landblock and the rest as a name ("Mosswart Maze").
|
||||
/// False for a name that doesn't start with 4 (or 8) hex digits on their own ("Mosswart Maze", "02CAB").
|
||||
/// </summary>
|
||||
internal static bool TryLandblockFromFileName(string fileName, out ushort landblock, out string rest)
|
||||
{
|
||||
landblock = 0;
|
||||
rest = string.Empty;
|
||||
Match m = FileNameRx.Match(fileName.Trim());
|
||||
if (!m.Success) return false;
|
||||
landblock = ushort.Parse(m.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
|
||||
if (landblock == 0) return false;
|
||||
rest = m.Groups[2].Value.Trim().TrimStart('-', '_', '.', ' ', '(').TrimEnd(')').Trim();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>A landblock written as "02CA", "0x02CA", "02CA0100" or "0x02CA0100"; 0 when it isn't one.</summary>
|
||||
internal static ushort ParseLandblock(string text)
|
||||
{
|
||||
string t = text.Trim();
|
||||
if (t.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) t = t[2..];
|
||||
if ((t.Length != 4 && t.Length != 8) || !uint.TryParse(t, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint v))
|
||||
return 0;
|
||||
return (ushort)(t.Length == 8 ? v >> 16 : v);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A dungeon list: "02CA;Mosswart Maze" a line (GoArrow's dungeons.txt, ACMAPS' dungeon_ids.csv); a comma or a
|
||||
/// tab works as the separator too, and "Mosswart Maze;02CA". Other lines are skipped. Returns the names added.
|
||||
/// </summary>
|
||||
internal static int ParseDungeonList(string text, Dictionary<ushort, string> names)
|
||||
{
|
||||
int added = 0;
|
||||
foreach (string raw in text.Split('\n'))
|
||||
{
|
||||
string line = raw.Trim().TrimStart('\uFEFF');
|
||||
if (line.Length == 0 || line[0] == '#') continue;
|
||||
char sep = line.Contains(';') ? ';' : line.Contains('\t') ? '\t' : ',';
|
||||
string[] parts = line.Split(sep);
|
||||
if (parts.Length < 2) continue;
|
||||
string a = Unquote(parts[0]), b = Unquote(parts[1]);
|
||||
ushort lb = ParseLandblock(a);
|
||||
string name = b;
|
||||
if (lb == 0) { lb = ParseLandblock(b); name = a; }
|
||||
if (lb == 0 || name.Length == 0 || ParseLandblock(name) != 0) continue;
|
||||
if (!names.ContainsKey(lb)) added++;
|
||||
names[lb] = name;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
private static readonly Regex LocationRx = new(@"<location\b[^>]*>(.*?)</location>",
|
||||
RegexOptions.CultureInvariant | RegexOptions.Singleline | RegexOptions.IgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// A GoArrow locations database: each <location> with a <dungeon_id> (or <type>Dungeon
|
||||
/// and an id) names its dungeon; its restrictions, entrance and description become the map's notes. A
|
||||
/// name the dungeon list already gave is kept. Returns the dungeons added.
|
||||
/// </summary>
|
||||
internal static int ParseLocationsXml(string text, Dictionary<ushort, string> names, Dictionary<ushort, string> notes)
|
||||
{
|
||||
int added = 0;
|
||||
foreach (Match m in LocationRx.Matches(text))
|
||||
{
|
||||
string body = m.Groups[1].Value;
|
||||
ushort lb = ParseLandblock(Tag(body, "dungeon_id"));
|
||||
if (lb == 0) continue;
|
||||
if (Tag(body, "retired").Equals("Y", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
string name = Tag(body, "name");
|
||||
if (name.Length > 0 && !names.ContainsKey(lb)) { names[lb] = name; added++; }
|
||||
if (!notes.ContainsKey(lb))
|
||||
{
|
||||
string note = LocationNote(body);
|
||||
if (note.Length > 0) notes[lb] = note;
|
||||
}
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
/// <summary>"Entrance 25.2S, 19.4E. Level 40+. Quest(s): ...".</summary>
|
||||
private static string LocationNote(string body)
|
||||
{
|
||||
var parts = new List<string>();
|
||||
if (TryCoord(Tag(body, "latitude"), 'S', 'N', out string ns) && TryCoord(Tag(body, "longitude"), 'E', 'W', out string ew)
|
||||
&& !(ns.StartsWith("0.0") && ew.StartsWith("0.0")))
|
||||
parts.Add($"Entrance {ns}, {ew}.");
|
||||
string restrictions = Tag(body, "restrictions");
|
||||
if (restrictions.Length > 0) parts.Add(restrictions.TrimEnd('.') + ".");
|
||||
string description = Tag(body, "description");
|
||||
if (description.Length > 0) parts.Add(description);
|
||||
return string.Join(" ", parts);
|
||||
}
|
||||
|
||||
/// <summary>GoArrow's coordinates: south and east positive ("22.200" is 22.2S), north and west negative.</summary>
|
||||
internal static bool TryCoord(string text, char positive, char negative, out string coord)
|
||||
{
|
||||
coord = string.Empty;
|
||||
if (!double.TryParse(text.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out double v)) return false;
|
||||
coord = Math.Abs(v).ToString("0.0", CultureInfo.InvariantCulture) + (v < 0 ? negative : positive);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string Tag(string body, string tag)
|
||||
{
|
||||
Match m = Regex.Match(body, "<" + tag + @"\b[^>]*>(.*?)</" + tag + ">",
|
||||
RegexOptions.CultureInvariant | RegexOptions.Singleline | RegexOptions.IgnoreCase);
|
||||
return m.Success ? Unescape(m.Groups[1].Value).Trim() : string.Empty;
|
||||
}
|
||||
|
||||
private static string Unescape(string s)
|
||||
{
|
||||
if (s.StartsWith("<![CDATA[", StringComparison.Ordinal) && s.EndsWith("]]>", StringComparison.Ordinal)) return s[9..^3];
|
||||
if (s.IndexOf('&') < 0) return s;
|
||||
s = Regex.Replace(s, "&#(x?)([0-9A-Fa-f]+);", m =>
|
||||
{
|
||||
bool hex = m.Groups[1].Value.Length > 0;
|
||||
return int.TryParse(m.Groups[2].Value, hex ? NumberStyles.HexNumber : NumberStyles.Integer, CultureInfo.InvariantCulture, out int c)
|
||||
&& c > 0 && c < 0x110000 ? char.ConvertFromUtf32(c) : string.Empty;
|
||||
});
|
||||
return s.Replace("<", "<").Replace(">", ">").Replace(""", "\"").Replace("'", "'").Replace("&", "&");
|
||||
}
|
||||
|
||||
private static string Unquote(string s)
|
||||
{
|
||||
s = s.Trim();
|
||||
if (s.Length >= 2 && s[0] == '"' && s[^1] == '"') s = s[1..^1].Replace("\"\"", "\"");
|
||||
return s.Trim();
|
||||
}
|
||||
|
||||
/// <summary>A name for matching: letters and digits, lower case ("The Mosswart Maze!" is "themosswartmaze").</summary>
|
||||
internal static string NameKey(string name)
|
||||
{
|
||||
var sb = new StringBuilder(name.Length);
|
||||
foreach (char c in name)
|
||||
if (char.IsLetterOrDigit(c)) sb.Append(char.ToLowerInvariant(c));
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
// ── Search ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The maps whose label has every word (any order, any case); every map for no words.</summary>
|
||||
public static List<AcMapEntry> Search(IReadOnlyList<AcMapEntry> maps, string words)
|
||||
{
|
||||
string[] w = words.Split(new[] { ' ', '\t', ',' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (w.Length == 0) return maps.ToList();
|
||||
return maps.Where(m => w.All(x => m.Label.Contains(x, StringComparison.OrdinalIgnoreCase)
|
||||
|| m.RelativePath.Contains(x, StringComparison.OrdinalIgnoreCase))).ToList();
|
||||
}
|
||||
}
|
||||
149
Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapSettings.cs
Normal file
149
Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapSettings.cs
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
// ============================================================================
|
||||
// RynthAi - AcMaps/AcMapSettings.cs
|
||||
// The ACMAPS maps' settings, for every character on this PC:
|
||||
// <RynthSuite>\RynthAi\acmaps.json - the maps folder, the chat line when a
|
||||
// dungeon has a map (off unless turned on), and each map's spots (keyed by
|
||||
// the image's path in the folder, so two parts of one dungeon keep their own).
|
||||
// Hand-written JSON (no reflection: RynthAi is NativeAOT).
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Install;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.AcMaps;
|
||||
|
||||
internal sealed class AcMapSettings
|
||||
{
|
||||
public const string FileName = "acmaps.json";
|
||||
public const string DefaultFolderName = "ACMaps";
|
||||
|
||||
/// <summary>Where the maps are put when the player hasn't picked a folder: <RynthSuite>\RynthAi\ACMaps.</summary>
|
||||
public static string DefaultFolder => Path.Combine(RynthInstallPaths.RynthAiDir, DefaultFolderName);
|
||||
|
||||
/// <summary>The settings file: <RynthSuite>\RynthAi\acmaps.json.</summary>
|
||||
public static string DefaultPath => Path.Combine(RynthInstallPaths.RynthAiDir, FileName);
|
||||
|
||||
/// <summary>The maps folder; empty = <see cref="DefaultFolder"/>.</summary>
|
||||
public string Folder { get; set; } = string.Empty;
|
||||
/// <summary>Say in chat when you enter a dungeon that has a map. Off by default.</summary>
|
||||
public bool Announce { get; set; }
|
||||
/// <summary>Each map's spots, by the image's path relative to the folder (case-insensitive).</summary>
|
||||
public Dictionary<string, AcMapCalibration> Maps { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public string FolderOrDefault => string.IsNullOrWhiteSpace(Folder) ? DefaultFolder : Folder;
|
||||
|
||||
/// <summary>The map's calibration, made empty the first time.</summary>
|
||||
public AcMapCalibration For(string relativePath)
|
||||
{
|
||||
if (!Maps.TryGetValue(relativePath, out AcMapCalibration? c)) Maps[relativePath] = c = new AcMapCalibration();
|
||||
return c;
|
||||
}
|
||||
|
||||
// ── JSON ─────────────────────────────────────────────────────────────
|
||||
|
||||
public string ToJson()
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("version", 1);
|
||||
w.WriteString("folder", Folder);
|
||||
w.WriteBoolean("announce", Announce);
|
||||
w.WriteStartObject("maps");
|
||||
foreach (var (path, cal) in Maps)
|
||||
{
|
||||
if (cal.IsEmpty && !cal.ScaleMeasuredOrSet) continue;
|
||||
w.WriteStartObject(path);
|
||||
w.WriteNumber("scale", Math.Round(cal.Scale, 4));
|
||||
w.WriteBoolean("scaleSet", cal.ScaleMeasuredOrSet);
|
||||
w.WriteStartArray("spots");
|
||||
foreach (MapSpot s in cal.Spots)
|
||||
{
|
||||
w.WriteStartArray();
|
||||
w.WriteNumberValue(Math.Round(s.X, 2));
|
||||
w.WriteNumberValue(Math.Round(s.Y, 2));
|
||||
w.WriteNumberValue(Math.Round(s.Z, 2));
|
||||
w.WriteNumberValue(Math.Round(s.Px, 1));
|
||||
w.WriteNumberValue(Math.Round(s.Py, 1));
|
||||
w.WriteEndArray();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndObject();
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(stream.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>The settings in <paramref name="json"/>; anything unreadable is left at its default.</summary>
|
||||
public static AcMapSettings FromJson(string json)
|
||||
{
|
||||
var s = new AcMapSettings();
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
|
||||
JsonElement root = doc.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object) return s;
|
||||
if (root.TryGetProperty("folder", out JsonElement f) && f.ValueKind == JsonValueKind.String) s.Folder = f.GetString() ?? string.Empty;
|
||||
if (root.TryGetProperty("announce", out JsonElement a) && (a.ValueKind == JsonValueKind.True || a.ValueKind == JsonValueKind.False))
|
||||
s.Announce = a.GetBoolean();
|
||||
if (root.TryGetProperty("maps", out JsonElement maps) && maps.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (JsonProperty map in maps.EnumerateObject())
|
||||
{
|
||||
if (map.Value.ValueKind != JsonValueKind.Object) continue;
|
||||
float scale = map.Value.TryGetProperty("scale", out JsonElement sc) && sc.TryGetDouble(out double d) ? (float)d : AcMapCalibration.DefaultScale;
|
||||
bool set = map.Value.TryGetProperty("scaleSet", out JsonElement ss) && ss.ValueKind == JsonValueKind.True;
|
||||
var spots = new List<MapSpot>();
|
||||
if (map.Value.TryGetProperty("spots", out JsonElement arr) && arr.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement e in arr.EnumerateArray())
|
||||
{
|
||||
if (e.ValueKind != JsonValueKind.Array || e.GetArrayLength() < 5) continue;
|
||||
var v = new float[5];
|
||||
bool ok = true;
|
||||
for (int i = 0; i < 5 && ok; i++)
|
||||
{
|
||||
ok = e[i].ValueKind == JsonValueKind.Number && e[i].TryGetDouble(out double x);
|
||||
if (ok) v[i] = (float)e[i].GetDouble();
|
||||
}
|
||||
if (ok) spots.Add(new MapSpot(v[0], v[1], v[2], v[3], v[4]));
|
||||
}
|
||||
s.Maps[map.Name] = new AcMapCalibration(scale, set, spots);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (JsonException) { }
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>The settings file, or defaults when it isn't there or can't be read. Any thread.</summary>
|
||||
public static AcMapSettings Load(string path)
|
||||
{
|
||||
try { return File.Exists(path) ? FromJson(File.ReadAllText(path, Encoding.UTF8)) : new AcMapSettings(); }
|
||||
catch { return new AcMapSettings(); }
|
||||
}
|
||||
|
||||
/// <summary>Writes the file (a temp file, then moved over). The error, or "" when saved.</summary>
|
||||
public static string Save(string path, string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
string tmp = path + ".tmp";
|
||||
File.WriteAllText(tmp, json, new UTF8Encoding(false));
|
||||
File.Move(tmp, path, overwrite: true);
|
||||
return string.Empty;
|
||||
}
|
||||
catch (Exception ex) { return ex.Message; }
|
||||
}
|
||||
|
||||
/// <summary>"3.00" for the window.</summary>
|
||||
public static string ScaleText(float scale) => scale.ToString("0.00", CultureInfo.InvariantCulture);
|
||||
}
|
||||
164
Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapTexture.cs
Normal file
164
Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapTexture.cs
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
// ============================================================================
|
||||
// RynthAi - AcMaps/AcMapTexture.cs
|
||||
// A decoded map image as D3D9 textures for ImGui, in Tile x Tile pieces
|
||||
// (power-of-two textures, so no device limit or non-power-of-two rule bites;
|
||||
// the edge pieces use part of theirs). Managed pool: they survive a device
|
||||
// reset. A few pieces are made a frame so a big map doesn't stall a frame.
|
||||
//
|
||||
// Render thread only (the D3D device isn't made for other threads). A new
|
||||
// device means the old textures belong to a dead one: they are forgotten,
|
||||
// not released, as HudIconCache does. Once every piece is made the decoded
|
||||
// pixels are let go (the managed pool keeps its own copy; the client is
|
||||
// 32-bit): a new device after that asks for the image again (NeedsReload).
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.AcMaps;
|
||||
|
||||
internal sealed unsafe class AcMapTexture
|
||||
{
|
||||
public const int Tile = 512;
|
||||
private const int TilesPerFrame = 6;
|
||||
|
||||
private const int VtRelease = 2, VtCreateTexture = 23, VtLockRect = 19, VtUnlockRect = 20;
|
||||
private const uint D3DFMT_A8R8G8B8 = 21, D3DPOOL_MANAGED = 1;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct LockedRect { public int Pitch; public IntPtr Bits; }
|
||||
|
||||
/// <summary>One piece: its texture (Zero until made, or when making it failed), where it sits and its UV corner.</summary>
|
||||
internal struct Piece
|
||||
{
|
||||
public IntPtr Tex;
|
||||
public int X, Y, W, H;
|
||||
public Vector2 Uv1;
|
||||
public bool Tried;
|
||||
}
|
||||
|
||||
private uint[]? _pixels; // until every piece is made
|
||||
private readonly int _width;
|
||||
private readonly Piece[] _pieces;
|
||||
private IntPtr _device;
|
||||
private int _made;
|
||||
|
||||
public AcMapTexture(DecodedImage image)
|
||||
{
|
||||
_pixels = image.Pixels;
|
||||
_width = image.Width;
|
||||
SourceWidth = image.SourceWidth;
|
||||
SourceHeight = image.SourceHeight;
|
||||
Factor = image.Factor;
|
||||
var list = new List<Piece>();
|
||||
for (int y = 0; y < image.Height; y += Tile)
|
||||
for (int x = 0; x < image.Width; x += Tile)
|
||||
{
|
||||
int w = Math.Min(Tile, image.Width - x), h = Math.Min(Tile, image.Height - y);
|
||||
int tw = Pow2(w), th = Pow2(h);
|
||||
list.Add(new Piece { X = x, Y = y, W = w, H = h, Uv1 = new Vector2(w / (float)tw, h / (float)th) });
|
||||
}
|
||||
_pieces = list.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>The file's size in pixels (spots and the view are in these).</summary>
|
||||
public int SourceWidth { get; }
|
||||
public int SourceHeight { get; }
|
||||
/// <summary>Decoded (piece) pixels per file pixel.</summary>
|
||||
public float Factor { get; }
|
||||
/// <summary>The device changed after the pixels were let go: decode the file again.</summary>
|
||||
public bool NeedsReload { get; private set; }
|
||||
public int PieceCount => _pieces.Length;
|
||||
/// <summary>Every piece has been made (or tried).</summary>
|
||||
public bool Complete => _made >= _pieces.Length;
|
||||
public ReadOnlySpan<Piece> Pieces => _pieces;
|
||||
|
||||
/// <summary>Makes the next few pieces on <paramref name="device"/>. Render thread, once a frame while drawn.</summary>
|
||||
public void Upload(IntPtr device)
|
||||
{
|
||||
if (device == IntPtr.Zero) return;
|
||||
if (device != _device && _device != IntPtr.Zero && _pixels == null)
|
||||
{
|
||||
NeedsReload = true;
|
||||
return;
|
||||
}
|
||||
if (device != _device)
|
||||
{
|
||||
for (int i = 0; i < _pieces.Length; i++) { _pieces[i].Tex = IntPtr.Zero; _pieces[i].Tried = false; }
|
||||
_made = 0;
|
||||
_device = device;
|
||||
}
|
||||
int budget = TilesPerFrame;
|
||||
for (int i = 0; i < _pieces.Length && budget > 0; i++)
|
||||
{
|
||||
if (_pieces[i].Tried) continue;
|
||||
_pieces[i].Tried = true;
|
||||
_pieces[i].Tex = Make(device, ref _pieces[i]);
|
||||
_made++;
|
||||
budget--;
|
||||
}
|
||||
if (_made >= _pieces.Length) _pixels = null;
|
||||
}
|
||||
|
||||
/// <summary>Releases every texture. Render thread.</summary>
|
||||
public void Release()
|
||||
{
|
||||
for (int i = 0; i < _pieces.Length; i++)
|
||||
{
|
||||
IntPtr t = _pieces[i].Tex;
|
||||
_pieces[i].Tex = IntPtr.Zero;
|
||||
_pieces[i].Tried = false;
|
||||
if (t == IntPtr.Zero || _device == IntPtr.Zero) continue;
|
||||
try { ((delegate* unmanaged[Stdcall]<IntPtr, uint>)Slot(t, VtRelease))(t); } catch { }
|
||||
}
|
||||
_made = 0;
|
||||
}
|
||||
|
||||
private IntPtr Make(IntPtr device, ref Piece p)
|
||||
{
|
||||
try
|
||||
{
|
||||
int tw = Pow2(p.W), th = Pow2(p.H);
|
||||
IntPtr tex;
|
||||
int hr = ((delegate* unmanaged[Stdcall]<IntPtr, uint, uint, uint, uint, uint, uint, IntPtr*, IntPtr, int>)Slot(device, VtCreateTexture))(
|
||||
device, (uint)tw, (uint)th, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &tex, IntPtr.Zero);
|
||||
if (hr < 0 || tex == IntPtr.Zero) return IntPtr.Zero;
|
||||
LockedRect locked;
|
||||
hr = ((delegate* unmanaged[Stdcall]<IntPtr, uint, LockedRect*, IntPtr, uint, int>)Slot(tex, VtLockRect))(tex, 0, &locked, IntPtr.Zero, 0);
|
||||
if (hr < 0)
|
||||
{
|
||||
((delegate* unmanaged[Stdcall]<IntPtr, uint>)Slot(tex, VtRelease))(tex);
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
uint[]? pixels = _pixels;
|
||||
if (pixels == null) return IntPtr.Zero;
|
||||
fixed (uint* src = pixels)
|
||||
{
|
||||
for (int row = 0; row < th; row++)
|
||||
{
|
||||
uint* dst = (uint*)((byte*)locked.Bits + (long)row * locked.Pitch);
|
||||
if (row < p.H)
|
||||
{
|
||||
Buffer.MemoryCopy(src + (long)(p.Y + row) * _width + p.X, dst, (long)tw * 4, (long)p.W * 4);
|
||||
for (int x = p.W; x < tw; x++) dst[x] = 0;
|
||||
}
|
||||
else
|
||||
for (int x = 0; x < tw; x++) dst[x] = 0;
|
||||
}
|
||||
}
|
||||
((delegate* unmanaged[Stdcall]<IntPtr, uint, int>)Slot(tex, VtUnlockRect))(tex, 0);
|
||||
return tex;
|
||||
}
|
||||
catch { return IntPtr.Zero; }
|
||||
}
|
||||
|
||||
internal static int Pow2(int v)
|
||||
{
|
||||
int p = 1;
|
||||
while (p < v) p <<= 1;
|
||||
return p;
|
||||
}
|
||||
|
||||
private static void* Slot(IntPtr com, int index) => (*(void***)com)[index];
|
||||
}
|
||||
706
Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapWindow.cs
Normal file
706
Plugins/RynthCore.Plugin.RynthAi/AcMaps/AcMapWindow.cs
Normal file
|
|
@ -0,0 +1,706 @@
|
|||
// ============================================================================
|
||||
// RynthAi - AcMaps/AcMapWindow.cs
|
||||
// The ACMAPS Maps window: the player's own ACMAPS map of the dungeon they're
|
||||
// in, with zoom, pan and their position on it once they've placed it.
|
||||
// RynthCore hosts it (the sections manifest's "acmaps" window, plugin API
|
||||
// v89; no bar button) and calls Draw through RynthPluginRenderEmbed.
|
||||
//
|
||||
// Top row: the dungeon's name and landblock; This dungeon, Maps (every map in
|
||||
// the folder, searchable), Folder (where the maps are, Browse..., Scan, the
|
||||
// chat line setting). The map: drag to pan, the wheel zooms where the cursor
|
||||
// is, Follow me keeps you in the middle. Bottom row: zoom - / + / Fit,
|
||||
// Follow me, Place me here (then click where you stand: AcMapCalibration),
|
||||
// Clear floor, the scale - / +.
|
||||
//
|
||||
// AC's render thread. Decoding is on a thread of its own (WicImage); the
|
||||
// textures are made here (AcMapTexture). Looks: Shared/RynthUi.
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Numerics;
|
||||
using System.Threading;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.Plugin.Shared.RynthUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.AcMaps;
|
||||
|
||||
/// <summary>What the window needs from RynthAi (RynthAiPlugin.AcMaps.cs).</summary>
|
||||
internal interface IAcMapsHost
|
||||
{
|
||||
AcMapIndex Index { get; }
|
||||
bool Scanning { get; }
|
||||
/// <summary>The settings; lock it to change them (the window's spots, the command's folder).</summary>
|
||||
AcMapSettings Settings { get; }
|
||||
void SetFolder(string folder);
|
||||
void Rescan();
|
||||
void SetAnnounce(bool on);
|
||||
/// <summary>Writes the settings file soon (off this thread).</summary>
|
||||
void SaveSettings();
|
||||
/// <summary>The player's cell and landblock position, compass heading (0 north, clockwise).</summary>
|
||||
bool TryPose(out uint cell, out float x, out float y, out float z, out float heading);
|
||||
IntPtr Device { get; }
|
||||
}
|
||||
|
||||
internal sealed class AcMapWindow
|
||||
{
|
||||
private const float MinZoom = 0.05f, MaxZoom = 8f;
|
||||
private const string ChooserTitle = "Choose the folder with your ACMAPS maps (the GIF or PNG files and dungeons.txt)";
|
||||
|
||||
internal const string HelpText =
|
||||
"Your own ACMAPS dungeon maps, as GoArrow showed them. RynthSuite doesn't come with the maps: " +
|
||||
"point Folder at the map pack you have (the images named by landblock, like 02CA.gif, and dungeons.txt).\n\n" +
|
||||
"In a dungeon with a map, it shows here. Drag to move it, the mouse wheel zooms.\n\n" +
|
||||
"Your position: the maps have no coordinates, so place each floor once. Stand somewhere you can find on the map " +
|
||||
"(the portal you came in by, a corner), press Place me here and click that spot. A second spot on the same floor, " +
|
||||
"some way off, measures the map's scale. Spots are saved for the map. Clear floor forgets this floor's spots.\n\n" +
|
||||
"Maps also lists every map in the folder, to look at any dungeon.\n\n" +
|
||||
"/ra acmaps opens this window; /ra acmaps folder <path>, /ra acmaps scan, /ra acmaps announce on|off.";
|
||||
|
||||
private readonly IAcMapsHost _host;
|
||||
private float _k = 1f;
|
||||
private float Px(float v) => v * _k;
|
||||
|
||||
// What is shown.
|
||||
private bool _followDungeon = true; // show the current dungeon's map (else _picked)
|
||||
private AcMapEntry? _picked;
|
||||
private int _part; // which of a dungeon's maps
|
||||
private AcMapEntry? _shown;
|
||||
private string _shownFolder = string.Empty;
|
||||
private AcMapTexture? _tex;
|
||||
private string _loadingPath = string.Empty;
|
||||
private string _loadError = string.Empty;
|
||||
private sealed record Loaded(string Path, DecodedImage? Image, string Error);
|
||||
private Loaded? _loaded; // the decode thread's result (Interlocked)
|
||||
|
||||
// View.
|
||||
private float _zoom = 1f;
|
||||
private Vector2 _center; // file pixel at the canvas centre
|
||||
private bool _fitPending; // a map just loaded: fit it, then centre on you if placed
|
||||
private bool _fitAll; // Fit: the whole map
|
||||
private bool _followMe = true;
|
||||
private bool _dragging;
|
||||
private bool _placing;
|
||||
private string _status = string.Empty;
|
||||
private long _statusUntil;
|
||||
|
||||
// Panels.
|
||||
private bool _mapsOpen, _folderOpen;
|
||||
private string _search = string.Empty;
|
||||
private string _folderText = string.Empty;
|
||||
private bool _folderTextSet;
|
||||
private volatile string? _chosenFolder;
|
||||
|
||||
public AcMapWindow(IAcMapsHost host) => _host = host;
|
||||
|
||||
/// <summary>The window was drawn this long ago: its textures go (they're remade when it shows).</summary>
|
||||
public void ReleaseTextures()
|
||||
{
|
||||
_tex?.Release();
|
||||
_tex = null;
|
||||
_shown = null;
|
||||
_loadingPath = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Draws the window body into the current ImGui window and returns the size it would like. Render thread.</summary>
|
||||
public Vector2 Draw()
|
||||
{
|
||||
_k = Math.Max(0.5f, Font(RynthUiFont.Ui11).FontSize / 11f);
|
||||
Vector2 origin = ImGui.GetCursorScreenPos();
|
||||
Vector2 size = ImGui.GetContentRegionAvail();
|
||||
var want = new Vector2(Px(620), Px(560));
|
||||
if (size.X < 80 || size.Y < 80) return want;
|
||||
|
||||
string? chosen = Interlocked.Exchange(ref _chosenFolder, null);
|
||||
if (chosen != null) { _folderText = chosen; _host.SetFolder(chosen); Say("Folder set: scanning it."); }
|
||||
|
||||
bool havePose = _host.TryPose(out uint cell, out float px, out float py, out float pz, out float heading);
|
||||
ushort here = havePose && (cell & 0xFFFF) >= 0x100 ? (ushort)(cell >> 16) : (ushort)0;
|
||||
AcMapIndex index = _host.Index;
|
||||
AcMapEntry? want_ = Choose(index, here);
|
||||
Track(index, want_);
|
||||
|
||||
ImDrawListPtr frame = ImGui.GetWindowDrawList();
|
||||
frame.AddRectFilled(origin, origin + size, Background, 4);
|
||||
using (PushFont(RynthUiFont.Ui11))
|
||||
{
|
||||
float pad = Px(6), rowH = Px(22);
|
||||
float w = size.X - pad * 2;
|
||||
Vector2 p = origin + new Vector2(pad, pad);
|
||||
DrawTop(index, here, p, w, rowH);
|
||||
p.Y += rowH + Px(4);
|
||||
DrawStatusLine(index, here, havePose, pz, p, w);
|
||||
p.Y += Px(18);
|
||||
float bottomH = rowH + Px(6);
|
||||
float canvasH = Math.Max(Px(40), origin.Y + size.Y - pad - bottomH - p.Y - Px(8));
|
||||
var cmin = p;
|
||||
var cmax = p + new Vector2(w, canvasH);
|
||||
bool onThisMap = _shown != null && here != 0 && _shown.Landblock == here;
|
||||
// The map takes the mouse only where no panel lies over it (ImGui gives a press to the first
|
||||
// item under it, and the canvas is drawn first).
|
||||
Vector2 inputMin = cmin;
|
||||
if (_mapsOpen) inputMin.X = cmin.X + MapsPanelWidth(cmin, cmax) + Px(6);
|
||||
if (_folderOpen) inputMin.Y = cmin.Y + FolderPanelHeight(cmin, cmax) + Px(6);
|
||||
DrawCanvas(cmin, cmax, inputMin, onThisMap, havePose, px, py, pz, heading);
|
||||
if (_mapsOpen) DrawMapsPanel(index, cmin, cmax);
|
||||
if (_folderOpen) DrawFolderPanel(index, cmin, cmax);
|
||||
DrawBottom(new Vector2(p.X, cmax.Y + Px(6)), w, rowH, onThisMap, havePose, pz);
|
||||
}
|
||||
frame.AddRect(origin, origin + size, Border, 4);
|
||||
return want;
|
||||
}
|
||||
|
||||
// ── What to show ────────────────────────────────────────────────────
|
||||
|
||||
private AcMapEntry? Choose(AcMapIndex index, ushort here)
|
||||
{
|
||||
if (!_followDungeon) return _picked;
|
||||
if (here == 0) return null;
|
||||
IReadOnlyList<AcMapEntry> maps = index.ForLandblock(here);
|
||||
if (maps.Count == 0) return null;
|
||||
return maps[Math.Clamp(_part, 0, maps.Count - 1)];
|
||||
}
|
||||
|
||||
/// <summary>Starts loading the map to show, takes a finished decode, makes its textures.</summary>
|
||||
private void Track(AcMapIndex index, AcMapEntry? entry)
|
||||
{
|
||||
Loaded? done = Interlocked.Exchange(ref _loaded, null);
|
||||
string path = entry == null ? string.Empty : Path.Combine(index.Folder, entry.RelativePath);
|
||||
if (done != null && done.Path == _loadingPath && done.Path == path)
|
||||
{
|
||||
_tex?.Release();
|
||||
_tex = done.Image != null ? new AcMapTexture(done.Image) : null;
|
||||
_loadError = done.Error;
|
||||
_loadingPath = string.Empty;
|
||||
_fitPending = true;
|
||||
}
|
||||
bool same = _shown != null && entry != null && _shown.RelativePath == entry.RelativePath && _shownFolder == index.Folder;
|
||||
if (!same)
|
||||
{
|
||||
_tex?.Release();
|
||||
_tex = null;
|
||||
_shown = entry;
|
||||
_shownFolder = index.Folder;
|
||||
_loadError = string.Empty;
|
||||
_placing = false;
|
||||
_loadingPath = string.Empty;
|
||||
if (entry != null)
|
||||
{
|
||||
_loadingPath = path;
|
||||
string p = path;
|
||||
// A decode for a map no longer wanted (the player moved on) is dropped, so it can't
|
||||
// take the slot from the one that is.
|
||||
WicImage.DecodeAsync(p, (img, err) =>
|
||||
{
|
||||
if (p == Volatile.Read(ref _loadingPath)) Interlocked.Exchange(ref _loaded, new Loaded(p, img, err));
|
||||
});
|
||||
}
|
||||
}
|
||||
_tex?.Upload(_host.Device);
|
||||
if (_tex is { NeedsReload: true })
|
||||
{
|
||||
// A new D3D device after the pixels were let go: read the file again.
|
||||
_tex = null;
|
||||
_shown = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Top row ─────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawTop(AcMapIndex index, ushort here, Vector2 p, float w, float h)
|
||||
{
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
const string thisLabel = "This dungeon", mapsLabel = "Maps", folderLabel = "Folder";
|
||||
float bw1 = ButtonWidth(thisLabel), bw2 = ButtonWidth(mapsLabel), bw3 = ButtonWidth(folderLabel), helpW = h;
|
||||
float right = p.X + w;
|
||||
float x3 = right - helpW - Px(4) - bw3, x2 = x3 - Px(4) - bw2, x1 = x2 - Px(4) - bw1;
|
||||
|
||||
string title = _shown != null ? _shown.Label
|
||||
: _followDungeon && here != 0 ? (index.NameOf(here) is { Length: > 0 } n ? $"{n} ({here:X4})" : $"Dungeon {here:X4}")
|
||||
: _followDungeon ? "Not in a dungeon" : "No map picked";
|
||||
using (PushFont(RynthUiFont.Ui14))
|
||||
{
|
||||
dl.PushClipRect(p, new Vector2(x1 - Px(6), p.Y + h), true);
|
||||
float th = ImGui.GetFontSize();
|
||||
dl.AddText(new Vector2(p.X, p.Y + (h - th) * 0.5f), Text, title);
|
||||
dl.PopClipRect();
|
||||
}
|
||||
IReadOnlyList<AcMapEntry> parts = _followDungeon && here != 0 ? index.ForLandblock(here) : Array.Empty<AcMapEntry>();
|
||||
if (parts.Count > 1)
|
||||
{
|
||||
// A dungeon with more than one map: which part.
|
||||
float pw = Px(70);
|
||||
float tx = x1 - Px(8) - pw;
|
||||
if (Button("##am_part", $"Map {Math.Clamp(_part, 0, parts.Count - 1) + 1} of {parts.Count}", new Vector2(tx, p.Y), new Vector2(pw, h), Text, ButtonFill))
|
||||
_part = (Math.Clamp(_part, 0, parts.Count - 1) + 1) % parts.Count;
|
||||
SafeImGui.SetItemTooltip("This dungeon has " + parts.Count + " maps: show the next.");
|
||||
}
|
||||
if (Button("##am_here", thisLabel, new Vector2(x1, p.Y), new Vector2(bw1, h), Text, _followDungeon ? AccentFill : ButtonFill))
|
||||
{
|
||||
_followDungeon = true;
|
||||
_mapsOpen = false;
|
||||
_followMe = true;
|
||||
}
|
||||
SafeImGui.SetItemTooltip("Show the map of the dungeon you're in (changes as you go).");
|
||||
if (Button("##am_maps", mapsLabel, new Vector2(x2, p.Y), new Vector2(bw2, h), Text, _mapsOpen ? AccentFill : ButtonFill))
|
||||
{
|
||||
_mapsOpen = !_mapsOpen;
|
||||
if (_mapsOpen) _folderOpen = false;
|
||||
}
|
||||
SafeImGui.SetItemTooltip("Every map in your folder: pick one to look at.");
|
||||
if (Button("##am_folder", folderLabel, new Vector2(x3, p.Y), new Vector2(bw3, h), Text, _folderOpen ? AccentFill : ButtonFill))
|
||||
{
|
||||
_folderOpen = !_folderOpen;
|
||||
if (_folderOpen) _mapsOpen = false;
|
||||
}
|
||||
SafeImGui.SetItemTooltip("Where your ACMAPS maps are, and the chat line setting.");
|
||||
IconButton("##am_help", RynthIcons.Info, new Vector2(right - helpW, p.Y), new Vector2(helpW, h), Mute, ButtonFill, font: RynthUiFont.Ui11);
|
||||
SafeImGui.SetItemTooltip(HelpText);
|
||||
}
|
||||
|
||||
private void DrawStatusLine(AcMapIndex index, ushort here, bool havePose, float z, Vector2 p, float w)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
string line;
|
||||
uint color = Mute;
|
||||
if (_status.Length > 0 && now < _statusUntil) { line = _status; color = Highlight; }
|
||||
else if (_host.Scanning) line = "Reading the maps folder...";
|
||||
else if (index.Maps.Count == 0)
|
||||
{
|
||||
line = index.Folder.Length == 0 && index.Problems.Count == 0
|
||||
? "No maps yet: press Folder and choose your ACMAPS map pack."
|
||||
: (index.Problems.Count > 0 ? index.Problems[0] + " " : string.Empty) + "Press Folder to choose another.";
|
||||
color = index.Problems.Count > 0 ? Red : Mute;
|
||||
}
|
||||
else if (_shown == null && _followDungeon)
|
||||
line = here == 0 ? "You're not in a dungeon. Maps lists every map in your folder."
|
||||
: $"No ACMAPS map for this dungeon ({here:X4}) in your folder.";
|
||||
else if (_loadError.Length > 0) { line = _loadError; color = Red; }
|
||||
else if (_loadingPath.Length > 0) line = "Loading the map...";
|
||||
else if (_placing) { line = "Click the spot on the map where you're standing (Esc: stop)."; color = Highlight; }
|
||||
else if (_shown != null && here != 0 && _shown.Landblock == here)
|
||||
{
|
||||
AcMapCalibration cal = Calibration(_shown);
|
||||
line = !havePose ? "Your position can't be read right now."
|
||||
: cal.FloorPlaced(z) ? (cal.ScaleMeasuredOrSet || cal.FloorSpots(z).Count >= 2
|
||||
? "You're the green arrow."
|
||||
: "You're the green arrow. A second spot on this floor, some way off, makes it exact.")
|
||||
: "This floor isn't placed: stand somewhere you can find on the map, press Place me here, click that spot.";
|
||||
}
|
||||
else line = _shown?.Notes is { Length: > 0 } notes ? notes : "Looking at another dungeon's map.";
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
dl.PushClipRect(p, p + new Vector2(w, Px(16)), true);
|
||||
dl.AddText(p, color, line);
|
||||
dl.PopClipRect();
|
||||
if (ImGui.IsMouseHoveringRect(p, p + new Vector2(w, Px(16))) && line.Length > 60) SafeImGui.SetTooltip(line);
|
||||
}
|
||||
|
||||
// ── The map ─────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawCanvas(Vector2 cmin, Vector2 cmax, Vector2 inputMin, bool onThisMap, bool havePose, float px, float py, float pz, float heading)
|
||||
{
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
dl.AddRectFilled(cmin, cmax, Field, 3);
|
||||
Vector2 csize = cmax - cmin;
|
||||
Vector2 mid = cmin + csize * 0.5f;
|
||||
bool hovered = false, active = false;
|
||||
Vector2 inputSize = cmax - inputMin;
|
||||
if (inputSize.X >= 4 && inputSize.Y >= 4)
|
||||
{
|
||||
ImGui.SetCursorScreenPos(inputMin);
|
||||
ImGui.InvisibleButton("##am_canvas", inputSize);
|
||||
hovered = ImGui.IsItemHovered();
|
||||
active = ImGui.IsItemActive();
|
||||
}
|
||||
|
||||
AcMapTexture? tex = _tex;
|
||||
if (tex == null)
|
||||
{
|
||||
dl.AddRect(cmin, cmax, Border, 3);
|
||||
return;
|
||||
}
|
||||
float factor = tex.Factor; // decoded per file pixel
|
||||
var fileSize = new Vector2(tex.SourceWidth, tex.SourceHeight);
|
||||
if (_fitAll)
|
||||
{
|
||||
_fitAll = false;
|
||||
Fit(fileSize, csize);
|
||||
}
|
||||
if (_fitPending)
|
||||
{
|
||||
_fitPending = false;
|
||||
Fit(fileSize, csize);
|
||||
if (onThisMap && havePose && Calibration(_shown!).TryToImage(px, py, pz, out Vector2 me))
|
||||
{
|
||||
_center = me;
|
||||
_zoom = Math.Max(_zoom, 1f);
|
||||
}
|
||||
}
|
||||
|
||||
AcMapCalibration cal = Calibration(_shown!);
|
||||
Vector2 mePx = default;
|
||||
bool meKnown = onThisMap && havePose && cal.TryToImage(px, py, pz, out mePx);
|
||||
|
||||
// Input: drag pans (Follow me off), the wheel zooms at the cursor, a click places when armed.
|
||||
ImGuiIOPtr io = ImGui.GetIO();
|
||||
if (active && ImGui.IsMouseDragging(ImGuiMouseButton.Left, 3f))
|
||||
{
|
||||
_dragging = true;
|
||||
_followMe = false;
|
||||
_center -= io.MouseDelta / _zoom;
|
||||
}
|
||||
if (hovered && io.MouseWheel != 0)
|
||||
{
|
||||
Vector2 before = ToFile(io.MousePos, mid);
|
||||
_zoom = Math.Clamp(_zoom * MathF.Pow(1.2f, io.MouseWheel), MinZoom, MaxZoom);
|
||||
if (!_followMe || !meKnown) _center += before - ToFile(io.MousePos, mid);
|
||||
}
|
||||
bool clicked = hovered && ImGui.IsMouseReleased(ImGuiMouseButton.Left) && !_dragging;
|
||||
if (!ImGui.IsMouseDown(ImGuiMouseButton.Left)) _dragging = false;
|
||||
if (_placing && ImGui.IsKeyPressed(ImGuiKey.Escape)) { _placing = false; Say("Stopped placing."); }
|
||||
if (_placing && clicked)
|
||||
{
|
||||
Vector2 at = ToFile(io.MousePos, mid);
|
||||
if (!onThisMap || !havePose) Say("Placing needs you in this map's dungeon.");
|
||||
else if (at.X < 0 || at.Y < 0 || at.X > fileSize.X || at.Y > fileSize.Y) Say("That's off the map: click on the map.");
|
||||
else
|
||||
{
|
||||
PlaceResult r;
|
||||
lock (_host.Settings) r = cal.Place(px, py, pz, at.X, at.Y);
|
||||
_host.SaveSettings();
|
||||
_placing = false;
|
||||
_followMe = true;
|
||||
Say(r switch
|
||||
{
|
||||
PlaceResult.FloorPlaced => "Floor placed. A second spot on this floor, some way off, measures the scale.",
|
||||
PlaceResult.Moved => "Spot moved (it was near the last one).",
|
||||
PlaceResult.ScaleMeasured => "Scale measured from two spots: " + AcMapSettings.ScaleText(cal.Scale) + " pixels a unit.",
|
||||
_ => "Those two spots don't fit a north-up map: the new spot places the floor on its own.",
|
||||
});
|
||||
meKnown = cal.TryToImage(px, py, pz, out mePx);
|
||||
}
|
||||
}
|
||||
if (_followMe && meKnown && !_dragging) _center = mePx;
|
||||
ClampCenter(fileSize);
|
||||
|
||||
// The image, piece by piece, culled to the canvas.
|
||||
dl.PushClipRect(cmin, cmax, true);
|
||||
ReadOnlySpan<AcMapTexture.Piece> pieces = tex.Pieces;
|
||||
int missing = 0;
|
||||
foreach (AcMapTexture.Piece piece in pieces)
|
||||
{
|
||||
if (piece.Tex == IntPtr.Zero) { if (!piece.Tried) missing++; continue; }
|
||||
Vector2 a = ToScreen(new Vector2(piece.X, piece.Y) / factor, mid);
|
||||
Vector2 b = ToScreen(new Vector2(piece.X + piece.W, piece.Y + piece.H) / factor, mid);
|
||||
if (b.X < cmin.X || b.Y < cmin.Y || a.X > cmax.X || a.Y > cmax.Y) continue;
|
||||
dl.AddImage(piece.Tex, a, b, Vector2.Zero, piece.Uv1);
|
||||
}
|
||||
|
||||
// The spots of this floor while placing (so a bad one can be clicked again).
|
||||
if (_placing && onThisMap && havePose)
|
||||
foreach (MapSpot s in cal.FloorSpots(pz))
|
||||
{
|
||||
Vector2 sp = ToScreen(new Vector2(s.Px, s.Py), mid);
|
||||
dl.AddCircle(sp, Px(6), Highlight, 12, 2f);
|
||||
}
|
||||
|
||||
// You: a green arrow pointing your way (north up).
|
||||
if (meKnown)
|
||||
{
|
||||
Vector2 c = ToScreen(mePx, mid);
|
||||
float rad = heading * MathF.PI / 180f;
|
||||
var fwd = new Vector2(MathF.Sin(rad), -MathF.Cos(rad));
|
||||
var side = new Vector2(-fwd.Y, fwd.X);
|
||||
float len = Px(11), half = Px(6);
|
||||
Vector2 tip = c + fwd * len, l = c - fwd * Px(5) + side * half, r = c - fwd * Px(5) - side * half;
|
||||
uint green = Green;
|
||||
dl.AddTriangleFilled(tip, l, r, WithAlpha(green, 0xE6));
|
||||
dl.AddTriangle(tip, l, r, 0xFF000000, 1.5f);
|
||||
dl.AddCircleFilled(c, Px(2.5f), 0xFF000000);
|
||||
}
|
||||
if (missing > 0)
|
||||
dl.AddText(cmin + new Vector2(Px(6), Px(4)), Mute, "Drawing the map...");
|
||||
|
||||
// Under the cursor: the landblock position, when the floor is placed.
|
||||
if (hovered && onThisMap && havePose && cal.FloorPlaced(pz) && cal.TryToWorld(ToFile(io.MousePos, mid), pz, out float wx, out float wy))
|
||||
{
|
||||
string t = string.Format(CultureInfo.InvariantCulture, "{0:0.0}, {1:0.0}", wx, wy);
|
||||
Vector2 ts = ImGui.CalcTextSize(t);
|
||||
Vector2 tp = new(cmax.X - ts.X - Px(6), cmax.Y - ts.Y - Px(4));
|
||||
dl.AddRectFilled(tp - new Vector2(Px(3), Px(1)), tp + ts + new Vector2(Px(3), Px(1)), WithAlpha(Background, 0xC0), 2);
|
||||
dl.AddText(tp, Mute, t);
|
||||
}
|
||||
dl.PopClipRect();
|
||||
dl.AddRect(cmin, cmax, _placing ? Highlight : Border, 3, ImDrawFlags.None, _placing ? 2f : 1f);
|
||||
if (_placing && hovered) ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
|
||||
}
|
||||
|
||||
private Vector2 ToScreen(Vector2 file, Vector2 mid) => mid + (file - _center) * _zoom;
|
||||
private Vector2 ToFile(Vector2 screen, Vector2 mid) => _center + (screen - mid) / _zoom;
|
||||
|
||||
private void Fit(Vector2 fileSize, Vector2 canvas)
|
||||
{
|
||||
if (fileSize.X <= 0 || fileSize.Y <= 0) return;
|
||||
_zoom = Math.Clamp(Math.Min(canvas.X / fileSize.X, canvas.Y / fileSize.Y), MinZoom, MaxZoom);
|
||||
_center = fileSize * 0.5f;
|
||||
}
|
||||
|
||||
private void ClampCenter(Vector2 fileSize)
|
||||
{
|
||||
_center = Vector2.Clamp(_center, Vector2.Zero, fileSize);
|
||||
if (!float.IsFinite(_center.X) || !float.IsFinite(_center.Y)) _center = fileSize * 0.5f;
|
||||
}
|
||||
|
||||
// ── Bottom row ──────────────────────────────────────────────────────
|
||||
|
||||
private void DrawBottom(Vector2 p, float w, float h, bool onThisMap, bool havePose, float pz)
|
||||
{
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
bool haveMap = _tex != null;
|
||||
float x = p.X, sq = h, gap = Px(4);
|
||||
if (Button("##am_zout", "-", new Vector2(x, p.Y), new Vector2(sq, h), Text, ButtonFill, haveMap)) Zoom(1f / 1.25f);
|
||||
SafeImGui.SetItemTooltip("Zoom out (or the mouse wheel).");
|
||||
x += sq + gap;
|
||||
string zt = Math.Round(_zoom * 100).ToString(CultureInfo.InvariantCulture) + "%";
|
||||
float zw = Px(44);
|
||||
Vector2 zs = ImGui.CalcTextSize(zt);
|
||||
dl.AddText(new Vector2(x + (zw - zs.X) * 0.5f, p.Y + (h - zs.Y) * 0.5f), haveMap ? Text : Faded(Text), zt);
|
||||
x += zw + gap;
|
||||
if (Button("##am_zin", "+", new Vector2(x, p.Y), new Vector2(sq, h), Text, ButtonFill, haveMap)) Zoom(1.25f);
|
||||
SafeImGui.SetItemTooltip("Zoom in (or the mouse wheel).");
|
||||
x += sq + gap;
|
||||
const string fitLabel = "Fit";
|
||||
float fw = ButtonWidth(fitLabel);
|
||||
if (Button("##am_fit", fitLabel, new Vector2(x, p.Y), new Vector2(fw, h), Text, ButtonFill, haveMap))
|
||||
{
|
||||
_followMe = false;
|
||||
_fitAll = true; // fitted to the canvas as it is drawn
|
||||
}
|
||||
SafeImGui.SetItemTooltip("The whole map in the window.");
|
||||
x += fw + gap * 2;
|
||||
|
||||
AcMapCalibration? cal = _shown != null ? Calibration(_shown) : null;
|
||||
bool canPlace = haveMap && onThisMap && havePose;
|
||||
const string followLabel = "Follow me";
|
||||
float folw = ButtonWidth(followLabel);
|
||||
bool meKnown = canPlace && cal!.FloorPlaced(pz);
|
||||
if (Button("##am_follow", followLabel, new Vector2(x, p.Y), new Vector2(folw, h), Text, _followMe && meKnown ? AccentFill : ButtonFill, meKnown))
|
||||
_followMe = !_followMe;
|
||||
SafeImGui.SetItemTooltip(meKnown ? "Keep you in the middle of the map (dragging the map turns it off)."
|
||||
: "Needs this floor placed (Place me here).");
|
||||
x += folw + gap;
|
||||
|
||||
const string placeLabel = "Place me here";
|
||||
float plw = ButtonWidth(placeLabel);
|
||||
if (Button("##am_place", placeLabel, new Vector2(x, p.Y), new Vector2(plw, h), Text, _placing ? AccentFill : ButtonFill, canPlace))
|
||||
{
|
||||
_placing = !_placing;
|
||||
if (_placing) Say("Now click the spot on the map where you're standing.");
|
||||
}
|
||||
SafeImGui.SetItemTooltip(canPlace
|
||||
? "Stand somewhere you can find on the map (a portal, a corner), press this, then click that spot on the map.\n" +
|
||||
"Once per floor; a second spot on a floor, some way off, measures the scale."
|
||||
: "Needs you in this map's dungeon, with the map loaded.");
|
||||
x += plw + gap;
|
||||
|
||||
const string clearLabel = "Clear floor";
|
||||
float clw = ButtonWidth(clearLabel);
|
||||
bool canClear = canPlace && cal!.FloorPlaced(pz);
|
||||
if (Button("##am_clear", clearLabel, new Vector2(x, p.Y), new Vector2(clw, h), Text, ButtonFill, canClear))
|
||||
{
|
||||
lock (_host.Settings) cal!.ClearFloor(pz);
|
||||
_host.SaveSettings();
|
||||
Say("This floor's spots are cleared.");
|
||||
}
|
||||
SafeImGui.SetItemTooltip("Forget this floor's spots (to place it again).");
|
||||
x += clw + gap * 2;
|
||||
|
||||
// Scale: - 3.00 +
|
||||
float right = p.X + w;
|
||||
float sw = Px(40);
|
||||
float need = sq * 2 + sw + gap * 2;
|
||||
if (x + need <= right && cal != null)
|
||||
{
|
||||
float sx = right - need;
|
||||
bool canScale = haveMap;
|
||||
if (Button("##am_sdn", "-", new Vector2(sx, p.Y), new Vector2(sq, h), Text, ButtonFill, canScale))
|
||||
{
|
||||
lock (_host.Settings) cal.NudgeScale(1f / 1.02f);
|
||||
_host.SaveSettings();
|
||||
}
|
||||
SafeImGui.SetItemTooltip("The map's scale, a little smaller (when the arrow runs ahead of you).");
|
||||
string st = AcMapSettings.ScaleText(cal.Scale);
|
||||
Vector2 ss = ImGui.CalcTextSize(st);
|
||||
dl.AddText(new Vector2(sx + sq + gap + (sw - ss.X) * 0.5f, p.Y + (h - ss.Y) * 0.5f), cal.ScaleMeasuredOrSet ? Text : Mute, st);
|
||||
if (ImGui.IsMouseHoveringRect(new Vector2(sx + sq + gap, p.Y), new Vector2(sx + sq + gap + sw, p.Y + h)))
|
||||
SafeImGui.SetTooltip(cal.ScaleMeasuredOrSet ? "Map pixels for each unit you walk (measured or set)."
|
||||
: "Map pixels for each unit you walk: GoArrow's 3 until a second spot measures it.");
|
||||
if (Button("##am_sup", "+", new Vector2(sx + sq + gap * 2 + sw, p.Y), new Vector2(sq, h), Text, ButtonFill, canScale))
|
||||
{
|
||||
lock (_host.Settings) cal.NudgeScale(1.02f);
|
||||
_host.SaveSettings();
|
||||
}
|
||||
SafeImGui.SetItemTooltip("The map's scale, a little bigger (when the arrow lags behind you).");
|
||||
}
|
||||
}
|
||||
|
||||
private void Zoom(float k) => _zoom = Math.Clamp(_zoom * k, MinZoom, MaxZoom);
|
||||
|
||||
// ── Maps panel ──────────────────────────────────────────────────────
|
||||
|
||||
private float MapsPanelWidth(Vector2 cmin, Vector2 cmax) => Math.Min(Px(280), (cmax.X - cmin.X) * 0.7f);
|
||||
|
||||
private float FolderPanelHeight(Vector2 cmin, Vector2 cmax) => Math.Min(cmax.Y - cmin.Y - Px(8), Px(250));
|
||||
|
||||
private void DrawMapsPanel(AcMapIndex index, Vector2 cmin, Vector2 cmax)
|
||||
{
|
||||
float pw = MapsPanelWidth(cmin, cmax);
|
||||
Vector2 a = cmin + new Vector2(Px(4), Px(4)), b = new(cmin.X + pw, cmax.Y - Px(4));
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
dl.AddRectFilled(a, b, WithAlpha(Background, 0xF0), 4);
|
||||
dl.AddRect(a, b, Border, 4);
|
||||
ImGui.SetCursorScreenPos(a + new Vector2(Px(6), Px(6)));
|
||||
ImGui.PushItemWidth(pw - Px(16));
|
||||
ImGui.InputTextWithHint("##am_search", "Find a map: a name or landblock", ref _search, 64u);
|
||||
ImGui.PopItemWidth();
|
||||
List<AcMapEntry> hits = AcMapIndex.Search(index.Maps, _search);
|
||||
Vector2 listPos = ImGui.GetCursorScreenPos();
|
||||
ImGui.SetCursorScreenPos(new Vector2(a.X + Px(6), listPos.Y + Px(2)));
|
||||
ImGui.BeginChild("##am_list", new Vector2(pw - Px(12), Math.Max(Px(20), b.Y - listPos.Y - Px(8))));
|
||||
if (hits.Count == 0) Label(index.Maps.Count == 0 ? "No maps in the folder." : "No map matches.", Mute);
|
||||
int i = 0;
|
||||
foreach (AcMapEntry e in hits)
|
||||
{
|
||||
bool sel = _shown != null && _shown.RelativePath == e.RelativePath;
|
||||
if (ImGui.Selectable(SafeLabel(e.Label) + "##am_e" + i, sel))
|
||||
{
|
||||
_followDungeon = false;
|
||||
_picked = e;
|
||||
_followMe = false;
|
||||
_mapsOpen = false;
|
||||
}
|
||||
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(e.RelativePath + (e.Notes.Length > 0 ? "\n" + e.Notes : string.Empty));
|
||||
i++;
|
||||
}
|
||||
ImGui.EndChild();
|
||||
}
|
||||
|
||||
// ── Folder panel ────────────────────────────────────────────────────
|
||||
|
||||
private void DrawFolderPanel(AcMapIndex index, Vector2 cmin, Vector2 cmax)
|
||||
{
|
||||
AcMapSettings s = _host.Settings;
|
||||
string current;
|
||||
bool announce;
|
||||
lock (s) { current = s.FolderOrDefault; announce = s.Announce; }
|
||||
if (!_folderTextSet) { _folderText = current; _folderTextSet = true; }
|
||||
float w = cmax.X - cmin.X - Px(8);
|
||||
Vector2 a = cmin + new Vector2(Px(4), Px(4));
|
||||
float h = FolderPanelHeight(cmin, cmax);
|
||||
Vector2 b = a + new Vector2(w, h);
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
dl.AddRectFilled(a, b, WithAlpha(Background, 0xF4), 4);
|
||||
dl.AddRect(a, b, Border, 4);
|
||||
float pad = Px(8), rowH = Px(22);
|
||||
Vector2 p = a + new Vector2(pad, pad);
|
||||
float iw = w - pad * 2;
|
||||
dl.AddText(p, Text, "Your ACMAPS maps folder");
|
||||
p.Y += Px(18);
|
||||
|
||||
const string browse = "Browse...", useDefault = "Default", scan = "Scan";
|
||||
float bw = ButtonWidth(browse), dw = ButtonWidth(useDefault), sw = ButtonWidth(scan);
|
||||
float boxW = iw - bw - dw - sw - Px(12);
|
||||
ImGui.SetCursorScreenPos(p);
|
||||
ImGui.PushItemWidth(Math.Max(Px(60), boxW));
|
||||
bool enter = ImGui.InputText("##am_folderbox", ref _folderText, 260u, ImGuiInputTextFlags.EnterReturnsTrue);
|
||||
ImGui.PopItemWidth();
|
||||
SafeImGui.SetItemTooltip("Type or paste the folder, then Enter (or Scan).");
|
||||
float bx = p.X + boxW + Px(4);
|
||||
bool picking = FolderPicker.IsOpen;
|
||||
if (Button("##am_browse", picking ? "Open..." : browse, new Vector2(bx, p.Y), new Vector2(bw, rowH), Text, ButtonFill, !picking))
|
||||
{
|
||||
string start = Directory.Exists(_folderText) ? _folderText : current;
|
||||
if (!FolderPicker.Pick(ChooserTitle, start, f => { if (f != null) _chosenFolder = f; }))
|
||||
Say("A folder chooser is already open.");
|
||||
else Say("The folder chooser is open (in full screen it may be behind the game: Alt+Tab).");
|
||||
}
|
||||
SafeImGui.SetItemTooltip("Choose the folder in Windows' folder chooser.");
|
||||
bx += bw + Px(4);
|
||||
if (Button("##am_default", useDefault, new Vector2(bx, p.Y), new Vector2(dw, rowH), Text, ButtonFill))
|
||||
{
|
||||
_folderText = AcMapSettings.DefaultFolder;
|
||||
enter = true;
|
||||
}
|
||||
SafeImGui.SetItemTooltip("RynthSuite's own maps folder: " + AcMapSettings.DefaultFolder + "\n(copy your map pack into it; it is made if it isn't there).");
|
||||
bx += dw + Px(4);
|
||||
bool doScan = Button("##am_scan", scan, new Vector2(bx, p.Y), new Vector2(sw, rowH), Text, ButtonFill, !_host.Scanning);
|
||||
SafeImGui.SetItemTooltip("Read the folder again (after adding maps).");
|
||||
if (enter || doScan)
|
||||
{
|
||||
string f = _folderText.Trim().Trim('"');
|
||||
if (f.Length == 0) f = AcMapSettings.DefaultFolder;
|
||||
if (!string.Equals(f, current, StringComparison.OrdinalIgnoreCase)) { _host.SetFolder(f); Say("Folder set: scanning it."); }
|
||||
else { _host.Rescan(); Say("Scanning the folder."); }
|
||||
}
|
||||
p.Y += rowH + Px(6);
|
||||
|
||||
string summary = _host.Scanning ? "Reading the folder..." : index.Summary();
|
||||
dl.AddText(p, Mute, summary);
|
||||
p.Y += Px(16);
|
||||
foreach (string problem in index.Problems)
|
||||
{
|
||||
dl.PushClipRect(p, p + new Vector2(iw, Px(16)), true);
|
||||
dl.AddText(p, Red, problem);
|
||||
dl.PopClipRect();
|
||||
p.Y += Px(16);
|
||||
if (p.Y > b.Y - Px(80)) break;
|
||||
}
|
||||
p.Y += Px(4);
|
||||
ImGui.SetCursorScreenPos(p);
|
||||
bool a2 = announce;
|
||||
if (ImGui.Checkbox("Say in chat when a dungeon has an ACMAPS map##am_announce", ref a2)) _host.SetAnnounce(a2);
|
||||
SafeImGui.SetItemTooltip("A line in chat as you enter a dungeon your folder has a map for (off unless you turn it on).");
|
||||
p.Y += rowH + Px(8);
|
||||
ImGui.SetCursorScreenPos(p);
|
||||
ImGui.PushTextWrapPos(a.X + w - pad);
|
||||
ImGui.PushStyleColor(ImGuiCol.Text, Mute);
|
||||
SafeImGui.TextWrapped("The maps are ACMAPS', made by its players and kept by the AC community; RynthSuite doesn't come with them. " +
|
||||
"A pack is the images named by landblock (02CA.gif) and dungeons.txt. GoArrow's \"Dungeon Map Cache\" folder works as it is.");
|
||||
ImGui.PopStyleColor();
|
||||
ImGui.PopTextWrapPos();
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
private AcMapCalibration Calibration(AcMapEntry e)
|
||||
{
|
||||
lock (_host.Settings) return _host.Settings.For(e.RelativePath);
|
||||
}
|
||||
|
||||
private void Say(string text)
|
||||
{
|
||||
_status = text;
|
||||
_statusUntil = Environment.TickCount64 + 6000;
|
||||
}
|
||||
|
||||
private static string SafeLabel(string s) => s.Replace("##", "# ");
|
||||
|
||||
/// <summary>"/ra acmaps" with a map named: show it (not following the dungeon).</summary>
|
||||
public void Show(AcMapEntry entry)
|
||||
{
|
||||
_followDungeon = false;
|
||||
_picked = entry;
|
||||
_followMe = false;
|
||||
}
|
||||
|
||||
/// <summary>Back to the dungeon you're in.</summary>
|
||||
public void FollowDungeon()
|
||||
{
|
||||
_followDungeon = true;
|
||||
_followMe = true;
|
||||
}
|
||||
}
|
||||
118
Plugins/RynthCore.Plugin.RynthAi/AcMaps/FolderPicker.cs
Normal file
118
Plugins/RynthCore.Plugin.RynthAi/AcMaps/FolderPicker.cs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
// ============================================================================
|
||||
// RynthAi - AcMaps/FolderPicker.cs
|
||||
// The ACMAPS window's "Browse..." button: Windows' folder chooser, on its own
|
||||
// STA thread so the game keeps running while it is open (it isn't owned by the
|
||||
// game window, so it never freezes it). In full-screen it may open behind the
|
||||
// game: the folder box beside the button takes a typed or pasted path too.
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.AcMaps;
|
||||
|
||||
internal static unsafe class FolderPicker
|
||||
{
|
||||
private const uint BifReturnOnlyFsDirs = 0x0001, BifEditBox = 0x0010, BifNewDialogStyle = 0x0040;
|
||||
private const uint BffmInitialized = 1, BffmSetSelectionW = 0x0400 + 103;
|
||||
private const int MaxPath = 260;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct BrowseInfo
|
||||
{
|
||||
public IntPtr Owner;
|
||||
public IntPtr Root;
|
||||
public char* DisplayName;
|
||||
public char* Title;
|
||||
public uint Flags;
|
||||
public IntPtr Callback;
|
||||
public IntPtr Param;
|
||||
public int Image;
|
||||
}
|
||||
|
||||
[DllImport("shell32.dll")] private static extern IntPtr SHBrowseForFolderW(BrowseInfo* info);
|
||||
[DllImport("shell32.dll")] private static extern int SHGetPathFromIDListW(IntPtr pidl, char* path);
|
||||
[DllImport("ole32.dll")] private static extern void CoTaskMemFree(IntPtr p);
|
||||
[DllImport("ole32.dll")] private static extern int OleInitialize(IntPtr reserved);
|
||||
[DllImport("ole32.dll")] private static extern void OleUninitialize();
|
||||
[DllImport("user32.dll")] private static extern IntPtr SendMessageW(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
[DllImport("user32.dll")] private static extern int SetForegroundWindow(IntPtr hwnd);
|
||||
|
||||
private static int _open;
|
||||
|
||||
/// <summary>A chooser is open now (one at a time).</summary>
|
||||
public static bool IsOpen => Volatile.Read(ref _open) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Opens the chooser starting at <paramref name="start"/>; <paramref name="done"/> gets the folder chosen, or
|
||||
/// null when cancelled, on the chooser's thread. False when one is already open.
|
||||
/// </summary>
|
||||
public static bool Pick(string title, string start, Action<string?> done)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _open, 1) != 0) return false;
|
||||
var t = new Thread(() =>
|
||||
{
|
||||
string? chosen = null;
|
||||
try { chosen = Run(title, start); }
|
||||
catch { }
|
||||
finally { Volatile.Write(ref _open, 0); }
|
||||
try { done(chosen); } catch { }
|
||||
})
|
||||
{ IsBackground = true, Name = "RynthAi folder chooser" };
|
||||
try { t.SetApartmentState(ApartmentState.STA); } catch { }
|
||||
t.Start();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string? Run(string title, string start)
|
||||
{
|
||||
int ole = OleInitialize(IntPtr.Zero);
|
||||
IntPtr startText = Marshal.StringToHGlobalUni(start ?? string.Empty);
|
||||
try
|
||||
{
|
||||
char* name = stackalloc char[MaxPath + 1];
|
||||
fixed (char* t = title)
|
||||
{
|
||||
var info = new BrowseInfo
|
||||
{
|
||||
DisplayName = name,
|
||||
Title = t,
|
||||
Flags = BifReturnOnlyFsDirs | BifNewDialogStyle | BifEditBox,
|
||||
Callback = (IntPtr)(delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr, IntPtr, int>)&OnEvent,
|
||||
Param = startText,
|
||||
};
|
||||
IntPtr pidl = SHBrowseForFolderW(&info);
|
||||
if (pidl == IntPtr.Zero) return null;
|
||||
try
|
||||
{
|
||||
char* path = stackalloc char[MaxPath + 1];
|
||||
if (SHGetPathFromIDListW(pidl, path) == 0) return null;
|
||||
string s = new string(path);
|
||||
return s.Length > 0 ? s : null;
|
||||
}
|
||||
finally { CoTaskMemFree(pidl); }
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(startText);
|
||||
if (ole >= 0) OleUninitialize();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>BFFM_INITIALIZED: start in the current folder and come to the front.</summary>
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvStdcall) })]
|
||||
private static int OnEvent(IntPtr hwnd, uint msg, IntPtr lParam, IntPtr data)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (msg == BffmInitialized)
|
||||
{
|
||||
if (data != IntPtr.Zero) SendMessageW(hwnd, BffmSetSelectionW, (IntPtr)1, data);
|
||||
SetForegroundWindow(hwnd);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
161
Plugins/RynthCore.Plugin.RynthAi/AcMaps/WicImage.cs
Normal file
161
Plugins/RynthCore.Plugin.RynthAi/AcMaps/WicImage.cs
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
// ============================================================================
|
||||
// RynthAi - AcMaps/WicImage.cs
|
||||
// Reads a map image (GIF, PNG, JPG, BMP) into 32-bit BGRA pixels with
|
||||
// Windows' own decoder (WIC, windowscodecs.dll): no image library to ship,
|
||||
// and no reflection (RynthAi is NativeAOT), so COM is called through its
|
||||
// vtables. The first frame only (ACMAPS GIFs are single-frame).
|
||||
//
|
||||
// A map larger than MaxSide or MaxPixels is scaled down on the way in (the
|
||||
// client is 32-bit; a 4096 x 4096 map is 64 MB of pixels): Width/Height are
|
||||
// what was decoded, SourceWidth/SourceHeight the file's, so spots stay in the
|
||||
// file's pixels.
|
||||
//
|
||||
// Runs on its own thread (Decode starts one): it joins COM as MTA there.
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.AcMaps;
|
||||
|
||||
/// <summary>A decoded image: BGRA pixels (one uint each, as D3DFMT_A8R8G8B8), top row first.</summary>
|
||||
internal sealed class DecodedImage
|
||||
{
|
||||
public int Width { get; init; }
|
||||
public int Height { get; init; }
|
||||
public int SourceWidth { get; init; }
|
||||
public int SourceHeight { get; init; }
|
||||
public uint[] Pixels { get; init; } = Array.Empty<uint>();
|
||||
/// <summary>Decoded pixels per file pixel (1 unless scaled down).</summary>
|
||||
public float Factor => SourceWidth > 0 ? Width / (float)SourceWidth : 1f;
|
||||
}
|
||||
|
||||
internal static unsafe class WicImage
|
||||
{
|
||||
public const int MaxSide = 4096;
|
||||
public const long MaxPixels = 8L * 1024 * 1024;
|
||||
|
||||
private static readonly Guid ClsidFactory = new("cacaf262-9370-4615-a13b-9f5539da4c0a");
|
||||
private static readonly Guid IidFactory = new("ec5ec8a9-c395-4314-9c77-54d7a935ff70");
|
||||
private static readonly Guid FormatBgra32 = new("6fddc324-4e03-4bfe-b185-3d77768dc90f");
|
||||
|
||||
private const uint ClsctxInprocServer = 1;
|
||||
private const uint GenericRead = 0x80000000;
|
||||
private const int CoinitMultithreaded = 0;
|
||||
private const int RpcEChangedMode = unchecked((int)0x80010106);
|
||||
|
||||
// vtable slots (wincodec.h order).
|
||||
private const int FactoryCreateDecoderFromFilename = 3, FactoryCreateFormatConverter = 10, FactoryCreateBitmapScaler = 11;
|
||||
private const int DecoderGetFrame = 13;
|
||||
private const int SourceGetSize = 3, SourceCopyPixels = 7;
|
||||
private const int ConverterInitialize = 8, ScalerInitialize = 8;
|
||||
private const int Release = 2;
|
||||
private const int DitherNone = 0, PaletteCustom = 0, InterpolationFant = 3;
|
||||
|
||||
[DllImport("ole32.dll")] private static extern int CoInitializeEx(IntPtr reserved, int coInit);
|
||||
[DllImport("ole32.dll")] private static extern void CoUninitialize();
|
||||
[DllImport("ole32.dll")] private static extern int CoCreateInstance(Guid* clsid, IntPtr outer, uint context, Guid* iid, IntPtr* ppv);
|
||||
|
||||
/// <summary>
|
||||
/// Decodes <paramref name="path"/> on a new background thread and hands the result (or null and why) to
|
||||
/// <paramref name="done"/> on that thread.
|
||||
/// </summary>
|
||||
public static void DecodeAsync(string path, Action<DecodedImage?, string> done)
|
||||
{
|
||||
var t = new System.Threading.Thread(() =>
|
||||
{
|
||||
DecodedImage? image = null;
|
||||
string error;
|
||||
try { image = Load(path, out error); }
|
||||
catch (Exception ex) { error = ex.Message; }
|
||||
try { done(image, error); } catch { }
|
||||
})
|
||||
{ IsBackground = true, Name = "RynthAi ACMAPS decode" };
|
||||
t.Start();
|
||||
}
|
||||
|
||||
/// <summary>The image at <paramref name="path"/>, or null and why. Joins COM on the calling thread for the call.</summary>
|
||||
public static DecodedImage? Load(string path, out string error)
|
||||
{
|
||||
int init = CoInitializeEx(IntPtr.Zero, CoinitMultithreaded);
|
||||
bool uninit = init >= 0; // S_OK or S_FALSE; RPC_E_CHANGED_MODE: the thread is STA already, still usable
|
||||
if (init < 0 && init != RpcEChangedMode) { error = $"COM didn't start (0x{init:X8})."; return null; }
|
||||
IntPtr factory = IntPtr.Zero, decoder = IntPtr.Zero, frame = IntPtr.Zero, scaler = IntPtr.Zero, converter = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
Guid clsid = ClsidFactory, iid = IidFactory;
|
||||
int hr = CoCreateInstance(&clsid, IntPtr.Zero, ClsctxInprocServer, &iid, &factory);
|
||||
if (hr < 0) { error = $"Windows' image decoder isn't available (0x{hr:X8})."; return null; }
|
||||
fixed (char* p = path)
|
||||
{
|
||||
hr = ((delegate* unmanaged[Stdcall]<IntPtr, char*, Guid*, uint, int, IntPtr*, int>)Slot(factory, FactoryCreateDecoderFromFilename))(
|
||||
factory, p, null, GenericRead, 0, &decoder);
|
||||
}
|
||||
if (hr < 0) { error = $"Couldn't open the image (0x{hr:X8}): not a GIF, PNG or JPG Windows can read?"; return null; }
|
||||
hr = ((delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr*, int>)Slot(decoder, DecoderGetFrame))(decoder, 0, &frame);
|
||||
if (hr < 0) { error = $"The image has no picture in it (0x{hr:X8})."; return null; }
|
||||
uint w, h;
|
||||
hr = ((delegate* unmanaged[Stdcall]<IntPtr, uint*, uint*, int>)Slot(frame, SourceGetSize))(frame, &w, &h);
|
||||
if (hr < 0 || w == 0 || h == 0) { error = "The image is empty."; return null; }
|
||||
|
||||
(int ow, int oh) = FitSize((int)w, (int)h);
|
||||
IntPtr source = frame;
|
||||
if (ow != (int)w || oh != (int)h)
|
||||
{
|
||||
hr = ((delegate* unmanaged[Stdcall]<IntPtr, IntPtr*, int>)Slot(factory, FactoryCreateBitmapScaler))(factory, &scaler);
|
||||
if (hr >= 0)
|
||||
hr = ((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, uint, uint, int, int>)Slot(scaler, ScalerInitialize))(
|
||||
scaler, frame, (uint)ow, (uint)oh, InterpolationFant);
|
||||
if (hr < 0) { error = $"Couldn't scale the {w} x {h} image down (0x{hr:X8})."; return null; }
|
||||
source = scaler;
|
||||
}
|
||||
|
||||
hr = ((delegate* unmanaged[Stdcall]<IntPtr, IntPtr*, int>)Slot(factory, FactoryCreateFormatConverter))(factory, &converter);
|
||||
if (hr < 0) { error = $"Couldn't convert the image (0x{hr:X8})."; return null; }
|
||||
Guid fmt = FormatBgra32;
|
||||
hr = ((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, Guid*, int, IntPtr, double, int, int>)Slot(converter, ConverterInitialize))(
|
||||
converter, source, &fmt, DitherNone, IntPtr.Zero, 0.0, PaletteCustom);
|
||||
if (hr < 0) { error = $"Couldn't convert the image to colour pixels (0x{hr:X8})."; return null; }
|
||||
|
||||
var pixels = new uint[(long)ow * oh];
|
||||
uint stride = (uint)ow * 4;
|
||||
fixed (uint* dst = pixels)
|
||||
{
|
||||
hr = ((delegate* unmanaged[Stdcall]<IntPtr, IntPtr, uint, uint, byte*, int>)Slot(converter, SourceCopyPixels))(
|
||||
converter, IntPtr.Zero, stride, stride * (uint)oh, (byte*)dst);
|
||||
}
|
||||
if (hr < 0) { error = $"Couldn't read the image's pixels (0x{hr:X8})."; return null; }
|
||||
error = string.Empty;
|
||||
return new DecodedImage { Width = ow, Height = oh, SourceWidth = (int)w, SourceHeight = (int)h, Pixels = pixels };
|
||||
}
|
||||
finally
|
||||
{
|
||||
ReleaseCom(converter);
|
||||
ReleaseCom(scaler);
|
||||
ReleaseCom(frame);
|
||||
ReleaseCom(decoder);
|
||||
ReleaseCom(factory);
|
||||
if (uninit) CoUninitialize();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The size to decode a w x h image at: itself, or scaled down (aspect kept) to MaxSide and MaxPixels.</summary>
|
||||
internal static (int W, int H) FitSize(int w, int h)
|
||||
{
|
||||
if (w <= 0 || h <= 0) return (0, 0);
|
||||
double k = 1.0;
|
||||
int side = Math.Max(w, h);
|
||||
if (side > MaxSide) k = MaxSide / (double)side;
|
||||
double px = (double)w * h * k * k;
|
||||
if (px > MaxPixels) k *= Math.Sqrt(MaxPixels / px);
|
||||
if (k >= 1.0) return (w, h);
|
||||
return (Math.Max(1, (int)Math.Floor(w * k)), Math.Max(1, (int)Math.Floor(h * k)));
|
||||
}
|
||||
|
||||
private static void* Slot(IntPtr com, int index) => (*(void***)com)[index];
|
||||
|
||||
private static void ReleaseCom(IntPtr com)
|
||||
{
|
||||
if (com == IntPtr.Zero) return;
|
||||
try { ((delegate* unmanaged[Stdcall]<IntPtr, uint>)Slot(com, Release))(com); } catch { }
|
||||
}
|
||||
}
|
||||
|
|
@ -89,6 +89,19 @@ public static partial class AmmoRecipes
|
|||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// About how much ammo one combine makes, for planning a top-off (Make ammo when low). The world
|
||||
/// database's success amounts (read 2026-11-23): a plain "Bundle of" shaft makes 100 (Crystal
|
||||
/// heads 250), a "Wrapped Bundle of" shaft 1000 (a few Greater Deadly and elemental wrapped
|
||||
/// bundles 2500). The shaft decides, so this reads the shaft: 100 or 1000, never more than made.
|
||||
/// </summary>
|
||||
public static int EstimatedYield(AmmoRecipe recipe) =>
|
||||
recipe.ShaftName.StartsWith("Wrapped", StringComparison.OrdinalIgnoreCase) ? 1000 : 100;
|
||||
|
||||
/// <summary>Infinite heads are not used up by a combine (only the shaft bundle is).</summary>
|
||||
public static bool HeadIsInfinite(AmmoRecipe recipe) =>
|
||||
recipe.HeadName.StartsWith("Infinite", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Rank of finished ammo on the recipes' scale (<see cref="AmmoRecipe.Rank"/>), or 1
|
||||
/// for ammo no recipe makes (quest arrows and the like) so crafted ammo outranks it.</summary>
|
||||
public static int OutputRank(string name, WeaponCategory category)
|
||||
|
|
|
|||
|
|
@ -395,6 +395,18 @@ public partial class BuffManager : IDisposable
|
|||
private DateTime _buffFightWaitSince = DateTime.MinValue;
|
||||
private DateTime _buffFightNeedCheckedAt = DateTime.MinValue;
|
||||
|
||||
// ── A fight that never ends (2026-11-25, R-20261125-130039-e3bc) ──
|
||||
// Conquest, a spot that respawns constantly with Monster Range 10: never more than ~15 s without a
|
||||
// monster in range, so the wait above never ended. Buffs waited 24,811 s (almost 7 hours), ran out,
|
||||
// and the character died several times; Force Rebuff (cast in the fight) worked. Now once buffs
|
||||
// have waited BuffFightWaitMaxSec through one unbroken fight, a full pass goes in it, the way a Force
|
||||
// Rebuff does: never while health is under Heal At, and it stops once nothing is due. A short fight
|
||||
// (the 11-20 Thread dispel case) is over long before that and still waits.
|
||||
internal const int BuffFightWaitMaxSec = 120;
|
||||
private bool _buffFightPass; // a pass let through a fight that doesn't end
|
||||
private bool _buffFightPassNeed; // NeedsAnyBuff, asked at most once a second during a pass
|
||||
private DateTime _buffFightPassCheckedAt = DateTime.MinValue;
|
||||
|
||||
/// <summary>True in a fight: no new buff cast. A Force Rebuff the player asked for waits only while health
|
||||
/// is under Heal At. Logs the start (when there are buffs to cast) and the end of each wait.</summary>
|
||||
public bool BuffsWaitForFight()
|
||||
|
|
@ -402,12 +414,34 @@ public partial class BuffManager : IDisposable
|
|||
bool fight = InCombatNow();
|
||||
bool hurt = _settings.HealAt > 0 && _vitals.HealthPct > 0 && _vitals.HealthPct < _settings.HealAt;
|
||||
bool playersOwn = _isForceRebuffing && !_isAutoBatchRebuff;
|
||||
bool wait = fight && (!playersOwn || hurt);
|
||||
DateTime now = RynthClock.Now;
|
||||
if (_buffFightPass)
|
||||
{
|
||||
// The pass ends with the fight or once nothing is due.
|
||||
if ((now - _buffFightPassCheckedAt).TotalMilliseconds >= 1000)
|
||||
{
|
||||
_buffFightPassCheckedAt = now;
|
||||
_buffFightPassNeed = NeedsAnyBuff();
|
||||
}
|
||||
if (!fight || !_buffFightPassNeed)
|
||||
{
|
||||
_buffFightPass = false;
|
||||
_host.Log($"[Buff] the rebuff pass in the fight is done ({(fight ? "nothing left to cast" : "the fight is over")}).");
|
||||
}
|
||||
}
|
||||
else if (fight && _buffFightWaitOn && (now - _buffFightWaitSince).TotalSeconds >= BuffFightWaitMaxSec)
|
||||
{
|
||||
_buffFightPass = true;
|
||||
_buffFightPassNeed = true;
|
||||
_buffFightPassCheckedAt = now;
|
||||
_host.Log($"[Buff] buffs have waited {(now - _buffFightWaitSince).TotalSeconds:0} s for a fight that doesn't end (a monster always within range): " +
|
||||
"a full rebuff pass goes now, in the fight, as Force Rebuff does (never under Heal At).");
|
||||
}
|
||||
bool wait = fight && (!(playersOwn || _buffFightPass) || hurt);
|
||||
if (!wait)
|
||||
{
|
||||
if (_buffFightWaitOn)
|
||||
_host.Log($"[Buff] buffs go on: {(fight ? $"health {_vitals.HealthPct}%, back over Heal At, for the Force Rebuff you asked for" : "the fight is over")} (they waited {(now - _buffFightWaitSince).TotalSeconds:0} s).");
|
||||
_host.Log($"[Buff] buffs go on: {(!fight ? "the fight is over" : _buffFightPass ? "the fight doesn't end, so they go in it" : $"health {_vitals.HealthPct}%, back over Heal At, for the Force Rebuff you asked for")} (they waited {(now - _buffFightWaitSince).TotalSeconds:0} s).");
|
||||
_buffFightWaitOn = false;
|
||||
return false;
|
||||
}
|
||||
|
|
@ -1324,8 +1358,28 @@ public partial class BuffManager : IDisposable
|
|||
/// monster near or hitting must not lower the line. Top Off HP applies then (2026-11-22: Combat off,
|
||||
/// Heal At 0, a monster hitting; every hit made it "a fight", Heal At 0 healed nothing, and the
|
||||
/// character stood until it died).
|
||||
/// Nor while Boost Loot Priority's looting has the tick over the fight (BoostLootHealsToTopOff): the
|
||||
/// looter isn't fighting either, so Top Off HP applies and the heal goes before the next pickup.
|
||||
/// </summary>
|
||||
private bool FightHealthLine(bool inCombat) => UseFightVitalLines(inCombat && _settings.EnableCombat);
|
||||
private bool FightHealthLine(bool inCombat)
|
||||
=> UseFightVitalLines(inCombat && _settings.EnableCombat && !BoostLootTopsOffNow());
|
||||
|
||||
/// <summary>
|
||||
/// Boost Loot Priority (2026-11-23, the owner: "for loot boost below health max it keeps looting. I
|
||||
/// think it should interrupt looting and heal"). The looter puts corpses ahead of a close monster at
|
||||
/// or over Heal At (RynthAiPlugin.BoostLootFirst.cs), and with a monster within Monster Range the
|
||||
/// health line was Heal At: a looter hit to 70% with Heal At 60 (or 0) looted on and healed nothing.
|
||||
/// While that looting would have the tick, health uses Top Off HP (the between-fights line): under
|
||||
/// it the heal wins the arbiter (Buffing halts the loot and keeps the claim), then looting resumes.
|
||||
/// Set by RynthAiPlugin; null (tests, no plugin) = never.
|
||||
/// </summary>
|
||||
internal Func<bool>? BoostLootHealsToTopOff { get; set; }
|
||||
|
||||
private bool BoostLootTopsOffNow()
|
||||
{
|
||||
if (BoostLootHealsToTopOff == null) return false;
|
||||
try { return BoostLootHealsToTopOff(); } catch { return false; }
|
||||
}
|
||||
|
||||
// ── What the activity display says while the arbiter's slot is "Buffing" ──
|
||||
// BotAction stays "Buffing" for every vitals job: it is a control string (CombatManager's
|
||||
|
|
|
|||
|
|
@ -0,0 +1,83 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Plugin.RynthAi - Combat/CombatManager.LosVerdicts.cs
|
||||
// Show Line of Sight (2026-11-26, a testing aid): the scan's own line-of-sight
|
||||
// verdict for each monster it tested, kept for the overlay (LosLineOverlay.cs)
|
||||
// so the line is drawn in the colour the targeting raycast gave, with no second
|
||||
// raycast per frame. Filled only while ShowLosLine is on; cleared each scan.
|
||||
//
|
||||
// Why: 2026-11-26, a melee character outdoors in 0xB470, locked monsters
|
||||
// 4.3-4.7 m off in the same outdoor cell behind a wall; the scan's raycast said
|
||||
// clear, nothing landed, and the target was blacklisted after three no-damage
|
||||
// attacks. The line shows in game what the raycast thinks.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public partial class CombatManager
|
||||
{
|
||||
/// <summary>One monster's line-of-sight verdict from the last scan.</summary>
|
||||
internal struct LosVerdict
|
||||
{
|
||||
/// <summary>What the targeting raycast said: true = blocked.</summary>
|
||||
public bool Blocked;
|
||||
/// <summary>The raycast tested geometry (false: clear without a test: raycasting off or warming up,
|
||||
/// no geometry near the path, too far, no position).</summary>
|
||||
public bool Tested;
|
||||
/// <summary>Where it is blocked, global metres (landblock * 192 + local; Z the height).</summary>
|
||||
public bool HasHit;
|
||||
public float HitX, HitY, HitZ;
|
||||
/// <summary>Blocked, but melee within MeleeIgnoresLosWithin fights it anyway (the scan kept it).</summary>
|
||||
public bool MeleeThrough;
|
||||
/// <summary>3D distance at the scan, metres.</summary>
|
||||
public double Distance;
|
||||
public TargetingFSM.AttackType Type;
|
||||
public DateTime At;
|
||||
}
|
||||
|
||||
private readonly Dictionary<int, LosVerdict> _losVerdicts = new();
|
||||
|
||||
/// <summary>The last scan's verdicts by monster id (empty while Show Line of Sight is off).</summary>
|
||||
internal IReadOnlyDictionary<int, LosVerdict> LosVerdicts => _losVerdicts;
|
||||
|
||||
internal bool TryGetLosVerdict(int id, out LosVerdict verdict) => _losVerdicts.TryGetValue(id, out verdict);
|
||||
|
||||
/// <summary>The monster the line goes to: the combat target, else the locked one.</summary>
|
||||
internal int LosLineTargetId => _activeTargetId != 0 ? _activeTargetId : _lockedTargetId;
|
||||
|
||||
/// <summary>Start of a scan: the cache holds this scan's verdicts only; on, the raycast reports hit points.</summary>
|
||||
private bool BeginLosVerdicts()
|
||||
{
|
||||
bool on = _settings.ShowLosLine;
|
||||
if (_losVerdicts.Count > 0) _losVerdicts.Clear();
|
||||
var fsm = _raycastSystem?.TargetingFSM;
|
||||
if (fsm != null && fsm.ReportHitPoints != on) fsm.ReportHitPoints = on;
|
||||
return on;
|
||||
}
|
||||
|
||||
private void NoteLosVerdict(int id, bool blocked, bool tested, in TargetingFSM.LosDetail detail, double dist, TargetingFSM.AttackType type)
|
||||
{
|
||||
var v = new LosVerdict
|
||||
{
|
||||
Blocked = blocked,
|
||||
Tested = tested,
|
||||
HasHit = blocked && detail.HasHit,
|
||||
HitX = detail.Hit.X, HitY = detail.Hit.Y, HitZ = detail.Hit.Z,
|
||||
Distance = dist,
|
||||
Type = type,
|
||||
At = RynthClock.Now,
|
||||
};
|
||||
_losVerdicts[id] = v;
|
||||
}
|
||||
|
||||
private void NoteLosMeleeThrough(int id)
|
||||
{
|
||||
if (_losVerdicts.TryGetValue(id, out var v)) { v.MeleeThrough = true; _losVerdicts[id] = v; }
|
||||
}
|
||||
|
||||
/// <summary>Tests: a verdict as a scan would leave it.</summary>
|
||||
internal void SetLosVerdictForTests(int id, LosVerdict verdict) => _losVerdicts[id] = verdict;
|
||||
}
|
||||
|
|
@ -1216,6 +1216,7 @@ public partial class CombatManager : IDisposable
|
|||
attackType = DetermineAttackTypeForLOS();
|
||||
bool losDebug = _settings.LosDebugLog;
|
||||
if (losDebug) LogLosDebugWeapon();
|
||||
bool noteLos = BeginLosVerdicts(); // Show Line of Sight (CombatManager.LosVerdicts.cs)
|
||||
|
||||
// The player's position once per scan: Distance(player, mob) re-read it for every
|
||||
// creature, two host reads per monster 20 times a second (2026-10-02 flood work).
|
||||
|
|
@ -1361,15 +1362,22 @@ public partial class CombatManager : IDisposable
|
|||
}
|
||||
|
||||
bool losBlocked = false;
|
||||
bool losTested = false;
|
||||
TargetingFSM.LosDetail losDetail = default;
|
||||
if (LosBlockedOverride != null)
|
||||
{
|
||||
losBlocked = LosBlockedOverride(wo.Id);
|
||||
losTested = true;
|
||||
}
|
||||
else if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem?.TargetingFSM != null)
|
||||
{
|
||||
RaycastCheckCount++;
|
||||
losBlocked = _raycastSystem.TargetingFSM.IsTargetBlocked(_host, (uint)wo.Id, attackType, out var losDetail);
|
||||
losBlocked = _raycastSystem.TargetingFSM.IsTargetBlocked(_host, (uint)wo.Id, attackType, out losDetail);
|
||||
losTested = losDetail.Checked;
|
||||
if (losBlocked) RaycastBlockCount++;
|
||||
if (losDebug) LogLosDebug(wo, losBlocked, losDetail);
|
||||
}
|
||||
if (noteLos) NoteLosVerdict(wo.Id, losBlocked, losTested, in losDetail, dist, attackType);
|
||||
|
||||
// Melee reaches through walls, on both sides: a monster this close is a target when
|
||||
// melee is, or is about to be, the attack (the owner, 2026-11-06). It was left out while
|
||||
|
|
@ -1390,6 +1398,7 @@ public partial class CombatManager : IDisposable
|
|||
if (notePassed) NotePassedOver(wo.Id, dist, PassedOverLos);
|
||||
continue;
|
||||
}
|
||||
if (noteLos) NoteLosMeleeThrough(wo.Id);
|
||||
losBlocked = false;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ using System.Collections.Generic;
|
|||
using System.Linq;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
|
@ -17,9 +18,81 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
///
|
||||
/// Crafting is chat-driven: issues UseObjectOn (ApplyItem), waits for "You make" chat,
|
||||
/// then advances to the next combine or equips. Retries every 2s if no response.
|
||||
///
|
||||
/// Make ammo when low (a players' request, 2026-11-23; MakeAmmoWhenLow, off by default): a top-off
|
||||
/// between fights, so the empty-slot path above is rarely needed. The plugin (RynthAiPlugin.Ammo.cs)
|
||||
/// decides when, on the Make kits when low rules (<see cref="Auto"/>, a KitAuto of its own): fewer
|
||||
/// than MakeAmmoBelow arrows, quarrels or darts for the launcher in hand (quiver and pack), nothing
|
||||
/// else going, no monster near, no hit for 20 s, in peace mode. <see cref="StartTopOff"/> then makes
|
||||
/// enough combines of the best recipe the pack and Fletching make reliably (the same choice as the
|
||||
/// empty-slot path, never a risky one) to reach MakeAmmoUpTo, and wields ammo only if the slot is
|
||||
/// empty. A fight, a launcher swap or leaving peace mode stops it at once (<see cref="StopTopOff"/>).
|
||||
/// </summary>
|
||||
public class MissileCraftingManager
|
||||
{
|
||||
// ── Make ammo when low ──────────────────────────────────────────────
|
||||
/// <summary>A plain bundle makes 100, so one combine always lifts you back over this.</summary>
|
||||
public const int DefaultAmmoBelow = 100;
|
||||
/// <summary>Five plain combines, or one wrapped bundle (1000).</summary>
|
||||
public const int DefaultAmmoUpTo = 500;
|
||||
public const int MaxAmmoBelow = 5000;
|
||||
public const int MaxAmmoUpTo = 10000;
|
||||
/// <summary>The most combines one top-off makes.</summary>
|
||||
public const int MaxTopOffCombines = 10;
|
||||
|
||||
/// <summary>When a top-off may start, and the waits after one (ticked by RynthAiPlugin.Ammo.cs).</summary>
|
||||
internal KitAuto Auto { get; } = new KitAuto { Name = "Make ammo when low", Doing = "make ammo" };
|
||||
/// <summary>The chat line for the top-off's own lines (the plugin's ChatLine; null = the host's chat).</summary>
|
||||
public Action<string>? Say { get; set; }
|
||||
|
||||
private bool _topOff, _topOffManual;
|
||||
private int _topOffTarget, _topOffYield, _topOffFailed;
|
||||
private WeaponCategory _topOffCategory;
|
||||
private string _topOffOutput = string.Empty;
|
||||
private KitStopKind? _topOffEndKind;
|
||||
private string _topOffWhy = string.Empty;
|
||||
private Func<KitStopKind, int, string>? _topOffEnded;
|
||||
private volatile bool _makeNowAsked, _stopAsked;
|
||||
|
||||
/// <summary>A top-off is under way (it holds the bot while it goes).</summary>
|
||||
public bool TopOffRunning => _topOff && State != CraftState.Idle;
|
||||
/// <summary>The top-off going was asked for (Make ammo now), not started by the low line.</summary>
|
||||
public bool TopOffManual => _topOff && _topOffManual;
|
||||
/// <summary>Combines made in the top-off going.</summary>
|
||||
public int TopOffMade => _topOff ? _combinesCompleted : 0;
|
||||
/// <summary>Combines the top-off going plans.</summary>
|
||||
public int TopOffPlanned => _topOff ? _totalCombines : 0;
|
||||
/// <summary>The last top-off's summary line ("" = none this session).</summary>
|
||||
public string LastTopOffSummary { get; private set; } = string.Empty;
|
||||
/// <summary>The last look at the launcher and the ammo (for the panels; null = none yet).</summary>
|
||||
internal AmmoLook? LastLook { get; private set; }
|
||||
/// <summary>Make ammo now: asked until this (plugin clock, ms; 0 = not asked).</summary>
|
||||
internal long MakeNowUntilMs { get; set; }
|
||||
|
||||
/// <summary>A panel's Make ammo now (any thread): the plugin takes it on its next tick.</summary>
|
||||
public void RequestMakeNow() => _makeNowAsked = true;
|
||||
/// <summary>A panel's Stop (any thread): the plugin takes it on its next tick.</summary>
|
||||
public void RequestStop() => _stopAsked = true;
|
||||
internal bool TakeMakeNowRequest() { if (!_makeNowAsked) return false; _makeNowAsked = false; return true; }
|
||||
internal bool TakeStopRequest() { if (!_stopAsked) return false; _stopAsked = false; return true; }
|
||||
|
||||
/// <summary>The launcher in hand and its ammo: what a top-off would make and why not.</summary>
|
||||
internal sealed record AmmoLook(bool Launcher, WeaponCategory Category, int Carried, bool Wielded,
|
||||
AmmoRecipe? Recipe, int Combines, string PackWhy)
|
||||
{
|
||||
public string CarriedText => AmmoText(Carried, Category);
|
||||
}
|
||||
|
||||
/// <summary>"1 arrow", "230 quarrels", "12 darts".</summary>
|
||||
public static string AmmoText(int n, WeaponCategory c) => $"{n} {AmmoNoun(c, n)}";
|
||||
|
||||
public static string AmmoNoun(WeaponCategory c, int n = 2) => c switch
|
||||
{
|
||||
WeaponCategory.Crossbow => n == 1 ? "quarrel" : "quarrels",
|
||||
WeaponCategory.Atlatl => n == 1 ? "dart" : "darts",
|
||||
_ => n == 1 ? "arrow" : "arrows",
|
||||
};
|
||||
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly LegacyUiSettings _settings;
|
||||
private WorldObjectCache? _objectCache;
|
||||
|
|
@ -105,6 +178,7 @@ public class MissileCraftingManager
|
|||
// crafting off mid-craft must let go too.
|
||||
if (!_settings.EnableMissileCrafting)
|
||||
{
|
||||
if (_topOff) _topOffEndKind = KitStopKind.Other;
|
||||
if (State != CraftState.Idle) Reset("Missile crafting turned off");
|
||||
return;
|
||||
}
|
||||
|
|
@ -131,6 +205,191 @@ public class MissileCraftingManager
|
|||
}
|
||||
}
|
||||
|
||||
// ══════════════════════════════════════════════════════════════════
|
||||
// MAKE AMMO WHEN LOW (the top-off between fights)
|
||||
// ══════════════════════════════════════════════════════════════════
|
||||
|
||||
/// <summary>
|
||||
/// The launcher in hand, the ammo carried for it (quiver and pack, stacks summed), and what a
|
||||
/// top-off would make: the best recipe the pack and Fletching make reliably (the empty-slot path's
|
||||
/// own choice, AmmoRecipes.BestCraftable; never one under its 90% line) and how many combines the
|
||||
/// bundles allow. <paramref name="forceRefresh"/> false re-reads a scan under a second old.
|
||||
/// </summary>
|
||||
internal AmmoLook LookTopOff(bool forceRefresh = true)
|
||||
{
|
||||
var inv = GetInventory(forceRefresh);
|
||||
AmmoLook look = LookTopOff(inv);
|
||||
LastLook = look;
|
||||
return look;
|
||||
}
|
||||
|
||||
private AmmoLook LookTopOff(List<WorldObject> inv)
|
||||
{
|
||||
if (!TryGetWieldedMissileCategory(inv, out WeaponCategory category, out _))
|
||||
return new AmmoLook(false, _lastWeaponCategory, 0, false, null, 0, "no bow, crossbow or atlatl in hand");
|
||||
_lastWeaponCategory = category;
|
||||
int carried = CountAmmo(inv, category);
|
||||
bool wielded = HasWieldedAmmo(inv, category);
|
||||
|
||||
var fletching = _charSkills?[AcSkillType.Fletching];
|
||||
if (fletching != null && fletching.Training < 2)
|
||||
return new AmmoLook(true, category, carried, wielded, null, 0, "Fletching is untrained");
|
||||
int skill = fletching?.Buffed ?? 250;
|
||||
var best = AmmoRecipes.BestCraftable(inv.Select(i => i.Name), category, skill, out var tooHard);
|
||||
if (best == null)
|
||||
{
|
||||
string why = tooHard != null
|
||||
? $"{tooHard.OutputName} is about {AmmoRecipes.SuccessChance(skill, tooHard.Difficulty):P0} with Fletching {skill}, under the 90% line (a failed combine destroys both bundles)"
|
||||
: $"no heads and shafts for {AmmoNoun(category)} carried";
|
||||
return new AmmoLook(true, category, carried, wielded, null, 0, why);
|
||||
}
|
||||
int pairs = PairsCarried(best, inv);
|
||||
return new AmmoLook(true, category, carried, wielded, best, pairs,
|
||||
pairs > 0 ? string.Empty : $"no bundles for {best.OutputName}");
|
||||
}
|
||||
|
||||
/// <summary>Loose ammo for the launcher: the stack in the quiver and every stack in the packs.</summary>
|
||||
private int CountAmmo(List<WorldObject> inv, WeaponCategory category)
|
||||
{
|
||||
int n = 0;
|
||||
var seen = new HashSet<int>();
|
||||
foreach (var item in WornCandidates(inv))
|
||||
{
|
||||
if (!seen.Add(item.Id) || !IsLooseAmmo(item, category)) continue;
|
||||
n += Math.Max(1, item.Values(LongValueKey.StackCount, 1));
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>Combines the first head and shaft stacks allow (an Infinite head is never used up).</summary>
|
||||
private static int PairsCarried(AmmoRecipe recipe, List<WorldObject> inv)
|
||||
{
|
||||
var head = inv.FirstOrDefault(i => recipe.IsHead(i.Name));
|
||||
var shaft = inv.FirstOrDefault(i => recipe.IsShaft(i.Name));
|
||||
if (head == null || shaft == null) return 0;
|
||||
int heads = AmmoRecipes.HeadIsInfinite(recipe) ? int.MaxValue : Math.Max(1, head.Values(LongValueKey.StackCount, 1));
|
||||
int shafts = Math.Max(1, shaft.Values(LongValueKey.StackCount, 1));
|
||||
return Math.Min(heads, shafts);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts a top-off toward <paramref name="target"/> (the caller has checked it is safe: no fight,
|
||||
/// no monster near, in peace mode). <paramref name="why"/> is the start line's reason ("under 100").
|
||||
/// <paramref name="ended"/> hears how it ended and the combines made, and returns what the summary
|
||||
/// adds (the next try). Returns "" or why not.
|
||||
/// </summary>
|
||||
internal string StartTopOff(int target, bool manual, string why, Func<KitStopKind, int, string>? ended)
|
||||
{
|
||||
if (!_settings.EnableMissileCrafting) return "Enable Missile Crafting is off";
|
||||
if (State != CraftState.Idle) return "ammo crafting is already under way";
|
||||
if (HoldWhile?.Invoke() == true) return "a launcher swap is under way";
|
||||
if (InFight()) return "a fight is on";
|
||||
var inv = GetInventory(forceRefresh: true);
|
||||
AmmoLook look = LookTopOff(inv);
|
||||
LastLook = look;
|
||||
if (!look.Launcher || look.Recipe == null || look.Combines <= 0) return look.PackWhy;
|
||||
if (look.Carried >= target) return $"{look.CarriedText} carried already (makes up to {target})";
|
||||
|
||||
var recipe = look.Recipe;
|
||||
int yield = AmmoRecipes.EstimatedYield(recipe);
|
||||
int combines = Math.Clamp((target - look.Carried + yield - 1) / yield, 1, Math.Min(MaxTopOffCombines, look.Combines));
|
||||
_topOffQuiet = true;
|
||||
try { StartCrafting(recipe, inv, upgrade: false, pairs: combines); }
|
||||
finally { _topOffQuiet = false; }
|
||||
if (State != CraftState.Combining) return StatusMessage.Length > 0 ? StatusMessage : "the bundles couldn't be read";
|
||||
|
||||
_topOff = true;
|
||||
_topOffManual = manual;
|
||||
_topOffTarget = target;
|
||||
_topOffYield = yield;
|
||||
_topOffFailed = 0;
|
||||
_topOffCategory = look.Category;
|
||||
_topOffOutput = recipe.OutputName;
|
||||
_topOffEndKind = null;
|
||||
_topOffWhy = string.Empty;
|
||||
_topOffEnded = ended;
|
||||
string line = $"[RynthAi] Make ammo when low: {look.CarriedText} carried ({why}); making {Combines(combines)} of "
|
||||
+ $"{recipe.OutputName}, about {combines * yield}, toward {target}.";
|
||||
SayLine(line);
|
||||
RynthLog.Write(LogCat.Crafting, "[Ammo] start: " + line);
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Stops the top-off going (a monster, a hit, the player's Stop, ...): one summary line.</summary>
|
||||
internal void StopTopOff(string why, KitStopKind kind)
|
||||
{
|
||||
if (!_topOff) return;
|
||||
_topOffEndKind = kind;
|
||||
_topOffWhy = why;
|
||||
Reset(why);
|
||||
}
|
||||
|
||||
/// <summary>What stops a top-off from inside crafting ("" = go on): a fight, a launcher swap, leaving peace mode.</summary>
|
||||
private string TopOffDanger()
|
||||
{
|
||||
if (InFight()) return "a fight";
|
||||
if (HoldWhile?.Invoke() == true) return "a launcher swap";
|
||||
try
|
||||
{
|
||||
if (_peaceSent && _host.HasGetCurrentCombatMode && _host.GetCurrentCombatMode() != CombatMode.NonCombat)
|
||||
return "left peace mode";
|
||||
}
|
||||
catch { }
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The top-off's summary line and the end callback (from <see cref="Reset"/>, before it clears the craft).</summary>
|
||||
private void FinishTopOff(string reason)
|
||||
{
|
||||
int made = _combinesCompleted, planned = _totalCombines, failed = _topOffFailed;
|
||||
KitStopKind kind = _topOffEndKind ?? (made > 0 ? KitStopKind.Finished : KitStopKind.Refused);
|
||||
string why = _topOffWhy.Length > 0 ? _topOffWhy : reason;
|
||||
if (why.StartsWith("Done", StringComparison.Ordinal))
|
||||
why = made >= planned ? $"made the {Combines(planned)} planned" : "done";
|
||||
var ended = _topOffEnded;
|
||||
string noun = AmmoNoun(_topOffCategory);
|
||||
int yield = _topOffYield;
|
||||
string output = _topOffOutput;
|
||||
_topOff = false;
|
||||
_topOffManual = false;
|
||||
_topOffEnded = null;
|
||||
_topOffEndKind = null;
|
||||
_topOffWhy = string.Empty;
|
||||
|
||||
string tail = string.Empty;
|
||||
try { tail = ended?.Invoke(kind, made) ?? string.Empty; }
|
||||
catch (Exception ex) { RynthLog.Exception(LogCat.Crafting, ex, "Make ammo when low: the end of a top-off"); }
|
||||
string madeText = made == 0 ? "made nothing" : $"made {Combines(made)} of {output} (about {made * yield} {noun})";
|
||||
string failText = failed == 0 ? "" : $", {Combines(failed)} failed (a failed combine destroys both bundles)";
|
||||
string line = $"[RynthAi] Make ammo when low: {madeText}{failText}. Stopped: {why}.{tail}";
|
||||
LastTopOffSummary = line;
|
||||
SayLine(line);
|
||||
RynthLog.Write(LogCat.Crafting, "[Ammo] " + line);
|
||||
}
|
||||
|
||||
private static string Combines(int n) => n == 1 ? "1 combine" : $"{n} combines";
|
||||
|
||||
/// <summary>All combines answered (or a timeout after some): wield only if the slot is empty, else done.</summary>
|
||||
private bool TopOffSlotFilled()
|
||||
{
|
||||
var inv = GetInventory(forceRefresh: true);
|
||||
return HasWieldedAmmo(inv, ResolveWeaponCategory(inv));
|
||||
}
|
||||
|
||||
private void SayLine(string line)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Say != null) Say(line);
|
||||
else if (_host.HasWriteToChat) _host.WriteToChat(line, 1);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// While a top-off starts or goes, crafting's own "[RynthAi Craft]" lines go to the log only:
|
||||
// the top-off says one line when it starts and one when it stops.
|
||||
private bool _topOffQuiet;
|
||||
|
||||
// ══════════════════════════════════════════════════════════════════
|
||||
// CHAT HANDLER — called from RynthAiPlugin.OnChatWindowText
|
||||
// ══════════════════════════════════════════════════════════════════
|
||||
|
|
@ -139,10 +398,15 @@ public class MissileCraftingManager
|
|||
{
|
||||
if (State != CraftState.Combining) return;
|
||||
if (string.IsNullOrEmpty(text)) return;
|
||||
if (text.IndexOf("You make", StringComparison.OrdinalIgnoreCase) < 0) return;
|
||||
bool made = text.IndexOf("You make", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
// A top-off counts a failed combine and goes on with the next (the empty-slot path never
|
||||
// matched failures and retries until its timeout, as before).
|
||||
bool failed = _topOff && !made && text.IndexOf("You fail to make", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
if (!made && !failed) return;
|
||||
|
||||
_combinesCompleted++;
|
||||
ChatLog($"Craft confirmed ({_combinesCompleted}/{_totalCombines})");
|
||||
if (made) _combinesCompleted++; else _topOffFailed++;
|
||||
if (_topOff) _phaseStart = RynthClock.Now; // each combine of a top-off gets its own timeout
|
||||
ChatLog(made ? $"Craft confirmed ({_combinesCompleted}/{_totalCombines})" : $"Combine failed ({_topOffFailed})");
|
||||
|
||||
if (_pendingBundlePairs.Count > 0)
|
||||
{
|
||||
|
|
@ -254,7 +518,8 @@ public class MissileCraftingManager
|
|||
Reset("No ammo and no bundles available");
|
||||
}
|
||||
|
||||
private void StartCrafting(AmmoRecipe recipe, List<WorldObject> inv, bool upgrade = false)
|
||||
/// <param name="pairs">Combines to queue (a top-off's count); 0 = the empty-slot path's up to 2.</param>
|
||||
private void StartCrafting(AmmoRecipe recipe, List<WorldObject> inv, bool upgrade = false, int pairs = 0)
|
||||
{
|
||||
_craftIsUpgrade = upgrade;
|
||||
_currentRecipe = recipe;
|
||||
|
|
@ -278,7 +543,7 @@ public class MissileCraftingManager
|
|||
// Check stack sizes to decide how many combines (1 or 2)
|
||||
int availableHeads = headItems[0].Values(LongValueKey.StackCount, 1);
|
||||
int availableShafts = shaftItems[0].Values(LongValueKey.StackCount, 1);
|
||||
int pairCount = Math.Min(2, Math.Min(availableHeads, availableShafts));
|
||||
int pairCount = pairs > 0 ? pairs : Math.Min(2, Math.Min(availableHeads, availableShafts));
|
||||
|
||||
// Queue combines with same IDs — server decrements stacked bundles
|
||||
for (int i = 0; i < pairCount; i++)
|
||||
|
|
@ -317,6 +582,14 @@ public class MissileCraftingManager
|
|||
|
||||
private void ProcessCombining()
|
||||
{
|
||||
// Make ammo when low: a top-off never holds the bot into a fight, a launcher swap or out of
|
||||
// peace mode. It stops at once; the combine already sent finishes on the server.
|
||||
if (_topOff)
|
||||
{
|
||||
string danger = TopOffDanger();
|
||||
if (danger.Length > 0) { StopTopOff(danger, KitStopKind.Danger); return; }
|
||||
}
|
||||
|
||||
// In a fight, with ammo to shoot (carried before the craft, or a combine already made):
|
||||
// stop holding combat and wield the best ammo carried now.
|
||||
if (!_allCombinesDone && (_craftIsUpgrade || _combinesCompleted > 0) && InFight())
|
||||
|
|
@ -334,6 +607,8 @@ public class MissileCraftingManager
|
|||
|
||||
if (_allCombinesDone)
|
||||
{
|
||||
// A top-off wields only into an empty slot; the ammo in the quiver stays.
|
||||
if (_topOff && TopOffSlotFilled()) { Reset("Done"); return; }
|
||||
StatusMessage = $"Equipping {_currentRecipe!.OutputName}...";
|
||||
_equipTargetId = 0;
|
||||
SetState(CraftState.EquippingAmmo);
|
||||
|
|
@ -342,7 +617,14 @@ public class MissileCraftingManager
|
|||
|
||||
if ((RynthClock.Now - _phaseStart).TotalMilliseconds > CRAFT_TIMEOUT_MS)
|
||||
{
|
||||
if (_combinesCompleted > 0)
|
||||
if (_topOff && (_combinesCompleted > 0 || _topOffFailed > 0))
|
||||
{
|
||||
_topOffWhy = $"no answer to the next combine after {Combines(_combinesCompleted + _topOffFailed)}";
|
||||
if (_combinesCompleted == 0 || TopOffSlotFilled()) { Reset("Craft timed out"); return; }
|
||||
_equipTargetId = 0;
|
||||
SetState(CraftState.EquippingAmmo);
|
||||
}
|
||||
else if (_combinesCompleted > 0)
|
||||
{
|
||||
ChatLog($"Timeout after {_combinesCompleted} combine(s). Equipping what we have.");
|
||||
_equipTargetId = 0;
|
||||
|
|
@ -642,7 +924,9 @@ public class MissileCraftingManager
|
|||
|
||||
private void Reset(string reason)
|
||||
{
|
||||
if (State != CraftState.Idle || reason.IndexOf("bundle", StringComparison.OrdinalIgnoreCase) >= 0)
|
||||
if (_topOff)
|
||||
FinishTopOff(reason); // the top-off's own summary line (crafting's are quiet for it)
|
||||
else if (State != CraftState.Idle || reason.IndexOf("bundle", StringComparison.OrdinalIgnoreCase) >= 0)
|
||||
ChatLog(reason);
|
||||
|
||||
StatusMessage = reason;
|
||||
|
|
@ -667,6 +951,11 @@ public class MissileCraftingManager
|
|||
|
||||
private void ChatLog(string msg)
|
||||
{
|
||||
if (_topOff || _topOffQuiet)
|
||||
{
|
||||
try { _host.Log($"[RynthAi] MissileCraft (Make ammo when low): {msg}"); } catch { }
|
||||
return;
|
||||
}
|
||||
try { _host.WriteToChat($"[RynthAi Craft] {msg}", 1); } catch { }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1584,11 +1584,21 @@ public class WorldObjectCache
|
|||
lock (_gate) return _homePack.TryGetValue(itemId, out int p) ? p : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Free main-pack slots kept for loot when a weapon with no known home goes to the main pack
|
||||
/// (loot goes only into the main pack).
|
||||
/// </summary>
|
||||
internal const int UnknownHomeMainPackMargin = 4;
|
||||
|
||||
/// <summary>
|
||||
/// As <see cref="FindPackFor(RynthCoreHost, WorldObjectCache?, bool, int)"/>, for putting
|
||||
/// <paramref name="forItems"/> away: the pack they all came from when it still has
|
||||
/// <paramref name="requireFree"/> free slots (the main pack only with <paramref name="includeMainPack"/>),
|
||||
/// else the usual choice.
|
||||
/// <paramref name="requireFree"/> free slots (the main pack only with <paramref name="includeMainPack"/>);
|
||||
/// with no home known for any of them (wielded since login, never seen in a pack), the main pack
|
||||
/// while it keeps <see cref="UnknownHomeMainPackMargin"/> slots more, as the game itself unwields;
|
||||
/// else the usual choice. R-20261125-040855-4588: "If I manually swap out wands from my main pack the
|
||||
/// one being disarmed goes into the main pack ... If the macro does this ... it puts the wand it is
|
||||
/// removing into the 1st pack down".
|
||||
/// </summary>
|
||||
public static int FindPackFor(RynthCoreHost host, WorldObjectCache? cache,
|
||||
bool includeMainPack, int requireFree, IReadOnlyList<int> forItems)
|
||||
|
|
@ -1598,15 +1608,20 @@ public class WorldObjectCache
|
|||
if (playerId == 0) return 0;
|
||||
var inv = cache.GetDirectInventory(forceRefresh: true);
|
||||
int home = 0;
|
||||
bool anyKnown = false;
|
||||
foreach (int id in forItems)
|
||||
{
|
||||
int h = id == 0 ? 0 : cache.HomePackOf(id);
|
||||
if (h != 0) anyKnown = true;
|
||||
if (h == 0 || (home != 0 && h != home)) { home = 0; break; }
|
||||
home = h;
|
||||
}
|
||||
if (home != 0 && (home != playerId || includeMainPack)
|
||||
&& FreeSlotsIn(inv, playerId, home, host) >= Math.Max(1, requireFree))
|
||||
return home;
|
||||
if (!anyKnown && forItems.Count > 0 && includeMainPack
|
||||
&& FreeSlotsIn(inv, playerId, playerId, host) >= Math.Max(1, requireFree) + UnknownHomeMainPackMargin)
|
||||
return playerId;
|
||||
return FindPackFor(inv, playerId, includeMainPack, requireFree, host);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,520 @@
|
|||
// ============================================================================
|
||||
// RynthAi - CommandButtons/CommandButtons.cs
|
||||
// Command Buttons (2026-11-26, a player's ask: "a configurable window of blank
|
||||
// buttons you can program with simple 1 line chat commands"): a grid of
|
||||
// buttons, each a label and one chat line (/ra start, *snow angel*, @home,
|
||||
// /lua start threads ...) sent as if typed in the chat box.
|
||||
//
|
||||
// Three lists, as the Timed Commands keep them: this character, every
|
||||
// character on this server, and every character. The window shows all three
|
||||
// (this character's first). Files beside the settings profiles, so switching
|
||||
// a settings profile keeps them:
|
||||
// SettingsProfiles\<server>\<character>\command_buttons.json (with the grid's
|
||||
// layout: columns, button width and height),
|
||||
// SettingsProfiles\<server>\command_buttons.json and
|
||||
// SettingsProfiles\command_buttons.json.
|
||||
// "Copy from" takes another character's buttons (same server) into this
|
||||
// character's list.
|
||||
//
|
||||
// Pure (no host, no ImGui): the host tests drive it.
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.CommandButtons;
|
||||
|
||||
/// <summary>Which list a button is in.</summary>
|
||||
internal enum ButtonScope { Character = 0, Server = 1, All = 2 }
|
||||
|
||||
/// <summary>One button: what it says, the chat line it sends, its colour and whether it asks first.</summary>
|
||||
internal sealed class CommandButton
|
||||
{
|
||||
public const int MaxLabel = 32;
|
||||
|
||||
public string Label = string.Empty;
|
||||
public string Command = string.Empty;
|
||||
/// <summary>The button's fill, ImGui ABGR with full alpha; 0 = the theme's button colour.</summary>
|
||||
public uint Color;
|
||||
/// <summary>Asks "Send ...?" before it sends (for a command that is hard to take back).</summary>
|
||||
public bool Confirm;
|
||||
|
||||
/// <summary>What the button shows: its label, else its command, else "(empty)".</summary>
|
||||
public string Shown => Label.Length > 0 ? Label : Command.Length > 0 ? Command : "(empty)";
|
||||
|
||||
public CommandButton Clone() => new() { Label = Label, Command = Command, Color = Color, Confirm = Confirm };
|
||||
|
||||
/// <summary>A label: one line, no control characters, trimmed, at most <see cref="MaxLabel"/> characters.</summary>
|
||||
public static string CleanLabel(string? text)
|
||||
{
|
||||
string t = CommandLine.OneLine(text);
|
||||
return t.Length > MaxLabel ? t[..MaxLabel].TrimEnd() : t;
|
||||
}
|
||||
|
||||
// ── Colours: "#RRGGBB" in the file, ImGui ABGR in memory ───────────
|
||||
|
||||
/// <summary>"#RRGGBB" for an ABGR colour; "" for 0 (the theme's colour).</summary>
|
||||
public static string ColorText(uint abgr) => abgr == 0
|
||||
? string.Empty
|
||||
: "#" + (abgr & 0xFF).ToString("X2", CultureInfo.InvariantCulture)
|
||||
+ ((abgr >> 8) & 0xFF).ToString("X2", CultureInfo.InvariantCulture)
|
||||
+ ((abgr >> 16) & 0xFF).ToString("X2", CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>"#RRGGBB" or "RRGGBB" to ABGR with full alpha. False (and 0) for anything else.</summary>
|
||||
public static bool TryParseColor(string? text, out uint abgr)
|
||||
{
|
||||
abgr = 0;
|
||||
string t = (text ?? string.Empty).Trim();
|
||||
if (t.StartsWith('#')) t = t[1..];
|
||||
if (t.Length != 6 || !uint.TryParse(t, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out uint rgb)) return false;
|
||||
uint r = (rgb >> 16) & 0xFF, g = (rgb >> 8) & 0xFF, b = rgb & 0xFF;
|
||||
abgr = 0xFF000000u | (b << 16) | (g << 8) | r;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Text that reads on <paramref name="fillAbgr"/>: near-black on a light fill, near-white on a dark one.</summary>
|
||||
public static uint TextOn(uint fillAbgr)
|
||||
{
|
||||
double r = fillAbgr & 0xFF, g = (fillAbgr >> 8) & 0xFF, b = (fillAbgr >> 16) & 0xFF;
|
||||
return 0.299 * r + 0.587 * g + 0.114 * b > 150 ? 0xFF141414u : 0xFFF2F2F2u;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The grid's shape (this character's file).</summary>
|
||||
internal sealed class ButtonLayout
|
||||
{
|
||||
/// <summary>Columns 0 = as many as fit the window's width.</summary>
|
||||
public const int ColumnsMin = 0, ColumnsMax = 12, WidthMin = 40, WidthMax = 320, HeightMin = 18, HeightMax = 96;
|
||||
public const int DefaultWidth = 110, DefaultHeight = 28;
|
||||
|
||||
public int Columns;
|
||||
public int Width = DefaultWidth;
|
||||
public int Height = DefaultHeight;
|
||||
|
||||
public void Clamp()
|
||||
{
|
||||
Columns = Math.Clamp(Columns, ColumnsMin, ColumnsMax);
|
||||
Width = Math.Clamp(Width, WidthMin, WidthMax);
|
||||
Height = Math.Clamp(Height, HeightMin, HeightMax);
|
||||
}
|
||||
|
||||
public ButtonLayout Clone() => new() { Columns = Columns, Width = Width, Height = Height };
|
||||
|
||||
/// <summary>
|
||||
/// How many columns the grid draws: <paramref name="columns"/> when set (1-12), else as many
|
||||
/// <paramref name="buttonWidth"/>-wide buttons with <paramref name="gap"/> between them as fit
|
||||
/// <paramref name="available"/> (at least one, at most 12).
|
||||
/// </summary>
|
||||
public static int ColumnsFor(int columns, float available, float buttonWidth, float gap)
|
||||
{
|
||||
if (columns > 0) return Math.Min(columns, ColumnsMax);
|
||||
if (!(buttonWidth > 0) || !float.IsFinite(available)) return 1;
|
||||
int fit = (int)Math.Floor((available + gap) / (buttonWidth + gap));
|
||||
return Math.Clamp(fit, 1, ColumnsMax);
|
||||
}
|
||||
|
||||
/// <summary>"Auto" or "4".</summary>
|
||||
public static string ColumnsText(int columns) => columns > 0 ? columns.ToString(CultureInfo.InvariantCulture) : "Auto";
|
||||
}
|
||||
|
||||
/// <summary>What a chat line is, as the chat box would send it.</summary>
|
||||
internal enum CommandKind
|
||||
{
|
||||
/// <summary>Nothing to send.</summary>
|
||||
Empty,
|
||||
/// <summary>A slash command: the game's own (/loc, /fillcomps), RynthCore's /rc, a plugin's (/ra, /lua, /rdef ...).</summary>
|
||||
Slash,
|
||||
/// <summary>An emote: *wave*, @e text, ; text.</summary>
|
||||
Emote,
|
||||
/// <summary>A server command: @home, @hp (the server runs it; nothing is said aloud).</summary>
|
||||
Server,
|
||||
/// <summary>Plain text: said aloud in local chat.</summary>
|
||||
Say,
|
||||
}
|
||||
|
||||
/// <summary>A chat line checked: the line as it will be sent, what it is, and why it can't be sent (null: it can).</summary>
|
||||
internal readonly record struct CommandCheck(string Line, CommandKind Kind, string? Problem)
|
||||
{
|
||||
public bool CanSend => Problem == null && Kind != CommandKind.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The rules for a button's chat line.</summary>
|
||||
internal static class CommandLine
|
||||
{
|
||||
/// <summary>As long as a chat line the engine sends (its sections manifest's command limit, a timed command's).</summary>
|
||||
public const int MaxLength = 200;
|
||||
|
||||
private static readonly string[] AtEmotes = { "@emotes", "@emote", "@em", "@e" };
|
||||
|
||||
/// <summary>One line: line breaks and tabs become spaces, other control characters go, trimmed.</summary>
|
||||
public static string OneLine(string? text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return string.Empty;
|
||||
var sb = new StringBuilder(text.Length);
|
||||
foreach (char c in text)
|
||||
{
|
||||
if (c is '\r' or '\n' or '\t') sb.Append(' ');
|
||||
else if (!char.IsControl(c)) sb.Append(c);
|
||||
}
|
||||
return sb.ToString().Trim();
|
||||
}
|
||||
|
||||
/// <summary>A command as stored: one line, at most <see cref="MaxLength"/> characters.</summary>
|
||||
public static string Clean(string? text)
|
||||
{
|
||||
string t = OneLine(text);
|
||||
return t.Length > MaxLength ? t[..MaxLength].TrimEnd() : t;
|
||||
}
|
||||
|
||||
/// <summary>What <paramref name="line"/> (cleaned) is, as RynthCore's chat dispatcher routes it.</summary>
|
||||
public static CommandKind KindOf(string line)
|
||||
{
|
||||
if (line.Length == 0) return CommandKind.Empty;
|
||||
char first = line[0];
|
||||
if (first == '/') return CommandKind.Slash;
|
||||
if (first is ';' or ':') return line.Length > 1 ? CommandKind.Emote : CommandKind.Say;
|
||||
if (first == '*')
|
||||
return line.Length > 2 && line[^1] == '*' && line.AsSpan(1, line.Length - 2).Trim().Length > 0 ? CommandKind.Emote : CommandKind.Say;
|
||||
if (first == '@')
|
||||
{
|
||||
foreach (string e in AtEmotes)
|
||||
if (line.StartsWith(e, StringComparison.OrdinalIgnoreCase) && (line.Length == e.Length || char.IsWhiteSpace(line[e.Length])))
|
||||
return CommandKind.Emote;
|
||||
return line.Length > 1 ? CommandKind.Server : CommandKind.Say;
|
||||
}
|
||||
return CommandKind.Say;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks a button's chat line. Refused: more than one line's worth (the cleaned line is what goes),
|
||||
/// longer than <see cref="MaxLength"/>, and a button that presses buttons ("/ra buttons press"),
|
||||
/// which could press itself forever. Empty is no problem while editing; it just sends nothing.
|
||||
/// </summary>
|
||||
public static CommandCheck Check(string? text)
|
||||
{
|
||||
string raw = text ?? string.Empty;
|
||||
string line = OneLine(raw);
|
||||
CommandKind kind = KindOf(line);
|
||||
if (kind == CommandKind.Empty) return new CommandCheck(line, kind, null);
|
||||
if (line.Length > MaxLength)
|
||||
return new CommandCheck(line[..MaxLength], kind, $"Too long: a chat line is at most {MaxLength} characters.");
|
||||
if (raw.IndexOfAny(new[] { '\r', '\n' }) >= 0)
|
||||
return new CommandCheck(line, kind, "One line only: each button sends one chat line.");
|
||||
if (PressesButtons(line))
|
||||
return new CommandCheck(line, kind, "A button can't press buttons (it could press itself forever).");
|
||||
return new CommandCheck(line, kind, null);
|
||||
}
|
||||
|
||||
/// <summary>"/ra buttons press ..." (or run), in any case and spacing.</summary>
|
||||
public static bool PressesButtons(string line)
|
||||
{
|
||||
string[] w = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (w.Length < 3 || !w[0].Equals("/ra", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (!(w[1].Equals("buttons", StringComparison.OrdinalIgnoreCase) || w[1].Equals("button", StringComparison.OrdinalIgnoreCase))) return false;
|
||||
int at = 2;
|
||||
if (w[at].ToLowerInvariant() is "server" or "all" or "char" or "character" or "me") at++;
|
||||
return w.Length > at && w[at].ToLowerInvariant() is "press" or "run";
|
||||
}
|
||||
|
||||
/// <summary>What pressing it does, in a few words (the edit row's tooltip).</summary>
|
||||
public static string Describe(CommandKind kind) => kind switch
|
||||
{
|
||||
CommandKind.Slash => "A chat command, as if typed (the game's, RynthCore's /rc, or a plugin's: /ra, /lua, /rdef ...).",
|
||||
CommandKind.Emote => "An emote.",
|
||||
CommandKind.Server => "A server command (the server runs it; nothing is said aloud).",
|
||||
CommandKind.Say => "Plain text: said aloud in local chat.",
|
||||
_ => "No command yet: pressing it does nothing.",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The three lists, the layout and their files.</summary>
|
||||
internal sealed class CommandButtonSet
|
||||
{
|
||||
public const string FileName = "command_buttons.json";
|
||||
public const int MaxPerList = 60;
|
||||
public const int FileVersion = 1;
|
||||
|
||||
/// <summary>Locks every read and edit (the window is on the render thread, presses and saves on the tick).</summary>
|
||||
public readonly object Sync = new();
|
||||
private readonly List<CommandButton>[] _lists = { new(), new(), new() };
|
||||
private readonly string[] _paths = { string.Empty, string.Empty, string.Empty };
|
||||
private readonly bool[] _dirty = new bool[3];
|
||||
|
||||
/// <summary>The grid's shape, saved with this character's list. Lock <see cref="Sync"/>.</summary>
|
||||
public ButtonLayout Layout { get; private set; } = new();
|
||||
|
||||
public string Character { get; private set; } = string.Empty;
|
||||
public string Server { get; private set; } = string.Empty;
|
||||
public bool Loaded { get; private set; }
|
||||
/// <summary>When the last edit was made (the tick saves a moment later).</summary>
|
||||
public long ChangedAtMs { get; private set; }
|
||||
|
||||
/// <summary>The list for <paramref name="scope"/>; lock <see cref="Sync"/> around any use.</summary>
|
||||
public List<CommandButton> List(ButtonScope scope) => _lists[(int)scope];
|
||||
|
||||
public static string ScopeName(ButtonScope s) => s switch
|
||||
{
|
||||
ButtonScope.Character => "this character",
|
||||
ButtonScope.Server => "this server",
|
||||
_ => "all characters",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Loads the three lists for the character whose settings folder is <paramref name="charFolder"/>
|
||||
/// (SettingsProfiles\<server>\<character>). A missing file is an empty list; one that can't be
|
||||
/// read is reported in <paramref name="problems"/> and left alone (it isn't saved over until edited).
|
||||
/// </summary>
|
||||
public void Load(string charFolder, List<string>? problems = null)
|
||||
{
|
||||
string? serverFolder = Path.GetDirectoryName(charFolder);
|
||||
string? baseFolder = serverFolder != null ? Path.GetDirectoryName(serverFolder) : null;
|
||||
lock (Sync)
|
||||
{
|
||||
Character = Path.GetFileName(charFolder);
|
||||
Server = serverFolder != null ? Path.GetFileName(serverFolder) : string.Empty;
|
||||
_paths[(int)ButtonScope.Character] = Path.Combine(charFolder, FileName);
|
||||
_paths[(int)ButtonScope.Server] = serverFolder != null ? Path.Combine(serverFolder, FileName) : string.Empty;
|
||||
_paths[(int)ButtonScope.All] = baseFolder != null ? Path.Combine(baseFolder, FileName) : string.Empty;
|
||||
Layout = new ButtonLayout();
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
_lists[i].Clear();
|
||||
_dirty[i] = false;
|
||||
if (_paths[i].Length == 0 || !File.Exists(_paths[i])) continue;
|
||||
try
|
||||
{
|
||||
_lists[i].AddRange(Parse(File.ReadAllText(_paths[i]), out ButtonLayout? layout));
|
||||
if (i == (int)ButtonScope.Character && layout != null) Layout = layout;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
|
||||
{
|
||||
problems?.Add($"{ScopeName((ButtonScope)i)} ({_paths[i]}): {ex.Message}");
|
||||
}
|
||||
}
|
||||
Loaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forgets the character (logout).</summary>
|
||||
public void Unload()
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
for (int i = 0; i < 3; i++) { _lists[i].Clear(); _paths[i] = string.Empty; _dirty[i] = false; }
|
||||
Layout = new ButtonLayout();
|
||||
Character = Server = string.Empty;
|
||||
Loaded = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A list (or, for this character, the layout) was edited. Call under <see cref="Sync"/>.</summary>
|
||||
public void MarkChanged(ButtonScope scope, long nowMs)
|
||||
{
|
||||
_dirty[(int)scope] = true;
|
||||
ChangedAtMs = nowMs;
|
||||
}
|
||||
|
||||
public bool AnyDirty { get { lock (Sync) return _dirty[0] || _dirty[1] || _dirty[2]; } }
|
||||
|
||||
/// <summary>Writes every edited list (temp file, then replace). Problems go to <paramref name="problems"/>.</summary>
|
||||
public void SaveDirty(List<string>? problems = null)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
if (!_dirty[i] || _paths[i].Length == 0) continue;
|
||||
_dirty[i] = false;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(_paths[i])!);
|
||||
string tmp = _paths[i] + ".tmp";
|
||||
File.WriteAllText(tmp, Serialize(_lists[i], i == (int)ButtonScope.Character ? Layout : null));
|
||||
File.Move(tmp, _paths[i], overwrite: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
problems?.Add($"{ScopeName((ButtonScope)i)} ({_paths[i]}): {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a button to <paramref name="scope"/>'s list and marks it changed. Null when the list is full
|
||||
/// (<see cref="MaxPerList"/>). Call under <see cref="Sync"/>.
|
||||
/// </summary>
|
||||
public CommandButton? Add(ButtonScope scope, string? label, string? command, long nowMs)
|
||||
{
|
||||
List<CommandButton> list = List(scope);
|
||||
if (list.Count >= MaxPerList) return null;
|
||||
var b = new CommandButton { Label = CommandButton.CleanLabel(label), Command = CommandLine.Clean(command) };
|
||||
list.Add(b);
|
||||
MarkChanged(scope, nowMs);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Moves button <paramref name="index"/> by <paramref name="delta"/> places in its list. False when it can't.</summary>
|
||||
public bool Move(ButtonScope scope, int index, int delta, long nowMs)
|
||||
{
|
||||
List<CommandButton> list = List(scope);
|
||||
int to = index + delta;
|
||||
if (index < 0 || index >= list.Count || to < 0 || to >= list.Count || delta == 0) return false;
|
||||
CommandButton b = list[index];
|
||||
list.RemoveAt(index);
|
||||
list.Insert(to, b);
|
||||
MarkChanged(scope, nowMs);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Copy from another character ─────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The other characters on this server with buttons of their own (their folder names, sorted), for
|
||||
/// "Copy from". Empty before a load.
|
||||
/// </summary>
|
||||
public List<string> OtherCharacters()
|
||||
{
|
||||
var names = new List<string>();
|
||||
string own, serverFolder;
|
||||
lock (Sync)
|
||||
{
|
||||
own = _paths[(int)ButtonScope.Character];
|
||||
serverFolder = own.Length > 0 ? Path.GetDirectoryName(Path.GetDirectoryName(own)) ?? string.Empty : string.Empty;
|
||||
}
|
||||
if (serverFolder.Length == 0 || !Directory.Exists(serverFolder)) return names;
|
||||
try
|
||||
{
|
||||
foreach (string dir in Directory.GetDirectories(serverFolder))
|
||||
{
|
||||
string name = Path.GetFileName(dir);
|
||||
if (name.Equals(Character, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (File.Exists(Path.Combine(dir, FileName))) names.Add(name);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
|
||||
names.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
return names;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends <paramref name="character"/>'s own buttons (same server) to this character's list, as many as
|
||||
/// fit. Returns how many were added; -1 when that character's buttons can't be read (the reason in
|
||||
/// <paramref name="problem"/>).
|
||||
/// </summary>
|
||||
public int CopyFrom(string character, long nowMs, out string problem)
|
||||
{
|
||||
problem = string.Empty;
|
||||
string own;
|
||||
lock (Sync) own = _paths[(int)ButtonScope.Character];
|
||||
string? serverFolder = own.Length > 0 ? Path.GetDirectoryName(Path.GetDirectoryName(own)) : null;
|
||||
if (serverFolder == null || string.IsNullOrWhiteSpace(character) || character.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0
|
||||
|| character is "." or "..")
|
||||
{
|
||||
problem = "no such character";
|
||||
return -1;
|
||||
}
|
||||
string path = Path.Combine(serverFolder, character, FileName);
|
||||
List<CommandButton> theirs;
|
||||
try { theirs = Parse(File.ReadAllText(path), out _); }
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
|
||||
{
|
||||
problem = ex is FileNotFoundException or DirectoryNotFoundException ? "they have no buttons" : ex.Message;
|
||||
return -1;
|
||||
}
|
||||
int added = 0;
|
||||
lock (Sync)
|
||||
{
|
||||
List<CommandButton> list = List(ButtonScope.Character);
|
||||
foreach (CommandButton b in theirs)
|
||||
{
|
||||
if (list.Count >= MaxPerList) break;
|
||||
list.Add(b.Clone());
|
||||
added++;
|
||||
}
|
||||
if (added > 0) MarkChanged(ButtonScope.Character, nowMs);
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
// ── File format ─────────────────────────────────────────────────────
|
||||
// {"version":1,"layout":{"columns","width","height"},"buttons":[{"label","command","color":"#RRGGBB","confirm"}]}
|
||||
// "layout" only in a character's file; "color" left out for the theme's colour.
|
||||
|
||||
public static string Serialize(IReadOnlyList<CommandButton> list, ButtonLayout? layout)
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("version", FileVersion);
|
||||
if (layout != null)
|
||||
{
|
||||
w.WriteStartObject("layout");
|
||||
w.WriteNumber("columns", layout.Columns);
|
||||
w.WriteNumber("width", layout.Width);
|
||||
w.WriteNumber("height", layout.Height);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteStartArray("buttons");
|
||||
foreach (CommandButton b in list)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("label", b.Label);
|
||||
w.WriteString("command", b.Command);
|
||||
if (b.Color != 0) w.WriteString("color", CommandButton.ColorText(b.Color));
|
||||
w.WriteBoolean("confirm", b.Confirm);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(stream.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>The buttons in a file (cleaned, at most <see cref="MaxPerList"/>), and its layout if it has one (clamped).</summary>
|
||||
public static List<CommandButton> Parse(string json, out ButtonLayout? layout)
|
||||
{
|
||||
layout = null;
|
||||
var list = new List<CommandButton>();
|
||||
using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
|
||||
JsonElement root = doc.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object) return list;
|
||||
if (root.TryGetProperty("layout", out JsonElement l) && l.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
layout = new ButtonLayout
|
||||
{
|
||||
Columns = Int(l, "columns", 0),
|
||||
Width = Int(l, "width", ButtonLayout.DefaultWidth),
|
||||
Height = Int(l, "height", ButtonLayout.DefaultHeight),
|
||||
};
|
||||
layout.Clamp();
|
||||
}
|
||||
if (!root.TryGetProperty("buttons", out JsonElement arr) || arr.ValueKind != JsonValueKind.Array) return list;
|
||||
foreach (JsonElement e in arr.EnumerateArray())
|
||||
{
|
||||
if (list.Count >= MaxPerList) break;
|
||||
if (e.ValueKind != JsonValueKind.Object) continue;
|
||||
var b = new CommandButton
|
||||
{
|
||||
Label = CommandButton.CleanLabel(Str(e, "label")),
|
||||
Command = CommandLine.Clean(Str(e, "command")),
|
||||
Confirm = e.TryGetProperty("confirm", out JsonElement c) && c.ValueKind == JsonValueKind.True,
|
||||
};
|
||||
if (CommandButton.TryParseColor(Str(e, "color"), out uint color)) b.Color = color;
|
||||
list.Add(b);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static string? Str(JsonElement e, string name) =>
|
||||
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;
|
||||
|
||||
private static int Int(JsonElement e, string name, int fallback) =>
|
||||
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out double d) && double.IsFinite(d)
|
||||
? (int)Math.Clamp(Math.Round(d), int.MinValue, int.MaxValue)
|
||||
: fallback;
|
||||
}
|
||||
|
|
@ -0,0 +1,623 @@
|
|||
// ============================================================================
|
||||
// RynthAi - CommandButtons/CommandButtonsWindow.cs
|
||||
// The Command Buttons window (2026-11-26): a grid of buttons, each sending one
|
||||
// chat line, and an edit view to make them. RynthCore hosts the window (the
|
||||
// sections manifest's "commandbuttons" window, plugin API v89: header,
|
||||
// pop-out, resize, remembered place; no bar button: the dashboard's options
|
||||
// menu, /ra buttons and Find a Feature open it) and calls Draw through
|
||||
// RynthPluginRenderEmbed.
|
||||
//
|
||||
// Grid: this character's buttons, then this server's, then every character's,
|
||||
// as many columns as set (Auto: as many as fit). A click sends the line (asks
|
||||
// first for a button with "Ask" ticked); a right-click opens the edit view on
|
||||
// that button's list. The pencil in the header opens the edit view.
|
||||
//
|
||||
// Edit view: the three lists as tabs; per button: move up / down, label,
|
||||
// command (with a mark saying what it is, or why it can't be sent), colour,
|
||||
// Ask, Send now and Remove; Add button; Copy from another character (this
|
||||
// character's tab); the grid's columns and button size.
|
||||
//
|
||||
// AC's render thread. Edits go straight into the lists under the set's lock and
|
||||
// mark them changed (the tick saves them a moment later); presses are queued
|
||||
// for the tick. Looks: Shared/RynthUi (the player's theme).
|
||||
// ============================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using System.Threading;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.Plugin.Shared.RynthUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.CommandButtons;
|
||||
|
||||
internal sealed class CommandButtonsWindow
|
||||
{
|
||||
private readonly CommandButtonSet _set;
|
||||
private readonly Action<ButtonScope, int> _press; // queued for the tick
|
||||
private bool _edit;
|
||||
private ButtonScope _scope = ButtonScope.Character;
|
||||
private int _focusRow = -1; // a row just added: focus its label box
|
||||
|
||||
// A button that asks first: which, and the line it will send.
|
||||
private ButtonScope _confirmScope;
|
||||
private int _confirmIndex = -1;
|
||||
private string _confirmLine = string.Empty;
|
||||
private bool _openConfirm;
|
||||
|
||||
// Copy from another character (read when the edit view opens and when the list is opened).
|
||||
private List<string> _others = new();
|
||||
private int _copyPick;
|
||||
|
||||
// The header's note: the last press, or a problem (set from the tick).
|
||||
private volatile string _note = string.Empty;
|
||||
private long _noteAtMs;
|
||||
private const long NoteMs = 5000;
|
||||
|
||||
private float _k = 1f;
|
||||
private float Px(float v) => v * _k;
|
||||
private const string ConfirmId = "##cb_confirm";
|
||||
|
||||
private const string HelpText =
|
||||
"Buttons that each send one chat line, as if you typed it in the chat box: a command (/ra start, " +
|
||||
"/lua start threads, /rdef weapons, /loc), an emote (*wave*, *snow angel*), a server command (@home) " +
|
||||
"or plain text (said aloud).\n\n" +
|
||||
"The pencil opens the edit view: a label and a command for each button, its colour, and Ask (it asks " +
|
||||
"before it sends: for commands that are hard to take back). Columns and the button size are there too.\n\n" +
|
||||
"Three lists: This character, This server (every character on this server) and All characters; the " +
|
||||
"grid shows all three. Copy from takes another character's buttons.\n\n" +
|
||||
"/ra buttons opens this window; /ra buttons list | add <label> = <command> | remove <n> | press <n> " +
|
||||
"(add \"server\" or \"all\" after buttons for the other lists). Command buttons is also in the " +
|
||||
"RynthAi window's options menu.";
|
||||
|
||||
public CommandButtonsWindow(CommandButtonSet set, Action<ButtonScope, int> press)
|
||||
{
|
||||
_set = set;
|
||||
_press = press;
|
||||
}
|
||||
|
||||
/// <summary>The header's note for a few seconds ("Sent: Start"). Any thread.</summary>
|
||||
public void Note(string text)
|
||||
{
|
||||
_note = text;
|
||||
Volatile.Write(ref _noteAtMs, Environment.TickCount64);
|
||||
}
|
||||
|
||||
/// <summary>Opens the edit view on <paramref name="scope"/>'s list (the /ra buttons edit command, a right-click).</summary>
|
||||
public void OpenEdit(ButtonScope scope)
|
||||
{
|
||||
_edit = true;
|
||||
_scope = scope;
|
||||
_others = _set.OtherCharacters();
|
||||
}
|
||||
|
||||
/// <summary>Draws the window body into the current ImGui window and returns the size it would like. Render thread.</summary>
|
||||
public Vector2 Draw()
|
||||
{
|
||||
_k = Math.Max(0.5f, Font(RynthUiFont.Ui11).FontSize / 11f);
|
||||
Vector2 origin = ImGui.GetCursorScreenPos();
|
||||
Vector2 size = ImGui.GetContentRegionAvail();
|
||||
Vector2 want = new(Px(_edit ? 680 : 360), Px(_edit ? 360 : 160));
|
||||
if (size.X < 60 || size.Y < 40) return want;
|
||||
ImDrawListPtr frame = ImGui.GetWindowDrawList();
|
||||
frame.AddRectFilled(origin, origin + size, Background, 4);
|
||||
using (PushFont(RynthUiFont.Ui11))
|
||||
{
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4));
|
||||
ImGui.SetCursorScreenPos(origin + new Vector2(6, 6));
|
||||
ImGui.Indent(6);
|
||||
float w = size.X - 12;
|
||||
float bottom = origin.Y + size.Y - 6;
|
||||
lock (_set.Sync)
|
||||
{
|
||||
if (!_set.Loaded)
|
||||
Label("Command buttons load once you are in the world.", Mute);
|
||||
else if (_edit)
|
||||
DrawEdit(w, bottom);
|
||||
else
|
||||
want = DrawGrid(w, bottom, want);
|
||||
}
|
||||
DrawConfirm();
|
||||
ImGui.Unindent(6);
|
||||
ImGui.PopStyleVar();
|
||||
}
|
||||
frame.AddRect(origin, origin + size, Border, 4);
|
||||
return want;
|
||||
}
|
||||
|
||||
// ── The grid ────────────────────────────────────────────────────────
|
||||
|
||||
private Vector2 DrawGrid(float w, float bottom, Vector2 want)
|
||||
{
|
||||
Vector2 p = ImGui.GetCursorScreenPos();
|
||||
float h = Px(20), icon = Px(22);
|
||||
// Header: the note on the left, edit and help on the right.
|
||||
string note = _note;
|
||||
if (note.Length > 0 && Environment.TickCount64 - Volatile.Read(ref _noteAtMs) < NoteMs)
|
||||
{
|
||||
ImDrawListPtr hdl = ImGui.GetWindowDrawList();
|
||||
hdl.PushClipRect(p, new Vector2(p.X + w - 2 * icon - Px(8), p.Y + h), true);
|
||||
hdl.AddText(new Vector2(p.X, p.Y + (h - ImGui.GetFontSize()) * 0.5f), Mute, note);
|
||||
hdl.PopClipRect();
|
||||
}
|
||||
if (IconButton("##cb_edit", RynthIcons.PencilSimple, new Vector2(p.X + w - 2 * icon - Px(4), p.Y), new Vector2(icon, h), Text, ButtonFill, font: RynthUiFont.Ui11))
|
||||
OpenEdit(ButtonScope.Character);
|
||||
ImGui.SetItemTooltip("Edit the buttons: add, remove, move, label, command, colour; columns and size.");
|
||||
HelpIcon(new Vector2(p.X + w - icon, p.Y), new Vector2(icon, h));
|
||||
ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h + Px(4)));
|
||||
ImGui.Dummy(Vector2.Zero);
|
||||
|
||||
int total = 0;
|
||||
for (int s = 0; s < 3; s++) total += _set.List((ButtonScope)s).Count;
|
||||
if (total == 0)
|
||||
{
|
||||
ImGui.PushTextWrapPos(ImGui.GetCursorPosX() + w);
|
||||
Label("No buttons yet. Each button sends one chat line: /ra start, *wave*, @home, /lua start <script>...", Mute);
|
||||
ImGui.PopTextWrapPos();
|
||||
Vector2 a = ImGui.GetCursorScreenPos();
|
||||
string label = "Add a button";
|
||||
if (Button("##cb_first", label, a, new Vector2(ButtonWidth(label) + Px(8), Px(22)), Text, ButtonFill, border: Accent))
|
||||
{
|
||||
OpenEdit(ButtonScope.Character);
|
||||
AddRow();
|
||||
}
|
||||
ImGui.SetCursorScreenPos(new Vector2(a.X, a.Y + Px(26)));
|
||||
ImGui.Dummy(Vector2.Zero);
|
||||
return want;
|
||||
}
|
||||
|
||||
ButtonLayout layout = _set.Layout;
|
||||
float bw = Px(layout.Width), bh = Px(layout.Height), gap = Px(4);
|
||||
int cols = ButtonLayout.ColumnsFor(layout.Columns, w, bw, gap);
|
||||
int rows = (total + cols - 1) / cols;
|
||||
float gridW = cols * bw + (cols - 1) * gap, gridH = rows * bh + (rows - 1) * gap;
|
||||
float top = ImGui.GetCursorScreenPos().Y;
|
||||
float bodyH = Math.Max(bh, bottom - top);
|
||||
ImGui.BeginChild("##cb_grid", new Vector2(w, bodyH), ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground);
|
||||
Vector2 g = ImGui.GetCursorScreenPos();
|
||||
int n = 0;
|
||||
for (int s = 0; s < 3; s++)
|
||||
{
|
||||
var scope = (ButtonScope)s;
|
||||
List<CommandButton> list = _set.List(scope);
|
||||
for (int i = 0; i < list.Count; i++, n++)
|
||||
{
|
||||
CommandButton b = list[i];
|
||||
var at = new Vector2(g.X + n % cols * (bw + gap), g.Y + n / cols * (bh + gap));
|
||||
uint fill = b.Color != 0 ? b.Color : ButtonFill;
|
||||
uint fg = b.Color != 0 ? CommandButton.TextOn(b.Color) : Text;
|
||||
bool can = b.Command.Length > 0;
|
||||
string id = "##cb_b" + s.ToString(CultureInfo.InvariantCulture) + "_" + i.ToString(CultureInfo.InvariantCulture);
|
||||
if (Button(id, b.Shown, at, new Vector2(bw, bh), fg, fill, enabled: can))
|
||||
Press(scope, i, b);
|
||||
if (ImGui.IsItemClicked(ImGuiMouseButton.Right))
|
||||
OpenEdit(scope);
|
||||
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
|
||||
SafeImGui.SetTooltip(Tooltip(b, scope));
|
||||
}
|
||||
}
|
||||
ImGui.SetCursorScreenPos(new Vector2(g.X, g.Y + gridH));
|
||||
ImGui.Dummy(new Vector2(gridW, 0));
|
||||
ImGui.EndChild();
|
||||
// The size it would like: the grid with fixed columns; the window's width when they fit to it.
|
||||
float wantW = layout.Columns > 0 ? gridW + 12 : w + 12;
|
||||
return new Vector2(Math.Max(Px(160), wantW), h + Px(4) + gridH + 16);
|
||||
}
|
||||
|
||||
private static string Tooltip(CommandButton b, ButtonScope scope)
|
||||
{
|
||||
string t = b.Command.Length > 0 ? b.Command : "No command yet (right-click to edit).";
|
||||
if (b.Label.Length > 0 && b.Command.Length > 0) t = b.Label + "\n" + t;
|
||||
if (b.Confirm) t += "\nAsks before it sends.";
|
||||
return t + "\n(" + CommandButtonSet.ScopeName(scope) + "; right-click to edit)";
|
||||
}
|
||||
|
||||
private void Press(ButtonScope scope, int index, CommandButton b)
|
||||
{
|
||||
if (!b.Confirm) { _press(scope, index); return; }
|
||||
_confirmScope = scope;
|
||||
_confirmIndex = index;
|
||||
_confirmLine = b.Command;
|
||||
_openConfirm = true;
|
||||
}
|
||||
|
||||
private void DrawConfirm()
|
||||
{
|
||||
if (_openConfirm) { ImGui.OpenPopup(ConfirmId); _openConfirm = false; }
|
||||
if (!ImGui.BeginPopup(ConfirmId)) return;
|
||||
SafeImGui.Text("Send " + _confirmLine + " ?");
|
||||
Vector2 p = ImGui.GetCursorScreenPos();
|
||||
float h = Px(22), bw = Px(70);
|
||||
if (Button("##cb_yes", "Send", p, new Vector2(bw, h), Text, ButtonFill, border: Accent))
|
||||
{
|
||||
if (_confirmIndex >= 0) _press(_confirmScope, _confirmIndex);
|
||||
_confirmIndex = -1;
|
||||
ImGui.CloseCurrentPopup();
|
||||
}
|
||||
if (Button("##cb_no", "Cancel", new Vector2(p.X + bw + Px(6), p.Y), new Vector2(bw, h), Text, ButtonFill))
|
||||
{
|
||||
_confirmIndex = -1;
|
||||
ImGui.CloseCurrentPopup();
|
||||
}
|
||||
ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h + Px(4)));
|
||||
ImGui.Dummy(new Vector2(2 * bw + Px(6), 0));
|
||||
ImGui.EndPopup();
|
||||
}
|
||||
|
||||
private void HelpIcon(Vector2 at, Vector2 size)
|
||||
{
|
||||
IconButton("##cb_help", RynthIcons.Info, at, size, Mute, ButtonFill, font: RynthUiFont.Ui11);
|
||||
if (!ImGui.IsItemHovered()) return;
|
||||
ImGui.BeginTooltip();
|
||||
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 32);
|
||||
ImGui.TextUnformatted(HelpText);
|
||||
ImGui.PopTextWrapPos();
|
||||
ImGui.EndTooltip();
|
||||
}
|
||||
|
||||
// ── The edit view (under the set's lock) ────────────────────────────
|
||||
|
||||
private void DrawEdit(float w, float bottom)
|
||||
{
|
||||
DrawTabs(w);
|
||||
DrawLayoutRow(w);
|
||||
DrawHeader(w);
|
||||
float bodyH = Math.Max(Px(30), bottom - ImGui.GetCursorScreenPos().Y - Px(30));
|
||||
ImGui.PushStyleColor(ImGuiCol.ChildBg, Field);
|
||||
ImGui.BeginChild("##cb_rows", new Vector2(w, bodyH));
|
||||
DrawRows();
|
||||
ImGui.EndChild();
|
||||
ImGui.PopStyleColor();
|
||||
DrawAddRow(w);
|
||||
}
|
||||
|
||||
private void DrawTabs(float w)
|
||||
{
|
||||
Vector2 p = ImGui.GetCursorScreenPos();
|
||||
float h = Px(22), x = p.X, icon = Px(22);
|
||||
for (int s = 0; s < 3; s++)
|
||||
{
|
||||
var scope = (ButtonScope)s;
|
||||
string who = scope switch
|
||||
{
|
||||
ButtonScope.Character => _set.Character.Length > 0 ? _set.Character : "This character",
|
||||
ButtonScope.Server => _set.Server.Length > 0 ? _set.Server : "This server",
|
||||
_ => "All characters",
|
||||
};
|
||||
int n = _set.List(scope).Count;
|
||||
string label = n > 0 ? $"{who} ({n})" : who;
|
||||
float bw = ButtonWidth(label) + Px(8);
|
||||
bool on = _scope == scope;
|
||||
if (Button("##cb_tab" + s.ToString(CultureInfo.InvariantCulture), label, new Vector2(x, p.Y), new Vector2(bw, h),
|
||||
on ? Text : Mute, on ? Selected : ButtonFill, border: on ? Accent : 0))
|
||||
{
|
||||
_scope = scope;
|
||||
_focusRow = -1;
|
||||
}
|
||||
ImGui.SetItemTooltip(scope switch
|
||||
{
|
||||
ButtonScope.Character => "Buttons only this character has.",
|
||||
ButtonScope.Server => "Buttons every character on this server has.",
|
||||
_ => "Buttons every character has, on every server.",
|
||||
});
|
||||
x += bw + Px(4);
|
||||
}
|
||||
string done = "Done";
|
||||
float dw = ButtonWidth(done) + Px(8);
|
||||
if (Button("##cb_done", done, new Vector2(p.X + w - icon - Px(4) - dw, p.Y), new Vector2(dw, h), Text, ButtonFill, border: Accent))
|
||||
_edit = false;
|
||||
ImGui.SetItemTooltip("Back to the buttons (edits are saved as you make them).");
|
||||
HelpIcon(new Vector2(p.X + w - icon, p.Y), new Vector2(icon, h));
|
||||
ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h + Px(6)));
|
||||
ImGui.Dummy(Vector2.Zero);
|
||||
}
|
||||
|
||||
/// <summary>Columns [-] Auto [+], Width and Height sliders: this character's layout.</summary>
|
||||
private void DrawLayoutRow(float w)
|
||||
{
|
||||
ButtonLayout l = _set.Layout;
|
||||
Vector2 p = ImGui.GetCursorScreenPos();
|
||||
float h = Px(20), x = p.X;
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
float ty = p.Y + (h - ImGui.GetFontSize()) * 0.5f;
|
||||
|
||||
dl.AddText(new Vector2(x, ty), Mute, "Columns");
|
||||
x += ImGui.CalcTextSize("Columns").X + Px(6);
|
||||
if (IconButton("##cb_colless", RynthIcons.Minus, new Vector2(x, p.Y), new Vector2(Px(20), h), Text, ButtonFill,
|
||||
enabled: l.Columns > ButtonLayout.ColumnsMin, font: RynthUiFont.Ui11))
|
||||
SetLayout(() => l.Columns--);
|
||||
ImGui.SetItemTooltip("Fewer columns (Auto: as many as fit the window).");
|
||||
x += Px(22);
|
||||
string cols = ButtonLayout.ColumnsText(l.Columns);
|
||||
float cw = Px(36);
|
||||
dl.AddText(new Vector2(x + (cw - ImGui.CalcTextSize(cols).X) * 0.5f, ty), Text, cols);
|
||||
x += cw;
|
||||
if (IconButton("##cb_colmore", RynthIcons.Plus, new Vector2(x, p.Y), new Vector2(Px(20), h), Text, ButtonFill,
|
||||
enabled: l.Columns < ButtonLayout.ColumnsMax, font: RynthUiFont.Ui11))
|
||||
SetLayout(() => l.Columns++);
|
||||
ImGui.SetItemTooltip("More columns (up to " + ButtonLayout.ColumnsMax.ToString(CultureInfo.InvariantCulture) + ").");
|
||||
x += Px(32);
|
||||
|
||||
ImGui.PushStyleColor(ImGuiCol.FrameBg, Field);
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(Px(4), Math.Max(1, (h - ImGui.GetFontSize()) * 0.5f)));
|
||||
float slider = Math.Clamp((w - (x - p.X)) * 0.5f - Px(50), Px(70), Px(150));
|
||||
x = Slider(dl, x, p.Y, ty, slider, "Width", "##cb_w", l.Width, ButtonLayout.WidthMin, ButtonLayout.WidthMax, v => l.Width = v,
|
||||
"Each button's width.");
|
||||
Slider(dl, x, p.Y, ty, slider, "Height", "##cb_h", l.Height, ButtonLayout.HeightMin, ButtonLayout.HeightMax, v => l.Height = v,
|
||||
"Each button's height.");
|
||||
ImGui.PopStyleVar();
|
||||
ImGui.PopStyleColor();
|
||||
|
||||
ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h + Px(6)));
|
||||
ImGui.Dummy(Vector2.Zero);
|
||||
}
|
||||
|
||||
private float Slider(ImDrawListPtr dl, float x, float y, float ty, float width, string label, string id, int value, int min, int max,
|
||||
Action<int> set, string tip)
|
||||
{
|
||||
dl.AddText(new Vector2(x, ty), Mute, label);
|
||||
x += ImGui.CalcTextSize(label).X + Px(6);
|
||||
ImGui.SetCursorScreenPos(new Vector2(x, y));
|
||||
ImGui.SetNextItemWidth(width);
|
||||
int v = value;
|
||||
if (ImGui.SliderInt(id, ref v, min, max)) SetLayout(() => set(Math.Clamp(v, min, max)));
|
||||
ImGui.SetItemTooltip(tip);
|
||||
return x + width + Px(14);
|
||||
}
|
||||
|
||||
private void SetLayout(Action change)
|
||||
{
|
||||
change();
|
||||
_set.Layout.Clamp();
|
||||
_set.MarkChanged(ButtonScope.Character, Environment.TickCount64);
|
||||
}
|
||||
|
||||
// ── Columns of the edit rows ────────────────────────────────────────
|
||||
|
||||
private float MoveW => Px(44);
|
||||
private float LabelW => Px(110);
|
||||
private float MarkW => Px(18);
|
||||
private float ColorW => Px(44);
|
||||
private float AskW => Px(30);
|
||||
private float BtnW => Px(24);
|
||||
|
||||
private float CommandW(float w) => Math.Max(Px(100), w - MoveW - LabelW - MarkW - ColorW - AskW - 2 * BtnW - Px(40));
|
||||
|
||||
private void DrawHeader(float w)
|
||||
{
|
||||
Vector2 p = ImGui.GetCursorScreenPos();
|
||||
float h = Px(16), x = p.X + Px(4);
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
void Head(string text, float width, string tip)
|
||||
{
|
||||
if (text.Length > 0)
|
||||
{
|
||||
ImGui.SetCursorScreenPos(new Vector2(x, p.Y));
|
||||
ImGui.InvisibleButton("##cbh_" + text, new Vector2(Math.Max(1, width), h));
|
||||
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(tip);
|
||||
dl.AddText(new Vector2(x, p.Y + (h - ImGui.GetFontSize()) * 0.5f), Mute, text);
|
||||
}
|
||||
x += width + Px(4);
|
||||
}
|
||||
Head("Order", MoveW, "Move a button earlier or later in the grid.");
|
||||
Head("Label", LabelW, "What the button says (empty: it shows its command).");
|
||||
Head("Command", CommandW(w) + MarkW + Px(4), "The one chat line it sends, as you would type it.");
|
||||
Head("Colour", ColorW, "The button's colour (the arrow puts the theme's back).");
|
||||
Head("Ask", AskW, "Asks before it sends: for commands that are hard to take back.");
|
||||
ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h + Px(2)));
|
||||
ImGui.Dummy(Vector2.Zero);
|
||||
}
|
||||
|
||||
private void DrawRows()
|
||||
{
|
||||
List<CommandButton> list = _set.List(_scope);
|
||||
float w = ImGui.GetContentRegionAvail().X;
|
||||
if (list.Count == 0)
|
||||
{
|
||||
ImGui.SetCursorPos(new Vector2(Px(8), Px(8)));
|
||||
ImGui.PushTextWrapPos(w - Px(8));
|
||||
Label(_scope switch
|
||||
{
|
||||
ButtonScope.Character => "No buttons for this character. Add button puts one here.",
|
||||
ButtonScope.Server => "No buttons for every character on this server. Add button puts one here.",
|
||||
_ => "No buttons for every character. Add button puts one here.",
|
||||
}, Mute);
|
||||
ImGui.PopTextWrapPos();
|
||||
return;
|
||||
}
|
||||
float rowH = Px(24);
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
int remove = -1, moveFrom = -1, moveBy = 0;
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
CommandButton b = list[i];
|
||||
ImGui.PushID(i);
|
||||
Vector2 p = ImGui.GetCursorScreenPos();
|
||||
if (i % 2 == 1) dl.AddRectFilled(p, p + new Vector2(w, rowH), RowAlt);
|
||||
float x = p.X + Px(4), y = p.Y + Px(2);
|
||||
float fieldH = rowH - Px(4);
|
||||
var small = new Vector2(Px(20), fieldH);
|
||||
|
||||
if (IconButton("##up", RynthIcons.CaretUp, new Vector2(x, y), small, Text, ButtonFill, enabled: i > 0, font: RynthUiFont.Ui11))
|
||||
{ moveFrom = i; moveBy = -1; }
|
||||
ImGui.SetItemTooltip("Earlier in the grid.");
|
||||
if (IconButton("##dn", RynthIcons.CaretDown, new Vector2(x + Px(22), y), small, Text, ButtonFill, enabled: i < list.Count - 1, font: RynthUiFont.Ui11))
|
||||
{ moveFrom = i; moveBy = 1; }
|
||||
ImGui.SetItemTooltip("Later in the grid.");
|
||||
x += MoveW + Px(4);
|
||||
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(Px(4), Math.Max(1, (fieldH - ImGui.GetFontSize()) * 0.5f)));
|
||||
ImGui.PushStyleColor(ImGuiCol.FrameBg, Background);
|
||||
|
||||
ImGui.SetCursorScreenPos(new Vector2(x, y));
|
||||
ImGui.SetNextItemWidth(LabelW);
|
||||
if (_focusRow == i) { ImGui.SetKeyboardFocusHere(); _focusRow = -1; }
|
||||
string label = b.Label;
|
||||
if (ImGui.InputTextWithHint("##label", "Label", ref label, (uint)CommandButton.MaxLabel + 1))
|
||||
{
|
||||
b.Label = CommandButton.CleanLabel(label);
|
||||
Changed();
|
||||
}
|
||||
x += LabelW + Px(4);
|
||||
|
||||
ImGui.SetCursorScreenPos(new Vector2(x, y));
|
||||
ImGui.SetNextItemWidth(CommandW(w));
|
||||
string cmd = b.Command;
|
||||
if (ImGui.InputTextWithHint("##cmd", "/ra start, *wave*, @home ...", ref cmd, (uint)CommandLine.MaxLength + 1))
|
||||
{
|
||||
b.Command = CommandLine.Clean(cmd);
|
||||
Changed();
|
||||
}
|
||||
x += CommandW(w) + Px(4);
|
||||
|
||||
ImGui.PopStyleColor();
|
||||
ImGui.PopStyleVar();
|
||||
|
||||
// What the line is, or why it can't be sent.
|
||||
CommandCheck check = CommandLine.Check(b.Command);
|
||||
bool bad = check.Problem != null;
|
||||
string mark = bad ? RynthIcons.Warning : check.Kind == CommandKind.Empty ? RynthIcons.Info : RynthIcons.Check;
|
||||
uint markColor = bad ? Red : check.Kind == CommandKind.Empty ? Mute : check.Kind == CommandKind.Say ? Highlight : Green;
|
||||
ImGui.SetCursorScreenPos(new Vector2(x, y));
|
||||
ImGui.InvisibleButton("##mark", new Vector2(MarkW, fieldH));
|
||||
DrawCentered(dl, Font(RynthUiFont.Ui11), mark, new Vector2(x, y), new Vector2(MarkW, fieldH), markColor);
|
||||
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(check.Problem ?? CommandLine.Describe(check.Kind));
|
||||
x += MarkW + Px(4);
|
||||
|
||||
// Colour: the picker's swatch, and the theme's colour back.
|
||||
uint shown = b.Color != 0 ? b.Color : ButtonFill;
|
||||
var rgb = new Vector3((shown & 0xFF) / 255f, ((shown >> 8) & 0xFF) / 255f, ((shown >> 16) & 0xFF) / 255f);
|
||||
ImGui.SetCursorScreenPos(new Vector2(x, y));
|
||||
if (ImGui.ColorEdit3("##color", ref rgb, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
|
||||
{
|
||||
b.Color = 0xFF000000u | (Byte(rgb.Z) << 16) | (Byte(rgb.Y) << 8) | Byte(rgb.X);
|
||||
Changed();
|
||||
}
|
||||
ImGui.SetItemTooltip(b.Color != 0 ? "This button's colour: " + CommandButton.ColorText(b.Color) : "The theme's button colour: click to pick one.");
|
||||
if (b.Color != 0)
|
||||
{
|
||||
if (IconButton("##nocolor", RynthIcons.ArrowCounterClockwise, new Vector2(x + Px(24), y), small, Mute, ButtonFill, font: RynthUiFont.Ui11))
|
||||
{
|
||||
b.Color = 0;
|
||||
Changed();
|
||||
}
|
||||
ImGui.SetItemTooltip("The theme's colour again.");
|
||||
}
|
||||
x += ColorW + Px(4);
|
||||
|
||||
ImGui.SetCursorScreenPos(new Vector2(x + (AskW - ImGui.GetFrameHeight()) * 0.5f, y));
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(Px(3), Math.Max(1, (fieldH - ImGui.GetFontSize()) * 0.5f)));
|
||||
bool ask = b.Confirm;
|
||||
if (ImGui.Checkbox("##ask", ref ask)) { b.Confirm = ask; Changed(); }
|
||||
ImGui.PopStyleVar();
|
||||
ImGui.SetItemTooltip("Ask before it sends.");
|
||||
x += AskW + Px(4);
|
||||
|
||||
if (IconButton("##send", RynthIcons.Play, new Vector2(x, y), new Vector2(BtnW, fieldH), Text, ButtonFill,
|
||||
enabled: check.CanSend, font: RynthUiFont.Ui11))
|
||||
_press(_scope, i);
|
||||
ImGui.SetItemTooltip("Send it now (no question asked).");
|
||||
x += BtnW + Px(4);
|
||||
if (IconButton("##del", RynthIcons.Trash, new Vector2(x, y), new Vector2(BtnW, fieldH), Red, ButtonFill, font: RynthUiFont.Ui11))
|
||||
remove = i;
|
||||
ImGui.SetItemTooltip("Remove this button.");
|
||||
|
||||
ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + rowH));
|
||||
ImGui.Dummy(Vector2.Zero);
|
||||
ImGui.PopID();
|
||||
}
|
||||
long now = Environment.TickCount64;
|
||||
if (remove >= 0)
|
||||
{
|
||||
list.RemoveAt(remove);
|
||||
Changed();
|
||||
}
|
||||
else if (moveFrom >= 0)
|
||||
_set.Move(_scope, moveFrom, moveBy, now);
|
||||
}
|
||||
|
||||
private static uint Byte(float v) => (uint)Math.Clamp((int)MathF.Round(v * 255f), 0, 255);
|
||||
|
||||
private void DrawAddRow(float w)
|
||||
{
|
||||
Vector2 p = ImGui.GetCursorScreenPos();
|
||||
float h = Px(22), y = p.Y + Px(2);
|
||||
string label = "Add button";
|
||||
bool full = _set.List(_scope).Count >= CommandButtonSet.MaxPerList;
|
||||
float aw = ButtonWidth(label) + Px(8);
|
||||
if (Button("##cb_add", label, new Vector2(p.X, y), new Vector2(aw, h), Text, ButtonFill, enabled: !full))
|
||||
AddRow();
|
||||
ImGui.SetItemTooltip(full
|
||||
? $"This list is full ({CommandButtonSet.MaxPerList} buttons)."
|
||||
: "A new button in this list: type its label and the chat line it sends.");
|
||||
float x = p.X + aw + Px(10);
|
||||
ImDrawListPtr dl = ImGui.GetWindowDrawList();
|
||||
float ty = y + (h - ImGui.GetFontSize()) * 0.5f;
|
||||
// The last press or copy for a few seconds, else where the list is saved.
|
||||
string note = _note;
|
||||
string saved = note.Length > 0 && Environment.TickCount64 - Volatile.Read(ref _noteAtMs) < NoteMs
|
||||
? note
|
||||
: "Saved for " + CommandButtonSet.ScopeName(_scope) + ".";
|
||||
float textRight = p.X + w;
|
||||
|
||||
// Copy from another character (this character's list only).
|
||||
if (_scope == ButtonScope.Character)
|
||||
{
|
||||
string copy = "Copy";
|
||||
float copyW = ButtonWidth(copy) + Px(8), comboW = Px(130);
|
||||
float cx = p.X + w - copyW - comboW - Px(4);
|
||||
if (cx > x + Px(200))
|
||||
{
|
||||
string from = "Copy from";
|
||||
float fw = ImGui.CalcTextSize(from).X;
|
||||
dl.AddText(new Vector2(cx - fw - Px(6), ty), Mute, from);
|
||||
if (_copyPick >= _others.Count) _copyPick = 0;
|
||||
string pick = _others.Count > 0 ? _others[_copyPick] : "(no other character)";
|
||||
ImGui.SetCursorScreenPos(new Vector2(cx, y));
|
||||
ImGui.SetNextItemWidth(comboW);
|
||||
ImGui.PushStyleColor(ImGuiCol.FrameBg, Field);
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(Px(4), Math.Max(1, (h - ImGui.GetFontSize()) * 0.5f)));
|
||||
if (ImGui.BeginCombo("##cb_from", pick))
|
||||
{
|
||||
if (ImGui.IsWindowAppearing()) _others = _set.OtherCharacters();
|
||||
for (int i = 0; i < _others.Count; i++)
|
||||
if (ImGui.Selectable(_others[i] + "##cbo" + i.ToString(CultureInfo.InvariantCulture), i == _copyPick))
|
||||
_copyPick = i;
|
||||
if (_others.Count == 0) Label("No other character on this server has buttons.", Mute);
|
||||
ImGui.EndCombo();
|
||||
}
|
||||
ImGui.PopStyleVar();
|
||||
ImGui.PopStyleColor();
|
||||
ImGui.SetItemTooltip("Another character on this server whose own buttons you want here too.");
|
||||
if (Button("##cb_copy", copy, new Vector2(cx + comboW + Px(4), y), new Vector2(copyW, h), Text, ButtonFill,
|
||||
enabled: _others.Count > 0 && !full))
|
||||
{
|
||||
string who = _others[_copyPick];
|
||||
int added = _set.CopyFrom(who, Environment.TickCount64, out string problem);
|
||||
Note(added < 0 ? $"Couldn't copy {who}'s buttons: {problem}."
|
||||
: added == 0 ? $"{who} has no buttons to copy (or this list is full)."
|
||||
: $"Copied {added} button{(added == 1 ? "" : "s")} from {who}.");
|
||||
}
|
||||
ImGui.SetItemTooltip("Adds that character's own buttons after this character's (nothing is replaced).");
|
||||
textRight = cx - ImGui.CalcTextSize(from).X - Px(12);
|
||||
}
|
||||
}
|
||||
dl.PushClipRect(new Vector2(x, y), new Vector2(Math.Max(x, textRight), y + h), true);
|
||||
dl.AddText(new Vector2(x, ty), Mute, saved);
|
||||
dl.PopClipRect();
|
||||
ImGui.SetCursorScreenPos(new Vector2(p.X, y + h + Px(2)));
|
||||
ImGui.Dummy(Vector2.Zero);
|
||||
}
|
||||
|
||||
private void AddRow()
|
||||
{
|
||||
if (_set.Add(_scope, null, null, Environment.TickCount64) != null)
|
||||
_focusRow = _set.List(_scope).Count - 1;
|
||||
}
|
||||
|
||||
/// <summary>An edit to the shown list (under the set's lock): saved by the tick a moment later.</summary>
|
||||
private void Changed() => _set.MarkChanged(_scope, Environment.TickCount64);
|
||||
}
|
||||
|
|
@ -158,6 +158,10 @@ public sealed partial class RynthAiPlugin
|
|||
private bool _currentLootItemPipelined; // sent while the last pickup's Return played (ACE queues it)
|
||||
private bool _currentLootItemJumped; // jump-loot: sent in the air, its own jump or the last one's (not a resend)
|
||||
private bool _currentLootItemSentInAirWindow; // sent on the strength of the last no-bend-down pickup (JumpPickupInAir)
|
||||
// 2026-11-22: a corpse that closed while a jump-loot pickup was under way (the hop took the
|
||||
// character outside its use radius at the client's once-a-second check). Its later pickups
|
||||
// bend down; jumping again closed it again, every time, for minutes (NoteCorpseClosedMidPickup).
|
||||
private int _noJumpLootCorpseId;
|
||||
private int _currentLootItemErrSeqAtSend; // TryGetLastWeenieError seq at the send (0 = unknown)
|
||||
private int _currentLootItemFreeRetries; // resends after a too-busy answer (not counted as attempts)
|
||||
// 2026-10-29 (R-20261029-122319-321f): what the server said to the last send, and what the
|
||||
|
|
@ -650,6 +654,7 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
if (wasOpenCorpse)
|
||||
{
|
||||
NoteCorpseClosedMidPickup(sid);
|
||||
_lastCorpseOpenAttemptAt = 0;
|
||||
_lastLootActionAt = CorpseNowMs;
|
||||
LootDiag($"[RynthAi] Corpse loot: container 0x{objectId:X8} closed before completion; will retry open until timeout.");
|
||||
|
|
@ -657,6 +662,32 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>Most closes of a corpse during one item's pickups before the item is left (with the unanswered-try limit, 3).</summary>
|
||||
internal const int MaxClosesPerLootItem = 3;
|
||||
|
||||
/// <summary>
|
||||
/// The open corpse closed while an item's move was out (2026-11-22). A reopen starts the item's
|
||||
/// tries over (ResetCurrentLootItem), so a corpse that closes on every pickup was opened again
|
||||
/// and again for minutes. Each such close is one of the item's tries on this corpse
|
||||
/// (_corpseItemAttempts survives a reopen of the same corpse): after
|
||||
/// <see cref="MaxClosesPerLootItem"/> it is left. A close during a jump-loot pickup turns
|
||||
/// jump-loot off for the corpse: the hop is what takes the character outside its use radius.
|
||||
/// </summary>
|
||||
private void NoteCorpseClosedMidPickup(int corpseId)
|
||||
{
|
||||
int itemId = _currentLootItemId;
|
||||
if (itemId == 0 || !_currentLootItemMovePending)
|
||||
return;
|
||||
if (_currentLootItemJumped && _noJumpLootCorpseId != corpseId)
|
||||
{
|
||||
_noJumpLootCorpseId = corpseId;
|
||||
LootDiag($"[RynthAi] {LootTag}: corpse 0x{(uint)corpseId:X8} closed during a jump-loot pickup of 0x{(uint)itemId:X8}; jump-loot is off for this corpse, its pickups bend down.");
|
||||
}
|
||||
int closes = IncrementCorpseItemAttempt(itemId);
|
||||
if (closes >= MaxClosesPerLootItem && _processedCorpseItems.Add(itemId))
|
||||
LootDiag($"[RynthAi] {LootTag}: leaving 0x{(uint)itemId:X8}{(_currentLootItemName.Length > 0 ? $" '{_currentLootItemName}'" : "")}: corpse 0x{(uint)corpseId:X8} closed during its pickup {closes} times.");
|
||||
}
|
||||
|
||||
public override void OnVendorOpen(uint vendorId)
|
||||
{
|
||||
CancelManualChestReopen(unchecked((int)vendorId), "a vendor was opened");
|
||||
|
|
@ -928,6 +959,14 @@ public sealed partial class RynthAiPlugin
|
|||
if (corpse == null)
|
||||
return;
|
||||
|
||||
// A wall between: set aside before any open, or the server's walk drives the character
|
||||
// into it (R-20261124-001522-b582); the next tick claims the next corpse.
|
||||
if (SetAsideBeforeClaim(corpse.Id, now))
|
||||
{
|
||||
_lootSkipWhy = $"corpse 0x{(uint)corpse.Id:X8} is behind a wall";
|
||||
return;
|
||||
}
|
||||
|
||||
_targetCorpseId = corpse.Id;
|
||||
_corpseTargetSince = now;
|
||||
_lastCorpseOpenAttemptAt = 0;
|
||||
|
|
@ -1498,6 +1537,26 @@ public sealed partial class RynthAiPlugin
|
|||
};
|
||||
}
|
||||
|
||||
// A killer that is known and not among the fellowship's known members is someone else:
|
||||
// their kill, or a player's death corpse (#rynth-issues 2026-11-25 "Fellowship kills and
|
||||
// looting": "Rynth treats all corpses as fellowship kills, both player corpses and monster
|
||||
// corpses are attempted opened"). Only while the member list isn't read yet does the
|
||||
// server decide, as before.
|
||||
int membersKnown = _fellowshipTracker?.GetMemberNames().Count() ?? 0;
|
||||
if (!FellowModeLoots(killerName, killerIsFellow, membersKnown))
|
||||
{
|
||||
return new CorpseLootDecision
|
||||
{
|
||||
ShouldLoot = false,
|
||||
ModeName = modeName,
|
||||
Reason = $"The corpse killer '{killerName}' is not in your fellowship ({membersKnown} members known).",
|
||||
KillerName = killerName,
|
||||
PlayerName = myName,
|
||||
LongDesc = longDesc,
|
||||
InFellowship = inFellowship,
|
||||
KillerIsFellow = killerIsFellow
|
||||
};
|
||||
}
|
||||
// When fellowship membership data lags behind the live client, allow the server
|
||||
// to be the final authority instead of skipping potentially valid fellowship corpses.
|
||||
return new CorpseLootDecision
|
||||
|
|
@ -1535,6 +1594,14 @@ public sealed partial class RynthAiPlugin
|
|||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fellowship kills mode, in a fellowship, the killer not you: loot while the killer isn't known yet
|
||||
/// (the ID is on its way), is a fellow, or the member list isn't read yet (fewer than 2 names);
|
||||
/// a known killer outside a read member list is someone else's corpse.
|
||||
/// </summary>
|
||||
internal static bool FellowModeLoots(string? killerName, bool killerIsFellow, int membersKnown)
|
||||
=> string.IsNullOrWhiteSpace(killerName) || killerIsFellow || membersKnown < 2;
|
||||
|
||||
private string GetPlayerNameForLootOwnership()
|
||||
{
|
||||
if (_playerId == 0)
|
||||
|
|
@ -1997,6 +2064,17 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
_flightHoldLogged = false;
|
||||
|
||||
// The server would refuse it for burden at once, with no code, so it read as "too busy"
|
||||
// and went 6 times a corpse (R-20261123-065337-d200): left now, lighter items still go.
|
||||
if (LootItemOverBurden(firstMatchId, out string overBurden))
|
||||
{
|
||||
LootDiag($"[RynthAi] {LootTag}: leaving 0x{(uint)firstMatchId:X8} '{matchItemName}' on 0x{(uint)corpseId:X8} - too heavy: {overBurden}.");
|
||||
WarnLootOverBurden(matchItemName, overBurden);
|
||||
_processedCorpseItems.Add(firstMatchId);
|
||||
_lastLootActionAt = now;
|
||||
return;
|
||||
}
|
||||
|
||||
ChatLine($"[RynthAi] Loot rule: {matchItemName} -> [{matchActionLabel}] {matchRuleLabel}");
|
||||
_currentLootItemId = firstMatchId;
|
||||
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)firstMatchId));
|
||||
|
|
@ -2583,6 +2661,7 @@ public sealed partial class RynthAiPlugin
|
|||
private bool ShouldJumpLoot(LegacyUiSettings settings) =>
|
||||
settings.LootJumpEnabled
|
||||
&& !IsChestLoot(_openedContainerId)
|
||||
&& !(_noJumpLootCorpseId != 0 && _noJumpLootCorpseId == _openedContainerId)
|
||||
&& Host.HasTapJump
|
||||
&& Host.HasMoveItemExternal
|
||||
&& _vitals.CurrentStamina > 5
|
||||
|
|
@ -4626,6 +4705,7 @@ public sealed partial class RynthAiPlugin
|
|||
return;
|
||||
}
|
||||
|
||||
NoteCorpseClosedMidPickup(previousOpen);
|
||||
ResetCurrentLootItem();
|
||||
_lastCorpseOpenAttemptAt = 0;
|
||||
_lastLootActionAt = now;
|
||||
|
|
|
|||
|
|
@ -93,6 +93,10 @@ internal interface IDashboardHost
|
|||
/// <summary>Debuff every monster in range before attacking (combat setting), for the options menu's toggle.</summary>
|
||||
bool DebuffAllBeforeAttacking { get; }
|
||||
void SetAutoSort(bool on);
|
||||
/// <summary>The vitals whose recharge is held (No recharge for now, LegacyUi/RechargeHold.cs).</summary>
|
||||
RechargeVital RechargeHeld { get; }
|
||||
/// <summary>Holds or releases those vitals' recharge (on the plugin tick).</summary>
|
||||
void SetRechargeHold(RechargeVital vitals, bool on);
|
||||
/// <summary>RynthSort's own window, shown or hidden.</summary>
|
||||
void ToggleSortWindow();
|
||||
void StartPatrol();
|
||||
|
|
@ -109,8 +113,12 @@ internal interface IDashboardHost
|
|||
void ToggleActiveGear();
|
||||
/// <summary>The Timed Commands window (commands sent every N seconds) open or closed.</summary>
|
||||
void ToggleTimedCommands();
|
||||
/// <summary>The Command Buttons window (buttons that each send one chat line) open or closed.</summary>
|
||||
void ToggleCommandButtons();
|
||||
/// <summary>The Find a Feature window (search every feature: where it is, its command) open, its box ready.</summary>
|
||||
void OpenFeatureSearch();
|
||||
/// <summary>The ACMAPS Maps window (the player's own ACMAPS map of this dungeon) open or closed.</summary>
|
||||
void ToggleAcMaps();
|
||||
/// <summary>The Classic (retail) look: RynthCore's own face comes back for it.</summary>
|
||||
void UseClassicLook();
|
||||
/// <summary>The Mini Remote, drawn into the current window; the size it wants.</summary>
|
||||
|
|
@ -700,7 +708,7 @@ internal sealed unsafe class InstrumentDashboard
|
|||
(RynthIcons.FileCode, "Lua", "Lua", "Lua scripts"),
|
||||
(RynthIcons.Skull, "Monsters", "Monsters", "Monsters: weapons, spells and rules per monster (the Damage panel)"),
|
||||
(RynthIcons.Gear, "Settings", "Settings", "Settings"),
|
||||
(RynthIcons.MapPin, "Map", "Dungeon Map", "Dungeon Map (shows while you're in a dungeon)"),
|
||||
(RynthIcons.MapPin, "Map", "Dungeon Map", "Dungeon Map (shows while you're in a dungeon).\nRight-click: ACMAPS Maps, your own ACMAPS map of this dungeon."),
|
||||
(RynthIcons.GlobeHemisphereWest, "World", "World Map", "World Map: Dereth, with your position, the route and places"),
|
||||
(RynthIcons.Backpack, "Items", "Items", "Items"),
|
||||
(RynthIcons.Footprints, "Patrol", "", "Patrol. Click: start dungeon patrol. Right-click: the Patrol drawer (hazards and routes)."),
|
||||
|
|
@ -783,6 +791,12 @@ internal sealed unsafe class InstrumentDashboard
|
|||
|
||||
private void LaunchRight(string label, DashboardPrefs prefs)
|
||||
{
|
||||
if (label == "Map")
|
||||
{
|
||||
// ACMAPS Maps (RynthAiPlugin.AcMaps.cs): the player's own ACMAPS map pack, beside the Dungeon Map.
|
||||
_d.ToggleAcMaps();
|
||||
return;
|
||||
}
|
||||
if (label == "Patrol")
|
||||
{
|
||||
prefs.ToggleDrawer(DashboardPrefs.PatrolDrawer);
|
||||
|
|
@ -931,9 +945,10 @@ internal sealed unsafe class InstrumentDashboard
|
|||
y += Px(8);
|
||||
if (prefs.ShowVitals)
|
||||
{
|
||||
y = Vital(dl, x0, y, w, "HP", _r.Health, _r.MaxHealth, Hp, _hpText, lowWarn: true) + Px(VitalGap);
|
||||
y = Vital(dl, x0, y, w, "ST", _r.Stamina, _r.MaxStamina, St, _stText) + Px(VitalGap);
|
||||
y = Vital(dl, x0, y, w, "MN", _r.Mana, _r.MaxMana, Mn, _mnText);
|
||||
RechargeVital held = _d.RechargeHeld;
|
||||
y = Vital(dl, x0, y, w, "HP", _r.Health, _r.MaxHealth, Hp, _hpText, lowWarn: true, RechargeVital.Health, held) + Px(VitalGap);
|
||||
y = Vital(dl, x0, y, w, "ST", _r.Stamina, _r.MaxStamina, St, _stText, vital: RechargeVital.Stamina, held: held) + Px(VitalGap);
|
||||
y = Vital(dl, x0, y, w, "MN", _r.Mana, _r.MaxMana, Mn, _mnText, vital: RechargeVital.Mana, held: held);
|
||||
}
|
||||
if (prefs.ShowTarget)
|
||||
{
|
||||
|
|
@ -943,9 +958,13 @@ internal sealed unsafe class InstrumentDashboard
|
|||
return y;
|
||||
}
|
||||
|
||||
/// <summary>A vital row: its label, a bar with quarter ticks, and "cur/max" in numbers that line up.</summary>
|
||||
/// <summary>
|
||||
/// A vital row: its label, a bar with quarter ticks, and "cur/max" in numbers that line up. The
|
||||
/// label is a switch (No recharge for now): click holds or releases this vital's recharge,
|
||||
/// right-click all three; held, the label is struck through in the faint colour.
|
||||
/// </summary>
|
||||
private float Vital(ImDrawListPtr dl, float x0, float y, float w, string label, uint cur, uint max, uint color,
|
||||
NumberText text, bool lowWarn = false)
|
||||
NumberText text, bool lowWarn = false, RechargeVital vital = RechargeVital.None, RechargeVital held = RechargeVital.None)
|
||||
{
|
||||
float h = Px(VitalH);
|
||||
float frac = max == 0 ? 0f : Math.Clamp((float)cur / max, 0f, 1f);
|
||||
|
|
@ -955,7 +974,31 @@ internal sealed unsafe class InstrumentDashboard
|
|||
|
||||
ImFontPtr lf = Font(RynthUiFont.NarrowBold11);
|
||||
float lsize = lf.FontSize * 10f / 11f;
|
||||
dl.AddText(lf, lsize, new Vector2(x0, MathF.Round(y + (h - lsize) * 0.5f)), low ? HpText : color, label);
|
||||
bool isHeld = vital != RechargeVital.None && (held & vital) != 0;
|
||||
Vector2 lpos = new(x0, MathF.Round(y + (h - lsize) * 0.5f));
|
||||
dl.AddText(lf, lsize, lpos, isHeld ? _faint : low ? HpText : color, label);
|
||||
if (vital != RechargeVital.None)
|
||||
{
|
||||
ImGui.SetCursorScreenPos(new Vector2(x0 - Px(2), y - Px(1)));
|
||||
bool click = ImGui.InvisibleButton("##recharge_" + label, new Vector2(Px(VitalLabelW) + Px(4), h + Px(2)),
|
||||
ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight)
|
||||
&& ImGui.IsMouseReleased(ImGuiMouseButton.Left);
|
||||
bool right = ImGui.IsItemClicked(ImGuiMouseButton.Right);
|
||||
string name = RechargeHold.Describe(vital);
|
||||
SafeImGui.SetItemTooltip((isHeld
|
||||
? $"No recharge for now: {name} isn't recharged (its lines are held at 0; your settings are kept). Click to recharge it again."
|
||||
: $"Click: no {name} recharge for now (no wand out for it mid-fight; your settings are kept).")
|
||||
+ (vital == RechargeVital.Health ? "\nEmergency Heal At still heals." : "")
|
||||
+ "\nRight-click: " + (held == RechargeVital.None ? "no recharge at all for now." : "recharge everything again."));
|
||||
if (click) _d.SetRechargeHold(vital, !isHeld);
|
||||
if (right) _d.SetRechargeHold(RechargeVital.All, held == RechargeVital.None);
|
||||
if (isHeld)
|
||||
{
|
||||
float tw = lf.CalcTextSizeA(lsize, float.MaxValue, 0f, label).X;
|
||||
float sy = MathF.Round(lpos.Y + lsize * 0.55f) + 0.5f;
|
||||
dl.AddLine(new Vector2(lpos.X - Px(1), sy), new Vector2(lpos.X + tw + Px(1), sy), _text, Px(1.5f));
|
||||
}
|
||||
}
|
||||
|
||||
float bx = x0 + Px(VitalLabelW) + Px(VitalColGap);
|
||||
float bw = w - Px(VitalLabelW) - Px(VitalNumW) - 2 * Px(VitalColGap);
|
||||
|
|
@ -1156,6 +1199,16 @@ internal sealed unsafe class InstrumentDashboard
|
|||
ImGui.CloseCurrentPopup();
|
||||
_d.Command("/ra debuffall");
|
||||
}
|
||||
// No recharge for now (RynthAiPlugin.RechargeHold.cs): all three vitals' recharge held, or released.
|
||||
RechargeVital rechargeHeld = _d.RechargeHeld;
|
||||
if (MenuItem(dl, ref p, w, "##m_norecharge", RynthIcons.BatteryCharging,
|
||||
"No recharge for now", rechargeHeld == RechargeVital.None ? "OFF" : rechargeHeld == RechargeVital.All ? "ON" : "SOME",
|
||||
"On: health, stamina and mana aren't recharged (no wand out for them mid-fight); your settings are kept and come back\n" +
|
||||
"when it goes off (/ra norecharge). Emergency Heal At still heals. Click HP, ST or MN by the bars for one vital."))
|
||||
{
|
||||
ImGui.CloseCurrentPopup();
|
||||
_d.SetRechargeHold(RechargeVital.All, rechargeHeld == RechargeVital.None);
|
||||
}
|
||||
// Which worn items have their magic on (RynthAiPlugin.ActiveGear.cs): its own window, no bar button.
|
||||
if (MenuItem(dl, ref p, w, "##m_gear", RynthIcons.BatteryCharging, "Active gear", "/ra gear",
|
||||
"Which worn items have their magic on, their mana and how long it lasts (the Active Gear window)."))
|
||||
|
|
@ -1163,6 +1216,14 @@ internal sealed unsafe class InstrumentDashboard
|
|||
ImGui.CloseCurrentPopup();
|
||||
_d.ToggleActiveGear();
|
||||
}
|
||||
// The player's own ACMAPS dungeon maps (RynthAiPlugin.AcMaps.cs): its own window, no bar button.
|
||||
if (MenuItem(dl, ref p, w, "##m_acmaps", RynthIcons.MapTrifold, "ACMAPS maps", "/ra acmaps",
|
||||
"Your own ACMAPS dungeon maps (the map pack you have), with where you are on them\n" +
|
||||
"(the ACMAPS Maps window; also the Map button, right-click)."))
|
||||
{
|
||||
ImGui.CloseCurrentPopup();
|
||||
_d.ToggleAcMaps();
|
||||
}
|
||||
// Commands sent every N seconds (RynthAiPlugin.TimedCommands.cs): its own window, no bar button.
|
||||
if (MenuItem(dl, ref p, w, "##m_timed", RynthIcons.HourglassMedium, "Timed commands", "/ra timed",
|
||||
"Chat commands sent every so many seconds, per character, server or all characters,\n" +
|
||||
|
|
@ -1171,6 +1232,22 @@ internal sealed unsafe class InstrumentDashboard
|
|||
ImGui.CloseCurrentPopup();
|
||||
_d.ToggleTimedCommands();
|
||||
}
|
||||
// Buttons that each send one chat line (RynthAiPlugin.CommandButtons.cs): its own window, no bar button.
|
||||
if (MenuItem(dl, ref p, w, "##m_buttons", RynthIcons.SquaresFour, "Command buttons", "/ra buttons",
|
||||
"A window of buttons you make, each sending one chat line: /ra start, *wave*, @home,\n" +
|
||||
"/lua start <script>... (the Command Buttons window)."))
|
||||
{
|
||||
ImGui.CloseCurrentPopup();
|
||||
_d.ToggleCommandButtons();
|
||||
}
|
||||
// The Trade Shop (RynthAiPlugin.TradeShop.cs): its own window, no bar button.
|
||||
if (MenuItem(dl, ref p, w, "##m_tradeshop", RynthIcons.Coins, "Trade shop", "/ra tradeshop",
|
||||
"A shop run from tells: buyers !list and !buy, the shop checks their payment (the Trade Shop window).\n" +
|
||||
"Off at every login; Confirm each sale asks you before every accept."))
|
||||
{
|
||||
ImGui.CloseCurrentPopup();
|
||||
_d.Command("/ra tradeshop");
|
||||
}
|
||||
// Dirty Fighting rotation: opens its window (the checkbox, order and default height are there).
|
||||
if (MenuItem(dl, ref p, w, "##m_dfheight", RynthIcons.Knife,
|
||||
"Dirty Fighting heights", _d.DfHeightRotation ? "ON" : "OFF",
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ internal enum TickStep
|
|||
GiveQueue,
|
||||
ItemTool,
|
||||
TimedCommands,
|
||||
CommandButtons,
|
||||
Jumper,
|
||||
Dashboard,
|
||||
// In world.
|
||||
|
|
@ -46,8 +47,10 @@ internal enum TickStep
|
|||
PatrolReroute,
|
||||
AutoVendor,
|
||||
AutoTrade,
|
||||
TradeShop,
|
||||
WeaponElements,
|
||||
AutoKits,
|
||||
AutoAmmo,
|
||||
CramStack,
|
||||
InventoryStatus,
|
||||
CombatTelemetry,
|
||||
|
|
@ -121,6 +124,7 @@ internal sealed class TickGuard
|
|||
Add(TickStep.GiveQueue, "give queue", LogCat.Inventory);
|
||||
Add(TickStep.ItemTool, "item tool", LogCat.Inventory);
|
||||
Add(TickStep.TimedCommands, "timed commands", LogCat.Commands);
|
||||
Add(TickStep.CommandButtons, "command buttons", LogCat.Commands);
|
||||
Add(TickStep.Jumper, "jumper", LogCat.Jumper, essential: true);
|
||||
Add(TickStep.Dashboard, "dashboard window", LogCat.UI);
|
||||
|
||||
|
|
@ -138,8 +142,10 @@ internal sealed class TickGuard
|
|||
Add(TickStep.PatrolReroute, "patrol reroute", LogCat.Navigation);
|
||||
Add(TickStep.AutoVendor, "AutoVendor", LogCat.Vendor);
|
||||
Add(TickStep.AutoTrade, "AutoTrade", LogCat.Vendor);
|
||||
Add(TickStep.TradeShop, "Trade Shop", LogCat.Vendor);
|
||||
Add(TickStep.WeaponElements, "weapon elements", LogCat.Combat);
|
||||
Add(TickStep.AutoKits, "make kits when low", LogCat.Crafting);
|
||||
Add(TickStep.AutoAmmo, "make ammo when low", LogCat.Crafting);
|
||||
Add(TickStep.CramStack, "AutoCram/AutoStack", LogCat.Inventory);
|
||||
Add(TickStep.InventoryStatus, "inventory status", LogCat.Inventory);
|
||||
Add(TickStep.CombatTelemetry, "combat telemetry", LogCat.Combat);
|
||||
|
|
|
|||
|
|
@ -47,6 +47,9 @@ internal static unsafe class HubInterface
|
|||
t->VaultedDungeonsEnabled = &VaultedDungeonsEnabled;
|
||||
t->BackAwayFrom = &BackAwayFrom;
|
||||
t->SetPlayerCounter = &SetPlayerCounter;
|
||||
t->LootActions = &LootActions;
|
||||
t->VendorSells = &VendorSells;
|
||||
t->TradeGives = &TradeGives;
|
||||
t->Version = RynthAiHubApiV1.InterfaceVersion;
|
||||
_table = t;
|
||||
}
|
||||
|
|
@ -277,6 +280,51 @@ internal static unsafe class HubInterface
|
|||
catch { return 0; }
|
||||
}
|
||||
|
||||
// ── Read only answers about items in the packs (RynthSort's pack jobs; RynthAiPlugin.HubReadOnly.cs) ──
|
||||
|
||||
private delegate bool ItemAnswer(uint[] ids, byte[] result, out string profileFile, out string? error);
|
||||
|
||||
/// <summary>Copies the ids in, runs <paramref name="answer"/>, copies the bytes out and the profile's name or the reason into text.</summary>
|
||||
private static int Answer(uint* ids, int count, byte* result, byte* text, int textCapacity, ItemAnswer? answer)
|
||||
{
|
||||
if (answer == null) { WriteUtf8("RynthAi isn't ready (log in first).", text, textCapacity); return 0; }
|
||||
if (count < 0 || count > 4096 || (count > 0 && (ids == null || result == null))) { WriteUtf8("bad arguments", text, textCapacity); return 0; }
|
||||
var a = new uint[count];
|
||||
for (int i = 0; i < count; i++) a[i] = ids[i];
|
||||
var r = new byte[count];
|
||||
bool ok = answer(a, r, out string file, out string? error);
|
||||
for (int i = 0; i < count; i++) result[i] = ok ? r[i] : (byte)0;
|
||||
WriteUtf8(ok ? file : error ?? "no answer", text, textCapacity);
|
||||
return ok ? 1 : 0;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int LootActions(uint* ids, int count, byte* actions, byte* text, int textCapacity)
|
||||
{
|
||||
try { return Answer(ids, count, actions, text, textCapacity, Plugin is { } p ? p.LootActionsForHub : null); }
|
||||
catch (Exception ex) { WriteUtf8("loot match failed: " + ex.Message, text, textCapacity); return 0; }
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int VendorSells(uint* ids, int count, byte* sells, byte* text, int textCapacity)
|
||||
{
|
||||
try { return Answer(ids, count, sells, text, textCapacity, Plugin is { } p ? p.VendorSellsForHub : null); }
|
||||
catch (Exception ex) { WriteUtf8("AutoVendor match failed: " + ex.Message, text, textCapacity); return 0; }
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int TradeGives(byte* partner, uint* ids, int count, byte* gives, byte* text, int textCapacity)
|
||||
{
|
||||
try
|
||||
{
|
||||
string who = Utf8(partner) ?? string.Empty;
|
||||
RynthAiPlugin? p = Plugin;
|
||||
ItemAnswer? answer = p == null ? null : (uint[] a, byte[] r, out string f, out string? e) => p.TradeGivesForHub(who, a, r, out f, out e);
|
||||
return Answer(ids, count, gives, text, textCapacity, answer);
|
||||
}
|
||||
catch (Exception ex) { WriteUtf8("AutoTrade match failed: " + ex.Message, text, textCapacity); return 0; }
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static void SessionReset()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -105,21 +105,46 @@ internal static class SectionsManifest
|
|||
/// </summary>
|
||||
public const string FeatureSearchTitle = RynthAiPlugin.FeatureSearchTitle, FeatureSearchSurface = RynthAiPlugin.FeatureSearchSurface;
|
||||
|
||||
/// <summary>
|
||||
/// The ACMAPS Maps window (RynthAiPlugin.AcMaps.cs, 2026-11-26): the player's own ACMAPS map of the dungeon
|
||||
/// they're in, drawn by RynthAi in the engine's frame (plugin API v89). No bar button (the bar is full): the
|
||||
/// dashboard's Map button (right-click), its options menu (ACMAPS maps) and /ra acmaps open it.
|
||||
/// </summary>
|
||||
public const string AcMapsTitle = RynthAiPlugin.AcMapsTitle, AcMapsSurface = RynthAiPlugin.AcMapsSurface;
|
||||
|
||||
/// <summary>
|
||||
/// The Command Buttons window (RynthAiPlugin.CommandButtons.cs, 2026-11-26): buttons that each send one
|
||||
/// chat line, per character, server and for all, drawn by RynthAi in the engine's frame (plugin API v89).
|
||||
/// No bar button (the bar is full): the dashboard's options menu (Command buttons), /ra buttons and Find
|
||||
/// a Feature open it.
|
||||
/// </summary>
|
||||
public const string CommandButtonsTitle = RynthAiPlugin.CommandButtonsTitle, CommandButtonsSurface = RynthAiPlugin.CommandButtonsSurface;
|
||||
|
||||
/// <summary>
|
||||
/// The Trade Shop window (RynthAiPlugin.TradeShop.cs, 2026-11-24): the shop's switch, the sale waiting for
|
||||
/// Accept sale, the catalog, payment and advertising, drawn by RynthAi (plugin API v89). No bar button
|
||||
/// (the bar is full): the dashboard's options menu (Trade shop) and /ra tradeshop open it.
|
||||
/// </summary>
|
||||
public const string TradeShopTitle = RynthAiPlugin.TradeShopTitle, TradeShopSurface = RynthAiPlugin.TradeShopSurface;
|
||||
|
||||
/// <summary>
|
||||
/// The manifest JSON for <paramref name="views"/> (UTF-8 text, schema version 1), with the dashboard
|
||||
/// window when <paramref name="dashboard"/>, the Monster Stats window when <paramref name="monsterStats"/>,
|
||||
/// the Timed Commands window when <paramref name="timedCommands"/>, the Active Gear window when
|
||||
/// <paramref name="activeGear"/> and the Find a Feature window when <paramref name="featureSearch"/>.
|
||||
/// <paramref name="activeGear"/>, the Find a Feature window when <paramref name="featureSearch"/>, the ACMAPS
|
||||
/// Maps window when <paramref name="acMaps"/>, the Command Buttons window when <paramref name="commandButtons"/>
|
||||
/// and the Trade Shop window when <paramref name="tradeShop"/>.
|
||||
/// </summary>
|
||||
public static string Build(IReadOnlyList<View> views, IReadOnlyList<Section> sections, bool dashboard = false, bool monsterStats = false,
|
||||
bool timedCommands = false, bool activeGear = false, bool featureSearch = false)
|
||||
bool timedCommands = false, bool activeGear = false, bool featureSearch = false, bool acMaps = false,
|
||||
bool commandButtons = false, bool tradeShop = false)
|
||||
{
|
||||
using var stream = new MemoryStream(4096);
|
||||
using (var w = new Utf8JsonWriter(stream))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("version", 1);
|
||||
bool windows = dashboard || monsterStats || timedCommands || activeGear || featureSearch;
|
||||
bool windows = dashboard || monsterStats || timedCommands || activeGear || featureSearch || acMaps || commandButtons || tradeShop;
|
||||
if (windows)
|
||||
w.WriteStartArray("windows");
|
||||
if (dashboard)
|
||||
|
|
@ -200,6 +225,51 @@ internal static class SectionsManifest
|
|||
w.WriteBoolean("edgeToEdge", true);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
if (acMaps)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("id", "acmaps");
|
||||
w.WriteString("title", AcMapsTitle);
|
||||
w.WriteString("surface", AcMapsSurface);
|
||||
w.WriteString("icon", RynthCore.Plugin.Shared.RynthUi.RynthIcons.MapTrifold);
|
||||
w.WriteNumber("width", 620);
|
||||
w.WriteNumber("height", 560);
|
||||
w.WriteNumber("minWidth", 420);
|
||||
w.WriteNumber("minHeight", 260);
|
||||
w.WriteBoolean("bar", false);
|
||||
w.WriteBoolean("edgeToEdge", true);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
if (commandButtons)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("id", "commandbuttons");
|
||||
w.WriteString("title", CommandButtonsTitle);
|
||||
w.WriteString("surface", CommandButtonsSurface);
|
||||
w.WriteString("icon", RynthCore.Plugin.Shared.RynthUi.RynthIcons.SquaresFour);
|
||||
w.WriteNumber("width", 380);
|
||||
w.WriteNumber("height", 180);
|
||||
w.WriteNumber("minWidth", 140);
|
||||
w.WriteNumber("minHeight", 80);
|
||||
w.WriteBoolean("bar", false);
|
||||
w.WriteBoolean("edgeToEdge", true);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
if (tradeShop)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("id", "tradeshop");
|
||||
w.WriteString("title", TradeShopTitle);
|
||||
w.WriteString("surface", TradeShopSurface);
|
||||
w.WriteString("icon", RynthCore.Plugin.Shared.RynthUi.RynthIcons.Coins);
|
||||
w.WriteNumber("width", 560);
|
||||
w.WriteNumber("height", 520);
|
||||
w.WriteNumber("minWidth", 420);
|
||||
w.WriteNumber("minHeight", 240);
|
||||
w.WriteBoolean("bar", false);
|
||||
w.WriteBoolean("edgeToEdge", true);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
if (windows)
|
||||
w.WriteEndArray();
|
||||
w.WriteStartArray("sections");
|
||||
|
|
|
|||
|
|
@ -54,6 +54,11 @@ internal interface IChestKeyEnv
|
|||
int FindKey(int keyId, string keyName, int excludeId);
|
||||
/// <summary>Why nothing may be sent now (combat, the client is busy, portal space, the server owes an answer); null = free.</summary>
|
||||
string? HoldReason();
|
||||
/// <summary>
|
||||
/// Why no key should be spent now: the loot would have nowhere to go (the main pack is full; loot
|
||||
/// goes only there). Null = room. Asked before each key use only.
|
||||
/// </summary>
|
||||
string? NoRoomReason();
|
||||
bool HasUseDone { get; }
|
||||
int UseDoneSeq();
|
||||
bool LastUseDone(out int seq, out uint error);
|
||||
|
|
@ -322,10 +327,31 @@ internal sealed class ChestKeyLooter
|
|||
return true;
|
||||
}
|
||||
|
||||
// ── No room for the loot (2026-11-24, #rynth-issues "Inventory Autocram does not actively run while
|
||||
// looting chests with ItemTool": "when the pack is full it keeps unlocking chests and using keys but
|
||||
// fails to loot them ... continues to burn keys anyway") ──
|
||||
// Before each key use the looter asks whether the loot has anywhere to go. With the main pack full it
|
||||
// waits (Auto Cram, which runs during a chest run, may make room), and after NoRoomMaxMs of it the
|
||||
// run ends: no key is spent on a chest whose loot would only be left behind.
|
||||
public const long NoRoomMaxMs = 30_000;
|
||||
private long _noRoomSince;
|
||||
|
||||
/// <summary>True while the loot has nowhere to go; ends the run after NoRoomMaxMs of it.</summary>
|
||||
private bool NoRoom(long now)
|
||||
{
|
||||
string? why = _env.NoRoomReason();
|
||||
if (why == null) { _noRoomSince = 0; return false; }
|
||||
_holdWhy = why;
|
||||
if (_noRoomSince == 0) { _noRoomSince = now; _env.Log($"[RynthAi] Chest looter: waits before the next key - {why}"); }
|
||||
else if (now - _noRoomSince >= NoRoomMaxMs) Finish($"stopped before the next key: {why} (no key spent on a chest whose loot would be left)");
|
||||
return true;
|
||||
}
|
||||
|
||||
private void TickKeyPending(long now)
|
||||
{
|
||||
if (now < _nextTryAt) return;
|
||||
if (Held(now)) return;
|
||||
if (_keyUsesThisCycle == 0 && NoRoom(now)) return;
|
||||
int key = _env.FindKey(KeyId, KeyName, _keyUsedUp ? KeyId : 0);
|
||||
if (key == 0) { Finish($"out of keys - no '{KeyName}' left"); return; }
|
||||
KeyId = key;
|
||||
|
|
|
|||
|
|
@ -41,8 +41,9 @@ internal interface IQuickGiveEnv
|
|||
bool NextItem(GiveItemKey key, ISet<int> skip, out int itemId, out int count);
|
||||
/// <summary>How many matching items are still carried (whole objects).</summary>
|
||||
int CountCarried(GiveItemKey key);
|
||||
/// <summary>The item left the pack, or its stack shrank below <paramref name="count"/>.</summary>
|
||||
bool Landed(int itemId, int count);
|
||||
/// <summary>The item left the pack, or its stack shrank below <paramref name="count"/>;
|
||||
/// <paramref name="left"/>: the units still in that stack in the pack (0 when it is gone).</summary>
|
||||
bool Landed(int itemId, int count, out int left);
|
||||
/// <summary>AC's give action for the whole object. False when the engine refused to send it.</summary>
|
||||
bool Send(int itemId, int targetId);
|
||||
/// <summary>A count of the server's refusals so far (rises when one arrives).</summary>
|
||||
|
|
@ -203,11 +204,14 @@ internal sealed class QuickGive
|
|||
|
||||
private void TickInFlight(long now)
|
||||
{
|
||||
if (_env.Landed(_inFlightId, _inFlightCount))
|
||||
if (_env.Landed(_inFlightId, _inFlightCount, out int left))
|
||||
{
|
||||
Given++;
|
||||
Units += _inFlightCount;
|
||||
_skip.Add(_inFlightId); // it is the target's now, whatever a stale inventory read still says
|
||||
Units += left > 0 ? _inFlightCount - left : _inFlightCount;
|
||||
// An NPC that takes one per give (R-20261125-205340-1218, DreamWeave: a Collector took one
|
||||
// Kirit Zefir Wing from each stack): the rest stays in the pack and is given again. Skipping
|
||||
// it ended the run after one give per stack ("gave 6", with 446 wings left).
|
||||
if (left <= 0) _skip.Add(_inFlightId); // it is the target's now, whatever a stale inventory read still says
|
||||
_refusals = 0;
|
||||
_left = Math.Max(0, _left - 1);
|
||||
State = Phase.Pending;
|
||||
|
|
|
|||
|
|
@ -429,6 +429,10 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Log each in-range mob's LoS verdict ([LOS] lines: straight line or arc,\n" +
|
||||
"how high the arc rises, where it hits, distance and cells). For tuning.");
|
||||
ImGui.SameLine();
|
||||
ImGui.Checkbox("Show Line of Sight", ref _settings.ShowLosLine);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip(LegacyUiSettings.ShowLosLineTip);
|
||||
|
||||
ImGui.Separator();
|
||||
ImGui.Spacing();
|
||||
|
|
|
|||
|
|
@ -524,7 +524,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
// The defaults now in memory (and the monster rules just loaded) are not a change: take
|
||||
// them as the saved state, so the autosave leaves the unreadable file alone until the
|
||||
// player changes something.
|
||||
try { CaptureTransientUiState(); _lastSavedJson = JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings); }
|
||||
try { CaptureTransientUiState(); _lastSavedJson = SerializeLiveSettings(); }
|
||||
catch { _lastSavedJson = string.Empty; }
|
||||
}
|
||||
_profileLoaded = true;
|
||||
|
|
@ -621,7 +621,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
try
|
||||
{
|
||||
CaptureTransientUiState();
|
||||
json = JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
json = SerializeLiveSettings();
|
||||
}
|
||||
catch (Exception ex) { reason = ex.Message; return false; }
|
||||
if (!WriteSettingsFile(_settingsFilePath, json, out reason, callerShows)) return false;
|
||||
|
|
@ -729,7 +729,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
try
|
||||
{
|
||||
CaptureTransientUiState();
|
||||
string json = JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
string json = SerializeLiveSettings();
|
||||
string path = GetProfileFilePath(name);
|
||||
if (!WriteSettingsFile(path, json, out string reason, callerShows: true))
|
||||
return $"Couldn't save profile '{name}' to {path}: {reason}";
|
||||
|
|
@ -770,7 +770,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
try
|
||||
{
|
||||
CaptureTransientUiState();
|
||||
json = JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
json = SerializeLiveSettings();
|
||||
}
|
||||
catch { return; }
|
||||
if (json == _lastSavedJson) return;
|
||||
|
|
@ -1336,6 +1336,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
MagicArcVelocity = s.MagicArcVelocity,
|
||||
MissileArcClearance = s.MissileArcClearance,
|
||||
LosDebugLog = s.LosDebugLog,
|
||||
ShowLosLine = s.ShowLosLine,
|
||||
BlacklistAttempts = s.BlacklistAttempts,
|
||||
BlacklistTimeoutSec = s.BlacklistTimeoutSec,
|
||||
BlacklistCastSettleMs = s.BlacklistCastSettleMs,
|
||||
|
|
@ -1626,6 +1627,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
if (p.MagicArcVelocity > 0f) s.MagicArcVelocity = p.MagicArcVelocity;
|
||||
if (p.MissileArcClearance >= 0f) s.MissileArcClearance = Math.Min(p.MissileArcClearance, 3f);
|
||||
s.LosDebugLog = p.LosDebugLog;
|
||||
if (p.ShowLosLine is bool losLine) s.ShowLosLine = losLine; // absent = unchanged
|
||||
s.BlacklistAttempts = p.BlacklistAttempts;
|
||||
s.BlacklistTimeoutSec = p.BlacklistTimeoutSec;
|
||||
// -1 = not sent. 0 is never meant (it judges a cast before its damage can land)
|
||||
|
|
@ -2120,7 +2122,17 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
/// Copies all JSON-serializable fields from src into dst without replacing the
|
||||
/// object reference (so all existing bindings to _settings remain valid).
|
||||
/// </summary>
|
||||
/// <summary>The live settings as saved: a recharge hold's lines at their real values (RechargeHold).</summary>
|
||||
private string SerializeLiveSettings() =>
|
||||
_settings.RechargeHold.WithRealValues(_settings, () => JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings));
|
||||
|
||||
private static void CopySettings(LegacyUiSettings src, LegacyUiSettings dst)
|
||||
{
|
||||
CopySettingsFields(src, dst);
|
||||
dst.RechargeHold.Reapply(dst); // a recharge hold stays, over the loaded profile's lines
|
||||
}
|
||||
|
||||
private static void CopySettingsFields(LegacyUiSettings src, LegacyUiSettings dst)
|
||||
{
|
||||
// Re-serialize src, then deserialize over dst's fields via reflection-free copy.
|
||||
// Simplest approach: copy field-by-field via JSON round-trip into dst.
|
||||
|
|
@ -2200,6 +2212,9 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
dst.NavOverlay.Sanitize();
|
||||
dst.EnableMissileCrafting = tmp.EnableMissileCrafting;
|
||||
dst.MissileCraftAmmoThreshold= tmp.MissileCraftAmmoThreshold;
|
||||
dst.MakeAmmoWhenLow = tmp.MakeAmmoWhenLow;
|
||||
dst.MakeAmmoBelow = Math.Clamp(tmp.MakeAmmoBelow, 1, MissileCraftingManager.MaxAmmoBelow);
|
||||
dst.MakeAmmoUpTo = Math.Clamp(tmp.MakeAmmoUpTo, 1, MissileCraftingManager.MaxAmmoUpTo);
|
||||
dst.LootInterItemDelayMs = tmp.LootInterItemDelayMs;
|
||||
dst.LootContentSettleMs = tmp.LootContentSettleMs;
|
||||
dst.LootEmptyCorpseMs = tmp.LootEmptyCorpseMs;
|
||||
|
|
@ -2356,6 +2371,7 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
dst.MagicArcVelocity = LegacyUiSettings.MigrateMagicArcVelocity(tmp.MagicArcVelocity);
|
||||
dst.MissileArcClearance = tmp.MissileArcClearance >= 0f ? Math.Min(tmp.MissileArcClearance, 3f) : 0.5f;
|
||||
dst.LosDebugLog = tmp.LosDebugLog;
|
||||
dst.ShowLosLine = tmp.ShowLosLine;
|
||||
dst.EnableFPSLimit = tmp.EnableFPSLimit;
|
||||
dst.TargetFPSFocused = tmp.TargetFPSFocused;
|
||||
dst.TargetFPSBackground = tmp.TargetFPSBackground;
|
||||
|
|
@ -2428,6 +2444,10 @@ internal sealed partial class LegacyDashboardRenderer
|
|||
dst.AutoTradeOnlyFromMainPack = tmp.AutoTradeOnlyFromMainPack;
|
||||
dst.AutoTradeAutoAccept = tmp.AutoTradeAutoAccept;
|
||||
dst.AutoTradeAutoAcceptChars = tmp.AutoTradeAutoAcceptChars ?? new();
|
||||
// The Trade Shop's on/off is not in the file: a reload keeps it as it is.
|
||||
bool tradeShopOn = dst.TradeShop?.Enabled == true;
|
||||
dst.TradeShop = tmp.TradeShop ?? new();
|
||||
dst.TradeShop.Enabled = tradeShopOn;
|
||||
dst.MetaDebug = tmp.MetaDebug;
|
||||
dst.AllowMetaKeystrokes = tmp.AllowMetaKeystrokes;
|
||||
dst.StartMacroOnLogin = tmp.StartMacroOnLogin;
|
||||
|
|
|
|||
|
|
@ -86,6 +86,8 @@ public sealed class LegacyUiSettings
|
|||
/// its checkboxes are greyed out, as the two fought over the packs (owner, 2026-11-03). Never saved.
|
||||
/// </summary>
|
||||
[JsonIgnore] public bool AutoSortOn;
|
||||
/// <summary>No recharge for now (RechargeHold.cs): vitals whose recharge lines are held at 0; never saved.</summary>
|
||||
[JsonIgnore] internal readonly RechargeHold RechargeHold = new();
|
||||
/// <summary>Meta state — set only by meta actions (SetState, CallState, ReturnFromCall, UI, meta load).</summary>
|
||||
[JsonIgnore] public string CurrentState = "Default";
|
||||
/// <summary>Bot action state — what the bot is doing right now (Default, Combat, Looting, Navigating, Buffing).
|
||||
|
|
@ -216,6 +218,13 @@ public sealed class LegacyUiSettings
|
|||
|
||||
public bool EnableMissileCrafting = true;
|
||||
public int MissileCraftAmmoThreshold = 1000;
|
||||
// Make ammo when low (a players' request, 2026-11-23; default off): with the macro on and nothing
|
||||
// around, when fewer than MakeAmmoBelow arrows, quarrels or darts for the launcher in hand are
|
||||
// carried (quiver and pack), make them up to MakeAmmoUpTo from the pack's bundles, between fights
|
||||
// only (MissileCraftingManager's top-off, RynthAiPlugin.Ammo.cs). Needs Enable Missile Crafting.
|
||||
public bool MakeAmmoWhenLow = false;
|
||||
public int MakeAmmoBelow = MissileCraftingManager.DefaultAmmoBelow;
|
||||
public int MakeAmmoUpTo = MissileCraftingManager.DefaultAmmoUpTo;
|
||||
|
||||
/// <summary>Not read by the corpse looting (pickups are paced by the server's confirmations);
|
||||
/// kept so saved profiles round-trip. Hidden in Advanced Settings.</summary>
|
||||
|
|
@ -889,6 +898,19 @@ public sealed class LegacyUiSettings
|
|||
/// the arc settings; off by default (a few lines a second in a crowd).
|
||||
/// </summary>
|
||||
public bool LosDebugLog;
|
||||
/// <summary>
|
||||
/// Show Line of Sight (2026-11-26, a testing aid): a line in the world from the character to the
|
||||
/// combat target, green when the scan's raycast says the line is clear, red when it says blocked
|
||||
/// (a marker where it is blocked). Dashed green: clear without a geometry test (raycasting off or
|
||||
/// warming up, or no geometry near the path). Thin, dim lines go to the other monsters in range.
|
||||
/// Off by default; /ra losline [on|off].
|
||||
/// </summary>
|
||||
public bool ShowLosLine;
|
||||
internal const string ShowLosLineTip =
|
||||
"A line from you to the combat target: green when RynthAi's line-of-sight raycast says clear,\n" +
|
||||
"red when it says blocked, with a yellow marker where the raycast hit. Dashed green: clear without\n" +
|
||||
"a geometry test (raycasting off or warming up, or no geometry near the path). Thin dim lines go\n" +
|
||||
"to the other monsters in range. A testing aid; off by default. /ra losline [on|off].";
|
||||
|
||||
public bool EnableFPSLimit = true;
|
||||
public int TargetFPSFocused = 60;
|
||||
|
|
@ -956,6 +978,10 @@ public sealed class LegacyUiSettings
|
|||
/// The autoAcceptList.json files (/ub autotrade autoaccept ...) are read as well.</summary>
|
||||
public List<string> AutoTradeAutoAcceptChars { get; set; } = new();
|
||||
|
||||
// ── Trade Shop (a player-run shop from tells; /ra tradeshop, the Trade Shop window) ────────
|
||||
/// <summary>The shop's settings and catalog (Trade/TradeShopSettings.cs). Its on/off is never saved: off at every login.</summary>
|
||||
public Trade.TradeShopSettings TradeShop { get; set; } = new();
|
||||
|
||||
public List<MonsterRule> MonsterRules { get; set; } = new();
|
||||
public List<ItemRule> ItemRules { get; set; } = new();
|
||||
/// <summary>Loose ammo the monster rules can prefer. Edited by the local monsters window.</summary>
|
||||
|
|
@ -1459,6 +1485,7 @@ public sealed class SettingsBridgePayload
|
|||
public float MagicArcVelocity { get; set; }
|
||||
public float MissileArcClearance { get; set; } = 0.5f; // absent in older payloads
|
||||
public bool LosDebugLog { get; set; }
|
||||
public bool? ShowLosLine { get; set; } // Show Line of Sight (2026-11-26); absent = unchanged
|
||||
public int BlacklistAttempts { get; set; }
|
||||
public int BlacklistTimeoutSec { get; set; }
|
||||
// -1 = absent from the payload: the overlay's Settings panel didn't send it, and
|
||||
|
|
|
|||
141
Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RechargeHold.cs
Normal file
141
Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RechargeHold.cs
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - RechargeHold.cs
|
||||
// No recharge for now: health, stamina and mana recharge held off, the settings kept (2026-11-24).
|
||||
//
|
||||
// R-20261124-121710-7876 (DreamWeave, Threads): "When running Threads ... you generally don't want
|
||||
// your character to pull out a wand to recharge vitals while fighting"; a quick way to turn the
|
||||
// Recharge lines off and "restore the previous settings with a single click".
|
||||
// Tried as a button players can turn on and off.
|
||||
//
|
||||
// A hold sets a vital's recharge lines to 0 (the settings' own "off") and keeps the real values:
|
||||
// Health Heal At, Top Off HP, Stamina To Health At (Emergency Heal At stays: the safety floor)
|
||||
// Stamina Re-stam At, Re-stam To, Top Off Stam
|
||||
// Mana Get Mana At, Top Off Mana
|
||||
// Zeroing the lines themselves, not one decision, keeps every reader in step (the vitals pass, the
|
||||
// arbiter's "wants a recharge", the mana reserve, the idle top-off). Releasing puts the real values
|
||||
// back, except a line the player set to something else while it was held (theirs wins). Every save
|
||||
// writes the real values (WithRealValues), so a hold never reaches the profile, and a profile
|
||||
// loaded while held keeps the hold over its own values. Not saved: a reload or relog ends it.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
/// <summary>The vitals a recharge hold can cover.</summary>
|
||||
[Flags]
|
||||
internal enum RechargeVital
|
||||
{
|
||||
None = 0,
|
||||
Health = 1,
|
||||
Stamina = 2,
|
||||
Mana = 4,
|
||||
All = Health | Stamina | Mana,
|
||||
}
|
||||
|
||||
internal sealed class RechargeHold
|
||||
{
|
||||
private sealed record Line(RechargeVital Vital, string Name, Func<LegacyUiSettings, int> Get, Action<LegacyUiSettings, int> Set);
|
||||
|
||||
private static readonly Line[] Lines =
|
||||
{
|
||||
new(RechargeVital.Health, "Heal At", s => s.HealAt, (s, v) => s.HealAt = v),
|
||||
new(RechargeVital.Health, "Top Off HP", s => s.TopOffHP, (s, v) => s.TopOffHP = v),
|
||||
new(RechargeVital.Health, "Stamina To Health At", s => s.StaminaToHealthAt, (s, v) => s.StaminaToHealthAt = v),
|
||||
new(RechargeVital.Stamina, "Re-stam At", s => s.RestamAt, (s, v) => s.RestamAt = v),
|
||||
new(RechargeVital.Stamina, "Re-stam To", s => s.RestamTo, (s, v) => s.RestamTo = v),
|
||||
new(RechargeVital.Stamina, "Top Off Stam", s => s.TopOffStam, (s, v) => s.TopOffStam = v),
|
||||
new(RechargeVital.Mana, "Get Mana At", s => s.GetManaAt, (s, v) => s.GetManaAt = v),
|
||||
new(RechargeVital.Mana, "Top Off Mana", s => s.TopOffMana, (s, v) => s.TopOffMana = v),
|
||||
};
|
||||
|
||||
private readonly object _sync = new();
|
||||
private readonly Dictionary<string, int> _real = new(); // a held line's real value
|
||||
|
||||
/// <summary>The vitals held now.</summary>
|
||||
public RechargeVital Held { get; private set; }
|
||||
|
||||
/// <summary>Holds (<paramref name="on"/>) or releases the recharge of <paramref name="vitals"/>.</summary>
|
||||
public void Set(LegacyUiSettings s, RechargeVital vitals, bool on)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
foreach (Line line in Lines)
|
||||
{
|
||||
if ((line.Vital & vitals) == 0) continue;
|
||||
bool held = _real.ContainsKey(line.Name);
|
||||
if (on && !held)
|
||||
{
|
||||
_real[line.Name] = line.Get(s);
|
||||
line.Set(s, 0);
|
||||
}
|
||||
else if (!on && held)
|
||||
{
|
||||
if (line.Get(s) == 0) line.Set(s, _real[line.Name]); // a value the player set meanwhile stays
|
||||
_real.Remove(line.Name);
|
||||
}
|
||||
}
|
||||
Held = on ? Held | vitals : Held & ~vitals;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="read"/> (a save) with the held lines at their real values, then holds them
|
||||
/// again: a hold never reaches the profile.
|
||||
/// </summary>
|
||||
public T WithRealValues<T>(LegacyUiSettings s, Func<T> read)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (_real.Count == 0) return read();
|
||||
var swapped = new List<Line>();
|
||||
foreach (Line line in Lines)
|
||||
{
|
||||
if (!_real.TryGetValue(line.Name, out int real) || line.Get(s) != 0) continue;
|
||||
line.Set(s, real);
|
||||
swapped.Add(line);
|
||||
}
|
||||
try { return read(); }
|
||||
finally { foreach (Line line in swapped) line.Set(s, 0); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A profile was copied over the settings: its values are the real ones now, held again (the
|
||||
/// hold stays, over the new profile's lines).
|
||||
/// </summary>
|
||||
public void Reapply(LegacyUiSettings s)
|
||||
{
|
||||
RechargeVital held;
|
||||
lock (_sync)
|
||||
{
|
||||
held = Held;
|
||||
_real.Clear();
|
||||
Held = RechargeVital.None;
|
||||
}
|
||||
if (held != RechargeVital.None) Set(s, held, true);
|
||||
}
|
||||
|
||||
/// <summary>The real value of a held line (tests, the tooltip); null when that line isn't held.</summary>
|
||||
public int? RealValue(string lineName)
|
||||
{
|
||||
lock (_sync) return _real.TryGetValue(lineName, out int v) ? v : null;
|
||||
}
|
||||
|
||||
/// <summary>"health, stamina and mana", "stamina", ...</summary>
|
||||
public static string Describe(RechargeVital v)
|
||||
{
|
||||
var parts = new List<string>(3);
|
||||
if ((v & RechargeVital.Health) != 0) parts.Add("health");
|
||||
if ((v & RechargeVital.Stamina) != 0) parts.Add("stamina");
|
||||
if ((v & RechargeVital.Mana) != 0) parts.Add("mana");
|
||||
return parts.Count switch
|
||||
{
|
||||
0 => "nothing",
|
||||
1 => parts[0],
|
||||
2 => parts[0] + " and " + parts[1],
|
||||
_ => parts[0] + ", " + parts[1] + " and " + parts[2],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -171,9 +171,16 @@ public sealed class InventoryManager
|
|||
private bool ManualCram => RynthClock.Now < _manualCramUntil;
|
||||
private bool ManualStack => RynthClock.Now < _manualStackUntil;
|
||||
|
||||
/// <summary>
|
||||
/// Auto Cram / Auto Stack also run with the macro off while this says so: the Item Tool's chest
|
||||
/// looter, which loots with the macro off too (2026-11-24, #rynth-issues "Inventory Autocram does
|
||||
/// not actively run while looting chests with ItemTool": the main pack filled and nothing moved).
|
||||
/// </summary>
|
||||
public Func<bool>? KeepsPacksWithoutMacro { get; set; }
|
||||
|
||||
public void OnHeartbeat(int busyCount)
|
||||
{
|
||||
if (!_settings.IsMacroRunning && !ManualCram && !ManualStack) return;
|
||||
if (!_settings.IsMacroRunning && !ManualCram && !ManualStack && KeepsPacksWithoutMacro?.Invoke() != true) return;
|
||||
if (busyCount != 0) return; // don't move items while the client is busy (casting, crafting, etc.)
|
||||
|
||||
// Age-prune the per-entry backoff/pending maps (replaces the old wholesale
|
||||
|
|
|
|||
160
Plugins/RynthCore.Plugin.RynthAi/LosLineOverlay.cs
Normal file
160
Plugins/RynthCore.Plugin.RynthAi/LosLineOverlay.cs
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Plugin.RynthAi - LosLineOverlay.cs
|
||||
// Show Line of Sight (2026-11-26, a testing aid, setting ShowLosLine, /ra losline):
|
||||
// a line in the world from the character's chest to the combat target's chest,
|
||||
// the path the targeting raycast tests, in the colour of the verdict the target
|
||||
// scan gave it (CombatManager.LosVerdicts.cs; no raycast here):
|
||||
// green the raycast tested the line and says clear
|
||||
// dashed green clear without a geometry test (raycasting off or warming up,
|
||||
// no geometry near the path, too far)
|
||||
// red the raycast says blocked; a yellow marker where it hit
|
||||
// Thin dim lines (green-grey / red-grey) go to the other monsters the scan tested,
|
||||
// nearest first, at most MaxOthers.
|
||||
//
|
||||
// Drawn on the engine's Nav3D buffer like the nav markers (NavMarkerRenderer):
|
||||
// frame X = east metres, Y = height, Z = north metres, in the player's landblock.
|
||||
// Submitted from the plugin tick, before the nav markers, so a long route's lines
|
||||
// can't crowd it out of the 512-line buffer.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
internal sealed class LosLineOverlay
|
||||
{
|
||||
// ARGB (D3D9).
|
||||
internal const uint ColorClear = 0xFF20E040;
|
||||
internal const uint ColorBlocked = 0xFFFF3030;
|
||||
internal const uint ColorHit = 0xFFFFE020;
|
||||
internal const uint ColorOtherClear = 0x9080B088;
|
||||
internal const uint ColorOtherBlocked = 0x90B07070;
|
||||
|
||||
internal const float MainThick = 0.05f; // half-width of the line's ground quad, metres
|
||||
internal const float OtherThick = 0.02f;
|
||||
internal const float ChestHeight = 1.0f; // TargetingFSM tests feet + 1 m on both ends
|
||||
internal const int MaxOthers = 12;
|
||||
internal const double StaleMs = 3000; // a verdict older than this isn't drawn (no scan lately)
|
||||
internal const float DashStep = 0.8f; // dashed: one dash per this many metres...
|
||||
internal const float DashFill = 0.55f; // ...of this fraction of the step
|
||||
internal const int MaxDashes = 40;
|
||||
internal const float HitRingRadius = 0.25f, HitRingHeight = 0.5f, HitSize = 0.18f;
|
||||
private static readonly float[] RimX = { 1f, 0f, -1f, 0f };
|
||||
private static readonly float[] RimZ = { 0f, 1f, 0f, -1f };
|
||||
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly Func<LegacyUiSettings?> _settings;
|
||||
private readonly Func<CombatManager?> _combat;
|
||||
private readonly List<(int Id, CombatManager.LosVerdict V)> _others = new();
|
||||
|
||||
/// <summary>Tests: the clock staleness is judged by.</summary>
|
||||
internal Func<DateTime> Clock { get; set; } = () => RynthClock.Now;
|
||||
|
||||
public LosLineOverlay(RynthCoreHost host, Func<LegacyUiSettings?> settings, Func<CombatManager?> combat)
|
||||
{
|
||||
_host = host;
|
||||
_settings = settings;
|
||||
_combat = combat;
|
||||
}
|
||||
|
||||
/// <summary>Lines drawn by the last Submit (tests and /ra losline status).</summary>
|
||||
internal int LastLines { get; private set; }
|
||||
|
||||
/// <summary>The plugin tick: submit this tick's line(s). Nothing when the setting is off.</summary>
|
||||
public void Submit()
|
||||
{
|
||||
LastLines = 0;
|
||||
var s = _settings();
|
||||
if (s == null || !s.ShowLosLine || !_host.HasNav3D) return;
|
||||
var cm = _combat();
|
||||
if (cm == null || cm.LosVerdicts.Count == 0) return;
|
||||
try { Draw(cm); }
|
||||
catch (Exception ex) { _host.Log($"LosLine(3D): {ex.Message}"); }
|
||||
}
|
||||
|
||||
private void Draw(CombatManager cm)
|
||||
{
|
||||
if (!_host.TryGetPlayerPose(out uint cell, out float px, out float py, out float pz, out _, out _, out _, out _))
|
||||
return;
|
||||
if ((cell >> 16) == 0) return; // portal space
|
||||
if (_host.HasIsPortaling && _host.IsPortaling()) return;
|
||||
|
||||
float baseX = ((cell >> 24) & 0xFF) * 192f, baseY = ((cell >> 16) & 0xFF) * 192f;
|
||||
float ax = px, ay = pz + ChestHeight, az = py; // the player's chest, Nav3D frame
|
||||
DateTime now = Clock();
|
||||
|
||||
int target = cm.LosLineTargetId;
|
||||
if (target != 0 && cm.TryGetLosVerdict(target, out var tv) && Fresh(tv, now)
|
||||
&& TargetChest(target, baseX, baseY, out float bx, out float by, out float bz))
|
||||
{
|
||||
uint color = tv.Blocked ? ColorBlocked : ColorClear;
|
||||
if (!tv.Blocked && !tv.Tested) Dashed(ax, ay, az, bx, by, bz, MainThick, color);
|
||||
else Line(ax, ay, az, bx, by, bz, MainThick, color);
|
||||
if (tv.Blocked && tv.HasHit) HitMarker(tv.HitX - baseX, tv.HitZ, tv.HitY - baseY);
|
||||
}
|
||||
|
||||
// The other monsters the scan tested, nearest first.
|
||||
_others.Clear();
|
||||
foreach (var kv in cm.LosVerdicts)
|
||||
if (kv.Key != target && Fresh(kv.Value, now)) _others.Add((kv.Key, kv.Value));
|
||||
if (_others.Count == 0) return;
|
||||
_others.Sort((a, b) => a.V.Distance.CompareTo(b.V.Distance));
|
||||
int n = Math.Min(_others.Count, MaxOthers);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var (id, v) = _others[i];
|
||||
if (!TargetChest(id, baseX, baseY, out float ox, out float oy, out float oz)) continue;
|
||||
Line(ax, ay, az, ox, oy, oz, OtherThick, v.Blocked ? ColorOtherBlocked : ColorOtherClear);
|
||||
}
|
||||
}
|
||||
|
||||
private bool Fresh(in CombatManager.LosVerdict v, DateTime now) => (now - v.At).TotalMilliseconds <= StaleMs;
|
||||
|
||||
/// <summary>A monster's chest in the player's Nav3D frame (its landblock can be the next one).</summary>
|
||||
private bool TargetChest(int id, float baseX, float baseY, out float x, out float y, out float z)
|
||||
{
|
||||
x = y = z = 0f;
|
||||
if (!_host.TryGetObjectPosition(unchecked((uint)id), out uint tc, out float tx, out float ty, out float tz) || tc == 0)
|
||||
return false;
|
||||
x = ((tc >> 24) & 0xFF) * 192f + tx - baseX;
|
||||
z = ((tc >> 16) & 0xFF) * 192f + ty - baseY;
|
||||
y = tz + ChestHeight;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thick, uint color)
|
||||
{
|
||||
_host.Nav3DAddLine(x1, y1, z1, x2, y2, z2, thick, color);
|
||||
LastLines++;
|
||||
}
|
||||
|
||||
private void Dashed(float x1, float y1, float z1, float x2, float y2, float z2, float thick, uint color)
|
||||
{
|
||||
float dx = x2 - x1, dy = y2 - y1, dz = z2 - z1;
|
||||
float len = MathF.Sqrt(dx * dx + dy * dy + dz * dz);
|
||||
int steps = Math.Clamp((int)MathF.Ceiling(len / DashStep), 2, MaxDashes);
|
||||
for (int i = 0; i < steps; i++)
|
||||
{
|
||||
float t0 = (float)i / steps, t1 = (i + DashFill) / steps;
|
||||
Line(x1 + dx * t0, y1 + dy * t0, z1 + dz * t0, x1 + dx * t1, y1 + dy * t1, z1 + dz * t1, thick, color);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A short yellow post round the hit point, and a small diamond on it when triangles are there.</summary>
|
||||
private void HitMarker(float x, float y, float z)
|
||||
{
|
||||
_host.Nav3DAddRingEx(x, y - HitRingHeight * 0.5f, z, HitRingRadius, 0.04f, HitRingHeight, ColorHit);
|
||||
if (!_host.HasNav3DTriangle) return;
|
||||
float h = HitSize;
|
||||
// An octahedron: four faces up, four down, round the rim (h,0) (0,h) (-h,0) (0,-h).
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
float ax = RimX[i] * h, az = RimZ[i] * h, bx = RimX[(i + 1) % 4] * h, bz = RimZ[(i + 1) % 4] * h;
|
||||
_host.Nav3DAddTriangle(x + ax, y, z + az, x + bx, y, z + bz, x, y + h, z, ColorHit);
|
||||
_host.Nav3DAddTriangle(x + ax, y, z + az, x + bx, y, z + bz, x, y - h, z, ColorHit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -184,6 +184,11 @@ NAVIGATION / GEOMETRY
|
|||
/ra lostest
|
||||
Run a line-of-sight raycast test from the player to the current target.
|
||||
|
||||
/ra losline [on|off]
|
||||
Show Line of Sight: a line in the world from you to the combat target, green when the
|
||||
targeting raycast says clear, red when it says blocked (a yellow marker where it hit),
|
||||
dashed when it wasn't tested. No argument toggles.
|
||||
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
FELLOWSHIP
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
|
|
|||
|
|
@ -197,6 +197,7 @@ internal sealed partial class ExpressionEngine
|
|||
{
|
||||
FlushVars(force: true); // persist the old char's pending pvars first
|
||||
_pvars = null;
|
||||
_pvarsUnresolved = false;
|
||||
_pvarPathCached = null;
|
||||
ResetXpMeter();
|
||||
}
|
||||
|
|
@ -680,10 +681,33 @@ internal sealed partial class ExpressionEngine
|
|||
|
||||
// ── Persistent variable implementations ───────────────────────────────────
|
||||
|
||||
// ── Before the character's name is known (2026-11-25, R-20261125-190541-5671) ──
|
||||
// Coldeve: "Doesn't seem like getpvar/setpvar works in the meta?". A pvar read before the client had
|
||||
// the character's name loaded the file for "unknown", and that stayed the session's pvars: the
|
||||
// character's own file was never read (every getpvar said 0), and the next save wrote the session's
|
||||
// values over it, so what a meta saved was gone next login. Now pvars read or written before the
|
||||
// name is known are held apart; once it is known the character's file is loaded and they are laid
|
||||
// over it (the session's writes win), and nothing is saved until then.
|
||||
// With no character at all (no player id) they go to unknown.txt as before.
|
||||
private bool _pvarsUnresolved;
|
||||
|
||||
private Dictionary<string, string> GetPvars()
|
||||
{
|
||||
if (_pvars != null) return _pvars;
|
||||
return _pvars = LoadVarFile(GetPvarPath());
|
||||
string path = GetPvarPath();
|
||||
bool resolved = _pvarPathCached != null || _playerId == 0; // no character at all: unknown.txt, as before
|
||||
if (_pvars != null)
|
||||
{
|
||||
if (_pvarsUnresolved && resolved)
|
||||
{
|
||||
var real = LoadVarFile(path);
|
||||
foreach (var (k, v) in _pvars) real[k] = v;
|
||||
_pvars = real;
|
||||
_pvarsUnresolved = false;
|
||||
}
|
||||
return _pvars;
|
||||
}
|
||||
_pvarsUnresolved = !resolved;
|
||||
return _pvars = resolved ? LoadVarFile(path) : new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private string GetPvarPath()
|
||||
|
|
@ -778,7 +802,11 @@ internal sealed partial class ExpressionEngine
|
|||
if (!_pvarsDirty && !_gvarsDirty) return;
|
||||
long now = TickMs();
|
||||
if (!force && now - _lastVarFlushMs < VarFlushIntervalMs) return;
|
||||
if (_pvarsDirty && _pvars != null) { SaveVarFile(GetPvarPath(), _pvars); _pvarsDirty = false; }
|
||||
if (_pvarsDirty && _pvars != null)
|
||||
{
|
||||
var pvars = GetPvars(); // joins the character's file once the name is known
|
||||
if (!_pvarsUnresolved) { SaveVarFile(GetPvarPath(), pvars); _pvarsDirty = false; }
|
||||
}
|
||||
if (_gvarsDirty && _gvars != null) { SaveVarFile(GvarsPath, _gvars); _gvarsDirty = false; }
|
||||
_lastVarFlushMs = now;
|
||||
}
|
||||
|
|
@ -3650,6 +3678,7 @@ internal sealed partial class ExpressionEngine
|
|||
["EnableRaycasting"] = (() => B(s.EnableRaycasting), v => s.EnableRaycasting = ToDouble(v) != 0),
|
||||
["UseArcs"] = (() => B(s.UseArcs), v => s.UseArcs = ToDouble(v) != 0),
|
||||
["LosDebugLog"] = (() => B(s.LosDebugLog), v => s.LosDebugLog = ToDouble(v) != 0),
|
||||
["ShowLosLine"] = (() => B(s.ShowLosLine), v => s.ShowLosLine = ToDouble(v) != 0),
|
||||
["BowArcVelocity"] = (() => F(s.BowArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.BowArcVelocity = Math.Clamp(f, 10f, 60f); }),
|
||||
["CrossbowArcVelocity"] = (() => F(s.CrossbowArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.CrossbowArcVelocity = Math.Clamp(f, 10f, 80f); }),
|
||||
["AtlatlArcVelocity"] = (() => F(s.AtlatlArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.AtlatlArcVelocity = Math.Clamp(f, 10f, 60f); }),
|
||||
|
|
|
|||
|
|
@ -19,6 +19,11 @@
|
|||
// - a run that made kits: the next look in 30 s (the count decides then).
|
||||
// Before a start, a pack that can't make a kit (out of an ingredient, under the floor, untrained)
|
||||
// is said once per reason, then looked at again every 30 s.
|
||||
//
|
||||
// "Make ammo when low" (MissileCraftingManager.Auto, RynthAiPlugin.Ammo.cs, 2026-11-23) runs on the
|
||||
// same rules with its own instance: its Name and Doing, and the facts' CountText ("230 arrows"),
|
||||
// BelowMax (ammo counts run to thousands) and IdleWhy ("no launcher in hand"). Their defaults are the
|
||||
// kits' own, so a kit look reads exactly as before.
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
|
||||
|
|
@ -79,6 +84,12 @@ internal sealed class KitAutoFacts
|
|||
public string VitalsWhy = string.Empty;
|
||||
/// <summary>"" when nothing else needs the character; else what does (buffing, a fight, looting, ...).</summary>
|
||||
public string BusyWhy = string.Empty;
|
||||
/// <summary>The most <see cref="Below"/> may be (kits: <see cref="KitAuto.MaxBelow"/>).</summary>
|
||||
public int BelowMax = KitAuto.MaxBelow;
|
||||
/// <summary>"N kits" for the count in the status and chat (null = <see cref="KitAuto.KitsText"/>).</summary>
|
||||
public Func<int, string>? CountText;
|
||||
/// <summary>"" = look as usual; else nothing to do for now, and why (no launcher in hand, ...): no start, no chat.</summary>
|
||||
public string IdleWhy = string.Empty;
|
||||
}
|
||||
|
||||
internal sealed class KitAuto
|
||||
|
|
@ -110,6 +121,10 @@ internal sealed class KitAuto
|
|||
public Func<long> NowMs = static () => Environment.TickCount64;
|
||||
/// <summary>A chat line for the player (a reason said once).</summary>
|
||||
public Action<string>? Say;
|
||||
/// <summary>The feature's name in chat ("Make kits when low").</summary>
|
||||
public string Name = "Make kits when low";
|
||||
/// <summary>What a run does, for the status ("stopping to make kits").</summary>
|
||||
public string Doing = "make kits";
|
||||
|
||||
private long _nextCheckAt;
|
||||
private string _waitWhy = string.Empty;
|
||||
|
|
@ -135,8 +150,9 @@ internal sealed class KitAuto
|
|||
{
|
||||
if (!f.Enabled) return (KitBlock.Off, "off");
|
||||
if (!f.MacroOn) return (KitBlock.MacroOff, "the macro is off");
|
||||
int below = Math.Clamp(f.Below, 1, MaxBelow);
|
||||
if (f.Kits >= below) return (KitBlock.Enough, $"{KitsText(f.Kits)} carried (makes more under {below})");
|
||||
if (f.IdleWhy.Length > 0) return (KitBlock.Enough, f.IdleWhy);
|
||||
int below = Math.Clamp(f.Below, 1, Math.Max(1, f.BelowMax));
|
||||
if (f.Kits >= below) return (KitBlock.Enough, $"{(f.CountText ?? KitsText)(f.Kits)} carried (makes more under {below})");
|
||||
if (f.BusyWhy.Length > 0) return (KitBlock.Busy, f.BusyWhy);
|
||||
if (f.VitalsWhy.Length > 0) return (KitBlock.Vitals, f.VitalsWhy);
|
||||
if (f.NearestMonsterYd <= f.RadiusYd) return (KitBlock.Monster, $"monster {f.NearestMonsterYd:0} yd away");
|
||||
|
|
@ -196,7 +212,7 @@ internal sealed class KitAuto
|
|||
if (_said != why && !why.StartsWith("can't read", StringComparison.Ordinal))
|
||||
{
|
||||
_said = why;
|
||||
SayLine($"[RynthAi] Make kits when low: {KitsText(f.Kits)} left, but none can be made now: {why}.");
|
||||
SayLine($"[RynthAi] {Name}: {(f.CountText ?? KitsText)(f.Kits)} left, but none can be made now: {why}.");
|
||||
}
|
||||
Wait(now, PackCheckMs, why);
|
||||
break;
|
||||
|
|
@ -241,7 +257,7 @@ internal sealed class KitAuto
|
|||
if (f.Moving)
|
||||
{
|
||||
_stillSince = -1;
|
||||
_status = "stopping to make kits";
|
||||
_status = "stopping to " + Doing;
|
||||
return KitAutoStep.Hold;
|
||||
}
|
||||
if (_stillSince < 0) _stillSince = now;
|
||||
|
|
@ -288,7 +304,7 @@ internal sealed class KitAuto
|
|||
return $" Next try in {CooldownMs / 1000} s at the earliest.";
|
||||
case KitStopKind.User:
|
||||
Wait(now, BackoffMs, "you stopped the last run");
|
||||
return $" Next try in {BackoffMs / 60_000} min (turn Make kits when low off to stop it for good).";
|
||||
return $" Next try in {BackoffMs / 60_000} min (turn {Name} off to stop it for good).";
|
||||
default:
|
||||
if (made <= 0)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@
|
|||
// ingredients, one combine at a time, only while the macro is off (also /ra kits). Under it,
|
||||
// "Make kits when low" (KitAuto; the macro side is RynthAiPlugin.Kits.cs) does the same by itself
|
||||
// while the macro runs, when the kits carried fall under the line and nothing is around.
|
||||
// The Ammo sub-tab: "Make ammo when low" and "Make ammo now" (MissileCraftingManager's top-off; the
|
||||
// macro side is RynthAiPlugin.Ammo.cs), arrows, quarrels or darts for the launcher in hand.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
|
@ -46,6 +48,16 @@ internal sealed class CraftingTab
|
|||
public void SelectKitsTab() => _selectKits = true;
|
||||
private static readonly byte[] KitsTabLabel = System.Text.Encoding.UTF8.GetBytes("Kits\0");
|
||||
|
||||
/// <summary>Make ammo when low / Make ammo now (the Ammo sub-tab): the plugin's crafting manager (null = not logged in).</summary>
|
||||
public Func<MissileCraftingManager?>? Ammo { get; set; }
|
||||
/// <summary>What Make ammo when low is doing (RynthAiPlugin.AmmoAutoStatusText).</summary>
|
||||
public Func<LegacyUiSettings, string>? AmmoStatus { get; set; }
|
||||
/// <summary>A command asked for the Ammo sub-tab (the next frame selects it).</summary>
|
||||
private volatile bool _selectAmmo;
|
||||
public void SelectAmmoTab() => _selectAmmo = true;
|
||||
private static readonly byte[] AmmoTabLabel = System.Text.Encoding.UTF8.GetBytes("Ammo\0");
|
||||
private long _ammoLookAskedAt;
|
||||
|
||||
// Custom-row editor (render thread only)
|
||||
private int _newMaterial = TinkerCatalog.Steel;
|
||||
private int _newKind;
|
||||
|
|
@ -146,9 +158,103 @@ internal sealed class CraftingTab
|
|||
bool selectKits = _selectKits;
|
||||
_selectKits = false;
|
||||
if (BeginTab(KitsTabLabel, selectKits ? ImGuiTabItemFlags.SetSelected : ImGuiTabItemFlags.None)) { RenderKits(); ImGui.EndTabItem(); }
|
||||
bool selectAmmo = _selectAmmo;
|
||||
_selectAmmo = false;
|
||||
if (BeginTab(AmmoTabLabel, selectAmmo ? ImGuiTabItemFlags.SetSelected : ImGuiTabItemFlags.None)) { RenderAmmo(); ImGui.EndTabItem(); }
|
||||
ImGui.EndTabBar();
|
||||
}
|
||||
|
||||
// ── Ammo (render thread) ────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The Ammo sub-tab: what is carried, Make ammo when low with its two numbers, Make ammo now / Stop.</summary>
|
||||
private void RenderAmmo()
|
||||
{
|
||||
var settings = _ctx.Settings;
|
||||
var cm = Ammo?.Invoke();
|
||||
if (settings == null || cm == null) { SafeImGui.TextDisabled("Log in to make ammo."); return; }
|
||||
|
||||
// A fresh look at the quiver and the pack every 2 s while the tab shows (the pump thread walks it).
|
||||
long now = MiniRemoteContext.NowMs;
|
||||
if (now - _ammoLookAskedAt > 2000)
|
||||
{
|
||||
_ammoLookAskedAt = now;
|
||||
_ctx.Post(() => cm.LookTopOff(forceRefresh: false));
|
||||
}
|
||||
|
||||
SafeImGui.TextWrapped("Makes arrows, quarrels or darts for the launcher in hand from the head and shaft bundles in your pack, "
|
||||
+ "between fights: only with no monster near, and it stops at once if one comes close or something hits you. "
|
||||
+ "It never goes to peace mode in a fight. Fletching must be trained; it only makes ammo your skill makes reliably.");
|
||||
if (!settings.EnableMissileCrafting)
|
||||
SafeImGui.TextColored(LegacyDashboardRenderer.ColAmber, "Enable Missile Crafting is off (Settings > Combat): turn it on first.");
|
||||
ImGui.Spacing();
|
||||
|
||||
var look = cm.LastLook;
|
||||
if (look == null) SafeImGui.TextDisabled("Reading your pack...");
|
||||
else if (!look.Launcher) SafeImGui.TextDisabled("No bow, crossbow or atlatl in hand.");
|
||||
else
|
||||
{
|
||||
ImGui.TextUnformatted($"Carried: {look.CarriedText} (quiver and pack)");
|
||||
if (look.Recipe != null && look.Combines > 0)
|
||||
SafeImGui.TextDisabled($"Your pack makes {look.Recipe.OutputName}, about {AmmoRecipes.EstimatedYield(look.Recipe)} a combine.");
|
||||
else
|
||||
SafeImGui.TextDisabled("None can be made now: " + look.PackWhy + ".");
|
||||
}
|
||||
|
||||
ImGui.Separator();
|
||||
bool on = settings.MakeAmmoWhenLow;
|
||||
if (ImGui.Checkbox("Make ammo when low##ammoauto", ref on))
|
||||
{
|
||||
bool value = on;
|
||||
_ctx.Post(() => { settings.MakeAmmoWhenLow = value; _ctx.SaveCombatSettings?.Invoke(); });
|
||||
}
|
||||
if (ImGui.IsItemHovered())
|
||||
SafeImGui.SetTooltip("While the macro runs: when you carry fewer arrows, quarrels or darts for the launcher in hand than the\n"
|
||||
+ "first number (quiver and pack), make them up to the second number from your bundles.\n"
|
||||
+ $"Only when nothing is around: no monster within {KitAuto.DefaultRadiusYd:0} yd (or your Monster Range, if bigger),\n"
|
||||
+ $"no hit for {KitAuto.HurtQuietMs / 1000} s, no healing, buffing, looting or fight. The macro waits meanwhile;\n"
|
||||
+ "a monster, a hit, a heal or moving stops it at once. Also /ra ammo auto on|off.");
|
||||
ImGui.SameLine();
|
||||
ImGui.AlignTextToFramePadding();
|
||||
ImGui.TextUnformatted("when fewer than");
|
||||
ImGui.SameLine();
|
||||
int below = Math.Clamp(settings.MakeAmmoBelow, 1, MissileCraftingManager.MaxAmmoBelow);
|
||||
ImGui.SetNextItemWidth(100);
|
||||
if (ImGui.InputInt("##ammobelow", ref below, 10, 100))
|
||||
{
|
||||
int value = Math.Clamp(below, 1, MissileCraftingManager.MaxAmmoBelow);
|
||||
_ctx.Post(() => { settings.MakeAmmoBelow = value; _ctx.SaveCombatSettings?.Invoke(); });
|
||||
}
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip($"A top-off starts when you carry fewer than this (1-{MissileCraftingManager.MaxAmmoBelow}). A plain bundle makes 100. Also /ra ammo auto below N.");
|
||||
ImGui.SameLine();
|
||||
ImGui.TextUnformatted(", make up to");
|
||||
ImGui.SameLine();
|
||||
int upTo = Math.Clamp(settings.MakeAmmoUpTo, 1, MissileCraftingManager.MaxAmmoUpTo);
|
||||
ImGui.SetNextItemWidth(100);
|
||||
if (ImGui.InputInt("##ammoupto", ref upTo, 100, 1000))
|
||||
{
|
||||
int value = Math.Clamp(upTo, 1, MissileCraftingManager.MaxAmmoUpTo);
|
||||
_ctx.Post(() => { settings.MakeAmmoUpTo = value; _ctx.SaveCombatSettings?.Invoke(); });
|
||||
}
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip($"A top-off makes combines until about this many are carried (1-{MissileCraftingManager.MaxAmmoUpTo}, at most {MissileCraftingManager.MaxTopOffCombines} combines;\n"
|
||||
+ "a plain bundle makes 100, a wrapped one 1000, so it can go over). Never under the first number. Also /ra ammo auto upto M.");
|
||||
|
||||
ImGui.BeginDisabled(!settings.EnableMissileCrafting || cm.TopOffRunning);
|
||||
if (ImGui.Button("Make ammo now##ammonow")) cm.RequestMakeNow();
|
||||
ImGui.EndDisabled();
|
||||
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
|
||||
SafeImGui.SetTooltip("Make ammo up to the second number at the next safe moment (macro on or off), waiting up to a minute. Also /ra ammo make.");
|
||||
ImGui.SameLine();
|
||||
ImGui.BeginDisabled(!cm.TopOffRunning && cm.MakeNowUntilMs <= 0);
|
||||
if (ImGui.Button("Stop##ammostop")) cm.RequestStop();
|
||||
ImGui.EndDisabled();
|
||||
ImGui.SameLine();
|
||||
SafeImGui.TextDisabled("Make ammo when low: " + (AmmoStatus?.Invoke(settings) ?? ""));
|
||||
if (cm.LastTopOffSummary.Length > 0) SafeImGui.TextWrapped("Last top-off: " + cm.LastTopOffSummary.Replace("[RynthAi] Make ammo when low: ", ""));
|
||||
SafeImGui.TextDisabled("When the quiver runs dry, Enable Missile Crafting still makes ammo on its own, as before. Also /ra ammo.");
|
||||
}
|
||||
|
||||
/// <summary>BeginTabItem with flags and no close button (ImGui.NET only wraps flags with p_open).</summary>
|
||||
private static unsafe bool BeginTab(byte[] labelUtf8Z, ImGuiTabItemFlags flags)
|
||||
{
|
||||
|
|
|
|||
104
Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.NpcTalk.cs
Normal file
104
Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.NpcTalk.cs
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - NavigationEngine.NpcTalk.cs
|
||||
// VTank "NPC" nav points (type 7): walk to the point, use the NPC, then go on (2026-11-23).
|
||||
//
|
||||
// #rynth-meta-and-expression-issues (a meta author, 11-23): "NPC 'talk' nav nodes do nothing
|
||||
// (breaks all 7 metas)". NavRouteParser read type 7 and its NPC name, but the point-type dispatch
|
||||
// handled only Pause, Chat, Recall and Portal, so an NPC point was walked like a plain waypoint
|
||||
// and passed without the NPC being used. Their navs do every task pickup and turn-in this way
|
||||
// (56 NPC points); with no talk there are no "X tells you" lines, no task flags, and the meta
|
||||
// loops round the NPC area or "finishes" without the tasks.
|
||||
//
|
||||
// Now an NPC point is walked to like any waypoint; on arriving (or passing it) the bot stops and
|
||||
// uses the NPC by name, the nearest one with that name, as a Portal point uses its portal
|
||||
// (FirePortalNpcUse: AC walks the character over and uses it), then waits for the use to finish
|
||||
// and the NPC to answer (NpcTalkMinMs, while the client is busy up to NpcTalkMaxMs) before it goes
|
||||
// on. An NPC that can't be found in NpcFindTimeoutMs is said once in chat and the route goes on.
|
||||
// ============================================================================
|
||||
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
internal sealed partial class NavigationEngine
|
||||
{
|
||||
/// <summary>After the use, the least wait before going on: the walk over and the NPC's lines.</summary>
|
||||
internal const long NpcTalkMinMs = 3_000;
|
||||
|
||||
/// <summary>After the use, the most wait (a long walk over, a busy client).</summary>
|
||||
internal const long NpcTalkMaxMs = 20_000;
|
||||
|
||||
/// <summary>How long the NPC is looked for before the route goes on without it.</summary>
|
||||
internal const long NpcFindTimeoutMs = 15_000;
|
||||
|
||||
private int _npcTalkIdx = -1; // the NPC point being handled (-1: none)
|
||||
private NavRouteParser? _npcTalkRoute; // on this route
|
||||
private long _npcTalkStart, _npcTalkTriedAt, _npcTalkFiredAt;
|
||||
private bool _npcTalkFired;
|
||||
|
||||
/// <summary>
|
||||
/// Arrived at (or passed) waypoint <paramref name="idx"/>: true when it is an NPC point, which now
|
||||
/// stops and uses its NPC (HandleNpcTalk) instead of advancing.
|
||||
/// </summary>
|
||||
private bool BeginNpcTalk(NavPoint pt, NavRouteParser route, int idx)
|
||||
{
|
||||
if (pt.Type != NavPointType.Npc || string.IsNullOrWhiteSpace(pt.TargetName)) return false;
|
||||
StopMovement();
|
||||
_npcTalkIdx = idx;
|
||||
_npcTalkRoute = route;
|
||||
_npcTalkStart = Now;
|
||||
_npcTalkTriedAt = 0;
|
||||
_npcTalkFiredAt = 0;
|
||||
_npcTalkFired = false;
|
||||
_settings.NavStatusLine = $"Nav: NPC '{pt.TargetName.Trim()}'...";
|
||||
_host.Log($"Nav: at NPC point [{idx}] '{pt.TargetName.Trim()}' - using the NPC before going on");
|
||||
return true;
|
||||
}
|
||||
|
||||
private void HandleNpcTalk(NavPoint pt, NavRouteParser route)
|
||||
{
|
||||
long now = Now;
|
||||
string name = pt.TargetName.Trim();
|
||||
if (!_npcTalkFired)
|
||||
{
|
||||
ClearTurnMotions();
|
||||
if (now - _npcTalkStart < (long)SettleDelayMs) return; // stand still first, as before a portal
|
||||
if (now - _npcTalkStart > NpcFindTimeoutMs)
|
||||
{
|
||||
string msg = $"Nav: the NPC '{name}' at waypoint [{_npcTalkIdx}] wasn't found in {NpcFindTimeoutMs / 1000} s - going on without it.";
|
||||
_host.Log(msg);
|
||||
_host.WriteToChat(msg, 1);
|
||||
EndNpcTalk(route);
|
||||
return;
|
||||
}
|
||||
if (_npcTalkTriedAt == 0 || now - _npcTalkTriedAt >= (long)PortalNpcRetryMs)
|
||||
{
|
||||
_npcTalkTriedAt = now;
|
||||
if (FirePortalNpcUse(pt, "NPC"))
|
||||
{
|
||||
_npcTalkFired = true;
|
||||
_npcTalkFiredAt = now;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Used: AC walks the character over and uses the NPC, which answers. No motions are cleared
|
||||
// now, or the walk over would be cancelled (as for a portal).
|
||||
long since = now - _npcTalkFiredAt;
|
||||
int busy = _host.HasGetBusyState ? _host.GetBusyState() : 0;
|
||||
if ((since >= NpcTalkMinMs && busy <= 0) || since >= NpcTalkMaxMs)
|
||||
{
|
||||
_host.Log($"Nav: NPC '{name}' used {since} ms ago{(busy > 0 ? " (the client still reads busy)" : "")} - going on");
|
||||
EndNpcTalk(route);
|
||||
}
|
||||
}
|
||||
|
||||
private void EndNpcTalk(NavRouteParser route)
|
||||
{
|
||||
_npcTalkIdx = -1;
|
||||
_npcTalkRoute = null;
|
||||
_closestDist = double.MaxValue;
|
||||
Advance(route);
|
||||
}
|
||||
}
|
||||
|
|
@ -25,7 +25,7 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
/// waypoint. A waypoint in a different area (another dungeon, dungeon vs landscape)
|
||||
/// holds nav instead: nothing can path there.
|
||||
/// </summary>
|
||||
internal sealed class NavigationEngine
|
||||
internal sealed partial class NavigationEngine
|
||||
{
|
||||
// ── Motion constants ─────────────────────────────────────────────────────
|
||||
private const uint MotionTurnRight = 0x6500000D;
|
||||
|
|
@ -685,10 +685,14 @@ internal sealed class NavigationEngine
|
|||
if (TeleportAlreadyDone(route, idx)) return;
|
||||
HandlePortalOrRecall(pt, route);
|
||||
return;
|
||||
case NavPointType.Npc when _npcTalkIdx == idx && ReferenceEquals(_npcTalkRoute, route):
|
||||
HandleNpcTalk(pt, route);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Standard coordinate waypoint ─────────────────────────────────────
|
||||
_portalState = PortalState.None;
|
||||
_npcTalkIdx = -1;
|
||||
_inPause = false;
|
||||
_teleportedRoute = null;
|
||||
_firedRoute = null;
|
||||
|
|
@ -743,6 +747,7 @@ internal sealed class NavigationEngine
|
|||
UpdateStatusLine(idx, dist, route, 0.0);
|
||||
// Advance before the jump: the Jumper pauses nav and later restores what it
|
||||
// saw, so jumping first turned a finished Once route back on (re-run from [0]).
|
||||
if (BeginNpcTalk(pt, route, idx)) return; // an NPC point advances once the NPC was used (NavigationEngine.NpcTalk.cs)
|
||||
Advance(route);
|
||||
if (pt.Type == NavPointType.Jump) FireJump(pt, idx);
|
||||
return;
|
||||
|
|
@ -759,6 +764,7 @@ internal sealed class NavigationEngine
|
|||
_host.Log($"Nav: passed [{idx}] dist={dist:F1}yd → advancing");
|
||||
_closestDist = double.MaxValue;
|
||||
UpdateStatusLine(idx, dist, route, 0.0);
|
||||
if (BeginNpcTalk(pt, route, idx)) return; // an NPC point advances once the NPC was used (NavigationEngine.NpcTalk.cs)
|
||||
Advance(route);
|
||||
if (pt.Type == NavPointType.Jump) FireJump(pt, idx);
|
||||
return;
|
||||
|
|
@ -770,6 +776,7 @@ internal sealed class NavigationEngine
|
|||
{
|
||||
_host.Log($"Nav: sweep-pass [{idx}] closest={_closestDist:F1} now={dist:F1}yd → advancing");
|
||||
_closestDist = double.MaxValue;
|
||||
if (BeginNpcTalk(pt, route, idx)) return; // an NPC point advances once the NPC was used (NavigationEngine.NpcTalk.cs)
|
||||
Advance(route);
|
||||
if (pt.Type == NavPointType.Jump) FireJump(pt, idx);
|
||||
return;
|
||||
|
|
@ -1760,9 +1767,9 @@ internal sealed class NavigationEngine
|
|||
/// Returns true iff UseObject was actually called (caller uses this to gate
|
||||
/// retries — a "no match" is retried by the caller until the cache catches up).
|
||||
/// </summary>
|
||||
private bool FirePortalNpcUse(NavPoint pt)
|
||||
private bool FirePortalNpcUse(NavPoint pt, string kind = "portal")
|
||||
{
|
||||
_settings.NavStatusLine = $"Nav: portal '{pt.TargetName}'...";
|
||||
_settings.NavStatusLine = $"Nav: {kind} '{pt.TargetName}'...";
|
||||
if (_objectCache == null || string.IsNullOrWhiteSpace(pt.TargetName) || !_host.HasUseObject)
|
||||
{
|
||||
_host.Log($"Nav: PortalNPC — cache/target/UseObject unavailable for '{pt.TargetName}'");
|
||||
|
|
@ -1920,14 +1927,14 @@ internal sealed class NavigationEngine
|
|||
// A use the engine did not send (UseObject said no) is not a use: false lets the caller ask again.
|
||||
if (!_host.UseFor((uint)bestId, "Nav", $"portal/NPC waypoint '{target}'"))
|
||||
{
|
||||
_host.Log($"Nav: UseObject portal '{target}' (0x{bestId:X8}) was not sent - will retry");
|
||||
_host.Log($"Nav: UseObject {kind} '{target}' (0x{bestId:X8}) was not sent - will retry");
|
||||
return false;
|
||||
}
|
||||
// Publish the resolved object so the marker renderer can draw a ring +
|
||||
// line to the portal's real position (the waypoint coord is a placeholder).
|
||||
_settings.ActivePortalObjId = (uint)bestId;
|
||||
_portalUseDistYd = bestDist;
|
||||
_host.Log($"Nav: UseObject portal '{target}' (dist={bestDist:F1}yd src={fallbackSource}) → 0x{bestId:X8}");
|
||||
_host.Log($"Nav: UseObject {kind} '{target}' (dist={bestDist:F1}yd src={fallbackSource}) → 0x{bestId:X8}");
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -172,6 +172,12 @@ public static unsafe class PluginExports
|
|||
int drawn = plugin.RenderTimedCommands(popped, out want);
|
||||
if (drawn != 1) return drawn;
|
||||
}
|
||||
else if (name.SequenceEqual("window:commandbuttons"u8))
|
||||
{
|
||||
// The Command Buttons window (RynthAiPlugin.CommandButtons.cs): 1 drawn, 0 not ready, -2 failed.
|
||||
int drawn = plugin.RenderCommandButtons(popped, out want);
|
||||
if (drawn != 1) return drawn;
|
||||
}
|
||||
else if (name.SequenceEqual("window:monsterstats"u8))
|
||||
{
|
||||
// The Monster Stats window (RynthAiPlugin.MonsterStats.cs): 1 drawn, 0 not ready, -2 failed.
|
||||
|
|
@ -184,12 +190,24 @@ public static unsafe class PluginExports
|
|||
int drawn = plugin.RenderActiveGear(popped, out want);
|
||||
if (drawn != 1) return drawn;
|
||||
}
|
||||
else if (name.SequenceEqual("window:tradeshop"u8))
|
||||
{
|
||||
// The Trade Shop window (RynthAiPlugin.TradeShop.cs): 1 drawn, 0 not ready, -2 failed.
|
||||
int drawn = plugin.RenderTradeShop(popped, out want);
|
||||
if (drawn != 1) return drawn;
|
||||
}
|
||||
else if (name.SequenceEqual("window:featuresearch"u8))
|
||||
{
|
||||
// The Find a Feature window (RynthAiPlugin.FeatureSearch.cs): 1 drawn, 0 not ready, -2 failed.
|
||||
int drawn = plugin.RenderFeatureSearch(popped, out want);
|
||||
if (drawn != 1) return drawn;
|
||||
}
|
||||
else if (name.SequenceEqual("window:acmaps"u8))
|
||||
{
|
||||
// The ACMAPS Maps window (RynthAiPlugin.AcMaps.cs): 1 drawn, 0 not ready, -2 failed.
|
||||
int drawn = plugin.RenderAcMaps(popped, out want);
|
||||
if (drawn != 1) return drawn;
|
||||
}
|
||||
else if (name.StartsWith("section:"u8))
|
||||
{
|
||||
// Section names are short ASCII ids (Huds/SectionsManifest.cs); anything longer isn't ours.
|
||||
|
|
@ -953,7 +971,7 @@ public static unsafe class PluginExports
|
|||
public static int LootEditRevision()
|
||||
{
|
||||
try { return Runtime.Plugin?.LootEditor.Revision() ?? 0; }
|
||||
catch { return 0; }
|
||||
catch (Exception ex) { LootEditFailed(ex); return 0; }
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetLootEditJson", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
|
|
@ -964,7 +982,7 @@ public static unsafe class PluginExports
|
|||
string? json = Runtime.Plugin?.LootEditor.StateJson();
|
||||
return json == null ? IntPtr.Zero : Utf8Swap(ref _lootStatePtr, json);
|
||||
}
|
||||
catch { return IntPtr.Zero; }
|
||||
catch (Exception ex) { LootEditFailed(ex); return IntPtr.Zero; }
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetLootEditRuleJson", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
|
|
@ -975,7 +993,7 @@ public static unsafe class PluginExports
|
|||
string? json = Runtime.Plugin?.LootEditor.RuleJson(index);
|
||||
return json == null ? IntPtr.Zero : Utf8Swap(ref _lootRulePtr, json);
|
||||
}
|
||||
catch { return IntPtr.Zero; }
|
||||
catch (Exception ex) { LootEditFailed(ex); return IntPtr.Zero; }
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetLootEditVocabJson", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
|
|
@ -986,7 +1004,7 @@ public static unsafe class PluginExports
|
|||
string? json = Runtime.Plugin?.LootEditor.VocabJson();
|
||||
return json == null ? IntPtr.Zero : Utf8Swap(ref _lootVocabPtr, json);
|
||||
}
|
||||
catch { return IntPtr.Zero; }
|
||||
catch (Exception ex) { LootEditFailed(ex); return IntPtr.Zero; }
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSendLootEditCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
|
|
@ -999,7 +1017,13 @@ public static unsafe class PluginExports
|
|||
if (string.IsNullOrEmpty(json)) return;
|
||||
Runtime.Plugin?.LootEditor.Command(json);
|
||||
}
|
||||
catch { }
|
||||
catch (Exception ex) { LootEditFailed(ex); }
|
||||
}
|
||||
|
||||
/// <summary>A Loot Editor call threw: RynthAi says why (an older core's loot library, R-20261124-085015-5215).</summary>
|
||||
private static void LootEditFailed(Exception ex)
|
||||
{
|
||||
try { Runtime.Plugin?.NoteLootEditorFailure(ex); } catch { }
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginAddSelectedWeapon", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
|
|
|
|||
|
|
@ -595,20 +595,16 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
{
|
||||
uint numPortals = BitConverter.ToUInt32(data, bOff);
|
||||
bOff += 4;
|
||||
// Each CBldPortal is variable size; skip conservatively
|
||||
// We got the building model, which is the main thing we need
|
||||
// Portal data is complex (flags + cell lists); skip the rest
|
||||
// for now by breaking out of building loop if we can't parse further
|
||||
// CBldPortal: Flags, OtherCellId, OtherPortalId, NumStabs (ushorts), then NumStabs ushorts,
|
||||
// aligned to 4 (RynthNav.Baker CollisionGeometry.ReadLandBlockInfo reads it the same way).
|
||||
// The old 8-byte skip lost its place after the first building with a stab list (2026-11-26):
|
||||
// B470 kept 1 of its 28 buildings, the world 2,425 of 6,979, and B470's town wall
|
||||
// (0x01002CDE) was never loaded, so melee ran into it.
|
||||
for (uint p = 0; p < numPortals && bOff + 8 <= data.Length; p++)
|
||||
{
|
||||
ushort portalFlags = BitConverter.ToUInt16(data, bOff);
|
||||
bOff += 2;
|
||||
// Skip remaining portal data (OtherCellId + OtherPortalId + StabList)
|
||||
// This is complex; break if we hit something unexpected
|
||||
if (bOff + 6 <= data.Length)
|
||||
{
|
||||
bOff += 6; // Approximate skip for simple portal entries
|
||||
}
|
||||
ushort numStabs = BitConverter.ToUInt16(data, bOff + 6);
|
||||
int size = 8 + numStabs * 2;
|
||||
bOff += (size + 3) & ~3;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -877,7 +873,10 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
Min = bMin,
|
||||
Max = bMax,
|
||||
MeshTriangles = gfxTris.ToArray(),
|
||||
IsDoor = false
|
||||
IsDoor = false,
|
||||
// Triangle hits only: the box round a building's drawing is no wall (doorways,
|
||||
// courtyards); its rooms' walls come from DungeonLOS, which loads every EnvCell.
|
||||
NoAabbFallback = true
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
|
@ -965,7 +964,8 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
Min = new Vector3(minX, minY, minZ),
|
||||
Max = new Vector3(maxX, maxY, maxZ),
|
||||
MeshTriangles = triangles.ToArray(),
|
||||
IsDoor = false
|
||||
IsDoor = false,
|
||||
NoAabbFallback = true
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -86,7 +86,24 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
public static bool IsLinearPathBlocked(Vector3 origin, Vector3 target,
|
||||
List<BoundingVolume> geometry,
|
||||
bool multiRay = false)
|
||||
=> IsLinearPathBlockedCore(origin, target, geometry, multiRay, wantHit: false, out _);
|
||||
|
||||
/// <summary>
|
||||
/// As <see cref="IsLinearPathBlocked(Vector3, Vector3, List{BoundingVolume}, bool)"/> (the same verdict),
|
||||
/// and where it is blocked: <paramref name="hit"/> is the nearest blocking point on the ray that
|
||||
/// was blocked (the centre ray first, then the silhouette rays in order), in the callers' frame.
|
||||
/// Zero when the path is clear. For the Show Line of Sight overlay (2026-11-26).
|
||||
/// </summary>
|
||||
public static bool IsLinearPathBlocked(Vector3 origin, Vector3 target,
|
||||
List<BoundingVolume> geometry,
|
||||
bool multiRay, out Vector3 hit)
|
||||
=> IsLinearPathBlockedCore(origin, target, geometry, multiRay, wantHit: true, out hit);
|
||||
|
||||
private static bool IsLinearPathBlockedCore(Vector3 origin, Vector3 target,
|
||||
List<BoundingVolume> geometry,
|
||||
bool multiRay, bool wantHit, out Vector3 hit)
|
||||
{
|
||||
hit = Vector3.Zero;
|
||||
if (geometry == null || geometry.Count == 0)
|
||||
return false;
|
||||
|
||||
|
|
@ -128,11 +145,11 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
if (near.Count == 0) return false;
|
||||
|
||||
// 5 rays: center, left shoulder, right shoulder, slightly up, slightly down
|
||||
if (IsSingleRayBlocked(origin, target, near)) return true;
|
||||
if (IsSingleRayBlocked(origin - L, target - L, near)) return true;
|
||||
if (IsSingleRayBlocked(origin + L, target + L, near)) return true;
|
||||
if (IsSingleRayBlocked(origin + U, target + U, near)) return true;
|
||||
if (IsSingleRayBlocked(origin - U, target - U, near)) return true;
|
||||
if (IsSingleRayBlocked(origin, target, near, wantHit, out hit)) return true;
|
||||
if (IsSingleRayBlocked(origin - L, target - L, near, wantHit, out hit)) return true;
|
||||
if (IsSingleRayBlocked(origin + L, target + L, near, wantHit, out hit)) return true;
|
||||
if (IsSingleRayBlocked(origin + U, target + U, near, wantHit, out hit)) return true;
|
||||
if (IsSingleRayBlocked(origin - U, target - U, near, wantHit, out hit)) return true;
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
|
|
@ -142,11 +159,18 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
}
|
||||
}
|
||||
|
||||
return IsSingleRayBlocked(origin, target, geometry);
|
||||
return IsSingleRayBlocked(origin, target, geometry, wantHit, out hit);
|
||||
}
|
||||
|
||||
private static bool IsSingleRayBlocked(Vector3 origin, Vector3 target, List<BoundingVolume> geometry)
|
||||
/// <summary>
|
||||
/// One ray. Without <paramref name="wantHit"/> it stops at the first blocking volume (the verdict
|
||||
/// only); with it, it goes on through the candidates for the nearest one, and
|
||||
/// <paramref name="hit"/> is that point (the verdict is the same either way).
|
||||
/// </summary>
|
||||
private static bool IsSingleRayBlocked(Vector3 origin, Vector3 target, List<BoundingVolume> geometry,
|
||||
bool wantHit, out Vector3 hit)
|
||||
{
|
||||
hit = Vector3.Zero;
|
||||
Vector3 delta = target - origin;
|
||||
float distanceToTarget = delta.Length();
|
||||
if (distanceToTarget < 1e-4f) return false;
|
||||
|
|
@ -154,6 +178,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
Vector3 direction = delta / distanceToTarget;
|
||||
SegmentBox(origin, target, out Vector3 lo, out Vector3 hi);
|
||||
|
||||
float nearest = float.MaxValue;
|
||||
foreach (var volume in geometry)
|
||||
{
|
||||
if (volume.IsDoor || OutsideBox(volume, lo, hi)) continue;
|
||||
|
|
@ -164,11 +189,16 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
// Ignore self-intersection at origin and hits within 0.3m of target
|
||||
// (reduced from 1.0m — the old 1m zone was hiding corner walls next to mobs).
|
||||
if (hitDist > 0.5f && hitDist < distanceToTarget - 0.3f)
|
||||
return true;
|
||||
{
|
||||
if (!wantHit) return true;
|
||||
if (hitDist < nearest) nearest = hitDist;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
if (nearest == float.MaxValue) return false;
|
||||
hit = origin + direction * nearest;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -294,6 +324,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
public float Apex; // highest point of the flight above the launch point (m)
|
||||
public float HitAlong; // horizontal distance from the shooter to the hit (m)
|
||||
public float HitZ; // height of the hit above the launch point (m)
|
||||
public Vector3 HitPoint; // the hit itself, in the callers' frame (zero when not blocked by geometry)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -376,6 +407,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
result.Blocked = true;
|
||||
result.HitAlong = (float)Math.Sqrt(hx * hx + hy * hy);
|
||||
result.HitZ = hit.Z - origin.Z;
|
||||
result.HitPoint = hit;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -78,6 +78,11 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
public RaycastEngine.ArcLosResult Arc;
|
||||
public bool TerrainBlocked; // outdoors: the ground rises above the path (a hill between)
|
||||
public float TerrainAlong; // where along the path, in meters from the shooter
|
||||
// Where the path is blocked (2026-11-26, Show Line of Sight): the wall or object the line
|
||||
// or the arc hits, or the ground above the path; global meters (landblock * 192 + local,
|
||||
// Z the height). HasHit false: clear, or blocked with no point (an arc out of reach).
|
||||
public bool HasHit;
|
||||
public Vector3 Hit;
|
||||
}
|
||||
|
||||
// ── Hills (2026-11-22, R-20261122-203611-ff3d) ─────────────────────────────────────────
|
||||
|
|
@ -95,8 +100,13 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
/// its middle (an arc). <paramref name="along"/>: where, in meters from <paramref name="a"/>.
|
||||
/// </summary>
|
||||
public bool TerrainBetween(Vector3 a, Vector3 b, float sag, out float along)
|
||||
=> TerrainBetween(a, b, sag, out along, out _);
|
||||
|
||||
/// <summary>As above; <paramref name="hit"/> is the ground point that rises above the path.</summary>
|
||||
public bool TerrainBetween(Vector3 a, Vector3 b, float sag, out float along, out Vector3 hit)
|
||||
{
|
||||
along = 0f;
|
||||
hit = Vector3.Zero;
|
||||
float dx = b.X - a.X, dy = b.Y - a.Y;
|
||||
float flat = (float)Math.Sqrt(dx * dx + dy * dy);
|
||||
if (flat <= 2 * TerrainEndSkipMeters) return false;
|
||||
|
|
@ -107,11 +117,31 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
float ground = _geoLoader.GetTerrainZWorld(x, y);
|
||||
if (float.IsNaN(ground)) continue;
|
||||
float pathZ = a.Z + (b.Z - a.Z) * f + (sag > 0 ? 4f * sag * f * (1f - f) : 0f);
|
||||
if (ground > pathZ + TerrainClearance) { along = s; return true; }
|
||||
if (ground > pathZ + TerrainClearance) { along = s; hit = new Vector3(x, y, ground); return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fill <see cref="LosDetail.HasHit"/>/<see cref="LosDetail.Hit"/> for a blocked straight line too
|
||||
/// (an arc's hit and the ground point are always given). Off: the straight-line test stops at the first wall
|
||||
/// it finds, as before; on, it looks on for the nearest (Show Line of Sight sets it; the verdict
|
||||
/// is the same either way).
|
||||
/// </summary>
|
||||
public bool ReportHitPoints { get; set; }
|
||||
|
||||
private bool LineTest(Vector3 origin, Vector3 targetPos, List<BoundingVolume> geometry, bool multiRay, ref LosDetail detail)
|
||||
{
|
||||
if (ReportHitPoints)
|
||||
{
|
||||
detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay, out Vector3 hit);
|
||||
if (detail.LineBlocked) { detail.HasHit = true; detail.Hit = hit; }
|
||||
}
|
||||
else
|
||||
detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay);
|
||||
return detail.LineBlocked;
|
||||
}
|
||||
|
||||
private static bool IsMissileArc(AttackType t) =>
|
||||
t == AttackType.BowArc || t == AttackType.CrossbowArc || t == AttackType.AtlatlArc;
|
||||
|
||||
|
|
@ -298,11 +328,13 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
if (!isDungeon)
|
||||
{
|
||||
float sag = missileArc && arc.Valid ? arc.MaxRiseAboveChord : 0f;
|
||||
if (TerrainBetween(missileArc ? launch : origin, targetPos, sag, out float along))
|
||||
if (TerrainBetween(missileArc ? launch : origin, targetPos, sag, out float along, out Vector3 ground))
|
||||
{
|
||||
detail.Checked = true;
|
||||
detail.TerrainBlocked = true;
|
||||
detail.TerrainAlong = along;
|
||||
detail.HasHit = true;
|
||||
detail.Hit = ground;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -321,8 +353,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
// Walls first (cheap, and most blocked targets stop here). In dungeons use
|
||||
// multi-ray: 5 rays covering the player silhouette catch thin corner
|
||||
// geometry that a single center ray slips through.
|
||||
detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
|
||||
if (detail.LineBlocked)
|
||||
if (LineTest(origin, targetPos, geometry, isDungeon, ref detail))
|
||||
return true;
|
||||
|
||||
// A short, flat shot is the straight line just tested.
|
||||
|
|
@ -334,8 +365,14 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
}
|
||||
|
||||
detail.ArcChecked = true;
|
||||
return RaycastEngine.IsBallisticArcBlocked(launch, targetPos, in arc,
|
||||
bool arcBlocked = RaycastEngine.IsBallisticArcBlocked(launch, targetPos, in arc,
|
||||
MissileArcClearance, geometry, out detail.Arc);
|
||||
if (arcBlocked && !detail.Arc.OutOfReach)
|
||||
{
|
||||
detail.HasHit = true;
|
||||
detail.Hit = detail.Arc.HitPoint;
|
||||
}
|
||||
return arcBlocked;
|
||||
}
|
||||
|
||||
// In dungeons use multi-ray checks — 5 rays covering the player silhouette
|
||||
|
|
@ -347,8 +384,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
case AttackType.CrossbowArc:
|
||||
case AttackType.AtlatlArc:
|
||||
case AttackType.MagicArc:
|
||||
detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
|
||||
return detail.LineBlocked;
|
||||
return LineTest(origin, targetPos, geometry, isDungeon, ref detail);
|
||||
|
||||
// Melee: nothing flies, so the only question is whether a wall stands
|
||||
// between the two bodies: one ray, chest to chest. The five silhouette rays
|
||||
|
|
@ -359,8 +395,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
|||
// single ray 88, and both block every one of 199 walls, also with the
|
||||
// player and the monster pressed against it.
|
||||
case AttackType.Melee:
|
||||
detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: false);
|
||||
return detail.LineBlocked;
|
||||
return LineTest(origin, targetPos, geometry, false, ref detail);
|
||||
|
||||
default:
|
||||
return false;
|
||||
|
|
|
|||
|
|
@ -69,6 +69,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra fellow — fellowship diagnostics and queries");
|
||||
ChatLine("[RynthAi] /ra help — show this list");
|
||||
ChatLine("[RynthAi] /ra find [words] — Find a Feature: search every RynthSuite feature, where it is and its command");
|
||||
ChatLine("[RynthAi] /ra acmaps [folder <path>|scan|announce on|off] — ACMAPS Maps: your own ACMAPS map of this dungeon");
|
||||
ChatLine("[RynthAi] /ra version — RynthAi version and build date, and the engine it runs on");
|
||||
ChatLine("[RynthAi] /ra server - which server RynthCore says this is, its overrides, and the server plugin's settings");
|
||||
ChatLine("[RynthAi] /ra power <0-100|auto> — set attack power (auto = recklessness-aware)");
|
||||
|
|
@ -101,6 +102,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra use[i|l][p|pi|lp] <name> [on <name2>] — use item (i=inv, l=land, p=partial)");
|
||||
ChatLine("[RynthAi] /ra raycast — raycast system status");
|
||||
ChatLine("[RynthAi] /ra lostest [mode] — LoS test (mode: linear|bow|crossbow|atlatl|magic)");
|
||||
ChatLine("[RynthAi] /ra losline [on|off] — Show Line of Sight: a line to the combat target, green = clear, red = blocked (toggle)");
|
||||
ChatLine("[RynthAi] /ra landtest — terrain heightmap info for player's landblock");
|
||||
ChatLine("[RynthAi] /ra rayland — landscape raycast test (down + 4 cardinals)");
|
||||
ChatLine("[RynthAi] /ra buildinfo — nearby geometry info");
|
||||
|
|
@ -120,6 +122,8 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra autoconfirm [status|on|off|<50-100>] — Yes to the craft-chance prompt at that % or better (Mini Remote > Crafting)");
|
||||
ChatLine("[RynthAi] /ra kits [status|make [N]|stop|floor <0-100>|show] — make Plentiful Healing Kits from their ingredients, macro off (Mini Remote > Crafting > Kits)");
|
||||
ChatLine("[RynthAi] /ra kits auto [status|on|off|below N|upto M] — Make kits when low: with the macro on and nothing around, make kits when fewer than N are carried");
|
||||
ChatLine("[RynthAi] /ra ammo [status|make|stop|show] — arrows, quarrels or darts carried for the launcher in hand; make up to M now, at a safe moment (Mini Remote > Crafting > Ammo)");
|
||||
ChatLine("[RynthAi] /ra ammo auto [status|on|off|below N|upto M] — Make ammo when low: with the macro on and nothing around, make ammo between fights when fewer than N are carried");
|
||||
ChatLine("[RynthAi] /ra petelement [status|any|fire|cold|acid|lightning|nether|slash|pierce|bludgeon] — the element combat pets are summoned for (Mini Remote > Pets)");
|
||||
ChatLine("[RynthAi] /ra offhand [auto|shield|weapon|none] [rule] — the off hand (shield / dual wield), global or for a Monsters rule; dual on|off");
|
||||
ChatLine("[RynthAi] /ra dunnav <NS> <EW> — navigate to NS/EW coords through dungeon (no nav file needed)");
|
||||
|
|
@ -151,6 +155,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra combat — dump combat state machine snapshot");
|
||||
ChatLine("[RynthAi] /ra mstats [monster] — its evades, resists, hits, spells and kills this session (list | reset | show | hide)");
|
||||
ChatLine("[RynthAi] /ra timed [server|all] list | add <seconds> <command> | remove|on|off|run <n> | show — commands sent every N seconds (window: the RynthAi options menu > Timed commands)");
|
||||
ChatLine("[RynthAi] /ra buttons [server|all] list | add <label> = <command> | remove|press <n> | show|edit — buttons that each send one chat line (window: the RynthAi options menu > Command buttons)");
|
||||
ChatLine("[RynthAi] /ra gear — which worn items have their magic on, mana and time left (check | list | hide; the Active Gear window)");
|
||||
ChatLine("[RynthAi] /ra why — one-glance diagnosis of why the bot is idle/attacking");
|
||||
ChatLine("[RynthAi] /ra start | stop — start/stop the macro from chat");
|
||||
|
|
@ -383,6 +388,36 @@ public sealed partial class RynthAiPlugin
|
|||
$"checks {_combatManager.RaycastCheckCount}, blocked {_combatManager.RaycastBlockCount}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /ra losline [on|off]: Show Line of Sight (ShowLosLine), the line from the character to the combat
|
||||
/// target in the scan's raycast colours. No argument toggles; every reply says the state now.
|
||||
/// </summary>
|
||||
private void HandleLosLineCommand(string[] parts)
|
||||
{
|
||||
var dash = _dashboard;
|
||||
var s = dash?.Settings;
|
||||
if (s == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
|
||||
string arg = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "";
|
||||
bool? set = arg switch
|
||||
{
|
||||
"" or "toggle" => !s.ShowLosLine,
|
||||
"on" or "1" or "true" => true,
|
||||
"off" or "0" or "false" => false,
|
||||
_ => null,
|
||||
};
|
||||
if (set is not bool on)
|
||||
{
|
||||
ReplyFail($"[RynthAi] Show Line of Sight: unknown '{arg}'. Usage: /ra losline [on|off] (now {(s.ShowLosLine ? "on" : "off")}).");
|
||||
return;
|
||||
}
|
||||
s.ShowLosLine = on;
|
||||
dash!.SaveSettings();
|
||||
string note = !on ? "" : !s.EnableRaycasting ? " Enable Raycasting is off, so every line is dashed (not tested)."
|
||||
: _combatManager?.RaycastInitialized != true ? " The raycast is still loading: lines are dashed until it is ready." : "";
|
||||
ReplyOk(on ? "[RynthAi] Show Line of Sight: on (green = the raycast says clear, red = blocked, yellow marker = where it hit; dashed = not tested)." + note
|
||||
: "[RynthAi] Show Line of Sight: off.");
|
||||
}
|
||||
|
||||
private void HandleLosTestCommand(string[] parts)
|
||||
{
|
||||
if (_raycast == null || !_raycast.IsInitialized)
|
||||
|
|
|
|||
366
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.AcMaps.cs
Normal file
366
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.AcMaps.cs
Normal file
|
|
@ -0,0 +1,366 @@
|
|||
// RynthAiPlugin.AcMaps.cs — the ACMAPS Maps window and /ra acmaps (2026-11-26, a player's request:
|
||||
// "Is there a way to display these ACMAPS maps in game? Like GoArrow used to?").
|
||||
//
|
||||
// ACMAPS' hand-drawn dungeon maps (rooms, quest items, levers, portals) are the player's own: RynthSuite
|
||||
// doesn't ship them. The player points the window at their map pack (Folder > Browse..., or the default
|
||||
// <RynthSuite>\RynthAi\ACMaps); AcMaps/AcMapIndex.cs reads it (images named by landblock, dungeons.txt,
|
||||
// a GoArrow locations file). In a dungeon with a map, the window shows it, and the player's arrow once
|
||||
// the floor is placed (AcMaps/AcMapCalibration.cs: "Place me here", saved per map in acmaps.json).
|
||||
//
|
||||
// Ways in, buttons first: the RynthAi window's Map button, right-click; the ⋯ menu > ACMAPS maps; and
|
||||
// /ra acmaps. The window is a plugin window (API v89) declared without a bar button (the bar is full).
|
||||
// The engine's Dungeon Map is RynthCore's panel and stays as it is (the layer rule: plugins own their
|
||||
// screens), so this is a window of RynthAi's own beside it.
|
||||
//
|
||||
// Optional (off by default): a chat line as you enter a dungeon your folder has a map for.
|
||||
//
|
||||
// Threads: the commands and the chat line on the pump thread; the window on the render thread; the
|
||||
// folder scan, the image decode and the settings write on threads of their own. The settings object is
|
||||
// locked for every change and the write.
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Plugin.RynthAi.AcMaps;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public sealed partial class RynthAiPlugin : IAcMapsHost
|
||||
{
|
||||
/// <summary>The window's title (its panel key) and surface (Huds/SectionsManifest.cs).</summary>
|
||||
internal const string AcMapsTitle = "ACMAPS Maps", AcMapsSurface = "window:acmaps";
|
||||
|
||||
internal const string AcMapsUsage = "Usage: /ra acmaps [folder <path> | scan | announce on|off | hide]";
|
||||
|
||||
/// <summary>The window's textures go after it hasn't been drawn this long (they're remade when it shows).</summary>
|
||||
private const long AcMapsIdleReleaseMs = 20000;
|
||||
|
||||
private AcMapSettings? _acSettings; // made on first use, then locked for changes
|
||||
private readonly object _acSettingsGate = new();
|
||||
private volatile AcMapIndex _acIndex = AcMapIndex.Empty;
|
||||
private int _acScanning; // 1 while a scan runs
|
||||
private int _acScanGeneration;
|
||||
private bool _acScannedOnce;
|
||||
private int _acSaveQueued;
|
||||
private AcMapWindow? _acWindow; // render thread
|
||||
private long _acDrawnMs = long.MinValue / 2; // render thread writes, render reads
|
||||
private int _acFailures; // render thread
|
||||
private ushort _acLastLandblock; // pump thread (the chat line)
|
||||
|
||||
/// <summary>The window goes in the manifest on an engine with plugin windows (v89).</summary>
|
||||
private bool AcMapsWindowWanted => Host.HasUiTheme && Host.HasSetPanelOpen;
|
||||
|
||||
/// <summary>Where the settings are written; tests point it at a scratch file.</summary>
|
||||
internal string AcMapsSettingsPath { get; set; } = AcMapSettings.DefaultPath;
|
||||
|
||||
// ── IAcMapsHost (the window) ─────────────────────────────────────────
|
||||
|
||||
AcMapIndex IAcMapsHost.Index => _acIndex;
|
||||
bool IAcMapsHost.Scanning => Volatile.Read(ref _acScanning) != 0;
|
||||
AcMapSettings IAcMapsHost.Settings => AcSettings;
|
||||
IntPtr IAcMapsHost.Device => Host.D3DDevice;
|
||||
void IAcMapsHost.SetFolder(string folder) => SetAcMapsFolder(folder);
|
||||
void IAcMapsHost.Rescan() => StartAcScan();
|
||||
void IAcMapsHost.SetAnnounce(bool on) => SetAcMapsAnnounce(on);
|
||||
void IAcMapsHost.SaveSettings() => SaveAcSettings();
|
||||
|
||||
bool IAcMapsHost.TryPose(out uint cell, out float x, out float y, out float z, out float heading)
|
||||
{
|
||||
cell = 0; x = y = z = heading = 0;
|
||||
if (!Host.HasGetPlayerPose || !Host.TryGetPlayerPose(out cell, out x, out y, out z, out float qw, out _, out _, out float qz))
|
||||
return false;
|
||||
double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
|
||||
heading = (float)((-yaw % 360.0 + 720.0) % 360.0);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The settings, read from acmaps.json the first time. Any thread.</summary>
|
||||
internal AcMapSettings AcSettings
|
||||
{
|
||||
get
|
||||
{
|
||||
AcMapSettings? s = Volatile.Read(ref _acSettings);
|
||||
if (s != null) return s;
|
||||
lock (_acSettingsGate)
|
||||
{
|
||||
_acSettings ??= AcMapSettings.Load(AcMapsSettingsPath);
|
||||
return _acSettings;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The current index (tests).</summary>
|
||||
internal AcMapIndex AcMapsIndexForTests => _acIndex;
|
||||
|
||||
// ── Folder, scan, save ───────────────────────────────────────────────
|
||||
|
||||
/// <summary>Reads the folder on a thread of its own; the window shows "Reading..." meanwhile. Any thread.</summary>
|
||||
internal Task StartAcScan()
|
||||
{
|
||||
_acScannedOnce = true;
|
||||
string folder;
|
||||
AcMapSettings s = AcSettings;
|
||||
lock (s) folder = s.FolderOrDefault;
|
||||
int gen = Interlocked.Increment(ref _acScanGeneration);
|
||||
Interlocked.Exchange(ref _acScanning, 1);
|
||||
return Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
// The default folder is made, so the player has somewhere to copy a pack to.
|
||||
if (string.Equals(folder, AcMapSettings.DefaultFolder, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
try { System.IO.Directory.CreateDirectory(folder); } catch { }
|
||||
}
|
||||
AcMapIndex index = AcMapIndex.Scan(folder);
|
||||
if (gen == Volatile.Read(ref _acScanGeneration)) _acIndex = index;
|
||||
}
|
||||
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "ACMAPS scan"); }
|
||||
finally
|
||||
{
|
||||
if (gen == Volatile.Read(ref _acScanGeneration)) Interlocked.Exchange(ref _acScanning, 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
internal Task SetAcMapsFolder(string folder)
|
||||
{
|
||||
AcMapSettings s = AcSettings;
|
||||
lock (s) s.Folder = string.Equals(folder, AcMapSettings.DefaultFolder, StringComparison.OrdinalIgnoreCase) ? string.Empty : folder;
|
||||
SaveAcSettings();
|
||||
return StartAcScan();
|
||||
}
|
||||
|
||||
internal void SetAcMapsAnnounce(bool on)
|
||||
{
|
||||
AcMapSettings s = AcSettings;
|
||||
lock (s) s.Announce = on;
|
||||
SaveAcSettings();
|
||||
if (on && !_acScannedOnce) StartAcScan();
|
||||
}
|
||||
|
||||
/// <summary>Writes acmaps.json soon, off the calling thread; several changes in a row make one write.</summary>
|
||||
internal void SaveAcSettings()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _acSaveQueued, 1) != 0) return;
|
||||
Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(300).ConfigureAwait(false);
|
||||
Interlocked.Exchange(ref _acSaveQueued, 0);
|
||||
AcMapSettings s = AcSettings;
|
||||
string json;
|
||||
lock (s) json = s.ToJson();
|
||||
string error = AcMapSettings.Save(AcMapsSettingsPath, json);
|
||||
if (error.Length > 0) Host.Log("[RynthAi] ACMAPS: couldn't save " + AcMapsSettingsPath + ": " + error);
|
||||
});
|
||||
}
|
||||
|
||||
// ── /ra acmaps ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// "/ra acmaps" opens the window and says what's there; "folder <path>" sets the maps folder and reads
|
||||
/// it; "scan" reads it again; "announce on|off" the chat line; "hide" closes the window. Every form replies.
|
||||
/// Pump thread.
|
||||
/// </summary>
|
||||
private void HandleAcMapsCommand(string[] parts)
|
||||
{
|
||||
string verb = parts.Length > 2 ? parts[2].Trim().ToLowerInvariant() : string.Empty;
|
||||
string rest = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3).Trim().Trim('"') : string.Empty;
|
||||
AcMapSettings s = AcSettings;
|
||||
switch (verb)
|
||||
{
|
||||
case "":
|
||||
case "show":
|
||||
case "open":
|
||||
{
|
||||
if (!_acScannedOnce) StartAcScan();
|
||||
int open = OpenAcMapsWindow(RynthPanelOpen.Open);
|
||||
ReplyOk("[RynthAi] ACMAPS maps: " + AcMapsHereLine() + AcWindowNote(open));
|
||||
return;
|
||||
}
|
||||
case "hide":
|
||||
case "close":
|
||||
{
|
||||
if (!Host.HasSetPanelOpen) { ReplyFail("[RynthAi] ACMAPS maps: this RynthCore has no plugin windows (plugin API 89+)."); return; }
|
||||
int open = Host.SetPanelOpen(AcMapsTitle, RynthPanelOpen.Close);
|
||||
if (open < 0) ReplyFail("[RynthAi] The ACMAPS Maps window isn't there yet (RynthCore adds it a few seconds after login).");
|
||||
else ReplyOk("[RynthAi] ACMAPS Maps window closed.");
|
||||
return;
|
||||
}
|
||||
case "folder":
|
||||
{
|
||||
if (rest.Length == 0)
|
||||
{
|
||||
string f;
|
||||
lock (s) f = s.FolderOrDefault;
|
||||
ReplyOk("[RynthAi] ACMAPS maps folder: " + f + " (/ra acmaps folder <path> to change it).");
|
||||
return;
|
||||
}
|
||||
if (!System.IO.Path.IsPathRooted(rest))
|
||||
{
|
||||
ReplyFail($"[RynthAi] ACMAPS maps: '{rest}' isn't a full folder path (like C:\\ACMaps). {AcMapsUsage}");
|
||||
return;
|
||||
}
|
||||
if (!System.IO.Directory.Exists(rest))
|
||||
{
|
||||
ReplyFail($"[RynthAi] ACMAPS maps: there's no folder {rest}. {AcMapsUsage}");
|
||||
return;
|
||||
}
|
||||
SetAcMapsFolder(rest);
|
||||
ReplyOk("[RynthAi] ACMAPS maps folder set to " + rest + ": reading it (the ACMAPS Maps window shows the count).");
|
||||
return;
|
||||
}
|
||||
case "scan":
|
||||
case "rescan":
|
||||
{
|
||||
string f;
|
||||
lock (s) f = s.FolderOrDefault;
|
||||
StartAcScan();
|
||||
ReplyOk("[RynthAi] ACMAPS maps: reading " + f + " again.");
|
||||
return;
|
||||
}
|
||||
case "announce":
|
||||
{
|
||||
bool? on = rest switch { "on" or "true" or "1" => true, "off" or "false" or "0" => false, "" => null, _ => null };
|
||||
if (on == null && rest.Length > 0) { ReplyFail($"[RynthAi] ACMAPS maps: announce takes on or off, not '{rest}'. {AcMapsUsage}"); return; }
|
||||
bool now;
|
||||
lock (s) now = on ?? !s.Announce;
|
||||
SetAcMapsAnnounce(now);
|
||||
ReplyOk(now ? "[RynthAi] ACMAPS maps: a line in chat when a dungeon has a map: ON."
|
||||
: "[RynthAi] ACMAPS maps: the chat line when a dungeon has a map: OFF.");
|
||||
return;
|
||||
}
|
||||
case "help":
|
||||
case "?":
|
||||
ChatLine("[RynthAi] /ra acmaps — opens the ACMAPS Maps window: your own ACMAPS map of the dungeon you're in (also: RynthAi window > Map, right-click)");
|
||||
ChatLine("[RynthAi] /ra acmaps folder <path> | scan | announce on|off | hide — the maps folder, read it again, the chat line, close the window");
|
||||
return;
|
||||
default:
|
||||
ReplyFail($"[RynthAi] ACMAPS maps: unknown option '{verb}'. {AcMapsUsage}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"123 maps in C:\..; this dungeon (Mosswart Maze, 02CA) has one" for the command's reply.</summary>
|
||||
private string AcMapsHereLine()
|
||||
{
|
||||
AcMapIndex index = _acIndex;
|
||||
string folder;
|
||||
AcMapSettings s = AcSettings;
|
||||
lock (s) folder = s.FolderOrDefault;
|
||||
if (Volatile.Read(ref _acScanning) != 0 && index.Maps.Count == 0) return "reading " + folder + "...";
|
||||
string count = index.Maps.Count == 1 ? "1 map" : $"{index.Maps.Count} maps";
|
||||
string line = $"{count} in {folder}";
|
||||
ushort lb = CurrentDungeonLandblock();
|
||||
if (lb != 0)
|
||||
{
|
||||
string name = index.NameOf(lb);
|
||||
string which = name.Length > 0 ? $"{name}, {lb:X4}" : lb.ToString("X4");
|
||||
line += index.Has(lb) ? $"; this dungeon ({which}) has one" : $"; none for this dungeon ({which})";
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
private string AcWindowNote(int open) =>
|
||||
open == -2 ? " (the window needs RynthCore with plugin windows)"
|
||||
: open < 0 ? " (the window isn't there yet: RynthCore adds it a few seconds after login)"
|
||||
: " (ACMAPS Maps open).";
|
||||
|
||||
/// <summary>The window opened, closed or toggled: 1 open, 0 closed, -1 not there yet, -2 no plugin windows. Any thread.</summary>
|
||||
private int OpenAcMapsWindow(RynthPanelOpen mode)
|
||||
{
|
||||
if (!Host.HasSetPanelOpen) return -2;
|
||||
int r = Host.SetPanelOpen(AcMapsTitle, mode);
|
||||
return r < 0 ? -1 : r;
|
||||
}
|
||||
|
||||
/// <summary>The dashboard's Map (right-click) and ⋯ > ACMAPS maps: the window toggled. Tick.</summary>
|
||||
internal void ToggleAcMapsWindow()
|
||||
{
|
||||
if (!_acScannedOnce) StartAcScan();
|
||||
int r = OpenAcMapsWindow(RynthPanelOpen.Toggle);
|
||||
if (r == -1) ChatLine("[RynthAi] ACMAPS Maps isn't there yet (RynthCore adds it a few seconds after login). Try again in a moment, or type /ra acmaps.");
|
||||
else if (r == -2) ChatLine("[RynthAi] ACMAPS Maps needs a RynthCore with plugin windows (plugin API 89+).");
|
||||
}
|
||||
|
||||
/// <summary>The landblock of the dungeon you're in (0 outdoors or before login).</summary>
|
||||
private ushort CurrentDungeonLandblock()
|
||||
{
|
||||
if (!Host.HasGetPlayerPose || !Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _)) return 0;
|
||||
return (cell & 0xFFFF) >= 0x100 ? (ushort)(cell >> 16) : (ushort)0;
|
||||
}
|
||||
|
||||
// ── The chat line (pump thread) ──────────────────────────────────────
|
||||
|
||||
/// <summary>With Announce on: a line as you enter a dungeon that has a map. Pump thread, every tick (cheap).</summary>
|
||||
private void TickAcMaps()
|
||||
{
|
||||
if (!_loginComplete) return;
|
||||
AcMapSettings? s = Volatile.Read(ref _acSettings);
|
||||
if (s == null)
|
||||
{
|
||||
// Read the settings once after login (a small file), so Announce works without the window.
|
||||
s = AcSettings;
|
||||
}
|
||||
bool announce;
|
||||
lock (s) announce = s.Announce;
|
||||
if (!announce) { _acLastLandblock = 0; return; }
|
||||
if (!_acScannedOnce) StartAcScan();
|
||||
ushort lb = CurrentDungeonLandblock();
|
||||
if (lb == _acLastLandblock) return;
|
||||
AcMapIndex index = _acIndex;
|
||||
if (lb != 0 && Volatile.Read(ref _acScanning) != 0 && index.Maps.Count == 0) return; // ask again when the scan is done
|
||||
_acLastLandblock = lb;
|
||||
string? line = AcAnnounceLine(index, lb);
|
||||
if (line != null) Host.WriteToChat(line, CommandReply.OkColor);
|
||||
}
|
||||
|
||||
/// <summary>The chat line for entering <paramref name="landblock"/>, or null (outdoors, or no map). Pure.</summary>
|
||||
internal static string? AcAnnounceLine(AcMapIndex index, ushort landblock)
|
||||
{
|
||||
if (landblock == 0 || !index.Has(landblock)) return null;
|
||||
string name = index.NameOf(landblock);
|
||||
if (name.Length == 0) name = index.ForLandblock(landblock)[0].Label;
|
||||
return $"[RynthAi] ACMAPS has a map of {name}: RynthAi window > Map (right-click), or /ra acmaps.";
|
||||
}
|
||||
|
||||
// ── Window (render thread) ───────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// RynthPluginRenderEmbed "window:acmaps": the ACMAPS Maps window body, docked or popped out.
|
||||
/// 1 drawn, 0 not ready, -2 failed (three draws in a row threw).
|
||||
/// </summary>
|
||||
internal int RenderAcMaps(bool popped, out Vector2 want)
|
||||
{
|
||||
want = default;
|
||||
if (!_initialized || Host.ImGuiContext == IntPtr.Zero) return 0;
|
||||
_acDrawnMs = Environment.TickCount64;
|
||||
if (!_acScannedOnce) StartAcScan();
|
||||
IntPtr previous = ImGui.GetCurrentContext();
|
||||
ImGui.SetCurrentContext(EmbedContext());
|
||||
try
|
||||
{
|
||||
_acWindow ??= new AcMapWindow(this);
|
||||
want = _acWindow.Draw();
|
||||
_acFailures = 0;
|
||||
return 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Exception(LogCat.UI, ex, "RenderAcMaps");
|
||||
return ++_acFailures >= 3 ? -2 : 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGui.SetCurrentContext(previous);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Render thread, every frame: a closed window's map textures go after a while.</summary>
|
||||
private void ReleaseIdleAcMapTextures()
|
||||
{
|
||||
if (_acWindow != null && Environment.TickCount64 - _acDrawnMs > AcMapsIdleReleaseMs) _acWindow.ReleaseTextures();
|
||||
}
|
||||
}
|
||||
413
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Ammo.cs
Normal file
413
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Ammo.cs
Normal file
|
|
@ -0,0 +1,413 @@
|
|||
using System;
|
||||
using System.Globalization;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.MiniRemote;
|
||||
using RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
// Make ammo when low (a players' request, 2026-11-23: "set an amount of arrows and if we fall below it
|
||||
// does it between combat"; MakeAmmoWhenLow, off by default; /ra ammo ...). The empty-slot path
|
||||
// (MissileCraftingManager) waited for the quiver to run dry, which is mid-fight, and its first combine
|
||||
// needs Peace mode. This tops the ammo up between fights instead, on the Make kits when low rules and
|
||||
// their checks (RynthAiPlugin.Kits.cs: KitBusyWhy, KitVitalsWhy, NearestMonsterYards, the hit and pose
|
||||
// tracking, the 35 yd / Monster Range radius), with a KitAuto of its own (MissileCraftingManager.Auto):
|
||||
// - with the macro on, fewer than MakeAmmoBelow arrows, quarrels or darts for the launcher in hand
|
||||
// (quiver and pack), nothing else going (buffing or healing, a fight, looting, salvaging, a vendor,
|
||||
// a portal, a launcher swap, Boost Loot's wait for a kill's corpse, a kit run), vitals over their
|
||||
// lines, no monster within the radius, no hit for 20 s: peace mode (given up after 6 s), stand
|
||||
// still a second, then MissileCraftingManager.StartTopOff makes up to MakeAmmoUpTo;
|
||||
// - a monster within the radius, a hit, a heal line, buffing, a fight, a launcher swap, moving or
|
||||
// leaving peace mode stops it at once (CheckAutoAmmoDanger, ahead of every hold); 60 s before the
|
||||
// next try after a stop for danger, 10 min after one that made nothing or the player's Stop;
|
||||
// - while it gets ready or goes, the rest of the tick waits (TickAutoAmmo, after the kits' hold).
|
||||
// Mid-fight it never asks for Peace mode: the empty-slot path is unchanged and still the only one
|
||||
// that crafts in a fight (one combine, with nothing at all to shoot).
|
||||
// Make ammo now (/ra ammo make, the Mini Remote's button): the same, up to MakeAmmoUpTo, with the
|
||||
// macro on or off, waiting up to a minute for a safe moment.
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
internal const string AmmoUsage = "Usage: /ra ammo [status | make | stop | show | auto [on|off|status|below N|upto M]]";
|
||||
internal const string AmmoAutoUsage = "Usage: /ra ammo auto [status | on | off | below <1-5000> | upto <1-10000>]";
|
||||
/// <summary>Make ammo now waits this long for a safe moment, then gives up (said in chat).</summary>
|
||||
internal const long AmmoMakeNowWaitMs = 60_000;
|
||||
/// <summary>Moving further than this from where a top-off started stops it (as a kit run).</summary>
|
||||
private const float AmmoMoveLimit = 1.5f;
|
||||
|
||||
private bool _ammoAutoWasOn;
|
||||
private long _ammoRunStartedAt = long.MinValue / 2;
|
||||
private bool _ammoStartPoseKnown;
|
||||
private uint _ammoStartCell;
|
||||
private float _ammoStartX, _ammoStartY, _ammoStartZ;
|
||||
|
||||
private static int AmmoBelow(LegacyUiSettings s) => Math.Clamp(s.MakeAmmoBelow, 1, MissileCraftingManager.MaxAmmoBelow);
|
||||
/// <summary>The top-off's target: Make up to, never under the start line.</summary>
|
||||
private static int AmmoUpTo(LegacyUiSettings s) => Math.Max(Math.Clamp(s.MakeAmmoUpTo, 1, MissileCraftingManager.MaxAmmoUpTo), AmmoBelow(s));
|
||||
|
||||
private void AmmoChat(string line)
|
||||
{
|
||||
try { if (Host.HasWriteToChat) Host.WriteToChat(line, 1); } catch { }
|
||||
}
|
||||
|
||||
/// <summary>Login: the top-off's lines, clock and the panels' view of it.</summary>
|
||||
private void WireAmmoTopOff(MissileCraftingManager cm)
|
||||
{
|
||||
cm.Say = AmmoChat;
|
||||
cm.Auto.Say = AmmoChat;
|
||||
cm.Auto.NowMs = KitNow;
|
||||
_ammoAutoWasOn = false;
|
||||
}
|
||||
|
||||
// ── /ra ammo ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>/ra ammo: status (the default), make, stop, show (the Ammo tab), auto ....</summary>
|
||||
private void HandleAmmoCommand(string[] parts)
|
||||
{
|
||||
string verb = parts.Length > 2 ? parts[2].Trim().ToLowerInvariant() : "status";
|
||||
switch (verb)
|
||||
{
|
||||
case "auto":
|
||||
HandleAmmoAutoCommand(parts);
|
||||
return;
|
||||
case "show":
|
||||
{
|
||||
var remote = _miniRemote;
|
||||
if (remote == null) { ReplyFail("[RynthAi] Make ammo: the Mini Remote isn't available yet (log in first)."); return; }
|
||||
remote.Crafting.SelectAmmoTab();
|
||||
string? reply = remote.MiniRemoteTabCommand?.Invoke(MiniRemoteTabs.Crafting, "show");
|
||||
if (reply == null) ReplyFail("[RynthAi] Make ammo: the Mini Remote isn't available yet.");
|
||||
else ReplyOk("[RynthAi] Make ammo: " + reply);
|
||||
return;
|
||||
}
|
||||
case "status":
|
||||
case "make":
|
||||
case "stop":
|
||||
break;
|
||||
default:
|
||||
ReplyFail($"[RynthAi] Make ammo: unknown option '{parts[2]}'. {AmmoUsage}");
|
||||
return;
|
||||
}
|
||||
|
||||
var s = _dashboard?.Settings;
|
||||
var cm = _missileCraftingManager;
|
||||
if (s == null || cm == null) { ReplyFail("[RynthAi] Make ammo: not ready yet (log in first)."); return; }
|
||||
switch (verb)
|
||||
{
|
||||
case "status":
|
||||
ChatLine("[RynthAi] Make ammo: " + AmmoLookLine(cm.LookTopOff(forceRefresh: true)));
|
||||
ChatLine(AmmoAutoStatusLine());
|
||||
break;
|
||||
case "make":
|
||||
{
|
||||
string line = AskMakeAmmoNow(s, cm, out bool ok);
|
||||
if (ok) ReplyOk(line); else ReplyFail(line);
|
||||
break;
|
||||
}
|
||||
case "stop":
|
||||
if (cm.TopOffRunning) { cm.StopTopOff("stopped by you", KitStopKind.User); Reply.Answered(); } // the summary line answers
|
||||
else if (cm.MakeNowUntilMs > 0) { cm.MakeNowUntilMs = 0; ReplyOk("[RynthAi] Make ammo now: cancelled."); }
|
||||
else ReplyOk("[RynthAi] Make ammo: nothing is running.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the pack holds and makes for the launcher in hand, one line.</summary>
|
||||
private static string AmmoLookLine(MissileCraftingManager.AmmoLook look)
|
||||
{
|
||||
if (!look.Launcher) return look.PackWhy + ".";
|
||||
string head = $"{look.CarriedText} carried for the launcher in hand (quiver and pack)";
|
||||
if (look.Recipe == null || look.Combines <= 0) return $"{head}; none can be made now: {look.PackWhy}.";
|
||||
int yield = AmmoRecipes.EstimatedYield(look.Recipe);
|
||||
string combines = look.Combines >= 1000 ? "many combines" : look.Combines == 1 ? "1 combine" : $"{look.Combines} combines";
|
||||
return $"{head}; the pack makes {look.Recipe.OutputName}, about {yield} a combine ({combines} of bundles).";
|
||||
}
|
||||
|
||||
/// <summary>Make ammo now: checks, then asks the next safe moment for a top-off up to Make up to.</summary>
|
||||
private string AskMakeAmmoNow(LegacyUiSettings s, MissileCraftingManager cm, out bool ok)
|
||||
{
|
||||
ok = false;
|
||||
if (!s.EnableMissileCrafting) return "[RynthAi] Make ammo now: Enable Missile Crafting is off (Settings > Combat).";
|
||||
if (cm.TopOffRunning) { ok = true; return $"[RynthAi] Make ammo now: already making ({cm.TopOffMade}/{cm.TopOffPlanned} combines). /ra ammo stop to stop."; }
|
||||
if (cm.IsCrafting) return "[RynthAi] Make ammo now: ammo crafting is already under way (an empty quiver).";
|
||||
var look = cm.LookTopOff(forceRefresh: true);
|
||||
if (!look.Launcher) return $"[RynthAi] Make ammo now: {look.PackWhy}.";
|
||||
if (look.Recipe == null || look.Combines <= 0) return $"[RynthAi] Make ammo now: {look.CarriedText} carried, but none can be made now: {look.PackWhy}.";
|
||||
int target = AmmoUpTo(s);
|
||||
if (look.Carried >= target)
|
||||
{
|
||||
ok = true;
|
||||
return $"[RynthAi] Make ammo now: {look.CarriedText} carried, already at Make up to ({target}): nothing to make.";
|
||||
}
|
||||
cm.MakeNowUntilMs = KitNow() + AmmoMakeNowWaitMs;
|
||||
cm.Auto.LookNow();
|
||||
ok = true;
|
||||
return $"[RynthAi] Make ammo now: making {look.Recipe.OutputName} up to {target} as soon as it is safe (no monster within "
|
||||
+ $"{KitSafeRadiusYd(s):0} yd, no fight, in peace mode); waits up to {AmmoMakeNowWaitMs / 1000} s. /ra ammo stop to stop.";
|
||||
}
|
||||
|
||||
// ── /ra ammo auto ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>/ra ammo auto [status | on | off | below N | upto M]: Make ammo when low (a profile setting).</summary>
|
||||
private void HandleAmmoAutoCommand(string[] parts)
|
||||
{
|
||||
var settings = _dashboard?.Settings;
|
||||
if (settings == null) { ReplyFail("[RynthAi] Make ammo when low: not ready yet (log in first)."); return; }
|
||||
string verb = parts.Length > 3 ? parts[3].Trim().ToLowerInvariant() : "status";
|
||||
var cm = _missileCraftingManager;
|
||||
switch (verb)
|
||||
{
|
||||
case "status":
|
||||
ChatLine(AmmoAutoStatusLine()); // the status asked for
|
||||
break;
|
||||
case "on":
|
||||
case "off":
|
||||
{
|
||||
bool on = verb == "on";
|
||||
settings.MakeAmmoWhenLow = on;
|
||||
_dashboard?.SaveSettings();
|
||||
if (cm != null)
|
||||
{
|
||||
_ammoAutoWasOn = on;
|
||||
if (on) cm.Auto.LookNow();
|
||||
else
|
||||
{
|
||||
if (cm.TopOffRunning && !cm.TopOffManual) cm.StopTopOff("Make ammo when low turned off", KitStopKind.Other);
|
||||
cm.Auto.Off();
|
||||
}
|
||||
}
|
||||
string needs = on && !settings.EnableMissileCrafting ? "; it needs Enable Missile Crafting on (Settings > Combat)."
|
||||
: on && !settings.IsMacroRunning ? "; it works while the macro runs."
|
||||
: ".";
|
||||
ReplyOk($"[RynthAi] Make ammo when low: {verb} (under {AmmoBelow(settings)}, make up to {AmmoUpTo(settings)}){needs}");
|
||||
break;
|
||||
}
|
||||
case "below":
|
||||
case "upto":
|
||||
{
|
||||
int max = verb == "below" ? MissileCraftingManager.MaxAmmoBelow : MissileCraftingManager.MaxAmmoUpTo;
|
||||
if (parts.Length < 5)
|
||||
{
|
||||
ReplyOk($"[RynthAi] Make ammo when low: {(verb == "below" ? $"starts under {AmmoBelow(settings)}" : $"makes up to {AmmoUpTo(settings)} a run")}. {AmmoAutoUsage}");
|
||||
break;
|
||||
}
|
||||
if (!int.TryParse(parts[4].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) || n < 1 || n > max)
|
||||
{
|
||||
ReplyFail($"[RynthAi] Make ammo when low: {verb} must be a number from 1 to {max} (got '{parts[4]}'). {AmmoAutoUsage}");
|
||||
break;
|
||||
}
|
||||
if (verb == "below") settings.MakeAmmoBelow = n; else settings.MakeAmmoUpTo = n;
|
||||
_dashboard?.SaveSettings();
|
||||
cm?.Auto.LookNow();
|
||||
string off = settings.MakeAmmoWhenLow ? "." : " (it is off: /ra ammo auto on).";
|
||||
ReplyOk(verb == "below"
|
||||
? $"[RynthAi] Make ammo when low: starts when you carry fewer than {n}{off}"
|
||||
: $"[RynthAi] Make ammo when low: makes up to {AmmoUpTo(settings)} a run{(AmmoUpTo(settings) > n ? $" (never under the start line, {AmmoBelow(settings)})" : "")}{off}");
|
||||
break;
|
||||
}
|
||||
default:
|
||||
ReplyFail($"[RynthAi] Make ammo when low: unknown option '{parts[3]}'. {AmmoAutoUsage}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One line: the setting, its numbers, the radius and what it is doing.</summary>
|
||||
private string AmmoAutoStatusLine()
|
||||
{
|
||||
var s = _dashboard?.Settings;
|
||||
if (s == null) return "[RynthAi] Make ammo when low: not ready yet (log in first).";
|
||||
return $"[RynthAi] Make ammo when low: {(s.MakeAmmoWhenLow ? "on" : "off")}, under {AmmoBelow(s)} make up to {AmmoUpTo(s)}, "
|
||||
+ $"no monster within {KitSafeRadiusYd(s):0} yd; {AmmoAutoStatusText(s)}. Mini Remote > Crafting > Ammo, /ra ammo auto on|off.";
|
||||
}
|
||||
|
||||
/// <summary>What Make ammo when low is doing ("running 2/5 combines", "waiting: monster 22 yd away; next check in 4 s", ...).</summary>
|
||||
internal string AmmoAutoStatusText(LegacyUiSettings s)
|
||||
{
|
||||
var cm = _missileCraftingManager;
|
||||
if (cm == null) return "not ready (log in first)";
|
||||
if (cm.TopOffRunning) return $"running {cm.TopOffMade}/{cm.TopOffPlanned} combines" + (cm.TopOffManual ? " (Make ammo now)" : "");
|
||||
if (cm.MakeNowUntilMs > 0) return "Make ammo now: " + cm.Auto.Status;
|
||||
if (!s.MakeAmmoWhenLow) return "off";
|
||||
if (!s.EnableMissileCrafting) return "waiting: Enable Missile Crafting is off";
|
||||
if (!s.IsMacroRunning) return "waiting: the macro is off";
|
||||
return cm.Auto.Status;
|
||||
}
|
||||
|
||||
// ── The macro side ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Every in-world tick, right after CheckAutoKitsDanger (which keeps the hit and pose notes): stops
|
||||
/// a top-off at once on a monster within the radius, buffing or a heal, a fight, a portal, a vendor,
|
||||
/// a launcher swap, a hit since it started, or moving away from where it started.
|
||||
/// </summary>
|
||||
private void CheckAutoAmmoDanger(LegacyUiSettings s)
|
||||
{
|
||||
var cm = _missileCraftingManager;
|
||||
if (cm == null || !cm.TopOffRunning) return;
|
||||
long now = KitNow();
|
||||
var f = new KitAutoFacts
|
||||
{
|
||||
Enabled = true,
|
||||
MacroOn = true,
|
||||
BusyWhy = AmmoBusyWhy(s, starting: false, readying: false),
|
||||
VitalsWhy = KitVitalsWhy(s),
|
||||
RadiusYd = KitSafeRadiusYd(s),
|
||||
};
|
||||
if (f.BusyWhy.Length == 0 && f.VitalsWhy.Length == 0) f.NearestMonsterYd = NearestMonsterYards(f.RadiusYd, now, force: false);
|
||||
string why = KitAuto.StopReason(f);
|
||||
if (why.Length == 0 && _kitHurtAt >= _ammoRunStartedAt) why = "you were hit";
|
||||
if (why.Length == 0 && AmmoMovedSinceStart()) why = "you moved";
|
||||
if (why.Length > 0) cm.StopTopOff(why, KitStopKind.Danger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Make ammo when low, after the kits' hold: true while a top-off gets ready or goes, and the rest
|
||||
/// of the tick (crafting's empty-slot path, combat, looting, navigation, item chores) waits.
|
||||
/// Also takes the panels' Make ammo now and Stop.
|
||||
/// </summary>
|
||||
private bool TickAutoAmmo(LegacyUiSettings s)
|
||||
{
|
||||
var cm = _missileCraftingManager;
|
||||
if (cm == null) return false;
|
||||
var auto = cm.Auto;
|
||||
long now = KitNow();
|
||||
|
||||
if (cm.TakeStopRequest())
|
||||
{
|
||||
if (cm.TopOffRunning) cm.StopTopOff("stopped by you", KitStopKind.User);
|
||||
else if (cm.MakeNowUntilMs > 0) { cm.MakeNowUntilMs = 0; AmmoChat("[RynthAi] Make ammo now: cancelled."); }
|
||||
}
|
||||
if (cm.TakeMakeNowRequest()) AmmoChat(AskMakeAmmoNow(s, cm, out _));
|
||||
|
||||
// The setting changed (a panel, a profile switch, a meta): look now, or let go.
|
||||
bool on = s.MakeAmmoWhenLow;
|
||||
if (on != _ammoAutoWasOn)
|
||||
{
|
||||
_ammoAutoWasOn = on;
|
||||
if (on) auto.LookNow();
|
||||
else
|
||||
{
|
||||
if (cm.TopOffRunning && !cm.TopOffManual) cm.StopTopOff("Make ammo when low turned off", KitStopKind.Other);
|
||||
auto.Off();
|
||||
}
|
||||
}
|
||||
|
||||
if (cm.TopOffRunning)
|
||||
{
|
||||
if (!cm.TopOffManual && !s.IsMacroRunning) { cm.StopTopOff("the macro was turned off", KitStopKind.MacroOff); return false; }
|
||||
auto.Running(cm.TopOffMade, cm.TopOffPlanned);
|
||||
cm.ProcessCrafting();
|
||||
return cm.IsCrafting;
|
||||
}
|
||||
|
||||
bool manual = cm.MakeNowUntilMs > 0;
|
||||
if (manual && now >= cm.MakeNowUntilMs)
|
||||
{
|
||||
cm.MakeNowUntilMs = 0;
|
||||
manual = false;
|
||||
AmmoChat($"[RynthAi] Make ammo now: gave up after {AmmoMakeNowWaitMs / 1000} s ({auto.Status}).");
|
||||
if (!on) auto.Off();
|
||||
}
|
||||
if (!manual && !on) { if (auto.Status != "off") auto.Off(); return false; }
|
||||
if (cm.IsCrafting) return false; // the empty-slot path is going: it holds the tick itself
|
||||
|
||||
KitAutoStep step = auto.Decide(() => AmmoStartFacts(s, cm, now, auto.Readying, manual));
|
||||
switch (step)
|
||||
{
|
||||
case KitAutoStep.GoPeace:
|
||||
Host.ChangeCombatModeFor(CombatMode.NonCombat, "Crafting", "peace mode for Make ammo when low");
|
||||
return true;
|
||||
case KitAutoStep.Hold:
|
||||
return true;
|
||||
case KitAutoStep.Start:
|
||||
{
|
||||
string why = manual ? "Make ammo now" : $"under {AmmoBelow(s)}";
|
||||
string refused = cm.StartTopOff(AmmoUpTo(s), manual, why, (kind, made) => auto.RunEnded(kind, made));
|
||||
if (refused.Length > 0)
|
||||
{
|
||||
auto.StartRefused(refused);
|
||||
if (manual) { cm.MakeNowUntilMs = 0; AmmoChat($"[RynthAi] Make ammo now: can't start - {refused}."); }
|
||||
return false;
|
||||
}
|
||||
cm.MakeNowUntilMs = 0;
|
||||
_ammoRunStartedAt = now;
|
||||
_ammoStartPoseKnown = Host.TryGetPlayerPose(out _ammoStartCell, out _ammoStartX, out _ammoStartY, out _ammoStartZ, out _, out _, out _, out _);
|
||||
auto.Running(0, cm.TopOffPlanned);
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One full look for a start (KitAuto reads it only when a look is due, every tick while getting ready).</summary>
|
||||
private KitAutoFacts AmmoStartFacts(LegacyUiSettings s, MissileCraftingManager cm, long now, bool readying, bool manual)
|
||||
{
|
||||
var f = new KitAutoFacts
|
||||
{
|
||||
Enabled = true,
|
||||
MacroOn = s.IsMacroRunning || manual,
|
||||
Below = manual ? AmmoUpTo(s) : AmmoBelow(s),
|
||||
BelowMax = manual ? MissileCraftingManager.MaxAmmoUpTo : MissileCraftingManager.MaxAmmoBelow,
|
||||
RadiusYd = KitSafeRadiusYd(s),
|
||||
};
|
||||
if (!s.EnableMissileCrafting) { f.IdleWhy = "Enable Missile Crafting is off"; return f; }
|
||||
if (!f.MacroOn) return f;
|
||||
// The scan as it is (under a second old, else walked again): the empty-slot check already forces
|
||||
// a walk every 5 s, and StartTopOff walks the packs once more before the first combine.
|
||||
var look = cm.LookTopOff(forceRefresh: false);
|
||||
var category = look.Category;
|
||||
f.CountText = n => MissileCraftingManager.AmmoText(n, category);
|
||||
if (!look.Launcher) { f.IdleWhy = look.PackWhy; return f; }
|
||||
f.Kits = look.Carried;
|
||||
if (f.Kits >= Math.Clamp(f.Below, 1, f.BelowMax)) return f;
|
||||
f.BusyWhy = AmmoBusyWhy(s, starting: true, readying: readying);
|
||||
f.VitalsWhy = KitVitalsWhy(s);
|
||||
f.NearestMonsterYd = NearestMonsterYards(f.RadiusYd, now, force: false);
|
||||
f.SinceHurtMs = _kitHurtAt <= long.MinValue / 4 ? long.MaxValue : Math.Max(0, now - _kitHurtAt);
|
||||
f.PackWhy = look.PackWhy;
|
||||
try { f.InPeace = !Host.HasGetCurrentCombatMode || Host.GetCurrentCombatMode() == CombatMode.NonCombat; }
|
||||
catch { f.InPeace = false; }
|
||||
f.Moving = _kitMoving;
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kits' "what else has the character" (KitBusyWhy), plus a launcher swap; for a start also Boost
|
||||
/// Loot's wait for a kill's corpse and a kit run getting ready or going.
|
||||
/// </summary>
|
||||
private string AmmoBusyWhy(LegacyUiSettings s, bool starting, bool readying)
|
||||
{
|
||||
string why = KitBusyWhy(s, starting, clientBusyCounts: !readying);
|
||||
if (why.Length > 0) return why;
|
||||
if (_combatManager?.AmmoSwapInProgress == true) return "a launcher swap";
|
||||
if (!starting) return string.Empty;
|
||||
if (s.BoostLootPriority && BoostLootAwaitsKillCorpse(s)) return "a kill's corpse to loot first (Boost Loot Priority)";
|
||||
var tab = _miniRemote?.Crafting;
|
||||
if (tab != null && (tab.Kits.Running || tab.AutoKits.Readying)) return "making kits";
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Further than 1.5 m from where the top-off started (another cell's landblock counts as moved).</summary>
|
||||
private bool AmmoMovedSinceStart()
|
||||
{
|
||||
if (!_ammoStartPoseKnown) return false;
|
||||
try
|
||||
{
|
||||
if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _)) return false;
|
||||
if ((cell >> 16) != (_ammoStartCell >> 16)) return true;
|
||||
float dx = x - _ammoStartX, dy = y - _ammoStartY, dz = z - _ammoStartZ;
|
||||
return dx * dx + dy * dy + dz * dz > AmmoMoveLimit * AmmoMoveLimit;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
/// <summary>Logout: this character's top-off notes go (the crafting manager goes with it).</summary>
|
||||
private void ResetAmmoTracking()
|
||||
{
|
||||
_ammoAutoWasOn = false;
|
||||
_ammoRunStartedAt = long.MinValue / 2;
|
||||
_ammoStartPoseKnown = false;
|
||||
}
|
||||
}
|
||||
|
|
@ -15,6 +15,16 @@
|
|||
// then the fight and the hunt go on. One exception kept for safety: with health under Heal At (the
|
||||
// line a fight heals at) a monster on you is fought as before, so looting never stands still while
|
||||
// the character is being killed.
|
||||
//
|
||||
// 2026-11-23 (the owner: "for loot boost below health max it keeps looting. I think it should
|
||||
// interrupt looting and heal"). The rule above kept looting at any health from Heal At up, and with
|
||||
// a monster within Monster Range the heal line was Heal At too (a fight's line), so a looter at 70%
|
||||
// with Heal At 60 (or Heal At 0) looted on and healed nothing until the corpses
|
||||
// were done. Now, while this looting would have the tick (loot work, Boost Loot can run, health at
|
||||
// or over Heal At), health uses the between-fights line, Top Off HP (BuffManager.FightHealthLine):
|
||||
// under it the heal wins the tick (Buffing halts the loot and keeps the claim), and looting resumes
|
||||
// once health is back over it. Under Heal At nothing changes: a monster on you is fought, and the
|
||||
// fight's heal line applies.
|
||||
// ============================================================================
|
||||
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
|
@ -33,4 +43,11 @@ public sealed partial class RynthAiPlugin
|
|||
/// <summary>CombatManager.HoldNewTargetThroughThreat: the hold on the next target applies with a monster close.</summary>
|
||||
private bool BoostLootHoldsThroughThreat()
|
||||
=> _dashboard?.Settings is { } s && BoostLootFirst(s);
|
||||
|
||||
/// <summary>
|
||||
/// BuffManager.BoostLootHealsToTopOff: Boost Loot's looting would have the tick over the fight
|
||||
/// (loot work last tick, and corpses first), so health heals at Top Off HP, not Heal At.
|
||||
/// </summary>
|
||||
private bool BoostLootHealsToTopOff()
|
||||
=> _lastWantLoot && _dashboard?.Settings is { } s && BoostLootFirst(s);
|
||||
}
|
||||
|
|
|
|||
267
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.CommandButtons.cs
Normal file
267
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.CommandButtons.cs
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Plugin.RynthAi.CommandButtons;
|
||||
using RynthCore.Plugin.RynthAi.Diagnostics;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
// Command Buttons (2026-11-26, a player's ask): a window of buttons that each send one chat line, per
|
||||
// character, per server and for every character (CommandButtons/CommandButtons.cs has the files). The
|
||||
// lists load once the character's settings folder is known, the tick saves edits a second after the
|
||||
// last one, and a press is sent on the tick through RynthCore's chat parser, as a line typed in the
|
||||
// chat box is (the game's commands, /rc, every plugin's commands, emotes, @ server commands, speech).
|
||||
// The window (a plugin window, API v89, no bar button) opens from the dashboard's options menu,
|
||||
// /ra buttons and Find a Feature.
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
internal const string CommandButtonsTitle = "Command Buttons", CommandButtonsSurface = "window:commandbuttons";
|
||||
private const long ButtonsSaveAfterMs = 1000;
|
||||
|
||||
private readonly CommandButtonSet _buttons = new();
|
||||
private CommandButtonsWindow? _buttonsWindow;
|
||||
private string _buttonsLoadedFor = string.Empty; // the settings folder the lists are for
|
||||
private int _buttonsFailures;
|
||||
|
||||
/// <summary>The tick (TickStep.CommandButtons): load for this character, save edits.</summary>
|
||||
private void TickCommandButtons()
|
||||
{
|
||||
if (!_loginComplete || _dashboard == null) return;
|
||||
string charFolder = _dashboard.CharFolder;
|
||||
if (string.IsNullOrEmpty(charFolder)) return;
|
||||
if (!string.Equals(charFolder, _buttonsLoadedFor, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
SaveCommandButtons();
|
||||
var problems = new List<string>();
|
||||
_buttons.Load(charFolder, problems);
|
||||
_buttonsLoadedFor = charFolder;
|
||||
foreach (string p in problems) ChatLine($"[RynthAi] Command buttons: couldn't read the list for {p}.");
|
||||
}
|
||||
if (_buttons.AnyDirty && Environment.TickCount64 - _buttons.ChangedAtMs >= ButtonsSaveAfterMs) SaveCommandButtons();
|
||||
}
|
||||
|
||||
private void SaveCommandButtons()
|
||||
{
|
||||
if (!_buttons.AnyDirty) return;
|
||||
var problems = new List<string>();
|
||||
_buttons.SaveDirty(problems);
|
||||
foreach (string p in problems) ChatLine($"[RynthAi] Command buttons: couldn't save the list for {p}.");
|
||||
}
|
||||
|
||||
/// <summary>Logout: the lists are saved and forgotten (the next character loads its own).</summary>
|
||||
private void OnLogoutCommandButtons()
|
||||
{
|
||||
SaveCommandButtons();
|
||||
_buttons.Unload();
|
||||
_buttonsLoadedFor = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends button <paramref name="index"/> of <paramref name="scope"/>'s list. On the tick only (the window
|
||||
/// and /ra buttons press queue it): RynthCore runs the line as typed, so a /ra line comes back to RynthAi,
|
||||
/// which must not be inside the chat parser's plugin step then. False (and why, in the window's note and
|
||||
/// in chat) when it can't be sent.
|
||||
/// </summary>
|
||||
private bool PressCommandButton(ButtonScope scope, int index)
|
||||
{
|
||||
string label, line;
|
||||
lock (_buttons.Sync)
|
||||
{
|
||||
List<CommandButton> list = _buttons.List(scope);
|
||||
if (index < 0 || index >= list.Count) return false;
|
||||
label = list[index].Shown;
|
||||
line = list[index].Command;
|
||||
}
|
||||
CommandCheck check = CommandLine.Check(line);
|
||||
string? problem = check.Kind == CommandKind.Empty ? "it has no command yet"
|
||||
: check.Problem != null ? check.Problem.TrimEnd('.').ToLowerInvariant()
|
||||
: !Host.HasInvokeChatParser ? "this RynthCore can't send chat lines for a plugin"
|
||||
: null;
|
||||
if (problem != null)
|
||||
{
|
||||
_buttonsWindow?.Note($"{label}: not sent ({problem}).");
|
||||
ReplyFail($"[RynthAi] Command button '{label}' wasn't sent: {problem}.");
|
||||
return false;
|
||||
}
|
||||
// The parser's answer is the game's (speech and emotes can say 0 and still go): the log keeps it, the
|
||||
// line's own effect (a command's reply, the emote, the server's answer) is what the player sees.
|
||||
bool taken = Host.InvokeChatParser(check.Line);
|
||||
Host.Log($"[RynthAi] Command button ({CommandButtonSet.ScopeName(scope)}) '{label}': {check.Line}{(taken ? "" : " (the chat parser answered 0)")}");
|
||||
_buttonsWindow?.Note("Sent: " + check.Line);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The dashboard's ⋯ > Command buttons: the window open or closed. Any thread.</summary>
|
||||
internal void ToggleCommandButtonsWindow()
|
||||
{
|
||||
if (Host.HasSetPanelOpen) Host.SetPanelOpen(CommandButtonsTitle, RynthPanelOpen.Toggle);
|
||||
}
|
||||
|
||||
// ── /ra buttons ──────────────────────────────────────────────────────
|
||||
|
||||
internal const string ButtonsUsage =
|
||||
"Usage: /ra buttons [server|all] list | add <label> = <command> | remove <n> | press <n or label>; /ra buttons [show|hide|edit]";
|
||||
|
||||
/// <summary>
|
||||
/// "/ra buttons ...": the window and the lists by chat. The list word ("server" or "all"; none = this
|
||||
/// character) comes right after buttons. Every form replies.
|
||||
/// </summary>
|
||||
private void HandleButtonsCommand(string[] parts)
|
||||
{
|
||||
int at = 2;
|
||||
ButtonScope scope = ButtonScope.Character;
|
||||
if (parts.Length > at)
|
||||
{
|
||||
string s = parts[at].ToLowerInvariant();
|
||||
if (s is "server") { scope = ButtonScope.Server; at++; }
|
||||
else if (s is "all" or "global") { scope = ButtonScope.All; at++; }
|
||||
else if (s is "char" or "character" or "me") at++;
|
||||
}
|
||||
string verb = parts.Length > at ? parts[at].ToLowerInvariant() : "show";
|
||||
string listName = CommandButtonSet.ScopeName(scope);
|
||||
|
||||
if (verb is "show" or "open" or "hide" or "close" or "toggle" or "window" or "edit")
|
||||
{
|
||||
if (!Host.HasSetPanelOpen) { ReplyFail("[RynthAi] The Command Buttons window needs RynthCore with plugin windows (plugin API 89+); /ra buttons list and press work."); return; }
|
||||
RynthPanelOpen mode = verb is "hide" or "close" ? RynthPanelOpen.Close : verb is "toggle" or "window" ? RynthPanelOpen.Toggle : RynthPanelOpen.Open;
|
||||
int open = Host.SetPanelOpen(CommandButtonsTitle, mode);
|
||||
if (open < 0) { ReplyFail("[RynthAi] The Command Buttons window isn't there yet (RynthCore adds it a few seconds after login). Try again in a moment."); return; }
|
||||
if (verb == "edit" && open == 1)
|
||||
{
|
||||
_buttonsWindow ??= NewButtonsWindow();
|
||||
_buttonsWindow.OpenEdit(scope);
|
||||
ReplyOk($"[RynthAi] Command Buttons window open, editing the buttons for {listName}.");
|
||||
return;
|
||||
}
|
||||
ReplyOk(open == 1 ? "[RynthAi] Command Buttons window open." : "[RynthAi] Command Buttons window closed.");
|
||||
return;
|
||||
}
|
||||
if (!_buttons.Loaded) { ReplyFail("[RynthAi] Command buttons load once you are in the world (your settings folder isn't known yet)."); return; }
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
string rest = parts.Length > at + 1 ? string.Join(' ', parts, at + 1, parts.Length - at - 1) : string.Empty;
|
||||
switch (verb)
|
||||
{
|
||||
case "list":
|
||||
case "ls":
|
||||
{
|
||||
var lines = new List<string>();
|
||||
lock (_buttons.Sync)
|
||||
{
|
||||
List<CommandButton> list = _buttons.List(scope);
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
CommandButton b = list[i];
|
||||
string label = b.Label.Length > 0 ? b.Label : "(no label)";
|
||||
lines.Add($"[RynthAi] {i + 1}. {label}: {(b.Command.Length > 0 ? b.Command : "(no command)")}{(b.Confirm ? " (asks first)" : "")}");
|
||||
}
|
||||
}
|
||||
if (lines.Count == 0) { ReplyOk($"[RynthAi] No command buttons for {listName}. /ra buttons{ScopeWord(scope)} add <label> = <command> adds one."); return; }
|
||||
ReplyOk($"[RynthAi] Command buttons for {listName} ({lines.Count}):");
|
||||
foreach (string l in lines) ChatLine(l);
|
||||
return;
|
||||
}
|
||||
case "add":
|
||||
{
|
||||
int eq = rest.IndexOf('=');
|
||||
string label = eq >= 0 ? rest[..eq] : string.Empty;
|
||||
string command = eq >= 0 ? rest[(eq + 1)..] : rest;
|
||||
CommandCheck check = CommandLine.Check(command);
|
||||
if (check.Kind == CommandKind.Empty) { ReplyFail($"[RynthAi] Usage: /ra buttons{ScopeWord(scope)} add <label> = <command> (or just add <command>)"); return; }
|
||||
if (check.Problem != null) { ReplyFail($"[RynthAi] Not added: {check.Problem}"); return; }
|
||||
CommandButton? b;
|
||||
int n;
|
||||
lock (_buttons.Sync)
|
||||
{
|
||||
b = _buttons.Add(scope, label, check.Line, now);
|
||||
n = _buttons.List(scope).Count;
|
||||
}
|
||||
if (b == null) { ReplyFail($"[RynthAi] The command buttons for {listName} are full ({CommandButtonSet.MaxPerList}): remove one first."); return; }
|
||||
SaveCommandButtons();
|
||||
ReplyOk($"[RynthAi] Command button {n} for {listName}: {b.Shown} sends {b.Command}");
|
||||
return;
|
||||
}
|
||||
case "remove":
|
||||
case "rm":
|
||||
case "delete":
|
||||
case "press":
|
||||
case "run":
|
||||
{
|
||||
int index = -1;
|
||||
string shown = string.Empty;
|
||||
lock (_buttons.Sync)
|
||||
{
|
||||
List<CommandButton> list = _buttons.List(scope);
|
||||
if (int.TryParse(rest, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
|
||||
index = n >= 1 && n <= list.Count ? n - 1 : -1;
|
||||
else if (rest.Length > 0)
|
||||
index = list.FindIndex(b => b.Label.Equals(rest.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||
if (index >= 0) shown = list[index].Shown;
|
||||
}
|
||||
if (rest.Length == 0) { ReplyFail($"[RynthAi] Usage: /ra buttons{ScopeWord(scope)} {verb} <n or label> (the number in /ra buttons{ScopeWord(scope)} list)"); return; }
|
||||
if (index < 0) { ReplyFail($"[RynthAi] There is no command button '{rest}' for {listName} (/ra buttons{ScopeWord(scope)} list)."); return; }
|
||||
if (verb is "press" or "run")
|
||||
{
|
||||
// On the tick: this line is being handled inside the chat parser's plugin step.
|
||||
ButtonScope sc = scope;
|
||||
int ix = index;
|
||||
QueueDashAction(() => PressCommandButton(sc, ix));
|
||||
ReplyOk($"[RynthAi] Pressing command button {index + 1} for {listName}: {shown}");
|
||||
return;
|
||||
}
|
||||
lock (_buttons.Sync)
|
||||
{
|
||||
_buttons.List(scope).RemoveAt(index);
|
||||
_buttons.MarkChanged(scope, now);
|
||||
}
|
||||
SaveCommandButtons();
|
||||
ReplyOk($"[RynthAi] Removed command button {index + 1} for {listName}: {shown}");
|
||||
return;
|
||||
}
|
||||
default:
|
||||
ReplyFail("[RynthAi] " + ButtonsUsage);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private static string ScopeWord(ButtonScope s) => s switch { ButtonScope.Server => " server", ButtonScope.All => " all", _ => string.Empty };
|
||||
|
||||
// ── The window (render thread) ───────────────────────────────────────
|
||||
|
||||
private CommandButtonsWindow NewButtonsWindow() =>
|
||||
new(_buttons, (scope, index) => QueueDashAction(() => PressCommandButton(scope, index)));
|
||||
|
||||
/// <summary>
|
||||
/// RynthPluginRenderEmbed "window:commandbuttons": the Command Buttons window body, docked or popped out
|
||||
/// (the engine's current context). 1 drawn, 0 not ready, -2 failed (three draws in a row threw).
|
||||
/// </summary>
|
||||
internal int RenderCommandButtons(bool popped, out Vector2 want)
|
||||
{
|
||||
want = default;
|
||||
if (!_initialized || Host.ImGuiContext == IntPtr.Zero) return 0;
|
||||
IntPtr previous = ImGui.GetCurrentContext();
|
||||
ImGui.SetCurrentContext(EmbedContext());
|
||||
try
|
||||
{
|
||||
_buttonsWindow ??= NewButtonsWindow();
|
||||
want = _buttonsWindow.Draw();
|
||||
_buttonsFailures = 0;
|
||||
return 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Exception(LogCat.UI, ex, "RenderCommandButtons");
|
||||
return ++_buttonsFailures >= 3 ? -2 : 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGui.SetCurrentContext(previous);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The window goes in the sections manifest on an engine with plugin windows (v89).</summary>
|
||||
private bool CommandButtonsWindowWanted => Host.HasUiTheme && Host.HasSetPanelOpen;
|
||||
}
|
||||
|
|
@ -13,6 +13,14 @@
|
|||
// use refusal, and it gets another look every CorpseWallRecheckMs: once the line is clear (the
|
||||
// character moved, the hunt walked round) it is a corpse like any other. Only a failed open leads
|
||||
// here, so a corpse the ray reads behind a wall that still opens is looted as before.
|
||||
//
|
||||
// 2026-11-23 (R-20261124-001522-b582, 2026.11.23.2, Shadowfang Keep again): "I am still trying to walk
|
||||
// through walls to loot others corpses". Each corpse behind a wall still got its first open, and
|
||||
// the server's walk drove the character into the wall for the 2.6-5 s that open took to fail, corpse
|
||||
// after corpse. Now the line is checked once when a corpse is about to be claimed: a wall in the
|
||||
// way sets it aside before any open (SetAsideBeforeClaim). In case the ray is wrong about it (a
|
||||
// corpse it can't see that a walk would reach), one held back that long still gets one open after
|
||||
// CorpseWallTryAnywayMs, and the old rule (set aside after a failed open) takes it from there.
|
||||
// ============================================================================
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
|
@ -27,6 +35,31 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
private readonly HashSet<int> _corpsesBehindWall = new();
|
||||
|
||||
/// <summary>A corpse set aside before any open gets one open anyway after this long behind the wall.</summary>
|
||||
internal const long CorpseWallTryAnywayMs = 20_000;
|
||||
|
||||
// Set aside before any open: since when (for the try-anyway), and those that had their try.
|
||||
private readonly Dictionary<int, long> _corpseWallSince = new();
|
||||
private readonly HashSet<int> _corpseWallTriedAnyway = new();
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="corpseId"/> is about to be claimed: true when the line to it crosses a wall, and
|
||||
/// it was set aside instead (no claim, no open, so no walk into the wall).
|
||||
/// </summary>
|
||||
private bool SetAsideBeforeClaim(int corpseId, long now)
|
||||
{
|
||||
if (corpseId == 0 || _corpseWallTriedAnyway.Contains(corpseId) || !CorpseBehindWall(corpseId)) return false;
|
||||
if (_corpsesBehindWall.Count >= 256) { _corpsesBehindWall.Clear(); _corpseWallSince.Clear(); _corpseWallTriedAnyway.Clear(); }
|
||||
_corpsesBehindWall.Add(corpseId);
|
||||
if (!_corpseWallSince.ContainsKey(corpseId)) _corpseWallSince[corpseId] = now;
|
||||
_corpseCooldownUntil[corpseId] = now + CorpseWallRecheckMs;
|
||||
string name = _objectCache?[corpseId]?.Name ?? $"0x{(uint)corpseId:X8}";
|
||||
double d = _objectCache?.Distance(unchecked((int)_playerId), corpseId) ?? double.MaxValue;
|
||||
LootDiag($"[RynthAi] Corpse loot: 0x{(uint)corpseId:X8} '{name}'{(d < 1000 ? $" ({d:0.0} m)" : "")} has a wall between: " +
|
||||
"set aside before any open (no walk into the wall) until the line to it is clear.");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Tests: whether a wall stands between the character and the corpse (else the raycast decides).</summary>
|
||||
internal System.Func<int, bool>? CorpseWallOverride { get; set; }
|
||||
|
||||
|
|
@ -72,10 +105,21 @@ public sealed partial class RynthAiPlugin
|
|||
if (!_corpsesBehindWall.Contains(corpseId)) return false;
|
||||
if (CorpseBehindWall(corpseId))
|
||||
{
|
||||
// Set aside before any open and still behind the wall after CorpseWallTryAnywayMs: one
|
||||
// open anyway, in case the ray is wrong (a failed one sets it aside the old way).
|
||||
if (_corpseWallSince.TryGetValue(corpseId, out long since) && now - since >= CorpseWallTryAnywayMs)
|
||||
{
|
||||
_corpseWallSince.Remove(corpseId);
|
||||
_corpseWallTriedAnyway.Add(corpseId);
|
||||
_corpsesBehindWall.Remove(corpseId);
|
||||
LootDiag($"[RynthAi] Corpse loot: 0x{(uint)corpseId:X8} is still behind a wall after {CorpseWallTryAnywayMs / 1000} s: one open anyway, in case the line reads wrong.");
|
||||
return false;
|
||||
}
|
||||
_corpseCooldownUntil[corpseId] = now + CorpseWallRecheckMs;
|
||||
return true;
|
||||
}
|
||||
_corpsesBehindWall.Remove(corpseId);
|
||||
_corpseWallSince.Remove(corpseId);
|
||||
LootDiag($"[RynthAi] Corpse loot: the line to 0x{(uint)corpseId:X8} is clear now: it can be looted.");
|
||||
return false;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -323,6 +323,8 @@ internal sealed class DashboardBridge : IDashboardHost
|
|||
public bool FightSelectedTarget => _p.DashboardRenderer?.Settings.FightSelectedTarget == true;
|
||||
public bool DebuffAllBeforeAttacking => _p.DashboardRenderer?.Settings.DebuffAllBeforeAttacking == true;
|
||||
public void SetAutoSort(bool on) => Queue(() => _p.SetDashAutoSort(on));
|
||||
public RechargeVital RechargeHeld => _p.RechargeHeld;
|
||||
public void SetRechargeHold(RechargeVital vitals, bool on) => Queue(() => _p.SetRechargeHold(vitals, on));
|
||||
public void ToggleSortWindow() => Queue(() => _p.SendSortCommand(string.Empty));
|
||||
public void StartPatrol() => Queue(_p.HandleDungeonNavPatrol);
|
||||
public void ToggleHunt() => Queue(_p.ToggleHunt);
|
||||
|
|
@ -333,7 +335,9 @@ internal sealed class DashboardBridge : IDashboardHost
|
|||
public void ToggleSpells() => _p.EnqueueRemoteCommand("spells", "toggle");
|
||||
public void ToggleActiveGear() => Queue(_p.ToggleActiveGearWindow);
|
||||
public void ToggleTimedCommands() => Queue(_p.ToggleTimedCommandsWindow);
|
||||
public void ToggleCommandButtons() => Queue(_p.ToggleCommandButtonsWindow);
|
||||
public void OpenFeatureSearch() => Queue(_p.OpenFeatureSearchWindow);
|
||||
public void ToggleAcMaps() => Queue(_p.ToggleAcMapsWindow);
|
||||
public void UseClassicLook() => _p.UseClassicLook();
|
||||
|
||||
public ProfileFileInfo ProfileInfo(int kind)
|
||||
|
|
|
|||
106
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HubReadOnly.cs
Normal file
106
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HubReadOnly.cs
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
// RynthAiPlugin.HubReadOnly.cs - read-only answers for other plugins through RynthAi.Hub
|
||||
// (HubInterface.cs; appended 2026-11-26 for RynthSort's pack jobs): what the loot profile in use
|
||||
// says about items in the packs, what AutoVendor would sell, what AutoTrade would give a partner.
|
||||
// Nothing here changes what RynthAi does: each answer uses its own copy of the profile, writes no
|
||||
// chat or log line, and sets nothing (the looter's loaders say "Loaded loot profile" in chat and
|
||||
// can set CurrentLootPath, so they aren't used). Pump thread only.
|
||||
using System;
|
||||
using System.IO;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.VTank;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
private VTankLootProfile? _askUtl;
|
||||
private LootProfile? _askJson;
|
||||
private string _askLootPath = string.Empty;
|
||||
private DateTime _askLootTime;
|
||||
|
||||
/// <summary>
|
||||
/// The first matching rule's action of the loot profile in use, per item (VTank numbers:
|
||||
/// <see cref="VTankLootAction"/>; 0 = no rule matches, or the item isn't known yet). The .json
|
||||
/// and .utl profiles both; the profile's rules only, as the looter's order has them (no Keep #
|
||||
/// counts, no built-in keeps). False with <paramref name="error"/>: not logged in, no profile, or
|
||||
/// Loot Mode "Rares only" (the profile isn't used). <paramref name="profileFile"/>: its file name.
|
||||
/// </summary>
|
||||
internal bool LootActionsForHub(uint[] ids, byte[] actions, out string profileFile, out string? error)
|
||||
{
|
||||
Array.Clear(actions);
|
||||
profileFile = string.Empty;
|
||||
error = null;
|
||||
var settings = _dashboard?.Settings;
|
||||
var cache = _objectCache;
|
||||
if (settings == null || cache == null || _playerId == 0) { error = "RynthAi isn't ready (log in first)"; return false; }
|
||||
if (LootModes.IsRares(settings.LootMode)) { error = "RynthAi's Loot Mode is rares only, so its loot profile isn't used"; return false; }
|
||||
string path = (settings.CurrentLootPath ?? string.Empty).Trim().Trim('"');
|
||||
if (path.Length == 0) { error = "RynthAi has no loot profile picked"; return false; }
|
||||
profileFile = Path.GetFileName(path);
|
||||
if (!File.Exists(path)) { error = "RynthAi's loot profile " + profileFile + " isn't there"; return false; }
|
||||
bool json = path.EndsWith(".json", StringComparison.OrdinalIgnoreCase);
|
||||
try
|
||||
{
|
||||
DateTime t = File.GetLastWriteTimeUtc(path);
|
||||
if (!string.Equals(_askLootPath, path, StringComparison.OrdinalIgnoreCase) || _askLootTime != t || (json ? _askJson == null : _askUtl == null))
|
||||
{
|
||||
_askUtl = null;
|
||||
_askJson = null;
|
||||
if (json) _askJson = LootProfile.Load(path);
|
||||
else _askUtl = VTankLootParser.Load(path);
|
||||
_askLootPath = path;
|
||||
_askLootTime = t;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) { error = "RynthAi's loot profile " + profileFile + " could not be read: " + ex.Message; return false; }
|
||||
|
||||
var ctx = new VTankLootContext(Host, _playerId) { Cache = cache };
|
||||
for (int i = 0; i < ids.Length && i < actions.Length; i++)
|
||||
{
|
||||
WorldObject? wo = cache[unchecked((int)ids[i])];
|
||||
if (wo == null || wo.Id == 0) continue;
|
||||
if (_askJson != null)
|
||||
{
|
||||
var (action, rule) = LootEvaluator.Classify(_askJson, wo, _charSkills);
|
||||
if (rule != null) actions[i] = (byte)ToVTank(action);
|
||||
}
|
||||
else if (_askUtl != null)
|
||||
{
|
||||
VTankLootRule? rule = VTankLootEvaluator.FirstMatch(_askUtl, wo, ctx, out _);
|
||||
if (rule != null) actions[i] = (byte)rule.Action;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static VTankLootAction ToVTank(LootAction a) => a switch
|
||||
{
|
||||
LootAction.Keep => VTankLootAction.Keep,
|
||||
LootAction.Sell => VTankLootAction.Sell,
|
||||
LootAction.Salvage => VTankLootAction.Salvage,
|
||||
LootAction.Read => VTankLootAction.Read,
|
||||
LootAction.KeepUpTo => VTankLootAction.KeepUpTo,
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
/// <summary>AutoVendor's answer (<see cref="Vendor.AutoVendorManager.WouldSell"/>); false before login.</summary>
|
||||
internal bool VendorSellsForHub(uint[] ids, byte[] sells, out string profileFile, out string? error)
|
||||
{
|
||||
Array.Clear(sells);
|
||||
profileFile = string.Empty;
|
||||
var av = _autoVendor;
|
||||
if (av == null) { error = "RynthAi isn't ready (log in first)"; return false; }
|
||||
return av.WouldSell(ids, sells, out profileFile, out error);
|
||||
}
|
||||
|
||||
/// <summary>AutoTrade's answer for <paramref name="partner"/> (<see cref="Trade.AutoTradeManager.WouldGive"/>); false before login.</summary>
|
||||
internal bool TradeGivesForHub(string partner, uint[] ids, byte[] gives, out string profileFile, out string? error)
|
||||
{
|
||||
Array.Clear(gives);
|
||||
profileFile = string.Empty;
|
||||
var at = _autoTrade;
|
||||
if (at == null) { error = "RynthAi isn't ready (log in first)"; return false; }
|
||||
return at.WouldGive(partner, ids, gives, out profileFile, out error);
|
||||
}
|
||||
}
|
||||
|
|
@ -490,6 +490,19 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
public string? HoldReason() => _p.ItemToolHoldReason(yieldToLooter: true);
|
||||
|
||||
public string? NoRoomReason()
|
||||
{
|
||||
var cache = _p._objectCache;
|
||||
int playerId = unchecked((int)_p._playerId);
|
||||
if (cache == null || playerId == 0) return null;
|
||||
try
|
||||
{
|
||||
int free = WorldObjectCache.MainPackFreeSlots(cache.GetDirectInventory(forceRefresh: false), playerId, Host);
|
||||
return free <= 0 ? "the main pack is full (loot goes only into the main pack); Auto Cram or you can make room" : null;
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
public bool HasUseDone => Host.HasUseDoneSeq;
|
||||
public int UseDoneSeq() => Host.HasUseDoneSeq ? Host.GetUseDoneSeq() : 0;
|
||||
public bool LastUseDone(out int seq, out uint error)
|
||||
|
|
@ -618,12 +631,16 @@ public sealed partial class RynthAiPlugin
|
|||
return n;
|
||||
}
|
||||
|
||||
public bool Landed(int itemId, int count)
|
||||
public bool Landed(int itemId, int count, out int left)
|
||||
{
|
||||
// As the give queue reads it (GiveLanded): gone from the cache, out of the packs, or a smaller stack.
|
||||
left = 0;
|
||||
if (_p._objectCache?[itemId] is not WorldObject wo) return true;
|
||||
if (!_p.InPlayerInventory(wo.Container)) return true;
|
||||
return Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) < count;
|
||||
int now = Math.Max(1, wo.Values(LongValueKey.StackCount, 1));
|
||||
if (now >= count) return false;
|
||||
left = now;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool Send(int itemId, int targetId)
|
||||
|
|
|
|||
|
|
@ -277,6 +277,8 @@ public sealed partial class RynthAiPlugin
|
|||
if (f.Kits >= f.Below) return f;
|
||||
// Getting ready, the client is busy with our own peace-mode switch: not a reason to give up.
|
||||
f.BusyWhy = KitBusyWhy(s, starting: true, clientBusyCounts: !readying);
|
||||
// Make ammo when low getting ready (RynthAiPlugin.Ammo.cs; its run is "crafting ammunition" above).
|
||||
if (f.BusyWhy.Length == 0 && _missileCraftingManager?.Auto.Readying == true) f.BusyWhy = "making ammunition";
|
||||
f.VitalsWhy = KitVitalsWhy(s);
|
||||
f.NearestMonsterYd = NearestMonsterYards(f.RadiusYd, now, force: false);
|
||||
f.SinceHurtMs = _kitHurtAt <= long.MinValue / 4 ? long.MaxValue : Math.Max(0, now - _kitHurtAt);
|
||||
|
|
|
|||
|
|
@ -141,6 +141,9 @@ public sealed partial class RynthAiPlugin
|
|||
var huds = _huds;
|
||||
_miniRemote.MiniRemoteCommand = mode => "[Mini Remote] " + huds.HandleCommand("remote", mode);
|
||||
_miniRemote.MiniRemoteTabCommand = (tab, mode) => huds.HandleTabCommand(tab, mode);
|
||||
// Crafting > Ammo: Make ammo when low and Make ammo now (RynthAiPlugin.Ammo.cs).
|
||||
_miniRemote.Crafting.Ammo = () => _missileCraftingManager;
|
||||
_miniRemote.Crafting.AmmoStatus = AmmoAutoStatusText;
|
||||
EnsureItemInfoUi();
|
||||
EnsureSpellsUi();
|
||||
}
|
||||
|
|
@ -197,6 +200,8 @@ public sealed partial class RynthAiPlugin
|
|||
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats tick"); }
|
||||
try { TickActiveGear(); } // RynthAiPlugin.ActiveGear.cs
|
||||
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "active gear tick"); }
|
||||
try { TickAcMaps(); } // RynthAiPlugin.AcMaps.cs (the chat line, when turned on)
|
||||
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "ACMAPS tick"); }
|
||||
try { _serverHub?.Tick(); }
|
||||
catch (Exception ex) { RynthLog.Exception(LogCat.UI, ex, "server plugin hub lookup"); }
|
||||
try { _miniRemote?.Tick(); }
|
||||
|
|
@ -284,6 +289,7 @@ public sealed partial class RynthAiPlugin
|
|||
RenderLootWhyWindow();
|
||||
RenderHuntPanel();
|
||||
RenderDfHeightPanel();
|
||||
ReleaseIdleAcMapTextures();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -494,7 +500,8 @@ public sealed partial class RynthAiPlugin
|
|||
if (!_initialized || !_loginComplete) return null;
|
||||
return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(), Huds.SectionsManifest.OwnSections,
|
||||
dashboard: DashboardWindowWanted, monsterStats: MonsterStatsWindowWanted, timedCommands: TimedCommandsWindowWanted,
|
||||
activeGear: ActiveGearWindowWanted, featureSearch: FeatureSearchWindowWanted);
|
||||
activeGear: ActiveGearWindowWanted, featureSearch: FeatureSearchWindowWanted, acMaps: AcMapsWindowWanted,
|
||||
commandButtons: CommandButtonsWindowWanted, tradeShop: TradeShopWindowWanted);
|
||||
}
|
||||
/// <summary>Chat Translate window in the dashboard colours (no-op while hidden).</summary>
|
||||
private void RenderTranslateWindow()
|
||||
|
|
|
|||
86
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootBurden.cs
Normal file
86
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootBurden.cs
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - RynthAiPlugin.LootBurden.cs
|
||||
// Loot the server would refuse for burden is left with a clear line, not resent (2026-11-23).
|
||||
//
|
||||
// R-20261123-065337-d200 (Item Tool chest looter on Legendary Armor Chests): "the item he is
|
||||
// trying to loot will flicker and he will seem like he is trying to pick the item up". An
|
||||
// 'Olthoi Breastplate' kept by the profile was refused 94 ms after every send with no error
|
||||
// code: 3 resends taken for "too busy", 3 tries, then left - and the next key on the chest
|
||||
// found it again, chest after chest. ACE turns a pickup away before any motion when the
|
||||
// character's burden plus the item's would pass 300% of its carrying capacity
|
||||
// (Player.HandleActionPutItemInContainer_Verify, HasEnoughBurdenToAddToInventory: "You are too
|
||||
// encumbered to carry that!" and InventoryServerSaveFailed with no code), so it looks exactly
|
||||
// like a busy refusal. The client knows all of it: its own burden (STypeInt 5, sent on login and
|
||||
// kept current), its Strength, the carrying capacity augmentation (STypeInt 230) and the item's
|
||||
// burden (STypeInt 5). An item that can't go in is now left before it is sent, with one chat
|
||||
// line every 5 minutes; lighter items on the same corpse or chest are still taken.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
private const uint BurdenIntKey = 5; // STypeInt ENCUMB_VAL: an object's burden (the character's: all it carries)
|
||||
private const uint CarryCapacityAugIntKey = 230; // STypeInt AugmentationIncreasedCarryingCapacity
|
||||
private const uint StrengthAttribute = 1;
|
||||
|
||||
/// <summary>
|
||||
/// ACE's carrying capacity: 150 burden per point of current Strength, plus 30 per point for
|
||||
/// each carrying capacity augmentation (Player.GetEncumbranceCapacity).
|
||||
/// </summary>
|
||||
internal static long CarryCapacity(uint strength, int capacityAugs)
|
||||
=> 150L * strength + 30L * Math.Max(0, capacityAugs) * strength;
|
||||
|
||||
/// <summary>
|
||||
/// The server refuses this pickup for burden: what the character carries plus the item's burden
|
||||
/// is over 3 times its carrying capacity (Player.HasEnoughBurdenToAddToInventory).
|
||||
/// </summary>
|
||||
internal static bool PickupOverBurdenLimit(int carried, int itemBurden, uint strength, int capacityAugs, out long limit)
|
||||
{
|
||||
limit = 3 * CarryCapacity(strength, capacityAugs);
|
||||
return strength > 0 && itemBurden > 0 && (long)carried + itemBurden > limit;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The item can't be picked up for burden. False whenever a number isn't known (no character, no
|
||||
/// Strength, no burden on the item yet): then the server decides, as before.
|
||||
/// </summary>
|
||||
private bool LootItemOverBurden(int itemId, out string detail)
|
||||
{
|
||||
detail = "";
|
||||
try
|
||||
{
|
||||
if (_playerId == 0 || _objectCache == null || !Host.HasGetObjectIntProperty || !Host.HasGetObjectAttribute)
|
||||
return false;
|
||||
if (!Host.TryGetObjectIntProperty(_playerId, BurdenIntKey, out int carried))
|
||||
return false;
|
||||
if (!Host.TryGetObjectAttribute(_playerId, StrengthAttribute, 0, out uint strength) || strength == 0)
|
||||
return false;
|
||||
int augs = Host.TryGetObjectIntProperty(_playerId, CarryCapacityAugIntKey, out int a) ? a : 0;
|
||||
int itemBurden = _objectCache.GetIntProperty(itemId, BurdenIntKey, 0);
|
||||
if (!PickupOverBurdenLimit(carried, itemBurden, strength, augs, out long limit))
|
||||
return false;
|
||||
long capacity = CarryCapacity(strength, augs);
|
||||
long total = carried + (long)itemBurden;
|
||||
detail = $"you carry {carried} burden and it weighs {itemBurden}: {total} is {total * 100 / capacity}% of your {capacity} capacity, over the server's 300% limit of {limit}";
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private DateTime _overBurdenWarnedAt = DateTime.MinValue;
|
||||
|
||||
/// <summary>Once per 5 minutes in chat: loot is left for burden (looting goes on).</summary>
|
||||
private void WarnLootOverBurden(string itemName, string detail)
|
||||
{
|
||||
if ((RynthClock.Now - _overBurdenWarnedAt).TotalMinutes < 5) return;
|
||||
_overBurdenWarnedAt = RynthClock.Now;
|
||||
ChatLine($"[RynthAi] Too heavy to loot: '{itemName}' is left ({detail}). The server won't let a character pick up past 300% burden. " +
|
||||
"Drop, sell or salvage something heavy and looting takes it again.");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - RynthAiPlugin.LootEditorFailure.cs
|
||||
// The Loot Editor's calls into RynthAi say why they fail (2026-11-24).
|
||||
//
|
||||
// R-20261124-085015-5215 (RynthAi 2026.11.23.2 on a 2026.11.12.1 core): "loot editor not loading".
|
||||
// The editor's exports (PluginExports: RynthPluginGetLootEditJson and the rest) caught every
|
||||
// failure and said nothing, so the window opened empty and closed with no line anywhere. The cause
|
||||
// was the one TickGuard now names for the looting tick: this RynthAi was built against a newer
|
||||
// RynthCore.LootSdk than the core's Runtime\PluginShared copy (the edit session's PerDay members).
|
||||
// Now such a failure says so once every 5 minutes in chat ("install the core update in the
|
||||
// launcher"), and any other failure is logged, at most every 10 s.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
private DateTime _lootEditorFailSaidAt = DateTime.MinValue;
|
||||
private DateTime _lootEditorFailLoggedAt = DateTime.MinValue;
|
||||
|
||||
/// <summary>The chat line for a Loot Editor failure caused by an older RynthCore core, else null.</summary>
|
||||
internal static string? LootEditorNeedsCoreLine(Exception ex) =>
|
||||
TickGuard.NeedsNewerCore(ex)
|
||||
? $"[RynthAi] The Loot Editor can't load: this RynthAi needs a newer RynthCore core: install the core update in the launcher ({ex.GetType().Name}: {ex.Message})."
|
||||
: null;
|
||||
|
||||
/// <summary>A call from the engine's Loot Editor threw (PluginExports): say why, rate-limited.</summary>
|
||||
internal void NoteLootEditorFailure(Exception ex)
|
||||
{
|
||||
DateTime now = RynthClock.Now;
|
||||
if (LootEditorNeedsCoreLine(ex) is { } line)
|
||||
{
|
||||
if ((now - _lootEditorFailSaidAt).TotalMinutes < 5) return;
|
||||
_lootEditorFailSaidAt = now;
|
||||
Host.Log(line);
|
||||
try { ChatLine(line); } catch { }
|
||||
return;
|
||||
}
|
||||
if ((now - _lootEditorFailLoggedAt).TotalSeconds < 10) return;
|
||||
_lootEditorFailLoggedAt = now;
|
||||
Host.Log($"[RynthAi] A Loot Editor call failed: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - RynthAiPlugin.RechargeHold.cs
|
||||
// No recharge for now: /ra norecharge and the dashboard (2026-11-24, R-20261124-121710-7876).
|
||||
//
|
||||
// /ra norecharge all three held, or all released when any is held
|
||||
// /ra norecharge hp|stam|mana [on|off] one vital (no on/off: toggle)
|
||||
// /ra norecharge all on|off
|
||||
// The dashboard: click HP, ST or MN by its bar to hold or release that vital, right-click any of
|
||||
// them for all three; the options menu has "No recharge for now". The hold itself is
|
||||
// LegacyUi/RechargeHold.cs: the recharge lines at 0 until released, never saved.
|
||||
// ============================================================================
|
||||
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
/// <summary>The vitals whose recharge is held now.</summary>
|
||||
internal RechargeVital RechargeHeld => _dashboard?.Settings.RechargeHold.Held ?? RechargeVital.None;
|
||||
|
||||
/// <summary>Holds or releases <paramref name="vitals"/>' recharge, and says so (chat, the command's reply).</summary>
|
||||
internal bool SetRechargeHold(RechargeVital vitals, bool on)
|
||||
{
|
||||
var s = _dashboard?.Settings;
|
||||
if (s == null) return false;
|
||||
s.RechargeHold.Set(s, vitals, on);
|
||||
RechargeVital now = s.RechargeHold.Held;
|
||||
string text = on
|
||||
? $"[RynthAi] No recharge for now: {RechargeHold.Describe(vitals)} won't be recharged (their Heal At / Re-stam At / Get Mana At and top-off lines are held at 0; " +
|
||||
"Emergency Heal At still heals). Your settings are kept: click the vital on the dashboard again, or /ra norecharge, to put them back."
|
||||
: $"[RynthAi] Recharge back on for {RechargeHold.Describe(vitals)}: your settings are as they were" +
|
||||
(now != RechargeVital.None ? $" ({RechargeHold.Describe(now)} still held)." : ".");
|
||||
ReplyOk(text);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void HandleNoRechargeCommand(string[] parts)
|
||||
{
|
||||
var s = _dashboard?.Settings;
|
||||
if (s == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
|
||||
string which = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "";
|
||||
string onOff = parts.Length >= 4 ? parts[3].ToLowerInvariant() : "";
|
||||
// "/ra norecharge on|off" means all three.
|
||||
if (which is "on" or "off" or "1" or "0" or "true" or "false") { onOff = which; which = "all"; }
|
||||
RechargeVital v = which switch
|
||||
{
|
||||
"" or "all" => RechargeVital.All,
|
||||
"hp" or "health" or "heal" => RechargeVital.Health,
|
||||
"st" or "stam" or "stamina" => RechargeVital.Stamina,
|
||||
"mn" or "mana" => RechargeVital.Mana,
|
||||
_ => RechargeVital.None,
|
||||
};
|
||||
if (v == RechargeVital.None)
|
||||
{
|
||||
ReplyFail($"[RynthAi] No recharge: unknown '{which}'. Usage: /ra norecharge [hp|stam|mana|all] [on|off] (held now: {RechargeHold.Describe(s.RechargeHold.Held)}).");
|
||||
return;
|
||||
}
|
||||
bool? set = onOff switch
|
||||
{
|
||||
"" or "toggle" => null,
|
||||
"on" or "1" or "true" => true,
|
||||
"off" or "0" or "false" => false,
|
||||
_ => null,
|
||||
};
|
||||
if (onOff.Length > 0 && onOff != "toggle" && set == null)
|
||||
{
|
||||
ReplyFail($"[RynthAi] No recharge: unknown '{onOff}'. Usage: /ra norecharge [hp|stam|mana|all] [on|off].");
|
||||
return;
|
||||
}
|
||||
// A toggle: all of them held -> release; otherwise hold (for "all": any held releases all).
|
||||
bool on = set ?? (v == RechargeVital.All ? s.RechargeHold.Held == RechargeVital.None : (s.RechargeHold.Held & v) == 0);
|
||||
SetRechargeHold(v, on);
|
||||
}
|
||||
}
|
||||
425
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.TradeShop.cs
Normal file
425
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.TradeShop.cs
Normal file
|
|
@ -0,0 +1,425 @@
|
|||
// RynthAiPlugin.TradeShop.cs — the Trade Shop: a player-run shop driven by tells (Trade/TradeShopManager.cs
|
||||
// has the sale flow and its safety rules). This file wires it into RynthAi: made at login, ticked on the
|
||||
// plugin tick (TickStep.TradeShop), fed incoming tells, paused in combat / while the macro or a hunt runs /
|
||||
// while AutoTrade is on, its window (a plugin window, API v89, no bar button: the RynthAi window's options
|
||||
// menu > Trade shop and /ra tradeshop open it) and /ra tradeshop.
|
||||
// Ported from SilentKelpie's Trade Shop (RynthSuite PR #12); re-implemented here.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Plugin.RynthAi.Trade;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
/// <summary>The window's title (its panel key) and surface (Huds/SectionsManifest.cs).</summary>
|
||||
internal const string TradeShopTitle = "Trade Shop", TradeShopSurface = "window:tradeshop";
|
||||
|
||||
internal const string TradeShopUsage =
|
||||
"Usage: /ra tradeshop [on | off | status | list | add <price> [name] | remove <#> | price <#> <py> | accept | decline | "
|
||||
+ "mode1 | mode2 | confirm on|off | keys <py per key> | advertise on|off|now|channel <name>|every <minutes>|prefix <text> | show | hide | help]";
|
||||
|
||||
private TradeShopManager? _tradeShop;
|
||||
private TradeShopWindow? _tradeShopWindow; // render thread
|
||||
private int _tradeShopFailures; // render thread
|
||||
|
||||
/// <summary>The shop's settings (the profile's TradeShop), never null once settings exist.</summary>
|
||||
private TradeShopSettings? TradeShopCfg
|
||||
{
|
||||
get
|
||||
{
|
||||
var s = _dashboard?.Settings;
|
||||
if (s == null) return null;
|
||||
return s.TradeShop ??= new TradeShopSettings();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Login: the shop for this character (off until the player turns it on).</summary>
|
||||
private void CreateTradeShop()
|
||||
{
|
||||
if (_objectCache == null || _dashboard == null) return;
|
||||
var dash = _dashboard;
|
||||
var game = new TradeShopHostGame(Host, _objectCache, () => _playerId, TradeShopPauseReason,
|
||||
() => dash?.CharFolder ?? string.Empty);
|
||||
_tradeShop = new TradeShopManager(game, () => TradeShopCfg ?? new TradeShopSettings());
|
||||
}
|
||||
|
||||
/// <summary>Why the shop must not trade now, or "" (plugin tick).</summary>
|
||||
internal string TradeShopPauseReason()
|
||||
{
|
||||
var s = _dashboard?.Settings;
|
||||
if (s == null) return "not ready";
|
||||
if (s.IsMacroRunning) return "the macro is running";
|
||||
if (HuntActive || _dunPatrolActive) return "a hunt is running";
|
||||
if (s.AutoTradeEnabled) return "AutoTrade is on (it would fill the same trade window)";
|
||||
int mode = _combatManager?.CurrentCombatMode ?? CombatMode.NonCombat;
|
||||
if (mode != CombatMode.NonCombat) return "in combat mode";
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The plugin tick: true while a sale holds the bot (inventory chores wait).</summary>
|
||||
private bool TickTradeShop()
|
||||
{
|
||||
var shop = _tradeShop;
|
||||
if (shop == null) return false;
|
||||
shop.Tick();
|
||||
return shop.HoldsBot;
|
||||
}
|
||||
|
||||
/// <summary>Chat thread: a line in the chat window (only incoming tells matter).</summary>
|
||||
private void TradeShopChat(string text, int chatType)
|
||||
{
|
||||
try { _tradeShop?.OnTell(text, chatType == RynthCore.Plugin.Shared.ChatSource.Tell); }
|
||||
catch (Exception ex) { Host.Log($"[RynthAi] TradeShop chat failed: {ex.Message}"); }
|
||||
}
|
||||
|
||||
// ── /ra tradeshop ────────────────────────────────────────────────────
|
||||
|
||||
private void HandleTradeShopRaCommand(string[] parts)
|
||||
{
|
||||
string verb = parts.Length > 2 ? parts[2].ToLowerInvariant() : "";
|
||||
string rest = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3).Trim() : string.Empty;
|
||||
TradeShopSettings? cfg = TradeShopCfg;
|
||||
TradeShopManager? shop = _tradeShop;
|
||||
if (cfg == null || shop == null)
|
||||
{
|
||||
ReplyFail("[RynthAi] Trade Shop: not ready yet (log in first). " + TradeShopUsage);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (verb)
|
||||
{
|
||||
case "":
|
||||
case "show":
|
||||
case "open":
|
||||
case "window":
|
||||
case "ui":
|
||||
ReplyOk("[RynthAi] Trade Shop: " + shop.Status + TradeShopWindowNote(RynthPanelOpen.Open));
|
||||
return;
|
||||
case "hide":
|
||||
case "close":
|
||||
{
|
||||
if (!Host.HasSetPanelOpen) { ReplyFail("[RynthAi] Trade Shop: this RynthCore has no plugin windows (plugin API 89+). " + TradeShopUsage); return; }
|
||||
int open = Host.SetPanelOpen(TradeShopTitle, RynthPanelOpen.Close);
|
||||
if (open < 0) ReplyFail("[RynthAi] The Trade Shop window isn't there yet (RynthCore adds it a few seconds after login).");
|
||||
else ReplyOk("[RynthAi] Trade Shop window closed.");
|
||||
return;
|
||||
}
|
||||
case "status":
|
||||
ChatLine($"[RynthAi] Trade Shop: {(cfg.Enabled ? "ON" : "OFF")}, {(cfg.Mode == TradeShopMode.Mode1Stock ? "Mode 1 (my packs)" : "Mode 2 (text, I accept by hand)")}, "
|
||||
+ $"confirm each sale {(cfg.ConfirmEachSale ? "ON" : "OFF")}, {cfg.ForSale().Count} for sale, "
|
||||
+ (cfg.AdvertiseEnabled ? $"advertising on {TradeShopAdvertise.DisplayName(cfg.AdvertiseChannel)} every {TradeShopSettings.ClampAdvertiseSec(cfg.AdvertiseIntervalSec) / 60} min." : "advertising off."));
|
||||
ChatLine("[RynthAi] " + shop.Status);
|
||||
if (shop.Prompt is { } p)
|
||||
ChatLine($"[RynthAi] Sale ready: {p.Buyer}, {p.Item}, {TradeShopRates.N(p.PricePyreals)} py, paid {p.Paid}. /ra tradeshop accept | decline");
|
||||
return;
|
||||
case "on":
|
||||
case "enable":
|
||||
Reply.Answered(); // the shop says what it does on the tick
|
||||
shop.SetEnabled(true);
|
||||
return;
|
||||
case "off":
|
||||
case "disable":
|
||||
Reply.Answered();
|
||||
shop.SetEnabled(false);
|
||||
return;
|
||||
case "accept":
|
||||
if (shop.Prompt == null) { ReplyFail("[RynthAi] Trade Shop: no sale is waiting for your accept."); return; }
|
||||
ReplyOk("[RynthAi] Trade Shop: checking the trade again before accepting...");
|
||||
shop.RequestAccept();
|
||||
return;
|
||||
case "decline":
|
||||
Reply.Answered(); // the shop says what it called off on the tick
|
||||
shop.RequestDecline();
|
||||
return;
|
||||
case "mode1":
|
||||
case "stock":
|
||||
cfg.Mode = TradeShopMode.Mode1Stock;
|
||||
ScheduleDashSave();
|
||||
ReplyOk("[RynthAi] Trade Shop: Mode 1 (items in this character's packs; the shop puts the item in the trade window).");
|
||||
return;
|
||||
case "mode2":
|
||||
case "text":
|
||||
cfg.Mode = TradeShopMode.Mode2Text;
|
||||
ScheduleDashSave();
|
||||
ReplyOk("[RynthAi] Trade Shop: Mode 2 (text listings; the shop checks the payment and you accept every sale by hand).");
|
||||
return;
|
||||
case "confirm":
|
||||
{
|
||||
bool? on = OnOff(rest);
|
||||
if (on == null) { ReplyFail($"[RynthAi] Trade Shop: confirm each sale is {(cfg.ConfirmEachSale ? "ON" : "OFF")}. Usage: /ra tradeshop confirm on|off"); return; }
|
||||
Reply.Answered(); // the shop says it (and warns when off) on the tick
|
||||
shop.SetConfirmEachSale(on.Value);
|
||||
ScheduleDashSave();
|
||||
return;
|
||||
}
|
||||
case "list":
|
||||
ListTradeShop(cfg);
|
||||
return;
|
||||
case "add":
|
||||
AddTradeShopListing(cfg, rest);
|
||||
return;
|
||||
case "remove":
|
||||
case "del":
|
||||
RemoveTradeShopListing(cfg, rest);
|
||||
return;
|
||||
case "price":
|
||||
PriceTradeShopListing(cfg, rest);
|
||||
return;
|
||||
case "keys":
|
||||
case "lk":
|
||||
{
|
||||
if (!TryParsePyreals(rest, out long py) || py < 0) { ReplyFail("[RynthAi] Usage: /ra tradeshop keys <pyreals per Legendary Key> (0 = keys not taken)"); return; }
|
||||
cfg.Rates.PyrealsPerLegendaryKey = py;
|
||||
cfg.Rates.AcceptLegendaryKeys = py > 0;
|
||||
ScheduleDashSave();
|
||||
ReplyOk("[RynthAi] Trade Shop: " + cfg.Rates.RatesHelpLine());
|
||||
return;
|
||||
}
|
||||
case "rates":
|
||||
ReplyOk("[RynthAi] Trade Shop: " + cfg.Rates.RatesHelpLine());
|
||||
return;
|
||||
case "advertise":
|
||||
case "ad":
|
||||
HandleTradeShopAdvertise(cfg, shop, rest);
|
||||
return;
|
||||
case "help":
|
||||
case "?":
|
||||
ChatLine("[RynthAi] /ra tradeshop — a shop run from tells (!list, !price, !buy); opens the Trade Shop window.");
|
||||
ChatLine("[RynthAi] " + TradeShopUsage);
|
||||
return;
|
||||
default:
|
||||
ReplyFail($"[RynthAi] Trade Shop: unknown option '{verb}'. {TradeShopUsage}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleTradeShopAdvertise(TradeShopSettings cfg, TradeShopManager shop, string rest)
|
||||
{
|
||||
string[] bits = rest.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
|
||||
string v = bits.Length > 0 ? bits[0].ToLowerInvariant() : "";
|
||||
string arg = bits.Length > 1 ? bits[1].Trim() : "";
|
||||
switch (v)
|
||||
{
|
||||
case "":
|
||||
case "status":
|
||||
ReplyOk(cfg.AdvertiseEnabled
|
||||
? $"[RynthAi] Trade Shop advertising ON: {TradeShopAdvertise.DisplayName(cfg.AdvertiseChannel)} every {TradeShopSettings.ClampAdvertiseSec(cfg.AdvertiseIntervalSec) / 60} min (while the shop is on)."
|
||||
: "[RynthAi] Trade Shop advertising OFF. /ra tradeshop advertise on|off|now|channel <name>|every <minutes>|prefix <text>");
|
||||
return;
|
||||
case "on":
|
||||
cfg.AdvertiseEnabled = true;
|
||||
ScheduleDashSave();
|
||||
ReplyOk($"[RynthAi] Trade Shop advertising ON: {TradeShopAdvertise.DisplayName(cfg.AdvertiseChannel)} every {TradeShopSettings.ClampAdvertiseSec(cfg.AdvertiseIntervalSec) / 60} min, while the shop is on.");
|
||||
return;
|
||||
case "off":
|
||||
cfg.AdvertiseEnabled = false;
|
||||
ScheduleDashSave();
|
||||
ReplyOk("[RynthAi] Trade Shop advertising OFF.");
|
||||
return;
|
||||
case "now":
|
||||
Reply.Answered(); // the shop says whether it went on the tick
|
||||
shop.RequestAdvertise();
|
||||
return;
|
||||
case "channel":
|
||||
if (!TradeShopAdvertise.TryParseChannel(arg, out TradeShopAdvertiseChannel ch))
|
||||
{
|
||||
ReplyFail("[RynthAi] Channels: Trade, General, LFG, Roleplay, Society, Local.");
|
||||
return;
|
||||
}
|
||||
cfg.AdvertiseChannel = ch;
|
||||
ScheduleDashSave();
|
||||
ReplyOk($"[RynthAi] Trade Shop advertises on {TradeShopAdvertise.DisplayName(ch)}.");
|
||||
return;
|
||||
case "every":
|
||||
case "interval":
|
||||
if (!int.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out int min))
|
||||
{
|
||||
ReplyFail($"[RynthAi] Usage: /ra tradeshop advertise every <minutes> ({TradeShopSettings.MinAdvertiseSec / 60}-{TradeShopSettings.MaxAdvertiseSec / 60}).");
|
||||
return;
|
||||
}
|
||||
cfg.AdvertiseIntervalSec = TradeShopSettings.ClampAdvertiseSec(min * 60);
|
||||
ScheduleDashSave();
|
||||
ReplyOk($"[RynthAi] Trade Shop advertises every {cfg.AdvertiseIntervalSec / 60} min.");
|
||||
return;
|
||||
case "prefix":
|
||||
cfg.AdvertisePrefix = arg.TrimStart('/', '@');
|
||||
ScheduleDashSave();
|
||||
ReplyOk(cfg.AdvertisePrefix.Length > 0 ? $"[RynthAi] Trade Shop adverts start with \"{cfg.AdvertisePrefix}\"." : "[RynthAi] Trade Shop advert prefix cleared.");
|
||||
return;
|
||||
default:
|
||||
ReplyFail("[RynthAi] Usage: /ra tradeshop advertise on|off|now|channel <name>|every <minutes>|prefix <text>");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void ListTradeShop(TradeShopSettings cfg)
|
||||
{
|
||||
List<TradeShopListing> rows;
|
||||
lock (cfg.Sync) rows = new List<TradeShopListing>(cfg.Listings ?? new List<TradeShopListing>());
|
||||
if (rows.Count == 0) { ChatLine("[RynthAi] Trade Shop: nothing listed. /ra tradeshop add <price> lists the selected item."); return; }
|
||||
ChatLine($"[RynthAi] Trade Shop ({rows.Count} listed):");
|
||||
for (int i = 0; i < rows.Count; i++)
|
||||
{
|
||||
TradeShopListing l = rows[i];
|
||||
ChatLine($"[RynthAi] #{i + 1} {l.Label()} — {cfg.Rates.FormatAlternatives(l.PricePyreals)}{(l.Enabled ? "" : " [not for sale]")}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"/ra tradeshop add <price> [name]": the selected item (Mode 1), or a typed listing (a name given).</summary>
|
||||
private void AddTradeShopListing(TradeShopSettings cfg, string rest)
|
||||
{
|
||||
string[] bits = rest.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (bits.Length == 0 || !TryParsePyreals(bits[0], out long price) || price <= 0)
|
||||
{
|
||||
ReplyFail("[RynthAi] Usage: /ra tradeshop add <price in pyreals> [name] (no name: the item selected in your inventory)");
|
||||
return;
|
||||
}
|
||||
string name = bits.Length > 1 ? bits[1].Trim() : "";
|
||||
if (name.Length > 0)
|
||||
{
|
||||
lock (cfg.Sync) (cfg.Listings ??= new List<TradeShopListing>()).Add(new TradeShopListing { Name = name, PricePyreals = price, Enabled = true });
|
||||
ScheduleDashSave();
|
||||
ReplyOk($"[RynthAi] Trade Shop: listed {name} at {TradeShopRates.N(price)} py (a text listing; Mode 1 sells only items picked from your inventory).");
|
||||
return;
|
||||
}
|
||||
// The packs are read on the plugin tick; the answer comes from there.
|
||||
Reply.Answered();
|
||||
QueueDashAction(() =>
|
||||
{
|
||||
string? fail = AddSelectedTradeShopItem(cfg, price, out string added);
|
||||
ChatLine("[RynthAi] Trade Shop: " + (fail ?? added));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Lists the selected inventory item at <paramref name="price"/>; null when done, else why not.</summary>
|
||||
private string? AddSelectedTradeShopItem(TradeShopSettings cfg, long price, out string added)
|
||||
{
|
||||
added = "";
|
||||
if (!Host.HasGetSelectedItemId) return "this RynthCore can't read the selected item.";
|
||||
uint sel = Host.GetSelectedItemId();
|
||||
if (sel == 0) return "select an item in your inventory first.";
|
||||
if (!Host.HasGetObjectWcid || !Host.TryGetObjectWcid(sel, out uint wcid) || wcid == 0) return "the selected item can't be read yet; try again.";
|
||||
WorldObject? wo = _objectCache?[unchecked((int)sel)];
|
||||
bool mine = _objectCache?.GetDirectInventory(forceRefresh: true).Any(o => o != null && unchecked((uint)o.Id) == sel) == true;
|
||||
if (wo == null || !mine) return "the selected item isn't in your packs.";
|
||||
if (wo.WieldedLocation > 0 || wo.Values(LongValueKey.EquippedSlots, 0) > 0) return "that item is equipped; unequip it to sell it.";
|
||||
int stack = Host.TryGetObjectIntProperty(sel, 12, out int s) && s > 0 ? s : 0;
|
||||
string name = string.IsNullOrWhiteSpace(wo.Name) ? (Host.TryGetObjectName(sel, out string n) ? n : "") : wo.Name;
|
||||
if (string.IsNullOrWhiteSpace(name)) return "the selected item has no name yet; try again.";
|
||||
var row = new TradeShopListing { Name = name.Trim(), PricePyreals = price, ObjectId = sel, Wcid = wcid, Stack = stack > 1 ? stack : 0, Enabled = true };
|
||||
lock (cfg.Sync)
|
||||
{
|
||||
cfg.Listings ??= new List<TradeShopListing>();
|
||||
if (cfg.Listings.Any(l => l != null && l.ObjectId == sel)) return $"{row.Label()} is already listed.";
|
||||
cfg.Listings.Add(row);
|
||||
}
|
||||
ScheduleDashSave();
|
||||
added = $"listed {row.Label()} at {cfg.Rates.FormatAlternatives(price)}.";
|
||||
return null;
|
||||
}
|
||||
|
||||
private void RemoveTradeShopListing(TradeShopSettings cfg, string rest)
|
||||
{
|
||||
if (!int.TryParse(rest.TrimStart('#'), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) || n < 1)
|
||||
{
|
||||
ReplyFail("[RynthAi] Usage: /ra tradeshop remove <#> (the number in /ra tradeshop list)");
|
||||
return;
|
||||
}
|
||||
TradeShopListing? gone = null;
|
||||
lock (cfg.Sync)
|
||||
{
|
||||
if (cfg.Listings != null && n <= cfg.Listings.Count) { gone = cfg.Listings[n - 1]; cfg.Listings.RemoveAt(n - 1); }
|
||||
}
|
||||
if (gone == null) { ReplyFail($"[RynthAi] Trade Shop: there is no #{n} (/ra tradeshop list)."); return; }
|
||||
ScheduleDashSave();
|
||||
ReplyOk($"[RynthAi] Trade Shop: removed #{n} {gone.Label()}.");
|
||||
}
|
||||
|
||||
private void PriceTradeShopListing(TradeShopSettings cfg, string rest)
|
||||
{
|
||||
string[] bits = rest.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (bits.Length != 2 || !int.TryParse(bits[0].TrimStart('#'), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) || n < 1
|
||||
|| !TryParsePyreals(bits[1], out long price) || price <= 0)
|
||||
{
|
||||
ReplyFail("[RynthAi] Usage: /ra tradeshop price <#> <pyreals>");
|
||||
return;
|
||||
}
|
||||
TradeShopListing? row = null;
|
||||
lock (cfg.Sync)
|
||||
{
|
||||
if (cfg.Listings != null && n <= cfg.Listings.Count) { row = cfg.Listings[n - 1]; row.PricePyreals = price; }
|
||||
}
|
||||
if (row == null) { ReplyFail($"[RynthAi] Trade Shop: there is no #{n} (/ra tradeshop list)."); return; }
|
||||
ScheduleDashSave();
|
||||
ReplyOk($"[RynthAi] Trade Shop: #{n} {row.Label()} now {cfg.Rates.FormatAlternatives(price)}.");
|
||||
}
|
||||
|
||||
private static bool TryParsePyreals(string text, out long py)
|
||||
=> long.TryParse((text ?? "").Replace(",", "").Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out py);
|
||||
|
||||
private static bool? OnOff(string text) => (text ?? "").Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"on" or "1" or "true" or "yes" => true,
|
||||
"off" or "0" or "false" or "no" => false,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
// ── Window ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The window goes in the sections manifest on an engine with plugin windows (v89).</summary>
|
||||
private bool TradeShopWindowWanted => Host.HasUiTheme && Host.HasSetPanelOpen;
|
||||
|
||||
/// <summary>" (window open)", or why it can't open.</summary>
|
||||
private string TradeShopWindowNote(RynthPanelOpen mode)
|
||||
{
|
||||
if (!Host.HasSetPanelOpen) return " (the window needs RynthCore with plugin windows; /ra tradeshop help for the commands)";
|
||||
int open = Host.SetPanelOpen(TradeShopTitle, mode);
|
||||
return open < 0 ? " (the window isn't there yet: RynthCore adds it a few seconds after login)"
|
||||
: open == 1 ? " (Trade Shop window open)" : " (Trade Shop window closed)";
|
||||
}
|
||||
|
||||
/// <summary>The RynthAi window's ⋯ > Trade shop: the window open or closed. Any thread.</summary>
|
||||
internal void ToggleTradeShopWindow()
|
||||
{
|
||||
if (Host.HasSetPanelOpen) Host.SetPanelOpen(TradeShopTitle, RynthPanelOpen.Toggle);
|
||||
}
|
||||
|
||||
/// <summary>RynthPluginRenderEmbed "window:tradeshop": 1 drawn, 0 not ready, -2 failed (three draws in a row threw).</summary>
|
||||
internal int RenderTradeShop(bool popped, out Vector2 want)
|
||||
{
|
||||
want = default;
|
||||
if (!_initialized || Host.ImGuiContext == IntPtr.Zero) return 0;
|
||||
IntPtr previous = ImGui.GetCurrentContext();
|
||||
ImGui.SetCurrentContext(EmbedContext());
|
||||
try
|
||||
{
|
||||
_tradeShopWindow ??= new TradeShopWindow(() => TradeShopCfg, () => _tradeShop,
|
||||
price => QueueDashAction(() =>
|
||||
{
|
||||
TradeShopSettings? cfg = TradeShopCfg;
|
||||
if (cfg == null) return;
|
||||
string? fail = AddSelectedTradeShopItem(cfg, price, out string added);
|
||||
ChatLine("[RynthAi] Trade Shop: " + (fail ?? added));
|
||||
}),
|
||||
() => QueueDashAction(ScheduleDashSave));
|
||||
want = _tradeShopWindow.Draw();
|
||||
_tradeShopFailures = 0;
|
||||
return 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Exception(LogCat.UI, ex, "RenderTradeShop");
|
||||
return ++_tradeShopFailures >= 3 ? -2 : 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGui.SetCurrentContext(previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,7 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
// /ra testitem TestItem the selected item against the loot profile
|
||||
// /ra propertydump [0xId] PropertyDump every property of the selection (/ra dumpprops)
|
||||
// /ra recharge Recharge one vitals pass with the Top Off lines
|
||||
// /ra norecharge [hp|stam|mana|all] [on|off] no recharge for now (RynthAiPlugin.RechargeHold.cs)
|
||||
// /ra heal | stam | mana One-touch heal the best kit / spell / potion for that vital now (RynthCore's One-touch hotkeys)
|
||||
// /ra navprio|lootprio|navlootprio [on|off] Boost Nav / Boost Loot Priority (no argument: toggle)
|
||||
// /ra lootthis LootThisCont loot the open corpse or chest now
|
||||
|
|
@ -69,6 +70,8 @@ public sealed partial class RynthAiPlugin
|
|||
case "testitem": HandleLootCheckSelectedCommand(new[] { "/ra", "lootcheck" }); return true;
|
||||
case "propertydump": HandleDumpPropsCommand(parts); return true;
|
||||
case "recharge": HandleRechargeCommand(); return true;
|
||||
case "norecharge":
|
||||
case "rechargehold": HandleNoRechargeCommand(parts); return true;
|
||||
case "heal":
|
||||
case "healme":
|
||||
case "onetouchheal": HandleOneTouchCommand(OneTouchVital.Health); return true;
|
||||
|
|
@ -97,6 +100,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra testitem - check the selected item against the loot profile");
|
||||
ChatLine("[RynthAi] /ra propertydump [0xId] - every property of the selected object");
|
||||
ChatLine("[RynthAi] /ra recharge - one heal / stamina / mana top-off with the Top Off lines, macro on or off");
|
||||
ChatLine("[RynthAi] /ra norecharge [hp|stam|mana|all] [on|off] - no recharge for now: hold those vitals' recharge (settings kept; toggle)");
|
||||
ChatLine("[RynthAi] /ra heal | stam | mana - one touch: the best kit, spell or potion for that vital now, whatever the lines say");
|
||||
ChatLine("[RynthAi] /ra navprio | lootprio | navlootprio [on|off] - Boost Nav / Boost Loot Priority (toggle)");
|
||||
ChatLine("[RynthAi] /ra lootthis - loot the open corpse or chest now (never house storage or your own packs)");
|
||||
|
|
|
|||
|
|
@ -80,6 +80,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
private NavMarkerRenderer? _navMarkerRenderer;
|
||||
private RadarWallRenderer? _radarWallRenderer;
|
||||
private TerrainPassabilityOverlay? _terrainOverlay;
|
||||
private LosLineOverlay? _losLineOverlay; // Show Line of Sight (ShowLosLine, /ra losline)
|
||||
private MainLogic? _raycast;
|
||||
// The session's _raycast once its background init has finished (null until then), and the
|
||||
// gate both the init thread and the session setup take to hand it to the CombatManager.
|
||||
|
|
@ -315,6 +316,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
try { _sessionStats?.Shutdown(); } catch { }
|
||||
try { ShutdownMonsterStats(); } catch { } // kept for the next copy, with the session
|
||||
try { SaveTimedCommands(); } catch { } // an edit made just before the unload
|
||||
try { SaveCommandButtons(); } catch { } // the same for the Command Buttons
|
||||
try { GameInput.Shutdown(); } catch { } // keys still held for /mt movement | jump | strafe
|
||||
// Release the Monster Editor process handle (if the toggle button
|
||||
// launched one) rather than leaking it on plugin unload/hot-reload.
|
||||
|
|
@ -374,6 +376,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
try { _sessionStats?.OnLogout(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats logout"); }
|
||||
try { OnLogoutMonsterStats(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats logout"); }
|
||||
try { OnLogoutTimedCommands(); } catch (Exception ex) { RynthLog.Exception(LogCat.Commands, ex, "timed commands logout"); }
|
||||
try { OnLogoutCommandButtons(); } catch (Exception ex) { RynthLog.Exception(LogCat.Commands, ex, "command buttons logout"); }
|
||||
Loot.T11ItemSupport.Reset();
|
||||
_boostNavNoticeSaid = false; // the Boost Nav Priority notice: once per session
|
||||
// A real logout: the next OnLoginComplete is a fresh login, not a hot reload.
|
||||
|
|
@ -488,6 +491,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// The dungeon cell graph is a static single-landblock cache; nothing may outlive the session.
|
||||
DungeonPathfinder.InvalidateCache();
|
||||
_navMarkerRenderer = null;
|
||||
_losLineOverlay = null;
|
||||
long tFlush0 = Environment.TickCount64;
|
||||
_radarWallRenderer?.Flush();
|
||||
long tFlushMs = Environment.TickCount64 - tFlush0;
|
||||
|
|
@ -522,6 +526,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_aetheriaUnboxer?.Reset();
|
||||
_aetheriaUnboxer = null;
|
||||
ResetKitTracking(); // Make kits when low (RynthAiPlugin.Kits.cs)
|
||||
ResetAmmoTracking(); // Make ammo when low (RynthAiPlugin.Ammo.cs)
|
||||
_manaStoneManager = null;
|
||||
_petManager = null;
|
||||
_buffManager?.Dispose();
|
||||
|
|
@ -534,6 +539,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_autoVendor = null;
|
||||
_autoTrade?.Reset();
|
||||
_autoTrade = null;
|
||||
_tradeShop?.Reset();
|
||||
_tradeShop = null;
|
||||
TeardownLocalFeatures(disposeTranslator: false);
|
||||
_playerId = 0;
|
||||
_loginComplete = false;
|
||||
|
|
@ -649,6 +656,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
CreateNavOverlay();
|
||||
_radarWallRenderer = new RadarWallRenderer(Host, _dashboard.Settings);
|
||||
_terrainOverlay = new TerrainPassabilityOverlay(Host);
|
||||
_losLineOverlay = new LosLineOverlay(Host, () => _dashboard?.Settings, () => _combatManager);
|
||||
Log($"RynthAi: NavMarkerRenderer created, HasNav3D={Host.HasNav3D}, version={Host.Version}");
|
||||
|
||||
// Init raycast on background thread — .dat parsing takes ~700ms and blocks the client
|
||||
|
|
@ -821,6 +829,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
{
|
||||
_buffManager.OffhandStowed = id => _combatManager?.NoteOffhandStowed(id);
|
||||
_buffManager.IdleForTopOff = IdleForBuffTopOff; // Rebuff When Idle's early top-off (RynthAiPlugin.Chores.cs)
|
||||
_buffManager.BoostLootHealsToTopOff = BoostLootHealsToTopOff; // Boost Loot heals at Top Off HP (RynthAiPlugin.BoostLootFirst.cs)
|
||||
}
|
||||
_combatManager.SetCharacterSkills(_charSkills);
|
||||
_combatManager.SetPlayerId(_playerId);
|
||||
|
|
@ -841,6 +850,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_missileCraftingManager.HoldWhile = () => _combatManager?.AmmoSwapInProgress == true;
|
||||
_missileCraftingManager.FightIsOn = () => FightIsOn(); // optional crafts wait for the fight (RynthAiPlugin.Chores.cs)
|
||||
_combatManager.AmmoWieldedElsewhereAt = () => _missileCraftingManager?.LastAmmoEquipAt ?? DateTime.MinValue; // no second wield on top of crafting's
|
||||
WireAmmoTopOff(_missileCraftingManager); // Make ammo when low (RynthAiPlugin.Ammo.cs)
|
||||
_dashboard.SetMissileCraftingManager(_missileCraftingManager);
|
||||
|
||||
_fellowshipTracker?.Dispose();
|
||||
|
|
@ -875,6 +885,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
if (_objectCache != null)
|
||||
{
|
||||
_inventoryManager = new InventoryManager(Host, _dashboard.Settings, _objectCache);
|
||||
_inventoryManager.KeepsPacksWithoutMacro = () => _chestKey?.Running == true; // the Item Tool's chest looter, macro on or off
|
||||
_manaStoneManager = new ManaStoneManager(Host, _dashboard.Settings, _objectCache);
|
||||
LegacyUi.NavPoint.SpellNameLookup = id => SpellTableStub.GetById(id)?.Name; // recall steps by name
|
||||
_manaStoneManager.IsLootKept = IsKeptByLootProfile;
|
||||
|
|
@ -922,6 +933,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
() => dashForAv?.CharFolder ?? string.Empty);
|
||||
var atForUi = _autoTrade;
|
||||
_dashboard.SetAutoTradeStatusProvider(() => atForUi.Status);
|
||||
|
||||
// The Trade Shop (RynthAiPlugin.TradeShop.cs): off until the player turns it on.
|
||||
CreateTradeShop();
|
||||
}
|
||||
|
||||
Log("RynthAi: login complete, legacy ImGui dashboard ready.");
|
||||
|
|
@ -1713,6 +1727,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
Guard(TickStep.GiveQueue, DrainGiveQueue);
|
||||
Guard(TickStep.ItemTool, TickItemTool); // the Item Tool: chest looter + Quick give (RynthAiPlugin.ItemTool.cs)
|
||||
Guard(TickStep.TimedCommands, TickTimedCommands); // commands every N seconds (RynthAiPlugin.TimedCommands.cs)
|
||||
Guard(TickStep.CommandButtons, TickCommandButtons); // the Command Buttons lists (RynthAiPlugin.CommandButtons.cs)
|
||||
if (diag) Host.Log("[RynthAi] OnTick: after drain give queue");
|
||||
Guard(TickStep.Jumper, () => _jumper?.Tick());
|
||||
if (diag) Host.Log("[RynthAi] OnTick: after jumper tick");
|
||||
|
|
@ -2029,6 +2044,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// After the decision, ahead of every hold below (buffing above all), so a monster, a
|
||||
// heal or a fight ends a kit run on this tick (RynthAiPlugin.Kits.cs).
|
||||
Guard(TickStep.AutoKits, () => CheckAutoKitsDanger(settings));
|
||||
// The same for a Make ammo when low top-off (RynthAiPlugin.Ammo.cs), on the notes just taken.
|
||||
Guard(TickStep.AutoAmmo, () => CheckAutoAmmoDanger(settings));
|
||||
|
||||
// ── Travel back to your corpse (TravelToOwnCorpse) ─────────────────
|
||||
// After the decision, ahead of every early return below: RynthNav walks only
|
||||
|
|
@ -2090,6 +2107,17 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
return;
|
||||
}
|
||||
|
||||
// ── Trade Shop (a player-run shop) ───────────────────────────────
|
||||
// Only trades with the macro off and no hunt running (it pauses itself otherwise).
|
||||
// While a sale is under way inventory chores wait, as for AutoTrade.
|
||||
if (_tradeShop != null && GuardHold(TickStep.TradeShop, TickTradeShop))
|
||||
{
|
||||
KeepThreatScanFresh(settings);
|
||||
FreezeCorpseTimeout(CorpseNowMs);
|
||||
ThinkMeta();
|
||||
return;
|
||||
}
|
||||
|
||||
Guard(TickStep.WeaponElements, TickWeaponElements);
|
||||
|
||||
// ── Priority 1: Buffing ───────────────────────────────────────────
|
||||
|
|
@ -2128,6 +2156,20 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
return;
|
||||
}
|
||||
|
||||
// Make ammo when low (RynthAiPlugin.Ammo.cs): the same hold while a top-off gets ready or
|
||||
// goes, ahead of crafting's empty-slot path. Make ammo now also runs with the macro off
|
||||
// (then nothing below moves the character anyway).
|
||||
if (inventorySettled
|
||||
&& GuardHold(TickStep.AutoAmmo, () => TickAutoAmmo(settings))
|
||||
&& settings.IsMacroRunning)
|
||||
{
|
||||
StopNavFor(BotActivity.Idle);
|
||||
KeepThreatScanFresh(settings);
|
||||
FreezeCorpseTimeout(CorpseNowMs); // a claimed corpse must not time out while held
|
||||
ThinkMeta();
|
||||
return;
|
||||
}
|
||||
|
||||
if (inventorySettled)
|
||||
TickCramStack(settings);
|
||||
|
||||
|
|
@ -2306,6 +2348,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// (Buffing / missile-crafting / BoostNavPriority branches).
|
||||
if (Host.HasNav3D)
|
||||
{
|
||||
_losLineOverlay?.Submit(); // first: the route's lines can't crowd it out
|
||||
_navMarkerRenderer?.SubmitNav3D();
|
||||
_navOverlay?.SubmitNav3D();
|
||||
}
|
||||
|
|
@ -2592,6 +2635,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_aetheriaUnboxer?.OnChat(text);
|
||||
_metaManager?.HandleChat(text, chatType);
|
||||
_questTracker?.OnChatLine(text);
|
||||
TradeShopChat(text, chatType); // incoming tells to the Trade Shop (RynthAiPlugin.TradeShop.cs)
|
||||
CheckChatForSafetyStops(text);
|
||||
try { OnOwnCorpseChat(text); } catch { }
|
||||
}
|
||||
|
|
@ -4090,6 +4134,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
case "offhand": HandleOffhandCommand(parts); break;
|
||||
case "raycast": HandleRaycastCommand(parts); break;
|
||||
case "lostest": HandleLosTestCommand(parts); break;
|
||||
case "losline": HandleLosLineCommand(parts); break;
|
||||
case "landtest": HandleLandTestCommand(); break;
|
||||
case "rayland": HandleRaylandCommand(); break;
|
||||
case "cast": HandleCastCommand(parts); break;
|
||||
|
|
@ -4205,10 +4250,14 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
case "mstats": HandleMonsterStatsCommand(parts); break; // RynthAiPlugin.MonsterStats.cs
|
||||
case "gear": HandleGearCommand(parts); break; // RynthAiPlugin.ActiveGear.cs
|
||||
case "timed": HandleTimedCommand(parts); break; // RynthAiPlugin.TimedCommands.cs
|
||||
case "button":
|
||||
case "buttons": HandleButtonsCommand(parts); break; // RynthAiPlugin.CommandButtons.cs
|
||||
case "find": HandleFindCommand(parts); break; // RynthAiPlugin.FeatureSearch.cs
|
||||
case "acmaps": HandleAcMapsCommand(parts); break; // RynthAiPlugin.AcMaps.cs
|
||||
case "aetheria": HandleAetheriaCommand(parts); break; // RynthAiPlugin.Aetheria.cs
|
||||
case "autoconfirm": HandleAutoConfirmCommand(parts); break; // RynthAiPlugin.AutoConfirm.cs
|
||||
case "kits": HandleKitsCommand(parts); break; // RynthAiPlugin.Kits.cs
|
||||
case "ammo": HandleAmmoCommand(parts); break; // RynthAiPlugin.Ammo.cs
|
||||
case "petelement": HandlePetElementCommand(parts); break; // RynthAiPlugin.PetElement.cs
|
||||
case "why": HandleWhyCommand(); break;
|
||||
case "ghost":
|
||||
|
|
@ -4249,6 +4298,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// /ra equipfor <monster>: VTank's /vt equipitemsfor (MagToolsCommands.Extra.cs)
|
||||
case "equipfor": HandleEquipForCommand(parts); break;
|
||||
case "autotrade": HandleAutoTradeRaCommand(parts); break;
|
||||
case "tradeshop": HandleTradeShopRaCommand(parts); break;
|
||||
case "trade": HandleTradeCommand(parts); break;
|
||||
case "busyinfo": HandleBusyInfoCommand(); break;
|
||||
// /ra quit | /ra exit: close the client (the engine's /rc quit: as its close button)
|
||||
|
|
|
|||
|
|
@ -919,6 +919,56 @@ internal sealed class AutoTradeManager
|
|||
|
||||
private static bool IsKeepAction(VTankLootAction a) => a is VTankLootAction.Keep or VTankLootAction.KeepUpTo;
|
||||
|
||||
// ── Read only, for other plugins (RynthAi.Hub TradeGives) ────────────────
|
||||
|
||||
private VTankLootProfile? _askProfile;
|
||||
private string _askPath = string.Empty;
|
||||
private DateTime _askTime;
|
||||
|
||||
/// <summary>
|
||||
/// Read only (RynthAi.Hub TradeGives, RynthSort's Mule packs): whether AutoTrade would add each item
|
||||
/// when a trade opens with <paramref name="partner"/>: the profile it would load for them
|
||||
/// (<partner>.utl, else default.utl, character, server, main folder), a Keep or Keep # rule
|
||||
/// that matches, and its safety checks (identified, not equipped, not on RynthAi's item lists, not
|
||||
/// attuned, retained, a container, a focus, tinkered, imbued or inscribed). Keep # counts are a
|
||||
/// trade's own business and aren't applied. Changes nothing: its own copy of the profile, no chat.
|
||||
/// False with <paramref name="error"/> when there is no profile. Pump thread.
|
||||
/// </summary>
|
||||
public bool WouldGive(string partner, uint[] ids, byte[] gives, out string profileFile, out string? error)
|
||||
{
|
||||
Array.Clear(gives);
|
||||
error = null;
|
||||
string name = string.IsNullOrWhiteSpace(partner) ? "default.utl" : partner.Trim() + ".utl";
|
||||
string path = GetProfilePath(name);
|
||||
profileFile = Path.GetFileName(path);
|
||||
if (!File.Exists(path)) { error = "AutoTrade has no " + name + " or default.utl profile"; return false; }
|
||||
try
|
||||
{
|
||||
DateTime t = File.GetLastWriteTimeUtc(path);
|
||||
if (_askProfile == null || !string.Equals(_askPath, path, StringComparison.OrdinalIgnoreCase) || _askTime != t)
|
||||
{
|
||||
_askProfile = VTankLootParser.Load(path);
|
||||
_askPath = path;
|
||||
_askTime = t;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) { error = "AutoTrade's profile could not be read: " + ex.Message; return false; }
|
||||
|
||||
uint player = PlayerId();
|
||||
var ctx = NewContext();
|
||||
HashSet<int> keepIds = ReadKeepIds();
|
||||
for (int i = 0; i < ids.Length && i < gives.Length; i++)
|
||||
{
|
||||
WorldObject? wo = _cache[unchecked((int)ids[i])];
|
||||
if (wo == null || wo.Id == 0 || keepIds.Contains(wo.Id)) continue;
|
||||
bool appraised = Appraised(ids[i]);
|
||||
if (UnsafeReason(wo, player, appraised) != null) continue;
|
||||
ProfileVerdict verdict = AutoVendorRules.Decide(_askProfile.Rules, Judge(EvalObject(wo), Facts(wo, appraised), ctx));
|
||||
if (verdict.Rule != null && verdict.Certain && IsKeepAction(verdict.Rule.Action)) gives[i] = 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Null when the item may be traded away; otherwise why it never will be.</summary>
|
||||
private string? UnsafeReason(WorldObject wo, uint player, bool appraised)
|
||||
{
|
||||
|
|
|
|||
67
Plugins/RynthCore.Plugin.RynthAi/Trade/ITradeShopGame.cs
Normal file
67
Plugins/RynthCore.Plugin.RynthAi/Trade/ITradeShopGame.cs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
// What the Trade Shop needs from the game. RynthAi's implementation (TradeShopHostGame.cs) reads the
|
||||
// engine's trade state and object cache; the tests use a fake. Keeping the shop behind this lets
|
||||
// RynthCore.RynthAiTests run its whole sale flow offline.
|
||||
//
|
||||
// Pure (System only): RynthCore.RynthAiTests links it.
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Trade;
|
||||
|
||||
/// <summary>A copy of the trade window's state (the engine's TradeState, API v72).</summary>
|
||||
public readonly record struct TradeShopTrade(
|
||||
bool IsOpen, bool YouAccepted, bool PartnerAccepted,
|
||||
uint Generation, uint Sequence, uint PartnerId, uint CompletedCount);
|
||||
|
||||
public interface ITradeShopGame
|
||||
{
|
||||
/// <summary>Milliseconds (a steady clock).</summary>
|
||||
long NowMs { get; }
|
||||
|
||||
/// <summary>The engine has player trading (API v72).</summary>
|
||||
bool HasTrade { get; }
|
||||
|
||||
bool TryGetTrade(out TradeShopTrade trade);
|
||||
|
||||
/// <summary>Item ids on one side of the trade window (partner: the buyer's side).</summary>
|
||||
uint[] TradeItems(bool partnerSide);
|
||||
|
||||
bool TradeAdd(uint itemId);
|
||||
bool TradeAccept();
|
||||
/// <summary>Withdraw our accept (ACE: clears only ours).</summary>
|
||||
bool TradeDecline();
|
||||
/// <summary>Clear the window (ACE: both sides' items and both accepts).</summary>
|
||||
bool TradeReset();
|
||||
bool TradeClose();
|
||||
|
||||
/// <summary>One object as the client knows it (null: the client doesn't have it).</summary>
|
||||
TradeShopItem? ReadItem(uint id);
|
||||
|
||||
/// <summary>The items in this character's packs (equipped ones flagged).</summary>
|
||||
IEnumerable<TradeShopItem> PackItems();
|
||||
|
||||
/// <summary>A nearby player with exactly this name (0: none in view).</summary>
|
||||
uint FindPlayer(string exactName);
|
||||
|
||||
/// <summary>An object's name ("" when unknown).</summary>
|
||||
string NameOf(uint id);
|
||||
|
||||
/// <summary>Send a /tell.</summary>
|
||||
void Tell(string to, string message);
|
||||
|
||||
/// <summary>Say a line on a chat channel (<paramref name="prefix"/>: "/ct ", or "" for local).</summary>
|
||||
void Say(string prefix, string message);
|
||||
|
||||
/// <summary>A line in this player's chat only.</summary>
|
||||
void Chat(string line);
|
||||
|
||||
void Log(string line);
|
||||
|
||||
/// <summary>A sale, for the sales log file.</summary>
|
||||
void RecordSale(string line);
|
||||
|
||||
/// <summary>Why the shop must not trade now (combat, the macro, a hunt, AutoTrade), or "".</summary>
|
||||
string PauseReason();
|
||||
|
||||
/// <summary>"HH:mm" now, for the window's last sales.</summary>
|
||||
string TimeOfDay();
|
||||
}
|
||||
67
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopAdvertise.cs
Normal file
67
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopAdvertise.cs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
// Trade Shop advertising: which chat channel and its slash prefix.
|
||||
// Ported from SilentKelpie's Trade Shop (RynthSuite PR #12); re-implemented here. Advertising is off
|
||||
// by default, Trade is the default channel, and the shortest interval is 5 minutes
|
||||
// (TradeShopSettings.MinAdvertiseSec).
|
||||
//
|
||||
// Pure (System only): RynthCore.RynthAiTests links it.
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Trade;
|
||||
|
||||
/// <summary>Where the shop may advertise.</summary>
|
||||
public enum TradeShopAdvertiseChannel
|
||||
{
|
||||
Trade = 0,
|
||||
General = 1,
|
||||
Lfg = 2,
|
||||
Roleplay = 3,
|
||||
Society = 4,
|
||||
Local = 5,
|
||||
}
|
||||
|
||||
public static class TradeShopAdvertise
|
||||
{
|
||||
public static readonly TradeShopAdvertiseChannel[] All =
|
||||
{
|
||||
TradeShopAdvertiseChannel.Trade, TradeShopAdvertiseChannel.General, TradeShopAdvertiseChannel.Lfg,
|
||||
TradeShopAdvertiseChannel.Roleplay, TradeShopAdvertiseChannel.Society, TradeShopAdvertiseChannel.Local,
|
||||
};
|
||||
|
||||
public static string DisplayName(TradeShopAdvertiseChannel ch) => ch switch
|
||||
{
|
||||
TradeShopAdvertiseChannel.Trade => "Trade (/ct)",
|
||||
TradeShopAdvertiseChannel.General => "General (/cg)",
|
||||
TradeShopAdvertiseChannel.Lfg => "LFG (/clfg)",
|
||||
TradeShopAdvertiseChannel.Roleplay => "Roleplay (/crp)",
|
||||
TradeShopAdvertiseChannel.Society => "Society (/cs)",
|
||||
TradeShopAdvertiseChannel.Local => "Local (say)",
|
||||
_ => ch.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>The chat command prefix (empty: say it locally).</summary>
|
||||
public static string SendPrefix(TradeShopAdvertiseChannel ch) => ch switch
|
||||
{
|
||||
TradeShopAdvertiseChannel.Trade => "/ct ",
|
||||
TradeShopAdvertiseChannel.General => "/cg ",
|
||||
TradeShopAdvertiseChannel.Lfg => "/clfg ",
|
||||
TradeShopAdvertiseChannel.Roleplay => "/crp ",
|
||||
TradeShopAdvertiseChannel.Society => "/cs ",
|
||||
_ => "",
|
||||
};
|
||||
|
||||
public static bool TryParseChannel(string? text, out TradeShopAdvertiseChannel ch)
|
||||
{
|
||||
ch = TradeShopAdvertiseChannel.Trade;
|
||||
string t = (text ?? "").Trim().TrimStart('/').ToLowerInvariant();
|
||||
switch (t)
|
||||
{
|
||||
case "trade": case "ct": ch = TradeShopAdvertiseChannel.Trade; return true;
|
||||
case "general": case "cg": ch = TradeShopAdvertiseChannel.General; return true;
|
||||
case "lfg": case "clfg": ch = TradeShopAdvertiseChannel.Lfg; return true;
|
||||
case "roleplay": case "rp": case "crp": ch = TradeShopAdvertiseChannel.Roleplay; return true;
|
||||
case "society": case "cs": ch = TradeShopAdvertiseChannel.Society; return true;
|
||||
case "local": case "say": case "s": ch = TradeShopAdvertiseChannel.Local; return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
// Trade Shop: what counts as payment, by weenie class id (WCID) only.
|
||||
// Ported from SilentKelpie's Trade Shop (RynthSuite PR #12); re-implemented here. His version read
|
||||
// payment by name and took any item's Value as pyreals, so a junk item with a high Value counted as
|
||||
// money. Here an item is payment only when its WCID is in this table, and a trade note is worth its
|
||||
// WCID's face value. Anything else is worth 0.
|
||||
//
|
||||
// The WCIDs are the retail weenies, as in the ACE world database (ACEmulator, AGPL; read for the
|
||||
// numbers only): ACE.Entity/Enum/WeenieClassName.cs (W_COINSTACK_CLASS, W_TRADENOTE*_CLASS) and the
|
||||
// weenie tables of ACE-World-Database v0.9.293 (name, use count, bonded / attuned flags).
|
||||
//
|
||||
// Pure (System only): RynthCore.RynthAiTests links it.
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Trade;
|
||||
|
||||
/// <summary>What one payment WCID is.</summary>
|
||||
public enum TradeShopCurrency
|
||||
{
|
||||
/// <summary>Not payment: worth 0.</summary>
|
||||
None = 0,
|
||||
Pyreals = 1,
|
||||
/// <summary>A trade note (MMD is the 250,000 one): worth its face value in pyreals.</summary>
|
||||
TradeNote = 2,
|
||||
/// <summary>A single-use Legendary Key: priced by the shop's own pyreals-per-key rate.</summary>
|
||||
LegendaryKey = 3,
|
||||
}
|
||||
|
||||
/// <summary>The payment WCIDs and what each is worth.</summary>
|
||||
public static class TradeShopCurrencyTable
|
||||
{
|
||||
/// <summary>W_COINSTACK_CLASS: a stack of pyreals (each is 1 pyreal).</summary>
|
||||
public const uint PyrealWcid = 273;
|
||||
|
||||
/// <summary>W_TRADENOTE250000_CLASS: the 250,000 trade note (an MMD).</summary>
|
||||
public const uint MmdWcid = 20630;
|
||||
|
||||
/// <summary>Pyreals in one MMD note.</summary>
|
||||
public const long PyrealsPerMmd = 250_000;
|
||||
|
||||
/// <summary>Trade note WCID -> face value (W_TRADENOTE<value>_CLASS, all fourteen).</summary>
|
||||
private static readonly Dictionary<uint, long> NoteFaces = new()
|
||||
{
|
||||
[2621] = 100,
|
||||
[2622] = 500,
|
||||
[2623] = 1_000,
|
||||
[2624] = 5_000,
|
||||
[2625] = 10_000,
|
||||
[7374] = 15_000,
|
||||
[7375] = 20_000,
|
||||
[7376] = 25_000,
|
||||
[2626] = 50_000,
|
||||
[7377] = 75_000,
|
||||
[2627] = 100_000,
|
||||
[20628] = 150_000,
|
||||
[20629] = 200_000,
|
||||
[MmdWcid] = 250_000,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// "Legendary Key" weenies that open a Legendary Armor, Magic, or Weapon Chest
|
||||
/// (key code legarmormagicweaponchest), have ONE use (MaxStructure 1) and are neither bonded nor
|
||||
/// attuned, so they can be traded and one key is always one key. Keys with more uses (48748-48750,
|
||||
/// 51586, 51648, 51963, 52010, 72338, 72807, 87168) are left out: a used one has fewer uses left than
|
||||
/// its weenie says. Bonded ones (72474, 72628, 72635, 72669) can't be traded. The Aged Legendary Key
|
||||
/// (48746) opens a different chest.
|
||||
/// </summary>
|
||||
private static readonly HashSet<uint> LegendaryKeyWcids = new() { 48747, 48914, 51558, 72048, 72600 };
|
||||
|
||||
/// <summary>What <paramref name="wcid"/> is as payment (None: not payment).</summary>
|
||||
public static TradeShopCurrency Classify(uint wcid)
|
||||
{
|
||||
if (wcid == PyrealWcid) return TradeShopCurrency.Pyreals;
|
||||
if (NoteFaces.ContainsKey(wcid)) return TradeShopCurrency.TradeNote;
|
||||
if (LegendaryKeyWcids.Contains(wcid)) return TradeShopCurrency.LegendaryKey;
|
||||
return TradeShopCurrency.None;
|
||||
}
|
||||
|
||||
/// <summary>A trade note's face value in pyreals, from its WCID (0 when it isn't a note).</summary>
|
||||
public static long NoteFaceValue(uint wcid) => NoteFaces.TryGetValue(wcid, out long v) ? v : 0;
|
||||
|
||||
/// <summary>Every payment WCID (the table, for tests and the window's help).</summary>
|
||||
public static IEnumerable<uint> AllWcids()
|
||||
{
|
||||
yield return PyrealWcid;
|
||||
foreach (uint w in NoteFaces.Keys) yield return w;
|
||||
foreach (uint w in LegendaryKeyWcids) yield return w;
|
||||
}
|
||||
}
|
||||
134
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopHostGame.cs
Normal file
134
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopHostGame.cs
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
// The Trade Shop's game side on RynthCore: the engine's trade calls (plugin API v72), WCIDs and
|
||||
// stack sizes from the client, RynthAi's object cache for the packs and nearby players.
|
||||
// Ported from SilentKelpie's Trade Shop (RynthSuite PR #12); re-implemented here.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Trade;
|
||||
|
||||
internal sealed class TradeShopHostGame : ITradeShopGame
|
||||
{
|
||||
private const uint StackSizeKey = 12; // PropertyInt StackSize (the engine reads the client's own copy)
|
||||
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly WorldObjectCache _cache;
|
||||
private readonly Func<uint> _playerId;
|
||||
private readonly Func<string> _pauseReason;
|
||||
private readonly Func<string> _charFolder;
|
||||
|
||||
public TradeShopHostGame(RynthCoreHost host, WorldObjectCache cache, Func<uint> playerId,
|
||||
Func<string> pauseReason, Func<string> charFolder)
|
||||
{
|
||||
_host = host;
|
||||
_cache = cache;
|
||||
_playerId = playerId;
|
||||
_pauseReason = pauseReason;
|
||||
_charFolder = charFolder;
|
||||
}
|
||||
|
||||
public long NowMs => Environment.TickCount64;
|
||||
|
||||
public bool HasTrade => _host.HasTrade;
|
||||
|
||||
public bool TryGetTrade(out TradeShopTrade trade)
|
||||
{
|
||||
trade = default;
|
||||
if (!_host.TryGetTradeState(out TradeState st)) return false;
|
||||
trade = new TradeShopTrade(st.IsOpen, st.YouAccepted, st.PartnerAccepted, st.Generation, st.Sequence,
|
||||
st.PartnerId, st.CompletedCount);
|
||||
return true;
|
||||
}
|
||||
|
||||
public uint[] TradeItems(bool partnerSide) => _host.GetTradeItems(partnerSide ? TradeSide.Partner : TradeSide.You);
|
||||
|
||||
public bool TradeAdd(uint itemId) => _host.TradeAdd(itemId);
|
||||
public bool TradeAccept() => _host.TradeAccept();
|
||||
public bool TradeDecline() => _host.TradeDecline();
|
||||
public bool TradeReset() => _host.TradeReset();
|
||||
public bool TradeClose() => _host.TradeClose();
|
||||
|
||||
public TradeShopItem? ReadItem(uint id)
|
||||
{
|
||||
if (id == 0) return null;
|
||||
if (!_host.HasGetObjectWcid || !_host.TryGetObjectWcid(id, out uint wcid) || wcid == 0)
|
||||
return new TradeShopItem(id, 0, NameOf(id), -1, Known: false);
|
||||
int stack = _host.TryGetObjectIntProperty(id, StackSizeKey, out int s) && s > 0 ? s : 0;
|
||||
bool equipped = false;
|
||||
WorldObject? wo = _cache[unchecked((int)id)];
|
||||
if (wo != null) equipped = wo.WieldedLocation > 0 || wo.Values(LongValueKey.EquippedSlots, 0) > 0;
|
||||
return new TradeShopItem(id, wcid, NameOf(id), stack, Known: true, equipped);
|
||||
}
|
||||
|
||||
public IEnumerable<TradeShopItem> PackItems()
|
||||
{
|
||||
var list = new List<TradeShopItem>();
|
||||
IReadOnlyList<WorldObject> inv;
|
||||
try { inv = _cache.GetDirectInventory(forceRefresh: true); }
|
||||
catch { return list; }
|
||||
foreach (WorldObject wo in inv)
|
||||
{
|
||||
if (wo == null || wo.Id == 0) continue;
|
||||
TradeShopItem? it = ReadItem(unchecked((uint)wo.Id));
|
||||
if (it is { } item) list.Add(item);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public uint FindPlayer(string exactName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(exactName)) return 0;
|
||||
int me = unchecked((int)_playerId());
|
||||
foreach (WorldObject wo in _cache.GetLandscapeObjects())
|
||||
{
|
||||
if (wo == null || wo.Id == me || wo.ObjectClass != AcObjectClass.Player) continue;
|
||||
if (string.Equals(wo.Name?.Trim(), exactName.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
return unchecked((uint)wo.Id);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public string NameOf(uint id)
|
||||
=> id != 0 && _host.TryGetObjectName(id, out string n) && !string.IsNullOrWhiteSpace(n) ? n.Trim() : "";
|
||||
|
||||
public void Tell(string to, string message)
|
||||
{
|
||||
if (!TradeShopTellParse.IsSafeName(to)) return;
|
||||
if (_host.HasInvokeChatParser) _host.InvokeChatParser($"/tell {to}, {message}");
|
||||
else _host.Log($"[RynthAi] TradeShop (no chat parser) -> {to}: {message}");
|
||||
}
|
||||
|
||||
public void Say(string prefix, string message)
|
||||
{
|
||||
// The line must never be a command of its own: a leading / or @ is dropped.
|
||||
string body = (message ?? "").TrimStart('/', '@', ' ');
|
||||
if (body.Length == 0) return;
|
||||
if (_host.HasInvokeChatParser) _host.InvokeChatParser(prefix + body);
|
||||
else _host.Log($"[RynthAi] TradeShop (no chat parser) advert: {body}");
|
||||
}
|
||||
|
||||
public void Chat(string line) => _host.WriteToChat(line, 1);
|
||||
|
||||
public void Log(string line) => _host.Log(line);
|
||||
|
||||
public void RecordSale(string line)
|
||||
{
|
||||
try
|
||||
{
|
||||
string dir = _charFolder();
|
||||
if (string.IsNullOrWhiteSpace(dir)) dir = RynthCore.Install.RynthInstallPaths.RynthAiDir;
|
||||
Directory.CreateDirectory(dir);
|
||||
File.AppendAllText(Path.Combine(dir, "TradeShopSales.log"),
|
||||
RynthClock.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + line + Environment.NewLine);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_host.Log($"[RynthAi] TradeShop: couldn't write the sales log: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public string PauseReason() => _pauseReason() ?? "";
|
||||
|
||||
public string TimeOfDay() => RynthClock.Now.ToString("HH:mm");
|
||||
}
|
||||
922
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopManager.cs
Normal file
922
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopManager.cs
Normal file
|
|
@ -0,0 +1,922 @@
|
|||
// Trade Shop: a player-run shop. Buyers tell !list / !price / !buy; after !buy the buyer opens a trade
|
||||
// (the shop never opens one: on ACE the opener walks to the other player), the shop puts the item in
|
||||
// the window (Mode 1), checks the buyer's payment by WCID, and the sale is accepted.
|
||||
// Ported from SilentKelpie's Trade Shop (RynthSuite PR #12); re-implemented here, with these changes:
|
||||
// * payment counts by WCID only (TradeShopPayment / TradeShopCurrencyTable), never by name or Value;
|
||||
// * the trade is checked again at the moment of accepting: both sides re-read, our side exactly the
|
||||
// listed item, the buyer's side covering the price, the trade state unchanged across the reads;
|
||||
// items the client can't read yet are never counted as paid;
|
||||
// * after we accept, any change re-checks: a trade that no longer passes is un-accepted
|
||||
// (TradeDecline), one that still passes is accepted again (or prompted again);
|
||||
// * no accept outside a sale: a trade nobody asked to !buy in is greeted and never accepted;
|
||||
// * "Confirm each sale" (on by default): the shop stops before the accept and asks the player
|
||||
// (Accept sale / Decline in the Trade Shop window, or /ra tradeshop accept | decline);
|
||||
// * Mode 2 (a text listing another account holds) is never accepted by the shop: always the prompt;
|
||||
// * tells are rate-limited (TradeShopTellLimiter) and queues capped; advertising is off by default;
|
||||
// * the shop is off at every login and pauses in combat, while the macro or a hunt runs;
|
||||
// * every sale goes to the log, the sales file and the player's chat.
|
||||
//
|
||||
// How ACE handles a change after an accept (ACE.Server/WorldObjects/Player_Trade.cs, read for this):
|
||||
// * HandleActionAddToTrade clears BOTH players' TradeAccepted before adding the item, but sends only
|
||||
// AddToTrade (no ClearTradeAcceptance); RynthCore's trade state clears both accepts on AddToTrade too;
|
||||
// * ResetTrade (GameActionResetTrade) runs on both players: both sides' items and both accepts cleared;
|
||||
// * DeclineTrade clears only the decliner's accept;
|
||||
// * there is no "remove one item": a side only grows, or is reset;
|
||||
// * the transfer happens inside the second accept (FinalizeTrade), with the items in the window then;
|
||||
// * items in a trade window can't be split, merged, moved or used (IsBeingTradedOrContainsItemBeingTraded).
|
||||
// So a buyer can't take payment back after our accept without clearing it, and adding only adds to
|
||||
// what we get. The shop still re-checks every change (a stale read, a reset and re-add) before it
|
||||
// lets an accept stand.
|
||||
//
|
||||
// Threading: OnTell and Request* are called from the chat / render threads and only queue; Tick runs
|
||||
// everything else on the plugin tick. Pure (System only): RynthCore.RynthAiTests links it.
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Trade;
|
||||
|
||||
/// <summary>The sale waiting for the player's Accept sale (the window and chat show it).</summary>
|
||||
public sealed record TradeShopPrompt(string Buyer, string Item, long PricePyreals, string Price, string Paid, TradeShopMode Mode);
|
||||
|
||||
/// <summary>What the accept-time check found.</summary>
|
||||
public enum TradeShopCheck { Ok, Pending, Short, Invalid }
|
||||
|
||||
public readonly record struct TradeShopCheckResult(TradeShopCheck Status, string Reason, TradeShopTally? Tally);
|
||||
|
||||
public sealed class TradeShopManager
|
||||
{
|
||||
public const long OpenTradeWaitMs = 30_000;
|
||||
public const long ShowItemWaitMs = 10_000;
|
||||
public const long PaymentWaitMs = 120_000;
|
||||
public const long ConfirmWaitMs = 180_000;
|
||||
public const long AcceptedWaitMs = 60_000;
|
||||
public const long TellGapMs = 1_200;
|
||||
public const long ManualAdvertiseGapMs = 60_000;
|
||||
public const int MaxReaccepts = 3;
|
||||
public const long AcceptEchoWaitMs = 1_500;
|
||||
public const int RecentSalesKept = 20;
|
||||
|
||||
private readonly ITradeShopGame _game;
|
||||
private readonly Func<TradeShopSettings> _cfg;
|
||||
private readonly TradeShopTellLimiter _limiter = new();
|
||||
private readonly ConcurrentQueue<(string Sender, string Body, long At)> _in = new();
|
||||
private int _inCount;
|
||||
private readonly ConcurrentQueue<Action> _commands = new();
|
||||
private readonly LinkedList<(string To, string Text, bool Sale)> _out = new();
|
||||
private long _nextTellAt;
|
||||
private long _nextAdvertiseAt;
|
||||
private long _lastManualAdAt = long.MinValue / 2;
|
||||
|
||||
// Trade window tracking.
|
||||
private bool _baselined;
|
||||
private bool _wasOpen;
|
||||
private uint _generation;
|
||||
private uint _completed;
|
||||
private uint _greetedGeneration;
|
||||
|
||||
private enum Phase { Idle, OpenTrade, ShowItem, WaitPayment, AwaitConfirm, Accepted }
|
||||
private Phase _phase = Phase.Idle;
|
||||
private TradeShopListing? _listing;
|
||||
private TradeShopMode _mode;
|
||||
private uint _stockId;
|
||||
private string _buyer = "";
|
||||
private uint _buyerId;
|
||||
private uint _sessionGeneration;
|
||||
private long _deadline;
|
||||
private uint _checkedSequence;
|
||||
private int _reaccepts;
|
||||
private long _acceptSentAt = long.MinValue / 2;
|
||||
private long _declineSentAt = long.MinValue / 2;
|
||||
private TradeShopCheckResult _lastOk;
|
||||
private bool _paymentSeenTold;
|
||||
|
||||
private volatile TradeShopPrompt? _prompt;
|
||||
private volatile string _status = "Off";
|
||||
private readonly object _salesLock = new();
|
||||
private readonly List<string> _sales = new();
|
||||
|
||||
public TradeShopManager(ITradeShopGame game, Func<TradeShopSettings> settings)
|
||||
{
|
||||
_game = game;
|
||||
_cfg = settings;
|
||||
}
|
||||
|
||||
private TradeShopSettings Cfg => _cfg() ?? new TradeShopSettings();
|
||||
|
||||
/// <summary>One line for the window and /ra tradeshop status (any thread).</summary>
|
||||
public string Status => _status;
|
||||
|
||||
/// <summary>The sale waiting for Accept sale, or null (any thread).</summary>
|
||||
public TradeShopPrompt? Prompt => _prompt;
|
||||
|
||||
/// <summary>A sale is under way: inventory chores wait.</summary>
|
||||
public bool HoldsBot => _phase != Phase.Idle;
|
||||
|
||||
/// <summary>The last sales, newest last (any thread).</summary>
|
||||
public List<string> RecentSales()
|
||||
{
|
||||
lock (_salesLock) return new List<string>(_sales);
|
||||
}
|
||||
|
||||
// ── From other threads ──────────────────────────────────────────────
|
||||
|
||||
/// <summary>Chat thread: a chat line; tells to us that look like shop commands are queued.</summary>
|
||||
public void OnTell(string? text, bool isIncomingTell)
|
||||
{
|
||||
if (!isIncomingTell || !Cfg.Enabled) return;
|
||||
if (!TradeShopTellParse.TryParseTell(text, out string sender, out string body)) return;
|
||||
if (TradeShopTellParse.SplitCommand(body).verb.Length == 0) return;
|
||||
if (Interlocked.Increment(ref _inCount) > TradeShopTellLimiter.MaxInQueue)
|
||||
{
|
||||
Interlocked.Decrement(ref _inCount);
|
||||
return; // queue full: dropped
|
||||
}
|
||||
_in.Enqueue((sender, body, _game.NowMs)); // the limits go by when it arrived
|
||||
}
|
||||
|
||||
/// <summary>Run <paramref name="action"/> on the next tick (commands, window buttons).</summary>
|
||||
public void Enqueue(Action action)
|
||||
{
|
||||
if (action != null) _commands.Enqueue(action);
|
||||
}
|
||||
|
||||
/// <summary>The Accept sale button / command: re-check, then accept.</summary>
|
||||
public void RequestAccept() => Enqueue(AcceptFromPlayer);
|
||||
|
||||
/// <summary>The Decline button / command: the sale is called off and the trade closed.</summary>
|
||||
public void RequestDecline() => Enqueue(DeclineFromPlayer);
|
||||
|
||||
/// <summary>Advertise now (the window's button, /ra tradeshop advertise now).</summary>
|
||||
public void RequestAdvertise() => Enqueue(() => Advertise(_game.NowMs, manual: true));
|
||||
|
||||
/// <summary>Turn the shop on or off; turning it on says what it does.</summary>
|
||||
public void SetEnabled(bool on) => Enqueue(() => ApplyEnabled(on));
|
||||
|
||||
/// <summary>Confirm each sale on or off; off says what that means once.</summary>
|
||||
public void SetConfirmEachSale(bool on) => Enqueue(() => ApplyConfirm(on));
|
||||
|
||||
/// <summary>Logout: drop everything quietly.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
ClearSession();
|
||||
_baselined = false;
|
||||
_wasOpen = false;
|
||||
while (_in.TryDequeue(out _)) { }
|
||||
Interlocked.Exchange(ref _inCount, 0);
|
||||
while (_commands.TryDequeue(out _)) { }
|
||||
_out.Clear();
|
||||
_limiter.Clear();
|
||||
_nextAdvertiseAt = 0;
|
||||
_status = "Off";
|
||||
}
|
||||
|
||||
// ── Tick ────────────────────────────────────────────────────────────
|
||||
|
||||
public void Tick()
|
||||
{
|
||||
while (_commands.TryDequeue(out Action? cmd))
|
||||
{
|
||||
try { cmd(); }
|
||||
catch (Exception ex) { _game.Log($"[RynthAi] TradeShop command failed: {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
long now = _game.NowMs;
|
||||
TradeShopSettings cfg = Cfg;
|
||||
if (!cfg.Enabled)
|
||||
{
|
||||
if (_phase != Phase.Idle) Abort("the shop was turned off", tellBuyer: true);
|
||||
DropInbound();
|
||||
DropPriceLines();
|
||||
DrainOut(now); // the "sale called off" tell still goes
|
||||
_nextAdvertiseAt = 0;
|
||||
_status = "Off";
|
||||
return;
|
||||
}
|
||||
|
||||
string pause = _game.PauseReason() ?? "";
|
||||
if (pause.Length > 0)
|
||||
{
|
||||
if (_phase != Phase.Idle) Abort("paused: " + pause, tellBuyer: true);
|
||||
DropInbound();
|
||||
DropPriceLines();
|
||||
_nextAdvertiseAt = 0;
|
||||
DrainOut(now); // the "sale called off" tell still goes
|
||||
_status = "Paused: " + pause;
|
||||
return;
|
||||
}
|
||||
|
||||
DrainOut(now);
|
||||
TickAdvertise(now, cfg);
|
||||
HandleTells(now, cfg);
|
||||
|
||||
if (!_game.HasTrade)
|
||||
{
|
||||
_status = "On, but this RynthCore has no player trading (plugin API 72+): price tells only";
|
||||
return;
|
||||
}
|
||||
|
||||
PollTrade(now);
|
||||
TickPhase(now, cfg);
|
||||
if (_phase == Phase.Idle) _status = $"On, {(cfg.Mode == TradeShopMode.Mode1Stock ? "Mode 1" : "Mode 2")}, waiting for buyers";
|
||||
}
|
||||
|
||||
// ── Tells ───────────────────────────────────────────────────────────
|
||||
|
||||
private void DropPriceLines()
|
||||
{
|
||||
var node = _out.First;
|
||||
while (node != null)
|
||||
{
|
||||
var next = node.Next;
|
||||
if (!node.Value.Sale) _out.Remove(node);
|
||||
node = next;
|
||||
}
|
||||
}
|
||||
|
||||
private void DropInbound()
|
||||
{
|
||||
while (_in.TryDequeue(out _)) Interlocked.Decrement(ref _inCount);
|
||||
}
|
||||
|
||||
// Every queued tell goes through the limits (by when it arrived); the ones let through are answered.
|
||||
private void HandleTells(long now, TradeShopSettings cfg)
|
||||
{
|
||||
for (int i = 0; i < TradeShopTellLimiter.MaxInQueue && _in.TryDequeue(out var tell); i++)
|
||||
{
|
||||
Interlocked.Decrement(ref _inCount);
|
||||
HandleTell(tell.Sender, tell.Body, tell.At, now, cfg);
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleTell(string sender, string body, long at, long now, TradeShopSettings cfg)
|
||||
{
|
||||
var tell = (Sender: sender, Body: body);
|
||||
switch (_limiter.OnIncoming(sender, at))
|
||||
{
|
||||
case TradeShopTellLimiter.Verdict.TooFast:
|
||||
case TradeShopTellLimiter.Verdict.Ignored:
|
||||
return;
|
||||
case TradeShopTellLimiter.Verdict.NowIgnored:
|
||||
_game.Log($"[RynthAi] TradeShop: {tell.Sender} sent too many tells; ignored for {TradeShopTellLimiter.SpamIgnoreMs / 1000} s.");
|
||||
Queue(tell.Sender, $"Too many messages. The shop will ignore you for {TradeShopTellLimiter.SpamIgnoreMs / 60000} minutes.", sale: true);
|
||||
return;
|
||||
}
|
||||
|
||||
var (verb, arg) = TradeShopTellParse.SplitCommand(tell.Body);
|
||||
List<TradeShopListing> forSale = cfg.ForSale();
|
||||
switch (verb)
|
||||
{
|
||||
case "help":
|
||||
Queue(tell.Sender, TradeShopMessages.HelpLine());
|
||||
break;
|
||||
case "rates":
|
||||
Queue(tell.Sender, TradeShopMessages.Clip(TradeShopMessages.RatesLine(cfg.Rates)));
|
||||
break;
|
||||
case "list":
|
||||
foreach (string chunk in TradeShopMessages.PriceSheet(forSale, cfg.Rates, includeRates: true))
|
||||
Queue(tell.Sender, chunk);
|
||||
break;
|
||||
case "price":
|
||||
{
|
||||
TradeShopListing? l = TradeShopMessages.ResolveListing(forSale, arg);
|
||||
Queue(tell.Sender, l == null
|
||||
? "No such item. Tell !list for the price sheet."
|
||||
: TradeShopMessages.Clip($"{l.Label()}: {cfg.Rates.FormatAlternatives(l.PricePyreals)}"));
|
||||
break;
|
||||
}
|
||||
case "buy":
|
||||
BeginBuy(tell.Sender, arg, forSale, cfg, now);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void Queue(string to, string text, bool sale = false)
|
||||
{
|
||||
string line = TradeShopMessages.Clip(text);
|
||||
if (!TradeShopTellParse.IsSafeName(to) || line.Length == 0) return;
|
||||
if (_out.Count >= TradeShopTellLimiter.MaxOutQueue)
|
||||
{
|
||||
if (!sale) { _game.Log($"[RynthAi] TradeShop: tell queue full, dropped a line to {to}."); return; }
|
||||
// A sale line goes in ahead of a price-sheet line.
|
||||
var node = _out.Last;
|
||||
while (node != null && node.Value.Sale) node = node.Previous;
|
||||
if (node == null) return;
|
||||
_out.Remove(node);
|
||||
}
|
||||
if (sale)
|
||||
{
|
||||
var after = _out.First;
|
||||
while (after != null && after.Value.Sale) after = after.Next;
|
||||
if (after == null) _out.AddLast((to, line, true));
|
||||
else _out.AddBefore(after, (to, line, true));
|
||||
}
|
||||
else _out.AddLast((to, line, false));
|
||||
}
|
||||
|
||||
private void DrainOut(long now)
|
||||
{
|
||||
if (_out.Count == 0 || now < _nextTellAt) return;
|
||||
while (_out.First != null)
|
||||
{
|
||||
var next = _out.First.Value;
|
||||
if (!_limiter.TryTakeOut(next.To, now, overBuyerCap: next.Sale))
|
||||
{
|
||||
if (_limiter.SentLastMinute(now) >= TradeShopTellLimiter.MaxOutPerMinute) return; // wait for room
|
||||
_out.RemoveFirst(); // that buyer had their share this minute: dropped
|
||||
_game.Log($"[RynthAi] TradeShop: dropped a line to {next.To} (their tell limit this minute).");
|
||||
continue;
|
||||
}
|
||||
_out.RemoveFirst();
|
||||
_game.Tell(next.To, next.Text);
|
||||
_nextTellAt = now + TellGapMs;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Advertising ─────────────────────────────────────────────────────
|
||||
|
||||
private void TickAdvertise(long now, TradeShopSettings cfg)
|
||||
{
|
||||
if (!cfg.AdvertiseEnabled) { _nextAdvertiseAt = 0; return; }
|
||||
long every = TradeShopSettings.ClampAdvertiseSec(cfg.AdvertiseIntervalSec) * 1000L;
|
||||
if (_nextAdvertiseAt == 0) { _nextAdvertiseAt = now + every; return; } // the first one after a full interval
|
||||
if (now < _nextAdvertiseAt) return;
|
||||
_nextAdvertiseAt = now + every;
|
||||
Advertise(now, manual: false);
|
||||
}
|
||||
|
||||
private void Advertise(long now, bool manual)
|
||||
{
|
||||
TradeShopSettings cfg = Cfg;
|
||||
if (manual)
|
||||
{
|
||||
if (!cfg.Enabled) { _game.Chat("[RynthAi] Trade Shop: turn the shop on first (it advertises only while on)."); return; }
|
||||
if (now - _lastManualAdAt < ManualAdvertiseGapMs)
|
||||
{
|
||||
_game.Chat($"[RynthAi] Trade Shop: advertised less than {ManualAdvertiseGapMs / 1000} s ago; wait a moment.");
|
||||
return;
|
||||
}
|
||||
_lastManualAdAt = now;
|
||||
}
|
||||
List<TradeShopListing> forSale = cfg.ForSale();
|
||||
if (forSale.Count == 0)
|
||||
{
|
||||
if (manual) _game.Chat("[RynthAi] Trade Shop: nothing listed for sale, so no advert was sent.");
|
||||
return;
|
||||
}
|
||||
string line = AdvertiseLine(cfg, forSale);
|
||||
_game.Say(TradeShopAdvertise.SendPrefix(cfg.AdvertiseChannel), line);
|
||||
_game.Log($"[RynthAi] TradeShop advertised on {TradeShopAdvertise.DisplayName(cfg.AdvertiseChannel)}: {line}");
|
||||
if (manual) _game.Chat($"[RynthAi] Trade Shop: advertised on {TradeShopAdvertise.DisplayName(cfg.AdvertiseChannel)}.");
|
||||
}
|
||||
|
||||
/// <summary>The advert: prefix, then the items and prices that fit, then how to ask.</summary>
|
||||
public static string AdvertiseLine(TradeShopSettings cfg, IReadOnlyList<TradeShopListing> forSale)
|
||||
{
|
||||
string prefix = (cfg.AdvertisePrefix ?? "").Trim().TrimStart('/', '@').Trim();
|
||||
string head = prefix.Length == 0 ? "[Trade Shop] Selling:" : prefix;
|
||||
const string tail = " Tell me !list";
|
||||
string line = TradeShopMessages.Clip(head);
|
||||
int shown = 0;
|
||||
foreach (TradeShopListing l in forSale)
|
||||
{
|
||||
string item = $" {l.Label()} {TradeShopRates.N(l.PricePyreals)} py;";
|
||||
if (line.Length + item.Length + tail.Length + 12 > TradeShopMessages.MaxLineChars) break;
|
||||
line += item;
|
||||
shown++;
|
||||
}
|
||||
if (shown < forSale.Count) line += $" +{forSale.Count - shown} more.";
|
||||
return line + tail;
|
||||
}
|
||||
|
||||
// ── Turning it on / off ─────────────────────────────────────────────
|
||||
|
||||
private void ApplyEnabled(bool on)
|
||||
{
|
||||
TradeShopSettings cfg = Cfg;
|
||||
if (cfg.Enabled == on)
|
||||
{
|
||||
_game.Chat($"[RynthAi] Trade Shop is already {(on ? "on" : "off")}.");
|
||||
return;
|
||||
}
|
||||
cfg.Enabled = on;
|
||||
if (!on)
|
||||
{
|
||||
_game.Chat("[RynthAi] Trade Shop OFF: it no longer answers tells, trades or advertises.");
|
||||
return;
|
||||
}
|
||||
int n = cfg.ForSale().Count;
|
||||
_game.Chat($"[RynthAi] Trade Shop ON ({(cfg.Mode == TradeShopMode.Mode1Stock ? "Mode 1: items from this character's packs" : "Mode 2: text listings")}, {n} item(s) for sale).");
|
||||
_game.Chat("[RynthAi] It answers tells (!list, !price, !buy). On !buy it opens a trade with the buyer"
|
||||
+ (cfg.Mode == TradeShopMode.Mode1Stock ? ", puts the item in the window" : "")
|
||||
+ " and checks their payment by item type (pyreals, trade notes, single-use Legendary Keys only).");
|
||||
_game.Chat(cfg.Mode == TradeShopMode.Mode2Text
|
||||
? "[RynthAi] Mode 2: you accept every sale yourself (Accept sale in the Trade Shop window), then hand the item over."
|
||||
: cfg.ConfirmEachSale
|
||||
? "[RynthAi] Confirm each sale is ON: it stops before accepting and asks you (Accept sale / Decline in the Trade Shop window)."
|
||||
: "[RynthAi] Confirm each sale is OFF: it accepts a sale itself once the payment checks out.");
|
||||
_game.Chat("[RynthAi] It never accepts a trade nobody asked to !buy in, and pauses in combat, while the macro or a hunt runs. "
|
||||
+ (cfg.AdvertiseEnabled ? $"It advertises on {TradeShopAdvertise.DisplayName(cfg.AdvertiseChannel)} every {TradeShopSettings.ClampAdvertiseSec(cfg.AdvertiseIntervalSec) / 60} min." : "Advertising is off."));
|
||||
}
|
||||
|
||||
private void ApplyConfirm(bool on)
|
||||
{
|
||||
TradeShopSettings cfg = Cfg;
|
||||
bool was = cfg.ConfirmEachSale;
|
||||
cfg.ConfirmEachSale = on;
|
||||
if (on) _game.Chat("[RynthAi] Trade Shop: Confirm each sale ON (it asks you before every accept).");
|
||||
else if (was) _game.Chat("[RynthAi] Trade Shop: Confirm each sale OFF. Warning: Mode 1 sales are now accepted without asking you, once the payment checks out.");
|
||||
else _game.Chat("[RynthAi] Trade Shop: Confirm each sale is already OFF.");
|
||||
}
|
||||
|
||||
// ── !buy ────────────────────────────────────────────────────────────
|
||||
|
||||
private void BeginBuy(string buyer, string arg, List<TradeShopListing> forSale, TradeShopSettings cfg, long now)
|
||||
{
|
||||
if (!_game.HasTrade) { Queue(buyer, "The shop can't trade right now. Try later.", sale: true); return; }
|
||||
if (forSale.Count == 0) { Queue(buyer, "Nothing is for sale right now.", sale: true); return; }
|
||||
TradeShopListing? listing = TradeShopMessages.ResolveListing(forSale, arg);
|
||||
if (listing == null) { Queue(buyer, "No such item. Tell !list, then !buy #<slot>.", sale: true); return; }
|
||||
|
||||
if (_phase != Phase.Idle && !NamesEqual(_buyer, buyer))
|
||||
{
|
||||
Queue(buyer, "The shop is busy with another buyer. Try again in a minute.", sale: true);
|
||||
return;
|
||||
}
|
||||
if (_phase == Phase.Accepted)
|
||||
{
|
||||
Queue(buyer, "Your trade is already accepted on my side: accept it, or cancel the trade first.", sale: true);
|
||||
return;
|
||||
}
|
||||
|
||||
uint stock = 0;
|
||||
if (cfg.Mode == TradeShopMode.Mode1Stock)
|
||||
{
|
||||
stock = ResolveStock(listing);
|
||||
if (stock == 0) { Queue(buyer, $"Out of stock: {listing.Label()}.", sale: true); return; }
|
||||
}
|
||||
|
||||
// A trade open with someone else: busy.
|
||||
_game.TryGetTrade(out TradeShopTrade st);
|
||||
if (st.IsOpen && !IsBuyer(st.PartnerId, buyer, 0))
|
||||
{
|
||||
Queue(buyer, "The shop is in another trade. Try again in a minute.", sale: true);
|
||||
return;
|
||||
}
|
||||
|
||||
bool restart = _phase != Phase.Idle;
|
||||
ClearSession();
|
||||
_listing = listing;
|
||||
_mode = cfg.Mode;
|
||||
_stockId = stock;
|
||||
_buyer = buyer;
|
||||
_buyerId = _game.FindPlayer(buyer);
|
||||
string price = cfg.Rates.FormatAlternatives(listing.PricePyreals);
|
||||
_game.Log($"[RynthAi] TradeShop: {buyer} wants {listing.Label()} ({price}){(restart ? " (changed their pick)" : "")}.");
|
||||
|
||||
Queue(buyer, _mode == TradeShopMode.Mode1Stock
|
||||
? $"{listing.Label()}: {price}. Open a trade with me: I'll put it in the window, then you put the payment in."
|
||||
: $"{listing.Label()}: {price}. Open a trade with me and put the payment in; the seller checks it and accepts by hand.", sale: true);
|
||||
|
||||
if (st.IsOpen)
|
||||
{
|
||||
StartSession(st, now);
|
||||
return;
|
||||
}
|
||||
|
||||
// The buyer opens the trade. The shop never sends one itself: on ACE the one who opens a trade
|
||||
// walks to the other player (CreateMoveToChain), and a shop must not be walked anywhere.
|
||||
_phase = Phase.OpenTrade;
|
||||
_deadline = now + OpenTradeWaitMs;
|
||||
_status = $"Waiting for {buyer} to open a trade";
|
||||
}
|
||||
|
||||
// A trade with the buyer is open: Mode 1 shows the item, Mode 2 waits for the payment.
|
||||
private void StartSession(TradeShopTrade st, long now)
|
||||
{
|
||||
_sessionGeneration = st.Generation;
|
||||
if (_buyerId == 0) _buyerId = st.PartnerId;
|
||||
if (_mode == TradeShopMode.Mode1Stock)
|
||||
{
|
||||
// Our side must be exactly the item: clear the window, then add it.
|
||||
_game.TradeReset();
|
||||
if (!_game.TradeAdd(_stockId))
|
||||
{
|
||||
Abort($"couldn't put {_listing?.Label()} in the trade window", tellBuyer: true);
|
||||
return;
|
||||
}
|
||||
_phase = Phase.ShowItem;
|
||||
_deadline = now + ShowItemWaitMs;
|
||||
_status = $"Putting {_listing?.Label()} in the window for {_buyer}";
|
||||
return;
|
||||
}
|
||||
_phase = Phase.WaitPayment;
|
||||
_deadline = now + PaymentWaitMs;
|
||||
_status = $"Mode 2: waiting for {_buyer}'s payment";
|
||||
}
|
||||
|
||||
// ── The trade window ────────────────────────────────────────────────
|
||||
|
||||
private void PollTrade(long now)
|
||||
{
|
||||
if (!_game.TryGetTrade(out TradeShopTrade st)) return;
|
||||
if (!_baselined)
|
||||
{
|
||||
_baselined = true;
|
||||
_generation = st.Generation;
|
||||
_completed = st.CompletedCount;
|
||||
_wasOpen = st.IsOpen;
|
||||
_greetedGeneration = st.Generation; // a trade open at load isn't greeted
|
||||
return;
|
||||
}
|
||||
|
||||
if (st.CompletedCount != _completed)
|
||||
{
|
||||
_completed = st.CompletedCount;
|
||||
OnTradeCompleted();
|
||||
}
|
||||
|
||||
bool newTrade = st.IsOpen && (!_wasOpen || st.Generation != _generation);
|
||||
bool ended = _wasOpen && (!st.IsOpen || st.Generation != _generation);
|
||||
_generation = st.Generation;
|
||||
_wasOpen = st.IsOpen;
|
||||
|
||||
if (ended && _phase != Phase.Idle && _phase != Phase.OpenTrade)
|
||||
{
|
||||
_game.Log($"[RynthAi] TradeShop: the trade with {_buyer} closed before the sale.");
|
||||
ClearSession();
|
||||
}
|
||||
|
||||
if (newTrade) OnTradeOpened(st, now);
|
||||
}
|
||||
|
||||
private void OnTradeOpened(TradeShopTrade st, long now)
|
||||
{
|
||||
string partner = _game.NameOf(st.PartnerId);
|
||||
if (_phase == Phase.OpenTrade && IsBuyer(st.PartnerId, _buyer, _buyerId))
|
||||
{
|
||||
StartSession(st, now);
|
||||
return;
|
||||
}
|
||||
// A trade nobody asked to !buy in: greet once, never accept.
|
||||
if (_greetedGeneration == st.Generation) return;
|
||||
_greetedGeneration = st.Generation;
|
||||
_game.Log($"[RynthAi] TradeShop: {partner} opened a trade without !buy: greeted, not accepted.");
|
||||
if (TradeShopTellParse.IsSafeName(partner))
|
||||
Queue(partner, "Hi! This is a shop: tell me !list for prices, then !buy #<slot>. I only accept a trade after !buy.");
|
||||
}
|
||||
|
||||
private void TickPhase(long now, TradeShopSettings cfg)
|
||||
{
|
||||
if (_phase == Phase.Idle) return;
|
||||
if (now > _deadline)
|
||||
{
|
||||
Abort(_phase switch
|
||||
{
|
||||
Phase.OpenTrade => "no trade was opened in time",
|
||||
Phase.ShowItem => "the item didn't show in the trade window",
|
||||
Phase.WaitPayment => "no payment in time",
|
||||
Phase.AwaitConfirm => "the sale wasn't confirmed in time",
|
||||
_ => "the buyer didn't accept in time",
|
||||
}, tellBuyer: true);
|
||||
return;
|
||||
}
|
||||
if (_phase == Phase.OpenTrade) return;
|
||||
|
||||
if (!_game.TryGetTrade(out TradeShopTrade st) || !st.IsOpen || st.Generation != _sessionGeneration)
|
||||
{
|
||||
ClearSession();
|
||||
return;
|
||||
}
|
||||
|
||||
// Accepted on our side while the shop hadn't accepted (the game's own Accept button, or an
|
||||
// accept still in flight from before a change): it stands only if the trade passes the check.
|
||||
if (st.YouAccepted && (_phase is Phase.ShowItem or Phase.WaitPayment or Phase.AwaitConfirm)
|
||||
&& now - _declineSentAt >= AcceptEchoWaitMs)
|
||||
{
|
||||
TradeShopCheckResult r = Check(st, cfg);
|
||||
if (r.Status == TradeShopCheck.Ok)
|
||||
{
|
||||
_prompt = null;
|
||||
_lastOk = r;
|
||||
_checkedSequence = st.Sequence;
|
||||
_phase = Phase.Accepted;
|
||||
_deadline = now + AcceptedWaitMs;
|
||||
_game.Log($"[RynthAi] TradeShop: accepted on our side (by hand) with the payment checked: {PaidText(r.Tally)}.");
|
||||
}
|
||||
else
|
||||
{
|
||||
_game.TradeDecline();
|
||||
_declineSentAt = now;
|
||||
_game.Chat($"[RynthAi] Trade Shop: accept withdrawn: {r.Reason}. (Decline the sale first to trade by hand.)");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
switch (_phase)
|
||||
{
|
||||
case Phase.ShowItem:
|
||||
if (_game.TradeItems(partnerSide: false).Contains(_stockId))
|
||||
{
|
||||
_phase = Phase.WaitPayment;
|
||||
_deadline = now + PaymentWaitMs;
|
||||
_status = $"Waiting for {_buyer}'s payment for {_listing?.Label()}";
|
||||
Queue(_buyer, $"{_listing?.Label()} is in the window. Put in {cfg.Rates.FormatAlternatives(_listing?.PricePyreals ?? 0)}, then accept.", sale: true);
|
||||
}
|
||||
break;
|
||||
|
||||
case Phase.WaitPayment:
|
||||
{
|
||||
TradeShopCheckResult r = Check(st, cfg);
|
||||
if (r.Status != TradeShopCheck.Ok)
|
||||
{
|
||||
_status = $"Waiting for {_buyer}'s payment: {r.Reason}";
|
||||
break;
|
||||
}
|
||||
if (_mode == TradeShopMode.Mode1Stock && !cfg.ConfirmEachSale)
|
||||
{
|
||||
TryAccept(cfg, now, fromPlayer: false);
|
||||
break;
|
||||
}
|
||||
ShowPrompt(st, r, cfg);
|
||||
break;
|
||||
}
|
||||
|
||||
case Phase.AwaitConfirm:
|
||||
// The trade changed while the prompt was up: back to checking.
|
||||
if (st.Sequence != _checkedSequence)
|
||||
{
|
||||
_prompt = null;
|
||||
_phase = Phase.WaitPayment;
|
||||
_game.Chat($"[RynthAi] Trade Shop: the trade with {_buyer} changed; checking it again.");
|
||||
}
|
||||
break;
|
||||
|
||||
case Phase.Accepted:
|
||||
TickAccepted(st, cfg, now);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void ShowPrompt(TradeShopTrade st, TradeShopCheckResult r, TradeShopSettings cfg)
|
||||
{
|
||||
TradeShopListing l = _listing!;
|
||||
_checkedSequence = st.Sequence;
|
||||
_lastOk = r;
|
||||
_phase = Phase.AwaitConfirm;
|
||||
_deadline = _game.NowMs + ConfirmWaitMs;
|
||||
string paid = PaidText(r.Tally);
|
||||
_prompt = new TradeShopPrompt(_buyer, l.Label(), l.PricePyreals, cfg.Rates.FormatAlternatives(l.PricePyreals), paid, _mode);
|
||||
_status = $"Sale ready: {l.Label()} to {_buyer}; waiting for your Accept sale";
|
||||
_game.Chat($"[RynthAi] Trade Shop: sale ready. Buyer {_buyer}, {l.Label()}, price {TradeShopRates.N(l.PricePyreals)} py, paid {paid}. "
|
||||
+ "Accept sale or Decline in the Trade Shop window (/ra tradeshop accept | decline).");
|
||||
if (!_paymentSeenTold)
|
||||
{
|
||||
_paymentSeenTold = true;
|
||||
Queue(_buyer, _mode == TradeShopMode.Mode2Text
|
||||
? "Payment seen. The seller will accept by hand in a moment."
|
||||
: "Payment seen. The seller confirms the sale in a moment.", sale: true);
|
||||
}
|
||||
}
|
||||
|
||||
private void TickAccepted(TradeShopTrade st, TradeShopSettings cfg, long now)
|
||||
{
|
||||
if (st.Sequence == _checkedSequence) return;
|
||||
TradeShopCheckResult r = Check(st, cfg);
|
||||
if (r.Status != TradeShopCheck.Ok)
|
||||
{
|
||||
if (st.YouAccepted) { _game.TradeDecline(); _declineSentAt = now; }
|
||||
_game.Log($"[RynthAi] TradeShop: the trade with {_buyer} changed after the accept ({r.Reason}): accept withdrawn, checking again.");
|
||||
_game.Chat($"[RynthAi] Trade Shop: the trade with {_buyer} changed after the accept ({r.Reason}); accept withdrawn.");
|
||||
_prompt = null;
|
||||
_phase = Phase.WaitPayment;
|
||||
_deadline = now + PaymentWaitMs;
|
||||
return;
|
||||
}
|
||||
if (st.YouAccepted)
|
||||
{
|
||||
_checkedSequence = st.Sequence; // still good (our own accept event, or the buyer's)
|
||||
_lastOk = r;
|
||||
return;
|
||||
}
|
||||
// Our accept was cleared (the buyer added an item) and the trade still passes. Right after
|
||||
// sending it, the server's echo may not be back yet: wait for it.
|
||||
if (now - _acceptSentAt < AcceptEchoWaitMs) return;
|
||||
if (_mode == TradeShopMode.Mode1Stock && !cfg.ConfirmEachSale && _reaccepts < MaxReaccepts)
|
||||
{
|
||||
_reaccepts++;
|
||||
TryAccept(cfg, now, fromPlayer: false);
|
||||
return;
|
||||
}
|
||||
if (_mode == TradeShopMode.Mode1Stock && !cfg.ConfirmEachSale)
|
||||
{
|
||||
Abort("the trade kept changing", tellBuyer: true);
|
||||
return;
|
||||
}
|
||||
ShowPrompt(st, r, cfg);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The accept-time check: read the state, both sides, then the state again; accept only when
|
||||
/// everything passes and nothing changed between the reads.
|
||||
/// </summary>
|
||||
private bool TryAccept(TradeShopSettings cfg, long now, bool fromPlayer)
|
||||
{
|
||||
if (!_game.TryGetTrade(out TradeShopTrade before))
|
||||
return false;
|
||||
TradeShopCheckResult r = Check(before, cfg);
|
||||
if (!_game.TryGetTrade(out TradeShopTrade after) || after.Sequence != before.Sequence
|
||||
|| after.Generation != before.Generation || after.IsOpen != before.IsOpen)
|
||||
{
|
||||
r = new TradeShopCheckResult(TradeShopCheck.Pending, "the trade changed while it was checked", r.Tally);
|
||||
}
|
||||
if (r.Status != TradeShopCheck.Ok)
|
||||
{
|
||||
_prompt = null;
|
||||
_phase = Phase.WaitPayment;
|
||||
if (fromPlayer) _game.Chat($"[RynthAi] Trade Shop: not accepted: {r.Reason}. Checking again.");
|
||||
return false;
|
||||
}
|
||||
if (!_game.TradeAccept())
|
||||
{
|
||||
_game.Chat("[RynthAi] Trade Shop: the accept couldn't be sent.");
|
||||
_phase = Phase.WaitPayment;
|
||||
_prompt = null;
|
||||
return false;
|
||||
}
|
||||
_prompt = null;
|
||||
_lastOk = r;
|
||||
_checkedSequence = after.Sequence;
|
||||
_acceptSentAt = now;
|
||||
_phase = Phase.Accepted;
|
||||
_deadline = now + AcceptedWaitMs;
|
||||
_status = $"Accepted {_listing?.Label()} for {_buyer}; waiting for them to accept";
|
||||
_game.Log($"[RynthAi] TradeShop: accepted the sale of {_listing?.Label()} to {_buyer} (paid {PaidText(r.Tally)}){(fromPlayer ? " (you confirmed)" : "")}.");
|
||||
Queue(_buyer, "Accepted on my side. Accept on yours to finish.", sale: true);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The check the shop runs before every accept (and while it waits for the payment).</summary>
|
||||
public TradeShopCheckResult Check(TradeShopTrade st, TradeShopSettings cfg)
|
||||
{
|
||||
TradeShopListing? l = _listing;
|
||||
if (l == null) return new(TradeShopCheck.Invalid, "no sale", null);
|
||||
if (!st.IsOpen) return new(TradeShopCheck.Invalid, "no trade open", null);
|
||||
if (st.Generation != _sessionGeneration) return new(TradeShopCheck.Invalid, "a different trade", null);
|
||||
if (!IsBuyer(st.PartnerId, _buyer, _buyerId)) return new(TradeShopCheck.Invalid, "trading with someone else", null);
|
||||
|
||||
uint[] mine = _game.TradeItems(partnerSide: false) ?? Array.Empty<uint>();
|
||||
uint[] theirs = _game.TradeItems(partnerSide: true) ?? Array.Empty<uint>();
|
||||
if (_mode == TradeShopMode.Mode1Stock)
|
||||
{
|
||||
if (mine.Length != 1 || mine[0] != _stockId)
|
||||
return new(TradeShopCheck.Invalid, $"our side isn't exactly {l.Label()}", null);
|
||||
if (!StockMatches(l, _game.ReadItem(_stockId)))
|
||||
return new(TradeShopCheck.Invalid, $"the item in the window isn't {l.Label()} any more", null);
|
||||
}
|
||||
else if (mine.Length != 0)
|
||||
{
|
||||
return new(TradeShopCheck.Invalid, "our side must be empty for a Mode 2 sale", null);
|
||||
}
|
||||
|
||||
TradeShopTally tally = TradeShopPayment.Tally(theirs, _game.ReadItem);
|
||||
if (tally.Unknown > 0) return new(TradeShopCheck.Pending, "reading the payment items", tally);
|
||||
long paid = cfg.Rates.AcceptedPyreals(tally);
|
||||
if (!cfg.Rates.Covers(l.PricePyreals, tally))
|
||||
return new(TradeShopCheck.Short, $"paid {TradeShopRates.N(paid)} of {TradeShopRates.N(l.PricePyreals)} py", tally);
|
||||
return new(TradeShopCheck.Ok, "paid", tally);
|
||||
}
|
||||
|
||||
private void OnTradeCompleted()
|
||||
{
|
||||
if (_phase is not (Phase.Accepted or Phase.AwaitConfirm) || _listing == null)
|
||||
{
|
||||
if (_phase != Phase.Idle)
|
||||
{
|
||||
_game.Log($"[RynthAi] TradeShop: a trade completed with {_buyer} before the shop had checked the payment (accepted by hand); not logged as a sale.");
|
||||
ClearSession();
|
||||
}
|
||||
return;
|
||||
}
|
||||
bool byHand = _phase == Phase.AwaitConfirm;
|
||||
TradeShopListing l = _listing;
|
||||
string paid = PaidText(_lastOk.Tally);
|
||||
string line = $"Sold {l.Label()} to {_buyer} for {TradeShopRates.N(l.PricePyreals)} py; paid {paid}"
|
||||
+ (_mode == TradeShopMode.Mode2Text ? $" (Mode 2: hand it over{(l.HeldBy.Length > 0 ? " from " + l.HeldBy : "")})" : "")
|
||||
+ (byHand ? " (accepted in the game's trade window)" : "") + ".";
|
||||
_game.Log("[RynthAi] TradeShop: " + line);
|
||||
_game.RecordSale(line);
|
||||
_game.Chat("[RynthAi] Trade Shop: " + line);
|
||||
lock (_salesLock)
|
||||
{
|
||||
_sales.Add(_game.TimeOfDay() + " " + line);
|
||||
if (_sales.Count > RecentSalesKept) _sales.RemoveAt(0);
|
||||
}
|
||||
Queue(_buyer, _mode == TradeShopMode.Mode2Text && l.Description.Length > 0
|
||||
? "Thanks! " + l.Description
|
||||
: "Thanks for your purchase!", sale: true);
|
||||
ClearSession();
|
||||
_game.TradeClose(); // ready for the next buyer
|
||||
}
|
||||
|
||||
// ── The player's buttons ────────────────────────────────────────────
|
||||
|
||||
private void AcceptFromPlayer()
|
||||
{
|
||||
if (_phase != Phase.AwaitConfirm)
|
||||
{
|
||||
_game.Chat("[RynthAi] Trade Shop: no sale is waiting for your accept.");
|
||||
return;
|
||||
}
|
||||
if (TryAccept(Cfg, _game.NowMs, fromPlayer: true))
|
||||
_game.Chat($"[RynthAi] Trade Shop: accepted. Waiting for {_buyer} to accept.");
|
||||
}
|
||||
|
||||
private void DeclineFromPlayer()
|
||||
{
|
||||
if (_phase == Phase.Idle)
|
||||
{
|
||||
if (_game.TryGetTrade(out TradeShopTrade st) && st.IsOpen)
|
||||
{
|
||||
_game.TradeClose();
|
||||
_game.Chat("[RynthAi] Trade Shop: no sale was under way; the trade window was closed.");
|
||||
}
|
||||
else _game.Chat("[RynthAi] Trade Shop: no sale to decline.");
|
||||
return;
|
||||
}
|
||||
string buyer = _buyer;
|
||||
Abort("you declined it", tellBuyer: false);
|
||||
Queue(buyer, "The seller declined this sale. Sorry!", sale: true);
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
private void Abort(string why, bool tellBuyer)
|
||||
{
|
||||
string buyer = _buyer;
|
||||
bool inTrade = _phase is not (Phase.Idle or Phase.OpenTrade);
|
||||
if (_phase == Phase.Accepted && _game.TryGetTrade(out TradeShopTrade st) && st.YouAccepted) _game.TradeDecline();
|
||||
if (inTrade) _game.TradeClose();
|
||||
_game.Log($"[RynthAi] TradeShop: sale to {buyer} called off: {why}.");
|
||||
_game.Chat($"[RynthAi] Trade Shop: sale to {buyer} called off: {why}.");
|
||||
if (tellBuyer && buyer.Length > 0) Queue(buyer, "The sale was called off (" + why + "). Tell !buy to try again.", sale: true);
|
||||
ClearSession();
|
||||
}
|
||||
|
||||
private void ClearSession()
|
||||
{
|
||||
_phase = Phase.Idle;
|
||||
_listing = null;
|
||||
_stockId = 0;
|
||||
_buyer = "";
|
||||
_buyerId = 0;
|
||||
_sessionGeneration = 0;
|
||||
_checkedSequence = 0;
|
||||
_reaccepts = 0;
|
||||
_acceptSentAt = long.MinValue / 2;
|
||||
_declineSentAt = long.MinValue / 2;
|
||||
_lastOk = default;
|
||||
_paymentSeenTold = false;
|
||||
_prompt = null;
|
||||
}
|
||||
|
||||
private uint ResolveStock(TradeShopListing l)
|
||||
{
|
||||
List<TradeShopItem> pack;
|
||||
try { pack = (_game.PackItems() ?? Enumerable.Empty<TradeShopItem>()).ToList(); }
|
||||
catch { return 0; }
|
||||
if (l.ObjectId != 0)
|
||||
foreach (TradeShopItem it in pack)
|
||||
if (it.Id == l.ObjectId && !it.Equipped && StockMatches(l, it)) return it.Id;
|
||||
foreach (TradeShopItem it in pack)
|
||||
if (!it.Equipped && StockMatches(l, it)) return it.Id;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>The stock item is still the listed one: same WCID (when known), name, and stack size (when a stack).</summary>
|
||||
public static bool StockMatches(TradeShopListing l, TradeShopItem? read)
|
||||
{
|
||||
if (read is not { } it || !it.Known || it.Equipped) return false;
|
||||
if (l.Wcid != 0 && it.Wcid != l.Wcid) return false;
|
||||
if (!string.Equals((it.Name ?? "").Trim(), l.Name.Trim(), StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (l.Stack > 0 && it.Stack != l.Stack) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool IsBuyer(uint partnerId, string buyer, uint buyerId)
|
||||
{
|
||||
if (partnerId == 0) return false;
|
||||
if (buyerId != 0) return partnerId == buyerId;
|
||||
return NamesEqual(_game.NameOf(partnerId), buyer);
|
||||
}
|
||||
|
||||
private static string PaidText(TradeShopTally? t)
|
||||
=> t == null ? "nothing" : t.Lines.Count == 0 ? "nothing" : string.Join(", ", t.Lines);
|
||||
|
||||
private static bool NamesEqual(string? a, string? b)
|
||||
=> !string.IsNullOrWhiteSpace(a) && !string.IsNullOrWhiteSpace(b)
|
||||
&& string.Equals(a.Trim(), b.Trim(), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
98
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopMessages.cs
Normal file
98
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopMessages.cs
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
// Trade Shop: the lines it tells and advertises, and finding a listing from a buyer's selector.
|
||||
// Ported from SilentKelpie's Trade Shop (RynthSuite PR #12); re-implemented here. A price sheet is
|
||||
// cut into tell-sized chunks and capped at MaxSheetChunks; the rest is one "and N more" line.
|
||||
//
|
||||
// Pure (System only): RynthCore.RynthAiTests links it.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Trade;
|
||||
|
||||
public static class TradeShopMessages
|
||||
{
|
||||
/// <summary>Longest line the shop sends (AC drops longer tells; "/tell Name, " needs room too).</summary>
|
||||
public const int MaxLineChars = 200;
|
||||
|
||||
/// <summary>Most chunks one price sheet sends.</summary>
|
||||
public const int MaxSheetChunks = 4;
|
||||
|
||||
public static string HelpLine()
|
||||
=> "Trade Shop: !list (price sheet), !rates, !price <#slot|name>, !buy <#slot|name>. Example: !buy #2";
|
||||
|
||||
public static string RatesLine(TradeShopRates? rates) => "Rates: " + (rates ?? new TradeShopRates()).RatesHelpLine();
|
||||
|
||||
public static string SheetRow(int slot, TradeShopListing l, TradeShopRates? rates)
|
||||
=> $"#{slot} {l.Label()}: {(rates ?? new TradeShopRates()).FormatAlternatives(l.PricePyreals)}";
|
||||
|
||||
/// <summary>The price sheet in at most <see cref="MaxSheetChunks"/> chunks of at most <see cref="MaxLineChars"/>.</summary>
|
||||
public static List<string> PriceSheet(IReadOnlyList<TradeShopListing> listings, TradeShopRates? rates,
|
||||
bool includeRates, string? header = null, int maxChunks = MaxSheetChunks)
|
||||
{
|
||||
maxChunks = Math.Max(1, maxChunks);
|
||||
var parts = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(header)) parts.Add(Clip(header.Trim()));
|
||||
if (includeRates) parts.Add(Clip(RatesLine(rates)));
|
||||
if (listings == null || listings.Count == 0) parts.Add("Price sheet: (empty)");
|
||||
else
|
||||
{
|
||||
parts.Add($"Price sheet ({listings.Count}):");
|
||||
for (int i = 0; i < listings.Count; i++)
|
||||
if (listings[i] != null) parts.Add(Clip(SheetRow(i + 1, listings[i], rates)));
|
||||
}
|
||||
|
||||
// Greedy chunks, remembering how many parts each holds.
|
||||
var chunks = new List<string>();
|
||||
var counts = new List<int>();
|
||||
var sb = new StringBuilder();
|
||||
int inChunk = 0;
|
||||
foreach (string part in parts)
|
||||
{
|
||||
if (sb.Length > 0 && sb.Length + 3 + part.Length > MaxLineChars)
|
||||
{
|
||||
chunks.Add(sb.ToString());
|
||||
counts.Add(inChunk);
|
||||
sb.Clear();
|
||||
inChunk = 0;
|
||||
}
|
||||
if (sb.Length > 0) sb.Append(" | ");
|
||||
sb.Append(part);
|
||||
inChunk++;
|
||||
}
|
||||
if (sb.Length > 0) { chunks.Add(sb.ToString()); counts.Add(inChunk); }
|
||||
if (chunks.Count <= maxChunks) return chunks;
|
||||
|
||||
// Too long: the first maxChunks - 1 chunks, then one line saying how many rows weren't sent.
|
||||
int sent = 0;
|
||||
for (int i = 0; i < maxChunks - 1; i++) sent += counts[i];
|
||||
var capped = chunks.GetRange(0, maxChunks - 1);
|
||||
capped.Add($"...and {parts.Count - sent} more. Ask !price <name> for one item.");
|
||||
return capped;
|
||||
}
|
||||
|
||||
/// <summary>Find a listing: #slot / slot:N / bare small number, a price (exact, else the nearest at or above), or a name.</summary>
|
||||
public static TradeShopListing? ResolveListing(IReadOnlyList<TradeShopListing> list, string? arg)
|
||||
{
|
||||
if (list == null || list.Count == 0) return null;
|
||||
var (slot, valuePy, text) = TradeShopTellParse.ParseSelector(arg);
|
||||
if (slot.HasValue)
|
||||
return slot.Value >= 1 && slot.Value <= list.Count ? list[slot.Value - 1] : null;
|
||||
if (valuePy.HasValue)
|
||||
{
|
||||
long v = valuePy.Value;
|
||||
return list.FirstOrDefault(l => l.PricePyreals == v)
|
||||
?? list.Where(l => l.PricePyreals >= v).OrderBy(l => l.PricePyreals).FirstOrDefault();
|
||||
}
|
||||
if (text.Length == 0) return null;
|
||||
return list.FirstOrDefault(l => string.Equals(l.Name, text, StringComparison.OrdinalIgnoreCase))
|
||||
?? list.FirstOrDefault(l => l.Name.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0);
|
||||
}
|
||||
|
||||
/// <summary>One line, no line breaks, at most <see cref="MaxLineChars"/>.</summary>
|
||||
public static string Clip(string? s)
|
||||
{
|
||||
string t = (s ?? "").Replace('\r', ' ').Replace('\n', ' ').Trim();
|
||||
return t.Length <= MaxLineChars ? t : t[..(MaxLineChars - 3)] + "...";
|
||||
}
|
||||
}
|
||||
100
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopPayment.cs
Normal file
100
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopPayment.cs
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
// Trade Shop: add up the payment on the buyer's side of the trade window, by WCID.
|
||||
// Ported from SilentKelpie's Trade Shop (RynthSuite PR #12); re-implemented here: an item counts
|
||||
// only through TradeShopCurrencyTable (WCID), never through its name or its Value property, and an
|
||||
// item the client can't read yet (no WCID, or a currency stack with no stack size) is Unknown, which
|
||||
// never counts as paid.
|
||||
//
|
||||
// Pure (System only): RynthCore.RynthAiTests links it.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Trade;
|
||||
|
||||
/// <summary>
|
||||
/// One object as the shop sees it. <see cref="Known"/> false: the client has no WCID for it (yet).
|
||||
/// <see cref="Stack"/>: the stack size; 0 = not stackable (one item), -1 = not readable.
|
||||
/// </summary>
|
||||
public readonly record struct TradeShopItem(uint Id, uint Wcid, string Name, int Stack, bool Known, bool Equipped = false);
|
||||
|
||||
/// <summary>What one side of the trade window adds up to.</summary>
|
||||
public sealed class TradeShopTally
|
||||
{
|
||||
public long Pyreals;
|
||||
/// <summary>Trade notes, at their WCID's face value.</summary>
|
||||
public long NotePyreals;
|
||||
public long LegendaryKeys;
|
||||
/// <summary>Items that are not payment (worth 0).</summary>
|
||||
public int OtherItems;
|
||||
/// <summary>Items the client can't read yet: the payment isn't known until this is 0.</summary>
|
||||
public int Unknown;
|
||||
/// <summary>Item count per kind, for the sale line ("3x Trade Note (250,000)").</summary>
|
||||
public readonly List<string> Lines = new();
|
||||
|
||||
/// <summary>"1,000,000 py (pyreals 0, notes 1,000,000), 2 LK, 1 other item worth 0".</summary>
|
||||
public string Describe()
|
||||
{
|
||||
var parts = new List<string>();
|
||||
if (Pyreals > 0) parts.Add(TradeShopRates.N(Pyreals) + " pyreals");
|
||||
if (NotePyreals > 0) parts.Add(TradeShopRates.N(NotePyreals) + " py in trade notes");
|
||||
if (LegendaryKeys > 0) parts.Add(TradeShopRates.N(LegendaryKeys) + " Legendary Key" + (LegendaryKeys == 1 ? "" : "s"));
|
||||
if (OtherItems > 0) parts.Add(OtherItems + " other item" + (OtherItems == 1 ? "" : "s") + " (worth 0)");
|
||||
if (Unknown > 0) parts.Add(Unknown + " item" + (Unknown == 1 ? "" : "s") + " not read yet");
|
||||
return parts.Count == 0 ? "nothing" : string.Join(", ", parts);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Adds up payment items by WCID.</summary>
|
||||
public static class TradeShopPayment
|
||||
{
|
||||
/// <summary>
|
||||
/// Tally <paramref name="itemIds"/>; <paramref name="lookup"/> reads one object (null: the client
|
||||
/// doesn't have it). Unknown objects and currency stacks without a readable size count as Unknown.
|
||||
/// </summary>
|
||||
public static TradeShopTally Tally(IEnumerable<uint> itemIds, Func<uint, TradeShopItem?> lookup)
|
||||
{
|
||||
var t = new TradeShopTally();
|
||||
if (itemIds == null) return t;
|
||||
foreach (uint id in itemIds)
|
||||
{
|
||||
if (id == 0) continue;
|
||||
TradeShopItem? read = lookup?.Invoke(id);
|
||||
if (read is not { } item || !item.Known || item.Wcid == 0)
|
||||
{
|
||||
t.Unknown++;
|
||||
continue;
|
||||
}
|
||||
TradeShopCurrency kind = TradeShopCurrencyTable.Classify(item.Wcid);
|
||||
switch (kind)
|
||||
{
|
||||
case TradeShopCurrency.Pyreals:
|
||||
if (item.Stack <= 0) { t.Unknown++; break; }
|
||||
t.Pyreals += item.Stack;
|
||||
t.Lines.Add(N(item.Stack) + " pyreals");
|
||||
break;
|
||||
case TradeShopCurrency.TradeNote:
|
||||
{
|
||||
if (item.Stack <= 0) { t.Unknown++; break; }
|
||||
long face = TradeShopCurrencyTable.NoteFaceValue(item.Wcid);
|
||||
t.NotePyreals += face * item.Stack;
|
||||
t.Lines.Add(item.Stack + "x Trade Note (" + N(face) + ")");
|
||||
break;
|
||||
}
|
||||
case TradeShopCurrency.LegendaryKey:
|
||||
{
|
||||
int n = Math.Max(1, item.Stack);
|
||||
t.LegendaryKeys += n;
|
||||
t.Lines.Add(n + "x Legendary Key");
|
||||
break;
|
||||
}
|
||||
default:
|
||||
t.OtherItems++;
|
||||
t.Lines.Add((string.IsNullOrWhiteSpace(item.Name) ? "an item" : item.Name.Trim()) + " (not payment)");
|
||||
break;
|
||||
}
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
private static string N(long v) => v.ToString("N0", CultureInfo.InvariantCulture);
|
||||
}
|
||||
105
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopRates.cs
Normal file
105
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopRates.cs
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
// Trade Shop prices: listings are priced in pyreals; a buyer pays in pyreals, trade notes (at face
|
||||
// value) or single-use Legendary Keys (at the seller's pyreals-per-key rate).
|
||||
// Ported from SilentKelpie's Trade Shop (RynthSuite PR #12); re-implemented here. His rates table
|
||||
// also took currencies that only one server has; those have no retail WCID, so they aren't payment
|
||||
// here (TradeShopCurrencyTable.cs).
|
||||
//
|
||||
// Pure (System only): RynthCore.RynthAiTests links it.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Trade;
|
||||
|
||||
/// <summary>Which currencies the shop takes, and what a Legendary Key is worth to it.</summary>
|
||||
public sealed class TradeShopRates
|
||||
{
|
||||
/// <summary>Default: 2 MMD a key.</summary>
|
||||
public const long DefaultPyrealsPerLegendaryKey = 2 * TradeShopCurrencyTable.PyrealsPerMmd;
|
||||
|
||||
/// <summary>What one single-use Legendary Key counts for, in pyreals (0 or less: keys not taken).</summary>
|
||||
public long PyrealsPerLegendaryKey = DefaultPyrealsPerLegendaryKey;
|
||||
|
||||
public bool AcceptPyreals = true;
|
||||
public bool AcceptTradeNotes = true;
|
||||
public bool AcceptLegendaryKeys = true;
|
||||
|
||||
/// <summary>True when keys are taken and have a rate.</summary>
|
||||
public bool TakesKeys => AcceptLegendaryKeys && PyrealsPerLegendaryKey > 0;
|
||||
|
||||
/// <summary>Keys that pay <paramref name="pricePyreals"/> (rounded up; 0 when keys aren't taken).</summary>
|
||||
public long KeysFor(long pricePyreals)
|
||||
{
|
||||
if (pricePyreals <= 0 || !TakesKeys) return 0;
|
||||
return (pricePyreals + PyrealsPerLegendaryKey - 1) / PyrealsPerLegendaryKey;
|
||||
}
|
||||
|
||||
/// <summary>MMD notes that pay <paramref name="pricePyreals"/> (rounded up; 0 when notes aren't taken).</summary>
|
||||
public long MmdFor(long pricePyreals)
|
||||
{
|
||||
if (pricePyreals <= 0 || !AcceptTradeNotes) return 0;
|
||||
return (pricePyreals + TradeShopCurrencyTable.PyrealsPerMmd - 1) / TradeShopCurrencyTable.PyrealsPerMmd;
|
||||
}
|
||||
|
||||
/// <summary>The pyreal worth of what the shop takes in <paramref name="tally"/> (refused currencies count 0).</summary>
|
||||
public long AcceptedPyreals(TradeShopTally tally)
|
||||
{
|
||||
if (tally == null) return 0;
|
||||
long total = 0;
|
||||
if (AcceptPyreals) total = Add(total, tally.Pyreals);
|
||||
if (AcceptTradeNotes) total = Add(total, tally.NotePyreals);
|
||||
if (TakesKeys) total = Add(total, Mul(tally.LegendaryKeys, PyrealsPerLegendaryKey));
|
||||
return total;
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="tally"/> covers <paramref name="pricePyreals"/> (and every item in it is known).</summary>
|
||||
public bool Covers(long pricePyreals, TradeShopTally tally)
|
||||
=> pricePyreals > 0 && tally != null && tally.Unknown == 0 && AcceptedPyreals(tally) >= pricePyreals;
|
||||
|
||||
/// <summary>The ways to pay a listing: "1,000,000 py (pyreals or notes, 4 MMD) / 2 LK".</summary>
|
||||
public string FormatAlternatives(long pricePyreals)
|
||||
{
|
||||
if (pricePyreals <= 0) return "(no price)";
|
||||
var parts = new List<string>();
|
||||
if (AcceptPyreals || AcceptTradeNotes)
|
||||
{
|
||||
string how = AcceptPyreals && AcceptTradeNotes ? "pyreals or notes" : AcceptPyreals ? "pyreals" : "notes";
|
||||
string py = N(pricePyreals) + " py (" + how;
|
||||
long mmd = MmdFor(pricePyreals);
|
||||
if (AcceptTradeNotes && pricePyreals >= TradeShopCurrencyTable.PyrealsPerMmd && mmd > 0) py += ", " + N(mmd) + " MMD";
|
||||
parts.Add(py + ")");
|
||||
}
|
||||
long keys = KeysFor(pricePyreals);
|
||||
if (keys > 0) parts.Add(N(keys) + " LK");
|
||||
return parts.Count == 0 ? "(the shop takes no payment)" : string.Join(" / ", parts);
|
||||
}
|
||||
|
||||
/// <summary>One line for !rates and the window.</summary>
|
||||
public string RatesHelpLine()
|
||||
{
|
||||
var take = new List<string>();
|
||||
if (AcceptPyreals) take.Add("pyreals");
|
||||
if (AcceptTradeNotes) take.Add("trade notes at face value (1 MMD = " + N(TradeShopCurrencyTable.PyrealsPerMmd) + " py)");
|
||||
if (TakesKeys) take.Add("single-use Legendary Keys (1 LK = " + N(PyrealsPerLegendaryKey) + " py)");
|
||||
return take.Count == 0 ? "The shop takes no payment right now." : "Takes " + string.Join(", ", take) + ".";
|
||||
}
|
||||
|
||||
/// <summary>A copy (the window edits one, the command line another).</summary>
|
||||
public TradeShopRates Clone() => new()
|
||||
{
|
||||
PyrealsPerLegendaryKey = PyrealsPerLegendaryKey,
|
||||
AcceptPyreals = AcceptPyreals,
|
||||
AcceptTradeNotes = AcceptTradeNotes,
|
||||
AcceptLegendaryKeys = AcceptLegendaryKeys,
|
||||
};
|
||||
|
||||
internal static string N(long v) => v.ToString("N0", CultureInfo.InvariantCulture);
|
||||
|
||||
private static long Add(long a, long b) => b > 0 && a > long.MaxValue - b ? long.MaxValue : a + Math.Max(0, b);
|
||||
|
||||
private static long Mul(long a, long b)
|
||||
{
|
||||
if (a <= 0 || b <= 0) return 0;
|
||||
return a > long.MaxValue / b ? long.MaxValue : a * b;
|
||||
}
|
||||
}
|
||||
92
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopSettings.cs
Normal file
92
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopSettings.cs
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
// Trade Shop settings and catalog rows (LegacyUiSettings.TradeShop).
|
||||
// Ported from SilentKelpie's Trade Shop (RynthSuite PR #12); re-implemented here.
|
||||
//
|
||||
// Pure (System only): RynthCore.RynthAiTests links it.
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Trade;
|
||||
|
||||
/// <summary>How a sale is fulfilled.</summary>
|
||||
public enum TradeShopMode
|
||||
{
|
||||
/// <summary>The item is in this character's pack: the shop puts it in the trade window.</summary>
|
||||
Mode1Stock = 0,
|
||||
/// <summary>
|
||||
/// A text listing (another account holds the item): the buyer pays in the window, the shop checks
|
||||
/// the payment and the player accepts by hand (the shop never accepts a Mode 2 sale itself), then
|
||||
/// hands the item over from wherever it is.
|
||||
/// </summary>
|
||||
Mode2Text = 1,
|
||||
}
|
||||
|
||||
/// <summary>One sellable row.</summary>
|
||||
public sealed class TradeShopListing
|
||||
{
|
||||
/// <summary>Display name (Mode 1: the item's name when it was listed; Mode 2: typed).</summary>
|
||||
public string Name = "";
|
||||
/// <summary>Mode 2: what the buyer is told after paying (where and how they get the item).</summary>
|
||||
public string Description = "";
|
||||
public long PricePyreals;
|
||||
/// <summary>Mode 1: the item's object id when it was listed (0: find it by WCID and name).</summary>
|
||||
public uint ObjectId;
|
||||
/// <summary>Mode 1: the item's WCID when it was listed (0: unknown, then the name must match).</summary>
|
||||
public uint Wcid;
|
||||
/// <summary>Mode 1: the stack size when it was listed (0: not a stack). The stack sold must still be this size.</summary>
|
||||
public int Stack;
|
||||
/// <summary>Mode 2: which character holds it (shown to the seller only).</summary>
|
||||
public string HeldBy = "";
|
||||
/// <summary>False: listed but not for sale.</summary>
|
||||
public bool Enabled = true;
|
||||
|
||||
public string Label() => (Name.Length > 0 ? Name : "(unnamed)") + (Stack > 1 ? " (stack of " + Stack + ")" : "");
|
||||
}
|
||||
|
||||
/// <summary>Every Trade Shop setting (one LegacyUiSettings field).</summary>
|
||||
public sealed class TradeShopSettings
|
||||
{
|
||||
/// <summary>Shortest advertise interval: 5 minutes.</summary>
|
||||
public const int MinAdvertiseSec = 300;
|
||||
public const int MaxAdvertiseSec = 3600;
|
||||
public const int DefaultAdvertiseSec = 600;
|
||||
|
||||
/// <summary>
|
||||
/// The shop is on. Never saved: every login starts with the shop off, and the player turns it on
|
||||
/// (the window's checkbox or /ra tradeshop on), which says what it does.
|
||||
/// </summary>
|
||||
[JsonIgnore] public bool Enabled;
|
||||
|
||||
public TradeShopMode Mode = TradeShopMode.Mode1Stock;
|
||||
|
||||
/// <summary>
|
||||
/// On (the default): the shop gets each sale ready (the item in the window, the payment checked by
|
||||
/// WCID) and waits for the player's Accept sale. Off: it accepts a checked Mode 1 sale itself.
|
||||
/// </summary>
|
||||
public bool ConfirmEachSale = true;
|
||||
|
||||
public TradeShopRates Rates { get; set; } = new();
|
||||
public List<TradeShopListing> Listings { get; set; } = new();
|
||||
|
||||
public bool AdvertiseEnabled;
|
||||
public TradeShopAdvertiseChannel AdvertiseChannel = TradeShopAdvertiseChannel.Trade;
|
||||
public int AdvertiseIntervalSec = DefaultAdvertiseSec;
|
||||
public string AdvertisePrefix = "";
|
||||
|
||||
/// <summary>Guards <see cref="Listings"/> (the window edits it on the render thread, the shop reads it on the tick).</summary>
|
||||
[JsonIgnore] public readonly object Sync = new();
|
||||
|
||||
public static int ClampAdvertiseSec(int sec) => sec < MinAdvertiseSec ? MinAdvertiseSec : sec > MaxAdvertiseSec ? MaxAdvertiseSec : sec;
|
||||
|
||||
/// <summary>The rows for sale now (enabled, priced, named), copied under the lock.</summary>
|
||||
public List<TradeShopListing> ForSale()
|
||||
{
|
||||
var list = new List<TradeShopListing>();
|
||||
lock (Sync)
|
||||
{
|
||||
foreach (TradeShopListing? l in Listings ?? new List<TradeShopListing>())
|
||||
if (l != null && l.Enabled && l.PricePyreals > 0 && !string.IsNullOrWhiteSpace(l.Name))
|
||||
list.Add(l);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
130
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopTellLimiter.cs
Normal file
130
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopTellLimiter.cs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
// Trade Shop: how many tells it reads and sends. A shop that answers every tell with a price sheet
|
||||
// can be made to flood chat (and get the seller muted), so (time passed in, pure):
|
||||
// * per buyer: one command every 2 s; at most 20 lines a minute read; past that, or after 5 too-fast
|
||||
// commands in a minute, the buyer is ignored for 2 minutes (told once);
|
||||
// * per buyer at most 12 lines a minute sent, and at most 30 lines a minute sent in all;
|
||||
// * the inbound and outbound queues are capped (TradeShopManager drops what doesn't fit).
|
||||
// Ported from SilentKelpie's Trade Shop (RynthSuite PR #12) as a new part: his shop had no limits.
|
||||
//
|
||||
// Pure (System only): RynthCore.RynthAiTests links it.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Trade;
|
||||
|
||||
public sealed class TradeShopTellLimiter
|
||||
{
|
||||
public const long MinCommandGapMs = 2_000;
|
||||
public const int MaxInLinesPerMinute = 20;
|
||||
public const int SpamStrikes = 5;
|
||||
public const long SpamIgnoreMs = 120_000;
|
||||
public const int MaxOutPerBuyerPerMinute = 12;
|
||||
public const int MaxOutPerMinute = 30;
|
||||
public const int MaxInQueue = 20;
|
||||
public const int MaxOutQueue = 40;
|
||||
private const long MinuteMs = 60_000;
|
||||
private const int MaxBuyers = 200;
|
||||
|
||||
public enum Verdict
|
||||
{
|
||||
/// <summary>Handle it.</summary>
|
||||
Accept,
|
||||
/// <summary>Within 2 s of their last command: dropped.</summary>
|
||||
TooFast,
|
||||
/// <summary>The buyer is being ignored: dropped.</summary>
|
||||
Ignored,
|
||||
/// <summary>This line started the ignore: dropped, and the buyer is told once.</summary>
|
||||
NowIgnored,
|
||||
}
|
||||
|
||||
private sealed class Buyer
|
||||
{
|
||||
public long LastCommandAt = long.MinValue / 2;
|
||||
public long IgnoredUntil = long.MinValue / 2;
|
||||
public long LastSeen;
|
||||
public readonly Queue<long> InLines = new();
|
||||
public readonly Queue<long> Strikes = new();
|
||||
public readonly Queue<long> OutLines = new();
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, Buyer> _buyers = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Queue<long> _out = new();
|
||||
|
||||
/// <summary>A tell from <paramref name="buyer"/> arrived at <paramref name="now"/> (ms).</summary>
|
||||
public Verdict OnIncoming(string buyer, long now)
|
||||
{
|
||||
Buyer b = Get(buyer, now);
|
||||
if (now < b.IgnoredUntil) return Verdict.Ignored;
|
||||
Trim(b.InLines, now);
|
||||
Trim(b.Strikes, now);
|
||||
b.InLines.Enqueue(now);
|
||||
bool tooFast = now - b.LastCommandAt < MinCommandGapMs;
|
||||
if (tooFast) b.Strikes.Enqueue(now);
|
||||
if (b.InLines.Count > MaxInLinesPerMinute || b.Strikes.Count >= SpamStrikes)
|
||||
{
|
||||
b.IgnoredUntil = now + SpamIgnoreMs;
|
||||
b.InLines.Clear();
|
||||
b.Strikes.Clear();
|
||||
return Verdict.NowIgnored;
|
||||
}
|
||||
if (tooFast) return Verdict.TooFast;
|
||||
b.LastCommandAt = now;
|
||||
return Verdict.Accept;
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="buyer"/> is being ignored now.</summary>
|
||||
public bool IsIgnored(string buyer, long now) => _buyers.TryGetValue(buyer, out Buyer? b) && now < b.IgnoredUntil;
|
||||
|
||||
/// <summary>May one line go to <paramref name="to"/> now? True takes the slot (the caller sends it).</summary>
|
||||
public bool TryTakeOut(string to, long now, bool overBuyerCap = false)
|
||||
{
|
||||
Trim(_out, now);
|
||||
if (_out.Count >= MaxOutPerMinute) return false;
|
||||
Buyer b = Get(to, now);
|
||||
Trim(b.OutLines, now);
|
||||
if (!overBuyerCap && b.OutLines.Count >= MaxOutPerBuyerPerMinute) return false;
|
||||
_out.Enqueue(now);
|
||||
b.OutLines.Enqueue(now);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Lines sent in the last minute (all buyers).</summary>
|
||||
public int SentLastMinute(long now) { Trim(_out, now); return _out.Count; }
|
||||
|
||||
public void Clear() { _buyers.Clear(); _out.Clear(); }
|
||||
|
||||
private Buyer Get(string name, long now)
|
||||
{
|
||||
string key = (name ?? "").Trim();
|
||||
if (!_buyers.TryGetValue(key, out Buyer? b))
|
||||
{
|
||||
if (_buyers.Count >= MaxBuyers) Forget(now);
|
||||
b = new Buyer();
|
||||
_buyers[key] = b;
|
||||
}
|
||||
b.LastSeen = now;
|
||||
return b;
|
||||
}
|
||||
|
||||
// Too many buyers remembered: drop those not ignored and not seen for a minute, else the oldest.
|
||||
private void Forget(long now)
|
||||
{
|
||||
var stale = new List<string>();
|
||||
foreach (var kv in _buyers)
|
||||
if (now >= kv.Value.IgnoredUntil && now - kv.Value.LastSeen > MinuteMs) stale.Add(kv.Key);
|
||||
if (stale.Count == 0)
|
||||
{
|
||||
string? oldest = null;
|
||||
long at = long.MaxValue;
|
||||
foreach (var kv in _buyers)
|
||||
if (kv.Value.LastSeen < at) { at = kv.Value.LastSeen; oldest = kv.Key; }
|
||||
if (oldest != null) stale.Add(oldest);
|
||||
}
|
||||
foreach (string k in stale) _buyers.Remove(k);
|
||||
}
|
||||
|
||||
private static void Trim(Queue<long> q, long now)
|
||||
{
|
||||
while (q.Count > 0 && now - q.Peek() >= MinuteMs) q.Dequeue();
|
||||
}
|
||||
}
|
||||
92
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopTellParse.cs
Normal file
92
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopTellParse.cs
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
// Trade Shop: parse an incoming tell and a buyer's item selector.
|
||||
// Ported from SilentKelpie's Trade Shop (RynthSuite PR #12); re-implemented here.
|
||||
//
|
||||
// Pure (System only): RynthCore.RynthAiTests links it.
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Trade;
|
||||
|
||||
public static class TradeShopTellParse
|
||||
{
|
||||
// "Name tells you, "msg"" with or without the client's <Tell:IIDString:...> name link. The name is
|
||||
// the first speaker (lazy), so a quoted "X tells you" inside the message can't change who sent it.
|
||||
private static readonly Regex TellLineRx = new(
|
||||
@"^(?:<Tell:IIDString:\d+:(?<linkName>[^>]+)>[^<]*<\\Tell>|(?<plainName>[^""<>]+?))\s+tells you,?\s*""(?<msg>.*)""\s*$",
|
||||
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Singleline, TimeSpan.FromMilliseconds(100));
|
||||
|
||||
// A character name the shop will send a /tell to: letters first, then letters, spaces, ' - (AC names).
|
||||
private static readonly Regex NameRx = new(@"^[A-Za-z][A-Za-z '\-]{0,31}$", RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>Longest tell body the shop reads (longer ones are ignored).</summary>
|
||||
public const int MaxMessageChars = 200;
|
||||
|
||||
/// <summary>Parse AC's "Name tells you, "msg"".</summary>
|
||||
public static bool TryParseTell(string? text, out string sender, out string message)
|
||||
{
|
||||
sender = "";
|
||||
message = "";
|
||||
if (string.IsNullOrWhiteSpace(text) || text.Length > 400) return false;
|
||||
Match m;
|
||||
try { m = TellLineRx.Match(text.Trim()); }
|
||||
catch (RegexMatchTimeoutException) { return false; }
|
||||
if (!m.Success) return false;
|
||||
sender = (m.Groups["linkName"].Success && m.Groups["linkName"].Length > 0
|
||||
? m.Groups["linkName"].Value : m.Groups["plainName"].Value).Trim();
|
||||
message = m.Groups["msg"].Value;
|
||||
return IsSafeName(sender) && message.Length <= MaxMessageChars;
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="name"/> looks like an AC character name (safe to put after /tell).</summary>
|
||||
public static bool IsSafeName(string? name) => !string.IsNullOrEmpty(name) && NameRx.IsMatch(name);
|
||||
|
||||
/// <summary>
|
||||
/// A selector: slot (#N, slot:N, bare 1..999), price (value:N, py:N, bare 1000 and up), or name text.
|
||||
/// </summary>
|
||||
public static (int? slot, long? valuePy, string text) ParseSelector(string? raw)
|
||||
{
|
||||
string text = (raw ?? "").Trim();
|
||||
if (text.Length == 0) return (null, null, "");
|
||||
if (text.Length > 1 && ((text[0] == '"' && text[^1] == '"') || (text[0] == '\'' && text[^1] == '\'')))
|
||||
text = text[1..^1].Trim();
|
||||
|
||||
if (text.StartsWith('#') && int.TryParse(text[1..].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int hash) && hash > 0)
|
||||
return (hash, null, "");
|
||||
foreach (string p in new[] { "slot:", "id:" })
|
||||
if (text.StartsWith(p, StringComparison.OrdinalIgnoreCase)
|
||||
&& int.TryParse(text[p.Length..].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int s) && s > 0)
|
||||
return (s, null, "");
|
||||
foreach (string p in new[] { "value:", "py:", "price:" })
|
||||
if (text.StartsWith(p, StringComparison.OrdinalIgnoreCase)
|
||||
&& long.TryParse(text[p.Length..].Trim().Replace(",", ""), NumberStyles.Integer, CultureInfo.InvariantCulture, out long v) && v > 0)
|
||||
return (null, v, "");
|
||||
if (long.TryParse(text.Replace(",", ""), NumberStyles.Integer, CultureInfo.InvariantCulture, out long n) && n > 0)
|
||||
return n < 1000 ? ((int)n, null, "") : (null, n, "");
|
||||
return (null, null, text);
|
||||
}
|
||||
|
||||
/// <summary>The verb and argument of a shop tell ("!buy #2" -> ("buy", "#2")); empty verb when it isn't one.</summary>
|
||||
public static (string verb, string arg) SplitCommand(string? body)
|
||||
{
|
||||
string raw = (body ?? "").Trim();
|
||||
bool bang = raw.StartsWith('!');
|
||||
if (bang) raw = raw[1..].Trim();
|
||||
if (raw.Length == 0) return ("", "");
|
||||
string[] parts = raw.Split((char[]?)null, 2, StringSplitOptions.RemoveEmptyEntries);
|
||||
string verb = parts[0].ToLowerInvariant();
|
||||
string arg = parts.Length > 1 ? parts[1].Trim() : "";
|
||||
verb = verb switch
|
||||
{
|
||||
"help" or "hi" or "hello" or "shop" => "help",
|
||||
"rates" or "rate" => "rates",
|
||||
"list" or "sheet" or "catalog" or "menu" => "list",
|
||||
"price" or "cost" => "price",
|
||||
"buy" => "buy",
|
||||
_ => "",
|
||||
};
|
||||
// Without the '!' only a lone greeting counts: free-form chat ("hello, how are you") gets nothing.
|
||||
if (!bang && (verb != "help" || arg.Length > 0)) return ("", "");
|
||||
return (verb, arg);
|
||||
}
|
||||
}
|
||||
298
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopWindow.cs
Normal file
298
Plugins/RynthCore.Plugin.RynthAi/Trade/TradeShopWindow.cs
Normal file
|
|
@ -0,0 +1,298 @@
|
|||
// The Trade Shop window: the shop's switch, the sale waiting for Accept sale, the catalog and its
|
||||
// prices, what payment it takes, advertising and the last sales.
|
||||
// Ported from SilentKelpie's Trade Shop (RynthSuite PR #12); re-implemented here. RynthCore hosts it
|
||||
// as a plugin window (the sections manifest's "tradeshop" window, plugin API v89) with no bar button:
|
||||
// the RynthAi window's options menu (Trade shop) and /ra tradeshop open it.
|
||||
//
|
||||
// AC's render thread. Settings edits go straight in (the catalog under its lock); anything that
|
||||
// trades, tells or prints is queued for the tick through the manager or the callbacks.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.Plugin.Shared.RynthUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Trade;
|
||||
|
||||
internal sealed class TradeShopWindow
|
||||
{
|
||||
private readonly Func<TradeShopSettings?> _settings;
|
||||
private readonly Func<TradeShopManager?> _shop;
|
||||
private readonly Action<long> _addSelected; // queued: the selected item at this price
|
||||
private readonly Action _changed; // a setting changed: save the profile
|
||||
|
||||
private int _newPrice = 100_000;
|
||||
private string _newName = "";
|
||||
private string _newDesc = "";
|
||||
private string _newHeldBy = "";
|
||||
|
||||
private const string HelpText =
|
||||
"A shop run from tells. Buyers tell you !list (prices), !rates, !price <#slot|name> and !buy <#slot|name>.\n\n" +
|
||||
"Mode 1 (items in this character's packs): after !buy, the buyer opens a trade with you, the shop puts the item " +
|
||||
"in the window and checks their payment. Mode 2 (an item another character holds): the shop checks the payment " +
|
||||
"and you accept by hand, then hand the item over.\n\n" +
|
||||
"Payment counts by item type only: pyreals, trade notes at face value, and single-use Legendary Keys at your rate. " +
|
||||
"Anything else in the window is worth 0, and an item the game hasn't shown yet is never counted.\n\n" +
|
||||
"Confirm each sale (on by default): the shop stops before accepting and asks you. Off: it accepts a checked " +
|
||||
"Mode 1 sale itself. Either way it checks both sides again the moment it accepts, and withdraws its accept " +
|
||||
"if the trade changes.\n\n" +
|
||||
"It never accepts a trade nobody asked to !buy in, is off at every login, and pauses in combat, while the macro " +
|
||||
"or a hunt runs, and while AutoTrade is on. Sales go to chat, the log and TradeShopSales.log.\n\n" +
|
||||
"/ra tradeshop on | off | status | list | add <price> [name] | remove <#> | price <#> <py> | accept | decline | " +
|
||||
"mode1 | mode2 | confirm on|off | advertise ... | help";
|
||||
|
||||
public TradeShopWindow(Func<TradeShopSettings?> settings, Func<TradeShopManager?> shop, Action<long> addSelected, Action changed)
|
||||
{
|
||||
_settings = settings;
|
||||
_shop = shop;
|
||||
_addSelected = addSelected;
|
||||
_changed = changed;
|
||||
}
|
||||
|
||||
private float _k = 1f;
|
||||
private float Px(float v) => v * _k;
|
||||
|
||||
/// <summary>Draws the window body and returns the size it would like. Render thread.</summary>
|
||||
public Vector2 Draw()
|
||||
{
|
||||
_k = Math.Max(0.5f, Font(RynthUiFont.Ui11).FontSize / 11f);
|
||||
var want = new Vector2(Px(560), Px(520));
|
||||
Vector2 origin = ImGui.GetCursorScreenPos();
|
||||
Vector2 size = ImGui.GetContentRegionAvail();
|
||||
if (size.X < 60 || size.Y < 40) return want;
|
||||
ImDrawListPtr frame = ImGui.GetWindowDrawList();
|
||||
frame.AddRectFilled(origin, origin + size, Background, 4);
|
||||
TradeShopSettings? cfg = _settings();
|
||||
TradeShopManager? shop = _shop();
|
||||
using (PushFont(RynthUiFont.Ui11))
|
||||
{
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4));
|
||||
ImGui.PushStyleColor(ImGuiCol.Text, Text);
|
||||
ImGui.PushStyleColor(ImGuiCol.FrameBg, Field);
|
||||
ImGui.PushStyleColor(ImGuiCol.Button, ButtonFill);
|
||||
ImGui.PushStyleColor(ImGuiCol.ChildBg, 0u);
|
||||
ImGui.SetCursorScreenPos(origin + new Vector2(6, 6));
|
||||
ImGui.BeginChild("##ts_body", size - new Vector2(12, 12));
|
||||
if (cfg == null || shop == null) Label("The Trade Shop is ready once you are in the world.", Mute);
|
||||
else DrawBody(cfg, shop);
|
||||
ImGui.EndChild();
|
||||
ImGui.PopStyleColor(4);
|
||||
ImGui.PopStyleVar();
|
||||
}
|
||||
frame.AddRect(origin, origin + size, Border, 4);
|
||||
return want;
|
||||
}
|
||||
|
||||
private void DrawBody(TradeShopSettings cfg, TradeShopManager shop)
|
||||
{
|
||||
// ── On / off, status, help ──
|
||||
bool on = cfg.Enabled;
|
||||
if (ImGui.Checkbox("Shop on##ts_on", ref on)) shop.SetEnabled(on);
|
||||
SafeImGui.SetItemTooltip("Off at every login. Turning it on says in chat what it does.");
|
||||
ImGui.SameLine();
|
||||
Label(shop.Status, Mute);
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X + ImGui.GetCursorPosX() - Px(22));
|
||||
ImGui.TextDisabled("(?)");
|
||||
if (ImGui.IsItemHovered())
|
||||
{
|
||||
ImGui.BeginTooltip();
|
||||
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 34);
|
||||
ImGui.TextUnformatted(HelpText);
|
||||
ImGui.PopTextWrapPos();
|
||||
ImGui.EndTooltip();
|
||||
}
|
||||
|
||||
// ── The sale waiting for the player ──
|
||||
TradeShopPrompt? p = shop.Prompt;
|
||||
if (p != null)
|
||||
{
|
||||
ImGui.Spacing();
|
||||
ImGui.PushStyleColor(ImGuiCol.ChildBg, AccentFill);
|
||||
ImGui.BeginChild("##ts_prompt", new Vector2(-1, Px(96)), ImGuiChildFlags.Borders);
|
||||
Label("Sale ready" + (p.Mode == TradeShopMode.Mode2Text ? " (Mode 2: you hand the item over after)" : ""), Accent);
|
||||
Label($"Buyer: {p.Buyer}", Text);
|
||||
Label($"Item: {p.Item} Price: {TradeShopRates.N(p.PricePyreals)} py ({p.Price})", Text);
|
||||
ImGui.PushTextWrapPos(0);
|
||||
Label($"Paid: {p.Paid}", Green);
|
||||
ImGui.PopTextWrapPos();
|
||||
if (ImGui.Button("Accept sale##ts_accept")) shop.RequestAccept();
|
||||
SafeImGui.SetItemTooltip("Checks both sides of the trade again, then accepts.");
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Decline##ts_decline")) shop.RequestDecline();
|
||||
SafeImGui.SetItemTooltip("Calls the sale off and closes the trade window.");
|
||||
ImGui.EndChild();
|
||||
ImGui.PopStyleColor();
|
||||
}
|
||||
|
||||
// ── Mode and Confirm each sale ──
|
||||
ImGui.Spacing();
|
||||
int mode = (int)cfg.Mode;
|
||||
bool modeChanged = ImGui.RadioButton("Mode 1: items in my packs##ts_m1", ref mode, 0);
|
||||
ImGui.SameLine();
|
||||
modeChanged |= ImGui.RadioButton("Mode 2: text listings (I accept by hand)##ts_m2", ref mode, 1);
|
||||
if (modeChanged) { cfg.Mode = (TradeShopMode)mode; _changed(); }
|
||||
bool confirm = cfg.ConfirmEachSale;
|
||||
if (ImGui.Checkbox("Confirm each sale##ts_confirm", ref confirm)) { shop.SetConfirmEachSale(confirm); _changed(); }
|
||||
SafeImGui.SetItemTooltip("On: the shop asks you before every accept (Accept sale / Decline here).\nOff: it accepts a checked Mode 1 sale itself.");
|
||||
if (!cfg.ConfirmEachSale)
|
||||
{
|
||||
ImGui.SameLine();
|
||||
Label(cfg.Mode == TradeShopMode.Mode1Stock ? "Warning: Mode 1 sales are accepted without asking you." : "(Mode 2 always asks.)", Red);
|
||||
}
|
||||
|
||||
// ── Catalog ──
|
||||
ImGui.Spacing();
|
||||
ImGui.Separator();
|
||||
Label("For sale", Accent);
|
||||
DrawCatalog(cfg);
|
||||
|
||||
// ── Payment ──
|
||||
ImGui.Spacing();
|
||||
ImGui.Separator();
|
||||
Label("Payment the shop takes", Accent);
|
||||
TradeShopRates r = cfg.Rates ??= new TradeShopRates();
|
||||
bool changed = ImGui.Checkbox("Pyreals##ts_py", ref r.AcceptPyreals);
|
||||
ImGui.SameLine();
|
||||
changed |= ImGui.Checkbox("Trade notes##ts_notes", ref r.AcceptTradeNotes);
|
||||
ImGui.SameLine();
|
||||
changed |= ImGui.Checkbox("Legendary Keys (single-use)##ts_lk", ref r.AcceptLegendaryKeys);
|
||||
if (r.AcceptLegendaryKeys)
|
||||
{
|
||||
int lk = (int)Math.Clamp(r.PyrealsPerLegendaryKey, 0, int.MaxValue);
|
||||
ImGui.SetNextItemWidth(Px(120));
|
||||
if (ImGui.InputInt("pyreals per key##ts_lkrate", ref lk, 0, 0)) { r.PyrealsPerLegendaryKey = Math.Max(0, lk); changed = true; }
|
||||
}
|
||||
if (changed) _changed();
|
||||
ImGui.PushTextWrapPos(0);
|
||||
Label(r.RatesHelpLine() + " Anything else is worth 0.", Mute);
|
||||
ImGui.PopTextWrapPos();
|
||||
|
||||
// ── Advertising ──
|
||||
ImGui.Spacing();
|
||||
ImGui.Separator();
|
||||
Label("Advertising", Accent);
|
||||
DrawAdvertise(cfg, shop);
|
||||
|
||||
// ── Last sales ──
|
||||
List<string> sales = shop.RecentSales();
|
||||
if (sales.Count > 0)
|
||||
{
|
||||
ImGui.Spacing();
|
||||
ImGui.Separator();
|
||||
Label($"Last sales ({sales.Count})", Accent);
|
||||
ImGui.PushTextWrapPos(0);
|
||||
for (int i = sales.Count - 1; i >= 0; i--) Label(sales[i], Mute);
|
||||
ImGui.PopTextWrapPos();
|
||||
}
|
||||
}
|
||||
|
||||
private void DrawCatalog(TradeShopSettings cfg)
|
||||
{
|
||||
TradeShopRates rates = cfg.Rates ?? new TradeShopRates();
|
||||
int removeAt = -1;
|
||||
bool changed = false;
|
||||
lock (cfg.Sync)
|
||||
{
|
||||
List<TradeShopListing> list = cfg.Listings ??= new List<TradeShopListing>();
|
||||
if (list.Count == 0)
|
||||
Label(cfg.Mode == TradeShopMode.Mode1Stock
|
||||
? "Nothing listed. Select an item in your inventory, set a price and press Add selected item."
|
||||
: "Nothing listed. Type a name, a price and what the buyer is told, then press Add listing.", Mute);
|
||||
else if (ImGui.BeginTable("##ts_cat", 5, ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp))
|
||||
{
|
||||
ImGui.TableSetupColumn("On", ImGuiTableColumnFlags.WidthFixed, Px(26));
|
||||
ImGui.TableSetupColumn("# Item", ImGuiTableColumnFlags.WidthStretch);
|
||||
ImGui.TableSetupColumn("Price (py)", ImGuiTableColumnFlags.WidthFixed, Px(100));
|
||||
ImGui.TableSetupColumn("Buyer pays", ImGuiTableColumnFlags.WidthStretch);
|
||||
ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthFixed, Px(46));
|
||||
ImGui.TableHeadersRow();
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
TradeShopListing? row = list[i];
|
||||
if (row == null) continue;
|
||||
ImGui.PushID(i);
|
||||
ImGui.TableNextRow();
|
||||
ImGui.TableNextColumn();
|
||||
changed |= ImGui.Checkbox("##en", ref row.Enabled);
|
||||
ImGui.TableNextColumn();
|
||||
ImGui.TextUnformatted($"#{i + 1} {row.Label()}");
|
||||
if (row.HeldBy.Length > 0 || row.Description.Length > 0)
|
||||
SafeImGui.SetItemTooltip((row.HeldBy.Length > 0 ? "Held by " + row.HeldBy + "\n" : "") + row.Description);
|
||||
ImGui.TableNextColumn();
|
||||
int price = (int)Math.Clamp(row.PricePyreals, 0, int.MaxValue);
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
if (ImGui.InputInt("##price", ref price, 0, 0)) { row.PricePyreals = Math.Max(0, price); changed = true; }
|
||||
ImGui.TableNextColumn();
|
||||
SafeImGui.TextDisabled(rates.FormatAlternatives(row.PricePyreals));
|
||||
ImGui.TableNextColumn();
|
||||
if (ImGui.SmallButton("Remove")) removeAt = i;
|
||||
ImGui.PopID();
|
||||
}
|
||||
ImGui.EndTable();
|
||||
}
|
||||
if (removeAt >= 0 && removeAt < list.Count) { list.RemoveAt(removeAt); changed = true; }
|
||||
}
|
||||
if (changed) _changed();
|
||||
|
||||
ImGui.SetNextItemWidth(Px(110));
|
||||
ImGui.InputInt("price (py)##ts_newprice", ref _newPrice, 0, 0);
|
||||
if (_newPrice < 1) _newPrice = 1;
|
||||
ImGui.SameLine();
|
||||
if (cfg.Mode == TradeShopMode.Mode1Stock)
|
||||
{
|
||||
if (ImGui.Button("Add selected item##ts_addsel")) _addSelected(_newPrice);
|
||||
SafeImGui.SetItemTooltip("Lists the item selected in your inventory at this price (/ra tradeshop add <price>).");
|
||||
return;
|
||||
}
|
||||
ImGui.SetNextItemWidth(Px(180));
|
||||
ImGui.InputText("name##ts_newname", ref _newName, 96);
|
||||
ImGui.SetNextItemWidth(Px(300));
|
||||
ImGui.InputText("told after paying##ts_newdesc", ref _newDesc, 160);
|
||||
ImGui.SetNextItemWidth(Px(140));
|
||||
ImGui.InputText("held by (you see it)##ts_newheld", ref _newHeldBy, 48);
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Add listing##ts_addtext") && _newName.Trim().Length > 0)
|
||||
{
|
||||
lock (cfg.Sync)
|
||||
(cfg.Listings ??= new List<TradeShopListing>()).Add(new TradeShopListing
|
||||
{
|
||||
Name = _newName.Trim(), Description = _newDesc.Trim(), HeldBy = _newHeldBy.Trim(), PricePyreals = _newPrice, Enabled = true,
|
||||
});
|
||||
_newName = _newDesc = _newHeldBy = "";
|
||||
_changed();
|
||||
}
|
||||
}
|
||||
|
||||
private void DrawAdvertise(TradeShopSettings cfg, TradeShopManager shop)
|
||||
{
|
||||
bool changed = ImGui.Checkbox("Advertise the price sheet##ts_ad", ref cfg.AdvertiseEnabled);
|
||||
SafeImGui.SetItemTooltip("Off by default. Posts one line with your items on a timer, only while the shop is on.");
|
||||
ImGui.SameLine();
|
||||
TradeShopAdvertiseChannel[] all = TradeShopAdvertise.All;
|
||||
int at = Math.Max(0, Array.IndexOf(all, cfg.AdvertiseChannel));
|
||||
ImGui.SetNextItemWidth(Px(130));
|
||||
if (ImGui.BeginCombo("##ts_adch", TradeShopAdvertise.DisplayName(all[at])))
|
||||
{
|
||||
for (int i = 0; i < all.Length; i++)
|
||||
if (ImGui.Selectable(TradeShopAdvertise.DisplayName(all[i]), i == at)) { cfg.AdvertiseChannel = all[i]; changed = true; }
|
||||
ImGui.EndCombo();
|
||||
}
|
||||
ImGui.SameLine();
|
||||
int minutes = TradeShopSettings.ClampAdvertiseSec(cfg.AdvertiseIntervalSec) / 60;
|
||||
ImGui.SetNextItemWidth(Px(60));
|
||||
if (ImGui.InputInt("min between##ts_adevery", ref minutes, 0, 0))
|
||||
{
|
||||
cfg.AdvertiseIntervalSec = TradeShopSettings.ClampAdvertiseSec(minutes * 60);
|
||||
changed = true;
|
||||
}
|
||||
SafeImGui.SetItemTooltip($"{TradeShopSettings.MinAdvertiseSec / 60} to {TradeShopSettings.MaxAdvertiseSec / 60} minutes.");
|
||||
ImGui.SetNextItemWidth(Px(200));
|
||||
if (ImGui.InputText("starts with##ts_adprefix", ref cfg.AdvertisePrefix, 48)) changed = true;
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Advertise now##ts_adnow")) shop.RequestAdvertise();
|
||||
if (changed) _changed();
|
||||
}
|
||||
}
|
||||
|
|
@ -37,7 +37,7 @@ public sealed partial class RynthAiPlugin
|
|||
"chunkaetheria", "chunkdebug", "chunkreset", "chunkstatus", "clapstatus", "dispel", "dispeltool",
|
||||
"egg", "element", "enlighten", "enlightenment", "getjob", "getui", "invcache", "joke", "keystore",
|
||||
"login", "lsdclearcache", "lsdlb", "mtbridge", "nav", "navfollow", "navfollowarrival",
|
||||
"onetouchheal", "pcap", "perf", "playeroption", "prepclick", "printcolors", "professor",
|
||||
"onetouchheal", "pcap", "perf", "playeroption", "printcolors", "professor",
|
||||
"questbonus", "queuestatus", "refreshqueues", "resolution", "revalidate", "setui", "shittalk",
|
||||
"soak", "spell", "statushud", "storm", "surgingstrength", "swearallegiance", "testassessor",
|
||||
"textures", "tinkcalc", "trace", "tracearmorbuffs", "ubhudrecover", "ucm", "unstack",
|
||||
|
|
@ -170,6 +170,11 @@ public sealed partial class RynthAiPlugin
|
|||
case "combat": return UbStormSwitch(cmd, sub, "enablecombat", w);
|
||||
case "sloot": return UbStormSwitch(cmd, sub, "enablelooting", w);
|
||||
|
||||
// ── Answer the next yes/no prompt (ub-IT's prepclick) ──────────────────
|
||||
case "prepclick":
|
||||
UbPrepClick(sub, w.Length > 1 ? w[1] : "");
|
||||
return true;
|
||||
|
||||
case "lps":
|
||||
case "lootprofilestatus":
|
||||
{
|
||||
|
|
@ -188,6 +193,46 @@ public sealed partial class RynthAiPlugin
|
|||
return false;
|
||||
}
|
||||
|
||||
// ── /ub prepclick yes|no [n] (2026-11-25, R-20261125-144721-b49a) ──────────
|
||||
// Coldeve: a meta turning alt currency in for promissory notes sent "/ub prepclick yes 100" before
|
||||
// each hand-in, and RynthAi only said "no RynthAi equivalent; ignored", so the server's yes/no prompt
|
||||
// waited for a click. The engine answers a server prompt itself (ArmConfirmation, plugin API v85):
|
||||
// "yes" arms a Yes for the next yes/no prompt (ConfirmationRequest YesNo) within the time given in
|
||||
// ms, never under PrepClickMinMs (metas send it again before each hand-in), at most PrepClickMaxMs.
|
||||
// "no" disarms (the engine can't say No to a prompt without a percent: the client shows it).
|
||||
internal const int PrepClickMinMs = 5000, PrepClickMaxMs = 60000;
|
||||
|
||||
private void UbPrepClick(string answer, string number)
|
||||
{
|
||||
if (!Host.HasConfirmationAnswers)
|
||||
{
|
||||
UbNoEquivalent("prepclick", "this RynthCore can't answer prompts (it needs a newer core)");
|
||||
return;
|
||||
}
|
||||
if (answer is "no" or "n" or "off" or "cancel")
|
||||
{
|
||||
Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.YesNo, 0, 0);
|
||||
Reply.Answered();
|
||||
Host.Log("[RynthAi] /ub prepclick no: disarmed; the next yes/no prompt is left to you.");
|
||||
return;
|
||||
}
|
||||
if (answer is not ("yes" or "y" or ""))
|
||||
{
|
||||
ReplyFail("[RynthAi] Usage: /ub prepclick yes|no [ms]");
|
||||
return;
|
||||
}
|
||||
int ms = int.TryParse(number, out int n) ? n : 0;
|
||||
ms = Math.Clamp(ms, PrepClickMinMs, PrepClickMaxMs);
|
||||
int r = Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.YesNo, 0, ms);
|
||||
if (r == 1)
|
||||
{
|
||||
Reply.Answered(); // a meta sends it every few seconds: the log, not chat
|
||||
Host.Log($"[RynthAi] /ub prepclick yes: the next yes/no prompt within {ms / 1000.0:0.#} s is answered Yes.");
|
||||
}
|
||||
else
|
||||
ReplyFail($"[RynthAi] /ub prepclick: RynthCore couldn't arm the answer ({r}).");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /ub close corpse|chest (ub-IT): closes the open container when it is that kind (a bare
|
||||
/// "/ub close" closes whatever is open). Metas send it after looting a quest corpse.
|
||||
|
|
|
|||
|
|
@ -124,6 +124,8 @@ internal sealed class AutoVendorManager
|
|||
// Stacks a split made to be sold, and the rule that sold the stack they came from: sold even when
|
||||
// a rule matches them differently at their new size ("Value = 250,000" on a one-note stack).
|
||||
private readonly Dictionary<uint, string> _splitOffForSale = new();
|
||||
// The count each of those stacks was made with: its Value reads fresh only while it still has it.
|
||||
private readonly Dictionary<uint, int> _splitOffAmount = new();
|
||||
// Per item key: the unit value read off a stack a split made (fresh from the server). Kept across
|
||||
// sessions, since the stale stacks it corrects stay stale until relog.
|
||||
private readonly Dictionary<string, int> _freshUnit = new(StringComparer.Ordinal);
|
||||
|
|
@ -1017,7 +1019,10 @@ internal sealed class AutoVendorManager
|
|||
// Only a stack the split made is sold past the rules; one it joined was already
|
||||
// there and keeps whatever the profile says about it.
|
||||
if (outcome.Kind == SplitOutcomeKind.NewStack && outcome.StackCount == ps.Amount)
|
||||
{
|
||||
_splitOffForSale[outcome.StackId] = ps.RuleName;
|
||||
_splitOffAmount[outcome.StackId] = outcome.StackCount;
|
||||
}
|
||||
_host.Log(outcome.Kind == SplitOutcomeKind.NewStack
|
||||
? $"[RynthAi] AutoVendor: split {ps.Amount} off {ps.Name}: new stack 0x{outcome.StackId:X8} (x{outcome.StackCount}) after {now - ps.SentAt} ms"
|
||||
: $"[RynthAi] AutoVendor: split {ps.Amount} off {ps.Name}: no new object; the units went onto stack 0x{outcome.StackId:X8} (now x{outcome.StackCount}) at the split's slot");
|
||||
|
|
@ -1143,7 +1148,10 @@ internal sealed class AutoVendorManager
|
|||
{
|
||||
var have = new HashSet<uint>(inv.Select(w => unchecked((uint)w.Id)));
|
||||
foreach (uint gone in _splitOffForSale.Keys.Where(k => !have.Contains(k)).ToList())
|
||||
{
|
||||
_splitOffForSale.Remove(gone);
|
||||
_splitOffAmount.Remove(gone);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var wo in inv)
|
||||
|
|
@ -1766,7 +1774,8 @@ internal sealed class AutoVendorManager
|
|||
if (!votes.TryGetValue(key, out var byUnit)) votes[key] = byUnit = new Dictionary<int, long>();
|
||||
int unit = value / stack;
|
||||
byUnit[unit] = byUnit.GetValueOrDefault(unit) + stack;
|
||||
if (_splitOffForSale.ContainsKey(unchecked((uint)wo.Id)) && unit > 0)
|
||||
if (unit > 0 && _splitOffForSale.ContainsKey(unchecked((uint)wo.Id))
|
||||
&& AutoVendorPlanner.FreshSplitReading(_splitOffAmount.GetValueOrDefault(unchecked((uint)wo.Id)), stack))
|
||||
_freshUnit[key] = unit;
|
||||
}
|
||||
var result = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
|
|
@ -1831,6 +1840,54 @@ internal sealed class AutoVendorManager
|
|||
return _playerId;
|
||||
}
|
||||
|
||||
// ── Read only, for other plugins (RynthAi.Hub VendorSells) ───────────────
|
||||
|
||||
private VTankLootProfile? _askProfile;
|
||||
private string _askPath = string.Empty;
|
||||
private DateTime _askTime;
|
||||
|
||||
/// <summary>
|
||||
/// Read only (RynthAi.Hub VendorSells, RynthSort's Sell packs): whether AutoVendor would sell each
|
||||
/// item with no particular vendor open: the profile it falls back to (default.utl, by the folders it
|
||||
/// searches), the same rule judgement (a Sell rule that surely matches, no Keep that could) and the
|
||||
/// same safety checks (identified, not equipped, retained, rare, attuned, tinkered, imbued,
|
||||
/// inscribed), "only from the main pack" left out (the item may be anywhere). What a vendor buys
|
||||
/// and pays can't be judged without one. Changes nothing: its own copy of the profile, no chat, no
|
||||
/// log. False with <paramref name="error"/> when there is no profile. Pump thread.
|
||||
/// </summary>
|
||||
public bool WouldSell(uint[] ids, byte[] sells, out string profileFile, out string? error)
|
||||
{
|
||||
Array.Clear(sells);
|
||||
error = null;
|
||||
string path = ResolveProfilePath("default.utl", false);
|
||||
profileFile = Path.GetFileName(path);
|
||||
if (!File.Exists(path)) { error = "AutoVendor has no default.utl profile"; return false; }
|
||||
try
|
||||
{
|
||||
DateTime t = File.GetLastWriteTimeUtc(path);
|
||||
if (_askProfile == null || !string.Equals(_askPath, path, StringComparison.OrdinalIgnoreCase) || _askTime != t)
|
||||
{
|
||||
_askProfile = VTankLootParser.Load(path);
|
||||
_askPath = path;
|
||||
_askTime = t;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) { error = "AutoVendor's profile could not be read: " + ex.Message; return false; }
|
||||
|
||||
uint player = PlayerId();
|
||||
VTankLootContext ctx = NewContext();
|
||||
for (int i = 0; i < ids.Length && i < sells.Length; i++)
|
||||
{
|
||||
WorldObject? wo = _cache[unchecked((int)ids[i])];
|
||||
if (wo == null || wo.Id == 0) continue;
|
||||
SafetyFacts safety = ReadSafety(wo, player);
|
||||
if (AutoVendorPlanner.UnsafeReason(safety, onlyFromMainPack: false) != null) continue;
|
||||
ProfileVerdict verdict = AutoVendorRules.Decide(_askProfile.Rules, Judge(EvalObject(wo), InventoryFacts(wo, safety.Appraised), ctx));
|
||||
if (AutoVendorRules.JudgeSell(verdict).Sell) sells[i] = 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private string VendorName(uint id)
|
||||
{
|
||||
if (id != 0 && _host.HasVendorTrade && _host.TryGetVendorInfo(out VendorInfo vi) && vi.VendorId == id && !string.IsNullOrEmpty(vi.Name))
|
||||
|
|
|
|||
|
|
@ -577,6 +577,15 @@ internal static class AutoVendorPlanner
|
|||
internal static int TrueUnit(IReadOnlyDictionary<int, long> unitsByValue, int freshUnit) =>
|
||||
freshUnit > 0 ? freshUnit : MostCarriedUnit(unitsByValue);
|
||||
|
||||
/// <summary>
|
||||
/// A split's new stack reads fresh only while it still holds what the split made: split again or
|
||||
/// partly sold, its Value is as stale as any other. R-20261125-011308-9444: a stack split off with
|
||||
/// 42 peas and later split down to 1 kept the 42 peas' Value, so 2,100,000 became the "true" unit
|
||||
/// and every pea read "worth 2,100,000 each, this vendor pays for items up to 1,000,000": AutoVendor
|
||||
/// finished early, and on every visit after it.
|
||||
/// </summary>
|
||||
internal static bool FreshSplitReading(int madeAmount, int stackNow) => madeAmount > 0 && stackNow == madeAmount;
|
||||
|
||||
/// <summary>The unit value carrying the most units (ties: the higher value, the safe side for a vendor's max).</summary>
|
||||
internal static int MostCarriedUnit(IReadOnlyDictionary<int, long> unitsByValue)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -187,6 +187,15 @@ internal static class PathMarkers
|
|||
return idx;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A plan (Route, not walked) is done once you stand at its goal: within <paramref name="arriveUnits"/>
|
||||
/// of it (the arrow's arrival distance), on the map. A walked trip (Live) reports its own arrival; a
|
||||
/// plan that ends in a dungeon's entrance goes when you walk through it (the landblock check).
|
||||
/// </summary>
|
||||
public static bool PlanReached(PlannedTrip trip, bool hasPos, double ns, double ew, double arriveUnits)
|
||||
=> !trip.Live && hasPos && !trip.EndsInEntrance
|
||||
&& NavCoords.Distance(ns, ew, trip.GoalNs, trip.GoalEw) <= arriveUnits;
|
||||
|
||||
/// <summary>The marker nearest the character (a plan only: where the guide line points), or -1.</summary>
|
||||
public static int Nearest(MarkerSnapshot s, double px, double py)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -43,6 +43,12 @@ internal sealed class RecallSpot
|
|||
public string Label = "";
|
||||
/// <summary>The chat command that does this recall, when it's a command (@lifestone, @house recall).</summary>
|
||||
public string Command = "";
|
||||
/// <summary>
|
||||
/// Portal Recall only: learned from walking through a portal RynthNav's portal list doesn't know, so
|
||||
/// it can't tell whether the server keeps it as your last portal (a no-recall portal isn't kept).
|
||||
/// Routes don't use it until a cast of Portal Recall confirms where it lands.
|
||||
/// </summary>
|
||||
public bool Unconfirmed;
|
||||
}
|
||||
|
||||
/// <summary>What a chat line tells RynthNav about recalls.</summary>
|
||||
|
|
@ -149,7 +155,7 @@ internal sealed class RecallMemory
|
|||
|
||||
// ── recalls.txt ──────────────────────────────────────────────────────────
|
||||
// # comment
|
||||
// <character>\t<slot>\t<ns or ->\t<ew or ->\t<label>\t<command>
|
||||
// <character>\t<slot>\t<ns or ->\t<ew or ->\t<label>\t<command>[\t? when unconfirmed]
|
||||
|
||||
public string Serialize()
|
||||
{
|
||||
|
|
@ -169,7 +175,8 @@ internal sealed class RecallMemory
|
|||
sb.Append(Clean(c)).Append('\t').Append(SlotName(slot)).Append('\t')
|
||||
.Append(s.OnMap ? s.Ns.ToString("F2", ci) : "-").Append('\t')
|
||||
.Append(s.OnMap ? s.Ew.ToString("F2", ci) : "-").Append('\t')
|
||||
.Append(Clean(s.Label)).Append('\t').Append(Clean(s.Command)).Append("\r\n");
|
||||
.Append(Clean(s.Label)).Append('\t').Append(Clean(s.Command))
|
||||
.Append(s.Unconfirmed ? "\t?" : "").Append("\r\n");
|
||||
}
|
||||
}
|
||||
return sb.ToString();
|
||||
|
|
@ -189,6 +196,7 @@ internal sealed class RecallMemory
|
|||
{
|
||||
Label = f.Length > 4 ? f[4] : "",
|
||||
Command = f.Length > 5 ? f[5] : "",
|
||||
Unconfirmed = f.Length > 6 && f[6] == "?",
|
||||
};
|
||||
s.OnMap = double.TryParse(f[2], NumberStyles.Float, CultureInfo.InvariantCulture, out s.Ns)
|
||||
& double.TryParse(f[3], NumberStyles.Float, CultureInfo.InvariantCulture, out s.Ew);
|
||||
|
|
|
|||
|
|
@ -99,12 +99,35 @@ internal static class RecallPlanner
|
|||
RecallSpot? spot = memory.Get(charKey, slot);
|
||||
if (spot == null) { notes?.Add(name + ": where it lands isn't known yet (" + howToLearn + ")."); return; }
|
||||
if (!spot.OnMap) { notes?.Add(name + " lands " + Where(spot) + ": not used for routes."); return; }
|
||||
if (spot.Unconfirmed)
|
||||
{
|
||||
notes?.Add(name + ": the last portal you used (" + (spot.Label.Length > 0 ? spot.Label : "unknown") + ") isn't in RynthNav's portal list, "
|
||||
+ "so whether the server lets Portal Recall go back there isn't known: not used for routes until you cast " + name + " once.");
|
||||
return;
|
||||
}
|
||||
list.Add(new RecallOption
|
||||
{
|
||||
Name = name, SpellId = spellId, Ns = spot.Ns, Ew = spot.Ew, CastSeconds = SpellCastSeconds, Learned = true,
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>What a portal walk does to Portal Recall's landing (RynthNavPlugin.Travel).</summary>
|
||||
internal enum LastPortalUpdate { Set, SetUnconfirmed, Keep }
|
||||
|
||||
/// <summary>ACE's PortalBitmask.NoRecall: the server doesn't keep such a portal as your last portal.</summary>
|
||||
internal const int PortalNoRecall = 0x20;
|
||||
|
||||
/// <summary>
|
||||
/// A teleport through a portal with this PortalBitmask (null: not in the portal list). ACE keeps
|
||||
/// a portal as your last portal only if it isn't NoRecall (Portal.ActOnUse), so Portal Recall then
|
||||
/// still goes to the one before (R-20261126-024033-5d60, Conquest: from the Dark Isle, which can't
|
||||
/// be recalled to, a goto cast Portal Recall and landed in a dungeon visited earlier).
|
||||
/// </summary>
|
||||
internal static LastPortalUpdate ForPortal(int? bitmask) =>
|
||||
bitmask is not int b ? LastPortalUpdate.SetUnconfirmed
|
||||
: (b & PortalNoRecall) != 0 ? LastPortalUpdate.Keep
|
||||
: LastPortalUpdate.Set;
|
||||
|
||||
private static void AddLearnedCommand(List<RecallOption> list, List<string>? notes, RecallMemory memory, string charKey,
|
||||
RecallSlot slot, string name, bool alwaysAvailable, string howToLearn)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -13,9 +13,11 @@ namespace RynthCore.Plugin.RynthNav;
|
|||
// those and a guide line from your feet to the next waypoint. The same path is what "save as nav
|
||||
// route" writes (RynthNavPlugin.SaveRoute.cs).
|
||||
//
|
||||
// The markers go away when the trip ends (arrived, stopped), is cancelled (Stop, the d-pad), or you
|
||||
// land in a landblock that isn't on it (a teleport elsewhere). Switches in rynthnav.json
|
||||
// (markers, markerLabels, markerGuide); /rnav markers and the panel's Go tab change them.
|
||||
// The markers go away when the trip ends (arrived, stopped), is cancelled (Stop, the d-pad), is
|
||||
// cleared (the Go tab's Clear, /rnav markers clear), you land in a landblock that isn't on it (a
|
||||
// teleport elsewhere), or, for a plan you aren't walking (Route, an Oracle or map pick), you walk to
|
||||
// its goal yourself (2026-11-26: a plan's markers stayed on the ground until Stop). Switches in
|
||||
// rynthnav.json (markers, markerLabels, markerGuide); /rnav markers and the panel's Go tab change them.
|
||||
//
|
||||
// Threads: everything here runs on the tick, except the path worker, which reads only the frozen
|
||||
// trip (PlannedTrip), the immutable route graph and Atlas portal list, and the tile files. The
|
||||
|
|
@ -205,6 +207,12 @@ public sealed partial class RynthNavPlugin
|
|||
HideMarkers($"landblock 0x{lb:X4} isn't on the trip");
|
||||
}
|
||||
}
|
||||
// A plan (Route, an Oracle or map pick) you walked to yourself: its markers go once you're there.
|
||||
if (_tripShown && !trip.Live && !_gotoActive)
|
||||
{
|
||||
bool hasPos = PlayerMapPos(out double ns, out double ew);
|
||||
if (PathMarkers.PlanReached(trip, hasPos, ns, ew, _arrow.ArriveUnits)) HideMarkers("arrived");
|
||||
}
|
||||
if (!_markersOn || !_tripShown || !Host.HasNav3D || !_hasPose) return;
|
||||
|
||||
if (!ReferenceEquals(trip, _snapTrip) || !ReferenceEquals(_tripPath, _snapPath))
|
||||
|
|
@ -232,10 +240,19 @@ public sealed partial class RynthNavPlugin
|
|||
|
||||
// ── /rnav markers ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>/rnav markers [on|off | labels on|off | guide on|off]</summary>
|
||||
/// <summary>/rnav markers [on|off | clear | labels on|off | guide on|off]</summary>
|
||||
private void CmdMarkers(string rest)
|
||||
{
|
||||
string[] a = rest.ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (a.Length == 1 && a[0] is "clear" or "hide")
|
||||
{
|
||||
// This trip's markers off the ground, the switch left as it is (the panel's Clear button).
|
||||
if (_trip == null || !_tripShown) { Say("path markers: no trip on the ground"); return; }
|
||||
string goal = _trip.Goal;
|
||||
HideMarkers("cleared");
|
||||
Say($"path markers: the trip to {goal} is off the ground (the next Route or Go shows its own)");
|
||||
return;
|
||||
}
|
||||
if (a.Length == 1 && a[0] is "on" or "off")
|
||||
{
|
||||
_markersOn = a[0] == "on";
|
||||
|
|
@ -246,7 +263,7 @@ public sealed partial class RynthNavPlugin
|
|||
{ _markerLabels = a[1] == "on"; NavDataConfig.WriteSwitch("markerLabels", _markerLabels); }
|
||||
else if (a.Length == 2 && a[0] == "guide" && a[1] is "on" or "off")
|
||||
{ _markerGuide = a[1] == "on"; NavDataConfig.WriteSwitch("markerGuide", _markerGuide); }
|
||||
else if (a.Length > 0) { Say("/rnav markers on|off, markers labels on|off, markers guide on|off"); return; }
|
||||
else if (a.Length > 0) { SayFail("/rnav markers on|off, markers clear, markers labels on|off, markers guide on|off"); return; }
|
||||
Say($"path markers {(_markersOn ? "ON" : "OFF")}, labels {(_markerLabels ? "on" : "off")}, guide line {(_markerGuide ? "on" : "off")}"
|
||||
+ (_trip == null ? "" : _tripShown ? $" — showing the trip to {_trip.Goal}" : $" — the trip to {_trip.Goal} isn't shown ({_markerStatus})"));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -431,7 +431,7 @@ public sealed partial class RynthNavPlugin
|
|||
{
|
||||
// As /rnav route: the panel shows the plan and the markers its path (worked out below, once).
|
||||
_shownRoute = plan.Steps ?? new List<RouteStep> { new(ns, ew, false, false, "walk") };
|
||||
_shownRouteFor = name; _shownRouteEst = plan.Est; _shownRouteLive = false; _routeVersion++;
|
||||
_shownRouteFor = name; SetShownRouteGoal(ns, ew); _shownRouteEst = plan.Est; _shownRouteLive = false; _routeVersion++;
|
||||
trip = SetTrip(plan.Steps, name, ns, ew, recalls, "", live: false, buildPath: false);
|
||||
}
|
||||
else trip = NewTrip(plan.Steps, name, ns, ew, recalls, "", live: false);
|
||||
|
|
|
|||
77
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Target.cs
Normal file
77
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Target.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
using System;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// One target at a time, the newest wins (11-24, a player: "It puts it into the top part of this arrow
|
||||
// window. The bottom part follows the rynthnav thing though"). The arrow window showed the arrow's
|
||||
// target (clicked chat coordinates) over the last route planned or walked, which was for somewhere
|
||||
// else. Now a new target replaces the old one (TargetSwitch): the arrow set elsewhere drops the shown
|
||||
// route and ends a walk to another place; a plan (/rnav route, Plan) points the arrow along itself;
|
||||
// /rnav clear (the arrow window's x) forgets all of it. The same place again changes nothing.
|
||||
// Tick thread: the commands run there (RunCommand).
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
// Where the shown route goes (NaN: none, or unknown), for "the same place" and the status's route goal.
|
||||
private double _shownRouteNs = double.NaN, _shownRouteEw = double.NaN;
|
||||
|
||||
private void SetShownRouteGoal(double ns, double ew) { _shownRouteNs = ns; _shownRouteEw = ew; }
|
||||
|
||||
/// <summary>The shown route and the trip, as TargetSwitch reads them.</summary>
|
||||
private HeldTarget Held() => new(
|
||||
_shownRoute != null, _shownRouteFor, _shownRouteNs, _shownRouteEw,
|
||||
_gotoActive, _gotoName,
|
||||
_gotoActive ? NavCoords.NsFromWorld(_finalTns) : double.NaN,
|
||||
_gotoActive ? NavCoords.EwFromWorld(_finalTew) : double.NaN);
|
||||
|
||||
/// <summary>
|
||||
/// Applies what a new target does to the old one: the walk stopped (as Stop does), the shown
|
||||
/// route forgotten. Returns what was ended, for the command's reply ("" for nothing).
|
||||
/// </summary>
|
||||
private string ApplyTargetChange(TargetChange c, in HeldTarget held)
|
||||
{
|
||||
string ended = "";
|
||||
if (c.StopTrip && held.Walking)
|
||||
{
|
||||
StopTripNow();
|
||||
ended = "stopped the walk to " + (held.TripFor.Length > 0 ? held.TripFor : NavCoords.Fmt(held.TripNs, held.TripEw));
|
||||
}
|
||||
if (c.DropPlan && _shownRoute != null)
|
||||
{
|
||||
if (ended.Length == 0 && !_shownRouteLive && _shownRouteFor.Length > 0) ended = "dropped the route to " + _shownRouteFor;
|
||||
_shownRoute = null;
|
||||
_shownRouteFor = "";
|
||||
_shownRouteLive = false;
|
||||
SetShownRouteGoal(double.NaN, double.NaN);
|
||||
_routeVersion++;
|
||||
HideMarkers("a new target");
|
||||
}
|
||||
return ended;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ends the trip at once, as Stop does (ProcessRequests' cancel), but here on the tick so a plan
|
||||
/// made right after keeps its markers (the cancel request would hide them later this tick).
|
||||
/// </summary>
|
||||
private void StopTripNow()
|
||||
{
|
||||
_goNote = "stopped";
|
||||
_gotoActive = false; _paused = false; _route = null; _portalWait = false;
|
||||
if (_recallWait) EndRecall();
|
||||
ResetHub();
|
||||
AutoRun.Stop();
|
||||
HideMarkers("a new target");
|
||||
lock (_moveGate) { _desiredRun = 0; _turnState = 0; _haltPending = true; } // ApplyMovement lets go of the keys
|
||||
}
|
||||
|
||||
/// <summary>/rnav clear: no target at all. The walk stops, the route goes, the arrow goes off.</summary>
|
||||
private void CmdClear()
|
||||
{
|
||||
HeldTarget held = Held();
|
||||
bool hadArrow = _arrow.Active;
|
||||
string ended = ApplyTargetChange(TargetSwitch.For(NewTarget.Clear, held), held);
|
||||
_arrow.Clear();
|
||||
if (!hadArrow && !held.HasPlan && !held.Walking) { Say("clear: no target to clear"); return; }
|
||||
Note("target cleared" + (ended.Length > 0 ? ": " + ended : "") + (hadArrow ? "; arrow off" : ""));
|
||||
}
|
||||
}
|
||||
|
|
@ -342,6 +342,7 @@ public sealed partial class RynthNavPlugin
|
|||
_castRecallSpell = 0;
|
||||
RecallSlot? learned = spell switch
|
||||
{
|
||||
RecallPlanner.PortalRecall => RecallSlot.LastPortal, // a cast confirms where it goes
|
||||
RecallPlanner.LifestoneRecall => RecallSlot.Lifestone,
|
||||
RecallPlanner.PrimaryPortalTieRecall => RecallSlot.Tie1,
|
||||
RecallPlanner.SecondaryPortalTieRecall => RecallSlot.Tie2,
|
||||
|
|
@ -365,15 +366,43 @@ public sealed partial class RynthNavPlugin
|
|||
// hand, or dying and waking at the lifestone) isn't a portal.
|
||||
if (landing.OnMap && LandsLikeARecall(landing)) return;
|
||||
string label = landing.Label;
|
||||
int? bitmask = null;
|
||||
if (havePre && IsOnMap(preCell))
|
||||
{
|
||||
AtlasLocation? p = _atlas.Nearest("Portal", NavCoords.NsFromWorld(preWy), NavCoords.EwFromWorld(preWx), PortalNearUnits);
|
||||
double ns = NavCoords.NsFromWorld(preWy), ew = NavCoords.EwFromWorld(preWx);
|
||||
AtlasLocation? p = _atlas.Nearest("Portal", ns, ew, PortalNearUnits);
|
||||
if (p != null) label = p.Name + (landing.Label.Length > 0 ? " → " + landing.Label : "");
|
||||
bitmask = PortalBitmaskNear(ns, ew);
|
||||
}
|
||||
landing.Label = label;
|
||||
switch (RecallPlanner.ForPortal(bitmask))
|
||||
{
|
||||
case RecallPlanner.LastPortalUpdate.Keep:
|
||||
Host.Log($"[RynthNav] {label}: a no-recall portal, so Portal Recall still goes to the last portal before it");
|
||||
return;
|
||||
case RecallPlanner.LastPortalUpdate.SetUnconfirmed:
|
||||
landing.Unconfirmed = true;
|
||||
Host.Log($"[RynthNav] {label}: not in the portal list; Portal Recall isn't used for routes until a cast confirms where it goes");
|
||||
break;
|
||||
}
|
||||
_memory.Set(who, RecallSlot.LastPortal, landing);
|
||||
}
|
||||
|
||||
/// <summary>The PortalBitmask of the listed portal whose entrance is nearest (within PortalNearUnits), or null.</summary>
|
||||
private int? PortalBitmaskNear(double ns, double ew)
|
||||
{
|
||||
EnsurePortalsLoaded();
|
||||
if (_portals == null) return null;
|
||||
double best = PortalNearUnits;
|
||||
int? mask = null;
|
||||
foreach (PortalLink p in _portals)
|
||||
{
|
||||
double d = NavCoords.Distance(ns, ew, p.SrcNs, p.SrcEw);
|
||||
if (d < best) { best = d; mask = p.Bitmask; }
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
private bool LandsLikeARecall(RecallSpot s)
|
||||
{
|
||||
foreach (AtlasRecall r in _atlas.Recalls)
|
||||
|
|
@ -701,12 +730,14 @@ public sealed partial class RynthNavPlugin
|
|||
/// <summary>The Atlas place the last ResolveTarget picked (null for bare coordinates). Tick thread.</summary>
|
||||
private AtlasLocation? _resolvedPlace;
|
||||
|
||||
private void SetArrow(string name, string type, double ns, double ew, bool announce)
|
||||
/// <param name="ended">What the new target ended (ApplyTargetChange: "stopped the walk to ..."), said after it.</param>
|
||||
private void SetArrow(string name, string type, double ns, double ew, bool announce, string ended = "")
|
||||
{
|
||||
_arrow.SetTarget(name, type, ns, ew);
|
||||
_store.Touch(new SavedPlace { Name = name, Type = type, Ns = ns, Ew = ew });
|
||||
_openArrowSeq++;
|
||||
if (announce) Say($"Arrow: {name}{(type.Length > 0 ? " (" + type + ")" : "")} at {NavCoords.Fmt(ns, ew)}{DistanceFromHere(ns, ew)}.");
|
||||
if (announce) Say($"Arrow: {name}{(type.Length > 0 ? " (" + type + ")" : "")} at {NavCoords.Fmt(ns, ew)}{DistanceFromHere(ns, ew)}"
|
||||
+ (ended.Length > 0 ? $" ({ended})." : "."));
|
||||
}
|
||||
|
||||
private string DistanceFromHere(double ns, double ew)
|
||||
|
|
@ -932,6 +963,8 @@ public sealed partial class RynthNavPlugin
|
|||
.Append(",\"avoidWalls\":").Append(_avoidWalls ? 1 : 0).Append(",\"avoidWallM\":").Append(_wallClearance.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture))
|
||||
.Append(",\"cornerM\":").Append(_cornerReach.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture));
|
||||
sb.Append(",\"openArrow\":").Append(_openArrowSeq);
|
||||
// /rnav clear is there (from 11-26): the arrow window's x sends it (older RynthNavs get "arrow off").
|
||||
sb.Append(",\"clearCmd\":1");
|
||||
|
||||
// Arrow
|
||||
sb.Append(",\"arrow\":");
|
||||
|
|
@ -956,7 +989,11 @@ public sealed partial class RynthNavPlugin
|
|||
if (_shownRoute == null) sb.Append("null");
|
||||
else
|
||||
{
|
||||
sb.Append("{\"for\":\"").Append(Esc(_shownRouteFor)).Append("\",\"est\":").Append(_shownRouteEst.ToString("F0", ci))
|
||||
sb.Append("{\"for\":\"").Append(Esc(_shownRouteFor)).Append("\",\"est\":").Append(_shownRouteEst.ToString("F0", ci));
|
||||
// Where it goes (from 11-26): the arrow window shows the route only under an arrow to the same place.
|
||||
if (!double.IsNaN(_shownRouteNs) && !double.IsNaN(_shownRouteEw))
|
||||
sb.Append(",\"gns\":").Append(_shownRouteNs.ToString("F3", ci)).Append(",\"gew\":").Append(_shownRouteEw.ToString("F3", ci));
|
||||
sb
|
||||
.Append(",\"active\":").Append(_gotoActive && _shownRouteLive ? 1 : 0)
|
||||
.Append(",\"idx\":").Append(_gotoActive && _shownRouteLive ? (_route != null ? routeIdx : 0) : -1);
|
||||
// How long the trip takes, in seconds (RynthNavPlugin.TripTime.cs; -1 = not known).
|
||||
|
|
@ -1023,7 +1060,8 @@ public sealed partial class RynthNavPlugin
|
|||
}
|
||||
|
||||
private const string HelpText =
|
||||
"/rnav arrow <place|coords> | arrow off | arrow route <place> — the arrow\n" +
|
||||
"/rnav arrow <place|coords> | arrow off | arrow route <place> — the arrow (one target: a new one replaces the route, and a walk elsewhere)\n" +
|
||||
"/rnav clear — no target: the walk stops, the route goes, the arrow goes off\n" +
|
||||
"/rnav go <place|coords> — walk there (route with portals/recalls when /rnav portals on)\n" +
|
||||
"/rnav route <place|coords> — plan a route (portals and recalls), no walking\n" +
|
||||
"/rnav route next — another way to the same place (switches a running goto) | route go — walk the way shown\n" +
|
||||
|
|
@ -1032,7 +1070,7 @@ public sealed partial class RynthNavPlugin
|
|||
"/rnav pause — stop walking, keep the trip on the map (drive by hand meanwhile) | resume — carry on\n" +
|
||||
"/rnav times — how long this character's trips take (run speed, portals, recalls, portal space)\n" +
|
||||
"/rnav avoid — show; avoid portals on|off|<m> | walls on|off|<m> | corners <m>\n" +
|
||||
"/rnav markers on|off | markers labels on|off | markers guide on|off — the trip on the ground\n" +
|
||||
"/rnav markers on|off | markers clear | markers labels on|off | markers guide on|off — the trip on the ground (clear: this trip's, now)\n" +
|
||||
"/rnav mesh on|off | floor on|off | walls on|off | radius <m> | triangles <n> — draw the navmesh: green floor, red walls\n" +
|
||||
"/rnav saveroute [name] [overwrite] — save the last trip as a RynthAi nav route (NavProfiles)\n" +
|
||||
"/rnav makeroute <name> to <place|coords> [overwrite] — plan a trip and save it as a nav route in one go, no walking\n" +
|
||||
|
|
@ -1082,6 +1120,7 @@ public sealed partial class RynthNavPlugin
|
|||
break;
|
||||
case "route": CmdRoute(rest); break;
|
||||
case "arrow": CmdArrow(rest); break;
|
||||
case "clear": CmdClear(); break; // RynthNavPlugin.Target.cs
|
||||
case "atlas": CmdAtlas(rest); break;
|
||||
case "fav": CmdFav(rest); break;
|
||||
case "recent":
|
||||
|
|
@ -1119,24 +1158,39 @@ public sealed partial class RynthNavPlugin
|
|||
if (rest.Equals("off", StringComparison.OrdinalIgnoreCase) || rest.Equals("clear", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_arrow.Clear();
|
||||
Say("arrow off");
|
||||
// One target: a plan goes with the arrow. A walk carries on (Stop, or /rnav clear, ends it).
|
||||
string dropped = _gotoActive ? "" : ApplyTargetChange(new TargetChange(true, false, false), Held());
|
||||
Say("arrow off" + (dropped.Length > 0 ? " (" + dropped + ")" : ""));
|
||||
return;
|
||||
}
|
||||
if (rest.StartsWith("route ", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
string where = rest.Substring(6);
|
||||
if (!ResolveTarget(where, out string n, out string t, out double rns, out double rew, out string err)) { Note(err); return; }
|
||||
HeldTarget rheld = Held();
|
||||
TargetChange rc = TargetSwitch.For(NewTarget.Plan, rheld, rns, rew);
|
||||
if (rc.KeepArrow) { _openArrowSeq++; Say($"arrow route: already walking to {n}; the arrow follows the trip."); return; }
|
||||
string rended = ApplyTargetChange(rc, rheld);
|
||||
List<RouteStep>? steps = PlanAndShow(n, rns, rew, out int used, out double est, out string refusal);
|
||||
if (refusal.Length > 0) Note("arrow route: " + refusal);
|
||||
if (steps == null || used == 0) { SetArrow(n, t, rns, rew, announce: true); return; }
|
||||
if (steps == null || used == 0) { SetArrow(n, t, rns, rew, announce: true, rended); return; }
|
||||
_arrow.SetRoute(steps, n, t, rns, rew);
|
||||
_store.Touch(new SavedPlace { Name = n, Type = t, Ns = rns, Ew = rew });
|
||||
_openArrowSeq++;
|
||||
Say($"arrow route to {n}: {used} teleport(s). First: {StepText(_arrow.Current!)}.");
|
||||
Say($"arrow route to {n}: {used} teleport(s). First: {StepText(_arrow.Current!)}{(rended.Length > 0 ? $" ({rended})" : "")}.");
|
||||
return;
|
||||
}
|
||||
if (!ResolveTarget(rest, out string name, out string type, out double ns, out double ew, out string error)) { Note(error); return; }
|
||||
SetArrow(name, type, ns, ew, announce: true);
|
||||
HeldTarget held = Held();
|
||||
TargetChange c = TargetSwitch.For(NewTarget.Arrow, held, ns, ew);
|
||||
if (c.KeepArrow)
|
||||
{
|
||||
// Walking there already: the arrow stays the trip's (along its portals and recalls).
|
||||
_openArrowSeq++;
|
||||
Say($"Arrow: already walking to {(held.TripFor.Length > 0 ? held.TripFor : name)}; the arrow follows the trip.");
|
||||
return;
|
||||
}
|
||||
SetArrow(name, type, ns, ew, announce: true, ApplyTargetChange(c, held));
|
||||
}
|
||||
|
||||
private void CmdGo(string rest)
|
||||
|
|
@ -1309,6 +1363,7 @@ public sealed partial class RynthNavPlugin
|
|||
used = plan.Teleports; est = plan.Est; refusal = plan.Refusal;
|
||||
_shownRoute = steps ?? new List<RouteStep> { new(ns, ew, false, false, "walk") };
|
||||
_shownRouteFor = name;
|
||||
SetShownRouteGoal(ns, ew);
|
||||
_shownRouteEst = est;
|
||||
_shownRouteLive = false;
|
||||
_routeVersion++;
|
||||
|
|
|
|||
|
|
@ -393,12 +393,25 @@ public sealed partial class RynthNavPlugin
|
|||
if (_wayCount > 1) Say($" {_wayCount} ways in all: /rnav route next for another, /rnav route go to walk this one");
|
||||
}
|
||||
|
||||
/// <summary>Plans (with the way chosen) and shows the route to a place: the panel, the arrow, chat.</summary>
|
||||
/// <summary>
|
||||
/// Plans (with the way chosen) and shows the route to a place: the panel, the arrow, chat. The plan
|
||||
/// is the target now (RynthNavPlugin.Target.cs): the arrow points along it, and a walk to somewhere
|
||||
/// else ends. A walk to the same place goes on with its own arrow.
|
||||
/// </summary>
|
||||
private void ShowRoute(string name, string type, double ns, double ew)
|
||||
{
|
||||
HeldTarget held = Held();
|
||||
TargetChange change = TargetSwitch.For(NewTarget.Plan, held, ns, ew);
|
||||
string ended = ApplyTargetChange(change, held);
|
||||
List<RouteStep>? steps = PlanAndShow(name, ns, ew, out int used, out double est, out string refusal);
|
||||
_waysType = type;
|
||||
if (refusal.Length > 0) { Note($"route to {name}: {refusal}"); return; }
|
||||
if (refusal.Length > 0) { Note($"route to {name}: {refusal}{(ended.Length > 0 ? " (" + ended + ")" : "")}"); return; }
|
||||
if (!change.KeepArrow)
|
||||
{
|
||||
if (steps != null && used > 0) _arrow.SetRoute(steps, name, type, ns, ew);
|
||||
else _arrow.SetTarget(name, type, ns, ew);
|
||||
}
|
||||
if (ended.Length > 0) Say($"route to {name}: {ended}");
|
||||
SayRoute(name, ns, ew, steps, used, est);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -535,7 +535,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
_enterName = enter; _enterType = enterType;
|
||||
if (enter.Length > 0) _route = Entrance.EndingInPortal(_route, tns, tew, enter);
|
||||
_shownRoute = _route ?? new List<RouteStep> { new(tns, tew, false, false, "walk") };
|
||||
_shownRouteFor = name; _shownRouteEst = est; _shownRouteLive = true; _routeVersion++;
|
||||
_shownRouteFor = name; SetShownRouteGoal(tns, tew); _shownRouteEst = est; _shownRouteLive = true; _routeVersion++;
|
||||
SetSubGoalToCurrentLeg();
|
||||
if (_route != null && portalsUsed > 0) _arrow.SetRoute(_route, name, type, tns, tew);
|
||||
else _arrow.SetTarget(name, type, tns, tew);
|
||||
|
|
|
|||
57
Plugins/RynthCore.Plugin.RynthNav/TargetSwitch.cs
Normal file
57
Plugins/RynthCore.Plugin.RynthNav/TargetSwitch.cs
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>What asks for a new target: the arrow (chat coords, the Atlas, /rnav arrow), a planned
|
||||
/// route (/rnav route, Plan), or /rnav clear (the arrow window's x).</summary>
|
||||
internal enum NewTarget { Arrow, Plan, Clear }
|
||||
|
||||
/// <summary>
|
||||
/// What RynthNav holds when a new target comes: the route shown in the panels (a plan, or the
|
||||
/// trip's own route), and the trip being walked (paused counts).
|
||||
/// </summary>
|
||||
internal readonly record struct HeldTarget(
|
||||
bool HasPlan, string PlanFor, double PlanNs, double PlanEw,
|
||||
bool Walking, string TripFor, double TripNs, double TripEw);
|
||||
|
||||
/// <summary>
|
||||
/// What the new target does to the old one. DropPlan: forget the shown route. StopTrip: end the
|
||||
/// walk. KeepArrow: leave the arrow as it is (the trip's own arrow, chained along its route).
|
||||
/// </summary>
|
||||
internal readonly record struct TargetChange(bool DropPlan, bool StopTrip, bool KeepArrow)
|
||||
{
|
||||
public static readonly TargetChange None = new(false, false, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One target at a time, the newest wins (11-24: the arrow window showed the clicked chat
|
||||
/// coordinates on top and an older route under them). A new target elsewhere replaces the shown
|
||||
/// route and ends a walk to somewhere else; the same place again leaves them be. Pure: the
|
||||
/// offline tests compile this file.
|
||||
/// </summary>
|
||||
internal static class TargetSwitch
|
||||
{
|
||||
/// <summary>Two targets this close are the same place (chat coordinates have one decimal: 0.05 degrees is 12 u).</summary>
|
||||
public const double SamePlaceUnits = 15.0;
|
||||
|
||||
/// <summary>By position only: two places with one name ("Lifestone") are not the same place.</summary>
|
||||
public static bool SamePlace(double nsA, double ewA, double nsB, double ewB) =>
|
||||
!double.IsNaN(nsA) && !double.IsNaN(ewA) && !double.IsNaN(nsB) && !double.IsNaN(ewB)
|
||||
&& NavCoords.Distance(nsA, ewA, nsB, ewB) <= SamePlaceUnits;
|
||||
|
||||
public static TargetChange For(NewTarget what, in HeldTarget held, double ns = double.NaN, double ew = double.NaN)
|
||||
{
|
||||
if (what == NewTarget.Clear) return new TargetChange(held.HasPlan, held.Walking, false);
|
||||
if (held.Walking)
|
||||
{
|
||||
// Going there already: the trip (and its arrow, along its portals) stays.
|
||||
if (SamePlace(ns, ew, held.TripNs, held.TripEw)) return new TargetChange(false, false, true);
|
||||
// Somewhere else: the walk ends, its route with it (a plan makes its own).
|
||||
return new TargetChange(what == NewTarget.Arrow, true, false);
|
||||
}
|
||||
// A plan replaces the shown route itself; the arrow drops one that is for another place.
|
||||
if (what == NewTarget.Arrow && held.HasPlan && !SamePlace(ns, ew, held.PlanNs, held.PlanEw))
|
||||
return new TargetChange(true, false, false);
|
||||
return TargetChange.None;
|
||||
}
|
||||
}
|
||||
|
|
@ -33,8 +33,38 @@ internal sealed class Quest
|
|||
/// <summary>The Name column: the curated name, else the one-line info, else "Unknown quest" (upstream's rule).</summary>
|
||||
public string DisplayName => Name.Length > 0 ? Name : Info.Length > 0 ? Info : "Unknown quest";
|
||||
|
||||
/// <summary>The list label: the display name, or for a flag no list knows "(new)" and its description or flag.</summary>
|
||||
public string Label => IsNew ? "(new) " + (Name.Length > 0 ? Name : Flag) : DisplayName;
|
||||
/// <summary>Another quest in the list has the same name (set when the list is built).</summary>
|
||||
internal bool NameShared;
|
||||
|
||||
private string? _detail;
|
||||
|
||||
/// <summary>
|
||||
/// What sets this quest apart from the others of its name: its info's first sentence, with
|
||||
/// "Pickup timer for", "Timer for", "Cooldown for" and "Counter for" taken off. "" without info.
|
||||
/// R-20261124-141130-ca54: 11 rows read "Colosseum Bosses", the weekly Gladiator Diemos token
|
||||
/// timer (pickedupmarkerboss10x) among them, and nothing on the row said which was which.
|
||||
/// </summary>
|
||||
public string Detail => _detail ??= DetailOf(Info);
|
||||
|
||||
/// <summary>The list label: the display name ("Name: detail" when the name is shared), or for a flag no list knows "(new)" and its description or flag.</summary>
|
||||
public string Label => IsNew ? "(new) " + (Name.Length > 0 ? Name : Flag)
|
||||
: NameShared && Name.Length > 0 && Detail.Length > 0 ? Name + ": " + Detail : DisplayName;
|
||||
|
||||
/// <summary>The Quest Timers window's label: the detail alone when the name is shared, else the label.</summary>
|
||||
public string ShortLabel => !IsNew && NameShared && Name.Length > 0 && Detail.Length > 0 ? Detail : Label;
|
||||
|
||||
private static readonly string[] DetailPrefixes = { "Pickup timer for ", "Timer for ", "Cooldown for ", "Counter for " };
|
||||
|
||||
internal static string DetailOf(string info)
|
||||
{
|
||||
string s = (info ?? "").Trim();
|
||||
int stop = s.IndexOf(". ", StringComparison.Ordinal);
|
||||
if (stop >= 0) s = s.Substring(0, stop);
|
||||
s = s.TrimEnd('.', ' ');
|
||||
foreach (string p in DetailPrefixes)
|
||||
if (s.StartsWith(p, StringComparison.OrdinalIgnoreCase) && s.Length > p.Length) { s = s.Substring(p.Length); break; }
|
||||
return s.Length > 0 ? char.ToUpperInvariant(s[0]) + s.Substring(1) : s;
|
||||
}
|
||||
|
||||
/// <summary>The server is the source of truth where it has spoken (the flag's timer); else the lists.</summary>
|
||||
public bool IsRepeatable(QuestFlagStore flags) =>
|
||||
|
|
@ -267,6 +297,12 @@ internal sealed class QuestCatalog
|
|||
retail -= hidden;
|
||||
}
|
||||
|
||||
var names = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (Quest q in _quests)
|
||||
if (q.Name.Length > 0) names[q.Name] = names.TryGetValue(q.Name, out int n) ? n + 1 : 1;
|
||||
foreach (Quest q in _quests)
|
||||
q.NameShared = q.Name.Length > 0 && names.TryGetValue(q.Name, out int n) && n > 1;
|
||||
|
||||
RetailCount = retail;
|
||||
ServerCount = server;
|
||||
HiddenCount = hidden;
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ internal sealed class QuestTimersView
|
|||
{
|
||||
string flag = q.Flag;
|
||||
Quest row = q;
|
||||
w.Selectable(Cut(q.Label, 26), "qt.r." + flag, false, () => _c.PrintQuest(row), StatusX - 10f);
|
||||
w.Selectable(Cut(q.ShortLabel, 26), "qt.r." + flag, false, () => _c.PrintQuest(row), StatusX - 10f);
|
||||
string reward = _c.Book.RewardText(flag);
|
||||
w.Tooltip((reward.Length > 0 ? $"{q.Label}\n{flag}\nRewards: {reward}" : $"{q.Label}\n{flag}") + "\nClick: prints its texts in chat.");
|
||||
w.SameLine(StatusX);
|
||||
|
|
|
|||
|
|
@ -686,8 +686,9 @@ internal sealed partial class OracleView
|
|||
bool done = q.IsComplete(flags);
|
||||
if (_qDone != _qNotDone && done != _qDone) continue;
|
||||
if (_qRepeatable != _qOneTime && q.IsRepeatable(flags) != _qRepeatable) continue;
|
||||
if (!MatchesAll(q.Flag + " " + q.DisplayName, terms)) continue;
|
||||
_questRows.Add(new QuestRow { Kind = QuestKind.Quest, Key = q.Flag, Label = q.DisplayName, Done = done, Q = q });
|
||||
// The info and hint too: "Diemos" finds the Gladiator Diemos token timer, whose name is "Colosseum Bosses".
|
||||
if (!MatchesAll(q.Flag + " " + q.Label + " " + q.Info + " " + q.Hint, terms)) continue;
|
||||
_questRows.Add(new QuestRow { Kind = QuestKind.Quest, Key = q.Flag, Label = q.Label, Done = done, Q = q });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthSort.Sorting;
|
||||
using RynthCore.Plugin.RynthSort.Views;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
|
|
@ -29,6 +31,17 @@ internal sealed unsafe class HostSortWorld : ISortWorld
|
|||
|
||||
public SortInventory? ReadInventory() => _reader.Read(_host);
|
||||
|
||||
/// <summary>The item selected in the game, looked up in the packs as they are now (for "Add selected").</summary>
|
||||
public SelectedItem ReadSelected()
|
||||
{
|
||||
if (!_host.HasGetSelectedItemId) return SelectedItem.Of(SelectionKind.Unavailable);
|
||||
uint id = _host.GetSelectedItemId();
|
||||
if (id == 0) return SelectedItem.Of(SelectionKind.Nothing);
|
||||
SortInventory? inv = _reader.Read(_host);
|
||||
if (inv == null) return SelectedItem.Of(SelectionKind.NoInventory, id);
|
||||
return SelectionLookup.Find(inv, id, _host.TryGetObjectName(id, out string name) ? name : string.Empty);
|
||||
}
|
||||
|
||||
// PutItemInContainer answered "not bound" once: plain moves from then on.
|
||||
private bool _putUnbound;
|
||||
|
||||
|
|
@ -129,6 +142,102 @@ internal sealed unsafe class HostSortWorld : ISortWorld
|
|||
public int ErrorSeqNow() =>
|
||||
_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;
|
||||
|
||||
// ── Pack jobs: RynthAi's answers (RynthAi.Hub, read only) ─────────────
|
||||
|
||||
/// <summary>How long RynthAi's answers are used before they are asked again (the items the same).</summary>
|
||||
private const long JobAskMs = 3000;
|
||||
private JobAnswers? _jobAnswers;
|
||||
private long _jobAskedMs = long.MinValue / 2;
|
||||
private string _jobKey = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// RynthAi's answers for the jobs <paramref name="wanted"/>: asked again every few seconds, or at
|
||||
/// once when the items carried, the jobs or the mule change. RynthAi not loaded, too old (no
|
||||
/// RynthAi.Hub answers), or with no profile: that job is unknown and says why. Pump thread.
|
||||
/// </summary>
|
||||
public JobAnswers? AskJobs(SortInventory inv, IReadOnlyList<JobKind> wanted, string mule, long nowMs)
|
||||
{
|
||||
var ids = new List<uint>(inv.Main.Items.Count + 64);
|
||||
foreach (SortItem it in inv.Main.Items) if (SortPlanner.Sortable(it)) ids.Add(it.Id);
|
||||
foreach (SortPack p in inv.Packs)
|
||||
foreach (SortItem it in p.Items) if (SortPlanner.Sortable(it)) ids.Add(it.Id);
|
||||
var key = new System.Text.StringBuilder();
|
||||
foreach (JobKind k in wanted) key.Append((int)k).Append(',');
|
||||
key.Append(mule).Append('|').Append(ids.Count);
|
||||
uint sum = 0;
|
||||
foreach (uint id in ids) sum = unchecked(sum * 31 + id);
|
||||
key.Append('|').Append(sum);
|
||||
string k2 = key.ToString();
|
||||
if (_jobAnswers != null && k2 == _jobKey && nowMs - _jobAskedMs < JobAskMs) return _jobAnswers;
|
||||
_jobKey = k2;
|
||||
_jobAskedMs = nowMs;
|
||||
_jobAnswers = AskRynthAi(_host, ids.ToArray(), wanted, mule);
|
||||
return _jobAnswers;
|
||||
}
|
||||
|
||||
/// <summary>Asks RynthAi.Hub for each job (resolved again every call: a RynthAi reload frees nothing but changes the table's version).</summary>
|
||||
internal static JobAnswers AskRynthAi(RynthCoreHost host, uint[] ids, IReadOnlyList<JobKind> wanted, string mule)
|
||||
{
|
||||
var answers = new JobAnswers { Mule = mule };
|
||||
RynthAiHubApiV1* hub = null;
|
||||
string? why = null;
|
||||
if (!host.HasGetPluginInterface) why = "This RynthCore can't reach RynthAi";
|
||||
else
|
||||
{
|
||||
try { hub = (RynthAiHubApiV1*)host.GetPluginInterface(RynthAiHub.PluginName, RynthAiHubApiV1.InterfaceName, RynthAiHubApiV1.InterfaceVersion); }
|
||||
catch { hub = null; }
|
||||
if (hub == null || hub->Version == 0) { hub = null; why = "RynthAi isn't loaded"; }
|
||||
}
|
||||
foreach (JobKind kind in wanted)
|
||||
{
|
||||
if (hub == null) { answers.ByKind[kind] = JobAnswer.Unknown(why!); continue; }
|
||||
int offset = kind switch
|
||||
{
|
||||
JobKind.Salvage => RynthAiHubApiV1.LootActionsOffset,
|
||||
JobKind.Sell => RynthAiHubApiV1.VendorSellsOffset,
|
||||
_ => RynthAiHubApiV1.TradeGivesOffset,
|
||||
};
|
||||
if (!RynthAiHubApiV1.Has(hub, offset)) { answers.ByKind[kind] = JobAnswer.Unknown("This RynthAi is too old to say which items (update RynthAi)"); continue; }
|
||||
answers.ByKind[kind] = Ask(hub, kind, ids, mule);
|
||||
}
|
||||
return answers;
|
||||
}
|
||||
|
||||
private static JobAnswer Ask(RynthAiHubApiV1* hub, JobKind kind, uint[] ids, string mule)
|
||||
{
|
||||
var result = new byte[Math.Max(1, ids.Length)];
|
||||
byte* text = stackalloc byte[256];
|
||||
text[0] = 0;
|
||||
int ok;
|
||||
fixed (uint* pi = ids)
|
||||
fixed (byte* pr = result)
|
||||
{
|
||||
switch (kind)
|
||||
{
|
||||
case JobKind.Salvage:
|
||||
ok = hub->LootActions == null ? 0 : hub->LootActions(pi, ids.Length, pr, text, 256);
|
||||
break;
|
||||
case JobKind.Sell:
|
||||
ok = hub->VendorSells == null ? 0 : hub->VendorSells(pi, ids.Length, pr, text, 256);
|
||||
break;
|
||||
default:
|
||||
{
|
||||
byte[] who = System.Text.Encoding.UTF8.GetBytes(mule + "\0");
|
||||
fixed (byte* pw = who)
|
||||
ok = hub->TradeGives == null ? 0 : hub->TradeGives(pw, pi, ids.Length, pr, text, 256);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
string said = Marshal.PtrToStringUTF8((IntPtr)text) ?? string.Empty;
|
||||
if (ok != 1) return JobAnswer.Unknown(said.Length > 0 ? said.TrimEnd('.') : "RynthAi gave no answer");
|
||||
var a = new JobAnswer { Known = true, Text = said };
|
||||
const byte Salvage = 2; // VTankLootAction.Salvage
|
||||
for (int i = 0; i < ids.Length; i++)
|
||||
if (kind == JobKind.Salvage ? result[i] == Salvage : result[i] == 1) a.Marked.Add(ids[i]);
|
||||
return a;
|
||||
}
|
||||
|
||||
// ── RynthAi ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
|
|
@ -9,8 +9,9 @@ namespace RynthCore.Plugin.RynthSort;
|
|||
/// <summary>
|
||||
/// C ABI exports. Nothing may throw out of an [UnmanagedCallersOnly] method (it would take
|
||||
/// acclient.exe down): every export goes through RynthPluginRuntime, which catches and logs.
|
||||
/// RynthSort draws through the engine's script windows (host calls from its own tick), so it
|
||||
/// exports no render callback and keeps no buffer the engine reads later.
|
||||
/// RynthSort draws its window itself (plugin API v90, RynthSortPlugin.Window.cs): the sections
|
||||
/// manifest names it and RynthPluginRenderEmbed draws it. On older engines it draws through the
|
||||
/// script windows (host calls from its own tick) and the manifest is empty.
|
||||
/// </summary>
|
||||
public static unsafe class PluginExports
|
||||
{
|
||||
|
|
@ -27,7 +28,7 @@ public static unsafe class PluginExports
|
|||
public static IntPtr GetName() => LiteralPointer("RynthSort"u8);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetVersion() => LiteralPointer("0.3.1"u8);
|
||||
public static IntPtr GetVersion() => LiteralPointer("0.6.1"u8);
|
||||
|
||||
private static IntPtr LiteralPointer(ReadOnlySpan<byte> literal)
|
||||
{
|
||||
|
|
@ -102,6 +103,60 @@ public static unsafe class PluginExports
|
|||
catch { }
|
||||
}
|
||||
|
||||
// -- The window (plugin API v90; RynthSortPlugin.Window.cs) --
|
||||
|
||||
private static string? _sectionsJson;
|
||||
private static IntPtr _sectionsPtr;
|
||||
|
||||
/// <summary>The sections manifest (polled every ~2 s): the window. Kept until it changes.</summary>
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetSectionsJson()
|
||||
{
|
||||
try
|
||||
{
|
||||
RynthSortPlugin? plugin = Runtime.Plugin;
|
||||
if (plugin == null) return IntPtr.Zero;
|
||||
string json = plugin.SectionsJson();
|
||||
if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr;
|
||||
_sectionsJson = json;
|
||||
IntPtr fresh = Marshal.StringToCoTaskMemUTF8(json);
|
||||
IntPtr old = System.Threading.Interlocked.Exchange(ref _sectionsPtr, fresh);
|
||||
if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old);
|
||||
return fresh;
|
||||
}
|
||||
catch { return IntPtr.Zero; }
|
||||
}
|
||||
|
||||
/// <summary>The window's body ("window:rynthsort"; ":popout" when popped out). 1 drawn, 0 not ready, -2 failed.</summary>
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (surface == null) return 0;
|
||||
ReadOnlySpan<byte> name = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(surface);
|
||||
bool popped = name.EndsWith(":popout"u8);
|
||||
if (popped) name = name[..^":popout"u8.Length];
|
||||
if (!name.SequenceEqual("window:rynthsort"u8)) return 0;
|
||||
RynthSortPlugin? plugin = Runtime.Plugin;
|
||||
if (plugin == null) return 0;
|
||||
int result = plugin.RenderWindow(popped, out float wantH);
|
||||
if (result != 1) return result;
|
||||
if (wantWidth != null) *wantWidth = width;
|
||||
if (wantHeight != null) *wantHeight = wantH > 0 ? wantH : height;
|
||||
return 1;
|
||||
}
|
||||
catch { return 0; }
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorClose", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnVendorClose(uint vendorId) => Runtime.OnVendorClose(vendorId);
|
||||
|
||||
// AC's drag and drop (API v77; delivered on the plugin pump): an item the player drags is left
|
||||
// alone for a while ("leave items I use alone", Sorting/TouchWatch.cs). Older engines never call them.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDragStart", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnDragStart(uint objectId, uint spellId, uint iconId) => Runtime.OnDragStart(objectId, spellId, iconId);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnItemDropped", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnItemDropped(uint objectId, uint spellId, uint targetElementId) => Runtime.OnItemDropped(objectId, spellId, targetElementId);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,8 +6,10 @@
|
|||
time; misplaced items move to theirs, stacks are joined and items are put in order inside
|
||||
each pack (slot orders, API v80); Sort now, Clean and Unpack on demand; /rsort. Replaces the RynthSort Lua script (its saved
|
||||
rules are imported on first run). Pack moves wait for RynthAi through its read-only
|
||||
"RynthAi.Activity" interface (Shared/RynthAiActivityApi.cs). UI: the engine's script
|
||||
windows (ImGui), no Avalonia.
|
||||
"RynthAi.Activity" interface (Shared/RynthAiActivityApi.cs). UI (0.5.0): its own window drawn with
|
||||
ImGui.NET (plugin API v90), else the engine's script windows; no Avalonia. 0.6.0: pack names in
|
||||
the feed, drops from RynthCore's Inventory, handy items at the front of the main pack, pack jobs
|
||||
(Salvage, Sell, Mule: RynthAi.Hub's read-only answers, Shared/RynthAiHubApi.cs) and full-pack warnings.
|
||||
-->
|
||||
|
||||
<PropertyGroup>
|
||||
|
|
@ -24,10 +26,13 @@
|
|||
<StripSymbols>false</StripSymbols>
|
||||
<RootNamespace>RynthCore.Plugin.RynthSort</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthSort</AssemblyName>
|
||||
<!-- The DLL's version (its ProductVersion reads 0.6.1+<commit>); RynthSortPlugin.Version and GetVersion say the same. -->
|
||||
<Version>0.6.1</Version>
|
||||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
|
||||
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi) draw the
|
||||
window; vendor info (v67), plugin interfaces (v68), refusals (v70), trade (v72) and slot
|
||||
highest API use NOT behind a Has*/version check. Frameless plugin windows (v90,
|
||||
HasFramelessWindows, HasShortcuts for item pictures) draw its own window, else script
|
||||
windows (v71, HasUi) draw the old one; vendor info (v67), plugin interfaces (v68), refusals (v70), trade (v72) and slot
|
||||
orders / moves to a slot (v80: in-pack order, top-to-bottom pack numbers) are each checked first. Below v71 it still sorts (/rsort on|off|now|tidy|clean|unpack). -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>Keeps your packs sorted: new loot goes to the pack its rule names.</RynthPluginDescription>
|
||||
|
|
@ -38,11 +43,26 @@
|
|||
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
|
||||
<!-- An older RynthAi without RynthAi.Activity: its RynthAi.Status bot state instead. -->
|
||||
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
|
||||
<!-- Pack jobs (0.6.0): RynthAi's read-only answers about items (loot profile actions, AutoVendor, AutoTrade). -->
|
||||
<Compile Include="..\Shared\RynthAiHubApi.cs" Link="Shared\RynthAiHubApi.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>
|
||||
<!-- The window (2026-11-26): drawn with ImGui.NET bound to the engine's cimgui, in the engine's
|
||||
look (Shared\RynthUi; plugin API v90 hosts the frameless window and gives item pictures),
|
||||
as RynthDefective's shortcut bar. -->
|
||||
<Compile Include="..\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
|
||||
<Compile Include="..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
|
||||
<Compile Include="..\Shared\RynthUi\RynthUi.cs" Link="Shared\RynthUi\RynthUi.cs" />
|
||||
<Compile Include="..\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
|
||||
<TrimmerRootAssembly Include="ImGui.NET" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
|
||||
|
|
|
|||
337
Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.Window.cs
Normal file
337
Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.Window.cs
Normal file
|
|
@ -0,0 +1,337 @@
|
|||
// ============================================================================
|
||||
// RynthSort - RynthSortPlugin.Window.cs
|
||||
// The window drawn with ImGui (2026-11-26, the approved design for #rynth-issues
|
||||
// "The bag sort feature is lacking in UX"): RynthCore hosts a frameless window
|
||||
// (sections manifest, plugin API v90, "chrome": "none", "scale": "draw") and
|
||||
// RynthSort draws it (Window/SortWindow.cs) through RynthPluginRenderEmbed, as
|
||||
// RynthDefective draws its shortcut bar. On an engine without v90's frameless
|
||||
// windows and item pictures the script-window panel (Views/SortPanel.cs,
|
||||
// Ui/UiWindow.cs) stays.
|
||||
//
|
||||
// The tick builds the window's view-model (Screen/ScreenBuilder.cs) while the
|
||||
// window shows (it was drawn in the last 2 s), twice a second and at once after
|
||||
// anything the window or a command changed, and publishes it whole; the render
|
||||
// thread reads it and queues every click for the tick (WindowActions).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using RynthCore.Plugin.RynthSort.Screen;
|
||||
using RynthCore.Plugin.RynthSort.Sorting;
|
||||
using RynthCore.Plugin.RynthSort.Views;
|
||||
using RynthCore.Plugin.RynthSort.Window;
|
||||
using RynthCore.Plugin.Shared.RynthUi;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort;
|
||||
|
||||
public sealed partial class RynthSortPlugin
|
||||
{
|
||||
internal const string WindowSurface = "window:rynthsort";
|
||||
private const long ScreenBuildMs = 500, ScreenShownMs = 2000, OpenWhenHostedMs = 8000, WindowSyncMs = 1000;
|
||||
|
||||
/// <summary>
|
||||
/// The engine hosts frameless plugin windows and hands out item pictures and its look (plugin API
|
||||
/// v90): the window drawn with ImGui. Else the script-window panel. Decided once, at Initialize.
|
||||
/// </summary>
|
||||
private bool _direct;
|
||||
|
||||
private SortWindow? _sortWindow; // render thread
|
||||
private int _drawFailures; // render thread
|
||||
private volatile ScreenModel _screen = ScreenModel.Empty; // tick writes, render reads
|
||||
private readonly ConcurrentQueue<Action> _windowActions = new();
|
||||
private readonly ScreenSession _session = new();
|
||||
private long _screenDrawnMs = long.MinValue / 2; // render writes (Volatile), tick reads
|
||||
private long _nextScreenMs;
|
||||
private bool _screenDirty = true;
|
||||
private volatile bool _wantLayouts;
|
||||
private long _openUntilMs, _nextSyncMs;
|
||||
|
||||
internal bool UsesDirectWindow(RynthCoreHost host) =>
|
||||
host.HasFramelessWindows && host.HasShortcuts && host.HasSetPanelOpen && host.HasUiTheme;
|
||||
|
||||
internal static readonly string Manifest =
|
||||
"{\"version\":1,\"windows\":[{\"id\":\"sort\",\"title\":\"" + SortWindow.Title + "\",\"surface\":\"" + WindowSurface +
|
||||
"\",\"icon\":\"\\u" + ((int)RynthIcons.SortAscending[0]).ToString("X4", CultureInfo.InvariantCulture) +
|
||||
"\",\"width\":1060,\"height\":660,\"minWidth\":340,\"minHeight\":240,\"bar\":false,\"edgeToEdge\":true," +
|
||||
"\"chrome\":\"none\",\"scale\":\"draw\"}]}";
|
||||
|
||||
/// <summary>The sections manifest: the window, on an engine that can host it. Any thread.</summary>
|
||||
internal string SectionsJson() => _direct ? Manifest : "{\"version\":1}";
|
||||
|
||||
/// <summary>RynthPluginRenderEmbed "window:rynthsort". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
|
||||
internal int RenderWindow(bool popped, out float wantHeight)
|
||||
{
|
||||
wantHeight = 0;
|
||||
if (!_direct) return 0;
|
||||
System.Threading.Volatile.Write(ref _screenDrawnMs, Environment.TickCount64);
|
||||
try
|
||||
{
|
||||
_sortWindow ??= new SortWindow(Host, new WindowActions(this));
|
||||
wantHeight = _sortWindow.Draw(_screen, popped);
|
||||
_drawFailures = 0;
|
||||
return 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Host.Log($"[RynthSort] window draw failed: {ex.GetType().Name}: {ex.Message}");
|
||||
return ++_drawFailures >= 3 ? -2 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Plugin tick: the window's clicks, then its view while it shows.</summary>
|
||||
private void TickWindow(long now)
|
||||
{
|
||||
while (_windowActions.TryDequeue(out Action? act))
|
||||
{
|
||||
try { act(); }
|
||||
catch (Exception ex) { Host.Log($"[RynthSort] window action failed: {ex.GetType().Name}: {ex.Message}"); }
|
||||
_screenDirty = true;
|
||||
}
|
||||
if (!_direct) return;
|
||||
_session.Expire(now);
|
||||
OpenWhenHosted(now);
|
||||
SyncWindowOpen(now);
|
||||
bool shown = now - System.Threading.Volatile.Read(ref _screenDrawnMs) < ScreenShownMs;
|
||||
if (!shown || (!_screenDirty && now < _nextScreenMs)) return;
|
||||
_screenDirty = false;
|
||||
_nextScreenMs = now + ScreenBuildMs;
|
||||
try
|
||||
{
|
||||
_screen = ScreenBuilder.Build(_sort, new ScreenInputs
|
||||
{
|
||||
Character = _identityKnown ? _character : string.Empty,
|
||||
Server = _identityKnown ? _server : string.Empty,
|
||||
Warnings = _warnings,
|
||||
CanAddSelected = Host.HasGetSelectedItemId,
|
||||
CanSelect = Host.HasSelectItem,
|
||||
WantLayouts = _wantLayouts,
|
||||
Session = _session,
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Host.Log($"[RynthSort] window view failed: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The window was open when this character was last seen: open it again once the engine hosts it.</summary>
|
||||
private void OpenWhenHosted(long now)
|
||||
{
|
||||
if (_openUntilMs == 0) return;
|
||||
int state = Host.SetPanelOpen(SortWindow.Title, RynthPanelOpen.Open);
|
||||
if (state >= 0 || now > _openUntilMs) _openUntilMs = 0;
|
||||
}
|
||||
|
||||
/// <summary>Keeps the saved "window open" in step with the engine's window (closed with its x, opened from the Inventory).</summary>
|
||||
private void SyncWindowOpen(long now)
|
||||
{
|
||||
if (!_identityKnown || _openUntilMs != 0 || now < _nextSyncMs) return;
|
||||
_nextSyncMs = now + WindowSyncMs;
|
||||
int state = Host.SetPanelOpen(SortWindow.Title, RynthPanelOpen.Ask);
|
||||
if (state < 0) return;
|
||||
bool open = state == 1;
|
||||
if (open == _sort.Data.Settings.WindowOpen) return;
|
||||
_sort.Data.Settings.WindowOpen = open;
|
||||
RequestSave();
|
||||
}
|
||||
|
||||
/// <summary>/rsort: shows or hides the window. Returns its state afterwards (-1: not hosted yet).</summary>
|
||||
private int ToggleWindow() => Host.SetPanelOpen(SortWindow.Title, RynthPanelOpen.Toggle);
|
||||
|
||||
/// <summary>"+ Add selected" through the window's toast (and /rsort add): the selected item's name into side pack <paramref name="number"/>'s rules.</summary>
|
||||
private AddOutcome AddSelectedHere(int number)
|
||||
{
|
||||
AddOutcome outcome = new() { Status = AddStatus.Refused, Message = "Nothing was added." };
|
||||
_session.Edit(_sort.Data.Rules, rules =>
|
||||
{
|
||||
outcome = AddSelectedRules.Apply(rules, _sort.Planner.View, number, _world?.ReadSelected() ?? SelectedItem.Of(SelectionKind.Unavailable));
|
||||
return new EditResult(outcome.Status == AddStatus.Added, outcome.Message);
|
||||
}, Environment.TickCount64);
|
||||
if (outcome.Status == AddStatus.Added) RequestSave();
|
||||
_screenDirty = true;
|
||||
return outcome;
|
||||
}
|
||||
|
||||
private void QueueWindow(Action action)
|
||||
{
|
||||
if (_windowActions.Count < 64) _windowActions.Enqueue(action);
|
||||
}
|
||||
|
||||
/// <summary>What the window asks (render thread: queue only; everything runs on the tick).</summary>
|
||||
private sealed class WindowActions : ISortWindowActions
|
||||
{
|
||||
private readonly RynthSortPlugin _p;
|
||||
|
||||
public WindowActions(RynthSortPlugin plugin) => _p = plugin;
|
||||
|
||||
private SortController C => _p._sort;
|
||||
private static long Now => Environment.TickCount64;
|
||||
|
||||
private void Q(Action a) => _p.QueueWindow(a);
|
||||
|
||||
/// <summary>A rule change with its toast and Undo; saved when it changed something.</summary>
|
||||
private void Edit(Func<System.Collections.Generic.List<SortRule>, EditResult> change) => Q(() =>
|
||||
{
|
||||
if (!_p._identityKnown) return;
|
||||
if (_p._session.Edit(C.Data.Rules, change, Now)) _p.RequestSave();
|
||||
});
|
||||
|
||||
public void SetAuto(bool on) => Q(() => { C.SetAuto(on); _p.RequestSave(); });
|
||||
public void SortNow() => Q(() => C.StartJob(SortScope.All));
|
||||
public void Clean() => Q(() => C.StartJob(SortScope.Clean));
|
||||
public void PutBack() => Q(() =>
|
||||
{
|
||||
int n = C.PutBackCount;
|
||||
if (C.StartPutBack()) _p._session.Show($"Putting back {SortPanel.Count(n, "item")}; auto-sort is off so nothing moves again.", false, Now);
|
||||
});
|
||||
|
||||
public void SendKind(int pack, int cls) => Edit(rules => RuleEdits.SendKind(rules, C.Planner.View, pack, cls));
|
||||
|
||||
public void AddOverflow(int pack, int cls) => Edit(rules => RuleEdits.AddOverflow(rules, C.Planner.View, pack, cls));
|
||||
public void SetJob(int pack, int kind, string mule) => Q(() =>
|
||||
{
|
||||
SortInventory? inv = C.LastInventory;
|
||||
if (!_p._identityKnown || inv == null) return;
|
||||
var k = (JobKind)kind;
|
||||
if (!PackJobs.Set(C.Data.Jobs, inv, pack, k, mule))
|
||||
{
|
||||
_p._session.Show("Nothing changed.", false, Now);
|
||||
return;
|
||||
}
|
||||
_p.RequestSave();
|
||||
string where = PackNames.Label(inv, pack);
|
||||
_p._session.Show(k switch
|
||||
{
|
||||
JobKind.Salvage => $"{where} now takes what RynthAi's loot profile marks Salvage. Nothing has moved yet.",
|
||||
JobKind.Sell => $"{where} now takes what RynthAi's AutoVendor would sell. Nothing has moved yet.",
|
||||
JobKind.Mule => $"{where} now holds what RynthAi's AutoTrade would give {(mule.Trim().Length > 0 ? mule.Trim() : "a mule")}. Nothing has moved yet.",
|
||||
_ => $"{where} has no job now: only its rules.",
|
||||
}, false, Now);
|
||||
});
|
||||
|
||||
public void SendName(int pack, uint itemId) => Edit(rules =>
|
||||
{
|
||||
SortItem? item = Find(itemId);
|
||||
return item == null ? EditResult.Nothing("That item isn't in your packs now.") : RuleEdits.SendName(rules, C.Planner.View, pack, item);
|
||||
});
|
||||
|
||||
public void MoveOnce(uint itemId, int pack) => Q(() =>
|
||||
{
|
||||
SortInventory? inv = C.LastInventory;
|
||||
SortItem? item = Find(itemId);
|
||||
if (inv == null || item == null) { _p._session.Show("That item isn't in your packs now.", false, Now); return; }
|
||||
uint dest = pack == 0 ? inv.Main.Id : pack <= inv.Packs.Count ? inv.Packs[pack - 1].Id : 0;
|
||||
if (!C.StartSend(itemId, dest)) { _p._session.Show("That pack isn't carried now.", false, Now); return; }
|
||||
string where = pack == 0 ? "the main pack" : inv.Packs[pack - 1].Name.Length > 0 ? inv.Packs[pack - 1].Name : "pack " + pack;
|
||||
int hold = C.Data.Settings.HoldMin;
|
||||
_p._session.Show(hold > 0
|
||||
? $"{Name(item)} goes to {where} now and is left alone for {hold} min."
|
||||
: $"{Name(item)} goes to {where} now. Leaving items alone is off, so a sort may move it back.", false, Now);
|
||||
});
|
||||
|
||||
public void Hold(uint itemId) => Q(() =>
|
||||
{
|
||||
C.Touch.Hold(itemId, C.Clock, TouchKind.Chosen);
|
||||
SortItem? item = Find(itemId);
|
||||
_p._session.Show($"{(item != null ? Name(item) : "It")} is left alone for {C.Data.Settings.HoldMin} min.", false, Now);
|
||||
});
|
||||
|
||||
public void Release(uint itemId) => Q(() =>
|
||||
{
|
||||
C.Touch.Release(itemId);
|
||||
SortItem? item = Find(itemId);
|
||||
_p._session.Show($"RynthSort may move {(item != null ? Name(item) : "it")} again.", false, Now);
|
||||
});
|
||||
|
||||
public void Unhold(uint itemId) => Q(() => C.Touch.Release(itemId));
|
||||
|
||||
public void RemoveChip(int ruleUid, bool isName, int cls, string name) =>
|
||||
Edit(rules => RuleEdits.RemoveEntry(rules, C.Planner.View, ruleUid, isName, cls, name));
|
||||
|
||||
public void TurnOn(int ruleUid) => Edit(rules => RuleEdits.TurnOn(rules, ruleUid));
|
||||
|
||||
public void AddSelected(int pack) => Q(() => _p.AddSelectedHere(pack));
|
||||
|
||||
public void UseLayout(string key) => Edit(rules =>
|
||||
{
|
||||
StarterLayout? l = StarterLayouts.Find(key);
|
||||
return l == null ? EditResult.Nothing("That layout is gone.") : RuleEdits.UseLayout(rules, C.LastInventory, l);
|
||||
});
|
||||
|
||||
public void Undo() => Q(() => { if (_p._session.Undo(C.Data.Rules, Now)) _p.RequestSave(); });
|
||||
public void DismissToast() => Q(() => _p._session.Show(string.Empty, false, Now));
|
||||
|
||||
public void SetSettle(int seconds) => Setting(s => s.SettleSec = seconds);
|
||||
public void SetHold(int minutes) => Setting(s => s.HoldMin = minutes);
|
||||
public void SetGap(int ms) => Setting(s => s.GapMs = ms);
|
||||
public void SetCombat(bool on) => Setting(s => s.SortInCombat = on);
|
||||
public void SetOrder(bool on) => Setting(s => s.OrderInPacks = on);
|
||||
public void SetKindFirst(bool on) => Setting(s => s.OrderKindFirst = on);
|
||||
public void SetHandy(bool on) => Setting(s => s.HandyFront = on);
|
||||
public void HandyKind(int cls, bool add) => Setting(s => { if (add) HandyItems.AddClass(s, cls); else s.HandyClasses.Remove(cls); });
|
||||
public void HandyName(string name, bool add) => Setting(s => { if (add) HandyItems.AddName(s, name); else HandyItems.RemoveName(s, name); });
|
||||
|
||||
private void Setting(Action<SortSettings> set) => Q(() =>
|
||||
{
|
||||
if (!_p._identityKnown) return;
|
||||
set(C.Data.Settings);
|
||||
C.Data.Settings.Clamp();
|
||||
_p.RequestSave();
|
||||
});
|
||||
|
||||
public void EmptySidePacks() => Q(() =>
|
||||
{
|
||||
C.StartUnpack(null);
|
||||
_p._session.Show("Emptying the side packs; auto-sort is off so nothing moves back.", false, Now);
|
||||
});
|
||||
|
||||
public void SelectInGame(uint objectId) => Q(() =>
|
||||
{
|
||||
if (_p.Host.HasSelectItem) _p.Host.SelectItem(objectId);
|
||||
});
|
||||
|
||||
public void WantLayouts(bool open) => Q(() => _p._wantLayouts = open);
|
||||
|
||||
public void SendNameText(int pack, string text) => Edit(rules => RuleEdits.SendNameText(rules, C.Planner.View, pack, text));
|
||||
|
||||
public void SetCollapsed(uint packId, bool collapsed) => Fold(s => s.SetCollapsed(packId, collapsed));
|
||||
|
||||
public void SetMainCollapsed(bool collapsed) => Fold(s =>
|
||||
{
|
||||
if (s.MainCollapsed == collapsed) return false;
|
||||
s.MainCollapsed = collapsed;
|
||||
return true;
|
||||
});
|
||||
|
||||
public void SetAllCollapsed(bool collapsed) => Fold(s =>
|
||||
{
|
||||
SortInventory? inv = C.LastInventory;
|
||||
if (inv == null) return false;
|
||||
bool changed = false;
|
||||
foreach (SortPack pk in inv.Packs) changed |= s.SetCollapsed(pk.Id, collapsed);
|
||||
return changed;
|
||||
});
|
||||
|
||||
/// <summary>A card folded or opened: saved, and the window's model made again at once (no toast, no Undo).</summary>
|
||||
private void Fold(Func<SortSettings, bool> change) => Q(() =>
|
||||
{
|
||||
if (!_p._identityKnown || !change(C.Data.Settings)) return;
|
||||
_p.RequestSave();
|
||||
_p._screenDirty = true;
|
||||
});
|
||||
|
||||
private SortItem? Find(uint id)
|
||||
{
|
||||
SortInventory? inv = C.LastInventory;
|
||||
if (inv == null || id == 0) return null;
|
||||
foreach (SortItem it in inv.Main.Items) if (it.Id == id) return it;
|
||||
foreach (SortPack p in inv.Packs)
|
||||
foreach (SortItem it in p.Items) if (it.Id == id) return it;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string Name(SortItem it) => it.Name.Length > 0 ? it.Name : "the item";
|
||||
}
|
||||
}
|
||||
|
|
@ -19,7 +19,15 @@ namespace RynthCore.Plugin.RynthSort;
|
|||
/// each pack. Clean also sends items no rule wants back to the main pack; Unpack empties the side
|
||||
/// packs. A rule lists classes and parts of names and the pack they go to; a name match beats a
|
||||
/// class match. Rules and settings are kept per character; the RynthSort Lua script's saved rules
|
||||
/// are taken over on a character's first run.
|
||||
/// are taken over on a character's first run. A character it hasn't seen starts with auto-sort off
|
||||
/// and no rules; the window offers starter layouts fitted to its packs (Sorting/StarterLayouts.cs),
|
||||
/// previews what a sort would move, and Put back undoes the last sort. Items the player is using
|
||||
/// (moved, selected, dragged, taken off, picked up) are left alone for a few minutes
|
||||
/// (Sorting/TouchWatch.cs; the selection is polled each tick, drags come from the v77 UI hooks).
|
||||
///
|
||||
/// The window (0.5.0, 2026-11-26): drawn by RynthSort with ImGui in RynthCore's frameless plugin
|
||||
/// window (RynthSortPlugin.Window.cs, Window/SortWindow.cs) on engines with plugin API v90; the
|
||||
/// script-window panel (Views/SortPanel.cs) on older ones.
|
||||
///
|
||||
/// It stays out of the way (Sorting/SortGate.cs): nothing moves while a corpse or chest is being
|
||||
/// looted, a vendor or trade window is open, the character is busy or animating, in portal space,
|
||||
|
|
@ -29,9 +37,9 @@ namespace RynthCore.Plugin.RynthSort;
|
|||
/// Everything runs on the plugin pump (OnTick and the events the engine drains into it) except
|
||||
/// OnChatBarEnter, which the engine may call on AC's thread: it only queues the command.
|
||||
/// </summary>
|
||||
public sealed class RynthSortPlugin : RynthPluginBase
|
||||
public sealed partial class RynthSortPlugin : RynthPluginBase
|
||||
{
|
||||
public const string Version = "0.3.1";
|
||||
public const string Version = "0.6.1";
|
||||
private const long IdentityRetryMs = 1000;
|
||||
private const long SaveDelayMs = 750;
|
||||
private const long PassIntervalMs = 500;
|
||||
|
|
@ -95,22 +103,35 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
_world = new HostSortWorld(Host, _reader, _loot, () => _vendorOpen);
|
||||
_sort.SettingsChanged = RequestSave;
|
||||
_sort.PacksFixed = OnPacksFixed;
|
||||
_sort.Warn = text => _reply.Fail(text); // what didn't fit, once per sort
|
||||
_direct = UsesDirectWindow(Host);
|
||||
if (_direct)
|
||||
{
|
||||
// The window drawn with ImGui.NET bound to the engine's cimgui, in the engine's look (as RynthDefective's bar).
|
||||
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log("[RynthSort] " + msg));
|
||||
RynthCore.Plugin.Shared.RynthUi.RynthUi.Init(Host);
|
||||
}
|
||||
_panel = new SortPanel(_sort, RequestSave)
|
||||
{
|
||||
Warnings = () => _warnings,
|
||||
Character = () => _identityKnown ? _character : string.Empty,
|
||||
Icons = IconsOn,
|
||||
OpLevel = OpLevelNow,
|
||||
CanSelect = () => Host.HasSelectItem,
|
||||
SelectInGame = id => Host.HasSelectItem && Host.SelectItem(id),
|
||||
ReadSelected = () => _world?.ReadSelected() ?? SelectedItem.Of(SelectionKind.Unavailable),
|
||||
};
|
||||
// No bar button of its own: opened from the engine Inventory window's Sort button, the
|
||||
// Scripts menu or /rsort.
|
||||
_window = _ui.Add(new UiWindow("RynthSort/Main", "RynthSort")
|
||||
{
|
||||
DefaultWidth = 360f, DefaultHeight = 420f, MinWidth = 300f, MinHeight = 200f,
|
||||
BarButton = false,
|
||||
});
|
||||
Host.Log($"[RynthSort] {Version} initialized. /rsort shows or hides the window; /rsort on|off|now|tidy|clean|unpack. Files: {_store.Root}");
|
||||
// Scripts menu or /rsort. Only on an engine without frameless plugin windows: the window
|
||||
// drawn with ImGui takes the "RynthSort" title, which a script window would hold.
|
||||
if (!_direct)
|
||||
_window = _ui.Add(new UiWindow("RynthSort/Main", "RynthSort")
|
||||
{
|
||||
// Room for the status lines, the four page buttons and a pack's buttons on one line each.
|
||||
DefaultWidth = 440f, DefaultHeight = 560f, MinWidth = 330f, MinHeight = 260f,
|
||||
BarButton = false,
|
||||
});
|
||||
Host.Log($"[RynthSort] {Version} initialized ({(_direct ? "its own window" : "script window")}). /rsort shows or hides the window; /rsort on|off|now|tidy|clean|unpack|back|add. Files: {_store.Root}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
|
@ -124,6 +145,8 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
_reader.Reset();
|
||||
_loot.Reset();
|
||||
_warnings.Clear();
|
||||
_session.Reset();
|
||||
_screenDirty = true;
|
||||
}
|
||||
|
||||
public override void OnLogout()
|
||||
|
|
@ -148,6 +171,17 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
public override void OnVendorOpen(uint vendorId) => _vendorOpen = true;
|
||||
public override void OnVendorClose(uint vendorId) => _vendorOpen = false;
|
||||
|
||||
// The player's own hands on an item (API v77 drag and drop, on the pump): left alone for a while.
|
||||
public override void OnDragStart(uint objectId, uint spellId, uint iconId)
|
||||
{
|
||||
if (objectId != 0 && _identityKnown) _sort.Touch.NoteDrag(objectId, Environment.TickCount64);
|
||||
}
|
||||
|
||||
public override void OnItemDropped(uint objectId, uint spellId, uint targetElementId)
|
||||
{
|
||||
if (objectId != 0 && _identityKnown) _sort.Touch.NoteDrop(objectId, Environment.TickCount64);
|
||||
}
|
||||
|
||||
// ── Chat ────────────────────────────────────────────────────────────────
|
||||
|
||||
// May run on AC's thread: classify and queue only.
|
||||
|
|
@ -175,7 +209,13 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
switch (c.Verb)
|
||||
{
|
||||
case SortVerb.Window:
|
||||
if (_window != null)
|
||||
if (_direct)
|
||||
{
|
||||
int state = ToggleWindow();
|
||||
if (state >= 0) Print(SortCommand.Window(state == 1));
|
||||
else PrintFail("The RynthSort window isn't ready yet; try again in a moment.");
|
||||
}
|
||||
else if (_window != null)
|
||||
{
|
||||
_window.Visible = !_window.Visible; _window.NeedsPass = true;
|
||||
if (Host.HasUi) Print(SortCommand.Window(_window.Visible));
|
||||
|
|
@ -202,6 +242,30 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
case SortVerb.Status:
|
||||
PrintStatus();
|
||||
break;
|
||||
case SortVerb.Back:
|
||||
{
|
||||
int count = _sort.PutBackCount;
|
||||
if (_sort.StartPutBack()) Print(SortCommand.PuttingBack(count));
|
||||
else PrintFail(SortCommand.PuttingBack(0));
|
||||
break;
|
||||
}
|
||||
case SortVerb.Add:
|
||||
// The selected item's name into a pack's rules: the window's "+ Add selected".
|
||||
if (c.Pack == null) PrintFail(SortCommand.AddUsage);
|
||||
else if (_direct)
|
||||
{
|
||||
AddOutcome added = AddSelectedHere(c.Pack.Value);
|
||||
if (added.Status == AddStatus.Refused) PrintFail(added.Message);
|
||||
else Print(added.Message);
|
||||
}
|
||||
else if (_panel == null) PrintFail("The RynthSort window isn't ready yet.");
|
||||
else
|
||||
{
|
||||
AddOutcome added = _panel.AddSelected(c.Pack.Value);
|
||||
if (added.Status == AddStatus.Refused) PrintFail(added.Message);
|
||||
else Print(added.Message);
|
||||
}
|
||||
break;
|
||||
case SortVerb.Help:
|
||||
Print(SortCommand.Usage);
|
||||
break;
|
||||
|
|
@ -210,13 +274,15 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
break;
|
||||
}
|
||||
if (_window != null) _window.NeedsPass = true;
|
||||
_screenDirty = true;
|
||||
}
|
||||
|
||||
private void PrintStatus()
|
||||
{
|
||||
SortView v = _sort.Planner.View;
|
||||
string held = v.Held.Count > 0 ? $", {v.Held.Count} left alone (you used them)" : string.Empty;
|
||||
Print($"{_character}: auto-sort {(_sort.Data.Settings.Auto ? "on" : "off")}, {_sort.Status}; {_sort.Data.Rules.Count} rules, "
|
||||
+ $"{v.Packs.Count} side packs, main pack {v.MainUsed}/{v.MainCapacity}; moved {_sort.Moved}, failed {_sort.Failed} this session.");
|
||||
+ $"{v.Packs.Count} side packs, main pack {v.MainUsed}/{v.MainCapacity}{held}; moved {_sort.Moved}, failed {_sort.Failed} this session.");
|
||||
}
|
||||
|
||||
// Chat lines wait in the shared reply queue (the host drops a line within 100 ms of another
|
||||
|
|
@ -241,6 +307,8 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
if (!_identityKnown && now >= _nextIdentityTryMs) TryStartCharacter(now);
|
||||
if (_identityKnown && _world != null)
|
||||
{
|
||||
// The item selected in the game counts as in use while it is selected (and for the hold after).
|
||||
if (Host.HasGetSelectedItemId) _sort.Touch.NoteSelected(Host.GetSelectedItemId(), now);
|
||||
try { _sort.Tick(_world, now); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -254,7 +322,8 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
_movedSeen = _sort.Moved;
|
||||
_moving = _inWorld && _identityKnown && (_sort.HasMoveOut || (_lastMoveMs != 0 && now - _lastMoveMs < MovingHoldMs));
|
||||
|
||||
if (!Host.HasUi || _window == null || _panel == null) return;
|
||||
TickWindow(now);
|
||||
if (_direct || !Host.HasUi || _window == null || _panel == null) return;
|
||||
Record(_window, now);
|
||||
_ui.Submit(Host, now);
|
||||
|
||||
|
|
@ -265,14 +334,17 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
}
|
||||
}
|
||||
|
||||
// Item icons in script windows need op level 2 (engines from 2026-09-30); asked until it says yes.
|
||||
private bool _icons;
|
||||
private bool IconsOn()
|
||||
// The engine's script-window op level: 2 draws item icons (engines from 2026-09-30), 3 tables
|
||||
// and fonts (not released yet). Asked until it answers.
|
||||
private int _opLevel = -1;
|
||||
private int OpLevelNow()
|
||||
{
|
||||
if (!_icons) _icons = Host.HasUi && Host.TryGetUiInfo(out RynthCore.PluginSdk.UiInfoNative info) && info.OpLevel >= 2;
|
||||
return _icons;
|
||||
if (_opLevel < 0 && Host.HasUi && Host.TryGetUiInfo(out RynthCore.PluginSdk.UiInfoNative info)) _opLevel = info.OpLevel;
|
||||
return Math.Max(_opLevel, 0);
|
||||
}
|
||||
|
||||
private bool IconsOn() => OpLevelNow() >= 2;
|
||||
|
||||
private void TryStartCharacter(long now)
|
||||
{
|
||||
_nextIdentityTryMs = now + IdentityRetryMs;
|
||||
|
|
@ -283,10 +355,10 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
_server = server;
|
||||
_character = name;
|
||||
CharacterSortData data = _store.Load(server, name, out string? problem);
|
||||
if (problem != null) Host.Log($"[RynthSort] couldn't read the saved rules ({problem}); using defaults.");
|
||||
if (problem != null) Host.Log($"[RynthSort] couldn't read the saved rules ({problem}); starting with none (the file is kept as .bak at the next save).");
|
||||
_sort.Data = data;
|
||||
_identityKnown = true;
|
||||
_backupOnSave = false;
|
||||
_backupOnSave = problem != null; // a broken file is kept beside the new one (.bak)
|
||||
|
||||
string own = _store.PathFor(server, name);
|
||||
if (data.ImportedFrom.Length > 0 && !File.Exists(own))
|
||||
|
|
@ -299,6 +371,12 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
}
|
||||
CheckLuaScriptAutostart(server, name);
|
||||
if (_window != null) { _window.Visible = data.Settings.WindowOpen; _window.NeedsPass = true; }
|
||||
if (_direct)
|
||||
{
|
||||
_session.Reset();
|
||||
_screenDirty = true;
|
||||
_openUntilMs = data.Settings.WindowOpen ? now + OpenWhenHostedMs : 0;
|
||||
}
|
||||
Host.Log($"[RynthSort] sorting for {name} on {server}: {data.Rules.Count} rules, auto-sort {(data.Settings.Auto ? "on" : "off")}; file {own}");
|
||||
}
|
||||
|
||||
|
|
@ -363,6 +441,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
|
|||
private void RequestSave()
|
||||
{
|
||||
if (_window != null) _window.NeedsPass = true;
|
||||
_screenDirty = true;
|
||||
if (_saveDueMs == 0) _saveDueMs = Environment.TickCount64 + SaveDelayMs;
|
||||
}
|
||||
|
||||
|
|
|
|||
56
Plugins/RynthCore.Plugin.RynthSort/Screen/Arrivals.cs
Normal file
56
Plugins/RynthCore.Plugin.RynthSort/Screen/Arrivals.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Screen;
|
||||
|
||||
/// <summary>
|
||||
/// Which tiles just arrived in another pack, for the window's pop-in: each new view-model is
|
||||
/// compared with the last one (an item whose pack changed arrived now). The first view of a
|
||||
/// character arrives nothing. Render thread only (the renderer owns one); pure, so the tests drive it.
|
||||
/// </summary>
|
||||
internal sealed class Arrivals
|
||||
{
|
||||
/// <summary>How long the pop-in lasts (seconds).</summary>
|
||||
public const double PopSeconds = 0.6;
|
||||
|
||||
private readonly Dictionary<uint, int> _where = new();
|
||||
private readonly Dictionary<uint, double> _arrived = new();
|
||||
private int _version = -1;
|
||||
private string _who = string.Empty;
|
||||
|
||||
/// <summary>Compares <paramref name="m"/> with the last view (once per build); <paramref name="now"/> in seconds.</summary>
|
||||
public void Update(ScreenModel m, double now)
|
||||
{
|
||||
if (m.Version == _version) return;
|
||||
_version = m.Version;
|
||||
if (!m.Ready) return;
|
||||
bool fresh = _who != m.Who || _where.Count == 0;
|
||||
_who = m.Who;
|
||||
foreach (KeyValuePair<uint, TileModel> kv in m.TilesById)
|
||||
if (!fresh && _where.TryGetValue(kv.Key, out int was) && was != kv.Value.Where) _arrived[kv.Key] = now;
|
||||
_where.Clear();
|
||||
foreach (KeyValuePair<uint, TileModel> kv in m.TilesById) _where[kv.Key] = kv.Value.Where;
|
||||
if (_arrived.Count > 64)
|
||||
{
|
||||
var old = new List<uint>();
|
||||
foreach (KeyValuePair<uint, double> kv in _arrived) if (now - kv.Value > PopSeconds) old.Add(kv.Key);
|
||||
foreach (uint id in old) _arrived.Remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>How far the pop-in of <paramref name="itemId"/> is (0 just arrived, 1 done or none).</summary>
|
||||
public float Progress(uint itemId, double now)
|
||||
{
|
||||
if (!_arrived.TryGetValue(itemId, out double at)) return 1f;
|
||||
double t = (now - at) / PopSeconds;
|
||||
if (t >= 1) { _arrived.Remove(itemId); return 1f; }
|
||||
return t <= 0 ? 0f : (float)t;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_where.Clear();
|
||||
_arrived.Clear();
|
||||
_version = -1;
|
||||
_who = string.Empty;
|
||||
}
|
||||
}
|
||||
33
Plugins/RynthCore.Plugin.RynthSort/Screen/DropOnce.cs
Normal file
33
Plugins/RynthCore.Plugin.RynthSort/Screen/DropOnce.cs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
namespace RynthCore.Plugin.RynthSort.Screen;
|
||||
|
||||
/// <summary>
|
||||
/// One drop, one set of choices. An item dragged out of RynthCore's Inventory window and let go
|
||||
/// over a pack card reaches the window twice: as the ImGui payload the Inventory publishes
|
||||
/// ("RYNTH_INV_ITEM") and through the engine's drop target (the Inventory offers a drop outside
|
||||
/// itself to every panel that takes items). A drag out of AC's own windows comes one way or the
|
||||
/// other, depending on the engine. The second arrival of the same item within
|
||||
/// <see cref="WindowSec"/> is the same drop. Pure; the window keeps one.
|
||||
/// </summary>
|
||||
internal sealed class DropOnce
|
||||
{
|
||||
public const double WindowSec = 1.0;
|
||||
|
||||
private uint _item;
|
||||
private double _at = double.MinValue;
|
||||
|
||||
/// <summary>True when <paramref name="itemId"/> dropped at <paramref name="now"/> (seconds) is a new drop, not the echo of the last one.</summary>
|
||||
public bool Take(uint itemId, double now)
|
||||
{
|
||||
if (itemId == 0) return false;
|
||||
if (itemId == _item && now - _at < WindowSec && now >= _at) return false;
|
||||
_item = itemId;
|
||||
_at = now;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_item = 0;
|
||||
_at = double.MinValue;
|
||||
}
|
||||
}
|
||||
93
Plugins/RynthCore.Plugin.RynthSort/Screen/Kinds.cs
Normal file
93
Plugins/RynthCore.Plugin.RynthSort/Screen/Kinds.cs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Screen;
|
||||
|
||||
/// <summary>
|
||||
/// How the window names and colours a kind of item (an ObjectClass): the approved design's
|
||||
/// sentence-case labels ("Spell components", "Mana stones") and its kind colours (ARGB), used for
|
||||
/// rule chips, the layout bars, the plan rows' fallback squares and a tile whose picture isn't made
|
||||
/// yet. Pure.
|
||||
/// </summary>
|
||||
internal static class Kinds
|
||||
{
|
||||
// The design's palette (rynthsort-packs.html KINDS), ARGB.
|
||||
public const uint Components = 0xFF2F7FA6, Salvage = 0xFF9A7330, Gems = 0xFF7550B5, Keys = 0xFFA87B30,
|
||||
Stones = 0xFF2E95AD, Kits = 0xFF3F8F50, Picks = 0xFF68737F, Food = 0xFFA44A60, Notes = 0xFF8F8A33,
|
||||
Coins = 0xFFB18F30, Gear = 0xFF56606C, Weapons = 0xFF5D5568, Scrolls = 0xFF85563F, Crafting = 0xFF6A7F3A;
|
||||
|
||||
/// <summary>The kind's colour (ARGB).</summary>
|
||||
public static uint Color(int cls) => cls switch
|
||||
{
|
||||
ObjectClasses.SpellComponent => Components,
|
||||
ObjectClasses.Salvage => Salvage,
|
||||
ObjectClasses.Gem => Gems,
|
||||
ObjectClasses.Key => Keys,
|
||||
ObjectClasses.ManaStone => Stones,
|
||||
ObjectClasses.HealingKit => Kits,
|
||||
ObjectClasses.Lockpick => Picks,
|
||||
ObjectClasses.Food => Food,
|
||||
ObjectClasses.TradeNote => Notes,
|
||||
ObjectClasses.Money => Coins,
|
||||
ObjectClasses.Armor or ObjectClasses.Clothing or ObjectClasses.Jewelry => Gear,
|
||||
ObjectClasses.MeleeWeapon or ObjectClasses.MissileWeapon or ObjectClasses.WandStaffOrb or ObjectClasses.Bundle => Weapons,
|
||||
ObjectClasses.Scroll or ObjectClasses.Book or ObjectClasses.Journal => Scrolls,
|
||||
ObjectClasses.Plant or ObjectClasses.BaseAlchemy or ObjectClasses.BaseCooking or ObjectClasses.BaseFletching
|
||||
or ObjectClasses.CraftedAlchemy or ObjectClasses.CraftedCooking or ObjectClasses.CraftedFletching or ObjectClasses.Ust => Crafting,
|
||||
_ => Gear,
|
||||
};
|
||||
|
||||
private static readonly Dictionary<int, string> LabelCache = new();
|
||||
|
||||
/// <summary>"Spell components", "Mana stones", "Melee weapons": what a chip or a layout row says.</summary>
|
||||
public static string Label(int cls)
|
||||
{
|
||||
lock (LabelCache)
|
||||
{
|
||||
if (LabelCache.TryGetValue(cls, out string? s)) return s;
|
||||
s = cls == ObjectClasses.SpellComponent ? "Spell components" : Sentence(ObjectClasses.Plural(cls));
|
||||
LabelCache[cls] = s;
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Mana Stones" to "Mana stones": the first letter as it is, the rest of each word's first letters small.</summary>
|
||||
internal static string Sentence(string text)
|
||||
{
|
||||
if (text.Length < 2) return text;
|
||||
char[] a = text.ToCharArray();
|
||||
for (int i = 1; i < a.Length; i++)
|
||||
if (a[i - 1] == ' ') a[i] = char.ToLowerInvariant(a[i]);
|
||||
return new string(a);
|
||||
}
|
||||
|
||||
/// <summary>A name rule's chip: <c>named "Opal"</c>.</summary>
|
||||
public static string NameChip(string name) => "named \"" + name + "\"";
|
||||
|
||||
private static readonly Dictionary<int, string> QtyCache = new();
|
||||
|
||||
/// <summary>A stack's count as the tile's corner shows it: "" for one, "75", "2.4k" from 1000.</summary>
|
||||
public static string Qty(int stack)
|
||||
{
|
||||
if (stack <= 1) return string.Empty;
|
||||
lock (QtyCache)
|
||||
{
|
||||
if (QtyCache.TryGetValue(stack, out string? s)) return s;
|
||||
s = stack < 1000
|
||||
? stack.ToString(CultureInfo.InvariantCulture)
|
||||
: (System.Math.Round(stack / 100.0) / 10.0).ToString("0.#", CultureInfo.InvariantCulture) + "k";
|
||||
if (QtyCache.Count < 4096) QtyCache[stack] = s;
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"AO" for "Amuli Shadow Coat": the letters a tile shows while its picture is being made.</summary>
|
||||
public static string Initials(string name)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name)) return "?";
|
||||
string[] words = name.Split(' ', System.StringSplitOptions.RemoveEmptyEntries);
|
||||
if (words.Length >= 2) return string.Concat(char.ToUpperInvariant(words[0][0]), char.ToUpperInvariant(words[^1][0]));
|
||||
return name.Length <= 3 ? name : name[..3];
|
||||
}
|
||||
}
|
||||
277
Plugins/RynthCore.Plugin.RynthSort/Screen/RuleEdits.cs
Normal file
277
Plugins/RynthCore.Plugin.RynthSort/Screen/RuleEdits.cs
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthSort.Sorting;
|
||||
using RynthCore.Plugin.RynthSort.Views;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Screen;
|
||||
|
||||
/// <summary>What a rule change did: whether anything changed, and the toast that says so.</summary>
|
||||
internal readonly record struct EditResult(bool Changed, string Text)
|
||||
{
|
||||
public static EditResult Nothing(string text) => new(false, text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The window's rule changes, in the design's terms: a pack card's chips are the kinds and names its
|
||||
/// rules hold. A kind sent to a pack leaves every other pack ("All gems"); a name sent to a pack
|
||||
/// leaves every other pack's rules too and, being a name, beats any kind ("Only \"Black Opal\"");
|
||||
/// a chip's × takes that one entry out of its rule (an emptied rule goes). Nothing here moves an
|
||||
/// item. Pure: works on the rule list and the planner's view (the packs as numbered now).
|
||||
/// </summary>
|
||||
internal static class RuleEdits
|
||||
{
|
||||
/// <summary>The side pack's name for a toast ("Satchel", "Satchel (2)" when two share it), or "pack 3".</summary>
|
||||
internal static string PackName(SortView view, int number) => PackNames.Label(view, number);
|
||||
|
||||
/// <summary>
|
||||
/// "All <kind>": class <paramref name="cls"/> goes to side pack <paramref name="number"/>,
|
||||
/// into one of its rules (a new one when it has none with room), and out of every other pack's.
|
||||
/// </summary>
|
||||
public static EditResult SendKind(List<SortRule> rules, SortView view, int number, int cls)
|
||||
{
|
||||
if (number < 1 || number > view.Packs.Count) return EditResult.Nothing("That pack isn't carried now.");
|
||||
string label = Kinds.Label(cls);
|
||||
string pack = PackName(view, number);
|
||||
bool already = false;
|
||||
foreach (SortRule r in rules)
|
||||
if (r.On && r.HasClass(cls) && SortPanel.ShownPack(view, r) == number) { already = true; break; }
|
||||
|
||||
var taken = new List<string>();
|
||||
for (int i = rules.Count - 1; i >= 0; i--)
|
||||
{
|
||||
SortRule r = rules[i];
|
||||
int at = SortPanel.ShownPack(view, r);
|
||||
if (at == number || !r.HasClass(cls)) continue;
|
||||
r.RemoveClass(cls);
|
||||
string from = at > 0 ? PackName(view, at) : "a pack you don't carry";
|
||||
if (!taken.Contains(from)) taken.Add(from);
|
||||
if (r.IsEmpty) rules.RemoveAt(i);
|
||||
}
|
||||
if (already && taken.Count == 0) return EditResult.Nothing($"{label} already go to {pack}.");
|
||||
if (!already)
|
||||
{
|
||||
SortRule? target = null;
|
||||
foreach (SortRule r in rules)
|
||||
if (SortPanel.ShownPack(view, r) == number && r.On && r.Classes.Count > 0 && r.Classes.Count < SortRule.MaxClasses) { target = r; break; }
|
||||
if (target == null)
|
||||
foreach (SortRule r in rules)
|
||||
if (SortPanel.ShownPack(view, r) == number && r.On && r.Classes.Count < SortRule.MaxClasses) { target = r; break; }
|
||||
if (target == null)
|
||||
{
|
||||
if (rules.Count >= SortStore.MaxRules)
|
||||
return new EditResult(taken.Count > 0, $"There is no room for another rule (the limit is {SortStore.MaxRules}).");
|
||||
target = new SortRule();
|
||||
SortPanel.SetPack(target, view, number);
|
||||
rules.Add(target);
|
||||
}
|
||||
target.AddClass(cls);
|
||||
}
|
||||
string fromText = taken.Count == 0 ? string.Empty : " (taken from " + string.Join(", ", taken) + ")";
|
||||
return new EditResult(true, $"All {label.ToLowerInvariant()} now go to {pack}{fromText}. Nothing has moved yet.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Overflow": class <paramref name="cls"/> stays with the pack that has it, and side pack
|
||||
/// <paramref name="number"/> takes it when that pack is full (the planner spills into the next
|
||||
/// pack with the same rule). A new rule at the end of the list, so the pack that has the kind
|
||||
/// keeps it first. Nothing when no other carried pack has the kind (that is "All <kind>").
|
||||
/// </summary>
|
||||
public static EditResult AddOverflow(List<SortRule> rules, SortView view, int number, int cls)
|
||||
{
|
||||
if (number < 1 || number > view.Packs.Count) return EditResult.Nothing("That pack isn't carried now.");
|
||||
string label = Kinds.Label(cls);
|
||||
int firstPack = 0;
|
||||
foreach (SortRule r in rules)
|
||||
if (r.On && r.HasClass(cls)) { firstPack = SortPanel.ShownPack(view, r); break; }
|
||||
if (firstPack <= 0) return EditResult.Nothing($"No pack you carry takes {label.ToLowerInvariant()} yet: add the kind to a pack first.");
|
||||
if (firstPack == number) return EditResult.Nothing($"{label} already go to {PackName(view, number)}.");
|
||||
foreach (SortRule r in rules)
|
||||
if (r.On && r.HasClass(cls) && SortPanel.ShownPack(view, r) == number)
|
||||
return EditResult.Nothing($"{PackName(view, number)} already takes {label.ToLowerInvariant()} when {PackName(view, firstPack)} is full.");
|
||||
if (rules.Count >= SortStore.MaxRules) return EditResult.Nothing($"There is no room for another rule (the limit is {SortStore.MaxRules}).");
|
||||
var rule = new SortRule();
|
||||
SortPanel.SetPack(rule, view, number);
|
||||
rule.AddClass(cls);
|
||||
rules.Add(rule);
|
||||
return new EditResult(true, $"{label} go to {PackName(view, firstPack)}, and to {PackName(view, number)} when it is full. Nothing has moved yet.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Only <name>": the item's name (without a "(100)" count) goes into side pack
|
||||
/// <paramref name="number"/>'s rules, and the same name comes out of every other pack's.
|
||||
/// </summary>
|
||||
public static EditResult SendName(List<SortRule> rules, SortView view, int number, SortItem item)
|
||||
{
|
||||
if (number < 1 || number > view.Packs.Count) return EditResult.Nothing("That pack isn't carried now.");
|
||||
string entry = AddSelectedRules.EntryFor(item.Name);
|
||||
if (entry.Length == 0) return EditResult.Nothing("That item has no name the client can read yet; try again in a moment.");
|
||||
bool removed = false;
|
||||
for (int i = rules.Count - 1; i >= 0; i--)
|
||||
{
|
||||
SortRule r = rules[i];
|
||||
if (SortPanel.ShownPack(view, r) == number || !r.HasName(entry)) continue;
|
||||
r.RemoveName(entry);
|
||||
removed = true;
|
||||
if (r.IsEmpty) rules.RemoveAt(i);
|
||||
}
|
||||
var sel = new SelectedItem { Kind = SelectionKind.Item, Id = item.Id, Name = item.Name, Item = item };
|
||||
AddOutcome o = AddSelectedRules.Apply(rules, view, number, sel);
|
||||
string pack = PackName(view, number);
|
||||
return o.Status switch
|
||||
{
|
||||
AddStatus.Added => new EditResult(true, $"\"{entry}\" now goes to {pack}. Nothing has moved yet."),
|
||||
AddStatus.AlreadyThere when removed => new EditResult(true, $"\"{entry}\" now goes to {pack}. Nothing has moved yet."),
|
||||
AddStatus.AlreadyThere => EditResult.Nothing($"\"{entry}\" already goes to {pack}."),
|
||||
_ => new EditResult(removed, o.Message),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A name typed into "+ Add a rule" (0.6.1): items whose name has <paramref name="text"/> in it go
|
||||
/// to side pack <paramref name="number"/>, and the same name comes out of every other pack's rules.
|
||||
/// No item needed (before, a name rule took an item dragged on, or the one selected in the game).
|
||||
/// </summary>
|
||||
public static EditResult SendNameText(List<SortRule> rules, SortView view, int number, string text)
|
||||
{
|
||||
if (number < 1 || number > view.Packs.Count) return EditResult.Nothing("That pack isn't carried now.");
|
||||
string entry = (text ?? string.Empty).Trim();
|
||||
if (entry.Length > SortRule.MaxNameLength) entry = entry.Substring(0, SortRule.MaxNameLength).Trim();
|
||||
if (entry.Length == 0) return EditResult.Nothing("Type part of a name first.");
|
||||
string pack = PackName(view, number);
|
||||
SortRule? here = rules.Find(r => SortPanel.ShownPack(view, r) == number && r.HasName(entry));
|
||||
if (here != null && !here.On) return EditResult.Nothing($"\"{entry}\" is in a rule of {pack} that is turned off: click it to turn it on.");
|
||||
bool removed = false;
|
||||
for (int i = rules.Count - 1; i >= 0; i--)
|
||||
{
|
||||
SortRule r = rules[i];
|
||||
if (SortPanel.ShownPack(view, r) == number || !r.HasName(entry)) continue;
|
||||
r.RemoveName(entry);
|
||||
removed = true;
|
||||
if (r.IsEmpty) rules.RemoveAt(i);
|
||||
}
|
||||
if (here != null)
|
||||
return removed
|
||||
? new EditResult(true, $"\"{entry}\" now goes to {pack} only. Nothing has moved yet.")
|
||||
: EditResult.Nothing($"\"{entry}\" already goes to {pack}.");
|
||||
SortRule? target = null;
|
||||
// This pack's rule that is on and already lists names, else a new rule, else any of its rules with room.
|
||||
foreach (SortRule r in rules)
|
||||
if (SortPanel.ShownPack(view, r) == number && r.On && r.Names.Count > 0 && r.Names.Count < SortRule.MaxNames) { target = r; break; }
|
||||
if (target == null && rules.Count < SortStore.MaxRules)
|
||||
{
|
||||
target = new SortRule();
|
||||
SortPanel.SetPack(target, view, number);
|
||||
rules.Add(target);
|
||||
}
|
||||
if (target == null)
|
||||
foreach (SortRule r in rules)
|
||||
if (SortPanel.ShownPack(view, r) == number && r.On && r.Names.Count < SortRule.MaxNames) { target = r; break; }
|
||||
if (target == null || !target.AddName(entry))
|
||||
return removed
|
||||
? new EditResult(true, $"\"{entry}\" left the other packs' rules, but {pack}'s rules are full.")
|
||||
: EditResult.Nothing($"There is no room in {pack}'s rules.");
|
||||
return new EditResult(true, $"Items with \"{entry}\" in their name now go to {pack}. Nothing has moved yet.");
|
||||
}
|
||||
|
||||
/// <summary>A chip's ×: the kind or name comes out of rule <paramref name="uid"/> (the rule goes when nothing is left in it).</summary>
|
||||
public static EditResult RemoveEntry(List<SortRule> rules, SortView view, int uid, bool isName, int cls, string name)
|
||||
{
|
||||
int i = rules.FindIndex(r => r.Uid == uid);
|
||||
if (i < 0) return EditResult.Nothing("That rule is gone already.");
|
||||
SortRule r = rules[i];
|
||||
int at = SortPanel.ShownPack(view, r);
|
||||
string where = at > 0 ? PackName(view, at) : "that pack";
|
||||
bool done = isName ? r.RemoveName(name) : r.RemoveClass(cls);
|
||||
if (!done) return EditResult.Nothing("That is gone from the rule already.");
|
||||
if (r.IsEmpty) rules.RemoveAt(i);
|
||||
return new EditResult(true, isName
|
||||
? $"\"{name}\" no longer goes to {where}."
|
||||
: $"{Kinds.Label(cls)} no longer go to {where}.");
|
||||
}
|
||||
|
||||
/// <summary>A faded chip's click: its rule is turned on.</summary>
|
||||
public static EditResult TurnOn(List<SortRule> rules, int uid)
|
||||
{
|
||||
SortRule? r = rules.Find(x => x.Uid == uid);
|
||||
if (r == null) return EditResult.Nothing("That rule is gone already.");
|
||||
if (r.On) return EditResult.Nothing("That rule is on already.");
|
||||
r.On = true;
|
||||
return new EditResult(true, $"Rule turned on: {SortRules.Describe(r)}.");
|
||||
}
|
||||
|
||||
/// <summary>"Use this layout": the layout's rules, fitted to the packs carried, replace the character's.</summary>
|
||||
public static EditResult UseLayout(List<SortRule> rules, SortInventory? inv, StarterLayout layout)
|
||||
{
|
||||
if (inv == null) return EditResult.Nothing("Your packs aren't read yet; try again in a moment.");
|
||||
if (inv.Packs.Count == 0) return EditResult.Nothing("You carry no side packs, so a layout has nowhere to put things.");
|
||||
LayoutPlan plan = StarterLayouts.Fit(layout, inv);
|
||||
rules.Clear();
|
||||
rules.AddRange(plan.Rules);
|
||||
return new EditResult(true, $"Rules set from {layout.Name}. Press Sort now when you're ready.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The window's tick-side state: the toast after a change and the one Undo it offers (the rules as
|
||||
/// they were before the last change). Pure; the plugin owns one per session.
|
||||
/// </summary>
|
||||
internal sealed class ScreenSession
|
||||
{
|
||||
public const long ToastMs = 6000;
|
||||
|
||||
private List<SortRule>? _undo;
|
||||
private int _seq;
|
||||
|
||||
/// <summary>The toast showing, or null.</summary>
|
||||
public ToastModel? Toast { get; private set; }
|
||||
|
||||
/// <summary>Bumped by every change the window should show at once.</summary>
|
||||
public int Version { get; private set; }
|
||||
|
||||
public bool CanUndo => _undo != null;
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_undo = null;
|
||||
Toast = null;
|
||||
Version++;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs a rule change on <paramref name="rules"/>: on a change the rules as they were become the
|
||||
/// Undo and the toast offers it; otherwise the toast just says why nothing changed. True on a change.
|
||||
/// </summary>
|
||||
public bool Edit(List<SortRule> rules, Func<List<SortRule>, EditResult> change, long nowMs)
|
||||
{
|
||||
List<SortRule> before = rules.ConvertAll(r => r.Clone());
|
||||
EditResult result = change(rules);
|
||||
if (result.Changed) _undo = before;
|
||||
Show(result.Text, result.Changed, nowMs);
|
||||
return result.Changed;
|
||||
}
|
||||
|
||||
/// <summary>Shows <paramref name="text"/> (with Undo when <paramref name="undo"/> and there is one).</summary>
|
||||
public void Show(string text, bool undo, long nowMs)
|
||||
{
|
||||
Version++;
|
||||
if (string.IsNullOrEmpty(text)) { Toast = null; return; }
|
||||
Toast = new ToastModel { Text = text, CanUndo = undo && _undo != null, Seq = ++_seq, UntilMs = nowMs + ToastMs };
|
||||
}
|
||||
|
||||
/// <summary>Undo: the rules as they were before the last change. False when there is nothing to undo.</summary>
|
||||
public bool Undo(List<SortRule> rules, long nowMs)
|
||||
{
|
||||
if (_undo == null) return false;
|
||||
rules.Clear();
|
||||
foreach (SortRule r in _undo) rules.Add(r.Clone());
|
||||
_undo = null;
|
||||
Show("Rules put back as they were.", false, nowMs);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The toast is past its time (or dismissed).</summary>
|
||||
public void Expire(long nowMs)
|
||||
{
|
||||
if (Toast != null && nowMs >= Toast.UntilMs) { Toast = null; Version++; }
|
||||
}
|
||||
}
|
||||
643
Plugins/RynthCore.Plugin.RynthSort/Screen/ScreenBuilder.cs
Normal file
643
Plugins/RynthCore.Plugin.RynthSort/Screen/ScreenBuilder.cs
Normal file
|
|
@ -0,0 +1,643 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthSort.Sorting;
|
||||
using RynthCore.Plugin.RynthSort.Views;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Screen;
|
||||
|
||||
/// <summary>What the builder needs besides the controller (the plugin fills it; the tests make one).</summary>
|
||||
internal sealed class ScreenInputs
|
||||
{
|
||||
public string Character = string.Empty;
|
||||
public string Server = string.Empty;
|
||||
/// <summary>The plugin's own warnings (the RynthSort Lua script set to start too).</summary>
|
||||
public IReadOnlyList<string> Warnings = Array.Empty<string>();
|
||||
public bool CanAddSelected;
|
||||
public bool CanSelect;
|
||||
/// <summary>The Layouts popup is open: fill <see cref="ScreenModel.Layouts"/>.</summary>
|
||||
public bool WantLayouts;
|
||||
public ScreenSession? Session;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the window's <see cref="ScreenModel"/> from the controller: the packs as last read, the
|
||||
/// rules, what a sort would move now (<see cref="SortPreview"/>, as Sort now would go), what is
|
||||
/// left alone, what settles, the feed. Pure (no host calls): the plugin calls it on its tick while
|
||||
/// the window shows and publishes the result; the tests call it on hand-made inventories.
|
||||
/// </summary>
|
||||
internal static class ScreenBuilder
|
||||
{
|
||||
/// <summary>The most Next moves and Left alone rows listed (the rest are counted).</summary>
|
||||
public const int MaxRows = 30;
|
||||
private static int _version;
|
||||
|
||||
public static ScreenModel Build(SortController c, ScreenInputs input)
|
||||
{
|
||||
if (input.Character.Length == 0) return ScreenModel.Empty;
|
||||
SortInventory? inv = c.LastInventory;
|
||||
string who = input.Server.Length > 0 ? input.Character + " · " + input.Server : input.Character;
|
||||
if (inv == null)
|
||||
return new ScreenModel { Who = who, NotReady = "Reading your packs...", Version = ++_version, Toast = input.Session?.Toast };
|
||||
|
||||
List<SortRule> rules = c.Data.Rules;
|
||||
SortSettings s = c.Data.Settings;
|
||||
bool clean = c.Job == SortScope.Clean;
|
||||
SortPreview p = SortPreview.Build(inv, rules, c.CurrentOptions, c.IsHeld, clean);
|
||||
SortView view = p.View; // the packs as numbered now (the preview planned on this read)
|
||||
SortView real = c.Planner.View; // the real planner's: what settles, what waits
|
||||
bool busy = c.Job != null || c.HasMoveOut || c.Status == "sorting" || c.Send != null;
|
||||
JobPlan? jobs = c.Jobs;
|
||||
|
||||
var m = new ScreenModel
|
||||
{
|
||||
Ready = true,
|
||||
Who = who,
|
||||
Auto = s.Auto,
|
||||
Busy = busy,
|
||||
PutBack = c.PutBackCount,
|
||||
NoRules = rules.Count == 0,
|
||||
CanAddSelected = input.CanAddSelected,
|
||||
CanSelect = input.CanSelect,
|
||||
Toast = input.Session?.Toast,
|
||||
Version = ++_version,
|
||||
};
|
||||
m.PutBackTip = $"Undo the last sort: the {SortPanel.Count(m.PutBack, "item")} it moved go back where they were. "
|
||||
+ "Turns auto-sort off first, so nothing moves again. Also: /rsort back";
|
||||
|
||||
var outgoing = new HashSet<uint>();
|
||||
foreach (SortMove mv in p.Moves) outgoing.Add(mv.Item.Id);
|
||||
uint flying = c.InFlightItem;
|
||||
|
||||
TileModel Tile(SortItem it, int where)
|
||||
{
|
||||
var t = new TileModel
|
||||
{
|
||||
Id = it.Id,
|
||||
Name = it.Name.Length > 0 ? it.Name : "(not known yet)",
|
||||
Stack = Math.Max(1, it.Stack),
|
||||
Qty = Kinds.Qty(it.Stack),
|
||||
Cls = it.ObjectClass,
|
||||
KindColor = Kinds.Color(it.ObjectClass),
|
||||
KindLabel = Kinds.Label(it.ObjectClass),
|
||||
Initials = Kinds.Initials(it.Name),
|
||||
Where = where,
|
||||
Outgoing = outgoing.Contains(it.Id),
|
||||
Settling = real.Settling.Contains(it.Id),
|
||||
};
|
||||
t.Moving = it.Id == flying || (busy && t.Outgoing);
|
||||
SortRule? r = SortRules.RuleFor(rules, it);
|
||||
if (r != null)
|
||||
{
|
||||
int to = SortPanel.ShownPack(view, r);
|
||||
t.Rule = to > 0 ? TileRule.Pack : TileRule.Missing;
|
||||
t.RulePack = to;
|
||||
t.ByName = SortRules.MatchesName(r, it);
|
||||
t.RuleText = t.ByName ? Kinds.NameChip(MatchedName(r, it)) : Kinds.Label(it.ObjectClass);
|
||||
}
|
||||
if (jobs != null && !t.ByName)
|
||||
{
|
||||
// A pack whose job picks it comes before a kind rule (a name rule beats both).
|
||||
foreach (int jp in jobs.PacksFor(it))
|
||||
{
|
||||
t.Rule = TileRule.Job;
|
||||
t.RulePack = jp;
|
||||
t.RuleText = PackJobs.Label(jobs.Packs[jp]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (c.Touch.TryGetHeld(it.Id, c.Clock, c.HoldMs, out long at, out TouchKind kind))
|
||||
{
|
||||
t.Held = true;
|
||||
t.HeldWhy = Capital(TouchWatch.Words(kind)) + " " + SortPanel.Ago(c.Clock - at);
|
||||
}
|
||||
m.TilesById[it.Id] = t;
|
||||
return t;
|
||||
}
|
||||
|
||||
// Main pack.
|
||||
int mainCap = SortPlanner.CapacityOf(inv.Main, SortPlanner.MainCapacityFallback);
|
||||
var mainTiles = new TileModel[inv.Main.Items.Count];
|
||||
for (int i = 0; i < mainTiles.Length; i++) mainTiles[i] = Tile(inv.Main.Items[i], 0);
|
||||
m.Main = new MainModel
|
||||
{
|
||||
Tiles = mainTiles,
|
||||
Used = mainTiles.Length,
|
||||
Capacity = mainCap,
|
||||
Count = $"{mainTiles.Length} / {mainCap}",
|
||||
Fill = mainCap > 0 ? Math.Clamp(mainTiles.Length / (float)mainCap, 0f, 1f) : 0f,
|
||||
NearlyFull = mainCap > 0 && mainTiles.Length > mainCap * 0.88f,
|
||||
Full = mainCap > 0 && mainTiles.Length >= mainCap,
|
||||
Wells = MainWells(mainTiles.Length, mainCap),
|
||||
Handy = s.HandyFront && c.Abilities.ReadOrder && c.Abilities.PlaceMoves
|
||||
? "Handy at the front: " + HandyItems.Describe(s.HandyClasses, s.HandyNames) + "."
|
||||
: string.Empty,
|
||||
Collapsed = s.MainCollapsed,
|
||||
};
|
||||
|
||||
// Side packs.
|
||||
int packs = inv.Packs.Count;
|
||||
m.Packs = new PackModel[packs];
|
||||
m.PacksNote = packs == 0 ? "none carried" : packs + " carried";
|
||||
var chips = ChipsByPack(rules, view, packs, out List<ChipModel> orphans);
|
||||
m.Orphans = orphans.ToArray();
|
||||
for (int i = 0; i < packs; i++)
|
||||
{
|
||||
SortPack sp = inv.Packs[i];
|
||||
int n = i + 1;
|
||||
int cap = SortPlanner.CapacityOf(sp, SortPlanner.SideCapacityFallback);
|
||||
var tiles = new TileModel[sp.Items.Count];
|
||||
for (int k = 0; k < tiles.Length; k++) tiles[k] = Tile(sp.Items[k], n);
|
||||
var ghosts = new List<GhostModel>();
|
||||
foreach (SortMove mv in p.Moves)
|
||||
if (mv.DestIndex == n) ghosts.Add(new GhostModel { ItemId = mv.Item.Id, Tip = $"{ItemName(mv.Item)} is coming here" });
|
||||
var warnings = new List<string>();
|
||||
int waiting = 0;
|
||||
foreach (NoFitLine l in view.NoFit) if (l.Pack == n) waiting++;
|
||||
if (waiting > 0) warnings.Add($"Full: {SortPanel.Count(waiting, "item")} for it {(waiting == 1 ? "waits" : "wait")} where {(waiting == 1 ? "it is" : "they are")}.");
|
||||
else if (view.Full.Contains(n) || real.Full.Contains(n)) warnings.Add("Full: the next pack with the same rule takes the rest.");
|
||||
warnings.AddRange(SortPanel.FallbackWarnings(view, n));
|
||||
float fill = cap > 0 ? Math.Clamp(tiles.Length / (float)cap, 0f, 1f) : 0f;
|
||||
m.Packs[i] = new PackModel
|
||||
{
|
||||
Number = n,
|
||||
Id = sp.Id,
|
||||
Name = sp.Name.Length > 0 ? sp.Name : "Pack " + n,
|
||||
Label = PackNames.Label(inv, n),
|
||||
Badge = n.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
Where = WhereWords(view, n, packs),
|
||||
Used = tiles.Length,
|
||||
Capacity = cap,
|
||||
Count = $"{tiles.Length}/{cap}",
|
||||
Fill = fill,
|
||||
NearlyFull = fill > 0.85f,
|
||||
Full = cap > 0 && tiles.Length >= cap,
|
||||
Incoming = ghosts.Count > 0 ? $"+{ghosts.Count} coming" : string.Empty,
|
||||
Tiles = tiles,
|
||||
Ghosts = ghosts.ToArray(),
|
||||
Chips = chips[n].ToArray(),
|
||||
Warnings = warnings.ToArray(),
|
||||
Tip = SortPanel.PackHeaderTooltip(view, n),
|
||||
Collapsed = s.CollapsedPacks.Contains(sp.Id),
|
||||
};
|
||||
JobOnCard(m.Packs[i], c, inv, n);
|
||||
}
|
||||
|
||||
// The plan column.
|
||||
m.MovesCount = p.Moves.Count;
|
||||
var moves = new List<RowModel>(Math.Min(p.Moves.Count, MaxRows));
|
||||
for (int i = 0; i < p.Moves.Count && i < MaxRows; i++)
|
||||
{
|
||||
SortMove mv = p.Moves[i];
|
||||
SortRule? r = SortRules.RuleFor(rules, mv.Item);
|
||||
int jobAt = JobPackFor(jobs, mv.Item, r);
|
||||
string ruleText = jobAt > 0 ? "Job: " + PackJobs.Label(jobs!.Packs[jobAt])
|
||||
: r == null ? "No rule: back to the main pack"
|
||||
: "Rule: " + (SortRules.MatchesName(r, mv.Item) ? Kinds.NameChip(MatchedName(r, mv.Item)) : Kinds.Label(mv.Item.ObjectClass));
|
||||
string to = mv.DestIndex == 0 ? "main pack" : m.PackName(mv.DestIndex);
|
||||
moves.Add(new RowModel
|
||||
{
|
||||
ItemId = mv.Item.Id,
|
||||
KindColor = Kinds.Color(mv.Item.ObjectClass),
|
||||
Name = ItemName(mv.Item),
|
||||
Sub = ruleText,
|
||||
Right = to,
|
||||
Tip = $"{ItemName(mv.Item)} goes from the {m.PackName(Math.Max(mv.FromIndex, 0))} to the {to}.",
|
||||
});
|
||||
}
|
||||
m.Moves = moves.ToArray();
|
||||
if (p.Moves.Count > 0 && !s.Auto && c.Job == null)
|
||||
m.MovesHint = "Nothing moves until you press Sort now or turn on Auto-sort.";
|
||||
if (p.ToOrder > 0 && !view.Ordering && view.Handy)
|
||||
m.OrderHint = p.Moves.Count > 0
|
||||
? "Then handy items go to the front of the main pack."
|
||||
: $"{SortPanel.Count(p.ToOrder, "handy item")} still to go to the front of the main pack.";
|
||||
else if (p.ToOrder > 0)
|
||||
m.OrderHint = p.Moves.Count > 0
|
||||
? "Then stacks are joined and items put in order inside each pack."
|
||||
: $"{SortPanel.Count(p.ToOrder, "item")} still to put in order inside packs.";
|
||||
|
||||
var held = new List<RowModel>();
|
||||
for (int i = 0; i < view.Held.Count && i < MaxRows; i++)
|
||||
{
|
||||
HeldLine h = view.Held[i];
|
||||
m.TilesById.TryGetValue(h.Item.Id, out TileModel? t);
|
||||
string why = t != null && t.HeldWhy.Length > 0 ? t.HeldWhy : "You used it";
|
||||
string to = h.To != h.From ? " · would go to " + (h.To == 0 ? "the main pack" : m.PackName(h.To)) : string.Empty;
|
||||
held.Add(new RowModel
|
||||
{
|
||||
ItemId = h.Item.Id,
|
||||
KindColor = Kinds.Color(h.Item.ObjectClass),
|
||||
Name = ItemName(h.Item),
|
||||
Sub = why + to,
|
||||
Tip = "Left alone: a sort doesn't move it until the time is up. Sort it lets RynthSort move it now.",
|
||||
});
|
||||
}
|
||||
m.Held = held.ToArray();
|
||||
m.HoldNote = s.HoldMin > 0 ? s.HoldMin + " min" : "off";
|
||||
|
||||
var feed = new RowModel[c.Feed.Count];
|
||||
for (int i = 0; i < feed.Length; i++)
|
||||
{
|
||||
FeedLine f = c.Feed[i];
|
||||
m.TilesById.TryGetValue(f.ItemId, out TileModel? t);
|
||||
feed[i] = new RowModel { ItemId = f.ItemId, KindColor = t?.KindColor ?? 0, Name = f.Text, Right = f.Time };
|
||||
}
|
||||
m.Feed = feed;
|
||||
|
||||
m.KindChoices = KindChoices(rules, view);
|
||||
m.Status = Status(c, real, p, rules.Count == 0, view.Held.Count, busy);
|
||||
m.Warnings = Warnings(c, real, view, input.Warnings);
|
||||
m.NoFit = NoFitLines(view, inv);
|
||||
m.Settings = new SettingsModel
|
||||
{
|
||||
SettleSec = s.SettleSec,
|
||||
HoldMin = s.HoldMin,
|
||||
GapMs = s.GapMs,
|
||||
SortInCombat = s.SortInCombat,
|
||||
OrderInPacks = s.OrderInPacks,
|
||||
KindFirst = s.OrderKindFirst,
|
||||
CanOrder = c.Abilities.ReadOrder && c.Abilities.PlaceMoves,
|
||||
HandyOn = s.HandyFront,
|
||||
HandyChips = HandyChips(s),
|
||||
HandyChoices = HandyChoices(s),
|
||||
};
|
||||
if (input.WantLayouts) m.Layouts = Layouts(c, inv, rules);
|
||||
return m;
|
||||
}
|
||||
|
||||
/// <summary>The empty wells after <paramref name="used"/> main-pack tiles: at least three rows of six, and a row past the last item, never past the capacity.</summary>
|
||||
internal static int MainWells(int used, int capacity)
|
||||
{
|
||||
int shown = Math.Max(18, (used + 1 + 5) / 6 * 6);
|
||||
if (capacity > 0) shown = Math.Min(shown, Math.Max(capacity, used));
|
||||
return Math.Max(0, shown - used);
|
||||
}
|
||||
|
||||
/// <summary>"Top of your pack column", "Pack 2 from the top", "Bottom of your pack column".</summary>
|
||||
internal static string WhereWords(SortView view, int number, int packs)
|
||||
{
|
||||
if (!view.PackOrderKnown) return "Place in the pack column not known";
|
||||
if (packs == 1) return "Your only side pack";
|
||||
if (number == 1) return "Top of your pack column";
|
||||
if (number == packs) return "Bottom of your pack column";
|
||||
return $"Pack {number} from the top";
|
||||
}
|
||||
|
||||
/// <summary>The name part of <paramref name="r"/> that <paramref name="it"/>'s name contains (the first), or "".</summary>
|
||||
internal static string MatchedName(SortRule r, SortItem it)
|
||||
{
|
||||
foreach (string n in r.Names)
|
||||
if (n.Length > 0 && it.Name.Contains(n, StringComparison.OrdinalIgnoreCase)) return n;
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Each side pack's chips ([1..packs]): its rules' kinds (A-Z) then names (A-Z), rule by rule; rules for packs not carried in <paramref name="orphans"/>.</summary>
|
||||
internal static List<ChipModel>[] ChipsByPack(List<SortRule> rules, SortView view, int packs, out List<ChipModel> orphans)
|
||||
{
|
||||
var byPack = new List<ChipModel>[packs + 1];
|
||||
for (int i = 0; i <= packs; i++) byPack[i] = new List<ChipModel>();
|
||||
var ordered = new List<SortRule>(rules);
|
||||
ordered.Sort(SortRules.CompareForList);
|
||||
// The rule (that is on) each kind follows first; another rule with the same kind is an overflow pack's.
|
||||
var firstFor = new Dictionary<int, SortRule>();
|
||||
foreach (SortRule r in rules)
|
||||
if (r.On)
|
||||
foreach (int cls in r.Classes) firstFor.TryAdd(cls, r);
|
||||
foreach (SortRule r in ordered)
|
||||
{
|
||||
int n = SortPanel.ShownPack(view, r);
|
||||
if (n > packs) n = 0;
|
||||
List<ChipModel> list = byPack[n];
|
||||
foreach (int cls in SortRules.SortedClasses(r))
|
||||
{
|
||||
SortRule? first = firstFor.GetValueOrDefault(cls);
|
||||
int firstPack = first != null ? SortPanel.ShownPack(view, first) : 0;
|
||||
bool overflow = r.On && n > 0 && first != null && first != r && firstPack > 0 && firstPack != n;
|
||||
list.Add(new ChipModel
|
||||
{
|
||||
Pack = n, RuleUid = r.Uid, Cls = cls, Dot = Kinds.Color(cls), Off = !r.On, Overflow = overflow,
|
||||
Label = overflow ? Kinds.Label(cls) + " (overflow)" : Kinds.Label(cls),
|
||||
Tip = !r.On ? "This rule is turned off: click to turn it on. The x takes it out."
|
||||
: overflow ? $"{Kinds.Label(cls)} come here when {RuleEdits.PackName(view, firstPack)} is full. The x takes it out (Undo brings it back)."
|
||||
: n > 0 ? $"Every {Kinds.Label(cls).ToLowerInvariant()} item goes here. The x takes it out (Undo brings it back)."
|
||||
: $"{Kinds.Label(cls)}: its pack ({(r.PackNote.Length > 0 ? r.PackNote : "pack " + r.Pack)}) isn't carried, so these stay where they are.",
|
||||
});
|
||||
}
|
||||
foreach (string name in SortRules.SortedNames(r))
|
||||
list.Add(new ChipModel
|
||||
{
|
||||
Pack = n, RuleUid = r.Uid, IsName = true, Name = name, Label = Kinds.NameChip(name), Off = !r.On,
|
||||
Tip = !r.On ? "This rule is turned off: click to turn it on. The x takes it out."
|
||||
: n > 0 ? $"Items with \"{name}\" in their name go here, whatever their kind (a name beats a kind)."
|
||||
: $"\"{name}\": its pack ({(r.PackNote.Length > 0 ? r.PackNote : "pack " + r.Pack)}) isn't carried, so these stay where they are.",
|
||||
});
|
||||
}
|
||||
orphans = byPack[0];
|
||||
return byPack;
|
||||
}
|
||||
|
||||
/// <summary>Every kind the picker offers, and which pack has it now.</summary>
|
||||
internal static KindChoice[] KindChoices(List<SortRule> rules, SortView view)
|
||||
{
|
||||
var a = new KindChoice[ObjectClasses.Choices.Length];
|
||||
for (int i = 0; i < a.Length; i++)
|
||||
{
|
||||
int cls = ObjectClasses.Choices[i];
|
||||
int at = 0;
|
||||
foreach (SortRule r in rules)
|
||||
{
|
||||
if (!r.On || !r.HasClass(cls)) continue;
|
||||
int n = SortPanel.ShownPack(view, r);
|
||||
at = n > 0 ? n : -1;
|
||||
break;
|
||||
}
|
||||
a[i] = new KindChoice { Cls = cls, Label = Kinds.Label(cls), Dot = Kinds.Color(cls), InPack = at };
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
/// <summary>The job pack an item goes to (a name rule beats a job), or 0.</summary>
|
||||
internal static int JobPackFor(JobPlan? jobs, SortItem it, SortRule? r)
|
||||
{
|
||||
if (jobs == null || (r != null && SortRules.MatchesName(r, it))) return 0;
|
||||
foreach (int n in jobs.PacksFor(it)) return n;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>A side pack's job as its card says it: the pill, the line under the bar, and whether it works now.</summary>
|
||||
internal static void JobOnCard(PackModel pk, SortController c, SortInventory inv, int number)
|
||||
{
|
||||
PackJob? job = PackJobs.On(c.Data.Jobs, inv, number);
|
||||
if (job == null) return;
|
||||
pk.Job = job.Kind;
|
||||
pk.JobMule = job.Mule;
|
||||
pk.JobLabel = job.Kind == JobKind.Mule && job.Mule.Length > 0 ? "Mule: " + job.Mule : PackJobs.Label(job.Kind);
|
||||
JobAnswer? a = c.Jobs?.Answers.Of(job.Kind);
|
||||
if (a == null)
|
||||
{
|
||||
pk.JobLine = "Asking RynthAi which items belong here...";
|
||||
return;
|
||||
}
|
||||
if (!a.Known)
|
||||
{
|
||||
pk.JobLine = $"{PackJobs.Label(job.Kind)} can't work now: {a.Text}. What is in this pack stays put until it can.";
|
||||
pk.JobProblem = true;
|
||||
return;
|
||||
}
|
||||
string profile = a.Text.Length > 0 ? " (" + a.Text + ")" : string.Empty;
|
||||
pk.JobLine = job.Kind switch
|
||||
{
|
||||
JobKind.Salvage => $"Takes what RynthAi's loot profile{profile} marks Salvage.",
|
||||
JobKind.Sell => $"Takes what RynthAi's AutoVendor would sell{profile}.",
|
||||
_ => $"Takes what RynthAi's AutoTrade would give {(job.Mule.Length > 0 ? job.Mule : "a mule")}{profile}.",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The handy list as chips: its kinds (in the list's order), then its names.</summary>
|
||||
internal static ChipModel[] HandyChips(SortSettings s)
|
||||
{
|
||||
var list = new List<ChipModel>(s.HandyClasses.Count + s.HandyNames.Count);
|
||||
foreach (int cls in s.HandyClasses)
|
||||
list.Add(new ChipModel { Cls = cls, Label = Kinds.Label(cls), Dot = Kinds.Color(cls), Tip = $"{Kinds.Label(cls)} sit at the front of the main pack. The x takes the kind off the list." });
|
||||
foreach (string n in s.HandyNames)
|
||||
list.Add(new ChipModel { IsName = true, Name = n, Label = Kinds.NameChip(n), Tip = $"Items with \"{n}\" in their name sit at the front of the main pack, whatever their kind. The x takes it off the list." });
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>The kinds the handy list's picker offers: every kind the rule picker offers that isn't on the list.</summary>
|
||||
internal static KindChoice[] HandyChoices(SortSettings s)
|
||||
{
|
||||
var list = new List<KindChoice>();
|
||||
foreach (int cls in ObjectClasses.Choices)
|
||||
if (!s.HandyClasses.Contains(cls))
|
||||
list.Add(new KindChoice { Cls = cls, Label = Kinds.Label(cls), Dot = Kinds.Color(cls) });
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>The status line and its pill (the design's Off / Moving / Waiting / All tidy).</summary>
|
||||
internal static StatusModel Status(SortController c, SortView v, SortPreview? p, bool noRules, int held, bool busy)
|
||||
{
|
||||
int moves = p?.Moves.Count ?? 0;
|
||||
string line;
|
||||
string pill;
|
||||
PillTone tone;
|
||||
if (c.Paused)
|
||||
{
|
||||
(tone, pill) = (PillTone.Waiting, "Waiting");
|
||||
line = "Paused: " + SortPanel.PausedWords(c.Status["paused: ".Length..]) + ".";
|
||||
}
|
||||
else if (c.Job is SortScope job)
|
||||
{
|
||||
(tone, pill) = (PillTone.Moving, "Moving");
|
||||
line = job switch
|
||||
{
|
||||
SortScope.Unpack => "Emptying side packs...",
|
||||
SortScope.PutBack => "Putting items back...",
|
||||
SortScope.Clean => "Cleaning packs...",
|
||||
_ => "Moving items to their packs...",
|
||||
};
|
||||
}
|
||||
else if (c.Send != null || (c.HasMoveOut && !c.Data.Settings.Auto))
|
||||
{
|
||||
(tone, pill) = (PillTone.Moving, "Moving");
|
||||
line = "Moving the item you sent...";
|
||||
}
|
||||
else if (!c.Data.Settings.Auto)
|
||||
{
|
||||
(tone, pill) = (PillTone.Off, "Off");
|
||||
line = moves > 0 ? $"Nothing moves by itself. A sort would move {SortPanel.Count(moves, "item")}." : "Nothing moves by itself.";
|
||||
}
|
||||
else if (c.Status == "sorting" || c.HasMoveOut)
|
||||
{
|
||||
(tone, pill) = (PillTone.Moving, "Moving");
|
||||
line = "Moving items to their packs...";
|
||||
}
|
||||
else if (c.Status is "starting" or "reading your packs" or "waiting for the inventory")
|
||||
{
|
||||
(tone, pill) = (PillTone.Waiting, "Reading");
|
||||
line = "Reading your packs...";
|
||||
}
|
||||
else if (v.WaitFull + v.WaitNoPack + v.WaitMainFull > 0)
|
||||
{
|
||||
(tone, pill) = (PillTone.Waiting, "Waiting");
|
||||
var why = new List<string>(3);
|
||||
if (v.WaitFull > 0) why.Add("a pack is full");
|
||||
if (v.WaitNoPack > 0) why.Add("a rule's pack isn't carried");
|
||||
if (v.WaitMainFull > 0) why.Add("the main pack is full");
|
||||
line = $"{SortPanel.Count(v.WaitFull + v.WaitNoPack + v.WaitMainFull, "item")} can't move: {string.Join(", ", why)}.";
|
||||
}
|
||||
else if (v.WaitSettle > 0)
|
||||
{
|
||||
(tone, pill) = (PillTone.Waiting, "Waiting");
|
||||
line = v.WaitSettle == 1
|
||||
? "1 new item settling, then it goes to its pack."
|
||||
: $"{v.WaitSettle} new items settling, then they go to their packs.";
|
||||
}
|
||||
else if (noRules)
|
||||
{
|
||||
(tone, pill) = (PillTone.Waiting, "No rules");
|
||||
line = "No rules yet: pick a layout, or add a kind to a pack.";
|
||||
}
|
||||
else if (moves > 0)
|
||||
{
|
||||
(tone, pill) = (PillTone.Waiting, "On");
|
||||
line = $"{moves} to move.";
|
||||
}
|
||||
else
|
||||
{
|
||||
(tone, pill) = (PillTone.Tidy, "All tidy");
|
||||
line = $"New loot goes to its pack {c.Data.Settings.SettleSec} s after it lands.";
|
||||
}
|
||||
if (held > 0 && !busy) line += $" {held} left alone.";
|
||||
return new StatusModel
|
||||
{
|
||||
Line = line,
|
||||
Pill = pill,
|
||||
Tone = tone,
|
||||
Tip = line + "\n\n" + SortPanel.AutoTooltip,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The red banner: per full pack, what didn't fit ("Satchel is full: Black Opal and Fire Opal stay where they are.").</summary>
|
||||
internal static string[] NoFitLines(SortView view, SortInventory inv)
|
||||
{
|
||||
var packs = new List<int>();
|
||||
foreach (NoFitLine l in view.NoFit) if (!packs.Contains(l.Pack)) packs.Add(l.Pack);
|
||||
var lines = new string[packs.Count];
|
||||
for (int i = 0; i < packs.Count; i++)
|
||||
lines[i] = SortController.NoFitText(view.NoFit.FindAll(l => l.Pack == packs[i]), inv);
|
||||
return lines;
|
||||
}
|
||||
|
||||
/// <summary>The amber lines under the header.</summary>
|
||||
internal static string[] Warnings(SortController c, SortView real, SortView view, IReadOnlyList<string> own)
|
||||
{
|
||||
var list = new List<string>();
|
||||
foreach (string w in own) list.Add(w);
|
||||
if (real.MainFull) list.Add("The main pack is full.");
|
||||
if (c.Data.Settings.Auto && c.LastBot is RynthAiActivity bot && (bot & RynthAiActivity.AutoCram) != 0 && (bot & RynthAiActivity.MacroRunning) != 0)
|
||||
list.Add("RynthAi's AutoCram also moves loot out of the main pack; turn one of them off.");
|
||||
string numbering = SortPanel.NumberingNote(view);
|
||||
if (numbering.Length > 0) list.Add(numbering);
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>The starter layouts fitted to these packs, with what each would move.</summary>
|
||||
internal static LayoutCard[] Layouts(SortController c, SortInventory inv, List<SortRule> rules)
|
||||
{
|
||||
if (inv.Packs.Count == 0) return Array.Empty<LayoutCard>();
|
||||
// The kinds carried (any pack), in the order met: what a layout leaves in the main pack.
|
||||
var carried = new List<int>();
|
||||
void See(SortItem it)
|
||||
{
|
||||
if (SortPlanner.Sortable(it) && !carried.Contains(it.ObjectClass)) carried.Add(it.ObjectClass);
|
||||
}
|
||||
foreach (SortItem it in inv.Main.Items) See(it);
|
||||
foreach (SortPack sp in inv.Packs) foreach (SortItem it in sp.Items) See(it);
|
||||
|
||||
var cards = new LayoutCard[StarterLayouts.All.Length];
|
||||
for (int k = 0; k < cards.Length; k++)
|
||||
{
|
||||
StarterLayout l = StarterLayouts.All[k];
|
||||
LayoutPlan plan = StarterLayouts.Fit(l, inv);
|
||||
SortPreview pv = SortPreview.Build(inv, plan.Rules, c.CurrentOptions, c.IsHeld);
|
||||
var bars = new uint[inv.Packs.Count][];
|
||||
var rows = new LayoutRow[inv.Packs.Count];
|
||||
var used = new HashSet<int>();
|
||||
for (int n = 1; n <= inv.Packs.Count; n++)
|
||||
{
|
||||
StarterGroup? g = null;
|
||||
foreach (var (group, pack) in plan.Placed) if (pack == n) { g = group; break; }
|
||||
int[] classes = g?.Classes ?? Array.Empty<int>();
|
||||
bars[n - 1] = new uint[classes.Length];
|
||||
var chips = new ChipModel[classes.Length];
|
||||
for (int j = 0; j < classes.Length; j++)
|
||||
{
|
||||
used.Add(classes[j]);
|
||||
bars[n - 1][j] = Kinds.Color(classes[j]);
|
||||
chips[j] = new ChipModel { Pack = n, Cls = classes[j], Label = Kinds.Label(classes[j]), Dot = Kinds.Color(classes[j]) };
|
||||
}
|
||||
SortPack sp = inv.Packs[n - 1];
|
||||
rows[n - 1] = new LayoutRow
|
||||
{
|
||||
Pack = n,
|
||||
Badge = n.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
PackName = sp.Name.Length > 0 ? sp.Name : "Pack " + n,
|
||||
Chips = chips,
|
||||
};
|
||||
}
|
||||
var left = new List<string>();
|
||||
foreach (int cls in carried)
|
||||
if (!used.Contains(cls))
|
||||
{
|
||||
string label = Kinds.Label(cls).ToLowerInvariant();
|
||||
if (!left.Contains(label)) left.Add(label);
|
||||
}
|
||||
cards[k] = new LayoutCard
|
||||
{
|
||||
Key = l.Key,
|
||||
Name = l.Name,
|
||||
Blurb = l.Blurb,
|
||||
Bars = bars,
|
||||
Meta = pv.Moves.Count > 0 ? $"{pv.Moves.Count} would move" : "nothing to move",
|
||||
Rows = rows,
|
||||
Left = left.Count > 0 ? "Stay in the main pack: " + string.Join(", ", left) + "." : "Every kind you carry has a pack.",
|
||||
Replaces = rules.Count > 0 ? " This replaces your rules; Undo brings them back." : string.Empty,
|
||||
};
|
||||
}
|
||||
return cards;
|
||||
}
|
||||
|
||||
private static string ItemName(SortItem it) => it.Name.Length > 0 ? it.Name : $"(item 0x{it.Id:X8})";
|
||||
|
||||
private static string Capital(string s) => s.Length > 0 ? char.ToUpperInvariant(s[0]) + s[1..] : s;
|
||||
}
|
||||
|
||||
/// <summary>The words the detail popup builds when it opens (pure, so the tests read them).</summary>
|
||||
internal static class ScreenText
|
||||
{
|
||||
/// <summary>One run of the "why" line: its text, and whether it is bold.</summary>
|
||||
internal readonly record struct Run(string Text, bool Bold);
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="t"/> is where it is: in its pack by which rule, goes to X by rule Y, or
|
||||
/// no rule names it so it stays in the main pack.
|
||||
/// </summary>
|
||||
public static Run[] Why(TileModel t, ScreenModel m)
|
||||
{
|
||||
switch (t.Rule)
|
||||
{
|
||||
case TileRule.Pack when t.RulePack == t.Where:
|
||||
return new[] { new Run("In its pack: ", false), new Run(m.PackName(t.RulePack), true), new Run(", by the rule ", false), new Run(t.RuleText, true), new Run(".", false) };
|
||||
case TileRule.Pack:
|
||||
return new[]
|
||||
{
|
||||
new Run("Goes to ", false), new Run(m.PackName(t.RulePack), true), new Run(" by the rule ", false), new Run(t.RuleText, true),
|
||||
new Run(t.Held ? ", once it's no longer left alone." : ".", false),
|
||||
};
|
||||
case TileRule.Job when t.RulePack == t.Where:
|
||||
return new[] { new Run("In its pack: ", false), new Run(m.PackName(t.RulePack), true), new Run(", by its job ", false), new Run(t.RuleText, true), new Run(".", false) };
|
||||
case TileRule.Job:
|
||||
return new[]
|
||||
{
|
||||
new Run("Goes to ", false), new Run(m.PackName(t.RulePack), true), new Run(": its job is ", false), new Run(t.RuleText, true),
|
||||
new Run(t.Held ? ", once it's no longer left alone." : ", and RynthAi says this item is one.", false),
|
||||
};
|
||||
case TileRule.Missing:
|
||||
return new[] { new Run("Its rule ", false), new Run(t.RuleText, true), new Run(" names a pack you don't carry, so it stays where it is.", false) };
|
||||
default:
|
||||
return t.Where == 0
|
||||
? new[] { new Run("No rule names it, so it stays in the main pack.", false) }
|
||||
: new[] { new Run("No rule names it. It stays in ", false), new Run(m.PackName(t.Where), true), new Run("; Clean sends it back to the main pack.", false) };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Gems · in Satchel": the detail popup's line under the name.</summary>
|
||||
public static string KindAndPlace(TileModel t, ScreenModel m) =>
|
||||
t.KindLabel + " · in " + (t.Where == 0 ? "the main pack" : m.PackName(t.Where));
|
||||
|
||||
/// <summary>Whether <paramref name="t"/>'s name has <paramref name="query"/> in it (any case); an empty query matches nothing (no highlight).</summary>
|
||||
public static bool Matches(TileModel t, string query) =>
|
||||
query.Length > 0 && t.Name.Contains(query, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
316
Plugins/RynthCore.Plugin.RynthSort/Screen/ScreenModel.cs
Normal file
316
Plugins/RynthCore.Plugin.RynthSort/Screen/ScreenModel.cs
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Screen;
|
||||
|
||||
// What the RynthSort window shows (2026-11-26, the approved design for #rynth-issues "The bag sort
|
||||
// feature is lacking in UX"): built on the plugin tick by ScreenBuilder from the controller, the
|
||||
// last read of the packs and the rules, published whole, and drawn by Window/SortWindow on AC's
|
||||
// render thread. Never changed after it is published: the renderer only reads it. Every string the
|
||||
// renderer draws is made here (or once when a popup opens), not per frame.
|
||||
|
||||
/// <summary>The coloured pill beside the status line.</summary>
|
||||
internal enum PillTone : byte
|
||||
{
|
||||
/// <summary>Grey: auto-sort is off.</summary>
|
||||
Off,
|
||||
/// <summary>Blue: items are moving.</summary>
|
||||
Moving,
|
||||
/// <summary>Amber: something waits (settling, paused, stuck, no rules).</summary>
|
||||
Waiting,
|
||||
/// <summary>Teal: on and tidy.</summary>
|
||||
Tidy,
|
||||
}
|
||||
|
||||
internal sealed class StatusModel
|
||||
{
|
||||
public string Line = string.Empty;
|
||||
public string Pill = "Off";
|
||||
public PillTone Tone;
|
||||
/// <summary>The status line's tooltip (the whole line, and what the colours mean).</summary>
|
||||
public string Tip = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Where a tile's item belongs by the rules.</summary>
|
||||
internal enum TileRule : byte
|
||||
{
|
||||
/// <summary>No rule names it: it stays in the main pack.</summary>
|
||||
None,
|
||||
/// <summary>A rule sends it to a side pack the character carries (<see cref="TileModel.RulePack"/>).</summary>
|
||||
Pack,
|
||||
/// <summary>Its rule names a pack the character doesn't carry: it stays where it is.</summary>
|
||||
Missing,
|
||||
/// <summary>A side pack's job picks it (<see cref="TileModel.RulePack"/>, the job in <see cref="TileModel.RuleText"/>).</summary>
|
||||
Job,
|
||||
}
|
||||
|
||||
/// <summary>One item in a pack: its picture, count and what is happening to it.</summary>
|
||||
internal sealed class TileModel
|
||||
{
|
||||
public uint Id;
|
||||
public string Name = string.Empty;
|
||||
/// <summary>The count in the corner ("", "75", "2.4k").</summary>
|
||||
public string Qty = string.Empty;
|
||||
public int Stack = 1;
|
||||
public int Cls;
|
||||
/// <summary>The kind's colour (ARGB): the tile's background while its picture is being made.</summary>
|
||||
public uint KindColor;
|
||||
/// <summary>"Gems": the kind as a chip says it.</summary>
|
||||
public string KindLabel = string.Empty;
|
||||
/// <summary>"AO": the letters shown while its picture is being made.</summary>
|
||||
public string Initials = string.Empty;
|
||||
/// <summary>The pack it is in: 0 = main pack, n = side pack n.</summary>
|
||||
public int Where;
|
||||
public TileRule Rule;
|
||||
/// <summary>The side pack its rule sends it to (1-based) when <see cref="Rule"/> is Pack.</summary>
|
||||
public int RulePack;
|
||||
/// <summary>The rule entry it follows, as a chip says it ("Gems", <c>named "Opal"</c>), or "".</summary>
|
||||
public string RuleText = string.Empty;
|
||||
/// <summary>It follows a name rule (a name beats a kind).</summary>
|
||||
public bool ByName;
|
||||
/// <summary>Left alone: the player used it lately (or asked).</summary>
|
||||
public bool Held;
|
||||
/// <summary>Why it is left alone ("you selected it just now").</summary>
|
||||
public string HeldWhy = string.Empty;
|
||||
/// <summary>A sort would move it to another pack now (it is in the Next moves list).</summary>
|
||||
public bool Outgoing;
|
||||
/// <summary>It is being moved, or the sort running now is about to move it: the tile lifts and pulses.</summary>
|
||||
public bool Moving;
|
||||
/// <summary>New in the main pack and still inside the settle time: the spinner ring.</summary>
|
||||
public bool Settling;
|
||||
}
|
||||
|
||||
/// <summary>A slot an item a sort would bring will take (the dashed "incoming" ghost).</summary>
|
||||
internal sealed class GhostModel
|
||||
{
|
||||
public uint ItemId;
|
||||
/// <summary>"Black Opal is coming here".</summary>
|
||||
public string Tip = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>One entry of a pack's rules: a kind or a name, with its ×.</summary>
|
||||
internal sealed class ChipModel
|
||||
{
|
||||
/// <summary>The side pack it sends to (1-based); 0 for a rule whose pack isn't carried.</summary>
|
||||
public int Pack;
|
||||
/// <summary>The rule it belongs to (SortRule.Uid).</summary>
|
||||
public int RuleUid;
|
||||
public bool IsName;
|
||||
public int Cls;
|
||||
/// <summary>The name part (name chips).</summary>
|
||||
public string Name = string.Empty;
|
||||
/// <summary>"Gems", <c>named "Opal"</c>.</summary>
|
||||
public string Label = string.Empty;
|
||||
/// <summary>The kind's colour (ARGB) for the dot (kind chips).</summary>
|
||||
public uint Dot;
|
||||
/// <summary>The rule is turned off (shown faded; a click turns it on).</summary>
|
||||
public bool Off;
|
||||
/// <summary>An overflow pack's kind: another pack's rule has it first, and this pack takes them when that one is full.</summary>
|
||||
public bool Overflow;
|
||||
public string Tip = string.Empty;
|
||||
}
|
||||
|
||||
internal sealed class PackModel
|
||||
{
|
||||
/// <summary>1-based, top pack first when the pack column's order is known.</summary>
|
||||
public int Number;
|
||||
public uint Id;
|
||||
public string Name = string.Empty;
|
||||
/// <summary>What a sentence calls it: <see cref="Name"/>, with its number when another pack has the same name ("Satchel (2)").</summary>
|
||||
public string Label = string.Empty;
|
||||
/// <summary>The bag badge's number ("1").</summary>
|
||||
public string Badge = string.Empty;
|
||||
/// <summary>"Top of your pack column", "Pack 2 from the top".</summary>
|
||||
public string Where = string.Empty;
|
||||
/// <summary>"12/24".</summary>
|
||||
public string Count = string.Empty;
|
||||
public int Used;
|
||||
public int Capacity;
|
||||
public float Fill;
|
||||
/// <summary>Over 85 % full: the meter turns amber.</summary>
|
||||
public bool NearlyFull;
|
||||
/// <summary>Every slot taken (its real capacity): the meter turns red.</summary>
|
||||
public bool Full;
|
||||
/// <summary>"+3 coming", or "".</summary>
|
||||
public string Incoming = string.Empty;
|
||||
public TileModel[] Tiles = Array.Empty<TileModel>();
|
||||
public GhostModel[] Ghosts = Array.Empty<GhostModel>();
|
||||
public ChipModel[] Chips = Array.Empty<ChipModel>();
|
||||
/// <summary>Amber lines under the grid (full, a rule that uses this pack only because its own isn't carried).</summary>
|
||||
public string[] Warnings = Array.Empty<string>();
|
||||
/// <summary>The header's tooltip: which pack in the game this is.</summary>
|
||||
public string Tip = string.Empty;
|
||||
/// <summary>Its job (Salvage, Sell, Mule), None when it has none.</summary>
|
||||
public Sorting.JobKind Job;
|
||||
/// <summary>"Salvage", "Mule: Name": the pill on the card, "" with no job.</summary>
|
||||
public string JobLabel = string.Empty;
|
||||
public string JobMule = string.Empty;
|
||||
/// <summary>What the job takes, or why it can't work now (RynthAi not loaded, too old, no profile).</summary>
|
||||
public string JobLine = string.Empty;
|
||||
/// <summary><see cref="JobLine"/> says why it can't work (amber).</summary>
|
||||
public bool JobProblem;
|
||||
/// <summary>Folded down to its header and rules (0.6.1): no slot grid.</summary>
|
||||
public bool Collapsed;
|
||||
}
|
||||
|
||||
internal sealed class MainModel
|
||||
{
|
||||
/// <summary>"12 / 102".</summary>
|
||||
public string Count = string.Empty;
|
||||
public int Used;
|
||||
public int Capacity;
|
||||
public float Fill;
|
||||
public bool NearlyFull;
|
||||
/// <summary>Every slot taken: the meter turns red.</summary>
|
||||
public bool Full;
|
||||
public TileModel[] Tiles = Array.Empty<TileModel>();
|
||||
/// <summary>Empty wells after the tiles (at least three rows in all, a row past the last item).</summary>
|
||||
public int Wells;
|
||||
/// <summary>"Handy at the front: healing kits, mana stones and food." while that option works, else "".</summary>
|
||||
public string Handy = string.Empty;
|
||||
/// <summary>Folded down to its header (0.6.1): no slot grid.</summary>
|
||||
public bool Collapsed;
|
||||
}
|
||||
|
||||
/// <summary>A Next moves row, a Left alone row or a feed row: picture, name, a line under it, and what is on the right.</summary>
|
||||
internal sealed class RowModel
|
||||
{
|
||||
/// <summary>The item (its picture); 0 = none (a feed line about a sort).</summary>
|
||||
public uint ItemId;
|
||||
public uint KindColor;
|
||||
public string Name = string.Empty;
|
||||
public string Sub = string.Empty;
|
||||
/// <summary>"Satchel" (Next moves: where it goes), the time (the feed), or "".</summary>
|
||||
public string Right = string.Empty;
|
||||
public string Tip = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>A kind the "+ Add a kind..." picker offers.</summary>
|
||||
internal sealed class KindChoice
|
||||
{
|
||||
public int Cls;
|
||||
public string Label = string.Empty;
|
||||
public uint Dot;
|
||||
/// <summary>The side pack whose rules (that are on) have it now (1-based), 0 = none, -1 = a pack not carried.</summary>
|
||||
public int InPack;
|
||||
}
|
||||
|
||||
/// <summary>A starter layout as the Layouts popup shows it.</summary>
|
||||
internal sealed class LayoutCard
|
||||
{
|
||||
public string Key = string.Empty;
|
||||
public string Name = string.Empty;
|
||||
public string Blurb = string.Empty;
|
||||
/// <summary>Per side pack (as carried), the kind colours (ARGB) of the mini bar; an empty array = the pack stays free.</summary>
|
||||
public uint[][] Bars = Array.Empty<uint[]>();
|
||||
/// <summary>"5 would move", "nothing to move".</summary>
|
||||
public string Meta = string.Empty;
|
||||
public LayoutRow[] Rows = Array.Empty<LayoutRow>();
|
||||
/// <summary>"Stay in the main pack: armor, trade notes." or "Every kind you carry has a pack."</summary>
|
||||
public string Left = string.Empty;
|
||||
/// <summary>" This replaces your rules; Undo brings them back." when the character has rules, else "".</summary>
|
||||
public string Replaces = string.Empty;
|
||||
}
|
||||
|
||||
internal sealed class LayoutRow
|
||||
{
|
||||
public int Pack;
|
||||
public string Badge = string.Empty;
|
||||
public string PackName = string.Empty;
|
||||
public ChipModel[] Chips = Array.Empty<ChipModel>();
|
||||
}
|
||||
|
||||
/// <summary>The settings popup's values (the renderer keeps its own copy while a slider is dragged).</summary>
|
||||
internal sealed class SettingsModel
|
||||
{
|
||||
public int SettleSec;
|
||||
public int HoldMin;
|
||||
public int GapMs;
|
||||
public bool SortInCombat;
|
||||
public bool OrderInPacks;
|
||||
public bool KindFirst;
|
||||
/// <summary>The engine can read the order inside packs (API v80).</summary>
|
||||
public bool CanOrder;
|
||||
/// <summary>"Keep handy items at the front of the main pack" is on.</summary>
|
||||
public bool HandyOn;
|
||||
/// <summary>The kinds and names that count as handy, as chips (IsName for a name part), with their ×.</summary>
|
||||
public ChipModel[] HandyChips = Array.Empty<ChipModel>();
|
||||
/// <summary>The kinds the handy list's picker offers (the ones not in it yet).</summary>
|
||||
public KindChoice[] HandyChoices = Array.Empty<KindChoice>();
|
||||
}
|
||||
|
||||
/// <summary>The line at the bottom after a change: what happened, and Undo when it can be undone.</summary>
|
||||
internal sealed class ToastModel
|
||||
{
|
||||
public string Text = string.Empty;
|
||||
public bool CanUndo;
|
||||
/// <summary>Changes with every new toast (the renderer restarts its fade).</summary>
|
||||
public int Seq;
|
||||
/// <summary>Shown until (the tick's clock, ms).</summary>
|
||||
public long UntilMs;
|
||||
}
|
||||
|
||||
internal sealed class ScreenModel
|
||||
{
|
||||
/// <summary>Logged in and the packs read: everything below is filled.</summary>
|
||||
public bool Ready;
|
||||
/// <summary>What to say instead ("Log in to sort your packs.").</summary>
|
||||
public string NotReady = string.Empty;
|
||||
/// <summary>"Character · Server".</summary>
|
||||
public string Who = string.Empty;
|
||||
public StatusModel Status = new();
|
||||
public bool Auto;
|
||||
/// <summary>A sort, Put back or Empty is running (Sort now is greyed).</summary>
|
||||
public bool Busy;
|
||||
/// <summary>How many items Put back would move back (0: no button).</summary>
|
||||
public int PutBack;
|
||||
public string PutBackTip = string.Empty;
|
||||
/// <summary>Amber lines under the header (the Lua script set to start too, AutoCram, numbering, main pack full).</summary>
|
||||
public string[] Warnings = Array.Empty<string>();
|
||||
/// <summary>The red banner: per full pack, the items that didn't fit (they stay where they are).</summary>
|
||||
public string[] NoFit = Array.Empty<string>();
|
||||
public MainModel Main = new();
|
||||
public PackModel[] Packs = Array.Empty<PackModel>();
|
||||
/// <summary>"4 carried".</summary>
|
||||
public string PacksNote = string.Empty;
|
||||
public RowModel[] Moves = Array.Empty<RowModel>();
|
||||
public int MovesCount;
|
||||
/// <summary>"Nothing moves until you press Sort now or turn on Auto-sort.", or "".</summary>
|
||||
public string MovesHint = string.Empty;
|
||||
/// <summary>"Then stacks are joined and 3 items put in order inside packs.", or "".</summary>
|
||||
public string OrderHint = string.Empty;
|
||||
public RowModel[] Held = Array.Empty<RowModel>();
|
||||
/// <summary>"3 min" (the Left alone eyebrow), "off".</summary>
|
||||
public string HoldNote = string.Empty;
|
||||
public RowModel[] Feed = Array.Empty<RowModel>();
|
||||
/// <summary>Rules whose pack isn't carried (their entries as chips, × removes).</summary>
|
||||
public ChipModel[] Orphans = Array.Empty<ChipModel>();
|
||||
public KindChoice[] KindChoices = Array.Empty<KindChoice>();
|
||||
/// <summary>The starter layouts, filled only while the Layouts popup is open.</summary>
|
||||
public LayoutCard[] Layouts = Array.Empty<LayoutCard>();
|
||||
public SettingsModel Settings = new();
|
||||
public ToastModel? Toast;
|
||||
/// <summary>The game's selection can be read (the picker's "The item selected in the game").</summary>
|
||||
public bool CanAddSelected;
|
||||
/// <summary>Items can be selected in the game (the bag badge selects its pack).</summary>
|
||||
public bool CanSelect;
|
||||
/// <summary>The character has no rules yet (the window suggests a layout).</summary>
|
||||
public bool NoRules;
|
||||
/// <summary>Every tile by item id (the detail and drop popups look items up here).</summary>
|
||||
public Dictionary<uint, TileModel> TilesById = new();
|
||||
/// <summary>Changes with every build.</summary>
|
||||
public int Version;
|
||||
|
||||
public static readonly ScreenModel Empty = new() { NotReady = "Log in to sort your packs." };
|
||||
|
||||
/// <summary>The side pack numbered <paramref name="number"/> (1-based), or null.</summary>
|
||||
public PackModel? Pack(int number) => number >= 1 && number <= Packs.Length ? Packs[number - 1] : null;
|
||||
|
||||
/// <summary>"main pack" for 0, else the side pack's name ("Satchel", "Satchel (2)" when two share it), or "pack 5" past the packs carried.</summary>
|
||||
public string PackName(int index)
|
||||
{
|
||||
if (index == 0) return "main pack";
|
||||
PackModel? p = Pack(index);
|
||||
return p != null ? (p.Label.Length > 0 ? p.Label : p.Name) : "pack " + index;
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@ using RynthCore.Plugin.Shared;
|
|||
|
||||
namespace RynthCore.Plugin.RynthSort;
|
||||
|
||||
internal enum SortVerb { Window, On, Off, Now, Clean, Unpack, Status, Help, Unknown }
|
||||
internal enum SortVerb { Window, On, Off, Now, Clean, Unpack, Back, Add, Status, Help, Unknown }
|
||||
|
||||
/// <summary>
|
||||
/// A parsed "/rsort ..." and the lines it answers with (2026-10-28: every command answers,
|
||||
|
|
@ -26,6 +26,8 @@ internal readonly record struct SortCommand(SortVerb Verb, int? Pack = null, boo
|
|||
"now" or "tidy" => new(SortVerb.Now),
|
||||
"clean" => new(SortVerb.Clean),
|
||||
"unpack" => new(SortVerb.Unpack, words.Length > 1 && int.TryParse(words[1], out int p) && p > 0 ? p : null),
|
||||
"back" or "undo" => new(SortVerb.Back),
|
||||
"add" => new(SortVerb.Add, words.Length > 1 && int.TryParse(words[1], out int a) && a > 0 ? a : null),
|
||||
"status" => new(SortVerb.Status),
|
||||
"help" or "?" => new(SortVerb.Help),
|
||||
_ => new(SortVerb.Unknown, Word: word),
|
||||
|
|
@ -35,10 +37,12 @@ internal readonly record struct SortCommand(SortVerb Verb, int? Pack = null, boo
|
|||
/// <summary>The window and help work before the character is known; everything else waits for it.</summary>
|
||||
public bool NeedsLogin => Verb is not (SortVerb.Window or SortVerb.Help);
|
||||
|
||||
public const string Usage = "/rsort [on | off | now | tidy | clean | unpack [pack] | status]";
|
||||
public const string Usage = "/rsort [on | off | now | tidy | clean | unpack [pack] | back | add <pack> | status]";
|
||||
|
||||
public const string AddUsage = "/rsort add <pack>: puts the item selected in the game into that pack's rules (pack numbers as the window shows them).";
|
||||
|
||||
public const string NoWindows =
|
||||
"This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Sorting still runs: /rsort on|off|now|tidy|clean|unpack.";
|
||||
"This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Sorting still runs: /rsort on|off|now|tidy|clean|unpack|back.";
|
||||
|
||||
public static string Window(bool shown) => CommandReply.Shown("RynthSort window", shown);
|
||||
|
||||
|
|
@ -50,5 +54,10 @@ internal readonly record struct SortCommand(SortVerb Verb, int? Pack = null, boo
|
|||
public static string Unpacking(int? pack) =>
|
||||
(pack != null ? $"Emptying pack {pack}" : "Emptying your side packs") + " into the main pack; auto-sort is off (/rsort on when done).";
|
||||
|
||||
/// <summary>"/rsort back": Put back starts, or there is nothing to put back.</summary>
|
||||
public static string PuttingBack(int count) => count > 0
|
||||
? $"Putting back the {count} item{(count == 1 ? "" : "s")} the last sort moved; auto-sort is off (/rsort on when done)."
|
||||
: "Nothing to put back: RynthSort hasn't moved anything to another pack lately.";
|
||||
|
||||
public static string Unknown(string word) => $"Unknown '/rsort {word}'. Usage: {Usage}";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,10 +11,16 @@ namespace RynthCore.Plugin.RynthSort;
|
|||
/// <summary>RynthSort's settings for one character (the Lua script's DEFAULTS, plus what the plugin adds).</summary>
|
||||
internal sealed class SortSettings
|
||||
{
|
||||
public const int SettleMin = 0, SettleMax = 30, GapMin = 100, GapMax = 3000;
|
||||
public const int SettleMin = 0, SettleMax = 30, GapMin = 100, GapMax = 3000, HoldMinMin = 0, HoldMinMax = 30;
|
||||
/// <summary>The hold a character gets until it changes it (minutes).</summary>
|
||||
public const int HoldMinDefault = 3;
|
||||
|
||||
/// <summary>Auto-sort: keeps every pack tidy (new items from the main pack after the settle time, misplaced items, stacks, order).</summary>
|
||||
public bool Auto = true;
|
||||
/// <summary>
|
||||
/// Auto-sort: keeps every pack tidy (new items from the main pack after the settle time, misplaced items, stacks, order).
|
||||
/// Off for a character RynthSort hasn't seen: players found items moving out from under them before they had
|
||||
/// set up any rules (#rynth-issues "The bag sort feature is lacking in UX"). A saved file keeps its own choice.
|
||||
/// </summary>
|
||||
public bool Auto;
|
||||
/// <summary>How long a new item sits in the main pack before it moves (seconds).</summary>
|
||||
public int SettleSec = 5;
|
||||
/// <summary>Auto-sort's pause between two moves (ms), to leave the bot room.</summary>
|
||||
|
|
@ -32,24 +38,72 @@ internal sealed class SortSettings
|
|||
/// script's rules, to show them.
|
||||
/// </summary>
|
||||
public bool WindowOpen;
|
||||
/// <summary>
|
||||
/// "Leave items I use alone": an item the player moved, selected, dragged, took off or picked up
|
||||
/// isn't sorted for this many minutes (0 = off). Files from before it have the default.
|
||||
/// </summary>
|
||||
public int HoldMin = HoldMinDefault;
|
||||
/// <summary>
|
||||
/// "Keep handy items at the front of the main pack" (0.6.0, <see cref="HandyItems"/>). Off for a
|
||||
/// file from before it and for a new character: it moves items in the main pack, so the player
|
||||
/// turns it on.
|
||||
/// </summary>
|
||||
public bool HandyFront;
|
||||
/// <summary>The kinds that count as handy (ObjectClass numbers), each once.</summary>
|
||||
public List<int> HandyClasses = new(HandyItems.DefaultClasses);
|
||||
/// <summary>Parts of names that count as handy whatever their kind ("Potion"), each once.</summary>
|
||||
public List<string> HandyNames = new(HandyItems.DefaultNames);
|
||||
/// <summary>
|
||||
/// Side packs folded down to their header and rules in the window (0.6.1, by the pack's object
|
||||
/// id, so it stays with the pack when packs are reordered), newest last, at most
|
||||
/// <see cref="MaxCollapsed"/>.
|
||||
/// </summary>
|
||||
public List<uint> CollapsedPacks = new();
|
||||
/// <summary>The main pack's card folded down to its header in the window.</summary>
|
||||
public bool MainCollapsed;
|
||||
public const int MaxCollapsed = 64;
|
||||
|
||||
/// <summary>Side pack <paramref name="id"/> folded or not; true when that changed something.</summary>
|
||||
public bool SetCollapsed(uint id, bool collapsed)
|
||||
{
|
||||
if (id == 0) return false;
|
||||
bool has = CollapsedPacks.Contains(id);
|
||||
if (has == collapsed) return false;
|
||||
if (collapsed)
|
||||
{
|
||||
if (CollapsedPacks.Count >= MaxCollapsed) CollapsedPacks.RemoveAt(0);
|
||||
CollapsedPacks.Add(id);
|
||||
}
|
||||
else CollapsedPacks.Remove(id);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Clamp()
|
||||
{
|
||||
SettleSec = Math.Clamp(SettleSec, SettleMin, SettleMax);
|
||||
GapMs = Math.Clamp(GapMs, GapMin, GapMax);
|
||||
HoldMin = Math.Clamp(HoldMin, HoldMinMin, HoldMinMax);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One character's rules and settings.</summary>
|
||||
internal sealed class CharacterSortData
|
||||
{
|
||||
public List<SortRule> Rules = SortRules.Defaults();
|
||||
/// <summary>
|
||||
/// None for a character RynthSort hasn't seen (2026-11-26): the window offers starter layouts
|
||||
/// fitted to the packs it carries instead of rules by pack number that may name the wrong packs
|
||||
/// (#rynth-issues "The bag sort feature is lacking in UX": "there is no common-sense default").
|
||||
/// A saved file, or the Lua script's, keeps its own rules.
|
||||
/// </summary>
|
||||
public List<SortRule> Rules = new();
|
||||
/// <summary>Side packs with a job (0.6.0: Salvage, Sell, Mule; <see cref="PackJobs"/>). None for a file from before them.</summary>
|
||||
public List<PackJob> Jobs = new();
|
||||
public SortSettings Settings = new();
|
||||
/// <summary>Where these came from on first run ("" = defaults, else the Lua script's file).</summary>
|
||||
/// <summary>Where these came from on first run ("" = RynthSort's own, or none yet; else the Lua script's file).</summary>
|
||||
public string ImportedFrom = string.Empty;
|
||||
/// <summary>
|
||||
/// The rules are tied to pack ids (<see cref="PackFix"/> ran once). False for files saved
|
||||
/// before pack ids, a new character's defaults and a fresh import from the Lua script.
|
||||
/// before pack ids and a fresh import from the Lua script.
|
||||
/// </summary>
|
||||
public bool PacksFixed;
|
||||
/// <summary>
|
||||
|
|
@ -99,7 +153,7 @@ internal sealed class SortStore
|
|||
/// <summary>
|
||||
/// The character's rules and settings: RynthSort's own file; else the Lua script's (imported:
|
||||
/// <see cref="CharacterSortData.ImportedFrom"/> says so, and the caller saves it as RynthSort's);
|
||||
/// else the defaults. A broken file reads as the defaults (the next save rewrites it).
|
||||
/// else no rules (the window offers starter layouts). A broken file reads as no rules (the plugin keeps a .bak of it at the next save).
|
||||
/// </summary>
|
||||
public CharacterSortData Load(string server, string character, out string? problem)
|
||||
{
|
||||
|
|
@ -179,8 +233,42 @@ internal sealed class SortStore
|
|||
st.OrderInPacks = Bool(s, "orderInPacks", st.OrderInPacks);
|
||||
st.OrderKindFirst = Bool(s, "orderKindFirst", st.OrderKindFirst);
|
||||
st.WindowOpen = Bool(s, "windowOpen", st.WindowOpen);
|
||||
st.HoldMin = Int(s, "holdMin", st.HoldMin);
|
||||
st.HandyFront = Bool(s, "handyFront", false);
|
||||
st.MainCollapsed = Bool(s, "mainCollapsed", false);
|
||||
if (s.TryGetProperty("collapsed", out JsonElement cp) && cp.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement c in cp.EnumerateArray())
|
||||
if (c.ValueKind == JsonValueKind.Number && c.TryGetUInt32(out uint id)) st.SetCollapsed(id, true);
|
||||
if (s.TryGetProperty("handyClasses", out JsonElement hc) && hc.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
st.HandyClasses.Clear();
|
||||
foreach (JsonElement c in hc.EnumerateArray())
|
||||
if (c.ValueKind == JsonValueKind.Number && c.TryGetDouble(out double v) && v >= 0 && v <= 1000) HandyItems.AddClass(st, (int)Math.Round(v));
|
||||
}
|
||||
if (s.TryGetProperty("handyNames", out JsonElement hn) && hn.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
st.HandyNames.Clear();
|
||||
foreach (JsonElement n in hn.EnumerateArray())
|
||||
if (n.ValueKind == JsonValueKind.String) HandyItems.AddName(st, n.GetString());
|
||||
}
|
||||
st.Clamp();
|
||||
}
|
||||
if (root.TryGetProperty("jobs", out JsonElement jobs) && jobs.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (JsonElement e in jobs.EnumerateArray())
|
||||
{
|
||||
if (e.ValueKind != JsonValueKind.Object || d.Jobs.Count >= MaxPack) continue;
|
||||
JobKind kind = PackJobs.Parse(e.TryGetProperty("job", out JsonElement jk) && jk.ValueKind == JsonValueKind.String ? jk.GetString() : null);
|
||||
if (kind == JobKind.None) continue;
|
||||
d.Jobs.Add(new PackJob
|
||||
{
|
||||
Kind = kind,
|
||||
PackId = UInt(e, "packId"),
|
||||
Pack = Math.Clamp(Int(e, "pack", 1), 1, MaxPack),
|
||||
Mule = kind == JobKind.Mule && e.TryGetProperty("mule", out JsonElement mu) && mu.ValueKind == JsonValueKind.String ? SortRule.Clean(mu.GetString()) : string.Empty,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (root.TryGetProperty("importedFrom", out JsonElement f) && f.ValueKind == JsonValueKind.String)
|
||||
d.ImportedFrom = f.GetString() ?? string.Empty;
|
||||
// Missing (a version 1 file, the Lua script's file): rules by number only, not fixed yet.
|
||||
|
|
@ -288,7 +376,38 @@ internal sealed class SortStore
|
|||
w.WriteBoolean("orderInPacks", d.Settings.OrderInPacks);
|
||||
w.WriteBoolean("orderKindFirst", d.Settings.OrderKindFirst);
|
||||
w.WriteBoolean("windowOpen", d.Settings.WindowOpen);
|
||||
// 2026-11-26: an older RynthSort reading this file skips it (it keeps no hold).
|
||||
w.WriteNumber("holdMin", d.Settings.HoldMin);
|
||||
// 0.6.0: handy items at the front of the main pack (an older RynthSort skips these).
|
||||
w.WriteBoolean("handyFront", d.Settings.HandyFront);
|
||||
w.WriteStartArray("handyClasses");
|
||||
foreach (int c in d.Settings.HandyClasses) w.WriteNumberValue(c);
|
||||
w.WriteEndArray();
|
||||
w.WriteStartArray("handyNames");
|
||||
foreach (string n in d.Settings.HandyNames) w.WriteStringValue(n);
|
||||
w.WriteEndArray();
|
||||
// 0.6.1: packs folded in the window (an older RynthSort skips these).
|
||||
w.WriteBoolean("mainCollapsed", d.Settings.MainCollapsed);
|
||||
w.WriteStartArray("collapsed");
|
||||
foreach (uint id in d.Settings.CollapsedPacks) w.WriteNumberValue(id);
|
||||
w.WriteEndArray();
|
||||
w.WriteEndObject();
|
||||
// 0.6.0: side packs with a job (an older RynthSort skips this).
|
||||
if (d.Jobs.Count > 0)
|
||||
{
|
||||
w.WriteStartArray("jobs");
|
||||
foreach (PackJob j in d.Jobs)
|
||||
{
|
||||
if (j.Kind == JobKind.None) continue;
|
||||
w.WriteStartObject();
|
||||
w.WriteString("job", PackJobs.Key(j.Kind));
|
||||
if (j.PackId != 0) w.WriteNumber("packId", j.PackId);
|
||||
w.WriteNumber("pack", j.Pack);
|
||||
if (j.Kind == JobKind.Mule && j.Mule.Length > 0) w.WriteString("mule", j.Mule);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
}
|
||||
if (d.ImportedFrom.Length > 0) w.WriteString("importedFrom", d.ImportedFrom);
|
||||
w.WriteBoolean("packsFixed", d.PacksFixed);
|
||||
w.WriteEndObject();
|
||||
|
|
|
|||
80
Plugins/RynthCore.Plugin.RynthSort/Sorting/HandyItems.cs
Normal file
80
Plugins/RynthCore.Plugin.RynthSort/Sorting/HandyItems.cs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
/// <summary>
|
||||
/// "Keep handy items at the front of the main pack": the things a player reaches for (healing
|
||||
/// kits, mana stones, food, potions and elixirs; the list is the player's to change) sit in the main
|
||||
/// pack's first slots. Only items that live in the main pack anyway: a kind a side pack's rule names
|
||||
/// still goes to that pack. It needs moves to a slot (plugin API v80). Items left alone (held) and
|
||||
/// items that can't move now are never moved for it: handy items go after them. Pure.
|
||||
/// </summary>
|
||||
internal static class HandyItems
|
||||
{
|
||||
public const int MaxClasses = 16, MaxNames = 12;
|
||||
|
||||
/// <summary>The kinds a character starts with.</summary>
|
||||
public static readonly int[] DefaultClasses = { ObjectClasses.HealingKit, ObjectClasses.ManaStone, ObjectClasses.Food };
|
||||
|
||||
/// <summary>
|
||||
/// Parts of names that count as handy whatever their kind: potions and elixirs (the client
|
||||
/// calls most of them Food already, but not every server's do).
|
||||
/// </summary>
|
||||
public static readonly string[] DefaultNames = { "Potion", "Elixir" };
|
||||
|
||||
/// <summary>Whether <paramref name="it"/> is handy by these kinds and names (a name part matches any case).</summary>
|
||||
public static bool Matches(IReadOnlyList<int> classes, IReadOnlyList<string> names, SortItem it)
|
||||
{
|
||||
for (int i = 0; i < classes.Count; i++)
|
||||
if (classes[i] == it.ObjectClass) return true;
|
||||
string name = it.Name ?? string.Empty;
|
||||
if (name.Length == 0) return false;
|
||||
for (int i = 0; i < names.Count; i++)
|
||||
if (names[i].Length > 0 && name.Contains(names[i], StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The planner's test for the settings now (a copy of the lists: later edits don't change a plan under way), or null when the option is off.</summary>
|
||||
public static Func<SortItem, bool>? For(SortSettings s)
|
||||
{
|
||||
if (!s.HandyFront || (s.HandyClasses.Count == 0 && s.HandyNames.Count == 0)) return null;
|
||||
int[] classes = s.HandyClasses.ToArray();
|
||||
string[] names = s.HandyNames.ToArray();
|
||||
return it => Matches(classes, names, it);
|
||||
}
|
||||
|
||||
/// <summary>"healing kits, mana stones, food, potions and elixirs": the list in a sentence (names as they are typed).</summary>
|
||||
public static string Describe(IReadOnlyList<int> classes, IReadOnlyList<string> names)
|
||||
{
|
||||
var parts = new List<string>(classes.Count + names.Count);
|
||||
foreach (int c in classes) parts.Add(ObjectClasses.Plural(c).ToLowerInvariant());
|
||||
foreach (string n in names) parts.Add(Plural(n).ToLowerInvariant());
|
||||
if (parts.Count == 0) return "nothing";
|
||||
if (parts.Count == 1) return parts[0];
|
||||
return string.Join(", ", parts.GetRange(0, parts.Count - 1)) + " and " + parts[^1];
|
||||
}
|
||||
|
||||
private static string Plural(string n) => n.EndsWith("s", StringComparison.OrdinalIgnoreCase) ? n : n + "s";
|
||||
|
||||
/// <summary>Adds a kind (false when it is there, the list is full, or it isn't one the picker offers).</summary>
|
||||
public static bool AddClass(SortSettings s, int cls)
|
||||
{
|
||||
if (ObjectClasses.ChoiceIndex(cls) < 0 || s.HandyClasses.Contains(cls) || s.HandyClasses.Count >= MaxClasses) return false;
|
||||
s.HandyClasses.Add(cls);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Adds a part of a name, trimmed (false when blank, there already, or the list is full).</summary>
|
||||
public static bool AddName(SortSettings s, string? text)
|
||||
{
|
||||
string t = SortRule.Clean(text);
|
||||
if (t.Length == 0 || s.HandyNames.Count >= MaxNames) return false;
|
||||
foreach (string n in s.HandyNames) if (string.Equals(n, t, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
s.HandyNames.Add(t);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool RemoveName(SortSettings s, string text) =>
|
||||
s.HandyNames.RemoveAll(n => string.Equals(n, text, StringComparison.OrdinalIgnoreCase)) > 0;
|
||||
}
|
||||
|
|
@ -72,7 +72,12 @@ internal sealed class InventoryReader
|
|||
bool capRead = isContainer && host.TryGetObjectIntProperty(id, IntItemsCapacity, out cap);
|
||||
// Every container entry, foci too and before the wielded check: the Lua script's count.
|
||||
if (isContainer) inv.Slots.Add(new SortSlot(id, capRead ? Math.Max(cap, 0) : -1));
|
||||
if (Wielded(host, id)) continue;
|
||||
if (Wielded(host, id))
|
||||
{
|
||||
// Kept so taking an item off reads as the player's doing (TouchWatch).
|
||||
inv.Worn.Add(id);
|
||||
continue;
|
||||
}
|
||||
if (isContainer)
|
||||
{
|
||||
// A side pack holds items; foci (containers that hold none) aren't packs or items.
|
||||
|
|
|
|||
190
Plugins/RynthCore.Plugin.RynthSort/Sorting/PackJobs.cs
Normal file
190
Plugins/RynthCore.Plugin.RynthSort/Sorting/PackJobs.cs
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthSort.Sorting;
|
||||
|
||||
/// <summary>What a side pack is for besides its rules (0.6.0): items another tool picks.</summary>
|
||||
internal enum JobKind : byte
|
||||
{
|
||||
None = 0,
|
||||
/// <summary>Items RynthAi's loot profile in use marks Salvage (its first matching rule).</summary>
|
||||
Salvage = 1,
|
||||
/// <summary>Items RynthAi's AutoVendor would sell (its default.utl and its safety checks).</summary>
|
||||
Sell = 2,
|
||||
/// <summary>Items set aside for a mule: what RynthAi's AutoTrade would give it (its <mule>.utl, else default.utl).</summary>
|
||||
Mule = 3,
|
||||
}
|
||||
|
||||
/// <summary>A side pack's job, kept by the pack's id (its number when the id isn't carried, as a rule).</summary>
|
||||
internal sealed class PackJob
|
||||
{
|
||||
public uint PackId;
|
||||
public int Pack = 1;
|
||||
public JobKind Kind;
|
||||
/// <summary>The mule's character name for <see cref="JobKind.Mule"/> ("" = AutoTrade's default.utl).</summary>
|
||||
public string Mule = string.Empty;
|
||||
|
||||
public PackJob Clone() => new() { PackId = PackId, Pack = Pack, Kind = Kind, Mule = Mule };
|
||||
}
|
||||
|
||||
/// <summary>What RynthAi answered for one job: whether there is an answer, and if not, why (the window says it).</summary>
|
||||
internal sealed class JobAnswer
|
||||
{
|
||||
/// <summary>RynthAi answered: <see cref="Marked"/> is the whole list of items it picks.</summary>
|
||||
public bool Known;
|
||||
/// <summary>The items it picks (object ids).</summary>
|
||||
public readonly HashSet<uint> Marked = new();
|
||||
/// <summary>Known: the profile it used ("Hunting.utl"); not known: why ("RynthAi isn't loaded").</summary>
|
||||
public string Text = string.Empty;
|
||||
|
||||
public static JobAnswer Unknown(string why) => new() { Text = why };
|
||||
}
|
||||
|
||||
/// <summary>RynthAi's answers for the jobs the carried packs have (the plugin asks; the tests make them).</summary>
|
||||
internal sealed class JobAnswers
|
||||
{
|
||||
public readonly Dictionary<JobKind, JobAnswer> ByKind = new();
|
||||
/// <summary>The mule a Mule pack asked about (one mule at a time: the first Mule pack's).</summary>
|
||||
public string Mule = string.Empty;
|
||||
|
||||
public JobAnswer? Of(JobKind kind) => ByKind.TryGetValue(kind, out JobAnswer? a) ? a : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pack jobs (0.6.0, #rynth-issues "The bag sort feature is lacking in UX" follow-up): a side pack can
|
||||
/// hold what another tool picks: Salvage (RynthAi's loot profile), Sell (RynthAi's AutoVendor), or a
|
||||
/// Mule (RynthAi's AutoTrade). Where an item goes: a name rule first (the player named it), then a
|
||||
/// job that picks it, then a kind rule. A job pack whose answer isn't known (RynthAi not loaded, too
|
||||
/// old, no profile) changes nothing: items in it stay, nothing new goes in. Pure.
|
||||
/// </summary>
|
||||
internal static class PackJobs
|
||||
{
|
||||
public static string Label(JobKind k) => k switch
|
||||
{
|
||||
JobKind.Salvage => "Salvage",
|
||||
JobKind.Sell => "Sell",
|
||||
JobKind.Mule => "Mule",
|
||||
_ => "No job",
|
||||
};
|
||||
|
||||
/// <summary>"salvage", "sell", "mule": how the file says it.</summary>
|
||||
public static string Key(JobKind k) => k switch
|
||||
{
|
||||
JobKind.Salvage => "salvage",
|
||||
JobKind.Sell => "sell",
|
||||
JobKind.Mule => "mule",
|
||||
_ => string.Empty,
|
||||
};
|
||||
|
||||
public static JobKind Parse(string? key) => (key ?? string.Empty).Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"salvage" => JobKind.Salvage,
|
||||
"sell" => JobKind.Sell,
|
||||
"mule" => JobKind.Mule,
|
||||
_ => JobKind.None,
|
||||
};
|
||||
|
||||
/// <summary>The side pack (1-based) job <paramref name="j"/> is on: its id when carried, else its number; 0 when neither.</summary>
|
||||
public static int Resolve(PackJob j, SortInventory inv)
|
||||
{
|
||||
int byId = inv.IndexOf(j.PackId);
|
||||
if (byId > 0) return byId;
|
||||
return j.PackId == 0 && j.Pack >= 1 && j.Pack <= inv.Packs.Count ? j.Pack : 0;
|
||||
}
|
||||
|
||||
/// <summary>Each carried side pack's job ([n] for pack n, None when it has none).</summary>
|
||||
public static JobKind[] ByPack(IReadOnlyList<PackJob> jobs, SortInventory inv)
|
||||
{
|
||||
var a = new JobKind[inv.Packs.Count + 1];
|
||||
foreach (PackJob j in jobs)
|
||||
{
|
||||
int n = Resolve(j, inv);
|
||||
if (n > 0 && j.Kind != JobKind.None && a[n] == JobKind.None) a[n] = j.Kind;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
/// <summary>The job on pack <paramref name="number"/>, or null.</summary>
|
||||
public static PackJob? On(IReadOnlyList<PackJob> jobs, SortInventory inv, int number)
|
||||
{
|
||||
foreach (PackJob j in jobs)
|
||||
if (j.Kind != JobKind.None && Resolve(j, inv) == number) return j;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets pack <paramref name="number"/>'s job (None takes it off). One job a pack; the pack is kept
|
||||
/// by its id. False when nothing changed or the pack isn't carried.
|
||||
/// </summary>
|
||||
public static bool Set(List<PackJob> jobs, SortInventory inv, int number, JobKind kind, string? mule)
|
||||
{
|
||||
if (number < 1 || number > inv.Packs.Count) return false;
|
||||
string m = SortRule.Clean(mule);
|
||||
PackJob? have = On(jobs, inv, number);
|
||||
if (kind == JobKind.None)
|
||||
{
|
||||
if (have == null) return false;
|
||||
jobs.RemoveAll(j => Resolve(j, inv) == number);
|
||||
return true;
|
||||
}
|
||||
if (have != null && have.Kind == kind && (kind != JobKind.Mule || string.Equals(have.Mule, m, StringComparison.Ordinal))) return false;
|
||||
jobs.RemoveAll(j => Resolve(j, inv) == number);
|
||||
jobs.Add(new PackJob { PackId = inv.Packs[number - 1].Id, Pack = number, Kind = kind, Mule = kind == JobKind.Mule ? m : string.Empty });
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The jobs the carried packs have, each once (what to ask RynthAi), and the first Mule pack's mule.</summary>
|
||||
public static List<JobKind> Wanted(IReadOnlyList<PackJob> jobs, SortInventory inv, out string mule)
|
||||
{
|
||||
mule = string.Empty;
|
||||
var list = new List<JobKind>();
|
||||
bool muleSet = false;
|
||||
foreach (PackJob j in jobs)
|
||||
{
|
||||
if (j.Kind == JobKind.None || Resolve(j, inv) == 0) continue;
|
||||
if (!list.Contains(j.Kind)) list.Add(j.Kind);
|
||||
if (j.Kind == JobKind.Mule && !muleSet) { mule = j.Mule; muleSet = true; }
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The jobs as the planner sees them for one pass: each carried pack's job and RynthAi's answers.</summary>
|
||||
internal sealed class JobPlan
|
||||
{
|
||||
/// <summary>[n] = side pack n's job.</summary>
|
||||
public JobKind[] Packs = Array.Empty<JobKind>();
|
||||
public JobAnswers Answers = new();
|
||||
|
||||
public bool Any
|
||||
{
|
||||
get
|
||||
{
|
||||
foreach (JobKind k in Packs) if (k != JobKind.None) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static JobPlan? For(IReadOnlyList<PackJob> jobs, SortInventory inv, JobAnswers? answers)
|
||||
{
|
||||
if (jobs.Count == 0) return null;
|
||||
var p = new JobPlan { Packs = PackJobs.ByPack(jobs, inv), Answers = answers ?? new JobAnswers() };
|
||||
return p.Any ? p : null;
|
||||
}
|
||||
|
||||
/// <summary>Pack <paramref name="index"/> has a job whose answer isn't known: what is in it stays.</summary>
|
||||
public bool Frozen(int index) =>
|
||||
index > 0 && index < Packs.Length && Packs[index] != JobKind.None && Answers.Of(Packs[index])?.Known != true;
|
||||
|
||||
/// <summary>The job packs (pack order) whose job picks <paramref name="it"/>, best first.</summary>
|
||||
public IEnumerable<int> PacksFor(SortItem it)
|
||||
{
|
||||
for (int n = 1; n < Packs.Length; n++)
|
||||
{
|
||||
JobKind k = Packs[n];
|
||||
if (k == JobKind.None) continue;
|
||||
JobAnswer? a = Answers.Of(k);
|
||||
if (a != null && a.Known && a.Marked.Contains(it.Id)) yield return n;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue