fix(engine): snapshot PWD ints off-thread and report merge-stack results (API v68)
Main-thread position walk now captures stack size, max stack, container, wielder, location, capacities and material so off-thread reads stop returning unknown (finding #24). MergeStackInternal records every outcome; new GetMergeStackResult API slot exposes it to plugins. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
a87d12a916
commit
6f9b9858fa
8 changed files with 394 additions and 70 deletions
54
Changelog/2026-10-04-pwd-int-snapshot-and-merge-results.md
Normal file
54
Changelog/2026-10-04-pwd-int-snapshot-and-merge-results.md
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
# 2026-10-04 — PublicWeenieDesc int snapshot + merge-stack results (API v68)
|
||||
|
||||
## Problem
|
||||
|
||||
AutoStack failed almost every merge (one session: 515 attempts / 514 failures;
|
||||
the day: 1,521 / 1,515 — mostly Prismatic Tapers and Diamond Scarabs).
|
||||
|
||||
* The RynthAi update loop runs on the plugin pump thread, not AC's main thread.
|
||||
* Since audit finding #24 (no live AC memory reads off-thread),
|
||||
`TryGetObjectIntProperty` refused stack size / max stack size off-thread and
|
||||
had no snapshot to fall back on, so every stack read as "unknown" → 1.
|
||||
* The engine's main-thread merge then read the *real* counts, found the target
|
||||
full and silently skipped it (logged only at Verbose). RynthAi waited its 10 s
|
||||
grace window and logged a failure — forever, for the same pairs.
|
||||
* The same bad count fed AutoCram amounts, missile-crafting head/shaft counts
|
||||
and ExpressionEngine item-count expressions.
|
||||
|
||||
## Fix
|
||||
|
||||
### PublicWeenieDesc int snapshot (`ClientObjectHooks`)
|
||||
|
||||
* The 100 ms main-thread position walk (`PrefetchPositions` →
|
||||
`CapturePositionForId`) now also captures, per object, the PWD fields:
|
||||
container (+28), wielder (+32), valid locations (+40), location (+44),
|
||||
items capacity (+48), containers capacity (+52), stack size (+96),
|
||||
max stack size (+100) and material (+148).
|
||||
* One `VirtualQuery` range check per object guards the whole field block; the
|
||||
walk stays allocation-free (struct values in pre-sized dictionaries).
|
||||
* The snapshot is double-buffered and swapped together with the weenie-pointer
|
||||
buffers under `_weeniePtrSwapLock`, so readers always see one coherent frame.
|
||||
* Off-thread reads route to the snapshot:
|
||||
* `TryGetObjectIntProperty` for STypes 6, 7, 9, 10, 11, 12, 131.
|
||||
Stack size / max stack of `<= 0` still prefer the appraisal cache.
|
||||
* `TryReadPwdInt32` (previously returned `false` off-thread).
|
||||
* `TryGetObjectOwnershipInfo` / `TryGetObjectWielderInfo` (container,
|
||||
wielder, location).
|
||||
* Main-thread reads are unchanged (live PWD reads).
|
||||
* A one-time `PWD int snapshot warm` log line confirms the snapshot is serving.
|
||||
|
||||
### Merge-stack results (`MergeStackResults`, API v68)
|
||||
|
||||
* New `MergeStackResults` table keyed by (source, target) records the outcome
|
||||
of every `MergeStackInternal` exit: `Queued`, `Sent` (with amount),
|
||||
`TargetFull`, `Failed`, `QueueFull`.
|
||||
* New API slot `GetMergeStackResultFn` (appended; `PluginContractVersion` 68):
|
||||
returns the latest status plus amount and age in milliseconds.
|
||||
* SDK: `RynthCoreHost.CurrentApiVersion = 68`, `HasGetMergeStackResult`,
|
||||
`GetMergeStackResult(...)` and `RynthCoreHost.MergeStackStatus` constants.
|
||||
Returns `None` on older engines, so plugins degrade to their old behaviour.
|
||||
|
||||
## Compatibility
|
||||
|
||||
* ABI: append-only; plugins built against v66/v67 keep working.
|
||||
* No behaviour change on the main thread.
|
||||
|
|
@ -539,12 +539,21 @@ internal static class ClientHelperHooks
|
|||
/// </summary>
|
||||
public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId)
|
||||
{
|
||||
// Every exit records its outcome in MergeStackResults so the plugin can poll
|
||||
// GetMergeStackResult instead of guessing from a later inventory snapshot.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId);
|
||||
{
|
||||
bool queued = AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId);
|
||||
MergeStackResults.Record(sourceObjectId, targetObjectId,
|
||||
queued ? MergeStackResults.Queued : MergeStackResults.QueueFull);
|
||||
return queued;
|
||||
}
|
||||
|
||||
if (_eventStackableMerge == null) return false;
|
||||
if (!IsValidObjectId(sourceObjectId)) return false;
|
||||
if (!IsValidObjectId(targetObjectId)) return false;
|
||||
if (_eventStackableMerge == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
|
||||
{
|
||||
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read counts via the PWD fast path (stypes 11/12 are served from
|
||||
// PublicWeenieDesc directly — no broken InqInt for inventory items).
|
||||
|
|
@ -563,6 +572,7 @@ internal static class ClientHelperHooks
|
|||
if (room <= 0)
|
||||
{
|
||||
RynthLog.Verbose($"Compat: Event_StackableMerge skipped - target 0x{targetObjectId:X8}({targetCount}) is full (max={maxStack})");
|
||||
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.TargetFull);
|
||||
return false;
|
||||
}
|
||||
amount = Math.Min(sourceCount, room);
|
||||
|
|
@ -573,17 +583,24 @@ internal static class ClientHelperHooks
|
|||
amount = sourceCount;
|
||||
}
|
||||
|
||||
if (amount <= 0) return false;
|
||||
if (amount <= 0)
|
||||
{
|
||||
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
byte rv = _eventStackableMerge(sourceObjectId, targetObjectId, amount);
|
||||
RynthLog.Verbose($"Compat: Event_StackableMerge from=0x{sourceObjectId:X8}({sourceCount}) to=0x{targetObjectId:X8}({targetCount}) amount={amount}/{maxStack} rv={rv}");
|
||||
MergeStackResults.Record(sourceObjectId, targetObjectId,
|
||||
rv != 0 ? MergeStackResults.Sent : MergeStackResults.Failed, rv != 0 ? amount : 0);
|
||||
return rv != 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"Compat: Event_StackableMerge threw - {ex.Message}");
|
||||
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -276,6 +276,28 @@ internal static class ClientObjectHooks
|
|||
private static readonly object _weeniePtrSwapLock = new();
|
||||
private static Dictionary<uint, IntPtr> _weeniePtrFront = new(512);
|
||||
private static Dictionary<uint, IntPtr> _weeniePtrBack = new(512);
|
||||
|
||||
// PublicWeenieDesc int-field snapshot (stack size, max stack, container, wielder,
|
||||
// locations, capacities, material). Deep-audit finding #24 made the PWD reads main-
|
||||
// thread-only, which left the off-thread plugin pump with NO source for these: every
|
||||
// stack read as unknown (treated as 1) — AutoStack's 1,500 failed merges, AutoCram
|
||||
// amounts, missile-crafting counts and meta item-count expressions. The main-thread
|
||||
// position walk now copies these fields for every live object (pack items included)
|
||||
// into _pwdBack and publishes it with the weenie-pointer swap, so off-thread readers
|
||||
// get values at most ~100 ms old without touching AC memory. Struct values + reused
|
||||
// dictionaries keep the walk zero-alloc (same constraint as _positionCache).
|
||||
private struct PwdIntEntry
|
||||
{
|
||||
public int ContainerId, WielderId, ValidLocations, Location;
|
||||
public int ItemsCapacity, ContainersCapacity, StackSize, MaxStackSize, MaterialType;
|
||||
}
|
||||
private static Dictionary<uint, PwdIntEntry> _pwdFront = new(512);
|
||||
private static Dictionary<uint, PwdIntEntry> _pwdBack = new(512);
|
||||
private static bool _loggedPwdServe;
|
||||
// PWD field offsets (Chorizite Weenie.cs; same layout as the PWD fast paths below).
|
||||
private const int PwdContainerIdOffset = 28, PwdWielderIdOffset = 32, PwdValidLocationsOffset = 40;
|
||||
private const int PwdLocationOffset = 44, PwdItemsCapacityOffset = 48, PwdContainersCapacityOffset = 52;
|
||||
private const int PwdStackSizeOffset = 96, PwdMaxStackSizeOffset = 100, PwdMaterialTypeOffset = 148;
|
||||
// Diagnostic (temporary): periodic snapshot-size log + live-read probe of
|
||||
// objects with a position but no cached name. Remove once the missing-
|
||||
// monsters cause is pinned. _diagSampleBuf preallocated to stay low-alloc.
|
||||
|
|
@ -1452,6 +1474,23 @@ internal static class ClientObjectHooks
|
|||
containerID = 0;
|
||||
wielderID = 0;
|
||||
location = 0;
|
||||
|
||||
// Off-thread: serve from the main-thread PWD snapshot instead of dereferencing a
|
||||
// cached (possibly freed and reused) weenie pointer — the finding #24 TOCTOU class.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
{
|
||||
PwdIntEntry e;
|
||||
lock (_weeniePtrSwapLock)
|
||||
{
|
||||
if (!_pwdFront.TryGetValue(objectId, out e))
|
||||
return false;
|
||||
}
|
||||
containerID = unchecked((uint)e.ContainerId);
|
||||
wielderID = unchecked((uint)e.WielderId);
|
||||
location = unchecked((uint)e.Location);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_getWeenieObject == null)
|
||||
{
|
||||
if (!Probe() || _getWeenieObject == null)
|
||||
|
|
@ -1498,8 +1537,9 @@ internal static class ClientObjectHooks
|
|||
value = 0;
|
||||
if (pwdFieldOffset < 0 || pwdFieldOffset > 172 || (pwdFieldOffset & 3) != 0)
|
||||
return false;
|
||||
// Off-thread: only the fields the main-thread PWD snapshot carries are available.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return false;
|
||||
return TryGetPwdSnapshotInt(objectId, pwdFieldOffset, out value);
|
||||
if (_getWeenieObject == null)
|
||||
{
|
||||
if (!Probe() || _getWeenieObject == null)
|
||||
|
|
@ -1895,10 +1935,50 @@ internal static class ClientObjectHooks
|
|||
/// All other stypes fall through to CBaseQualities::InqInt.
|
||||
/// Common stypes: LOCATIONS=9, CURRENT_WIELDED_LOCATION=10, STACK_SIZE=12, DAMAGE_TYPE=45.
|
||||
/// </summary>
|
||||
/// <summary>PWD offset for STypeInt properties stored in PublicWeenieDesc, or -1.</summary>
|
||||
private static int PwdOffsetForIntStype(uint stype) => stype switch
|
||||
{
|
||||
6 => PwdItemsCapacityOffset, // ITEMS_CAPACITY → _itemsCapacity
|
||||
7 => PwdContainersCapacityOffset, // CONTAINERS_CAPACITY → _containersCapacity
|
||||
9 => PwdValidLocationsOffset, // LOCATIONS → _valid_locations
|
||||
10 => PwdLocationOffset, // CURRENT_WIELDED_LOCATION → _location
|
||||
11 => PwdMaxStackSizeOffset, // MAX_STACK_SIZE → _maxStackSize
|
||||
12 => PwdStackSizeOffset, // STACK_SIZE → _stackSize
|
||||
131 => PwdMaterialTypeOffset, // MATERIAL_TYPE → _material_type
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
public static unsafe bool TryGetObjectIntProperty(uint objectId, uint stype, out int value)
|
||||
{
|
||||
value = 0;
|
||||
|
||||
// Stypes whose values live in PublicWeenieDesc are served from the PWD first: it is
|
||||
// network-populated and current, while the appraisal cache can be stale (a stack
|
||||
// size cached before a merge). On AC's main thread the PWD is read live; off-thread
|
||||
// it comes from the main-thread PWD snapshot (finding #24 forbids live reads there).
|
||||
int pwdOffset = PwdOffsetForIntStype(stype);
|
||||
if (pwdOffset >= 0)
|
||||
{
|
||||
bool gotPwd = MainThreadGuard.IsOnMainThread()
|
||||
? TryReadPwdInt32(objectId, pwdOffset, out int pwdValue)
|
||||
: TryGetPwdSnapshotInt(objectId, pwdOffset, out pwdValue);
|
||||
// A zero stack field means "not sent" — let a cached appraisal value fill it in.
|
||||
bool isStackField = stype is 11 or 12;
|
||||
if (gotPwd && (!isStackField || pwdValue > 0))
|
||||
{
|
||||
value = pwdValue;
|
||||
return true;
|
||||
}
|
||||
if (AppraisalHooks.TryGetCachedIntProperty(objectId, stype, out value))
|
||||
return true;
|
||||
if (gotPwd)
|
||||
{
|
||||
value = pwdValue;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Appraisal cache covers objects where m_pQualities is null (doors, inventory items, etc.)
|
||||
if (AppraisalHooks.TryGetCachedIntProperty(objectId, stype, out value))
|
||||
return true;
|
||||
|
|
@ -1909,68 +1989,13 @@ internal static class ClientObjectHooks
|
|||
return false;
|
||||
}
|
||||
|
||||
// Fast path: stypes whose values live in PublicWeenieDesc.
|
||||
// PWD starts at weenie + _phys_obj_offset + 4. Layout (Chorizite Weenie.cs:1734):
|
||||
// +28 _containerID, +32 _wielderID, +40 _valid_locations, +44 _location,
|
||||
// +48 _itemsCapacity, +52 _containersCapacity, +96 _stackSize, +100 _maxStackSize,
|
||||
// +148 _material_type
|
||||
// CBaseQualities::InqInt fails for inventory/corpse items (m_pQualities is null on pack wienies).
|
||||
// Any stype whose value lives in PWD must be served from here instead.
|
||||
int pwdFieldOffset = stype switch
|
||||
{
|
||||
6 => 48, // ITEMS_CAPACITY → _itemsCapacity
|
||||
7 => 52, // CONTAINERS_CAPACITY → _containersCapacity
|
||||
9 => 40, // LOCATIONS → _valid_locations
|
||||
10 => 44, // CURRENT_WIELDED_LOCATION → _location
|
||||
11 => 100, // MAX_STACK_SIZE → _maxStackSize
|
||||
12 => 96, // STACK_SIZE → _stackSize
|
||||
131 => 148, // MATERIAL_TYPE → _material_type (4 bytes, int)
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
// Deep-audit finding #24 (2026-06-18): this PWD fast path used to run
|
||||
// BEFORE the IsOnMainThread check below, dereferencing a weenie
|
||||
// pointer captured on a <=100ms-stale main-thread walk with raw
|
||||
// Marshal.ReadInt32. IsReadablePointer catches an unmapped page but
|
||||
// not a freed-then-reallocated one (TOCTOU) — off-thread that risks
|
||||
// feeding a garbage property value into loot/salvage logic. Hoisted
|
||||
// the gate up here (same place the InqInt fallback already gates) so
|
||||
// the fast path only ever runs on the main thread; off-thread
|
||||
// callers fall through to the appraisal cache only (already checked
|
||||
// above) rather than touching AC memory directly.
|
||||
// Deep-audit finding #24 (2026-06-18): never touch AC memory off-thread here. PWD-backed
|
||||
// stypes were handled above (live on the main thread, snapshot off-thread); InqInt
|
||||
// walks qualities and stays main-thread-only.
|
||||
if (!MainThreadGuard.IsOnMainThread())
|
||||
return false;
|
||||
|
||||
if (pwdFieldOffset >= 0 && _weeniePhysicsObjOffset >= 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr weeniePtr = _getWeenieObject(objectId);
|
||||
if (weeniePtr == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
int pwdBase = _weeniePhysicsObjOffset + 4;
|
||||
IntPtr fieldAddr = weeniePtr + pwdBase + pwdFieldOffset;
|
||||
// Page-probe BOTH ends of the 4-byte read span (mirrors
|
||||
// TryGetObjectOwnershipInfo's dual-end probe): a freed-but-decommitted
|
||||
// weenie whose field straddles a committed/decommitted page boundary is
|
||||
// an uncatchable AV under NativeAOT; the catch below only covers
|
||||
// null-page faults. All stypes served here are Marshal.ReadInt32
|
||||
// (4 bytes), so the span is [fieldAddr, fieldAddr+3].
|
||||
if (!IsReadablePointer(fieldAddr) || !IsReadablePointer(fieldAddr + 3))
|
||||
return false;
|
||||
|
||||
value = Marshal.ReadInt32(fieldAddr);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Fall through to CBaseQualities::InqInt for stypes not in PWD.
|
||||
// (IsOnMainThread already checked above, before the PWD fast path.)
|
||||
// CBaseQualities::InqInt for stypes not in PWD.
|
||||
if (_inqInt == null)
|
||||
{
|
||||
if (!Probe() || _inqInt == null)
|
||||
|
|
@ -2930,14 +2955,24 @@ internal static class ClientObjectHooks
|
|||
{
|
||||
_positionCache.Clear();
|
||||
_weeniePtrBack.Clear();
|
||||
_pwdBack.Clear();
|
||||
CObjectMaintHooks.EnumerateLiveWeenieObjectIds(_capturePositionDelegate);
|
||||
}
|
||||
|
||||
// Publish the freshly-walked id->weeniePtr map to off-thread readers
|
||||
// (GetWeenieObjectResolve). The swap is brief and is NOT held during
|
||||
// the walk, so the pump's resolver reads never stall on the walk.
|
||||
// Publish the freshly-walked id->weeniePtr map (GetWeenieObjectResolve) and the
|
||||
// PWD int snapshot (TryGetPwdSnapshotInt) to off-thread readers together. The
|
||||
// swap is brief and is NOT held during the walk, so pump reads never stall on it.
|
||||
lock (_weeniePtrSwapLock)
|
||||
{
|
||||
(_weeniePtrFront, _weeniePtrBack) = (_weeniePtrBack, _weeniePtrFront);
|
||||
(_pwdFront, _pwdBack) = (_pwdBack, _pwdFront);
|
||||
}
|
||||
|
||||
if (!_loggedPwdServe && _pwdFront.Count > 0)
|
||||
{
|
||||
_loggedPwdServe = true;
|
||||
RynthLog.Compat($"ClientObjectHooks: PWD int snapshot warm — {_pwdFront.Count} objects (stack size / max stack / container / location served off-thread).");
|
||||
}
|
||||
|
||||
if (!_loggedPositionServe && _positionCache.Count > 0)
|
||||
{
|
||||
|
|
@ -3023,6 +3058,82 @@ internal static class ClientObjectHooks
|
|||
// thread under _positionCacheLock; reads the live position and stores it.
|
||||
// Method group is cached in _capturePositionDelegate so the enumerate call
|
||||
// allocates no closure per frame.
|
||||
/// <summary>
|
||||
/// Copies the PublicWeenieDesc int fields of a freshly resolved (main-thread, live)
|
||||
/// weenie into <see cref="_pwdBack"/>. One VirtualQuery covers the whole +28..+151
|
||||
/// span when it sits in a single region (the normal case), so the 10 Hz walk stays
|
||||
/// cheap; a span crossing a region boundary is probed at both ends. Zero-alloc.
|
||||
/// </summary>
|
||||
private static void CapturePwdInts(uint id, IntPtr weeniePtr)
|
||||
{
|
||||
if (_weeniePhysicsObjOffset < 0)
|
||||
return;
|
||||
try
|
||||
{
|
||||
IntPtr pwd = weeniePtr + _weeniePhysicsObjOffset + 4;
|
||||
IntPtr first = pwd + PwdContainerIdOffset;
|
||||
IntPtr last = pwd + PwdMaterialTypeOffset + 3;
|
||||
if (!IsReadableRange(first, last))
|
||||
return;
|
||||
|
||||
_pwdBack[id] = new PwdIntEntry
|
||||
{
|
||||
ContainerId = Marshal.ReadInt32(pwd + PwdContainerIdOffset),
|
||||
WielderId = Marshal.ReadInt32(pwd + PwdWielderIdOffset),
|
||||
ValidLocations = Marshal.ReadInt32(pwd + PwdValidLocationsOffset),
|
||||
Location = Marshal.ReadInt32(pwd + PwdLocationOffset),
|
||||
ItemsCapacity = Marshal.ReadInt32(pwd + PwdItemsCapacityOffset),
|
||||
ContainersCapacity = Marshal.ReadInt32(pwd + PwdContainersCapacityOffset),
|
||||
StackSize = Marshal.ReadInt32(pwd + PwdStackSizeOffset),
|
||||
MaxStackSize = Marshal.ReadInt32(pwd + PwdMaxStackSizeOffset),
|
||||
MaterialType = Marshal.ReadInt32(pwd + PwdMaterialTypeOffset),
|
||||
};
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Unreadable descriptor: leave the id out of the snapshot (readers fail closed).
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when every byte in [first, last] is committed, readable memory.</summary>
|
||||
private static bool IsReadableRange(IntPtr first, IntPtr last)
|
||||
{
|
||||
if (VirtualQuery(first, out var mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0)
|
||||
return false;
|
||||
if (mbi.State != MEM_COMMIT || (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0)
|
||||
return false;
|
||||
long regionEnd = mbi.BaseAddress.ToInt64() + mbi.RegionSize.ToInt64();
|
||||
return last.ToInt64() < regionEnd || IsReadablePointer(last);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Off-thread read of a PWD int field from the main-thread snapshot. Returns false for
|
||||
/// offsets the snapshot doesn't carry or objects not seen by the last walk.
|
||||
/// </summary>
|
||||
private static bool TryGetPwdSnapshotInt(uint objectId, int pwdFieldOffset, out int value)
|
||||
{
|
||||
value = 0;
|
||||
PwdIntEntry e;
|
||||
lock (_weeniePtrSwapLock)
|
||||
{
|
||||
if (!_pwdFront.TryGetValue(objectId, out e))
|
||||
return false;
|
||||
}
|
||||
switch (pwdFieldOffset)
|
||||
{
|
||||
case PwdContainerIdOffset: value = e.ContainerId; return true;
|
||||
case PwdWielderIdOffset: value = e.WielderId; return true;
|
||||
case PwdValidLocationsOffset: value = e.ValidLocations; return true;
|
||||
case PwdLocationOffset: value = e.Location; return true;
|
||||
case PwdItemsCapacityOffset: value = e.ItemsCapacity; return true;
|
||||
case PwdContainersCapacityOffset: value = e.ContainersCapacity; return true;
|
||||
case PwdStackSizeOffset: value = e.StackSize; return true;
|
||||
case PwdMaxStackSizeOffset: value = e.MaxStackSize; return true;
|
||||
case PwdMaterialTypeOffset: value = e.MaterialType; return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void CapturePositionForId(uint id)
|
||||
{
|
||||
// Resolve natively here (we are on AC's main thread, so the CObjectMaint
|
||||
|
|
@ -3030,7 +3141,10 @@ internal static class ClientObjectHooks
|
|||
// via GetWeenieObjectResolve without walking AC's table itself.
|
||||
IntPtr weeniePtr = _getWeenieObjectNative != null ? _getWeenieObjectNative(id) : IntPtr.Zero;
|
||||
if (weeniePtr != IntPtr.Zero)
|
||||
{
|
||||
_weeniePtrBack[id] = weeniePtr;
|
||||
CapturePwdInts(id, weeniePtr);
|
||||
}
|
||||
if (ReadObjectPositionLive(id, out uint cell, out float x, out float y, out float z))
|
||||
_positionCache[id] = new PosEntry { Cell = cell, X = x, Y = y, Z = z };
|
||||
}
|
||||
|
|
|
|||
77
src/RynthCore.Engine/Compatibility/MergeStackResults.cs
Normal file
77
src/RynthCore.Engine/Compatibility/MergeStackResults.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Engine.Compatibility;
|
||||
|
||||
/// <summary>
|
||||
/// Outcome of the most recent <see cref="ClientHelperHooks.MergeStackInternal"/> request per
|
||||
/// (source, target) pair, so a plugin can learn what happened on AC's main thread instead of
|
||||
/// only "queued". Before this, a merge the engine skipped (target already full) or that AC
|
||||
/// rejected looked identical to one in flight, and RynthAi's AutoStack waited 10 s per pair
|
||||
/// and logged a "confirmed failure". Thread-safe; bounded.
|
||||
/// </summary>
|
||||
internal static class MergeStackResults
|
||||
{
|
||||
// ABI status codes (GetMergeStackResult return value). Never renumber.
|
||||
public const int None = 0; // no request recorded for this pair (or it aged out)
|
||||
public const int Queued = 1; // accepted onto the main-thread queue, not executed yet
|
||||
public const int Sent = 2; // Event_StackableMerge sent for 'amount' units
|
||||
public const int TargetFull = 3; // skipped: target stack already at max stack size
|
||||
public const int Failed = 4; // invalid ids, merge API unavailable, AC returned 0, or threw
|
||||
public const int QueueFull = 5; // main-thread queue full; request dropped before execution
|
||||
|
||||
private struct Entry { public int Status; public int Amount; public long TickMs; }
|
||||
|
||||
private const int MaxEntries = 512; // prune threshold
|
||||
private const long PruneAgeMs = 120_000; // results older than this are dropped on prune
|
||||
|
||||
private static readonly object _lock = new();
|
||||
private static readonly Dictionary<ulong, Entry> _results = new();
|
||||
|
||||
private static ulong Key(uint source, uint target) => ((ulong)source << 32) | target;
|
||||
|
||||
/// <summary>Records the latest outcome for a pair (replaces any earlier one).</summary>
|
||||
public static void Record(uint source, uint target, int status, int amount = 0)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_results.Count >= MaxEntries)
|
||||
Prune(now);
|
||||
_results[Key(source, target)] = new Entry { Status = status, Amount = amount, TickMs = now };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Latest outcome for the pair, or <see cref="None"/>. <paramref name="amount"/>
|
||||
/// is the unit count sent (Sent only) and <paramref name="ageMs"/> how long ago it was recorded.</summary>
|
||||
public static int Get(uint source, uint target, out int amount, out int ageMs)
|
||||
{
|
||||
amount = 0;
|
||||
ageMs = 0;
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_results.TryGetValue(Key(source, target), out Entry e))
|
||||
return None;
|
||||
amount = e.Amount;
|
||||
long age = Environment.TickCount64 - e.TickMs;
|
||||
ageMs = age > int.MaxValue ? int.MaxValue : (int)age;
|
||||
return e.Status;
|
||||
}
|
||||
}
|
||||
|
||||
// Drops aged results; if everything is recent, clears the map (callers re-request anyway).
|
||||
private static void Prune(long now)
|
||||
{
|
||||
List<ulong>? old = null;
|
||||
foreach (var kv in _results)
|
||||
if (now - kv.Value.TickMs > PruneAgeMs)
|
||||
(old ??= new List<ulong>()).Add(kv.Key);
|
||||
if (old == null)
|
||||
{
|
||||
_results.Clear();
|
||||
return;
|
||||
}
|
||||
foreach (ulong k in old)
|
||||
_results.Remove(k);
|
||||
}
|
||||
}
|
||||
|
|
@ -638,6 +638,14 @@ internal struct RynthCoreAPI
|
|||
/// Fills the state of the most recent VendorBuy/VendorSell request. Returns 1 if a
|
||||
/// request has been made this session, 0 if not. Any thread. Requires API v67+.</summary>
|
||||
public IntPtr GetVendorTradeStatusFn;
|
||||
|
||||
/// <summary>Function pointer: int GetMergeStackResult(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs)
|
||||
/// Outcome of the latest MergeStackInternal(source, target) request: 0 none, 1 queued,
|
||||
/// 2 sent (amount = units sent), 3 skipped because the target was already full,
|
||||
/// 4 failed (invalid ids / AC rejected / threw), 5 dropped (main-thread queue full).
|
||||
/// ageMs = how long ago the outcome was recorded. Either out pointer may be null.
|
||||
/// Any thread. Requires API v68+. APPENDED-AT-END for ABI safety.</summary>
|
||||
public IntPtr GetMergeStackResultFn;
|
||||
}
|
||||
|
||||
// ─── Vendor trading ABI structs (v67) ───────────────────────────────────
|
||||
|
|
@ -739,7 +747,7 @@ internal unsafe struct VendorTradeStatusNative
|
|||
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
|
||||
internal static class PluginContractVersion
|
||||
{
|
||||
public const uint Current = 67;
|
||||
public const uint Current = 68; // v68: GetMergeStackResult
|
||||
}
|
||||
|
||||
internal static class ClientActionHookFlags
|
||||
|
|
@ -1206,3 +1214,4 @@ internal unsafe delegate uint VendorSellCallbackDelegate(uint vendorId, uint* it
|
|||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetVendorTradeStatusCallbackDelegate(VendorTradeStatusNative* status);
|
||||
internal unsafe delegate int GetMergeStackResultCallbackDelegate(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs);
|
||||
|
|
|
|||
|
|
@ -239,6 +239,7 @@ internal static class PluginManager
|
|||
private static VendorBuyCallbackDelegate? _vendorBuyCallback;
|
||||
private static VendorSellCallbackDelegate? _vendorSellCallback;
|
||||
private static GetVendorTradeStatusCallbackDelegate? _getVendorTradeStatusCallback;
|
||||
private static GetMergeStackResultCallbackDelegate? _getMergeStackResultCallback;
|
||||
private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback;
|
||||
private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback;
|
||||
private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback;
|
||||
|
|
@ -2462,6 +2463,7 @@ internal static class PluginManager
|
|||
_vendorBuyCallback ??= VendorBuyAction;
|
||||
_vendorSellCallback ??= VendorSellAction;
|
||||
_getVendorTradeStatusCallback ??= GetVendorTradeStatusAction;
|
||||
_getMergeStackResultCallback ??= GetMergeStackResultAction;
|
||||
|
||||
_api.Version = PluginContractVersion.Current;
|
||||
_api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback);
|
||||
|
|
@ -2578,6 +2580,7 @@ internal static class PluginManager
|
|||
_api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback);
|
||||
_api.VendorSellFn = Marshal.GetFunctionPointerForDelegate(_vendorSellCallback);
|
||||
_api.GetVendorTradeStatusFn = Marshal.GetFunctionPointerForDelegate(_getVendorTradeStatusCallback);
|
||||
_api.GetMergeStackResultFn = Marshal.GetFunctionPointerForDelegate(_getMergeStackResultCallback);
|
||||
}
|
||||
|
||||
private static void ProbeClientHooks()
|
||||
|
|
@ -3142,6 +3145,22 @@ internal static class PluginManager
|
|||
return ToAbiBool(ClientHelperHooks.MergeStackInternal(sourceObjectId, targetObjectId));
|
||||
}
|
||||
|
||||
// v68: outcome of the latest MergeStackInternal(source, target) (MergeStackResults codes).
|
||||
private static unsafe int GetMergeStackResultAction(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs)
|
||||
{
|
||||
try
|
||||
{
|
||||
int status = MergeStackResults.Get(sourceObjectId, targetObjectId, out int sent, out int age);
|
||||
if (amount != null) *amount = sent;
|
||||
if (ageMs != null) *ageMs = age;
|
||||
return status;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return MergeStackResults.None;
|
||||
}
|
||||
}
|
||||
|
||||
private static int GiveObjectTo(uint objectId, uint targetId, int amount)
|
||||
{
|
||||
return ToAbiBool(ClientHelperHooks.GiveObjectTo(objectId, targetId, amount));
|
||||
|
|
|
|||
|
|
@ -125,4 +125,5 @@ public struct RynthCoreApiNative
|
|||
public IntPtr VendorBuyFn; // uint VendorBuy(uint vendorId, VendorTradeEntryNative*, int count)
|
||||
public IntPtr VendorSellFn; // uint VendorSell(uint vendorId, uint* itemIds, int count)
|
||||
public IntPtr GetVendorTradeStatusFn; // int GetVendorTradeStatus(VendorTradeStatusNative*)
|
||||
public IntPtr GetMergeStackResultFn; // v68: int GetMergeStackResult(uint src, uint tgt, int* amount, int* ageMs)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ namespace RynthCore.PluginSdk;
|
|||
|
||||
public readonly unsafe struct RynthCoreHost
|
||||
{
|
||||
public const uint CurrentApiVersion = 67;
|
||||
public const uint CurrentApiVersion = 68; // v68: GetMergeStackResult
|
||||
|
||||
/// <summary>
|
||||
/// The oldest engine API a plugin built on this SDK loads on by default
|
||||
|
|
@ -129,6 +129,8 @@ public readonly unsafe struct RynthCoreHost
|
|||
public bool HasSendPluginCommand => _api.Version >= 64 && _api.SendPluginCommandFn != IntPtr.Zero;
|
||||
public bool HasGetObjectDataIdProperty => _api.Version >= 65 && _api.GetObjectDataIdPropertyFn != IntPtr.Zero;
|
||||
public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero;
|
||||
// Version-checked first: on an older engine the field lies past the end of its API table.
|
||||
public bool HasGetMergeStackResult => _api.Version >= 68 && _api.GetMergeStackResultFn != IntPtr.Zero;
|
||||
|
||||
// ─── Methods ────────────────────────────────────────────────────────────
|
||||
|
||||
|
|
@ -503,6 +505,37 @@ public readonly unsafe struct RynthCoreHost
|
|||
((delegate* unmanaged[Cdecl]<uint, uint, int>)_api.MergeStackInternalFn)(sourceObjectId, targetObjectId) != 0;
|
||||
}
|
||||
|
||||
/// <summary>Outcome codes returned by <see cref="GetMergeStackResult"/>.</summary>
|
||||
public static class MergeStackStatus
|
||||
{
|
||||
public const int None = 0; // no request recorded for this pair (or it aged out)
|
||||
public const int Queued = 1; // accepted onto AC's main-thread queue, not executed yet
|
||||
public const int Sent = 2; // merge sent to the server for 'amount' units
|
||||
public const int TargetFull = 3; // skipped: the target stack was already full
|
||||
public const int Failed = 4; // invalid ids, merge API unavailable, AC rejected, or threw
|
||||
public const int QueueFull = 5; // dropped: main-thread queue full
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What happened to the latest <see cref="MergeStackInternal"/> request for this pair
|
||||
/// (a <see cref="MergeStackStatus"/> code). <paramref name="amount"/> = units sent
|
||||
/// (Sent only); <paramref name="ageMs"/> = how long ago the outcome was recorded.
|
||||
/// Returns <see cref="MergeStackStatus.None"/> on engines older than API v68.
|
||||
/// </summary>
|
||||
public int GetMergeStackResult(uint sourceObjectId, uint targetObjectId, out int amount, out int ageMs)
|
||||
{
|
||||
amount = 0;
|
||||
ageMs = 0;
|
||||
if (!HasGetMergeStackResult)
|
||||
return MergeStackStatus.None;
|
||||
int a = 0, age = 0;
|
||||
int status = ((delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)_api.GetMergeStackResultFn)(
|
||||
sourceObjectId, targetObjectId, &a, &age);
|
||||
amount = a;
|
||||
ageMs = age;
|
||||
return status;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gives an item to an NPC or another player by sending the F7B1 give
|
||||
/// GameAction (CM_Inventory::Event_GiveObjectRequest). This is the correct
|
||||
|
|
|
|||
Loading…
Reference in a new issue