aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 60397dff3d8e1177737f8511c87b71fd9e52dfa6
parent ebb24cbcbc335c77259feef6d4c27aee49463023
Author: anon <anon@example.com>
Date:   Thu, 22 Oct 2026 18:20:46 +0000

Support Treatment Laboratory healing and patient cooldowns

Diffstat:
MTODO.md | 4+++-
Adocs/treatment-kit.md | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/backpacks.go | 5++++-
Mserver/combat.go | 2++
Mserver/combat_test.go | 11+++++++++++
Mserver/inventory.go | 1+
Mserver/stacks.go | 2+-
Aserver/treatment_kit.go | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/treatment_kit_test.go | 248+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/users.go | 9+++++++++
10 files changed, 495 insertions(+), 3 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -224,13 +224,15 @@ remaining reward-rule gaps are recorded in [character progression](docs/characte the applicable quantity/charge and cannot be reused during its skill lock. - [x] Use one nano-restoring item. Check: nano recovery, consumption and its lock match that item rather than inheriting the health item's behavior. -- [ ] Use one sitting treatment kit. Check: it works in the permitted posture +- [x] Use one sitting treatment kit. Check: it works in the permitted posture and combat state and is rejected outside those conditions without consumption. The First Aid item, native charge protocol and unresolved combat-healing delivery are recorded in [First Aid research](docs/first-aid.md). Simple Nano Kit restoration, charge persistence, native teammate use and the shared First Aid lock are recorded in [nano kits](docs/nano-kit.md). +Treatment Laboratory posture, combat restrictions, patient locks and native +checks are recorded in [treatment kits](docs/treatment-kit.md). ## Character creation diff --git a/docs/treatment-kit.md b/docs/treatment-kit.md @@ -0,0 +1,121 @@ +# Treatment Laboratory + +The supported item is Treatment Laboratory25812, QL1, from the selected +14.9.1 database. Its record is at offset128476411 with payload SHA256 +`216cf2dc3a20028e17b718895a17f7ae746f6912192ba37d374086f4279e9dff`. + +## Authored behavior and native interpretation + +The laboratory carries 50 charges. Use3 restores exactly 30 Health27 to the +selected patient, runs graphics13600, and locks the patient's Treatment124 +for 15 seconds. Range is3 and AttackDelay is0. SkillTimeOnSelectedTarget371 +is1; native `kkr.dll` `1008ede0` rewrites SkillTime53033 targets to3 for this +setting. Activate's AddSkill53028 initializes the item's skill metadata; +it does not grant a character Treatment bonus. + +The Use3 expression checks the user's Treatment greater than7, combat410 +equal to0 and target-mask431 against35. Operator18 switches context to the +selected patient, who must have Sitting430 equal to2 and combat410 equal +to0. The repeated combat test before the switch still refers to the user. +The healer can stand while treating a sitting patient. Self-use requires +sitting because user and patient are the same actor. + +Stat410's original short and long names are `IsFightingMe` and +`Number of fighting opponents`. These are separate registry entries for the +same ID, at original `10031ca2` and `100366ca`, rather than conflicting stats. +The client stores the replicated value; its original server producer is +unknown. This reconstruction treats either an outgoing attack or an active +incoming attacker as combat, for both user and patient. The shipped +`cd_image/text/tips/LookatStartupTreatmentLaboratory.txt` describes treatment +after combat. A [September2001 PvP account](https://martin.brenner.de/ao/vampiguide/pvpguide.html#deal) +also reports kit restrictions after the attack bar became inactive, but +does not establish exact14.9.1 PvM combat expiry rules. + +The recovered ordinary right-click Use3 resource predicate `1008fda0` +does not itself query skill locks. UseOnCharacter32 has a separate lock +predicate `10090210`; it is not proof of ordinary Use3 GUI behavior. The +server enforces the authored patient lock. No recovered evidence justifies +additionally rejecting a standing healer whose own Treatment is locked +when the selected patient is unlocked. + +## Server and persistence + +Accepted use decrements the source charge and saves the patient's absolute +lock deadline in the source inventory's `treatment_locks` map, in one atomic +replacement. Only after this succeeds does the server update health and +publish success. The map can retain distinct patients treated within the +same15-second interval. Expired entries are pruned on the next accepted +treatment. Startup combines these receipts with each player's existing +clinic deadline, retaining the later deadline. This avoids a partial +two-player save while preserving the shared Treatment lock. + +Native proxy success consumes the charge; TemplateAction3 supplies the +item graphics to ready observers. HealthDamage carries the authoritative +clamped health with zero feedback delta. Use is rejected during incoming +or outgoing combat, where absolute HP could otherwise conflict with +queued weapon results. Ordinary stop/death/disconnect paths retain their +existing queue-flush behavior. Treatment does not interrupt combat to heal. +Starting an attack also clears the server's sitting state, matching native +AttackIIR `10078fc0` and its sitting-controller exit. This keeps posture +validation correct after combat ends. + +The item has Eat and Stackable, but lacks the stims' UseEmptyDestruct flag. +Native count helper `1005e790` decrements independently of that flag and +emits ItemRemoved at zero. The row getter returns zero exactly; resource +validation can still see the template's positive capacity, so retaining +the empty row permits ushort underflow on another accepted ACK. Explicit +CharacterAction112 completes the last-charge removal. The supported kit +also participates in the existing matching-template split/join paths. + +## Limits and verification + +The exact original server producer and expiry rules for combat410 remain +unrecovered. Full-health consumption is an implementation policy: there +is no full-health rejection in the authored expression. Friendly-player +permissions retain the nano kit's connected-player server subset and the +native client's stricter team gate. NPC/PvP categories, direct use inside +backpacks and general stack merge limits remain outside this milestone. +Health-restoring First Aid remains blocked by its separate combat delivery +problem; see [First Aid research](first-aid.md). + +Go tests cover exact healing, posture, skill, range, both combat directions +for healer and patient, shared clinic locks, replay/concurrent requests, +failed saves, closed-owner output, multiple patient locks across startup, +clamping, final-charge removal and exact expiry. Manual WASM verification +is recorded under `local/treatment-kit-smoke/`. + +The first WASM run verified standing rejection without consumption, sitting +self-use from200 to230 HP with50 to49 charges, and rejection during the +Treatment lock. An incoming-only Leet attack left the player's own attack +target empty while treatment consumed nothing; a read-only probe confirmed +a pending incoming weapon result during this check. A standing healer then +treated a sitting native teammate from10 to its37-HP maximum, consuming +49 to48 charges and locking only the patient. An immediate repeat consumed +nothing. Recipient native health and its mirror both reached37. + +Ctrl-click split48 charges into1 and47. After clearing the held-item/target +interaction and selecting self again, the single charge clamped server +health921 to922, removed its native row, and preserved the47-charge stack. +Lowering effective Treatment to7 produced the native requirement message +without consuming anything. A healer attacking the Leet also failed to +consume a charge when treating the sitting teammate. The test verifier +asserts the retained states and read-only native traces. Both clients +closed without a page or missing-adapter error. + +The fixture disabled server regeneration to isolate the laboratory's +authoritative30-HP gain. Native client regeneration continued independently: +self-use briefly synchronized both native health fields to230, followed by +a separate native15-HP sitting tick. These ticks are not laboratory healing; +the fixture does not establish continuous regeneration synchronization. + +A fresh build verified the attack-posture correction. Before attacking, +server sitting was true and native430 was2. Attack start changed them to +false and0 respectively. After stopping combat, standing self-use retained +all47 charges. This run also closed without client errors. + +The full `go test ./server/...` suite passed after the posture correction. +Three race-detector repetitions of treatment, portable-clinic, stack and +attack-posture tests also passed. +All test-owned clients and servers were closed before the final automated +checks, and the temporary WASM fixture binary was removed after recording +its SHA256. diff --git a/server/backpacks.go b/server/backpacks.go @@ -71,12 +71,15 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error client.useSequence = sequence if binary.BigEndian.Uint32(body[40:44]) == 104 { index := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { - return item.Slot == binary.BigEndian.Uint32(body[44:48]) && (item.Template == 43552 || item.Template == 85366) + return item.Slot == binary.BigEndian.Uint32(body[44:48]) && (item.Template == 43552 || item.Template == 85366 || item.Template == 25812) }) if index >= 0 { if player.inventory.Items[index].Template == 85366 { return server.useNanoKit_locked(client, index, body) } + if player.inventory.Items[index].Template == 25812 { + return server.useTreatmentKit_locked(client, index, body) + } return server.useClinic_locked(client, index, body) } } diff --git a/server/combat.go b/server/combat.go @@ -210,6 +210,8 @@ func (server *server) startAttack_locked(attacker, target *character, now time.T if attacker.fighting == target.id { return } + // AttackIIR exits the native sitting controller state before attacking. + attacker.sitting = false attacker.fighting = target.id attacker.nextAttack = now if attacker.nextAttack.Before(attacker.rechargeUntil) { diff --git a/server/combat_test.go b/server/combat_test.go @@ -59,6 +59,17 @@ func TestCombatTimesSwingsAndRetaliation(t *testing.T) { } } +func TestCombatStartingAttackStandsTheAttacker(t *testing.T) { + world, _ := newCombatWorld() + world.characters[1].sitting = true + + err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) + + if err != nil || world.characters[1].sitting || world.characters[1].fighting != 1000000 { + t.Fatalf("attack did not leave the sitting posture: %v", err) + } +} + func TestCombatRepeatedRequestsDoNotResetClockOrCatchUpTicks(t *testing.T) { world, conn := newCombatWorld() request := attackPacket(1, 1000000)[20:] diff --git a/server/inventory.go b/server/inventory.go @@ -31,6 +31,7 @@ type playerInventory struct { Reclaim []reclaimItem `yaml:"reclaim,omitempty"` Containers map[uint32][]ownedItem `yaml:"containers,omitempty"` FirstAidLockedUntil time.Time `yaml:"first_aid_locked_until,omitempty"` + TreatmentLocks map[uint32]time.Time `yaml:"treatment_locks,omitempty"` } func (inventory playerInventory) validate() error { diff --git a/server/stacks.go b/server/stacks.go @@ -8,7 +8,7 @@ import ( ) func (item ownedItem) isStackable() bool { - return item.Type == 51005 && (item.Template == 152030 && item.Quality == 42 || item.Template == 85366 && item.Quality == 1) + return item.Type == 51005 && (item.Template == 152030 && item.Quality == 42 || (item.Template == 85366 || item.Template == 25812) && item.Quality == 1) } func (server *server) changeStack_locked(client *worldClient, index int, body []byte) error { diff --git a/server/treatment_kit.go b/server/treatment_kit.go @@ -0,0 +1,95 @@ +package main + +import ( + "encoding/binary" + "maps" + "slices" + "time" +) + +func (server *server) useTreatmentKit_locked(client *worldClient, index int, body []byte) error { + player := server.characters[client.id] + item := player.inventory.Items[index] + target := server.characters[client.selectedTarget[1]] + stats := player.baseStats() + now := time.Now() + accepted := item.Type == 51005 && item.Template == 25812 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 && + client.selectedTarget[0] == 50000 && target != nil && !target.npc && target.health > 0 && target.sitting && + target.playfield == player.playfield && server.clients[target.id] != nil && server.clients[target.id].ready && !server.clients[target.id].loading && + stats.effectiveSkill(stats.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 7 && !now.Before(target.treatmentLockedUntil) && + player.fighting == 0 && target.fighting == 0 + if accepted { + // InBattle includes incoming combat; its original server producer is unknown. + for _, attacker := range server.fighting { + if attacker.fighting == player.id || attacker.fighting == target.id { + accepted = false + break + } + } + first := predictedPosition_locked(player, client, now) + second := predictedPosition_locked(target, server.clients[target.id], now) + x, y, z := first[0]-second[0], first[1]-second[1], first[2]-second[2] + distance := 3 + player.physicalExtent() + target.physicalExtent() + accepted = accepted && x*x+y*y+z*z <= distance*distance + } + if accepted { + // Save the charge and patient lock together, including uses on another player. + inventory := player.inventory + inventory.Items = slices.Clone(inventory.Items) + inventory.Items[index].Count-- + if inventory.Items[index].Count == 0 { + inventory.Items = slices.Delete(inventory.Items, index, index+1) + } + inventory.TreatmentLocks = maps.Clone(inventory.TreatmentLocks) + if inventory.TreatmentLocks == nil { + inventory.TreatmentLocks = make(map[uint32]time.Time) + } + for id, deadline := range inventory.TreatmentLocks { + if !now.Before(deadline) { + delete(inventory.TreatmentLocks, id) + } + } + inventory.TreatmentLocks[target.id] = now.Add(15 * time.Second) + if err := server.saveInventory_locked(player, inventory); err != nil { + return err + } + target.treatmentLockedUntil = inventory.TreatmentLocks[target.id] + target.health = min(target.maximumHealth(), target.health+30) + } + + reply := append([]byte(nil), body[16:]...) + binary.BigEndian.PutUint32(reply, 2) + if accepted { + binary.BigEndian.PutUint32(reply, 1) + } + if err := client.send(n3Packet(0x52526858, 50000, client.id, reply)); err != nil { + return err + } + if !accepted { + return nil + } + + // Native success consumes one charge; the template action supplies the graphics. + var action []byte + for _, value := range []uint32{25812, 25812, 1, 1, 3, 104, item.Slot, 50000, target.id} { + action = binary.BigEndian.AppendUint32(action, value) + } + updates := make(map[*worldClient][][]byte) + server.queueCombat_locked(updates, player, target, n3Packet(0x35505644, 50000, client.id, action)) + var health []byte + for _, value := range []uint32{target.health, 0, 0, 0} { + health = binary.BigEndian.AppendUint32(health, value) + } + server.queueCombat_locked(updates, target, target, n3Packet(0x3710256c, 50000, target.id, health)) + server.sendCombatUpdates(updates) + if item.Count == 1 { + var removal []byte + for _, value := range []uint32{112, 104, item.Slot, 25812, 25812} { + removal = binary.BigEndian.AppendUint32(removal, value) + } + if err := client.send(n3Packet(0x5e477770, 50000, client.id, removal)); err != nil { + return err + } + } + return server.clients[target.id].send(skillLockPacket(target.id, 124, 15)) +} diff --git a/server/treatment_kit_test.go b/server/treatment_kit_test.go @@ -0,0 +1,248 @@ +package main + +import ( + "encoding/binary" + "os" + "reflect" + "sync" + "testing" + "time" +) + +func newTreatmentKitWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + t.Chdir(t.TempDir()) + world, conn := newCombatWorld() + player := world.characters[1] + player.name, player.level, player.appearance = "Treatment Kit Owner", 1, 277 + player.rotation[3], player.stats = 1, defaultCharacterStats() + player.stats.Treatment, player.health, player.sitting = 6, 1, true + world.clients[1].selectedTarget = [2]uint32{50000, 1} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if granted, err := world.grantItem_locked(player, 25812); err != nil || !granted { + t.Fatal(granted, err) + } + return world, conn +} + +func TestTreatmentKitSelfUseHealsAndPersistsChargeWithLock(t *testing.T) { + world, conn := newTreatmentKitWorld(t) + player, started := world.characters[1], time.Now() + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t).characters[1] + + if err != nil || player.health != 31 || player.nano != 0 || player.inventory.Items[0].Count != 49 || !player.sitting || + !reflect.DeepEqual(restored.inventory.Items, player.inventory.Items) || !restored.inventory.TreatmentLocks[1].Equal(player.treatmentLockedUntil) || + !restored.treatmentLockedUntil.Equal(player.treatmentLockedUntil) || player.treatmentLockedUntil.Before(started.Add(15*time.Second)) || + player.treatmentLockedUntil.After(time.Now().Add(15*time.Second)) { + t.Fatalf("treatment health, charge or patient lock: player=%+v err=%v", player, err) + } + if len(conn.packets) != 4 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 1 || + binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x35505644 || binary.BigEndian.Uint32(conn.packets[1][61:65]) != 1 || + binary.BigEndian.Uint32(conn.packets[2][16:20]) != 0x3710256c || binary.BigEndian.Uint32(conn.packets[2][29:33]) != 31 || + binary.BigEndian.Uint32(conn.packets[3][41:45]) != 124 || binary.BigEndian.Uint32(conn.packets[3][45:49]) != 15 { + t.Fatalf("treatment native messages: %x", conn.packets) + } +} + +func TestTreatmentKitRejectsInvalidUseWithoutConsumption(t *testing.T) { + for _, scenario := range []string{"standing patient", "skill 7", "patient lock", "healer attacking", "patient attacking", "healer under attack", "patient under attack", "far", "loading patient", "dead patient", "npc", "other zone", "no target", "noncharacter", "wrong quality", "wrong type", "foreign owner", "failed save"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newTreatmentKitWorld(t) + player, client := world.characters[1], world.clients[1] + target := &character{id: 2, playfield: player.playfield, level: 1, appearance: 277, health: 1, sitting: true} + world.characters[2] = target + world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true} + client.selectedTarget = [2]uint32{50000, 2} + request := backpackUseRequest(1, 64, 1)[20:] + switch scenario { + case "standing patient": + target.sitting = false + case "skill 7": + player.stats.Treatment = 5 + case "patient lock": + target.treatmentLockedUntil = time.Now().Add(time.Minute) + case "healer attacking": + player.fighting = 1000000 + case "patient attacking": + target.fighting = 1000000 + case "healer under attack", "patient under attack": + npc := world.characters[1000000] + npc.fighting = 1 + if scenario == "patient under attack" { + npc.fighting = 2 + } + world.fighting[npc.id] = npc + case "far": + target.position[0] = 7.125 + case "loading patient": + world.clients[2].loading = true + case "dead patient": + target.health = 0 + case "npc": + target.npc = true + case "other zone": + target.playfield = 705 + case "no target": + client.selectedTarget = [2]uint32{} + case "noncharacter": + client.selectedTarget[0] = 51050 + case "wrong quality": + player.inventory.Items[0].Quality = 200 + case "wrong type": + player.inventory.Items[0].Type = 51022 + case "foreign owner": + binary.BigEndian.PutUint32(request[8:12], 2) + case "failed save": + os.Remove("data/players/1/inventory.yaml") + os.Mkdir("data/players/1/inventory.yaml", 0700) + } + before, health, deadline := player.inventory, target.health, target.treatmentLockedUntil + + err := world.handleOwnedItemUse(client, request) + + if (err != nil) != (scenario == "failed save") || !reflect.DeepEqual(before, player.inventory) || + target.health != health || !target.treatmentLockedUntil.Equal(deadline) { + t.Fatalf("rejected treatment changed health, charge or patient lock: %v", err) + } + }) + } +} + +func TestTreatmentKitStandingHealerTreatsDistinctPatientsAndRestoresLocks(t *testing.T) { + world, _ := newTreatmentKitWorld(t) + player, client := world.characters[1], world.clients[1] + player.sitting = false + player.treatmentLockedUntil = time.Now().Add(600 * time.Second) + connections := make(map[uint32]*combatTestConn) + for _, id := range []uint32{2, 3} { + world.characters[id] = &character{id: id, name: "Patient", playfield: player.playfield, position: [3]float32{7, 0, 0}, rotation: [4]float32{0, 0, 0, 1}, level: 1, appearance: 277, stats: defaultCharacterStats(), health: 1, sitting: true} + connections[id] = &combatTestConn{} + world.clients[id] = &worldClient{id: id, conn: connections[id], target: true, ready: true} + if err := world.saveUser_locked(world.characters[id]); err != nil { + t.Fatal(err) + } + } + + for _, id := range []uint32{2, 3} { + client.selectedTarget = [2]uint32{50000, id} + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, id)[20:]); err != nil { + t.Fatal(err) + } + } + restored := newTestInventoryServer(t) + + if player.inventory.Items[0].Count != 48 || player.health != 1 || player.sitting || len(player.inventory.TreatmentLocks) != 2 { + t.Fatalf("standing healer lost charge conservation or patient locks: %+v", player) + } + for _, id := range []uint32{2, 3} { + if world.characters[id].health != 31 || !restored.characters[id].treatmentLockedUntil.Equal(world.characters[id].treatmentLockedUntil) || + !restored.characters[1].inventory.TreatmentLocks[id].Equal(world.characters[id].treatmentLockedUntil) { + t.Fatalf("patient %d health or persistent lock", id) + } + locks := 0 + for _, packet := range connections[id].packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 170 { + locks++ + if binary.BigEndian.Uint32(packet[24:28]) != id { + t.Fatal("patient received another player's skill lock") + } + } + } + if locks != 1 { + t.Fatalf("patient %d received %d locks", id, locks) + } + } +} + +func TestTreatmentKitReplayLockExpiryAndClinicShareTreatment(t *testing.T) { + world, conn := newTreatmentKitWorld(t) + player, client := world.characters[1], world.clients[1] + if _, err := world.grantItem_locked(player, 43552); err != nil { + t.Fatal(err) + } + + world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) + deadline := player.treatmentLockedUntil + world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) + world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 2)[20:]) + world.handleOwnedItemUse(client, backpackUseRequest(1, 65, 3)[20:]) + world.advanceItemEffects(deadline.Add(-time.Nanosecond)) + locked := player.treatmentLockedUntil + world.advanceItemEffects(deadline) + world.advanceItemEffects(deadline.Add(time.Second)) + + if player.health != 31 || player.inventory.Items[0].Count != 49 || !locked.Equal(deadline) || !player.treatmentLockedUntil.IsZero() || !player.implantChangesUntil.IsZero() || + len(conn.packets) != 7 || binary.BigEndian.Uint32(conn.packets[4][29:33]) != 2 || binary.BigEndian.Uint32(conn.packets[5][29:33]) != 2 || + binary.BigEndian.Uint32(conn.packets[6][29:33]) != 164 || binary.BigEndian.Uint32(conn.packets[6][45:49]) != 124 { + t.Fatalf("treatment replay, clinic or expiry: player=%+v packets=%x", player, conn.packets) + } +} + +func TestTreatmentKitLastChargeClampsAndRemovesItem(t *testing.T) { + world, conn := newTreatmentKitWorld(t) + player := world.characters[1] + player.inventory.Items[0].Count, player.health = 1, 36 + + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t).characters[1] + + if err != nil || player.health != 37 || len(player.inventory.Items) != 0 || len(restored.inventory.Items) != 0 || + len(conn.packets) != 5 || binary.BigEndian.Uint32(conn.packets[3][29:33]) != 112 || binary.BigEndian.Uint32(conn.packets[3][37:41]) != 48 { + t.Fatalf("last-charge health or item removal: player=%+v err=%v", player, err) + } +} + +func TestTreatmentKitClinicLockRejectsTreatment(t *testing.T) { + world, _ := newTreatmentKitWorld(t) + player, client := world.characters[1], world.clients[1] + if _, err := world.grantItem_locked(player, 43552); err != nil { + t.Fatal(err) + } + + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 65, 1)[20:]); err != nil { + t.Fatal(err) + } + deadline := player.treatmentLockedUntil + err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 2)[20:]) + + if err != nil || player.health != 1 || player.inventory.Items[0].Count != 50 || !player.treatmentLockedUntil.Equal(deadline) || len(player.inventory.TreatmentLocks) != 0 { + t.Fatal("laboratory bypassed or replaced the clinic's Treatment lock") + } +} + +func TestTreatmentKitSavedChargeHealsDespiteClosedOwnerOutput(t *testing.T) { + world, _ := newTreatmentKitWorld(t) + client := world.clients[1] + client.writeWake, client.writeClosed = make(chan struct{}, 1), true + + err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) + + player := world.characters[1] + if err == nil || player.health != 31 || player.inventory.Items[0].Count != 49 || player.treatmentLockedUntil.IsZero() { + t.Fatalf("saved treatment charge lost its healing or lock: player=%+v err=%v", player, err) + } +} + +func TestTreatmentKitConcurrentUsesConsumeOnce(t *testing.T) { + world, _ := newTreatmentKitWorld(t) + var workers sync.WaitGroup + + for i := 0; i < 8; i++ { + workers.Add(1) + go func() { + defer workers.Done() + if err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]); err != nil { + t.Error(err) + } + }() + } + workers.Wait() + + if world.characters[1].health != 31 || world.characters[1].inventory.Items[0].Count != 49 { + t.Fatal("concurrent treatment consumed or healed more than once") + } +} diff --git a/server/users.go b/server/users.go @@ -208,6 +208,15 @@ func (server *server) loadUsers() error { server.nextCharacter = user.ID } } + + // Patient locks are saved with the healer's consumed inventory charge. + for _, player := range server.characters { + for id, deadline := range player.inventory.TreatmentLocks { + if patient := server.characters[id]; patient != nil && deadline.After(patient.treatmentLockedUntil) { + patient.treatmentLockedUntil = deadline + } + } + } return nil }