Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Agents/status/items-and-crafting.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 19 additions & 15 deletions Modules/Core/Game/Item/Equipment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,13 @@ public static bool PlayerHasEnergyShieldForRecovery(ClientState conn, Func<strin
var catalog = ItemsFor(conn);
foreach (byte row in new[] { PlayerInventories.BodyArmour, PlayerInventories.Helmet, PlayerInventories.Gloves, PlayerInventories.Boots, PlayerInventories.Offhand1 })
if (items.Items(row) is [var equipped, ..] && !IsInactive(conn, equipped.Id)
&& catalog.ByHash(equipped.Item.TypeHash) is { } type && catalog.Defences(type) is { } defences)
&& catalog.ByHash(equipped.Item.TypeHash) is { } type && catalog.Defences(type) is not null)
{
var (a, e, s) = ItemDefences.Calculate(equipped.Item, defences, catalog.Mods);
var (a, e, s, localWard) = SkinTransferStats.Defences(equipped.Item, catalog);
int percent = row == PlayerInventories.BodyArmour
? Math.Clamp(get?.Invoke("ward_instead_of_%_body_armour_and_evasion") ?? 0, 0, 100) : 0;
decimal armourWard = a * percent / 100m, evasionWard = e * percent / 100m;
var local = ItemModStats.Local(equipped.Item, catalog.Mods);
decimal ward = armourWard + evasionWard
+ (long)WardState.Max((decimal)defences.WardMin + local.GetValueOrDefault("local_ward"), local.GetValueOrDefault("local_ward_+%"))
* (100 + Math.Clamp((int)equipped.Item.Quality, 0, 100)) / 100;
decimal ward = armourWard + evasionWard + localWard;
yield return (row, (a - armourWard, e - evasionWard, s, ward));
}
}
Expand Down Expand Up @@ -98,12 +95,14 @@ public static SkillCatalog.Unarmed WeaponOf(ClientState conn, (Item Item, ItemCa
{
var unarmed = skills.UnarmedFor(classRow);
if (hand is not var (item, type) || type is null || skills.WeaponBase(type.Row) is not var (ms, min, max, range)) return null;
var local = ItemWeaponStats.Calculate(item, (ms, min, max, range), catalog.Mods);
var local = SkinTransferStats.Weapon(item, (ms, min, max, range), skills, catalog);
var physical = local.Damage[GameServer.Core.World.DamageType.Physical];
// The weapon's class decides Arcane Might's wand-only grant and the melee context of its own components.
return new SkillCatalog.Unarmed(local.AttackMs, (int)physical.Min, (int)physical.Max, Math.Max(range, unarmed.Range))
return new SkillCatalog.Unarmed(local.AttackMs, (int)Math.Clamp(physical.Min, 0, int.MaxValue),
(int)Math.Clamp(physical.Max, 0, int.MaxValue), Math.Max(range, unarmed.Range))
{
LocalDamage = local.Damage, LocalSources = ItemModStats.Local(item, catalog.Mods).ToFrozenDictionary(),
LocalDamage = local.Damage, ExactAttackMs = local.ExactAttackMs,
LocalSources = SkinTransferStats.Local(item, catalog.Mods).ToFrozenDictionary(),
WieldingWand = type.Class == "Wand", Bow = type.Class == "Bow", Melee = type.Class is not ("Wand" or "Bow"),
};
}
Expand All @@ -116,7 +115,7 @@ public static SkillCatalog.Unarmed WeaponOf(ClientState conn, (Item Item, ItemCa
public static (Dictionary<string, int> Main, Dictionary<string, int> Off) HandLocalStats(ClientState conn)
{
Dictionary<string, int> 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)));
}
Expand Down Expand Up @@ -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,
Expand All @@ -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"));
}
Expand All @@ -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<ItemCatalog.BaseType> OffhandTypes(ClientState conn)
{
Expand Down Expand Up @@ -235,6 +234,11 @@ public static IReadOnlyList<VisibleItem> 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))
Expand Down
5 changes: 4 additions & 1 deletion Modules/Core/Game/Item/ItemWeaponStats.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
/// <summary>A weapon's local item damage and duration, before character, skill and support modifiers.</summary>
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; }
}

/// <summary>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.</summary>
Expand Down
106 changes: 106 additions & 0 deletions Modules/Core/Game/Item/SkinTransferStats.cs
Original file line number Diff line number Diff line change
@@ -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<Item> Donors(IEnumerable<Item> items, ModCatalog mods) => (EquipmentAttachmentPolicy.Current.GlobalModifiers ? items : [])
.Select(i => i.SkinTransferSource).OfType<Item>()
.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<string, int> Sum(IEnumerable<Item> items, ModCatalog mods,
StatConditions.Subject subject = default, Func<string, bool>? 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<uint, int> Global(IEnumerable<Item> 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<string, long> RawAttributes(IEnumerable<Item> items, ModCatalog mods)
{
var equipped = items.ToArray();
return ItemModStats.RawAttributes(equipped.Concat(Donors(equipped, mods)), mods);
}

public static IEnumerable<Item> Items(Item item)
{
yield return item;
if (EquipmentAttachmentPolicy.Current.LocalDefences && item.SkinTransferSource is { } source) yield return source;
}

public static Dictionary<string, int> 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);
}
}
62 changes: 62 additions & 0 deletions Modules/Core/Game/Item/SkinTransfers.cs
Original file line number Diff line number Diff line change
@@ -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);
}
}
4 changes: 2 additions & 2 deletions Modules/Core/Game/Passive/Progression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,7 @@ static void AddCounts(Dictionary<uint, int> counts, IReadOnlyList<(uint Key, int
passiveAttributes[name] = passiveAttributes.GetValueOrDefault(name) + value;
Dictionary<string, long> RawAttributes(IEnumerable<Item> 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;
}
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion Modules/Core/Game/Player/DualWieldPanel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ public static (int PerUse, int PerSecond, int HundredTimesAttacksPerSecond) Aver
/// <summary>The off hand's swing time: its own duration (local speed included) at the off-hand increased attack
/// speed, at least one server tick.</summary>
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));
}
Loading
Loading