From 5c6cbb15e31edcd7ac62b4d6b3d8b57aad755bdb Mon Sep 17 00:00:00 2001 From: oy Date: Tue, 10 Nov 2026 17:16:42 +0800 Subject: [PATCH] feat: expose lifetime-owned equipment attachment rules --- Agents/status/items-and-crafting.md | 3 + Modules/Core/Game/Item/Equipment.cs | 34 +-- Modules/Core/Game/Item/ItemWeaponStats.cs | 5 +- Modules/Core/Game/Item/SkinTransferStats.cs | 106 ++++++++ Modules/Core/Game/Item/SkinTransfers.cs | 62 +++++ Modules/Core/Game/Passive/Progression.cs | 4 +- Modules/Core/Game/Player/DualWieldPanel.cs | 2 +- Modules/Core/Game/Player/Messages.cs | 4 + Modules/Core/Game/Player/OffHandPanel.cs | 6 +- Modules/Core/Game/Skill/ShieldCharge.cs | 2 +- .../Protocol/Instance/InstanceItems.cs | 11 +- .../Protocol/Instance/InstanceProtocol.cs | 2 + .../Instance/InstanceSkinTransfers.cs | 28 ++ src/GameServer.Gateway/Item/ItemRolls.cs | 2 +- src/GameServer.Gateway/Item/UniqueCatalog.cs | 1 + .../Modding/EquipmentAttachmentPolicy.cs | 38 +++ .../Modding/EquipmentAttachmentRules.cs | 2 + .../Player/PlayerInventories.SkinTransfer.cs | 75 ++++++ .../Player/PlayerInventories.cs | 9 +- .../Saves/CharacterSaves.cs | 8 +- src/GameServer.Gateway/Skill/SkillCatalog.cs | 4 +- .../SkinTransferTests.cs | 247 ++++++++++++++++++ .../TestEnvironment.cs | 1 + 23 files changed, 626 insertions(+), 30 deletions(-) create mode 100644 Modules/Core/Game/Item/SkinTransferStats.cs create mode 100644 Modules/Core/Game/Item/SkinTransfers.cs create mode 100644 src/GameServer.Core/Protocol/Instance/InstanceSkinTransfers.cs create mode 100644 src/GameServer.Gateway/Modding/EquipmentAttachmentPolicy.cs create mode 100644 src/GameServer.Gateway/Modding/EquipmentAttachmentRules.cs create mode 100644 src/GameServer.Gateway/Player/PlayerInventories.SkinTransfer.cs create mode 100644 tests/GameServer.Gateway.Tests/SkinTransferTests.cs diff --git a/Agents/status/items-and-crafting.md b/Agents/status/items-and-crafting.md index 31d23cec9..8784d9d71 100644 --- a/Agents/status/items-and-crafting.md +++ b/Agents/status/items-and-crafting.md @@ -217,6 +217,9 @@ Part of [Status](../Status.md); what to build next in this area is in ## Partly working - The mod SDK validates native character-build previews and commits confirmed imports after session drain; the optional POB mod and converter are external. +- Native skin-transfer donors persist and reclaim independently; attachment stat contributions require a user mod. + Global modifiers, completed damage, defences and accuracy are separately opt-in; weapon speed, critical chance and donor skills stay unchanged. + Fresh native checks of the mod lifecycle are pending. - **On-kill explosions and attribute damage reduction (implemented 2026-11-04; native behavior checked with the official client 2026-11-05, server live check pending):** "Enemies you Kill Explode, dealing X% of their Life as diff --git a/Modules/Core/Game/Item/Equipment.cs b/Modules/Core/Game/Item/Equipment.cs index 1dcd7f3d0..a87076138 100644 --- a/Modules/Core/Game/Item/Equipment.cs +++ b/Modules/Core/Game/Item/Equipment.cs @@ -19,16 +19,13 @@ public static bool PlayerHasEnergyShieldForRecovery(ClientState conn, Func Main, Dictionary Off) HandLocalStats(ClientState conn) { Dictionary Local((Item Item, ItemCatalog.BaseType? Type)? hand) => hand is { } active - ? ItemModStats.Local(active.Item, ItemsFor(conn).Mods) : []; + ? SkinTransferStats.Local(active.Item, ItemsFor(conn).Mods) : []; // Weapon swaps exchange the equipment rows; rows 14/15 remain inactive even when an active hand is empty. return (Local(ActiveMainHand(conn)), Local(ActiveOffHand(conn))); } @@ -158,7 +157,7 @@ static bool Pair(ItemCatalog.BaseType? main, ItemCatalog.BaseType? off) => var claws = (main1?.Class == "Claw" && off1?.Class == "Claw") || (main2?.Class == "Claw" && off2?.Class == "Claw"); var unarmed = main1 is null && main2 is null; var mainItem = rowItems(2).Concat(activeSet ? [] : rowItems(14)).Where(i => !inactive(i.Id)).Select(i => i.Item).FirstOrDefault(); - var local = mainItem is null ? [] : ItemModStats.Local(mainItem, catalog.Mods); + var local = mainItem is null ? [] : SkinTransferStats.Local(mainItem, catalog.Mods); return new WeaponProfile( Shield: activeSet ? off1?.Class == "Shield" : hasShield(), DualWield: dual, @@ -179,8 +178,7 @@ static bool Pair(ItemCatalog.BaseType? main, ItemCatalog.BaseType? off) => Wand: all.Any(t => t.Class == "Wand"), // The main hand's local critical chance and accuracy feed its character calculations. Local attack speed // is item metadata here; ItemWeaponStats already includes it in that hand's duration. - Critical: (main1 ?? main2) is { } main ? AddedBaseCriticalStrike.LocalWeaponChance(catalog.WeaponCritical(main), - local.GetValueOrDefault("local_critical_strike_chance"), local.GetValueOrDefault("local_critical_strike_chance_+%")) : 0, + Critical: mainItem is not null ? SkinTransferStats.Critical(mainItem, catalog) : 0, LocalAttackSpeedPct: local.GetValueOrDefault("local_attack_speed_+%"), LocalAccuracy: local.GetValueOrDefault("local_accuracy_rating")); } @@ -189,8 +187,9 @@ static bool Pair(ItemCatalog.BaseType? main, ItemCatalog.BaseType? off) => public static bool HasShield(ClientState conn) => OffhandTypes(conn).Any(t => t.Class == "Shield"); // Base block comes from the active, requirement-enabled shield, like its local defences and global modifiers. - public static int ShieldBaseBlock(ClientState conn) => ActiveOffHand(conn)?.Type is { Class: "Shield" } shield - ? ItemsFor(conn).ShieldBlock(shield) : 0; + public static int ShieldBaseBlock(ClientState conn) => ActiveOffHand(conn) is { Type: { Class: "Shield" }, Item: var shield } + ? (int)Math.Min(int.MaxValue, SkinTransferStats.Items(shield).Sum(i => (long)(ItemsFor(conn).ByHash(i.TypeHash) is { } t + ? ItemsFor(conn).ShieldBlock(t) : 0))) : 0; public static IEnumerable OffhandTypes(ClientState conn) { @@ -235,6 +234,11 @@ public static IReadOnlyList Looks(ClientState conn, PlayerInventori ushort quiverArt = quiver >= 0 ? looks[quiver].VisualIdentity : ItemsFor(conn).Visual("DefaultQuiver") ?? 0x328b; looks.RemoveAll(l => l.Slot is 0 or 1 or 7); looks.AddRange(BowSetup.Entries(bow, ItemsFor(conn).Visual("DefaultArrow") ?? 0xb2f6, quiverArt)); + if (ActiveMainHand(conn)?.Item.SkinTransferSource is { } source) + { + int at = looks.FindIndex(l => l.Slot == 1); + if (at >= 0) looks[at] = looks[at] with { SkinVisual = source.VisualIdentity }; + } } var cosmeticSlots = CosmeticEffects.CosmeticOnlySlots.ToDictionary(s => s, VisibleItem.Empty); foreach (var worn in WornCosmetics(conn)) diff --git a/Modules/Core/Game/Item/ItemWeaponStats.cs b/Modules/Core/Game/Item/ItemWeaponStats.cs index 45a844a59..079eadd78 100644 --- a/Modules/Core/Game/Item/ItemWeaponStats.cs +++ b/Modules/Core/Game/Item/ItemWeaponStats.cs @@ -5,7 +5,10 @@ /// A weapon's local item damage and duration, before character, skill and support modifiers. public static class ItemWeaponStats { - public sealed record Result(DamagePacket Damage, int AttackMs); + public sealed record Result(DamagePacket Damage, int AttackMs) + { + public double? ExactAttackMs { get; init; } + } /// PoB 3.29.x Item.lua: local physical increases and ordinary quality multiply, then round once. /// Elemental local increases apply to fire, cold and lightning; chaos has only its local flat range here. diff --git a/Modules/Core/Game/Item/SkinTransferStats.cs b/Modules/Core/Game/Item/SkinTransferStats.cs new file mode 100644 index 000000000..91bd3fd59 --- /dev/null +++ b/Modules/Core/Game/Item/SkinTransferStats.cs @@ -0,0 +1,106 @@ +using GameServer.Core.Protocol.Instance; +using GameServer.Core.World; + +// Combine completed damage and defences; A alone owns weapon speed, critical chance, identity and sockets. +static class SkinTransferStats +{ + // Keep donor selection outside ItemModStats: both items use upstream's effect and condition evaluation. + // A's own skill modifiers remain active; only B's granted/triggered skill sources are excluded. + static IEnumerable Donors(IEnumerable items, ModCatalog mods) => (EquipmentAttachmentPolicy.Current.GlobalModifiers ? items : []) + .Select(i => i.SkinTransferSource).OfType() + .Select(i => i with { Mods = i.Mods.Where(m => mods.ByHash(m.Hash)?.GrantedEffects is 0).ToArray() }); + + static bool SkillExecutionStat(string id) => id.Contains("trigger_a_", StringComparison.OrdinalIgnoreCase) + || id.Contains("trigger_socketed", StringComparison.OrdinalIgnoreCase) + || id.Contains("trigger_level_", StringComparison.OrdinalIgnoreCase) + || id.Contains("_trigger_on_", StringComparison.OrdinalIgnoreCase) + || id.Contains("_spells_triggered", StringComparison.OrdinalIgnoreCase) + || id.Contains("cast_on_", StringComparison.OrdinalIgnoreCase) + || id.Contains("cast_when_", StringComparison.OrdinalIgnoreCase) + || id.Contains("granted_skill", StringComparison.OrdinalIgnoreCase); + + internal static Dictionary Sum(IEnumerable items, ModCatalog mods, + StatConditions.Subject subject = default, Func? statExists = null) + { + var equipped = items.ToArray(); + var result = ItemModStats.Sum(equipped, mods, subject: subject, statExists: statExists); + foreach (var donor in Donors(equipped, mods)) + foreach (var (id, value) in ItemModStats.Sum([donor], mods, subject: subject, statExists: statExists)) + if (!SkillExecutionStat(id)) result[id] = ArcaneMight.Combine(id, result.GetValueOrDefault(id), value); + return result; + } + + internal static Dictionary Global(IEnumerable items, ModCatalog mods, StatCatalog stats, + StatConditions.Subject subject = default) + { + var equipped = items.ToArray(); + var result = ItemModStats.Global(equipped, mods, stats, subject); + foreach (var donor in Donors(equipped, mods)) + { + var contribution = ItemModStats.Global([donor], mods, stats, subject); + foreach (uint key in contribution.Keys.Where(k => stats.Name(k) is string id && SkillExecutionStat(id)).ToArray()) + contribution.Remove(key); + result = ItemModStats.Plus(result, contribution); + } + return result; + } + + internal static Dictionary RawAttributes(IEnumerable items, ModCatalog mods) + { + var equipped = items.ToArray(); + return ItemModStats.RawAttributes(equipped.Concat(Donors(equipped, mods)), mods); + } + + public static IEnumerable Items(Item item) + { + yield return item; + if (EquipmentAttachmentPolicy.Current.LocalDefences && item.SkinTransferSource is { } source) yield return source; + } + + public static Dictionary Local(Item item, ModCatalog mods) + { + var result = ItemModStats.Local(item, mods); + if (EquipmentAttachmentPolicy.Current.LocalAccuracy && item.SkinTransferSource is { } source) + { + // Only completed flat accuracy joins A's raw local view. B's damage is calculated separately below. + const string accuracy = "local_accuracy_rating"; + result[accuracy] = (int)Math.Clamp((long)result.GetValueOrDefault(accuracy) + + ItemModStats.Local(source, mods).GetValueOrDefault(accuracy), int.MinValue, int.MaxValue); + } + return result; + } + + public static int Critical(Item item, ItemCatalog catalog) + { + if (catalog.ByHash(item.TypeHash) is not { } type) return 0; + var local = ItemModStats.Local(item, catalog.Mods); + return AddedBaseCriticalStrike.LocalWeaponChance(catalog.WeaponCritical(type), + local.GetValueOrDefault("local_critical_strike_chance"), local.GetValueOrDefault("local_critical_strike_chance_+%")); + } + + public static ItemWeaponStats.Result Weapon(Item item, (int AttackMs, int Min, int Max, int Range) basis, + SkillCatalog skills, ItemCatalog catalog) + { + var a = ItemWeaponStats.Calculate(item, basis, catalog.Mods); + if (!EquipmentAttachmentPolicy.Current.LocalDamage || item.SkinTransferSource is not { } source || catalog.ByHash(source.TypeHash) is not { } type + || skills.WeaponBase(type.Row) is not { } bBase) return a; + var b = ItemWeaponStats.Calculate(source, bBase, catalog.Mods); + return a with { Damage = a.Damage.Add(b.Damage) }; + } + + public static (decimal Armour, decimal Evasion, int EnergyShield, decimal Ward) Defences(Item item, ItemCatalog catalog) + { + decimal armour = 0, evasion = 0, ward = 0; + long es = 0; + foreach (var part in Items(item)) + if (catalog.ByHash(part.TypeHash) is { } type && catalog.Defences(type) is { } basis) + { + var (a, e, s) = ItemDefences.Calculate(part, basis, catalog.Mods); + armour += a; evasion += e; es += s; + var local = ItemModStats.Local(part, catalog.Mods); + ward += (long)WardState.Max((decimal)basis.WardMin + local.GetValueOrDefault("local_ward"), + local.GetValueOrDefault("local_ward_+%")) * (100 + Math.Clamp((int)part.Quality, 0, 100)) / 100; + } + return (armour, evasion, (int)Math.Min(int.MaxValue, es), ward); + } +} diff --git a/Modules/Core/Game/Item/SkinTransfers.cs b/Modules/Core/Game/Item/SkinTransfers.cs new file mode 100644 index 000000000..cff243c01 --- /dev/null +++ b/Modules/Core/Game/Item/SkinTransfers.cs @@ -0,0 +1,62 @@ +using System.Net.Sockets; +using GameServer.Core.Protocol.Instance; +using GameServer.Core.Protocol.Login; + +static partial class Game +{ + internal static async Task NativeReclaimSkin(string remote, NetworkStream stream, ConnectionCiphers ciphers, + ClientState conn, InstanceSkinTransfers.Reclaim pick) + { + string why = "Invalid skin-transfer inventory"; + var change = PlayerInventories.Row(pick.InventoryId) is byte row + ? ItemsOf(conn).UnbindSkin(pick.ItemId, out why, row) : null; + Console.WriteLine($"[gateway] {remote} <= 0x0122 reclaim skin {pick}: {(change is null ? why : "returned B")}"); + if (change is not null) await SendSkinTransfer(remote, stream, ciphers, conn, change, bind: false); + else await RefuseSkinTransfer(remote, stream, ciphers, conn, why, [(pick.InventoryId, pick.ItemId)]); + } + + internal static async Task NativeSkinTransfer(string remote, NetworkStream stream, ConnectionCiphers ciphers, + ClientState conn, InstanceSkinTransfers.Bind pick) + { + string why = "Invalid skin-transfer record or inventory"; + var items = ItemsOf(conn); + var change = Mtx.Find(pick.RecordId)?.MtxTypeHash == InstanceSkinTransfers.MtxTypeHash + && PlayerInventories.Row(pick.SourceInventoryId) is byte sourceRow + && PlayerInventories.Row(pick.TargetInventoryId) is byte targetRow + ? items.BindSkin(pick.TargetId, targetRow, sourceRow, pick.SourceId, ShapeOf, out why) : null; + Console.WriteLine($"[gateway] {remote} <= 0x0207 skin transfer {pick}: {(change is null ? why : "bound")}"); + if (change is not null) await SendSkinTransfer(remote, stream, ciphers, conn, change, bind: true); + else await RefuseSkinTransfer(remote, stream, ciphers, conn, why, + [(pick.TargetInventoryId, pick.TargetId), (pick.SourceInventoryId, pick.SourceId)]); + } + + static async Task RefuseSkinTransfer(string remote, NetworkStream stream, ConnectionCiphers ciphers, ClientState conn, + string why, (uint Inventory, uint Item)[] requested) + { + await Send(remote, stream, ciphers, InstanceChat.ChatLine(why), "skin transfer refused"); + // The native picker marks its selected items pending. Reconcile them even when the request is stale/refused. + var items = ItemsOf(conn); + foreach (var group in requested.GroupBy(i => i.Inventory)) + if (PlayerInventories.Row(group.Key) is byte row) + { + var ids = group.Select(i => i.Item).Distinct().ToArray(); + await Send(remote, stream, ciphers, InstanceItems.InventoryChange(group.Key, items.NextRevision(row), ids, + items.Items(row).Where(i => ids.Contains(i.Id)).ToArray()), "skin transfer: reconcile refused pick"); + } + } + + public static async Task SendSkinTransfer(string remote, NetworkStream stream, ConnectionCiphers ciphers, + ClientState conn, PlayerInventories.SkinTransferChange change, bool bind) + { + var items = ItemsOf(conn); + bool same = bind && change.Row == change.SourceRow; + await Send(remote, stream, ciphers, InstanceItems.InventoryChange(PlayerInventories.InventoryId(change.Row), + items.NextRevision(change.Row), same ? [change.Target.Id, change.Source.Id] : [change.Target.Id], + [change.Target]), "skin transfer: update A"); + if (!same) + await Send(remote, stream, ciphers, InstanceItems.InventoryChange(PlayerInventories.InventoryId(change.SourceRow), + items.NextRevision(change.SourceRow), bind ? [change.Source.Id] : [], bind ? [] : [change.Source]), + bind ? "skin transfer: bind B" : "skin transfer: return B"); + await SendEquipment(remote, stream, ciphers, conn, items); + } +} diff --git a/Modules/Core/Game/Passive/Progression.cs b/Modules/Core/Game/Passive/Progression.cs index b83d968c7..bdf359432 100644 --- a/Modules/Core/Game/Passive/Progression.cs +++ b/Modules/Core/Game/Passive/Progression.cs @@ -519,7 +519,7 @@ static void AddCounts(Dictionary counts, IReadOnlyList<(uint Key, int passiveAttributes[name] = passiveAttributes.GetValueOrDefault(name) + value; Dictionary RawAttributes(IEnumerable active) { - var raw = ItemModStats.RawAttributes(active, ItemsFor(conn).Mods); + var raw = SkinTransferStats.RawAttributes(active, ItemsFor(conn).Mods); foreach (var (name, value) in passiveAttributes) raw[name] = raw.GetValueOrDefault(name) + value; return raw; } @@ -592,7 +592,7 @@ int ForRequirements(string attribute, int value) => "rage" => null, _ => (int?)null, }, KnownRecent: TrackedItemRecentEvents, Flags: conditionFlags); - var sources = ItemModStats.Plus(passives, ItemModStats.Global(active, ItemsFor(conn).Mods, Stats, conditionSubject)); + var sources = ItemModStats.Plus(passives, SkinTransferStats.Global(active, ItemsFor(conn).Mods, Stats, conditionSubject)); // The tree's base_devotion and the item's ..._per_10_devotion stats meet here: replace the latter with their // normal stat at floor(Devotion / 10) steps before the pools and panels read this view. DevotionStats.Apply(sources, Stats); diff --git a/Modules/Core/Game/Player/DualWieldPanel.cs b/Modules/Core/Game/Player/DualWieldPanel.cs index da5c176f1..527672901 100644 --- a/Modules/Core/Game/Player/DualWieldPanel.cs +++ b/Modules/Core/Game/Player/DualWieldPanel.cs @@ -26,5 +26,5 @@ public static (int PerUse, int PerSecond, int HundredTimesAttacksPerSecond) Aver /// The off hand's swing time: its own duration (local speed included) at the off-hand increased attack /// speed, at least one server tick. public static double OffHandSeconds(SkillCatalog.Unarmed offHand, int offHandAttackSpeedPct) => - Math.Max(Program.TickSeconds, offHand.AttackMs / 1000.0 / Math.Max(0.01, 1 + offHandAttackSpeedPct / 100.0)); + Math.Max(Program.TickSeconds, offHand.EffectiveAttackMs / 1000.0 / Math.Max(0.01, 1 + offHandAttackSpeedPct / 100.0)); } diff --git a/Modules/Core/Game/Player/Messages.cs b/Modules/Core/Game/Player/Messages.cs index c7ac190ac..c247794ef 100644 --- a/Modules/Core/Game/Player/Messages.cs +++ b/Modules/Core/Game/Player/Messages.cs @@ -500,6 +500,10 @@ await Send(remote, stream, ciphers, InstanceProtocol.MoveTo(PlayerId, use.X, use } else if (id == InstanceItems.InventoryRequestId) Console.WriteLine($"[gateway] {remote} <= 0x{id:x4} (inventory request, not handled yet): {Convert.ToHexString(bytes)}"); + else if (id == InstanceSkinTransfers.BindId) + await NativeSkinTransfer(remote, stream, ciphers, conn, InstanceSkinTransfers.ReadBind(bytes)); + else if (id == InstanceSkinTransfers.ReclaimId) + await NativeReclaimSkin(remote, stream, ciphers, conn, InstanceSkinTransfers.ReadReclaim(bytes)); else if (id == InstanceItems.PickUpItemId) await PickUpItem(remote, stream, ciphers, conn, InstanceItems.ReadPickUpItem(bytes)); else if (id == InstanceProtocol.ExitToCharacterSelectId) diff --git a/Modules/Core/Game/Player/OffHandPanel.cs b/Modules/Core/Game/Player/OffHandPanel.cs index 4746797c2..5e2a5c634 100644 --- a/Modules/Core/Game/Player/OffHandPanel.cs +++ b/Modules/Core/Game/Player/OffHandPanel.cs @@ -41,8 +41,10 @@ public static partial class Game rating = TimedBlind.Apply(rating, blindLess); var accuracy = AttackAccuracyProfile.From(pools, player, Stats, own, offLocal) with { Rating = rating }; // Critical chance: the off-hand weapon's base with its local mods, the same override and global increases. - int weaponBase = AddedBaseCriticalStrike.LocalWeaponChance(catalog.WeaponCritical(offType), - offLocal.GetValueOrDefault("local_critical_strike_chance"), offLocal.GetValueOrDefault("local_critical_strike_chance_+%")); + int weaponBase = activeOffHand() is { Item.SkinTransferSource: not null } off + ? SkinTransferStats.Critical(off.Item, catalog) + : AddedBaseCriticalStrike.LocalWeaponChance(catalog.WeaponCritical(offType), + offLocal.GetValueOrDefault("local_critical_strike_chance"), offLocal.GetValueOrDefault("local_critical_strike_chance_+%")); int chance = AttackBaseCriticalStrike.Chance(true, weaponBase, pools.CriticalStrikeChancePct + (own is null ? 0 : AttackBaseCriticalStrike.IncreasedSum(profile, n => Own(n))), Player, own is null ? null : Own); diff --git a/Modules/Core/Game/Skill/ShieldCharge.cs b/Modules/Core/Game/Skill/ShieldCharge.cs index 53cae24ca..46bc01968 100644 --- a/Modules/Core/Game/Skill/ShieldCharge.cs +++ b/Modules/Core/Game/Skill/ShieldCharge.cs @@ -31,7 +31,7 @@ public static int ShieldChargeMaxDistance(ClientState conn, ushort skillId) => (100 + (Stats.Key("shield_charge_range_+%") is uint k ? SupportedStats(conn, skillId).GetValueOrDefault(k) : 0)) * ShieldChargeBaseDistance / 100; - // In the use's StartAction: the bonus on, the pools and walk speed with it, and the walk to the aimed cell, no further + // After paid admission: the bonus on, the pools and walk speed with it, and the walk to the aimed cell, no further // than the charge's maximum distance. Returns the run's token, which only the latest charge's end may clear. public static int BeginShieldCharge(ClientState conn, ushort skillId, int percent, int x, int y, double at) { diff --git a/src/GameServer.Core/Protocol/Instance/InstanceItems.cs b/src/GameServer.Core/Protocol/Instance/InstanceItems.cs index 1927afe07..67d24c62e 100644 --- a/src/GameServer.Core/Protocol/Instance/InstanceItems.cs +++ b/src/GameServer.Core/Protocol/Instance/InstanceItems.cs @@ -40,6 +40,9 @@ public sealed record ItemMod(ModSection Section, ushort Hash, IReadOnlyList /// public sealed record Item(uint TypeHash, IReadOnlyList Components, ushort VisualIdentity) { + /// The independently preserved donor, carried by Base's nested skin item rather than A's mods or sockets. + public Item? SkinTransferSource { get; init; } + public byte ItemLevel { get; init; } = 1; public byte Quality { get; init; } @@ -167,7 +170,13 @@ public byte[] Payload() // Bit 7 (a vendor price): u8 n, then n × (u32 item type hash, compact uint amount; 0x141fabcc0 looks the type // up, 0x141e655b0 reads the amount); stored in the Base's +0xb8 item list. case "Base": - w.U16(VisualIdentity).U8(0).U8((byte)(Corrupted ? 1 : 0)).U16((ushort)(Price.Count > 0 ? 0x80 : 0)).U8((byte)Influences); + w.U16(VisualIdentity).U8(0).U8((byte)(Corrupted ? 1 : 0)) + .U16((ushort)((Price.Count > 0 ? 0x80 : 0) | (SkinTransferSource is not null ? 0x40 : 0))).U8((byte)Influences); + if (SkinTransferSource is { } skin) + { + if (skin.SkinTransferSource is not null) throw new InvalidDataException("Nested skin transfers are not supported"); + w.Bytes(skin.Payload()); + } if (Price.Count > 0) { w.U8((byte)Price.Count); diff --git a/src/GameServer.Core/Protocol/Instance/InstanceProtocol.cs b/src/GameServer.Core/Protocol/Instance/InstanceProtocol.cs index d93943fab..445831880 100644 --- a/src/GameServer.Core/Protocol/Instance/InstanceProtocol.cs +++ b/src/GameServer.Core/Protocol/Instance/InstanceProtocol.cs @@ -105,6 +105,8 @@ public static byte[] Pong(ushort serverDelayMs = 0, ushort ackIndex = 0, uint si InstanceWaypoints.AscendancyChosenId => InstanceWaypoints.AscendancyChosenLength, InstanceMicrotransactions.SkillPickId => InstanceMicrotransactions.SkillPickLength, InstanceMicrotransactions.RequestId => InstanceMicrotransactions.RequestLength, + InstanceSkinTransfers.BindId => InstanceSkinTransfers.BindLength, + InstanceSkinTransfers.ReclaimId => InstanceSkinTransfers.ReclaimLength, InstanceHideouts.SelectId => InstanceHideouts.SelectLength, InstanceHideoutEditing.MoveId => InstanceHideoutEditing.MoveLength, InstanceBench.CraftId => InstanceBench.CraftLength, InstanceBench.MoveId => InstanceBench.MoveLength, InstanceHarvest.CraftId => InstanceHarvest.CraftLength, diff --git a/src/GameServer.Core/Protocol/Instance/InstanceSkinTransfers.cs b/src/GameServer.Core/Protocol/Instance/InstanceSkinTransfers.cs new file mode 100644 index 000000000..2195700ee --- /dev/null +++ b/src/GameServer.Core/Protocol/Instance/InstanceSkinTransfers.cs @@ -0,0 +1,28 @@ +using GameServer.Core.Protocol.Login; + +namespace GameServer.Core.Protocol.Instance; + +public static class InstanceSkinTransfers +{ + public const uint MtxTypeHash = 3551001385u; // MicrotransactionApplyVisualIdentity + // Native 3.29.3b confirmation 0x1402fc2e0, writer 0x141f9c650: five network-order u32 fields. + public const ushort BindId = 0x207; + public const int BindLength = 22; + // Shift-click reclaim confirmation callback 0x14032abe0, writer 0x141f926a0. + public const ushort ReclaimId = 0x122; + public const int ReclaimLength = 10; + public sealed record Bind(uint RecordId, uint SourceId, uint TargetId, uint SourceInventoryId, uint TargetInventoryId); + public sealed record Reclaim(uint InventoryId, uint ItemId); + + public static Bind ReadBind(ReadOnlySpan bytes) + { + var r = new LoginReader(bytes[2..]); + return new(r.U32(), r.U32(), r.U32(), r.U32(), r.U32()); + } + + public static Reclaim ReadReclaim(ReadOnlySpan bytes) + { + var r = new LoginReader(bytes[2..]); + return new(r.U32(), r.U32()); + } +} diff --git a/src/GameServer.Gateway/Item/ItemRolls.cs b/src/GameServer.Gateway/Item/ItemRolls.cs index 426e7a6af..c03331c11 100644 --- a/src/GameServer.Gateway/Item/ItemRolls.cs +++ b/src/GameServer.Gateway/Item/ItemRolls.cs @@ -271,7 +271,7 @@ type.Class is not ("Helmet" or "Body Armour" or "Gloves" or "Boots") || /// unmodifiable, with every property kept (mods and their values, fractured mods, quality, sockets, links, socketed /// gems, name). The original stays as it was; the caller puts the copy on the cursor. public Item? Mirror(Item item) => - item.Rarity != ItemRarity.Unique && TryModifiable(item, out var type) && type.CanBeMirrored + item.SkinTransferSource is null && item.Rarity != ItemRarity.Unique && TryModifiable(item, out var type) && type.CanBeMirrored ? item with { Mirrored = true } : null; /// Vaal Orb, the documented LocalExile rule: a weapon, armour piece or jewellery (ring, amulet, belt) diff --git a/src/GameServer.Gateway/Item/UniqueCatalog.cs b/src/GameServer.Gateway/Item/UniqueCatalog.cs index d72c33e9a..96aa63aea 100644 --- a/src/GameServer.Gateway/Item/UniqueCatalog.cs +++ b/src/GameServer.Gateway/Item/UniqueCatalog.cs @@ -255,6 +255,7 @@ IEnumerable Rolled(Definition definition, string[] ids, ModSection sect return Create(chosen, random) is { } created ? created with { ItemLevel = item.ItemLevel, Quality = item.Quality, Sockets = item.Sockets, Links = item.Links, Identified = item.Identified, + SkinTransferSource = item.SkinTransferSource, } : null; } diff --git a/src/GameServer.Gateway/Modding/EquipmentAttachmentPolicy.cs b/src/GameServer.Gateway/Modding/EquipmentAttachmentPolicy.cs new file mode 100644 index 000000000..cd571774a --- /dev/null +++ b/src/GameServer.Gateway/Modding/EquipmentAttachmentPolicy.cs @@ -0,0 +1,38 @@ +/// Rules used by the server while the registering owner is loaded. +public static class EquipmentAttachmentPolicy +{ + /// Uses these rules until the registration is disposed or its owner unloads. + public static IDisposable Use(string owner, EquipmentAttachmentRules options) => + GameEventOwners.Own(owner, Use(options)); + + static readonly Lock Gate = new(); + static readonly List<(object Owner, EquipmentAttachmentRules Options)> Active = []; + static EquipmentAttachmentRules _current = new(); + /// The latest active rules, or the server defaults when no owner supplies any. + public static EquipmentAttachmentRules Current => Volatile.Read(ref _current); + + internal static IDisposable Use(EquipmentAttachmentRules options) + { + ArgumentNullException.ThrowIfNull(options); + var owner = new object(); + lock (Gate) + { + Active.Add((owner, options)); + Volatile.Write(ref _current, options); + } + return new Lease(() => + { + lock (Gate) + { + Active.RemoveAll(entry => ReferenceEquals(entry.Owner, owner)); + Volatile.Write(ref _current, Active.Count == 0 ? new() : Active[^1].Options); + } + }); + } + + sealed class Lease(Action remove) : IDisposable + { + Action? _remove = remove; + public void Dispose() => Interlocked.Exchange(ref _remove, null)?.Invoke(); + } +} diff --git a/src/GameServer.Gateway/Modding/EquipmentAttachmentRules.cs b/src/GameServer.Gateway/Modding/EquipmentAttachmentRules.cs new file mode 100644 index 000000000..846d1d4b9 --- /dev/null +++ b/src/GameServer.Gateway/Modding/EquipmentAttachmentRules.cs @@ -0,0 +1,2 @@ +/// Global options registered by a user mod; disposing its registration restores the previous options. +public sealed record EquipmentAttachmentRules(bool GlobalModifiers = false, bool LocalDamage = false, bool LocalDefences = false, bool LocalAccuracy = false); diff --git a/src/GameServer.Gateway/Player/PlayerInventories.SkinTransfer.cs b/src/GameServer.Gateway/Player/PlayerInventories.SkinTransfer.cs new file mode 100644 index 000000000..570789a59 --- /dev/null +++ b/src/GameServer.Gateway/Player/PlayerInventories.SkinTransfer.cs @@ -0,0 +1,75 @@ +using GameServer.Core.Protocol.Instance; + +public sealed partial class PlayerInventories +{ + public sealed record SkinTransferChange(byte Row, InventoryItem Target, InventoryItem Source, byte SourceRow = Cursor); + + // The donor moves from the cursor into A, in the same inventory snapshot and save. No second usable B exists. + public SkinTransferChange? BindSkin(uint targetId, Func shapeOf, out string why) + => BindSkin(targetId, null, Cursor, null, shapeOf, out why); + + // The native picker names both inventories and items; an item moved since the pick must not be rebound elsewhere. + public SkinTransferChange? BindSkin(uint targetId, byte? targetRow, byte sourceRow, uint? sourceId, + Func shapeOf, out string why) + { + SkinTransferChange result; + lock (_lock) + { + why = ""; + var donor = sourceId is uint id ? ItemsIn(sourceRow).FirstOrDefault(i => i.Id == id) + : ItemsIn(sourceRow) is [var held] ? held : null; + if (donor is null) { why = "Source B is missing"; return null; } + if (RowOf(targetId) is not byte row || row == Cursor || _offered.ContainsKey(targetId)) + { why = "Target A is missing or offered for sale"; return null; } + if (targetRow is byte expected && expected != row || targetId == donor.Id + || !SkinInventory(row) || sourceRow != Cursor && (!SkinInventory(sourceRow) || ItemsIn(Cursor).Count != 0) + || _offered.ContainsKey(donor.Id)) + { why = "Items moved, are offered for sale, or are not in an available equipment inventory"; return null; } + var target = ItemsIn(row).Single(i => i.Id == targetId); + if (target.Item.SkinTransferSource is not null || donor.Item.SkinTransferSource is not null) + { why = "Remove the existing skin transfer first"; return null; } + if (!target.Item.Identified || !donor.Item.Identified || target.Item.StackSize != 1 || donor.Item.StackSize != 1 + || shapeOf(target.Item) is not { } a || shapeOf(donor.Item) is not { } b + || EquipmentFamily(a.Class) is not { } family || family != EquipmentFamily(b.Class)) + { why = "A and B must be identified equipment for the same slot (weapons may differ in type)"; return null; } + var bound = target with { Item = target.Item with { SkinTransferSource = donor.Item } }; + var list = ItemsIn(row); + list[list.IndexOf(target)] = bound; + ItemsIn(sourceRow).Remove(donor); + result = new(row, bound, donor, sourceRow); + } + Persist(); + return result; + } + + static bool SkinInventory(byte row) => row <= 10 || row is Weapon2 or Offhand2; + + public SkinTransferChange? UnbindSkin(uint targetId, out string why, byte? targetRow = null) + { + SkinTransferChange result; + lock (_lock) + { + why = ""; + if (ItemsIn(Cursor).Count != 0) { why = "Empty the cursor before reclaiming B"; return null; } + if (RowOf(targetId) is not byte row || row == Cursor || _offered.ContainsKey(targetId)) + { why = "Target A is missing or offered for sale"; return null; } + if (targetRow is byte expected && expected != row) + { why = "Target A moved to another inventory"; return null; } + var target = ItemsIn(row).Single(i => i.Id == targetId); + if (target.Item.SkinTransferSource is not { } source) { why = "A has no skin transfer"; return null; } + // Returned items get a fresh placement id, including after A crossed a stash/account boundary. + var returned = new InventoryItem(NewItemId(), 0, 0, source); + var unbound = target with { Item = target.Item with { SkinTransferSource = null } }; + var list = ItemsIn(row); + list[list.IndexOf(target)] = unbound; + ItemsIn(Cursor).Add(returned); + result = new(row, unbound, returned); + } + Persist(); + return result; + } + + static string? EquipmentFamily(string itemClass) => OneHand.Contains(itemClass) || TwoHand.Contains(itemClass) + ? "Weapon" : itemClass is "Body Armour" or "Helmet" or "Gloves" or "Boots" or "Shield" or "Quiver" + or "Amulet" or "Ring" or "Belt" ? itemClass : null; +} diff --git a/src/GameServer.Gateway/Player/PlayerInventories.cs b/src/GameServer.Gateway/Player/PlayerInventories.cs index 077efd9fc..f87a74e44 100644 --- a/src/GameServer.Gateway/Player/PlayerInventories.cs +++ b/src/GameServer.Gateway/Player/PlayerInventories.cs @@ -8,7 +8,7 @@ /// in memory per character name and saved after every change (, data/saves/), so they follow /// the player through area changes and Gateway restarts. /// -public sealed class PlayerInventories +public sealed partial class PlayerInventories { public const byte MainInventory = 0, BodyArmour = 1, Weapon1 = 2, Offhand1 = 3, Helmet = 4, Gloves = 8, Boots = 9, Belt = 10, Flask = 11, MapDevice = 13, Weapon2 = 14, Offhand2 = 15, CraftingBench = 16, @@ -483,7 +483,10 @@ public IReadOnlyList Equipped(Func look) { lock (_lock) return [.. VisibleSlots.OrderBy(e => e.Value).Select(e => - _items.TryGetValue(e.Key, out var l) && l.Count > 0 && look(l[0].Item) is { } v ? v with { Slot = e.Value } : VisibleItem.Empty(e.Value))]; + _items.TryGetValue(e.Key, out var l) && l.Count > 0 && look(l[0].Item) is { } v + ? v with { Slot = e.Value, SkinVisual = l[0].Item.SkinTransferSource is { } source + && look(source) is { } donor ? donor.VisualIdentity : v.SkinVisual } + : VisibleItem.Empty(e.Value))]; } /// Which weapon set is in the hands: 0 the first, 1 the second (the 0x21 / 0xde flag the panel's I / II tab @@ -896,7 +899,7 @@ public IReadOnlyList Offered() lock (_lock) { if (_offered.ContainsKey(itemId) || ItemsIn(row).FirstOrDefault(i => i.Id == itemId) is not { } it - || it.Item.Sockets.Any(s => s.Gem is not null)) return null; + || it.Item.SkinTransferSource is not null || it.Item.Sockets.Any(s => s.Gem is not null)) return null; if (row == Cursor) { var shape = shapeOf(it.Item) ?? new(1, 1, ""); diff --git a/src/GameServer.Gateway/Saves/CharacterSaves.cs b/src/GameServer.Gateway/Saves/CharacterSaves.cs index 3cb6c515c..9b1868f7d 100644 --- a/src/GameServer.Gateway/Saves/CharacterSaves.cs +++ b/src/GameServer.Gateway/Saves/CharacterSaves.cs @@ -30,7 +30,8 @@ public sealed record SavedItem(uint Type, byte ItemLevel = 1, byte Quality = 0, int GemVariant = 0, bool Corrupted = false, byte Fractured = 0, bool Mirrored = false, byte GemFlags = 0, ushort? Visual = null, byte DefenceBaseRoll = 0, ItemInfluence Influences = ItemInfluence.None, bool Split = false, bool Synthesised = false, bool Foreseeing = false, uint ForeseeSeed = 0, byte? AlternateQualityType = null, - [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] SavedItem? OriginalItem = null); + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] SavedItem? OriginalItem = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] SavedItem? SkinTransferSource = null); public sealed record SavedPlacement(uint Id, byte X, byte Y, SavedItem Item); @@ -519,7 +520,8 @@ static void Update(string character, Func change) => [.. i.Mods.Select(m => new SavedMod(mods?.ByHash(m.Hash)?.Id ?? $"0x{m.Hash:x4}", m.Section, [.. m.Values]))], i.NameWords.Count == 0 ? null : [.. i.NameWords], i.GemVariant, i.Corrupted, i.FracturedCount, i.Mirrored, i.GemFlags, i.Rarity == ItemRarity.Unique ? i.VisualIdentity : null, i.DefenceBaseRoll, i.Influences, i.Split, i.Synthesised, i.Foreseeing, i.ForeseeSeed, i.AlternateQualityType, - i.OriginalItem is null ? null : ToSaved(i.OriginalItem, mods)); + i.OriginalItem is null ? null : ToSaved(i.OriginalItem, mods), + i.SkinTransferSource is { } source ? ToSaved(source, mods) : null); /// The item again, with its socketed gems and mods. A type, gem or mod the game data doesn't know throws /// : dropping it would lose it at the next save. @@ -540,6 +542,8 @@ public static Item FromSaved(SavedItem s, ItemCatalog catalog) OriginalItem = s.OriginalItem is null ? null : FromSaved(s.OriginalItem, catalog), Influences = s.Influences, Split = s.Split, Synthesised = s.Synthesised, Foreseeing = s.Foreseeing, ForeseeSeed = s.ForeseeSeed, AlternateQualityType = s.AlternateQualityType, + SkinTransferSource = s.SkinTransferSource is { } source ? source.SkinTransferSource is null + ? FromSaved(source, catalog) : throw new InvalidDataException("Nested skin transfers are not supported") : null, }; if (s.Mods is not null) item = item with { Mods = [.. s.Mods.Select(m => FromSaved(m, catalog.Mods))] }; return ImpossibleEscapeCatalogue.Migrate(item, catalog.Mods); diff --git a/src/GameServer.Gateway/Skill/SkillCatalog.cs b/src/GameServer.Gateway/Skill/SkillCatalog.cs index 6b76b091a..d22c22777 100644 --- a/src/GameServer.Gateway/Skill/SkillCatalog.cs +++ b/src/GameServer.Gateway/Skill/SkillCatalog.cs @@ -1124,6 +1124,8 @@ public IReadOnlyList PlayerDefaults(IReadOnlyList<(uint, int)> sta /// A class's unarmed "weapon" (Characters.dat WeaponSpeed, MinDamage, MaxDamage, MaxAttackDistance). public sealed record Unarmed(int AttackMs, int MinDamage, int MaxDamage, int Range) { + public double? ExactAttackMs { get; init; } + public double EffectiveAttackMs => ExactAttackMs ?? AttackMs; /// The equipped item's local typed ranges. Class unarmed records retain their physical fallback. public DamagePacket? LocalDamage { get; init; } /// Raw local modifiers captured with this weapon, including penetration and impale chance. @@ -1220,7 +1222,7 @@ public DamagePacket HitDamage(IReadOnlyDictionary? player, bool melee /// main_hand_attack_speed_+% (the final value already includes more multipliers), at least one server tick /// (: at most 30 attacks per second). public double AttackSeconds(IReadOnlyDictionary? player) => - Math.Max(Program.TickSeconds, AttackMs / 1000.0 / Math.Max(0.01, 1 + IncreasedAttackSpeed(player) / 100.0)); + Math.Max(Program.TickSeconds, EffectiveAttackMs / 1000.0 / Math.Max(0.01, 1 + IncreasedAttackSpeed(player) / 100.0)); /// /// The skill's final main-hand stats (client keys = Stats.dat row + 1). The server computes them, as the real one diff --git a/tests/GameServer.Gateway.Tests/SkinTransferTests.cs b/tests/GameServer.Gateway.Tests/SkinTransferTests.cs new file mode 100644 index 000000000..cdf50eeb8 --- /dev/null +++ b/tests/GameServer.Gateway.Tests/SkinTransferTests.cs @@ -0,0 +1,247 @@ +using System.Text.Json; +using GameServer.Core.Protocol.Instance; +using GameServer.Core.World; +using GameServer.Modding; +using League = GameServer.Core.Accounts.League; + +namespace GameServer.Gateway.Tests; + +public sealed class SkinTransferTests +{ + static ItemMod Mod(ItemCatalog items, string stat, int value) => items.Mods.All + .First(m => m.Stats.Count == 1 && m.Stats[0].Id == stat) + .With(ModSection.Explicit, [value], new Random(1)); + + static string Saved(Item item, ItemCatalog items) => JsonSerializer.Serialize(CharacterSaves.ToSaved(item, items.Mods)); + + [Fact] + public void Damage_defences_and_globals_add_but_weapon_speed_and_critical_chance_stay_A() + { + using var mod = new AttachmentModFixture(); + byte[] native = Convert.FromHexString("02070000177300000008000000060000000100000002"); + Assert.Equal(new InstanceSkinTransfers.Bind(6003, 8, 6, 1, 2), InstanceSkinTransfers.ReadBind(native)); + byte[] reclaim = Convert.FromHexString("01220000000200000006"); + Assert.Equal(new InstanceSkinTransfers.Reclaim(2, 6), InstanceSkinTransfers.ReadReclaim(reclaim)); + for (int cut = 1; cut < native.Length; cut++) + { + Assert.Empty(InstanceProtocol.SplitClientMessages(native.AsSpan(0, cut), out var partial, out var unknown)); + Assert.Empty(unknown); + byte[] next = [.. partial, .. native.AsSpan(cut).ToArray(), .. reclaim, 0x01, 0x53]; + Assert.Equal(new ushort[] { InstanceSkinTransfers.BindId, InstanceSkinTransfers.ReclaimId, InstanceProtocol.ExitToCharacterSelectId }, + InstanceProtocol.SplitClientMessages(next, out partial, out unknown).Select(m => m.Id)); + Assert.Empty(partial); + Assert.Empty(unknown); + } + var items = Program.Items; + var skills = new SkillCatalog("data"); + var wand = items.All.First(t => t.Class == "Wand" && t.Supported); + var sword = items.All.First(t => t.Class == "One Hand Sword" && t.Supported); + var fire = items.Mods.All.First(m => m.Stats.Count == 2 + && m.Stats[0].Id == "local_minimum_added_fire_damage" && m.Stats[1].Id == "local_maximum_added_fire_damage") + .With(ModSection.Explicit, [10, 20], new Random(2)); + var a = ItemCatalog.Create(wand) with { Quality = 20, Mods = [Mod(items, "local_physical_damage_+%", 50), + Mod(items, "local_attack_speed_+%", 20), Mod(items, "local_critical_strike_chance_+%", 50), + Mod(items, "local_accuracy_rating", 10), Mod(items, "base_maximum_life", 60)] }; + var b = ItemCatalog.Create(sword) with { Quality = 10, Mods = [Mod(items, "local_physical_damage_+%", 100), + Mod(items, "local_attack_speed_+%", 40), Mod(items, "local_critical_strike_chance_+%", 100), + Mod(items, "local_accuracy_rating", 500), Mod(items, "base_maximum_life", 80), fire] }; + string beforeA = Saved(a, items), beforeB = Saved(b, items); + var bound = a with { SkinTransferSource = b }; + Assert.Equal(60, SkinTransferStats.Sum([bound], items.Mods)["base_maximum_life"]); + Assert.True(mod.Host.SetEnabled("equipmentfusion", true)); + mod.Host.Reload("equipmentfusion"); + Assert.True(EquipmentAttachmentPolicy.Current.GlobalModifiers); + var wa = Game.WeaponIn(skills, items, 3, (a, wand))!; + var wb = Game.WeaponIn(skills, items, 3, (b, sword))!; + var combined = Game.WeaponIn(skills, items, 3, (bound, wand))!; + foreach (var type in DamageTypes.ConversionOrder) + { + Assert.Equal(wa.LocalDamage![type].Min + wb.LocalDamage![type].Min, combined.LocalDamage![type].Min, 8); + Assert.Equal(wa.LocalDamage[type].Max + wb.LocalDamage[type].Max, combined.LocalDamage[type].Max, 8); + } + var noSpeed = new Dictionary { [StatKeys.MainHandAttackSpeedPct] = 0 }; + Assert.Equal(wa.AttackSeconds(noSpeed), combined.AttackSeconds(noSpeed), 9); + var withSpeed = new Dictionary { [StatKeys.MainHandAttackSpeedPct] = 30 }; + Assert.Equal(wa.AttackSeconds(withSpeed), combined.AttackSeconds(withSpeed), 9); + Assert.Equal(wa.Range, combined.Range); + Assert.Equal(wa.WieldingWand, combined.WieldingWand); + Assert.Equal(wa.Melee, combined.Melee); + Assert.Equal(SkinTransferStats.Critical(a, items), SkinTransferStats.Critical(bound, items)); + var profile = Game.WeaponProfileFrom(row => row == PlayerInventories.Weapon1 + ? [new InventoryItem(1, 0, 0, bound)] : [], _ => false, items, true, () => false); + Assert.Equal(SkinTransferStats.Critical(a, items), profile.Critical); + Assert.Equal(510, profile.LocalAccuracy); + Assert.Equal(510, combined.LocalSources!["local_accuracy_rating"]); + Assert.True(profile.Wand); + Assert.False(profile.Sword); + Assert.Equal(60, ItemModStats.Sum([bound], items.Mods)["base_maximum_life"]); // upstream calculator stays item-only + Assert.Equal(140, SkinTransferStats.Sum([bound], items.Mods)["base_maximum_life"]); + var conditional = a with { SkinTransferSource = b with { Mods = [ + items.Mods.All.Single(m => m.Id == "WrathIncreasedLightningDamage").With(ModSection.Explicit, [40], new Random(2)), + Mod(items, "additional_strength", 80)] } }; + uint lightning = Program.Stats.Key("lightning_damage_+%")!.Value; + Assert.Equal(40, SkinTransferStats.Global([conditional], items.Mods, Program.Stats, + new(Auras: new HashSet { "wrath" })).GetValueOrDefault(lightning)); + Assert.Equal(0, SkinTransferStats.Global([conditional], items.Mods, Program.Stats, + new(Auras: new HashSet())).GetValueOrDefault(lightning)); + Assert.Equal(80L, SkinTransferStats.RawAttributes([conditional], items.Mods)["additional_strength"]); + Assert.Equal(50, combined.LocalSources!["local_physical_damage_+%"]); + var prohibited = bound with { SkinTransferSource = b with { Mods = [Mod(items, "local_weapon_no_physical_damage", 1)] } }; + Assert.Equal(wa.LocalDamage![DamageType.Physical], Game.WeaponIn(skills, items, 3, (prohibited, wand))!.LocalDamage![DamageType.Physical]); + + var armour = items.All.First(t => t.Class == "Body Armour" && items.Defences(t) is { ArmourMin: > 0 }); + var ca = ItemCatalog.Create(armour) with { Quality = 20, Mods = [Mod(items, "local_physical_damage_reduction_rating_+%", 50)] }; + var cb = ItemCatalog.Create(armour) with { Quality = 10, Mods = [Mod(items, "local_physical_damage_reduction_rating_+%", 100)] }; + Assert.Equal(SkinTransferStats.Defences(ca, items).Armour + SkinTransferStats.Defences(cb, items).Armour, + SkinTransferStats.Defences(ca with { SkinTransferSource = cb }, items).Armour); + Assert.Equal(beforeA, Saved(a, items)); + Assert.Equal(beforeB, Saved(b, items)); + Assert.Equal(a.Wire(), (bound with { SkinTransferSource = null }).Wire()); + var payload = bound.Payload(); + Assert.Equal(0x40, System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian(payload.AsSpan(10))); + Assert.Equal(b.Payload(), payload.AsSpan(13, b.Payload().Length).ToArray()); // Base owns B, A's components stay separate + byte[] root = [.. payload.AsSpan(0, 13).ToArray(), .. payload.AsSpan(13 + b.Payload().Length).ToArray()]; + root[10] &= 0xbf; + Assert.Equal(a.Payload(), root); + Assert.Null(new ItemRolls(items).Mirror(bound)); + Assert.True(mod.Host.SetEnabled("equipmentfusion", false)); + Assert.Equal(60, SkinTransferStats.Sum([bound], items.Mods)["base_maximum_life"]); + var restored = Game.WeaponIn(skills, items, 3, (bound, wand))!; + foreach (var type in DamageTypes.ConversionOrder) + Assert.Equal(wa.LocalDamage![type], restored.LocalDamage![type]); + } + + [Fact] + public void Binding_reloads_switches_with_A_excludes_donor_skills_and_returns_B_atomically() + { + using var policy = EquipmentAttachmentPolicy.Use(new(true, true, true, true)); + string path = Path.Combine(Path.GetTempPath(), $"localexile-skin-transfer-{Guid.NewGuid():N}.db"); + string character = "SkinTransfer" + Guid.NewGuid().ToString("N"); + var previousLogic = Program.GameLogicOrNull; + Saves.Open(path); + Program.SetGameLogic(new GameServer.Modules.Game.GameLogic()); + var items = Program.Items; + var conn = new ClientState(new(1, "skin-transfer", 1000, 1000, 100, 100, null, []), 1, 1) + { + Character = character, PlayerLife = 1000, PlayerMana = 1000, Instance = new(), + Experience = CharacterStats.ExperienceFor(100), Pools = new(100, 1000, 1000, int.MaxValue, 0, + Strength: 1000, Dexterity: 1000, Intelligence: 1000), + LeagueModule = new(new League("test", "Standard", false, false), new HashSet(["Game"])), + }; + try + { + CharacterSaves.SetInventories(character, [], null); + var inventory = PlayerInventories.For(character, items); + var wand = items.All.First(t => t.Class == "Wand" && t.Supported); + var a = ItemCatalog.Create(wand) with { Mods = [Mod(items, "base_maximum_life", 60)] }; + var grant = items.Mods.All.First(m => m.GrantedEffects > 0 && m.Stats.Any(s => !s.Local)); + var trigger = items.Mods.All.First(m => m.Stats.Any(s => !s.Local && s.Id.Contains("trigger_a_socketed"))); + var gem = ItemCatalog.Create(items.Find("Metadata/Items/Gems/SkillGemFireball")!); + var b = ItemCatalog.Create(wand) with { Quality = 17, Mods = [Mod(items, "base_maximum_life", 80), + grant.Roll(ModSection.Explicit, new Random(1)), trigger.Roll(ModSection.Explicit, new Random(2))], + Sockets = [new(SocketColour.White, gem)], Links = [1] }; + string originalB = Saved(b, items), originalA = Saved(a, items); + var target = inventory.Add(PlayerInventories.Weapon1, 0, 0, a); + inventory.Add(PlayerInventories.Cursor, 0, 0, b); + var lifeKey = Program.Stats.Key("base_maximum_life")!.Value; + int initialLife = Game.CharacterStatSources(conn).Stats.GetValueOrDefault(lifeKey); + var binding = inventory.BindSkin(target.Id, Game.ShapeOf, out string why); + Assert.NotNull(binding); + Assert.Empty(inventory.Items(PlayerInventories.Cursor)); + Assert.Null(inventory.BindSkin(target.Id, Game.ShapeOf, out _)); + var contributions = SkinTransferStats.Sum([binding.Target.Item], items.Mods); + Assert.Equal(140, contributions["base_maximum_life"]); + Assert.Equal(initialLife + 80, Game.CharacterStatSources(conn).Stats.GetValueOrDefault(lifeKey)); + foreach (var stat in trigger.Stats.Where(s => !s.Local && s.Id.Contains("trigger_a_socketed"))) + Assert.False(contributions.ContainsKey(stat.Id)); + Assert.Empty(inventory.SocketedGems()); + Assert.Empty(Game.GemSkillEffects(conn)); + Assert.Null(inventory.Offer(PlayerInventories.Weapon1, target.Id, 0, 0, Game.ShapeOf)); + var look = inventory.Equipped(i => new VisibleItem(0, i.VisualIdentity)).Single(i => i.Slot == 0); + Assert.Equal(b.VisualIdentity, look.SkinVisual); + inventory.SwapWeaponSets(); + Assert.Empty(inventory.EquipmentSnapshot()); + Assert.Equal(initialLife - 60, Game.CharacterStatSources(conn).Stats.GetValueOrDefault(lifeKey)); + inventory.SwapWeaponSets(); + Assert.Same(binding.Target.Item, inventory.EquipmentSnapshot().Single().Item.Item); + + PlayerInventories.Forget(character); + inventory = PlayerInventories.For(character, items); + var loaded = inventory.Items(PlayerInventories.Weapon1).Single(); + Assert.Equal(originalA, Saved(loaded.Item with { SkinTransferSource = null }, items)); + Assert.Equal(originalB, Saved(loaded.Item.SkinTransferSource!, items)); + var occupied = inventory.Add(PlayerInventories.Cursor, 0, 0, a); + Assert.Null(inventory.UnbindSkin(target.Id, out _)); + inventory.Remove(PlayerInventories.Cursor, occupied.Id); + Saves.FailWrite = key => key == character; + Assert.Throws(() => inventory.UnbindSkin(target.Id, out _)); + Saves.FailWrite = null; + inventory = PlayerInventories.For(character, items); + Assert.NotNull(inventory.Items(PlayerInventories.Weapon1).Single().Item.SkinTransferSource); + Assert.Empty(inventory.Items(PlayerInventories.Cursor)); + var removed = inventory.UnbindSkin(target.Id, out why); + Assert.NotNull(removed); + Assert.Equal(originalA, Saved(removed.Target.Item, items)); + Assert.Equal(originalB, Saved(removed.Source.Item, items)); + Assert.Single(inventory.Items(PlayerInventories.Cursor)); + Assert.Equal(60, ItemModStats.Sum([removed.Target.Item], items.Mods)["base_maximum_life"]); + Assert.Equal(initialLife, Game.CharacterStatSources(conn).Stats.GetValueOrDefault(lifeKey)); + Assert.Null(inventory.UnbindSkin(target.Id, out _)); + PlayerInventories.Forget(character); + inventory = PlayerInventories.For(character, items); + Assert.Null(inventory.Items(PlayerInventories.Weapon1).Single().Item.SkinTransferSource); + Assert.Equal(originalB, Saved(inventory.Items(PlayerInventories.Cursor).Single().Item, items)); + var nativeB = inventory.Items(PlayerInventories.Cursor).Single(); + inventory.Remove(PlayerInventories.Cursor, nativeB.Id); + inventory.Put(PlayerInventories.MainInventory, nativeB); + Assert.Null(inventory.BindSkin(target.Id, PlayerInventories.MainInventory, PlayerInventories.MainInventory, + nativeB.Id, Game.ShapeOf, out _)); // stale target inventory + Assert.Null(inventory.BindSkin(target.Id, PlayerInventories.Weapon1, PlayerInventories.MainInventory, + nativeB.Id + 1000, Game.ShapeOf, out _)); // stale donor + var nativeBound = inventory.BindSkin(target.Id, PlayerInventories.Weapon1, PlayerInventories.MainInventory, + nativeB.Id, Game.ShapeOf, out _); + Assert.NotNull(nativeBound); + Assert.Equal(PlayerInventories.MainInventory, nativeBound.SourceRow); + Assert.Empty(inventory.Items(PlayerInventories.MainInventory)); + Assert.Equal(originalA, Saved(nativeBound.Target.Item with { SkinTransferSource = null }, items)); + Assert.Equal(originalB, Saved(nativeBound.Target.Item.SkinTransferSource!, items)); + Assert.Null(inventory.UnbindSkin(target.Id, out _, PlayerInventories.MainInventory)); + Assert.NotNull(inventory.Items(PlayerInventories.Weapon1).Single().Item.SkinTransferSource); + Assert.Null(inventory.BindSkin(target.Id, PlayerInventories.Weapon1, PlayerInventories.MainInventory, + nativeB.Id, Game.ShapeOf, out _)); // replay cannot consume another source + } + finally + { + Saves.FailWrite = null; + PlayerInventories.Forget(character); + Program.SetGameLogic(previousLogic!); + TestEnvironment.ReleaseSaves(path); + } + } + + sealed class AttachmentModFixture : IDisposable + { + readonly string _folder = Path.Combine(Path.GetTempPath(), "localexile-equipmentfusion-" + Guid.NewGuid().ToString("N")); + internal ModHost Host { get; } + internal AttachmentModFixture() + { + string mod = Path.Combine(_folder, "equipmentfusion"); + Directory.CreateDirectory(mod); + File.WriteAllText(Path.Combine(mod, "mod.json"), """{"id":"equipmentfusion","enabled":false}"""); + File.WriteAllText(Path.Combine(mod, "main.cs"), """ + public class TestMod : IMod + { + public void Load(IModContext mod) => EquipmentAttachmentPolicy.Use(mod.Manifest.Id, new(true, true, true, true)); + } + """); + Host = new ModHost(_folder, _ => { }); + Host.Start(watch: false); + } + public void Dispose() + { + Host.Dispose(); + Directory.Delete(_folder, recursive: true); + } + } + +} diff --git a/tests/GameServer.Gateway.Tests/TestEnvironment.cs b/tests/GameServer.Gateway.Tests/TestEnvironment.cs index b84d2724e..423d7ebaf 100644 --- a/tests/GameServer.Gateway.Tests/TestEnvironment.cs +++ b/tests/GameServer.Gateway.Tests/TestEnvironment.cs @@ -19,6 +19,7 @@ internal static void Initialize() GameServer.Storage.SqlUpdater.Update(GameServer.Core.ClientTables.DefaultPath, "client", log: _ => { }); // The game content (settings, catalogues, drop tables) from a scratch world.db, as the Gateway opens its own. GameData.Open(ScratchWorld); + Saves.Open(ScratchSaves); return; } throw new DirectoryNotFoundException("Gateway tests need a LocalExile checkout.");