using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using RynthCore.PluginSdk; namespace RynthCore.RynthAiHostTests.Fakes; /// /// An in-process stand-in for the engine. The real RynthCoreHost is a struct of native function /// pointers; here each pointer is an [UnmanagedCallersOnly] static method that answers from the /// static state below, so tested code gets the answers a test sets up and nothing reaches a game. /// /// Deliberately NOT faked: /// * GetPlayerId, unless a test asks for it with Create(playerId): ExpressionEngine's getgame* /// functions read raw client memory (0x008379A8) once GetPlayerId returns non-zero, which /// would crash this process. With no GetPlayerId they return the calendar for a zero clock, /// which the tests pin. Buff tests (no expressions) use the opt-in. /// * GetContainerContents: WorldObjectCache then builds its inventory from objects it already /// knows (see ). /// * Most action calls (combat mode, ...) stay no-ops. The nav, buff and weapon calls are /// recorded: SetAutoRun, TurnToHeading (the fake turns instantly), JumpNonAutonomous, /// CastSpell, UseObject and RequestId. /// /// State is static because function pointers cannot capture; call first. /// internal static unsafe class FakeHost { // ── State a test sets up ────────────────────────────────────────────────── public static readonly Dictionary Names = new(); public static readonly Dictionary Positions = new(); public static readonly Dictionary ItemTypes = new(); public static readonly Dictionary<(uint Id, uint Key), int> Ints = new(); public static readonly Dictionary<(uint Id, uint Key), double> Doubles = new(); public static readonly Dictionary<(uint Id, uint Key), long> Quads = new(); public static readonly Dictionary<(uint Id, uint Key), bool> Bools = new(); public static readonly Dictionary<(uint Id, uint Key), string> Strings = new(); public static readonly Dictionary<(uint Id, uint Skill), (int Buffed, int Training)> Skills = new(); public static readonly Dictionary<(uint Id, uint Skill, int Raw), int> SkillLevels = new(); public static readonly Dictionary<(uint Id, uint Attr, int Raw), uint> Attributes = new(); public static readonly Dictionary SpellIds = new(); /// Data id properties (STypeDID): (object, key) -> value, e.g. a scroll's Spell 28. public static readonly Dictionary<(uint Id, uint Key), uint> DataIds = new(); /// Instance id properties (STypeIID): (object, key) -> object id, e.g. a pet's PetOwner 44. /// When it has entries at Create() time the host also gets GetObjectInstanceIdProperty (opt-in). public static readonly Dictionary<(uint Id, uint Key), uint> InstanceIds = new(); public static readonly Dictionary Palettes = new(); public static readonly HashSet KnownSpells = new(); public static readonly HashSet NotAttackable = new(); public static readonly List<(uint SpellId, double Expiry)> Enchantments = new(); /// Item id -> container id. When it has entries at Create() time the host also gets /// GetObjectOwnershipInfo (opt-in, so tests written without it see no ownership, as before). public static readonly Dictionary Containers = new(); /// Extra ids GetContainerContents lists for a container without them being in it (the /// client lists what the player wields in the player's own contents; ownership says no container). public static readonly Dictionary> ContentsExtra = new(); /// Opt-in (set before Create): v87 GetWieldedItems answering (the /// engine's EquipmentTracker: item -> EquipMask). answers -1. public static bool EquippedCalls; public static bool EquippedNotReady; public static readonly Dictionary Equipped = new(); /// Item id -> the creature wielding it (GetObjectOwnershipInfo's wielder). Entries here /// also install GetObjectOwnershipInfo; an id in neither map reads as unknown ownership. public static readonly Dictionary Wielders = new(); /// Object id -> PublicWeenieDesc bitfield (0x2000 corpse, 0x8 player, ...). When it has /// entries at Create() time the host also gets GetObjectBitfield (opt-in, as Containers). public static readonly Dictionary Bitfields = new(); /// The api struct the last Create() built (a test attaching a plugin needs it). public static RynthCoreApiNative LastApi; public static double ServerTime; public static float Vitae = 1.0f; public static bool Portaling; public static (uint Cell, float X, float Y, float Z) PlayerPose; public static bool HasPose = true; public static (uint Hp, uint MaxHp, uint Stam, uint MaxStam, uint Mana, uint MaxMana) Vitals; public static (uint Hp, uint Stam, uint Mana) BaseVitals; public static string WorldName = ""; public static string AccountName = ""; /// A test's extra engine calls (e.g. FakeServerState), set into the table last by Create; Reset clears it. public delegate void ApiHook(ref RynthCoreApiNative api); public static ApiHook? ConfigureApi; /// The player's facing, 0 = north, clockwise (read back through the pose quaternion). public static double HeadingDeg; public static readonly Dictionary Wcids = new(); /// The character's spellbook as ReadKnownSpells returns it (empty = snapshot cold). public static readonly List Spellbook = new(); /// Only used when Create(playerId: ...) installs GetPlayerId (see the class note). public static uint PlayerIdValue; // ── What tested code sent to the engine ─────────────────────────────────── public static readonly List Logs = new(); public static readonly List Chat = new(); public static readonly List ChatCommands = new(); /// Every SetAutoRun call, in order; AutoRun is the last value sent. public static readonly List AutoRunCalls = new(); public static bool AutoRun; public static int Jumps; /// Runs inside CastSpell, after the cast is recorded (a UseDone that lands during the send). public static Action? AfterCastSpell; /// Opt-in: wires TapJump (the keyboard jump, 0xF61B); calls land in . public static bool TapJumpCalls; public static int TapJumps; /// TapJump returns 0 (the client refused the jump); the call still counts in TapJumps. public static bool TapJumpRefuse; public static int Turns; public static readonly List<(uint Target, int SpellId)> Casts = new(); /// True: CastSpell returns false (the client refused it; nothing is recorded in ). public static bool CastRefused; /// CastSpell calls refused while was set. public static int CastsRefused; /// Opt-in: wires GiveObjectTo (AC's give action); every call lands in . public static bool GiveCalls; /// Every GiveObjectTo (item, target, amount; 0 = the whole object), in order. public static readonly List<(uint Item, uint Target, int Amount)> Gives = new(); /// When true (the default) a give lands at once, as the server does when it isn't busy: /// the item goes to the target. False = the server hasn't taken it (still carried). public static bool GiveLands = true; /// Optional: runs for every give instead of the default landing (a test's own server: NPC takes one per give, busy, ...). public static Action? GiveHandler; /// Opt-in: wires StopCompletely (off by default so no other test sees it). public static bool StopCalls; /// StopCompletely calls (opt-in with ). public static int Stops; /// Opt-in: wires MeleeAttack and MissileAttack; calls land in . public static bool AttackSendCalls; /// Every melee or missile attack (kind, target, height, power), in order (opt-in with ). public static readonly List<(string Kind, uint Target, int Height, float Power)> AttackCalls = new(); /// Opt-in: wires SetMotion; calls land in . public static bool SetMotionCalls; /// Every SetMotion (motion, on), in order (opt-in with ). public static readonly List<(uint Motion, bool On)> MotionCalls = new(); /// Movement and cast calls in the order they reached the engine ("autorun on/off", "stop", /// "motion 0x.. on/off", "cast N"). public static readonly List Sent = new(); /// Every UseObject (a wield, a use) and RequestId (an identify), in order. public static readonly List Uses = new(); public static readonly List IdRequests = new(); /// Opt-in (set before Create): QueryHealth (counted in ) and GetLastIdTime (answering , 0 = never). public static bool TargetCalls; public static readonly List HealthQueries = new(); public static readonly Dictionary IdTimes = new(); /// Every MoveItemInternal (an item into a pack), in order (opt-in with ). public static readonly List<(uint Id, uint Pack, int Amount)> Moves = new(); /// Objects the fake says have appraisal data (HasAppraisalData). public static readonly HashSet Appraised = new(); /// False = RequestId refuses (as the engine does around a teleport or a death): returns 0 /// and is counted in , not in . public static bool RequestIdAccepts = true; public static int RefusedIdRequests; /// False = UseObject returns 0 (the engine did not send it); the use is still recorded in . public static bool UseObjectAccepts = true; /// Opt-in (set before Create): UseObject, RequestId, HasAppraisalData and /// GetCurrentCombatMode (answering ). Tests written without /// them keep seeing those calls as absent. public static bool WeaponCalls; /// Opt-in GetContainerContents answering from (item -> container), /// in insertion order. Off by default: see the class note. public static bool ContentsCalls; /// The engine's VTank signal (API v74 GetVTankState flags: 1 = watching, 2 = running); /// -1 = not installed (an engine before v74). Opt-in: set before Create(). public static int VTankFlags = -1; /// Opt-in (set before Create): the server gates combat paces casts on, GetUseDoneSeq /// (answering ) and GetCastBusyState (answering ). public static bool ServerGates; /// The count of server UseDone (0x01C7) events the fake reports. public static int UseDoneSeq; /// The error code of the last UseDone (GetLastUseDone, v70; 0 = completed, 0x1D = too busy). /// Opt-in with (set before Create, together with ServerGates). public static uint LastUseDoneError; public static bool LastUseDoneCalls; /// One more UseDone with (0 = the action completed). public static void UseDone(uint error) { UseDoneSeq++; LastUseDoneError = error; } /// 1 while a cast gesture animates (GetCastBusyState), else 0. public static int CastBusy; /// Opt-in (set before Create): GetLastWeenieError, answering the fields below. public static bool WeenieErrorCalls; public static int WeenieErrSeq; public static uint WeenieErrCode, WeenieErrEvent, WeenieErrObject; /// The server refused something: 0x028A WeenieError, or 0x00A0 InventoryServerSaveFailed (obj = the item). public static void WeenieError(uint code, uint evt = 0x028A, uint obj = 0) { WeenieErrSeq++; WeenieErrCode = code; WeenieErrEvent = evt; WeenieErrObject = obj; } public static int VTankSeq; public static int CombatModeValue = 1; /// Opt-in (set before Create): ChangeCombatMode, recorded in . public static bool CombatModeCalls; public static readonly List CombatModeRequests = new(); /// True: ChangeCombatMode returns 0 (the engine refused, e.g. around a teleport) and records nothing in . public static bool CombatModeRefuse; /// ChangeCombatMode calls refused while was set. public static int CombatModeRefusals; /// Opt-in (set before Create): WieldItem (a wield into a named slot, API v70+). The /// host then reports API version 73, so only tests that ask for it see the newer calls. public static bool WieldCalls; /// Opt-in (set before Create): v80 PutItemInContainer (the raw move packet), recorded in . public static bool PutCalls; /// Every PutItemInContainer (item, container, placement), in order (opt-in with ). public static readonly List<(uint Id, uint Container, int Placement)> Puts = new(); /// Every WieldItem (item, EquipMask slot), in order (opt-in with ). public static readonly List<(uint Id, uint Mask)> Wields = new(); /// Opt-in (set before Create): UseObject, MoveItemExternal, the salvage panel /// (open / add / execute) and GetObjectWielderInfo (answering from ). public static bool SalvageCalls; /// Every MoveItemExternal (item, target container, amount), in order (opt-in with ). public static readonly List<(uint Id, uint Target, int Amount)> ExternalMoves = new(); /// Every SalvagePanelAddItem, in order. public static readonly List SalvageAdds = new(); /// The items added since the last execute, each SalvagePanelExecute, in order. public static readonly List> SalvageExecutes = new(); /// Items SalvagePanelAddItem turns down (the panel refuses them). public static readonly HashSet RefuseSalvageAdd = new(); /// Called on SalvagePanelExecute with what was added since the last one (the test /// removes the salvaged items from its world here). public static Action>? OnSalvageExecute; /// Item id -> wielded location: GetObjectWielderInfo says the player wields it there. public static readonly Dictionary Wielded = new(); /// Opt-in (set before Create): SalvageDirect (API v82, salvage without the panel). public static bool SalvageDirectCalls; /// Every SalvageDirect (UST, ids), in order (opt-in with ). public static readonly List<(uint Tool, List Ids)> SalvageDirects = new(); /// What SalvageDirect answers; null = the count of ids (sent). -1 = sender not bound. public static int? SalvageDirectAnswer; /// Called on a sent SalvageDirect with (UST, ids) (the test plays the server here). public static Action>? OnSalvageDirect; private static readonly List _panelItems = new(); /// Opt-in (set before Create): CloseContainer (API v76; the host then reports at /// least v76) and GetGroundContainerId (answering ). public static bool CloseContainerCalls; /// Every CloseContainer (container id), in order (opt-in with ). public static readonly List Closes = new(); /// The container the client has open (GetGroundContainerId), 0 = none. public static uint GroundContainer; /// The item selected in the game (GetSelectedItemId); 0 = none. public static uint SelectedItem; /// Opt-in (set before Create): UseObjectOn (an item used on another, e.g. a spirit on a /// pet essence); every call lands in . public static bool UseOnCalls; /// Every UseObjectOn (source, target), in order (opt-in with ). public static readonly List<(uint Source, uint Target)> UsesOn = new(); /// Opt-in (set before Create): the trade window and vendor calls (API v72 / v67). A vendor named /// (id 0x70000001) is open; every trade action and vendor transaction is recorded. public static bool TradeVendorCalls; public static string VendorName = "Town Vendor"; /// Trade actions in order: "accept", "decline", "reset", "close", "add:". public static readonly List TradeActions = new(); /// Every VendorSell: the vendor id and the item ids. public static readonly List<(uint Vendor, uint[] Items)> VendorSells = new(); /// Every VendorBuy: the vendor id and the (object, amount) entries. public static readonly List<(uint Vendor, (uint Id, int Amount)[] Entries)> VendorBuys = new(); /// Opt-in: install SendPluginCommand (the engine's plugin-command broker, API v64). public static bool PluginCommandCalls; /// What SendPluginCommand answers: true = delivered (the target plugin is loaded). public static bool PluginCommandDelivered = true; /// Every SendPluginCommand (plugin, action, value), in order. public static readonly List<(string Plugin, string Action, string Value)> PluginCommands = new(); /// Opt-in (set before Create): ForceResetBusyCount (counted in ) /// and GetBusyState (answering ). public static bool BusyCalls; public static int ForceResets; public static int BusyStateValue; /// Opt-in (set before Create): GetObjectProperties (API v84), answering the record /// returns for an id (null = the engine knows nothing: 0). public static bool ObjectPropertiesCalls; public static Func? PropertyRecord; /// GetObjectProperties calls, in order (the buffer-size retries included). public static readonly List PropertyQueries = new(); /// Object id -> CPhysicsObj m_state (GetObjectState; 0x4 ETHEREAL = a door that is open). /// When it has entries at Create() time the host also gets GetObjectState (opt-in, as Bitfields). public static readonly Dictionary ObjectStates = new(); /// Runs inside UseObject, after the use is recorded (the test plays the server here). public static Action? OnUseObject; /// Runs inside UseObjectOn, after it is recorded. public static Action? OnUseObjectOn; /// Object id -> (health, max health) for GetTargetVitals (opt-in: installed when it has entries at Create()). public static readonly Dictionary TargetVitals = new(); /// Opt-in (set before Create): GetLiveObjectIds (API v69) lists every id in . public static bool LiveObjectsCalls; // ANSI strings handed back to tested code stay alive for the whole run. private static readonly Dictionary _ansi = new(); /// Opt-in: install the Nav3D calls (clear, ring, line, triangle) and record them. public static bool Nav3DCalls; public static readonly List<(float X, float Y, float Z, float Radius, uint Color)> Nav3DRings = new(); public static readonly List<(float X1, float Y1, float Z1, float X2, float Y2, float Z2, float Thick, uint Color)> Nav3DLines = new(); public static readonly List<(float X1, float Y1, float Z1, float X2, float Y2, float Z2, float X3, float Y3, float Z3, uint Color)> Nav3DTriangles = new(); public static void Reset() { EquippedCalls = false; EquippedNotReady = false; Equipped.Clear(); #if !RYNTHILT_TESTS RynthCore.Plugin.RynthAi.EquippedState.Invalidate(); #endif Nav3DCalls = false; Nav3DRings.Clear(); Nav3DLines.Clear(); Nav3DTriangles.Clear(); Names.Clear(); Positions.Clear(); ItemTypes.Clear(); Ints.Clear(); Doubles.Clear(); Quads.Clear(); Bools.Clear(); Strings.Clear(); Skills.Clear(); SkillLevels.Clear(); Attributes.Clear(); SpellIds.Clear(); DataIds.Clear(); InstanceIds.Clear(); Palettes.Clear(); KnownSpells.Clear(); NotAttackable.Clear(); Enchantments.Clear(); Containers.Clear(); ContentsExtra.Clear(); Wielders.Clear(); Bitfields.Clear(); ServerTime = 0; Vitae = 1.0f; Portaling = false; PlayerPose = default; HasPose = true; Vitals = default; BaseVitals = default; WorldName = ""; AccountName = ""; HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0; Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); AfterCastSpell = null; AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null; Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; ContentsCalls = false; CombatModeValue = 1; RequestIdAccepts = true; RefusedIdRequests = 0; UseObjectAccepts = true; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; ServerGates = false; UseDoneSeq = 0; CastBusy = 0; LastUseDoneError = 0; LastUseDoneCalls = false; WeenieErrorCalls = false; WeenieErrSeq = 0; WeenieErrCode = WeenieErrEvent = WeenieErrObject = 0; #if !RYNTHILT_TESTS // Spell mana costs "unknown" (no reserve beyond Get Mana At, no cost gate), so a portal.dat on // the PC doesn't change results; the mana reserve tests set their own costs. RynthCore.Plugin.RynthAi.BuffManager.ManaCostOverride = _ => 0; #endif WieldCalls = false; Wields.Clear(); PutCalls = false; Puts.Clear(); SalvageCalls = false; ExternalMoves.Clear(); SalvageAdds.Clear(); SalvageExecutes.Clear(); RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear(); SalvageDirectCalls = false; SalvageDirects.Clear(); SalvageDirectAnswer = null; OnSalvageDirect = null; CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0; SelectedItem = 0; UseOnCalls = false; UsesOn.Clear(); PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear(); TradeVendorCalls = false; TradeActions.Clear(); VendorSells.Clear(); VendorBuys.Clear(); CombatModeCalls = false; CombatModeRequests.Clear(); CombatModeRefuse = false; CombatModeRefusals = 0; BusyCalls = false; ForceResets = 0; BusyStateValue = 0; ObjectPropertiesCalls = false; PropertyRecord = null; PropertyQueries.Clear(); ObjectStates.Clear(); OnUseObject = null; OnUseObjectOn = null; TargetVitals.Clear(); LiveObjectsCalls = false; ConfigureApi = null; } /// /// Puts the player at nav coordinates (ns, ew) on the landscape: the landblock cell and /// local x/y that NavCoordinateHelper converts back to the same coordinates. /// public static void SetNavPosition(double ns, double ew, float z = 0f) { PlayerPose = (NavCell(ns, ew, out float x, out float y), x, y, z); } /// The outdoor cell id holding (ns, ew), and the local x/y in it. public static uint NavCell(double ns, double ew, out float x, out float y) { double gx = (ew * 10.0 + 1019.5) * 24.0, gy = (ns * 10.0 + 1019.5) * 24.0; uint lbX = (uint)(gx / 192.0), lbY = (uint)(gy / 192.0); x = (float)(gx - lbX * 192.0); y = (float)(gy - lbY * 192.0); uint cell = (uint)(x / 24f) * 8 + (uint)(y / 24f) + 1; // outdoor cells 0x0001-0x0040 return (lbX << 24) | (lbY << 16) | cell; } /// /// A host whose faked calls answer from the state above. non-zero /// also installs GetPlayerId; never do that for a test that runs expressions (see the class note). /// public static RynthCoreHost Create(uint playerId = 0) { var api = new RynthCoreApiNative { Version = RynthCoreHost.CurrentApiVersion }; PlayerIdValue = playerId; if (playerId != 0) api.GetPlayerIdFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetPlayerId; if (Containers.Count > 0 || Wielders.Count > 0) api.GetObjectOwnershipInfoFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectOwnershipInfo; if (EquippedCalls) api.GetWieldedItemsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetWieldedItems; if (ContentsCalls) api.GetContainerContentsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetContainerContents; if (Bitfields.Count > 0) api.GetObjectBitfieldFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectBitfield; if (ObjectStates.Count > 0) api.GetObjectStateFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectState; if (InstanceIds.Count > 0) api.GetObjectInstanceIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectInstanceIdProperty; api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl])&SetAutoRun; api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl])&TurnToHeading; api.GetPlayerHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetPlayerHeading; api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl])&JumpNonAutonomous; if (TapJumpCalls) api.TapJumpFn = (IntPtr)(delegate* unmanaged[Cdecl])&TapJump; api.CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl])&CastSpell; if (StopCalls) api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl])&StopCompletely; if (SetMotionCalls) api.SetMotionFn = (IntPtr)(delegate* unmanaged[Cdecl])&SetMotion; if (AttackSendCalls) { api.MeleeAttackFn = (IntPtr)(delegate* unmanaged[Cdecl])&MeleeAttack; api.MissileAttackFn = (IntPtr)(delegate* unmanaged[Cdecl])&MissileAttack; } if (Nav3DCalls) { api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DClear; api.Nav3DAddRingFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DAddRing; api.Nav3DAddLineFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DAddLine; api.Nav3DAddTriangleFn = (IntPtr)(delegate* unmanaged[Cdecl])&Nav3DAddTriangle; } if (GiveCalls) api.GiveObjectToFn = (IntPtr)(delegate* unmanaged[Cdecl])&GiveObjectTo; if (WeaponCalls) { api.UseObjectFn = (IntPtr)(delegate* unmanaged[Cdecl])&UseObject; api.RequestIdFn = (IntPtr)(delegate* unmanaged[Cdecl])&RequestId; api.HasAppraisalDataFn = (IntPtr)(delegate* unmanaged[Cdecl])&HasAppraisalData; api.GetCurrentCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetCurrentCombatMode; api.MoveItemInternalFn = (IntPtr)(delegate* unmanaged[Cdecl])&MoveItemInternal; } if (TargetCalls) { api.QueryHealthFn = (IntPtr)(delegate* unmanaged[Cdecl])&QueryHealth; api.GetLastIdTimeFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetLastIdTime; } if (SalvageCalls) { api.UseObjectFn = (IntPtr)(delegate* unmanaged[Cdecl])&UseObject; api.MoveItemExternalFn = (IntPtr)(delegate* unmanaged[Cdecl])&MoveItemExternal; api.SalvagePanelOpenFn = (IntPtr)(delegate* unmanaged[Cdecl])&SalvagePanelOpen; api.SalvagePanelAddItemFn = (IntPtr)(delegate* unmanaged[Cdecl])&SalvagePanelAddItem; api.SalvagePanelExecuteFn = (IntPtr)(delegate* unmanaged[Cdecl])&SalvagePanelExecute; api.GetObjectWielderInfoFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectWielderInfo; } if (SalvageDirectCalls) { api.Version = Math.Max(api.Version, 82u); api.SalvageDirectFn = (IntPtr)(delegate* unmanaged[Cdecl])&SalvageDirect; } if (CombatModeCalls) api.ChangeCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl])&ChangeCombatMode; if (TargetVitals.Count > 0) api.GetTargetVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetTargetVitals; if (LiveObjectsCalls) { api.Version = Math.Max(api.Version, 69u); api.GetLiveObjectIdsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetLiveObjectIds; } if (BusyCalls) { api.ForceResetBusyCountFn = (IntPtr)(delegate* unmanaged[Cdecl])&ForceResetBusyCount; api.GetBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetBusyState; } if (UseOnCalls) api.UseObjectOnFn = (IntPtr)(delegate* unmanaged[Cdecl])&UseObjectOn; if (TradeVendorCalls) { api.Version = Math.Max(api.Version, 82u); api.GetVendorInfoFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetVendorInfo; api.GetVendorItemsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetVendorItems; api.VendorBuyFn = (IntPtr)(delegate* unmanaged[Cdecl])&VendorBuy; api.VendorSellFn = (IntPtr)(delegate* unmanaged[Cdecl])&VendorSell; api.GetVendorTradeStatusFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetVendorTradeStatus; api.GetTradeStateFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetTradeState; api.GetTradeItemsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetTradeItems; api.TradeOpenFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeOpen; api.TradeAddFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeAdd; api.TradeAcceptFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeAccept; api.TradeDeclineFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeDecline; api.TradeResetFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeReset; api.TradeCloseFn = (IntPtr)(delegate* unmanaged[Cdecl])&TradeClose; } if (WieldCalls) { api.Version = 73; api.WieldItemFn = (IntPtr)(delegate* unmanaged[Cdecl])&WieldItem; } if (PutCalls) { api.Version = Math.Max(api.Version, 80u); api.PutItemInContainerFn = (IntPtr)(delegate* unmanaged[Cdecl])&PutItemInContainer; } api.GetObjectWcidFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectWcid; api.GetSelectedItemIdFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetSelectedItemId; api.ReadKnownSpellsFn = (IntPtr)(delegate* unmanaged[Cdecl])&ReadKnownSpells; api.LogFn = (IntPtr)(delegate* unmanaged[Cdecl])&Log; api.WriteToChatFn = (IntPtr)(delegate* unmanaged[Cdecl])&WriteToChat; api.InvokeChatParserFn = (IntPtr)(delegate* unmanaged[Cdecl])&InvokeChatParser; api.GetObjectNameFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectName; api.GetObjectPositionFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectPosition; api.GetItemTypeFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetItemType; api.ObjectIsAttackableFn = (IntPtr)(delegate* unmanaged[Cdecl])&ObjectIsAttackable; api.GetObjectIntPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectIntProperty; api.GetObjectDoublePropertyFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectDoubleProperty; api.GetObjectQuadPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectQuadProperty; api.GetObjectBoolPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectBoolProperty; api.GetObjectStringPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectStringProperty; api.GetObjectSkillFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectSkill; api.GetObjectSkillBuffedFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectSkillLevel; api.GetObjectAttributeFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectAttribute; api.GetObjectSpellIdsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectSpellIds; api.GetObjectDataIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectDataIdProperty; api.GetObjectPalettesFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectPalettes; api.IsSpellKnownFn = (IntPtr)(delegate* unmanaged[Cdecl])&IsSpellKnown; api.ReadPlayerEnchantmentsFn = (IntPtr)(delegate* unmanaged[Cdecl])&ReadPlayerEnchantments; api.GetServerTimeFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetServerTime; api.GetVitaeFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetVitae; api.IsPortalingFn = (IntPtr)(delegate* unmanaged[Cdecl])&IsPortaling; api.GetPlayerPoseFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetPlayerPose; api.GetPlayerVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetPlayerVitals; api.GetPlayerBaseVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetPlayerBaseVitals; api.GetWorldNameFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetWorldName; api.GetAccountNameFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetAccountName; if (ServerGates) { api.GetUseDoneSeqFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetUseDoneSeq; api.GetCastBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetCastBusyState; if (LastUseDoneCalls) api.GetLastUseDoneFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetLastUseDone; } if (WeenieErrorCalls) api.GetLastWeenieErrorFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetLastWeenieError; if (VTankFlags >= 0) { api.Version = Math.Max(api.Version, 74u); api.GetVTankStateFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetVTankState; } if (CloseContainerCalls) { api.Version = Math.Max(api.Version, 76u); api.CloseContainerFn = (IntPtr)(delegate* unmanaged[Cdecl])&CloseContainer; api.GetGroundContainerIdFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetGroundContainerId; } if (PluginCommandCalls) { api.Version = Math.Max(api.Version, 64u); api.SendPluginCommandFn = (IntPtr)(delegate* unmanaged[Cdecl])&SendPluginCommand; } if (ObjectPropertiesCalls) { api.Version = Math.Max(api.Version, 84u); api.GetObjectPropertiesFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectProperties; } ConfigureApi?.Invoke(ref api); LastApi = api; if (EquippedCalls) api.Version = Math.Max(api.Version, 87u); // v87 GetWieldedItems return new RynthCoreHost(api); } #if !RYNTHILT_TESTS /// /// A WorldObjectCache that knows the given objects: each id must have a name in /// . Ids with a entry land on the landscape /// (a creature when has the creature flag 0x10), the rest in the /// inventory. Health ratios make creatures count as alive for the meta monster conditions. /// public static RynthCore.Plugin.RynthAi.WorldObjectCache MakeCache(RynthCoreHost host, uint playerId, IEnumerable ids, IReadOnlyDictionary? health = null) { var cache = new RynthCore.Plugin.RynthAi.WorldObjectCache(host); cache.SetPlayerId(playerId); foreach (uint id in ids) { _ = cache[unchecked((int)id)]; // the indexer's lazy lookup classifies and files it if (health != null && health.TryGetValue(id, out float hr)) cache.OnUpdateHealth(id, hr); } return cache; } #endif private static IntPtr Ansi(string s) { if (!_ansi.TryGetValue(s, out IntPtr p)) _ansi[s] = p = Marshal.StringToHGlobalAnsi(s); return p; } // ── The fakes ───────────────────────────────────────────────────────────── /// /// Microseconds each Log call costs, spun on the calling thread (0 = free). The engine's real /// log sink opens, appends to and closes the log file for every line, on the caller's thread: /// about 350 us a line measured on the PC the clients run on (2026-10-02), so the flood /// benchmark sets this to make plugin log volume cost what it costs in game. /// public static int LogCostMicros; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static void Log(IntPtr msg) { Logs.Add(Marshal.PtrToStringAnsi(msg) ?? ""); if (LogCostMicros > 0) { long until = System.Diagnostics.Stopwatch.GetTimestamp() + LogCostMicros * System.Diagnostics.Stopwatch.Frequency / 1_000_000; while (System.Diagnostics.Stopwatch.GetTimestamp() < until) { } } } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetUseDoneSeq() => UseDoneSeq; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetCastBusyState() => CastBusy; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetLastWeenieError(int* seq, uint* error, uint* eventType, uint* objectId) { *seq = WeenieErrSeq; *error = WeenieErrCode; *eventType = WeenieErrEvent; *objectId = WeenieErrObject; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetLastUseDone(int* seq, uint* error) { *seq = UseDoneSeq; *error = UseDoneSeq == 0 ? 0 : LastUseDoneError; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int WriteToChat(IntPtr text, int type) { Chat.Add(Marshal.PtrToStringUni(text) ?? ""); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int SendPluginCommand(IntPtr plugin, IntPtr action, IntPtr value) { PluginCommands.Add((Marshal.PtrToStringAnsi(plugin) ?? "", Marshal.PtrToStringAnsi(action) ?? "", Marshal.PtrToStringAnsi(value) ?? "")); return PluginCommandDelivered ? 1 : 0; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int InvokeChatParser(IntPtr text) { ChatCommands.Add(Marshal.PtrToStringUni(text) ?? ""); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static IntPtr GetObjectName(uint id) => Names.TryGetValue(id, out string? n) ? Ansi(n) : IntPtr.Zero; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectPosition(uint id, uint* cell, float* x, float* y, float* z) { if (!Positions.TryGetValue(id, out var p)) return 0; *cell = p.Cell; *x = p.X; *y = p.Y; *z = p.Z; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetItemType(uint id, uint* flags) { if (!ItemTypes.TryGetValue(id, out uint f)) return 0; *flags = f; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectOwnershipInfo(uint id, uint* container, uint* wielder, uint* location) { bool inPack = Containers.TryGetValue(id, out uint c); bool worn = Wielders.TryGetValue(id, out uint w); if (!inPack && !worn) return 0; *container = c; *wielder = w; *location = 0; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetWieldedItems(uint* ids, uint* locations, int max) { if (EquippedNotReady) return -1; int n = 0; foreach (var kv in Equipped) { if (n >= max) break; ids[n] = kv.Key; locations[n] = kv.Value; n++; } return n; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetContainerContents(uint container, uint* output, int max) { int n = 0; foreach (var kv in Containers) if (kv.Value == container && n < max) output[n++] = kv.Key; if (ContentsExtra.TryGetValue(container, out var extra)) foreach (uint id in extra) if (n < max) output[n++] = id; return n; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static uint GetObjectBitfield(uint id) => Bitfields.TryGetValue(id, out uint b) ? b : 0u; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int MoveItemInternal(uint id, uint pack, int slot, int amount) { Moves.Add((id, pack, amount)); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int ObjectIsAttackable(uint id) => NotAttackable.Contains(id) ? 0 : 1; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetTargetVitals(uint id, uint* hp, uint* maxHp, uint* stam, uint* maxStam, uint* mana, uint* maxMana) { if (!TargetVitals.TryGetValue(id, out var v)) return 0; *hp = v.Hp; *maxHp = v.MaxHp; *stam = 0; *maxStam = 0; *mana = 0; *maxMana = 0; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetLiveObjectIds(uint* buffer, int capacity) { int n = 0; foreach (uint id in Names.Keys) { if (n < capacity) buffer[n] = id; n++; } return n; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectIntProperty(uint id, uint key, int* v) { if (!Ints.TryGetValue((id, key), out int x)) return 0; *v = x; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectDoubleProperty(uint id, uint key, double* v) { if (!Doubles.TryGetValue((id, key), out double x)) return 0; *v = x; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectQuadProperty(uint id, uint key, long* v) { if (!Quads.TryGetValue((id, key), out long x)) return 0; *v = x; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectBoolProperty(uint id, uint key, int* v) { if (!Bools.TryGetValue((id, key), out bool x)) return 0; *v = x ? 1 : 0; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static IntPtr GetObjectStringProperty(uint id, uint key) => Strings.TryGetValue((id, key), out string? s) ? Ansi(s) : IntPtr.Zero; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectSkill(uint id, uint skill, int* buffed, int* training) { if (!Skills.TryGetValue((id, skill), out var s)) return 0; *buffed = s.Buffed; *training = s.Training; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectSkillLevel(uint id, uint skill, int raw, int* level) { if (!SkillLevels.TryGetValue((id, skill, raw), out int l)) return 0; *level = l; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectAttribute(uint id, uint attr, int raw, uint* value) { if (!Attributes.TryGetValue((id, attr, raw), out uint v)) return 0; *value = v; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectInstanceIdProperty(uint id, uint key, uint* v) { if (!InstanceIds.TryGetValue((id, key), out uint x)) return 0; *v = x; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectDataIdProperty(uint id, uint key, uint* v) { if (!DataIds.TryGetValue((id, key), out uint x)) return 0; *v = x; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectSpellIds(uint id, uint* buf, int max) { if (!SpellIds.TryGetValue(id, out uint[]? ids)) return -1; for (int i = 0; i < ids.Length && i < max; i++) buf[i] = ids[i]; return ids.Length; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectProperties(uint id, byte* buf, int size) { PropertyQueries.Add(id); byte[]? rec = PropertyRecord?.Invoke(id); if (rec == null) return 0; if (rec.Length <= size) rec.AsSpan().CopyTo(new Span(buf, size)); return rec.Length; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectPalettes(uint id, uint* subIds, uint* offsets, int max) { if (!Palettes.TryGetValue(id, out uint[]? p)) return -1; for (int i = 0; i < p.Length && i < max; i++) { subIds[i] = p[i]; offsets[i] = 0; } return p.Length; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int IsSpellKnown(uint id, uint spell) => KnownSpells.Contains(spell) ? 1 : 0; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int ReadPlayerEnchantments(uint* ids, double* expiry, int max) { int n = Math.Min(Enchantments.Count, max); for (int i = 0; i < n; i++) { ids[i] = Enchantments[i].SpellId; expiry[i] = Enchantments[i].Expiry; } return Enchantments.Count; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static double GetServerTime() => ServerTime; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static float GetVitae(uint id) => Vitae; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int IsPortaling() => Portaling ? 1 : 0; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetVTankState(int* sequence) { if (sequence != null) *sequence = VTankSeq; return VTankFlags < 0 ? 0 : VTankFlags; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetPlayerPose(uint* cell, float* x, float* y, float* z, float* qw, float* qx, float* qy, float* qz) { if (!HasPose) return 0; *cell = PlayerPose.Cell; *x = PlayerPose.X; *y = PlayerPose.Y; *z = PlayerPose.Z; // Heading h (0 = north, clockwise) is a physics yaw of -h about z. double half = -HeadingDeg * 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 uint GetPlayerId() => PlayerIdValue; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static void Nav3DClear() { Nav3DRings.Clear(); Nav3DLines.Clear(); Nav3DTriangles.Clear(); } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static void Nav3DAddRing(float x, float y, float z, float radius, float thick, uint color) => Nav3DRings.Add((x, y, z, radius, color)); [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static void Nav3DAddLine(float x1, float y1, float z1, float x2, float y2, float z2, float thick, uint color) => Nav3DLines.Add((x1, y1, z1, x2, y2, z2, thick, color)); [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static void Nav3DAddTriangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint color) => Nav3DTriangles.Add((x1, y1, z1, x2, y2, z2, x3, y3, z3, color)); [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static uint GetSelectedItemId() => SelectedItem; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int SetAutoRun(int on) { AutoRun = on != 0; AutoRunCalls.Add(AutoRun); Sent.Add(AutoRun ? "autorun on" : "autorun off"); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int MeleeAttack(uint target, int height, float power) { AttackCalls.Add(("melee", target, height, power)); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int MissileAttack(uint target, int height, float power) { AttackCalls.Add(("missile", target, height, power)); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int SetMotion(uint motion, int on) { MotionCalls.Add((motion, on != 0)); Sent.Add($"motion 0x{motion:X8} {(on != 0 ? "on" : "off")}"); return 1; } // The fake character turns instantly. [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int TurnToHeading(float deg) { HeadingDeg = deg; Turns++; return 1; } // What the engine's GetPlayerHeading really returns: 0 = East, counter-clockwise, i.e. // 90 - the compass heading (Freya 2026-10-20: quaternion 13.9, GetPlayerHeading 76.1). [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetPlayerHeading(float* deg) { if (!HasPose) return 0; *deg = (float)(((90.0 - HeadingDeg) % 360.0 + 360.0) % 360.0); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int JumpNonAutonomous(float extent) { Jumps++; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int TapJump() { TapJumps++; return TapJumpRefuse ? 0 : 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int CastSpell(uint target, int spellId) { if (CastRefused) { CastsRefused++; return 0; } Casts.Add((target, spellId)); Sent.Add($"cast {spellId}"); AfterCastSpell?.Invoke(); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int StopCompletely() { Stops++; Sent.Add("stop"); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetVendorInfo(VendorInfoNative* info) { *info = default; info->VendorId = 0x70000001; byte[] name = System.Text.Encoding.ASCII.GetBytes(VendorName); for (int i = 0; i < name.Length && i < 63; i++) info->Name[i] = name[i]; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetVendorItems(VendorItemNative* items, int max) => 0; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static uint VendorBuy(uint vendor, VendorTradeEntryNative* entries, int count) { var list = new (uint, int)[count]; for (int i = 0; i < count; i++) list[i] = (entries[i].ObjectId, entries[i].Amount); VendorBuys.Add((vendor, list)); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static uint VendorSell(uint vendor, uint* ids, int count) { var list = new uint[count]; for (int i = 0; i < count; i++) list[i] = ids[i]; VendorSells.Add((vendor, list)); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetVendorTradeStatus(VendorTradeStatusNative* status) => 0; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetTradeState(IntPtr state) => 0; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetTradeItems(int side, uint* buffer, int capacity) => 0; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int TradeOpen(uint target) { TradeActions.Add("open:" + target.ToString("X8")); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int TradeAdd(uint item, uint slot) { TradeActions.Add("add:" + item.ToString("X8")); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int TradeAccept() { TradeActions.Add("accept"); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int TradeDecline() { TradeActions.Add("decline"); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int TradeReset() { TradeActions.Add("reset"); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int TradeClose() { TradeActions.Add("close"); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static void ForceResetBusyCount() { ForceResets++; BusyStateValue = 0; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetBusyState() => BusyStateValue; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GiveObjectTo(uint item, uint target, int amount) { Gives.Add((item, target, amount)); if (GiveHandler != null) { GiveHandler(item, target, amount); return 1; } // The server takes the whole object for amount 0, or for an amount that covers the stack (a single // item has no StackCount: its stack is 1, so an explicit 1 takes it whole). if (GiveLands && (amount == 0 || amount >= (Ints.TryGetValue((item, 12), out int stack) ? stack : 1))) Containers[item] = target; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetCurrentCombatMode() => CombatModeValue; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int ChangeCombatMode(int mode) { if (CombatModeRefuse) { CombatModeRefusals++; return 0; } CombatModeRequests.Add(mode); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int UseObject(uint id) { Uses.Add(id); OnUseObject?.Invoke(id); return UseObjectAccepts ? 1 : 0; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectState(uint id, uint* state) { if (!ObjectStates.TryGetValue(id, out uint s)) return 0; *state = s; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int UseObjectOn(uint source, uint target) { UsesOn.Add((source, target)); OnUseObjectOn?.Invoke(source, target); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int WieldItem(uint id, uint mask) { Wields.Add((id, mask)); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int PutItemInContainer(uint id, uint container, int placement) { Puts.Add((id, container, placement)); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int CloseContainer(uint id) { Closes.Add(id); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static uint GetGroundContainerId() => GroundContainer; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int MoveItemExternal(uint id, uint target, int amount) { ExternalMoves.Add((id, target, amount)); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int SalvagePanelOpen(uint tool) => 1; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int SalvagePanelAddItem(uint id) { SalvageAdds.Add(id); if (RefuseSalvageAdd.Contains(id)) return 0; _panelItems.Add(id); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int SalvagePanelExecute() { var items = new List(_panelItems); _panelItems.Clear(); SalvageExecutes.Add(items); OnSalvageExecute?.Invoke(items); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int SalvageDirect(uint tool, uint* ids, int count) { var list = new List(); for (int i = 0; i < count; i++) list.Add(ids[i]); SalvageDirects.Add((tool, list)); int answer = SalvageDirectAnswer ?? count; if (answer > 0) OnSalvageDirect?.Invoke(tool, list); return answer; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetObjectWielderInfo(uint id, uint* wielder, uint* location) { if (!Wielded.TryGetValue(id, out uint loc)) return 0; *wielder = PlayerIdValue; *location = loc; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int RequestId(uint id) { if (!RequestIdAccepts) { RefusedIdRequests++; return 0; } IdRequests.Add(id); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int QueryHealth(uint id) { HealthQueries.Add(id); return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static long GetLastIdTime(uint id) => IdTimes.TryGetValue(id, out long t) ? t : 0L; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int HasAppraisalData(uint id) => Appraised.Contains(id) ? 1 : 0; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static uint GetObjectWcid(uint id) => Wcids.TryGetValue(id, out uint w) ? w : 0; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int ReadKnownSpells(uint* buf, int max) { for (int i = 0; i < Spellbook.Count && i < max; i++) buf[i] = Spellbook[i]; return Spellbook.Count; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetPlayerVitals(uint* hp, uint* maxHp, uint* stam, uint* maxStam, uint* mana, uint* maxMana) { *hp = Vitals.Hp; *maxHp = Vitals.MaxHp; *stam = Vitals.Stam; *maxStam = Vitals.MaxStam; *mana = Vitals.Mana; *maxMana = Vitals.MaxMana; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int GetPlayerBaseVitals(uint* hp, uint* stam, uint* mana) { *hp = BaseVitals.Hp; *stam = BaseVitals.Stam; *mana = BaseVitals.Mana; return 1; } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static IntPtr GetWorldName() => WorldName.Length > 0 ? Ansi(WorldName) : IntPtr.Zero; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static IntPtr GetAccountName() => AccountName.Length > 0 ? Ansi(AccountName) : IntPtr.Zero; }