commit 0a87efbac73a313099f765dbf7a8f4d8cd616f58
parent 7f5d27c87dd99e391c9be51c7894ecc84ea3c0e3
Author: anon <anon@example.com>
Date: Thu, 22 Oct 2026 20:24:08 +0000
Award individual loot rights by accumulated damage
Diffstat:
5 files changed, 260 insertions(+), 6 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -187,8 +187,10 @@ are recorded in [reclaim](docs/reclaim.md).
corpse and remains owned after restart.
- [x] Resolve simultaneous pickup attempts. Check: two clients requesting the
same item produce one owner and no duplicate or lost item.
-- [ ] Enforce individual loot rights. Check: the entitled player can loot and
+- [x] Enforce individual loot rights. Check: the entitled player can loot and
an unrelated player cannot; expiry follows an explicit policy.
+- [ ] Release public loot rights. Check: a period-supported unlock rule allows
+ another player to loot, with an explicit relationship to corpse expiry.
- [x] Award and retain credits. Check: taking a known corpse credit amount
changes the balance once and survives reconnect and restart.
- [ ] Roll loot for one creature profile. Check: controlled rolls select the
diff --git a/docs/corpse-loot.md b/docs/corpse-loot.md
@@ -124,7 +124,7 @@ historical drop rate or a production loot table.
Left-clicking the displayed item emits `ContainerAddItem` (`0x47537a24`):
source identity `(107, 0)`, target player identity `(50000, playerID)`, and
destination 111, the next-free-slot sentinel. The request contains no corpse
-identity. The server validates the session's opened corpse, killer ownership,
+identity. The server validates the session's opened corpse, loot entitlement,
visibility, playfield and five-metre use range. It chooses an empty inventory
slot and atomically saves ownership before removing the corpse item. Its
ContainerAddItem response carries the chosen destination translated into the
@@ -135,12 +135,13 @@ update the corpse window without a replacement contents update.
Failed saves, full inventory, stale sessions and unavailable items retain the
previous owner. Repeated and concurrent requests cannot take the same item
twice. Corpses and untaken contents are currently runtime state; taken inventory
-survives reconnect and server restart. Killer-only access is an initial policy:
-public loot rights, team loot and random drops remain separate milestones.
+survives reconnect and server restart. Individual entitlement follows damage
+contribution as described below. Public loot rights, team loot and random
+drops remain separate milestones.
[Corpse credits](corpse-credits.md) describes known-amount cash collection and
persistence. The level-1 Leet's corpse expiry is described below.
-The two-player pickup check exercises the current killer-only policy.
+The two-player pickup check uses a kill by one entitled player.
`TestLootConcurrentPlayersHaveOnePersistentOwner` releases two authenticated
players' requests together, including a stale or forged container handle for
the competitor. Only the entitled player's request is acknowledged; its
@@ -161,6 +162,75 @@ This verifies pickup serialization and ownership checks, not historical public
or team loot eligibility. Captures and read-only native inventory probes are
retained in `local/loot-race-smoke/`.
+## Individual loot rights
+
+The shipped `cd_image/text/tips/OnSelectRemains.txt` assigns loot to the player
+or team inflicting the majority of damage. The contemporary
+[Vampi guide](https://martin.brenner.de/ao/vampiguide/pvpguide.html#looting),
+whose header says final update 13 September 2001, describes the most-damage
+player receiving rights, while qualifying its observations. A later
+[official FAQ](https://archive.anarchy-online.com/wsp/anarchy/frontend.cgi?func=publish.show&func_id=2269&table=CONTENT&template=content)
+also defines the killing team by most damage. Neither supplies a controlled
+three-contender result or an equal-damage tie rule.
+
+The server accumulates each player's applied HP damage for one NPC life and
+grants individual rights to the greatest contributor. Overkill contributes
+only remaining HP. Stopping and restarting attacks does not erase damage.
+Departure, death or a playfield change does not transfer an existing lead to
+another player; opening and taking still require the entitled player to be
+alive, connected, ready, nearby and in the same playfield. Respawn creates a
+new identity with no inherited contributions. Damage credit does not imply
+an XP reward; that remains unimplemented.
+
+Ties retain the first contributor to reach the tied total. Greatest damage
+without a strict majority, applied-damage accounting, contribution retention
+and this tie rule are explicit reconstruction policies where period evidence
+does not establish the exact arithmetic or reset behavior. NPCs currently do
+not heal or reset health during a life. Pets, teams and damage shields are
+outside the implemented combat scope.
+
+Entitlement lasts until the corpse's existing deadline; opening, closing and
+taking do not release rights. The level-1 Leet retains the provisional
+180-second death-based lifetime below. A
+[February 2002 Nuggetz guide](https://forums-archive.anarchy-online.com/showthread.php?11360-Guide-to-getting-Shades-of-Lucubration=)
+describes public looting roughly a minute after guards kill that unique NPC.
+It does not establish an ordinary Leet's public timer or an owner-close rule,
+so no public unlock duration has been invented.
+
+The native `CorpseFullUpdate` carries team ID, loot mode and looter identity.
+`100afcb0` passes them to `1008c740`, which stores the looter on the original
+hidden actor at offsets `0x12c/0x130` when that actor still resolves, and prints
+entitlement text. An absent original actor skips the store. The corpse's
+Use predicate `1009fcd0` returns eligible without checking the looter. Closing
+clears local container state without changing entitlement. Replaying creation
+does not update an existing corpse, and no public-unlock update path was
+recovered. Server-side authorization remains necessary for both Use and
+pickup. These addresses refer to the shipped `kkr.dll` at base `0x10000000`;
+the retained audit is `local/loot-rights-smoke/native-source-audit.json`.
+
+`TestLootRights*` covers competing contributors, changing leads, ties,
+three-way plurality, extreme overkill, stopped attacks, departure, fresh
+respawn, concurrent combat ticks, credit collection, item pickup and denial
+through stale handles before and after expiry. Source copies and remaining
+research gaps are retained in `local/loot-rights-smoke/source-ledger.json`.
+
+Two WASM clients contested an actual combat kill: player 2 dealt nine of
+thirteen HP, stopped attacking, and player 1 dealt the final four. Player 2
+received the native entitlement message, opened the corpse, collected 123
+fixture credits once across close/reopen, and took Monster Parts item 501,
+QL 1, Count 1. Player 1 selected the corpse and emitted a real native Use
+request but received no open handle, credits or item. Read-only native
+inventory probes found item 501 in player 2's native slot 48 and no items in
+player 1's inventory. Expiry removed the corpse and closed the open handle;
+both clients' subsequent Use input recovered nothing. A server restart and
+both page reloads preserved the same single item and balances, including the
+native client state. The first run also exercised contributor death and
+automatic removal at the unchanged 180-second deadline; the interaction run
+used tougher fixture characters and advanced expiry to its existing deadline.
+Neither run had page exceptions or adapter failures. Connection refusals were
+limited to the deliberate server restart. Captures, request logs and native
+probes are retained in `local/loot-rights-smoke/`.
+
## Corpse expiry
The shipped 14.9.1 `cd_image/text/help/combat.txt` states that an unlooted
diff --git a/server/combat.go b/server/combat.go
@@ -294,6 +294,17 @@ func (server *server) advanceCombat(now time.Time) {
}
}
target.health -= damage
+ // Keep individual contributions for this NPC life, including stopped attacks.
+ if target.npc && !attacker.npc {
+ if target.damageContributors == nil {
+ target.damageContributors = make(map[uint32]uint32)
+ }
+ target.damageContributors[attacker.id] += damage
+ // Equal totals retain the first contributor to reach that total.
+ if target.damageContributors[attacker.id] > target.damageContributors[target.leadingContributor] {
+ target.leadingContributor = attacker.id
+ }
+ }
attack, recharge := attacker.attackDelays()
attacker.rechargeUntil = now.Add(recharge)
attacker.nextAttack = attacker.rechargeUntil.Add(attack)
@@ -317,7 +328,8 @@ func (server *server) advanceCombat(now time.Time) {
if target.corpse == nil {
target.corpse = &npcCorpse{}
}
- target.corpse.looter = attacker.id
+ target.corpse.looter = target.leadingContributor
+ target.damageContributors = nil
if target.combatProfile != nil && target.combatProfile.CorpseSeconds != 0 {
target.corpse.expiresAt = now.Add(time.Duration(target.combatProfile.CorpseSeconds) * time.Second)
server.corpseExpiry = append(server.corpseExpiry, target)
diff --git a/server/loot_rights_test.go b/server/loot_rights_test.go
@@ -0,0 +1,167 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "sync"
+ "testing"
+ "time"
+)
+
+func newLootRightsWorld(t *testing.T) *server {
+ t.Helper()
+ world, _ := newCombatWorld()
+ for range 3 {
+ player := world.newCharacter()
+ player.position = [3]float32{}
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ world.clients[player.id] = &worldClient{id: player.id, conn: &combatTestConn{}, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}
+ }
+ // High melee AC makes ordinary fists deal exactly three damage.
+ npc := world.characters[1000000]
+ npc.monsterData = 17655
+ npc.inventory.Items = []ownedItem{{ID: 99, Type: 51022, Template: 85685, Quality: 200, Slot: 21, Count: 1}}
+ npc.combatProfile = &gamedata.NPCCombatProfile{Health: 100, RespawnSeconds: 100, CorpseSeconds: 180}
+ world.nextNPC = 1000001
+ return world
+}
+
+func TestLootRightsFollowAccumulatedDamageAcrossStoppedAttacks(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ health uint32
+ swings []uint32
+ owner uint32
+ }{
+ {"earlier contributor", 13, []uint32{2, 2, 2, 1, 1}, 2},
+ {"leader changes", 13, []uint32{2, 1, 1, 1, 2}, 1},
+ {"tie retains first leader", 6, []uint32{2, 1}, 2},
+ {"three contributors without majority", 19, []uint32{3, 3, 2, 1, 2, 1, 3}, 3},
+ {"overkill counts remaining health", 7, []uint32{2, 2, 1}, 2},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world := newLootRightsWorld(t)
+ npc := world.characters[1000000]
+ npc.health = scenario.health
+ if scenario.name == "overkill counts remaining health" {
+ world.characters[1].stats.MartialArts = 60000
+ }
+
+ for _, id := range scenario.swings {
+ if err := world.handleCombat(world.clients[id], attackPacket(id, npc.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(world.characters[id].nextAttack)
+ if err := world.handleCombat(world.clients[id], stopFightPacket(id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if npc.health != 0 || npc.corpse == nil || npc.corpse.looter != scenario.owner {
+ t.Fatalf("damage contribution did not determine loot rights: %+v", npc.corpse)
+ }
+ packet := corpsePacket(npc)
+ length := int(binary.BigEndian.Uint16(packet[6:8]))
+ if binary.BigEndian.Uint32(packet[length-8:]) != scenario.owner {
+ t.Fatal("native corpse announcement identified a different looter")
+ }
+ })
+ }
+}
+
+func TestLootRightsRejectFinalHitterAndSurviveCloseUntilExpiry(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world := newLootRightsWorld(t)
+ npc := world.characters[1000000]
+ npc.health = 7
+ for _, id := range []uint32{2, 2, 1} {
+ world.handleCombat(world.clients[id], attackPacket(id, npc.id)[20:])
+ world.advanceCombat(world.characters[id].nextAttack)
+ world.handleCombat(world.clients[id], stopFightPacket(id)[20:])
+ }
+ npc.corpse.items = []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Count: 1}}
+ npc.corpse.credits = 123
+ ownerUse := lootUseRequest(1)
+ binary.BigEndian.PutUint32(ownerUse[8:12], 2)
+ binary.BigEndian.PutUint32(ownerUse[36:40], 2)
+
+ world.handleLootUse(world.clients[1], lootUseRequest(1))
+ world.clients[1].lootCorpse = npc.id // A stale window cannot authorize pickup.
+ world.handleInventory(world.clients[1], lootTakeRequest())
+ world.handleLootUse(world.clients[2], ownerUse)
+ if world.clients[2].lootCorpse != npc.id || world.characters[2].inventory.Credits != 123 {
+ t.Fatal("entitled contributor could not open the corpse or collect credits")
+ }
+ binary.BigEndian.PutUint32(ownerUse[20:24], 2)
+ world.handleLootUse(world.clients[2], ownerUse)
+ world.handleLootUse(world.clients[1], lootUseRequest(2))
+ if world.characters[1].inventory.Credits != 0 || len(world.characters[1].inventory.Items) != 0 || len(npc.corpse.items) != 1 {
+ t.Fatal("closing released loot to the final hitter")
+ }
+ binary.BigEndian.PutUint32(ownerUse[20:24], 3)
+ world.handleLootUse(world.clients[2], ownerUse)
+ ownerTake := lootTakeRequest()
+ binary.BigEndian.PutUint32(ownerTake[8:12], 2)
+ binary.BigEndian.PutUint32(ownerTake[28:32], 2)
+ if err := world.handleInventory(world.clients[2], ownerTake); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCorpseExpiry(npc.corpse.expiresAt)
+ binary.BigEndian.PutUint32(ownerUse[20:24], 4)
+ world.handleLootUse(world.clients[2], ownerUse)
+
+ if world.clients[1].lootCorpse != 0 || world.clients[2].lootCorpse != 0 || world.characters[npc.id] != nil ||
+ len(world.characters[1].inventory.Items) != 0 || world.characters[1].inventory.Credits != 0 || len(npc.corpse.items) != 0 ||
+ len(world.characters[2].inventory.Items) != 1 || world.characters[2].inventory.Items[0].ID != 17 {
+ t.Fatal("final hit, stale handle, closing or expiry transferred loot rights")
+ }
+}
+
+func TestLootRightsConcurrentSwingsKeepOneDeathAndOwner(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world := newLootRightsWorld(t)
+ npc := world.characters[1000000]
+ npc.health = 7
+ world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:])
+ world.handleCombat(world.clients[2], attackPacket(2, npc.id)[20:])
+ first := world.characters[2].nextAttack
+ var workers sync.WaitGroup
+
+ for range 8 {
+ workers.Go(func() { world.advanceCombat(first) })
+ }
+ workers.Wait()
+ world.advanceCombat(world.characters[1].nextAttack)
+
+ if npc.health != 0 || npc.corpse == nil || npc.corpse.looter != 1 || len(world.npcRespawns) != 1 || len(world.corpseExpiry) != 1 {
+ t.Fatal("concurrent swings duplicated death or changed contribution ownership")
+ }
+}
+
+func TestLootRightsDoNotTransferWhenContributorLeavesAndRespawnStartsFresh(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world := newLootRightsWorld(t)
+ npc := world.characters[1000000]
+ npc.health = 7
+ world.handleCombat(world.clients[2], attackPacket(2, npc.id)[20:])
+ world.advanceCombat(world.characters[2].nextAttack)
+ world.advanceCombat(world.characters[2].nextAttack)
+ world.clients[2].ready = false
+ world.characters[2].playfield = 951
+
+ world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:])
+ killed := world.characters[1].nextAttack
+ world.advanceCombat(killed)
+ world.advanceNPCRespawns(killed.Add(100 * time.Second))
+ replacement := world.characters[1000001]
+ replacement.health = 1
+ world.handleCombat(world.clients[1], attackPacket(1, replacement.id)[20:])
+ world.advanceCombat(world.characters[1].nextAttack)
+
+ if npc.corpse.looter != 2 || replacement.corpse == nil || replacement.corpse.looter != 1 {
+ t.Fatal("departure reassigned loot or respawn inherited an old contribution")
+ }
+}
diff --git a/server/state.go b/server/state.go
@@ -37,6 +37,9 @@ type character struct {
npcDefinitionID string
roaming *npcRoaming
+ damageContributors map[uint32]uint32
+ leadingContributor uint32
+
browserTokenHash string
resurrectionTerminal uint32
implantChangesUntil time.Time