diff --git a/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs b/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs index 5afef9d..2bf83c5 100644 --- a/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs +++ b/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs @@ -267,6 +267,27 @@ internal static class AppraisalHooks } } + /// + /// v84 (GetObjectProperties): a copy of everything the object's last identify carried (with later + /// updates folded in) and its spell book, or false when it was never identified. Any thread. + /// + internal static bool TryCopyIdentify(uint guid, out PropertyBag? bag, out uint[]? spells) + { + bag = null; + spells = null; + lock (_cacheLock) + { + if (_bags.TryGetValue(guid, out PropertyBag? b)) + { + bag = new PropertyBag(); + bag.MergeFrom(b); + } + if (_spellIdCache.TryGetValue(guid, out uint[]? s)) + spells = (uint[])s.Clone(); + } + return bag != null || spells != null; + } + public static bool TryGetCachedInt64Property(uint guid, uint stype, out long value) { value = 0; diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index 6cb312a..8151693 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -1438,9 +1438,26 @@ internal static class ClientObjectHooks if (!TryGetPlayerQualitiesPtr(out IntPtr qualities) || qualities == IntPtr.Zero) return; IntPtr bq = qualities + CBaseQualitiesOffset; - if (!IsReadableSpan(bq, 0x24)) + PropertyBag? bag = WalkQualitiesBag(qualities, _qualitiesInt64Layout >= 0, _qualitiesFloatLayout >= 0); + if (bag == null) return; + VerifyQualitiesLayout(bq, bag); + if (_qualitiesInt64Layout < 0) bag.Int64s.Clear(); + if (_qualitiesFloatLayout < 0) bag.Floats.Clear(); + _playerQualities = new OwnedBag(playerId, bag); + } + + // Every table of one CACQualities' CBaseQualities, copied (MAIN THREAD ONLY; every node is + // page-checked before it is read). The int64 and float tables (8-byte values) only when asked: + // their node layout is verified once against AC's own readers (VerifyQualitiesLayout). + // Null when the CBaseQualities header isn't readable. + private static PropertyBag? WalkQualitiesBag(IntPtr qualities, bool int64s, bool floats) + { + IntPtr bq = qualities + CBaseQualitiesOffset; + if (!IsReadableSpan(bq, 0x24)) + return null; + var bag = new PropertyBag(); WalkQualitiesTable(Marshal.ReadIntPtr(bq + 0x08), 8, (k, n) => bag.Ints[k] = Marshal.ReadInt32(n + 4)); WalkQualitiesTable(Marshal.ReadIntPtr(bq + 0x10), 8, (k, n) => bag.Bools[k] = Marshal.ReadInt32(n + 4) != 0); @@ -1454,19 +1471,127 @@ internal static class ClientObjectHooks if (len > 1 && len < 4096 && IsReadableSpan(buf + 20, len - 1)) bag.Strings[k] = Marshal.PtrToStringAnsi(buf + 20, len - 1) ?? string.Empty; }); - if (_qualitiesInt64Layout >= 0) + if (int64s) WalkQualitiesTable(Marshal.ReadIntPtr(bq + 0x0C), 16, (k, n) => bag.Int64s[k] = Marshal.ReadInt64(n + 8)); - if (_qualitiesFloatLayout >= 0) + if (floats) WalkQualitiesTable(Marshal.ReadIntPtr(bq + 0x14), 16, (k, n) => { double v = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(n + 8)); if (double.IsFinite(v)) bag.Floats[k] = v; }); + return bag; + } - VerifyQualitiesLayout(bq, bag); - if (_qualitiesInt64Layout < 0) bag.Int64s.Clear(); - if (_qualitiesFloatLayout < 0) bag.Floats.Clear(); - _playerQualities = new OwnedBag(playerId, bag); + // ── v84: every property of one object (GetObjectProperties, ObjectPropertyDump) ── + // The client's qualities tables of any object, read on AC's main thread: live when the call + // is made there, else the plugin's request is served at the next main-thread tick + // (ServeObjectQualitiesRequest, next to PrefetchPlayerStats) and the copy answers off-thread + // for a few seconds. One object at a time: it is a diagnostic (/ub propertydump). + private sealed record ObjectQualities(uint Owner, PropertyBag? Bag, long AtMs); + private static volatile ObjectQualities? _objectQualities; + private static uint _objectQualitiesRequest; + private const long ObjectQualitiesKeepMs = 5000, ObjectQualitiesRefreshMs = 500; + + /// + /// v84: the client's qualities tables of (null: it has none, or + /// not read yet). Off AC's main thread a walk is requested and is + /// set until the first copy for this object exists. Never touches AC memory off the main thread. + /// The bag returned is never changed afterwards (callers only read it). + /// + internal static PropertyBag? GetObjectQualitiesForDump(uint objectId, out bool pending, out bool read) + { + pending = false; + read = false; + if (objectId == 0) + return null; + if (MainThreadGuard.IsOnMainThread()) + { + PropertyBag? live = TryWalkObjectQualitiesLive(objectId); + read = live != null; + return live; + } + long now = Environment.TickCount64; + ObjectQualities? q = _objectQualities; + if (q != null && q.Owner == objectId && now - q.AtMs <= ObjectQualitiesKeepMs) + { + if (now - q.AtMs > ObjectQualitiesRefreshMs) + System.Threading.Volatile.Write(ref _objectQualitiesRequest, objectId); + read = q.Bag != null; + return q.Bag; + } + System.Threading.Volatile.Write(ref _objectQualitiesRequest, objectId); + pending = true; + return null; + } + + /// v84: serves a plugin's qualities request (MAIN THREAD; returns at once when there is none). + public static void ServeObjectQualitiesRequest() + { + if (System.Threading.Volatile.Read(ref _objectQualitiesRequest) == 0 || !MainThreadGuard.IsOnMainThread()) + return; + uint id = System.Threading.Interlocked.Exchange(ref _objectQualitiesRequest, 0); + if (id == 0) + return; + PropertyBag? bag = null; + try { bag = TryWalkObjectQualitiesLive(id); } + catch (Exception ex) { RynthLog.Compat($"Compat: object qualities walk 0x{id:X8} failed - {ex.GetType().Name}: {ex.Message}"); } + _objectQualities = new ObjectQualities(id, bag, Environment.TickCount64); + } + + /// Logout: the copy belongs to the session that ended. + internal static void ClearObjectQualities() + { + _objectQualities = null; + System.Threading.Volatile.Write(ref _objectQualitiesRequest, 0); + } + + // MAIN THREAD ONLY: a freshly resolved weenie (never a cached pointer), its qualities pointer, + // then the page-checked table walk. Int64 / float tables only once their node layout was + // verified on the player's own tables. + private static PropertyBag? TryWalkObjectQualitiesLive(uint objectId) + { + if (!MainThreadGuard.IsOnMainThread()) + return null; + if (_getWeenieObject == null) + { + if (!Probe() || _getWeenieObject == null) + return null; + } + try + { + IntPtr weeniePtr; + if (SehTrampoline.IsAvailable) + { + weeniePtr = SehTrampoline.CdeclPtrUint(_getWeenieObjectPtr, objectId, out bool av); + if (av) + return null; + } + else + { + weeniePtr = _getWeenieObject(objectId); + } + if (weeniePtr == IntPtr.Zero || !TryGetQualitiesPtr(weeniePtr, out IntPtr qualities) || qualities == IntPtr.Zero) + return null; + // Only a real CACQualities (the vtable learned from the player's): no AC calls are made + // here, but a sibling object in the qualities slot would read as garbage properties. + if (!IsCacQualitiesObject(qualities)) + return null; + return WalkQualitiesBag(qualities, _qualitiesInt64Layout == 1, _qualitiesFloatLayout == 1); + } + catch + { + return null; + } + } + + /// v84: the CreateObject copy's fields of as properties (the ~0.1 s + /// old PublicWeenieDesc snapshot). False when the last walk didn't see it. Any thread; never touches AC. + internal static bool CopyCreateDataProperties(uint objectId, PropertyBag dst) + { + if (!TryGetPwdSnapshot(objectId, out PwdEntry e)) + return false; + PwdLayout.FillBag(e.Bytes, dst); + return true; } // The 8-byte node layout is checked once against AC's own readers: a walked value must diff --git a/src/RynthCore.Engine/Compatibility/ObjectPropertyDump.cs b/src/RynthCore.Engine/Compatibility/ObjectPropertyDump.cs new file mode 100644 index 0000000..42633aa --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ObjectPropertyDump.cs @@ -0,0 +1,53 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ObjectPropertyDump.cs +// +// Plugin API v84 (GetObjectProperties): gathers every property the engine +// knows for one object and encodes it (ObjectPropertyRecord). Sources: +// - the CreateObject copy (PublicWeenieDesc snapshot, ~0.1 s old); +// - the client's own qualities tables (CBaseQualities), walked on AC's main +// thread (live there; off it, requested for the next main-thread tick); +// - the last identify (all six tables + profile values, spell book); +// - the server's public property updates, and for the player its own record +// (PlayerDescription + private updates) and the 1 s qualities snapshot. +// Off the main thread nothing here touches AC memory: every source is a copy. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +internal static class ObjectPropertyDump +{ + /// The record for , or null when the engine knows nothing about it. + public static byte[]? Collect(uint objectId) + { + if (objectId == 0) + return null; + + uint me = ClientHelperHooks.GetPlayerId(); + bool isPlayer = me != 0 && me == objectId; + ObjectPropertyFlags flags = isPlayer ? ObjectPropertyFlags.IsPlayer : ObjectPropertyFlags.None; + + var createData = new PropertyBag(); + bool hasCreate = ClientObjectHooks.CopyCreateDataProperties(objectId, createData); + if (hasCreate) flags |= ObjectPropertyFlags.HasCreateData; + + PropertyBag? qualities = ClientObjectHooks.GetObjectQualitiesForDump(objectId, out bool pending, out bool read); + if (read) flags |= ObjectPropertyFlags.QualitiesRead; + if (pending) flags |= ObjectPropertyFlags.QualitiesPending; + if (isPlayer && qualities == null) + qualities = ClientObjectHooks.PlayerQualitiesSnapshot(objectId); // never changed once published + + AppraisalHooks.TryCopyIdentify(objectId, out PropertyBag? identify, out uint[]? spells); + PropertyBag? updates = PropertyUpdateHooks.CopyPublicUpdates(objectId); + PropertyBag? self = isPlayer ? PropertyUpdateHooks.CopySelf() : null; + + if (AppraisalHooks.HasAppraisalData(objectId)) flags |= ObjectPropertyFlags.HasIdData; + long lastId = AppraisalHooks.GetLastIdTime(objectId); + + PropertyBag all = ObjectPropertyRecord.Combine(isPlayer, hasCreate ? createData : null, qualities, identify, updates, self); + if (all.Count == 0 && (spells == null || spells.Length == 0) && !hasCreate && !pending) + return null; + return ObjectPropertyRecord.Encode(all, spells, flags, lastId); + } +} diff --git a/src/RynthCore.Engine/Compatibility/ObjectPropertyRecord.cs b/src/RynthCore.Engine/Compatibility/ObjectPropertyRecord.cs new file mode 100644 index 0000000..9fee3e9 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ObjectPropertyRecord.cs @@ -0,0 +1,181 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ObjectPropertyRecord.cs +// +// Plugin API v84 (GetObjectProperties): every property the engine knows for +// one object, as one compact buffer the SDK turns into a dictionary per type +// (RynthCore.PluginSdk ObjectProperties.TryParse). Pure: no AC memory, no +// engine state, so tools\ObjectPropertyTests compiles it in with the SDK's +// parser and round-trips it. +// +// Before v84 a plugin could only ask for one key at a time, so RynthAi's +// /ub propertydump probed fixed ranges (int 0-400, bool 0-300, ...) and missed +// every key outside them, had no spell book and no names for int64 / float / +// data id / instance id properties. UtilityBelt prints every key Decal holds. +// +// Record (little-endian): +// +0 u32 magic 0x31445052 ("RPD1") +// +4 u16 format version (1) +// +6 u16 flags (ObjectPropertyFlags) +// +8 i64 last identify time, Unix seconds (0 never identified) +// +16 u32 entry count +// +20 entries, sorted by kind then key: +// u8 kind (PropertyKind 0-6, 7 = a spell of the spell book), u32 key, value: +// Int i32 | Int64 i64 | Bool u8 | Float f64 | String u16 byte count + UTF-8 | +// DataId u32 | InstanceId u32 | Spell (no value; the key is the spell id) +// ============================================================================ + +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Engine.Compatibility; + +/// v84 record flags (the SDK's ObjectPropertyFlags has the same bits). +[Flags] +internal enum ObjectPropertyFlags : ushort +{ + None = 0, + /// The server answered an identify (appraisal) for the object this session. + HasIdData = 0x0001, + /// The client's own qualities tables of the object (CBaseQualities) were read in. + QualitiesRead = 0x0002, + /// Asked off AC's main thread: a walk of the object's qualities tables was requested for + /// the next main-thread tick. Ask again in a moment for the full set. + QualitiesPending = 0x0004, + /// The object is the player's character. + IsPlayer = 0x0008, + /// The client's CreateObject copy (PublicWeenieDesc snapshot) of the object was read in. + HasCreateData = 0x0010, +} + +internal static class ObjectPropertyRecord +{ + public const uint Magic = 0x31445052; // "RPD1" + public const ushort FormatVersion = 1; + public const int HeaderSize = 20; + public const byte KindSpell = 7; + /// Longest string kept (bytes of UTF-8); longer ones are cut at a character boundary. + public const int MaxStringBytes = 4096; + /// Most spells kept from a spell book. + public const int MaxSpells = 1024; + + /// + /// One object's properties from every source, in the order the per-key reads + /// (TryGetObject*Property / PropertyCaches) prefer them, so the dump shows what a per-key read + /// returns. Lowest first, later sources replace same-key values: + /// the player: CreateObject copy, last identify, client qualities, public updates, own record + /// (PlayerDescription + private updates); + /// any other: CreateObject copy, client qualities, public updates, last identify (instance + /// ids: the last identify, then public updates over it). + /// Then the client's own stack size and container / wielder win when set, as in the per-key reads. + /// Null sources are skipped. Never changes the sources. + /// + public static PropertyBag Combine(bool isPlayer, PropertyBag? createData, PropertyBag? qualities, + PropertyBag? identify, PropertyBag? publicUpdates, PropertyBag? self) + { + var all = new PropertyBag(); + if (createData != null) all.MergeFrom(createData); + if (isPlayer) + { + if (identify != null) all.MergeFrom(identify); + if (qualities != null) all.MergeFrom(qualities); + if (publicUpdates != null) all.MergeFrom(publicUpdates); + if (self != null) all.MergeFrom(self); + } + else + { + if (qualities != null) all.MergeFrom(qualities); + if (publicUpdates != null) all.MergeFrom(publicUpdates); + if (identify != null) all.MergeFrom(identify); + if (identify != null && publicUpdates != null) + foreach (var kv in publicUpdates.InstanceIds) all.InstanceIds[kv.Key] = kv.Value; + } + if (createData != null) + { + if (createData.Ints.TryGetValue(12, out int stack) && stack > 0) all.Ints[12] = stack; // StackSize + if (createData.InstanceIds.TryGetValue(2, out uint container) && container != 0) all.InstanceIds[2] = container; + if (createData.InstanceIds.TryGetValue(3, out uint wielder) && wielder != 0) all.InstanceIds[3] = wielder; + } + return all; + } + + /// Encodes the record (the layout above). Spells are kept in their spell book order, without repeats. + public static byte[] Encode(PropertyBag bag, IReadOnlyList? spells, ObjectPropertyFlags flags, long lastIdTime) + { + var strings = new List<(uint Key, byte[] Bytes)>(bag.Strings.Count); + foreach (uint key in SortedKeys(bag.Strings.Keys)) + strings.Add((key, Utf8Cut(bag.Strings[key] ?? string.Empty))); + + var spellList = new List(); + if (spells != null) + { + var seen = new HashSet(); + foreach (uint s in spells) + if (s != 0 && seen.Add(s) && spellList.Count < MaxSpells) spellList.Add(s); + } + + int count = bag.Ints.Count + bag.Int64s.Count + bag.Bools.Count + bag.Floats.Count + strings.Count + + bag.DataIds.Count + bag.InstanceIds.Count + spellList.Count; + int size = HeaderSize + + bag.Ints.Count * 9 + bag.Int64s.Count * 13 + bag.Bools.Count * 6 + bag.Floats.Count * 13 + + bag.DataIds.Count * 9 + bag.InstanceIds.Count * 9 + spellList.Count * 5; + foreach (var s in strings) size += 7 + s.Bytes.Length; + + byte[] buf = new byte[size]; + Span o = buf; + BinaryPrimitives.WriteUInt32LittleEndian(o, Magic); + BinaryPrimitives.WriteUInt16LittleEndian(o.Slice(4), FormatVersion); + BinaryPrimitives.WriteUInt16LittleEndian(o.Slice(6), (ushort)flags); + BinaryPrimitives.WriteInt64LittleEndian(o.Slice(8), lastIdTime); + BinaryPrimitives.WriteUInt32LittleEndian(o.Slice(16), (uint)count); + int p = HeaderSize; + + foreach (uint k in SortedKeys(bag.Ints.Keys)) + { p = Head(o, p, PropertyKind.Int, k); BinaryPrimitives.WriteInt32LittleEndian(o.Slice(p), bag.Ints[k]); p += 4; } + foreach (uint k in SortedKeys(bag.Int64s.Keys)) + { p = Head(o, p, PropertyKind.Int64, k); BinaryPrimitives.WriteInt64LittleEndian(o.Slice(p), bag.Int64s[k]); p += 8; } + foreach (uint k in SortedKeys(bag.Bools.Keys)) + { p = Head(o, p, PropertyKind.Bool, k); o[p++] = bag.Bools[k] ? (byte)1 : (byte)0; } + foreach (uint k in SortedKeys(bag.Floats.Keys)) + { p = Head(o, p, PropertyKind.Float, k); BinaryPrimitives.WriteInt64LittleEndian(o.Slice(p), BitConverter.DoubleToInt64Bits(bag.Floats[k])); p += 8; } + foreach (var s in strings) + { + p = Head(o, p, PropertyKind.String, s.Key); + BinaryPrimitives.WriteUInt16LittleEndian(o.Slice(p), (ushort)s.Bytes.Length); p += 2; + s.Bytes.CopyTo(o.Slice(p)); p += s.Bytes.Length; + } + foreach (uint k in SortedKeys(bag.DataIds.Keys)) + { p = Head(o, p, PropertyKind.DataId, k); BinaryPrimitives.WriteUInt32LittleEndian(o.Slice(p), bag.DataIds[k]); p += 4; } + foreach (uint k in SortedKeys(bag.InstanceIds.Keys)) + { p = Head(o, p, PropertyKind.InstanceId, k); BinaryPrimitives.WriteUInt32LittleEndian(o.Slice(p), bag.InstanceIds[k]); p += 4; } + foreach (uint s in spellList) + { o[p++] = KindSpell; BinaryPrimitives.WriteUInt32LittleEndian(o.Slice(p), s); p += 4; } + + return buf; + } + + private static int Head(Span o, int p, PropertyKind kind, uint key) + { + o[p] = (byte)kind; + BinaryPrimitives.WriteUInt32LittleEndian(o.Slice(p + 1), key); + return p + 5; + } + + private static List SortedKeys(Dictionary.KeyCollection keys) + { + var list = new List(keys); + list.Sort(); + return list; + } + + // UTF-8 of s, at most MaxStringBytes, never ending inside a character. + private static byte[] Utf8Cut(string s) + { + byte[] b = Encoding.UTF8.GetBytes(s); + if (b.Length <= MaxStringBytes) return b; + int n = MaxStringBytes; + while (n > 0 && (b[n] & 0xC0) == 0x80) n--; // b[n] starts the first character left out + return b.AsSpan(0, n).ToArray(); + } +} diff --git a/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs b/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs index 51824cb..157c3a3 100644 --- a/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs +++ b/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs @@ -145,6 +145,29 @@ internal static class PropertyUpdateHooks return _bags.TryGetValue(objectId, out PropertyBag? b) && b.InstanceIds.TryGetValue(stype, out value); } + /// v84 (GetObjectProperties): a copy of every public update the server sent for the object, or null. Any thread. + internal static PropertyBag? CopyPublicUpdates(uint objectId) + { + lock (_lock) + { + if (!_bags.TryGetValue(objectId, out PropertyBag? b)) return null; + var copy = new PropertyBag(); + copy.MergeFrom(b); + return copy; + } + } + + /// v84 (GetObjectProperties): a copy of the player's own record (PlayerDescription + private updates). Any thread. + internal static PropertyBag CopySelf() + { + lock (_lock) + { + var copy = new PropertyBag(); + copy.MergeFrom(_self); + return copy; + } + } + // The player's own record (PlayerDescription + private updates). public static bool TryGetSelfInt(uint stype, out int value) { lock (_lock) return _self.Ints.TryGetValue(stype, out value); } public static bool TryGetSelfInt64(uint stype, out long value) { lock (_lock) return _self.Int64s.TryGetValue(stype, out value); } @@ -196,6 +219,7 @@ internal static class PropertyUpdateHooks _selfDescribed = false; } ClientObjectHooks.ClearPlayerQualitiesSnapshot(); + ClientObjectHooks.ClearObjectQualities(); } // --- Wire entry points (AC's main thread, SmartBoxHooks.ParseGameEvent) --- diff --git a/src/RynthCore.Engine/Compatibility/PropertyWire.cs b/src/RynthCore.Engine/Compatibility/PropertyWire.cs index 4574c6c..98293c7 100644 --- a/src/RynthCore.Engine/Compatibility/PropertyWire.cs +++ b/src/RynthCore.Engine/Compatibility/PropertyWire.cs @@ -573,6 +573,28 @@ internal static class PwdLayout _ => -1, }; + /// v84: every property the CreateObject copy holds, for . + public static readonly uint[] IntStypes = { 1, 4, 5, 6, 7, 9, 10, 11, 12, 16, 18, 19, 50, 51, 91, 92, 94, 95, 131, 133, 151, 152, 280 }; + public static readonly uint[] DataIdStypes = { 8, 28, 50, 52 }; + public static readonly uint[] InstanceIdStypes = { 2, 3, 26, 32, 44 }; + + /// + /// v84 (GetObjectProperties): the CreateObject fields as properties, as the per-key readers + /// answer them (a zero field answers nothing). Float 280 (the engine's workmanship read) is + /// left out: it is no property id (workmanship is ItemWorkmanship, int 105, in the identify). + /// + public static void FillBag(ReadOnlySpan pwd, PropertyBag bag) + { + foreach (uint s in IntStypes) + if (TryGetInt(pwd, s, out int v)) bag.Ints[s] = v; + foreach (uint s in DataIdStypes) + if (TryGetDataId(pwd, s, out uint d)) bag.DataIds[s] = d; + foreach (uint s in InstanceIdStypes) + if (TryGetInstanceId(pwd, s, out uint i)) bag.InstanceIds[s] = i; + if (TryGetFloat(pwd, 54, out double r)) bag.Floats[54] = r; + if (TryGetFloat(pwd, 167, out double c)) bag.Floats[167] = c; + } + public static bool TryGetInt(ReadOnlySpan pwd, uint stype, out int value) { value = 0; diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index bbe9460..ec4de6e 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -329,6 +329,7 @@ internal static class EngineFrameController // Same main-thread guard: snapshot XP/luminance/deaths/vitae (main-thread-only // Inq* reads) so the GetEngineStatusJson host bridge can serve them off-thread (throttled). Compatibility.ClientObjectHooks.PrefetchPlayerStats(); + Compatibility.ClientObjectHooks.ServeObjectQualitiesRequest(); // v84 GetObjectProperties (none asked: one read) // Cold-login object backfill on the SAME AC main thread as the // skill prefetch above: deliver objects already present at login @@ -465,6 +466,7 @@ internal static class EngineFrameController Compatibility.ClientObjectHooks.PrefetchObjectIdentity(); Compatibility.ClientObjectHooks.PrefetchPositions(); Compatibility.ClientObjectHooks.PrefetchPlayerStats(); + Compatibility.ClientObjectHooks.ServeObjectQualitiesRequest(); // v84 GetObjectProperties (none asked: one read) try { Plugins.PluginManager.TrySeedLiveObjectsFromCObjectMaintOnce(); } catch (Exception ex) { RynthLog.Plugin($"CObjectMaint seed threw {ex.GetType().Name}: {ex.Message}"); } } diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 763cabc..34dd2ff 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -911,6 +911,17 @@ internal struct RynthCoreAPI /// it (checked again there). Returns 1 removed, 2 queued, 0 refused, -1 the client's /// DeleteObject isn't bound yet (no delete seen since the hook went in). Requires API v83+. public IntPtr RemoveClientObjectFn; + + /// v84: int GetObjectProperties(uint objectId, byte* buffer, int bufferSize): every + /// property the engine knows for the object (int, int64, bool, float, string, data id, instance id + /// and the spell book), merged from the client's CreateObject copy, its qualities tables (read on + /// AC's main thread), the last identify and the server's property updates, as one record + /// (Compatibility/ObjectPropertyRecord.cs; the SDK's ObjectProperties.TryParse reads it). Returns the + /// record's size in bytes; it was copied only when that is <= bufferSize (call again with a buffer + /// that big). 0 when the engine knows nothing about the object, -1 a zero id or a negative size. + /// Off AC's main thread a walk of the object's qualities tables is requested for the next tick + /// (flag QualitiesPending): ask again a moment later for the full set. Any thread. Requires API v84+. + public IntPtr GetObjectPropertiesFn; } /// v79 bits. @@ -1750,3 +1761,6 @@ internal delegate int GetObjectServerAgeCallbackDelegate(uint objectId); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int RemoveClientObjectCallbackDelegate(uint objectId); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetObjectPropertiesCallbackDelegate(uint objectId, byte* buffer, int bufferSize); diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index f84925e..0c3bb68 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -18,5 +18,6 @@ internal static class PluginContractVersion // v81: GetMergeStackResult (was v77 on QOL-items, then v80; renumbered after upstream's v77-v80). // v82: SalvageDirect (salvage without the salvage panel; was v81 on feature/salvage-direct). // v83: GetObjectServerAge and RemoveClientObject (ghost creatures, 2026-10-12). - public const uint Current = 83; + // v84: GetObjectProperties (every property of an object, for /ub propertydump; 2026-10-13). + public const uint Current = 84; } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 8965039..07de43d 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -269,6 +269,7 @@ internal static partial class PluginManager private static SalvageDirectCallbackDelegate? _salvageDirectCallback; // v82 private static GetObjectServerAgeCallbackDelegate? _getObjectServerAgeCallback; // v83 private static RemoveClientObjectCallbackDelegate? _removeClientObjectCallback; // v83 + private static GetObjectPropertiesCallbackDelegate? _getObjectPropertiesCallback; // v84 private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback; private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback; private static VendorBuyCallbackDelegate? _vendorBuyCallback; @@ -3056,6 +3057,7 @@ internal static partial class PluginManager unsafe { _salvageDirectCallback ??= SalvageDirectAction; } // v82 _getObjectServerAgeCallback ??= GetObjectServerAgeAction; // v83 _removeClientObjectCallback ??= RemoveClientObjectAction; // v83 + unsafe { _getObjectPropertiesCallback ??= GetObjectPropertiesAction; } // v84 _getVendorInfoCallback ??= GetVendorInfoAction; _getVendorItemsCallback ??= GetVendorItemsAction; _vendorBuyCallback ??= VendorBuyAction; @@ -3205,6 +3207,7 @@ internal static partial class PluginManager _api.SalvageDirectFn = Marshal.GetFunctionPointerForDelegate(_salvageDirectCallback); _api.GetObjectServerAgeFn = Marshal.GetFunctionPointerForDelegate(_getObjectServerAgeCallback); _api.RemoveClientObjectFn = Marshal.GetFunctionPointerForDelegate(_removeClientObjectCallback); + _api.GetObjectPropertiesFn = Marshal.GetFunctionPointerForDelegate(_getObjectPropertiesCallback); _api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback); _api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback); _api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback); @@ -4393,6 +4396,27 @@ internal static partial class PluginManager } } + // ── v84: every property of an object (ObjectPropertyDump) ── + + /// v84: see PluginContract.GetObjectPropertiesFn. + private static unsafe int GetObjectPropertiesAction(uint objectId, byte* buffer, int bufferSize) + { + try + { + if (objectId == 0 || bufferSize < 0 || (buffer == null && bufferSize > 0)) return -1; + byte[]? rec = Compatibility.ObjectPropertyDump.Collect(objectId); + if (rec == null) return 0; + if (rec.Length <= bufferSize) + rec.AsSpan().CopyTo(new Span(buffer, bufferSize)); + return rec.Length; + } + catch (Exception ex) + { + RynthLog.Compat($"GetObjectProperties 0x{objectId:X8} failed - {ex.GetType().Name}: {ex.Message}"); + return -1; + } + } + // ── v83: ghost creatures (ObjectFreshness, DeleteObjectHooks.RemoveClientObject) ── /// v83: see PluginContract.GetObjectServerAgeFn. diff --git a/src/RynthCore.PluginSdk/ObjectPropertyTypes.cs b/src/RynthCore.PluginSdk/ObjectPropertyTypes.cs new file mode 100644 index 0000000..91b3e33 --- /dev/null +++ b/src/RynthCore.PluginSdk/ObjectPropertyTypes.cs @@ -0,0 +1,125 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.PluginSdk; + +// ─── Every property of an object (engine API v84) ────────────────────────── +// RynthCoreHost.TryGetObjectProperties returns all the keys the engine holds for one object +// (what UtilityBelt's propertydump lists from Decal's WorldObject), not one key at a time: +// +// if (Host.TryGetObjectProperties(id, out ObjectProperties p)) +// foreach (var kv in p.Ints) Log($"{kv.Key} = {kv.Value}"); +// +// Item properties beyond the CreateObject basics only exist after an identify (RequestId): +// check p.HasIdData. Asked off AC's main thread, the client's own qualities tables are read at +// the next main-thread tick: when p.QualitiesPending is set, ask again ~0.2 s later. + +/// What was built from (the engine's record flags). +[Flags] +public enum ObjectPropertyFlags : ushort +{ + None = 0, + /// The server answered an identify (appraisal) for the object this session. + HasIdData = 0x0001, + /// The client's own qualities tables of the object were read in. + QualitiesRead = 0x0002, + /// A read of the client's qualities tables was requested for AC's next main-thread tick: ask again shortly. + QualitiesPending = 0x0004, + /// The object is the player's character. + IsPlayer = 0x0008, + /// The client's CreateObject copy of the object was read in. + HasCreateData = 0x0010, +} + +/// Every property of one object, a dictionary per AC property type (keys are the AC/ACE property ids). +public sealed class ObjectProperties +{ + public const uint RecordMagic = 0x31445052; // "RPD1" + public const ushort RecordVersion = 1; + private const int HeaderSize = 20; + private const byte KindInt = 0, KindInt64 = 1, KindBool = 2, KindFloat = 3, KindString = 4, + KindDataId = 5, KindInstanceId = 6, KindSpell = 7; + + public ObjectPropertyFlags Flags { get; private set; } + /// Unix seconds of the last identify answer; 0 never. + public long LastIdTime { get; private set; } + + public bool HasIdData => (Flags & ObjectPropertyFlags.HasIdData) != 0; + public bool QualitiesPending => (Flags & ObjectPropertyFlags.QualitiesPending) != 0; + public bool IsPlayer => (Flags & ObjectPropertyFlags.IsPlayer) != 0; + + public Dictionary Ints { get; } = new(); + public Dictionary Int64s { get; } = new(); + public Dictionary Bools { get; } = new(); + public Dictionary Floats { get; } = new(); + public Dictionary Strings { get; } = new(); + /// Data ids (STypeDID: icons, setups, spell, ...). + public Dictionary DataIds { get; } = new(); + /// Instance ids (STypeIID: container, wielder, owner, monarch, ...). + public Dictionary InstanceIds { get; } = new(); + /// The spell book from the last identify, in its order. + public List Spells { get; } = new(); + + public int Count => Ints.Count + Int64s.Count + Bools.Count + Floats.Count + Strings.Count + + DataIds.Count + InstanceIds.Count + Spells.Count; + + /// + /// Reads the engine's v84 record. False (and null) when it isn't + /// one: wrong magic, a newer format, or an entry that runs past the end. + /// + public static bool TryParse(ReadOnlySpan rec, out ObjectProperties? props) + { + props = null; + if (rec.Length < HeaderSize || BinaryPrimitives.ReadUInt32LittleEndian(rec) != RecordMagic) + return false; + if (BinaryPrimitives.ReadUInt16LittleEndian(rec.Slice(4)) != RecordVersion) + return false; + var p = new ObjectProperties + { + Flags = (ObjectPropertyFlags)BinaryPrimitives.ReadUInt16LittleEndian(rec.Slice(6)), + LastIdTime = BinaryPrimitives.ReadInt64LittleEndian(rec.Slice(8)), + }; + uint count = BinaryPrimitives.ReadUInt32LittleEndian(rec.Slice(16)); + int o = HeaderSize; + for (uint i = 0; i < count; i++) + { + if (o + 5 > rec.Length) return false; + byte kind = rec[o]; + uint key = BinaryPrimitives.ReadUInt32LittleEndian(rec.Slice(o + 1)); + o += 5; + int need = kind switch + { + KindInt or KindDataId or KindInstanceId => 4, + KindInt64 or KindFloat => 8, + KindBool => 1, + KindString => 2, + KindSpell => 0, + _ => -1, + }; + if (need < 0 || o + need > rec.Length) return false; + switch (kind) + { + case KindInt: p.Ints[key] = BinaryPrimitives.ReadInt32LittleEndian(rec.Slice(o)); break; + case KindInt64: p.Int64s[key] = BinaryPrimitives.ReadInt64LittleEndian(rec.Slice(o)); break; + case KindBool: p.Bools[key] = rec[o] != 0; break; + case KindFloat: p.Floats[key] = BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64LittleEndian(rec.Slice(o))); break; + case KindDataId: p.DataIds[key] = BinaryPrimitives.ReadUInt32LittleEndian(rec.Slice(o)); break; + case KindInstanceId: p.InstanceIds[key] = BinaryPrimitives.ReadUInt32LittleEndian(rec.Slice(o)); break; + case KindSpell: p.Spells.Add(key); break; + case KindString: + { + int len = BinaryPrimitives.ReadUInt16LittleEndian(rec.Slice(o)); + if (o + 2 + len > rec.Length) return false; + p.Strings[key] = Encoding.UTF8.GetString(rec.Slice(o + 2, len)); + o += 2 + len; + continue; + } + } + o += need; + } + props = p; + return true; + } +} diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index bd054ad..6dfa0e0 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -172,6 +172,8 @@ public struct RynthCoreApiNative // v83: ghost creatures (objects the client draws but the server no longer has for this player) public IntPtr GetObjectServerAgeFn; // int GetObjectServerAge(uint id) -> ms since the server's last message about it, -1 none public IntPtr RemoveClientObjectFn; // int RemoveClientObject(uint id) -> 1 removed, 2 queued, 0 refused, -1 unbound + // v84: every property of an object (/ub propertydump), one record (ObjectProperties.TryParse) + public IntPtr GetObjectPropertiesFn; // int GetObjectProperties(uint id, byte* buf, int size) -> record size (copied if <= size), 0 unknown, -1 bad args } /// diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index e039025..c8bf994 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -176,6 +176,9 @@ public readonly unsafe struct RynthCoreHost /// v83: (drop a ghost creature from the client). public bool HasRemoveClientObject => _api.Version >= 83 && _api.RemoveClientObjectFn != IntPtr.Zero; + + /// v84: (every property of an object at once). + public bool HasGetObjectProperties => _api.Version >= 84 && _api.GetObjectPropertiesFn != 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 >= 81 && _api.GetMergeStackResultFn != IntPtr.Zero; @@ -1919,6 +1922,37 @@ public readonly unsafe struct RynthCoreHost ? ((delegate* unmanaged[Cdecl])_api.RemoveClientObjectFn)(objectId) : -2; + // ─── Every property of an object (API v84) ───────────────────────────── + + /// + /// v84: every property the engine knows for (int, int64, bool, + /// float, string, data id, instance id and the spell book), merged from the client's + /// CreateObject copy, its qualities tables, the last identify and the server's property + /// updates, the way the per-key reads (TryGetObjectIntProperty, ...) answer. False on an + /// engine before v84 (fall back to per-key reads) or when the engine knows nothing about + /// the object. Item details need an identify first (, then + /// ). When + /// is set, the client's qualities tables are read at AC's next main-thread tick: ask again + /// shortly. Any thread. + /// + public bool TryGetObjectProperties(uint objectId, out ObjectProperties? properties) + { + properties = null; + if (!HasGetObjectProperties || objectId == 0) return false; + var fn = (delegate* unmanaged[Cdecl])_api.GetObjectPropertiesFn; + byte[] buffer = new byte[8192]; + for (int attempt = 0; attempt < 4; attempt++) + { + int n; + fixed (byte* p = buffer) n = fn(objectId, p, buffer.Length); + if (n <= 0) return false; + if (n <= buffer.Length) + return ObjectProperties.TryParse(new ReadOnlySpan(buffer, 0, n), out properties); + buffer = new byte[Math.Max(n + 1024, buffer.Length * 2)]; // grew between calls: some room + } + return false; + } + public int SalvageDirect(uint toolId, ReadOnlySpan itemIds) { if (!HasSalvageDirect) return -2; diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets index 51a99bd..bbb2dfd 100644 --- a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -33,7 +33,7 @@ - 83 + 84 <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true diff --git a/tools/ObjectPropertyTests/ObjectPropertyTests.csproj b/tools/ObjectPropertyTests/ObjectPropertyTests.csproj new file mode 100644 index 0000000..5d8dbe2 --- /dev/null +++ b/tools/ObjectPropertyTests/ObjectPropertyTests.csproj @@ -0,0 +1,33 @@ + + + + + Exe + net10.0-windows + enable + enable + true + ObjectPropertyTests + + + + + + + + + + + + diff --git a/tools/ObjectPropertyTests/Program.cs b/tools/ObjectPropertyTests/Program.cs new file mode 100644 index 0000000..977b563 --- /dev/null +++ b/tools/ObjectPropertyTests/Program.cs @@ -0,0 +1,209 @@ +using System.Buffers.Binary; +using RynthCore.Engine.Compatibility; +using EngineFlags = RynthCore.Engine.Compatibility.ObjectPropertyFlags; +using SdkFlags = RynthCore.PluginSdk.ObjectPropertyFlags; +using SdkProps = RynthCore.PluginSdk.ObjectProperties; + +namespace ObjectPropertyTests; + +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + Run("record: every type round-trips engine encoder -> SDK parser", RoundTrip); + Run("record: header, flags and the sorted, de-duplicated layout", HeaderAndLayout); + Run("record: long strings are cut on a character boundary", LongStrings); + Run("record: an empty object, and malformed records are refused", EmptyAndMalformed); + Run("merge: another object prefers its identify, instance ids its updates", MergeOther); + Run("merge: the player prefers its own record, then updates, qualities, identify", MergePlayer); + Run("merge: the client's stack size, container and wielder win when set", MergeCreateOverrides); + Run("create data: the PublicWeenieDesc fields come out as their properties", CreateDataFill); + Run("flags: engine and SDK bits agree", FlagParity); + Console.WriteLine($"{_checks} check(s), {_failed} failed."); + return _failed == 0 ? 0 : 1; + } + + private static void Run(string name, Action test) + { + _case = name; + int before = _failed; + try { test(); } + catch (Exception ex) { Fail($"threw {ex.GetType().Name}: {ex.Message}"); } + Console.WriteLine($"[{(_failed == before ? "PASS" : "FAIL")}] {name}"); + } + + private static void Check(bool ok, string what) { _checks++; if (!ok) Fail(what); } + private static void Fail(string what) { _failed++; Console.WriteLine($" FAIL {_case}: {what}"); } + + private static SdkProps Parse(byte[] rec) + { + Check(SdkProps.TryParse(rec, out SdkProps? p) && p != null, "the SDK parses the engine's record"); + return p ?? throw new InvalidOperationException("no parse"); + } + + private static PropertyBag SampleBag() + { + var b = new PropertyBag(); + b.Ints[1] = 2; // ItemType Armor + b.Ints[9015] = -7; // a key no fixed probe range reached (ACE InventoryOrder) + b.Ints[19] = 12345; + b.Int64s[4] = 1_000_000_000_000L; // ItemTotalXp + b.Bools[22] = true; + b.Bools[69] = false; + b.Floats[13] = 1.25; // ArmorModVsSlash + b.Floats[5] = -0.0333; + b.Strings[1] = "Olthoi Amuli Coat"; + b.Strings[16] = "Grün — été"; // non-ASCII survives + b.Strings[7] = ""; + b.DataIds[8] = 0x06001234; // Icon + b.DataIds[8044] = 0xFFFFFFFF; + b.InstanceIds[2] = 0x50000001; + b.InstanceIds[38] = 0x80000ABC; + return b; + } + + private static void RoundTrip() + { + PropertyBag b = SampleBag(); + uint[] spells = { 2783, 4400, 6055 }; + byte[] rec = ObjectPropertyRecord.Encode(b, spells, EngineFlags.HasIdData | EngineFlags.QualitiesRead, 1_760_000_000L); + SdkProps p = Parse(rec); + Check(p.Ints.Count == 3 && p.Ints[1] == 2 && p.Ints[9015] == -7 && p.Ints[19] == 12345, "ints"); + Check(p.Int64s.Count == 1 && p.Int64s[4] == 1_000_000_000_000L, "int64s"); + Check(p.Bools.Count == 2 && p.Bools[22] && !p.Bools[69], "bools"); + Check(p.Floats.Count == 2 && p.Floats[13] == 1.25 && p.Floats[5] == -0.0333, "floats (exact doubles)"); + Check(p.Strings.Count == 3 && p.Strings[1] == "Olthoi Amuli Coat" && p.Strings[16] == "Grün — été" && p.Strings[7] == "", "strings (UTF-8, empty)"); + Check(p.DataIds.Count == 2 && p.DataIds[8] == 0x06001234 && p.DataIds[8044] == 0xFFFFFFFF, "data ids"); + Check(p.InstanceIds.Count == 2 && p.InstanceIds[2] == 0x50000001 && p.InstanceIds[38] == 0x80000ABC, "instance ids"); + Check(p.Spells.SequenceEqual(spells), "spells in spell book order"); + Check(p.HasIdData && !p.QualitiesPending && !p.IsPlayer && (p.Flags & SdkFlags.QualitiesRead) != 0, "flags"); + Check(p.LastIdTime == 1_760_000_000L, "last id time"); + Check(p.Count == b.Count + spells.Length, $"count {p.Count}"); + } + + private static void HeaderAndLayout() + { + var b = new PropertyBag(); + b.Ints[300] = 3; b.Ints[2] = 1; b.Ints[45] = 2; + byte[] rec = ObjectPropertyRecord.Encode(b, new uint[] { 9, 0, 9, 7 }, EngineFlags.IsPlayer, 0); + Check(BinaryPrimitives.ReadUInt32LittleEndian(rec) == SdkProps.RecordMagic && SdkProps.RecordMagic == ObjectPropertyRecord.Magic, "magic"); + Check(BinaryPrimitives.ReadUInt16LittleEndian(rec.AsSpan(4)) == SdkProps.RecordVersion && ObjectPropertyRecord.FormatVersion == SdkProps.RecordVersion, "version"); + Check(BinaryPrimitives.ReadUInt32LittleEndian(rec.AsSpan(16)) == 5, "entry count 3 ints + 2 spells (0 and the repeat dropped)"); + // Ints sorted by key: 2, 45, 300. + uint k0 = BinaryPrimitives.ReadUInt32LittleEndian(rec.AsSpan(ObjectPropertyRecord.HeaderSize + 1)); + uint k1 = BinaryPrimitives.ReadUInt32LittleEndian(rec.AsSpan(ObjectPropertyRecord.HeaderSize + 9 + 1)); + uint k2 = BinaryPrimitives.ReadUInt32LittleEndian(rec.AsSpan(ObjectPropertyRecord.HeaderSize + 18 + 1)); + Check(k0 == 2 && k1 == 45 && k2 == 300, $"sorted keys {k0},{k1},{k2}"); + Check(rec.Length == ObjectPropertyRecord.HeaderSize + 3 * 9 + 2 * 5, $"size {rec.Length}"); + SdkProps p = Parse(rec); + Check(p.IsPlayer && p.Spells.SequenceEqual(new uint[] { 9, 7 }), "player flag, spells 9 then 7"); + } + + private static void LongStrings() + { + var b = new PropertyBag(); + b.Strings[16] = new string('a', ObjectPropertyRecord.MaxStringBytes - 1) + "€€"; // 3-byte euro across the cut + b.Strings[1] = new string('x', 100_000); + SdkProps p = Parse(ObjectPropertyRecord.Encode(b, null, EngineFlags.None, 0)); + Check(p.Strings[16] == new string('a', ObjectPropertyRecord.MaxStringBytes - 1), "cut before a character that doesn't fit, never inside it"); + Check(p.Strings[1].Length == ObjectPropertyRecord.MaxStringBytes, "ASCII cut at the cap"); + } + + private static void EmptyAndMalformed() + { + byte[] rec = ObjectPropertyRecord.Encode(new PropertyBag(), null, EngineFlags.QualitiesPending, 0); + Check(rec.Length == ObjectPropertyRecord.HeaderSize, "empty record = header only"); + SdkProps p = Parse(rec); + Check(p.Count == 0 && p.QualitiesPending, "empty, pending"); + + byte[] full = ObjectPropertyRecord.Encode(SampleBag(), new uint[] { 1 }, EngineFlags.None, 0); + Check(!SdkProps.TryParse(full.AsSpan(0, full.Length - 1), out _), "truncated by one byte refused"); + Check(!SdkProps.TryParse(full.AsSpan(0, 10), out _), "shorter than the header refused"); + byte[] bad = (byte[])full.Clone(); bad[0] ^= 0xFF; + Check(!SdkProps.TryParse(bad, out _), "wrong magic refused"); + byte[] newer = (byte[])full.Clone(); newer[4] = 2; + Check(!SdkProps.TryParse(newer, out _), "a newer format refused"); + byte[] kind = (byte[])full.Clone(); kind[ObjectPropertyRecord.HeaderSize] = 42; + Check(!SdkProps.TryParse(kind, out _), "unknown kind refused"); + } + + private static void MergeOther() + { + var create = new PropertyBag(); create.Ints[19] = 10; create.Ints[5] = 50; + var qual = new PropertyBag(); qual.Ints[19] = 20; qual.Ints[25] = 7; qual.InstanceIds[38] = 0xA; + var upd = new PropertyBag(); upd.Ints[19] = 30; upd.Ints[92] = 4; upd.InstanceIds[38] = 0xB; + var id = new PropertyBag(); id.Ints[19] = 40; id.Ints[92] = 5; id.Strings[16] = "long"; id.InstanceIds[38] = 0xC; + PropertyBag m = ObjectPropertyRecord.Combine(false, create, qual, id, upd, null); + Check(m.Ints[19] == 40 && m.Ints[92] == 5, "identify over updates over qualities over the create copy"); + Check(m.Ints[5] == 50 && m.Ints[25] == 7, "keys only one source has are kept"); + Check(m.InstanceIds[38] == 0xB, "instance ids: updates over identify (PropertyCaches.TryGetInstanceId)"); + Check(m.Strings[16] == "long", "strings"); + PropertyBag none = ObjectPropertyRecord.Combine(false, null, null, null, null, null); + Check(none.Count == 0, "no sources, nothing"); + Check(create.Ints[19] == 10 && id.Ints[19] == 40 && qual.Ints[19] == 20, "sources unchanged"); + } + + private static void MergePlayer() + { + var id = new PropertyBag(); id.Ints[25] = 1; id.Ints[1] = 1; + var qual = new PropertyBag(); qual.Ints[25] = 2; qual.Int64s[1] = 100; + var upd = new PropertyBag(); upd.Ints[25] = 3; upd.Int64s[1] = 200; + var self = new PropertyBag(); self.Ints[25] = 4; self.Strings[1] = "Me"; + PropertyBag m = ObjectPropertyRecord.Combine(true, null, qual, id, upd, self); + Check(m.Ints[25] == 4, "own record wins"); + Check(m.Int64s[1] == 200, "public updates over the qualities snapshot"); + Check(m.Ints[1] == 1 && m.Strings[1] == "Me", "the rest is kept"); + PropertyBag m2 = ObjectPropertyRecord.Combine(true, null, qual, id, null, null); + Check(m2.Ints[25] == 2, "qualities over the player's last identify"); + } + + private static void MergeCreateOverrides() + { + var create = new PropertyBag(); create.Ints[12] = 25; create.InstanceIds[2] = 0x500; create.InstanceIds[3] = 0; + var id = new PropertyBag(); id.Ints[12] = 1; id.InstanceIds[2] = 0x400; id.InstanceIds[3] = 0x600; + PropertyBag m = ObjectPropertyRecord.Combine(false, create, null, id, null, null); + Check(m.Ints[12] == 25, "the client's stack size wins (it follows every split and merge)"); + Check(m.InstanceIds[2] == 0x500, "the client's container wins"); + Check(m.InstanceIds[3] == 0x600, "a zero wielder in the create copy doesn't hide the identify's"); + } + + private static void CreateDataFill() + { + byte[] pwd = new byte[PwdLayout.Size]; + void U32(int off, uint v) => BinaryPrimitives.WriteUInt32LittleEndian(pwd.AsSpan(off), v); + U32(PwdLayout.Type, 0x10); // ItemType 1 + U32(PwdLayout.Value, 500); // Value 19 + U32(PwdLayout.Burden, 75); // EncumbranceVal 5 + U32(PwdLayout.StackSize, 3); // StackSize 12 + U32(PwdLayout.Icon, 0x06003355); // Icon (DID 8) + U32(PwdLayout.SpellId, 1234); // Spell (DID 28) + U32(PwdLayout.Container, 0x50000002);// Container (IID 2) + U32(PwdLayout.PetOwner, 0x50000003); // PetOwner (IID 44) + U32(PwdLayout.CooldownId, 9); // SharedCooldown (int 280) + BinaryPrimitives.WriteInt32LittleEndian(pwd.AsSpan(PwdLayout.UseRadius), BitConverter.SingleToInt32Bits(2.5f)); + BinaryPrimitives.WriteInt32LittleEndian(pwd.AsSpan(PwdLayout.Workmanship), BitConverter.SingleToInt32Bits(7.5f)); + var bag = new PropertyBag(); + PwdLayout.FillBag(pwd, bag); + Check(bag.Ints.Count == 5 && bag.Ints[1] == 0x10 && bag.Ints[19] == 500 && bag.Ints[5] == 75 && bag.Ints[12] == 3 && bag.Ints[280] == 9, "ints (zero fields answer nothing)"); + Check(bag.DataIds.Count == 2 && bag.DataIds[8] == 0x06003355 && bag.DataIds[28] == 1234, "data ids"); + Check(bag.InstanceIds.Count == 2 && bag.InstanceIds[2] == 0x50000002 && bag.InstanceIds[44] == 0x50000003, "instance ids"); + Check(bag.Floats.Count == 1 && bag.Floats[54] == 2.5, "UseRadius; the workmanship float (no property id) left out"); + foreach (uint s in PwdLayout.IntStypes) Check(PwdLayout.IntOffset(s) >= 0, $"int {s} has a PWD field"); + foreach (uint s in PwdLayout.DataIdStypes) Check(PwdLayout.DataIdOffset(s) >= 0, $"did {s} has a PWD field"); + foreach (uint s in PwdLayout.InstanceIdStypes) Check(PwdLayout.InstanceIdOffset(s) >= 0, $"iid {s} has a PWD field"); + int mapped = 0; + for (uint s = 0; s < 10000; s++) if (PwdLayout.IntOffset(s) >= 0) mapped++; + Check(mapped == PwdLayout.IntStypes.Length, $"every int the PWD maps is listed ({mapped} vs {PwdLayout.IntStypes.Length})"); + } + + private static void FlagParity() + { + foreach (EngineFlags f in Enum.GetValues()) + Check(Enum.GetName((SdkFlags)(ushort)f) == f.ToString(), $"bit 0x{(ushort)f:X4} is {f} on both sides"); + Check(Enum.GetValues().Length == Enum.GetValues().Length, "same number of flags"); + Check((byte)PropertyKind.InstanceId == 6 && ObjectPropertyRecord.KindSpell == 7, "kind numbers"); + } +} diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index 0813c05..c2b537b 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -474,27 +474,29 @@ internal static class Program Eq((int)Marshal.OffsetOf(f.Name), (int)Marshal.OffsetOf(f.Name), "TrainingEntryNative." + f.Name + " offset"); Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); - // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn end the table. - var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(3).TakeLast(6).ToArray(); + // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v84 follow). + var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(4).TakeLast(6).ToArray(); Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetContainerOrderFn", "PutItemInContainerFn", "GetMergeStackResultFn" }), "v79, v80 then v81 slots last: " + string.Join(",", names)); - var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(3).TakeLast(6).ToArray(); + var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(4).TakeLast(6).ToArray(); Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order"); } // v80: GetContainerOrder and PutItemInContainer come right before v81's slot, engine and SDK alike; - // v81: GetMergeStackResult, then v82: SalvageDirect is the table's last slot. The whole table has the same field names in the same + // v81: GetMergeStackResult, then v82: SalvageDirect, v83's two and v84's GetObjectProperties last. The whole table has the same field names in the same // order on both sides, and the same size. private static void ContainerOrderSlots() { var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray(); var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray(); // v81's GetMergeStackResultFn follows v80's two slots. - Check(names.SkipLast(4).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's, v82's and v83's: " + string.Join(",", names.SkipLast(4).TakeLast(2))); - Check(sdkNames.SkipLast(4).TakeLast(2).SequenceEqual(names.SkipLast(4).TakeLast(2)), "SDK v80 slots in the same order"); - Check(names.SkipLast(2).Last() == "SalvageDirectFn", "v82 slot before v83's"); - // v83: GetObjectServerAge and RemoveClientObject end the table (ghost creatures). - Check(names.TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots last: " + string.Join(",", names.TakeLast(2))); + Check(names.SkipLast(5).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's to v84's: " + string.Join(",", names.SkipLast(5).TakeLast(2))); + Check(sdkNames.SkipLast(5).TakeLast(2).SequenceEqual(names.SkipLast(5).TakeLast(2)), "SDK v80 slots in the same order"); + Check(names.SkipLast(3).Last() == "SalvageDirectFn", "v82 slot before v83's"); + // v83: GetObjectServerAge and RemoveClientObject (ghost creatures), then v84's slot. + Check(names.SkipLast(1).TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots before v84's: " + string.Join(",", names.SkipLast(1).TakeLast(2))); + // v84: GetObjectProperties ends the table (every property of an object, /ub propertydump). + Check(names.Last() == "GetObjectPropertiesFn", "v84 slot last: " + names.Last()); Check(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SequenceEqual(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name)), "SDK table has the engine's slots in the same order"); Eq(Marshal.SizeOf(), Marshal.SizeOf(), "SDK table size = engine table size"); Eq((int)Marshal.OffsetOf("PutItemInContainerFn"), @@ -505,6 +507,10 @@ internal static class Program Eq(RynthCore.PluginSdk.RynthCoreHost.MaxSalvageDirectItems, 100, "SalvageDirect item cap"); Eq((int)Marshal.OffsetOf("RemoveClientObjectFn"), (int)Marshal.OffsetOf("RemoveClientObjectFn"), "RemoveClientObjectFn offset"); + Eq((int)Marshal.OffsetOf("GetObjectPropertiesFn"), + (int)Marshal.OffsetOf("GetObjectPropertiesFn"), "GetObjectPropertiesFn offset"); + Eq((int)Marshal.OffsetOf("GetObjectPropertiesFn"), + (int)Marshal.OffsetOf("RemoveClientObjectFn") + IntPtr.Size, "GetObjectPropertiesFn right after RemoveClientObjectFn"); } private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { }