commit 19e2c9c9fae32eaa7fdf17d12ae8f0df5d3b3eaf
parent 96ba73e368fe4f3ab48bab01278ccd6c31644b33
Author: anon <anon@example.com>
Date: Tue, 3 Nov 2026 11:08:57 +0000
Implement durable native team loot modes and Alpha allocation
Diffstat:
16 files changed, 905 insertions(+), 42 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -2554,6 +2554,18 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
The original command/feedback protocol is retained in
`local/team-loot-research/wire-audit.md`; unresolved policies are listed in
`local/team-loot-research/server-audit.md`.
+ All/Leader/Alpha commands, feedback and durable captured rights now work.
+ Alpha advancement shares every killing-outcome transaction, including the
+ ranged round, nano cost and Fling lock; cursor/corpse/commit faults and retries
+ retain exact state. Three WASM clients type actual commands and collect five
+ exact drops through All, Leader and repeating Alpha turns. A separate fresh
+ server/WASM check retains Alpha, rejects the unassigned leader and collects
+ the designated non-killer's corpse without its original actor. Keep this
+ checkbox open for original allocation/collation, absent-member, roster-change
+ and existing-remains policies: current edge choices are explicitly provisional
+ in [team loot](docs/team-loot.md#selected-allocation-policy). Evidence:
+ `local/team-loot-modes/verification.json` (180 related Go roots/641 results,
+ 9 focused race roots/45 results, clean vet and 24 clean native traces).
- [ ] [P1] Recover and implement team money splitting. Check: original rules and
native receipts agree for eligible/remote/full-balance members, rollback,
concurrent Use and restart; the current first eligible looter receives cash.
diff --git a/docs/corpse-loot.md b/docs/corpse-loot.md
@@ -150,7 +150,8 @@ previous owner. Repeated and concurrent requests cannot take the same item
twice. Corpses, untaken contents and taken inventory survive reconnect and
server restart in SQLite. Entitlement follows individual or aggregate team
damage contribution as described below and in [team loot](team-loot.md).
-Public loot rights, Leader/Alpha orders and random drops remain separate work.
+Leader/Alpha orders and their selected allocation policies are described in
+[team loot](team-loot.md). Public rights release remains separate work.
[Corpse credits](corpse-credits.md) describes known-amount cash collection and
persistence. The level-1 Leet's corpse expiry is described below.
diff --git a/docs/team-loot.md b/docs/team-loot.md
@@ -1,20 +1,22 @@
# Team loot
-Accepted teams share the default All loot order. Damage from current teammates
+Accepted teams can select All, Leader or Alpha loot order. Damage from current teammates
counts toward one team total, independently of solo players and other teams.
The greatest total wins; the final hitter need not belong to that team. Current
-members can open its remains and take items under the ordinary visibility,
+members can open All remains and take items under the ordinary visibility,
session, life, playfield, range and expiry checks. Both Use and pickup recheck
membership. Leaving, being kicked or dissolving a team revokes open handles;
a newly formed team cannot inherit the old team's remains.
+Leader and Alpha remains also require their designated player to remain a
+current member. Team money splitting and the historical edge policies below
+remain unresolved.
## Original contract
The shipped 14.9.1 `cd_image/text/tips/OnSelectRemains.txt` assigns rights to
the player or team doing the majority of damage. `help/Team Commands.txt` and
`help/TeamHelp.txt` establish All as the default, Leader as leader-only, and
-Alpha as a repeating alphabetical order. Leader and Alpha are not implemented.
-Changing the loot order is therefore not acknowledged as a successful action.
+Alpha as a repeating alphabetical order.
Original `kkr.dll`, SHA256
`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`,
@@ -22,8 +24,10 @@ reads the corpse's team DWORD, mode DWORD and looter identity at
`100af9c0`. Activation `100afcb0` passes them to `1008c740`. With mode3 and
a matching local team stat6, it prints the native All-team entitlement message.
A null designated looter is accepted without the missing-looter warning.
-The server supplies the historical team ID, mode3 and null looter for team
-remains; solo remains retain their individual identity.
+The server supplies the awarded team ID, mode3 and null looter for All remains.
+Leader/Alpha remains use mode4/5 and the designated player's identity. Solo
+remains retain their individual identity. The short three-client check confirms
+the native All, named Leader and named Alpha entitlement messages.
Retained Ghidra observations, using original image-base addresses:
@@ -41,7 +45,38 @@ The independent original-code audit also recovered `/team loot` action145
and `/team loot MODE` action127 on CharacterAction `5e477770`. Set uses the
first identity's instance; query feedback uses the second. All=3, Leader=4,
Alpha=5. The source/address ledger is
-`local/team-loot-research/wire-audit.md`; these commands remain follow-up work.
+`local/team-loot-research/wire-audit.md`. Queries now answer only their owner;
+accepted setters notify ready members. Only the current leader can set modes,
+and the server whitelists3/4/5 and zero unused arguments. Failed or ignored writes
+publish neither configuration nor success. These recipient choices are current
+server policy; the client audit alone does not prove the original recipient set.
+
+## Selected allocation policy
+
+The core order descriptions above are shipped rules. The following edge choices
+are explicit reconstruction policy, pending period server/capture evidence:
+
+- Capture mode and designated player when an awarded corpse is committed.
+ Subsequent mode changes and leadership transfers do not reassign old remains.
+- Leader captures the leader at death. Alpha selects from the entire current
+ roster, including offline, dead or remote members. Current visibility, life,
+ range and membership checks still apply when that player tries to loot.
+- Alpha sorts names using SQLite's ASCII case-insensitive collation, then player
+ ID for ties. It selects the member after the last assigned ID, wrapping. If
+ that ID has left the roster, selection starts at its first member. Roster and
+ name changes are read afresh for each award.
+- Every awarded corpse advances Alpha, including an empty one. Opening,
+ refusals, cash collection and item pickup do not advance it. Switching away
+ from Alpha and back preserves its cursor.
+- Departure revokes designated access without assigning a substitute. Those
+ remains can become inaccessible until expiry under the current policy.
+
+The team stores its live order and last Alpha assignee. The corpse stores its
+captured order, team and designated player. Alpha advancement shares the same
+transaction as corpse state and generated items, plus ranged ammunition, nano
+cost or a special lock when applicable. There is no separate in-memory cursor
+to advance after a failed commit. Routine simulation keeps its existing
+checkpoint cadence. The broader original-policy TODO remains open.
## Accounting and durability
@@ -89,10 +124,36 @@ replacement teams, failed saves, restart during combat, immediate durable death,
and normal/nano/Fling awards. Broader verification and runtime captures are
retained in `local/team-loot-research/`.
-The full server suite passed (292.644s), along with gamedata tests (7.631s),
-focused race checks (101.312s) and the final team scenarios (12.139s). Full
-`go vet` reports the existing Go 1.24 declaration versus Go 1.25 `WaitGroup.Go`
-usage in concurrency tests; its other analyzers pass with `stdversion` disabled.
+`TestTeamLootOrder*` additionally covers the original query/set pair layouts,
+mode persistence, invalid modes/owners/arguments, ignored writes, alphabetical
+rotation, empty remains, roster/leader/mode changes and absent members. Cursor,
+corpse and COMMIT failures cover ordinary, ranged, Fling and nano kills with
+unchanged live/cold outcomes and exact retry. These tests verify the selected
+policies above, not their historical provenance.
+
+`TestBrowserTeamLootOrders` types real commands into three WASM clients and
+checks native queries, both members' notifications, foreign/undesignated Use
+refusal and actual pickup. Five controlled killing blows yield item assignments
+2/1/2/1/2 across All, Leader and three Alpha turns. Both page reconnects and a
+fresh database reader retain those exact instances and cash. This is controlled
+fixture evidence, not earned progression. Captures and current validation logs
+are under `local/team-loot-modes/`.
+
+`TestBrowserColdAlphaCorpsePickup` resumes a controlled prior Alpha cursor,
+commits the next awarded corpse, closes the database and starts a fresh server.
+Three fresh WASM clients query the retained mode, reject the unassigned leader
+and outsider, and let the designated non-killer collect and reopen the empty
+corpse without its former living actor. Collection leaves the stored cursor
+unchanged. Its captures are referenced by the current evidence report.
+
+The earlier All-only full-suite results are retained with their original
+`local/team-loot-research/` evidence. They do not validate the new modes.
+
+Current related Go checks pass 180 roots/641 results. Focused race checks pass
+9 roots/45 results, including simultaneous deaths. Vet and both native checks
+pass; all 24 saved native traces have no errors or dropped events. Exact scopes,
+source hashes, controlled-fixture limits and terminal results are recorded in
+`local/team-loot-modes/verification.json`.
Three WASM clients used the GPU/OpenGL renderer against the single HTTPS
preview. An ordinary production-server combat kill immediately persisted team 14
@@ -111,14 +172,13 @@ cash and NPC state were restored; team 14 was removed and owned browsers closed.
The production preview remains on HTTPS 8443. Assertions and limits are retained
in `local/team-loot-research/verification.json`.
-The earlier reconnect pass restored the native corpse object and server rights
-but could not locate clickable remains at its original camera/fixture placement.
-That does not establish a rendering defect or verify the replay's picking path.
-Interest replay order, original-actor prerequisites, mesh visibility and camera
-placement remain an explicit native audit TODO. Earlier fixture/harness setup
-failures are excluded from the successful runtime evidence above.
+The earlier reconnect pass could not locate clickable remains at its original
+camera/fixture placement. The maintained flat-ground cold checks now pick All
+and Alpha remains without their former living actors. Broader corpse placement
+and slope conformance remain separate native audit work.
-Remaining work includes Leader/Alpha allocation and persistence, native mode
-query/set feedback, team money splitting, original membership/disconnect and
+Remaining work includes original allocation edge policies, team money splitting,
+original membership/disconnect and
public unlock rules, and production drop tables. Team XP additionally requires
-the still-unimplemented base kill-XP award path and verified reward arithmetic.
+verified share arithmetic and historical base rewards; the existing solo kill-XP
+path uses explicitly provisional reward values.
diff --git a/docs/teams.md b/docs/teams.md
@@ -5,7 +5,8 @@ rosters and their leader persist atomically in SQLite before membership is
published. Each player belongs to at most one team, with at most six members.
This implements formation, leadership transfer and member removal. Private
[Team chat](team-chat.md) and [resource replication](team-resources.md) are also
-implemented; rewards and loot policy remain separate work.
+implemented. [Team loot orders](team-loot.md) now support All/Leader/Alpha;
+reward arithmetic and historical allocation edges remain separate work.
## Original client contract
diff --git a/server/browser_corpse_replay_test.go b/server/browser_corpse_replay_test.go
@@ -18,6 +18,15 @@ import (
)
func TestBrowserColdCorpsePickup(t *testing.T) {
+ testBrowserColdCorpsePickup(t, 3)
+}
+
+func TestBrowserColdAlphaCorpsePickup(t *testing.T) {
+ testBrowserColdCorpsePickup(t, 5)
+}
+
+func testBrowserColdCorpsePickup(t *testing.T, mode uint32) {
+ t.Helper()
if os.Getenv("AO_GAME_TEST") != "1" {
t.Skip("set AO_GAME_TEST=1 for the focused cold corpse check")
}
@@ -41,6 +50,15 @@ func TestBrowserColdCorpsePickup(t *testing.T) {
}
world.characters = players
formTestTeam(t, world, 1, 2)
+ if mode == 5 {
+ if err := world.handleTeamAction(world.clients[1], characterActionPacket(1, [5]uint32{127, 0, 5})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ // Resume a controlled prior Alpha turn before the killing outcome.
+ if _, err := world.db.Exec("UPDATE teams SET alpha_cursor=1 WHERE id=1"); err != nil {
+ t.Fatal(err)
+ }
+ }
world.characters[1000000] = &character{id: 1000000, name: "Cold Leet", npc: true,
playfield: 705, position: [3]float32{960, 16.5, 514}, rotation: [4]float32{0, 0, 0, 1},
appearance: 229, monsterData: 17655, level: 1, health: 1,
@@ -70,7 +88,8 @@ func TestBrowserColdCorpsePickup(t *testing.T) {
defer world.mutex.Unlock()
player := world.browserCharacter_locked(r)
json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "corpse": world.characters[1000000].corpse.items,
- "credits": world.characters[1000000].corpse.credits, "item": item, "expiresAt": world.characters[1000000].corpse.expiresAt})
+ "credits": world.characters[1000000].corpse.credits, "item": item, "expiresAt": world.characters[1000000].corpse.expiresAt,
+ "mode": world.characters[1000000].corpse.lootOrder + 3})
})
host := httptest.NewServer(mux)
t.Cleanup(host.Close)
@@ -93,5 +112,14 @@ func TestBrowserColdCorpsePickup(t *testing.T) {
len(restored.characters[1000000].corpse.items) != 0 || restored.characters[1000000].corpse.credits != 0 {
t.Fatal("cold corpse pickup did not preserve exact item/cash ownership")
}
+ if mode == 5 {
+ var cursor uint32
+ if err := restored.db.QueryRow("SELECT alpha_cursor FROM teams WHERE id=1").Scan(&cursor); err != nil {
+ t.Fatal(err)
+ }
+ if cursor != 2 || restored.characters[2].team.lootOrder != 2 || restored.characters[1000000].corpse.looter != 2 {
+ t.Fatal("cold Alpha replay or collection advanced/reassigned the captured turn")
+ }
+ }
t.Logf("Browser artifacts: %s", output)
}
diff --git a/server/browser_team_loot_order_test.go b/server/browser_team_loot_order_test.go
@@ -0,0 +1,140 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "testing"
+ "time"
+)
+
+func TestBrowserTeamLootOrders(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for native All/Leader/Alpha loot")
+ }
+
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/team-loot-modes", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ players := make(map[uint32]*character)
+ for index, name := range []string{"Zulu", "Alpha", "Visitor"} {
+ player := world.newCharacter()
+ player.name = name
+ player.playfield, player.position = 705, [3]float32{960 + float32(index), 16.5, 511}
+ player.rotation = [4]float32{0, 0, 0, 1}
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("team-loot-%d", player.id))))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ players[player.id] = player
+ }
+ world.characters = players
+ if err := world.saveTeam_locked(nil, &playerTeam{leader: 1, members: []uint32{1, 2}}); err != nil {
+ t.Fatal(err)
+ }
+ positions := [][3]float32{{960, 16.5, 514}, {958.8, 16.5, 514}, {961.2, 16.5, 514}, {959.4, 16.5, 515.5}, {960.6, 16.5, 515.5}}
+ for index, position := range positions {
+ id := 1000000 + uint32(index)
+ world.characters[id] = &character{id: id, name: "Loot-order Leet", npc: true, level: 1,
+ playfield: 705, position: position, rotation: [4]float32{0, 0, 0, 1}, health: 1,
+ appearance: 229, monsterData: 17655, npcDefinitionID: "950/district/2/group/0/authored_point",
+ combatProfile: gamedata.NPCCombatProfiles[17655][1]}
+ }
+ world.combatRoll = func(uint32) uint32 { return 0 }
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ drops := make(map[uint32]ownedItem)
+ mux := http.NewServeMux()
+ mux.Handle("/", world.httpHandler())
+ mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ inventories := make(map[uint32]playerInventory)
+ for id := uint32(1); id <= 3; id++ {
+ inventories[id] = world.characters[id].inventory
+ }
+ corpses := make(map[uint32]any)
+ for id := uint32(1000000); id < 1000005; id++ {
+ if corpse := world.characters[id].corpse; corpse != nil {
+ corpses[id] = map[string]any{"looter": corpse.looter, "mode": corpse.lootOrder + 3,
+ "items": corpse.items, "credits": corpse.credits}
+ }
+ }
+ json.NewEncoder(w).Encode(map[string]any{"players": inventories, "corpses": corpses,
+ "mode": world.characters[1].team.lootOrder + 3, "drops": drops})
+ })
+ for id := uint32(1000000); id < 1000005; id++ {
+ mux.HandleFunc(fmt.Sprintf("POST /test-kill/%d", id), func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ client := world.clients[1]
+ world.mutex.Unlock()
+ if err := world.handleCombat(client, attackPacket(1, id)[20:]); err != nil {
+ t.Error(err)
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ world.mutex.Lock()
+ deadline := world.characters[1].nextAttack
+ world.mutex.Unlock()
+ world.advanceCombat(deadline)
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ corpse := world.characters[id].corpse
+ if corpse == nil || len(corpse.items) != 1 {
+ t.Error("controlled death did not generate one item")
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ drops[id] = corpse.items[0]
+ })
+ }
+ host := httptest.NewServer(mux)
+ t.Cleanup(host.Close)
+ closeTestBrowserStreams(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
+ defer cancel()
+
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_team_loot_order.mjs"), host.URL, output)
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ err := command.Run()
+ t.Logf("Browser artifacts: %s", output)
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+ expected := make(map[uint32][]ownedItem)
+ for index, owner := range []uint32{2, 1, 2, 1, 2} {
+ id := 1000000 + uint32(index)
+ item := drops[id]
+ item.Slot = 64 + uint32(len(expected[owner]))
+ expected[owner] = append(expected[owner], item)
+ if len(cold.characters[id].corpse.items) != 0 || cold.characters[id].corpse.credits != 0 {
+ t.Fatal("native pickup did not retire its exact item and cash")
+ }
+ }
+ for id := uint32(1); id <= 3; id++ {
+ if !slices.Equal(cold.characters[id].inventory.Items, expected[id]) {
+ t.Fatal("native loot allocation changed physical identity or location")
+ }
+ }
+ var cursor uint32
+ if err := cold.db.QueryRow("SELECT alpha_cursor FROM teams WHERE id=1").Scan(&cursor); err != nil {
+ t.Fatal(err)
+ }
+ if cursor != 2 || cold.characters[1].team.lootOrder != 2 || cold.characters[1].inventory.Credits != 3 ||
+ cold.characters[2].inventory.Credits != 2 || cold.characters[3].inventory.Credits != 0 {
+ t.Fatal("cold mode/cursor/cash differs from native collection")
+ }
+}
diff --git a/server/loot.go b/server/loot.go
@@ -15,6 +15,7 @@ type npcCorpse struct {
items []ownedItem
credits uint32
expiresAt time.Time
+ lootOrder uint32
}
func corpsePacket(character *character) []byte {
@@ -50,12 +51,12 @@ func corpsePacket(character *character) []byte {
// The creation event holds the final death frame; an empty animation list
// makes n3VisualDynel_t::Run replace the otherwise valid model with a cube.
looterType := uint32(50000)
- if character.corpse.team != 0 {
+ if character.corpse.team != 0 && character.corpse.lootOrder == 0 {
looterType = 0
}
for _, value := range []uint32{2, 0, 1009, 3, 2018, 53003, 0, 4, 0, 1, 0, 0, 0xffffffff,
51050, character.id, monster.DeathAnimations[0], 1, 0,
- 50000, character.id, 1009, 0, character.corpse.team, 3, looterType, character.corpse.looter, 0} {
+ 50000, character.id, 1009, 0, character.corpse.team, 3 + character.corpse.lootOrder, looterType, character.corpse.looter, 0} {
body = binary.BigEndian.AppendUint32(body, value)
}
return n3Packet(0x4f474e05, 51050, character.id, body)
@@ -96,6 +97,9 @@ func (server *server) canLoot_locked(client *worldClient, corpse *character) boo
if team := server.characters[client.id].team; team == nil || team.id != corpse.corpse.team {
return false
}
+ if corpse.corpse.lootOrder != 0 && corpse.corpse.looter != client.id {
+ return false
+ }
} else if corpse.corpse.looter != client.id {
return false
}
diff --git a/server/main.go b/server/main.go
@@ -580,7 +580,7 @@ func (server *server) serveWorldClient(client *worldClient) error {
}
action := binary.BigEndian.Uint32(body[16:20])
switch action {
- case 22, 24, 25, 26, 28:
+ case 22, 24, 25, 26, 28, 127, 145:
if err := server.handleTeamAction(client, body); err != nil {
return err
}
diff --git a/server/npc_outcome.go b/server/npc_outcome.go
@@ -12,6 +12,11 @@ func (server *server) writeNPCOutcome_locked(tx *sql.Tx, target *character, now
if err != nil {
return npcState{}, err
}
+ if target.health == 0 && target.corpse != nil && server.characters[target.id].health != 0 {
+ if err := server.assignTeamLoot_locked(tx, target); err != nil {
+ return npcState{}, err
+ }
+ }
state := target.worldState(true, time.Time{})
if target.health == 0 {
state.Motion.Moving, state.Motion.Returning = false, false
diff --git a/server/team_loot_order.go b/server/team_loot_order.go
@@ -0,0 +1,89 @@
+package main
+
+import (
+ "database/sql"
+ "encoding/binary"
+ "fmt"
+ "slices"
+)
+
+func (server *server) handleTeamLootOrder_locked(client *worldClient, body []byte, updates map[*worldClient][][]byte) error {
+ team := server.characters[client.id].team
+ if team == nil {
+ return nil
+ }
+ if binary.BigEndian.Uint32(body[16:20]) == 145 {
+ if binary.BigEndian.Uint64(body[20:28]) != 0 || binary.BigEndian.Uint64(body[28:36]) != 0 {
+ return nil
+ }
+ updates[client] = append(updates[client], characterActionPacket(client.id, [5]uint32{145, 0, 0, 0, team.lootOrder + 3}))
+ return nil
+ }
+ mode := binary.BigEndian.Uint32(body[24:28])
+ if team.leader != client.id || binary.BigEndian.Uint32(body[20:24]) != 0 ||
+ binary.BigEndian.Uint64(body[28:36]) != 0 || mode < 3 || mode > 5 {
+ return nil
+ }
+ // Internal All/Leader/Alpha are 0/1/2; the original wire uses 3/4/5.
+ if team.lootOrder != mode-3 {
+ updated := *team
+ updated.lootOrder = mode - 3
+ if err := server.saveTeam_locked(team, &updated); err != nil {
+ return err
+ }
+ team = &updated
+ }
+ for _, member := range team.members {
+ if other := server.clients[member]; other != nil && other.ready && !other.loading {
+ updates[other] = append(updates[other], characterActionPacket(member, [5]uint32{127, 0, mode}))
+ }
+ }
+ return nil
+}
+
+func (server *server) assignTeamLoot_locked(tx *sql.Tx, target *character) error {
+ if target.corpse.team == 0 {
+ return nil
+ }
+ var order, leader, cursor uint32
+ err := tx.QueryRow("SELECT loot_order, leader_id, alpha_cursor FROM teams WHERE id=?", target.corpse.team).Scan(&order, &leader, &cursor)
+ if err == sql.ErrNoRows {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ target.corpse.lootOrder = order
+ if order == 1 {
+ target.corpse.looter = leader
+ return nil
+ }
+ if order != 2 {
+ return nil
+ }
+
+ // Capture alphabetical allocation at death, including absent current members.
+ rows, err := tx.Query("SELECT player_id FROM team_members JOIN characters ON characters.id=player_id WHERE team_id=? ORDER BY name COLLATE NOCASE, player_id", target.corpse.team)
+ if err != nil {
+ return err
+ }
+ var members []uint32
+ for rows.Next() {
+ var member uint32
+ if err := rows.Scan(&member); err != nil {
+ rows.Close()
+ return err
+ }
+ members = append(members, member)
+ }
+ err = rows.Err()
+ rows.Close()
+ if err != nil {
+ return err
+ }
+ if len(members) == 0 {
+ return fmt.Errorf("team %d has no Alpha roster", target.corpse.team)
+ }
+ target.corpse.looter = members[(slices.Index(members, cursor)+1)%len(members)]
+ return updateRecord(tx, "teams", target.corpse.team, "alpha_cursor", []any{target.corpse.looter})
+}
diff --git a/server/team_loot_order_test.go b/server/team_loot_order_test.go
@@ -0,0 +1,395 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "reflect"
+ "slices"
+ "sync"
+ "testing"
+)
+
+func TestTeamLootOrderQueryUsesOriginalDefaultMode(t *testing.T) {
+ world, connections := newTeamWorld(t)
+ formTestTeam(t, world, 1, 2)
+ connections[0].packets, connections[1].packets = nil, nil
+
+ err := world.handleTeamAction(world.clients[2], characterActionPacket(2, [5]uint32{145})[20:])
+
+ if err != nil || len(connections[0].packets) != 0 || len(connections[1].packets) != 1 ||
+ !bytes.Equal(connections[1].packets[0][16:], targetPacket(characterActionPacket(2, [5]uint32{145, 0, 0, 0, 3}))[16:]) {
+ t.Fatalf("native team loot query did not return All to its owner: leader %x, member %x, error %v", connections[0].packets, connections[1].packets, err)
+ }
+}
+
+func TestTeamLootOrderModesBroadcastQueryAndColdRestore(t *testing.T) {
+ for _, mode := range []uint32{3, 4, 5} {
+ t.Run(fmt.Sprint(mode), func(t *testing.T) {
+ world, connections := newTeamWorld(t)
+ formTestTeam(t, world, 1, 2)
+ for _, connection := range connections {
+ connection.packets = nil
+ }
+
+ if err := world.handleTeamAction(world.clients[1], characterActionPacket(1, [5]uint32{127, 0, mode})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleTeamAction(world.clients[2], characterActionPacket(2, [5]uint32{145})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+
+ if len(connections[0].packets) != 1 || len(connections[1].packets) != 2 || len(connections[2].packets) != 0 ||
+ world.characters[1].team.lootOrder != mode-3 || cold.characters[1].team.lootOrder != mode-3 ||
+ cold.characters[1].team != cold.characters[2].team {
+ t.Fatal("mode delivery or durable team state differs")
+ }
+ for _, connection := range connections[:2] {
+ if binary.BigEndian.Uint32(connection.packets[0][29:33]) != 127 || binary.BigEndian.Uint32(connection.packets[0][37:41]) != mode {
+ t.Fatal("set feedback uses the wrong original pair")
+ }
+ }
+ if binary.BigEndian.Uint32(connections[1].packets[1][29:33]) != 145 || binary.BigEndian.Uint32(connections[1].packets[1][45:49]) != mode {
+ t.Fatal("query feedback uses the wrong original pair")
+ }
+ })
+ }
+}
+
+func TestTeamLootOrderRejectsForgedAndFailedChanges(t *testing.T) {
+ for _, scenario := range []string{"zero", "team keyword", "loot keyword", "outside", "nonleader", "foreign owner", "not teamed", "first type", "second pair", "query arguments", "loading", "stale", "failed write", "ignored write"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, connections := newTeamWorld(t)
+ formTestTeam(t, world, 1, 2)
+ client := world.clients[1]
+ request := characterActionPacket(1, [5]uint32{127, 0, 4})[20:]
+ switch scenario {
+ case "zero", "team keyword", "loot keyword", "outside":
+ mode := map[string]uint32{"zero": 0, "team keyword": 1, "loot keyword": 2, "outside": 6}[scenario]
+ binary.BigEndian.PutUint32(request[24:28], mode)
+ case "nonleader", "not teamed":
+ owner := uint32(2)
+ if scenario == "not teamed" {
+ owner = 3
+ }
+ client = world.clients[owner]
+ request = characterActionPacket(owner, [5]uint32{127, 0, 4})[20:]
+ case "foreign owner":
+ binary.BigEndian.PutUint32(request[8:12], 2)
+ case "first type":
+ binary.BigEndian.PutUint32(request[20:24], 50000)
+ case "second pair":
+ binary.BigEndian.PutUint32(request[32:36], 1)
+ case "query arguments":
+ request = characterActionPacket(1, [5]uint32{145, 0, 4})[20:]
+ case "loading":
+ client.loading = true
+ case "stale":
+ world.clients[1] = &worldClient{id: 1}
+ case "failed write", "ignored write":
+ raise := "RAISE(FAIL, 'mode failure')"
+ if scenario == "ignored write" {
+ raise = "RAISE(IGNORE)"
+ }
+ if _, err := world.db.Exec("CREATE TRIGGER refuse_mode BEFORE UPDATE ON teams BEGIN SELECT " + raise + "; END"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ before := world.characters[1].team
+ for _, connection := range connections {
+ connection.packets = nil
+ }
+
+ err := world.handleTeamAction(client, request)
+ cold := newTestInventoryServer(t)
+
+ if (err != nil) != (scenario == "failed write" || scenario == "ignored write") ||
+ world.characters[1].team != before || !reflect.DeepEqual(cold.characters[1].team, before) {
+ t.Fatal("refused mode changed the team", err)
+ }
+ for _, connection := range connections {
+ if len(connection.packets) != 0 {
+ t.Fatal("refused mode sent success")
+ }
+ }
+ })
+ }
+}
+
+func newTeamLootOrderWorld(t *testing.T, mode uint32) *server {
+ t.Helper()
+ t.Chdir(t.TempDir())
+ world := newLootRightsWorld(t)
+ for index, name := range []string{"Zulu", "Alpha", "Beta"} {
+ player := world.characters[uint32(index+1)]
+ player.name = name
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ }
+ formTestTeam(t, world, 1, 2)
+ if err := world.handleTeamAction(world.clients[1], characterActionPacket(1, [5]uint32{127, 0, mode})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.characters[1000000].health = 1
+ world.characters[1000000].inventory.Items = nil
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ return world
+}
+
+func TestTeamLootOrderCapturedRightsAndNativeCorpseMetadata(t *testing.T) {
+ for _, scenario := range []struct {
+ mode uint32
+ looter uint32
+ access []uint32
+ }{{3, 0, []uint32{1, 2}}, {4, 1, []uint32{1}}, {5, 2, []uint32{2}}} {
+ t.Run(fmt.Sprint(scenario.mode), func(t *testing.T) {
+ world := newTeamLootOrderWorld(t, scenario.mode)
+ npc := world.characters[1000000]
+
+ if err := world.handleCombat(world.clients[2], attackPacket(2, npc.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(world.characters[2].nextAttack)
+ for id := uint32(1); id <= 3; id++ {
+ if err := world.handleLootUse(world.clients[id], teamLootUse(id, 1)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ cold := newTestInventoryServer(t)
+
+ if npc.health != 0 || npc.corpse == nil || npc.corpse.looter != scenario.looter || npc.corpse.lootOrder+3 != scenario.mode ||
+ cold.characters[npc.id].corpse.looter != scenario.looter || cold.characters[npc.id].corpse.lootOrder != npc.corpse.lootOrder {
+ t.Fatal("death did not capture and retain its loot mode")
+ }
+ for id := uint32(1); id <= 3; id++ {
+ allowed := false
+ for _, member := range scenario.access {
+ allowed = allowed || member == id
+ }
+ if (world.clients[id].lootCorpse == npc.id) != allowed {
+ t.Fatalf("mode %d grants the wrong access to player %d", scenario.mode, id)
+ }
+ }
+ packet := corpsePacket(npc)
+ length := int(binary.BigEndian.Uint16(packet[6:8]))
+ if binary.BigEndian.Uint32(packet[length-16:]) != scenario.mode || binary.BigEndian.Uint32(packet[length-8:]) != scenario.looter {
+ t.Fatal("native corpse mode or designated owner differs")
+ }
+ })
+ }
+}
+
+func TestTeamLootOrderFailedDeathRetainsCursorAndRetriesAtomically(t *testing.T) {
+ for _, attack := range []string{"unarmed", "pistol", "fling", "nano"} {
+ for _, failure := range []struct{ name, sql string }{
+ {"cursor", "CREATE TRIGGER refuse_loot BEFORE UPDATE OF alpha_cursor ON teams BEGIN SELECT RAISE(FAIL,'cursor'); END"},
+ {"ignored cursor", "CREATE TRIGGER refuse_loot BEFORE UPDATE OF alpha_cursor ON teams BEGIN SELECT RAISE(IGNORE); END"},
+ {"corpse", "CREATE TRIGGER refuse_loot BEFORE UPDATE ON npcs WHEN NEW.has_corpse=1 BEGIN SELECT RAISE(FAIL,'corpse'); END"},
+ {"commit", "CREATE TABLE pending_team_loot (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER refuse_loot AFTER UPDATE OF alpha_cursor ON teams BEGIN INSERT INTO pending_team_loot VALUES(999999); END"},
+ } {
+ t.Run(attack+"/"+failure.name, func(t *testing.T) {
+ world, output := newKillExperienceWorld(t, attack)
+ world.combatRoll = func(uint32) uint32 { return 0 }
+ player := world.characters[1]
+ player.name = "Zulu"
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ member := world.newCharacter()
+ member.name = "Alpha"
+ if err := world.saveUser_locked(member); err != nil {
+ t.Fatal(err)
+ }
+ world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: &combatTestConn{}, npcs: map[uint32]bool{1000000: true}}
+ formTestTeam(t, world, 1, 2)
+ if err := world.handleTeamAction(world.clients[1], characterActionPacket(1, [5]uint32{127, 0, 5})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ identity := world.nextItem
+ output.packets = nil
+ if _, err := world.db.Exec(failure.sql); err != nil {
+ t.Fatal(err)
+ }
+
+ if attack == "fling" {
+ if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]); err == nil {
+ t.Fatal("failed Fling assignment returned success")
+ }
+ } else {
+ attackForExperience(t, world, attack)
+ }
+ cold := newTestInventoryServer(t)
+ var cursor uint32
+ err := world.db.QueryRow("SELECT alpha_cursor FROM teams WHERE id=1").Scan(&cursor)
+
+ if err != nil || cursor != 0 || !player.skillLocks[150].IsZero() {
+ t.Fatal("failed death advanced Alpha or consumed Fling's lock", err)
+ }
+ for _, current := range []*server{world, cold} {
+ if current.characters[1000000].health != 1 || current.characters[1000000].corpse != nil || current.nextItem != identity {
+ t.Fatal("failed assignment committed death or item allocation")
+ }
+ }
+ for _, packet := range output.packets {
+ switch binary.BigEndian.Uint32(packet[16:20]) {
+ case 0x46002f16, 0x754f1115, 0x4727213e, 0x4f474e05:
+ t.Fatal("failed assignment published damage or a corpse")
+ }
+ }
+ if _, err := world.db.Exec("DROP TRIGGER refuse_loot"); err != nil {
+ t.Fatal(err)
+ }
+ attackForExperience(t, world, attack)
+ retried := newTestInventoryServer(t)
+ if err := world.db.QueryRow("SELECT alpha_cursor FROM teams WHERE id=1").Scan(&cursor); err != nil {
+ t.Fatal(err)
+ }
+ if cursor != 2 || retried.characters[1000000].corpse == nil || retried.characters[1000000].corpse.looter != 2 ||
+ retried.characters[1000000].corpse.lootOrder != 2 || len(retried.characters[1000000].corpse.items) != 1 || retried.nextItem != identity+1 {
+ t.Fatal("retried death failed to commit exactly one Alpha assignment and item")
+ }
+ })
+ }
+ }
+}
+
+func TestTeamLootOrderCapturedLeaderSurvivesModeAndLeadershipChanges(t *testing.T) {
+ world := newTeamLootOrderWorld(t, 4)
+ formTestTeam(t, world, 1, 3)
+ if err := world.handleCombat(world.clients[2], attackPacket(2, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(world.characters[2].nextAttack)
+
+ if err := world.handleTeamAction(world.clients[1], characterActionPacket(1, [5]uint32{127, 0, 3})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleTeamAction(world.clients[1], teamRequest(1, 25, 2, 0)); err != nil {
+ t.Fatal(err)
+ }
+ for id := uint32(1); id <= 2; id++ {
+ if err := world.handleLootUse(world.clients[id], teamLootUse(id, 1)); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ corpse := world.characters[1000000].corpse
+ if corpse.lootOrder != 1 || corpse.looter != 1 || world.clients[1].lootCorpse != 1000000 || world.clients[2].lootCorpse != 0 ||
+ world.characters[2].team.leader != 2 || world.characters[2].team.lootOrder != 0 {
+ t.Fatal("new live team settings reassigned an existing corpse")
+ }
+ if err := world.handleTeamAction(world.clients[1], teamRequest(1, 24, 0, 0)); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleLootUse(world.clients[1], teamLootUse(1, 2)); err != nil {
+ t.Fatal(err)
+ }
+ if world.clients[1].lootCorpse != 0 || world.characters[2].team.id != corpse.team {
+ t.Fatal("departed designated owner retained a usable team handle")
+ }
+ cold := newTestInventoryServer(t)
+ if cold.characters[1000000].corpse.looter != 1 || cold.characters[1000000].corpse.lootOrder != 1 || cold.characters[2].team.leader != 2 {
+ t.Fatal("cold replay changed the captured owner or current team leader")
+ }
+}
+
+func TestTeamLootOrderAlphaIncludesAbsentMembersAndRechecksRoster(t *testing.T) {
+ world := newTeamLootOrderWorld(t, 5)
+ base := *world.characters[1000000]
+ delete(world.clients, 2)
+ world.characters[2].playfield = 705
+ var owners []uint32
+
+ for index := uint32(0); index < 3; index++ {
+ if index == 1 {
+ formTestTeam(t, world, 1, 3)
+ } else if index == 2 {
+ if err := world.handleTeamAction(world.clients[1], teamRequest(1, 22, 3, 0)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ npc := base
+ npc.id = 1000000 + index
+ world.characters[npc.id] = &npc
+ world.clients[1].npcs[npc.id] = true
+ if err := world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(world.characters[1].nextAttack)
+ owners = append(owners, npc.corpse.looter)
+ }
+
+ if !reflect.DeepEqual(owners, []uint32{2, 3, 2}) {
+ t.Fatal("Alpha skipped an absent member or used a stale roster", owners)
+ }
+}
+
+func TestTeamLootOrderAlphaRotatesEmptyCorpsesAndSurvivesColdLoad(t *testing.T) {
+ world := newTeamLootOrderWorld(t, 5)
+ base := *world.characters[1000000]
+ var owners []uint32
+
+ for index := uint32(0); index < 3; index++ {
+ npc := base
+ npc.id = 1000000 + index
+ world.characters[npc.id] = &npc
+ world.clients[1].npcs[npc.id] = true
+ if err := world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(world.characters[1].nextAttack)
+ if npc.corpse == nil || len(npc.corpse.items) != 0 {
+ t.Fatal("fixture did not produce an empty awarded corpse")
+ }
+ owners = append(owners, npc.corpse.looter)
+ }
+ cold := newTestInventoryServer(t)
+ var cursor uint32
+ err := world.db.QueryRow("SELECT alpha_cursor FROM teams WHERE id=1").Scan(&cursor)
+
+ if err != nil || cursor != 2 || !reflect.DeepEqual(owners, []uint32{2, 1, 2}) || cold.characters[1].team.lootOrder != 2 {
+ t.Fatal("Alpha did not repeat alphabetical allocation durably", owners, cursor, err)
+ }
+ for index, owner := range owners {
+ if cold.characters[1000000+uint32(index)].corpse.looter != owner {
+ t.Fatal("cold loading changed an existing Alpha assignment")
+ }
+ }
+}
+
+func TestTeamLootOrderConcurrentDeathsAdvanceAlphaOnceEach(t *testing.T) {
+ world := newTeamLootOrderWorld(t, 5)
+ second := *world.characters[1000000]
+ second.id = 1000001
+ world.characters[second.id] = &second
+ world.clients[2].npcs[second.id] = true
+
+ if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleCombat(world.clients[2], attackPacket(2, second.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ deadline := world.characters[1].nextAttack
+ if world.characters[2].nextAttack.After(deadline) {
+ deadline = world.characters[2].nextAttack
+ }
+ var pending sync.WaitGroup
+ for range 2 {
+ pending.Go(func() { world.advanceCombat(deadline) })
+ }
+ pending.Wait()
+ cold := newTestInventoryServer(t)
+ var cursor uint32
+ err := world.db.QueryRow("SELECT alpha_cursor FROM teams WHERE id=1").Scan(&cursor)
+
+ owners := []uint32{cold.characters[1000000].corpse.looter, cold.characters[1000001].corpse.looter}
+ slices.Sort(owners)
+ if err != nil || cursor != 1 || !slices.Equal(owners, []uint32{1, 2}) {
+ t.Fatal("concurrent deaths repeated or skipped an Alpha turn", owners, cursor, err)
+ }
+}
diff --git a/server/teams.go b/server/teams.go
@@ -7,9 +7,10 @@ import (
)
type playerTeam struct {
- id uint32
- leader uint32
- members []uint32
+ id uint32
+ leader uint32
+ lootOrder uint32
+ members []uint32
}
type teamInvitation struct {
@@ -22,19 +23,19 @@ func (server *server) loadTeams() error {
if err != nil {
return err
}
- rows, err := db.Query("SELECT teams.id, leader_id, player_id FROM teams JOIN team_members ON team_id=teams.id ORDER BY teams.id, position")
+ rows, err := db.Query("SELECT teams.id, leader_id, loot_order, player_id FROM teams JOIN team_members ON team_id=teams.id ORDER BY teams.id, position")
if err != nil {
return err
}
defer rows.Close()
teams := make(map[uint32]*playerTeam)
for rows.Next() {
- var id, leader, member uint32
- if err := rows.Scan(&id, &leader, &member); err != nil {
+ var id, leader, order, member uint32
+ if err := rows.Scan(&id, &leader, &order, &member); err != nil {
return err
}
if teams[id] == nil {
- teams[id] = &playerTeam{id: id, leader: leader}
+ teams[id] = &playerTeam{id: id, leader: leader, lootOrder: order}
}
teams[id].members = append(teams[id].members, member)
server.characters[member].team = teams[id]
@@ -72,7 +73,7 @@ func (server *server) saveTeam_locked(previous, updated *playerTeam) error {
}
}
if previous == nil {
- result, err := tx.Exec("INSERT INTO teams (leader_id) VALUES (?)", updated.leader)
+ result, err := tx.Exec("INSERT INTO teams (leader_id, loot_order) VALUES (?, ?)", updated.leader, updated.lootOrder)
if err != nil {
return err
}
@@ -82,7 +83,7 @@ func (server *server) saveTeam_locked(previous, updated *playerTeam) error {
}
updated.id = uint32(id)
} else {
- if err := updateRecord(tx, "teams", updated.id, "leader_id", []any{updated.leader}); err != nil {
+ if err := updateRecord(tx, "teams", updated.id, "leader_id, loot_order", []any{updated.leader, updated.lootOrder}); err != nil {
return err
}
result, err := tx.Exec("DELETE FROM team_members WHERE team_id=?", updated.id)
@@ -221,6 +222,9 @@ func (server *server) handleTeamAction(client *worldClient, body []byte) error {
return nil
}
action := binary.BigEndian.Uint32(body[16:20])
+ if action == 127 || action == 145 {
+ return server.handleTeamLootOrder_locked(client, body, updates)
+ }
if action == 24 {
if binary.BigEndian.Uint64(body[20:28]) != 0 || binary.BigEndian.Uint64(body[28:36]) != 0 {
return nil
diff --git a/server/world.sql b/server/world.sql
@@ -181,7 +181,8 @@ CREATE TABLE IF NOT EXISTS npcs (
looter INTEGER NOT NULL,
loot_team INTEGER NOT NULL,
credits INTEGER NOT NULL,
- expires_at DATETIME NOT NULL
+ expires_at DATETIME NOT NULL,
+ loot_order INTEGER NOT NULL DEFAULT 0 CHECK (loot_order BETWEEN 0 AND 2)
);
CREATE TABLE IF NOT EXISTS npc_damage_contributors (
npc_id INTEGER NOT NULL REFERENCES npcs(id) ON DELETE CASCADE,
@@ -280,7 +281,9 @@ CREATE TABLE IF NOT EXISTS chat_history (
CREATE INDEX IF NOT EXISTS chat_owner ON chat_history(owner, id);
CREATE TABLE IF NOT EXISTS teams (
id INTEGER PRIMARY KEY AUTOINCREMENT CHECK (id BETWEEN 1 AND 4294967295),
- leader_id INTEGER NOT NULL REFERENCES players(id)
+ leader_id INTEGER NOT NULL REFERENCES players(id),
+ loot_order INTEGER NOT NULL DEFAULT 0 CHECK (loot_order BETWEEN 0 AND 2),
+ alpha_cursor INTEGER NOT NULL DEFAULT 0 CHECK (alpha_cursor BETWEEN 0 AND 4294967295)
);
CREATE TABLE IF NOT EXISTS team_members (
player_id INTEGER PRIMARY KEY REFERENCES players(id),
diff --git a/server/world_store.go b/server/world_store.go
@@ -20,6 +20,7 @@ type corpseState struct {
Team uint32
Credits uint32
ExpiresAt time.Time
+ LootOrder uint32
}
type npcState struct {
@@ -40,12 +41,12 @@ type savedNPC struct {
NextSave time.Time
}
-const npcColumns = "definition, present, respawn_at, leading_contributor, leading_team, idle_roaming, home_x, home_y, home_z, destination_x, destination_y, destination_z, next_move, moving, returning_home, has_corpse, looter, loot_team, credits, expires_at"
+const npcColumns = "definition, present, respawn_at, leading_contributor, leading_team, idle_roaming, home_x, home_y, home_z, destination_x, destination_y, destination_z, next_move, moving, returning_home, has_corpse, looter, loot_team, credits, expires_at, loot_order"
func (state *npcState) fields() []any {
return []any{&state.Definition, &state.Present, &state.RespawnAt, &state.LeadingContributor.player, &state.LeadingContributor.team, &state.IdleRoaming,
&state.Motion.Home[0], &state.Motion.Home[1], &state.Motion.Home[2], &state.Motion.Destination[0], &state.Motion.Destination[1], &state.Motion.Destination[2],
- &state.Motion.NextMove, &state.Motion.Moving, &state.Motion.Returning, &state.HasCorpse, &state.Corpse.Looter, &state.Corpse.Team, &state.Corpse.Credits, &state.Corpse.ExpiresAt}
+ &state.Motion.NextMove, &state.Motion.Moving, &state.Motion.Returning, &state.HasCorpse, &state.Corpse.Looter, &state.Corpse.Team, &state.Corpse.Credits, &state.Corpse.ExpiresAt, &state.Corpse.LootOrder}
}
func (npc *character) worldState(present bool, respawnAt time.Time) npcState {
@@ -58,7 +59,7 @@ func (npc *character) worldState(present bool, respawnAt time.Time) npcState {
}
if npc.corpse != nil {
state.HasCorpse = true
- state.Corpse = corpseState{npc.corpse.looter, npc.corpse.team, npc.corpse.credits, npc.corpse.expiresAt}
+ state.Corpse = corpseState{npc.corpse.looter, npc.corpse.team, npc.corpse.credits, npc.corpse.expiresAt, npc.corpse.lootOrder}
}
return state
}
@@ -107,7 +108,7 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[ui
leaving := server.npcZones[npc.playfield] && !zones[npc.playfield]
corpse := corpseState{}
if npc.corpse != nil {
- corpse = corpseState{npc.corpse.looter, npc.corpse.team, npc.corpse.credits, npc.corpse.expiresAt}
+ corpse = corpseState{npc.corpse.looter, npc.corpse.team, npc.corpse.credits, npc.corpse.expiresAt, npc.corpse.lootOrder}
}
// Loot transactions must persist corpse ownership and cash atomically.
lootChanged := npc.corpse != nil && (!exists || !previous.State.HasCorpse || previous.State.Corpse != corpse)
@@ -206,7 +207,7 @@ func (server *server) loadNPCs() (bool, error) {
}
}
if state.HasCorpse {
- npc.corpse = &npcCorpse{looter: state.Corpse.Looter, team: state.Corpse.Team, credits: state.Corpse.Credits, expiresAt: state.Corpse.ExpiresAt}
+ npc.corpse = &npcCorpse{looter: state.Corpse.Looter, team: state.Corpse.Team, credits: state.Corpse.Credits, expiresAt: state.Corpse.ExpiresAt, lootOrder: state.Corpse.LootOrder}
}
if state.Present {
server.characters[npc.id] = npc
diff --git a/tools/client/test_corpse_replay.mjs b/tools/client/test_corpse_replay.mjs
@@ -34,6 +34,22 @@ try {
assert.deepEqual(await server(owner), before);
await foreign.save(output + '/foreign-refusal');
+ if (before.mode === 5) {
+ const sequence = owner.sequence;
+ await owner.key('Enter');
+ await owner.page.keyboard.type('/team loot');
+ await owner.key('Enter');
+ await owner.wait('cold team retains Alpha mode', () => owner.events.some(event => event.sequence > sequence &&
+ event.direction === 'framereceived' && event.opcode === '5e477770' &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(29) === 145 && Buffer.from(event.hex, 'hex').readUInt32BE(45) === 5));
+ const leader = games[0], refusal = leader.sequence;
+ await leader.click(...await leader.pick(51050, 1000000), 'right');
+ await leader.wait('unassigned leader refused after cold Alpha replay', () => leader.events.some(event => event.sequence > refusal &&
+ event.direction === 'framereceived' && event.opcode === '52526858' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 2));
+ assert.deepEqual(await server(owner), before);
+ await leader.save(output + '/alpha-refusal');
+ }
+
await owner.page.bringToFront();
const [x, y] = await owner.pick(51050, 1000000);
await owner.click(x, y, 'right');
diff --git a/tools/client/test_team_loot_order.mjs b/tools/client/test_team_loot_order.mjs
@@ -0,0 +1,104 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import {createRequire} from 'node:module';
+import {GameTest} from './game_test.mjs';
+
+const {chromium} = createRequire(import.meta.url)('playwright');
+const [url, output] = process.argv.slice(2);
+const browser = await chromium.launch({executablePath: '/usr/bin/chromium',
+ args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage',
+ '--disable-background-timer-throttling', '--disable-renderer-backgrounding']});
+const games = [];
+const evidence = {collections: []};
+const action = event => event.opcode === '5e477770' ? Buffer.from(event.hex, 'hex').readUInt32BE(29) : 0;
+try {
+ for (let id = 1; id <= 3; ++id) {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'team-loot-' + id, url}]);
+ const page = await context.newPage();
+ const game = await GameTest.attach(page);
+ games.push(game);
+ await page.goto(url);
+ await game.ready();
+ if (id <= 2) await game.wait('team leader delivered', () => game.events.some(event =>
+ event.direction === 'framereceived' && action(event) === 35));
+ }
+ const server = async () => (await games[0].page.request.get(url + '/test-state')).json();
+ const command = async (game, text) => {
+ await game.key('Enter');
+ await game.page.keyboard.type(text);
+ await game.key('Enter');
+ };
+ const setMode = async (text, mode) => {
+ const sequences = games.map(game => game.sequence);
+ await command(games[0], '/team loot ' + text);
+ for (let index = 0; index < 2; ++index) await games[index].wait('native loot mode changed', () => games[index].events.some(event =>
+ event.sequence > sequences[index] && event.direction === 'framereceived' && action(event) === 127 &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(37) === mode));
+ assert.equal((await server()).mode, mode);
+ const sequence = games[1].sequence;
+ await command(games[1], '/team loot');
+ await games[1].wait('native current loot order', () => games[1].events.some(event => event.sequence > sequence &&
+ event.direction === 'framereceived' && action(event) === 145 && Buffer.from(event.hex, 'hex').readUInt32BE(45) === mode));
+ await games[1].save(output + '/mode-' + mode);
+ };
+ const use = async (game, id, accepted) => {
+ const sequence = game.sequence;
+ await game.click(...await game.pick(51050, id), 'right');
+ await game.wait('actual corpse Use result', () => game.events.some(event => event.sequence > sequence &&
+ event.direction === 'framereceived' && event.opcode === '52526858' &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(29) === (accepted ? 1 : 2)));
+ if (accepted) await game.wait('corpse loot window', state => state.regions.some(region =>
+ region[0] === 0 && region[1] === 0 && region[2] === 178 && region[3] === 128));
+ };
+ await setMode('all', 3);
+ for (const [index, owner] of [2, 1, 2, 1, 2].entries()) {
+ if (index === 1) await setMode('leader', 4);
+ if (index === 2) await setMode('alpha', 5);
+ const id = 1000000 + index;
+ assert((await games[0].page.request.post(url + '/test-kill/' + id)).ok());
+ for (const game of games) await game.wait('new typed corpse', state => state.actors.some(actor => actor.type === 51050 && actor.id === id));
+ const before = await server();
+ assert.equal(before.corpses[id].looter, index === 0 ? 0 : owner);
+ if (index === 0) {
+ await use(games[2], id, false);
+ assert.deepEqual(await server(), before);
+ await use(games[0], id, true);
+ await games[0].click(170, 8);
+ } else {
+ const denied = games[owner === 1 ? 1 : 0];
+ await use(denied, id, false);
+ assert.deepEqual(await server(), before);
+ await denied.save(output + '/refused-' + index);
+ }
+ const game = games[owner - 1];
+ await use(game, id, true);
+ const count = game.local().inventory.length;
+ await game.click(30, 45);
+ await game.wait('native assigned item collected', state => game.local(state).inventory.length === count + 1);
+ const after = await server();
+ const item = before.corpses[id].items[0];
+ assert(after.players[owner].Items.some(owned => owned.ID === item.ID && owned.Template === item.Template));
+ assert.deepEqual(after.corpses[id].items, []);
+ assert.equal(after.corpses[id].credits, 0);
+ evidence.collections.push({id, owner, item, mode: before.corpses[id].mode});
+ await game.save(output + '/collected-' + index);
+ await game.click(170, 8);
+ }
+ evidence.after = await server();
+ for (let index = 0; index < 2; ++index) {
+ const game = games[index];
+ await game.page.reload();
+ await game.ready();
+ const expected = evidence.after.players[index + 1].Items.map(item => [item.ID, item.Slot - 16, item.Count]);
+ assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.count]).sort((a, b) => a[0] - b[0]), expected);
+ }
+ assert(games.every(game => game.errors.length === 0));
+ console.log('PASS: real All/Leader/Alpha commands, native refusal/collection, repeating allocation and exact page/cold ownership');
+} finally {
+ try {
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n');
+ for (let index = 0; index < games.length; ++index) await games[index].save(output + '/final-' + (index + 1));
+ } finally { await browser.close(); }
+}