RynthSuite as of 2026-10-05 evening (internal a078b8e): release 2026.10.5.20 - healing delay fixes, stuck-cast safeguards, buffs over items, slayers recognised and chosen first, recover my corpse, /ub give and /mt give, Mana Tap skips wands, dungeon floor-plan bake, heal latency log
This commit is contained in:
parent
53438c65c1
commit
6847868401
60 changed files with 6361 additions and 769 deletions
373
Tools/RynthCore.DatReaderCheck/Program.cs
Normal file
373
Tools/RynthCore.DatReaderCheck/Program.cs
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
// RynthCore.DatReaderCheck - proves a dat reader change on the real dat files (read only).
|
||||
// Written for RynthCore (MIT). See the .csproj for the modes; the README-style notes are there.
|
||||
//
|
||||
// Every check goes through the reader's public API only (Open, header properties, RecordCount,
|
||||
// EnumerateEntries, FindFile, GetFileData, GetLandblockCellIds, GetSampleIds), so the same
|
||||
// source builds against any reader that keeps that API, and two builds' manifests can be
|
||||
// compared line by line.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||
|
||||
namespace RynthCore.DatReaderCheck;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
if (args.Length >= 3 && args[0] == "manifest") return Manifest(args[1], args[2]);
|
||||
if (args.Length >= 3 && args[0] == "geo") return Geo(args[1], args[2]);
|
||||
if (args.Length >= 3 && args[0] == "diff") return Diff(args[1], args[2]);
|
||||
if (args.Length >= 2 && args[0] == "bench") return Bench(args[1], args.Length > 2 ? int.Parse(args[2]) : 3);
|
||||
Console.WriteLine("usage: manifest <AC folder> <out> | geo <AC folder> <out> | diff <a> <b> | bench <AC folder> [rounds]");
|
||||
return 2;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ manifest
|
||||
|
||||
private static int Manifest(string acDir, string outPath)
|
||||
{
|
||||
using var w = new StreamWriter(outPath, false, new UTF8Encoding(false));
|
||||
w.NewLine = "\n";
|
||||
int rc = 0;
|
||||
rc |= DumpDat(w, Path.Combine(acDir, "client_portal.dat"), cellDat: false);
|
||||
rc |= DumpDat(w, Path.Combine(acDir, "client_cell_1.dat"), cellDat: true);
|
||||
var p = Process.GetCurrentProcess();
|
||||
p.Refresh();
|
||||
w.WriteLine($"#t process peak working set {p.PeakWorkingSet64 / 1048576.0:F1} MB, peak private {p.PeakPagedMemorySize64 / 1048576.0:F1} MB");
|
||||
Console.WriteLine($"peak working set {p.PeakWorkingSet64 / 1048576.0:F1} MB");
|
||||
return rc;
|
||||
}
|
||||
|
||||
private static int DumpDat(StreamWriter w, string path, bool cellDat)
|
||||
{
|
||||
string name = Path.GetFileName(path);
|
||||
Console.WriteLine($"== {name}");
|
||||
w.WriteLine($"== {name}");
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
var db = new DatDatabase();
|
||||
bool ok = db.Open(path);
|
||||
double openMs = sw.Elapsed.TotalMilliseconds;
|
||||
w.WriteLine($"open {ok}");
|
||||
w.WriteLine($"#t open {openMs:F1} ms");
|
||||
if (!ok)
|
||||
{
|
||||
foreach (var l in db.DiagLog) w.WriteLine("#t diag " + l);
|
||||
Console.WriteLine("open failed: " + string.Join(" | ", db.DiagLog));
|
||||
return 1;
|
||||
}
|
||||
w.WriteLine($"header FileType={db.FileType:X8} BlockSize={db.BlockSize} FileSize={db.FileSize} DataSet={db.DataSet:X8} BTreeRoot={db.BTreeRoot:X8} IsLoaded={db.IsLoaded}");
|
||||
|
||||
sw.Restart();
|
||||
int count = db.RecordCount;
|
||||
w.WriteLine($"records {count}");
|
||||
w.WriteLine($"#t RecordCount {sw.Elapsed.TotalMilliseconds:F1} ms");
|
||||
w.WriteLine("samples " + string.Join(",", db.GetSampleIds(30).Select(i => i.ToString("X8"))));
|
||||
|
||||
// 1. Enumerate (ids, flags, offsets, sizes) without reading any file.
|
||||
sw.Restart();
|
||||
var entries = new List<DatBTreeEntry>(count);
|
||||
foreach (var e in db.EnumerateEntries())
|
||||
entries.Add(new DatBTreeEntry { BitFlags = e.BitFlags, ObjectId = e.ObjectId, FileOffset = e.FileOffset, FileSize = e.FileSize });
|
||||
double enumMs = sw.Elapsed.TotalMilliseconds;
|
||||
w.WriteLine($"enumerated {entries.Count}");
|
||||
w.WriteLine($"#t EnumerateEntries {enumMs:F1} ms");
|
||||
bool ascending = true;
|
||||
for (int i = 1; i < entries.Count; i++) if (entries[i].ObjectId <= entries[i - 1].ObjectId) { ascending = false; break; }
|
||||
w.WriteLine($"ascending {ascending}");
|
||||
|
||||
// 2. Every file by id: FindFile must return the same entry, GetFileData its bytes.
|
||||
sw.Restart();
|
||||
long bytes = 0;
|
||||
int nulls = 0, entryMismatch = 0;
|
||||
double findMs = 0, readMs = 0;
|
||||
var swOne = new Stopwatch();
|
||||
foreach (var e in entries)
|
||||
{
|
||||
swOne.Restart();
|
||||
var f = db.FindFile(e.ObjectId);
|
||||
findMs += swOne.Elapsed.TotalMilliseconds;
|
||||
bool same = f != null && f.ObjectId == e.ObjectId && f.FileOffset == e.FileOffset && f.FileSize == e.FileSize && f.BitFlags == e.BitFlags;
|
||||
if (!same) entryMismatch++;
|
||||
swOne.Restart();
|
||||
byte[] data = db.GetFileData(e.ObjectId);
|
||||
readMs += swOne.Elapsed.TotalMilliseconds;
|
||||
string digest;
|
||||
if (data == null) { nulls++; digest = "NULL"; }
|
||||
else { bytes += data.Length; digest = data.Length + " " + Convert.ToHexString(SHA256.HashData(data)); }
|
||||
w.WriteLine($"f {e.ObjectId:X8} {e.BitFlags:X8} {e.FileOffset:X8} {e.FileSize} {(same ? "=" : "!")} {digest}");
|
||||
}
|
||||
double allMs = sw.Elapsed.TotalMilliseconds;
|
||||
w.WriteLine($"files {entries.Count} read-null {nulls} find-mismatch {entryMismatch} bytes {bytes}");
|
||||
w.WriteLine($"#t all files {allMs:F0} ms (FindFile {findMs:F0} ms, GetFileData incl. its own find {readMs:F0} ms, hashing the rest), {bytes / 1048576.0:F0} MB");
|
||||
Console.WriteLine($" {entries.Count} files, {nulls} null, {entryMismatch} find mismatches, {bytes / 1048576.0:F0} MB in {allMs:F0} ms");
|
||||
|
||||
// 3. Misses. Ids next to every real id, and a fixed pseudo-random set.
|
||||
var idSet = new HashSet<uint>(entries.Select(e => e.ObjectId));
|
||||
sw.Restart();
|
||||
int probes = 0, misses = 0, wrongHits = 0, wrongMisses = 0;
|
||||
void Probe(uint id)
|
||||
{
|
||||
probes++;
|
||||
var f = db.FindFile(id);
|
||||
bool expect = idSet.Contains(id);
|
||||
if (f == null) { misses++; if (expect) wrongMisses++; }
|
||||
else if (!expect || f.ObjectId != id) wrongHits++;
|
||||
}
|
||||
foreach (var e in entries)
|
||||
{
|
||||
if (e.ObjectId != uint.MaxValue) Probe(e.ObjectId + 1);
|
||||
if (e.ObjectId != 0) Probe(e.ObjectId - 1);
|
||||
}
|
||||
var rng = new Random(20261005);
|
||||
for (int i = 0; i < 1_000_000; i++) Probe((uint)rng.NextInt64(0, 1L << 32));
|
||||
// The prefix the reader is used for: the portal types 0x01-0x40 near the low ids.
|
||||
for (uint t = 0; t <= 0x40; t++) for (uint lo = 0; lo < 0x400; lo++) Probe((t << 24) | lo);
|
||||
Probe(0); Probe(uint.MaxValue);
|
||||
w.WriteLine($"probes {probes} misses {misses} wrong-hits {wrongHits} wrong-misses {wrongMisses}");
|
||||
w.WriteLine($"#t probes {sw.Elapsed.TotalMilliseconds:F0} ms");
|
||||
|
||||
// 4. Landblocks: the cell dat's per-landblock lookups.
|
||||
sw.Restart();
|
||||
int lbWithCells = 0, cellIds = 0, lbFound = 0, infoFound = 0;
|
||||
for (uint lb = 0; lb <= 0xFFFF; lb++)
|
||||
{
|
||||
var ids = db.GetLandblockCellIds(lb);
|
||||
bool hasLb = db.FindFile((lb << 16) | 0xFFFF) != null;
|
||||
bool hasInfo = db.FindFile((lb << 16) | 0xFFFE) != null;
|
||||
if (hasLb) lbFound++;
|
||||
if (hasInfo) infoFound++;
|
||||
if (ids.Count > 0) lbWithCells++;
|
||||
cellIds += ids.Count;
|
||||
if (cellDat || ids.Count > 0 || hasLb || hasInfo)
|
||||
w.WriteLine($"lb {lb:X4} {(hasLb ? 1 : 0)}{(hasInfo ? 1 : 0)} {ids.Count} {Hash(ids)}");
|
||||
}
|
||||
w.WriteLine($"landblocks with-FFFF {lbFound} with-FFFE {infoFound} with-cells {lbWithCells} cell-ids {cellIds}");
|
||||
w.WriteLine($"#t landblock scan {sw.Elapsed.TotalMilliseconds:F0} ms");
|
||||
|
||||
// Cross-check GetLandblockCellIds against the enumeration.
|
||||
var expected = new Dictionary<uint, int>();
|
||||
foreach (var e in entries)
|
||||
{
|
||||
uint low = e.ObjectId & 0xFFFF;
|
||||
if (low >= 0x0100 && low <= 0xFFFD) expected[e.ObjectId >> 16] = expected.TryGetValue(e.ObjectId >> 16, out int n) ? n + 1 : 1;
|
||||
}
|
||||
int lbMismatch = 0;
|
||||
foreach (var kv in expected) if (db.GetLandblockCellIds(kv.Key).Count != kv.Value) lbMismatch++;
|
||||
w.WriteLine($"landblock-vs-enumeration mismatches {lbMismatch}");
|
||||
|
||||
db.Close();
|
||||
w.WriteLine($"closed IsLoaded={db.IsLoaded} find-after-close={(db.FindFile(0x0E00000E) == null ? "null" : "hit")} data-after-close={(db.GetFileData(0x0E00000E) == null ? "null" : "data")}");
|
||||
db.Dispose();
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static string Hash(List<uint> ids)
|
||||
{
|
||||
if (ids.Count == 0) return "-";
|
||||
var b = new byte[ids.Count * 4];
|
||||
for (int i = 0; i < ids.Count; i++) BitConverter.TryWriteBytes(b.AsSpan(i * 4), ids[i]);
|
||||
return Convert.ToHexString(SHA256.HashData(b), 0, 12);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ bench
|
||||
|
||||
// Timings only (no hashing, no output file): run it a few times against warm OS file cache.
|
||||
private static int Bench(string acDir, int rounds)
|
||||
{
|
||||
foreach (string name in new[] { "client_portal.dat", "client_cell_1.dat" })
|
||||
{
|
||||
string path = Path.Combine(acDir, name);
|
||||
Console.WriteLine($"== {name} (managed heap the open reader holds after the lookups below: {ReaderHeapKb(path):F0} KB)");
|
||||
for (int r = 0; r < rounds; r++)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
var db = new DatDatabase();
|
||||
db.Open(path);
|
||||
double open = sw.Elapsed.TotalMilliseconds;
|
||||
sw.Restart(); int count = db.RecordCount; double rcMs = sw.Elapsed.TotalMilliseconds;
|
||||
sw.Restart();
|
||||
var ids = new List<uint>(count);
|
||||
foreach (var e in db.EnumerateEntries()) ids.Add(e.ObjectId);
|
||||
double enumMs = sw.Elapsed.TotalMilliseconds;
|
||||
sw.Restart();
|
||||
long bytes = 0;
|
||||
foreach (uint id in ids) bytes += db.GetFileData(id)?.Length ?? 0;
|
||||
double readMs = sw.Elapsed.TotalMilliseconds;
|
||||
// A fresh reader for the lookups, so they start cold (like a plugin after Open).
|
||||
db.Dispose();
|
||||
db = new DatDatabase();
|
||||
db.Open(path);
|
||||
var rng = new Random(7);
|
||||
sw.Restart();
|
||||
for (int i = 0; i < 200_000; i++) db.FindFile(ids[rng.Next(ids.Count)]);
|
||||
double findMs = sw.Elapsed.TotalMilliseconds;
|
||||
sw.Restart();
|
||||
int cells = 0;
|
||||
for (uint lb = 0; lb <= 0xFFFF; lb++) { cells += db.GetLandblockCellIds(lb).Count; db.FindFile((lb << 16) | 0xFFFF); db.FindFile((lb << 16) | 0xFFFE); }
|
||||
double lbMs = sw.Elapsed.TotalMilliseconds;
|
||||
db.Dispose();
|
||||
Console.WriteLine($" round {r + 1}: open {open:F1} ms, RecordCount {rcMs:F0} ms, enumerate {enumMs:F0} ms, read all {ids.Count} files ({bytes / 1048576.0:F0} MB) {readMs:F0} ms, " +
|
||||
$"200k random FindFile {findMs:F0} ms, 65,536 landblocks (cell ids + FFFF + FFFE) {lbMs:F0} ms");
|
||||
}
|
||||
}
|
||||
var p = Process.GetCurrentProcess();
|
||||
p.Refresh();
|
||||
Console.WriteLine($"peak working set {p.PeakWorkingSet64 / 1048576.0:F1} MB");
|
||||
return 0;
|
||||
}
|
||||
|
||||
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
|
||||
private static double ReaderHeapKb(string path)
|
||||
{
|
||||
long before = GC.GetTotalMemory(true);
|
||||
var db = Warm(path);
|
||||
long after = GC.GetTotalMemory(true);
|
||||
GC.KeepAlive(db);
|
||||
db.Dispose();
|
||||
return (after - before) / 1024.0;
|
||||
}
|
||||
|
||||
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
|
||||
private static DatDatabase Warm(string path)
|
||||
{
|
||||
var db = new DatDatabase();
|
||||
db.Open(path);
|
||||
_ = db.RecordCount;
|
||||
for (uint lb = 0; lb <= 0xFFFF; lb++) { db.GetLandblockCellIds(lb); db.FindFile((lb << 16) | 0xFFFF); }
|
||||
return db;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ geo
|
||||
|
||||
private static int Geo(string acDir, string outPath)
|
||||
{
|
||||
using var w = new StreamWriter(outPath, false, new UTF8Encoding(false));
|
||||
w.NewLine = "\n";
|
||||
var sw = Stopwatch.StartNew();
|
||||
var geo = new GeometryLoader();
|
||||
if (!geo.Initialize(acDir)) { Console.WriteLine("Geometry loader failed: " + geo.StatusMessage); return 1; }
|
||||
w.WriteLine($"#t GeometryLoader.Initialize {sw.Elapsed.TotalMilliseconds:F0} ms");
|
||||
w.WriteLine("status " + geo.StatusMessage);
|
||||
|
||||
var dungeonLbs = new SortedSet<uint>();
|
||||
foreach (var e in geo.CellDat.EnumerateEntries())
|
||||
{
|
||||
uint low = e.ObjectId & 0xFFFF;
|
||||
if (low >= 0x0100 && low <= 0xFFFD) dungeonLbs.Add(e.ObjectId >> 16);
|
||||
}
|
||||
w.WriteLine($"landblocks-with-cells {dungeonLbs.Count}");
|
||||
|
||||
double dungeonMs = 0, outdoorMs = 0, slowest = 0;
|
||||
uint slowestLb = 0;
|
||||
int vols = 0, polys = 0;
|
||||
foreach (uint lb in dungeonLbs)
|
||||
{
|
||||
var t = Stopwatch.StartNew();
|
||||
var v = geo.GetLandblockGeometry((lb << 16) | 0x0100);
|
||||
var p = geo.DungeonLOS.GetDungeonMapPolygons(lb);
|
||||
var fl = geo.DungeonLOS.GetDungeonMapFloorPolygons(lb);
|
||||
var cells = geo.DungeonLOS.GetDungeonMapCells(lb);
|
||||
double ms = t.Elapsed.TotalMilliseconds;
|
||||
dungeonMs += ms;
|
||||
if (ms > slowest) { slowest = ms; slowestLb = lb; }
|
||||
vols += v.Count; polys += p.Count;
|
||||
w.WriteLine($"d {lb:X4} v{v.Count} {Digest(v)} p{p.Count} {Digest(p)} f{fl.Count} {Digest(fl)} c{cells.Count}");
|
||||
geo.FlushLandblock(lb);
|
||||
}
|
||||
w.WriteLine($"#t dungeon landblocks {dungeonLbs.Count}: {dungeonMs:F0} ms total, {dungeonMs / Math.Max(1, dungeonLbs.Count):F2} ms each, slowest {slowestLb:X4} {slowest:F1} ms");
|
||||
Console.WriteLine($"dungeons: {dungeonLbs.Count} landblocks, {vols} volumes, {polys} polygons, {dungeonMs:F0} ms");
|
||||
|
||||
int outdoor = 0;
|
||||
for (uint x = 0; x < 256; x += 4)
|
||||
for (uint y = 0; y < 256; y += 4)
|
||||
{
|
||||
uint lb = (x << 8) | y;
|
||||
var t = Stopwatch.StartNew();
|
||||
var v = geo.GetLandblockGeometry((lb << 16) | 0x0001);
|
||||
float z = geo.GetTerrainZWorld(x * 192f + 96f, y * 192f + 96f);
|
||||
outdoorMs += t.Elapsed.TotalMilliseconds;
|
||||
outdoor++;
|
||||
w.WriteLine($"o {lb:X4} v{v.Count} {Digest(v)} z{BitConverter.SingleToInt32Bits(z):X8}");
|
||||
geo.FlushLandblock(lb);
|
||||
}
|
||||
w.WriteLine($"#t outdoor landblocks {outdoor}: {outdoorMs:F0} ms total, {outdoorMs / outdoor:F2} ms each");
|
||||
Console.WriteLine($"outdoor: {outdoor} landblocks, {outdoorMs:F0} ms");
|
||||
var proc = Process.GetCurrentProcess();
|
||||
proc.Refresh();
|
||||
w.WriteLine($"#t process peak working set {proc.PeakWorkingSet64 / 1048576.0:F1} MB");
|
||||
geo.Dispose();
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static string Digest(List<BoundingVolume> vs)
|
||||
{
|
||||
using var h = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
foreach (var v in vs)
|
||||
{
|
||||
Add(h, (int)v.Type); Add(h, v.Center); Add(h, v.Dimensions); Add(h, v.Min); Add(h, v.Max);
|
||||
Add(h, v.IsDoor ? 1 : 0); Add(h, v.NoAabbFallback ? 1 : 0);
|
||||
Add(h, v.Vertices); Add(h, v.MeshTriangles);
|
||||
}
|
||||
return Convert.ToHexString(h.GetHashAndReset(), 0, 12);
|
||||
}
|
||||
|
||||
private static string Digest(List<DungeonLOS.MapPolygon> ps)
|
||||
{
|
||||
using var h = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
foreach (var p in ps)
|
||||
{
|
||||
Add(h, p.Vertices); Add(h, new Vector3(p.CellX, p.CellY, p.CellZ));
|
||||
Add(h, p.IsPortal ? 1 : 0); Add(h, p.IsFloor ? 1 : 0); Add(h, (int)p.CellId);
|
||||
}
|
||||
return Convert.ToHexString(h.GetHashAndReset(), 0, 12);
|
||||
}
|
||||
|
||||
private static void Add(IncrementalHash h, int v) { Span<byte> b = stackalloc byte[4]; BitConverter.TryWriteBytes(b, v); h.AppendData(b); }
|
||||
private static void Add(IncrementalHash h, Vector3 v)
|
||||
{
|
||||
Add(h, BitConverter.SingleToInt32Bits(v.X)); Add(h, BitConverter.SingleToInt32Bits(v.Y)); Add(h, BitConverter.SingleToInt32Bits(v.Z));
|
||||
}
|
||||
private static void Add(IncrementalHash h, Vector3[] vs)
|
||||
{
|
||||
if (vs == null) { Add(h, -1); return; }
|
||||
Add(h, vs.Length);
|
||||
foreach (var v in vs) Add(h, v);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ diff
|
||||
|
||||
private static int Diff(string a, string b)
|
||||
{
|
||||
var la = File.ReadLines(a).Where(l => !l.StartsWith("#t")).GetEnumerator();
|
||||
var lb = File.ReadLines(b).Where(l => !l.StartsWith("#t")).GetEnumerator();
|
||||
long n = 0, diffs = 0;
|
||||
while (true)
|
||||
{
|
||||
bool ha = la.MoveNext(), hb = lb.MoveNext();
|
||||
if (!ha && !hb) break;
|
||||
n++;
|
||||
string sa = ha ? la.Current : "<end>", sb = hb ? lb.Current : "<end>";
|
||||
if (sa != sb)
|
||||
{
|
||||
if (diffs < 40) Console.WriteLine($"line {n}:\n a: {sa}\n b: {sb}");
|
||||
diffs++;
|
||||
}
|
||||
}
|
||||
Console.WriteLine($"{n} lines compared, {diffs} differ");
|
||||
Console.WriteLine("timings a:");
|
||||
foreach (var l in File.ReadLines(a).Where(l => l.StartsWith("#t"))) Console.WriteLine(" " + l);
|
||||
Console.WriteLine("timings b:");
|
||||
foreach (var l in File.ReadLines(b).Where(l => l.StartsWith("#t"))) Console.WriteLine(" " + l);
|
||||
return diffs == 0 ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Checks a change to the dat reader (Shared\RynthCore.TerrainData\DatDatabase.cs) against the
|
||||
reader it replaces, on the real dat files, read only. It uses only the reader's public API, so
|
||||
the same source builds against the old reader (check out the base commit) and the new one;
|
||||
each build writes a manifest and "diff" compares two manifests:
|
||||
|
||||
manifest <AC folder> <out> every file in client_portal.dat and client_cell_1.dat: id,
|
||||
flags, offset, size and a SHA-256 of its bytes; FindFile misses
|
||||
for every landblock and for a fixed set of random ids;
|
||||
GetLandblockCellIds for all 65,536 landblocks; timings.
|
||||
geo <AC folder> <out> every dungeon landblock (and every 16th outdoor one) through
|
||||
RynthAi's GeometryLoader + DungeonLOS: a digest of the LOS
|
||||
volumes and map polygons, and how long each load took.
|
||||
diff <a> <b> compares two manifests (timing lines, "#t", are skipped).
|
||||
|
||||
Run: dotnet run -c Release (after the usual separator) manifest "C:\Turbine\Asheron's Call" old.txt
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<Nullable>disable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>RynthCore.DatReaderCheck</RootNamespace>
|
||||
<NoWarn>$(NoWarn);CS8632</NoWarn>
|
||||
<ServerGarbageCollection>false</ServerGarbageCollection>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\BoundingVolume.cs" Link="Linked\BoundingVolume.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\DungeonLOS.cs" Link="Linked\DungeonLOS.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\GeometryLoader.cs" Link="Linked\GeometryLoader.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\LandblockStructs.cs" Link="Linked\LandblockStructs.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\ScatterSystem.cs" Link="Linked\ScatterSystem.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
|
||||
<ProjectReference Include="..\..\Shared\RynthCore.TerrainData\RynthCore.TerrainData.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -38,6 +38,7 @@ internal static partial class Program
|
|||
TestAddJsonInsert(crlf: false);
|
||||
TestAddJsonInsert(crlf: true);
|
||||
TestAddJsonEdgeCases();
|
||||
TestAddBuiltInReasonWire();
|
||||
TestAddDeployedCopies(args);
|
||||
}
|
||||
finally
|
||||
|
|
@ -46,6 +47,20 @@ internal static partial class Program
|
|||
}
|
||||
}
|
||||
|
||||
// The popup's "why RynthAi takes it anyway" (2026-10-05): on the wire next to OrderNote,
|
||||
// and a payload from a RynthAi without it reads as empty.
|
||||
private static void TestAddBuiltInReasonWire()
|
||||
{
|
||||
Console.WriteLine("\n-- LootAdd: built-in keep reason on the wire --");
|
||||
var st = new LootEditState { ItemDraft = new LootEditItemDraft { Seq = 3, OrderNote = "Goes in at the end. Why.", BuiltInReason = "Why." } };
|
||||
string json = System.Text.Json.JsonSerializer.Serialize(st, LootEditJsonContext.Default.LootEditState);
|
||||
LootEditState? back = System.Text.Json.JsonSerializer.Deserialize(json, LootEditJsonContext.Default.LootEditState);
|
||||
Eq(back?.ItemDraft?.BuiltInReason, "Why.", "BuiltInReason round-trips");
|
||||
Eq(back?.ItemDraft?.OrderNote, "Goes in at the end. Why.", "OrderNote too");
|
||||
LootEditState? old = System.Text.Json.JsonSerializer.Deserialize("{\"ItemDraft\":{\"Seq\":1,\"OrderNote\":\"x\"}}", LootEditJsonContext.Default.LootEditState);
|
||||
Eq(old?.ItemDraft?.BuiltInReason, "", "an older RynthAi's draft: empty");
|
||||
}
|
||||
|
||||
private static string AddFile(string name, byte[] bytes)
|
||||
{
|
||||
string path = Path.Combine(_addDir, name);
|
||||
|
|
|
|||
|
|
@ -81,6 +81,14 @@ internal static unsafe class FakeHost
|
|||
public static int Jumps;
|
||||
public static int Turns;
|
||||
public static readonly List<(uint Target, int SpellId)> Casts = new();
|
||||
/// <summary>Opt-in: wires GiveObjectTo (AC's give action); every call lands in <see cref="Gives"/>.</summary>
|
||||
public static bool GiveCalls;
|
||||
/// <summary>Every GiveObjectTo (item, target, amount; 0 = the whole object), in order.</summary>
|
||||
public static readonly List<(uint Item, uint Target, int Amount)> Gives = new();
|
||||
/// <summary>Opt-in: wires StopCompletely (off by default so no other test sees it).</summary>
|
||||
public static bool StopCalls;
|
||||
/// <summary>StopCompletely calls (opt-in with <see cref="StopCalls"/>).</summary>
|
||||
public static int Stops;
|
||||
/// <summary>Every UseObject (a wield, a use) and RequestId (an identify), in order.</summary>
|
||||
public static readonly List<uint> Uses = new();
|
||||
public static readonly List<uint> IdRequests = new();
|
||||
|
|
@ -100,6 +108,12 @@ internal static unsafe class FakeHost
|
|||
public static bool ServerGates;
|
||||
/// <summary>The count of server UseDone (0x01C7) events the fake reports.</summary>
|
||||
public static int UseDoneSeq;
|
||||
/// <summary>The error code of the last UseDone (GetLastUseDone, v70; 0 = completed, 0x1D = too busy).
|
||||
/// Opt-in with <see cref="LastUseDoneCalls"/> (set before Create, together with ServerGates).</summary>
|
||||
public static uint LastUseDoneError;
|
||||
public static bool LastUseDoneCalls;
|
||||
/// <summary>One more UseDone with <paramref name="error"/> (0 = the action completed).</summary>
|
||||
public static void UseDone(uint error) { UseDoneSeq++; LastUseDoneError = error; }
|
||||
/// <summary>1 while a cast gesture animates (GetCastBusyState), else 0.</summary>
|
||||
public static int CastBusy;
|
||||
public static int VTankSeq;
|
||||
|
|
@ -135,6 +149,12 @@ internal static unsafe class FakeHost
|
|||
public static uint GroundContainer;
|
||||
/// <summary>The item selected in the game (GetSelectedItemId); 0 = none.</summary>
|
||||
public static uint SelectedItem;
|
||||
/// <summary>Opt-in: install SendPluginCommand (the engine's plugin-command broker, API v64).</summary>
|
||||
public static bool PluginCommandCalls;
|
||||
/// <summary>What SendPluginCommand answers: true = delivered (the target plugin is loaded).</summary>
|
||||
public static bool PluginCommandDelivered = true;
|
||||
/// <summary>Every SendPluginCommand (plugin, action, value), in order.</summary>
|
||||
public static readonly List<(string Plugin, string Action, string Value)> PluginCommands = new();
|
||||
|
||||
// ANSI strings handed back to tested code stay alive for the whole run.
|
||||
private static readonly Dictionary<string, IntPtr> _ansi = new();
|
||||
|
|
@ -150,15 +170,16 @@ internal static unsafe class FakeHost
|
|||
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
|
||||
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
|
||||
Logs.Clear(); Chat.Clear(); ChatCommands.Clear();
|
||||
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; Turns = 0; Casts.Clear();
|
||||
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; Turns = 0; Casts.Clear(); StopCalls = false; Stops = 0; GiveCalls = false; Gives.Clear();
|
||||
Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1;
|
||||
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
|
||||
ServerGates = false; UseDoneSeq = 0; CastBusy = 0;
|
||||
ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false;
|
||||
WieldCalls = false; Wields.Clear();
|
||||
SalvageCalls = false; ExternalMoves.Clear(); SalvageAdds.Clear(); SalvageExecutes.Clear();
|
||||
RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear();
|
||||
CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0;
|
||||
SelectedItem = 0;
|
||||
PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -199,6 +220,10 @@ internal static unsafe class FakeHost
|
|||
api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&TurnToHeading;
|
||||
api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&JumpNonAutonomous;
|
||||
api.CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&CastSpell;
|
||||
if (StopCalls)
|
||||
api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&StopCompletely;
|
||||
if (GiveCalls)
|
||||
api.GiveObjectToFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int>)&GiveObjectTo;
|
||||
if (WeaponCalls)
|
||||
{
|
||||
api.UseObjectFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&UseObject;
|
||||
|
|
@ -256,6 +281,8 @@ internal static unsafe class FakeHost
|
|||
{
|
||||
api.GetUseDoneSeqFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetUseDoneSeq;
|
||||
api.GetCastBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetCastBusyState;
|
||||
if (LastUseDoneCalls)
|
||||
api.GetLastUseDoneFn = (IntPtr)(delegate* unmanaged[Cdecl]<int*, uint*, int>)&GetLastUseDone;
|
||||
}
|
||||
if (VTankFlags >= 0)
|
||||
{
|
||||
|
|
@ -268,6 +295,11 @@ internal static unsafe class FakeHost
|
|||
api.CloseContainerFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&CloseContainer;
|
||||
api.GetGroundContainerIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetGroundContainerId;
|
||||
}
|
||||
if (PluginCommandCalls)
|
||||
{
|
||||
api.Version = Math.Max(api.Version, 64u);
|
||||
api.SendPluginCommandFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, IntPtr, IntPtr, int>)&SendPluginCommand;
|
||||
}
|
||||
LastApi = api;
|
||||
return new RynthCoreHost(api);
|
||||
}
|
||||
|
|
@ -327,9 +359,24 @@ internal static unsafe class FakeHost
|
|||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetCastBusyState() => CastBusy;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetLastUseDone(int* seq, uint* error)
|
||||
{
|
||||
*seq = UseDoneSeq;
|
||||
*error = UseDoneSeq == 0 ? 0 : LastUseDoneError;
|
||||
return 1;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int WriteToChat(IntPtr text, int type) { Chat.Add(Marshal.PtrToStringUni(text) ?? ""); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int SendPluginCommand(IntPtr plugin, IntPtr action, IntPtr value)
|
||||
{
|
||||
PluginCommands.Add((Marshal.PtrToStringAnsi(plugin) ?? "", Marshal.PtrToStringAnsi(action) ?? "", Marshal.PtrToStringAnsi(value) ?? ""));
|
||||
return PluginCommandDelivered ? 1 : 0;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int InvokeChatParser(IntPtr text) { ChatCommands.Add(Marshal.PtrToStringUni(text) ?? ""); return 1; }
|
||||
|
||||
|
|
@ -511,6 +558,10 @@ internal static unsafe class FakeHost
|
|||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int CastSpell(uint target, int spellId) { Casts.Add((target, spellId)); return 1; }
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int StopCompletely() { Stops++; return 1; }
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GiveObjectTo(uint item, uint target, int amount) { Gives.Add((item, target, amount)); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetCurrentCombatMode() => CombatModeValue;
|
||||
|
|
|
|||
|
|
@ -28,6 +28,8 @@ internal static class Program
|
|||
ExpressionEngine.PvarsDir = Path.Combine(TempRoot, "pvars");
|
||||
ExpressionEngine.GvarsPath = Path.Combine(TempRoot, "gvars.txt");
|
||||
ExpressionEngine.ItemGiverDir = Path.Combine(TempRoot, "ItemGiver");
|
||||
// The dungeon map bake writes floor plans under C:\Games\RynthSuite\RynthAi\Maps.
|
||||
RynthCore.Plugin.RynthAi.Maps.DungeonMapBake.CacheDir = Path.Combine(TempRoot, "Maps");
|
||||
|
||||
// Spell names (item spells, spell expiry by name) come from the plugin's embedded table.
|
||||
SpellDatabase.Load();
|
||||
|
|
@ -50,13 +52,18 @@ internal static class Program
|
|||
FloodPerfTests.Register(runner);
|
||||
LootSalvageTests.Register(runner);
|
||||
LootCorpseTests.Register(runner);
|
||||
OwnCorpseTests.Register(runner);
|
||||
VitalsTests.Register(runner);
|
||||
CastSafetyTests.Register(runner);
|
||||
HealLatencyTests.Register(runner);
|
||||
BlastTests.Register(runner);
|
||||
ArcWhenClearTests.Register(runner);
|
||||
UseAtLoginTests.Register(runner);
|
||||
LearnSpellsTests.Register(runner);
|
||||
AttackLatencyTests.Register(runner);
|
||||
LootAddItemTests.Register(runner);
|
||||
GiveTests.Register(runner);
|
||||
DungeonMapBakeTests.Register(runner);
|
||||
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
|
@ -48,6 +51,9 @@ internal static class BuffTests
|
|||
r.Add("rebuff: permanent, expired, and two enchantments in one family", RebuffPermanentAndDuplicates);
|
||||
r.Add("rebuff: a higher tier is only chased above the tier that has landed", RebuffTierUpgrade);
|
||||
r.Add("rebuff: a chat-confirmed item spell counts as on", ItemSpellFromChat);
|
||||
r.Add("rebuff: our own lower tier under an expiring higher one counts as on", RebuffUnderExpiringHigherTier);
|
||||
r.Add("rebuff: cast over item-granted buffs (CastBuffsOverItemBuffs on)", RebuffOverItemBuffs);
|
||||
r.Add("rebuff: CastBuffsOverItemBuffs defaults on, loads, saves, bridges", OverItemBuffsSetting);
|
||||
|
||||
r.Add("buff choice: spell names the tables miss (Bludgeon Bane, Nuhmudira's, T'ing, Celdiseth's)", NameGapsResolve); // was a known failure; fixed by 940cb21
|
||||
r.Add("buff choice: a mastery whose name has several spell ids", MultiIdMastery); // was a known failure; fixed by 0aedcee
|
||||
|
|
@ -438,21 +444,26 @@ internal static class BuffTests
|
|||
Check.True(rig.B.NeedsAnyBuff(), "Force Rebuff: everything is due");
|
||||
}
|
||||
|
||||
// CastBuffsOverItemBuffs off: the behaviour before 2026-10-05 (an item-granted permanent
|
||||
// entry at the tier we'd cast satisfies the family). The setting's own cases are below.
|
||||
private static void RebuffPermanentAndDuplicates()
|
||||
{
|
||||
var rig = StrengthRig(300, "Strength Self VI");
|
||||
rig.S.CastBuffsOverItemBuffs = false;
|
||||
rig.Live(("Strength Self VI", double.MaxValue));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "a permanent enchantment counts as on");
|
||||
rig.Live(("Strength Self VI", -5));
|
||||
Check.True(rig.B.NeedsAnyBuff(), "an expired entry is dropped: recast");
|
||||
|
||||
var t7 = StrengthRig(340, "Strength Self VI", "Might of the Lugians"); // 340 buffed: tier 7
|
||||
t7.S.CastBuffsOverItemBuffs = false;
|
||||
t7.Live(("Strength Self VI", double.MaxValue), ("Might of the Lugians", 3000));
|
||||
Check.False(t7.B.NeedsAnyBuff(), "a permanent VI and a timed VII: the VII owns the family");
|
||||
t7.Live(("Might of the Lugians", 3000), ("Strength Self VI", double.MaxValue));
|
||||
Check.False(t7.B.NeedsAnyBuff(), "same in the other order");
|
||||
|
||||
var item = StrengthRig(340, "Strength Self VI", "Might of the Lugians");
|
||||
item.S.CastBuffsOverItemBuffs = false;
|
||||
item.Live(("Strength Self VI", double.MaxValue));
|
||||
Check.True(item.B.NeedsAnyBuff(), "only a permanent (item-granted) VI while VII is castable: cast the VII");
|
||||
}
|
||||
|
|
@ -473,6 +484,118 @@ internal static class BuffTests
|
|||
Check.False(inc.B.NeedsAnyBuff(), "an Incantation that lands as VI isn't recast for ever");
|
||||
}
|
||||
|
||||
// A buff bot's level 8 that runs out while our own lower tier is already under it
|
||||
// (Drakkon, 2026-10-05): the 8 owns the family timer, so the family read "due"
|
||||
// right after our VI landed and every pass recast it until the batch audit parked it.
|
||||
private static void RebuffUnderExpiringHigherTier()
|
||||
{
|
||||
var rig = StrengthRig(300, "Strength Self VI"); // 300 buffed: tier 6
|
||||
rig.Live(("Incantation of Strength Self", 3000));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "a bot's 8 with 3000 s left: fine");
|
||||
rig.Live(("Incantation of Strength Self", 200));
|
||||
Check.True(rig.B.NeedsAnyBuff(), "the 8 is running out and nothing is under it: cast our VI");
|
||||
rig.Live(("Incantation of Strength Self", 200), ("Strength Self VI", 1800));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "our VI is under the expiring 8: covered, no recast");
|
||||
rig.Live(("Strength Self VI", 1800), ("Incantation of Strength Self", 200));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "same in the other order");
|
||||
rig.Live(("Incantation of Strength Self", 200), ("Strength Self VI", 250));
|
||||
Check.True(rig.B.NeedsAnyBuff(), "both under the threshold: recast");
|
||||
|
||||
var low = StrengthRig(300, "Strength Self V", "Strength Self VI");
|
||||
low.Live(("Incantation of Strength Self", 200), ("Strength Self V", 1800));
|
||||
Check.True(low.B.NeedsAnyBuff(), "only a V under it while VI is castable: still cast the VI");
|
||||
low.S.CastBuffsOverItemBuffs = false;
|
||||
low.Live(("Incantation of Strength Self", 200), ("Strength Self VI", double.MaxValue));
|
||||
Check.False(low.B.NeedsAnyBuff(), "setting off: a permanent VI under it covers it");
|
||||
low.S.CastBuffsOverItemBuffs = true;
|
||||
low.Live(("Incantation of Strength Self", 200), ("Strength Self VI", double.MaxValue));
|
||||
Check.True(low.B.NeedsAnyBuff(), "setting on: a permanent (item) VI under it doesn't cover it: cast ours");
|
||||
}
|
||||
|
||||
// "Cast buffs even when an item already gives that buff" (CastBuffsOverItemBuffs, default
|
||||
// on, 2026-10-05). On servers with buff augments a player's own cast is stronger or longer
|
||||
// than the item's, so a permanent item-granted entry must not satisfy the family; the timer
|
||||
// follows our own timed entry, and once that lands it reads on until it runs low.
|
||||
private static void RebuffOverItemBuffs()
|
||||
{
|
||||
var rig = StrengthRig(300, "Strength Self VI"); // tier 6
|
||||
Check.True(rig.S.CastBuffsOverItemBuffs, "on by default");
|
||||
rig.Live(("Strength Self VI", double.MaxValue));
|
||||
Check.True(rig.B.NeedsAnyBuff(), "only an item's permanent VI: cast our own");
|
||||
rig.Live(("Strength Self VI", double.MaxValue), ("Strength Self VI", 3000));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "our VI landed (3000 s) over the item's VI: on, no recast loop");
|
||||
rig.Live(("Strength Self VI", 3000), ("Strength Self VI", double.MaxValue));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "same in the other order");
|
||||
rig.Live(("Strength Self VI", double.MaxValue), ("Strength Self VI", 200));
|
||||
Check.True(rig.B.NeedsAnyBuff(), "ours running low (200 s) with the item's VI still on: recast");
|
||||
rig.Live(("Strength Self VI", 200), ("Strength Self VI", double.MaxValue));
|
||||
Check.True(rig.B.NeedsAnyBuff(), "same in the other order");
|
||||
rig.Live(("Strength Self VI", double.MaxValue), ("Strength Self VI", 2700));
|
||||
Check.False(rig.B.NeedsAnyBuff(), "recast landed: on again");
|
||||
|
||||
// A higher item tier than we can cast: ours is still cast and tracked.
|
||||
var high = StrengthRig(300, "Strength Self VI");
|
||||
high.Live(("Might of the Lugians", double.MaxValue));
|
||||
Check.True(high.B.NeedsAnyBuff(), "an item's permanent VII, we cast VI: cast it");
|
||||
high.Live(("Might of the Lugians", double.MaxValue), ("Strength Self VI", 3000));
|
||||
Check.False(high.B.NeedsAnyBuff(), "our VI under the item's VII: on until it runs low");
|
||||
high.Live(("Might of the Lugians", double.MaxValue), ("Strength Self VI", 100));
|
||||
Check.True(high.B.NeedsAnyBuff(), "our VI running low: recast");
|
||||
|
||||
// The tier-upgrade rule still works on our timed entries.
|
||||
var up = StrengthRig(340, "Strength Self VI", "Might of the Lugians"); // tier 7
|
||||
up.Live(("Might of the Lugians", 3000));
|
||||
up.Live(("Strength Self VI", double.MaxValue), ("Strength Self V", 3000));
|
||||
Check.True(up.B.NeedsAnyBuff(), "VII has landed before: our V is upgraded, the item's VI doesn't stop it");
|
||||
up.Live(("Strength Self VI", double.MaxValue), ("Might of the Lugians", 3000));
|
||||
Check.False(up.B.NeedsAnyBuff(), "our VII on: fine");
|
||||
|
||||
// Switched on between live reads: a permanent that owns the timer no longer counts.
|
||||
var toggled = StrengthRig(300, "Strength Self VI");
|
||||
toggled.S.CastBuffsOverItemBuffs = false;
|
||||
toggled.Live(("Strength Self VI", double.MaxValue));
|
||||
Check.False(toggled.B.NeedsAnyBuff(), "off: the item's VI counts");
|
||||
toggled.S.CastBuffsOverItemBuffs = true;
|
||||
Check.True(toggled.B.NeedsAnyBuff(), "switched on before the next read: cast ours");
|
||||
toggled.S.CastBuffsOverItemBuffs = false;
|
||||
toggled.Live(("Strength Self VI", double.MaxValue));
|
||||
Check.False(toggled.B.NeedsAnyBuff(), "switched back off: the item's VI counts again");
|
||||
}
|
||||
|
||||
private static void OverItemBuffsSetting()
|
||||
{
|
||||
Check.True(new LegacyUiSettings().CastBuffsOverItemBuffs, "a new profile: on");
|
||||
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true,\"RebuffSecondsRemaining\":300}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(old != null && old.CastBuffsOverItemBuffs, "a profile saved before the setting: on");
|
||||
var off = JsonSerializer.Deserialize(
|
||||
JsonSerializer.Serialize(new LegacyUiSettings { CastBuffsOverItemBuffs = false }, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(off != null && !off.CastBuffsOverItemBuffs, "off is saved and loaded");
|
||||
|
||||
// Profile switch/load copies it (CopySettings is the hand-written field list).
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { new LegacyUiSettings { CastBuffsOverItemBuffs = false }, dst });
|
||||
Check.False(dst.CastBuffsOverItemBuffs, "a profile with it off loads off");
|
||||
copy.Invoke(null, new object[] { old!, dst });
|
||||
Check.True(dst.CastBuffsOverItemBuffs, "an old profile loads on");
|
||||
|
||||
// Engine Settings face: the payload carries it; an engine without the field leaves it alone.
|
||||
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.CastBuffsOverItemBuffs == null, "an older engine's payload has no value");
|
||||
var s = new LegacyUiSettings { CastBuffsOverItemBuffs = false };
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
|
||||
.SetValue(dash, new LegacyAdvancedSettingsUi(s)); // BuildSettingsJson reads its crafting state
|
||||
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(sent != null && sent.CastBuffsOverItemBuffs == false, "sent to the engine face");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.False(s.CastBuffsOverItemBuffs, "a save without the field leaves it off");
|
||||
dash.ApplySettingsJson("{\"CastBuffsOverItemBuffs\":true}");
|
||||
Check.True(s.CastBuffsOverItemBuffs, "a save with it on turns it on");
|
||||
}
|
||||
|
||||
private static BuffRig ArmorRig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
|
|
|
|||
457
Tools/RynthCore.RynthAiHostTests/Tests/CastSafetyTests.cs
Normal file
457
Tools/RynthCore.RynthAiHostTests/Tests/CastSafetyTests.cs
Normal file
|
|
@ -0,0 +1,457 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Cast safeguards after Drakkon's held casts on DreamWeave (2026-10-05,
|
||||
// ops\overnight\2026-10-05-stuck-cast.md): give-up timed from the incantation, a refusal never
|
||||
// counts as the server finishing, the first cast after a stance change waits for the stance,
|
||||
// and a cast the server holds open gets exactly one movement nudge.
|
||||
//
|
||||
// BuffManager's cast-safety timing runs on an injectable clock (BuffManager.Clock), so these
|
||||
// tests move time by hand. The rig is a mage at 10% mana: the only thing CheckVitals can do is
|
||||
// cast Stamina to Mana Self.
|
||||
internal static class CastSafetyTests
|
||||
{
|
||||
private const uint Player = 0x50000B01;
|
||||
private const uint STypeLife = 33;
|
||||
private const uint TooBusy = 0x1D;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("cast safety: a vital's give-up runs from its incantation; from the send without one", GiveUpFromIncantation);
|
||||
r.Add("cast safety: give-up time is capped, and never earlier than the send-timed one", GiveUpCap);
|
||||
r.Add("cast safety: 'You're too busy!' and a 0x1D UseDone don't count as the server finishing", TooBusyIsNotDone);
|
||||
r.Add("cast safety: a result line for another spell doesn't clear the pending cast", ResultForAnotherSpell);
|
||||
r.Add("cast safety: the first cast after a stance change waits for Magic plus the settle", StanceWait);
|
||||
r.Add("cast safety: a cast held open gets exactly one movement nudge", NudgeOnce);
|
||||
// Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md).
|
||||
r.Add("cast safety: an emergency heal waits for Magic plus 300 ms only; a top-off heal the full 1 s", EmergencyStanceWait);
|
||||
r.Add("cast safety: the stance clock starts when the client reads Magic, not at the first cast attempt", StanceClockFromObservation);
|
||||
r.Add("cast safety: the 4.1 s settle line: the stance was ready at 1 s, a kit in flight held the cast, and the line says so", StanceLateHolderNamed);
|
||||
r.Add("cast safety: a held heal is nudged at 2.8 s without waiting for a refusal, once", UrgentNudgeForHeal);
|
||||
r.Add("cast safety: any held cast is nudged early while health is under a heal line; not when health is fine", UrgentNudgeForLowHealth);
|
||||
r.Add("cast safety: no kit or potion while a cast is held open until its nudge, then one try per 3 s", HeldCastItemGate);
|
||||
r.Add("move audit: one line per call, repeats counted, subsystem in the line", MoveAuditLines);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public DateTime T0 = new(2026, 10, 5, 10, 30, 40);
|
||||
public DateTime NowAt;
|
||||
public readonly BuffManager B;
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly PlayerVitalsCache V;
|
||||
|
||||
public Rig(int combatMode = CombatMode.Magic)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.ServerGates = true;
|
||||
FakeHost.LastUseDoneCalls = true;
|
||||
FakeHost.CombatModeValue = combatMode;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
|
||||
var host = FakeHost.Create();
|
||||
S = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false,
|
||||
EnableBuffing = false,
|
||||
// OnHeartbeat's interval check runs on the real clock: keep it shut so a heartbeat
|
||||
// only resolves the pending cast and never casts again.
|
||||
SpellCastIntervalMs = 600_000,
|
||||
};
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, S);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
V = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 10 };
|
||||
B = new BuffManager(host, S, sm, V);
|
||||
B.SetCharacterSkills(skills);
|
||||
NowAt = T0;
|
||||
B.Clock = () => NowAt;
|
||||
B.MarkLiveBuffsReadyForTests();
|
||||
}
|
||||
|
||||
public void At(double seconds) => NowAt = T0.AddSeconds(seconds);
|
||||
public void Chat(string text, int type = 0) => B.OnChatWindowText(text, type);
|
||||
public void Incantation() => Chat("You say, \"Puish Zharil\"", 17);
|
||||
public int CastId => FakeHost.Casts.Last().SpellId;
|
||||
public string CastName => SpellTable.ById(CastId)?.Name ?? "";
|
||||
public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
private static void GiveUpFromIncantation()
|
||||
{
|
||||
// The DreamWeave case: incantation 1.0 s after the send, result 2.3 s after that.
|
||||
var r = new Rig();
|
||||
r.At(0);
|
||||
Check.True(r.B.CheckVitals(), "10% mana: Stamina to Mana is cast");
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "one cast");
|
||||
int pending = r.B.PendingSpellId;
|
||||
Check.True(pending != 0, "the vital is pending");
|
||||
r.At(1.0); r.Incantation();
|
||||
r.At(2.6); r.B.OnHeartbeat();
|
||||
Check.Eq(r.B.PendingSpellId, pending, "2.6 s after the send, 1.6 s after the incantation: still waiting (the old timer gave up at 2.5 s)");
|
||||
r.At(3.9); r.B.OnHeartbeat();
|
||||
Check.Eq(r.B.PendingSpellId, pending, "2.9 s after the incantation: still waiting");
|
||||
r.At(4.1); r.B.OnHeartbeat();
|
||||
Check.Eq(r.B.PendingSpellId, 0, "3.1 s after the incantation: given up");
|
||||
Check.True(r.Logged("after its incantation") && r.Logged("released, no strike"), "the release line says it was timed from the incantation");
|
||||
|
||||
// No incantation at all: the send-timed 2.5 s as before.
|
||||
var q = new Rig();
|
||||
q.At(0);
|
||||
q.B.CheckVitals();
|
||||
int p2 = q.B.PendingSpellId;
|
||||
q.At(2.4); q.B.OnHeartbeat();
|
||||
Check.Eq(q.B.PendingSpellId, p2, "no incantation, 2.4 s: still waiting");
|
||||
q.At(2.6); q.B.OnHeartbeat();
|
||||
Check.Eq(q.B.PendingSpellId, 0, "no incantation, 2.6 s: given up from the send");
|
||||
Check.True(q.Logged("no incantation in"), "the release line says no incantation came");
|
||||
|
||||
// A healthy result inside the window resolves it, and the time is logged.
|
||||
var h = new Rig();
|
||||
h.At(0); h.B.CheckVitals();
|
||||
h.At(0.3); h.Incantation();
|
||||
h.At(2.6); h.Chat($"You cast {h.CastName} on yourself and lose 35 points of stamina and also gain 47 points of mana");
|
||||
Check.Eq(h.B.PendingSpellId, 0, "its result clears the pending cast");
|
||||
Check.True(h.Logged("[CastTime]") && h.Logged("2.30 s after its incantation (send to incantation 300 ms)"),
|
||||
"[CastTime] logs incantation-to-result and send-to-incantation");
|
||||
}
|
||||
|
||||
private static void GiveUpCap()
|
||||
{
|
||||
var t0 = new DateTime(2026, 10, 5);
|
||||
var c = new CastTracker.Cast { SentAt = t0 };
|
||||
Check.Eq(CastTracker.GiveUpAt(c, 2500), t0.AddMilliseconds(2500), "no incantation: the fallback from the send");
|
||||
c.IncantAt = t0.AddMilliseconds(100);
|
||||
Check.Eq(CastTracker.GiveUpAt(c, 2500), t0.AddMilliseconds(3100), "incantation at 0.1 s: 3 s after it");
|
||||
c.IncantAt = t0.AddMilliseconds(4500);
|
||||
Check.Eq(CastTracker.GiveUpAt(c, 2500), t0.AddMilliseconds(6000), "a very late incantation: capped 6 s after the send");
|
||||
c.IncantAt = t0.AddMilliseconds(500);
|
||||
Check.Eq(CastTracker.GiveUpAt(c, 5000), t0.AddMilliseconds(5000), "armor (5 s from the send): an early incantation never makes it earlier");
|
||||
}
|
||||
|
||||
private static void TooBusyIsNotDone()
|
||||
{
|
||||
// The cast is running on the server (incantation seen).
|
||||
var r = new Rig();
|
||||
r.At(0); r.B.CheckVitals();
|
||||
int pending = r.B.PendingSpellId;
|
||||
r.At(0.1);
|
||||
Check.True(r.B.IsAwaitingCastResolution(), "just sent: waiting for the server");
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(r.B.IsAwaitingCastResolution(), "a UseDone(0) before the incantation is some earlier action's, not this cast's (the old wait cleared on it)");
|
||||
r.At(0.5); r.Incantation();
|
||||
FakeHost.UseDone(TooBusy);
|
||||
Check.True(r.B.IsAwaitingCastResolution(), "a 0x1D UseDone is a refusal, not 'done' (the old wait cleared on it)");
|
||||
r.At(1.0); r.Chat("You're too busy!");
|
||||
Check.True(r.B.IsAwaitingCastResolution(), "'You're too busy!' is not 'done'");
|
||||
Check.Eq(r.B.PendingSpellId, pending, "the running cast stays pending: the refusal was for something else");
|
||||
r.At(2.0); FakeHost.UseDone(0);
|
||||
Check.False(r.B.IsAwaitingCastResolution(), "a UseDone(0) after the incantation: the server finished it");
|
||||
Check.True(r.Logged("UseDone #"), "[CastTime] logs the UseDone that finished it");
|
||||
|
||||
// A cast refused before it started: the refusal is not 'done' either; the next UseDone(0)
|
||||
// (whatever the server was busy with, finishing) is.
|
||||
var q = new Rig();
|
||||
q.At(0); q.B.CheckVitals();
|
||||
q.At(0.3); q.Chat("You're too busy!");
|
||||
Check.Eq(q.B.PendingSpellId, 0, "a cast refused before its incantation is parked, as before");
|
||||
FakeHost.UseDone(TooBusy);
|
||||
Check.True(q.B.IsAwaitingCastResolution(), "refused: still waiting for the server to be free");
|
||||
q.At(1.0); FakeHost.UseDone(0);
|
||||
Check.False(q.B.IsAwaitingCastResolution(), "a UseDone(0) after the refusal: the server is free");
|
||||
|
||||
// The cast's own result line ends the wait.
|
||||
var s = new Rig();
|
||||
s.At(0); s.B.CheckVitals();
|
||||
s.At(0.4); s.Incantation();
|
||||
s.At(2.5); s.Chat($"You cast {s.CastName} on yourself and lose 18 points of stamina and also gain 24 points of mana");
|
||||
Check.False(s.B.IsAwaitingCastResolution(), "its result line: done");
|
||||
|
||||
// Mana and stamina casts wait for the server too (heals don't).
|
||||
var w = new Rig();
|
||||
w.At(0); w.B.CheckVitals();
|
||||
w.At(0.4); w.Incantation();
|
||||
w.At(3.5); w.B.OnHeartbeat(); // pending released (incantation + 3 s)
|
||||
Check.Eq(w.B.PendingSpellId, 0, "released");
|
||||
int before = FakeHost.Casts.Count;
|
||||
w.At(3.6);
|
||||
Check.True(w.B.CheckVitals(), "past the give-up the next Stamina to Mana may go");
|
||||
Check.Eq(FakeHost.Casts.Count, before + 1, "and it is cast");
|
||||
}
|
||||
|
||||
private static void ResultForAnotherSpell()
|
||||
{
|
||||
var r = new Rig();
|
||||
r.At(0); r.B.CheckVitals();
|
||||
int pending = r.B.PendingSpellId;
|
||||
r.At(0.2); r.Chat("You cast Strength Self V on yourself, refreshing Strength Self V");
|
||||
Check.Eq(r.B.PendingSpellId, pending, "a late result for Strength Self V doesn't clear the pending Stamina to Mana");
|
||||
Check.True(r.Logged("pending kept"), "and says so");
|
||||
r.At(1.0); r.Chat($"You cast {r.CastName} on yourself and lose 35 points of stamina and also gain 47 points of mana");
|
||||
Check.Eq(r.B.PendingSpellId, 0, "its own result does");
|
||||
}
|
||||
|
||||
private static void StanceWait()
|
||||
{
|
||||
// Peace mode, no wand listed: the bare-handed switch to Magic.
|
||||
var r = new Rig(CombatMode.NonCombat);
|
||||
r.At(0);
|
||||
Check.True(r.B.CheckVitals(), "out of Magic: the vital yields while the stance changes");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no cast before the stance");
|
||||
FakeHost.CombatModeValue = CombatMode.Magic; // the client field flips 60 ms later
|
||||
r.At(0.06);
|
||||
Check.True(r.B.CheckVitals(), "client reads Magic: still yielding");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no cast 60 ms after the stance request");
|
||||
r.At(0.55);
|
||||
r.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no cast at 0.55 s (when the first hung cast went out)");
|
||||
r.At(1.01);
|
||||
r.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "cast once the stance has settled (1 s after the request, 300 ms after Magic)");
|
||||
Check.True(r.Logged("Magic stance settled"), "the settle is logged");
|
||||
|
||||
// Already in Magic, no stance change from us: no wait.
|
||||
var q = new Rig();
|
||||
q.At(0); q.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "already in Magic: cast at once");
|
||||
}
|
||||
|
||||
private static void NudgeOnce()
|
||||
{
|
||||
var r = new Rig();
|
||||
MoveAudit.Reset();
|
||||
r.At(0); r.B.CheckVitals();
|
||||
string name = r.CastName;
|
||||
r.At(0.3); r.Incantation();
|
||||
r.At(5.0); r.Chat("You're too busy!");
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "4.7 s after the incantation: no nudge yet");
|
||||
r.At(6.5); r.Chat("You're too busy!");
|
||||
Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "held 6.2 s and still refused: one nudge, autorun on then off");
|
||||
Check.Eq(r.B.CastNudges, 1, "one nudge counted");
|
||||
Check.True(r.Logged("[CastSafe]") && r.Logged("Buff/Nudge SetAutoRun(True)"), "the nudge is logged, with its subsystem");
|
||||
r.At(8.0); r.Chat("You're too busy!");
|
||||
r.At(12.0); r.Chat("You're too busy!");
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 2, "more refusals: no second nudge for the same held cast");
|
||||
Check.True(r.Logged("HELD"), "the held cast is logged once it passes 6 s");
|
||||
r.At(13.0); r.Chat($"You cast {name} on yourself and lose 97 points of stamina and also gain 131 points of mana");
|
||||
Check.True(r.Logged("(after the movement nudge)"), "its late result is logged as coming after the nudge");
|
||||
|
||||
// Macro off: no nudge.
|
||||
var q = new Rig();
|
||||
q.At(0); q.B.CheckVitals();
|
||||
q.At(0.3); q.Incantation();
|
||||
q.S.IsMacroRunning = false;
|
||||
q.At(7.0); q.Chat("You're too busy!");
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "macro off: nothing moves the character");
|
||||
}
|
||||
|
||||
// The same spell at any tier (skill 400 casts a high tier with its own name, e.g. Adja's Intervention).
|
||||
private static bool CastIs(string baseName)
|
||||
{
|
||||
if (FakeHost.Casts.Count == 0) return false;
|
||||
int cat = SpellTable.Named(baseName + " I").First().Category;
|
||||
return SpellTable.ById(FakeHost.Casts.Last().SpellId)?.Category == cat;
|
||||
}
|
||||
|
||||
// Drakkon at 27% under Emergency Heal At 30%: Heal Self waited the full stance settle
|
||||
// (at least 1 s after the request). An emergency heal now waits only for Magic plus 300 ms.
|
||||
private static void EmergencyStanceWait()
|
||||
{
|
||||
var r = new Rig(CombatMode.NonCombat);
|
||||
r.S.EmergencyHealAt = 30; r.S.HealAt = 60; r.S.TopOffHP = 60;
|
||||
r.V.CurrentHealth = 20;
|
||||
r.At(0);
|
||||
Check.True(r.B.CheckVitals(), "20% health out of Magic: Heal Self yields while the stance changes");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no cast before the stance");
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
r.At(0.06); r.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "the client reads Magic: the 300 ms settle still runs");
|
||||
r.At(0.30); r.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "240 ms after Magic: still settling");
|
||||
r.At(0.37); r.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "310 ms after Magic (370 ms after the request): Heal Self goes, no 1 s floor");
|
||||
Check.True(CastIs("Heal Self"), "and it is Heal Self");
|
||||
Check.True(r.Logged("emergency heal"), "the stance lines say it was an emergency heal");
|
||||
Check.Eq(r.B.UrgentStanceSettles, 1, "counted");
|
||||
|
||||
// A top-off heal (idle, nothing in range): the full settle, as for a buff.
|
||||
var q = new Rig(CombatMode.NonCombat);
|
||||
q.S.EmergencyHealAt = 30; q.S.HealAt = 60; q.S.TopOffHP = 60;
|
||||
q.V.CurrentHealth = 50;
|
||||
q.At(0); q.B.CheckVitals();
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
q.At(0.06); q.B.CheckVitals();
|
||||
q.At(0.5); q.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "50% under Top Off HP: no cast at 0.5 s");
|
||||
q.At(1.01); q.B.CheckVitals();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "cast once 1 s has passed since the request");
|
||||
Check.Eq(q.B.UrgentStanceSettles, 0, "not an emergency");
|
||||
}
|
||||
|
||||
// The settle clock started at the first StanceSettled CALL in Magic, so any gate in front of
|
||||
// it (a busy count here) pushed the 300 ms back. It now starts when a heartbeat sees Magic.
|
||||
private static void StanceClockFromObservation()
|
||||
{
|
||||
var r = new Rig(CombatMode.NonCombat);
|
||||
r.S.SpellCastIntervalMs = 0;
|
||||
r.S.EmergencyHealAt = 30; r.S.HealAt = 60; r.S.TopOffHP = 60;
|
||||
r.V.CurrentHealth = 20;
|
||||
r.At(0); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "stance requested");
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
FakeHost.UseDoneSeq = 5;
|
||||
r.B.BusyCount = 1; // a live busy count: the vitals step doesn't run
|
||||
r.At(0.1); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "held by the busy count, but the heartbeat saw Magic");
|
||||
FakeHost.UseDone(0); // the server finished it: the count is a leftover now
|
||||
r.At(0.45); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "Magic seen at 0.1 s + 300 ms: Heal Self at 0.45 s (the old clock started at 0.45 s)");
|
||||
}
|
||||
|
||||
// 13:43:12.67 stance request, 13:43:13.10 the client reads Magic (ready at 13.67), 13:43:13.56 a
|
||||
// healing kit, 13:43:16.02 its UseDone, 13:43:16.77 Heal Self: "first cast 4097 ms after the
|
||||
// stance request". The stance had settled; the kit in flight (KitPending: its result line plus
|
||||
// a 700 ms grace) held the spell. The settle line now says when it was ready and what held it.
|
||||
private static void StanceLateHolderNamed()
|
||||
{
|
||||
var r = new Rig(CombatMode.NonCombat);
|
||||
r.S.SpellCastIntervalMs = 0;
|
||||
r.S.HealAt = 60; r.S.TopOffHP = 60;
|
||||
r.V.CurrentHealth = 50;
|
||||
r.At(0); r.B.OnHeartbeat();
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
r.At(0.4); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "settling");
|
||||
r.At(0.9); r.B.MarkKitUsed(); // a healing kit goes out during the wait
|
||||
r.At(1.2); r.B.OnHeartbeat();
|
||||
r.At(2.0); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "the kit in flight holds the spell past the stance's ready time");
|
||||
r.Chat("You heal yourself for 10 Health points.");
|
||||
System.Threading.Thread.Sleep(750); // the kit's grace runs on the real clock
|
||||
r.At(3.1); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "the kit landed: Heal Self goes");
|
||||
string? line = FakeHost.Logs.LastOrDefault(l => l.Contains("Magic stance settled", StringComparison.Ordinal));
|
||||
Check.NotNull(line, "the settle is logged");
|
||||
Check.True(line != null && line.Contains("first cast 3100 ms after the stance request")
|
||||
&& line.Contains("the stance was ready 1000 ms after the request and the cast then waited 2100 ms for: healing kit in flight"),
|
||||
$"and says the stance was ready at 1 s and the kit held the cast: {line}");
|
||||
}
|
||||
|
||||
private static void UrgentNudgeForHeal()
|
||||
{
|
||||
var r = new Rig();
|
||||
MoveAudit.Reset();
|
||||
r.S.HealAt = 60; r.S.TopOffHP = 60;
|
||||
r.V.CurrentHealth = 50;
|
||||
r.At(0); r.B.CheckVitals();
|
||||
Check.True(CastIs("Heal Self"), "50% health: Heal Self is cast");
|
||||
r.At(0.2); r.Incantation();
|
||||
r.At(2.7); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "2.5 s after the incantation (a healthy cast takes 2.2-2.5 s): no nudge");
|
||||
r.At(3.1); r.B.OnHeartbeat();
|
||||
Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "2.9 s with no result: one nudge, no refusal needed");
|
||||
Check.Eq(r.B.UrgentNudges, 1, "counted as an early nudge");
|
||||
Check.True(r.Logged("it is a heal: nudged at 2.8 s, not 6 s"), "the line says why it was early");
|
||||
r.At(4.0); r.Chat("You're too busy!");
|
||||
r.At(7.0); r.Chat("You're too busy!");
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 2, "still once per held cast");
|
||||
}
|
||||
|
||||
private static void UrgentNudgeForLowHealth()
|
||||
{
|
||||
// 20% health under Emergency Heal At, nothing that can heal: Stamina to Mana is what's held.
|
||||
var r = new Rig();
|
||||
r.S.EmergencyHealAt = 30;
|
||||
r.V.CurrentHealth = 20;
|
||||
r.At(0); r.B.CheckVitals();
|
||||
Check.True(CastIs("Stamina to Mana Self"), "Stamina to Mana is cast");
|
||||
r.At(0.3); r.Incantation();
|
||||
r.At(3.2); r.B.OnHeartbeat();
|
||||
Check.True(FakeHost.AutoRunCalls.SequenceEqual(new[] { true, false }), "held 2.9 s while health is critical: nudged");
|
||||
Check.True(r.Logged("health 20% is under a heal line"), "and says why");
|
||||
|
||||
// Health fine: the 6 s rule (on a refusal) as before.
|
||||
var q = new Rig();
|
||||
q.At(0); q.B.CheckVitals();
|
||||
q.At(0.3); q.Incantation();
|
||||
q.At(3.2); q.B.OnHeartbeat();
|
||||
q.At(5.0); q.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "health fine: no early nudge");
|
||||
}
|
||||
|
||||
// ACE refuses a kit or potion while the player is busy, and every kit Drakkon used while a
|
||||
// Heal Self was held open came back 0x1D.
|
||||
private static void HeldCastItemGate()
|
||||
{
|
||||
var r = new Rig();
|
||||
r.At(0); r.B.CheckVitals();
|
||||
string name = r.CastName;
|
||||
r.At(0.3); r.Incantation();
|
||||
r.At(2.0);
|
||||
Check.False(r.B.HeldCastBlocksItemUse(out _), "inside the normal result window: no gate (the vital is still pending)");
|
||||
r.At(3.5);
|
||||
Check.True(r.B.HeldCastBlocksItemUse(out string why), "held 3.2 s, not nudged yet: no kit or potion");
|
||||
Check.True(why.Contains("nudge first"), $"why: {why}");
|
||||
r.At(6.5); r.Chat("You're too busy!");
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 2, "the refusal at 6.2 s nudges it");
|
||||
r.At(6.6);
|
||||
Check.False(r.B.HeldCastBlocksItemUse(out _), "after the nudge: one kit or potion try");
|
||||
r.At(7.0);
|
||||
Check.True(r.B.HeldCastBlocksItemUse(out why), "the next try waits");
|
||||
Check.True(why.Contains("next kit/potion try in"), $"why: {why}");
|
||||
r.At(9.7);
|
||||
Check.False(r.B.HeldCastBlocksItemUse(out _), "3 s later: another try");
|
||||
r.At(10.0); r.Chat($"You cast {name} on yourself and lose 35 points of stamina and also gain 47 points of mana");
|
||||
Check.False(r.B.HeldCastBlocksItemUse(out _), "the cast resolved: no gate");
|
||||
Check.Eq(r.B.HeldItemSkips, 2, "two attempts skipped");
|
||||
}
|
||||
|
||||
private static void MoveAuditLines()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var host = FakeHost.Create();
|
||||
UseAudit.Reset("RynthAi", null);
|
||||
MoveAudit.Reset();
|
||||
long now = 1000;
|
||||
var oldClock = MoveAudit.NowMs;
|
||||
MoveAudit.NowMs = () => now;
|
||||
try
|
||||
{
|
||||
host.SetAutoRunBy("Nav", true);
|
||||
host.SetAutoRunBy("Nav", true); // a repeat 0 ms later: counted
|
||||
now += 100;
|
||||
host.TurnToHeadingBy("Nav", 10f);
|
||||
now += 30; host.TurnToHeadingBy("Nav", 12f);
|
||||
now += 30; host.TurnToHeadingBy("Nav", 14f);
|
||||
now += 30; host.SetAutoRunBy("Meta", false);
|
||||
var lines = FakeHost.Logs.Where(l => l.StartsWith("[Move]", StringComparison.Ordinal)).ToList();
|
||||
Check.Eq(lines.Count, 3, "three lines: autorun, the first turn (carrying the autorun repeat), the meta stop (carrying the turns)");
|
||||
if (lines.Count == 3)
|
||||
{
|
||||
Check.Eq(lines[0], "[Move] RynthAi/Nav SetAutoRun(True)", "plugin/subsystem and the call");
|
||||
Check.True(lines[1].StartsWith("[Move] RynthAi/Nav TurnToHeading(10.0) (+1 more SetAutoRun(True)", StringComparison.Ordinal), $"the repeat is counted: {lines[1]}");
|
||||
Check.True(lines[2].StartsWith("[Move] RynthAi/Meta SetAutoRun(False) (+2 more TurnToHeading, last 14.0", StringComparison.Ordinal), $"turns collapse whatever the angle: {lines[2]}");
|
||||
}
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 3, "every call still reaches the engine");
|
||||
Check.Eq(FakeHost.Turns, 3, "every turn still reaches the engine");
|
||||
|
||||
now += 2000; host.SetAutoRunBy("Meta", false);
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.StartsWith("[Move]", StringComparison.Ordinal)), 4, "the same call after the 1 s window gets its own line");
|
||||
}
|
||||
finally { MoveAudit.NowMs = oldClock; }
|
||||
}
|
||||
}
|
||||
217
Tools/RynthCore.RynthAiHostTests/Tests/DungeonMapBakeTests.cs
Normal file
217
Tools/RynthCore.RynthAiHostTests/Tests/DungeonMapBakeTests.cs
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Maps;
|
||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Dungeon floor-plan bake (2026-10-05): RynthAi writes <landblock>_<layer>.bin floor plans for
|
||||
// the StatusAgent's /map (DrakRemote's dungeon map). The bake was the disk half of the old
|
||||
// DungeonMapTexture, deleted with the D3D9 textures on 2026-09-30 (f78392b); this is it back,
|
||||
// disk only. The plans already in C:\Games\RynthSuite\RynthAi\Maps are READ here, never
|
||||
// written: every bake in these tests goes to the scratch folder.
|
||||
internal static class DungeonMapBakeTests
|
||||
{
|
||||
private const string AcDir = @"C:\Turbine\Asheron's Call";
|
||||
private const string LiveMaps = @"C:\Games\RynthSuite\RynthAi\Maps";
|
||||
private const uint Matron = 0x6346; // Matron Hive South (PatrolProof / LosProof fixtures)
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("map bake: file format is the StatusAgent's (header, ARGB pixels, north row first)", Format);
|
||||
r.Add("map bake: same bytes are not rewritten, changed bytes are, no temp files left", NoChurn);
|
||||
r.Add("map bake: file names use the short landblock id", Names);
|
||||
r.Add("map bake: 0x6346 from the real dats matches the plan already on disk (if dats and plan are here)", MatchesExisting6346);
|
||||
r.Add("map bake: the plans already on disk keep their names, most byte for byte (if the dats are here)", MatchesAllExisting);
|
||||
}
|
||||
|
||||
private static string Dir(string name)
|
||||
{
|
||||
string d = Path.Combine(Program.TempRoot, "mapbake", name);
|
||||
Directory.CreateDirectory(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
private static void Format()
|
||||
{
|
||||
// A 3x2 block of flat cells at gx 10..12, gy 4..5 plus one ramp cell north of it.
|
||||
var cells = new Dictionary<(int, int), DungeonMapUi.CellType>();
|
||||
for (int gx = 10; gx <= 12; gx++)
|
||||
for (int gy = 4; gy <= 5; gy++)
|
||||
cells[(gx, gy)] = DungeonMapUi.CellType.Flat;
|
||||
cells[(11, 6)] = DungeonMapUi.CellType.SlopeUp;
|
||||
|
||||
byte[]? bytes = DungeonMapBake.BuildFile(cells);
|
||||
Check.NotNull(bytes, "built");
|
||||
if (bytes is null) return;
|
||||
int w = 3, h = 3;
|
||||
Check.Eq(bytes.Length, 20 + w * h * 4, "length = header + w*h*4");
|
||||
Check.Eq(BitConverter.ToUInt32(bytes, 0), 0x524D5458u, "magic XTMR");
|
||||
Check.Eq(BitConverter.ToInt32(bytes, 4), 10, "xMin");
|
||||
Check.Eq(BitConverter.ToInt32(bytes, 8), 4, "yMin");
|
||||
Check.Eq(BitConverter.ToInt32(bytes, 12), w, "w");
|
||||
Check.Eq(BitConverter.ToInt32(bytes, 16), h, "h");
|
||||
|
||||
uint Px(int col, int row) => BitConverter.ToUInt32(bytes, 20 + (row * w + col) * 4);
|
||||
// Row 0 is the northernmost row (gy 6): only the ramp cell at gx 11, an edge cell.
|
||||
Check.Eq(Px(0, 0), 0u, "empty cell is transparent");
|
||||
Check.Eq(Px(1, 0) >> 24, 255u, "edge cell is opaque");
|
||||
Check.Eq((Px(1, 0) >> 16) & 0xFF, 255u, "ramp-up edge is red");
|
||||
// Row 1 (gy 5): (11,5) has neighbours on all four sides, so it is the translucent fill.
|
||||
Check.Eq(Px(1, 1) >> 24, (uint)(0.40f * 255f), "interior cell is the translucent fill");
|
||||
Check.Eq(Px(0, 1) >> 24, 255u, "border cell is an edge");
|
||||
// Row 2 (gy 4): southern edge.
|
||||
Check.Eq(Px(2, 2) >> 24, 255u, "south-east corner is an edge");
|
||||
}
|
||||
|
||||
private static void NoChurn()
|
||||
{
|
||||
string dir = Dir("churn");
|
||||
var cells = new Dictionary<(int, int), DungeonMapUi.CellType> { [(0, 0)] = DungeonMapUi.CellType.Flat, [(1, 0)] = DungeonMapUi.CellType.Flat };
|
||||
byte[] a = DungeonMapBake.BuildFile(cells)!;
|
||||
string path = Path.Combine(dir, "00001234_2.bin");
|
||||
|
||||
Check.Eq(DungeonMapBake.SaveToDisk(dir, 0x1234, 2, a), DungeonMapBake.SaveResult.Written, "first save writes");
|
||||
Check.True(File.ReadAllBytes(path).AsSpan().SequenceEqual(a), "file holds the bytes");
|
||||
var past = new DateTime(2026, 5, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
File.SetLastWriteTimeUtc(path, past);
|
||||
|
||||
Check.Eq(DungeonMapBake.SaveToDisk(dir, 0x1234, 2, a), DungeonMapBake.SaveResult.Unchanged, "same bytes: unchanged");
|
||||
Check.Eq(File.GetLastWriteTimeUtc(path), past, "same bytes: file not touched (mtime kept, so the agent's ETag holds)");
|
||||
|
||||
cells[(2, 0)] = DungeonMapUi.CellType.SlopeDown;
|
||||
byte[] b = DungeonMapBake.BuildFile(cells)!;
|
||||
Check.Eq(DungeonMapBake.SaveToDisk(dir, 0x1234, 2, b), DungeonMapBake.SaveResult.Written, "changed bytes: written");
|
||||
Check.True(File.ReadAllBytes(path).AsSpan().SequenceEqual(b), "file holds the new bytes");
|
||||
Check.Eq(Directory.GetFiles(dir).Length, 1, "no temp files left: " + string.Join(", ", Directory.GetFiles(dir).Select(Path.GetFileName)));
|
||||
|
||||
// A reader holding the file open the way the agent does (ReadWrite share, no Delete)
|
||||
// makes the replace fail; the save must not throw or leave a temp file.
|
||||
cells[(3, 0)] = DungeonMapUi.CellType.Flat;
|
||||
byte[] c = DungeonMapBake.BuildFile(cells)!;
|
||||
DungeonMapBake.SaveResult held;
|
||||
using (new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
held = DungeonMapBake.SaveToDisk(dir, 0x1234, 2, c);
|
||||
Console.WriteLine($" save while the agent holds the file open: {held}");
|
||||
Check.Eq(Directory.GetFiles(dir).Length, 1, "no temp files left after a held file");
|
||||
Check.Eq(DungeonMapBake.SaveToDisk(dir, 0x1234, 2, c), DungeonMapBake.SaveResult.Written, "written once released");
|
||||
}
|
||||
|
||||
private static void Names()
|
||||
{
|
||||
Check.Eq(DungeonMapBake.FileName(0x6346, 1), "00006346_1.bin", "short id");
|
||||
Check.Eq(DungeonMapBake.FileName(0x63460000, 1), "00006346_1.bin", "long id is shortened");
|
||||
Check.Eq(DungeonMapBake.FileName(0x002B, 10), "0000002B_10.bin", "two-digit layer");
|
||||
Check.Eq(DungeonMapBake.ShortLandblock(0x63460000), 0x6346u, "ShortLandblock");
|
||||
}
|
||||
|
||||
private static GeometryLoader? _geo;
|
||||
private static bool _geoTried;
|
||||
|
||||
private static DungeonLOS? Los()
|
||||
{
|
||||
if (!_geoTried)
|
||||
{
|
||||
_geoTried = true;
|
||||
if (Directory.Exists(AcDir))
|
||||
{
|
||||
var g = new GeometryLoader();
|
||||
if (g.Initialize(AcDir)) _geo = g;
|
||||
else Console.WriteLine(" geometry loader failed: " + g.StatusMessage);
|
||||
}
|
||||
}
|
||||
return _geo?.DungeonLOS;
|
||||
}
|
||||
|
||||
/// <summary>Bake one landblock into a scratch folder and compare each layer with the live plan.</summary>
|
||||
private static (int Same, int Differ, int OnlyNew, int OnlyLive, List<string> Notes) Compare(DungeonLOS los, uint lb, string outDir)
|
||||
{
|
||||
var notes = new List<string>();
|
||||
var (zLayers, cells) = DungeonMapUi.BuildFloorCells(los, lb);
|
||||
DungeonMapBake.BakeLayers(outDir, lb, zLayers, cells);
|
||||
string prefix = $"{lb:X8}_";
|
||||
var baked = Directory.GetFiles(outDir, prefix + "*.bin").Select(Path.GetFileName).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var live = Directory.Exists(LiveMaps)
|
||||
? Directory.GetFiles(LiveMaps, prefix + "*.bin").Select(Path.GetFileName).ToHashSet(StringComparer.OrdinalIgnoreCase)
|
||||
: new HashSet<string?>();
|
||||
int same = 0, differ = 0, onlyNew = 0, onlyLive = 0;
|
||||
foreach (string? name in baked.Union(live).OrderBy(n => n))
|
||||
{
|
||||
if (name is null) continue;
|
||||
bool inNew = baked.Contains(name), inLive = live.Contains(name);
|
||||
if (inNew && !inLive) { onlyNew++; notes.Add($"{name}: new (no live plan)"); continue; }
|
||||
if (!inNew) { onlyLive++; notes.Add($"{name}: live plan has no new counterpart"); continue; }
|
||||
byte[] n = File.ReadAllBytes(Path.Combine(outDir, name));
|
||||
byte[] l = File.ReadAllBytes(Path.Combine(LiveMaps, name));
|
||||
if (n.AsSpan().SequenceEqual(l)) { same++; continue; }
|
||||
differ++;
|
||||
notes.Add($"{name}: differs - new {Header(n)} vs live {Header(l)}, {DiffPixels(n, l)}");
|
||||
}
|
||||
return (same, differ, onlyNew, onlyLive, notes);
|
||||
}
|
||||
|
||||
private static string Header(byte[] b) => b.Length < 20 ? $"({b.Length} bytes)"
|
||||
: $"x{BitConverter.ToInt32(b, 4)} y{BitConverter.ToInt32(b, 8)} {BitConverter.ToInt32(b, 12)}x{BitConverter.ToInt32(b, 16)}";
|
||||
|
||||
private static string DiffPixels(byte[] a, byte[] b)
|
||||
{
|
||||
if (a.Length != b.Length || a.Length < 20 || a.AsSpan(4, 16).SequenceEqual(b.AsSpan(4, 16)) == false) return "different bounds";
|
||||
int diff = 0, total = (a.Length - 20) / 4;
|
||||
for (int i = 20; i < a.Length; i += 4)
|
||||
if (BitConverter.ToUInt32(a, i) != BitConverter.ToUInt32(b, i)) diff++;
|
||||
return $"{diff} of {total} pixels differ";
|
||||
}
|
||||
|
||||
private static void MatchesExisting6346()
|
||||
{
|
||||
var los = Los();
|
||||
if (los is null) { Console.WriteLine(" skipped: no dats at " + AcDir); return; }
|
||||
if (!File.Exists(Path.Combine(LiveMaps, DungeonMapBake.FileName(Matron, 0))))
|
||||
{ Console.WriteLine(" skipped: no live plan for 0x6346"); return; }
|
||||
var (same, differ, onlyNew, onlyLive, notes) = Compare(los, Matron, Dir("6346"));
|
||||
Console.WriteLine($" 0x6346: {same} identical, {differ} differ, {onlyNew} new only, {onlyLive} live only");
|
||||
foreach (string n in notes) Console.WriteLine(" " + n);
|
||||
Check.True(same > 0, "some layers baked");
|
||||
Check.Eq(differ + onlyNew + onlyLive, 0, "every 0x6346 layer is byte-identical to the live plan");
|
||||
}
|
||||
|
||||
private static void MatchesAllExisting()
|
||||
{
|
||||
var los = Los();
|
||||
if (los is null) { Console.WriteLine(" skipped: no dats at " + AcDir); return; }
|
||||
if (!Directory.Exists(LiveMaps)) { Console.WriteLine(" skipped: no live maps folder"); return; }
|
||||
var rx = new Regex(@"^([0-9A-Fa-f]{8})_(\d+)\.bin$");
|
||||
var lbs = Directory.GetFiles(LiveMaps, "*.bin")
|
||||
.Select(f => rx.Match(Path.GetFileName(f)))
|
||||
.Where(m => m.Success)
|
||||
.Select(m => Convert.ToUInt32(m.Groups[1].Value, 16))
|
||||
.Distinct().OrderBy(x => x).ToList();
|
||||
string outDir = Dir("all");
|
||||
int same = 0, differ = 0, onlyNew = 0, onlyLive = 0;
|
||||
foreach (uint lb in lbs)
|
||||
{
|
||||
var c = Compare(los, lb, outDir);
|
||||
same += c.Same; differ += c.Differ; onlyNew += c.OnlyNew; onlyLive += c.OnlyLive;
|
||||
if (c.Notes.Count > 0)
|
||||
{
|
||||
Console.WriteLine($" 0x{lb:X4}: {c.Same} identical, {c.Differ} differ, {c.OnlyNew} new only, {c.OnlyLive} live only");
|
||||
foreach (string n in c.Notes) Console.WriteLine(" " + n);
|
||||
}
|
||||
}
|
||||
Console.WriteLine($" {lbs.Count} landblocks: {same} plans identical, {differ} differ, {onlyNew} new only, {onlyLive} live only");
|
||||
// 2026-10-05: 59 of the 81 plans baked May-June are identical; 22 differ by a few
|
||||
// pixels (or a few cells of bounds) because the floor rasteriser has changed since
|
||||
// they were baked. Those 22 are refreshed once, on the next visit, to what the radar
|
||||
// draws today; the identical ones are left alone. What must hold: the layer numbering
|
||||
// is unchanged (every live plan has a counterpart under the same name), the header
|
||||
// format is the same, and most plans come out identical.
|
||||
Check.Eq(onlyLive, 0, "every live plan has a counterpart under the same file name (layer numbering unchanged)");
|
||||
Check.Eq(onlyNew, 0, "no extra layers compared with the live plans");
|
||||
Check.True(same > differ, $"most live plans are reproduced byte for byte ({same} identical, {differ} differ)");
|
||||
}
|
||||
}
|
||||
121
Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs
Normal file
121
Tools/RynthCore.RynthAiHostTests/Tests/GiveTests.cs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// /ub give and /mt give (Tom, 2026-10-05): "/ub give ... should give every item that matches the
|
||||
// name in the inventory. /mt give should give the first one it finds." Both use AC's give action
|
||||
// (an NPC ignores MoveItemExternal) and never hand over worn or wielded gear.
|
||||
internal static class GiveTests
|
||||
{
|
||||
private const uint Player = 0x50000F01;
|
||||
private const uint Npc = 0x80281000;
|
||||
private const uint Mote1 = 0x80281101, Mote2 = 0x80281102, Mote3 = 0x80281103, WornMote = 0x80281104, Other = 0x80281105;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("give: /ub give hands over every matching carried item, never worn gear", UbGivesAll);
|
||||
r.Add("give: /ub give with a count hands over that many", UbGiveCount);
|
||||
r.Add("give: /mt give hands over only the first match", MtGivesFirst);
|
||||
r.Add("give: /ub givep matches part of the name", UbGivePartial);
|
||||
}
|
||||
|
||||
private sealed class World
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new() { GiveQueueIntervalMs = 0 };
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public World()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // MoveItemExternal + GetObjectWielderInfo (Wielded)
|
||||
FakeHost.GiveCalls = true;
|
||||
FakeHost.Names[Player] = "Giver";
|
||||
FakeHost.PlayerIdValue = Player;
|
||||
FakeHost.Names[Npc] = "Town Crier";
|
||||
FakeHost.Positions[Npc] = (0x1048002Au, 101f, 100f, 0f);
|
||||
FakeHost.ItemTypes[Npc] = 0x10; // a creature (an NPC)
|
||||
FakeHost.NotAttackable.Add(Npc);
|
||||
FakeHost.Positions[Player] = (0x1048002Au, 100f, 100f, 0f);
|
||||
FakeHost.PlayerPose = (0x1048002Au, 100f, 100f, 0f);
|
||||
foreach (var (id, name) in new[] { (Mote1, "Mana Mote"), (Mote2, "Mana Mote"), (Mote3, "Mana Mote"), (WornMote, "Mana Mote"), (Other, "Lesser Mana Mote") })
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Containers[id] = Player;
|
||||
FakeHost.ItemTypes[id] = 0x80; // misc
|
||||
}
|
||||
FakeHost.Wielded[WornMote] = 0x8000; // worn: never given
|
||||
var host = FakeHost.Create(playerId: Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
foreach (uint id in new[] { Npc, Mote1, Mote2, Mote3, WornMote, Other }) Cache.OnCreateObject(id);
|
||||
Cache.Tick();
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public object? Call(string m, params object?[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
|
||||
|
||||
/// <summary>Runs the chat command, then drains the give queue.</summary>
|
||||
public void Run(string command)
|
||||
{
|
||||
if (command.StartsWith("/ub", StringComparison.Ordinal)) Call("HandleUbCommand", command);
|
||||
else Call("HandleMtCommand", command);
|
||||
for (int i = 0; i < 20; i++) Call("DrainGiveQueue");
|
||||
}
|
||||
|
||||
public uint[] GivenItems => FakeHost.Gives.Select(g => g.Item).ToArray();
|
||||
}
|
||||
|
||||
private static void UbGivesAll()
|
||||
{
|
||||
var w = new World();
|
||||
w.Run("/ub give Mana Mote to Town Crier");
|
||||
Check.Eq(FakeHost.Gives.Count, 3, "all three carried Mana Motes");
|
||||
Check.True(new[] { Mote1, Mote2, Mote3 }.All(id => w.GivenItems.Contains(id)), "each of them");
|
||||
Check.False(w.GivenItems.Contains(WornMote), "the worn one stays on");
|
||||
Check.False(w.GivenItems.Contains(Other), "an exact name doesn't take 'Lesser Mana Mote'");
|
||||
Check.True(FakeHost.Gives.All(g => g.Target == Npc), "all to the NPC, with AC's give action");
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 0, "never MoveItemExternal (an NPC ignores it)");
|
||||
}
|
||||
|
||||
private static void UbGiveCount()
|
||||
{
|
||||
var w = new World();
|
||||
w.Run("/ub give 2 Mana Mote to Town Crier");
|
||||
Check.Eq(FakeHost.Gives.Count, 2, "a count gives that many");
|
||||
}
|
||||
|
||||
private static void MtGivesFirst()
|
||||
{
|
||||
var w = new World();
|
||||
w.Run("/mt give Mana Mote to Town Crier");
|
||||
Check.Eq(FakeHost.Gives.Count, 1, "/mt give: one item");
|
||||
Check.False(w.GivenItems.Contains(WornMote), "and never the worn one");
|
||||
}
|
||||
|
||||
private static void UbGivePartial()
|
||||
{
|
||||
var w = new World();
|
||||
w.Run("/ub givep Mana Mote to Town");
|
||||
Check.Eq(FakeHost.Gives.Count, 4, "partial: the three Mana Motes and the Lesser Mana Mote");
|
||||
Check.False(w.GivenItems.Contains(WornMote), "still not the worn one");
|
||||
}
|
||||
}
|
||||
331
Tools/RynthCore.RynthAiHostTests/Tests/HealLatencyTests.cs
Normal file
331
Tools/RynthCore.RynthAiHostTests/Tests/HealLatencyTests.cs
Normal file
|
|
@ -0,0 +1,331 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Heal latency (2026-10-05): a mage's heals "sometimes fine, sometimes several seconds late".
|
||||
// - A war cast's busy count is a leftover once the server's UseDone arrives (AC lowers its own
|
||||
// count inline, unseen), and only combat cleared it. With health under a line the arbiter
|
||||
// hands the tick to vitals, combat stops running, and the heal waited for the 5 s force-clear.
|
||||
// - A healing kit the server refused (too busy, in the air) never gets a result line, so every
|
||||
// vital waited the kit's 8 s result timeout.
|
||||
// - [HealLatency] logs each episode's delay and what held it.
|
||||
// - The activity display says Healing / Restoring mana / Restoring stamina, not "Buffing".
|
||||
internal static class HealLatencyTests
|
||||
{
|
||||
private const uint Player = 0x50000B01;
|
||||
private const uint STypeLife = 33;
|
||||
private const uint TooBusy = 0x1D;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("heal latency: a heal goes ahead of a leftover busy count (a war cast the server finished)", HealBeatsLeftoverBusy);
|
||||
r.Add("heal latency: a live busy count still holds the heal; a leftover doesn't free buffs or mana", LiveBusyStillHolds);
|
||||
r.Add("heal latency: a refused kit ends the kit wait (UseDone error or 'too busy'), Heal Self goes next", KitRefusalEndsWait);
|
||||
r.Add("heal latency: Heal Self refused for mana rests 2 s, not the 15 s a buff rests", LowManaHealRest);
|
||||
r.Add("heal latency: [HealLatency] logs delay, line and blockers per episode, and a summary", TrackerLines);
|
||||
r.Add("heal latency: the heartbeat files a held heal under its blocker", HeartbeatLogsEpisode);
|
||||
r.Add("activity label: the Buffing slot shows Healing / Restoring mana / Buffing; control string unchanged", ActivityLabels);
|
||||
r.Add("heal latency: an emergency heal goes out during the login buff refresh; buffs still wait for it", EmergencyBeatsLoginRefresh);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public DateTime T0 = new(2026, 10, 5, 21, 0, 0);
|
||||
public DateTime NowAt;
|
||||
public readonly BuffManager B;
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly PlayerVitalsCache V;
|
||||
public readonly List<string> StaleResets = new();
|
||||
|
||||
public Rig(int healthPct = 40, int manaPct = 100, bool lastUseDone = true, bool liveBuffsReady = true)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.ServerGates = true;
|
||||
FakeHost.LastUseDoneCalls = lastUseDone;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
|
||||
var host = FakeHost.Create();
|
||||
// No combat manager here, so the idle line applies: Heal At = Top Off HP = 60.
|
||||
S = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false,
|
||||
EnableBuffing = false,
|
||||
};
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, S);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
V = new PlayerVitalsCache
|
||||
{
|
||||
MaxHealth = 100, CurrentHealth = (uint)healthPct, MaxStamina = 100, CurrentStamina = 100,
|
||||
MaxMana = 100, CurrentMana = (uint)manaPct,
|
||||
};
|
||||
B = new BuffManager(host, S, sm, V);
|
||||
B.SetCharacterSkills(skills);
|
||||
B.SetStaleBusyCallback(why => StaleResets.Add(why));
|
||||
NowAt = T0;
|
||||
B.Clock = () => NowAt;
|
||||
if (liveBuffsReady) B.MarkLiveBuffsReadyForTests();
|
||||
}
|
||||
|
||||
public void At(double seconds) => NowAt = T0.AddSeconds(seconds);
|
||||
public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
|
||||
public string? Log(string part) => FakeHost.Logs.LastOrDefault(l => l.Contains(part, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
// Heal Self at any tier (skill 400 casts a high tier with its own name): same category as Heal Self I.
|
||||
private static int HealSelfCasts()
|
||||
{
|
||||
int cat = SpellTable.Named("Heal Self I").First().Category;
|
||||
return FakeHost.Casts.Count(c => SpellTable.ById(c.SpellId)?.Category == cat);
|
||||
}
|
||||
|
||||
// The mage's case: a war cast went out (busy 0 -> 1 at UseDone #5), the server finished it
|
||||
// (UseDone #6, AC lowered its own count unseen), and health dropped under Heal At. Before the
|
||||
// fix the heal waited at BusyCount > 0 until CheckBusyTimeout's 5 s force-clear.
|
||||
private static void HealBeatsLeftoverBusy()
|
||||
{
|
||||
var r = new Rig(healthPct: 40);
|
||||
FakeHost.UseDoneSeq = 5;
|
||||
r.B.BusyCount = 1; // the war cast's increment
|
||||
FakeHost.UseDone(0); // the server finished it; nothing decrements the plugin's count
|
||||
r.At(0.1);
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(HealSelfCasts(), 1, "Heal Self goes out on the first heartbeat, not after the 5 s force-clear");
|
||||
Check.Eq(r.B.StaleBusyClears, 1, "the leftover was cleared once");
|
||||
Check.Eq(r.B.BusyCount, 0, "and the shared mirror is 0");
|
||||
Check.Eq(r.StaleResets.Count, 1, "through the same callback combat uses");
|
||||
Check.True(r.StaleResets[0].StartsWith("vitals:", StringComparison.Ordinal), "the reason says it was the heal");
|
||||
}
|
||||
|
||||
private static void LiveBusyStillHolds()
|
||||
{
|
||||
// A count with no UseDone since it rose is real (a swing, a cast still on the server).
|
||||
var r = new Rig(healthPct: 40);
|
||||
FakeHost.UseDoneSeq = 5;
|
||||
r.B.BusyCount = 1;
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no UseDone since the count rose: the heal waits");
|
||||
Check.Eq(r.B.StaleBusyClears, 0, "nothing cleared");
|
||||
|
||||
// A gesture still animating: real too, even after a UseDone.
|
||||
FakeHost.UseDone(0);
|
||||
FakeHost.CastBusy = 1;
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "a cast gesture animating: the heal waits");
|
||||
FakeHost.CastBusy = 0;
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(HealSelfCasts(), 1, "gesture done, UseDone seen: the heal goes");
|
||||
|
||||
// Health fine, mana low: the leftover rule is for heals only, so Stamina to Mana still waits.
|
||||
var m = new Rig(healthPct: 100, manaPct: 10);
|
||||
m.S.GetManaAt = 50; m.S.TopOffMana = 50;
|
||||
FakeHost.UseDoneSeq = 5;
|
||||
m.B.BusyCount = 1;
|
||||
FakeHost.UseDone(0);
|
||||
m.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no heal wanted: a leftover count still holds mana and buffs");
|
||||
Check.Eq(m.B.BusyCount, 1, "and is left for combat / the watchdog");
|
||||
}
|
||||
|
||||
// ACE Healer.cs answers a kit used while busy with UseDone(YoureTooBusy) and no chat result.
|
||||
private static void KitRefusalEndsWait()
|
||||
{
|
||||
// UseDone error.
|
||||
var r = new Rig(healthPct: 40);
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
r.B.MarkKitUsed();
|
||||
Check.True(r.B.KitPending(), "kit just used: waiting for its result");
|
||||
FakeHost.UseDone(TooBusy);
|
||||
Check.False(r.B.KitPending(), "a UseDone error after the kit: refused, no 8 s wait");
|
||||
Check.Eq(r.B.KitRefusals, 1, "counted");
|
||||
Check.True(r.Logged("kit was refused") && r.Logged("UseDone error 0x1D"), "and logged with the error");
|
||||
Check.True(r.B.CheckVitals(), "vitals carry on at once");
|
||||
Check.Eq(HealSelfCasts(), 1, "Heal Self is cast (the kit waits a second after a refusal)");
|
||||
|
||||
// UseDone(0) after the kit is not a refusal: the kit is still healing.
|
||||
var ok = new Rig(healthPct: 40);
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
ok.B.MarkKitUsed();
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(ok.B.KitPending(), "UseDone(0): no refusal, still waiting for the result line");
|
||||
Check.Eq(ok.B.KitRefusals, 0, "not counted");
|
||||
|
||||
// No GetLastUseDone on this engine: the "too busy" line ends it.
|
||||
var c = new Rig(healthPct: 40, lastUseDone: false);
|
||||
c.B.MarkKitUsed();
|
||||
c.B.OnChatWindowText("You're too busy!", 26);
|
||||
Check.False(c.B.KitPending(), "'You're too busy!' right after the kit: refused");
|
||||
Check.Eq(c.B.KitRefusals, 1, "counted");
|
||||
|
||||
// A result line first: a later "too busy" (something else refused) doesn't cut the grace.
|
||||
var g = new Rig(healthPct: 40, lastUseDone: false);
|
||||
g.B.MarkKitUsed();
|
||||
g.B.OnChatWindowText("You heal yourself for 52 Health points.", 0);
|
||||
g.B.OnChatWindowText("You're too busy!", 26);
|
||||
Check.True(g.B.KitPending(), "result seen: the grace for the vitals still runs");
|
||||
Check.Eq(g.B.KitRefusals, 0, "no refusal counted");
|
||||
}
|
||||
|
||||
// A mage out of mana mid-fight: "You don't have enough Mana" parked Heal Self for 15 s, so after
|
||||
// Stamina to Mana refilled it 2-3 s later the mage still couldn't heal for 12 s more.
|
||||
private static void LowManaHealRest()
|
||||
{
|
||||
var r = new Rig(healthPct: 40, manaPct: 2);
|
||||
r.S.GetManaAt = 50; r.S.TopOffMana = 50;
|
||||
Check.True(r.B.CheckVitals(), "40% health: Heal Self is cast");
|
||||
Check.Eq(HealSelfCasts(), 1, "one Heal Self");
|
||||
r.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 0);
|
||||
Check.True(r.Logged("not enough mana; resting the family 2s"), "Heal Self rests 2 s");
|
||||
Check.Eq(r.B.PendingSpellId, 0, "pending cleared");
|
||||
Check.True(r.B.CheckVitals(), "next check: something is done");
|
||||
Check.Eq(HealSelfCasts(), 1, "not Heal Self inside the rest...");
|
||||
Check.Eq(FakeHost.Casts.Count, 2, "...but Stamina to Mana, so the mana comes back");
|
||||
Check.Eq(r.B.BuffingLabel, "Restoring mana", "and the slot reads Restoring mana");
|
||||
r.B.OnChatWindowText("You don't have enough Mana to cast this spell.", 0);
|
||||
Check.True(r.Logged("not enough mana; resting the family 15s"), "a non-heal still rests 15 s");
|
||||
System.Threading.Thread.Sleep(2100);
|
||||
r.V.CurrentMana = 60;
|
||||
Check.True(r.B.CheckVitals(), "2 s later, mana back");
|
||||
Check.Eq(HealSelfCasts(), 2, "Heal Self is cast again");
|
||||
}
|
||||
|
||||
private static void TrackerLines()
|
||||
{
|
||||
var logs = new List<string>();
|
||||
var t = new HealLatencyTracker(logs.Add);
|
||||
DateTime t0 = new(2026, 10, 5, 21, 0, 0);
|
||||
DateTime At(double s) => t0.AddSeconds(s);
|
||||
|
||||
t.Observe(At(0), 41, "Heal At", 60, inCombat: true, healInFlight: false);
|
||||
for (int i = 1; i <= 30; i++)
|
||||
t.EndTick(At(i * 0.1), i <= 28 ? "busy count" : "cast gate (a gesture is animating)", "busy 1", "Buffing");
|
||||
t.HealSent(At(3.1), "Heal Self");
|
||||
string line = logs.Last();
|
||||
Check.True(line.StartsWith("[HealLatency] 3100 ms: health 41% under Heal At 60% (in combat) -> Heal Self", StringComparison.Ordinal), $"episode line: {line}");
|
||||
Check.True(line.Contains("busy count 2800 ms") && line.Contains("cast gate (a gesture is animating) 200 ms"), "blockers with their time, biggest first");
|
||||
Check.Eq(t.Episodes, 1, "one episode");
|
||||
|
||||
// Still under the line: the next episode opens only once the heal has resolved.
|
||||
t.Observe(At(3.2), 45, "Heal At", 60, true, healInFlight: true);
|
||||
Check.False(t.IsOpen, "heal in flight: no new episode yet");
|
||||
t.Observe(At(5.5), 45, "Heal At", 60, true, healInFlight: false);
|
||||
Check.True(t.IsOpen, "resolved and still under: a follow-up episode");
|
||||
t.EndTick(At(5.6), "cast interval", "", "Combat");
|
||||
t.HealSent(At(5.9), "Heal Self");
|
||||
Check.True(logs.Last().Contains("400 ms") && logs.Last().Contains("(follow-up)") && logs.Last().Contains("arbiter gave the tick to Combat 100 ms"),
|
||||
$"follow-up measured from when it became possible: {logs.Last()}");
|
||||
|
||||
// Over the line with no heal: logged when it lasted a second or more.
|
||||
t.Observe(At(6), 80, "", 0, true, false);
|
||||
t.Observe(At(7), 55, "Top Off HP", 95, false, false);
|
||||
t.Observe(At(7.5), 96, "", 0, false, false);
|
||||
Check.False(logs.Last().Contains("no heal"), "a half-second dip isn't logged");
|
||||
t.Observe(At(8), 55, "Top Off HP", 95, false, false);
|
||||
t.EndTick(At(8.5), "nothing could heal", "kit: no healing kit", "Navigating");
|
||||
t.Observe(At(9.5), 96, "", 0, false, false);
|
||||
Check.True(logs.Last().StartsWith("[HealLatency] no heal in 1500 ms", StringComparison.Ordinal) && logs.Last().Contains("nothing could heal"),
|
||||
$"a 1.5 s episode with no heal is: {logs.Last()}");
|
||||
|
||||
// Summary every 10 heals.
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
double s0 = 20 + i * 10;
|
||||
t.Observe(At(s0), 50, "Heal At", 60, true, false);
|
||||
t.EndTick(At(s0 + 0.5), "busy count", "", "Buffing");
|
||||
t.HealSent(At(s0 + 0.5), "Heal Self");
|
||||
}
|
||||
string sum = logs.Last();
|
||||
Check.True(sum.StartsWith("[HealLatency] summary of 10 heals:", StringComparison.Ordinal), $"summary line: {sum}");
|
||||
Check.True(sum.Contains("max 3100 ms (Heal Self, busy count)") && sum.Contains("2 over 1 s") == false && sum.Contains("1 over 1 s") && sum.Contains("1 over 3 s") && sum.Contains("1 episode(s) with no heal"),
|
||||
$"summary numbers: {sum}");
|
||||
}
|
||||
|
||||
private static void HeartbeatLogsEpisode()
|
||||
{
|
||||
var r = new Rig(healthPct: 40);
|
||||
r.S.SpellCastIntervalMs = 0;
|
||||
FakeHost.UseDoneSeq = 5;
|
||||
r.B.BusyCount = 1;
|
||||
r.At(0);
|
||||
r.B.OnHeartbeat(); // opens the episode; a live count holds it
|
||||
r.At(0.4);
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "held by the live busy count");
|
||||
FakeHost.UseDone(0);
|
||||
r.At(0.5);
|
||||
r.B.OnHeartbeat();
|
||||
Check.Eq(HealSelfCasts(), 1, "the UseDone frees it");
|
||||
string? line = r.Log("[HealLatency] 500 ms: health 40% under Top Off HP 60% (idle) -> Heal Self");
|
||||
Check.NotNull(line, "the episode line is logged with the delay and the line");
|
||||
Check.True(line!.Contains("busy count 400 ms"), $"and what held it: {line}");
|
||||
Check.Eq(r.B.BuffingLabel, BuffManager.LabelHealing, "while Heal Self is in flight the slot reads Healing");
|
||||
}
|
||||
|
||||
// Drakkon, 2026-10-05 13:43:09: "[HealLatency] 5831 ms: health 12% under Emergency Heal At 30%
|
||||
// (idle) -> Peerless Healing Kit; held by: login buff refresh 5737 ms". An engine hot reload
|
||||
// made RynthAi wait for its login buff refresh, and the refresh held heals too. It holds buffs
|
||||
// only now. (The registry read never succeeds here: server time 0, as before a time sync.)
|
||||
private static void EmergencyBeatsLoginRefresh()
|
||||
{
|
||||
var r = new Rig(healthPct: 12, liveBuffsReady: false);
|
||||
r.S.EmergencyHealAt = 30;
|
||||
r.S.EnableBuffing = true;
|
||||
r.At(0);
|
||||
r.B.OnHeartbeat();
|
||||
Check.False(r.B.LiveBuffsReady, "the login refresh hasn't got a snapshot");
|
||||
Check.Eq(HealSelfCasts(), 1, "Heal Self goes out on the first heartbeat anyway");
|
||||
string? line = r.Log("[HealLatency]");
|
||||
Check.True(line != null && !line.Contains("login buff refresh"), $"the heal was not held by the refresh: {line}");
|
||||
|
||||
// Health fine: the refresh still holds every buff.
|
||||
var q = new Rig(healthPct: 100, liveBuffsReady: false);
|
||||
q.S.EnableBuffing = true;
|
||||
q.S.SpellCastIntervalMs = 0;
|
||||
q.B.OnHeartbeat();
|
||||
q.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no buff cast before the refresh is ready");
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "and no buff item used");
|
||||
}
|
||||
|
||||
private static void ActivityLabels()
|
||||
{
|
||||
Check.Eq(ActivityArbiter.DisplayLabel("Buffing", "Healing"), "Healing", "Buffing slot: its label");
|
||||
Check.Eq(ActivityArbiter.DisplayLabel("Buffing", ""), "Buffing", "no label: Buffing");
|
||||
Check.Eq(ActivityArbiter.DisplayLabel("Combat", "Healing"), "Combat", "anything else: the control string");
|
||||
Check.Eq(ActivityArbiter.DisplayLabel(null, "Healing"), "Default", "empty: Default (the dashboard shows Idle)");
|
||||
Check.Eq(ActivityArbiter.ToBotAction(BotActivity.Buffing), "Buffing", "the control string stays Buffing");
|
||||
|
||||
Check.Eq(BuffManager.VitalLabel("Heal Self"), "Healing", "Heal Self");
|
||||
Check.Eq(BuffManager.VitalLabel("Stamina to Health Self"), "Healing", "Stamina to Health");
|
||||
Check.Eq(BuffManager.VitalLabel("Stamina to Mana Self"), "Restoring mana", "Stamina to Mana");
|
||||
Check.Eq(BuffManager.VitalLabel("Revitalize Self"), "Restoring stamina", "Revitalize");
|
||||
|
||||
var mana = new Rig(healthPct: 100, manaPct: 10);
|
||||
mana.S.GetManaAt = 50; mana.S.TopOffMana = 50;
|
||||
Check.True(mana.B.CheckVitals(), "10% mana: Stamina to Mana is cast");
|
||||
Check.Eq(mana.B.BuffingLabel, "Restoring mana", "and the slot reads Restoring mana");
|
||||
|
||||
var heal = new Rig(healthPct: 40);
|
||||
Check.Eq(heal.B.BuffingLabel, "Healing", "health under the line before anything ran: Healing");
|
||||
heal.B.MarkKitUsed();
|
||||
Check.Eq(heal.B.BuffingLabel, "Healing", "a healing kit in flight: Healing");
|
||||
var stam = new Rig(healthPct: 100);
|
||||
stam.B.MarkKitUsed(stamina: true);
|
||||
Check.Eq(stam.B.BuffingLabel, "Restoring stamina", "a stamina kit in flight: Restoring stamina");
|
||||
|
||||
var idle = new Rig(healthPct: 100);
|
||||
Check.Eq(idle.B.BuffingLabel, "Buffing", "nothing vital going on: Buffing");
|
||||
}
|
||||
}
|
||||
|
|
@ -27,6 +27,8 @@ internal static class LootAddItemTests
|
|||
{
|
||||
private const uint Player = 0x50000E01;
|
||||
private const uint Opal = 0x80271101, Taper = 0x80271102, Coin = 0x80271103;
|
||||
private const uint Ring = 0x80271104, Stone = 0x80271105, Sceptre = 0x80271106;
|
||||
private const uint ItemTypeJewelry = 0x8, ItemTypeCaster = 0x8000, ItemTypeManaStone = 0x80000, CurrentMana = 107;
|
||||
private const uint ItemTypeGem = 0x800, ItemTypeComponent = 0x1000;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
|
|
@ -39,6 +41,8 @@ internal static class LootAddItemTests
|
|||
r.Add("loot add: refusals (nothing selected, the same rule twice, no profile)", Refusals);
|
||||
r.Add("loot add: the popup's item_preview / item_add / item_close through the editor bridge", BridgePopupFlow);
|
||||
r.Add("loot add: unsaved edits in the Loot Editor block the add (nothing saved behind them)", BridgeRefusesUnderEdits);
|
||||
r.Add("loot add: the popup says when RynthAi's built-in looting takes the item (Mana Tap, mana stones)", BuiltInReasons);
|
||||
r.Add("loot: Mana Tap never loots a wand (ACE won't drain one, so it was kept for good)", ManaTapSkipsWands);
|
||||
}
|
||||
|
||||
// ── World and plugin ──────────────────────────────────────────────────────
|
||||
|
|
@ -48,8 +52,10 @@ internal static class LootAddItemTests
|
|||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new();
|
||||
public readonly WorldObjectCache Cache;
|
||||
public readonly RynthCoreHost Host;
|
||||
|
||||
public Bot()
|
||||
/// <summary><paramref name="world"/> adds objects (after the standard ones, before the host); list their ids in <paramref name="extra"/>.</summary>
|
||||
public Bot(Action? world = null, params uint[] extra)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Names[Player] = "Tester";
|
||||
|
|
@ -62,12 +68,14 @@ internal static class LootAddItemTests
|
|||
FakeHost.Ints[(Taper, 11)] = 100; // MaxStackSize
|
||||
FakeHost.Ints[(Taper, 12)] = 37; // StackCount
|
||||
FakeHost.Names[Coin] = "Pyreal";
|
||||
world?.Invoke();
|
||||
var host = FakeHost.Create(Player);
|
||||
Host = host;
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = FakeHost.MakeCache(host, Player, new[] { Player, Opal, Taper, Coin });
|
||||
Cache = FakeHost.MakeCache(host, Player, new[] { Player, Opal, Taper, Coin }.Concat(extra));
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_charSkills", new CharacterSkills(host));
|
||||
|
|
@ -340,4 +348,113 @@ internal static class LootAddItemTests
|
|||
Check.Eq(File.ReadAllText(path), SellGems, "nothing saved");
|
||||
Check.Eq(State(b).Rules[1].Name, "half-done", "the edit is still there, unsaved");
|
||||
}
|
||||
|
||||
// ── Built-in keeps (2026-10-05) ───────────────────────────────────────────
|
||||
|
||||
// A ring with 3,001 mana, an empty mana stone in the pack, tapping on at 2,500.
|
||||
private static Bot TapWorld()
|
||||
{
|
||||
var bot = new Bot(() =>
|
||||
{
|
||||
FakeHost.Names[Ring] = "Gold Ring";
|
||||
FakeHost.ItemTypes[Ring] = ItemTypeJewelry;
|
||||
FakeHost.Ints[(Ring, CurrentMana)] = 3001;
|
||||
FakeHost.Names[Stone] = "Mana Stone";
|
||||
FakeHost.ItemTypes[Stone] = ItemTypeManaStone;
|
||||
FakeHost.Ints[(Stone, CurrentMana)] = 0;
|
||||
FakeHost.Names[Sceptre] = "Piercing Sceptre";
|
||||
FakeHost.ItemTypes[Sceptre] = ItemTypeCaster;
|
||||
FakeHost.Ints[(Sceptre, CurrentMana)] = 3001;
|
||||
}, Ring, Stone, Sceptre);
|
||||
bot.S.EnableManaTapping = true;
|
||||
bot.S.ManaTapMinMana = 2500;
|
||||
bot.Set("_manaStoneManager", new ManaStoneManager(bot.Host, bot.S, bot.Cache));
|
||||
return bot;
|
||||
}
|
||||
|
||||
/// <summary>The looter's own call (what [LootEval] logs): taken?, action tag, rule label.</summary>
|
||||
private static (bool Taken, string Action, string Rule) LootEval(Bot bot, uint id)
|
||||
{
|
||||
MethodInfo m = typeof(RynthAiPlugin).GetMethod("ClassifyItemAgainstProfile", Any)!;
|
||||
object?[] args = { bot.Item(id), bot.S, null, null, null };
|
||||
bool taken = (bool)m.Invoke(bot.P, args)!;
|
||||
return (taken, (string)args[2]!, (string)args[4]!);
|
||||
}
|
||||
|
||||
private static void BuiltInReasons()
|
||||
{
|
||||
// Tom, 2026-10-05: "when I click on the wand it says no rule matches" - Mana Tap had
|
||||
// looted it. The popup now says which built-in keep takes an item and where to change it.
|
||||
var bot = TapWorld();
|
||||
string path = Temp("tap.utl", SellGems);
|
||||
bot.S.CurrentLootPath = path;
|
||||
LootEditorBridge b = bot.P.LootEditor;
|
||||
FakeHost.Chat.Clear();
|
||||
|
||||
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Ring, Seq = 1 } });
|
||||
LootEditItemDraft? d = State(b).ItemDraft;
|
||||
Check.True(d != null && d.Ok, "draft: " + d?.Error);
|
||||
const string tap = "No rule in the loot profile in use takes it, but RynthAi keeps it anyway: "
|
||||
+ "Mana Tap (3,001 mana >= 2,500), looted to drain into an empty mana stone - change in the Items panel, Mana Stone Tapping.";
|
||||
Check.Eq(d?.BuiltInReason, tap, "the reason, with the numbers and where to change it");
|
||||
Check.True(d != null && d.OrderNote.Contains("at the end") && d.OrderNote.EndsWith(tap, StringComparison.Ordinal),
|
||||
"OrderNote (what every engine's popup shows) carries it: " + d?.OrderNote);
|
||||
Check.True(d != null && d.OrderNote.All(c => c < 128), "ASCII only (the popup's font)");
|
||||
|
||||
// The same function the looter runs: [LootEval] tags it [ManaTap].
|
||||
Check.Eq(bot.Get<System.Collections.Generic.HashSet<int>>("_pendingManaTapIds")?.Count, 0, "the preview recorded nothing");
|
||||
Check.False(bot.ChatText.Contains("Mana tap candidate"), "and said nothing in chat\n" + bot.ChatText);
|
||||
var eval = LootEval(bot, Ring);
|
||||
Check.True(eval.Taken && eval.Action == "ManaTap", "the looter takes it as [ManaTap]: " + eval.Action);
|
||||
Check.True(eval.Rule.StartsWith("ManaTap (mana=3001", StringComparison.Ordinal), "rule label as in the log: " + eval.Rule);
|
||||
|
||||
// A profile rule decides: no built-in reason.
|
||||
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Opal, Seq = 2 } });
|
||||
d = State(b).ItemDraft;
|
||||
Check.Eq(d?.BuiltInReason, "", "the gem: rule 1 sells it, nothing built in");
|
||||
Check.True(d != null && d.OrderNote.Contains("just before rule 1 'Sell all gems'"), "order note as before: " + d?.OrderNote);
|
||||
|
||||
// Mana stones are checked ahead of the profile.
|
||||
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Stone, Seq = 3 } });
|
||||
d = State(b).ItemDraft;
|
||||
Check.True(d != null && d.BuiltInReason.StartsWith("RynthAi takes it before any loot profile rule: a mana stone,", StringComparison.Ordinal),
|
||||
"mana stone: " + d?.BuiltInReason);
|
||||
Check.True(d != null && d.BuiltInReason.Contains("of 5 kept - change in the Items panel"), "with the keep count");
|
||||
|
||||
// Under the threshold: not taken, nothing to explain.
|
||||
bot.S.ManaTapMinMana = 5000;
|
||||
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Ring, Seq = 4 } });
|
||||
Check.Eq(State(b).ItemDraft?.BuiltInReason, "", "3,001 mana under a 5,000 threshold: no reason");
|
||||
bot.S.ManaTapMinMana = 2500;
|
||||
|
||||
// Already in the pack after a Mana Tap pickup, quota full now: still says why it was taken.
|
||||
bot.Get<System.Collections.Generic.HashSet<int>>("_pendingManaTapIds")!.Clear(); // (the LootEval call above approved it)
|
||||
bot.Get<ManaStoneManager>("_manaStoneManager")!.MarkLootedForTap(unchecked((int)Ring));
|
||||
FakeHost.Ints[(Stone, CurrentMana)] = 500; // the only stone is charged: no free slot
|
||||
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Ring, Seq = 5 } });
|
||||
Check.Eq(State(b).ItemDraft?.BuiltInReason,
|
||||
"No rule in the loot profile in use takes it, but RynthAi keeps it anyway: it was looted for Mana Tap, to drain into an empty mana stone - change in the Items panel, Mana Stone Tapping.",
|
||||
"looted for tapping earlier");
|
||||
|
||||
// /ra loot add preview shows it in chat too.
|
||||
FakeHost.Ints[(Stone, CurrentMana)] = 0;
|
||||
FakeHost.SelectedItem = Ring;
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Ra("/ra loot add preview");
|
||||
Check.True(bot.ChatText.Contains("RynthAi keeps it anyway: it was looted for Mana Tap"), "/ra loot add preview says it\n" + bot.ChatText);
|
||||
Check.Eq(File.ReadAllText(path), SellGems, "preview saves nothing");
|
||||
}
|
||||
|
||||
private static void ManaTapSkipsWands()
|
||||
{
|
||||
var bot = TapWorld();
|
||||
bot.S.CurrentLootPath = Temp("wand.utl", SellGems);
|
||||
var wand = LootEval(bot, Sceptre);
|
||||
Check.False(wand.Taken, $"a 3,001-mana sceptre is left: [{wand.Action}] {wand.Rule}");
|
||||
Check.Eq(bot.Get<System.Collections.Generic.HashSet<int>>("_pendingManaTapIds")?.Count, 0, "not counted against the tap quota");
|
||||
var ring = LootEval(bot, Ring);
|
||||
Check.True(ring.Taken && ring.Action == "ManaTap", "a ring with the same mana is still tapped: " + ring.Action);
|
||||
Send(bot.P.LootEditor, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Sceptre, Seq = 1 } });
|
||||
Check.Eq(State(bot.P.LootEditor).ItemDraft?.BuiltInReason, "", "the popup has no built-in reason for the wand");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
461
Tools/RynthCore.RynthAiHostTests/Tests/OwnCorpseTests.cs
Normal file
461
Tools/RynthCore.RynthAiHostTests/Tests/OwnCorpseTests.cs
Normal file
|
|
@ -0,0 +1,461 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-10-05, owner: "It needs to loot your corpse and every item on it. If it's a setting default
|
||||
// to true please." Recover My Corpse (LootOwnCorpse, default on) takes every item on your own death
|
||||
// corpse whatever the loot profile and Loot From say; the death spot is remembered; Travel Back To
|
||||
// My Corpse (TravelToOwnCorpse, default off) walks back with RynthNav (/rnav go via the broker).
|
||||
internal static class OwnCorpseTests
|
||||
{
|
||||
private const uint Player = 0x50000D01;
|
||||
private const uint Corpse = 0x80261100;
|
||||
private const uint Gem = 0x80261101;
|
||||
private const uint Cloak = 0x80261102;
|
||||
private const uint Coins = 0x80261103;
|
||||
private const uint ItemTypeClothing = 0x4, ItemTypeMoney = 0x40, ItemTypeContainer = 0x200, ItemTypeGem = 0x800;
|
||||
private const uint LongDescKey = 16;
|
||||
private const string Me = "Dargoth Hera";
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("own corpse: recognised by exact name + 'Killed by' line, never a namesake or another player's", Identification);
|
||||
r.Add("own corpse: every item is taken, the loot profile and Loot From ignored, then closed", RecoveredWhole);
|
||||
r.Add("own corpse: another player's corpse with a similar name is left alone", SimilarNameUntouched);
|
||||
r.Add("own corpse: Recover My Corpse off = the behaviour before (profile only, My Kills skips it)", SettingOffIsOldBehaviour);
|
||||
r.Add("own corpse: beats a nearer corpse of your kill; a timeout retries it instead of writing it off", PriorityAndTimeout);
|
||||
r.Add("own corpse: settings default on/off, an old profile loads on, saved and bridged", SettingsDefaults);
|
||||
r.Add("own corpse: the death spot is remembered and said, server lines read", DeathSpotRemembered);
|
||||
r.Add("own corpse: travel back walks with RynthNav, stops for combat, ends in loot range", TravelBack);
|
||||
r.Add("own corpse: travel back refuses an indoor death and a missing RynthNav", TravelRefusals);
|
||||
}
|
||||
|
||||
// ── World ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static (uint Cell, float X, float Y, float Z) Me0 => (0x1048002Au, 100f, 100f, 0f);
|
||||
|
||||
private static void World(string corpseName, string? longDesc, bool closeCalls = false)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
|
||||
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
|
||||
FakeHost.CloseContainerCalls = closeCalls;
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
FakeHost.Names[Corpse] = corpseName;
|
||||
FakeHost.ItemTypes[Corpse] = ItemTypeContainer;
|
||||
if (longDesc != null)
|
||||
FakeHost.Strings[(Corpse, LongDescKey)] = longDesc;
|
||||
FakeHost.NotAttackable.Add(Corpse);
|
||||
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
|
||||
Item(Gem, "Black Opal", ItemTypeGem); // the test profile keeps gems
|
||||
Item(Cloak, "Faran Cloak", ItemTypeClothing); // ...and nothing else
|
||||
Item(Coins, "Pyreal", ItemTypeMoney);
|
||||
}
|
||||
|
||||
private static void Item(uint id, string name, uint type)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.ItemTypes[id] = type;
|
||||
FakeHost.Containers[id] = Corpse; // also installs GetObjectOwnershipInfo
|
||||
FakeHost.Appraised.Add(id);
|
||||
}
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new()
|
||||
{
|
||||
IsMacroRunning = true,
|
||||
EnableLooting = true,
|
||||
EnableCombat = false,
|
||||
LootOwnership = 0, // My Kills Only
|
||||
LootContentSettleMs = 0,
|
||||
LootEmptyCorpseMs = 0,
|
||||
StopLootingWhenPackFull = false,
|
||||
};
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public Bot(RynthCoreHost host)
|
||||
{
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
|
||||
string profile = Path.Combine(Program.TempRoot, "own-corpse-test.json");
|
||||
var p = new LootProfile { Name = "gems" };
|
||||
var rule = new LootRule { Name = "Gems", Action = LootAction.Keep };
|
||||
rule.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
|
||||
p.Rules.Add(rule);
|
||||
p.Save(profile);
|
||||
S.CurrentLootPath = profile;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public T Get<T>(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
|
||||
public object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
|
||||
public bool HasLootWork() => (bool)Call("HasLootWork", S, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())!;
|
||||
public void Tick(BotActivity act)
|
||||
{
|
||||
Set("_activity", act);
|
||||
Call("TickCorpseOpening");
|
||||
}
|
||||
public bool Completed => Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)Corpse));
|
||||
public bool ShouldLoot(uint id) => (bool)Call("ShouldLootCorpse", Cache[unchecked((int)id)]!)!;
|
||||
}
|
||||
|
||||
private static Bot NewBot()
|
||||
{
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.Cache.OnCreateObject(Corpse);
|
||||
bot.Cache.Tick();
|
||||
return bot;
|
||||
}
|
||||
|
||||
/// <summary>Claims and opens the corpse, then ticks; each item the bot moves lands in the pack.</summary>
|
||||
private static void LootToTheEnd(Bot bot, int maxTicks = 400)
|
||||
{
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
|
||||
foreach (uint id in new[] { Gem, Cloak, Coins })
|
||||
bot.Cache.OnCreateObject(id);
|
||||
bot.Cache.Tick();
|
||||
if (FakeHost.CloseContainerCalls) FakeHost.GroundContainer = Corpse;
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
|
||||
for (int i = 0; i < maxTicks && !bot.Completed; i++)
|
||||
{
|
||||
bot.Tick(BotActivity.Looting);
|
||||
foreach (var m in FakeHost.ExternalMoves)
|
||||
FakeHost.Containers[m.Id] = Player; // the server moved it
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Moves() => string.Join(",", FakeHost.ExternalMoves.Select(m => $"{m.Id:X8}->{m.Target:X8}"));
|
||||
|
||||
// ── Identification ────────────────────────────────────────────────────
|
||||
|
||||
private static void Identification()
|
||||
{
|
||||
OwnCorpseMatch M(string name, string me, string? desc) => RynthAiPlugin.MatchOwnDeathCorpse(name, me, desc);
|
||||
Check.Eq(M("Corpse of Dargoth Hera", Me, "Killed by Drudge Skulker."), OwnCorpseMatch.Yes, "your name, killed by a monster");
|
||||
Check.Eq(M("Corpse of Dargoth Hera", Me, "Killed by misadventure."), OwnCorpseMatch.Yes, "a fall (misadventure)");
|
||||
Check.Eq(M("Corpse of Dargoth Hera", Me, null), OwnCorpseMatch.Pending, "no ID yet: wait for it");
|
||||
Check.Eq(M("Corpse of Dargoth Hera", Me, "Killed by Dargoth Hera."), OwnCorpseMatch.No, "a namesake you killed is not your death corpse");
|
||||
Check.Eq(M("Corpse of Dargoth Hera", Me, "A corpse."), OwnCorpseMatch.No, "no 'Killed by' line: not a death corpse");
|
||||
Check.Eq(M("Corpse of Dargoth Heras", Me, "Killed by Drudge."), OwnCorpseMatch.No, "a longer name");
|
||||
Check.Eq(M("Corpse of Dargoth Her", Me, "Killed by Drudge."), OwnCorpseMatch.No, "a shorter name");
|
||||
Check.Eq(M("Corpse of dargoth hera", Me, "Killed by Drudge."), OwnCorpseMatch.No, "exact case only");
|
||||
Check.Eq(M("Corpse of Dargoth Hera's Wolf", Me, "Killed by Drudge."), OwnCorpseMatch.No, "a pet's corpse");
|
||||
Check.Eq(M("Dargoth Hera's corpse", Me, "Killed by Drudge."), OwnCorpseMatch.No, "another naming");
|
||||
Check.Eq(M("Corpse of +Dargoth Hera", "+Dargoth Hera", "Killed by Drudge."), OwnCorpseMatch.Yes, "a GM's corpse carries the sigil, as the name does");
|
||||
Check.Eq(M("Corpse of Dargoth Hera", "+Dargoth Hera", "Killed by Drudge."), OwnCorpseMatch.No, "a GM never matches the plain name");
|
||||
Check.Eq(M("Corpse of Dargoth Hera", "", "Killed by Drudge."), OwnCorpseMatch.No, "no player name yet: nothing matches");
|
||||
}
|
||||
|
||||
// ── Recovery ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void RecoveredWhole()
|
||||
{
|
||||
World("Corpse of " + Me, "Killed by Ancient Water Elemental.", closeCalls: true);
|
||||
var bot = NewBot();
|
||||
Check.True(bot.ShouldLoot(Corpse), "My Kills Only, killed by a monster: still yours to recover");
|
||||
Check.True(bot.HasLootWork(), "looting wants the tick");
|
||||
|
||||
LootToTheEnd(bot);
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "the gem (the profile keeps it) is taken: " + Moves());
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Cloak), "the cloak (no profile rule) is taken too: " + Moves());
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Coins), "and the pyreals: " + Moves());
|
||||
Check.True(FakeHost.ExternalMoves.All(m => m.Target == Player), "into the pack");
|
||||
Check.False(FakeHost.Uses.Any(u => u is Gem or Cloak or Coins), "never a use (a use can wield)");
|
||||
var first = FakeHost.ExternalMoves.Select(m => m.Id).ToList();
|
||||
Check.Eq(first.Distinct().Count(), 3, "one move per item (each confirmed before the next)");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[RynthAi] Own corpse: recovering 3 items.")), "says how many it recovers");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[RynthAi] Own corpse: recovered everything (3 items).")), "and that it got everything");
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("recovered everything")), "in chat too");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("[LootEval]")), "no loot profile evaluation at all");
|
||||
Check.True(bot.Completed, "the corpse is completed");
|
||||
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{Corpse:X8}", "and closed, once");
|
||||
Check.False(bot.Get<bool>("_currentLootItemIsSalvage"), "nothing queued for salvage");
|
||||
}
|
||||
|
||||
private static void SimilarNameUntouched()
|
||||
{
|
||||
World("Corpse of " + Me + "s", "Killed by Ancient Water Elemental.");
|
||||
var bot = NewBot();
|
||||
Check.False(bot.ShouldLoot(Corpse), "My Kills Only: a similar name is someone else's corpse");
|
||||
Check.False(bot.HasLootWork(), "nothing to loot");
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Check.Eq(bot.Get<int>("_targetCorpseId"), 0, "not claimed");
|
||||
Check.False(FakeHost.Uses.Contains(Corpse), "not opened");
|
||||
|
||||
// Loot From All Corpses: looted by the profile only (the gem), never recovered whole.
|
||||
World("Corpse of " + Me + "s", "Killed by Ancient Water Elemental.");
|
||||
var all = NewBot();
|
||||
all.S.LootOwnership = 2;
|
||||
LootToTheEnd(all);
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "All Corpses: the profile's gem: " + Moves());
|
||||
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Cloak || m.Id == Coins), "nothing else: " + Moves());
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("Own corpse")), "never treated as your corpse");
|
||||
|
||||
// Your exact name but no ID yet: held, not looted by the profile meanwhile.
|
||||
World("Corpse of " + Me, null);
|
||||
var pending = NewBot();
|
||||
pending.S.LootOwnership = 2;
|
||||
Check.False(pending.ShouldLoot(Corpse), "named like yours, unidentified: waits for its ID");
|
||||
Check.True(FakeHost.IdRequests.Contains(Corpse), "its ID is asked for");
|
||||
}
|
||||
|
||||
private static void SettingOffIsOldBehaviour()
|
||||
{
|
||||
World("Corpse of " + Me, "Killed by Ancient Water Elemental.");
|
||||
var bot = NewBot();
|
||||
bot.S.LootOwnCorpse = false;
|
||||
Check.False(bot.ShouldLoot(Corpse), "My Kills Only: a monster killed you, so it is skipped (as before)");
|
||||
Check.False(bot.HasLootWork(), "nothing to loot");
|
||||
|
||||
World("Corpse of " + Me, "Killed by Ancient Water Elemental.");
|
||||
var all = NewBot();
|
||||
all.S.LootOwnCorpse = false;
|
||||
all.S.LootOwnership = 2;
|
||||
LootToTheEnd(all);
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "All Corpses: the profile's gem: " + Moves());
|
||||
Check.False(FakeHost.ExternalMoves.Any(m => m.Id == Cloak || m.Id == Coins), "only what the profile keeps: " + Moves());
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("Own corpse")), "no own-corpse recovery");
|
||||
}
|
||||
|
||||
private static void PriorityAndTimeout()
|
||||
{
|
||||
const uint Kill = 0x80261200;
|
||||
World("Corpse of " + Me, "Killed by Ancient Water Elemental.");
|
||||
FakeHost.Positions[Corpse] = (Me0.Cell, Me0.X + 4.0f, Me0.Y, Me0.Z); // yours, 4 m
|
||||
FakeHost.Names[Kill] = "Corpse of Drudge Skulker";
|
||||
FakeHost.ItemTypes[Kill] = ItemTypeContainer;
|
||||
FakeHost.Strings[(Kill, LongDescKey)] = $"Killed by {Me}.";
|
||||
FakeHost.NotAttackable.Add(Kill);
|
||||
FakeHost.Positions[Kill] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z); // your kill, 1 m
|
||||
var bot = NewBot();
|
||||
bot.Cache.OnCreateObject(Kill);
|
||||
bot.Cache.Tick();
|
||||
Check.True(bot.ShouldLoot(Kill), "your kill is lootable");
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Check.Eq(bot.Get<int>("_targetCorpseId"), unchecked((int)Corpse), "your own corpse is claimed first, though further");
|
||||
|
||||
// It timed out once it was opened: not completed (that would leave your things for good).
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
bot.Call("AbandonCurrentCorpse", Environment.TickCount64, "timeout");
|
||||
Check.False(bot.Completed, "an own corpse that timed out is not written off");
|
||||
Check.True(bot.Get<Dictionary<int, long>>("_corpseCooldownUntil").ContainsKey(unchecked((int)Corpse)), "it is retried after a short wait");
|
||||
for (int i = 1; i < RynthAiPlugin.OwnCorpseMaxAbandons; i++)
|
||||
{
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
bot.Call("AbandonCurrentCorpse", Environment.TickCount64, "timeout");
|
||||
}
|
||||
Check.True(bot.Completed, $"after {RynthAiPlugin.OwnCorpseMaxAbandons} timeouts it is given up");
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("Own corpse: giving up")), "and it says so");
|
||||
}
|
||||
|
||||
// ── Settings ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void SettingsDefaults()
|
||||
{
|
||||
Check.True(new LegacyUiSettings().LootOwnCorpse, "Recover My Corpse: on for a new profile");
|
||||
Check.False(new LegacyUiSettings().TravelToOwnCorpse, "Travel Back To My Corpse: off for a new profile");
|
||||
var old = JsonSerializer.Deserialize("{\"EnableLooting\":true,\"LootOwnership\":0}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(old != null && old.LootOwnCorpse, "a profile saved before the setting: on");
|
||||
Check.True(old != null && !old.TravelToOwnCorpse, "and travel off");
|
||||
var saved = JsonSerializer.Deserialize(
|
||||
JsonSerializer.Serialize(new LegacyUiSettings { LootOwnCorpse = false, TravelToOwnCorpse = true }, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(saved != null && !saved.LootOwnCorpse && saved.TravelToOwnCorpse, "both are saved and loaded");
|
||||
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { new LegacyUiSettings { LootOwnCorpse = false, TravelToOwnCorpse = true }, dst });
|
||||
Check.True(!dst.LootOwnCorpse && dst.TravelToOwnCorpse, "a profile switch copies both");
|
||||
copy.Invoke(null, new object[] { old!, dst });
|
||||
Check.True(dst.LootOwnCorpse && !dst.TravelToOwnCorpse, "an old profile loads the defaults");
|
||||
|
||||
// The engine's Settings face: sent, and an engine without the fields leaves them alone.
|
||||
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.LootOwnCorpse == null && payload.TravelToOwnCorpse == null, "an older engine's payload has no value");
|
||||
var s = new LegacyUiSettings { LootOwnCorpse = false, TravelToOwnCorpse = true };
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
|
||||
.SetValue(dash, new LegacyAdvancedSettingsUi(s));
|
||||
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(sent != null && sent.LootOwnCorpse == false && sent.TravelToOwnCorpse == true, "sent to the engine face");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.True(!s.LootOwnCorpse && s.TravelToOwnCorpse, "a save without the fields leaves them");
|
||||
dash.ApplySettingsJson("{\"LootOwnCorpse\":true,\"TravelToOwnCorpse\":false}");
|
||||
Check.True(s.LootOwnCorpse && !s.TravelToOwnCorpse, "a save with them sets them");
|
||||
}
|
||||
|
||||
// ── Death spot ────────────────────────────────────────────────────────
|
||||
|
||||
private static Bot DieAt(double ns, double ew, uint? cell = null, bool broker = false, bool navLoaded = true)
|
||||
{
|
||||
World("Corpse of " + Me, "Killed by Ancient Water Elemental.");
|
||||
FakeHost.PluginCommandCalls = broker;
|
||||
FakeHost.PluginCommandDelivered = navLoaded;
|
||||
FakeHost.SetNavPosition(ns, ew);
|
||||
if (cell is uint c) FakeHost.PlayerPose = (c, 50f, 60f, -12f);
|
||||
FakeHost.Positions[Player] = FakeHost.PlayerPose;
|
||||
var bot = NewBot();
|
||||
var vitals = bot.Get<PlayerVitalsCache>("_vitals");
|
||||
vitals.MaxHealth = 100;
|
||||
vitals.CurrentHealth = 0;
|
||||
bot.Call("CheckPlayerDeath", bot.S);
|
||||
return bot;
|
||||
}
|
||||
|
||||
private static void DeathSpotRemembered()
|
||||
{
|
||||
var bot = DieAt(42.10, 33.60);
|
||||
var spot = bot.P.DeathSpot;
|
||||
Check.True(spot != null, "the death spot is remembered");
|
||||
Check.True(spot != null && Math.Abs(spot.Ns - 42.10) < 0.01 && Math.Abs(spot.Ew - 33.60) < 0.01, $"at the death position ({spot?.Ns:0.00}, {spot?.Ew:0.00})");
|
||||
Check.True(spot != null && spot.Outdoors && spot.Cell == FakeHost.PlayerPose.Cell, "with its landblock and cell");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[RynthAi] Your corpse is at 42.10N, 33.60E (landblock 0x")), "logged: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("corpse is at"))));
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("Your corpse is at 42.10N, 33.60E")), "and said in chat");
|
||||
|
||||
bot.Call("OnOwnCorpseChat", "You have retained all your items. You do not need to recover your corpse!"); // OnChatWindowText hands chat lines here
|
||||
Check.True(bot.P.DeathSpot!.NothingDropped, "the server's 'nothing dropped' line is noted");
|
||||
|
||||
var indoor = DieAt(0, 0, cell: 0x01D90123u);
|
||||
Check.True(indoor.P.DeathSpot != null && !indoor.P.DeathSpot.Outdoors, "a dungeon death is remembered as indoors");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Your corpse is at landblock 0x01D9, cell 0x0123")), "with landblock and cell");
|
||||
|
||||
// No position at the death: the server's line gives the spot.
|
||||
World("Corpse of " + Me, "Killed by Ancient Water Elemental.");
|
||||
var noPose = NewBot();
|
||||
noPose.Call("OnOwnCorpseChat", "Your corpse is located at (12.3S, 45.6W)."); // OnChatWindowText hands chat lines here
|
||||
var fromChat = noPose.P.DeathSpot;
|
||||
Check.True(fromChat != null && Math.Abs(fromChat.Ns + 12.3) < 0.001 && Math.Abs(fromChat.Ew + 45.6) < 0.001, "taken from the server's line");
|
||||
}
|
||||
|
||||
// ── Travel back ───────────────────────────────────────────────────────
|
||||
|
||||
private static void BackdateIdle(Bot bot) => bot.Set("_travelIdleSince", Environment.TickCount64 - 10_000);
|
||||
|
||||
private static void TravelBack()
|
||||
{
|
||||
var bot = DieAt(42.10, 33.60, broker: true);
|
||||
bot.S.TravelToOwnCorpse = true;
|
||||
|
||||
// Respawned at a lifestone ~100 m away.
|
||||
FakeHost.SetNavPosition(42.50, 33.60);
|
||||
FakeHost.Positions[Player] = FakeHost.PlayerPose;
|
||||
bot.Call("OnRespawnedForOwnCorpse");
|
||||
Check.True(bot.Get<bool>("_ownCorpseTravelManual") == false, "started by the respawn, not by hand");
|
||||
Check.True((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(bot.P)!, "RynthAi's own route is parked meanwhile");
|
||||
|
||||
bot.Set("_activity", BotActivity.Idle);
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
Check.Eq(FakeHost.PluginCommands.Count, 0, "waits a moment of quiet before walking");
|
||||
BackdateIdle(bot);
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
Check.True(FakeHost.PluginCommands.Contains(("RynthNav", "rnav", "go 42.10N, 33.60E")),
|
||||
"walks with RynthNav: " + string.Join(" | ", FakeHost.PluginCommands));
|
||||
|
||||
// A monster: RynthAi fights, the walk stops.
|
||||
bot.Set("_activity", BotActivity.Combat);
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
Check.Eq(FakeHost.PluginCommands.Last(), ("RynthNav", "rnav", "stop"), "the walk stops for combat");
|
||||
int count = FakeHost.PluginCommands.Count;
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
Check.Eq(FakeHost.PluginCommands.Count, count, "one stop, not one per tick");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("travel paused for Combat")), "logged");
|
||||
|
||||
// Fight over: walk on.
|
||||
bot.Set("_activity", BotActivity.Idle);
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
BackdateIdle(bot);
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
Check.Eq(FakeHost.PluginCommands.Last(), ("RynthNav", "rnav", "go 42.10N, 33.60E"), "resumes after the fight");
|
||||
|
||||
// Near the spot, the corpse is in loot range: travel ends, looting takes over.
|
||||
FakeHost.SetNavPosition(42.10, 33.61); // ~2.4 m east... 0.01 coord = 2.4 m
|
||||
FakeHost.Positions[Player] = FakeHost.PlayerPose;
|
||||
var p = FakeHost.PlayerPose;
|
||||
FakeHost.Positions[Corpse] = (p.Cell, p.X + 1.0f, p.Y, p.Z);
|
||||
bot.Cache.OnCreateObject(Corpse);
|
||||
bot.Cache.Tick();
|
||||
bot.Call("TickOwnCorpseTravel", bot.S);
|
||||
Check.Eq(FakeHost.PluginCommands.Last(), ("RynthNav", "rnav", "stop"), "the walk stops");
|
||||
Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(bot.P)!, "travel is over");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("travel back ended: your corpse") && l.Contains("is in loot range")), "says why");
|
||||
Check.True(bot.HasLootWork(), "and looting wants the tick for it");
|
||||
|
||||
// Timeout with no progress.
|
||||
var stuck = DieAt(42.10, 33.60, broker: true);
|
||||
stuck.S.TravelToOwnCorpse = true;
|
||||
FakeHost.SetNavPosition(42.50, 33.60);
|
||||
FakeHost.Positions[Player] = FakeHost.PlayerPose;
|
||||
stuck.Call("OnRespawnedForOwnCorpse");
|
||||
stuck.Set("_activity", BotActivity.Idle);
|
||||
BackdateIdle(stuck);
|
||||
stuck.Call("TickOwnCorpseTravel", stuck.S);
|
||||
stuck.Call("TickOwnCorpseTravel", stuck.S); // first distance sample
|
||||
stuck.Set("_travelBestAt", Environment.TickCount64 - RynthAiPlugin.OwnCorpseTravelNoProgressMs - 1000);
|
||||
stuck.Call("TickOwnCorpseTravel", stuck.S);
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("travel back ended: gave up: no closer")), "no progress: gives up and says so");
|
||||
Check.Eq(FakeHost.PluginCommands.Last(), ("RynthNav", "rnav", "stop"), "and stops RynthNav");
|
||||
|
||||
// Nothing dropped: no trip.
|
||||
var none = DieAt(42.10, 33.60);
|
||||
none.Call("OnOwnCorpseChat", "You have retained all your items. You do not need to recover your corpse!"); // OnChatWindowText hands chat lines here
|
||||
none.S.TravelToOwnCorpse = true;
|
||||
none.Call("OnRespawnedForOwnCorpse");
|
||||
Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(none.P)!, "nothing dropped: no trip back");
|
||||
|
||||
// Setting off (the default): no trip.
|
||||
var off = DieAt(42.10, 33.60);
|
||||
off.Call("OnRespawnedForOwnCorpse");
|
||||
Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(off.P)!, "Travel Back off: no trip back");
|
||||
}
|
||||
|
||||
private static void TravelRefusals()
|
||||
{
|
||||
var indoor = DieAt(0, 0, cell: 0x01D90123u, broker: true);
|
||||
indoor.S.TravelToOwnCorpse = true;
|
||||
indoor.Call("OnRespawnedForOwnCorpse");
|
||||
Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(indoor.P)!, "an indoor death: no trip");
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("you died indoors") && l.Contains("only works outdoors")), "and it says why");
|
||||
|
||||
var noNav = DieAt(42.10, 33.60, broker: true, navLoaded: false); // RynthNav not loaded
|
||||
noNav.S.TravelToOwnCorpse = true;
|
||||
FakeHost.SetNavPosition(42.50, 33.60);
|
||||
FakeHost.Positions[Player] = FakeHost.PlayerPose;
|
||||
noNav.Call("OnRespawnedForOwnCorpse");
|
||||
noNav.Set("_activity", BotActivity.Idle);
|
||||
BackdateIdle(noNav);
|
||||
noNav.Call("TickOwnCorpseTravel", noNav.S);
|
||||
Check.False((bool)typeof(RynthAiPlugin).GetProperty("OwnCorpseTravelHoldsNav", Any)!.GetValue(noNav.P)!, "RynthNav missing: the trip ends");
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("RynthNav isn't loaded")), "and it says why");
|
||||
}
|
||||
}
|
||||
|
|
@ -24,6 +24,46 @@ internal static class VitalsTests
|
|||
r.Add("vitals: profiles without the Stamina to Health keys load today's 30 / 20", StaminaToHealthDefaults);
|
||||
r.Add("vitals: after a kit, nothing else heals until the kit's result line lands", KitResultWait);
|
||||
r.Add("vitals: low health wins the arbiter even on a busy tick; backs off when nothing can heal", HealthWinsArbiter);
|
||||
r.Add("vitals: 'You're too busy!' paces vital casts, and a long streak stops the character once", TooBusyVitals);
|
||||
// Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md).
|
||||
r.Add("vitals: a hot reload's login refresh trusts its first read; a real login waits for two equal reads", HotReloadRefresh);
|
||||
r.Add("vitals: RynthAi tells the engine a reload is unsafe while engaged, under a heal line or casting", ReloadBlockerReport);
|
||||
}
|
||||
|
||||
// Drakkon, 2026-10-05: stuck in the cast gesture, AC answering "You're too busy!" every
|
||||
// 0.4 s. The buff path backed off; Stamina to Mana didn't, and re-cast on every
|
||||
// SpellCastIntervalMs tick until the player moved. Mana/stamina casts now wait out the
|
||||
// backoff, and a streak of refusals sends one StopCompletely (what moving did).
|
||||
private static void TooBusyVitals()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.StopCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
|
||||
var host = FakeHost.Create();
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false };
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 10 };
|
||||
var b = new BuffManager(host, s, sm, vitals);
|
||||
b.SetCharacterSkills(skills);
|
||||
|
||||
Check.True(b.CheckVitals(), "10% mana: Stamina to Mana is cast");
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "one cast");
|
||||
b.OnChatWindowText("You're too busy!", 26);
|
||||
Check.True(b.CheckVitals(), "too busy: the vital tick still yields (no potion, no buff)");
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "but nothing is re-cast inside the backoff");
|
||||
|
||||
for (int i = 0; i < 3; i++) b.OnChatWindowText("You're too busy!", 26);
|
||||
Check.Eq(FakeHost.Stops, 1, "4 refusals in a row: one StopCompletely to clear the stuck gesture");
|
||||
for (int i = 0; i < 4; i++) b.OnChatWindowText("You're too busy!", 26);
|
||||
Check.Eq(FakeHost.Stops, 1, "only once per streak");
|
||||
}
|
||||
|
||||
// 2026-10-04, "nav and looting have priority over healing, almost dying in packs": the
|
||||
|
|
@ -172,6 +212,80 @@ internal static class VitalsTests
|
|||
Check.False(BuffManager.StaminaToHealthAllowed(d, 31, 99), "predicate: 31 on defaults");
|
||||
}
|
||||
|
||||
private static BuffManager RefreshRig(out LegacyUiSettings s, out PlayerVitalsCache vitals, int healthPct = 100)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
|
||||
var host = FakeHost.Create();
|
||||
s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 30, StaminaToHealthAt = 0,
|
||||
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false };
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = (uint)healthPct, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, s, sm, vitals);
|
||||
b.SetCharacterSkills(skills);
|
||||
return b;
|
||||
}
|
||||
|
||||
// The engine reload at 13:42:55 looked like a login to RynthAi: the buff refresh waited 5.8 s
|
||||
// for two equal reads of a registry that was already complete (the client never left the world).
|
||||
private static void HotReloadRefresh()
|
||||
{
|
||||
int strength = SpellTable.Named("Strength Self I").First().Id;
|
||||
int endurance = SpellTable.Named("Endurance Self I").First().Id;
|
||||
|
||||
var b = RefreshRig(out _, out _);
|
||||
FakeHost.ServerTime = 1000;
|
||||
FakeHost.Enchantments.Add(((uint)strength, 1000 + 3600));
|
||||
FakeHost.Enchantments.Add(((uint)endurance, 1000 + 3600));
|
||||
b.CarriedOverSession = true;
|
||||
b.OnHeartbeat();
|
||||
Check.True(b.LiveBuffsReady, "hot reload: ready on the first successful read");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("login refresh ready") && l.Contains("hot reload")), "and the line says why");
|
||||
|
||||
var real = RefreshRig(out _, out _);
|
||||
FakeHost.ServerTime = 1000;
|
||||
FakeHost.Enchantments.Add(((uint)strength, 1000 + 3600));
|
||||
real.OnHeartbeat();
|
||||
Check.False(real.LiveBuffsReady, "a real login: one read isn't trusted (the registry may still be streaming)");
|
||||
System.Threading.Thread.Sleep(1100);
|
||||
real.OnHeartbeat();
|
||||
Check.True(real.LiveBuffsReady, "two equal reads a second apart: ready");
|
||||
}
|
||||
|
||||
private static void ReloadBlockerReport()
|
||||
{
|
||||
// The pure text.
|
||||
Check.Eq(ReloadSafety.Reason(false, true, "Emergency Heal At", 12, 30, "Heal Self V"), "", "macro off: never blocks a reload");
|
||||
Check.Eq(ReloadSafety.Reason(true, false, "", 100, 0, ""), "", "nothing going on: safe");
|
||||
Check.Eq(ReloadSafety.Reason(true, true, "", 100, 0, ""), "in combat (a monster engaged)", "a monster engaged");
|
||||
Check.Eq(ReloadSafety.Reason(true, false, "Emergency Heal At", 12, 30, ""), "in combat (health 12% under Emergency Heal At 30%)", "under a heal line");
|
||||
Check.Eq(ReloadSafety.Reason(true, false, "", 100, 0, "Strength Self VI"), "casting ('Strength Self VI' awaiting its result)", "a buff in flight");
|
||||
Check.Eq(ReloadSafety.Reason(true, true, "Heal At", 45, 60, "Heal Self V"),
|
||||
"in combat (a monster engaged, health 45% under Heal At 60%, 'Heal Self V' awaiting its result)", "all three");
|
||||
|
||||
// What BuffManager feeds it.
|
||||
var b = RefreshRig(out _, out var v, healthPct: 50);
|
||||
b.MarkLiveBuffsReadyForTests();
|
||||
Check.Eq(b.HealLineNow(out int hp, out int lineValue), "Top Off HP", "50% under Top Off HP (no monster: the idle line)");
|
||||
Check.Eq((hp, lineValue), (50, 60), "with the health and the line");
|
||||
Check.Eq(b.CastInFlightName, "", "nothing cast yet");
|
||||
Check.True(b.CheckVitals(), "Heal Self is cast");
|
||||
int healCat = SpellTable.Named("Heal Self I").First().Category;
|
||||
Check.True(b.CastInFlightName.Length > 0 && SpellTable.Named(b.CastInFlightName).Any(row => row.Category == healCat),
|
||||
$"the cast in flight is a Heal Self tier: {b.CastInFlightName}");
|
||||
v.CurrentHealth = 100;
|
||||
Check.Eq(b.HealLineNow(out _, out _), "", "full health: no line");
|
||||
v.MaxHealth = 0;
|
||||
Check.Eq(b.HealLineNow(out _, out _), "", "vitals not read yet: no line");
|
||||
}
|
||||
|
||||
private static void StaminaToHealthDefaults()
|
||||
{
|
||||
var old = JsonSerializer.Deserialize("{\"EmergencyHealAt\":25}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
|
|
|
|||
|
|
@ -37,8 +37,13 @@ internal static class WeaponTests
|
|||
r.Add("element choice: a wand always casts its own element (rule, Damage tab, no match)", ChoiceWandCastsOwn);
|
||||
r.Add("element choice: elements the character can't cast are skipped", ChoiceCastable);
|
||||
r.Add("slayer: beats the weakness and the Monsters rule's damage type", SlayerBeatsWeaknessAndRule);
|
||||
r.Add("slayer: a weapon the player picked (for the monster or on the DEFAULT row) beats it", SlayerVsDamageTab);
|
||||
r.Add("slayer: other creature types, no bonus and other kinds are ignored", SlayerNonMatching);
|
||||
r.Add("slayer: only this monster's own Damage tab weapon beats it, not the DEFAULT row's", SlayerVsDamageTab);
|
||||
r.Add("slayer (owner's rule 2026-10-05): a Slash slayer beats a Pierce weapon the monster is weaker to", SlayerBeatsLowerResist);
|
||||
r.Add("slayer: this monster's own pick that is a slayer is used, labelled", SlayerManualPickIsSlayer);
|
||||
r.Add("slayer: the Damage tab's learned best never beats it", SlayerBeatsLearnedBest);
|
||||
r.Add("slayer: bonus not sent (ACE never sends float 138) still slays, ranked below a known bonus", SlayerBonusUnknown);
|
||||
r.Add("slayer: creature type from the world-database table before the monster's appraisal", SlayerTypeFromTable);
|
||||
r.Add("slayer: other creature types, an x1 bonus and other kinds are ignored", SlayerNonMatching);
|
||||
r.Add("slayer: the bigger bonus wins, then the element order, then the hand", SlayerOrder);
|
||||
r.Add("slayer: creature type unknown, the old choice", SlayerUnknownType);
|
||||
r.Add("slayer: the element follows the chosen weapon", SlayerElement);
|
||||
|
|
@ -376,12 +381,18 @@ internal static class WeaponTests
|
|||
var list = new List<WeaponCandidate> { Wand(1, "Fire"), Slayer(2, CombatMode.Magic, "Cold", Olthoi, 2.0) };
|
||||
|
||||
var pick = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 1, creatureType: Olthoi);
|
||||
Check.Eq(pick.WeaponId, 1, "the Damage tab's weapon for this monster is the player's pick: it wins");
|
||||
Check.Eq(pick.WeaponId, 1, "a non-slayer set on this monster's own Damage tab row: the player's pick wins");
|
||||
Check.Eq(pick.Source, "Damage tab", "source");
|
||||
Check.Eq(pick.Element, "Fire", "and casts its own element");
|
||||
|
||||
var def = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 1, fixedSource: "Damage tab default",
|
||||
creatureType: Olthoi, fixedIsDefault: true);
|
||||
Check.Eq(def.WeaponId, 1, "the Damage tab DEFAULT row's weapon is a player pick too: it beats a matching slayer");
|
||||
Check.Eq(def.WeaponId, 2, "the DEFAULT row's non-slayer weapon: a slayer of this monster still wins");
|
||||
Check.Eq(def.Source, "slayer (Olthoi x2)", "source");
|
||||
|
||||
var defRule = WeaponPlanner.Choose(list, "Fire", weak, All, fixedWeaponId: 1, fixedSource: "Damage tab default",
|
||||
creatureType: Olthoi, fixedIsDefault: true);
|
||||
Check.Eq(defRule.WeaponId, 2, "the DEFAULT row's weapon and a Monsters rule of Fire: still the slayer");
|
||||
|
||||
var defNoSlayer = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 1, fixedSource: "Damage tab default",
|
||||
creatureType: Undead, fixedIsDefault: true);
|
||||
|
|
@ -389,6 +400,109 @@ internal static class WeaponTests
|
|||
Check.Eq(defNoSlayer.Source, "Damage tab default", "source");
|
||||
}
|
||||
|
||||
private static void SlayerBeatsLowerResist()
|
||||
{
|
||||
// Owner, 2026-10-05: an Olthoi slayer that does Slash is picked before a Pierce weapon
|
||||
// even when the Olthoi resists Pierce less, because the slayer outperforms it.
|
||||
var weak = Rank(("Pierce", 0.86), ("Slash", 0.67), ("Fire", 0.65));
|
||||
var spear = new WeaponCandidate(1, "Spear", CombatMode.Melee, "Pierce", "", true);
|
||||
var list = new List<WeaponCandidate> { spear, Slayer(2, CombatMode.Melee, "Slash", Olthoi, 2.0) };
|
||||
|
||||
var p = WeaponPlanner.Choose(list, "", weak, All, creatureType: Olthoi);
|
||||
Check.Eq(p.WeaponId, 2, "the Slash Olthoi slayer, not the Pierce spear in hand");
|
||||
Check.Eq(p.Element, "Slash", "it hits with Slash");
|
||||
Check.Eq(p.Source, "slayer (Olthoi x2)", "source");
|
||||
|
||||
var r = WeaponPlanner.Choose(list, "Pierce", weak, All, creatureType: Olthoi);
|
||||
Check.Eq(r.WeaponId, 2, "a Monsters rule of Pierce: still the slayer");
|
||||
|
||||
Check.Eq(WeaponPlanner.Choose(list, "", weak, All, creatureType: Undead).WeaponId, 1,
|
||||
"not an Olthoi: the Pierce spear (weakness)");
|
||||
}
|
||||
|
||||
private static void SlayerManualPickIsSlayer()
|
||||
{
|
||||
var weak = Rank(("Fire", 1.4), ("Cold", 1.0));
|
||||
var list = new List<WeaponCandidate>
|
||||
{
|
||||
Wand(1, "Fire"),
|
||||
Slayer(2, CombatMode.Magic, "Acid", Olthoi, 3.0),
|
||||
Slayer(3, CombatMode.Magic, "Cold", Olthoi, 2.0),
|
||||
};
|
||||
var p = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 3, creatureType: Olthoi);
|
||||
Check.Eq(p.WeaponId, 3, "this monster's own pick is a slayer: that one, though another has a bigger bonus");
|
||||
Check.Eq(p.Element, "Cold", "its own element");
|
||||
Check.Eq(p.Source, "Damage tab, slayer (Olthoi x2)", "source names the pick and the slayer");
|
||||
|
||||
// The DEFAULT row's pick is a slayer: step 2 finds it like any listed slayer (biggest bonus first).
|
||||
var d = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 3, fixedSource: "Damage tab default",
|
||||
creatureType: Olthoi, fixedIsDefault: true);
|
||||
Check.Eq(d.WeaponId, 2, "DEFAULT row's slayer pick: the best slayer of the monster (x3)");
|
||||
}
|
||||
|
||||
private static void SlayerBeatsLearnedBest()
|
||||
{
|
||||
var weak = Rank(("Fire", 1.4), ("Cold", 1.0));
|
||||
var list = new List<WeaponCandidate> { Wand(1, "Fire"), Slayer(2, CombatMode.Magic, "Cold", Olthoi, 2.0) };
|
||||
Check.Eq(WeaponPlanner.Choose(list, "", weak, All, learnedBestId: 1, creatureType: Olthoi).WeaponId, 2,
|
||||
"weakness known, the learned best is the Fire wand: the slayer");
|
||||
Check.Eq(WeaponPlanner.Choose(list, "", null, All, learnedBestId: 1, creatureType: Olthoi).WeaponId, 2,
|
||||
"weakness unknown, learned best: the slayer");
|
||||
Check.Eq(WeaponPlanner.Choose(list, "", null, All, learnedBestId: 1, creatureType: 0).WeaponId, 1,
|
||||
"creature type unknown: the learned best, as before");
|
||||
|
||||
// Through CombatManager: the store's learned best (GetBestWeapon) doesn't beat a listed slayer.
|
||||
var rig = new Rig(990002, "Olthoi Learner");
|
||||
rig.S.ItemRules.Add(new() { Id = unchecked((int)FireWand), Name = "Fire Wand", Element = "Fire", ElementSource = "icon" });
|
||||
for (int i = 0; i < 4; i++) rig.Store.RecordHit(FireWand, 990002, "Olthoi Learner", "Fire", 7, 300, false);
|
||||
Check.Eq(rig.Store.GetBestWeapon(990002), FireWand, "the Damage tab learned the fire wand as best");
|
||||
rig.C.InHandOverride = () => unchecked((int)FireWand);
|
||||
FakeHost.Ints[(ListedWand, 166)] = Olthoi;
|
||||
FakeHost.Ints[(Monster, 2)] = Olthoi;
|
||||
Check.Eq(unchecked((uint)rig.C.PlanFor(rig.Target, null).WeaponId), ListedWand, "the slayer wand, not the learned best");
|
||||
}
|
||||
|
||||
private static void SlayerBonusUnknown()
|
||||
{
|
||||
var weak = Rank(("Fire", 1.4), ("Cold", 1.0));
|
||||
var unknown = Slayer(2, CombatMode.Magic, "Cold", Olthoi, 0);
|
||||
Check.True(WeaponPlanner.Slays(unknown, Olthoi), "SlayerCreatureType sent, bonus not: it slays");
|
||||
Check.False(WeaponPlanner.Slays(unknown, Undead), "not another type");
|
||||
var p = WeaponPlanner.Choose(new List<WeaponCandidate> { Wand(1, "Fire", inHand: true), unknown }, "", weak, All, creatureType: Olthoi);
|
||||
Check.Eq(p.WeaponId, 2, "the slayer with no bonus sent beats the Fire wand the monster is weak to");
|
||||
Check.Eq(p.Source, "slayer (Olthoi)", "source has no multiplier");
|
||||
|
||||
var both = new List<WeaponCandidate> { unknown, Slayer(3, CombatMode.Magic, "Acid", Olthoi, 2.0) };
|
||||
Check.Eq(WeaponPlanner.Choose(both, "", weak, All, creatureType: Olthoi).WeaponId, 3,
|
||||
"a known x2 bonus ranks above one not sent");
|
||||
var two = new List<WeaponCandidate> { Slayer(4, CombatMode.Magic, "Acid", Olthoi, 0), unknown };
|
||||
Check.Eq(WeaponPlanner.Choose(two, "", weak, All, creatureType: Olthoi).WeaponId, 2,
|
||||
"two with no bonus sent: the element order (Cold before Acid)");
|
||||
}
|
||||
|
||||
private static void SlayerTypeFromTable()
|
||||
{
|
||||
// wcid 3 "Olthoi Worker" is type 1 (Olthoi) in creature_resists.tsv. The monster isn't
|
||||
// appraised (no int 2) and the creature store doesn't know it: the table answers.
|
||||
var rig = new Rig(3, "Olthoi Worker");
|
||||
rig.S.ItemRules.Add(new() { Id = unchecked((int)FireWand), Name = "Fire Wand", Element = "Fire", ElementSource = "icon" });
|
||||
rig.C.InHandOverride = () => unchecked((int)FireWand);
|
||||
FakeHost.Ints[(ListedWand, 166)] = Olthoi; // no float 138, as ACE sends it
|
||||
Check.Eq(CreatureWeakness.TableCreatureType(3, "Olthoi Worker"), Olthoi, "table: wcid 3 is an Olthoi");
|
||||
Check.Eq(CreatureWeakness.TableCreatureType(3, "Not An Olthoi"), 0, "a custom monster reusing the wcid: no type");
|
||||
Check.Eq(rig.C.CreatureTypeOf(3, "Olthoi Worker"), Olthoi, "CreatureTypeOf falls back to the table");
|
||||
var p = rig.C.PlanFor(rig.Target, null);
|
||||
Check.Eq(unchecked((uint)p.WeaponId), ListedWand, "first sight of an Olthoi Worker: the slayer wand");
|
||||
Check.Eq(p.Source, "slayer (Olthoi)", "source");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("slays Olthoi (bonus not sent)")), "the weapon's slayer is logged");
|
||||
|
||||
// A listed slayer and a monster of unknown type: logged once, no slayer step.
|
||||
var odd = new WorldObject(unchecked((int)Monster) + 5, "Custom Thing", AcObjectClass.Monster);
|
||||
FakeHost.Wcids[Monster + 5] = 990005;
|
||||
Check.Eq(unchecked((uint)rig.C.PlanFor(odd, null).WeaponId), FireWand, "type unknown: the weakness choice");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("creature type not known yet")), "and it is logged");
|
||||
}
|
||||
|
||||
private static void SlayerNonMatching()
|
||||
{
|
||||
var weak = Rank(("Fire", 1.4), ("Cold", 1.0));
|
||||
|
|
@ -396,7 +510,6 @@ internal static class WeaponTests
|
|||
{
|
||||
Wand(1, "Fire"),
|
||||
Slayer(2, CombatMode.Magic, "Cold", Undead, 2.0), // another type
|
||||
Slayer(3, CombatMode.Magic, "Cold", Olthoi, 0), // no bonus property (ACE needs both)
|
||||
Slayer(4, CombatMode.Magic, "Cold", Olthoi, 1.0), // x1: no gain
|
||||
Slayer(5, CombatMode.Melee, "Slash", Olthoi, 3.0), // not the main kind (magic)
|
||||
};
|
||||
|
|
@ -455,6 +568,9 @@ internal static class WeaponTests
|
|||
Check.Eq(p.Source, "weak to Fire (test)", "source");
|
||||
var r = WeaponPlanner.Choose(list, "Cold", weak, All, creatureType: 0);
|
||||
Check.Eq(r.Source, "Monsters rule Cold", "and the rule as before");
|
||||
var d = WeaponPlanner.Choose(list, "", weak, All, fixedWeaponId: 1, fixedSource: "Damage tab default", creatureType: 0, fixedIsDefault: true);
|
||||
Check.Eq(d.WeaponId, 1, "type unknown and a DEFAULT row weapon: the default, as before");
|
||||
Check.Eq(d.Source, "Damage tab default", "source");
|
||||
}
|
||||
|
||||
private static void SlayerElement()
|
||||
|
|
@ -488,6 +604,9 @@ internal static class WeaponTests
|
|||
|
||||
var before = rig.C.PlanFor(rig.Target, null);
|
||||
Check.Eq(unchecked((uint)before.WeaponId), FireWand, "no slayer properties yet: the Fire wand (weakness)");
|
||||
Check.Eq(rig.C.SlayerOf(unchecked((int)ListedWand)), (0, 0.0), "no int 166: no slayer");
|
||||
FakeHost.Ints[(ListedWand, 166)] = Olthoi;
|
||||
Check.Eq(rig.C.SlayerOf(unchecked((int)ListedWand)), (Olthoi, 0.0), "int 166 alone (what ACE sends): a slayer, bonus not known");
|
||||
|
||||
FakeHost.Ints[(ListedWand, 166)] = Olthoi;
|
||||
FakeHost.Doubles[(ListedWand, 138)] = 2.0;
|
||||
|
|
|
|||
Loading…
Reference in a new issue