Snapshot for release 2026.10.31.1 (internal 69b244e)
This commit is contained in:
parent
8cb74c7685
commit
2546497f37
122 changed files with 22896 additions and 170 deletions
771
tools/HeadlessHostTests/ActionsTests.cs
Normal file
771
tools/HeadlessHostTests/ActionsTests.cs
Normal file
|
|
@ -0,0 +1,771 @@
|
|||
// ============================================================================
|
||||
// ActionsTests - the ACTIONS area: each action's game action (type + payload), the
|
||||
// busy count with its events, use-done / weenie-error sequences, merge results,
|
||||
// selection, chat (InvokeChatParser through a plugin's OnChatBarEnter, WriteToChat
|
||||
// echo), confirmations, jumps and manual driving (autorun + heading, turning, stops,
|
||||
// living with a planned walk and the server's move-to).
|
||||
// ============================================================================
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using RynthCore.Headless.Host;
|
||||
using RynthCore.Headless.Messages;
|
||||
using RynthCore.Headless.Session;
|
||||
using RynthCore.Headless.World;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace HeadlessHostTests;
|
||||
|
||||
internal static unsafe class ActionsTests
|
||||
{
|
||||
[System.Runtime.CompilerServices.ModuleInitializer]
|
||||
internal static void Register() => Suites.Add("actions", Run, order: 30);
|
||||
|
||||
private const uint TurnRight = 0x6500000D, WalkBackwards = 0x45000006;
|
||||
|
||||
private static Fixture F => Fixture.Shared;
|
||||
private static RynthCoreApiNative* Api => F.Api;
|
||||
private static uint Me => F.Session.World.Player.Id;
|
||||
|
||||
private static void Run()
|
||||
{
|
||||
WieldOnUse();
|
||||
PickUpOnUseInCorpse();
|
||||
SalvageDirect();
|
||||
Fixture f = F;
|
||||
using var _ = f.Context.Enter();
|
||||
T.Check(f.Session.State == SessionState.InWorld, "session in world");
|
||||
|
||||
Combat();
|
||||
BusyAndUseDone();
|
||||
Errors();
|
||||
Inventory();
|
||||
Merge();
|
||||
Selection();
|
||||
Chat();
|
||||
Confirmation();
|
||||
Jumps();
|
||||
Drive();
|
||||
DriveAndWalks();
|
||||
}
|
||||
|
||||
// ── helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static uint U32(byte[] b, int at) => BinaryPrimitives.ReadUInt32LittleEndian(b.AsSpan(at));
|
||||
private static int I32(byte[] b, int at) => BinaryPrimitives.ReadInt32LittleEndian(b.AsSpan(at));
|
||||
private static float F32(byte[] b, int at) => BinaryPrimitives.ReadSingleLittleEndian(b.AsSpan(at));
|
||||
|
||||
private static string S16(byte[] b, ref int at)
|
||||
{
|
||||
int n = BinaryPrimitives.ReadUInt16LittleEndian(b.AsSpan(at));
|
||||
string s = Encoding.Latin1.GetString(b, at + 2, n);
|
||||
at += 2 + n;
|
||||
at = (at + 3) & ~3;
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>Exactly one action of <paramref name="type"/> sent since the mark (and nothing else): its payload.</summary>
|
||||
private static byte[] One(int mark, uint type, string what)
|
||||
{
|
||||
var sent = F.ActionsSince(mark);
|
||||
T.Check(sent.Count == 1 && sent[0].Type == type,
|
||||
$"{what}: one 0x{type:X4} sent (got {string.Join(", ", sent.Select(s => $"0x{s.Type:X4}"))})");
|
||||
return sent.Count > 0 ? sent[^1].Payload : Array.Empty<byte>();
|
||||
}
|
||||
|
||||
private static byte[] GameEvent(uint type, byte[] body)
|
||||
{
|
||||
var b = new byte[16 + body.Length];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b, 0xF7B0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(4), Me);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(8), 0x1000);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(12), type);
|
||||
body.CopyTo(b, 16);
|
||||
return b;
|
||||
}
|
||||
|
||||
private static byte[] U32s(params uint[] v)
|
||||
{
|
||||
var b = new byte[v.Length * 4];
|
||||
for (int i = 0; i < v.Length; i++) BinaryPrimitives.WriteUInt32LittleEndian(b.AsSpan(i * 4), v[i]);
|
||||
return b;
|
||||
}
|
||||
|
||||
private static byte[] UseDone(uint error) => GameEvent(0x01C7, U32s(error));
|
||||
|
||||
private static List<PluginEvent> Drain() => F.Context.Events.Drain();
|
||||
|
||||
/// <summary>A stub object (no ObjectCreate) in a made-up container, so the real world model is untouched.</summary>
|
||||
private static WorldObject Stub(uint id)
|
||||
{
|
||||
F.Receive(GameEvent(0x0022, U32s(id, 0x7FFF00FF, 0, 0)));
|
||||
return F.Session.World.Get(id)!;
|
||||
}
|
||||
|
||||
private static void Advance(long ms, long step = 50)
|
||||
{
|
||||
for (long t = 0; t < ms; t += step)
|
||||
{
|
||||
F.Now += step;
|
||||
F.Session.Tick();
|
||||
}
|
||||
}
|
||||
|
||||
// Not equipment: "use" on equipment is a wield, as in the retail client (checked in WieldOnUse).
|
||||
|
||||
/// <summary>"Use" on carried equipment wields it (the retail client's behaviour); on wielded equipment it unwields.</summary>
|
||||
private static void WieldOnUse()
|
||||
{
|
||||
using var _ = F.Context.Enter();
|
||||
var w = F.Session.World;
|
||||
var gear = w.Inventory().FirstOrDefault(o => o.WielderId == 0 && (o.Desc.ValidLocations ?? 0) != 0 && (o.Desc.ValidLocations & 0xC0000) != 0xC0000);
|
||||
var worn = w.Inventory().FirstOrDefault(o => o.WielderId == Me);
|
||||
T.Check(gear != null && worn != null, "the replay has pack equipment and worn equipment");
|
||||
if (gear == null || worn == null) return;
|
||||
int m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(gear.Id), 1, "UseObject on pack equipment");
|
||||
var acts = F.ActionsSince(m);
|
||||
T.Check(acts.Count == 1 && acts[0].Type == 0x001A && U32(acts[0].Payload, 0) == gear.Id && U32(acts[0].Payload, 4) == gear.Desc.ValidLocations,
|
||||
"it goes out as GetAndWieldItem with the item's locations");
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(worn.Id), 1, "UseObject on worn equipment");
|
||||
acts = F.ActionsSince(m);
|
||||
T.Check(acts.Count == 1 && acts[0].Type == 0x0019 && U32(acts[0].Payload, 0) == worn.Id && U32(acts[0].Payload, 4) == Me,
|
||||
"it goes out as PutItemInContainer into the pack");
|
||||
}
|
||||
|
||||
/// <summary>SalvageDirect: one 0x027D action (tool, count, ids) for carried items; anything else is refused.</summary>
|
||||
private static void SalvageDirect()
|
||||
{
|
||||
using var _ = F.Context.Enter();
|
||||
var carried = F.Session.World.Inventory().Where(o => !o.IsContainer && o.WielderId == 0).Select(o => o.Id).Take(3).ToArray();
|
||||
T.Check(carried.Length == 3, "three carried items to stand in for the tool and the salvage");
|
||||
if (carried.Length < 3) return;
|
||||
T.Check(Api->SalvageDirectFn != IntPtr.Zero, "SalvageDirect is filled (RynthAi's HasSalvageDirect)");
|
||||
var salvage = (delegate* unmanaged[Cdecl]<uint, uint*, int, int>)Api->SalvageDirectFn;
|
||||
uint tool = carried[0];
|
||||
uint* ids = stackalloc uint[] { carried[1], carried[2] };
|
||||
int m = F.Mark;
|
||||
T.Eq(salvage(tool, ids, 2), 2, "two items sent");
|
||||
var acts = F.ActionsSince(m);
|
||||
T.Check(acts.Count == 1 && acts[0].Type == 0x027D && U32(acts[0].Payload, 0) == tool && U32(acts[0].Payload, 4) == 2
|
||||
&& U32(acts[0].Payload, 8) == carried[1] && U32(acts[0].Payload, 12) == carried[2],
|
||||
"it goes out as 0x027D: tool, count, ids");
|
||||
uint* stranger = stackalloc uint[] { carried[1], 0x80FFFFFE };
|
||||
m = F.Mark;
|
||||
T.Eq(salvage(tool, stranger, 2), 0, "an item not carried: refused");
|
||||
T.Eq(salvage(tool, ids, 0), 0, "no items: refused");
|
||||
T.Check(F.ActionsSince(m).Count == 0, "nothing sent for the refusals");
|
||||
}
|
||||
|
||||
/// <summary>"Use" on an item in the open corpse picks it up into the main pack (the retail client's behaviour).</summary>
|
||||
private static void PickUpOnUseInCorpse()
|
||||
{
|
||||
using var _ = F.Context.Enter();
|
||||
var w = F.Session.World;
|
||||
var item = w.Get(FirstPackItem());
|
||||
T.Check(item != null, "a pack item to stand in for the loot");
|
||||
if (item == null) return;
|
||||
uint wasIn = item.ContainerId, wasOpen = w.OpenContainer;
|
||||
const uint corpse = 0x80004D5B;
|
||||
try
|
||||
{
|
||||
item.ContainerId = corpse;
|
||||
w.OpenContainer = corpse;
|
||||
int m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(item.Id), 1, "UseObject on an item in the open corpse");
|
||||
var acts = F.ActionsSince(m);
|
||||
T.Check(acts.Count == 1 && acts[0].Type == 0x0019 && U32(acts[0].Payload, 0) == item.Id && U32(acts[0].Payload, 4) == Me,
|
||||
"it goes out as PutItemInContainer into the main pack, not a Use (and the busy count is untouched)");
|
||||
}
|
||||
finally
|
||||
{
|
||||
item.ContainerId = wasIn;
|
||||
w.OpenContainer = wasOpen;
|
||||
}
|
||||
}
|
||||
|
||||
private static uint FirstPackItem() => F.Session.World.Inventory().FirstOrDefault(o => !o.IsContainer && o.WielderId == 0 && (o.Desc.ValidLocations ?? 0) == 0)?.Id ?? 0;
|
||||
|
||||
private static uint SomeCreature() => F.Session.World.Objects.Values.FirstOrDefault(o => o.IsCreature && o.Id != Me)?.Id ?? 0x80001234;
|
||||
|
||||
// ── combat + casts ──────────────────────────────────────────────────────
|
||||
|
||||
private static void Combat()
|
||||
{
|
||||
uint mob = SomeCreature();
|
||||
int m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int, int>)Api->ChangeCombatModeFn)(2), 1, "ChangeCombatMode(Melee)");
|
||||
T.Eq(U32(One(m, 0x0053, "ChangeCombatMode"), 0), 2u, "ChangeCombatMode payload");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int, int>)Api->ChangeCombatModeFn)(3), 0, "ChangeCombatMode(3) refused");
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, float, int>)Api->MeleeAttackFn)(mob, 1, 0.75f), 1, "MeleeAttack");
|
||||
byte[] p = One(m, 0x0008, "MeleeAttack");
|
||||
T.Check(p.Length == 12 && U32(p, 0) == mob && U32(p, 4) == 1 && Math.Abs(F32(p, 8) - 0.75f) < 1e-6, "MeleeAttack payload (target, height, power)");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, float, int>)Api->MeleeAttackFn)(0, 1, 0.5f), 0, "MeleeAttack(0) refused");
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, float, int>)Api->MissileAttackFn)(mob, 3, 0.25f), 1, "MissileAttack");
|
||||
p = One(m, 0x000A, "MissileAttack");
|
||||
T.Check(p.Length == 12 && U32(p, 0) == mob && U32(p, 4) == 3 && Math.Abs(F32(p, 8) - 0.25f) < 1e-6, "MissileAttack payload");
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->CancelAttackFn)(), 1, "CancelAttack");
|
||||
T.Eq(One(m, 0x01B7, "CancelAttack").Length, 0, "CancelAttack has no payload");
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->QueryHealthFn)(mob), 1, "QueryHealth");
|
||||
T.Eq(U32(One(m, 0x01BF, "QueryHealth"), 0), mob, "QueryHealth payload");
|
||||
|
||||
// NativeAttack: the selected target, by combat mode.
|
||||
WorldObject me = F.Session.World.PlayerObject!;
|
||||
bool had = me.Ints.TryGetValue(40, out int oldMode);
|
||||
try
|
||||
{
|
||||
((delegate* unmanaged[Cdecl]<uint, int>)Api->SetSelectedObjectIdFn)(mob);
|
||||
me.Ints[40] = 1;
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int, float, int>)Api->NativeAttackFn)(2, 0.5f), 0, "NativeAttack refused in NonCombat");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->GetCurrentCombatModeFn)(), 1, "GetCurrentCombatMode = NonCombat");
|
||||
me.Ints[40] = 2;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int, float, int>)Api->NativeAttackFn)(2, 0.5f), 1, "NativeAttack in Melee");
|
||||
T.Eq(U32(One(m, 0x0008, "NativeAttack (melee)"), 0), mob, "NativeAttack hits the selection");
|
||||
me.Ints[40] = 4;
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int, float, int>)Api->NativeAttackFn)(1, 0.5f), 1, "NativeAttack in Missile");
|
||||
One(m, 0x000A, "NativeAttack (missile)");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (had) me.Ints[40] = oldMode; else me.Ints.Remove(40);
|
||||
((delegate* unmanaged[Cdecl]<uint, int>)Api->SetSelectedObjectIdFn)(0);
|
||||
}
|
||||
|
||||
// Casts: targeted 0x4A (target, spell); untargeted 0x48 (spell).
|
||||
Drain();
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, int>)Api->CastSpellFn)(mob, 27), 1, "CastSpell on a target");
|
||||
p = One(m, 0x004A, "CastSpell targeted");
|
||||
T.Check(p.Length == 8 && U32(p, 0) == mob && U32(p, 4) == 27, "CastTargeted payload (target, spell)");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->GetCastBusyStateFn)(), 1, "cast gate closed while the cast is out");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->IsPlayerReadyFn)(), 0, "not ready while casting");
|
||||
F.Receive(UseDone(0));
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->GetCastBusyStateFn)(), 0, "cast gate open after UseDone");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->IsPlayerReadyFn)(), 1, "ready again");
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, int>)Api->CastSpellFn)(0, 2), 1, "CastSpell untargeted");
|
||||
T.Eq(U32(One(m, 0x0048, "CastSpell untargeted"), 0), 2u, "CastUntargeted payload");
|
||||
F.Receive(UseDone(0));
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, int>)Api->CastSpellFn)(mob, 0), 0, "CastSpell(spell 0) refused");
|
||||
var ev = Drain();
|
||||
T.Eq(ev.Count(e => e is PluginEvent.BusyIncremented), 2, "a cast counts busy");
|
||||
T.Eq(ev.Count(e => e is PluginEvent.BusyDecremented), 2, "its UseDone uncounts it");
|
||||
}
|
||||
|
||||
// ── busy count, use-done ────────────────────────────────────────────────
|
||||
|
||||
private static void BusyAndUseDone()
|
||||
{
|
||||
uint item = FirstPackItem();
|
||||
T.Check(item != 0, "a pack item to use");
|
||||
var getBusy = (delegate* unmanaged[Cdecl]<int>)Api->GetBusyStateFn;
|
||||
var seqFn = (delegate* unmanaged[Cdecl]<int>)Api->GetUseDoneSeqFn;
|
||||
var lastFn = (delegate* unmanaged[Cdecl]<int*, uint*, int>)Api->GetLastUseDoneFn;
|
||||
|
||||
Drain();
|
||||
T.Eq(getBusy(), 0, "busy 0 at rest");
|
||||
int seq0 = seqFn();
|
||||
int m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(item), 1, "UseObject");
|
||||
T.Eq(U32(One(m, 0x0036, "UseObject"), 0), item, "UseObject payload");
|
||||
T.Eq(getBusy(), 1, "busy 1 after a use");
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int>)Api->UseObjectOnFn)(item, Me), 1, "UseObjectOn");
|
||||
byte[] p = One(m, 0x0035, "UseObjectOn");
|
||||
T.Check(U32(p, 0) == item && U32(p, 4) == Me, "UseObjectOn payload (source, target)");
|
||||
T.Eq(getBusy(), 2, "busy 2 after two uses");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(0), 0, "UseObject(0) refused");
|
||||
|
||||
F.Receive(UseDone(0));
|
||||
T.Eq(getBusy(), 1, "UseDone takes one off");
|
||||
T.Eq(seqFn(), seq0 + 1, "use-done seq +1");
|
||||
F.Receive(UseDone(0x1D));
|
||||
T.Eq(getBusy(), 0, "second UseDone: busy 0");
|
||||
int s; uint e;
|
||||
T.Eq(lastFn(&s, &e), 1, "GetLastUseDone");
|
||||
T.Check(s == seq0 + 2 && e == 0x1D, $"last use-done (seq {s}, err 0x{e:X}) = (seq0+2, 0x1D)");
|
||||
F.Receive(UseDone(0));
|
||||
T.Eq(getBusy(), 0, "an extra UseDone doesn't go negative");
|
||||
|
||||
var ev = Drain();
|
||||
T.Eq(ev.Count(x => x is PluginEvent.BusyIncremented), 2, "two busy-incremented events");
|
||||
T.Eq(ev.Count(x => x is PluginEvent.BusyDecremented), 2, "two busy-decremented events (none for the unpaired UseDone)");
|
||||
|
||||
// Force reset: one decrement per unit.
|
||||
((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(item);
|
||||
((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(item);
|
||||
((delegate* unmanaged[Cdecl]<uint, int>)Api->UseObjectFn)(item);
|
||||
Drain();
|
||||
((delegate* unmanaged[Cdecl]<void>)Api->ForceResetBusyCountFn)();
|
||||
T.Eq(getBusy(), 0, "ForceResetBusyCount -> 0");
|
||||
T.Eq(Drain().Count(x => x is PluginEvent.BusyDecremented), 3, "three decrements for the three units dropped");
|
||||
|
||||
// UseEquippedItem is a UseWithTarget too, and counts.
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int>)Api->UseEquippedItemFn)(item, Me), 1, "UseEquippedItem");
|
||||
One(m, 0x0035, "UseEquippedItem");
|
||||
T.Eq(getBusy(), 1, "UseEquippedItem counts busy");
|
||||
F.Receive(UseDone(0));
|
||||
Drain();
|
||||
}
|
||||
|
||||
private static void Errors()
|
||||
{
|
||||
var fn = (delegate* unmanaged[Cdecl]<int*, uint*, uint*, uint*, int>)Api->GetLastWeenieErrorFn;
|
||||
int s0; uint e, t, o;
|
||||
fn(&s0, &e, &t, &o);
|
||||
|
||||
F.Receive(GameEvent(0x028A, U32s(0x0402)));
|
||||
int s;
|
||||
T.Eq(fn(&s, &e, &t, &o), 1, "GetLastWeenieError");
|
||||
T.Check(s == s0 + 1 && e == 0x402 && t == 0x028A && o == 0, $"WeenieError recorded (seq {s}, 0x{e:X}, evt 0x{t:X}, obj 0x{o:X})");
|
||||
|
||||
var body = new List<byte>(U32s(0x051F));
|
||||
body.AddRange(new byte[] { 4, 0, (byte)'f', (byte)'u', (byte)'l', (byte)'l', 0, 0 });
|
||||
F.Receive(GameEvent(0x028B, body.ToArray()));
|
||||
fn(&s, &e, &t, &o);
|
||||
T.Check(s == s0 + 2 && e == 0x51F && t == 0x028B, "WeenieErrorWithString recorded");
|
||||
|
||||
F.Receive(GameEvent(0x00A0, U32s(0x7FFF0010, 0x0029)));
|
||||
fn(&s, &e, &t, &o);
|
||||
T.Check(s == s0 + 3 && e == 0x29 && t == 0x00A0 && o == 0x7FFF0010, "InventoryServerSaveFailed recorded with its item");
|
||||
}
|
||||
|
||||
// ── inventory ───────────────────────────────────────────────────────────
|
||||
|
||||
private static void Inventory()
|
||||
{
|
||||
uint item = FirstPackItem();
|
||||
uint pack = 0x7FFF0020; // a container id the server would judge; not one of ours to the client
|
||||
int m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int, int>)Api->MoveItemInternalFn)(item, pack, 3, 1), 1, "MoveItemInternal");
|
||||
byte[] p = One(m, 0x0019, "MoveItemInternal");
|
||||
T.Check(U32(p, 0) == item && U32(p, 4) == pack && I32(p, 8) == 3, "MoveItemInternal payload (item, container, slot)");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int, int>)Api->MoveItemInternalFn)(item, pack, 0, 0), 0, "MoveItemInternal amount 0 refused");
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int>)Api->PutItemInContainerFn)(item, Me, 5), 1, "PutItemInContainer");
|
||||
p = One(m, 0x0019, "PutItemInContainer");
|
||||
T.Check(U32(p, 0) == item && U32(p, 4) == Me && I32(p, 8) == 5, "PutItemInContainer payload");
|
||||
|
||||
WorldObject stack = Stub(0x7FFF0030);
|
||||
stack.StackSize = 25;
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int>)Api->MoveItemExternalFn)(stack.Id, Me, 10), 1, "MoveItemExternal part of a stack");
|
||||
p = One(m, 0x0055, "MoveItemExternal (split)");
|
||||
T.Check(U32(p, 0) == stack.Id && U32(p, 4) == Me && I32(p, 8) == 0 && I32(p, 12) == 10, "split payload (stack, container, 0, amount)");
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int>)Api->MoveItemExternalFn)(stack.Id, Me, 0), 1, "MoveItemExternal whole");
|
||||
p = One(m, 0x0019, "MoveItemExternal (whole)");
|
||||
T.Check(U32(p, 0) == stack.Id && U32(p, 4) == Me, "whole move payload");
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int, int>)Api->SplitStackInternalFn)(stack.Id, Me, 2, 7), 1, "SplitStackInternal");
|
||||
p = One(m, 0x0055, "SplitStackInternal");
|
||||
T.Check(U32(p, 0) == stack.Id && U32(p, 4) == Me && I32(p, 8) == 2 && I32(p, 12) == 7, "SplitStackInternal payload");
|
||||
|
||||
uint npc = SomeCreature();
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int>)Api->GiveObjectToFn)(stack.Id, npc, 0), 1, "GiveObjectTo whole stack");
|
||||
p = One(m, 0x00CD, "GiveObjectTo");
|
||||
T.Check(U32(p, 0) == npc && U32(p, 4) == stack.Id && I32(p, 8) == 25, "give payload (target, item, whole stack = 25)");
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int>)Api->WieldItemFn)(item, 0x00100000), 1, "WieldItem");
|
||||
p = One(m, 0x001A, "WieldItem");
|
||||
T.Check(U32(p, 0) == item && U32(p, 4) == 0x00100000, "wield payload (item, mask)");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int>)Api->WieldItemFn)(item, 0), 0, "WieldItem mask 0 refused");
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->CloseContainerFn)(0x7FFF0040), 1, "CloseContainer");
|
||||
T.Eq(U32(One(m, 0x0195, "CloseContainer"), 0), 0x7FFF0040u, "close payload");
|
||||
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->GetBusyStateFn)(), 0, "inventory sends don't count busy");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint>)Api->GetGroundContainerIdFn)(), F.Context.GroundContainer, "GetGroundContainerId");
|
||||
}
|
||||
|
||||
private static void Merge()
|
||||
{
|
||||
WorldObject a = Stub(0x7FFF0050), b = Stub(0x7FFF0051);
|
||||
a.StackSize = 30; b.StackSize = 80;
|
||||
a.Desc.MaxStackSize = 100; b.Desc.MaxStackSize = 100;
|
||||
var merge = (delegate* unmanaged[Cdecl]<uint, uint, int>)Api->MergeStackInternalFn;
|
||||
var result = (delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)Api->GetMergeStackResultFn;
|
||||
int amount, age;
|
||||
T.Eq(result(a.Id, b.Id, &amount, &age), 0, "no merge result before a merge");
|
||||
int m = F.Mark;
|
||||
T.Eq(merge(a.Id, b.Id), 1, "MergeStackInternal");
|
||||
byte[] p = One(m, 0x0054, "MergeStackInternal");
|
||||
T.Check(U32(p, 0) == a.Id && U32(p, 4) == b.Id && I32(p, 8) == 20, "merge payload (from, to, what fits = 20)");
|
||||
T.Eq(result(a.Id, b.Id, &amount, &age), 2, "merge result Sent");
|
||||
T.Eq(amount, 20, "merge result amount");
|
||||
b.StackSize = 100;
|
||||
m = F.Mark;
|
||||
T.Eq(merge(a.Id, b.Id), 0, "merge onto a full stack refused");
|
||||
T.Eq(F.ActionsSince(m).Count, 0, "nothing sent for a full target");
|
||||
T.Eq(result(a.Id, b.Id, &amount, &age), 3, "merge result TargetFull");
|
||||
}
|
||||
|
||||
// ── selection ───────────────────────────────────────────────────────────
|
||||
|
||||
private static void Selection()
|
||||
{
|
||||
var select = (delegate* unmanaged[Cdecl]<uint, int>)Api->SelectItemFn;
|
||||
var get = (delegate* unmanaged[Cdecl]<uint>)Api->GetSelectedItemIdFn;
|
||||
var prev = (delegate* unmanaged[Cdecl]<uint>)Api->GetPreviousSelectedItemIdFn;
|
||||
uint a = SomeCreature();
|
||||
WorldObject b = Stub(0x7FFF0060);
|
||||
|
||||
F.Now += 1000;
|
||||
Drain();
|
||||
uint before = get();
|
||||
T.Eq(select(a), 1, "SelectItem");
|
||||
T.Eq(get(), a, "selected");
|
||||
var ev = Drain().OfType<PluginEvent.SelectedTargetChange>().ToList();
|
||||
T.Check(ev.Count == 1 && ev[0].Current == a && ev[0].Previous == before, "SelectedTargetChange(a, previous)");
|
||||
|
||||
T.Eq(select(a), 1, "the same target again within 150 ms: still 1");
|
||||
T.Eq(Drain().OfType<PluginEvent.SelectedTargetChange>().Count(), 0, "no event for a repeat");
|
||||
|
||||
T.Eq(select(b.Id), 1, "select another");
|
||||
T.Eq(get(), b.Id, "selected b");
|
||||
T.Eq(prev(), a, "previous = a");
|
||||
ev = Drain().OfType<PluginEvent.SelectedTargetChange>().ToList();
|
||||
T.Check(ev.Count == 1 && ev[0].Current == b.Id && ev[0].Previous == a, "SelectedTargetChange(b, a)");
|
||||
|
||||
// The selected object leaving the world clears the selection.
|
||||
var del = new byte[8];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(del, 0xF747);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(del.AsSpan(4), b.Id);
|
||||
F.Receive(del);
|
||||
T.Eq(get(), 0u, "selection cleared when its object is deleted");
|
||||
ev = Drain().OfType<PluginEvent.SelectedTargetChange>().ToList();
|
||||
T.Check(ev.Count == 1 && ev[0].Current == 0 && ev[0].Previous == b.Id, "SelectedTargetChange(0, b)");
|
||||
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int>)Api->SetSelectedObjectIdFn)(a), 1, "SetSelectedObjectId");
|
||||
T.Eq(get(), a, "set selected");
|
||||
((delegate* unmanaged[Cdecl]<uint, int>)Api->SetSelectedObjectIdFn)(0);
|
||||
Drain();
|
||||
}
|
||||
|
||||
// ── chat ────────────────────────────────────────────────────────────────
|
||||
|
||||
private static readonly List<string> ChatBarLines = new();
|
||||
|
||||
/// <summary>A plugin's OnChatBarEnter: eats "/ra ..."; "/chain" sends "/ra chained" back through InvokeChatParser.</summary>
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static void FakeChatBarEnter(IntPtr text, int* eat)
|
||||
{
|
||||
string s = Marshal.PtrToStringUni(text) ?? "";
|
||||
ChatBarLines.Add(s);
|
||||
if (s.StartsWith("/ra ", StringComparison.Ordinal)) *eat = 1;
|
||||
if (s == "/chain")
|
||||
{
|
||||
IntPtr t = Marshal.StringToHGlobalUni("/ra chained");
|
||||
try { ((delegate* unmanaged[Cdecl]<IntPtr, int>)Fixture.Shared.Api->InvokeChatParserFn)(t); }
|
||||
finally { Marshal.FreeHGlobal(t); }
|
||||
*eat = 1;
|
||||
}
|
||||
}
|
||||
|
||||
private static int Parse(string line)
|
||||
{
|
||||
IntPtr t = Marshal.StringToHGlobalUni(line);
|
||||
try { return ((delegate* unmanaged[Cdecl]<IntPtr, int>)Api->InvokeChatParserFn)(t); }
|
||||
finally { Marshal.FreeHGlobal(t); }
|
||||
}
|
||||
|
||||
private static int Write(string line, int type)
|
||||
{
|
||||
IntPtr t = Marshal.StringToHGlobalUni(line);
|
||||
try { return ((delegate* unmanaged[Cdecl]<IntPtr, int, int>)Api->WriteToChatFn)(t, type); }
|
||||
finally { Marshal.FreeHGlobal(t); }
|
||||
}
|
||||
|
||||
private static void Chat()
|
||||
{
|
||||
// Without plugins: straight to the server.
|
||||
int m = F.Mark;
|
||||
T.Eq(Parse("hello there"), 1, "InvokeChatParser bare text");
|
||||
byte[] p = One(m, 0x0015, "bare text -> Talk");
|
||||
int at = 0;
|
||||
T.Eq(S16(p, ref at), "hello there", "Talk text");
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(Parse("/tell Bob Smith, meet at the lifestone"), 1, "/tell");
|
||||
p = One(m, 0x005D, "/tell -> Tell");
|
||||
at = 0;
|
||||
string msg = S16(p, ref at), target = S16(p, ref at);
|
||||
T.Check(msg == "meet at the lifestone" && target == "Bob Smith", $"Tell payload (message '{msg}', target '{target}')");
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(Parse("/myquests"), 1, "an unknown slash command");
|
||||
at = 0;
|
||||
T.Eq(S16(One(m, 0x0015, "/myquests -> Talk"), ref at), "@myquests", "sent as an @ server command");
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(Parse("/f anyone?"), 0, "/f refused headless");
|
||||
T.Eq(F.ActionsSince(m).Count, 0, "nothing sent for /f");
|
||||
m = F.Mark;
|
||||
T.Eq(Parse("/e waves"), 1, "/e");
|
||||
One(m, 0x01DF, "/e -> Emote");
|
||||
|
||||
// With a plugin: offered first, eaten lines stay home.
|
||||
var host = new PluginHost(F.Context);
|
||||
try
|
||||
{
|
||||
var plugin = new PluginHost.Plugin
|
||||
{
|
||||
Path = "fake",
|
||||
Name = "FakeChat",
|
||||
Exports = new Dictionary<string, IntPtr>
|
||||
{
|
||||
["RynthPluginOnChatBarEnter"] = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, int*, void>)&FakeChatBarEnter,
|
||||
},
|
||||
Initialized = true,
|
||||
};
|
||||
var list = (List<PluginHost.Plugin>)typeof(PluginHost).GetField("_plugins", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(host)!;
|
||||
list.Add(plugin);
|
||||
ChatBarLines.Clear();
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(Parse("/ra start"), 1, "a line a plugin eats");
|
||||
T.Check(ChatBarLines.SequenceEqual(new[] { "/ra start" }), "offered to the plugin's OnChatBarEnter");
|
||||
T.Eq(F.ActionsSince(m).Count, 0, "an eaten line isn't sent");
|
||||
|
||||
m = F.Mark;
|
||||
T.Eq(Parse("good morning"), 1, "a line no plugin eats");
|
||||
One(m, 0x0015, "not eaten -> Talk");
|
||||
|
||||
ChatBarLines.Clear();
|
||||
m = F.Mark;
|
||||
T.Eq(Parse("/chain"), 1, "a plugin chaining InvokeChatParser from its handler");
|
||||
T.Check(ChatBarLines.SequenceEqual(new[] { "/chain" }), "the chained line isn't offered again (no loop)");
|
||||
at = 0;
|
||||
T.Eq(S16(One(m, 0x0015, "chained line -> Talk"), ref at), "@ra chained", "the chained line goes to the server");
|
||||
}
|
||||
finally
|
||||
{
|
||||
F.Context.Plugins = null;
|
||||
}
|
||||
|
||||
// WriteToChat: logged and echoed as chat-window text, one line per 100 ms.
|
||||
F.Now += 1000;
|
||||
Drain();
|
||||
var logged = new List<string>();
|
||||
Action<string> sink = F.Context.LogSink;
|
||||
F.Context.LogSink = logged.Add;
|
||||
try
|
||||
{
|
||||
T.Eq(Write("RynthAi: buffing", 5), 1, "WriteToChat");
|
||||
T.Eq(Write("too soon", 5), 0, "a second line within 100 ms is dropped");
|
||||
F.Now += 100;
|
||||
T.Eq(Write("bad\u0001line", 5), 0, "control characters refused");
|
||||
T.Eq(Write("later", 0x16), 1, "after 100 ms");
|
||||
}
|
||||
finally { F.Context.LogSink = sink; }
|
||||
T.Check(logged.Any(l => l.Contains("RynthAi: buffing")), "WriteToChat logged");
|
||||
var echo = Drain().OfType<PluginEvent.ChatWindowText>().ToList();
|
||||
T.Check(echo.Count == 2 && echo[0].Text == "RynthAi: buffing" && echo[0].ChatType == 5 && echo[1].ChatType == 0x16,
|
||||
"echoed to the plugins as chat-window text");
|
||||
}
|
||||
|
||||
// ── confirmations, jumps ────────────────────────────────────────────────
|
||||
|
||||
private static void Confirmation()
|
||||
{
|
||||
var arm = (delegate* unmanaged[Cdecl]<uint, int, int, int>)Api->ArmConfirmationFn;
|
||||
var last = (delegate* unmanaged[Cdecl]<uint*, uint*, int*, int*, int*, int>)Api->GetLastConfirmationFn;
|
||||
T.Eq(arm(0, 50, 1000), -3, "ArmConfirmation bad type");
|
||||
T.Eq(arm(5, 50, 10_000), 1, "ArmConfirmation(craft, 50%)");
|
||||
int m = F.Mark;
|
||||
F.Context.OnConfirmationRequest(5, 0x1234, "You determine that you have a 38 percent chance to succeed.");
|
||||
byte[] p = One(m, 0x0275, "declined prompt answered");
|
||||
T.Check(U32(p, 0) == 5 && U32(p, 4) == 0x1234 && U32(p, 8) == 0, "ConfirmationResponse (type, context, no)");
|
||||
uint type, ctx; int pct, outcome, age;
|
||||
int seq = last(&type, &ctx, &pct, &outcome, &age);
|
||||
T.Check(seq >= 1 && type == 5 && ctx == 0x1234 && pct == 38 && outcome == 3, $"last confirmation (seq {seq}, pct {pct}, outcome {outcome})");
|
||||
|
||||
m = F.Mark;
|
||||
F.Context.OnConfirmationRequest(5, 0x1235, "You determine that you have a 90 percent chance to succeed.");
|
||||
T.Eq(F.ActionsSince(m).Count, 0, "one-shot: an unarmed prompt isn't answered");
|
||||
last(&type, &ctx, &pct, &outcome, &age);
|
||||
T.Eq(outcome, 1, "unarmed prompt: Shown");
|
||||
|
||||
arm(5, 50, 10_000);
|
||||
m = F.Mark;
|
||||
F.Context.OnConfirmationRequest(5, 0x1236, "You determine that you have a 90 percent chance to succeed.");
|
||||
T.Eq(U32(One(m, 0x0275, "accepted prompt answered"), 8), 1u, "answered yes");
|
||||
}
|
||||
|
||||
private static void Jumps()
|
||||
{
|
||||
int m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->TapJumpFn)(), 1, "TapJump");
|
||||
byte[] p = One(m, 0xF61B, "TapJump -> Jump");
|
||||
T.Check(p.Length >= 16 && F32(p, 0) == 0f && F32(p, 12) > 0f, "tap jump: extent 0, upward velocity");
|
||||
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int>)Api->CommenceJumpFn)(), 1, "CommenceJump");
|
||||
F.Now += 500;
|
||||
m = F.Mark;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<int, int>)Api->DoJumpFn)(1), 1, "DoJump");
|
||||
p = One(m, 0xF61B, "DoJump -> Jump");
|
||||
T.Check(Math.Abs(F32(p, 0) - 0.5f) < 0.01f, $"half a second's charge = extent 0.5 (got {F32(p, 0)})");
|
||||
}
|
||||
|
||||
// ── driving ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static WorldPosition Pos => F.Session.World.PlayerObject!.Position!.Value;
|
||||
|
||||
private static (float X, float Y) Global(WorldPosition p) => (p.X + (p.Cell >> 24) * 192f, p.Y + ((p.Cell >> 16) & 0xFF) * 192f);
|
||||
|
||||
private static List<uint> Types(int mark) => F.ActionsSince(mark).Select(a => a.Type).ToList();
|
||||
|
||||
private static void Drive()
|
||||
{
|
||||
var autorun = (delegate* unmanaged[Cdecl]<int, int>)Api->SetAutoRunFn;
|
||||
var turnTo = (delegate* unmanaged[Cdecl]<float, int>)Api->TurnToHeadingFn;
|
||||
var stop = (delegate* unmanaged[Cdecl]<int>)Api->StopCompletelyFn;
|
||||
var setMotion = (delegate* unmanaged[Cdecl]<uint, int, int>)Api->SetMotionFn;
|
||||
T.Check(F.Session.World.PlayerObject?.Position != null, "player has a position");
|
||||
if (F.Session.World.PlayerObject?.Position == null) return;
|
||||
if (F.Session.Moving) F.Session.StopMoving();
|
||||
|
||||
// Autorun east for 3 s.
|
||||
var start = Global(Pos);
|
||||
int m = F.Mark;
|
||||
T.Eq(autorun(1), 1, "SetAutoRun(1)");
|
||||
T.Eq(turnTo(90f), 1, "TurnToHeading(90)");
|
||||
var sent = F.ActionsSince(m);
|
||||
T.Check(sent.Count >= 1 && sent[0].Type == 0xF61C, "autorun: MoveToState first");
|
||||
if (sent.Count >= 1 && sent[0].Type == 0xF61C)
|
||||
{
|
||||
byte[] mts = sent[0].Payload;
|
||||
T.Check(U32(mts, 0) == 0x0D && U32(mts, 4) == 2 && U32(mts, 8) == MotionCommand.WalkForward && U32(mts, 12) == 2,
|
||||
$"MoveToState = run forward (flags 0x{U32(mts, 0):X})");
|
||||
}
|
||||
Advance(3000);
|
||||
var end = Global(Pos);
|
||||
float dx = end.X - start.X, dy = end.Y - start.Y;
|
||||
float speed = F.Session.MoveSpeed;
|
||||
T.Info($"3 s of autorun at {speed:F2} m/s moved ({dx:F2}, {dy:F2}); heading {ClientSession.HeadingDegrees(Pos):F1}");
|
||||
T.Check(dx > speed * 2.5f && dx < speed * 3.3f, $"moved east about 3 s x {speed:F2} m/s (dx {dx:F2})");
|
||||
T.Check(Math.Abs(dy) < 0.5f, $"not north/south (dy {dy:F2})");
|
||||
T.Check(Math.Abs(ClientSession.HeadingDegrees(Pos) - 90f) < 0.5f, "facing east");
|
||||
var types = Types(m);
|
||||
int reports = types.Count(t => t == 0xF753);
|
||||
T.Check(reports >= 5 && reports <= 9, $"AutonomousPosition about every 0.5 s ({reports} in 3 s)");
|
||||
T.Eq(types.Count(t => t == 0xF61C), 1, "one MoveToState while the keys didn't change");
|
||||
var lastReport = F.ActionsSince(m).Last(a => a.Type == 0xF753).Payload;
|
||||
T.Check(U32(lastReport, 0) == Pos.Cell && Math.Abs(F32(lastReport, 4) - Pos.X) <= speed * 0.6f, "the reports carry the new position");
|
||||
|
||||
// Stop.
|
||||
m = F.Mark;
|
||||
T.Eq(stop(), 1, "StopCompletely");
|
||||
sent = F.ActionsSince(m);
|
||||
T.Check(sent.Count == 2 && sent[0].Type == 0xF61C && U32(sent[0].Payload, 0) == 0 && sent[1].Type == 0xF753,
|
||||
$"stop: MoveToState (no keys) + position (got {string.Join(", ", sent.Select(s => $"0x{s.Type:X4}"))})");
|
||||
var stopped = Global(Pos);
|
||||
m = F.Mark;
|
||||
Advance(1000);
|
||||
var after = Global(Pos);
|
||||
T.Check(Math.Abs(after.X - stopped.X) < 0.01f && Math.Abs(after.Y - stopped.Y) < 0.01f, "stays put after the stop");
|
||||
T.Eq(Types(m).Count(t => t is 0xF61C or 0xF753), 0, "nothing sent standing still");
|
||||
T.Eq(autorun(0), 1, "SetAutoRun(0) when already off");
|
||||
T.Eq(F.ActionsSince(m).Count, 0, "an unchanged autorun sends nothing");
|
||||
|
||||
// Turning in place: SetMotion(TurnRight) for 1 s turns about 135 degrees.
|
||||
float h0 = ClientSession.HeadingDegrees(Pos);
|
||||
m = F.Mark;
|
||||
T.Eq(setMotion(TurnRight, 1), 1, "SetMotion(TurnRight, on)");
|
||||
Advance(1000);
|
||||
T.Eq(setMotion(TurnRight, 0), 1, "SetMotion(TurnRight, off)");
|
||||
float turned = (ClientSession.HeadingDegrees(Pos) - h0 + 360f) % 360f;
|
||||
T.Check(turned > 110f && turned < 160f, $"turned right about 135 deg in 1 s (got {turned:F1})");
|
||||
var turnSent = F.ActionsSince(m);
|
||||
T.Check(turnSent.Count >= 2 && turnSent[0].Type == 0xF61C && (U32(turnSent[0].Payload, 0) & 0x100) != 0, "turn: MoveToState with the turn command");
|
||||
T.Check(turnSent.Last(a => a.Type == 0xF61C).Payload is var lp && U32(lp, 0) == 0, "turn released: MoveToState stop");
|
||||
var turnedAt = Global(Pos);
|
||||
T.Check(Math.Abs(turnedAt.X - stopped.X) < 0.01f, "turning in place doesn't move");
|
||||
|
||||
// TurnToHeading standing still: the heading goes out with the next step.
|
||||
m = F.Mark;
|
||||
turnTo(180f);
|
||||
T.Eq(F.ActionsSince(m).Count, 0, "TurnToHeading standing still: nothing yet");
|
||||
Advance(200);
|
||||
T.Check(Types(m).Contains(0xF753u), "the new heading is reported within a step");
|
||||
T.Check(Math.Abs(ClientSession.HeadingDegrees(Pos) - 180f) < 0.5f, "facing south");
|
||||
|
||||
// Backwards (DoMovement / StopMovement) moves north while facing south, slower.
|
||||
var b0 = Global(Pos);
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, float, int, int>)Api->DoMovementFn)(WalkBackwards, 1f, 1), 1, "DoMovement(WalkBackwards)");
|
||||
Advance(1000);
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, int>)Api->StopMovementFn)(WalkBackwards, 1), 1, "StopMovement(WalkBackwards)");
|
||||
var b1 = Global(Pos);
|
||||
T.Check(b1.Y - b0.Y > speed * 0.4f && b1.Y - b0.Y < speed * 0.8f, $"backwards: north at ~0.65 x speed (dy {b1.Y - b0.Y:F2})");
|
||||
T.Check(!F.Session.Driving, "no keys held after the stop");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, int, int>)Api->SetMotionFn)(0x10000057, 1), 0, "an unsupported motion (an emote) refused");
|
||||
}
|
||||
|
||||
private static void DriveAndWalks()
|
||||
{
|
||||
var autorun = (delegate* unmanaged[Cdecl]<int, int>)Api->SetAutoRunFn;
|
||||
var stop = (delegate* unmanaged[Cdecl]<int>)Api->StopCompletelyFn;
|
||||
ClientSession s = F.Session;
|
||||
if (s.World.PlayerObject?.Position == null) return;
|
||||
|
||||
// A planned walk that starts while driving ends the drive (its stop first, then the walk's run).
|
||||
autorun(1);
|
||||
Advance(300);
|
||||
WorldPosition here = Pos;
|
||||
WorldPosition goal = here with { X = here.X + (here.X < 96 ? 20 : -20) };
|
||||
int m = F.Mark;
|
||||
s.WalkTo(goal);
|
||||
Advance(200);
|
||||
T.Check(!s.Driving && s.Moving, "WalkTo takes over from the drive");
|
||||
var mts = F.ActionsSince(m).Where(a => a.Type == 0xF61C).Select(a => U32(a.Payload, 0)).ToList();
|
||||
T.Check(mts.Count == 2 && mts[0] == 0 && mts[1] == 0x0D, $"drive stop, then the walk's run ({string.Join(", ", mts.Select(x => $"0x{x:X}"))})");
|
||||
|
||||
// A drive key cancels the planned walk.
|
||||
m = F.Mark;
|
||||
T.Eq(autorun(1), 1, "SetAutoRun(1) during a walk");
|
||||
T.Check(!s.Moving && s.Driving, "the drive cancels the walk");
|
||||
mts = F.ActionsSince(m).Where(a => a.Type == 0xF61C).Select(a => U32(a.Payload, 0)).ToList();
|
||||
T.Check(mts.Count == 1 && mts[0] == 0x0D, $"just the drive's run goes out ({string.Join(", ", mts.Select(x => $"0x{x:X}"))})");
|
||||
stop();
|
||||
|
||||
// The server's move-to pauses the drive: no MoveToState while it lasts, the keys go out once it ends.
|
||||
MethodInfo begin = typeof(ClientSession).GetMethod("BeginMove", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
begin.Invoke(s, new object[] { 0u, new[] { Pos with { X = Pos.X + (Pos.X < 96 ? 30 : -30) } }, 0.3f, 15_000L, true });
|
||||
T.Check(s.ServerMoving, "server move-to in progress");
|
||||
m = F.Mark;
|
||||
T.Eq(autorun(1), 1, "SetAutoRun(1) during the server's move-to");
|
||||
Advance(600);
|
||||
var during = Types(m);
|
||||
T.Eq(during.Count(t => t == 0xF61C), 0, "no MoveToState during the server's move-to");
|
||||
T.Check(during.Contains(0xF753u), "the server's move-to still reports positions");
|
||||
m = F.Mark;
|
||||
s.StopMoving();
|
||||
Advance(200);
|
||||
T.Check(!s.Moving && s.Driving, "move-to over, the drive resumes");
|
||||
mts = F.ActionsSince(m).Where(a => a.Type == 0xF61C).Select(a => U32(a.Payload, 0)).ToList();
|
||||
T.Check(mts.Count == 1 && mts[0] == 0x0D, "the held keys go out once the move-to ends");
|
||||
stop();
|
||||
Advance(100);
|
||||
T.Check(!s.Driving && !s.Moving, "all stopped");
|
||||
}
|
||||
}
|
||||
27
tools/HeadlessHostTests/CoreTests.cs
Normal file
27
tools/HeadlessHostTests/CoreTests.cs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
// ============================================================================
|
||||
// CoreTests - the host's core slots (version, player id, names, screen mode).
|
||||
// ============================================================================
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace HeadlessHostTests;
|
||||
|
||||
internal static unsafe class CoreTests
|
||||
{
|
||||
[System.Runtime.CompilerServices.ModuleInitializer]
|
||||
internal static void Register() => Suites.Add("core", Run, order: 0);
|
||||
|
||||
private static void Run()
|
||||
{
|
||||
Fixture f = Fixture.Shared;
|
||||
using var _ = f.Context.Enter();
|
||||
T.Eq(f.Api->Version, 92u, "API version");
|
||||
T.Check(f.Api->ImGuiContext == IntPtr.Zero && f.Api->GameHwnd == IntPtr.Zero, "no ImGui, no window");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint>)f.Api->GetPlayerIdFn)(), 0x50000001u, "GetPlayerId while in the world");
|
||||
T.Eq(Marshal.PtrToStringAnsi(((delegate* unmanaged[Cdecl]<IntPtr>)f.Api->GetAccountNameFn)()), Fixture.Account, "account name");
|
||||
T.Eq(Marshal.PtrToStringAnsi(((delegate* unmanaged[Cdecl]<IntPtr>)f.Api->GetWorldNameFn)()), "RynthAce", "world name");
|
||||
int mode = 0;
|
||||
T.Check(((delegate* unmanaged[Cdecl]<int*, int>)f.Api->GetScreenModeFn)(&mode) == 1 && mode == 0x10000008, "screen mode: in world");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint>)f.Api->GetClientHookFlagsFn)(), 0x1FFFFu, "client hook flags");
|
||||
}
|
||||
}
|
||||
31
tools/HeadlessHostTests/HeadlessHostTests.csproj
Normal file
31
tools/HeadlessHostTests/HeadlessHostTests.csproj
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the headless plugin host's API (src/RynthCore.Headless/Host): a session
|
||||
replayed from a captured ACE session (tools/HeadlessNetTests/Captures/ace-p1-session.txt)
|
||||
gives a real world model; the API table is built and its functions are called through the
|
||||
same function pointers plugins use; the game actions they send are decoded and checked.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>HeadlessHostTests</RootNamespace>
|
||||
<AssemblyName>HeadlessHostTests</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Left out of the public source snapshots (it holds a live login): the tests then skip (Program.Main). -->
|
||||
<None Include="..\HeadlessNetTests\Captures\ace-p1-session.txt" Link="Captures\ace-p1-session.txt" CopyToOutputDirectory="PreserveNewest"
|
||||
Condition="Exists('..\HeadlessNetTests\Captures\ace-p1-session.txt')" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\RynthCore.Headless\RynthCore.Headless.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
475
tools/HeadlessHostTests/ObjectsTests.cs
Normal file
475
tools/HeadlessHostTests/ObjectsTests.cs
Normal file
|
|
@ -0,0 +1,475 @@
|
|||
// ============================================================================
|
||||
// ObjectsTests - the objects / properties slots (HostApi.Objects.cs) against the replayed
|
||||
// session: names, positions, types, flags, every property kind with the CreateObject
|
||||
// header fallbacks, ownership, container contents and counts, live ids, identify
|
||||
// (request, appraisal data, spell book, creature vitals from a synthetic reply), door
|
||||
// motion, server age, ghost removal, the v84 record, container order, wielded items.
|
||||
// ============================================================================
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Headless.Host;
|
||||
using RynthCore.Headless.Net;
|
||||
using RynthCore.Headless.World;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace HeadlessHostTests;
|
||||
|
||||
internal static unsafe class ObjectsTests
|
||||
{
|
||||
[System.Runtime.CompilerServices.ModuleInitializer]
|
||||
internal static void Register() => Suites.Add("objects", Run, order: 10);
|
||||
|
||||
private const uint Player = 0x50000001;
|
||||
|
||||
private static Fixture F => Fixture.Shared;
|
||||
private static RynthCoreApiNative* Api => F.Api;
|
||||
private static WorldState W => F.Session.World;
|
||||
|
||||
private static WorldObject First(string name) => W.Objects.Values.Where(o => o.Name == name).OrderBy(o => o.Id).First();
|
||||
|
||||
// ── the slots, called through the table as plugins do ──────────────────
|
||||
|
||||
private static string? Name(uint id) => Marshal.PtrToStringAnsi(((delegate* unmanaged[Cdecl]<uint, IntPtr>)Api->GetObjectNameFn)(id));
|
||||
|
||||
private static bool Int(uint id, uint stype, out int v)
|
||||
{
|
||||
int x = 0;
|
||||
bool ok = ((delegate* unmanaged[Cdecl]<uint, uint, int*, int>)Api->GetObjectIntPropertyFn)(id, stype, &x) != 0;
|
||||
v = x;
|
||||
return ok;
|
||||
}
|
||||
|
||||
private static int? IntOrNull(uint id, uint stype) => Int(id, stype, out int v) ? v : null;
|
||||
|
||||
private static double? Dbl(uint id, uint stype)
|
||||
{
|
||||
double x = 0;
|
||||
return ((delegate* unmanaged[Cdecl]<uint, uint, double*, int>)Api->GetObjectDoublePropertyFn)(id, stype, &x) != 0 ? x : null;
|
||||
}
|
||||
|
||||
private static long? Quad(uint id, uint stype)
|
||||
{
|
||||
long x = 0;
|
||||
return ((delegate* unmanaged[Cdecl]<uint, uint, long*, int>)Api->GetObjectQuadPropertyFn)(id, stype, &x) != 0 ? x : null;
|
||||
}
|
||||
|
||||
private static bool? Bool(uint id, uint stype)
|
||||
{
|
||||
int x = 0;
|
||||
return ((delegate* unmanaged[Cdecl]<uint, uint, int*, int>)Api->GetObjectBoolPropertyFn)(id, stype, &x) != 0 ? x != 0 : null;
|
||||
}
|
||||
|
||||
private static string? Str(uint id, uint stype) => Marshal.PtrToStringAnsi(((delegate* unmanaged[Cdecl]<uint, uint, IntPtr>)Api->GetObjectStringPropertyFn)(id, stype));
|
||||
|
||||
private static uint? Did(uint id, uint stype)
|
||||
{
|
||||
uint x = 0;
|
||||
return ((delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)Api->GetObjectDataIdPropertyFn)(id, stype, &x) != 0 ? x : null;
|
||||
}
|
||||
|
||||
private static uint? Iid(uint id, uint stype)
|
||||
{
|
||||
uint x = 0;
|
||||
return ((delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)Api->GetObjectInstanceIdPropertyFn)(id, stype, &x) != 0 ? x : null;
|
||||
}
|
||||
|
||||
private static uint[] Contents(uint container, int max = 512)
|
||||
{
|
||||
uint[] buf = new uint[max];
|
||||
fixed (uint* p = buf)
|
||||
{
|
||||
int n = ((delegate* unmanaged[Cdecl]<uint, uint*, int, int>)Api->GetContainerContentsFn)(container, p, max);
|
||||
return buf.Take(n).ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static int SpellIds(uint id, uint[] buf)
|
||||
{
|
||||
fixed (uint* p = buf)
|
||||
return ((delegate* unmanaged[Cdecl]<uint, uint*, int, int>)Api->GetObjectSpellIdsFn)(id, p, buf.Length);
|
||||
}
|
||||
|
||||
private static int Call1(IntPtr fn, uint id) => ((delegate* unmanaged[Cdecl]<uint, int>)fn)(id);
|
||||
|
||||
private static void Run()
|
||||
{
|
||||
using var _ = F.Context.Enter();
|
||||
Identity();
|
||||
Positions();
|
||||
Properties();
|
||||
Ownership();
|
||||
Identify();
|
||||
Physics();
|
||||
Removal();
|
||||
Record();
|
||||
OrderAndWielded();
|
||||
}
|
||||
|
||||
private static void Identity()
|
||||
{
|
||||
// The captured character's own name, from the server's character list (no "+" admin prefix).
|
||||
string listed = F.Session.Characters.FirstOrDefault(c => c.Id == Player).Name?.TrimStart('+') ?? "";
|
||||
T.Check(listed.Length > 0, "the character list names the player");
|
||||
T.Eq(Name(Player), listed, "GetObjectName: the player");
|
||||
WorldObject boots = First("Viamontian Laced Boots");
|
||||
T.Eq(Name(boots.Id), "Viamontian Laced Boots", "GetObjectName: an item in the pack");
|
||||
T.Check(Name(0) == null && Name(0x7FFFFFF0) == null, "GetObjectName: 0 / unknown id answer null");
|
||||
|
||||
WorldObject sack = First("Sack");
|
||||
uint flags = 0;
|
||||
var itemType = (delegate* unmanaged[Cdecl]<uint, uint*, int>)Api->GetItemTypeFn;
|
||||
T.Check(itemType(sack.Id, &flags) == 1 && flags == 0x200, $"GetItemType: Sack = Container 0x200 (got 0x{flags:X})");
|
||||
T.Check(itemType(Player, &flags) == 1 && flags == 0x10, "GetItemType: the player = Creature");
|
||||
T.Eq(itemType(0x7FFFFFF0, &flags), 0, "GetItemType: unknown id");
|
||||
T.Eq(itemType(sack.Id, null), 0, "GetItemType: null out-pointer");
|
||||
|
||||
var bitfield = (delegate* unmanaged[Cdecl]<uint, uint>)Api->GetObjectBitfieldFn;
|
||||
var wcid = (delegate* unmanaged[Cdecl]<uint, uint>)Api->GetObjectWcidFn;
|
||||
T.Eq(bitfield(sack.Id), 0x13u, "GetObjectBitfield: Sack (Openable|Inscribable|Requires... 0x13)");
|
||||
T.Eq(wcid(sack.Id), 166u, "GetObjectWcid: Sack");
|
||||
T.Eq(wcid(0x7FFFFFF0), 0u, "GetObjectWcid: unknown id");
|
||||
|
||||
WorldObject slasher = First("Olthoi Slasher");
|
||||
WorldObject shop = First("Shopkeeper Renald the Elder");
|
||||
T.Eq(Call1(Api->ObjectIsAttackableFn, slasher.Id), 1, "ObjectIsAttackable: a monster (Attackable bit)");
|
||||
T.Eq(Call1(Api->ObjectIsAttackableFn, shop.Id), 0, "ObjectIsAttackable: a vendor NPC");
|
||||
T.Eq(Call1(Api->ObjectIsAttackableFn, Player), 0, "ObjectIsAttackable: never the player");
|
||||
T.Eq(Call1(Api->ObjectIsAttackableFn, sack.Id), 0, "ObjectIsAttackable: an item");
|
||||
T.Eq(Call1(Api->ObjectIsAttackableFn, 0x7FFFFFF0), 0, "ObjectIsAttackable: unknown id");
|
||||
T.Eq(Call1(Api->ObjectIsAttackableFn, First("Corpse of Drudge Skulker").Id), 0, "ObjectIsAttackable: a corpse");
|
||||
T.Eq(Call1(Api->ObjectIsAttackableFn, First("Trade Note (250,000)").Id), 0, "ObjectIsAttackable: an item with the Attackable bit");
|
||||
// Players: only PK vs PK (or PK-lite vs PK-lite).
|
||||
static WorldObject Pc(uint id, uint bf) => new(id) { Desc = new RynthCore.Headless.Messages.ObjectCreateData { Id = id, ItemType = 0x10, DescriptionFlags = bf } };
|
||||
T.Check(RynthCore.Headless.Host.Objects.ObjectProps.IsAttackable(Pc(2, 0x38), Pc(1, 0x38)), "attackable: PK vs PK");
|
||||
T.Check(!RynthCore.Headless.Host.Objects.ObjectProps.IsAttackable(Pc(2, 0x38), Pc(1, 0x18)), "not attackable: PK vs non-PK");
|
||||
T.Check(!RynthCore.Headless.Host.Objects.ObjectProps.IsAttackable(Pc(2, 0x18), Pc(1, 0x18)), "not attackable: non-PK players");
|
||||
T.Check(RynthCore.Headless.Host.Objects.ObjectProps.IsAttackable(Pc(2, 0x2000018), Pc(1, 0x2000018)), "attackable: PK-lite vs PK-lite");
|
||||
|
||||
// Live ids: every created object, ascending; the total even when the buffer is short.
|
||||
int created = W.Objects.Values.Count(o => o.Desc.Id != 0);
|
||||
var live = (delegate* unmanaged[Cdecl]<uint*, int, int>)Api->GetLiveObjectIdsFn;
|
||||
uint[] ids = new uint[1024];
|
||||
int total;
|
||||
fixed (uint* p = ids) total = live(p, ids.Length);
|
||||
T.Eq(total, created, "GetLiveObjectIds: the count of created objects");
|
||||
T.Check(ids.Take(total).Contains(Player) && ids.Take(total).Contains(sack.Id), "GetLiveObjectIds: player and pack items listed");
|
||||
T.Check(ids.Take(total).SequenceEqual(ids.Take(total).OrderBy(x => x)), "GetLiveObjectIds: ascending");
|
||||
uint* small = stackalloc uint[3];
|
||||
T.Eq(live(small, 3), created, "GetLiveObjectIds: the total with a short buffer");
|
||||
T.Eq(live(null, 0), created, "GetLiveObjectIds: count only");
|
||||
}
|
||||
|
||||
private static void Positions()
|
||||
{
|
||||
var pos = (delegate* unmanaged[Cdecl]<uint, uint*, float*, float*, float*, int>)Api->GetObjectPositionFn;
|
||||
uint cell = 0; float x = 0, y = 0, z = 0;
|
||||
WorldObject me = W.PlayerObject!;
|
||||
T.Check(pos(Player, &cell, &x, &y, &z) == 1 && cell == me.Position!.Value.Cell && x == me.Position.Value.X && z == me.Position.Value.Z,
|
||||
$"GetObjectPosition: the player (cell 0x{cell:X8} {x:F1},{y:F1},{z:F1})");
|
||||
WorldObject slasher = First("Olthoi Slasher");
|
||||
T.Check(pos(slasher.Id, &cell, &x, &y, &z) == 1 && cell == slasher.Position!.Value.Cell, "GetObjectPosition: a monster");
|
||||
cell = 0xDEAD;
|
||||
T.Check(pos(First("Viamontian Laced Boots").Id, &cell, &x, &y, &z) == 0 && cell == 0xDEAD, "GetObjectPosition: a pack item has none (out untouched)");
|
||||
T.Eq(pos(Player, null, &x, &y, &z), 0, "GetObjectPosition: null out-pointer");
|
||||
T.Eq(pos(0x7FFFFFF0, &cell, &x, &y, &z), 0, "GetObjectPosition: unknown id");
|
||||
}
|
||||
|
||||
private static void Properties()
|
||||
{
|
||||
// Header fallbacks (never identified): a stack's size, value, burden, type.
|
||||
WorldObject note = First("Trade Note (250,000)");
|
||||
T.Eq(IntOrNull(note.Id, 12), 215, "int 12 StackSize: Trade Notes from CreateObject");
|
||||
T.Eq(IntOrNull(note.Id, 19), 53750000, "int 19 Value");
|
||||
T.Eq(IntOrNull(note.Id, 5), 215, "int 5 EncumbranceVal (burden)");
|
||||
T.Eq(IntOrNull(note.Id, 1), 0x40000, "int 1 ItemType");
|
||||
T.Eq(IntOrNull(note.Id, 11), (int?)note.Desc.MaxStackSize, "int 11 MaxStackSize");
|
||||
WorldObject pyreals = W.Objects.Values.First(o => o.Name == "Pyreal" && o.ContainerId != 0);
|
||||
T.Eq(IntOrNull(pyreals.Id, 12), (int)pyreals.StackSize, $"int 12: the Pyreal stack in a pack ({pyreals.StackSize})");
|
||||
WorldObject sack = First("Sack");
|
||||
T.Eq(IntOrNull(sack.Id, 6), 24, "int 6 ItemsCapacity: Sack");
|
||||
T.Eq(IntOrNull(sack.Id, 12), null, "int 12 on a non-stackable answers nothing");
|
||||
T.Eq(IntOrNull(sack.Id, 9999), null, "unknown int stype");
|
||||
WorldObject coat = First("Academy Coat");
|
||||
T.Eq(IntOrNull(coat.Id, 10), 0x1E00, "int 10 CurrentWieldedLocation: the worn Academy Coat");
|
||||
T.Eq(IntOrNull(coat.Id, 9), (int?)coat.Desc.ValidLocations, "int 9 ValidLocations");
|
||||
T.Eq(IntOrNull(First("Viamontian Laced Boots").Id, 10), null, "int 10 on an item in a pack answers nothing");
|
||||
|
||||
// The player's own tables (PlayerDescription): every int, int64 and bool as the world model has it.
|
||||
WorldObject me = W.PlayerObject!;
|
||||
T.Check(me.Ints.Count > 0 && me.Ints.All(kv => IntOrNull(Player, kv.Key) == kv.Value), $"player ints from PlayerDescription ({me.Ints.Count})");
|
||||
T.Check(me.Int64s.All(kv => Quad(Player, kv.Key) == kv.Value), $"player int64s ({me.Int64s.Count})");
|
||||
T.Check(me.Bools.All(kv => Bool(Player, kv.Key) == kv.Value), $"player bools ({me.Bools.Count})");
|
||||
T.Check(me.Strings.All(kv => Str(Player, kv.Key) == kv.Value), $"player strings ({me.Strings.Count})");
|
||||
T.Eq(Quad(Player, 0x7FFF), null, "unknown quad stype");
|
||||
|
||||
// Identify-merged tables (the boots' replayed identify).
|
||||
WorldObject boots = First("Viamontian Laced Boots");
|
||||
T.Check(boots.Ints.Count > 0 && boots.Ints.Where(kv => kv.Key is not (10 or 12)).All(kv => IntOrNull(boots.Id, kv.Key) == kv.Value),
|
||||
$"boots: identify ints ({boots.Ints.Count})");
|
||||
T.Check(boots.Floats.All(kv => Dbl(boots.Id, kv.Key) == kv.Value), $"boots: identify floats ({boots.Floats.Count})");
|
||||
T.Check(boots.Strings.All(kv => Str(boots.Id, kv.Key) == kv.Value), $"boots: identify strings ({boots.Strings.Count})");
|
||||
|
||||
// Strings and doubles from the header.
|
||||
T.Eq(Str(sack.Id, 1), "Sack", "string 1 Name from the header");
|
||||
T.Eq(Str(sack.Id, 9999), null, "unknown string stype");
|
||||
WorldObject? withRadius = W.Objects.Values.FirstOrDefault(o => o.Desc.UseRadius is > 0f && !o.Floats.ContainsKey(54));
|
||||
if (withRadius != null) T.Eq(Dbl(withRadius.Id, 54), (double)withRadius.Desc.UseRadius!.Value, $"double 54 UseRadius ({withRadius.Name})");
|
||||
else T.Info("no object with a UseRadius in the capture");
|
||||
WorldObject? worked = W.Objects.Values.FirstOrDefault(o => o.Desc.Workmanship is > 0f);
|
||||
if (worked != null)
|
||||
{
|
||||
T.Eq(Dbl(worked.Id, 280), (double)worked.Desc.Workmanship!.Value, $"double 280 workmanship ({worked.Name})");
|
||||
if (!worked.Ints.ContainsKey(105)) T.Eq(IntOrNull(worked.Id, 105), (int)MathF.Round(worked.Desc.Workmanship.Value), "int 105 ItemWorkmanship from the header");
|
||||
}
|
||||
else T.Info("no object with a workmanship in the capture");
|
||||
T.Eq(Dbl(sack.Id, 9999), null, "unknown double stype");
|
||||
|
||||
// Data ids and instance ids.
|
||||
T.Eq(Did(sack.Id, 8), sack.Desc.Icon, "data id 8 Icon from the header");
|
||||
T.Check((sack.Desc.Icon & 0xFF000000) == 0x06000000, "the icon is a full 0x06 data id");
|
||||
T.Eq(Did(sack.Id, 9999), null, "unknown data id stype");
|
||||
T.Eq(Iid(boots.Id, 2), Player, "instance id 2 Container: boots in the main pack");
|
||||
T.Eq(Iid(coat.Id, 3), Player, "instance id 3 Wielder: the worn coat");
|
||||
T.Eq(Iid(coat.Id, 2), null, "instance id 2 of a wielded item answers nothing");
|
||||
T.Eq(Iid(0x7FFFFFF0, 2), null, "instance id of an unknown object");
|
||||
|
||||
// Null out-pointers.
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int*, int>)Api->GetObjectIntPropertyFn)(note.Id, 12, null), 0, "int: null out-pointer");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, double*, int>)Api->GetObjectDoublePropertyFn)(note.Id, 54, null), 0, "double: null out-pointer");
|
||||
}
|
||||
|
||||
private static void Ownership()
|
||||
{
|
||||
WorldObject coat = First("Academy Coat");
|
||||
uint c = 1, w = 1, l = 1;
|
||||
var own = (delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, int>)Api->GetObjectOwnershipInfoFn;
|
||||
T.Check(own(coat.Id, &c, &w, &l) == 1 && c == 0 && w == Player && l == 0x1E00, $"GetObjectOwnershipInfo: worn coat ({c:X8},{w:X8},0x{l:X})");
|
||||
WorldObject boots = First("Viamontian Laced Boots");
|
||||
T.Check(own(boots.Id, &c, &w, &l) == 1 && c == Player && w == 0 && l == 0, "GetObjectOwnershipInfo: boots in the main pack");
|
||||
T.Eq(own(boots.Id, null, &w, &l), 0, "GetObjectOwnershipInfo: null out-pointer");
|
||||
T.Eq(own(0x7FFFFFF0, &c, &w, &l), 0, "GetObjectOwnershipInfo: unknown id");
|
||||
var wi = (delegate* unmanaged[Cdecl]<uint, uint*, uint*, int>)Api->GetObjectWielderInfoFn;
|
||||
T.Check(wi(coat.Id, &w, &l) == 1 && w == Player && l == 0x1E00, "GetObjectWielderInfo: worn coat");
|
||||
|
||||
// A pack's contents: what the world model has in it, ascending.
|
||||
WorldObject sack = First("Sack");
|
||||
uint[] inSack = Contents(sack.Id);
|
||||
uint[] expected = W.Objects.Values.Where(o => o.ContainerId == sack.Id || o.WielderId == sack.Id).Select(o => o.Id).OrderBy(x => x).ToArray();
|
||||
T.Check(inSack.Length > 0 && inSack.SequenceEqual(expected), $"GetContainerContents: Sack holds {inSack.Length}");
|
||||
// The player: main pack + side packs/foci (PlayerState) + what she wields.
|
||||
PlayerState p = W.Player;
|
||||
uint[] mine = Contents(Player);
|
||||
var fromState = p.MainPackOrder.Concat(p.SidePackOrder).Concat(p.EquippedItems.Keys).OrderBy(x => x).ToArray();
|
||||
T.Check(mine.SequenceEqual(fromState), $"GetContainerContents: the player = main pack {p.MainPackOrder.Count} + packs {p.SidePackOrder.Count} + wielded {p.EquippedItems.Count} (got {mine.Length})");
|
||||
uint[] three = Contents(Player, 3);
|
||||
T.Check(three.SequenceEqual(fromState.Take(3)), "GetContainerContents: a short buffer gets the lowest ids");
|
||||
T.Eq(Contents(0x7FFFFFF0).Length, 0, "GetContainerContents: unknown container");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint*, int, int>)Api->GetContainerContentsFn)(Player, null, 10), 0, "GetContainerContents: null buffer");
|
||||
|
||||
T.Eq(Call1(Api->GetNumContainedItemsFn, Player), p.MainPackOrder.Count, "GetNumContainedItems: the player's main pack");
|
||||
T.Eq(Call1(Api->GetNumContainedContainersFn, Player), 7, "GetNumContainedContainers: 3 sacks + 4 foci");
|
||||
int sackItems = W.Objects.Values.Count(o => o.ContainerId == sack.Id);
|
||||
T.Eq(Call1(Api->GetNumContainedItemsFn, sack.Id), sackItems, "GetNumContainedItems: a sack");
|
||||
T.Eq(Call1(Api->GetNumContainedContainersFn, sack.Id), 0, "GetNumContainedContainers: a sack holds no packs");
|
||||
T.Eq(Call1(Api->GetNumContainedItemsFn, 0x7FFFFFF0), -1, "GetNumContainedItems: unknown id");
|
||||
}
|
||||
|
||||
// An identify reply (game event 0xC9) for a monster: one int, a two-spell book, a creature profile with attributes.
|
||||
private static byte[] IdentifyReply(uint id, uint level, uint[] spells, uint hp, uint hpMax, uint st, uint stMax, uint mp, uint mpMax)
|
||||
{
|
||||
var w = new WireWriter(128);
|
||||
w.U32(0xF7B0).U32(Player).U32(9999).U32(0xC9);
|
||||
w.U32(id).U32(0x0001 | 0x0010 | 0x0100).U32(1);
|
||||
w.U16(1).U16(8).U32(25).U32(level); // int table: Level
|
||||
w.U32((uint)spells.Length);
|
||||
foreach (uint s in spells) w.U32(s);
|
||||
w.U32(0x8).U32(hp).U32(hpMax); // creature profile, ShowAttributes
|
||||
for (int i = 0; i < 6; i++) w.U32(50);
|
||||
w.U32(st).U32(mp).U32(stMax).U32(mpMax);
|
||||
return w.ToArray();
|
||||
}
|
||||
|
||||
private static byte[] UpdateHealth(uint id, float ratio)
|
||||
=> new WireWriter(32).U32(0xF7B0).U32(Player).U32(10000).U32(0x01C0).U32(id).F32(ratio).ToArray();
|
||||
|
||||
private static void Identify()
|
||||
{
|
||||
WorldObject boots = First("Viamontian Laced Boots");
|
||||
WorldObject slasher = First("Olthoi Slasher");
|
||||
|
||||
// RequestId sends IdentifyObject (0xC8) with the id.
|
||||
int mark = F.Mark;
|
||||
T.Eq(Call1(Api->RequestIdFn, slasher.Id), 1, "RequestId: sent");
|
||||
var sent = F.ActionsSince(mark);
|
||||
T.Check(sent.Count == 1 && sent[0].Type == 0xC8 && BinaryPrimitives.ReadUInt32LittleEndian(sent[0].Payload) == slasher.Id,
|
||||
$"RequestId: game action 0xC8 with the id ({string.Join(",", sent.Select(a => $"0x{a.Type:X}"))})");
|
||||
T.Eq(Call1(Api->RequestIdFn, 0), 0, "RequestId: id 0 refused");
|
||||
|
||||
// The replayed identify of the boots.
|
||||
T.Eq(Call1(Api->HasAppraisalDataFn, boots.Id), 1, "HasAppraisalData: the identified boots");
|
||||
T.Eq(Call1(Api->HasAppraisalDataFn, slasher.Id), 0, "HasAppraisalData: a monster not identified yet");
|
||||
var lastId = (delegate* unmanaged[Cdecl]<uint, long>)Api->GetLastIdTimeFn;
|
||||
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
T.Check(Math.Abs(lastId(boots.Id) - now) < 600, "GetLastIdTime: the boots (Unix seconds)");
|
||||
T.Eq(lastId(slasher.Id), 0L, "GetLastIdTime: never identified");
|
||||
uint[] buf = new uint[16];
|
||||
int n = SpellIds(boots.Id, buf);
|
||||
T.Check(n == boots.Spells.Count && n > 0 && buf.Take(n).SequenceEqual(boots.Spells), $"GetObjectSpellIds: the boots' spell book ({n}: {string.Join(",", buf.Take(Math.Max(n, 0)))})");
|
||||
uint[] one = new uint[1];
|
||||
T.Eq(SpellIds(boots.Id, one), boots.Spells.Count, "GetObjectSpellIds: the total with a short buffer");
|
||||
T.Eq(one[0], boots.Spells[0], "GetObjectSpellIds: the first id copied");
|
||||
T.Eq(SpellIds(slasher.Id, buf), -1, "GetObjectSpellIds: no identify = -1");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint*, int, int>)Api->GetObjectSpellIdsFn)(boots.Id, null, 4), -1, "GetObjectSpellIds: null buffer = -1");
|
||||
|
||||
var vitals = (delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, uint*, uint*, uint*, int>)Api->GetTargetVitalsFn;
|
||||
uint h = 0, hm = 0, s = 0, sm = 0, m = 0, mm = 0;
|
||||
T.Eq(vitals(slasher.Id, &h, &hm, &s, &sm, &m, &mm), 0, "GetTargetVitals: nothing before an identify");
|
||||
|
||||
// A synthetic identify reply with a spell book and a creature profile.
|
||||
F.Context.Events.Drain();
|
||||
F.Receive(IdentifyReply(slasher.Id, 100, new uint[] { 0x3E1, 0x3E2 }, 150, 200, 90, 100, 40, 50));
|
||||
T.Eq(Call1(Api->HasAppraisalDataFn, slasher.Id), 1, "HasAppraisalData after the reply");
|
||||
T.Check(Math.Abs(lastId(slasher.Id) - now) < 600, "GetLastIdTime after the reply");
|
||||
T.Eq(IntOrNull(slasher.Id, 25), 100, "the reply's int table merged (Level 25)");
|
||||
n = SpellIds(slasher.Id, buf);
|
||||
T.Check(n == 2 && buf[0] == 0x3E1 && buf[1] == 0x3E2, $"GetObjectSpellIds: the reply's spell book ({n})");
|
||||
T.Check(vitals(slasher.Id, &h, &hm, &s, &sm, &m, &mm) == 1 && h == 150 && hm == 200 && s == 90 && sm == 100 && m == 40 && mm == 50,
|
||||
$"GetTargetVitals: the creature profile ({h}/{hm} {s}/{sm} {m}/{mm})");
|
||||
T.Eq(vitals(slasher.Id, null, &hm, &s, &sm, &m, &mm), 0, "GetTargetVitals: null out-pointer");
|
||||
var events = F.Context.Events.Drain();
|
||||
T.Check(events.OfType<PluginEvent.UpdateHealth>().Any(e => e.Target == slasher.Id && e.CurrentHealth == 150 && e.MaxHealth == 200),
|
||||
"the reply's creature profile is reported as a health update (as the engine does)");
|
||||
T.Eq(F.Context.MaxHealthOf(slasher.Id), 200u, "MaxHealthHook: the identify's max health");
|
||||
T.Eq(F.Context.HealthOf(slasher.Id, 0.5f), (100u, 200u), "HealthOf: ratio 0.5 of 200");
|
||||
|
||||
// UpdateHealth keeps the target's current health.
|
||||
F.Receive(UpdateHealth(slasher.Id, 0.25f));
|
||||
T.Check(vitals(slasher.Id, &h, &hm, &s, &sm, &m, &mm) == 1 && h == 50 && hm == 200, $"GetTargetVitals after UpdateHealth 0.25 ({h}/{hm})");
|
||||
}
|
||||
|
||||
private static byte[] DoorMotion(uint id, ushort command)
|
||||
=> new WireWriter(32).U32(0xF74C).U32(id).U16(1).U16(1).U16(0).U8(0).U8(0).U8(0).U8(0).U16(0x3D)
|
||||
.U32(0x2).U16(command).Align4().ToArray();
|
||||
|
||||
private static void Physics()
|
||||
{
|
||||
var heading = (delegate* unmanaged[Cdecl]<uint, float*, int>)Api->GetObjectHeadingFn;
|
||||
float hd = -1;
|
||||
WorldObject me = W.PlayerObject!;
|
||||
float expect = (float)(((-2.0 * Math.Atan2(me.Position!.Value.Qz, me.Position.Value.Qw) * 180.0 / Math.PI) % 360.0 + 720.0) % 360.0);
|
||||
T.Check(heading(Player, &hd) == 1 && hd >= 0 && hd < 360 && Math.Abs(hd - expect) < 0.01f, $"GetObjectHeading: the player ({hd:F1})");
|
||||
T.Eq(RynthCore.Headless.Host.Objects.ObjectProps.Heading(1, 0), 0f, "heading: identity rotation = north");
|
||||
T.Check(Math.Abs(RynthCore.Headless.Host.Objects.ObjectProps.Heading(MathF.Cos(-MathF.PI / 4), MathF.Sin(-MathF.PI / 4)) - 90f) < 0.01f,
|
||||
"heading: a -90 degree yaw = east (clockwise)");
|
||||
T.Eq(heading(First("Viamontian Laced Boots").Id, &hd), 0, "GetObjectHeading: a pack item has none");
|
||||
|
||||
var state = (delegate* unmanaged[Cdecl]<uint, uint*, int>)Api->GetObjectStateFn;
|
||||
uint st = 0;
|
||||
T.Check(state(Player, &st) == 1 && st == me.PhysicsState, $"GetObjectState: the player (0x{st:X})");
|
||||
T.Eq(state(0x7FFFFFF0, &st), 0, "GetObjectState: unknown id");
|
||||
|
||||
// Door On / Off from UpdateMotion (a chest stands in for a door).
|
||||
WorldObject chest = First("Chest");
|
||||
var motionOn = (delegate* unmanaged[Cdecl]<uint, int*, int>)Api->GetObjectMotionOnFn;
|
||||
int on = -1;
|
||||
T.Eq(motionOn(chest.Id, &on), 0, "GetObjectMotionOn: nothing seen yet");
|
||||
T.Eq(Call1(Api->GetObjectServerAgeFn, chest.Id), -1, "GetObjectServerAge: nothing heard since the host started");
|
||||
F.Receive(DoorMotion(chest.Id, 0x000B));
|
||||
T.Check(motionOn(chest.Id, &on) == 1 && on == 1, "GetObjectMotionOn: On (0x4000000B)");
|
||||
F.Receive(DoorMotion(chest.Id, 0x000C));
|
||||
T.Check(motionOn(chest.Id, &on) == 1 && on == 0, "GetObjectMotionOn: Off (0x4000000C)");
|
||||
int age = Call1(Api->GetObjectServerAgeFn, chest.Id);
|
||||
T.Check(age >= 0 && age < 2000, $"GetObjectServerAge: just heard ({age} ms)");
|
||||
T.Eq(Call1(Api->GetObjectServerAgeFn, 0), -1, "GetObjectServerAge: id 0");
|
||||
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint*, uint*, int, int>)Api->GetObjectPalettesFn)(chest.Id, &st, &st, 1), -1, "GetObjectPalettes: no data");
|
||||
}
|
||||
|
||||
private static void Removal()
|
||||
{
|
||||
WorldObject slasher = First("Olthoi Slasher"); // heard from (UpdateHealth) a moment ago
|
||||
WorldObject ghost = W.Objects.Values.Where(o => o.Name == "Olthoi Slasher" && o.Id != slasher.Id).OrderBy(o => o.Id).First();
|
||||
T.Eq(Call1(Api->RemoveClientObjectFn, Player), 0, "RemoveClientObject: never the player");
|
||||
T.Eq(Call1(Api->RemoveClientObjectFn, First("Sack").Id), 0, "RemoveClientObject: not a creature");
|
||||
T.Eq(Call1(Api->RemoveClientObjectFn, slasher.Id), 0, "RemoveClientObject: heard from in the last 5 s");
|
||||
F.Context.Events.Drain();
|
||||
T.Eq(Call1(Api->RemoveClientObjectFn, ghost.Id), 1, "RemoveClientObject: a quiet monster is removed");
|
||||
T.Check(W.Get(ghost.Id) == null, "the ghost is gone from the world model");
|
||||
T.Check(F.Context.Events.Drain().OfType<PluginEvent.DeleteObject>().Any(d => d.Id == ghost.Id), "plugins are told (OnDeleteObject)");
|
||||
T.Eq(Call1(Api->RemoveClientObjectFn, ghost.Id), 0, "RemoveClientObject: already gone");
|
||||
T.Eq(Name(ghost.Id), null, "the ghost has no name any more");
|
||||
}
|
||||
|
||||
private static byte[]? RecordOf(uint id)
|
||||
{
|
||||
var fn = (delegate* unmanaged[Cdecl]<uint, byte*, int, int>)Api->GetObjectPropertiesFn;
|
||||
int size = fn(id, null, 0);
|
||||
if (size <= 0) return null;
|
||||
byte[] buf = new byte[size];
|
||||
fixed (byte* p = buf)
|
||||
return fn(id, p, size) == size ? buf : null;
|
||||
}
|
||||
|
||||
private static void Record()
|
||||
{
|
||||
var fn = (delegate* unmanaged[Cdecl]<uint, byte*, int, int>)Api->GetObjectPropertiesFn;
|
||||
WorldObject boots = First("Viamontian Laced Boots");
|
||||
byte[]? rec = RecordOf(boots.Id);
|
||||
T.Check(rec != null && ObjectProperties.TryParse(rec, out _), "GetObjectProperties: the boots' record parses");
|
||||
if (rec != null && ObjectProperties.TryParse(rec, out ObjectProperties? props) && props != null)
|
||||
{
|
||||
T.Check(props.HasIdData && (props.Flags & ObjectPropertyFlags.HasCreateData) != 0 && !props.IsPlayer, $"record flags ({props.Flags})");
|
||||
T.Check(props.LastIdTime > 0, "record: last identify time");
|
||||
T.Check(props.Spells.SequenceEqual(boots.Spells), $"record: spell book ({props.Spells.Count})");
|
||||
T.Check(props.Ints.All(kv => IntOrNull(boots.Id, kv.Key) == kv.Value), $"record ints = per-key reads ({props.Ints.Count})");
|
||||
T.Check(props.Floats.All(kv => Dbl(boots.Id, kv.Key) == kv.Value), $"record floats = per-key reads ({props.Floats.Count})");
|
||||
T.Eq(props.InstanceIds.GetValueOrDefault(2u), Player, "record: container");
|
||||
T.Eq(props.Strings.GetValueOrDefault(1u), "Viamontian Laced Boots", "record: name");
|
||||
T.Eq(props.Ints.GetValueOrDefault(19u), boots.Value, "record: value from the header");
|
||||
}
|
||||
byte[]? mine = RecordOf(Player);
|
||||
T.Check(mine != null && ObjectProperties.TryParse(mine, out ObjectProperties? pp) && pp!.IsPlayer && pp.Ints.Count >= W.PlayerObject!.Ints.Count,
|
||||
"GetObjectProperties: the player's record (IsPlayer, PlayerDescription ints)");
|
||||
WorldObject note = First("Trade Note (250,000)");
|
||||
byte[]? nrec = RecordOf(note.Id);
|
||||
T.Check(nrec != null && ObjectProperties.TryParse(nrec, out ObjectProperties? np) && np!.Ints.GetValueOrDefault(12u) == 215 && !np.HasIdData,
|
||||
"GetObjectProperties: an unidentified stack (header stack size, no id data)");
|
||||
byte small = 0;
|
||||
T.Eq(fn(boots.Id, &small, 1), rec?.Length ?? -2, "GetObjectProperties: a short buffer gets the size");
|
||||
T.Eq(fn(0x7FFFFFF0, null, 0), 0, "GetObjectProperties: unknown id = 0");
|
||||
T.Eq(fn(0, null, 0), -1, "GetObjectProperties: id 0 = -1");
|
||||
T.Eq(fn(boots.Id, null, -1), -1, "GetObjectProperties: negative size = -1");
|
||||
T.Eq(fn(boots.Id, null, 10), -1, "GetObjectProperties: null buffer with a size = -1");
|
||||
}
|
||||
|
||||
private static void OrderAndWielded()
|
||||
{
|
||||
var order = (delegate* unmanaged[Cdecl]<uint, int, uint*, int, int>)Api->GetContainerOrderFn;
|
||||
PlayerState p = W.Player;
|
||||
uint[] buf = new uint[256];
|
||||
fixed (uint* b = buf)
|
||||
{
|
||||
int n = order(Player, 0, b, buf.Length);
|
||||
T.Check(n == p.MainPackOrder.Count && buf.Take(n).SequenceEqual(p.MainPackOrder), $"GetContainerOrder: the main pack's items in slot order ({n})");
|
||||
n = order(Player, 1, b, buf.Length);
|
||||
T.Check(n == 7 && buf.Take(n).SequenceEqual(p.SidePackOrder), $"GetContainerOrder: the pack column ({n})");
|
||||
T.Eq(order(Player, 0, null, 0), p.MainPackOrder.Count, "GetContainerOrder: count only");
|
||||
T.Eq(order(First("Sack").Id, 0, b, buf.Length), -1, "GetContainerOrder: a side pack is unknown (-1)");
|
||||
T.Eq(order(Player, 2, b, buf.Length), -1, "GetContainerOrder: bad slot kind");
|
||||
T.Eq(order(Player, 0, null, 5), -1, "GetContainerOrder: null buffer with a size");
|
||||
}
|
||||
|
||||
var wielded = (delegate* unmanaged[Cdecl]<uint*, uint*, int, int>)Api->GetWieldedItemsFn;
|
||||
uint* ids = stackalloc uint[64];
|
||||
uint* locs = stackalloc uint[64];
|
||||
int count = wielded(ids, locs, 64);
|
||||
var got = new Dictionary<uint, uint>();
|
||||
for (int i = 0; i < Math.Max(count, 0); i++) got[ids[i]] = locs[i];
|
||||
T.Check(count == p.EquippedItems.Count && p.EquippedItems.All(kv => got.TryGetValue(kv.Key, out uint l) && l == kv.Value),
|
||||
$"GetWieldedItems: PlayerDescription's equipped list ({count})");
|
||||
T.Eq(got.GetValueOrDefault(First("Academy Coat").Id), 0x1E00u, "GetWieldedItems: the coat's location");
|
||||
T.Eq(wielded(ids, locs, 2), 2, "GetWieldedItems: at most max");
|
||||
T.Eq(wielded(null, locs, 64), -1, "GetWieldedItems: null buffer");
|
||||
}
|
||||
}
|
||||
511
tools/HeadlessHostTests/PlayerTests.cs
Normal file
511
tools/HeadlessHostTests/PlayerTests.cs
Normal file
|
|
@ -0,0 +1,511 @@
|
|||
// ============================================================================
|
||||
// PlayerTests - the PLAYER slots (vitals, attributes, skills, spells, enchantments,
|
||||
// server time, pose) against the replayed test session, checked against the portal
|
||||
// dat formulas and against synthetic enchantment / vitae events.
|
||||
// ============================================================================
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using RynthCore.Headless.Dat;
|
||||
using RynthCore.Headless.Host;
|
||||
using RynthCore.Headless.Messages;
|
||||
using RynthCore.Headless.World;
|
||||
|
||||
namespace HeadlessHostTests;
|
||||
|
||||
internal static unsafe class PlayerTests
|
||||
{
|
||||
[System.Runtime.CompilerServices.ModuleInitializer]
|
||||
internal static void Register() => Suites.Add("player", Run, order: 20);
|
||||
|
||||
private const uint Me = 0x50000001;
|
||||
|
||||
private static void Run()
|
||||
{
|
||||
Fixture f = Fixture.Shared;
|
||||
using var _ = f.Context.Enter();
|
||||
PlayerState p = f.Session.World.Player;
|
||||
SkillTable? table = SkillTable.Shared;
|
||||
T.Check(table != null, "portal dat skill table loads");
|
||||
if (table == null) return;
|
||||
|
||||
DatFacts(table);
|
||||
Vitals(f, p, table);
|
||||
Attributes(f, p);
|
||||
Skills(f, p, table);
|
||||
SkillEnchantment(f, p);
|
||||
AttributeEnchantment(f, p, table);
|
||||
Vitae(f);
|
||||
Spells(f, p);
|
||||
Enchantments(f, p);
|
||||
ServerTime(f);
|
||||
Pose(f);
|
||||
EdgeCases(f);
|
||||
}
|
||||
|
||||
// ── the API through its function pointers ───────────────────────────────
|
||||
|
||||
private static bool Vitals(Fixture f, out uint h, out uint mh, out uint s, out uint ms, out uint m, out uint mm)
|
||||
{
|
||||
uint a = 0, b = 0, c = 0, d = 0, e = 0, g = 0;
|
||||
int ok = ((delegate* unmanaged[Cdecl]<uint*, uint*, uint*, uint*, uint*, uint*, int>)f.Api->GetPlayerVitalsFn)(&a, &b, &c, &d, &e, &g);
|
||||
h = a; mh = b; s = c; ms = d; m = e; mm = g;
|
||||
return ok == 1;
|
||||
}
|
||||
|
||||
private static bool BaseVitals(Fixture f, out uint h, out uint s, out uint m)
|
||||
{
|
||||
uint a = 0, b = 0, c = 0;
|
||||
int ok = ((delegate* unmanaged[Cdecl]<uint*, uint*, uint*, int>)f.Api->GetPlayerBaseVitalsFn)(&a, &b, &c);
|
||||
h = a; s = b; m = c;
|
||||
return ok == 1;
|
||||
}
|
||||
|
||||
private static uint? Attr2nd(Fixture f, uint obj, uint stype)
|
||||
{
|
||||
uint v = 0;
|
||||
return ((delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)f.Api->GetObjectAttribute2ndBaseLevelFn)(obj, stype, &v) == 1 ? v : null;
|
||||
}
|
||||
|
||||
private static uint? Attr(Fixture f, uint obj, uint stype, int raw)
|
||||
{
|
||||
uint v = 0;
|
||||
return ((delegate* unmanaged[Cdecl]<uint, uint, int, uint*, int>)f.Api->GetObjectAttributeFn)(obj, stype, raw, &v) == 1 ? v : null;
|
||||
}
|
||||
|
||||
private static (int Buffed, int Training)? Skill(Fixture f, uint obj, uint skill)
|
||||
{
|
||||
int b = 0, t = 0;
|
||||
return ((delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)f.Api->GetObjectSkillFn)(obj, skill, &b, &t) == 1 ? (b, t) : null;
|
||||
}
|
||||
|
||||
private static int? SkillLevel(Fixture f, uint obj, uint skill, int raw)
|
||||
{
|
||||
int v = 0;
|
||||
return ((delegate* unmanaged[Cdecl]<uint, uint, int, int*, int>)f.Api->GetObjectSkillBuffedFn)(obj, skill, raw, &v) == 1 ? v : null;
|
||||
}
|
||||
|
||||
private static float Vitae(Fixture f, uint id) => ((delegate* unmanaged[Cdecl]<uint, float>)f.Api->GetVitaeFn)(id);
|
||||
|
||||
private static double ServerTimeNow(Fixture f) => ((delegate* unmanaged[Cdecl]<double>)f.Api->GetServerTimeFn)();
|
||||
|
||||
private static (uint[] Ids, double[] Expiry, int Result) ReadEnchantments(Fixture f, int max = 512)
|
||||
{
|
||||
uint[] ids = new uint[max];
|
||||
double[] exp = new double[max];
|
||||
int n;
|
||||
fixed (uint* pi = ids)
|
||||
fixed (double* pe = exp)
|
||||
n = ((delegate* unmanaged[Cdecl]<uint*, double*, int, int>)f.Api->ReadPlayerEnchantmentsFn)(pi, pe, max);
|
||||
return (ids[..Math.Max(0, n)], exp[..Math.Max(0, n)], n);
|
||||
}
|
||||
|
||||
// ── server messages ─────────────────────────────────────────────────────
|
||||
|
||||
private static byte[] GameEvent(uint eventType, byte[] body)
|
||||
{
|
||||
var m = new byte[16 + body.Length];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(m, 0xF7B0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(m.AsSpan(4), Me);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(m.AsSpan(8), 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(m.AsSpan(12), eventType);
|
||||
body.CopyTo(m, 16);
|
||||
return m;
|
||||
}
|
||||
|
||||
private static byte[] EnchantmentBody(ushort spell, ushort layer, ushort category, uint power, double start, double duration,
|
||||
uint type, uint key, float value)
|
||||
{
|
||||
var ms = new MemoryStream();
|
||||
var w = new BinaryWriter(ms);
|
||||
w.Write(spell); w.Write(layer); w.Write(category); w.Write((ushort)0);
|
||||
w.Write(power); w.Write(start); w.Write(duration); w.Write(Me);
|
||||
w.Write(0f); w.Write(0f); w.Write(0.0);
|
||||
w.Write(type); w.Write(key); w.Write(value);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
private static void AddEnchantment(Fixture f, ushort spell, ushort layer, ushort category, uint power, double start, double duration,
|
||||
uint type, uint key, float value)
|
||||
=> f.Receive(GameEvent(0x02C2, EnchantmentBody(spell, layer, category, power, start, duration, type, key, value)));
|
||||
|
||||
private static void RemoveEnchantment(Fixture f, ushort spell, ushort layer)
|
||||
{
|
||||
var b = new byte[4];
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b, spell);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b.AsSpan(2), layer);
|
||||
f.Receive(GameEvent(0x02C3, b));
|
||||
}
|
||||
|
||||
private const uint SingleStat = 0x1000, Multiplicative = 0x4000, Additive = 0x8000, Beneficial = 0x2000000;
|
||||
|
||||
// ── expectations computed here from the dat ─────────────────────────────
|
||||
|
||||
private static uint BaseAttr(PlayerState p, uint a) => p.AttributeTable.TryGetValue(a, out AttributeInfo i) ? i.Init + i.Ranks : 0;
|
||||
|
||||
private static uint Formula(SkillFormula fm, Func<uint, uint> attr)
|
||||
{
|
||||
if (fm.X == 0) return 0;
|
||||
uint t = attr(fm.Attr1) + (fm.Attr2 != 0 ? attr(fm.Attr2) : 0);
|
||||
return fm.Divisor > 1 ? (uint)Math.Round((double)t / fm.Divisor, MidpointRounding.AwayFromZero) : t;
|
||||
}
|
||||
|
||||
private static int PlayerInt(Fixture f, uint key)
|
||||
=> f.Session.World.PlayerObject is { } o && o.TryGetInt(key, out int v) ? v : 0;
|
||||
|
||||
// ── checks ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static void DatFacts(SkillTable t)
|
||||
{
|
||||
T.Eq(t.MaxHealth.ToString(), "a2 / 2", "dat: max health = Endurance / 2");
|
||||
T.Eq(t.MaxStamina.ToString(), "a2 / 1", "dat: max stamina = Endurance");
|
||||
T.Eq(t.MaxMana.ToString(), "a6 / 1", "dat: max mana = Self");
|
||||
T.Eq(t.Get(6)?.Formula.ToString(), "(a3 + a4) / 3", "dat: Melee Defense = (Quickness + Coordination) / 3");
|
||||
T.Eq(t.Get(15)?.Formula.ToString(), "(a6 + a5) / 7", "dat: Magic Defense = (Self + Focus) / 7");
|
||||
T.Eq(t.Get(34)?.Formula.ToString(), "(a5 + a6) / 4", "dat: War Magic = (Focus + Self) / 4");
|
||||
T.Eq(t.Get(6)?.Name, "Melee Defense", "dat: skill 6 name");
|
||||
T.Check(t.Skills.Count >= 45, $"dat: {t.Skills.Count} skills");
|
||||
}
|
||||
|
||||
private static void Vitals(Fixture f, PlayerState p, SkillTable t)
|
||||
{
|
||||
T.Check(Vitals(f, out uint h, out uint mh, out uint s, out uint ms, out uint m, out uint mm), "GetPlayerVitals succeeds");
|
||||
T.Check(BaseVitals(f, out uint bh, out uint bs, out uint bm), "GetPlayerBaseVitals succeeds");
|
||||
T.Info($"vitals {h}/{mh} {s}/{ms} {m}/{mm}; base max {bh} {bs} {bm}; attributes {string.Join(" ", Enumerable.Range(1, 6).Select(a => BaseAttr(p, (uint)a)))}");
|
||||
T.Eq(h, p.CurrentVital(Vital.Health), "current health = PlayerState");
|
||||
T.Eq(s, p.CurrentVital(Vital.Stamina), "current stamina = PlayerState");
|
||||
T.Eq(m, p.CurrentVital(Vital.Mana), "current mana = PlayerState");
|
||||
T.Check(mh >= bh && ms >= bs && mm >= bm, "buffed max >= base max");
|
||||
|
||||
int enlightenment = PlayerInt(f, 390);
|
||||
uint[] expected = new uint[4];
|
||||
for (uint v = 1; v <= 3; v++)
|
||||
{
|
||||
VitalInfo vi = p.Vitals[v];
|
||||
expected[v] = Formula(t.VitalFormula(v), a => BaseAttr(p, a)) + vi.Init + vi.Ranks;
|
||||
}
|
||||
expected[1] += (uint)(enlightenment * 2);
|
||||
T.Eq(bh, expected[1], "base max health = End/2 + init + ranks (dat formula)");
|
||||
T.Eq(bs, expected[2], "base max stamina = End + init + ranks");
|
||||
T.Eq(bm, expected[3], "base max mana = Self + init + ranks");
|
||||
T.Eq(Attr2nd(f, Me, 1), (uint?)bh, "Attribute2ndBaseLevel(MaxHealth) = base max health");
|
||||
T.Eq(Attr2nd(f, Me, 3), (uint?)bs, "Attribute2ndBaseLevel(MaxStamina) = base max stamina");
|
||||
T.Eq(Attr2nd(f, Me, 5), (uint?)bm, "Attribute2ndBaseLevel(MaxMana) = base max mana");
|
||||
T.Eq(Attr2nd(f, Me, 2), (uint?)h, "Attribute2ndBaseLevel(Health) = current health");
|
||||
T.Check(Attr2nd(f, 0x12345678, 1) == null && Attr2nd(f, Me, 7) == null && Attr2nd(f, Me, 0) == null, "Attribute2ndBaseLevel: other object / bad stype fail");
|
||||
|
||||
// A multiplicative max-health buff (Asheron's Benediction style) and an additive one.
|
||||
uint before = mh;
|
||||
AddEnchantment(f, 4100, 1, 0xFFE0, 999, 0, 600, SingleStat | Multiplicative | 0x2 | Beneficial, 1, 1.10f);
|
||||
AddEnchantment(f, 4101, 1, 0xFFE1, 999, 0, 600, SingleStat | Additive | 0x2 | Beneficial, 1, 7f);
|
||||
Vitals(f, out _, out uint mh2, out _, out uint ms2, out _, out _);
|
||||
T.Eq(mh2, (uint)Math.Round(before * 1.10f + 7f, MidpointRounding.AwayFromZero), "max health: * 1.10 (multiplicative) then + 7 (additive)");
|
||||
T.Eq(ms2, ms, "max stamina unchanged by a max-health buff");
|
||||
BaseVitals(f, out uint bh2, out _, out _);
|
||||
T.Eq(bh2, bh, "base max health ignores enchantments");
|
||||
RemoveEnchantment(f, 4100, 1);
|
||||
RemoveEnchantment(f, 4101, 1);
|
||||
Vitals(f, out _, out uint mh3, out _, out _, out _, out _);
|
||||
T.Eq(mh3, before, "max health back after the buffs are removed");
|
||||
}
|
||||
|
||||
private static void Attributes(Fixture f, PlayerState p)
|
||||
{
|
||||
var line = new List<string>();
|
||||
for (uint a = 1; a <= 6; a++)
|
||||
{
|
||||
uint? raw = Attr(f, Me, a, 1), buffed = Attr(f, Me, a, 0);
|
||||
T.Eq(raw, (uint?)BaseAttr(p, a), $"attribute {a} raw = init + ranks");
|
||||
T.Check(buffed != null && buffed >= raw, $"attribute {a} buffed ({buffed}) >= raw ({raw})");
|
||||
line.Add($"{a}:{raw}/{buffed}");
|
||||
}
|
||||
T.Info("attributes raw/buffed " + string.Join(" ", line));
|
||||
T.Check(Attr(f, Me, 0, 0) == null && Attr(f, Me, 7, 0) == null && Attr(f, 0x12345678, 1, 0) == null, "attribute: bad stype / other object fail");
|
||||
}
|
||||
|
||||
private static void Skills(Fixture f, PlayerState p, SkillTable t)
|
||||
{
|
||||
T.Eq(p.SkillTable.Count, 38, "38 skills");
|
||||
int checkedBase = 0;
|
||||
var lines = new List<string>();
|
||||
uint[] attrBuffed = new uint[7];
|
||||
for (uint a = 1; a <= 6; a++) attrBuffed[a] = Attr(f, Me, a, 0) ?? 0;
|
||||
bool augs = PlayerInt(f, 365) != 0 || PlayerInt(f, 300) != 0 || PlayerInt(f, 301) != 0 || PlayerInt(f, 302) != 0
|
||||
|| PlayerInt(f, 390) != 0 || PlayerInt(f, 326) != 0 || PlayerInt(f, 344) != 0;
|
||||
T.Info($"augmentation properties present: {augs}");
|
||||
foreach (SkillInfo si in p.SkillTable.Values.OrderBy(s => s.Id))
|
||||
{
|
||||
var r = Skill(f, Me, si.Id);
|
||||
int? raw = SkillLevel(f, Me, si.Id, 1), buffed = SkillLevel(f, Me, si.Id, 0);
|
||||
T.Check(r != null && raw != null && buffed != null, $"skill {si.Id} readable");
|
||||
if (r == null || raw == null || buffed == null) continue;
|
||||
T.Eq(r.Value.Training, (int)si.Training, $"skill {si.Id} training class");
|
||||
T.Eq(r.Value.Buffed, buffed.Value, $"skill {si.Id}: GetObjectSkill = GetObjectSkillBuffed(raw 0)");
|
||||
T.Check(buffed >= raw, $"skill {si.Id} buffed {buffed} >= base {raw}");
|
||||
SkillBaseInfo? sb = t.Get(si.Id);
|
||||
bool usable = si.Training >= 2 || (si.Training == 1 && sb?.MinLevel == 1);
|
||||
if (!augs && sb != null)
|
||||
{
|
||||
uint expectBase = (usable ? Formula(sb.Formula, a => BaseAttr(p, a)) : 0) + si.Init + si.Ranks;
|
||||
T.Eq(raw.Value, (int)expectBase, $"skill {si.Id} ({sb.Name}) base = formula + init + ranks");
|
||||
checkedBase++;
|
||||
}
|
||||
if (lines.Count < 8 || si.Id is 6 or 15 or 24 or 34)
|
||||
lines.Add($"{si.Id} {sb?.Name} sac{si.Training} init{si.Init} ranks{si.Ranks} -> {raw}/{buffed}");
|
||||
}
|
||||
foreach (string l in lines.Distinct()) T.Info(l);
|
||||
T.Check(checkedBase >= 30 || augs, $"base formula checked on {checkedBase} skills");
|
||||
T.Check(Skill(f, Me, 9999) == null, "unknown skill fails");
|
||||
T.Check(Skill(f, 0x12345678, 6) == null && SkillLevel(f, 0x12345678, 6, 0) == null, "other object's skill fails");
|
||||
|
||||
// Melee defense, trained, specialised?
|
||||
SkillInfo md = p.SkillTable.TryGetValue(6, out SkillInfo x) ? x : default;
|
||||
T.Check(md.Training >= 2, "Melee Defense trained or specialized");
|
||||
T.Eq(SkillLevel(f, Me, 6, 1), (int?)(int)(Formula(t.Get(6)!.Formula, a => BaseAttr(p, a)) + md.Init + md.Ranks), "Melee Defense base = (Coord + Quick)/3 + init + ranks");
|
||||
}
|
||||
|
||||
private static void SkillEnchantment(Fixture f, PlayerState p)
|
||||
{
|
||||
uint skill = p.SkillTable.Values.Where(s => s.Training >= 2).Select(s => s.Id).OrderBy(i => i).First();
|
||||
int baseBefore = SkillLevel(f, Me, skill, 1)!.Value;
|
||||
int before = SkillLevel(f, Me, skill, 0)!.Value;
|
||||
|
||||
AddEnchantment(f, 4102, 1, 0xFFE2, 999, 0, 600, SingleStat | Additive | 0x10 | Beneficial, skill, 25f);
|
||||
int after = SkillLevel(f, Me, skill, 0)!.Value;
|
||||
T.Eq(after - before, 25, $"skill {skill}: +25 additive enchantment adds 25");
|
||||
T.Eq(SkillLevel(f, Me, skill, 1), (int?)baseBefore, $"skill {skill}: base unchanged by the enchantment");
|
||||
T.Eq(Skill(f, Me, skill)?.Buffed, (int?)after, $"skill {skill}: GetObjectSkill sees it");
|
||||
|
||||
// Same category, lower power: does not stack (top layer only).
|
||||
AddEnchantment(f, 4103, 2, 0xFFE2, 10, 0, 600, SingleStat | Additive | 0x10 | Beneficial, skill, 50f);
|
||||
T.Eq(SkillLevel(f, Me, skill, 0), (int?)after, $"skill {skill}: a weaker spell in the same category is ignored");
|
||||
// Same category, higher power: replaces.
|
||||
AddEnchantment(f, 4104, 3, 0xFFE2, 2000, 0, 600, SingleStat | Additive | 0x10 | Beneficial, skill, 40f);
|
||||
T.Eq(SkillLevel(f, Me, skill, 0), (int?)(before + 40), $"skill {skill}: the stronger spell in the category wins");
|
||||
RemoveEnchantment(f, 4103, 2);
|
||||
RemoveEnchantment(f, 4104, 3);
|
||||
|
||||
// Multiplicative (applies before the additive).
|
||||
AddEnchantment(f, 4105, 1, 0xFFE3, 999, 0, 600, SingleStat | Multiplicative | 0x10 | Beneficial, skill, 1.5f);
|
||||
int mult = SkillLevel(f, Me, skill, 0)!.Value;
|
||||
T.Check(mult > after, $"skill {skill}: * 1.5 raises it ({after} -> {mult})");
|
||||
// A different skill's key doesn't apply.
|
||||
AddEnchantment(f, 4106, 1, 0xFFE4, 999, 0, 600, SingleStat | Additive | 0x10, skill + 1000, 99f);
|
||||
T.Eq(SkillLevel(f, Me, skill, 0), (int?)mult, $"skill {skill}: another skill's enchantment doesn't apply");
|
||||
RemoveEnchantment(f, 4102, 1);
|
||||
RemoveEnchantment(f, 4105, 1);
|
||||
RemoveEnchantment(f, 4106, 1);
|
||||
T.Eq(SkillLevel(f, Me, skill, 0), (int?)before, $"skill {skill}: back to {before} when removed");
|
||||
}
|
||||
|
||||
private static void AttributeEnchantment(Fixture f, PlayerState p, SkillTable t)
|
||||
{
|
||||
// +20 Quickness: buffed Quickness +20 and Melee Defense ((Coord + Quick)/3) up by about 20/3.
|
||||
uint q0 = Attr(f, Me, 3, 0)!.Value;
|
||||
int md0 = SkillLevel(f, Me, 6, 0)!.Value;
|
||||
int mdBase0 = SkillLevel(f, Me, 6, 1)!.Value;
|
||||
AddEnchantment(f, 4107, 1, 0xFFE5, 999, 0, 600, SingleStat | Additive | 0x1 | Beneficial, 3, 30f);
|
||||
uint q1 = Attr(f, Me, 3, 0)!.Value;
|
||||
T.Eq(q1 - q0, 30u, "Quickness +30 additive");
|
||||
T.Eq(Attr(f, Me, 3, 1), (uint?)BaseAttr(p, 3), "Quickness raw unchanged");
|
||||
int md1 = SkillLevel(f, Me, 6, 0)!.Value;
|
||||
T.Eq(md1 - md0, 10, "Melee Defense follows buffed Quickness (+30 / 3)");
|
||||
T.Eq(SkillLevel(f, Me, 6, 1), (int?)mdBase0, "Melee Defense base uses base attributes");
|
||||
// Endurance buff raises max health (End/2) and stamina.
|
||||
Vitals(f, out _, out uint mh0, out _, out uint ms0, out _, out _);
|
||||
AddEnchantment(f, 4108, 1, 0xFFE6, 999, 0, 600, SingleStat | Additive | 0x1 | Beneficial, 2, 40f);
|
||||
Vitals(f, out _, out uint mh1, out _, out uint ms1, out _, out _);
|
||||
T.Eq(mh1 - mh0, 20u, "max health follows buffed Endurance (+40 / 2)");
|
||||
T.Eq(ms1 - ms0, 40u, "max stamina follows buffed Endurance (+40)");
|
||||
RemoveEnchantment(f, 4107, 1);
|
||||
RemoveEnchantment(f, 4108, 1);
|
||||
T.Eq(Attr(f, Me, 3, 0), (uint?)q0, "Quickness back after removal");
|
||||
}
|
||||
|
||||
private static void Vitae(Fixture f)
|
||||
{
|
||||
T.Eq(Vitae(f, Me), 1.0f, "no vitae: 1.0");
|
||||
T.Eq(Vitae(f, 0x12345678), 1.0f, "another object's vitae: 1.0");
|
||||
Vitals(f, out _, out uint mh0, out _, out uint ms0, out _, out uint mm0);
|
||||
BaseVitals(f, out uint bh0, out _, out _);
|
||||
int sk0 = SkillLevel(f, Me, 6, 0)!.Value;
|
||||
int skBase0 = SkillLevel(f, Me, 6, 1)!.Value;
|
||||
int count0 = ReadEnchantments(f).Result;
|
||||
AddEnchantment(f, 666, 0, 204, 0, 0, -1, 0x800000 | 0x2 | Multiplicative, 0, 0.9f);
|
||||
T.Eq(Vitae(f, Me), 0.9f, "vitae 10%: 0.9");
|
||||
Vitals(f, out _, out uint mh1, out _, out uint ms1, out _, out uint mm1);
|
||||
T.Eq(mh1, (uint)Math.Round(mh0 * 0.9f, MidpointRounding.AwayFromZero), "vitae scales max health");
|
||||
T.Eq(mm1, (uint)Math.Round(mm0 * 0.9f, MidpointRounding.AwayFromZero), "vitae scales max mana");
|
||||
T.Check(ms1 < ms0, "vitae lowers max stamina");
|
||||
BaseVitals(f, out uint bh1, out _, out _);
|
||||
T.Eq(bh1, bh0, "vitae doesn't change base max");
|
||||
// ACE / the client: (formula(buffed attributes) + init + ranks) * multipliers * vitae, then the additives.
|
||||
// Melee Defense has no multiplicative mods here, so the additive part is what the buffs add on top.
|
||||
SkillInfo md = f.Session.World.Player.SkillTable[6];
|
||||
uint mdPlain = (uint)Math.Round((Attr(f, Me, 3, 0)!.Value + Attr(f, Me, 4, 0)!.Value) / 3.0, MidpointRounding.AwayFromZero) + md.Init + md.Ranks;
|
||||
int mdAdd = sk0 - (int)mdPlain;
|
||||
T.Info($"Melee Defense {sk0} = {mdPlain} + {mdAdd} from additive buffs");
|
||||
T.Eq(SkillLevel(f, Me, 6, 0), (int?)(int)Math.Round(mdPlain * 0.9f + mdAdd, MidpointRounding.AwayFromZero), "vitae scales buffed skills before the additives");
|
||||
T.Eq(SkillLevel(f, Me, 6, 1), (int?)skBase0, "vitae doesn't change base skills");
|
||||
T.Eq(ReadEnchantments(f).Result, count0, "vitae is not listed by ReadPlayerEnchantments");
|
||||
RemoveEnchantment(f, 666, 0);
|
||||
T.Eq(Vitae(f, Me), 1.0f, "vitae removed: 1.0");
|
||||
}
|
||||
|
||||
private static void Spells(Fixture f, PlayerState p)
|
||||
{
|
||||
uint[] buf = new uint[1024];
|
||||
int n;
|
||||
fixed (uint* b = buf) n = ((delegate* unmanaged[Cdecl]<uint*, int, int>)f.Api->ReadKnownSpellsFn)(b, buf.Length);
|
||||
T.Eq(n, 503, "ReadKnownSpells: 503 spells");
|
||||
T.Check(buf.Take(Math.Max(0, n)).Contains(24u), "spellbook has Armor Self I (24)");
|
||||
T.Check(buf.Take(Math.Max(0, n)).ToHashSet().SetEquals(p.SpellBook), "ReadKnownSpells = the spellbook");
|
||||
fixed (uint* b = buf) n = ((delegate* unmanaged[Cdecl]<uint*, int, int>)f.Api->ReadKnownSpellsFn)(b, 10);
|
||||
T.Eq(n, 10, "ReadKnownSpells stops at maxCount");
|
||||
var known = (delegate* unmanaged[Cdecl]<uint, uint, int>)f.Api->IsSpellKnownFn;
|
||||
T.Eq(known(Me, 24), 1, "IsSpellKnown(Armor Self I) = 1");
|
||||
uint unknown = Enumerable.Range(1, 7000).Select(i => (uint)i).First(i => !p.SpellBook.Contains(i));
|
||||
T.Eq(known(Me, unknown), 0, $"IsSpellKnown({unknown}) = 0");
|
||||
T.Eq(known(0x12345678, 24), -1, "IsSpellKnown(another object) = -1");
|
||||
T.Eq(known(0, 24), -1, "IsSpellKnown(0) = -1");
|
||||
}
|
||||
|
||||
private static void Enchantments(Fixture f, PlayerState p)
|
||||
{
|
||||
double now = ServerTimeNow(f);
|
||||
var (ids, exp, n) = ReadEnchantments(f);
|
||||
int expected = p.ActiveEnchantments.Count(e => e.SpellId != 666);
|
||||
T.Eq(n, expected, "ReadPlayerEnchantments: every enchantment but vitae");
|
||||
T.Info($"{n} enchantments, server time {now:F1}; spells {string.Join(",", ids.Take(12))}...");
|
||||
int forever = 0, finite = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
Enchantment e = p.ActiveEnchantments.First(x => x.SpellId == ids[i]);
|
||||
if (e.Duration <= 0) { forever++; T.Eq(exp[i], double.MaxValue, $"spell {ids[i]} (duration {e.Duration}): no expiry"); }
|
||||
else { finite++; T.Check(exp[i] > now && exp[i] <= now + e.Duration + 0.001, $"spell {ids[i]}: expiry {exp[i] - now:F1}s ahead, within its duration {e.Duration}"); }
|
||||
}
|
||||
T.Info($"{finite} timed, {forever} without duration (item spells)");
|
||||
T.Check(finite > 0, "some timed enchantments");
|
||||
int armor = Array.IndexOf(ids, 24u);
|
||||
T.Check(armor >= 0, "Armor Self I (24, cast during the capture) is active");
|
||||
if (armor >= 0)
|
||||
{
|
||||
Enchantment e = p.ActiveEnchantments.First(x => x.SpellId == 24);
|
||||
T.Info($"Armor Self I: start {e.StartTime:F1}, duration {e.Duration}, {exp[armor] - now:F1}s left");
|
||||
T.Check(Math.Abs(exp[armor] - now - (e.Duration + e.StartTime)) < 1.0, "Armor Self I expiry = now + duration + (negative) start");
|
||||
}
|
||||
|
||||
// A fresh cast: StartTime 0, duration 100 -> expires 100 s from now; time passes; it gets closer.
|
||||
AddEnchantment(f, 4109, 1, 0xFFE7, 999, 0, 100, SingleStat | Additive | 0x10 | Beneficial, 6, 1f);
|
||||
double t0 = ServerTimeNow(f);
|
||||
var r1 = ReadEnchantments(f);
|
||||
int k = Array.IndexOf(r1.Ids, 4109u);
|
||||
T.Check(k >= 0 && Math.Abs(r1.Expiry[k] - (t0 + 100)) < 0.01, "new enchantment expires at server time + duration");
|
||||
f.Now += 30_000;
|
||||
double t1 = ServerTimeNow(f);
|
||||
T.Check(Math.Abs(t1 - t0 - 30) < 0.001, "server time advances with the clock");
|
||||
var r2 = ReadEnchantments(f);
|
||||
int k2 = Array.IndexOf(r2.Ids, 4109u);
|
||||
T.Check(k2 >= 0 && Math.Abs(r2.Expiry[k2] - r1.Expiry[k]) < 0.001 && r2.Expiry[k2] - t1 < 70.01, "expiry is fixed; remaining shrinks as time passes");
|
||||
// A refresh (the server re-sends it with a new StartTime) moves the expiry.
|
||||
AddEnchantment(f, 4109, 1, 0xFFE7, 999, 0, 100, SingleStat | Additive | 0x10 | Beneficial, 6, 1f);
|
||||
var r3 = ReadEnchantments(f);
|
||||
int k3 = Array.IndexOf(r3.Ids, 4109u);
|
||||
T.Check(k3 >= 0 && Math.Abs(r3.Expiry[k3] - (t1 + 100)) < 0.01, "a refreshed enchantment expires 100 s from the refresh");
|
||||
// An ACE resend of a running one: StartTime -40 (running 40 s).
|
||||
AddEnchantment(f, 4110, 1, 0xFFE8, 999, -40, 100, SingleStat | Additive | 0x10 | Beneficial, 6, 1f);
|
||||
var r4 = ReadEnchantments(f);
|
||||
int k4 = Array.IndexOf(r4.Ids, 4110u);
|
||||
T.Check(k4 >= 0 && Math.Abs(r4.Expiry[k4] - (t1 + 60)) < 0.01, "StartTime -40 with duration 100 expires in 60 s");
|
||||
RemoveEnchantment(f, 4109, 1);
|
||||
RemoveEnchantment(f, 4110, 1);
|
||||
T.Eq(ReadEnchantments(f).Result, expected, "removed enchantments are gone");
|
||||
|
||||
// maxCount clips; ReadObjectEnchantments for the player = ReadPlayerEnchantments; others -1.
|
||||
T.Eq(ReadEnchantments(f, 5).Result, Math.Min(5, expected), "ReadPlayerEnchantments stops at maxCount");
|
||||
uint[] ids2 = new uint[512];
|
||||
double[] exp2 = new double[512];
|
||||
int n2, n3;
|
||||
fixed (uint* pi = ids2)
|
||||
fixed (double* pe = exp2)
|
||||
{
|
||||
n2 = ((delegate* unmanaged[Cdecl]<uint, uint*, double*, int, int>)f.Api->ReadObjectEnchantmentsFn)(Me, pi, pe, 512);
|
||||
n3 = ((delegate* unmanaged[Cdecl]<uint, uint*, double*, int, int>)f.Api->ReadObjectEnchantmentsFn)(0x12345678, pi, pe, 512);
|
||||
}
|
||||
T.Eq(n2, expected, "ReadObjectEnchantments(player) = the player's");
|
||||
T.Eq(n3, -1, "ReadObjectEnchantments(other) = -1");
|
||||
}
|
||||
|
||||
private static void ServerTime(Fixture f)
|
||||
{
|
||||
double t = ServerTimeNow(f);
|
||||
T.Check(t > 0, $"server time known ({t:F1})");
|
||||
T.Check(t >= f.Session.ServerTime, "server time >= the last sync");
|
||||
f.Now += 2_500;
|
||||
T.Check(Math.Abs(ServerTimeNow(f) - t - 2.5) < 0.001, "server time = last sync + local time since");
|
||||
}
|
||||
|
||||
private static void Pose(Fixture f)
|
||||
{
|
||||
WorldPosition pos = f.Session.World.PlayerObject!.Position!.Value;
|
||||
uint cell = 0;
|
||||
float x = 0, y = 0, z = 0, qw = 0, qx = 0, qy = 0, qz = 0;
|
||||
int ok = ((delegate* unmanaged[Cdecl]<uint*, float*, float*, float*, float*, float*, float*, float*, int>)f.Api->GetPlayerPoseFn)(&cell, &x, &y, &z, &qw, &qx, &qy, &qz);
|
||||
T.Eq(ok, 1, "GetPlayerPose succeeds");
|
||||
T.Info($"pose cell 0x{cell:X8} ({x:F2}, {y:F2}, {z:F2}) q({qw:F3}, {qx:F3}, {qy:F3}, {qz:F3})");
|
||||
T.Eq(cell, 0x61460249u, "pose cell = her dungeon spot");
|
||||
T.Check(cell == pos.Cell && x == pos.X && y == pos.Y && z == pos.Z && qw == pos.Qw && qz == pos.Qz, "pose = the world model's position");
|
||||
|
||||
float heading = 0;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<float*, int>)f.Api->GetPlayerHeadingFn)(&heading), 1, "GetPlayerHeading succeeds");
|
||||
// The engine: compass = -2 atan2(qz, qw) (0 = north, clockwise); GetPlayerHeading = 90 - compass.
|
||||
double compass = ((-2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI) % 360.0 + 720.0) % 360.0;
|
||||
double expect = ((90.0 - compass) % 360.0 + 360.0) % 360.0;
|
||||
T.Info($"heading {heading:F2} (compass {compass:F2})");
|
||||
T.Check(Math.Abs(heading - expect) < 0.01 || Math.Abs(Math.Abs(heading - expect) - 360) < 0.01, "heading = 90 - compass of her quaternion");
|
||||
// Convention: facing north -> 90, east -> 0, south -> 270, west -> 180 (0 = east, counter-clockwise).
|
||||
static (float W, float Z) Facing(double compassDeg) { double yaw = -compassDeg * Math.PI / 180; return ((float)Math.Cos(yaw / 2), (float)Math.Sin(yaw / 2)); }
|
||||
foreach ((double c, float h) in new[] { (0.0, 90f), (90.0, 0f), (180.0, 270f), (270.0, 180f), (45.0, 45f) })
|
||||
{
|
||||
(float w, float zq) = Facing(c);
|
||||
float got = HostApi.DecalHeadingFromQuaternion(w, zq);
|
||||
float d = Math.Abs(got - h);
|
||||
T.Check(d < 0.01f || Math.Abs(d - 360f) < 0.01f, $"facing compass {c}: heading {got:F2}, expected {h}");
|
||||
}
|
||||
|
||||
double ns = 0, ew = 0;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<double*, double*, int>)f.Api->GetCurCoordsFn)(&ns, &ew), 1, "GetCurCoords succeeds");
|
||||
double eEw = (((cell >> 24) & 0xFF) * 8.0 + x / 24.0 - 1019.5) / 10.0;
|
||||
double eNs = (((cell >> 16) & 0xFF) * 8.0 + y / 24.0 - 1019.5) / 10.0;
|
||||
T.Info($"coords {Math.Abs(ns):F2}{(ns >= 0 ? "N" : "S")} {Math.Abs(ew):F2}{(ew >= 0 ? "E" : "W")}");
|
||||
T.Check(Math.Abs(ns - eNs) < 1e-9 && Math.Abs(ew - eEw) < 1e-9, "coords = the landblock formula");
|
||||
}
|
||||
|
||||
private static void EdgeCases(Fixture f)
|
||||
{
|
||||
uint u = 0;
|
||||
int i = 0;
|
||||
float fl = 0;
|
||||
double d = 0;
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint*, uint*, uint*, uint*, uint*, uint*, int>)f.Api->GetPlayerVitalsFn)(null, &u, &u, &u, &u, &u), 0, "GetPlayerVitals(null) = 0");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint*, uint*, uint*, int>)f.Api->GetPlayerBaseVitalsFn)(&u, null, &u), 0, "GetPlayerBaseVitals(null) = 0");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)f.Api->GetObjectAttribute2ndBaseLevelFn)(Me, 1, null), 0, "Attribute2ndBaseLevel(null) = 0");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)f.Api->GetObjectSkillFn)(Me, 6, null, &i), 0, "GetObjectSkill(null) = 0");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, int*, int>)f.Api->GetObjectSkillBuffedFn)(Me, 6, 0, null), 0, "GetObjectSkillBuffed(null) = 0");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int, uint*, int>)f.Api->GetObjectAttributeFn)(Me, 1, 0, null), 0, "GetObjectAttribute(null) = 0");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint*, int, int>)f.Api->ReadKnownSpellsFn)(null, 10), -1, "ReadKnownSpells(null) = -1");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint*, int, int>)f.Api->ReadKnownSpellsFn)(&u, 0), -1, "ReadKnownSpells(max 0) = -1");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint*, double*, int, int>)f.Api->ReadPlayerEnchantmentsFn)(null, &d, 4), -1, "ReadPlayerEnchantments(null) = -1");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint*, double*, int, int>)f.Api->ReadPlayerEnchantmentsFn)(&u, &d, 0), 0, "ReadPlayerEnchantments(max 0) = 0");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint*, double*, int, int>)f.Api->ReadObjectEnchantmentsFn)(Me, &u, null, 4), -1, "ReadObjectEnchantments(null) = -1");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint*, float*, float*, float*, float*, float*, float*, float*, int>)f.Api->GetPlayerPoseFn)(&u, &fl, &fl, null, &fl, &fl, &fl, &fl), 0, "GetPlayerPose(null) = 0");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<float*, int>)f.Api->GetPlayerHeadingFn)(null), 0, "GetPlayerHeading(null) = 0");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<double*, double*, int>)f.Api->GetCurCoordsFn)(&d, null), 0, "GetCurCoords(null) = 0");
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint*, int, uint*, int>)f.Api->GetCharacterTitlesFn)(null, 0, &u), -1, "GetCharacterTitles = -1 (not tracked)");
|
||||
T.Check(f.Api->GetPlayerVitalsFn != IntPtr.Zero && f.Api->GetVitaeFn != IntPtr.Zero && f.Api->GetServerTimeFn != IntPtr.Zero
|
||||
&& f.Api->ReadKnownSpellsFn != IntPtr.Zero && f.Api->GetCharacterTitlesFn != IntPtr.Zero, "player slots filled");
|
||||
|
||||
// No context at all (a plugin thread before any context exists can't happen here; with the
|
||||
// fixture's context current, an out-of-world question is answered by the "not the player" paths).
|
||||
T.Eq(((delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)f.Api->GetObjectSkillFn)(0, 6, &i, &i), 0, "GetObjectSkill(0) = 0");
|
||||
}
|
||||
}
|
||||
166
tools/HeadlessHostTests/Program.cs
Normal file
166
tools/HeadlessHostTests/Program.cs
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
// ============================================================================
|
||||
// HeadlessHostTests - the plugin host's API against a replayed ACE session.
|
||||
// Each area has its own file (ObjectsTests.cs, PlayerTests.cs, ActionsTests.cs) that
|
||||
// registers its suite from a module initializer:
|
||||
// [System.Runtime.CompilerServices.ModuleInitializer]
|
||||
// internal static void Register() => Suites.Add("objects", Run, order: 10);
|
||||
// and uses Fixture.Shared (a session that replayed the capture, its HostContext and the
|
||||
// API table) plus T.Check / T.Eq / T.Info.
|
||||
// ============================================================================
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using RynthCore.Engine.Net;
|
||||
using RynthCore.Headless.Dat;
|
||||
using RynthCore.Headless.Host;
|
||||
using RynthCore.Headless.Net;
|
||||
using RynthCore.Headless.Session;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace HeadlessHostTests;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
private static int Main()
|
||||
{
|
||||
// Every suite runs against the captured session. The public source snapshots leave the
|
||||
// captures out (they hold a live login), so without one there is nothing to check.
|
||||
if (!File.Exists(Fixture.CapturePath))
|
||||
{
|
||||
Console.WriteLine($"SKIPPED: no captured session at {Fixture.CapturePath} (the public source leaves the captures out).");
|
||||
return 0;
|
||||
}
|
||||
Fixture f = Fixture.Shared;
|
||||
Console.WriteLine($"fixture: player 0x{f.Session.World.Player.Id:X8}, {f.Session.World.Objects.Count} objects, state {f.Session.State}, spells table {(f.Context.Spells != null ? "yes" : "no")}");
|
||||
foreach (var (name, run) in Suites.All)
|
||||
{
|
||||
T.Case(name);
|
||||
try { run(); }
|
||||
catch (Exception ex) { T.Check(false, $"threw {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); }
|
||||
}
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"{T.Checks - T.Failed}/{T.Checks} checks passed.");
|
||||
Console.WriteLine(T.Failed == 0 ? "ALL HEADLESS HOST TESTS PASSED." : $"{T.Failed} FAILED.");
|
||||
return T.Failed == 0 ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class Suites
|
||||
{
|
||||
private static readonly List<(int Order, string Name, Action Run)> _all = new();
|
||||
public static void Add(string name, Action run, int order) => _all.Add((order, name, run));
|
||||
public static IEnumerable<(string Name, Action Run)> All => _all.OrderBy(s => s.Order).Select(s => (s.Name, s.Run));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A ClientSession that has replayed the captured P1 session (the test character: login, teleport out,
|
||||
/// identify, use, cast, pickup, give, drop, melee kill, teleport back), its HostContext and the API table.
|
||||
/// Call API functions inside <c>using var _ = f.Context.Enter();</c>.
|
||||
/// </summary>
|
||||
internal sealed unsafe class Fixture
|
||||
{
|
||||
public static Fixture Shared { get; } = new();
|
||||
|
||||
/// <summary>The account name the replay logs in with (only the outbound LoginRequest, which the capture leaves out, uses it).</summary>
|
||||
public const string Account = "testaccount";
|
||||
|
||||
/// <summary>The captured session (tools\HeadlessNetTests\Captures, copied beside the test).</summary>
|
||||
public static string CapturePath => Path.Combine(AppContext.BaseDirectory, "Captures", "ace-p1-session.txt");
|
||||
|
||||
public readonly FakeLink Link = new();
|
||||
public readonly ClientSession Session;
|
||||
public readonly HostContext Context;
|
||||
public readonly RynthCoreApiNative* Api;
|
||||
public long Now = 1000;
|
||||
|
||||
private Fixture()
|
||||
{
|
||||
Session = new ClientSession(Link, new SessionOptions { Account = Account, PickFirstCharacter = true }, () => Now);
|
||||
// The API suites look at objects from every part of the capture (Holtburg's shop and corpse after
|
||||
// the teleport back): keep them. TeleportForgets checks the real behaviour on its own replay.
|
||||
Session.World.ForgetOnTeleport = false;
|
||||
Session.Start("x");
|
||||
foreach (string line in File.ReadLines(CapturePath))
|
||||
{
|
||||
if (line.StartsWith('#') || line.Length == 0) continue;
|
||||
string[] f = line.Split(' ');
|
||||
if (f[1] != "S") continue;
|
||||
Link.Inbox.Enqueue(Convert.FromHexString(f[2]));
|
||||
Now += 5;
|
||||
Session.Tick();
|
||||
}
|
||||
string? ac = DatFile.FindAcFolder();
|
||||
Context = new HostContext(Session, Account, geometry: null, spells: ac != null ? SpellTable.Load(ac, out _) : null);
|
||||
Api = HostApi.Build();
|
||||
}
|
||||
|
||||
/// <summary>A mark for <see cref="ActionsSince"/>.</summary>
|
||||
public int Mark => Link.Sent.Count;
|
||||
|
||||
/// <summary>The game actions (type, payload) sent since a mark.</summary>
|
||||
public List<(uint Type, byte[] Payload)> ActionsSince(int mark)
|
||||
{
|
||||
var list = new List<(uint, byte[])>();
|
||||
foreach (byte[] m in MessagesSince(mark))
|
||||
if (m.Length >= 12 && BinaryPrimitives.ReadUInt32LittleEndian(m) == 0xF7B1)
|
||||
list.Add((BinaryPrimitives.ReadUInt32LittleEndian(m.AsSpan(8)), m.AsSpan(12).ToArray()));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Every whole message (opcode first) sent since a mark (single-fragment messages).</summary>
|
||||
public List<byte[]> MessagesSince(int mark)
|
||||
{
|
||||
var list = new List<byte[]>();
|
||||
foreach (var (d, _) in Link.Sent.Skip(mark))
|
||||
{
|
||||
if (!InboundPacket.TryParse(d, out InboundPacket p) || !p.Has(PacketFlags.BlobFragments)) continue;
|
||||
int at = p.OptionalEnd;
|
||||
int size = BinaryPrimitives.ReadUInt16LittleEndian(d.AsSpan(at + 10));
|
||||
list.Add(d.AsSpan(at + 16, size - 16).ToArray());
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Feeds a server message (opcode first) straight into the world model, as if it had arrived.</summary>
|
||||
public void Receive(byte[] message)
|
||||
{
|
||||
if (RynthCore.PluginSdk.Net.ServerMessage.TryFromWire(message, out var msg)) Session.World.Apply(msg);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class FakeLink : IDatagramLink
|
||||
{
|
||||
public readonly List<(byte[] Data, bool ConnectPort)> Sent = new();
|
||||
public readonly Queue<byte[]> Inbox = new();
|
||||
public void Send(ReadOnlySpan<byte> d, bool connectPort) => Sent.Add((d.ToArray(), connectPort));
|
||||
public bool TryReceive(out byte[] d) => Inbox.TryDequeue(out d!);
|
||||
}
|
||||
|
||||
internal static class T
|
||||
{
|
||||
public static int Checks, Failed;
|
||||
private static string _case = "";
|
||||
|
||||
public static void Case(string name)
|
||||
{
|
||||
_case = name;
|
||||
Console.WriteLine($"-- {name}");
|
||||
}
|
||||
|
||||
public static void Check(bool ok, string what)
|
||||
{
|
||||
Checks++;
|
||||
if (ok) return;
|
||||
Failed++;
|
||||
Console.WriteLine($" FAIL [{_case}] {what}");
|
||||
}
|
||||
|
||||
public static void Eq<TV>(TV actual, TV expected, string what)
|
||||
{
|
||||
Checks++;
|
||||
if (EqualityComparer<TV>.Default.Equals(actual, expected)) return;
|
||||
Failed++;
|
||||
Console.WriteLine($" FAIL [{_case}] {what}: got {actual}, expected {expected}");
|
||||
}
|
||||
|
||||
public static void Info(string s) => Console.WriteLine($" info: {s}");
|
||||
}
|
||||
124
tools/HeadlessHostTests/StatusTests.cs
Normal file
124
tools/HeadlessHostTests/StatusTests.cs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
// ============================================================================
|
||||
// StatusTests - the per-character status files and command inbox (StatusExporter) and
|
||||
// the phone's hold-to-move rules (RemoteMove), in a temp folder.
|
||||
// ============================================================================
|
||||
|
||||
using System.Text.Json;
|
||||
using RynthCore.Headless.Host.Status;
|
||||
|
||||
namespace HeadlessHostTests;
|
||||
|
||||
internal static class StatusTests
|
||||
{
|
||||
[System.Runtime.CompilerServices.ModuleInitializer]
|
||||
internal static void Register() => Suites.Add("status", Run, order: 50);
|
||||
|
||||
private static void Run()
|
||||
{
|
||||
Move();
|
||||
Exporter();
|
||||
}
|
||||
|
||||
private static void Move()
|
||||
{
|
||||
var m = new RemoteMove();
|
||||
T.Check(RemoteMove.TryParseStart("forward", out string d, out long? dm) && d == "forward" && dm == null, "legacy start: a bare direction");
|
||||
T.Check(RemoteMove.TryParseStart("{\"dir\":\"Right\",\"deadmanMs\":800}", out d, out dm) && d == "right" && dm == 800, "protocol 2 start");
|
||||
T.Check(RemoteMove.TryParseStart("{\"dir\":\"left\"}", out _, out dm) && dm == RemoteMove.DefaultDeadMs, "protocol 2 start: default dead-man");
|
||||
T.Check(!RemoteMove.TryParseStart("{\"dir\":\"up\"}", out _, out _), "an unknown direction is refused");
|
||||
T.Check(RemoteMove.TryParseKeepAlive("{\"dirs\":[\"forward\",\"jump\",\"FORWARD\"]}", out var dirs) && dirs.Count == 1, "keep-alive: unknown and repeated names dropped");
|
||||
T.Eq(RemoteMove.ParseStop("garbage"), "stop", "an unreadable stop stops everything");
|
||||
|
||||
// Legacy: 2 s window, re-armed by a repeated start.
|
||||
T.Eq(m.Start("forward", null, 0).Count, 1, "start presses once");
|
||||
T.Eq(m.Start("forward", null, 1500).Count, 0, "a repeated start doesn't press again");
|
||||
m.Tick(3000, out bool fired);
|
||||
T.Check(!fired, "re-armed: still held at 3.0 s");
|
||||
m.Tick(3600, out fired);
|
||||
T.Check(fired && m.Held.Count == 0, "legacy dead-man at 2 s after the last start");
|
||||
|
||||
// Protocol 2: keep-alives hold it, a keep-alive naming less lets go, the dead-man fires, resume.
|
||||
m.Start("forward", 600, 10_000);
|
||||
m.Start("left", 600, 10_000);
|
||||
m.KeepAlive(new[] { "forward", "left" }, 10_500);
|
||||
m.Tick(11_000, out fired);
|
||||
T.Check(!fired && m.Held.Count == 2, "keep-alive refreshes the dead-man");
|
||||
var acts = m.KeepAlive(new[] { "forward" }, 11_100);
|
||||
T.Check(acts.Count == 1 && acts[0] == ("left", false), "a keep-alive that no longer names a direction lets go of it");
|
||||
m.Tick(11_800, out fired);
|
||||
T.Check(fired && m.Held.Count == 0 && m.KeepAliveMode, "no keep-alive for 600 ms: dead-man");
|
||||
acts = m.KeepAlive(new[] { "forward" }, 12_500);
|
||||
T.Check(acts.Count == 1 && acts[0] == ("forward", true), "a keep-alive soon after resumes what the dead-man stopped");
|
||||
m.Stop("stop");
|
||||
T.Eq(m.KeepAlive(new[] { "forward" }, 12_600).Count, 0, "but never after an explicit stop");
|
||||
}
|
||||
|
||||
private static void Exporter()
|
||||
{
|
||||
Fixture f = Fixture.Shared;
|
||||
string dir = Path.Combine(Path.GetTempPath(), "rynth-headless-status-" + Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
int id = StatusExporter.MakeClientId(3);
|
||||
T.Check(id > 1_000_000_000 && id % 2 == 1, "client id: odd and above a billion (never a real pid)");
|
||||
T.Check(StatusExporter.MakeClientId(4) != id, "a different slot, a different id");
|
||||
var x = new StatusExporter(dir, id, Fixture.Account) { ServerName = "ACEmulator", LastCharacter = "+Test Character" };
|
||||
|
||||
x.Tick();
|
||||
using (var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(dir, $"RynthCore.{id}.status.json"))))
|
||||
{
|
||||
JsonElement r = doc.RootElement;
|
||||
T.Check(!r.GetProperty("inWorld").GetBoolean() && r.GetProperty("fps").GetInt32() == 0, "no session yet: not in the world (reads loading)");
|
||||
T.Check(r.GetProperty("headless").GetBoolean() && r.GetProperty("hostPid").GetInt32() == Environment.ProcessId, "headless + hostPid");
|
||||
T.Eq(r.GetProperty("character").GetString(), "+Test Character", "the configured character until one is seen");
|
||||
}
|
||||
|
||||
// A command waiting before the first in-world tick is drained (oldest first) and deleted.
|
||||
Directory.CreateDirectory(Path.Combine(dir, "commands"));
|
||||
string cmd = Path.Combine(dir, "commands", $"RynthCore.{id}.0000000000000000001-a.cmd.json");
|
||||
File.WriteAllText(cmd, "{\"action\":\"moveStart\",\"value\":{\"dir\":\"forward\",\"deadmanMs\":600}}");
|
||||
string other = Path.Combine(dir, "commands", "RynthCore.12345.0000000000000000001-a.cmd.json");
|
||||
File.WriteAllText(other, "{\"action\":\"moveStart\",\"value\":\"forward\"}");
|
||||
x.Context = f.Context;
|
||||
x.Tick();
|
||||
T.Check(!File.Exists(cmd), "its command file is drained");
|
||||
T.Check(File.Exists(other), "another client's command file is left alone");
|
||||
T.Check(f.Session.DriveMotion.Moving, "moveStart forward: autorun on");
|
||||
File.WriteAllText(cmd, "{\"action\":\"moveStop\",\"value\":\"stop\"}");
|
||||
Thread.Sleep(250);
|
||||
x.Tick();
|
||||
T.Check(!f.Session.DriveMotion.Moving, "moveStop: stopped");
|
||||
|
||||
using (var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(dir, $"RynthCore.{id}.status.json"))))
|
||||
{
|
||||
JsonElement r = doc.RootElement;
|
||||
T.Eq(r.GetProperty("schema").GetString(), "rynthcore.client-status/1", "status schema");
|
||||
T.Eq(r.GetProperty("pid").GetInt32(), id, "pid = the client id");
|
||||
T.Eq(r.GetProperty("account").GetString(), Fixture.Account, "account");
|
||||
T.Eq(r.GetProperty("server").GetString(), "ACEmulator", "server (the configured name)");
|
||||
T.Check(r.GetProperty("inWorld").GetBoolean(), "in the world");
|
||||
T.Check(r.TryGetProperty("opos", out JsonElement opos) && opos.GetProperty("cell").GetString()!.Length == 8, "opos with the cell");
|
||||
T.Check(r.GetProperty("enchantments").ValueKind == JsonValueKind.Array, "enchantments listed");
|
||||
T.Eq(r.GetProperty("moveProto").GetInt32(), 2, "move protocol 2");
|
||||
}
|
||||
string sheet = Path.Combine(dir, $"RynthCore.{id}.character.json");
|
||||
T.Check(File.Exists(sheet), "character sheet written");
|
||||
using (var doc = JsonDocument.Parse(File.ReadAllText(sheet)))
|
||||
{
|
||||
JsonElement r = doc.RootElement;
|
||||
T.Eq(r.GetProperty("schema").GetString(), "rynthcore.character/1", "sheet schema");
|
||||
T.Eq(r.GetProperty("attributes").GetArrayLength(), 6, "six attributes");
|
||||
T.Eq(r.GetProperty("vitals").GetArrayLength(), 3, "three vitals");
|
||||
T.Check(r.GetProperty("skills").GetArrayLength() > 0, "trained skills listed");
|
||||
T.Check(r.GetProperty("level").GetInt32() > 0, "level");
|
||||
}
|
||||
|
||||
x.Retire();
|
||||
T.Check(!File.Exists(Path.Combine(dir, $"RynthCore.{id}.status.json")) && !File.Exists(sheet), "retire removes its files");
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(dir, recursive: true); } catch (IOException) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
44
tools/HeadlessHostTests/TeleportTests.cs
Normal file
44
tools/HeadlessHostTests/TeleportTests.cs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// ============================================================================
|
||||
// TeleportTests - a teleport drops the surroundings, as the retail client does (the captured session
|
||||
// goes from the dungeon to Holtburg and back: Holtburg's shop and corpse must not follow the character home).
|
||||
// ============================================================================
|
||||
|
||||
using RynthCore.Headless.Session;
|
||||
using RynthCore.Headless.World;
|
||||
|
||||
namespace HeadlessHostTests;
|
||||
|
||||
internal static class TeleportTests
|
||||
{
|
||||
[System.Runtime.CompilerServices.ModuleInitializer]
|
||||
internal static void Register() => Suites.Add("teleport", Run, order: 60);
|
||||
|
||||
private static void Run()
|
||||
{
|
||||
long now = 1000;
|
||||
var link = new FakeLink();
|
||||
var session = new ClientSession(link, new SessionOptions { Account = Fixture.Account, PickFirstCharacter = true }, () => now);
|
||||
session.Start("x");
|
||||
int teleports = 0, deleted = 0;
|
||||
session.World.PlayerTeleported += () => teleports++;
|
||||
session.World.ObjectDeleted += _ => deleted++;
|
||||
foreach (string line in File.ReadLines(Fixture.CapturePath))
|
||||
{
|
||||
if (line.StartsWith('#') || line.Length == 0) continue;
|
||||
string[] f = line.Split(' ');
|
||||
if (f[1] != "S") continue;
|
||||
link.Inbox.Enqueue(Convert.FromHexString(f[2]));
|
||||
now += 5;
|
||||
session.Tick();
|
||||
}
|
||||
WorldState w = session.World;
|
||||
bool Has(string name) => w.Objects.Values.Any(o => o.Name == name);
|
||||
T.Check(teleports >= 2, $"the capture teleports out and back ({teleports})");
|
||||
T.Check(deleted > 0, $"plugins hear the dropped objects as deletes ({deleted})");
|
||||
T.Check(!Has("Shopkeeper Renald the Elder") && !Has("Corpse of Drudge Skulker"), "Holtburg's shopkeeper and corpse are gone after the teleport home");
|
||||
T.Check(Has("Viamontian Laced Boots") && Has("Sack"), "what the character carries stays");
|
||||
T.Check(w.Objects.ContainsKey(w.Player.Id), "the player stays");
|
||||
T.Check(w.Objects.Count < Fixture.Shared.Session.World.Objects.Count,
|
||||
$"fewer objects than the replay that keeps them ({w.Objects.Count} < {Fixture.Shared.Session.World.Objects.Count})");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue