RynthSuite as of 2026-10-04 (internal c94715f): RynthOracle (based on Oracle of Dereth by Advis Eveldan) and RynthInventory, RynthAi patrol doorways and rooms, healing priority, strict monster priority, finish the wounded target, slayer weapons, arcs when clear, blasts like rings, learn unknown spells, looting fixes, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:29 -04:00
commit 12ca25f911
426 changed files with 108239 additions and 7521 deletions

View file

@ -0,0 +1,668 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginSdk;
namespace RynthLua.CompatTests;
/// <summary>
/// The fake engine: a <see cref="RynthCoreApiNative"/> whose function pointers are the
/// static functions below, all served from <see cref="FakeWorld.W"/>. The plugin's own
/// SDK wrapper (RynthCoreHost) calls them exactly as it calls the real engine, so RynthLua
/// runs unmodified. Functions the plugin doesn't need stay null (the SDK's Has* checks
/// then say "not available", as on an older engine).
/// </summary>
internal static unsafe class FakeHost
{
private static FakeWorld W => FakeWorld.W;
private static readonly Dictionary<string, IntPtr> AnsiCache = new();
private static IntPtr Ansi(string s)
{
if (!AnsiCache.TryGetValue(s, out IntPtr p)) AnsiCache[s] = p = Marshal.StringToHGlobalAnsi(s);
return p;
}
public static RynthCoreApiNative Build()
{
var a = new RynthCoreApiNative { Version = 73 };
a.LogFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, void>)&LogImpl;
a.WriteToChatFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, int, int>)&WriteToChat;
a.InvokeChatParserFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, int>)&InvokeChatParser;
a.GetPlayerIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetPlayerId;
a.GetWorldNameFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr>)&GetWorldName;
a.GetAccountNameFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr>)&GetAccountName;
a.GetObjectNameFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, IntPtr>)&GetObjectName;
a.GetObjectWcidFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint>)&GetObjectWcid;
a.GetObjectBitfieldFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint>)&GetObjectBitfield;
a.GetItemTypeFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int>)&GetItemType;
a.GetObjectIntPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int*, int>)&GetInt;
a.GetObjectQuadPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, long*, int>)&GetInt64;
a.GetObjectDoublePropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, double*, int>)&GetFloat;
a.GetObjectStringPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, IntPtr>)&GetString;
a.GetObjectBoolPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int*, int>)&GetBool;
a.GetObjectDataIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)&GetDataId;
a.GetObjectOwnershipInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, int>)&GetOwnership;
a.GetObjectInstanceIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)&GetInstanceId;
a.GetObjectWielderInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, int>)&GetWielder;
a.GetContainerContentsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int, int>)&GetContents;
a.GetObjectPositionFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, float*, float*, float*, int>)&GetPosition;
a.GetPlayerPoseFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, float*, float*, float*, float*, float*, float*, float*, int>)&GetPose;
a.GetObjectHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, float*, int>)&GetHeading;
a.GetSelectedItemIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetSelected;
a.GetPreviousSelectedItemIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetPrevSelected;
a.SelectItemFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&SelectItem;
a.GetGroundContainerIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetGroundContainer;
a.GetCurrentCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetCombatMode;
a.ChangeCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&ChangeCombatMode;
a.IsPortalingFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&IsPortaling;
a.GetVitaeFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, float>)&GetVitae;
a.GetPlayerVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, uint*, uint*, uint*, uint*, int>)&GetVitals;
a.GetPlayerBaseVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, uint*, int>)&GetBaseVitals;
a.GetObjectAttribute2ndBaseLevelFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)&GetVitalMax;
a.GetObjectSkillFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)&GetSkill;
a.GetObjectSkillBuffedFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int*, int>)&GetSkillLevel;
a.GetObjectAttributeFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, uint*, int>)&GetAttribute;
a.ReadPlayerEnchantmentsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, double*, int, int>)&ReadEnchantments;
a.ReadObjectEnchantmentsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, double*, int, int>)&ReadObjectEnchantments;
a.ReadKnownSpellsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, int, int>)&ReadKnownSpells;
a.GetServerTimeFn = (IntPtr)(delegate* unmanaged[Cdecl]<double>)&GetServerTime;
a.GetObjectSpellIdsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int, int>)&GetSpellIds;
a.GetBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetBusy;
a.GetCastBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetCastBusy;
a.GetUseDoneSeqFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetUseDoneSeq;
a.GetLastUseDoneFn = (IntPtr)(delegate* unmanaged[Cdecl]<int*, uint*, int>)&GetLastUseDone;
a.GetLastWeenieErrorFn = (IntPtr)(delegate* unmanaged[Cdecl]<int*, uint*, uint*, uint*, int>)&GetLastWeenieError;
a.UseObjectFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&UseObject;
a.UseObjectOnFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&UseObjectOn;
a.UseEquippedItemFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&UseEquippedItem;
a.MoveItemExternalFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int>)&MoveItemExternal;
a.MoveItemInternalFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int, int>)&MoveItemInternal;
a.SplitStackInternalFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int, int>)&SplitStack;
a.MergeStackInternalFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&MergeStack;
a.GiveObjectToFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int>)&GiveObjectTo;
a.WieldItemFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&WieldItem;
a.CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&CastSpell;
a.RequestIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&RequestId;
a.HasAppraisalDataFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&HasAppraisal;
a.GetLastIdTimeFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, long>)&GetLastIdTime;
a.ObjectIsAttackableFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&IsAttackable;
a.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&SetAutoRun;
a.SalvagePanelOpenFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&SalvageOpen;
a.SalvagePanelAddItemFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&SalvageAdd;
a.SalvagePanelExecuteFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&SalvageExecute;
a.GetLiveObjectIdsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, int, int>)&GetLiveObjectIds;
a.GetObjectStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int>)&GetObjectState;
a.GetPluginInterfaceFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint, IntPtr>)&GetPluginInterface;
a.GetVendorInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorInfoNative*, int>)&GetVendorInfo;
a.GetVendorItemsFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorItemNative*, int, int>)&GetVendorItems;
a.VendorBuyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, VendorTradeEntryNative*, int, uint>)&VendorBuy;
a.VendorSellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int, uint>)&VendorSell;
a.GetVendorTradeStatusFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorTradeStatusNative*, int>)&GetVendorStatus;
a.GetTradeStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<TradeStateNative*, int>)&GetTradeState;
a.GetTradeItemsFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, uint*, int, int>)&GetTradeItems;
a.TradeOpenFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&TradeOpen;
a.TradeAddFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&TradeAdd;
a.TradeAcceptFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&TradeAccept;
a.TradeDeclineFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&TradeDecline;
a.TradeResetFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&TradeReset;
a.TradeCloseFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&TradeClose;
return a;
}
private static int B(bool b) => b ? 1 : 0;
// ── Logging / chat ──────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void LogImpl(IntPtr text) => W.Log.Add(Marshal.PtrToStringAnsi(text) ?? string.Empty);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int WriteToChat(IntPtr text, int type) { W.ChatOut.Add(Marshal.PtrToStringUni(text) ?? string.Empty); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int InvokeChatParser(IntPtr text) { W.Invoked.Add(Marshal.PtrToStringUni(text) ?? string.Empty); return 1; }
// ── Identity ────────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint GetPlayerId() => FakeWorld.Player;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetWorldName() => Ansi("TestServer");
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetAccountName() => Ansi("testaccount");
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetPluginInterface(IntPtr plugin, IntPtr iface, uint version) => IntPtr.Zero;
// ── Objects ─────────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetObjectName(uint id) => W.Get(id) is { } o ? Ansi(o.Name) : IntPtr.Zero;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint GetObjectWcid(uint id) => W.Get(id)?.Wcid ?? 0;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint GetObjectBitfield(uint id) => W.Get(id)?.Bitfield ?? 0;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetItemType(uint id, uint* type)
{
if (W.Get(id) is not { } o) return 0;
*type = o.ItemType;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetInt(uint id, uint key, int* value)
{
if (W.Get(id) is not { } o) return 0;
if (key == 1) { *value = (int)o.ItemType; return 1; }
if (!o.Ints.TryGetValue(key, out int v)) return 0;
*value = v;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetInt64(uint id, uint key, long* value)
{
if (W.Get(id) is not { } o || !o.Int64s.TryGetValue(key, out long v)) return 0;
*value = v;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetFloat(uint id, uint key, double* value)
{
if (W.Get(id) is not { } o || !o.Floats.TryGetValue(key, out double v)) return 0;
*value = v;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetString(uint id, uint key) =>
W.Get(id) is { } o && o.Strings.TryGetValue(key, out string? v) ? Ansi(v) : IntPtr.Zero;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetBool(uint id, uint key, int* value)
{
if (W.Get(id) is not { } o || !o.Bools.TryGetValue(key, out bool v)) return 0;
*value = B(v);
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetDataId(uint id, uint key, uint* value)
{
if (W.Get(id) is not { } o || !o.DataIds.TryGetValue(key, out uint v)) return 0;
*value = v;
return 1;
}
// v73: like the engine, Container/Wielder from the object's ownership, others from its table; 0 = unknown.
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetInstanceId(uint id, uint key, uint* value)
{
if (W.Get(id) is not { } o) return 0;
uint v = key switch { 2 => o.Container, 3 => o.Wielder, _ => o.InstanceIds.TryGetValue(key, out uint x) ? x : 0 };
if (v == 0) return 0;
*value = v;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetOwnership(uint id, uint* container, uint* wielder, uint* location)
{
if (W.Get(id) is not { } o) return 0;
*container = o.Container; *wielder = o.Wielder; *location = o.Location;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetWielder(uint id, uint* wielder, uint* location)
{
if (W.Get(id) is not { } o) return 0;
*wielder = o.Wielder; *location = o.Location;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetContents(uint container, uint* buffer, int capacity)
{
var ids = W.Contents(container);
for (int i = 0; i < Math.Min(ids.Count, capacity); i++) buffer[i] = ids[i];
return ids.Count;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetPosition(uint id, uint* cell, float* x, float* y, float* z)
{
if (W.Get(id) is not { } o || !o.HasPosition) return 0;
*cell = o.Cell; *x = o.X; *y = o.Y; *z = o.Z;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetPose(uint* cell, float* x, float* y, float* z, float* qw, float* qx, float* qy, float* qz)
{
var me = W.Me;
*cell = me.Cell; *x = me.X; *y = me.Y; *z = me.Z;
double half = -me.Heading * Math.PI / 360.0;
*qw = (float)Math.Cos(half); *qx = 0; *qy = 0; *qz = (float)Math.Sin(half);
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetHeading(uint id, float* heading)
{
if (W.Get(id) is not { } o) return 0;
*heading = o.Heading;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetLiveObjectIds(uint* buffer, int capacity)
{
var ids = W.Objects.Keys.OrderBy(i => i).ToList();
for (int i = 0; i < Math.Min(ids.Count, capacity); i++) buffer[i] = ids[i];
return ids.Count;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectState(uint id, uint* state)
{
if (W.Get(id) is not { } o || o.PhysicsState == 0) return 0;
*state = o.PhysicsState;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int IsAttackable(uint id) => B(W.Get(id) is { } o && (o.Bitfield & 0x10) != 0);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int HasAppraisal(uint id) => B(W.Get(id)?.Appraised == true);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static long GetLastIdTime(uint id) => W.Get(id)?.LastIdTime ?? 0;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetSpellIds(uint id, uint* buffer, int capacity)
{
if (W.Get(id) is not { } o) return -1;
for (int i = 0; i < Math.Min(o.Spells.Count, capacity); i++) buffer[i] = o.Spells[i];
return o.Spells.Count;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ReadObjectEnchantments(uint id, uint* spells, double* expiry, int capacity) => id == FakeWorld.Player ? ReadEnch(spells, expiry, capacity) : 0;
// ── Selection / state ───────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint GetSelected() => W.Selected;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint GetPrevSelected() => W.PreviousSelected;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SelectItem(uint id)
{
W.Calls.Add($"SelectItem 0x{id:X8}");
if (W.Get(id) == null) return 0;
W.SetSelected(id);
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint GetGroundContainer() => W.GroundContainer;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetCombatMode() => W.CombatMode;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ChangeCombatMode(int mode) => B(W.ChangeCombat(mode));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int IsPortaling() => B(W.Portaling);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetBusy() => W.BusyState;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetCastBusy() => W.CastBusy;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetUseDoneSeq() => W.UseDoneSeq;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetLastUseDone(int* seq, uint* error)
{
*seq = W.UseDoneSeq; *error = W.UseDoneError;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetLastWeenieError(int* seq, uint* error, uint* eventType, uint* objectId)
{
*seq = W.RefusalSeq; *error = W.RefusalError; *eventType = W.RefusalEvent; *objectId = W.RefusalObject;
return 1;
}
// ── Character ───────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static float GetVitae(uint id) => W.Vitae;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetVitals(uint* hp, uint* maxHp, uint* st, uint* maxSt, uint* mana, uint* maxMana)
{
*hp = W.Hp; *maxHp = W.MaxHp; *st = W.St; *maxSt = W.MaxSt; *mana = W.Mana; *maxMana = W.MaxMana;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetBaseVitals(uint* hp, uint* st, uint* mana)
{
*hp = W.BaseHp; *st = W.BaseSt; *mana = W.BaseMana;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetVitalMax(uint id, uint stype2nd, uint* value)
{
if (id != FakeWorld.Player) return 0;
*value = stype2nd switch { 1 => W.MaxHp, 3 => W.MaxSt, 5 => W.MaxMana, _ => 0 };
return *value != 0 ? 1 : 0;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetSkill(uint id, uint skill, int* buffed, int* training)
{
if (id != FakeWorld.Player) return 0;
var s = W.Skills.TryGetValue((int)skill, out var v) ? v : (0, 0, 1);
*buffed = s.Item1; *training = s.Item3;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetSkillLevel(uint id, uint skill, int raw, int* level)
{
if (id != FakeWorld.Player) return 0;
var s = W.Skills.TryGetValue((int)skill, out var v) ? v : (0, 0, 1);
*level = raw != 0 ? s.Item2 : s.Item1;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetAttribute(uint id, uint attr, int raw, uint* value)
{
if (id != FakeWorld.Player || !W.Attributes.TryGetValue((int)attr, out var a)) return 0;
*value = raw != 0 ? a.Base : a.Cur;
return 1;
}
private static int ReadEnch(uint* spells, double* expiry, int capacity)
{
int n = W.Enchantments.Count;
for (int i = 0; i < Math.Min(n, capacity); i++) { spells[i] = W.Enchantments[i].Spell; expiry[i] = W.Enchantments[i].Expiry; }
return n;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ReadEnchantments(uint* spells, double* expiry, int capacity) => ReadEnch(spells, expiry, capacity);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ReadKnownSpells(uint* spells, int capacity)
{
for (int i = 0; i < Math.Min(W.KnownSpells.Count, capacity); i++) spells[i] = W.KnownSpells[i];
return W.KnownSpells.Count;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static double GetServerTime() => W.ServerTime;
// ── Actions ─────────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int UseObject(uint id) => B(W.UseObject(id));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int UseObjectOn(uint id, uint target) => B(W.UseObject(id, target));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int UseEquippedItem(uint id, uint target)
{
W.Calls.Add($"UseEquippedItem 0x{id:X8} 0x{target:X8}");
if (W.Get(id) == null) return 0;
W.Later(() => W.UseDone());
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int MoveItemExternal(uint id, uint target, int amount) => B(W.MoveExternal(id, target, amount));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int MoveItemInternal(uint id, uint container, int slot, int amount) => B(W.MoveInternal(id, container, slot, amount));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SplitStack(uint id, uint container, int slot, int amount) => B(W.Split(id, container, slot, amount));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int MergeStack(uint src, uint dst) => B(W.Merge(src, dst));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GiveObjectTo(uint id, uint target, int amount) => B(W.Give(id, target, amount));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int WieldItem(uint id, uint mask) => B(W.Wield(id, mask));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int CastSpell(uint target, int spell) => B(W.Cast(target, spell));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int RequestId(uint id) => B(W.RequestId(id));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetAutoRun(int enabled)
{
W.Calls.Add($"SetAutoRun {enabled}");
W.AutoRun = enabled != 0;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SalvageOpen(uint tool)
{
W.Calls.Add($"SalvagePanelOpen 0x{tool:X8}");
if (W.Get(tool) == null) return 0;
W.SalvageTool = tool;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SalvageAdd(uint item)
{
W.Calls.Add($"SalvagePanelAddItem 0x{item:X8}");
if (W.SalvageTool == 0 || W.Get(item) == null) return 0;
if (!W.SalvageItems.Contains(item)) W.SalvageItems.Add(item);
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SalvageExecute() => B(W.Salvage());
// ── Vendor ──────────────────────────────────────────────────────────────
private static void WriteAnsi(byte* dest, int capacity, string text)
{
int n = Math.Min(text.Length, capacity - 1);
for (int i = 0; i < n; i++) dest[i] = (byte)text[i];
dest[n] = 0;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetVendorInfo(VendorInfoNative* info)
{
if (W.VendorOpenId == 0) return 0;
*info = default;
info->VendorId = W.VendorOpenId;
info->Generation = W.VendorGeneration;
info->ItemTypes = 0x20 | 0x80000 | 0x800;
info->MinValue = 0;
info->MaxValue = 10000;
info->DealsMagic = 1;
info->BuyRate = 0.6f;
info->SellRate = 1.15f;
info->AltCurrencyServerCount = -1;
info->AltCurrencyHave = -1;
info->PlayerCoins = W.Me.Ints.TryGetValue(20, out int c) ? c : 0;
info->ItemCount = W.VendorItems.Count;
info->Flags = 1;
WriteAnsi(info->Name, 64, W.Get(W.VendorOpenId)?.Name ?? "Vendor");
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetVendorItems(VendorItemNative* items, int capacity)
{
if (W.VendorOpenId == 0) return 0;
if (items == null) return W.VendorItems.Count;
for (int i = 0; i < Math.Min(W.VendorItems.Count, capacity); i++)
{
var v = W.VendorItems[i];
items[i] = default;
items[i].ObjectId = v.Id;
items[i].Wcid = v.Wcid;
items[i].ItemType = v.ItemType;
items[i].Amount = v.Amount;
items[i].StackSize = 1;
items[i].MaxStackSize = 100;
items[i].UnitPrice = v.UnitPrice;
items[i].Value = v.UnitPrice;
items[i].UnitValue = v.UnitPrice;
items[i].Flags = (uint)((v.Amount < 0 ? 1 : 0) | 2);
WriteAnsi(items[i].Name, 64, v.Name);
}
return W.VendorItems.Count;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint VendorBuy(uint vendorId, VendorTradeEntryNative* entries, int count)
{
var lines = new List<(uint, int)>();
for (int i = 0; i < count; i++) lines.Add((entries[i].ObjectId, entries[i].Amount));
return W.VendorTrade(buy: true, lines);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint VendorSell(uint vendorId, uint* ids, int count)
{
var lines = new List<(uint, int)>();
for (int i = 0; i < count; i++) lines.Add((ids[i], 1));
return W.VendorTrade(buy: false, lines);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetVendorStatus(VendorTradeStatusNative* status)
{
*status = default;
status->RequestId = W.VendorRequestId;
status->State = W.VendorState;
status->Result = W.VendorResult;
status->IsBuy = W.VendorIsBuy;
status->VendorId = W.VendorOpenId;
status->EntryCount = W.VendorEntries;
return 1;
}
// ── Trade ───────────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetTradeState(TradeStateNative* s)
{
uint size = s->Size;
*s = default;
s->Size = size;
s->Flags = (uint)((W.TradeOpen ? 1 : 0) | (W.TradeYouAccepted ? 2 : 0) | (W.TradePartnerAccepted ? 4 : 0) | 8 | 16);
s->Generation = W.TradeGeneration;
s->Sequence = W.TradeSequence;
s->PartnerId = W.TradeOpen ? W.TradePartner : 0;
s->InitiatorId = W.TradeInitiator;
s->SelfItemCount = W.TradeSelf.Count;
s->PartnerItemCount = W.TradePartnerItems.Count;
s->LastEventType = W.TradeLastEvent;
s->LastCloseReason = W.TradeLastClose;
s->LastAcceptedBy = W.TradeLastAcceptedBy;
s->LastDeclinedBy = W.TradeLastDeclinedBy;
s->LastResetBy = W.TradeLastResetBy;
s->CompletedCount = W.TradeCompleted;
s->PartnerAcceptCount = W.TradePartnerAccepts;
return sizeof(TradeStateNative);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetTradeItems(int side, uint* buffer, int capacity)
{
var list = side == 1 ? W.TradeSelf : W.TradePartnerItems;
for (int i = 0; i < Math.Min(list.Count, capacity); i++) buffer[i] = list[i];
return list.Count;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TradeOpen(uint target)
{
W.Calls.Add($"TradeOpen 0x{target:X8}");
W.Later(() => W.StartTrade(target));
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TradeAdd(uint item, uint slot)
{
W.Calls.Add($"TradeAdd 0x{item:X8}");
if (!W.TradeOpen) return 0;
W.Later(() => W.TradeEvent(0x0200, () => { W.TradeSelf.Add(item); W.TradeYouAccepted = W.TradePartnerAccepted = false; }));
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TradeAccept()
{
W.Calls.Add("TradeAccept");
if (!W.TradeOpen) return 0;
W.Later(() => W.TradeEvent(0x0202, () => { W.TradeYouAccepted = true; W.TradeLastAcceptedBy = FakeWorld.Player; }));
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TradeDecline()
{
W.Calls.Add("TradeDecline");
if (!W.TradeOpen) return 0;
W.Later(() => W.TradeEvent(0x0203, () => { W.TradeYouAccepted = false; W.TradeLastDeclinedBy = FakeWorld.Player; }));
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TradeReset()
{
W.Calls.Add("TradeReset");
if (!W.TradeOpen) return 0;
W.Later(() => W.TradeEvent(0x0205, () => { W.TradeSelf.Clear(); W.TradePartnerItems.Clear(); W.TradeLastResetBy = FakeWorld.Player; }));
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int TradeClose()
{
W.Calls.Add("TradeClose");
if (!W.TradeOpen) return 0;
W.Later(() => W.TradeEvent(0x01FF, () => { W.TradeOpen = false; W.TradeLastClose = 1; }));
return 1;
}
}

View file

@ -0,0 +1,520 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using RynthCore.Plugin.RynthLua;
namespace RynthLua.CompatTests;
/// <summary>One object the fake client knows.</summary>
internal sealed class FakeObject
{
public uint Id;
public string Name = string.Empty;
public uint Wcid;
public uint ItemType;
public uint Bitfield;
public uint Container, Wielder, Location;
public uint Cell;
public float X, Y, Z, Heading;
public readonly Dictionary<uint, int> Ints = new();
public readonly Dictionary<uint, long> Int64s = new();
public readonly Dictionary<uint, double> Floats = new();
public readonly Dictionary<uint, string> Strings = new();
public readonly Dictionary<uint, bool> Bools = new();
public readonly Dictionary<uint, uint> DataIds = new();
public readonly Dictionary<uint, uint> InstanceIds = new(); // besides Container/Wielder
public readonly List<uint> Spells = new();
public bool Appraised;
public long LastIdTime;
public uint PhysicsState;
public int Stack
{
get => Ints.TryGetValue(12, out int v) ? v : 1;
set => Ints[12] = value;
}
public bool HasPosition => Container == 0 && Wielder == 0 && Cell != 0;
}
/// <summary>
/// The scripted world behind the fake engine: a player ("Tester") with vitals, skills,
/// attributes, spells, enchantments and a small inventory, a few landscape objects (a
/// monster, an NPC, a portal, a lever, a chest, another player, a vendor), and a very
/// small "server" that answers the client actions one step later (UseDone, moves, splits,
/// wields, casts, vendor and trade). Events the engine would raise (object created,
/// selection, chat, ...) are queued and delivered to the plugin between ticks, the way the
/// engine's pump does.
/// </summary>
internal sealed class FakeWorld
{
public static FakeWorld W = new();
// Fixture ids (also given to scripts as harness.ids).
public const uint Player = 0x50000001;
public const uint OtherPlayer = 0x50000002;
public const uint Potion = 0x80000101;
public const uint Pyreals = 0x80000102;
public const uint Backpack = 0x80000103;
public const uint ManaStone = 0x80000104;
public const uint Tapers = 0x80000105;
public const uint Ust = 0x80000106;
public const uint Sword = 0x80000107;
public const uint Wand = 0x80000110;
public const uint Cap = 0x80000111;
public const uint Drudge = 0x80000201;
public const uint Crier = 0x80000202;
public const uint PortalObj = 0x80000203;
public const uint Lever = 0x80000204;
public const uint Chest = 0x80000205;
public const uint Shopkeeper = 0x80000206;
public const uint ChestGem = 0x80000301;
public const uint VendorItemA = 0x80000401; // "Mana Potion" on the vendor's list
public const uint VendorItemB = 0x80000402; // "Iron Arrowhead"
public const uint HomeCell = 0x7D640013;
public const float HomeX = 100f, HomeY = 100f, HomeZ = 10f;
public readonly Dictionary<uint, FakeObject> Objects = new();
public uint Selected, PreviousSelected, GroundContainer;
public int CombatMode = 1;
public bool Portaling;
public int PortalStepsLeft;
public uint Hp = 300, MaxHp = 350, St = 400, MaxSt = 400, Mana = 250, MaxMana = 500;
public uint BaseHp = 320, BaseSt = 380, BaseMana = 450;
public float Vitae = 1f;
public readonly Dictionary<int, (int Buffed, int Base, int Training)> Skills = new();
public readonly Dictionary<int, (uint Cur, uint Base)> Attributes = new();
public readonly List<(uint Spell, double Expiry)> Enchantments = new();
public readonly List<uint> KnownSpells = new();
public bool AutoRun;
public int UseDoneSeq;
public uint UseDoneError;
public int RefusalSeq;
public uint RefusalError, RefusalEvent, RefusalObject;
public int BusyState, CastBusy;
// What the client was asked to do.
public readonly List<string> ChatOut = new(); // WriteToChat
public readonly List<string> Invoked = new(); // InvokeChatParser
public readonly List<string> Calls = new(); // "UseObject 0x80000101", ...
public readonly List<string> Log = new();
// Salvage panel.
public uint SalvageTool;
public readonly List<uint> SalvageItems = new();
// Vendor.
public uint VendorOpenId;
public uint VendorGeneration;
public readonly List<(uint Id, string Name, uint Wcid, uint ItemType, int Amount, int UnitPrice)> VendorItems = new();
public uint VendorRequestId, VendorRequestSeq;
public int VendorState, VendorResult, VendorIsBuy, VendorEntries;
// Trade.
public bool TradeOpen, TradeYouAccepted, TradePartnerAccepted;
public uint TradeGeneration, TradeSequence, TradePartner, TradeInitiator, TradeLastEvent;
public uint TradeCompleted, TradeLastClose, TradeLastAcceptedBy, TradeLastDeclinedBy, TradeLastResetBy, TradePartnerAccepts;
public readonly List<uint> TradeSelf = new(), TradePartnerItems = new();
private readonly Stopwatch _clock = Stopwatch.StartNew();
private long _step;
private readonly List<(long Step, Action Act)> _pending = new();
private uint _nextId = 0x80010000;
/// <summary>Events for the plugin, delivered between ticks (the engine's pump order).</summary>
public readonly Queue<Action<RynthLuaPlugin>> Events = new();
public double ServerTime => 50_000.0 + _clock.Elapsed.TotalSeconds;
public FakeWorld()
{
var p = Add(Player, "Tester", 0, itemType: 0x10, bitfield: 0x8);
p.Cell = HomeCell; p.X = HomeX; p.Y = HomeY; p.Z = HomeZ; p.Heading = 90f;
p.Ints[25] = 100; // Level
p.Ints[5] = 1500; // EncumbranceVal
p.Ints[20] = 25000; // CoinValue
p.Int64s[1] = 1_000_000; // TotalExperience
p.InstanceIds[26] = OtherPlayer; // Monarch (PlayerDescription's instance id table)
p.Int64s[2] = 50_000; // AvailableExperience
p.Int64s[6] = 5_000; // AvailableLuminance
p.Int64s[7] = 100_000; // MaximumLuminance
p.Strings[1] = "Tester";
p.Strings[5] = "Adventurer"; // Template
var potion = Add(Potion, "Healing Potion", 2457, itemType: 0x20, container: Player);
potion.Stack = 5; potion.Ints[11] = 100; potion.Ints[19] = 100; potion.Ints[5] = 25;
var pyr = Add(Pyreals, "Pyreal", 273, itemType: 0x40, container: Player);
pyr.Stack = 2500; pyr.Ints[11] = 25000; pyr.Ints[19] = 2500;
Add(Backpack, "Backpack", 136, itemType: 0x200, container: Player);
var stone = Add(ManaStone, "Mana Stone", 2434, itemType: 0x80000, container: Backpack);
stone.Ints[19] = 50;
var tapers = Add(Tapers, "Prismatic Taper", 20631, itemType: 0x1000, container: Backpack);
tapers.Stack = 100; tapers.Ints[11] = 5000; tapers.Ints[19] = 100;
Add(Ust, "Ust", 20646, itemType: 0x20000000, container: Player);
var sword = Add(Sword, "Plain Sword", 351, itemType: 0x1, container: Player);
sword.Ints[9] = 0x00100000; // ValidLocations: MeleeWeapon
sword.Ints[19] = 500;
sword.Ints[131] = 64; // MaterialType: Steel
sword.Floats[21] = 1.25; // WeaponLength
sword.Bools[22] = true; // Inscribable
sword.Strings[16] = "A plain sword."; // LongDesc
sword.DataIds[8] = 0x06001234; // Icon
sword.Int64s[4] = 0; // ItemTotalXp
var wand = Add(Wand, "Wand of Testing", 12345, itemType: 0x8000, wielder: Player, location: 0x01000000);
wand.Ints[9] = 0x01000000;
wand.DataIds[28] = 2345; // Spell
wand.Spells.Add(2345);
var cap = Add(Cap, "Leather Cap", 118, itemType: 0x2, wielder: Player, location: 0x1);
cap.Ints[9] = 0x1;
cap.Ints[28] = 45; // ArmorLevel
Place(Add(Drudge, "Drudge Skulker", 7, itemType: 0x10, bitfield: 0x10), 10, 0, 0);
Place(Add(Crier, "Town Crier", 22, itemType: 0x10, bitfield: 0x0), 8, 0, 0);
Place(Add(PortalObj, "Portal to Town", 1955, itemType: 0x10000, bitfield: 0x40000), 20, 0, 30).PhysicsState = 0x0C;
Place(Add(Lever, "Tower Lever", 3000, itemType: 0x80), 5, 0, 40);
Place(Add(Chest, "Chest", 3001, itemType: 0x200), 3, 3, 0);
var gem = Add(ChestGem, "Amethyst", 2400, itemType: 0x800, container: Chest);
gem.Ints[19] = 750;
var other = Place(Add(OtherPlayer, "Friendly Player", 1, itemType: 0x10, bitfield: 0x8), 4, -4, 0);
other.Strings[1] = "Friendly Player";
Place(Add(Shopkeeper, "Shopkeeper", 4000, itemType: 0x10, bitfield: 0x200), 6, 6, 0);
foreach (var (id, b, t) in new[] { (6, 350, 3), (34, 380, 2), (40, 200, 2), (1, 50, 1), (11, 0, 0), (12, 120, 2), (26, 90, 2), (47, 300, 3) })
Skills[id] = (b + (t >= 2 ? 50 : 0), b, t);
Attributes[1] = (200, 190); Attributes[2] = (150, 150); Attributes[3] = (180, 170);
Attributes[4] = (170, 170); Attributes[5] = (160, 150); Attributes[6] = (190, 180);
KnownSpells.AddRange(new uint[] { 1234, 2345, 3456, 4567 });
Enchantments.Add((3456, ServerTime + 600));
Enchantments.Add((5000, double.MaxValue));
}
// ── Building ────────────────────────────────────────────────────────────
public FakeObject Add(uint id, string name, uint wcid, uint itemType = 0, uint bitfield = 0,
uint container = 0, uint wielder = 0, uint location = 0)
{
var o = new FakeObject
{
Id = id, Name = name, Wcid = wcid, ItemType = itemType, Bitfield = bitfield,
Container = container, Wielder = wielder, Location = location,
};
o.Strings[1] = name;
Objects[id] = o;
return o;
}
private static FakeObject Place(FakeObject o, float dx, float dy, float dz)
{
o.Cell = HomeCell; o.X = HomeX + dx; o.Y = HomeY + dy; o.Z = HomeZ + dz;
return o;
}
public uint NewId() => _nextId++;
public FakeObject? Get(uint id) => Objects.TryGetValue(id, out var o) ? o : null;
public FakeObject Me => Objects[Player];
/// <summary>A new object arrives from the server (plugin sees OnCreateObject).</summary>
public FakeObject Create(FakeObject o)
{
Objects[o.Id] = o;
Events.Enqueue(p => p.OnCreateObject(o.Id));
return o;
}
/// <summary>The server releases an object (plugin sees OnDeleteObject).</summary>
public void Delete(uint id)
{
if (!Objects.Remove(id)) return;
if (Selected == id) Selected = 0;
Events.Enqueue(p => p.OnDeleteObject(id));
}
public List<uint> Contents(uint container) =>
Objects.Values.Where(o => o.Container == container && o.Wielder == 0).Select(o => o.Id).OrderBy(i => i).ToList();
public bool IsMine(uint id)
{
var o = Get(id);
if (o == null) return false;
if (o.Wielder == Player || o.Container == Player) return true;
var c = Get(o.Container);
return c != null && c.Container == Player;
}
// ── The small server ────────────────────────────────────────────────────
/// <summary>Runs <paramref name="act"/> on the next step (the server answering).</summary>
public void Later(Action act, int steps = 1) => _pending.Add((_step + steps, act));
public void Step()
{
_step++;
var due = _pending.Where(p => p.Step <= _step).ToList();
_pending.RemoveAll(p => p.Step <= _step);
foreach (var (_, act) in due) act();
if (Portaling && --PortalStepsLeft <= 0) Portaling = false;
}
public void UseDone(uint error = 0)
{
UseDoneSeq++;
UseDoneError = error;
}
public void Refuse(uint code, uint eventType = 0x028A, uint objectId = 0)
{
RefusalSeq++;
RefusalError = code;
RefusalEvent = eventType;
RefusalObject = objectId;
}
public void IncomingChat(string text, int type) => Events.Enqueue(p =>
{
int eat = 0;
p.OnChatWindowText(text, type, ref eat);
});
public void SetSelected(uint id)
{
uint prev = Selected;
PreviousSelected = prev;
Selected = id;
Events.Enqueue(p => p.OnSelectedTargetChange(id, prev));
}
// Client actions (called from the fake engine functions) ─────────────────
public bool UseObject(uint id, uint target = 0)
{
var o = Get(id);
Calls.Add(target == 0 ? $"UseObject 0x{id:X8}" : $"UseObjectOn 0x{id:X8} 0x{target:X8}");
if (o == null) return false;
Later(() =>
{
if (o.ItemType == 0x20 && o.Name.Contains("Potion"))
{
Hp = Math.Min(MaxHp, Hp + 50);
if (o.Stack > 1) o.Stack--;
else Delete(o.Id);
}
else if (o.Ints.TryGetValue(9, out int valid) && valid != 0 && o.Wielder == 0 && IsMine(o.Id))
{
o.Container = 0; o.Wielder = Player; o.Location = (uint)valid;
}
else if (o.ItemType == 0x200 && o.Container == 0 && !IsMine(o.Id))
{
uint was = GroundContainer;
if (was != 0) Events.Enqueue(p => p.OnStopViewingObjectContents(was));
GroundContainer = o.Id;
Events.Enqueue(p => p.OnViewObjectContents(o.Id));
}
else if (o.ItemType == 0x20000000)
SalvageTool = o.Id; // using an Ust opens the salvage panel
else if ((o.Bitfield & 0x40000) != 0)
{
Portaling = true;
PortalStepsLeft = 5;
}
UseDone();
});
return true;
}
public bool MoveInternal(uint id, uint container, int slot, int amount)
{
Calls.Add($"MoveItemInternal 0x{id:X8} 0x{container:X8} {slot} {amount}");
var o = Get(id);
if (o == null) return false;
Later(() => { o.Container = container; o.Wielder = 0; o.Location = 0; });
return true;
}
public bool MoveExternal(uint id, uint target, int amount)
{
Calls.Add($"MoveItemExternal 0x{id:X8} 0x{target:X8} {amount}");
var o = Get(id);
if (o == null) return false;
Later(() =>
{
if (target == 0)
{
o.Container = 0; o.Wielder = 0; o.Location = 0;
o.Cell = HomeCell; o.X = HomeX + 1; o.Y = HomeY; o.Z = HomeZ;
}
else if (Get(target) is { } t && (t.ItemType & 0x10) != 0)
Delete(o.Id); // handed to a creature
else
{
o.Container = target; o.Wielder = 0; o.Cell = 0;
}
});
return true;
}
public bool Give(uint id, uint target, int amount)
{
Calls.Add($"GiveObjectTo 0x{id:X8} 0x{target:X8} {amount}");
if (Get(id) == null) return false;
Later(() => Delete(id));
return true;
}
public bool Split(uint id, uint container, int slot, int amount)
{
Calls.Add($"SplitStackInternal 0x{id:X8} 0x{container:X8} {slot} {amount}");
var o = Get(id);
if (o == null || amount >= o.Stack) return false;
Later(() =>
{
o.Stack -= amount;
var n = new FakeObject { Id = NewId(), Name = o.Name, Wcid = o.Wcid, ItemType = o.ItemType, Container = container };
foreach (var kv in o.Ints) n.Ints[kv.Key] = kv.Value;
n.Strings[1] = o.Name;
n.Stack = amount;
Create(n);
});
return true;
}
public bool Merge(uint src, uint dst)
{
Calls.Add($"MergeStackInternal 0x{src:X8} 0x{dst:X8}");
var s = Get(src); var d = Get(dst);
if (s == null || d == null) return false;
Later(() => { d.Stack += s.Stack; Delete(src); });
return true;
}
public bool Wield(uint id, uint mask)
{
Calls.Add($"WieldItem 0x{id:X8} 0x{mask:X8}");
var o = Get(id);
if (o == null) return false;
Later(() => { o.Container = 0; o.Wielder = Player; o.Location = mask; });
return true;
}
public bool Cast(uint target, int spell)
{
Calls.Add($"CastSpell {spell} 0x{target:X8}");
Later(() =>
{
string on = target != 0 && Get(target) is { } t ? " on " + t.Name : string.Empty;
IncomingChat($"You cast Spell {spell}{on}.", 7);
UseDone();
});
return true;
}
public bool ChangeCombat(int mode)
{
Calls.Add($"ChangeCombatMode {mode}");
Later(() =>
{
int prev = CombatMode;
CombatMode = mode;
Events.Enqueue(p => p.OnCombatModeChange(mode, prev));
});
return true;
}
public bool RequestId(uint id)
{
Calls.Add($"RequestId 0x{id:X8}");
var o = Get(id);
if (o == null) return false;
Later(() => { o.Appraised = true; o.LastIdTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds() + (long)_step; });
return true;
}
public bool Salvage()
{
Calls.Add($"SalvagePanelExecute {SalvageItems.Count}");
if (SalvageTool == 0 || SalvageItems.Count == 0) return false;
var items = SalvageItems.ToList();
SalvageItems.Clear();
Later(() =>
{
foreach (uint id in items) Delete(id);
var bag = new FakeObject { Id = NewId(), Name = "Salvaged Steel", Wcid = 20993, ItemType = 0x40000000, Container = Player };
bag.Strings[1] = bag.Name;
Create(bag);
UseDone();
});
return true;
}
// Vendor ──────────────────────────────────────────────────────────────
public void OpenVendor(uint id)
{
VendorOpenId = id;
VendorGeneration++;
VendorItems.Clear();
VendorItems.Add((VendorItemA, "Mana Potion", 2460, 0x20, -1, 80));
VendorItems.Add((VendorItemB, "Iron Arrowhead", 5000, 0x2000000, 500, 2));
Events.Enqueue(p => p.OnVendorOpen(id));
}
public void CloseVendor()
{
uint id = VendorOpenId;
VendorOpenId = 0;
Events.Enqueue(p => p.OnVendorClose(id));
}
public uint VendorTrade(bool buy, List<(uint Id, int Amount)> lines)
{
Calls.Add($"Vendor{(buy ? "Buy" : "Sell")} {string.Join(",", lines.Select(l => $"0x{l.Id:X8}x{l.Amount}"))}");
if (VendorOpenId == 0 || lines.Count == 0) return 0;
uint req = ++VendorRequestSeq;
VendorRequestId = req;
VendorState = 2; VendorResult = 0; VendorIsBuy = buy ? 1 : 0; VendorEntries = lines.Count;
Later(() =>
{
foreach (var (id, amount) in lines)
{
if (buy)
{
var item = VendorItems.First(v => v.Id == id);
var n = new FakeObject { Id = NewId(), Name = item.Name, Wcid = item.Wcid, ItemType = item.ItemType, Container = Player };
n.Strings[1] = item.Name;
n.Stack = amount;
Create(n);
}
else Delete(id);
}
VendorGeneration++;
VendorState = 3; VendorResult = 1;
});
return req;
}
// Trade ───────────────────────────────────────────────────────────────
public void StartTrade(uint partner)
{
TradeOpen = true;
TradeGeneration++;
TradeSequence++;
TradePartner = partner;
TradeInitiator = partner;
TradeLastEvent = 0x01FD;
TradeYouAccepted = TradePartnerAccepted = false;
TradeSelf.Clear();
TradePartnerItems.Clear();
}
public void TradeEvent(uint evt, Action change)
{
change();
TradeSequence++;
TradeLastEvent = evt;
}
}

View file

@ -0,0 +1,221 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MoonSharp.Interpreter;
using RynthCore.Plugin.RynthLua;
namespace RynthLua.CompatTests;
/// <summary>
/// What a test script sees besides RynthLua's own API: <c>check(cond, msg)</c>,
/// <c>eq(actual, expected, msg)</c>, <c>done()</c>, and the <c>harness</c> table that drives
/// the fake world (chat lines, new objects, vitals, enchantments, vendor, trade, ...) and
/// reads back what the client was asked to do. World changes reach the plugin the way the
/// engine delivers them: queued, between ticks.
/// </summary>
internal static class Harness
{
public static int Checks;
public static readonly List<string> Failures = new();
public static bool Done;
public static RynthLuaPlugin? Plugin;
private static FakeWorld W => FakeWorld.W;
public static void Reset()
{
Checks = 0;
Failures.Clear();
Done = false;
}
public static void Register(Script s, string scriptName)
{
s.Globals["check"] = DynValue.NewCallback((c, a) =>
{
Checks++;
bool ok = a.Count > 0 && a[0].CastToBool();
if (!ok) Failures.Add(a.Count > 1 ? a[1].ToPrintString() : "(check failed)");
return DynValue.NewBoolean(ok);
});
s.Globals["eq"] = DynValue.NewCallback((c, a) =>
{
Checks++;
DynValue actual = a.Count > 0 ? a[0] : DynValue.Nil;
DynValue expected = a.Count > 1 ? a[1] : DynValue.Nil;
bool ok = actual.Equals(expected)
|| (actual.Type == DataType.Number && expected.Type == DataType.Number && Math.Abs(actual.Number - expected.Number) < 1e-6);
if (!ok) Failures.Add($"{(a.Count > 2 ? a[2].ToPrintString() : "eq")}: expected <{expected.ToPrintString()}>, got <{actual.ToPrintString()}>");
return DynValue.NewBoolean(ok);
});
s.Globals["done"] = DynValue.NewCallback((c, a) => { Done = true; return DynValue.Nil; });
var h = new Table(s);
var ids = new Table(s);
foreach (var f in typeof(FakeWorld).GetFields().Where(f => f.IsLiteral && f.FieldType == typeof(uint)))
ids[f.Name] = (double)(uint)f.GetRawConstantValue()!;
h["ids"] = ids;
h["player"] = (double)FakeWorld.Player;
void Fn(string name, Func<CallbackArguments, DynValue> body) => h[name] = DynValue.NewCallback((c, a) => body(a));
static double Num(CallbackArguments a, int i, double d = 0) => i < a.Count && a[i].Type == DataType.Number ? a[i].Number : d;
static string Str(CallbackArguments a, int i, string d = "") => i < a.Count && !a[i].IsNil() ? a[i].CastToString() ?? d : d;
static uint Id(CallbackArguments a, int i)
{
if (i >= a.Count) return 0;
if (a[i].Type == DataType.Number) return (uint)a[i].Number;
if (a[i].Type == DataType.Table && a[i].Table.Get("Id").Type == DataType.Number) return (uint)a[i].Table.Get("Id").Number;
return 0;
}
DynValue Strings(IEnumerable<string> list)
{
var t = new Table(s);
foreach (string x in list) t.Append(DynValue.NewString(x));
return DynValue.NewTable(t);
}
Fn("chat", a => { W.IncomingChat(Str(a, 0), (int)Num(a, 1, 0)); return DynValue.Nil; });
Fn("chatInput", a =>
{
int eat = 0;
Plugin!.OnChatBarEnter(Str(a, 0), ref eat);
return DynValue.NewBoolean(eat != 0);
});
Fn("create", a =>
{
Table t = a[0].Table;
var o = new FakeObject
{
Id = W.NewId(),
Name = t.Get("Name").CastToString() ?? "Thing",
Wcid = (uint)(t.Get("Wcid").CastToNumber() ?? 1),
ItemType = (uint)(t.Get("ItemType").CastToNumber() ?? 0x80),
Bitfield = (uint)(t.Get("Bitfield").CastToNumber() ?? 0),
Container = (uint)(t.Get("Container").CastToNumber() ?? 0),
};
o.Strings[1] = o.Name;
if (t.Get("Stack").Type == DataType.Number) o.Stack = (int)t.Get("Stack").Number;
if (t.Get("Value").Type == DataType.Number) o.Ints[19] = (int)t.Get("Value").Number;
if (o.Container == 0)
{
o.Cell = FakeWorld.HomeCell;
o.X = FakeWorld.HomeX + (float)(t.Get("X").CastToNumber() ?? 1);
o.Y = FakeWorld.HomeY + (float)(t.Get("Y").CastToNumber() ?? 0);
o.Z = FakeWorld.HomeZ + (float)(t.Get("Z").CastToNumber() ?? 0);
}
W.Create(o);
return DynValue.NewNumber(o.Id);
});
Fn("delete", a => { W.Delete(Id(a, 0)); return DynValue.Nil; });
Fn("set", a =>
{
var o = W.Get(Id(a, 0)) ?? throw new ScriptRuntimeException("harness.set: no such object");
string kind = Str(a, 1);
uint key = (uint)Num(a, 2);
DynValue v = a.Count > 3 ? a[3] : DynValue.Nil;
switch (kind)
{
case "int": o.Ints[key] = (int)v.Number; break;
case "int64": o.Int64s[key] = (long)v.Number; break;
case "float": o.Floats[key] = v.Number; break;
case "string": o.Strings[key] = v.String; break;
case "bool": o.Bools[key] = v.CastToBool(); break;
case "data": o.DataIds[key] = (uint)v.Number; break;
default: throw new ScriptRuntimeException("harness.set: kind is int, int64, float, string, bool or data");
}
return DynValue.Nil;
});
Fn("move", a =>
{
var o = W.Get(Id(a, 0)) ?? throw new ScriptRuntimeException("harness.move: no such object");
o.X += (float)Num(a, 1); o.Y += (float)Num(a, 2); o.Z += (float)Num(a, 3);
return DynValue.Nil;
});
Fn("vitals", a =>
{
Table t = a[0].Table;
if (t.Get("Health").Type == DataType.Number) W.Hp = (uint)t.Get("Health").Number;
if (t.Get("Stamina").Type == DataType.Number) W.St = (uint)t.Get("Stamina").Number;
if (t.Get("Mana").Type == DataType.Number) W.Mana = (uint)t.Get("Mana").Number;
return DynValue.Nil;
});
Fn("level", a => { W.Me.Ints[25] = (int)Num(a, 0); return DynValue.Nil; });
Fn("xp", a => { W.Me.Int64s[1] = (long)Num(a, 0); return DynValue.Nil; });
Fn("luminance", a => { W.Me.Int64s[6] = (long)Num(a, 0); return DynValue.Nil; });
Fn("vitae", a => { W.Vitae = (float)Num(a, 0, 1); return DynValue.Nil; });
Fn("combatMode", a =>
{
int prev = W.CombatMode;
int mode = (int)Num(a, 0, 1);
W.CombatMode = mode;
W.Events.Enqueue(p => p.OnCombatModeChange(mode, prev));
return DynValue.Nil;
});
Fn("enchant", a =>
{
uint spell = (uint)Num(a, 0);
double secs = Num(a, 1, -1);
W.Enchantments.RemoveAll(e => e.Spell == spell);
W.Enchantments.Add((spell, secs < 0 ? double.MaxValue : W.ServerTime + secs));
W.Events.Enqueue(p => p.OnEnchantmentAdded(spell, secs));
return DynValue.Nil;
});
Fn("dispel", a =>
{
uint spell = (uint)Num(a, 0);
W.Enchantments.RemoveAll(e => e.Spell == spell);
W.Events.Enqueue(p => p.OnEnchantmentRemoved(spell));
return DynValue.Nil;
});
Fn("select", a => { W.SetSelected(Id(a, 0)); return DynValue.Nil; });
Fn("portal", a => { W.Portaling = a.Count > 0 && a[0].CastToBool(); W.PortalStepsLeft = int.MaxValue; return DynValue.Nil; });
Fn("vendor", a =>
{
uint id = Id(a, 0);
if (id != 0) W.OpenVendor(id); else W.CloseVendor();
return DynValue.Nil;
});
Fn("container", a =>
{
uint id = Id(a, 0);
uint was = W.GroundContainer;
W.GroundContainer = id;
if (was != 0) W.Events.Enqueue(p => p.OnStopViewingObjectContents(was));
if (id != 0) W.Events.Enqueue(p => p.OnViewObjectContents(id));
return DynValue.Nil;
});
Fn("tradeStart", a => { W.StartTrade(Id(a, 0)); return DynValue.Nil; });
Fn("partnerAdd", a =>
{
uint item = Id(a, 0);
W.TradeEvent(0x0200, () => W.TradePartnerItems.Add(item));
return DynValue.Nil;
});
Fn("partnerAccept", a =>
{
W.TradeEvent(0x0202, () => { W.TradePartnerAccepted = true; W.TradePartnerAccepts++; W.TradeLastAcceptedBy = W.TradePartner; });
return DynValue.Nil;
});
Fn("tradeComplete", a =>
{
W.TradeEvent(0x01FF, () => { W.TradeCompleted++; W.TradeOpen = false; W.TradeLastClose = 1; });
return DynValue.Nil;
});
Fn("chatLog", a => Strings(W.ChatOut));
Fn("invoked", a => Strings(W.Invoked));
Fn("calls", a => Strings(W.Calls));
Fn("clearCalls", a => { W.Calls.Clear(); W.Invoked.Clear(); W.ChatOut.Clear(); return DynValue.Nil; });
Fn("exists", a => DynValue.NewBoolean(W.Get(Id(a, 0)) != null));
Fn("containerOf", a => DynValue.NewNumber(W.Get(Id(a, 0))?.Container ?? 0));
Fn("wielderOf", a => DynValue.NewNumber(W.Get(Id(a, 0))?.Wielder ?? 0));
Fn("stackOf", a => DynValue.NewNumber(W.Get(Id(a, 0))?.Stack ?? 0));
Fn("autorun", a => DynValue.NewBoolean(W.AutoRun));
Fn("salvageItems", a =>
{
var t = new Table(s);
foreach (uint id in W.SalvageItems) t.Append(DynValue.NewNumber(id));
return DynValue.NewTable(t);
});
s.Globals["harness"] = DynValue.NewTable(h);
}
}

View file

@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using RynthCore.Plugin.RynthLua;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthLua.CompatTests;
// Runs every Scripts\*.lua through RynthLua's real Lua runtime against the fake engine
// (FakeHost / FakeWorld), one fresh plugin and world per script, and reports PASS/FAIL.
// A script passes when it called done(), every check() / eq() held, at least one ran, and
// its console shows no "error" line. Files go to a temp folder that is removed afterwards.
//
// Run: dotnet run -c Release [-- filter] (exit 0 = pass, 1 = fail)
internal static unsafe class Program
{
private const int TimeoutMs = 30_000;
private static int Main(string[] args)
{
string filter = args.Length > 0 ? args[0] : string.Empty;
string root = Path.Combine(Path.GetTempPath(), "RynthLuaCompat-" + Guid.NewGuid().ToString("N")[..8]);
RynthLuaPaths.Root = root;
RynthLuaPaths.LegacyScripts = Path.Combine(root, "no-legacy-scripts");
RynthLuaPlugin.ExtraGlobals = Harness.Register;
string scriptDir = ScriptFolder();
var scripts = Directory.GetFiles(scriptDir, "*.lua")
.Where(f => Path.GetFileNameWithoutExtension(f).Contains(filter, StringComparison.OrdinalIgnoreCase))
.OrderBy(f => f, StringComparer.OrdinalIgnoreCase)
.ToList();
Console.WriteLine($"=== RynthLua UtilityBelt compatibility tests ({scripts.Count} scripts) ===");
int passed = 0, checks = 0;
var failed = new List<string>();
try
{
foreach (string file in scripts)
{
var (ok, n) = RunOne(file);
checks += n;
if (ok) passed++;
else failed.Add(Path.GetFileNameWithoutExtension(file));
}
}
finally
{
try { Directory.Delete(root, recursive: true); } catch { }
}
Console.WriteLine();
Console.WriteLine($"{passed}/{scripts.Count} scripts passed, {checks} checks.");
if (scripts.Count == 0) { Console.WriteLine("ABORT: no scripts ran."); return 1; }
if (failed.Count > 0) Console.WriteLine("FAILED: " + string.Join(", ", failed));
else Console.WriteLine("ALL RYNTHLUA COMPAT TESTS PASSED.");
return failed.Count == 0 ? 0 : 1;
}
private static (bool Ok, int Checks) RunOne(string file)
{
string name = Path.GetFileNameWithoutExtension(file);
FakeWorld.W = new FakeWorld();
Harness.Reset();
RynthCoreApiNative api = FakeHost.Build();
var runtime = new RynthPluginRuntime<RynthLuaPlugin>();
int init = runtime.Init(&api);
RynthLuaPlugin? plugin = runtime.Plugin;
if (init != 0 || plugin == null)
{
Console.WriteLine($"FAIL {name}: the plugin didn't initialize ({init})");
return (false, 0);
}
Harness.Plugin = plugin;
var sw = Stopwatch.StartNew();
string? startError = null;
try
{
plugin.OnLoginComplete();
for (int i = 0; i < 3; i++) Tick(plugin);
Directory.CreateDirectory(RynthLuaPaths.Scripts);
File.Copy(file, Path.Combine(RynthLuaPaths.Scripts, name + ".lua"), overwrite: true);
startError = plugin.StartScript(name);
while (startError == null && !Harness.Done && plugin.ScriptIsLoaded(name) && sw.ElapsedMilliseconds < TimeoutMs)
{
Tick(plugin);
Thread.Sleep(1);
}
}
catch (Exception ex)
{
startError = "harness exception: " + ex;
}
string console = plugin.ScriptConsoleText(name);
// A script may raise an error on purpose; it marks the message "(expected)".
var errors = console.Split('\n')
.Where(l => l.StartsWith("error", StringComparison.OrdinalIgnoreCase) && !l.Contains("(expected)", StringComparison.Ordinal))
.ToList();
var reasons = new List<string>();
if (startError != null) reasons.Add(startError);
if (!Harness.Done) reasons.Add(sw.ElapsedMilliseconds >= TimeoutMs ? "timed out before done()" : "stopped before done()");
if (Harness.Checks == 0) reasons.Add("no checks ran");
reasons.AddRange(Harness.Failures.Select(f => "check: " + f));
reasons.AddRange(errors.Select(e => "console: " + e));
try { plugin.StopScript(name); } catch { }
runtime.Shutdown();
bool ok = reasons.Count == 0;
Console.WriteLine($"{(ok ? "PASS" : "FAIL")} {name} ({Harness.Checks} checks, {sw.ElapsedMilliseconds} ms)");
if (!ok)
{
foreach (string r in reasons.Take(25)) Console.WriteLine(" " + r);
Console.WriteLine(" --- console (last 25 lines) ---");
foreach (string l in console.Split('\n').TakeLast(25)) Console.WriteLine(" | " + l);
}
return (ok, Harness.Checks);
}
/// <summary>The project's own Scripts folder (so a deleted script can't linger in bin), else the copy in bin.</summary>
private static string ScriptFolder([System.Runtime.CompilerServices.CallerFilePath] string source = "")
{
string beside = Path.Combine(Path.GetDirectoryName(source) ?? string.Empty, "Scripts");
return Directory.Exists(beside) ? beside : Path.Combine(AppContext.BaseDirectory, "Scripts");
}
private static void Tick(RynthLuaPlugin plugin)
{
FakeWorld.W.Step();
while (FakeWorld.W.Events.Count > 0) FakeWorld.W.Events.Dequeue()(plugin);
plugin.OnTick();
}
}

View file

@ -0,0 +1,40 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
UtilityBelt-compatibility tests for RynthLua: runs UB-style Lua scripts (Scripts\*.lua)
against RynthLua's real Lua runtime with a fake engine (FakeHost.cs) that serves a
scripted world: a player with vitals, skills and inventory, a few objects, chat, a
vendor and a trade. No AC client, no engine, nothing written outside a temp folder.
The plugin itself is a NativeAOT x86 library, so its sources (and the SDK's) are
compiled in here directly instead of referencing the projects.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
A filter after the usual double dash runs only the scripts whose name contains it.
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>RynthLua.CompatTests</RootNamespace>
<!-- The plugin's own warnings belong to the plugin build. -->
<NoWarn>$(NoWarn);CS0649;CS0169;CS0414;CS8618</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MoonSharp" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthLua\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthLua\obj\**;..\..\Plugins\RynthCore.Plugin.RynthLua\bin\**" Link="Plugin\%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="..\..\Plugins\Shared\RynthAiScriptApi.cs" Link="Plugin\Shared\RynthAiScriptApi.cs" />
<Compile Include="..\..\Plugins\Shared\UseAudit.cs" Link="Plugin\Shared\UseAudit.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\*.cs" Link="Sdk\%(Filename)%(Extension)" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.PluginCore\*.cs" Link="Sdk\%(Filename)%(Extension)" />
</ItemGroup>
<ItemGroup>
<None Include="Scripts\**\*.lua" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,193 @@
-- UB-style game.Actions use: UB's argument order and defaults, ActionOptions, callbacks,
-- await, action fields (ActionType, Error), RunAllOrdered, the vendor, trade and salvage
-- actions, the WorldObject action methods, and game.ActionQueue.
local ids = harness.ids
local Actions = game.Actions
local me = game.Character.Id
local function waitUntil(fn, ms)
local t = 0
while not fn() and t < (ms or 5000) do sleep(20); t = t + 20 end
return fn()
end
local function invokedHas(text)
for _, line in ipairs(harness.invoked()) do if line == text then return true end end
return false
end
local function callsHave(prefix)
for _, line in ipairs(harness.calls()) do if line:sub(1, #prefix) == prefix then return true end end
return false
end
-- use with await; the action is queued already when the call returns
local use = Actions.ObjectUse(ids.Potion)
check(use.ActionType == ActionType.Misc, "ObjectUse ActionType == ActionType.Misc")
eq(use.ObjectId, ids.Potion, "ObjectUse.ObjectId")
check(game.ActionQueue.Contains(use), "ActionQueue.Contains")
await(use)
check(use.IsFinished and use.Success, "ObjectUse succeeded: " .. tostring(use.ErrorDetails))
check(use.Error == ActionError.None, "Error == ActionError.None")
eq(harness.stackOf(ids.Potion), 4, "a potion was used")
-- UB's positional callback: ObjectUse(id, target, options, callback)
local cbResult
Actions.ObjectUse(ids.Potion, 0, nil, function(a) cbResult = a end)
check(waitUntil(function() return cbResult ~= nil end), "callback ran")
check(cbResult and cbResult.Success, "callback got the finished action")
-- action:Await()
local sel = Actions.ObjectSelect(ids.Drudge)
sel:Await()
check(sel.Success, "ObjectSelect")
eq(game.World.Selected.Id, ids.Drudge, "selected")
-- ActionOptions, the UB way
local opts = ActionOptions.new()
opts.Priority = ActionType.Wield
opts.MaxRetryCount = 0
opts.TimeoutMilliseconds = 4000
local appraise = Actions.ObjectAppraise(ids.Drudge, opts)
eq(appraise.Priority, ActionType.Wield, "options Priority used")
await(appraise)
check(appraise.Success, "ObjectAppraise")
check(game.World.Get(ids.Drudge).HasAppraisalData, "appraised")
local opts2 = ActionOptions()
check(opts2 ~= nil, "ActionOptions() also constructs")
-- a failure reports UB's error names
local bad = await(Actions.ObjectUse(0x7FFFFFF0))
check(not bad.Success, "using an unknown object fails")
check(bad.Error == ActionError.InvalidSourceObject, "Error == ActionError.InvalidSourceObject, got " .. tostring(bad.Error))
-- inventory actions with UB's arguments
local move = await(Actions.ObjectMove(ids.Tapers, me, 0, true))
check(move.Success, "ObjectMove to the main pack: " .. tostring(move.ErrorDetails))
check(move.ActionType == ActionType.Inventory, "ObjectMove ActionType == ActionType.Inventory")
eq(harness.containerOf(ids.Tapers), me, "tapers moved")
local split = await(Actions.ObjectSplit(ids.Pyreals, me, 100))
check(split.Success, "ObjectSplit: " .. tostring(split.ErrorDetails))
check(split.NewStackObjectId ~= nil and split.NewStackObjectId ~= 0, "ObjectSplit.NewStackObjectId")
eq(harness.stackOf(ids.Pyreals), 2400, "source stack shrank")
eq(harness.stackOf(split.NewStackObjectId), 100, "new stack of 100")
local drop = await(Actions.ObjectDrop(split.NewStackObjectId))
check(drop.Success, "ObjectDrop")
local give = await(Actions.ObjectGive(ids.ManaStone, ids.OtherPlayer))
check(give.Success, "ObjectGive")
check(not harness.exists(ids.ManaStone), "given away")
local wield = await(Actions.ObjectWield(ids.Sword, EquipMask.MeleeWeapon))
check(wield.Success, "ObjectWield with a slot: " .. tostring(wield.ErrorDetails))
check(wield.ActionType == ActionType.Wield, "ObjectWield ActionType == ActionType.Wield")
eq(harness.wielderOf(ids.Sword), me, "sword wielded")
-- combat mode and casting
local mode = await(Actions.SetCombatMode(CombatMode.Magic))
check(mode.Success, "SetCombatMode(CombatMode.Magic)")
check(game.Character.CombatMode == CombatMode.Magic, "in magic mode")
local cast = await(Actions.CastSpell(4567, ids.Drudge))
check(cast.Success, "CastSpell: " .. tostring(cast.ErrorDetails))
check(cast.ActionType == ActionType.CastSpell, "CastSpell ActionType")
local wandCast = await(Actions.CastEquippedWandSpell(ids.Drudge))
check(wandCast.Success, "CastEquippedWandSpell: " .. tostring(wandCast.ErrorDetails))
check(callsHave(string.format("UseEquippedItem 0x%08X 0x%08X", ids.Wand, ids.Drudge)), "the wand was used on the target")
-- chat, tells, sleep, blank, autorun
check(await(Actions.InvokeChat("/say hello")).Success, "InvokeChat")
check(invokedHas("/say hello"), "InvokeChat line")
check(await(Actions.SendTellById(ids.OtherPlayer, "hi there")).Success, "SendTellById")
check(invokedHas("/t Friendly Player, hi there"), "SendTellById line")
local t0 = clock()
check(await(Actions.Sleep(150)).Success, "Sleep action")
check(clock() - t0 >= 140, "Sleep waited")
check(await(Actions.Blank()).Success, "Blank")
check(await(Actions.SetAutorun(true)).Success, "SetAutorun")
check(harness.autorun(), "autorun on")
-- RunAllOrdered
local steps = {
Actions.ObjectSelect(ids.Crier),
Actions.Sleep(50),
Actions.ObjectSelect(ids.Lever),
}
local all = await(Actions.RunAllOrdered(steps))
check(all.Success, "RunAllOrdered")
eq(game.World.Selected.Id, ids.Lever, "RunAllOrdered ran in order")
-- salvage with the ust
local salvageAdd = await(Actions.SalvageAdd(ids.Tapers))
check(salvageAdd.Success, "SalvageAdd: " .. tostring(salvageAdd.ErrorDetails))
eq(harness.salvageItems()[1], ids.Tapers, "in the salvage panel")
local salvage = await(Actions.Salvage())
check(salvage.Success, "Salvage: " .. tostring(salvage.ErrorDetails))
check(not harness.exists(ids.Tapers), "salvaged")
-- the vendor
harness.vendor(ids.Shopkeeper)
check(waitUntil(function() return game.World.Vendor.IsOpen end), "vendor open")
check(await(Actions.VendorAddToBuyList(ids.VendorItemA, 2)).Success, "VendorAddToBuyList")
local buy = await(Actions.VendorBuyAll())
check(buy.Success, "VendorBuyAll: " .. tostring(buy.ErrorDetails))
check(buy.ActionType == ActionType.Vendor, "VendorBuyAll ActionType")
check(game.Character.GetFirstInventory("Mana Potion") ~= nil, "bought a Mana Potion")
eq(game.Character.GetInventoryCount("Mana Potion"), 2, "bought two")
check(await(Actions.VendorAddToSellList(ids.Ust)).Success, "VendorAddToSellList")
check(await(Actions.VendorClearSellList()).Success, "VendorClearSellList")
check(await(Actions.VendorAddToSellList(ids.Potion)).Success, "VendorAddToSellList again")
local sell = await(Actions.VendorSellAll())
check(sell.Success, "VendorSellAll: " .. tostring(sell.ErrorDetails))
check(not harness.exists(ids.Potion), "sold the potions")
check(harness.exists(ids.Ust), "the cleared item wasn't sold")
harness.vendor(nil)
check(waitUntil(function() return not game.World.Vendor.IsOpen end), "vendor closed")
local noVendor = await(Actions.VendorBuyAll())
check(noVendor.Error == ActionError.VendorNotOpen, "VendorBuyAll without a vendor: " .. tostring(noVendor.Error))
-- trade
harness.tradeStart(ids.OtherPlayer)
check(waitUntil(function() return game.Character.Trade.IsOpen end), "trade open")
local add = await(Actions.TradeAdd(ids.Ust))
check(add.Success, "TradeAdd: " .. tostring(add.ErrorDetails))
eq(game.Character.Trade.YourItemIds[1], ids.Ust, "in the trade window")
check(await(Actions.TradeAccept()).Success, "TradeAccept")
check(game.Character.Trade.YouAccepted, "accepted")
check(await(Actions.TradeDecline()).Success, "TradeDecline")
check(await(Actions.TradeReset()).Success, "TradeReset")
eq(#game.Character.Trade.YourItemIds, 0, "trade window emptied")
check(await(Actions.TradeEnd()).Success, "TradeEnd")
check(not game.Character.Trade.IsOpen, "trade ended")
-- WorldObject action methods
local lever = game.World.Get(ids.Lever)
check(await(lever:Select()).Success, "wo:Select()")
check(await(lever:Use()).Success, "wo:Use()")
local cap = game.World.Get(ids.Cap)
harness.tradeStart(ids.OtherPlayer)
check(waitUntil(function() return game.Character.Trade.IsOpen end), "trade open again")
check(await(cap:AddToTrade()).Success, "wo:AddToTrade()")
local sword = game.World.Get(ids.Sword)
local woSalvage = await(sword:Salvage())
check(woSalvage.Success, "wo:Salvage(): " .. tostring(woSalvage.ErrorDetails))
check(not harness.exists(ids.Sword), "wo:Salvage() salvaged it")
-- not available yet: these fail cleanly instead of being missing
for _, name in ipairs({ "Login", "Logout", "SkillAdvance", "AttributeAddExperience", "SkillAddExperience",
"VitalAddExperience", "FellowCreate", "FellowDisband", "FellowDismiss", "FellowSetLeader", "FellowQuit",
"FellowRecruit", "FellowSetOpen", "AllegianceSwear", "AllegianceBreak", "Inscribe" }) do
check(type(Actions[name]) == "function", "Actions." .. name .. " exists")
end
local inscribe = await(Actions.Inscribe(ids.Cap, "mine"))
check(not inscribe.Success and inscribe.ErrorDetails:find("engine") ~= nil, "Inscribe fails and says why")
-- the queue
local q1 = Actions.Sleep(300, { Priority = ActionType.Misc })
local q2 = Actions.ObjectSelect(ids.Crier, { Priority = ActionType.Inventory })
check(game.ActionQueue.Contains(q2), "queued")
game.ActionQueue.Remove(q2)
check(q2.IsFinished and q2.Error == ActionError.Cancelled, "Remove cancels")
await(q1)
local n = 0
for _, a in ipairs(game.ActionQueue.Queue) do n = n + 1 end
eq(n, 0, "queue empty")
done()

View file

@ -0,0 +1,172 @@
-- UB-style game.Character use: identity, stats on the weenie, inventory lists and
-- searches, spellbook, enchantments, the character events, and the trade window.
local ids = harness.ids
local Character = game.Character
local function waitUntil(fn, ms)
local t = 0
while not fn() and t < (ms or 3000) do sleep(20); t = t + 20 end
return fn()
end
-- identity and simple state
eq(Character.Id, harness.player, "Character.Id")
eq(game.CharacterId, harness.player, "game.CharacterId")
eq(Character.Weenie.Name, "Tester", "Character.Weenie.Name")
eq(Character.Weenie:Value(IntId.Level), 100, "level from the weenie")
eq(Character.Weenie:Value(Int64Id.TotalExperience), 1000000, "total xp from the weenie")
eq(Character.Weenie:Value(StringId.Template), "Adventurer", "template from the weenie")
check(Character.CombatMode == CombatMode.NonCombat, "CombatMode == CombatMode.NonCombat")
eq(Character.InPortalSpace, false, "InPortalSpace")
eq(Character.Vitae, 1, "Vitae")
eq(Character.BurdenUnits, 1500, "BurdenUnits")
eq(Character.MaxBurdenUnits, 200 * 150, "MaxBurdenUnits")
eq(Character.IsBusy(), false, "IsBusy()")
-- stats the UB way (on the weenie) and with the vital numbering UB uses
local vitals = Character.Weenie.Vitals
eq(vitals[VitalId.Health].Current, 300, "Health.Current")
eq(vitals[VitalId.Health].Max, 350, "Health.Max")
eq(vitals[VitalId.Stamina].Current, 400, "Stamina.Current")
eq(vitals[VitalId.Mana].Current, 250, "Mana.Current")
eq(vitals[3].Current, 400, "a hard-coded 3 is Stamina, as in UB")
eq(vitals[5].Max, 500, "a hard-coded 5 is Mana, as in UB")
local skills = Character.Weenie.Skills
eq(skills[SkillId.WarMagic].Current, 430, "WarMagic.Current")
eq(skills[SkillId.WarMagic].Base, 380, "WarMagic.Base")
check(skills[SkillId.WarMagic].Training == SkillTrainingType.Trained, "WarMagic trained")
check(skills[SkillId.Axe].Training == SkillTrainingType.Untrained, "Axe untrained")
eq(skills[SkillId.MissleWeapons].Current, 350, "UB's MissleWeapons spelling")
eq(Character.Weenie.Attributes[AttributeId.Self].Current, 190, "Self.Current")
-- inventory as UB lists
local inv = Character.Inventory
check(#inv >= 8, "Inventory has everything carried")
local seen = {}
for _, wo in ipairs(inv) do seen[wo.Name] = true end
check(seen["Healing Potion"] and seen["Mana Stone"] and seen["Wand of Testing"], "Inventory: packs, side packs and equipment")
eq(#Character.Containers, 1, "Containers")
eq(Character.Containers[1].Name, "Backpack", "Containers[1]")
local eqp = {}
for _, wo in ipairs(Character.Equipment) do eqp[wo.Name] = true end
check(eqp["Wand of Testing"] and eqp["Leather Cap"], "Equipment")
local n = 0
for wo in Character.Inventory do n = n + 1 end
eq(n, #inv, "for wo in Character.Inventory do")
-- UB's searches
local potions = Character.GetInventory("Potion")
eq(#potions, 1, "GetInventory(name)")
eq(#Character.GetInventory(ObjectClass.SpellComponent), 1, "GetInventory(ObjectClass)")
eq(#Character.GetInventory(function(wo) return wo:Value(IntId.Value) >= 500 end), 2, "GetInventory(function)")
eq(Character.GetFirstInventory("Healing Potion").Id, ids.Potion, "GetFirstInventory(name)")
check(Character.GetFirstInventory("Nonexistent Thing") == nil, "GetFirstInventory miss")
eq(Character.GetInventoryCount("Prismatic Taper"), 100, "GetInventoryCount counts stack sizes")
eq(Character.GetInventoryCount(ObjectClass.Money), 2500, "GetInventoryCount(ObjectClass)")
eq(Character:GetInventoryCount("Healing Potion"), 5, "colon call form")
-- RynthLua's own call forms keep working
eq(#Character.Inventory("Potion"), 1, "Inventory(filter) still works")
eq(Character.InventoryCount("Prismatic Taper"), 100, "InventoryCount still works")
-- spellbook
local known = Character.SpellBook.KnownSpellsIds
eq(#known, 4, "SpellBook.KnownSpellsIds")
check(Character.SpellBook.IsKnown(2345), "SpellBook.IsKnown")
check(not Character.SpellBook.IsKnown(9999), "SpellBook.IsKnown false")
eq(Character.SpellBook.Count, 4, "SpellBook.Count")
-- enchantments
local active = Character.ActiveEnchantments()
eq(#active, 2, "ActiveEnchantments()")
local byId = {}
for _, e in ipairs(active) do byId[e.SpellId] = e end
check(byId[3456] ~= nil and byId[3456].ExpiresAt ~= nil, "enchantment 3456 has ExpiresAt")
check(byId[5000] ~= nil, "permanent enchantment 5000")
eq(#Character.AllEnchantments(), 2, "AllEnchantments()")
-- events
local vital, ench, level, xp, lum, vitae, death
local portalIn, portalOut = false, false
Character.OnVitalChanged.Add(function(e) if e.Type == VitalId.Stamina then vital = e end end)
Character.OnEnchantmentsChanged.Add(function(e) ench = e end)
Character.OnLevelChanged.Add(function(e) level = e end)
Character.OnTotalExperienceChanged.Add(function(e) xp = e end)
Character.OnAvailableLuminanceChanged.Add(function(e) lum = e end)
Character.OnVitaeChanged.Add(function(e) vitae = e end)
Character.OnPortalSpaceEntered.Add(function() portalIn = true end)
Character.OnPortalSpaceExited.Add(function() portalOut = true end)
Character.OnDeath.Add(function(e) death = e end)
sleep(700) -- the slow polls take their baseline
harness.vitals({ Stamina = 350 })
check(waitUntil(function() return vital ~= nil end), "OnVitalChanged")
if vital then
eq(vital.Value, 350, "OnVitalChanged.Value")
eq(vital.OldValue, 400, "OnVitalChanged.OldValue")
end
harness.enchant(7777, 1800)
check(waitUntil(function() return ench ~= nil end), "OnEnchantmentsChanged")
if ench then
check(ench.Type == AddRemoveEventType.Added, "OnEnchantmentsChanged.Type Added")
eq(ench.Enchantment.SpellId, 7777, "Enchantment.SpellId")
eq(ench.LayeredSpellId.Id, 7777, "LayeredSpellId.Id")
end
ench = nil
harness.dispel(7777)
check(waitUntil(function() return ench ~= nil end), "OnEnchantmentsChanged removed")
if ench then check(ench.Type == AddRemoveEventType.Removed, "OnEnchantmentsChanged.Type Removed") end
harness.level(101)
harness.xp(1200000)
harness.luminance(6000)
harness.vitae(0.95)
check(waitUntil(function() return level and xp and lum and vitae end), "level/xp/luminance/vitae events")
if level then eq(level.Level, 101, "Level"); eq(level.OldLevel, 100, "OldLevel") end
if xp then eq(xp.TotalExperience, 1200000, "TotalExperience"); eq(xp.OldTotalExperience, 1000000, "OldTotalExperience") end
if lum then eq(lum.AvailableLuminance, 6000, "AvailableLuminance"); eq(lum.OldAvailableLuminance, 5000, "OldAvailableLuminance") end
if vitae then check(math.abs(vitae.Vitae - 0.95) < 0.001, "Vitae") end
harness.portal(true)
check(waitUntil(function() return portalIn end), "OnPortalSpaceEntered")
harness.portal(false)
check(waitUntil(function() return portalOut end), "OnPortalSpaceExited")
harness.chat("You have been killed by a Drudge Skulker!", ChatMessageType.System)
check(waitUntil(function() return death ~= nil end), "OnDeath")
if death then
check(death.Text:find("killed") ~= nil, "OnDeath.Text")
eq(death.KillerId, 0, "OnDeath.KillerId (unknown: 0)")
end
-- the trade window
local Trade = Character.Trade
check(not Trade.IsOpen, "no trade open")
local started, added, accepted, completed, ended
Trade.OnStarted.Add(function(e) started = e end)
Trade.OnObjectAdded.Add(function(e) added = e end)
Trade.OnAccepted.Add(function(e) accepted = e end)
Trade.OnCompleted.Add(function(e) completed = e end)
Trade.OnEnded.Add(function(e) ended = e end)
harness.tradeStart(ids.OtherPlayer)
check(waitUntil(function() return started ~= nil end), "Trade.OnStarted")
if started then eq(started.PartnerId, ids.OtherPlayer, "OnStarted.PartnerId") end
check(Trade.IsOpen, "Trade.IsOpen")
eq(Trade.PartnerId, ids.OtherPlayer, "Trade.PartnerId")
harness.partnerAdd(ids.ChestGem)
check(waitUntil(function() return added ~= nil end), "Trade.OnObjectAdded")
if added then
eq(added.ObjectId, ids.ChestGem, "OnObjectAdded.ObjectId")
check(added.Side == TradeSide.Partner, "OnObjectAdded.Side")
end
eq(Trade.PartnerItemIds[1], ids.ChestGem, "Trade.PartnerItemIds")
harness.partnerAccept()
check(waitUntil(function() return accepted ~= nil end), "Trade.OnAccepted")
if accepted then eq(accepted.AcceptorId, ids.OtherPlayer, "OnAccepted.AcceptorId") end
check(Trade.PartnerAccepted, "Trade.PartnerAccepted")
harness.tradeComplete()
check(waitUntil(function() return completed ~= nil and ended ~= nil end), "Trade.OnCompleted and OnEnded")
if completed then eq(completed.PartnerItemIds[1], ids.ChestGem, "OnCompleted.PartnerItemIds") end
check(not Trade.IsOpen, "trade closed")
done()

View file

@ -0,0 +1,82 @@
-- UB-style use of the enum globals (UtilityBelt.Common.Enums and the scripting enums).
-- Written the way UB scripts use them: comparisons against fields, flag helpers,
-- ToNumber(), tostring() for display, and the property-id enums passed to wo:Value().
-- Globals UB scripts expect to exist
for _, name in ipairs({ "ObjectClass", "ObjectType", "SkillId", "AttributeId", "VitalId", "CombatMode",
"IntId", "Int64Id", "FloatId", "StringId", "BoolId", "DataId", "InstanceId", "EquipMask",
"ChatMessageType", "ChatChannel", "SkillTrainingType", "MagicSchool", "ClientState", "DistanceType",
"AddRemoveEventType", "ActionError", "ActionType", "UseActionType", "CoverageMask", "ClientCapability",
"TradeSide", "CharacterOptions1", "MaterialType", "DamageType", "CreatureType", "WeenieError" }) do
check(_G[name] ~= nil, "global enum " .. name)
end
-- Values that match UB's numbering
eq(ObjectClass.Monster, 5, "ObjectClass.Monster")
eq(ObjectClass.NumObjectClasses, 43, "ObjectClass.NumObjectClasses")
eq(SkillId.MeleeDefense, 6, "SkillId.MeleeDefense")
eq(SkillId.MissleWeapons, 47, "SkillId.MissleWeapons (UB's spelling)")
eq(SkillId.ThrownWeapons, 12, "SkillId.ThrownWeapons")
eq(SkillId.ArmorRepair, 26, "SkillId.ArmorRepair")
eq(SkillId.Undef, 0, "SkillId.Undef")
eq(AttributeId.Undef, 0, "AttributeId.Undef")
eq(VitalId.Health, 1, "VitalId.Health")
eq(VitalId.Stamina, 3, "VitalId.Stamina (UB numbering)")
eq(VitalId.Mana, 5, "VitalId.Mana (UB numbering)")
eq(CombatMode.Magic, 8, "CombatMode.Magic")
eq(CombatMode.Invalid, 153, "CombatMode.Invalid")
eq(EquipMask.Head, 1, "EquipMask.Head")
eq(EquipMask.MeleeWeapon, 1048576, "EquipMask.MeleeWeapon")
eq(ChatMessageType.Tell, 3, "ChatMessageType.Tell")
eq(ChatMessageType.Fellowship, 19, "ChatMessageType.Fellowship")
eq(ChatChannel.General, 2, "ChatChannel.General")
eq(SkillTrainingType.Specialized, 3, "SkillTrainingType.Specialized")
eq(MagicSchool.WarMagic, 1, "MagicSchool.WarMagic")
eq(DistanceType.T2D, 0, "DistanceType.T2D")
eq(AddRemoveEventType.Removed, 1, "AddRemoveEventType.Removed")
eq(ActionType.Inventory, 9000, "ActionType.Inventory")
eq(IntId.Value, 19, "IntId.Value")
eq(IntId.MerchandiseObjectTypes, 74, "IntId.MerchandiseObjectTypes (UB name)")
eq(UseActionType.SummonPortal, 2, "UseActionType.SummonPortal")
eq(TradeSide.Partner, 2, "TradeSide.Partner")
eq(MaterialType.Steel, 64, "MaterialType.Steel")
eq(DamageType.Fire, 16, "DamageType.Fire")
-- ToNumber() on any enum value, as UB scripts do before arithmetic
eq(SkillId.Axe:ToNumber(), 1, "SkillId.Axe:ToNumber()")
eq(CombatMode.Melee:ToNumber() + 1, 3, "CombatMode.Melee:ToNumber() + 1")
eq(StringId.Name:ToNumber(), 1, "StringId.Name:ToNumber()")
eq(ObjectType.Creature:ToNumber(), 16, "ObjectType.Creature:ToNumber()")
-- tostring() of the typed enums gives the name (UB prints enum values by name)
eq(tostring(StringId.Name), "Name", "tostring(StringId.Name)")
eq(tostring(FloatId.WeaponLength), "WeaponLength", "tostring(FloatId.WeaponLength)")
eq(tostring(ObjectType.Creature), "Creature", "tostring(ObjectType.Creature)")
-- Flag helpers on flag enums
local both = ObjectType.Creature:AddFlags(ObjectType.Misc)
check(both:HasFlags(ObjectType.Creature), "AddFlags/HasFlags Creature")
check(both:HasFlags(ObjectType.Misc), "AddFlags/HasFlags Misc")
check(not both:HasFlags(ObjectType.Portal), "HasFlags Portal is false")
eq(both:ToNumber(), 16 + 128, "combined flags value")
local back = both:RemoveFlags(ObjectType.Misc)
check(back == ObjectType.Creature, "RemoveFlags gives the same enum value back")
check(EquipMask.Head:HasFlags(EquipMask.Head), "HasFlags on a numeric flag enum")
-- Typed enums compare with each other, not with plain numbers (UB userdata behaves so too)
check(StringId.Name == StringId.Name, "same typed value is equal")
check(StringId.Name ~= StringId.Title, "different typed values differ")
check(FloatId.WeaponLength < FloatId.DamageMod, "typed values order by number")
-- Reverse lookup of a number to its name (RynthLua's way; UB uses tostring)
eq(SkillId[6], "MeleeDefense", "SkillId[6]")
eq(ObjectClass[5], "Monster", "ObjectClass[5]")
-- ClientState: UB compares game.State and OnStateChanged.NewState against it
check(game.State == ClientState.In_Game, "game.State == ClientState.In_Game")
check(ClientState.Character_Select_Screen ~= ClientState.In_Game, "ClientState values differ")
-- ActionError compares with the action's Error
eq(ActionError.TooBusy, ActionError.TooBusy, "ActionError.TooBusy")
done()

View file

@ -0,0 +1,93 @@
-- UB-style event handling: Add/Once/Until/Remove in either case and call style, handlers
-- that sleep, several handlers on one event, errors that don't unsubscribe, event args
-- that can be written to (Eat), and the game-level events.
local function waitUntil(fn, ms)
local t = 0
while not fn() and t < (ms or 3000) do sleep(20); t = t + 20 end
return fn()
end
local chat = game.World.OnChatText
-- Add, in UB's call styles
local a, b, c = 0, 0, 0
local fa = function(e) a = a + 1 end
chat.Add(fa)
chat:Add(function(e) b = b + 1 end)
chat.add(function(e) c = c + 1 end) -- lower-case verb
harness.chat("one", 0)
check(waitUntil(function() return a == 1 and b == 1 and c == 1 end), "Add / :Add / add all fire")
-- Remove (both cases)
chat.Remove(fa)
harness.chat("two", 0)
check(waitUntil(function() return b == 2 and c == 2 end), "others still fire")
eq(a, 1, "Remove(fn) unsubscribed")
-- Once
local once = 0
chat.Once(function(e) once = once + 1 end)
local once2 = 0
chat.once(function(e) once2 = once2 + 1 end)
harness.chat("three", 0)
harness.chat("four", 0)
check(waitUntil(function() return c == 4 end), "lines delivered")
eq(once, 1, "Once fires once")
eq(once2, 1, "once fires once")
-- Until: kept until the handler returns true
local seen = {}
chat.Until(function(e)
seen[#seen + 1] = e.Message
return e.Message == "stop"
end)
harness.chat("go", 0)
harness.chat("stop", 0)
harness.chat("after", 0)
check(waitUntil(function() return c == 7 end), "lines delivered again")
eq(#seen, 2, "Until stopped after returning true")
eq(seen[2], "stop", "Until saw the stopping line")
-- handlers can sleep and still see their own args
local slept
chat.Add(function(e)
local msg = e.Message
sleep(100)
if msg == "sleepy" then slept = e.Message end
end)
harness.chat("sleepy", 0)
check(waitUntil(function() return slept == "sleepy" end), "a handler that sleeps keeps its args")
-- args are writable (UB scripts set e.Eat)
local wrote
chat.Add(function(e) e.Eat = true; wrote = e.Eat end)
harness.chat("eat me", 0)
check(waitUntil(function() return wrote == true end), "e.Eat can be set")
-- an error in a handler is reported but the handler stays subscribed
local calls = 0
game.World.OnTell.Add(function(e)
calls = calls + 1
if calls == 1 then error("first tell fails (expected)") end
end)
harness.chat('Friendly Player tells you, "one"', ChatMessageType.Tell)
harness.chat('Friendly Player tells you, "two"', ChatMessageType.Tell)
check(waitUntil(function() return calls == 2 end), "handler still subscribed after an error")
-- game-level events
local ticks = 0
local tick = function() ticks = ticks + 1 end
game.OnTick.Add(tick)
check(waitUntil(function() return ticks >= 3 end), "game.OnTick")
game.OnTick.Remove(tick)
local frozen = ticks
sleep(100)
eq(ticks, frozen, "game.OnTick removed")
check(game.OnStateChanged ~= nil and game.OnScriptEnd ~= nil, "game.OnStateChanged / OnScriptEnd exist")
game.OnScriptEnd.Add(function() end)
-- tostring of an event
check(tostring(chat):find("OnChatText") ~= nil, "tostring(event)")
done()

View file

@ -0,0 +1,35 @@
-- UB-style use of the game root: state, identity, capabilities, and a script command
-- (RynthLua's RegisterCommand, next to UB's OnChatInput way in world.lua).
check(game ~= nil, "game global")
check(game.State == ClientState.In_Game, "game.State == ClientState.In_Game")
eq(game.ServerName, "TestServer", "game.ServerName")
eq(game.AccountName, "testaccount", "game.AccountName")
eq(game.CharacterId, harness.player, "game.CharacterId")
check(type(game.LastTick) == "number", "game.LastTick")
check(game.World ~= nil and game.Character ~= nil and game.Actions ~= nil and game.ActionQueue ~= nil, "game's parts")
check(game.OnTick ~= nil and game.OnStateChanged ~= nil and game.OnScriptEnd ~= nil, "game events")
-- capabilities (UB: game.Capabilities.Has(ClientCapability.ImGui))
check(game.Capabilities ~= nil, "game.Capabilities")
check(type(game.Capabilities.Has(ClientCapability.ImGui)) == "boolean", "Capabilities.Has")
check(type(game.Capabilities.Get()) == "number", "Capabilities.Get")
-- a quick look at the world through game
eq(game.Character.Weenie.Name, "Tester", "character name")
eq(game.World.Get(harness.ids.Drudge).Name, "Drudge Skulker", "drudge")
local a = await(game.Actions.ObjectUse(harness.ids.Potion))
check(a.Success, "use a potion: " .. tostring(a.ErrorDetails))
-- script commands
local got
game.RegisterCommand("/testcmd", function(args) got = args end)
check(harness.chatInput("/testcmd hello world"), "a registered command is eaten")
local t = 0
while got == nil and t < 2000 do sleep(20); t = t + 20 end
eq(got, "hello world", "the command got its arguments")
game.UnregisterCommand("/testcmd")
check(not harness.chatInput("/testcmd again"), "unregistered")
-- the script's own name
eq(game.ScriptName, "game", "game.ScriptName")
done()

View file

@ -0,0 +1,64 @@
-- UB-style JSON: the require'd module and the global, the names UB's interpreter ships
-- (parse / serialize / null / isnull) and the rxi-style encode / decode many UB scripts
-- bundle.
local json = require("json")
check(json ~= nil, "require('json')")
check(_G.json ~= nil, "global json")
-- rxi-style round trip
local data = {
name = "Tester",
level = 100,
ratio = 0.25,
alive = true,
tags = { "one", "two", "three" },
nested = { deep = { deeper = { 1, 2, 3 } } },
unicode = "Élan – “quotes” ✓",
}
local text = json.encode(data)
check(type(text) == "string", "encode gives text")
local back = json.decode(text)
eq(back.name, "Tester", "string")
eq(back.level, 100, "integer")
eq(back.ratio, 0.25, "fraction")
eq(back.alive, true, "boolean")
eq(#back.tags, 3, "array length")
eq(back.tags[2], "two", "array order")
eq(back.nested.deep.deeper[3], 3, "nested")
eq(back.unicode, data.unicode, "unicode text survives")
eq(json.encode({}), "[]", "empty table is an array")
eq(json.encode({ 1, 2, 3 }), "[1,2,3]", "array text")
eq(json.encode(12), "12", "whole numbers without .0")
-- UB interpreter's names
local parsed = json.parse('{"a": 1, "b": null, "list": [1, null, 3]}')
eq(parsed.a, 1, "parse")
check(json.isnull(parsed.b), "parse keeps null as json.null()")
check(parsed.b == json.null(), "json.null() is one value")
eq(#parsed.list, 3, "arrays keep their null holes")
check(json.isnull(parsed.list[2]), "null in an array")
check(json.isnull(nil), "isnull(nil)")
check(not json.isnull(0), "isnull(0) is false")
eq(json.serialize({ x = json.null() }), '{"x":null}', "json.null() serializes as null")
eq(tostring(json.null()), "null", "tostring(json.null())")
local dec = json.decode('{"a": null, "b": 2}')
eq(dec.a, nil, "decode turns null into nil")
eq(dec.b, 2, "decode keeps the rest")
-- API values encode sensibly
local sword = game.World.Get(harness.ids.Sword)
eq(json.encode({ item = sword }), '{"item":' .. harness.ids.Sword .. '}', "a WorldObject encodes as its id")
eq(json.encode({ key = StringId.Name }), '{"key":1}', "a typed enum value encodes as its number")
eq(json.encode({ skill = SkillId.WarMagic }), '{"skill":34}', "a numeric enum value is a number")
-- errors say what's wrong
local ok, err = pcall(json.decode, "{not json")
check(not ok and tostring(err):find("not valid JSON") ~= nil, "bad JSON is an error")
local cyc = {}
cyc.self = cyc
local ok2, err2 = pcall(json.encode, cyc)
check(not ok2 and tostring(err2):find("contains itself") ~= nil, "a cycle is an error")
local ok3 = pcall(json.encode, { f = function() end })
check(not ok3, "a function can't be encoded")
done()

View file

@ -0,0 +1,60 @@
-- storage: RynthLua's saved values (UB has no storage module; UB scripts write their own
-- JSON through filesystem, which this also checks against).
local storage = require("storage")
local json = require("json")
local fs = require("filesystem").GetData()
storage.Clear()
eq(#storage.Keys(), 0, "starts empty")
eq(storage.Get("missing"), nil, "missing is nil")
eq(storage.Get("missing", 42), 42, "missing with a default")
storage.Set("count", 3)
storage.Set("name", "Tester")
storage.Set("flags", { a = true, list = { 1, 2, 3 } })
storage.Set("skill", SkillId.WarMagic)
storage.Set("typed", StringId.Name)
eq(storage.Get("count"), 3, "number")
eq(storage.Get("name"), "Tester", "string")
eq(storage.Get("flags").list[3], 3, "table")
eq(storage.Get("skill"), 34, "numeric enum stored as its number")
eq(storage.Get("typed"), 1, "typed enum stored as its number")
check(storage.Has("name"), "Has")
local keys = storage.Keys()
eq(#keys, 5, "Keys")
eq(keys[1], "count", "Keys are sorted")
-- values are copies
local t = storage.Get("flags")
t.a = false
eq(storage.Get("flags").a, true, "Get returns a copy")
check(storage.Remove("count"), "Remove says it was there")
check(not storage.Has("count"), "removed")
storage.Set("name", nil)
check(not storage.Has("name"), "Set(nil) removes")
-- written to the script's data folder as JSON
storage.Save()
local text, err = fs.ReadText("storage.json")
check(text ~= nil, "storage.json written: " .. tostring(err))
if text then
local onDisk = json.decode(text)
eq(onDisk.skill, 34, "on disk")
end
-- per character
storage.Character.Set("seen", true)
eq(storage.Character.Get("seen"), true, "storage.Character")
check(not storage.Has("seen"), "character values are separate")
-- the UB way: a script's own JSON file through filesystem
local ok, werr = fs.WriteText("settings.json", json.encode({ enabled = true, range = 30 }))
check(ok, "WriteText: " .. tostring(werr))
local saved = json.decode((fs.ReadText("settings.json")))
eq(saved.range, 30, "read back")
check(fs.FileExists("settings.json"), "FileExists")
storage.Clear()
eq(#storage.Keys(), 0, "Clear")
done()

View file

@ -0,0 +1,73 @@
-- UB-style timing: sleep(ms) and await(action) as globals, in the main chunk, in handlers
-- and in callbacks; coroutines; plus RynthLua's spawn / waitfor / clock helpers.
-- sleep in the main chunk
local t0 = clock()
sleep(120)
check(clock() - t0 >= 110, "sleep(ms) waits")
sleep(0)
check(true, "sleep(0) returns")
-- await an action in the main chunk and in a callback
local a = await(game.Actions.Sleep(80))
check(a.IsFinished and a.Success, "await returns the finished action")
local inner
game.Actions.Sleep(30, nil, function(res)
inner = await(game.Actions.Sleep(30))
end)
local t = 0
while inner == nil and t < 3000 do sleep(20); t = t + 20 end
check(inner ~= nil and inner.Success, "await inside an action callback")
-- sleep inside an event handler doesn't block other handlers
local order = {}
game.World.OnChatText.Add(function(e)
if e.Message == "slow" then sleep(200) end
order[#order + 1] = e.Message
end)
harness.chat("slow", 0)
harness.chat("fast", 0)
t = 0
while #order < 2 and t < 3000 do sleep(20); t = t + 20 end
eq(order[1], "fast", "a sleeping handler doesn't hold up the next event")
eq(order[2], "slow", "the sleeping handler finishes later")
-- plain Lua coroutines work alongside
local co = coroutine.create(function(x)
local y = coroutine.yield(x + 1)
return y * 2
end)
local ok1, v1 = coroutine.resume(co, 1)
local ok2, v2 = coroutine.resume(co, 10)
check(ok1 and v1 == 2 and ok2 and v2 == 20, "coroutine.create / resume / yield")
local gen = coroutine.wrap(function() for i = 1, 3 do coroutine.yield(i) end end)
eq(gen() + gen() + gen(), 6, "coroutine.wrap")
-- spawn / waitfor
local flag = false
spawn(function(msg)
sleep(50)
flag = (msg == "go")
end, "go")
check(waitfor(function() return flag end, 2000), "spawn + waitfor")
check(not waitfor(function() return false end, 100), "waitfor times out")
-- the action object's Await()
local b = game.Actions.Sleep(40)
b.Await()
check(b.IsFinished, "action.Await()")
-- a long loop doesn't freeze anything (auto-yield), and sleeping in it keeps ticks going
local ticks = 0
game.OnTick.Add(function() ticks = ticks + 1 end)
local sum = 0
for i = 1, 200000 do sum = sum + i end
eq(sum, 200000 * 200001 / 2, "long loop finished")
sleep(100)
check(ticks > 0, "ticks kept coming")
-- os time functions of the sandbox
check(type(os.time()) == "number" and type(os.clock()) == "number", "os.time / os.clock")
check(type(os.date("%Y")) == "string", "os.date")
done()

View file

@ -0,0 +1,167 @@
-- UB-style game.World use: lookups, searches with every filter kind, nearest by 2D/3D,
-- the open container and vendor, and the world events (objects, selection, chat, input).
local ids = harness.ids
local World = game.World
local function waitUntil(fn, ms)
local t = 0
while not fn() and t < (ms or 3000) do sleep(20); t = t + 20 end
return fn()
end
local function names(list)
local set = {}
for _, wo in ipairs(list) do set[wo.Name] = true end
return set
end
-- lookups
eq(World.Get(ids.Drudge).Name, "Drudge Skulker", "Get")
local ok, wo = World.TryGet(ids.Crier)
check(ok and wo.Name == "Town Crier", "TryGet found")
local ok2, wo2 = World.TryGet(0x7FFFFFF0)
check(not ok2 and wo2 == nil, "TryGet missing")
check(World.Exists(ids.PortalObj), "Exists")
check(not World.Exists(0x7FFFFFF1), "Exists missing")
eq(World[ids.Lever].Name, "Tower Lever", "World[id]")
check(World.Selected == nil, "nothing selected")
-- searches
local all = names(World.GetAll())
check(all["Plain Sword"] and all["Drudge Skulker"] and all["Tester"], "GetAll() has pack items, landscape and me")
local monsters = World.GetAll(ObjectClass.Monster)
eq(#monsters, 1, "GetAll(ObjectClass.Monster)")
eq(monsters[1].Name, "Drudge Skulker", "the monster")
local creatures = names(World.GetAll(ObjectType.Creature))
check(creatures["Drudge Skulker"] and creatures["Town Crier"] and creatures["Shopkeeper"] and creatures["Friendly Player"], "GetAll(ObjectType.Creature)")
check(not creatures["Plain Sword"], "GetAll(ObjectType.Creature) has no items")
local cheap = World.GetAll(function(w) return w:Value(IntId.Value) >= 500 end)
local cheapNames = names(cheap)
check(cheapNames["Plain Sword"] and cheapNames["Amethyst"], "GetAll(function)")
local land = names(World.GetLandscape())
check(land["Drudge Skulker"] and land["Chest"], "GetLandscape()")
check(not land["Tester"] and not land["Plain Sword"] and not land["Amethyst"], "GetLandscape() has no me and no pack/chest items")
local portals = World.GetLandscape(ObjectType.Portal)
eq(#portals, 1, "GetLandscape(ObjectType.Portal)")
eq(#World.GetLandscape(ObjectClass.Npc), 1, "GetLandscape(ObjectClass.Npc)")
-- nearest
eq(World.GetNearest(ObjectClass.Monster).Name, "Drudge Skulker", "GetNearest(ObjectClass)")
eq(World.GetNearest(ObjectType.Portal).Name, "Portal to Town", "GetNearest(ObjectType)")
eq(World.GetNearest("Town Crier").Name, "Town Crier", "GetNearest(name)")
local leverOrCrier = function(w) return w.Name == "Tower Lever" or w.Name == "Town Crier" end
eq(World.GetNearest(leverOrCrier).Name, "Town Crier", "GetNearest default is 3D")
eq(World.GetNearest(leverOrCrier, DistanceType.T3D).Name, "Town Crier", "GetNearest T3D")
eq(World.GetNearest(leverOrCrier, DistanceType.T2D).Name, "Tower Lever", "GetNearest T2D ignores height")
-- selection
local selected
World.OnObjectSelected.Add(function(e) selected = e.ObjectId end)
harness.select(ids.Crier)
check(waitUntil(function() return selected == ids.Crier end), "OnObjectSelected.ObjectId")
eq(World.Selected.Id, ids.Crier, "World.Selected")
-- objects created and released
local created, released
World.OnObjectCreated.Add(function(e) created = e.ObjectId end)
World.OnObjectReleased.Add(function(e) released = e.ObjectId end)
local newId = harness.create({ Name = "Olthoi Grub", ItemType = ObjectType.Creature:ToNumber(), Bitfield = 0x10, X = 2 })
check(waitUntil(function() return created == newId end), "OnObjectCreated.ObjectId")
eq(World.Get(newId).Name, "Olthoi Grub", "new object is known")
harness.delete(newId)
check(waitUntil(function() return released == newId end), "OnObjectReleased.ObjectId")
check(World.Get(newId) == nil, "released object is gone")
-- the open container
local opened, closed
World.OnContainerOpened.Add(function(e) opened = e.Container end)
World.OnContainerClosed.Add(function(e) closed = e.Container end)
harness.container(ids.Chest)
check(waitUntil(function() return opened ~= nil end), "OnContainerOpened")
eq(opened and opened.Id, ids.Chest, "OnContainerOpened.Container")
eq(World.OpenContainer.Id, ids.Chest, "World.OpenContainer")
eq(World.OpenContainer.Items[1].Name, "Amethyst", "OpenContainer.Items")
harness.container(nil)
check(waitUntil(function() return closed ~= nil end), "OnContainerClosed")
eq(closed and closed.Id, ids.Chest, "OnContainerClosed.Container")
check(World.OpenContainer == nil, "no open container")
-- the vendor
local vendorOpened, vendorClosed = false, false
World.Vendor.OnOpened.Add(function() vendorOpened = true end)
World.Vendor.OnClosed.Add(function() vendorClosed = true end)
check(not World.Vendor.IsOpen, "Vendor closed")
harness.vendor(ids.Shopkeeper)
check(waitUntil(function() return vendorOpened end), "Vendor.OnOpened")
check(World.Vendor.IsOpen, "Vendor.IsOpen")
eq(World.Vendor.VendorId, ids.Shopkeeper, "Vendor.VendorId")
eq(#World.Vendor.Items, 2, "Vendor.Items")
eq(World.Vendor.Items[1].ObjectId, ids.VendorItemA, "Vendor.Items[1].ObjectId")
eq(World.Vendor.Items[2].Amount, 500, "Vendor.Items[2].Amount")
check(math.abs(World.Vendor.SellPriceModifier - 1.15) < 0.001, "Vendor.SellPriceModifier")
check(World.Vendor.Category:HasFlags(ObjectType.Gem), "Vendor.Category")
harness.vendor(nil)
check(waitUntil(function() return vendorClosed end), "Vendor.OnClosed")
check(not World.Vendor.IsOpen, "Vendor closed again")
-- chat
local lines, tells, locals, channels, fellows, emotes = {}, {}, {}, {}, {}, {}
World.OnChatText.Add(function(e) lines[#lines + 1] = e end)
World.OnTell.Add(function(e) tells[#tells + 1] = e end)
World.OnLocalMessage.Add(function(e) locals[#locals + 1] = e end)
World.OnChannelMessage.Add(function(e) channels[#channels + 1] = e end)
World.OnFellowMessage.Add(function(e) fellows[#fellows + 1] = e end)
World.OnEmote.Add(function(e) emotes[#emotes + 1] = e end)
harness.chat("You have 5 minutes left.", ChatMessageType.System:ToNumber())
harness.chat('<Tell:IIDString:1342177282:Friendly Player>Friendly Player<\\Tell> tells you, "buff me"', ChatMessageType.Tell)
harness.chat('Town Crier says, "Hear ye!"', ChatMessageType.Speech)
harness.chat('[General] Friendly Player says, "WTS sword"', ChatMessageType.Channels)
harness.chat('[Fellowship] Friendly Player says, "pull"', ChatMessageType.Fellowship)
harness.chat('Friendly Player waves.', ChatMessageType.Emote)
check(waitUntil(function() return #lines >= 6 end), "OnChatText saw every line")
local sys = lines[1]
eq(sys.Message, "You have 5 minutes left.", "ChatText.Message")
eq(sys.Type, ChatMessageType.System, "ChatText.Type")
eq(sys.SenderName, "", "no sender gives an empty SenderName")
eq(sys.SenderId, 0, "no sender gives SenderId 0")
eq(sys.Room, ChatChannel.None, "ChatText.Room None")
eq(sys.Eat, false, "ChatText.Eat")
eq(#tells, 1, "OnTell once")
eq(tells[1].SenderName, "Friendly Player", "Tell.SenderName")
eq(tells[1].SenderId, 1342177282, "Tell.SenderId")
eq(tells[1].Message, "buff me", "Tell.Message")
eq(#locals, 1, "OnLocalMessage once")
eq(locals[1].SenderName, "Town Crier", "Local.SenderName")
eq(locals[1].Message, "Hear ye!", "Local.Message")
eq(#channels, 1, "OnChannelMessage once")
eq(channels[1].Room, ChatChannel.General, "Channel.Room")
eq(channels[1].SenderName, "Friendly Player", "Channel.SenderName")
eq(channels[1].Message, "WTS sword", "Channel.Message")
eq(#fellows, 1, "OnFellowMessage once")
eq(fellows[1].Message, "pull", "Fellow.Message")
eq(#emotes, 1, "OnEmote once")
eq(emotes[1].Message, "Friendly Player waves.", "Emote.Message")
-- chat input: UB scripts eat their own commands with e.Eat = true
local inputs = {}
World.OnChatInput.Add(function(e)
inputs[#inputs + 1] = e.Text
if e.Text:sub(1, 4) == "/mm " then e.Eat = true end
end)
local eaten1 = harness.chatInput("/mm hello")
check(waitUntil(function() return #inputs >= 1 end), "OnChatInput fired")
eq(inputs[1], "/mm hello", "OnChatInput.Text")
sleep(50)
local eaten2 = harness.chatInput("/mm again")
check(eaten2, "a command a handler ate once is eaten from then on")
check(waitUntil(function() return #inputs >= 2 end), "OnChatInput fired again")
eq(inputs[2], "/mm again", "second input")
local eaten3 = harness.chatInput("hello everyone")
check(not eaten3, "plain chat is never eaten")
-- World.OnTick
local ticks = 0
World.OnTick.Add(function() ticks = ticks + 1 end)
check(waitUntil(function() return ticks >= 3 end), "World.OnTick")
done()

View file

@ -0,0 +1,143 @@
-- UB-style WorldObject use: typed Value() reads, HasValue, list properties, positions,
-- distances, parents, enum-valued fields and the per-object events.
local ids = harness.ids
local sword = game.World.Get(ids.Sword)
check(sword ~= nil, "World.Get(sword)")
eq(sword.Id, ids.Sword, "Id")
eq(sword.Name, "Plain Sword", "Name")
eq(sword.WeenieClassId, 351, "WeenieClassId")
check(sword.ObjectClass == ObjectClass.MeleeWeapon, "ObjectClass == ObjectClass.MeleeWeapon")
check(sword.ObjectType == ObjectType.MeleeWeapon, "ObjectType == ObjectType.MeleeWeapon")
check(sword.ObjectType:HasFlags(ObjectType.MeleeWeapon), "ObjectType:HasFlags")
-- Value(key [, default]) picks the property kind from the key's enum
eq(sword:Value(IntId.Value), 500, "Value(IntId.Value)")
eq(sword:Value(StringId.Name), "Plain Sword", "Value(StringId.Name)")
eq(sword:Value(StringId.LongDesc), "A plain sword.", "Value(StringId.LongDesc)")
eq(sword:Value(FloatId.WeaponLength), 1.25, "Value(FloatId.WeaponLength)")
eq(sword:Value(BoolId.Inscribable), true, "Value(BoolId.Inscribable)")
eq(sword:Value(DataId.Icon), 0x06001234, "Value(DataId.Icon)")
eq(sword:Value(Int64Id.ItemTotalXp), 0, "Value(Int64Id.ItemTotalXp)")
eq(sword:Value(InstanceId.Container), game.Character.Id, "Value(InstanceId.Container)")
-- API v73: every instance id, not just Container/Wielder
eq(game.Character.Weenie:Value(InstanceId.Monarch), ids.OtherPlayer, "Value(InstanceId.Monarch) on the character")
check(game.Character.Weenie:HasValue(InstanceId.Monarch), "HasValue(InstanceId.Monarch)")
check(not sword:HasValue(InstanceId.Wielder), "an unwielded sword has no Wielder")
eq(sword:Value(InstanceId.PetOwner), 0, "missing instance id defaults to 0")
-- defaults when the object doesn't have the property
eq(sword:Value(IntId.ArmorLevel), 0, "missing int defaults to 0")
eq(sword:Value(IntId.ArmorLevel, 7), 7, "missing int uses the given default")
eq(sword:Value(StringId.Inscription), "", "missing string defaults to empty")
eq(sword:Value(BoolId.Stuck), false, "missing bool defaults to false")
eq(sword:Value(FloatId.DamageMod, 1.5), 1.5, "missing float uses the given default")
-- HasValue
check(sword:HasValue(IntId.Value), "HasValue(IntId.Value)")
check(not sword:HasValue(IntId.ArmorLevel), "not HasValue(IntId.ArmorLevel)")
check(sword:HasValue(StringId.LongDesc), "HasValue(StringId.LongDesc)")
check(not sword:HasValue(FloatId.DamageMod), "not HasValue(FloatId.DamageMod)")
-- the enum-typed fields
eq(sword.ValidWieldedLocations, EquipMask.MeleeWeapon, "ValidWieldedLocations")
eq(sword.Material, MaterialType.Steel, "Material")
eq(sword.Burden, 0, "Burden (none set)")
check(sword.Container ~= nil and sword.Container.Id == game.Character.Id, "Container is the character")
eq(sword.ContainerId, game.Character.Id, "ContainerId")
eq(sword.WielderId, 0, "WielderId")
check(sword:GetTopmostParent().Id == game.Character.Id, "GetTopmostParent of a pack item")
-- a pack in a pack
local stone = game.World.Get(ids.ManaStone)
eq(stone.ContainerId, ids.Backpack, "stone in the backpack")
eq(stone:GetTopmostParent().Id, game.Character.Id, "GetTopmostParent through a side pack")
-- list properties: Items / ItemIds / Containers / ContainerIds / AllItems / Equipment
local me = game.Character.Weenie
local itemNames = {}
for _, wo in ipairs(me.Items) do itemNames[wo.Name] = true end
check(itemNames["Healing Potion"] and itemNames["Plain Sword"], "Weenie.Items has pack items")
check(not itemNames["Backpack"], "Weenie.Items has no containers")
check(not itemNames["Mana Stone"], "Weenie.Items is only the main pack")
eq(#me.ContainerIds, 1, "one side pack")
eq(me.Containers[1].Name, "Backpack", "Containers[1]")
local all = {}
for _, wo in ipairs(me.AllItems) do all[wo.Name] = true end
check(all["Mana Stone"] and all["Prismatic Taper"] and all["Healing Potion"], "AllItems includes side-pack items")
local eqNames = {}
for _, wo in ipairs(me.Equipment) do eqNames[wo.Name] = true end
check(eqNames["Wand of Testing"] and eqNames["Leather Cap"], "Equipment")
eq(#me.EquipmentIds, 2, "EquipmentIds")
local backpack = game.World.Get(ids.Backpack)
eq(#backpack.Items, 2, "backpack.Items")
eq(#backpack.ItemIds, 2, "backpack.ItemIds")
-- the old call form still works
eq(#backpack:Items(), 2, "backpack:Items() still callable")
-- iterating a list with a plain generic for
local n = 0
for wo in backpack.Items do n = n + 1; check(wo.Name ~= nil, "for-in item has a name") end
eq(n, 2, "for wo in list do")
-- equipment slot
local cap = game.World.Get(ids.Cap)
check(cap.CurrentWieldedLocation == EquipMask.Head, "CurrentWieldedLocation == EquipMask.Head")
eq(cap.WielderId, game.Character.Id, "cap WielderId")
eq(cap.Wielder.Id, game.Character.Id, "cap Wielder")
local wand = game.World.Get(ids.Wand)
eq(#wand.SpellIds, 1, "wand SpellIds")
eq(wand.SpellIds[1].Id, 2345, "wand SpellIds[1].Id")
eq(wand.SpellId, 2345, "wand SpellId")
-- positions and distances
local drudge = game.World.Get(ids.Drudge)
local pos = drudge.ServerPosition
check(pos ~= nil, "ServerPosition")
eq(pos.Landcell, 0x7D640013, "ServerPosition.Landcell")
eq(pos.Frame.Origin.X, 110, "Frame.Origin.X")
eq(pos.Frame.Origin.Z, 10, "Frame.Origin.Z")
check(pos.Frame.Orientation ~= nil and pos.Frame.Orientation.W ~= nil, "Frame.Orientation")
local mePos = me.ServerPosition
check(math.abs(mePos:DistanceTo3D(pos) - 10) < 0.01, "Position:DistanceTo3D")
check(math.abs(me:DistanceTo3D(drudge) - 10) < 0.01, "DistanceTo3D(wo)")
check(math.abs(me:DistanceTo3D(ids.Drudge) - 10) < 0.01, "DistanceTo3D(id)")
local portal = game.World.Get(ids.PortalObj)
check(math.abs(me:DistanceTo2D(portal) - 20) < 0.01, "DistanceTo2D(wo) ignores height")
check(math.abs(me:DistanceTo2d(ids.PortalObj) - 20) < 0.01, "DistanceTo2d(id)")
check(math.abs(me:DistanceTo3D(portal) - 36.0555) < 0.01, "DistanceTo3D includes height")
check(sword.ServerPosition == nil, "pack items have no ServerPosition")
check(ObjectDescriptionFlag ~= nil, "ObjectDescriptionFlag enum")
eq(portal.ObjectDescriptionFlag, 0x40000, "ObjectDescriptionFlag (the description bitfield)")
check(PhysicsState ~= nil, "PhysicsState enum")
eq(portal.PhysicsState, 0x0C, "PhysicsState (the last state the server sent)")
eq(sword.PhysicsState, 0, "PhysicsState 0 when none was seen")
-- the player's stats on the weenie, the way UB keeps them
eq(me.Vitals[VitalId.Health].Current, 300, "Weenie.Vitals[VitalId.Health].Current")
eq(me.Vitals[VitalId.Mana].Max, 500, "Weenie.Vitals[VitalId.Mana].Max")
eq(me.Vitals[VitalId.Stamina].Type, VitalId.Stamina, "Vital.Type")
eq(me.Skills[SkillId.MeleeDefense].Current, 400, "Weenie.Skills[...].Current")
eq(me.Skills[SkillId.MeleeDefense].Training, SkillTrainingType.Specialized, "Skill.Training")
eq(me.Skills[SkillId.MeleeDefense].Type, SkillId.MeleeDefense, "Skill.Type")
eq(me.Attributes[AttributeId.Strength].Base, 190, "Weenie.Attributes[...].Base")
eq(me.Attributes[AttributeId.Strength].Type, AttributeId.Strength, "Attribute.Type")
-- tostring and equality
check(tostring(sword):find("Plain Sword") ~= nil, "tostring(wo)")
check(game.World.Get(ids.Sword) == sword, "two wrappers of one object are ==")
-- per-object events: OnPositionChanged and OnDestroyed
local moved, destroyed = nil, false
drudge.OnPositionChanged.Add(function(e) moved = e end)
harness.move(ids.Drudge, 5, 0, 0)
local t = 0
while moved == nil and t < 3000 do sleep(20); t = t + 20 end
check(moved ~= nil, "OnPositionChanged fired")
if moved then
eq(moved.Weenie.Id, ids.Drudge, "OnPositionChanged.Weenie")
eq(moved.Position.Frame.Origin.X, 115, "OnPositionChanged.Position")
end
drudge.OnDestroyed.Add(function(e) destroyed = e.ObjectId == ids.Drudge end)
harness.delete(ids.Drudge)
t = 0
while not destroyed and t < 3000 do sleep(20); t = t + 20 end
check(destroyed, "OnDestroyed fired with ObjectId")
done()