Initial commit

A modern .NET 9 NativeAOT framework for Asheron's Call client modding.
Self-contained injection system that hooks D3D9 EndScene to render an
ImGui overlay inside the AC client process.
This commit is contained in:
tombohar 2026-04-10 18:38:07 -04:00
commit 80b71d295d
179 changed files with 52858 additions and 0 deletions

View file

@ -0,0 +1,58 @@
// ============================================================================
// RynthCore.Engine - Plugins/LoadedPlugin.cs
// Represents a single plugin DLL that has been loaded and had its exports
// resolved. Holds the module handle and cached delegates.
// ============================================================================
using System;
namespace RynthCore.Engine.Plugins;
internal sealed class LoadedPlugin
{
public string SourceFilePath { get; init; } = "";
public string FilePath { get; init; } = "";
public string FileName { get; init; } = "";
public IntPtr ModuleHandle { get; init; }
// ─── Required exports ────────────────────────────────────────────
public PluginInitDelegate? Init { get; set; }
public PluginShutdownDelegate? Shutdown { get; set; }
// ─── Optional exports ────────────────────────────────────────────
public PluginNameDelegate? GetName { get; set; }
public PluginVersionDelegate? GetVersion { get; set; }
public PluginOnLoginCompleteDelegate? OnLoginComplete { get; set; }
public PluginOnUIInitializedDelegate? OnUIInitialized { get; set; }
public PluginOnBusyCountIncrementedDelegate? OnBusyCountIncremented { get; set; }
public PluginOnBusyCountDecrementedDelegate? OnBusyCountDecremented { get; set; }
public PluginOnSelectedTargetChangeDelegate? OnSelectedTargetChange { get; set; }
public PluginOnCombatModeChangeDelegate? OnCombatModeChange { get; set; }
public IntPtr OnSmartBoxEventPtr { get; set; }
public PluginOnSmartBoxEventDelegate? OnSmartBoxEvent { get; set; }
public PluginOnDeleteObjectDelegate? OnDeleteObject { get; set; }
public PluginOnCreateObjectDelegate? OnCreateObject { get; set; }
public IntPtr OnUpdateObjectPtr { get; set; }
public PluginOnUpdateObjectDelegate? OnUpdateObject { get; set; }
public PluginOnUpdateObjectInventoryDelegate? OnUpdateObjectInventory { get; set; }
public PluginOnViewObjectContentsDelegate? OnViewObjectContents { get; set; }
public PluginOnStopViewingObjectContentsDelegate? OnStopViewingObjectContents { get; set; }
public IntPtr OnUpdateHealthPtr { get; set; }
public PluginOnUpdateHealthDelegate? OnUpdateHealth { get; set; }
public IntPtr OnChatWindowTextPtr { get; set; }
public PluginOnChatWindowTextDelegate? OnChatWindowText { get; set; }
public PluginOnChatBarEnterDelegate? OnChatBarEnter { get; set; }
public PluginBarActionDelegate? OnBarAction { get; set; }
public PluginOnEnchantmentAddedDelegate? OnEnchantmentAdded { get; set; }
public PluginOnEnchantmentRemovedDelegate? OnEnchantmentRemoved { get; set; }
public PluginTickDelegate? Tick { get; set; }
public PluginRenderDelegate? Render { get; set; }
// ─── Runtime state ───────────────────────────────────────────────
public bool Initialized { get; set; }
public bool LoginCompleteDispatched { get; set; }
public bool UIInitializedDispatched { get; set; }
public bool Failed { get; set; }
public string DisplayName { get; set; } = "";
public string VersionString { get; set; } = "";
}

View file

@ -0,0 +1,617 @@
// ============================================================================
// RynthCore.Engine - Plugins/PluginContract.cs
// Defines the C ABI contract between RynthCore and plugin DLLs.
//
// A plugin DLL must export at least:
// int RynthPluginInit(RynthCoreAPI* api) — return 0 on success
// void RynthPluginShutdown()
//
// Optional exports:
// const char* RynthPluginName() — human-readable name
// const char* RynthPluginVersion() — version string (e.g. "1.0.0")
// void RynthPluginTick() — per-frame logic (before render)
// void RynthPluginRender() — per-frame ImGui drawing
// ============================================================================
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Plugins;
/// <summary>
/// The host API struct passed to every plugin at init time.
/// Plugins receive a pointer to this and can call back into RynthCore.
/// Layout must stay ABI-stable — append new fields at the end only.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct RynthCoreAPI
{
/// <summary>API version. Plugins should check this before using later fields.</summary>
public uint Version;
/// <summary>ImGui context pointer — plugin must call igSetCurrentContext before drawing.</summary>
public IntPtr ImGuiContext;
/// <summary>IDirect3DDevice9* — the game's active D3D device.</summary>
public IntPtr D3DDevice;
/// <summary>HWND of the game window.</summary>
public IntPtr GameHwnd;
/// <summary>Function pointer: void Log(const char* message)</summary>
public IntPtr LogFn;
/// <summary>Function pointer: void ProbeClientHooks()</summary>
public IntPtr ProbeClientHooksFn;
/// <summary>Function pointer: uint GetClientHookFlags()</summary>
public IntPtr GetClientHookFlagsFn;
/// <summary>Function pointer: int ChangeCombatMode(int combatMode)</summary>
public IntPtr ChangeCombatModeFn;
/// <summary>Function pointer: int CancelAttack()</summary>
public IntPtr CancelAttackFn;
/// <summary>Function pointer: int QueryHealth(uint targetId)</summary>
public IntPtr QueryHealthFn;
/// <summary>Function pointer: int MeleeAttack(uint targetId, int attackHeight, float powerLevel)</summary>
public IntPtr MeleeAttackFn;
/// <summary>Function pointer: int MissileAttack(uint targetId, int attackHeight, float accuracyLevel)</summary>
public IntPtr MissileAttackFn;
/// <summary>Function pointer: int DoMovement(uint motion, float speed, int holdKey)</summary>
public IntPtr DoMovementFn;
/// <summary>Function pointer: int StopMovement(uint motion, int holdKey)</summary>
public IntPtr StopMovementFn;
/// <summary>Function pointer: int JumpNonAutonomous(float extent)</summary>
public IntPtr JumpNonAutonomousFn;
/// <summary>Function pointer: int SetAutonomyLevel(uint level)</summary>
public IntPtr SetAutonomyLevelFn;
/// <summary>Function pointer: int SetAutoRun(int enabled)</summary>
public IntPtr SetAutoRunFn;
/// <summary>Function pointer: int TapJump()</summary>
public IntPtr TapJumpFn;
/// <summary>Function pointer: void SetIncomingChatSuppression(int enabled)</summary>
public IntPtr SetIncomingChatSuppressionFn;
/// <summary>Function pointer: int SelectItem(uint objectId)</summary>
public IntPtr SelectItemFn;
/// <summary>Function pointer: int SetSelectedObjectId(uint objectId)</summary>
public IntPtr SetSelectedObjectIdFn;
/// <summary>Function pointer: uint GetSelectedItemId()</summary>
public IntPtr GetSelectedItemIdFn;
/// <summary>Function pointer: uint GetPreviousSelectedItemId()</summary>
public IntPtr GetPreviousSelectedItemIdFn;
/// <summary>Function pointer: uint GetPlayerId()</summary>
public IntPtr GetPlayerIdFn;
/// <summary>Function pointer: uint GetGroundContainerId()</summary>
public IntPtr GetGroundContainerIdFn;
/// <summary>Function pointer: int GetCurCoords(double* northSouth, double* eastWest)</summary>
public IntPtr GetCurCoordsFn;
/// <summary>Function pointer: int UseObject(uint objectId)</summary>
public IntPtr UseObjectFn;
/// <summary>Function pointer: int UseObjectOn(uint sourceObjectId, uint targetObjectId)</summary>
public IntPtr UseObjectOnFn;
/// <summary>Function pointer: int UseEquippedItem(uint sourceObjectId, uint targetObjectId)</summary>
public IntPtr UseEquippedItemFn;
/// <summary>Function pointer: int MoveItemExternal(uint objectId, uint targetContainerId, int amount)</summary>
public IntPtr MoveItemExternalFn;
/// <summary>Function pointer: int MoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount)</summary>
public IntPtr MoveItemInternalFn;
/// <summary>Function pointer: int WriteToChat(const wchar_t* textUtf16, int chatType)</summary>
public IntPtr WriteToChatFn;
/// <summary>Function pointer: int GetPlayerPose(uint* objCellId, float* x, float* y, float* z, float* qw, float* qx, float* qy, float* qz)</summary>
public IntPtr GetPlayerPoseFn;
/// <summary>Function pointer: int SetMotion(uint motion, int enabled)</summary>
public IntPtr SetMotionFn;
/// <summary>Function pointer: int StopCompletely()</summary>
public IntPtr StopCompletelyFn;
/// <summary>Function pointer: int TurnToHeading(float headingDegrees)</summary>
public IntPtr TurnToHeadingFn;
/// <summary>Function pointer: int GetPlayerHeading(float* headingDegrees)</summary>
public IntPtr GetPlayerHeadingFn;
/// <summary>Function pointer: const char* GetObjectName(uint objectId)</summary>
public IntPtr GetObjectNameFn;
/// <summary>Function pointer: int GetPlayerVitals(uint* health, uint* maxHealth, uint* stamina, uint* maxStamina, uint* mana, uint* maxMana)</summary>
public IntPtr GetPlayerVitalsFn;
/// <summary>Function pointer: int GetObjectPosition(uint objectId, uint* objCellId, float* x, float* y, float* z)</summary>
public IntPtr GetObjectPositionFn;
/// <summary>Function pointer: int RequestId(uint objectId) — sends appraisal/identify request to server</summary>
public IntPtr RequestIdFn;
/// <summary>Function pointer: int GetTargetVitals(uint objectId, uint* health, uint* maxHealth, uint* stamina, uint* maxStamina, uint* mana, uint* maxMana)</summary>
public IntPtr GetTargetVitalsFn;
/// <summary>Function pointer: int CastSpell(uint targetId, int spellId)</summary>
public IntPtr CastSpellFn;
/// <summary>Function pointer: int GetItemType(uint objectId, uint* typeFlags)</summary>
public IntPtr GetItemTypeFn;
/// <summary>Function pointer: int GetObjectIntProperty(uint objectId, uint stype, int* value)</summary>
public IntPtr GetObjectIntPropertyFn;
/// <summary>Function pointer: int GetObjectBoolProperty(uint objectId, uint stype, int* value) — returns 1 if property exists, value is 0/1</summary>
public IntPtr GetObjectBoolPropertyFn;
/// <summary>Function pointer: int ObjectIsAttackable(uint objectId) — calls ClientCombatSystem::ObjectIsAttackable, returns 1 if attackable</summary>
public IntPtr ObjectIsAttackableFn;
/// <summary>Function pointer: int GetObjectSkill(uint objectId, uint skillStype, int* buffed, int* training)</summary>
public IntPtr GetObjectSkillFn;
/// <summary>Function pointer: int IsSpellKnown(uint objectId, uint spellId) — returns 1 if in spell book</summary>
public IntPtr IsSpellKnownFn;
/// <summary>
/// Function pointer: int ReadPlayerEnchantments(uint* spellIds, double* expiryTimes, int maxCount)
/// Fills arrays with active player enchantments. expiryTimes are in server-time seconds.
/// Returns number written, or -1 if not available (not logged in / no registry).
/// </summary>
public IntPtr ReadPlayerEnchantmentsFn;
/// <summary>
/// Function pointer: double GetServerTime()
/// Returns estimated current server time in seconds. Returns 0 if no time sync received yet.
/// </summary>
public IntPtr GetServerTimeFn;
/// <summary>
/// Function pointer: int ReadObjectEnchantments(uint objectId, uint* spellIds, double* expiryTimes, int maxCount)
/// Reads enchantments from any game object (armor, weapon, etc.) by ID.
/// Returns number written, 0 if no enchantments, -1 if object not found or has no registry.
/// </summary>
public IntPtr ReadObjectEnchantmentsFn;
/// <summary>
/// Function pointer: int WorldToScreen(float worldX, float worldY, float worldZ, float* screenX, float* screenY)
/// Projects a 3D game-world position to 2D screen coordinates.
/// World coordinates are in the same space as GetObjectPosition returns.
/// Returns 1 if on screen, 0 if behind camera or unavailable.
/// </summary>
public IntPtr WorldToScreenFn;
/// <summary>
/// Function pointer: int GetViewportSize(uint* width, uint* height)
/// Returns the current D3D9 viewport dimensions.
/// Returns 1 on success, 0 if not available yet.
/// </summary>
public IntPtr GetViewportSizeFn;
/// <summary>
/// Function pointer: void Nav3DClear()
/// Clears the 3D nav marker submission buffer. Call once per frame before adding markers.
/// </summary>
public IntPtr Nav3DClearFn;
/// <summary>
/// Function pointer: void Nav3DAddRing(float wx, float wy, float wz, float radius, float thickness, uint colorArgb)
/// Submits a flat 3D ring at the given world position. Coordinates are D3D: X=EW, Y=height, Z=NS.
/// Color is ARGB (D3DCOLOR format).
/// </summary>
public IntPtr Nav3DAddRingFn;
/// <summary>
/// Function pointer: void Nav3DAddLine(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb)
/// Submits a flat 3D line between two world positions. Coordinates are D3D: X=EW, Y=height, Z=NS.
/// </summary>
public IntPtr Nav3DAddLineFn;
/// <summary>
/// Function pointer: int InvokeChatParser(const wchar_t* textUtf16)
/// Passes text to the AC outgoing chat parser as if the player typed it.
/// Returns 1 on success, 0 if the hook is not installed yet.
/// </summary>
public IntPtr InvokeChatParserFn;
/// <summary>
/// Function pointer: int GetObjectDoubleProperty(uint objectId, uint stype, double* value)
/// Reads an STypeFloat (double) property from any game object.
/// Returns 1 on success, 0 if undefined.
/// </summary>
public IntPtr GetObjectDoublePropertyFn;
/// <summary>
/// Function pointer: IntPtr GetObjectStringProperty(uint objectId, uint stype)
/// Returns pointer to ANSI string data, or IntPtr.Zero if undefined.
/// </summary>
public IntPtr GetObjectStringPropertyFn;
/// <summary>
/// Function pointer: int GetObjectWielderInfo(uint objectId, uint* wielderID, uint* location)
/// Reads PublicWeenieDesc._wielderID and _location from the weenie struct.
/// </summary>
public IntPtr GetObjectWielderInfoFn;
/// <summary>
/// Function pointer: int NativeAttack(int attackHeight, float power)
/// Uses the client's native combat pipeline (ClientCombatSystem) which handles
/// turn-to-face and attack execution naturally. Requires target to be selected first.
/// Returns 1 on success, 0 if not available.
/// </summary>
public IntPtr NativeAttackFn;
/// <summary>
/// Function pointer: int IsPlayerReady()
/// Returns 1 if the player is in a ready position to begin an attack.
/// </summary>
public IntPtr IsPlayerReadyFn;
/// <summary>
/// Function pointer: void SetFpsLimit(int enabled, int focusedFps, int backgroundFps)
/// Controls the engine-level EndScene frame governor.
/// </summary>
public IntPtr SetFpsLimitFn;
/// <summary>
/// Function pointer: int GetContainerContents(uint containerId, uint* itemIds, int maxCount)
/// Writes contained item IDs into the provided buffer and returns the number written.
/// </summary>
public IntPtr GetContainerContentsFn;
/// <summary>
/// Function pointer: int GetObjectOwnershipInfo(uint objectId, uint* containerID, uint* wielderID, uint* location)
/// Reads PublicWeenieDesc ownership fields from the weenie struct.
/// </summary>
public IntPtr GetObjectOwnershipInfoFn;
/// <summary>
/// Function pointer: int SplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount)
/// Moves a stack of items onto a specific slot in the target container, merging
/// with any existing same-type stack at that slot. Unlike MoveItemInternal which
/// sends opcode 0x19 (whole move, first empty slot), this sends opcode 0x55
/// (StackableSplitToContainer) which honors the slot parameter.
/// </summary>
public IntPtr SplitStackInternalFn;
/// <summary>
/// Function pointer: int MergeStackInternal(uint sourceObjectId, uint targetObjectId)
/// Merges two stacks of the same item type by sending opcode 0x1A (STACKABLE_MERGE).
/// This is the real merge path used by drag-drop UI — opcode 0x55 (split-to-slot)
/// creates new stacks instead of merging, so AutoStack must use this entry point.
/// </summary>
public IntPtr MergeStackInternalFn;
}
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
internal static class PluginContractVersion
{
public const uint Current = 34;
}
internal static class ClientActionHookFlags
{
public const uint CombatInitialized = 1u << 0;
public const uint MovementInitialized = 1u << 1;
public const uint MeleeAttack = 1u << 2;
public const uint MissileAttack = 1u << 3;
public const uint ChangeCombatMode = 1u << 4;
public const uint CancelAttack = 1u << 5;
public const uint QueryHealth = 1u << 6;
public const uint DoMovement = 1u << 7;
public const uint StopMovement = 1u << 8;
public const uint JumpNonAutonomous = 1u << 9;
public const uint SetAutonomyLevel = 1u << 10;
public const uint SetAutoRun = 1u << 11;
public const uint TapJump = 1u << 12;
public const uint SetMotion = 1u << 13;
public const uint StopCompletely = 1u << 14;
public const uint TurnToHeading = 1u << 15;
public const uint GetPlayerHeading = 1u << 16;
}
// ─── Delegate types matching the plugin's exported functions ────────────
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int PluginInitDelegate(ref RynthCoreAPI api);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginShutdownDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate IntPtr PluginNameDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate IntPtr PluginVersionDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnLoginCompleteDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnUIInitializedDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnBusyCountIncrementedDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnBusyCountDecrementedDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnSelectedTargetChangeDelegate(uint currentTargetId, uint previousTargetId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnCombatModeChangeDelegate(int currentCombatMode, int previousCombatMode);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnSmartBoxEventDelegate(uint opcode, uint blobSize, uint status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnDeleteObjectDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnCreateObjectDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnUpdateObjectDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnUpdateObjectInventoryDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnViewObjectContentsDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnStopViewingObjectContentsDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnUpdateHealthDelegate(uint targetId, float healthRatio, uint currentHealth, uint maxHealth);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnChatWindowTextDelegate(IntPtr textUtf16, int chatType, IntPtr eatFlag);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnChatBarEnterDelegate(IntPtr textUtf16, IntPtr eatFlag);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginBarActionDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginTickDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginRenderDelegate();
// ─── Log callback that plugins can call ─────────────────────────────────
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void LogCallbackDelegate(IntPtr messageUtf8);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void ProbeClientHooksCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate uint GetClientHookFlagsCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int ChangeCombatModeCallbackDelegate(int combatMode);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int CancelAttackCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int QueryHealthCallbackDelegate(uint targetId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int MeleeAttackCallbackDelegate(uint targetId, int attackHeight, float powerLevel);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int MissileAttackCallbackDelegate(uint targetId, int attackHeight, float accuracyLevel);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int NativeAttackCallbackDelegate(int attackHeight, float power);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int IsPlayerReadyCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void SetFpsLimitCallbackDelegate(int enabled, int focusedFps, int backgroundFps);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int DoMovementCallbackDelegate(uint motion, float speed, int holdKey);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int StopMovementCallbackDelegate(uint motion, int holdKey);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int JumpNonAutonomousCallbackDelegate(float extent);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int SetAutonomyLevelCallbackDelegate(uint level);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int SetAutoRunCallbackDelegate(int enabled);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int TapJumpCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int SetMotionCallbackDelegate(uint motion, int enabled);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int StopCompletelyCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int TurnToHeadingCallbackDelegate(float headingDegrees);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetPlayerHeadingCallbackDelegate(float* headingDegrees);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void SetIncomingChatSuppressionCallbackDelegate(int enabled);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int SelectItemCallbackDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int SetSelectedObjectIdCallbackDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate uint GetItemIdCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetCurCoordsCallbackDelegate(double* northSouth, double* eastWest);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int UseObjectCallbackDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int UseObjectOnCallbackDelegate(uint sourceObjectId, uint targetObjectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int UseEquippedItemCallbackDelegate(uint sourceObjectId, uint targetObjectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int MoveItemExternalCallbackDelegate(uint objectId, uint targetContainerId, int amount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int MoveItemInternalCallbackDelegate(uint objectId, uint targetContainerId, int slot, int amount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int SplitStackInternalCallbackDelegate(uint objectId, uint targetContainerId, int slot, int amount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int MergeStackInternalCallbackDelegate(uint sourceObjectId, uint targetObjectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int WriteToChatCallbackDelegate(IntPtr textUtf16, int chatType);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetPlayerPoseCallbackDelegate(
uint* objCellId,
float* x,
float* y,
float* z,
float* qw,
float* qx,
float* qy,
float* qz);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate IntPtr GetObjectNameCallbackDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetPlayerVitalsCallbackDelegate(
uint* health,
uint* maxHealth,
uint* stamina,
uint* maxStamina,
uint* mana,
uint* maxMana);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectPositionCallbackDelegate(
uint objectId,
uint* objCellId,
float* x,
float* y,
float* z);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int RequestIdCallbackDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetTargetVitalsCallbackDelegate(
uint objectId,
uint* health,
uint* maxHealth,
uint* stamina,
uint* maxStamina,
uint* mana,
uint* maxMana);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int CastSpellCallbackDelegate(uint targetId, int spellId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetItemTypeCallbackDelegate(uint objectId, uint* typeFlags);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectIntPropertyCallbackDelegate(uint objectId, uint stype, int* value);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectBoolPropertyCallbackDelegate(uint objectId, uint stype, int* value);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int ObjectIsAttackableCallbackDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectSkillCallbackDelegate(uint objectId, uint skillStype, int* buffed, int* training);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int IsSpellKnownCallbackDelegate(uint objectId, uint spellId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnEnchantmentAddedDelegate(uint spellId, double durationSeconds);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnEnchantmentRemovedDelegate(uint enchantmentId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int ReadPlayerEnchantmentsCallbackDelegate(uint* spellIds, double* expiryTimes, int maxCount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate double GetServerTimeCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int ReadObjectEnchantmentsCallbackDelegate(uint objectId, uint* spellIds, double* expiryTimes, int maxCount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int WorldToScreenCallbackDelegate(float worldX, float worldY, float worldZ, float* screenX, float* screenY);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetViewportSizeCallbackDelegate(uint* width, uint* height);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void Nav3DClearCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void Nav3DAddRingCallbackDelegate(float wx, float wy, float wz, float radius, float thickness, uint colorArgb);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void Nav3DAddLineCallbackDelegate(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int InvokeChatParserCallbackDelegate(IntPtr textUtf16);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectDoublePropertyCallbackDelegate(uint objectId, uint stype, double* value);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate IntPtr GetObjectStringPropertyCallbackDelegate(uint objectId, uint stype);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectWielderInfoCallbackDelegate(uint objectId, uint* wielderID, uint* location);
internal unsafe delegate int GetContainerContentsCallbackDelegate(uint containerId, uint* itemIds, int maxCount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectOwnershipInfoCallbackDelegate(uint objectId, uint* containerID, uint* wielderID, uint* location);

View file

@ -0,0 +1,367 @@
// ============================================================================
// RynthCore.Engine - Plugins/PluginLoader.cs
// Scans the Plugins directory, loads each DLL, and resolves exports.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Plugins;
internal static class PluginLoader
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr LoadLibraryW(string lpLibFileName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
/// <summary>
/// Scans <paramref name="pluginsDir"/> for *.dll files, loads each one,
/// and resolves the plugin contract exports.
/// Returns only plugins that have the two required exports (Init + Shutdown).
/// </summary>
public static List<LoadedPlugin> LoadAll(string pluginsDir, string shadowRootDir, int generation)
{
var plugins = new List<LoadedPlugin>();
if (!Directory.Exists(pluginsDir))
{
RynthLog.Verbose($"PluginLoader: Creating plugins directory: {pluginsDir}");
try { Directory.CreateDirectory(pluginsDir); }
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: Failed to create directory: {ex.Message}");
return plugins;
}
return plugins;
}
string sessionShadowDir = PrepareShadowDirectory(shadowRootDir, generation);
string[] dllFiles;
try { dllFiles = Directory.GetFiles(pluginsDir, "*.dll"); }
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: Failed to enumerate {pluginsDir}: {ex.Message}");
return plugins;
}
Array.Sort(dllFiles, StringComparer.OrdinalIgnoreCase);
if (dllFiles.Length == 0)
{
RynthLog.Verbose("PluginLoader: No plugin DLLs found.");
return plugins;
}
RynthLog.Verbose($"PluginLoader: Found {dllFiles.Length} DLL(s) in {pluginsDir}");
foreach (string dllPath in dllFiles)
{
var plugin = TryLoad(dllPath, sessionShadowDir);
if (plugin != null)
plugins.Add(plugin);
}
RynthLog.Verbose($"PluginLoader: {plugins.Count} plugin(s) loaded successfully.");
return plugins;
}
/// <summary>
/// Unloads a plugin by freeing its DLL.
/// </summary>
public static void Unload(LoadedPlugin plugin)
{
if (plugin.ModuleHandle != IntPtr.Zero)
{
FreeLibrary(plugin.ModuleHandle);
RynthLog.Verbose($"PluginLoader: Unloaded {plugin.FileName}");
}
TryDeleteFile(plugin.FilePath);
TryDeleteFile(Path.ChangeExtension(plugin.FilePath, ".pdb"));
TryDeleteEmptyDirectory(Path.GetDirectoryName(plugin.FilePath));
}
public static void CleanupShadowCopies(string shadowRootDir)
{
if (!Directory.Exists(shadowRootDir))
return;
try
{
foreach (string dir in Directory.GetDirectories(shadowRootDir))
TryDeleteDirectory(dir);
}
catch (Exception ex)
{
RynthLog.Verbose($"PluginLoader: Shadow cleanup skipped ({ex.Message})");
}
}
private static LoadedPlugin? TryLoad(string sourcePath, string sessionShadowDir)
{
string fileName = Path.GetFileName(sourcePath);
RynthLog.Verbose($"PluginLoader: Loading {fileName}...");
string shadowPath;
try
{
shadowPath = CreateShadowCopy(sourcePath, sessionShadowDir);
}
catch (Exception ex)
{
RynthLog.Plugin($"PluginLoader: FAILED to stage {fileName} ({ex.Message})");
return null;
}
IntPtr handle = LoadLibraryW(shadowPath);
if (handle == IntPtr.Zero)
{
int err = Marshal.GetLastWin32Error();
RynthLog.Plugin($"PluginLoader: FAILED to load {fileName} (Win32 error {err})");
return null;
}
// Resolve required exports
IntPtr initPtr = GetProcAddress(handle, "RynthPluginInit");
IntPtr shutdownPtr = GetProcAddress(handle, "RynthPluginShutdown");
if (initPtr == IntPtr.Zero || shutdownPtr == IntPtr.Zero)
{
RynthLog.Plugin($"PluginLoader: {fileName} missing required exports (RynthPluginInit/RynthPluginShutdown) — skipping.");
FreeLibrary(handle);
return null;
}
var plugin = new LoadedPlugin
{
SourceFilePath = sourcePath,
FilePath = shadowPath,
FileName = fileName,
ModuleHandle = handle,
Init = Marshal.GetDelegateForFunctionPointer<PluginInitDelegate>(initPtr),
Shutdown = Marshal.GetDelegateForFunctionPointer<PluginShutdownDelegate>(shutdownPtr),
DisplayName = fileName
};
// Resolve optional exports
IntPtr namePtr = GetProcAddress(handle, "RynthPluginName");
if (namePtr != IntPtr.Zero)
plugin.GetName = Marshal.GetDelegateForFunctionPointer<PluginNameDelegate>(namePtr);
IntPtr versionPtr = GetProcAddress(handle, "RynthPluginVersion");
if (versionPtr != IntPtr.Zero)
plugin.GetVersion = Marshal.GetDelegateForFunctionPointer<PluginVersionDelegate>(versionPtr);
IntPtr onLoginCompletePtr = GetProcAddress(handle, "RynthPluginOnLoginComplete");
if (onLoginCompletePtr != IntPtr.Zero)
plugin.OnLoginComplete = Marshal.GetDelegateForFunctionPointer<PluginOnLoginCompleteDelegate>(onLoginCompletePtr);
IntPtr onUiInitializedPtr = GetProcAddress(handle, "RynthPluginOnUIInitialized");
if (onUiInitializedPtr != IntPtr.Zero)
plugin.OnUIInitialized = Marshal.GetDelegateForFunctionPointer<PluginOnUIInitializedDelegate>(onUiInitializedPtr);
IntPtr onBusyCountIncrementedPtr = GetProcAddress(handle, "RynthPluginOnBusyCountIncremented");
if (onBusyCountIncrementedPtr != IntPtr.Zero)
plugin.OnBusyCountIncremented = Marshal.GetDelegateForFunctionPointer<PluginOnBusyCountIncrementedDelegate>(onBusyCountIncrementedPtr);
IntPtr onBusyCountDecrementedPtr = GetProcAddress(handle, "RynthPluginOnBusyCountDecremented");
if (onBusyCountDecrementedPtr != IntPtr.Zero)
plugin.OnBusyCountDecremented = Marshal.GetDelegateForFunctionPointer<PluginOnBusyCountDecrementedDelegate>(onBusyCountDecrementedPtr);
IntPtr onSelectedTargetChangePtr = GetProcAddress(handle, "RynthPluginOnSelectedTargetChange");
if (onSelectedTargetChangePtr != IntPtr.Zero)
plugin.OnSelectedTargetChange = Marshal.GetDelegateForFunctionPointer<PluginOnSelectedTargetChangeDelegate>(onSelectedTargetChangePtr);
IntPtr onCombatModeChangePtr = GetProcAddress(handle, "RynthPluginOnCombatModeChange");
if (onCombatModeChangePtr != IntPtr.Zero)
plugin.OnCombatModeChange = Marshal.GetDelegateForFunctionPointer<PluginOnCombatModeChangeDelegate>(onCombatModeChangePtr);
IntPtr onSmartBoxEventPtr = GetProcAddress(handle, "RynthPluginOnSmartBoxEvent");
if (onSmartBoxEventPtr != IntPtr.Zero)
{
plugin.OnSmartBoxEventPtr = onSmartBoxEventPtr;
plugin.OnSmartBoxEvent = Marshal.GetDelegateForFunctionPointer<PluginOnSmartBoxEventDelegate>(onSmartBoxEventPtr);
}
IntPtr onDeleteObjectPtr = GetProcAddress(handle, "RynthPluginOnDeleteObject");
if (onDeleteObjectPtr != IntPtr.Zero)
plugin.OnDeleteObject = Marshal.GetDelegateForFunctionPointer<PluginOnDeleteObjectDelegate>(onDeleteObjectPtr);
IntPtr onCreateObjectPtr = GetProcAddress(handle, "RynthPluginOnCreateObject");
if (onCreateObjectPtr != IntPtr.Zero)
plugin.OnCreateObject = Marshal.GetDelegateForFunctionPointer<PluginOnCreateObjectDelegate>(onCreateObjectPtr);
IntPtr onUpdateObjectPtr = GetProcAddress(handle, "RynthPluginOnUpdateObject");
if (onUpdateObjectPtr != IntPtr.Zero)
{
plugin.OnUpdateObjectPtr = onUpdateObjectPtr;
plugin.OnUpdateObject = Marshal.GetDelegateForFunctionPointer<PluginOnUpdateObjectDelegate>(onUpdateObjectPtr);
}
IntPtr onUpdateObjectInventoryPtr = GetProcAddress(handle, "RynthPluginOnUpdateObjectInventory");
if (onUpdateObjectInventoryPtr != IntPtr.Zero)
plugin.OnUpdateObjectInventory = Marshal.GetDelegateForFunctionPointer<PluginOnUpdateObjectInventoryDelegate>(onUpdateObjectInventoryPtr);
IntPtr onViewObjectContentsPtr = GetProcAddress(handle, "RynthPluginOnViewObjectContents");
if (onViewObjectContentsPtr != IntPtr.Zero)
plugin.OnViewObjectContents = Marshal.GetDelegateForFunctionPointer<PluginOnViewObjectContentsDelegate>(onViewObjectContentsPtr);
IntPtr onStopViewingObjectContentsPtr = GetProcAddress(handle, "RynthPluginOnStopViewingObjectContents");
if (onStopViewingObjectContentsPtr != IntPtr.Zero)
plugin.OnStopViewingObjectContents = Marshal.GetDelegateForFunctionPointer<PluginOnStopViewingObjectContentsDelegate>(onStopViewingObjectContentsPtr);
IntPtr onUpdateHealthPtr = GetProcAddress(handle, "RynthPluginOnUpdateHealth");
if (onUpdateHealthPtr != IntPtr.Zero)
{
plugin.OnUpdateHealthPtr = onUpdateHealthPtr;
plugin.OnUpdateHealth = Marshal.GetDelegateForFunctionPointer<PluginOnUpdateHealthDelegate>(onUpdateHealthPtr);
}
IntPtr onChatWindowTextPtr = GetProcAddress(handle, "RynthPluginOnChatWindowText");
if (onChatWindowTextPtr != IntPtr.Zero)
{
plugin.OnChatWindowTextPtr = onChatWindowTextPtr;
plugin.OnChatWindowText = Marshal.GetDelegateForFunctionPointer<PluginOnChatWindowTextDelegate>(onChatWindowTextPtr);
}
IntPtr onChatBarEnterPtr = GetProcAddress(handle, "RynthPluginOnChatBarEnter");
if (onChatBarEnterPtr != IntPtr.Zero)
plugin.OnChatBarEnter = Marshal.GetDelegateForFunctionPointer<PluginOnChatBarEnterDelegate>(onChatBarEnterPtr);
IntPtr onBarActionPtr = GetProcAddress(handle, "RynthPluginOnBarAction");
if (onBarActionPtr != IntPtr.Zero)
plugin.OnBarAction = Marshal.GetDelegateForFunctionPointer<PluginBarActionDelegate>(onBarActionPtr);
IntPtr onEnchantmentAddedPtr = GetProcAddress(handle, "RynthPluginOnEnchantmentAdded");
if (onEnchantmentAddedPtr != IntPtr.Zero)
plugin.OnEnchantmentAdded = Marshal.GetDelegateForFunctionPointer<PluginOnEnchantmentAddedDelegate>(onEnchantmentAddedPtr);
IntPtr onEnchantmentRemovedPtr = GetProcAddress(handle, "RynthPluginOnEnchantmentRemoved");
if (onEnchantmentRemovedPtr != IntPtr.Zero)
plugin.OnEnchantmentRemoved = Marshal.GetDelegateForFunctionPointer<PluginOnEnchantmentRemovedDelegate>(onEnchantmentRemovedPtr);
IntPtr tickPtr = GetProcAddress(handle, "RynthPluginTick");
if (tickPtr != IntPtr.Zero)
plugin.Tick = Marshal.GetDelegateForFunctionPointer<PluginTickDelegate>(tickPtr);
IntPtr renderPtr = GetProcAddress(handle, "RynthPluginRender");
if (renderPtr != IntPtr.Zero)
plugin.Render = Marshal.GetDelegateForFunctionPointer<PluginRenderDelegate>(renderPtr);
// Read name/version from the plugin if available
if (plugin.GetName != null)
{
IntPtr strPtr = plugin.GetName();
if (strPtr != IntPtr.Zero)
plugin.DisplayName = Marshal.PtrToStringAnsi(strPtr) ?? fileName;
}
if (plugin.GetVersion != null)
{
IntPtr strPtr = plugin.GetVersion();
if (strPtr != IntPtr.Zero)
plugin.VersionString = Marshal.PtrToStringAnsi(strPtr) ?? "";
}
string ver = string.IsNullOrEmpty(plugin.VersionString) ? "" : $" v{plugin.VersionString}";
string caps = BuildCapsList(plugin);
RynthLog.Verbose($"PluginLoader: {plugin.DisplayName}{ver} loaded ({caps})");
return plugin;
}
private static string PrepareShadowDirectory(string shadowRootDir, int generation)
{
string sessionDir = Path.Combine(shadowRootDir, $"session-{generation:D4}-pid{Environment.ProcessId}");
Directory.CreateDirectory(sessionDir);
return sessionDir;
}
private static string CreateShadowCopy(string sourcePath, string sessionShadowDir)
{
string fileName = Path.GetFileName(sourcePath);
string shadowPath = Path.Combine(sessionShadowDir, fileName);
File.Copy(sourcePath, shadowPath, true);
string sourcePdb = Path.ChangeExtension(sourcePath, ".pdb");
string shadowPdb = Path.ChangeExtension(shadowPath, ".pdb");
if (File.Exists(sourcePdb))
File.Copy(sourcePdb, shadowPdb, true);
return shadowPath;
}
private static void TryDeleteFile(string? path)
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
return;
try
{
File.Delete(path);
}
catch
{
}
}
private static void TryDeleteEmptyDirectory(string? path)
{
if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path))
return;
try
{
if (Directory.GetFileSystemEntries(path).Length == 0)
Directory.Delete(path);
}
catch
{
}
}
private static void TryDeleteDirectory(string path)
{
try
{
Directory.Delete(path, true);
}
catch
{
}
}
private static string BuildCapsList(LoadedPlugin p)
{
var parts = new List<string>(4) { "init", "shutdown" };
if (p.OnLoginComplete != null) parts.Add("login");
if (p.OnUIInitialized != null) parts.Add("ui");
if (p.OnBusyCountIncremented != null) parts.Add("busy+");
if (p.OnBusyCountDecremented != null) parts.Add("busy-");
if (p.OnSelectedTargetChange != null) parts.Add("target");
if (p.OnCombatModeChange != null) parts.Add("combat-mode");
if (p.OnSmartBoxEvent != null) parts.Add("smartbox");
if (p.OnCreateObject != null) parts.Add("create");
if (p.OnDeleteObject != null) parts.Add("delete");
if (p.OnUpdateObject != null) parts.Add("update-object");
if (p.OnUpdateObjectInventory != null) parts.Add("inventory");
if (p.OnViewObjectContents != null) parts.Add("contents-open");
if (p.OnStopViewingObjectContents != null) parts.Add("contents-close");
if (p.OnUpdateHealth != null || p.OnUpdateHealthPtr != IntPtr.Zero) parts.Add("health");
if (p.OnChatWindowText != null) parts.Add("chat-in");
if (p.OnChatBarEnter != null) parts.Add("chat-out");
if (p.OnBarAction != null) parts.Add("bar");
if (p.Tick != null) parts.Add("tick");
if (p.Render != null) parts.Add("render");
return string.Join(", ", parts);
}
}

File diff suppressed because it is too large Load diff