commit 50d1b3fcd9c9da28d5c1f69b39ff16db006f9bc0
parent 0e9711f1487e1ce3f2ebd846eea5364f2bf7839d
Author: anon <anon@example.com>
Date: Sat, 24 Oct 2026 23:46:38 +0000
Unify skill cooldowns and support catalog Nano Rechargers
Diffstat:
39 files changed, 937 insertions(+), 370 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -136,6 +136,15 @@ unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md).
qualities and rounding boundaries, including after equip/remove and restart.
- [x] Equip one implant. Check: its slot, treatment/ability requirements and
bonuses work independently of armor and weapon slots.
+- [ ] Expand implant admission to complete catalog contracts and slots.
+ Check Jobe SkillLockModifier382 sources, signed bonuses, strict requirements,
+ surgery access, removal and cold recovery with actual WASM gear changes.
+ Verify native OnWear replay order and countdown reconstruction under a changed
+ modifier when those real implant sources become usable.
+ Original modifier-only fixtures include chest178218/219, leg191026/027 and
+ hand193502/503; QL1 bonuses are positive and QL200 negative. Exact records are
+ retained in `local/skill-lock-research/catalog/`. Do not infer intermediate
+ qualities or silently admit unsupported OnWear effects.
- [x] Equip one belt. Check: the corresponding deck slots become available and
invalid belt removal cannot strand installed equipment.
- [x] Install one NCU memory. Check: available NCU changes by the item's amount
@@ -236,7 +245,8 @@ Normal-hit additions and weapon-range modifiers are described in
the action once, with native feedback and an enforced skill lock.
The Kinetic Axe now has a shared-handler Fast Attack normal-damage prototype.
Keep this open for critical selection, historical action gates, exact reuse
- floor/rounding and SkillLockModifier. See [Fast Attack](docs/fast-attack.md).
+ floor/rounding. Modifier scaling uses shared [skill locks](docs/skill-locks.md).
+ See [Fast Attack](docs/fast-attack.md).
Brawl's original content, capability gates, request/result and lock contracts
are recorded in [Brawl research](docs/brawl.md). Its own skill-to-QL selector
and stun outcome rules remain unproven; do not reuse MA's tentative selector
@@ -248,7 +258,7 @@ Normal-hit additions and weapon-range modifiers are described in
match the chosen action; repeated requests cannot bypass the lock.
Native Fling Shot requests, result feedback and persistent shared locks now
have a tested prototype. Keep this open until its critical damage/selection,
- exact recharge floor/rounding, SkillLockModifier and remaining action gates
+ exact recharge floor/rounding and remaining action gates
are evidenced. See [Fling Shot](docs/fling-shot.md).
- [ ] Verify Fling Shot's empty-clip, reload, equip/swap, cast, animation and
combat-start behavior. Check: period evidence and native tests distinguish
@@ -451,13 +461,20 @@ replay/failure tests and WASM checks are recorded in [IP training](docs/ip-train
both resources atomically. Shared catalog rules also cover the three authored
qualities of ordinary health laboratories and nano stims; see
[medical consumables](docs/medical-consumables.md).
-- [ ] Generalize persistent skill locks for Nano Rechargers and other SkillTime
+- [x] Generalize persistent skill locks for Nano Rechargers and other SkillTime
effects. Check: patient TimeSpace131 locks remain distinct from Treatment124
and user FirstAid123, survive restart and expire correctly. Apply the native
SkillLockModifier382 formula coherently on use and on lock reconstruction,
including equipment/nano modifiers and timing boundaries; avoid scaling the
remaining duration twice at login. Use the same rule across kits, clinics
and specials where their recovered contracts agree.
+ One actor-owned map/table now replaces separate inventory/patient/special
+ representations. The three authored rechargers, private native lock ownership,
+ simultaneous skills, cold restoration and last-charge deletion are verified.
+ Two racing healers share one patient lock; deleting a healer preserves it.
+ Modifier rounding and combined equipment/nano effects have regression coverage;
+ real Jobe implant admission and WASM modifier changes remain tracked above.
+ See [skill locks](docs/skill-locks.md).
The First Aid item, native charge protocol and unresolved combat-healing
delivery are recorded in [First Aid research](docs/first-aid.md).
diff --git a/docs/fast-attack.md b/docs/fast-attack.md
@@ -54,7 +54,8 @@ delay and skill, a float32 store after multiplication by15, then a500cs floor
and truncation. However, its only observed direct caller10079700 discards that
result. This proves client arithmetic, including a5s floor, without proving an
active local timer or the original server's floor/whole-second conversion.
-Resolving that difference and SkillLockModifier382 remains required.
+Resolving that base-duration difference remains required. Modifier382 and
+reconnect conversion use shared [skill-lock rules](skill-locks.md).
The attributed [15.5.5 patch notes](https://wiki.aodb.us/wiki/Patch_15.5#Version_15.5.5)
introduce defensive checks for Fast Attack and remove SkillLockModifier's reuse
diff --git a/docs/fling-shot.md b/docs/fling-shot.md
@@ -90,14 +90,14 @@ It triggers normal NPC retaliation and the existing contribution, corpse and
respawn lifecycle. Starting the player's normal attack automatically and
special firing animation/request forwarding remain unverified.
-`special_attack_locks` stores player, skill and an absolute deadline. Repeated
+`skill_locks` stores player, skill and an absolute deadline. Repeated
requests, swapping and reconnecting cannot create another Fling before that
deadline. Startup loads active locks;
initialization publishes their remaining native countdown. Expiry removes the
in-memory lock and emits action 164 once; no per-tick SQL writes are needed.
Expired rows are ignored at startup and overwritten on the next use.
-Profile edits preserve active locks. SkillLockModifier 382 is not yet accounted
-for in the authoritative special deadline or reconnect conversion.
+Profile edits preserve active locks. The authoritative deadline and reconnect
+conversion use shared [SkillLockModifier382 rules](skill-locks.md).
The handler prepares damage on a detached NPC copy, then commits the lock,
NPC HP, contributions and corpse/respawn state in one SQLite transaction before
diff --git a/docs/implants.md b/docs/implants.md
@@ -56,8 +56,9 @@ ownership checks and atomic inventory saves also apply.
The server saves absolute permission and cooldown deadlines before acknowledging
use. Repeated requests cannot extend either deadline. Reconnect/restart restores
the remaining window and cooldown, without re-executing the 30-second Use effect.
-Expiry removes the permission and unlocks Treatment. The supported profile has
-SkillLockModifier 382 equal to zero. Historical handling of portable permission
+Expiry removes the permission and unlocks Treatment. The cooldown uses shared
+[SkillLockModifier382 rules](skill-locks.md); its independent access window
+remains 30 seconds. Historical handling of portable permission
across zoning, death and server downtime remains unverified; retaining these
absolute deadlines is the current persistence policy.
diff --git a/docs/medical-consumables.md b/docs/medical-consumables.md
@@ -3,7 +3,7 @@
The server decodes immediate resource kits from their catalog functions,
requirements, quality, range and lock metadata. There are no template-ID
branches for medical use. The full catalog admission test currently identifies
-these seven definitions:
+these ten definitions:
| Template / authored QL | Item | Health | Nano | Lock |
| --- | --- | ---: | ---: | --- |
@@ -14,6 +14,9 @@ these seven definitions:
| 85366 / 1 | Simple Nano Kit | 0 | 10..12 | User First Aid 123, 40s |
| 85367 / 200 | Sophisticated Nano Kit | 0 | 1000 | User First Aid 123, 40s |
| 160295 / 400 | Ultra Sophisticated Nano Kit | 0 | 1500 | User First Aid 123, 40s |
+| 25820 / 1 | Basic Nano Recharger | 0 | 30 | Patient Time & Space 131, 20s |
+| 25821 / 200 | Advanced Nano Recharger | 0 | 2000 | Patient Time & Space 131, 20s |
+| 160278 / 400 | Advanced Nano Recharger | 0 | 5000 | Patient Time & Space 131, 20s |
Exact qualities are supported; no new interpolation endpoints are inferred.
The startup laboratory requires Treatment strictly greater than 5, while
@@ -67,17 +70,20 @@ five-record comparison and reused native evidence are retained under
The named search bounds the research; the Go admission test scans all templates.
Uniform inclusive rolls, full-resource consumption and absolute persisted lock
-lifetimes remain reconstruction policies. SkillLockModifier382 and raw-duration
-reconstruction on login need a shared cooldown audit. Nano Rechargers
-25820/25821/160278 require patient TimeSpace131 locks, beyond the current
-Treatment receipts. Emergency laboratories add53051; Purge kits add53177 and
+lifetimes remain reconstruction policies. Shared actor-owned deadlines,
+SkillLockModifier382 and raw-duration reconstruction on login are described in
+[skill locks](skill-locks.md). Nano Rechargers require user Treatment and Time
+& Space strictly greater than 7/7, 700/700 and 1500/1200 respectively. Both
+actors must be out of combat and the patient must sit. The patient's131 lock
+is distinct from Treatment124 and the user's FirstAid123.
+Emergency laboratories add53051; Purge kits add53177 and
different lock semantics. These functions must be implemented as complete
contracts before those items are admitted. General use from inside backpacks
and other quality families remain open.
## Verification
-Public item-use tests cover all seven admitted definitions, exact qualities,
+Public item-use tests cover all ten admitted definitions, exact qualities,
strict skill thresholds, posture, incoming/outgoing combat, inclusive range,
dead/loading/missing targets, unknown effects and predicates, independent
resource clamps, last-charge removal, replay and concurrent use. Injected
@@ -108,3 +114,4 @@ Passive regeneration remained enabled; short read-only native traces isolate
the kit's gains from regeneration ticks. Screenshots, WebSocket captures,
native observations, SQLite snapshots and fixture adjustments are retained
under `local/starter-laboratory-smoke/`. Both browser error lists were empty.
+
diff --git a/docs/skill-locks.md b/docs/skill-locks.md
@@ -0,0 +1,77 @@
+# Skill locks
+
+Each character owns a map from skill to absolute expiry. SQLite `skill_locks`
+stores the same `(player_id, skill, locked_until)` relation. Item charges,
+resource gains and the appropriate actor's lock commit together. Clinics
+commit Treatment124 with their separate surgery-access window. Fast Attack147
+and Fling150 commit their locks with the NPC damage/death outcome. Unrelated
+inventory edits do not save or remove cooldowns.
+
+The selected patient owns laboratory Treatment124 and Nano Recharger
+TimeAndSpace131 locks. Nano stims lock the user's FirstAid123. Different skills
+remain independent; a patient's lock survives deletion of the healer. There
+are no healer-owned receipts or inventory-specific cooldown fields.
+
+Expiry removes the in-memory entry and sends CharacterAction164 once. It does
+not write SQL on countdown ticks or expiry notifications. Startup ignores
+expired rows; another use overwrites that owner's row for the same skill.
+Profile edits, gear changes and reconnects preserve the original deadline.
+
+## Native calculation and replication
+
+Original kkr.dll `10073ae0` samples the locked actor's effective stat382 once.
+It multiplies signed 32-bit raw seconds and the modifier, retaining the low
+32 bits, scales the signed product by the original binary32 constant `0.01`,
+adds signed raw seconds and truncates toward zero through `_ftol`. The stored
+result is the low 32 bits. The server matches the translated WASM client's
+separate binary64 multiplication and addition; it does not substitute exact
+decimal percentages or round a negative value down.
+
+| Raw seconds | Modifier +5 | +50 | -5 | -50 |
+| ---: | ---: | ---: | ---: | ---: |
+| 15 | 15 | 22 | 14 | 7 |
+| 20 | 20 | 29 | 19 | 10 |
+| 40 | 41 | 59 | 38 | 20 |
+| 600 | 629 | 899 | 570 | 300 |
+
+Use-time action170 carries the authored raw duration. The server persists its
+already-scaled deadline. On a fresh connection, it instead finds the smallest
+raw argument whose native calculation reaches `ceil(deadline-now)` under the
+current modifier. Sending scaled remaining seconds directly would scale the
+cooldown twice. Positive modifiers can leave integer gaps in representable
+durations; authoritative expiry164 removes any excess client countdown.
+An existing native lock ignores another action170, including after gear changes.
+
+This reproduces the proven ordinary-duration contract. Original x87 precision
+control remains unpinned; pathological billion-second inputs can differ from
+the translated client's binary64 result. Native one-second countdown phase can
+also differ from the server's wall-clock expiry by less than one second.
+If gear changes to modifier <= -100 during a positive lock, ordinary positive
+raw arguments cannot reconstruct its countdown. The server preserves the
+deadline and expiry notification but omits an unrepresentable start. No
+negative-argument or integer-overflow trick is used to fabricate a display.
+
+## Evidence and checks
+
+The original binary hash, 19 complete retained REA records, translated source,
+53 arithmetic fixtures, exact removal route and inverse examples are under
+`local/skill-lock-research/native/`. Setter assembly evidence is
+`ev_7b0b159708714234fe2b12acaa00c1561360f684f87d83a192764c032f4d5787`;
+removal is `ev_d3c272efae71f0e9f1fb434009133f7fd20de4805140ed3e5fafc0a54d9c7a17`.
+
+Tests exercise public kit, clinic, equipment-move and special-attack handlers,
+cold reopening, recipient ownership, unrelated skills, last-charge rollback,
+reconnect conversion and one-time expiry without database churn. Modifier
+aggregation tests substitute complete OnWear/nano Modify effects to isolate the stat;
+they do not claim that implant101173 originally modifies382. The original
+modifier sources are Jobe implants/components and require further implant
+catalog support before ordinary players can use those sources. Their complete
+records and original-payload verification are under
+`local/skill-lock-research/catalog/`.
+
+The full Go suite passed in 577.287 seconds, with focused race tests passing
+in 112.788 seconds and vet clean. Supplemental normal/race runs verify combined
+modifiers; a separate 94.251-second race run verifies that two competing
+healers restore once and consume only one charge for the same patient.
+Logs are under `local/skill-lock-research/`.
+
diff --git a/docs/treatment-kit.md b/docs/treatment-kit.md
@@ -45,15 +45,15 @@ when the selected patient is unlocked.
## Server and persistence
Accepted use commits the source charge, the patient's absolute lock deadline
-in the source inventory's `treatment_locks` map, and the recipient's clamped
-health and any authored nano gain together in one SQLite transaction. Only
+in `skill_locks`, and the recipient's clamped health and any authored nano gain
+together in one SQLite transaction. Only
after commit does the server publish the in-memory inventory, health and lock
and acknowledge 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.
+Different patients have independent deadlines in the same 15-second interval.
+Expired entries are ignored on startup and overwritten on the next accepted
+treatment. Clinics and laboratories share the same patient Treatment124 row,
+so either blocks the other until expiry. Modifier scaling, reconnect and
+expiry notification use shared [skill-lock rules](skill-locks.md).
Native proxy success consumes the charge; TemplateAction3 supplies the
item graphics to ready observers. HealthDamage carries the authoritative
diff --git a/docs/world-state.md b/docs/world-state.md
@@ -6,8 +6,8 @@ The database contains:
- `world`: item/player/NPC identity counters and the clock's starting time.
- `characters`: individual profile, ability/skill, appearance, position and vital columns.
-- `players`: player identity, credits and first-aid cooldown.
-- `learned_nanos` and `treatment_locks`: one row per learned program or patient lock.
+- `players`: player identity and credits.
+- `learned_nanos` and `skill_locks`: one row per learned program or actor/skill lock.
- `npcs`: live NPC poses, health, roaming state, damage contributors, corpse
cash/ownership/expiry and respawn deadlines, including expired actors whose
replacements are still pending.
@@ -27,13 +27,14 @@ changes, corpse loot transfers and cash transfers commit atomically before
success is published. Profiles and admin clock changes save immediately.
Player movement and routine vitals save at staggered 20-second intervals. The
one-second world checkpoint does not rewrite player resources, inventory
-metadata, learned programs or treatment locks. Inventory actions still save
+metadata, learned programs or skill locks. Inventory actions still save
their significant changes immediately. Inventory metadata belongs to the acting
player, so another player's expired-cooldown notification cannot be folded
-into the transaction. Inventory transactions update credits
-and first-aid cooldowns only when their scalar values change. Patient-lock
-rows retain unchanged deadlines; learned programs retain existing members of
-the set. Removed entries are deleted only for their owning player. These
+into the transaction. Inventory transactions update credits only when they
+change. Skill locks save with the action that starts them, independently of
+inventory metadata; expiry notifications only update memory. Learned programs
+retain existing members of the set. Removed programs are deleted only for
+their owning player. These
transactions do not checkpoint unrelated players' routine vitals. An equipment
change that limits current health or nano commits that clamp with ownership;
explicit character edits and full world flushes retain their resource saves.
diff --git a/server/character_initialization_test.go b/server/character_initialization_test.go
@@ -107,7 +107,7 @@ func TestFreshCharacterNanoKitRequiresTrainingWithoutLosingCharges(t *testing.T)
if err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]); err != nil {
t.Fatal(err)
}
- if player.inventory.Items[0].Count != 25 || player.nano != 0 || !player.inventory.FirstAidLockedUntil.IsZero() {
+ if player.inventory.Items[0].Count != 25 || player.nano != 0 || !player.skillLocks[123].IsZero() {
t.Fatal("untrained use consumed the kit or supplied its effect")
}
proposed := player.stats
@@ -121,7 +121,7 @@ func TestFreshCharacterNanoKitRequiresTrainingWithoutLosingCharges(t *testing.T)
restored := newTestInventoryServer(t).characters[1]
if player.stats.ImprovementPoints != 1478 || restored.stats.NanoAiding.FirstAid != 7 || restored.inventory.Items[0].Count != 24 ||
- restored.nano < 10 || restored.nano > 12 || restored.inventory.FirstAidLockedUntil.IsZero() {
+ restored.nano < 10 || restored.nano > 12 || restored.skillLocks[123].IsZero() {
t.Fatal("trained fresh player lost its IP, charge, nano gain or cooldown")
}
}
diff --git a/server/checkpoint_test.go b/server/checkpoint_test.go
@@ -27,8 +27,8 @@ func newCheckpointWorld(t *testing.T) *server {
}
inventory := player.inventory
inventory.Credits, inventory.LearnedNanos = 42, []uint32{43324}
- inventory.FirstAidLockedUntil = time.Now().Add(time.Minute)
- inventory.TreatmentLocks = map[uint32]time.Time{1: time.Now().Add(time.Minute)}
+ setTestSkillLock(t, world, player, 123, time.Now().Add(time.Minute))
+ setTestSkillLock(t, world, player, 124, time.Now().Add(time.Minute))
if err := world.saveInventory_locked(player, inventory); err != nil {
t.Fatal(err)
}
@@ -43,7 +43,7 @@ func auditCheckpointWrites(t *testing.T, world *server) {
if _, err := world.db.Exec("CREATE TABLE checkpoint_writes (table_name TEXT, operation TEXT)"); err != nil {
t.Fatal(err)
}
- for _, table := range []string{"world", "characters", "players", "learned_nanos", "treatment_locks", "items", "item_locations", "npcs", "npc_damage_contributors"} {
+ for _, table := range []string{"world", "characters", "players", "learned_nanos", "skill_locks", "items", "item_locations", "npcs", "npc_damage_contributors"} {
for _, operation := range []string{"INSERT", "UPDATE", "DELETE"} {
query := "CREATE TRIGGER audit_" + table + "_" + operation + " AFTER " + operation + " ON " + table +
" BEGIN INSERT INTO checkpoint_writes VALUES ('" + table + "','" + operation + "'); END"
@@ -199,8 +199,8 @@ func TestInventoryUseAfterWorldCheckpointStillCommitsImmediately(t *testing.T) {
err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:])
restored := newTestInventoryServer(t).characters[1]
- if err != nil || restored.inventory.Items[0].Count != 24 || restored.inventory.FirstAidLockedUntil.Before(now.Add(40*time.Second)) ||
- !restored.inventory.FirstAidLockedUntil.Equal(world.characters[1].inventory.FirstAidLockedUntil) {
+ if err != nil || restored.inventory.Items[0].Count != 24 || restored.skillLocks[123].Before(now.Add(40*time.Second)) ||
+ !restored.skillLocks[123].Equal(world.characters[1].skillLocks[123]) {
t.Fatal("world checkpoint deferred or lost an important charge/lock save", err)
}
}
diff --git a/server/consumable_outcome_test.go b/server/consumable_outcome_test.go
@@ -16,7 +16,7 @@ type consumableCommitConn struct {
health uint32
nano uint32
count uint16
- firstAid time.Time
+ firstAid sql.NullTime
patient sql.NullTime
err error
}
@@ -27,10 +27,11 @@ func (conn *consumableCommitConn) Write(packet []byte) (int, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
conn.err = conn.db.QueryRowContext(ctx, `SELECT recipient.health, recipient.nano, coalesce(debit.count, 0),
- healer.first_aid_locked_until, receipt.locked_until
- FROM characters recipient JOIN players healer ON healer.id=1
+ healer.locked_until, receipt.locked_until
+ FROM characters recipient
+ LEFT JOIN skill_locks healer ON healer.player_id=1 AND healer.skill=123
LEFT JOIN items debit ON debit.id=1
- LEFT JOIN treatment_locks receipt ON receipt.player_id=1 AND receipt.patient_id=recipient.id
+ LEFT JOIN skill_locks receipt ON receipt.player_id=recipient.id AND receipt.skill=124
WHERE recipient.id=?`, conn.target).Scan(&conn.health, &conn.nano, &conn.count, &conn.firstAid, &conn.patient)
}
return conn.combatTestConn.Write(packet)
@@ -93,11 +94,11 @@ func TestConsumableResourceGainSurvivesBeforeCheckpoint(t *testing.T) {
}
if use.template == 85366 {
if target.nano < 11 || target.nano > 13 || restored.characters[target.id].nano != target.nano ||
- restored.characters[1].inventory.Items[0].Count != 24 || restored.characters[1].inventory.FirstAidLockedUntil.IsZero() {
+ restored.characters[1].inventory.Items[0].Count != 24 || restored.characters[1].skillLocks[123].IsZero() {
t.Fatalf("acknowledged nano gain was not committed with charge/lock: live=%d saved=%d", target.nano, restored.characters[target.id].nano)
}
} else if target.health != 31 || restored.characters[target.id].health != 31 ||
- restored.characters[1].inventory.Items[0].Count != 49 || restored.characters[target.id].treatmentLockedUntil.IsZero() {
+ restored.characters[1].inventory.Items[0].Count != 49 || restored.characters[target.id].skillLocks[124].IsZero() {
t.Fatalf("acknowledged health gain was not committed with charge/lock: live=%d saved=%d", target.health, restored.characters[target.id].health)
}
})
@@ -128,10 +129,10 @@ func TestConsumableLastChargeCommitsBeforeSuccessPacket(t *testing.T) {
t.Fatalf("last charge/resource outcome was not durable at first success: observed=%t count=%d, %v %v", conn.observed, conn.count, err, conn.err)
}
if use.template == 85366 {
- if conn.nano < 11 || conn.nano > 13 || conn.nano != target.nano || conn.firstAid.IsZero() || conn.patient.Valid {
+ if conn.nano < 11 || conn.nano > 13 || conn.nano != target.nano || !conn.firstAid.Valid || conn.patient.Valid {
t.Fatal("first success preceded the nano gain or source cooldown")
}
- } else if conn.health != 31 || !conn.patient.Valid || conn.patient.Time.IsZero() || !conn.firstAid.IsZero() {
+ } else if conn.health != 31 || !conn.patient.Valid || conn.patient.Time.IsZero() || conn.firstAid.Valid {
t.Fatal("first success preceded the health gain or patient lock")
}
})
@@ -157,9 +158,9 @@ func TestConsumableFailureRollsBackGainChargeAndLockThenRetries(t *testing.T) {
case "charge":
statement = "CREATE TRIGGER reject_item_effect BEFORE UPDATE ON items WHEN NEW.id=1 BEGIN SELECT RAISE(FAIL, 'test charge failure'); END"
case "lock":
- statement = "CREATE TRIGGER reject_item_effect BEFORE INSERT ON treatment_locks WHEN NEW.player_id=1 BEGIN SELECT RAISE(FAIL, 'test patient lock failure'); END"
+ statement = "CREATE TRIGGER reject_item_effect BEFORE INSERT ON skill_locks WHEN NEW.player_id=2 BEGIN SELECT RAISE(FAIL, 'test patient lock failure'); END"
if template == 85366 {
- statement = "CREATE TRIGGER reject_item_effect BEFORE UPDATE ON players WHEN NEW.id=1 BEGIN SELECT RAISE(FAIL, 'test first aid lock failure'); END"
+ statement = "CREATE TRIGGER reject_item_effect BEFORE INSERT ON skill_locks WHEN NEW.player_id=1 BEGIN SELECT RAISE(FAIL, 'test first aid lock failure'); END"
}
case "ignored resource":
statement = "CREATE TRIGGER reject_item_effect BEFORE UPDATE OF health ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(IGNORE); END"
@@ -176,7 +177,8 @@ func TestConsumableFailureRollsBackGainChargeAndLockThenRetries(t *testing.T) {
if failed == nil || len(conn.packets) != 0 || player.inventory.Items[0].Count != count || world.items[1].Count != count ||
rolledBack.characters[1].inventory.Items[0].Count != count || target.vitals() != before || target.savedVitals != before ||
rolledBack.characters[2].health != before.Health || rolledBack.characters[2].nano != before.Nano ||
- !player.inventory.FirstAidLockedUntil.IsZero() || len(player.inventory.TreatmentLocks) != 0 || !target.treatmentLockedUntil.IsZero() {
+ len(player.skillLocks) != 0 || len(target.skillLocks) != 0 ||
+ len(rolledBack.characters[1].skillLocks) != 0 || len(rolledBack.characters[2].skillLocks) != 0 {
t.Fatal("failed item effect changed caches, resources, charge/lock rows or published success", failed)
}
if _, err := world.db.Exec("DROP TRIGGER reject_item_effect"); err != nil {
@@ -190,10 +192,10 @@ func TestConsumableFailureRollsBackGainChargeAndLockThenRetries(t *testing.T) {
t.Fatal("retry did not commit one complete item effect", err)
}
if template == 85366 {
- if target.nano < 11 || target.nano > 13 || restored.characters[1].inventory.FirstAidLockedUntil.IsZero() {
+ if target.nano < 11 || target.nano > 13 || restored.characters[1].skillLocks[123].IsZero() {
t.Fatal("retry lost nano restoration or its cooldown")
}
- } else if target.health != 31 || restored.characters[2].treatmentLockedUntil.IsZero() {
+ } else if target.health != 31 || restored.characters[2].skillLocks[124].IsZero() {
t.Fatal("retry lost health restoration or its patient lock")
}
})
@@ -221,7 +223,7 @@ func TestConsumableLastChargeFailurePreservesInstanceAndRecipient(t *testing.T)
if err == nil || len(conn.packets) != 0 || len(player.inventory.Items) != 1 || player.inventory.Items[0].ID != 1 || player.inventory.Items[0].Count != 1 ||
len(restored.items) != 1 || restored.characters[1].inventory.Items[0].ID != 1 || restored.items[1].Count != 1 || restored.nextItem != 1 ||
target.vitals() != before || restored.characters[2].health != before.Health || restored.characters[2].nano != before.Nano ||
- len(player.inventory.TreatmentLocks) != 0 || !player.inventory.FirstAidLockedUntil.IsZero() {
+ len(target.skillLocks) != 0 || !player.skillLocks[123].IsZero() {
t.Fatal("failed last-charge effect destroyed its instance or changed the recipient", err)
}
})
@@ -302,10 +304,10 @@ func TestConsumableOutputFailureKeepsDurableOutcomeAndRestartPreventsReplay(t *t
t.Fatal("output failure lost the committed effect or restart let it consume another charge", failedOutput, replay)
}
if use.template == 85366 {
- if target.nano < 11 || target.nano > 13 || restored.characters[1].inventory.FirstAidLockedUntil.IsZero() {
+ if target.nano < 11 || target.nano > 13 || restored.characters[1].skillLocks[123].IsZero() {
t.Fatal("output failure lost nano restoration or its durable source cooldown")
}
- } else if target.health != 31 || restored.characters[target.id].treatmentLockedUntil.IsZero() {
+ } else if target.health != 31 || restored.characters[target.id].skillLocks[124].IsZero() {
t.Fatal("output failure lost health restoration or its durable patient lock")
}
})
diff --git a/server/control.go b/server/control.go
@@ -292,7 +292,6 @@ func (server *server) updateUser_locked(destination userData) error {
updated.browserTokenHash = character.browserTokenHash
updated.resurrectionTerminal = character.resurrectionTerminal
updated.implantChangesUntil = character.implantChangesUntil
- updated.treatmentLockedUntil = character.treatmentLockedUntil
updated.savedProfile = character.savedProfile
updated.savedPosition = character.savedPosition
updated.savedVitals = character.savedVitals
@@ -310,7 +309,7 @@ func (server *server) updateUser_locked(destination userData) error {
}
func (server *server) prepareUser_locked(character, updated *character) {
- updated.specialAttackLocks = character.specialAttackLocks
+ updated.skillLocks = character.skillLocks
updated.activeNanos = character.activeNanos
updated.team = character.team
updated.buddies = character.buddies
diff --git a/server/database.go b/server/database.go
@@ -70,7 +70,7 @@ func (character *character) profile() playerProfile {
Level: character.level, Experience: character.experience, InsuredExperience: character.insuredExperience,
Profession: max(1, character.profession), Stats: character.baseStats(), Running: character.running,
BrowserTokenHash: character.browserTokenHash, ResurrectionTerminal: character.resurrectionTerminal,
- ImplantChangesUntil: character.implantChangesUntil, TreatmentLockedUntil: character.treatmentLockedUntil}
+ ImplantChangesUntil: character.implantChangesUntil}
}
func (character *character) vitals() playerVitals {
@@ -144,7 +144,7 @@ func (record characterRecord) character() *character {
player := data.character()
player.applyVitals(record.Vitals)
player.resurrectionTerminal = profile.ResurrectionTerminal
- player.implantChangesUntil, player.treatmentLockedUntil = profile.ImplantChangesUntil, profile.TreatmentLockedUntil
+ player.implantChangesUntil = profile.ImplantChangesUntil
player.savedProfile, player.savedPosition, player.savedVitals = profile, position, record.Vitals
return player
}
diff --git a/server/fast_attack_test.go b/server/fast_attack_test.go
@@ -49,10 +49,10 @@ func TestFastAttackPublishesWeaponDamageAndPersistsItsOwnLock(t *testing.T) {
target.damageContributors[damageContributor{player: 1}] != 1000-target.health ||
!reflect.DeepEqual(player.inventory, inventory) ||
!reflect.DeepEqual(restored.characters[1].inventory.Items, inventory.Items) ||
- !restored.characters[1].specialAttackLocks[147].Equal(player.specialAttackLocks[147]) ||
- player.specialAttackLocks[147].Before(started.Add(19*time.Second)) ||
- player.specialAttackLocks[147].After(time.Now().Add(19*time.Second)) || !player.specialAttackLocks[150].IsZero() {
- t.Fatalf("Fast Attack damage, inventory or durable lock mismatch: HP=%d locks=%v, %v", target.health, player.specialAttackLocks, err)
+ !restored.characters[1].skillLocks[147].Equal(player.skillLocks[147]) ||
+ player.skillLocks[147].Before(started.Add(19*time.Second)) ||
+ player.skillLocks[147].After(time.Now().Add(19*time.Second)) || !player.skillLocks[150].IsZero() {
+ t.Fatalf("Fast Attack damage, inventory or durable lock mismatch: HP=%d locks=%v, %v", target.health, player.skillLocks, err)
}
if len(owner.packets) != 3 || len(observer.packets) != 2 ||
binary.BigEndian.Uint32(owner.packets[0][16:20]) != 0x754f1115 ||
@@ -115,7 +115,7 @@ func TestFastAttackRejectsInvalidRequestsWithoutDamageOrLocks(t *testing.T) {
case "reloading":
client.reloadUntil = time.Now().Add(time.Hour)
case "locked":
- player.specialAttackLocks = map[uint32]time.Time{147: time.Now().Add(time.Hour)}
+ player.skillLocks = map[uint32]time.Time{147: time.Now().Add(time.Hour)}
case "unarmed":
player.inventory.Items = nil
case "stored axe":
@@ -127,13 +127,13 @@ func TestFastAttackRejectsInvalidRequestsWithoutDamageOrLocks(t *testing.T) {
case "unsupported quality":
player.inventory.Items[0].Quality = 2
}
- deadline := player.specialAttackLocks[147]
+ deadline := player.skillLocks[147]
health := target.health
err := world.handleWeaponSpecial(client, request)
- if err != nil || target.health != health || player.specialAttackLocks[147] != deadline || len(conn.packets) != 0 {
- t.Fatalf("invalid Fast Attack changed state: HP=%d locks=%v, %v", target.health, player.specialAttackLocks, err)
+ if err != nil || target.health != health || player.skillLocks[147] != deadline || len(conn.packets) != 0 {
+ t.Fatalf("invalid Fast Attack changed state: HP=%d locks=%v, %v", target.health, player.skillLocks, err)
}
})
}
@@ -173,7 +173,7 @@ func TestFastAttackConcurrentRequestsApplyOnceWithoutResettingAttackOrCast(t *te
func TestFastAttackFailedOutcomePublishesNothingAndRollsBackItsLock(t *testing.T) {
for _, statement := range []string{
- "CREATE TRIGGER fail_special BEFORE INSERT ON special_attack_locks BEGIN SELECT RAISE(FAIL, 'test lock failure'); END",
+ "CREATE TRIGGER fail_special BEFORE INSERT ON skill_locks BEGIN SELECT RAISE(FAIL, 'test lock failure'); END",
"CREATE TRIGGER fail_special BEFORE UPDATE OF health ON characters WHEN NEW.id=1000000 BEGIN SELECT RAISE(FAIL, 'test health failure'); END",
"CREATE TRIGGER fail_special BEFORE UPDATE ON npcs BEGIN SELECT RAISE(FAIL, 'test NPC failure'); END",
"CREATE TRIGGER fail_special BEFORE INSERT ON npc_damage_contributors BEGIN SELECT RAISE(FAIL, 'test contribution failure'); END",
@@ -187,7 +187,7 @@ func TestFastAttackFailedOutcomePublishesNothingAndRollsBackItsLock(t *testing.T
restored := newTestInventoryServer(t)
if err == nil || world.characters[1000000].health != 1000 || len(conn.packets) != 0 ||
- len(world.characters[1].specialAttackLocks) != 0 || len(restored.characters[1].specialAttackLocks) != 0 {
+ len(world.characters[1].skillLocks) != 0 || len(restored.characters[1].skillLocks) != 0 {
t.Fatal("failed Fast Attack changed durable/live outcome or published feedback")
}
}
@@ -202,11 +202,11 @@ func TestFastAttackKillAndCooldownRecoverTogether(t *testing.T) {
err := world.handleWeaponSpecial(world.clients[1], fastAttackRequest(1, 1000000)[20:])
restored := newTestInventoryServer(t)
corpse := restored.characters[1000000]
- deadline := restored.characters[1].specialAttackLocks[147]
+ deadline := restored.characters[1].skillLocks[147]
if err != nil || corpse.health != 0 || corpse.corpse == nil || corpse.corpse.looter != 1 ||
corpse.corpse.expiresAt.IsZero() || len(restored.npcRespawns) != 1 ||
- !deadline.Equal(world.characters[1].specialAttackLocks[147]) ||
+ !deadline.Equal(world.characters[1].skillLocks[147]) ||
binary.BigEndian.Uint32(conn.packets[0][33:37]) != 1 ||
binary.BigEndian.Uint32(conn.packets[0][53:57]) != 4 {
t.Fatal("Fast Attack kill/corpse/lock did not recover atomically", err)
@@ -221,7 +221,7 @@ func TestFastAttackStoredLockRejectsAfterRestartAndExpiresOnce(t *testing.T) {
restored := newTestInventoryServer(t)
conn := &combatTestConn{}
restored.clients = map[uint32]*worldClient{1: {id: 1, ready: true, target: true, conn: conn, npcs: map[uint32]bool{1000000: true}}}
- deadline, health := restored.characters[1].specialAttackLocks[147], restored.characters[1000000].health
+ deadline, health := restored.characters[1].skillLocks[147], restored.characters[1000000].health
err := restored.handleWeaponSpecial(restored.clients[1], fastAttackRequest(1, 1000000)[20:])
restored.advanceItemEffects(deadline.Add(-time.Nanosecond))
@@ -231,7 +231,7 @@ func TestFastAttackStoredLockRejectsAfterRestartAndExpiresOnce(t *testing.T) {
restored.advanceItemEffects(deadline)
restored.advanceItemEffects(deadline.Add(time.Second))
- if err != nil || len(conn.packets) != 1 || !restored.characters[1].specialAttackLocks[147].IsZero() ||
+ if err != nil || len(conn.packets) != 1 || !restored.characters[1].skillLocks[147].IsZero() ||
binary.BigEndian.Uint32(conn.packets[0][29:33]) != 164 || binary.BigEndian.Uint32(conn.packets[0][45:49]) != 147 {
t.Fatal("Fast Attack lock did not expire exactly once", err)
}
diff --git a/server/fling_crash_test.go b/server/fling_crash_test.go
@@ -183,7 +183,7 @@ func TestFlingShotProcessCrashRecovery(t *testing.T) {
t.Fatal("crash separated XP, level or IP from the killing special")
}
if strings.HasPrefix(mode, "before/") {
- if target.health != initialHealth || len(player.specialAttackLocks) != 0 || len(target.damageContributors) != 0 ||
+ if target.health != initialHealth || len(player.skillLocks) != 0 || len(target.damageContributors) != 0 ||
target.corpse != nil || len(restored.npcRespawns) != 0 {
t.Fatalf("uncommitted shot survived the process kill: %+v", target)
}
@@ -192,10 +192,10 @@ func TestFlingShotProcessCrashRecovery(t *testing.T) {
t.Fatalf("first post-commit output was not the native special result: %x", checkpoint.Packet)
}
damage := binary.BigEndian.Uint32(checkpoint.Packet[33:37])
- if damage == 0 || damage > initialHealth || target.health != initialHealth-damage || !player.specialAttackLocks[skill].After(time.Now()) ||
+ if damage == 0 || damage > initialHealth || target.health != initialHealth-damage || !player.skillLocks[skill].After(time.Now()) ||
binary.BigEndian.Uint32(checkpoint.Packet[49:53]) != skill ||
initialHealth != 1 && target.damageContributors[damageContributor{player: 1}] != damage {
- t.Fatalf("committed shot was lost or partially recovered: HP=%d damage=%d lock=%v", target.health, damage, player.specialAttackLocks)
+ t.Fatalf("committed shot was lost or partially recovered: HP=%d damage=%d lock=%v", target.health, damage, player.skillLocks)
}
if initialHealth == 1 && (target.corpse == nil || target.corpse.looter != 1 || target.corpse.expiresAt.IsZero() || len(restored.npcRespawns) != 1) {
t.Fatal("committed death lost corpse rights, expiry or pending respawn")
@@ -224,7 +224,7 @@ func TestFlingShotProcessCrashRecovery(t *testing.T) {
}
again := newTestInventoryServer(t)
if target.health >= initialHealth || initialHealth != 1 && target.damageContributors[damageContributor{player: 1}] != initialHealth-target.health ||
- again.characters[1000000].health != target.health || !again.characters[1].specialAttackLocks[skill].Equal(player.specialAttackLocks[skill]) ||
+ again.characters[1000000].health != target.health || !again.characters[1].skillLocks[skill].Equal(player.skillLocks[skill]) ||
!reflect.DeepEqual(again.characters[1].inventory.Items, inventory) {
t.Fatal("retry lost or duplicated a durable damage, cooldown or ammunition outcome")
}
diff --git a/server/fling_shot_test.go b/server/fling_shot_test.go
@@ -31,10 +31,10 @@ func TestFlingShotDamagesOnceWithoutConsumingPre155Ammunition(t *testing.T) {
if err != nil || target.health < 988 || target.health > 997 || player.inventory.Items[0].Ammo != 3 ||
player.inventory.Items[1].Count != 100 || restored.inventory.Items[0].Ammo != 3 ||
- !restored.specialAttackLocks[150].Equal(player.specialAttackLocks[150]) ||
- player.specialAttackLocks[150].Before(started.Add(19*time.Second)) || target.fighting != 1 ||
+ !restored.skillLocks[150].Equal(player.skillLocks[150]) ||
+ player.skillLocks[150].Before(started.Add(19*time.Second)) || target.fighting != 1 ||
target.damageContributors[damageContributor{player: 1}] != 1000-target.health {
- t.Fatalf("special result or persistent lock mismatch: HP=%d lock=%v, %v", target.health, player.specialAttackLocks, err)
+ t.Fatalf("special result or persistent lock mismatch: HP=%d lock=%v, %v", target.health, player.skillLocks, err)
}
if len(owner.packets) != 3 || len(observer.packets) != 2 ||
binary.BigEndian.Uint32(owner.packets[0][16:20]) != 0x754f1115 ||
@@ -155,7 +155,7 @@ func TestFlingShotRejectsInvalidRequestsWithoutDamageOrLocks(t *testing.T) {
case "reloading":
client.reloadUntil = time.Now().Add(time.Hour)
case "locked":
- player.specialAttackLocks = map[uint32]time.Time{150: time.Now().Add(time.Hour)}
+ player.skillLocks = map[uint32]time.Time{150: time.Now().Add(time.Hour)}
case "empty clip":
player.inventory.Items[0].Ammo = 0
case "unarmed":
@@ -166,11 +166,11 @@ func TestFlingShotRejectsInvalidRequestsWithoutDamageOrLocks(t *testing.T) {
player.inventory.Items[0].Slot = 65
}
health := target.health
- deadline := player.specialAttackLocks[150]
+ deadline := player.skillLocks[150]
err := world.handleWeaponSpecial(client, request)
- if err != nil || target.health != health || player.specialAttackLocks[150] != deadline || len(conn.packets) != 0 {
+ if err != nil || target.health != health || player.skillLocks[150] != deadline || len(conn.packets) != 0 {
t.Fatalf("rejected special changed health/lock/output: %d -> %d, %v", health, target.health, err)
}
})
@@ -192,13 +192,13 @@ func TestFlingShotMalformedLengthReturnsError(t *testing.T) {
func TestFlingShotSaveFailureDoesNotPublishOrDamage(t *testing.T) {
world, conn := newRangedWorld(t)
- if _, err := world.db.Exec("CREATE TRIGGER fail_fling BEFORE INSERT ON special_attack_locks BEGIN SELECT RAISE(FAIL, 'test lock failure'); END"); err != nil {
+ if _, err := world.db.Exec("CREATE TRIGGER fail_fling BEFORE INSERT ON skill_locks BEGIN SELECT RAISE(FAIL, 'test lock failure'); END"); err != nil {
t.Fatal(err)
}
err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:])
- if err == nil || world.characters[1000000].health != 1000 || len(world.characters[1].specialAttackLocks) != 0 || len(conn.packets) != 0 {
+ if err == nil || world.characters[1000000].health != 1000 || len(world.characters[1].skillLocks) != 0 || len(conn.packets) != 0 {
t.Fatal("failed special lock save published a hit or changed live state")
}
}
@@ -219,12 +219,12 @@ func TestFlingShotOutcomeFailureRollsBackLockAndNPCState(t *testing.T) {
if err := world.db.QueryRow("SELECT health FROM characters WHERE id=1000000").Scan(&health); err != nil {
t.Fatal(err)
}
- if err := world.db.QueryRow("SELECT count(*) FROM special_attack_locks").Scan(&locks); err != nil {
+ if err := world.db.QueryRow("SELECT count(*) FROM skill_locks").Scan(&locks); err != nil {
t.Fatal(err)
}
if err == nil || health != 1000 || locks != 0 || world.characters[1000000].health != 1000 ||
- len(world.characters[1000000].damageContributors) != 0 || len(world.characters[1].specialAttackLocks) != 0 || len(conn.packets) != 0 {
+ len(world.characters[1000000].damageContributors) != 0 || len(world.characters[1].skillLocks) != 0 || len(conn.packets) != 0 {
t.Fatalf("partial special commit escaped rollback: health=%d locks=%d error=%v", health, locks, err)
}
}
@@ -246,7 +246,7 @@ func TestFlingShotPersistsDamageAndContributionBeforeAnyCheckpoint(t *testing.T)
if err != nil || health != world.characters[1000000].health || contribution != 1000-health ||
world.savedNPCs[1000000].State.Character.Vitals.Health != health || restored.characters[1000000].health != health ||
restored.characters[1000000].damageContributors[damageContributor{player: 1}] != contribution ||
- !restored.characters[1].specialAttackLocks[150].Equal(world.characters[1].specialAttackLocks[150]) {
+ !restored.characters[1].skillLocks[150].Equal(world.characters[1].skillLocks[150]) {
t.Fatalf("published special was not durable: HP=%d contribution=%d, %v", health, contribution, err)
}
}
@@ -271,7 +271,7 @@ func TestFlingShotKillingSaveFailurePreservesCorpseAndContributors(t *testing.T)
if err == nil || target.health != 1 || target.corpse.looter != 2 || !target.corpse.expiresAt.IsZero() ||
target.damageContributors[damageContributor{player: 2}] != 10 || len(target.damageContributors) != 1 || len(world.npcRespawns) != 0 ||
len(conn.packets) != 0 || restored.characters[1000000].health != 1 || restored.characters[1000000].corpse.looter != 2 ||
- len(restored.characters[1].specialAttackLocks) != 0 {
+ len(restored.characters[1].skillLocks) != 0 {
t.Fatal("failed special kill leaked staged corpse, contribution or lock state")
}
}
@@ -282,7 +282,7 @@ func TestFlingShotLockSurvivesProfileEditAndBlocksAfterRestart(t *testing.T) {
if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
t.Fatal(err)
}
- deadline := player.specialAttackLocks[150]
+ deadline := player.skillLocks[150]
delete(world.clients, 1)
destination := player.userData()
destination.Name = "Fling Owner"
@@ -296,8 +296,8 @@ func TestFlingShotLockSurvivesProfileEditAndBlocksAfterRestart(t *testing.T) {
err = restored.handleWeaponSpecial(restored.clients[1], flingShotRequest(1, 1000000)[20:])
}
- if err != nil || world.characters[1].specialAttackLocks[150] != deadline ||
- !restored.characters[1].specialAttackLocks[150].Equal(deadline) || restored.characters[1000000].health != 1000 || len(conn.packets) != 0 {
+ if err != nil || world.characters[1].skillLocks[150] != deadline ||
+ !restored.characters[1].skillLocks[150].Equal(deadline) || restored.characters[1000000].health != 1000 || len(conn.packets) != 0 {
t.Fatal("profile edit or restart cleared the special lock", err)
}
}
@@ -307,9 +307,9 @@ func TestFlingShotLockExpiryUnlocksOnceAndDoesNotChurnDatabase(t *testing.T) {
if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
t.Fatal(err)
}
- deadline := world.characters[1].specialAttackLocks[150]
+ deadline := world.characters[1].skillLocks[150]
conn.packets = nil
- if _, err := world.db.Exec("CREATE TRIGGER fail_expiry BEFORE UPDATE ON special_attack_locks BEGIN SELECT RAISE(FAIL, 'expiry must be in memory'); END"); err != nil {
+ if _, err := world.db.Exec("CREATE TRIGGER fail_expiry BEFORE UPDATE ON skill_locks BEGIN SELECT RAISE(FAIL, 'expiry must be in memory'); END"); err != nil {
t.Fatal(err)
}
@@ -320,7 +320,7 @@ func TestFlingShotLockExpiryUnlocksOnceAndDoesNotChurnDatabase(t *testing.T) {
world.advanceItemEffects(deadline)
world.advanceItemEffects(deadline.Add(time.Second))
- if len(conn.packets) != 1 || !world.characters[1].specialAttackLocks[150].IsZero() ||
+ if len(conn.packets) != 1 || !world.characters[1].skillLocks[150].IsZero() ||
binary.BigEndian.Uint32(conn.packets[0][29:33]) != 164 || binary.BigEndian.Uint32(conn.packets[0][45:49]) != 150 {
t.Fatalf("lock did not clear exactly once: %x", conn.packets)
}
@@ -331,13 +331,13 @@ func TestFlingShotExpiredStoredLockDoesNotReturnAfterRestart(t *testing.T) {
if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil {
t.Fatal(err)
}
- if _, err := world.db.Exec("UPDATE special_attack_locks SET locked_until=?", time.Now().Add(-time.Second)); err != nil {
+ if _, err := world.db.Exec("UPDATE skill_locks SET locked_until=?", time.Now().Add(-time.Second)); err != nil {
t.Fatal(err)
}
restored := newTestInventoryServer(t)
- if len(restored.characters[1].specialAttackLocks) != 0 {
+ if len(restored.characters[1].skillLocks) != 0 {
t.Fatal("expired special lock was restored")
}
}
diff --git a/server/implants.go b/server/implants.go
@@ -29,16 +29,31 @@ func (server *server) useClinic_locked(client *worldClient, index int, body []by
now := time.Now()
accepted := client.selectedTarget == [2]uint32{50000, client.id} && slot >= 64 && slot < 94 &&
player.inventory.Items[index].Type == 51005 && player.inventory.Items[index].Template == 43552 && player.inventory.Items[index].Quality == 1 &&
- player.effectiveSkill(124, stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 5 && !now.Before(player.treatmentLockedUntil)
+ player.effectiveSkill(124, stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 5 && !now.Before(player.skillLocks[124])
if accepted {
// Save the cooldown and access window before acknowledging any authored effects.
- updated := *player
- updated.implantChangesUntil = now.Add(30 * time.Second)
- updated.treatmentLockedUntil = now.Add(600 * time.Second)
- if err := server.saveUser_locked(&updated); err != nil {
+ db, err := server.database()
+ if err != nil {
return err
}
- *player = updated
+ tx, err := db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ window := now.Add(30 * time.Second)
+ deadline := now.Add(time.Duration(player.skillLockSeconds(600)) * time.Second)
+ if err := updateRecord(tx, "characters", player.id, "implant_changes_until", []any{window}); err != nil {
+ return err
+ }
+ if err := writeSkillLock(tx, player.id, 124, deadline); err != nil {
+ return err
+ }
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+ player.implantChangesUntil, player.savedProfile.ImplantChangesUntil = window, window
+ player.setSkillLock_locked(124, deadline)
}
reply := append([]byte(nil), body[16:]...)
binary.BigEndian.PutUint32(reply, 2)
@@ -82,9 +97,9 @@ func (server *server) advanceItemEffects(now time.Time) {
continue
}
player := server.characters[id]
- for skill, deadline := range player.specialAttackLocks {
+ for skill, deadline := range player.skillLocks {
if !now.Before(deadline) {
- delete(player.specialAttackLocks, skill)
+ delete(player.skillLocks, skill)
updates[client] = append(updates[client], characterActionPacket(id, [5]uint32{164, 0, 0, 0, skill}))
}
}
@@ -94,22 +109,6 @@ func (server *server) advanceItemEffects(now time.Time) {
body = binary.BigEndian.AppendUint32(body, 0)
updates[client] = append(updates[client], n3Packet(0x2b333d6e, 50000, id, body))
}
- if !player.treatmentLockedUntil.IsZero() && !now.Before(player.treatmentLockedUntil) {
- player.treatmentLockedUntil = time.Time{}
- var body []byte
- for _, value := range []uint32{164, 0, 0, 0, 124} {
- body = binary.BigEndian.AppendUint32(body, value)
- }
- updates[client] = append(updates[client], n3Packet(0x5e477770, 50000, id, body))
- }
- if !player.inventory.FirstAidLockedUntil.IsZero() && !now.Before(player.inventory.FirstAidLockedUntil) {
- player.inventory.FirstAidLockedUntil = time.Time{}
- var body []byte
- for _, value := range []uint32{164, 0, 0, 0, 123} {
- body = binary.BigEndian.AppendUint32(body, value)
- }
- updates[client] = append(updates[client], n3Packet(0x5e477770, 50000, id, body))
- }
}
server.mutex.Unlock()
server.sendCombatUpdates(updates)
diff --git a/server/implants_test.go b/server/implants_test.go
@@ -12,6 +12,9 @@ func newImplantWorld(t *testing.T) (*server, *combatTestConn) {
t.Helper()
world, conn := newArmorWorld(t)
world.characters[1].stats.NanoAiding.Treatment = 9
+ if err := world.saveUser_locked(world.characters[1]); err != nil {
+ t.Fatal(err)
+ }
world.clients[1].selectedTarget = [2]uint32{50000, 1}
for _, template := range []uint32{43552, 101173} {
if granted, err := world.grantItem_locked(world.characters[1], template); err != nil || !granted {
@@ -49,7 +52,7 @@ func TestImplantClinicEquipBonusesAndRestart(t *testing.T) {
}
if !reflect.DeepEqual(restored.inventory.Items, player.inventory.Items) || restored.inventory.LastID != 5 || restored.inventory.equipmentBonus(91) != 14 ||
restored.implantChangesUntil.UnixNano() != player.implantChangesUntil.UnixNano() ||
- restored.treatmentLockedUntil.UnixNano() != player.treatmentLockedUntil.UnixNano() || restored.stats.NanoAiding.Treatment != 9 {
+ restored.skillLocks[124].UnixNano() != player.skillLocks[124].UnixNano() || restored.stats.NanoAiding.Treatment != 9 {
t.Fatalf("implant or clinic state did not persist: %+v", restored)
}
last := conn.packets[len(conn.packets)-1]
@@ -131,7 +134,7 @@ func TestImplantRemovalRetainsOtherEquipmentAndNeedsClinic(t *testing.T) {
if client.equipment != nil || !reflect.DeepEqual(before, player.inventory) || player.inventory.equipmentBonus(91) != 14 {
t.Fatal("implant removed after surgery access expired")
}
- world.advanceItemEffects(player.treatmentLockedUntil)
+ world.advanceItemEffects(player.skillLocks[124])
world.handleOwnedItemUse(client, backpackUseRequest(1, 67, 2)[20:])
// Removal does not recheck the implant's install requirements.
player.stats.NanoAiding.Treatment, player.stats.Abilities.Strength = 0, 1
@@ -228,12 +231,12 @@ func TestPortableClinicCooldownAndExpiry(t *testing.T) {
started := time.Now()
world.handleOwnedItemUse(client, backpackUseRequest(1, 67, 1)[20:])
- window, cooldown := player.implantChangesUntil, player.treatmentLockedUntil
+ window, cooldown := player.implantChangesUntil, player.skillLocks[124]
first := append([][]byte(nil), conn.packets...)
world.handleOwnedItemUse(client, backpackUseRequest(1, 67, 1)[20:])
world.handleOwnedItemUse(client, backpackUseRequest(1, 67, 2)[20:])
world.advanceItemEffects(window.Add(-time.Nanosecond))
- if len(conn.packets) != 4 || !player.implantChangesUntil.Equal(window) || !player.treatmentLockedUntil.Equal(cooldown) {
+ if len(conn.packets) != 4 || !player.implantChangesUntil.Equal(window) || !player.skillLocks[124].Equal(cooldown) {
t.Fatal("replay or cooldown use extended clinic effects")
}
world.advanceItemEffects(window)
@@ -249,7 +252,7 @@ func TestPortableClinicCooldownAndExpiry(t *testing.T) {
t.Fatalf("clinic Use or cooldown wire: %x", first)
}
if len(conn.packets) != 6 || binary.BigEndian.Uint32(conn.packets[4][29:33]) != 224 || binary.BigEndian.Uint32(conn.packets[4][33:37]) != 0 ||
- binary.BigEndian.Uint32(conn.packets[5][29:33]) != 164 || !player.implantChangesUntil.IsZero() || !player.treatmentLockedUntil.IsZero() {
+ binary.BigEndian.Uint32(conn.packets[5][29:33]) != 164 || !player.implantChangesUntil.IsZero() || !player.skillLocks[124].IsZero() {
t.Fatalf("clinic expiry repeated or omitted: %x", conn.packets)
}
}
@@ -286,7 +289,7 @@ func TestPortableClinicRejectsInvalidUseAndFailedSave(t *testing.T) {
err := world.handleOwnedItemUse(client, request)
- if (err != nil) != (scenario == "failed save") || !player.implantChangesUntil.IsZero() || !player.treatmentLockedUntil.IsZero() || !reflect.DeepEqual(before, player.inventory) {
+ if (err != nil) != (scenario == "failed save") || !player.implantChangesUntil.IsZero() || !player.skillLocks[124].IsZero() || !reflect.DeepEqual(before, player.inventory) {
t.Fatalf("invalid clinic use changed state: %v", err)
}
for _, packet := range conn.packets {
diff --git a/server/inventory.go b/server/inventory.go
@@ -25,15 +25,13 @@ type reclaimItem struct {
}
type playerInventory struct {
- LastID uint32
- Credits uint32
- Items []ownedItem
- Bank []ownedItem
- Reclaim []reclaimItem
- Containers map[uint32][]ownedItem
- FirstAidLockedUntil time.Time
- TreatmentLocks map[uint32]time.Time
- LearnedNanos []uint32
+ LastID uint32
+ Credits uint32
+ Items []ownedItem
+ Bank []ownedItem
+ Reclaim []reclaimItem
+ Containers map[uint32][]ownedItem
+ LearnedNanos []uint32
}
func (inventory playerInventory) validate() error {
@@ -127,7 +125,7 @@ func (server *server) saveInventory_locked(character *character, inventory playe
return nil
}
-func (server *server) saveItemEffect_locked(player, target *character, inventory playerInventory, vitals playerVitals) error {
+func (server *server) saveItemEffect_locked(player, target *character, inventory playerInventory, vitals playerVitals, lock skillLockUpdate) error {
if err := inventory.validate(); err != nil {
return err
}
@@ -136,6 +134,7 @@ func (server *server) saveItemEffect_locked(player, target *character, inventory
return err
}
store.vitalUpdate = &playerVitalUpdate{target.id, vitals}
+ store.skillLock = &lock
if err := server.writeItemStore_locked(store); err != nil {
return err
}
@@ -144,6 +143,7 @@ func (server *server) saveItemEffect_locked(player, target *character, inventory
player.inventory = inventory
target.applyVitals(vitals)
target.savedVitals = vitals
+ server.characters[lock.Player].setSkillLock_locked(lock.Skill, lock.Until)
return nil
}
diff --git a/server/inventory_write_test.go b/server/inventory_write_test.go
@@ -22,7 +22,7 @@ func newInventoryWriteWorld(t *testing.T) (*server, *combatTestConn) {
other.position, other.health, other.nano = [3]float32{52, 14, 57}, 25, 20
inventory := other.inventory
inventory.Credits, inventory.LearnedNanos = 91, []uint32{43324}
- inventory.TreatmentLocks = map[uint32]time.Time{2: time.Now().Add(time.Minute)}
+ setTestSkillLock(t, world, other, 124, time.Now().Add(time.Minute))
if err := world.saveInventory_locked(other, inventory); err != nil {
t.Fatal(err)
}
@@ -71,7 +71,7 @@ func TestInventoryMoveIgnoresUnrelatedPlayerWriteFailures(t *testing.T) {
restored := newTestInventoryServer(t)
if err != nil || world.characters[1].inventory.Items[0].Slot != 65 || restored.characters[1].inventory.Items[0].Slot != 65 ||
- restored.characters[2].inventory.Credits != 91 || len(restored.characters[2].inventory.LearnedNanos) != 1 || len(restored.characters[2].inventory.TreatmentLocks) != 1 {
+ restored.characters[2].inventory.Credits != 91 || len(restored.characters[2].inventory.LearnedNanos) != 1 || len(restored.characters[2].skillLocks) != 1 {
t.Fatal("an unrelated player write blocked a valid item move or changed their metadata", err)
}
}
@@ -95,7 +95,7 @@ func TestInventoryMetadataRetainsUnchangedProgramsAndLocks(t *testing.T) {
restored := newTestInventoryServer(t)
if response.Code != http.StatusSeeOther || !reflect.DeepEqual(restored.characters[1].inventory.LearnedNanos, []uint32{29618, 43324}) ||
- len(restored.characters[1].inventory.TreatmentLocks) != 1 || len(restored.characters[2].inventory.TreatmentLocks) != 1 {
+ len(restored.characters[1].skillLocks) != 2 || len(restored.characters[2].skillLocks) != 1 {
t.Fatal("an unchanged metadata set lost rows", response.Body.String())
}
if writes := checkpointWrites(t, world); !reflect.DeepEqual(writes, map[string]int{"characters/UPDATE": 1}) {
@@ -103,13 +103,11 @@ func TestInventoryMetadataRetainsUnchangedProgramsAndLocks(t *testing.T) {
}
}
-func TestInventoryMetadataWritesOnlyAdditionsAndChangedDeadlines(t *testing.T) {
+func TestInventoryMetadataWritesOnlyChangedCreditsAndPrograms(t *testing.T) {
world, _ := newInventoryWriteWorld(t)
data := world.characters[1].editor()
- deadline := time.Date(2050, 1, 1, 0, 0, 0, 0, time.UTC)
- data.Inventory.Credits, data.Inventory.FirstAidLockedUntil = 43, deadline
+ data.Inventory.Credits = 43
data.Inventory.LearnedNanos = []uint32{43324, 29618}
- data.Inventory.TreatmentLocks = map[uint32]time.Time{1: deadline, 3: deadline}
contents, err := yaml.Marshal(data)
if err != nil {
t.Fatal(err)
@@ -120,12 +118,11 @@ func TestInventoryMetadataWritesOnlyAdditionsAndChangedDeadlines(t *testing.T) {
restored := newTestInventoryServer(t)
inventory := restored.characters[1].inventory
- if response.Code != http.StatusSeeOther || inventory.Credits != 43 || !inventory.FirstAidLockedUntil.Equal(deadline) ||
- !reflect.DeepEqual(inventory.LearnedNanos, []uint32{29618, 43324}) || len(inventory.TreatmentLocks) != 2 ||
- !inventory.TreatmentLocks[1].Equal(deadline) || !inventory.TreatmentLocks[3].Equal(deadline) || restored.characters[2].inventory.Credits != 91 {
+ if response.Code != http.StatusSeeOther || inventory.Credits != 43 ||
+ !reflect.DeepEqual(inventory.LearnedNanos, []uint32{29618, 43324}) || len(restored.characters[1].skillLocks) != 2 || restored.characters[2].inventory.Credits != 91 {
t.Fatal("changed metadata did not persist independently", response.Body.String())
}
- expected := map[string]int{"characters/UPDATE": 1, "players/UPDATE": 1, "learned_nanos/INSERT": 1, "treatment_locks/INSERT": 1, "treatment_locks/UPDATE": 1}
+ expected := map[string]int{"characters/UPDATE": 1, "players/UPDATE": 1, "learned_nanos/INSERT": 1}
if writes := checkpointWrites(t, world); !reflect.DeepEqual(writes, expected) {
t.Fatalf("metadata save rewrote retained rows or missed a change: %v", writes)
}
@@ -133,19 +130,19 @@ func TestInventoryMetadataWritesOnlyAdditionsAndChangedDeadlines(t *testing.T) {
func TestInventoryMetadataRemovalKeepsOtherPlayers(t *testing.T) {
world, _ := newInventoryWriteWorld(t)
- contents := "inventory:\n first_aid_locked_until: 0001-01-01T00:00:00Z\n learned_nanos: []\n treatment_locks: null\n"
+ contents := "inventory:\n learned_nanos: []\n"
auditCheckpointWrites(t, world)
response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}})
restored := newTestInventoryServer(t)
inventory, other := restored.characters[1].inventory, restored.characters[2].inventory
- if response.Code != http.StatusSeeOther || inventory.Credits != 42 || !inventory.FirstAidLockedUntil.IsZero() ||
- len(inventory.LearnedNanos) != 0 || len(inventory.TreatmentLocks) != 0 || other.Credits != 91 ||
- !reflect.DeepEqual(other.LearnedNanos, []uint32{43324}) || len(other.TreatmentLocks) != 1 {
+ if response.Code != http.StatusSeeOther || inventory.Credits != 42 ||
+ len(inventory.LearnedNanos) != 0 || len(restored.characters[1].skillLocks) != 2 || other.Credits != 91 ||
+ !reflect.DeepEqual(other.LearnedNanos, []uint32{43324}) || len(restored.characters[2].skillLocks) != 1 {
t.Fatal("clearing metadata retained stale rows or removed another player's entries", response.Body.String())
}
- expected := map[string]int{"characters/UPDATE": 1, "players/UPDATE": 1, "learned_nanos/DELETE": 1, "treatment_locks/DELETE": 1}
+ expected := map[string]int{"characters/UPDATE": 1, "learned_nanos/DELETE": 1}
if writes := checkpointWrites(t, world); !reflect.DeepEqual(writes, expected) {
t.Fatalf("clearing metadata rewrote unrelated rows: %v", writes)
}
@@ -155,7 +152,6 @@ func TestInventoryMetadataFailureRollsBackWithOwnershipThenRetries(t *testing.T)
world, _ := newInventoryWriteWorld(t)
data := world.characters[1].editor()
data.Inventory.Credits, data.Inventory.LearnedNanos = 43, []uint32{29618}
- data.Inventory.TreatmentLocks = map[uint32]time.Time{3: time.Date(2050, 1, 1, 0, 0, 0, 0, time.UTC)}
data.Inventory.Slots["inventory_slot_2"] = data.Inventory.Slots["inventory_slot_1"]
data.Inventory.Slots["inventory_slot_1"] = nil
contents, err := yaml.Marshal(data)
@@ -187,32 +183,40 @@ func TestInventoryMetadataFailureRollsBackWithOwnershipThenRetries(t *testing.T)
inventory := restored.characters[1].inventory
if retry.Code != http.StatusSeeOther || inventory.Credits != 43 || !reflect.DeepEqual(inventory.LearnedNanos, []uint32{29618}) ||
- len(inventory.TreatmentLocks) != 2 || inventory.TreatmentLocks[1].IsZero() || inventory.TreatmentLocks[3].Year() != 2050 || inventory.Items[0].Slot != 65 ||
- restored.characters[2].inventory.Credits != 91 || len(restored.characters[2].inventory.TreatmentLocks) != 1 {
+ len(restored.characters[1].skillLocks) != 2 || inventory.Items[0].Slot != 65 ||
+ restored.characters[2].inventory.Credits != 91 || len(restored.characters[2].skillLocks) != 1 {
t.Fatal("retry lost metadata, ownership or an unrelated player's state", retry.Body.String())
}
}
-func TestTreatmentUseDeletesOnlyExpiredPatientLocks(t *testing.T) {
- world, _ := newTreatmentKitWorld(t)
+func TestTreatmentUsePreservesOtherSkillsAndPatients(t *testing.T) {
+ world, _ := newInventoryWriteWorld(t)
world.clockStarted = time.Now()
player := world.characters[1]
- inventory := player.inventory
- deadline := time.Date(2050, 1, 1, 0, 0, 0, 0, time.UTC)
- inventory.TreatmentLocks = map[uint32]time.Time{2: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), 3: deadline}
- if err := world.saveInventory_locked(player, inventory); err != nil {
+ setTestSkillLock(t, world, player, 123, time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC))
+ delete(player.skillLocks, 124)
+ if _, err := world.db.Exec("DELETE FROM skill_locks WHERE player_id=1 AND skill=124"); err != nil {
+ t.Fatal(err)
+ }
+ player.inventory.Items[0] = ownedItem{ID: 1, Type: 51005, Template: 25812, Quality: 1, Count: 50, Slot: 64}
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
t.Fatal(err)
}
+ player.sitting, player.health = true, 1
+ player.stats.NanoAiding.Treatment = 7
+ world.clients[1].selectedTarget = [2]uint32{50000, 1}
+ deadline := world.characters[2].skillLocks[124]
auditCheckpointWrites(t, world)
err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:])
- restored := newTestInventoryServer(t).characters[1].inventory
+ restored := newTestInventoryServer(t)
- if err != nil || restored.Items[0].Count != 49 || len(restored.TreatmentLocks) != 2 || !restored.TreatmentLocks[2].IsZero() ||
- !restored.TreatmentLocks[1].Equal(player.inventory.TreatmentLocks[1]) || !restored.TreatmentLocks[3].Equal(deadline) {
- t.Fatal("treatment use lost a retained lock, kept an expired lock or missed the new lock", err)
+ if err != nil || restored.characters[1].inventory.Items[0].Count != 49 ||
+ !restored.characters[1].skillLocks[124].Equal(player.skillLocks[124]) ||
+ !restored.characters[2].skillLocks[124].Equal(deadline) {
+ t.Fatal("treatment use lost an unrelated skill/patient lock", err)
}
- expected := map[string]int{"characters/UPDATE": 1, "items/UPDATE": 1, "treatment_locks/INSERT": 1, "treatment_locks/DELETE": 1}
+ expected := map[string]int{"characters/UPDATE": 1, "items/UPDATE": 1, "skill_locks/INSERT": 1}
if writes := checkpointWrites(t, world); !reflect.DeepEqual(writes, expected) {
t.Fatalf("treatment use rewrote retained locks or unrelated state: %v", writes)
}
@@ -221,19 +225,18 @@ func TestTreatmentUseDeletesOnlyExpiredPatientLocks(t *testing.T) {
func TestInventoryMoveLeavesUnrelatedExpiredCooldownOnDisk(t *testing.T) {
world, _ := newInventoryWriteWorld(t)
other := world.characters[2]
- inventory := other.inventory
deadline := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
- inventory.FirstAidLockedUntil = deadline
- if err := world.saveInventory_locked(other, inventory); err != nil {
- t.Fatal(err)
- }
- other.inventory.FirstAidLockedUntil = time.Time{}
+ setTestSkillLock(t, world, other, 123, deadline)
+ delete(other.skillLocks, 123)
auditCheckpointWrites(t, world)
err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 65)[20:])
- restored := newTestInventoryServer(t)
+ var saved time.Time
+ if queryErr := world.db.QueryRow("SELECT locked_until FROM skill_locks WHERE player_id=2 AND skill=123").Scan(&saved); queryErr != nil {
+ t.Fatal(queryErr)
+ }
- if err != nil || !other.inventory.FirstAidLockedUntil.IsZero() || !restored.characters[2].inventory.FirstAidLockedUntil.Equal(deadline) {
+ if err != nil || !other.skillLocks[123].IsZero() || !saved.Equal(deadline) {
t.Fatal("another player's item move rewrote an expired cooldown notification", err)
}
if writes := checkpointWrites(t, world); !reflect.DeepEqual(writes, map[string]int{"item_locations/DELETE": 1, "item_locations/INSERT": 1}) {
diff --git a/server/item_database.go b/server/item_database.go
@@ -65,26 +65,7 @@ func (server *server) persistItems_locked(store itemStore) error {
if !store.flush && id != store.inventoryPlayer {
continue
}
- if _, err := tx.Exec(`UPDATE players SET credits=?1, first_aid_locked_until=?2
- WHERE id=?3 AND (credits, first_aid_locked_until) IS NOT (?1, ?2)`, references.Credits, references.FirstAidLockedUntil, id); err != nil {
- return err
- }
-
- // Keep unchanged patient locks and remove only entries absent from the new set.
- patients := []any{id}
- for patient, deadline := range references.TreatmentLocks {
- patients = append(patients, patient)
- if _, err := tx.Exec(`INSERT INTO treatment_locks (player_id, patient_id, locked_until) VALUES (?, ?, ?)
- ON CONFLICT(player_id, patient_id) DO UPDATE SET locked_until=excluded.locked_until
- WHERE locked_until IS NOT excluded.locked_until`, id, patient, deadline); err != nil {
- return err
- }
- }
- removeLocks := "DELETE FROM treatment_locks WHERE player_id=?"
- if len(patients) > 1 {
- removeLocks += " AND patient_id NOT IN (" + strings.TrimSuffix(strings.Repeat("?, ", len(patients)-1), ", ") + ")"
- }
- if _, err := tx.Exec(removeLocks, patients...); err != nil {
+ if _, err := tx.Exec(`UPDATE players SET credits=?1 WHERE id=?2 AND credits IS NOT ?1`, references.Credits, id); err != nil {
return err
}
@@ -183,6 +164,11 @@ func (server *server) persistItems_locked(store itemStore) error {
return err
}
}
+ if store.skillLock != nil {
+ if err := writeSkillLock(tx, store.skillLock.Player, store.skillLock.Skill, store.skillLock.Until); err != nil {
+ return err
+ }
+ }
if store.vitalUpdate != nil {
// A resource effect must reach its existing recipient with the item debit.
assignments := strings.ReplaceAll(vitalColumns, ", ", " = ?, ") + " = ?"
@@ -246,40 +232,17 @@ func (server *server) readItems() (itemStore, error) {
return store, err
}
rows.Close()
- rows, err = db.Query("SELECT id, credits, first_aid_locked_until FROM players")
+ rows, err = db.Query("SELECT id, credits FROM players")
if err != nil {
return store, err
}
for rows.Next() {
var id uint32
references := characterItemReferences{inventoryReferences: inventoryReferences{Slots: emptyInventorySlots()}, Equipment: emptyEquipmentSlots(), Bank: emptyItemSlots(bankCapacity)}
- if err := rows.Scan(&id, &references.Credits, &references.FirstAidLockedUntil); err != nil {
- rows.Close()
- return store, err
- }
- store.Players[id] = references
- }
- if err := rows.Err(); err != nil {
- rows.Close()
- return store, err
- }
- rows.Close()
- rows, err = db.Query("SELECT player_id, patient_id, locked_until FROM treatment_locks")
- if err != nil {
- return store, err
- }
- for rows.Next() {
- var id, patient uint32
- var deadline time.Time
- if err := rows.Scan(&id, &patient, &deadline); err != nil {
+ if err := rows.Scan(&id, &references.Credits); err != nil {
rows.Close()
return store, err
}
- references := store.Players[id]
- if references.TreatmentLocks == nil {
- references.TreatmentLocks = make(map[uint32]time.Time)
- }
- references.TreatmentLocks[patient] = deadline
store.Players[id] = references
}
if err := rows.Err(); err != nil {
diff --git a/server/item_store.go b/server/item_store.go
@@ -26,12 +26,10 @@ type reclaimReference struct {
}
type inventoryReferences struct {
- Credits uint32 `yaml:"credits"`
- Slots map[string]*uint32 `yaml:"slots"`
- Reclaim []reclaimReference `yaml:"reclaim"`
- FirstAidLockedUntil time.Time `yaml:"first_aid_locked_until"`
- TreatmentLocks map[uint32]time.Time `yaml:"treatment_locks"`
- LearnedNanos []uint32 `yaml:"learned_nanos"`
+ Credits uint32 `yaml:"credits"`
+ Slots map[string]*uint32 `yaml:"slots"`
+ Reclaim []reclaimReference `yaml:"reclaim"`
+ LearnedNanos []uint32 `yaml:"learned_nanos"`
}
type characterItemReferences struct {
@@ -52,6 +50,7 @@ type itemStore struct {
Corpses map[uint32][]ownedItem
edited *character
vitalUpdate *playerVitalUpdate
+ skillLock *skillLockUpdate
inventoryPlayer uint32
checkpointAt time.Time
flush bool
@@ -67,7 +66,7 @@ func emptyItemSlots(count uint32) map[string]*uint32 {
func (inventory playerInventory) references() characterItemReferences {
result := characterItemReferences{inventoryReferences: inventoryReferences{Credits: inventory.Credits, Slots: emptyInventorySlots(),
- FirstAidLockedUntil: inventory.FirstAidLockedUntil, TreatmentLocks: maps.Clone(inventory.TreatmentLocks), LearnedNanos: slices.Clone(inventory.LearnedNanos)}, Equipment: emptyEquipmentSlots(), Bank: emptyItemSlots(bankCapacity)}
+ LearnedNanos: slices.Clone(inventory.LearnedNanos)}, Equipment: emptyEquipmentSlots(), Bank: emptyItemSlots(bankCapacity)}
for _, item := range inventory.Items {
if item.Slot >= 64 {
result.Slots[fmt.Sprintf("inventory_slot_%d", item.Slot-63)] = &item.ID
@@ -118,8 +117,7 @@ func referencedItems(slots map[string]*uint32, first, count uint32, records map[
}
func (references characterItemReferences) inventory(records map[uint32]itemRecord, lastID uint32) (playerInventory, error) {
- inventory := playerInventory{LastID: lastID, Credits: references.Credits, FirstAidLockedUntil: references.FirstAidLockedUntil,
- TreatmentLocks: references.TreatmentLocks, LearnedNanos: references.LearnedNanos}
+ inventory := playerInventory{LastID: lastID, Credits: references.Credits, LearnedNanos: references.LearnedNanos}
// Named character slots map directly to the native placement numbers.
names := make(map[string]uint32)
for slot, name := range equipmentSlots {
diff --git a/server/kill_experience_test.go b/server/kill_experience_test.go
@@ -160,7 +160,7 @@ func TestKillExperienceFailedRewardRollsBackThenRetries(t *testing.T) {
restored := newTestInventoryServer(t)
if player.level != 1 || player.experience != 1400 || player.stats.ImprovementPoints != 1500 || target.health != 1 || target.corpse != nil ||
- len(world.npcRespawns) != 0 || len(world.corpseExpiry) != 0 || len(player.specialAttackLocks) != 0 ||
+ len(world.npcRespawns) != 0 || len(world.corpseExpiry) != 0 || len(player.skillLocks) != 0 ||
restored.characters[1].experience != 1400 || restored.characters[1].level != 1 || restored.characters[1].stats.ImprovementPoints != 1500 ||
restored.characters[1000000].health != 1 || restored.characters[1000000].corpse != nil {
t.Fatal("failed kill committed part of its progression or corpse")
diff --git a/server/main.go b/server/main.go
@@ -391,17 +391,7 @@ func (server *server) serveWorldClient(client *worldClient) error {
}
}
updates = append(updates, equippedWeaponPackets(character)...)
- if remaining := time.Until(character.treatmentLockedUntil); remaining > 0 {
- updates = append(updates, skillLockPacket(character.id, 124, uint32((remaining+time.Second-1)/time.Second)))
- }
- if remaining := time.Until(character.inventory.FirstAidLockedUntil); remaining > 0 {
- updates = append(updates, skillLockPacket(character.id, 123, uint32((remaining+time.Second-1)/time.Second)))
- }
- for skill, deadline := range character.specialAttackLocks {
- if remaining := time.Until(deadline); remaining > 0 {
- updates = append(updates, skillLockPacket(character.id, skill, uint32((remaining+time.Second-1)/time.Second)))
- }
- }
+ updates = append(updates, character.skillLockPackets(time.Now())...)
updates = append(updates, server.combatInterest_locked(client, nil)...)
if client.target {
for _, id := range []uint32{0xc00003b6, 0xc00003b8} {
diff --git a/server/nano_kit_test.go b/server/nano_kit_test.go
@@ -38,9 +38,9 @@ func TestNanoKitUseRestoresNanoConsumesAndPersistsLock(t *testing.T) {
if err != nil || player.nano < before+10 || player.nano > before+12 || player.health != 17 || player.inventory.Items[0].Count != 24 {
t.Fatalf("nano kit did not restore nano and consume one charge: nano=%d inventory=%+v err=%v", player.nano, player.inventory, err)
}
- if player.inventory.FirstAidLockedUntil.Before(started.Add(40*time.Second)) || player.inventory.FirstAidLockedUntil.After(time.Now().Add(40*time.Second)) ||
+ if player.skillLocks[123].Before(started.Add(40*time.Second)) || player.skillLocks[123].After(time.Now().Add(40*time.Second)) ||
!reflect.DeepEqual(restored.inventory.Items, player.inventory.Items) || restored.inventory.LastID != 1 ||
- !restored.inventory.FirstAidLockedUntil.Equal(player.inventory.FirstAidLockedUntil) || restored.stats.NanoAiding.FirstAid != 6 {
+ !restored.skillLocks[123].Equal(player.skillLocks[123]) || restored.stats.NanoAiding.FirstAid != 6 {
t.Fatal("charge, skill or lock deadline did not persist together")
}
if len(conn.packets) != 5 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 1 ||
@@ -57,15 +57,15 @@ func TestNanoKitLockRejectsRepeatAndClearsAtDeadline(t *testing.T) {
player, client := world.characters[1], world.clients[1]
world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:])
- deadline, nano := player.inventory.FirstAidLockedUntil, player.nano
+ deadline, nano := player.skillLocks[123], player.nano
world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:])
world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 2)[20:])
world.advanceItemEffects(deadline.Add(-time.Nanosecond))
- locked := player.inventory.FirstAidLockedUntil
+ locked := player.skillLocks[123]
world.advanceItemEffects(deadline)
world.advanceItemEffects(deadline.Add(time.Second))
- if nano != player.nano || player.inventory.Items[0].Count != 24 || !locked.Equal(deadline) || !player.inventory.FirstAidLockedUntil.IsZero() {
+ if nano != player.nano || player.inventory.Items[0].Count != 24 || !locked.Equal(deadline) || !player.skillLocks[123].IsZero() {
t.Fatal("replay or cooldown use changed nano, charges or expiry")
}
if len(conn.packets) != 7 || binary.BigEndian.Uint32(conn.packets[5][29:33]) != 2 ||
@@ -160,7 +160,7 @@ func TestNanoKitRestoresFriendAtNativeRangeDuringCombat(t *testing.T) {
err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:])
if err != nil || target.nano < 10 || target.nano > 12 || player.nano != 0 || target.health != 10 || player.inventory.Items[0].Count != 24 ||
- target.fighting != 1000000 || player.fighting != 1000000 || !target.inventory.FirstAidLockedUntil.IsZero() {
+ target.fighting != 1000000 || player.fighting != 1000000 || !target.skillLocks[123].IsZero() {
t.Fatalf("friend nano recovery changed combat, locked the target or failed its 7m boundary: %+v %v", target, err)
}
if len(friendConn.packets) != 3 || binary.BigEndian.Uint32(friendConn.packets[1][24:28]) != 2 || binary.BigEndian.Uint32(friendConn.packets[1][33:37]) != target.nano ||
@@ -180,7 +180,7 @@ func TestNanoKitAcceptedUseRestoresNanoWhenOwnerOutputIsClosed(t *testing.T) {
err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:])
player := world.characters[1]
- if err == nil || player.nano < 10 || player.nano > 12 || player.inventory.Items[0].Count != 24 || player.inventory.FirstAidLockedUntil.IsZero() {
+ if err == nil || player.nano < 10 || player.nano > 12 || player.inventory.Items[0].Count != 24 || player.skillLocks[123].IsZero() {
t.Fatalf("saved charge lost its nano restoration on output failure: nano=%d err=%v", player.nano, err)
}
}
@@ -202,7 +202,7 @@ func TestNanoKitConcurrentUsesConsumeOnce(t *testing.T) {
t.Fatal(err)
}
}
- if world.characters[1].inventory.Items[0].Count != 24 || world.characters[1].inventory.FirstAidLockedUntil.IsZero() {
+ if world.characters[1].inventory.Items[0].Count != 24 || world.characters[1].skillLocks[123].IsZero() {
t.Fatal("simultaneous use consumed twice or bypassed the lock")
}
}
diff --git a/server/nano_recharger_test.go b/server/nano_recharger_test.go
@@ -0,0 +1,187 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+)
+
+func newNanoRechargerWorld(t *testing.T, other bool) (*server, *character, *combatTestConn) {
+ t.Helper()
+ world, patient, conn := newConsumableOutcomeWorld(t, 25820, other)
+ world.characters[1].stats.NanoAiding.TimeAndSpace = 6
+ if err := world.saveUser_locked(world.characters[1]); err != nil {
+ t.Fatal(err)
+ }
+ patient.nano = 1
+ if err := world.savePosition_locked(patient); err != nil {
+ t.Fatal(err)
+ }
+ return world, patient, conn
+}
+
+func TestNanoRechargersUseAuthoredAmountsAndPatientTimeSpaceLocks(t *testing.T) {
+ for _, scenario := range []struct{ template, quality, nano uint32 }{
+ {25820, 1, 30}, {25821, 200, 2000}, {160278, 400, 5000},
+ } {
+ for _, other := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%d/other%t", scenario.template, other), func(t *testing.T) {
+ world, patient, conn := newNanoRechargerWorld(t, other)
+ player := world.characters[1]
+ player.stats.NanoAiding.Treatment, player.stats.NanoAiding.TimeAndSpace = 5000, 5000
+ patient.stats.Body.NanoPool = 60000
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.saveUser_locked(patient); err != nil {
+ t.Fatal(err)
+ }
+ player.inventory.Items[0].Template, player.inventory.Items[0].Quality = scenario.template, scenario.quality
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ unrelated := time.Now().Add(time.Minute)
+ setTestSkillLock(t, world, player, 123, unrelated)
+ setTestSkillLock(t, world, player, 124, unrelated)
+ if other {
+ setTestSkillLock(t, world, player, 131, unrelated)
+ setTestSkillLock(t, world, patient, 124, unrelated)
+ }
+ started := time.Now()
+
+ err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:])
+ restored := newTestInventoryServer(t)
+ world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 2)[20:])
+
+ if err != nil || patient.nano != 1+scenario.nano || restored.characters[patient.id].nano != patient.nano ||
+ player.inventory.Items[0].Count != 49 || restored.characters[1].inventory.Items[0].Count != 49 ||
+ !restored.characters[patient.id].skillLocks[131].Equal(patient.skillLocks[131]) ||
+ patient.skillLocks[131].Before(started.Add(20*time.Second)) || patient.skillLocks[131].After(time.Now().Add(20*time.Second)) ||
+ !player.skillLocks[123].Equal(unrelated) || !player.skillLocks[124].Equal(unrelated) ||
+ binary.BigEndian.Uint32(conn.packets[len(conn.packets)-1][29:33]) != 2 {
+ t.Fatal("recharger lost its amount, patient lock, unrelated lock or charge conservation", err)
+ }
+ if other && (!player.skillLocks[131].Equal(unrelated) || !patient.skillLocks[124].Equal(unrelated)) {
+ t.Fatal("recharger locked its user or replaced the patient's Treatment lock")
+ }
+ })
+ }
+ }
+}
+
+func TestNanoRechargerRejectsBothSkillBoundariesAndPatientLock(t *testing.T) {
+ for _, scenario := range []string{"Treatment equality", "TimeSpace equality", "patient lock"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, patient, conn := newNanoRechargerWorld(t, true)
+ player := world.characters[1]
+ switch scenario {
+ case "Treatment equality":
+ player.stats.NanoAiding.Treatment = 5
+ case "TimeSpace equality":
+ player.stats.NanoAiding.TimeAndSpace = 5
+ case "patient lock":
+ patient.setSkillLock_locked(131, time.Now().Add(time.Minute))
+ }
+
+ err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:])
+ restored := newTestInventoryServer(t)
+
+ if err != nil || patient.nano != 1 || player.inventory.Items[0].Count != 50 ||
+ restored.characters[patient.id].nano != 1 || restored.characters[1].inventory.Items[0].Count != 50 ||
+ len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 {
+ t.Fatal("rejected recharger consumed a charge or restored nano", err)
+ }
+ })
+ }
+}
+
+func TestNanoRechargerLastChargeRollsBackWithLockThenRetries(t *testing.T) {
+ for _, failure := range []string{"FAIL, 'lock failure'", "IGNORE"} {
+ t.Run(failure, func(t *testing.T) {
+ world, patient, conn := newNanoRechargerWorld(t, true)
+ player := world.characters[1]
+ player.inventory.Items[0].Count = 1
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec("CREATE TRIGGER reject_recharger BEFORE INSERT ON skill_locks WHEN NEW.skill=131 BEGIN SELECT RAISE(" + failure + "); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ failed := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:])
+ rolledBack := newTestInventoryServer(t)
+ if failed == nil || len(conn.packets) != 0 || patient.nano != 1 || len(patient.skillLocks) != 0 ||
+ len(player.inventory.Items) != 1 || rolledBack.characters[1].inventory.Items[0].Count != 1 || rolledBack.characters[2].nano != 1 ||
+ len(rolledBack.characters[1].skillLocks) != 0 || len(rolledBack.characters[2].skillLocks) != 0 {
+ t.Fatal("failed last charge lost the instance or committed part of the effect", failed)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER reject_recharger"); err != nil {
+ t.Fatal(err)
+ }
+ err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 2)[20:])
+ restored := newTestInventoryServer(t)
+
+ if err != nil || len(restored.items) != 0 || len(player.inventory.Items) != 0 ||
+ patient.nano != 31 || restored.characters[2].nano != 31 || restored.characters[2].skillLocks[131].IsZero() {
+ t.Fatal("retry did not commit the complete final-charge effect", err)
+ }
+ })
+ }
+}
+
+func TestDeletingHealerDoesNotRemovePatientCooldown(t *testing.T) {
+ world, patient, _ := newNanoRechargerWorld(t, true)
+ if err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ deadline := patient.skillLocks[131]
+
+ if _, err := world.db.Exec("DELETE FROM item_locations WHERE player_id=1; DELETE FROM items WHERE id=1; DELETE FROM characters WHERE id=1"); err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t)
+
+ if restored.characters[1] != nil || !restored.characters[2].skillLocks[131].Equal(deadline) || restored.characters[2].nano != 31 {
+ t.Fatal("patient cooldown/resources depended on the healer's continued existence")
+ }
+}
+
+func TestConcurrentHealersShareOnePatientLock(t *testing.T) {
+ world, patient, _ := newNanoRechargerWorld(t, true)
+ healer := world.newCharacter()
+ healer.stats = testCharacterStats()
+ healer.stats.NanoAiding.Treatment, healer.stats.NanoAiding.TimeAndSpace = 6, 6
+ if err := world.saveUser_locked(healer); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(healer, 25820); !granted || err != nil {
+ t.Fatal(granted, err)
+ }
+ world.clients[3] = &worldClient{id: 3, conn: &combatTestConn{}, target: true, ready: true, selectedTarget: [2]uint32{50000, 2}}
+ var group sync.WaitGroup
+ errors := make(chan error, 2)
+
+ for _, owner := range []uint32{1, 3} {
+ group.Go(func() {
+ errors <- world.handleOwnedItemUse(world.clients[owner], backpackUseRequest(owner, 64, 1)[20:])
+ })
+ }
+ group.Wait()
+ close(errors)
+ restored := newTestInventoryServer(t)
+
+ for err := range errors {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ if patient.nano != 31 || restored.characters[2].nano != 31 || patient.skillLocks[131].IsZero() ||
+ !restored.characters[2].skillLocks[131].Equal(patient.skillLocks[131]) ||
+ world.characters[1].inventory.Items[0].Count+healer.inventory.Items[0].Count != 99 ||
+ restored.characters[1].inventory.Items[0].Count+restored.characters[3].inventory.Items[0].Count != 99 ||
+ !world.characters[1].skillLocks[131].IsZero() || !healer.skillLocks[131].IsZero() {
+ t.Fatal("racing healers restored twice, consumed two charges or locked a healer")
+ }
+}
diff --git a/server/profile_database.go b/server/profile_database.go
@@ -18,7 +18,7 @@ const profileColumns = "name, appearance_race, appearance_fatness, appearance_br
"nano_aiding_matter_creation, nano_aiding_time_and_space, nano_aiding_sensory_improvement, nano_aiding_first_aid, " +
"nano_aiding_treatment, spying_concealment, spying_breaking_and_entering, spying_trap_disarm, spying_perception, " +
"navigation_vehicle_air, navigation_vehicle_ground, navigation_vehicle_water, navigation_map_navigation, running, " +
- "browser_token_hash, resurrection_terminal, implant_changes_until, treatment_locked_until"
+ "browser_token_hash, resurrection_terminal, implant_changes_until"
func (profile *playerProfile) fields() []any {
return []any{
@@ -44,6 +44,6 @@ func (profile *playerProfile) fields() []any {
&profile.Stats.NanoAiding.FirstAid, &profile.Stats.NanoAiding.Treatment, &profile.Stats.Spying.Concealment, &profile.Stats.Spying.BreakingAndEntering,
&profile.Stats.Spying.TrapDisarm, &profile.Stats.Spying.Perception, &profile.Stats.Navigation.VehicleAir, &profile.Stats.Navigation.VehicleGround,
&profile.Stats.Navigation.VehicleWater, &profile.Stats.Navigation.MapNavigation, &profile.Running, &profile.BrowserTokenHash,
- &profile.ResurrectionTerminal, &profile.ImplantChangesUntil, &profile.TreatmentLockedUntil,
+ &profile.ResurrectionTerminal, &profile.ImplantChangesUntil,
}
}
diff --git a/server/resource_kit.go b/server/resource_kit.go
@@ -3,7 +3,6 @@ package main
import (
"ao/server/gamedata"
"encoding/binary"
- "maps"
"math/rand/v2"
"slices"
"time"
@@ -97,7 +96,7 @@ func (item ownedItem) resourceKit() (resourceKit, bool) {
// Combat HP delivery is unresolved; do not consume only a stim's nano half.
return kit, kit.health[1] == 0
}
- return kit, kit.lockSkill == 124 && itemStat(definition, 371) != 0
+ return kit, (kit.lockSkill == 124 || kit.lockSkill == 131) && itemStat(definition, 371) != 0
}
func (server *server) itemUseRequirementsMet_locked(player, target *character, item ownedItem) bool {
@@ -134,17 +133,17 @@ func (server *server) useResourceKit_locked(client *worldClient, index int, body
player := server.characters[client.id]
item := player.inventory.Items[index]
target := server.characters[client.selectedTarget[1]]
+ lockRecipient := target
+ if kit.lockSkill == 123 {
+ lockRecipient = player
+ }
now := time.Now()
accepted := item.Slot >= 64 && item.Slot < 94 && client.selectedTarget[0] == 50000 &&
target != nil && !target.npc && target.health > 0 && target.playfield == player.playfield &&
server.clients[target.id] != nil && server.clients[target.id].ready && !server.clients[target.id].loading
if accepted {
accepted = server.itemUseRequirementsMet_locked(player, target, item)
- if kit.lockSkill == 123 {
- accepted = accepted && !now.Before(player.inventory.FirstAidLockedUntil)
- } else {
- accepted = accepted && !now.Before(target.treatmentLockedUntil)
- }
+ accepted = accepted && !now.Before(lockRecipient.skillLocks[kit.lockSkill])
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]
@@ -159,21 +158,7 @@ func (server *server) useResourceKit_locked(client *worldClient, index int, body
if inventory.Items[index].Count == 0 {
inventory.Items = slices.Delete(inventory.Items, index, index+1)
}
- deadline := now.Add(time.Duration(kit.lockSeconds) * time.Second)
- if kit.lockSkill == 123 {
- inventory.FirstAidLockedUntil = deadline
- } else {
- inventory.TreatmentLocks = maps.Clone(inventory.TreatmentLocks)
- if inventory.TreatmentLocks == nil {
- inventory.TreatmentLocks = make(map[uint32]time.Time)
- }
- for id, until := range inventory.TreatmentLocks {
- if !now.Before(until) {
- delete(inventory.TreatmentLocks, id)
- }
- }
- inventory.TreatmentLocks[target.id] = deadline
- }
+ deadline := now.Add(time.Duration(lockRecipient.skillLockSeconds(kit.lockSeconds)) * time.Second)
vitals := target.vitals()
// Uniform inclusive endpoint rolls remain a reconstruction policy.
if kit.health[1] != 0 {
@@ -182,12 +167,9 @@ func (server *server) useResourceKit_locked(client *worldClient, index int, body
if kit.nano[1] != 0 {
vitals.Nano = min(target.maximumNano(), vitals.Nano+kit.nano[0]+rand.Uint32N(kit.nano[1]-kit.nano[0]+1))
}
- if err := server.saveItemEffect_locked(player, target, inventory, vitals); err != nil {
+ if err := server.saveItemEffect_locked(player, target, inventory, vitals, skillLockUpdate{lockRecipient.id, kit.lockSkill, deadline}); err != nil {
return err
}
- if kit.lockSkill == 124 {
- target.treatmentLockedUntil = deadline
- }
}
reply := append([]byte(nil), body[16:]...)
@@ -218,10 +200,6 @@ func (server *server) useResourceKit_locked(client *worldClient, index int, body
}
updates[client] = append(updates[client], n3Packet(0x5e477770, 50000, client.id, removal))
}
- lockRecipient := player
- if kit.lockSkill == 124 {
- lockRecipient = target
- }
lockClient := server.clients[lockRecipient.id]
updates[lockClient] = append(updates[lockClient], skillLockPacket(lockRecipient.id, kit.lockSkill, kit.lockSeconds))
if kit.nano[1] != 0 {
diff --git a/server/resource_kit_test.go b/server/resource_kit_test.go
@@ -26,7 +26,7 @@ func TestResourceKitCatalogAdmission(t *testing.T) {
}
slices.Sort(admitted)
- if !reflect.DeepEqual(admitted, []uint32{25811, 25812, 85366, 85367, 116628, 160277, 160295}) {
+ if !reflect.DeepEqual(admitted, []uint32{25811, 25812, 25820, 25821, 85366, 85367, 116628, 160277, 160278, 160295}) {
t.Fatal("unexpected medical use contract in the full catalog", admitted)
}
}
@@ -42,9 +42,13 @@ func newStartupLaboratoryWorld(t *testing.T, other bool) (*server, *character, *
t.Fatal(err)
}
// Persist the fixture's source quantity and both patient resources.
- if err := world.saveItemEffect_locked(player, target, player.inventory, target.vitals()); err != nil {
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
t.Fatal(err)
}
+ if _, err := world.db.Exec("UPDATE characters SET health=?, nano=? WHERE id=?", target.health, target.nano, target.id); err != nil {
+ t.Fatal(err)
+ }
+ target.savedVitals = target.vitals()
return world, target, conn
}
@@ -84,9 +88,9 @@ func TestCatalogResourceKitsUseAuthoredQualityAmountsAndLocks(t *testing.T) {
binary.BigEndian.Uint32(conn.packets[1][29:33]) != scenario.template || binary.BigEndian.Uint32(conn.packets[1][37:41]) != scenario.quality {
t.Fatal("catalog restoration, quality, charge or persistence mismatch", err)
}
- deadline, seconds := player.treatmentLockedUntil, 15*time.Second
+ deadline, seconds := player.skillLocks[124], 15*time.Second
if scenario.health == 0 {
- deadline, seconds = player.inventory.FirstAidLockedUntil, 40*time.Second
+ deadline, seconds = player.skillLocks[123], 40*time.Second
}
if deadline.Before(started.Add(seconds)) || deadline.After(time.Now().Add(seconds)) {
t.Fatal("cooldown differs from the authored SkillTime")
@@ -112,9 +116,9 @@ func TestStartupLaboratoryCommitsBothResourcesBeforeSuccess(t *testing.T) {
restored := newTestInventoryServer(t)
if err != nil || !conn.observed || conn.err != nil || conn.health != 16 || conn.nano != 16 || conn.count != count-1 ||
- !conn.patient.Valid || conn.patient.Time.IsZero() || !conn.firstAid.IsZero() ||
+ !conn.patient.Valid || conn.patient.Time.IsZero() || conn.firstAid.Valid ||
target.health != 16 || target.nano != 16 || restored.characters[target.id].health != 16 || restored.characters[target.id].nano != 16 ||
- !restored.characters[target.id].treatmentLockedUntil.Equal(target.treatmentLockedUntil) {
+ !restored.characters[target.id].skillLocks[124].Equal(target.skillLocks[124]) {
t.Fatal("success preceded an atomic dual-resource/charge/patient-lock commit", err, conn.err)
}
if count == 1 {
@@ -144,7 +148,7 @@ func TestStartupLaboratoryRollbackPreservesBothResourcesAndRetries(t *testing.T)
statement := "CREATE TRIGGER reject_startup BEFORE UPDATE ON items BEGIN SELECT RAISE(FAIL, 'charge'); END"
switch phase {
case "lock":
- statement = "CREATE TRIGGER reject_startup BEFORE INSERT ON treatment_locks BEGIN SELECT RAISE(FAIL, 'lock'); END"
+ statement = "CREATE TRIGGER reject_startup BEFORE INSERT ON skill_locks BEGIN SELECT RAISE(FAIL, 'lock'); END"
case "health":
statement = "CREATE TRIGGER reject_startup BEFORE UPDATE OF health ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(FAIL, 'health'); END"
case "nano":
@@ -162,7 +166,7 @@ func TestStartupLaboratoryRollbackPreservesBothResourcesAndRetries(t *testing.T)
t.Fatal(queryErr)
}
if err == nil || !bytes.Equal(before, after) || target.health != 1 || target.nano != 1 || player.inventory.Items[0].Count != 25 ||
- savedHealth != 1 || savedNano != 1 || len(player.inventory.TreatmentLocks) != 0 || !target.treatmentLockedUntil.IsZero() || len(conn.packets) != 0 {
+ savedHealth != 1 || savedNano != 1 || len(player.skillLocks) != 0 || !target.skillLocks[124].IsZero() || len(conn.packets) != 0 {
t.Fatal("failed dual restoration left a partial gain, debit or cooldown", err)
}
if _, err := world.db.Exec("DROP TRIGGER reject_startup"); err != nil {
@@ -172,7 +176,7 @@ func TestStartupLaboratoryRollbackPreservesBothResourcesAndRetries(t *testing.T)
restored := newTestInventoryServer(t)
if err != nil || target.health != 16 || target.nano != 16 || player.inventory.Items[0].Count != 24 ||
- restored.characters[2].health != 16 || restored.characters[2].nano != 16 || restored.characters[2].treatmentLockedUntil.IsZero() {
+ restored.characters[2].health != 16 || restored.characters[2].nano != 16 || restored.characters[2].skillLocks[124].IsZero() {
t.Fatal("rolled-back startup use could not retry atomically", err)
}
})
@@ -193,7 +197,7 @@ func TestStartupLaboratoryRejectsInvalidStateAndRetainsBothResources(t *testing.
case "skill equality":
player.stats.NanoAiding.Treatment = 3
case "patient lock":
- target.treatmentLockedUntil = time.Now().Add(time.Minute)
+ target.setSkillLock_locked(124, time.Now().Add(time.Minute))
case "healer attacking":
player.fighting = 1000000
case "patient attacking":
@@ -250,7 +254,7 @@ func TestStartupLaboratoryRejectsInvalidStateAndRetainsBothResources(t *testing.
after, _ := readTestItemStore(world)
if err != nil || !bytes.Equal(before, after) || player.inventory.Items[0].Count != 25 || target.health != health || target.nano != nano ||
- len(player.inventory.TreatmentLocks) != 0 || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 {
+ len(player.skillLocks) != 0 || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 {
t.Fatal("rejected startup use consumed a charge or partially restored a resource", err)
}
})
@@ -315,8 +319,8 @@ func TestStartupLaboratoryPatientCooldownRangeBoundaryAndPrivateNano(t *testing.
world, target, _ := newStartupLaboratoryWorld(t, true)
player := world.characters[1]
player.sitting = false
- player.treatmentLockedUntil = time.Now().Add(600 * time.Second)
- healerLock := player.treatmentLockedUntil
+ player.setSkillLock_locked(124, time.Now().Add(600*time.Second))
+ healerLock := player.skillLocks[124]
target.position = player.position
target.position[0] += 7
observer := &combatTestConn{}
@@ -324,7 +328,7 @@ func TestStartupLaboratoryPatientCooldownRangeBoundaryAndPrivateNano(t *testing.
world.clients[3] = &worldClient{id: 3, conn: observer, target: true, ready: true}
err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:])
- deadline := target.treatmentLockedUntil
+ deadline := target.skillLocks[124]
world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 2)[20:])
if player.inventory.Items[0].Count != 24 || target.health != 16 || target.nano != 16 {
t.Fatal("patient cooldown admitted the immediate repeat")
@@ -333,7 +337,7 @@ func TestStartupLaboratoryPatientCooldownRangeBoundaryAndPrivateNano(t *testing.
world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 3)[20:])
if err != nil || target.health != 31 || target.nano != 31 || player.inventory.Items[0].Count != 23 ||
- !player.treatmentLockedUntil.Equal(healerLock) || len(observer.packets) != 4 {
+ !player.skillLocks[124].Equal(healerLock) || len(observer.packets) != 4 {
t.Fatal("standing, locked healer failed at the inclusive range boundary or patient expiry", err)
}
for _, packet := range observer.packets {
@@ -357,7 +361,7 @@ func TestStartupLaboratoryOutputFailurePreservesBothGainsAndPatientLock(t *testi
replay := restored.handleOwnedItemUse(restored.clients[1], backpackUseRequest(1, 64, 2)[20:])
if failedOutput == nil || replay != nil || target.health != 16 || target.nano != 16 ||
- restored.characters[2].health != 16 || restored.characters[2].nano != 16 || restored.characters[2].treatmentLockedUntil.IsZero() ||
+ restored.characters[2].health != 16 || restored.characters[2].nano != 16 || restored.characters[2].skillLocks[124].IsZero() ||
restored.characters[1].inventory.Items[0].Count != 24 || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 {
t.Fatal("output failure lost part of the committed effect or allowed another debit", failedOutput, replay)
}
@@ -382,7 +386,7 @@ func TestUnimplementedFirstAidNeverConsumesOnlyPartOfItsEffect(t *testing.T) {
after, _ := readTestItemStore(world)
if err != nil || !bytes.Equal(before, after) || target.health != 1 || target.nano != 1 || player.inventory.Items[0].Count != 1 ||
- !player.inventory.FirstAidLockedUntil.IsZero() || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 {
+ !player.skillLocks[123].IsZero() || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 {
t.Fatal("unsupported First Aid partially restored a resource, consumed its last charge or started a lock", err)
}
})
diff --git a/server/skill_locks.go b/server/skill_locks.go
@@ -0,0 +1,95 @@
+package main
+
+import (
+ "database/sql"
+ "fmt"
+ "math"
+ "time"
+)
+
+type skillLockUpdate struct {
+ Player uint32
+ Skill uint32
+ Until time.Time
+}
+
+func (server *server) loadSkillLocks() error {
+ db, err := server.database()
+ if err != nil {
+ return err
+ }
+ rows, err := db.Query("SELECT player_id, skill, locked_until FROM skill_locks")
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ now := time.Now()
+ for rows.Next() {
+ var id, skill uint32
+ var deadline time.Time
+ if err := rows.Scan(&id, &skill, &deadline); err != nil {
+ return err
+ }
+ if now.Before(deadline) {
+ server.characters[id].setSkillLock_locked(skill, deadline)
+ }
+ }
+ return rows.Err()
+}
+
+func writeSkillLock(tx *sql.Tx, player, skill uint32, deadline time.Time) error {
+ result, err := tx.Exec(`INSERT INTO skill_locks (player_id, skill, locked_until) VALUES (?, ?, ?)
+ ON CONFLICT(player_id, skill) DO UPDATE SET locked_until=excluded.locked_until`, player, skill, deadline)
+ if err != nil {
+ return err
+ }
+ changed, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if changed != 1 {
+ return fmt.Errorf("player %d skill %d lock update affected %d rows", player, skill, changed)
+ }
+ return nil
+}
+
+func (player *character) setSkillLock_locked(skill uint32, deadline time.Time) {
+ if player.skillLocks == nil {
+ player.skillLocks = make(map[uint32]time.Time)
+ }
+ player.skillLocks[skill] = deadline
+}
+
+func scaledSkillLockSeconds(raw uint32, modifier int32) int32 {
+ // kkr.dll 10073ae0 multiplies signed integers before scaling by float32 .01.
+ product := int32(raw) * modifier
+ // Explicit rounding keeps multiply/add separate; _ftol stores the low 32 bits.
+ scaled := float64(float64(product) * float64(float32(0.01)))
+ return int32(int64(float64(int32(raw)) + scaled))
+}
+
+func (player *character) skillLockSeconds(raw uint32) int32 {
+ return scaledSkillLockSeconds(raw, player.equipmentBonus(382)+player.nanoBonus(382))
+}
+
+func (player *character) skillLockPackets(now time.Time) [][]byte {
+ var packets [][]byte
+ modifier := player.equipmentBonus(382) + player.nanoBonus(382)
+ for skill, deadline := range player.skillLocks {
+ if !now.Before(deadline) || modifier <= -100 {
+ continue
+ }
+ // Reconstruct raw seconds without applying the current modifier twice.
+ seconds := uint32((deadline.Sub(now) + time.Second - 1) / time.Second)
+ raw := uint32(math.Ceil(float64(seconds) / (1 + float64(modifier)*float64(float32(0.01)))))
+ for scaledSkillLockSeconds(raw, modifier) < int32(seconds) {
+ raw++
+ }
+ for raw > 1 && scaledSkillLockSeconds(raw-1, modifier) >= int32(seconds) {
+ raw--
+ }
+ // Some durations are unrepresentable; authoritative expiry also sends action164.
+ packets = append(packets, skillLockPacket(player.id, skill, raw))
+ }
+ return packets
+}
diff --git a/server/skill_locks_test.go b/server/skill_locks_test.go
@@ -0,0 +1,292 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "fmt"
+ "slices"
+ "testing"
+ "time"
+)
+
+func setTestSkillLock(t *testing.T, world *server, player *character, skill uint32, deadline time.Time) {
+ t.Helper()
+ tx, err := world.db.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback()
+ if err := writeSkillLock(tx, player.id, skill, deadline); err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ player.setSkillLock_locked(skill, deadline)
+}
+
+func TestSkillLockMatchesNativeRounding(t *testing.T) {
+ for _, scenario := range []struct {
+ raw uint32
+ modifier int32
+ seconds int32
+ }{
+ {15, 5, 15}, {15, 50, 22}, {15, -5, 14}, {15, -50, 7}, {15, -100, 0}, {15, -150, -7},
+ {20, 5, 20}, {20, 50, 29}, {20, -5, 19}, {20, -50, 10}, {20, -100, 0}, {20, -150, -9},
+ {40, 5, 41}, {40, 50, 59}, {40, -5, 38}, {40, -50, 20}, {40, -100, 0}, {40, -150, -19},
+ {600, 5, 629}, {600, 50, 899}, {600, -5, 570}, {600, -50, 300}, {600, -100, 0}, {600, -150, -299},
+ } {
+ t.Run(fmt.Sprintf("%d/%d", scenario.raw, scenario.modifier), func(t *testing.T) {
+ // Values come from the native instruction audit, not another server formula.
+
+ seconds := scaledSkillLockSeconds(scenario.raw, scenario.modifier)
+
+ if seconds != scenario.seconds {
+ t.Fatalf("native lock rounding: got %d, want %d", seconds, scenario.seconds)
+ }
+ })
+ }
+}
+
+func setTestSkillModifier(t *testing.T, world *server, player *character, modifier int32) {
+ t.Helper()
+ // Substitute one complete OnWear modifier to isolate equipment/stat accounting.
+ original := gamedata.ItemTemplates[101173]
+ definition := *original
+ definition.Sections = slices.Clone(original.Sections)
+ stat := int32(382)
+ for index, section := range definition.Sections {
+ if section.Type == 2 && section.Subtype == 14 {
+ functions := []gamedata.ItemFunction{{ID: 53045, Target: 2, TickCount: 1,
+ Arguments: []gamedata.ItemArgument{{Integer: &stat}, {Integer: &modifier}}}}
+ definition.Sections[index].Functions = &functions
+ }
+ }
+ gamedata.ItemTemplates[101173] = &definition
+ t.Cleanup(func() { gamedata.ItemTemplates[101173] = original })
+ player.inventory.LastID = world.nextItem + 1
+ player.inventory.Items = append(player.inventory.Items, ownedItem{ID: player.inventory.LastID, Type: 51022, Template: 101173, Quality: 1, Slot: 37, Count: 1})
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestSkillLockReplayUsesCurrentModifierWithoutChangingDeadline(t *testing.T) {
+ for _, scenario := range []struct {
+ modifier int32
+ seconds uint32
+ raw uint32
+ }{
+ {0, 10, 10}, {-50, 10, 20}, {-15, 34, 40}, {50, 10, 7}, {100, 2, 2}, {100, 10, 6},
+ } {
+ t.Run(fmt.Sprintf("%d/%d", scenario.modifier, scenario.seconds), func(t *testing.T) {
+ world, conn := newNanoKitWorld(t)
+ player := world.characters[1]
+ setTestSkillModifier(t, world, player, scenario.modifier)
+ now := time.Now()
+ deadline := now.Add(time.Duration(scenario.seconds)*time.Second - time.Millisecond)
+ setTestSkillLock(t, world, player, 123, deadline)
+
+ restored := newTestInventoryServer(t).characters[1]
+ packets := restored.skillLockPackets(now)
+ for _, packet := range packets {
+ if err := world.clients[1].send(packet); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 170 ||
+ binary.BigEndian.Uint32(conn.packets[0][41:45]) != 123 || binary.BigEndian.Uint32(conn.packets[0][45:49]) != scenario.raw ||
+ !restored.skillLocks[123].Equal(deadline) {
+ t.Fatalf("replay scaled an absolute deadline twice or selected the wrong raw duration: packets=%x lock=%v want=%v modifier=%d", packets, restored.skillLocks[123], deadline, restored.equipmentBonus(382))
+ }
+ })
+ }
+}
+
+func TestSkillLockExpiryChangesOnlyMemoryAndNotifiesOnce(t *testing.T) {
+ world, conn := newNanoKitWorld(t)
+ player := world.characters[1]
+ deadline := time.Now().Add(time.Minute)
+ setTestSkillLock(t, world, player, 123, deadline)
+ setTestSkillLock(t, world, player, 124, deadline.Add(time.Second))
+ setTestSkillLock(t, world, player, 131, deadline)
+ auditCheckpointWrites(t, world)
+
+ world.advanceItemEffects(deadline.Add(-time.Nanosecond))
+ if len(conn.packets) != 0 {
+ t.Fatal("lock expired before its authoritative deadline")
+ }
+ world.advanceItemEffects(deadline)
+ world.advanceItemEffects(deadline)
+ var persisted int
+ if err := world.db.QueryRow("SELECT count(*) FROM skill_locks WHERE player_id=1").Scan(&persisted); err != nil {
+ t.Fatal(err)
+ }
+
+ if len(player.skillLocks) != 1 || !player.skillLocks[124].Equal(deadline.Add(time.Second)) || len(conn.packets) != 2 || persisted != 3 || len(checkpointWrites(t, world)) != 0 {
+ t.Fatal("expiry removed another skill, repeated notifications or churned the database")
+ }
+ var cleared []uint32
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[29:33]) != 164 {
+ t.Fatal("expiry did not use the recovered native removal action")
+ }
+ cleared = append(cleared, binary.BigEndian.Uint32(packet[45:49]))
+ }
+ slices.Sort(cleared)
+ if !slices.Equal(cleared, []uint32{123, 131}) {
+ t.Fatal("expiry notified the wrong skills", cleared)
+ }
+}
+
+func TestRechargerSamplesPatientModifierAndKeepsDeadlineAfterGearRemoval(t *testing.T) {
+ world, patient, _ := newNanoRechargerWorld(t, true)
+ setTestSkillModifier(t, world, patient, -50)
+ patient.implantChangesUntil = time.Now().Add(time.Minute)
+ started := time.Now()
+
+ err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:])
+ deadline := patient.skillLocks[131]
+ patientPackets := world.clients[2].conn.(*combatTestConn).packets
+ if err := world.handleInventory(world.clients[2], itemMovePacket(2, 37, 64)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if world.clients[2].equipment == nil {
+ t.Fatal("modifier implant removal was rejected")
+ }
+ world.advanceEquipment(world.clients[2].equipment.readyAt)
+ restored := newTestInventoryServer(t).characters[2]
+
+ if err != nil || deadline.Before(started.Add(10*time.Second)) || deadline.After(time.Now().Add(10*time.Second)) ||
+ !patient.skillLocks[131].Equal(deadline) || !restored.skillLocks[131].Equal(deadline) || patient.equipmentBonus(382) != 0 ||
+ len(patientPackets) != 4 || binary.BigEndian.Uint32(patientPackets[1][41:45]) != 131 || binary.BigEndian.Uint32(patientPackets[1][45:49]) != 20 {
+ t.Fatalf("patient lock: elapsed=%v modifier=%d live=%v cold=%v packets=%x err=%v", deadline.Sub(started), patient.equipmentBonus(382), patient.skillLocks[131], restored.skillLocks[131], patientPackets, err)
+ }
+}
+
+func TestClinicSharesScaledTreatmentLock(t *testing.T) {
+ world, conn := newNanoKitWorld(t)
+ player := world.characters[1]
+ setTestSkillModifier(t, world, player, 50)
+ if granted, err := world.grantItem_locked(player, 43552); !granted || err != nil {
+ t.Fatal(granted, err)
+ }
+ started := time.Now()
+
+ err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 65, 1)[20:])
+ restored := newTestInventoryServer(t).characters[1]
+
+ if err != nil || player.skillLocks[124].Before(started.Add(899*time.Second)) || player.skillLocks[124].After(time.Now().Add(899*time.Second)) ||
+ !restored.skillLocks[124].Equal(player.skillLocks[124]) || restored.implantChangesUntil.Before(started.Add(30*time.Second)) ||
+ len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[2][41:45]) != 124 || binary.BigEndian.Uint32(conn.packets[2][45:49]) != 600 {
+ t.Fatal("clinic did not share the native-scaled Treatment lock or changed its independent access window", err)
+ }
+}
+
+func TestWeaponSpecialSharesScaledSkillLock(t *testing.T) {
+ world, conn := newFastAttackWorld(t)
+ player := world.characters[1]
+ setTestSkillModifier(t, world, player, -50)
+ started := time.Now()
+
+ err := world.handleWeaponSpecial(world.clients[1], fastAttackRequest(1, 1000000)[20:])
+ restored := newTestInventoryServer(t).characters[1]
+
+ if err != nil || len(conn.packets) < 2 {
+ t.Fatal("special attack was rejected", err)
+ }
+ raw := binary.BigEndian.Uint32(conn.packets[1][45:49])
+ if raw != 19 || player.skillLocks[147].Before(started.Add(9*time.Second)) || player.skillLocks[147].After(time.Now().Add(9*time.Second)) ||
+ !restored.skillLocks[147].Equal(player.skillLocks[147]) {
+ t.Fatal("special attack used a separate unscaled cooldown or failed cold recovery")
+ }
+}
+
+func TestUnrepresentableReplayRetainsAuthoritativeLock(t *testing.T) {
+ for _, modifier := range []int32{-100, -150} {
+ t.Run(fmt.Sprint(modifier), func(t *testing.T) {
+ world, conn := newNanoKitWorld(t)
+ player := world.characters[1]
+ setTestSkillModifier(t, world, player, modifier)
+ deadline := time.Now().Add(time.Minute)
+ setTestSkillLock(t, world, player, 123, deadline)
+
+ packets := player.skillLockPackets(time.Now())
+ world.advanceItemEffects(deadline)
+
+ if len(packets) != 0 || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 164 {
+ t.Fatal("unrepresentable replay fabricated a positive duration or lost authoritative expiry")
+ }
+ })
+ }
+}
+
+func TestClinicWindowAndSkillLockRollbackTogether(t *testing.T) {
+ for _, phase := range []string{"window", "lock", "ignored lock", "commit"} {
+ t.Run(phase, func(t *testing.T) {
+ world, conn := newImplantWorld(t)
+ player := world.characters[1]
+ statement := "CREATE TRIGGER reject_clinic BEFORE UPDATE OF implant_changes_until ON characters BEGIN SELECT RAISE(FAIL, 'window'); END"
+ switch phase {
+ case "lock":
+ statement = "CREATE TRIGGER reject_clinic BEFORE INSERT ON skill_locks BEGIN SELECT RAISE(FAIL, 'lock'); END"
+ case "ignored lock":
+ statement = "CREATE TRIGGER reject_clinic BEFORE INSERT ON skill_locks BEGIN SELECT RAISE(IGNORE); END"
+ case "commit":
+ statement = "CREATE TABLE pending_clinic (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_clinic AFTER INSERT ON skill_locks BEGIN INSERT INTO pending_clinic VALUES (999999); END"
+ }
+ if _, err := world.db.Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+
+ failed := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 67, 1)[20:])
+ rolledBack := newTestInventoryServer(t).characters[1]
+ if failed == nil || len(conn.packets) != 0 || !player.implantChangesUntil.IsZero() || len(player.skillLocks) != 0 ||
+ !rolledBack.implantChangesUntil.IsZero() || len(rolledBack.skillLocks) != 0 {
+ t.Fatal("failed clinic use published or committed only one part of the effect", failed)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER reject_clinic"); err != nil {
+ t.Fatal(err)
+ }
+ err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 67, 2)[20:])
+ restored := newTestInventoryServer(t).characters[1]
+
+ if err != nil || player.implantChangesUntil.IsZero() || player.skillLocks[124].IsZero() ||
+ !restored.implantChangesUntil.Equal(player.implantChangesUntil) || !restored.skillLocks[124].Equal(player.skillLocks[124]) || len(conn.packets) != 3 {
+ t.Fatal("clinic retry did not commit one complete window/cooldown outcome", err)
+ }
+ })
+ }
+}
+
+func TestKitCombinesPatientEquipmentAndNanoLockModifiers(t *testing.T) {
+ world, patient, _ := newNanoRechargerWorld(t, true)
+ setTestSkillModifier(t, world, patient, -25)
+ original := gamedata.NanoTemplates[26360]
+ definition := *original
+ definition.Sections = slices.Clone(original.Sections)
+ stat, modifier := int32(382), int32(-25)
+ for index, section := range definition.Sections {
+ if section.Type == 2 && section.Subtype == 0 {
+ functions := []gamedata.ItemFunction{{ID: 53045, Target: 3, TickCount: 1,
+ Arguments: []gamedata.ItemArgument{{Integer: &stat}, {Integer: &modifier}}}}
+ definition.Sections[index].Functions = &functions
+ }
+ }
+ gamedata.NanoTemplates[26360] = &definition
+ t.Cleanup(func() { gamedata.NanoTemplates[26360] = original })
+ patient.activeNanos = []activeNano{{program: 26360, caster: 1, remaining: time.Minute}}
+ if err := world.savePosition_locked(patient); err != nil {
+ t.Fatal(err)
+ }
+ started := time.Now()
+
+ err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:])
+ restored := newTestInventoryServer(t).characters[2]
+
+ if err != nil || patient.skillLocks[131].Before(started.Add(10*time.Second)) || patient.skillLocks[131].After(time.Now().Add(10*time.Second)) ||
+ !restored.skillLocks[131].Equal(patient.skillLocks[131]) || restored.nanoBonus(382) != -25 || restored.equipmentBonus(382) != -25 {
+ t.Fatal("combined modifiers did not apply once to the patient's persistent lock", err)
+ }
+}
diff --git a/server/special_locks.go b/server/special_locks.go
@@ -2,33 +2,6 @@ package main
import "time"
-func (server *server) loadSpecialAttackLocks() error {
- db, err := server.database()
- if err != nil {
- return err
- }
- rows, err := db.Query("SELECT player_id, skill, locked_until FROM special_attack_locks")
- if err != nil {
- return err
- }
- defer rows.Close()
- for rows.Next() {
- var id, skill uint32
- var deadline time.Time
- if err := rows.Scan(&id, &skill, &deadline); err != nil {
- return err
- }
- if deadline.After(time.Now()) {
- player := server.characters[id]
- if player.specialAttackLocks == nil {
- player.specialAttackLocks = make(map[uint32]time.Time)
- }
- player.specialAttackLocks[skill] = deadline
- }
- }
- return rows.Err()
-}
-
func (server *server) saveSpecialAttack_locked(player, target *character, skill uint32, deadline, now time.Time) (*experienceAward, error) {
db, err := server.database()
if err != nil {
@@ -40,8 +13,7 @@ func (server *server) saveSpecialAttack_locked(player, target *character, skill
}
defer tx.Rollback()
// Commit the shared lock, damage, contributions and death state together.
- if _, err := tx.Exec("INSERT INTO special_attack_locks (player_id, skill, locked_until) VALUES (?, ?, ?) "+
- "ON CONFLICT (player_id, skill) DO UPDATE SET locked_until=excluded.locked_until", player.id, skill, deadline); err != nil {
+ if err := writeSkillLock(tx, player.id, skill, deadline); err != nil {
return nil, err
}
state, err := writeNPCOutcome_locked(tx, target, now)
@@ -56,10 +28,7 @@ func (server *server) saveSpecialAttack_locked(player, target *character, skill
return nil, err
}
- if player.specialAttackLocks == nil {
- player.specialAttackLocks = make(map[uint32]time.Time)
- }
- player.specialAttackLocks[skill] = deadline
+ player.setSkillLock_locked(skill, deadline)
server.rememberNPCOutcome_locked(target, state, now)
return award, nil
}
diff --git a/server/starter_weapons_test.go b/server/starter_weapons_test.go
@@ -189,7 +189,7 @@ func TestSolarShotgunFiresAndFlingsWithoutFiniteAmmo(t *testing.T) {
}
if normal != 1 || fling != 1 || target.health >= 1000 || player.inventory.Items[0].Ammo != 0 ||
restored.inventory.Items[0].Ammo != 0 || restored.inventory.Items[1].Count != 100 ||
- !restored.specialAttackLocks[150].Equal(player.specialAttackLocks[150]) {
+ !restored.skillLocks[150].Equal(player.skillLocks[150]) {
t.Fatal("solar combat consumed ammunition or repeated a locked special")
}
}
diff --git a/server/state.go b/server/state.go
@@ -52,9 +52,8 @@ type character struct {
browserTokenHash string
resurrectionTerminal uint32
implantChangesUntil time.Time
- treatmentLockedUntil time.Time
nanoRechargeUntil time.Time
- specialAttackLocks map[uint32]time.Time
+ skillLocks map[uint32]time.Time
activeNanos []activeNano
regenerationAt time.Time
regenerationSeconds uint32
diff --git a/server/treatment_kit_test.go b/server/treatment_kit_test.go
@@ -34,9 +34,9 @@ func TestTreatmentKitSelfUseHealsAndPersistsChargeWithLock(t *testing.T) {
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)) {
+ !reflect.DeepEqual(restored.inventory.Items, player.inventory.Items) ||
+ !restored.skillLocks[124].Equal(player.skillLocks[124]) || player.skillLocks[124].Before(started.Add(15*time.Second)) ||
+ player.skillLocks[124].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 ||
@@ -63,7 +63,7 @@ func TestTreatmentKitRejectsInvalidUseWithoutConsumption(t *testing.T) {
case "skill 7":
player.stats.NanoAiding.Treatment = 5
case "patient lock":
- target.treatmentLockedUntil = time.Now().Add(time.Minute)
+ target.setSkillLock_locked(124, time.Now().Add(time.Minute))
case "healer attacking":
player.fighting = 1000000
case "patient attacking":
@@ -98,12 +98,12 @@ func TestTreatmentKitRejectsInvalidUseWithoutConsumption(t *testing.T) {
case "failed save":
failDatabaseWrites(t, world)
}
- before, health, deadline := player.inventory, target.health, target.treatmentLockedUntil
+ before, health, deadline := player.inventory, target.health, target.skillLocks[124]
err := world.handleOwnedItemUse(client, request)
if (err != nil) != (scenario == "failed save") || !reflect.DeepEqual(before, player.inventory) ||
- target.health != health || !target.treatmentLockedUntil.Equal(deadline) {
+ target.health != health || !target.skillLocks[124].Equal(deadline) {
t.Fatalf("rejected treatment changed health, charge or patient lock: %v", err)
}
})
@@ -114,7 +114,7 @@ func TestTreatmentKitStandingHealerTreatsDistinctPatientsAndRestoresLocks(t *tes
world, _ := newTreatmentKitWorld(t)
player, client := world.characters[1], world.clients[1]
player.sitting = false
- player.treatmentLockedUntil = time.Now().Add(600 * time.Second)
+ player.setSkillLock_locked(124, 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: testCharacterStats(), health: 1, sitting: true}
@@ -133,12 +133,11 @@ func TestTreatmentKitStandingHealerTreatsDistinctPatientsAndRestoresLocks(t *tes
}
restored := newTestInventoryServer(t)
- if player.inventory.Items[0].Count != 48 || player.health != 1 || player.sitting || len(player.inventory.TreatmentLocks) != 2 {
+ if player.inventory.Items[0].Count != 48 || player.health != 1 || player.sitting {
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) {
+ if world.characters[id].health != 31 || !restored.characters[id].skillLocks[124].Equal(world.characters[id].skillLocks[124]) {
t.Fatalf("patient %d health or persistent lock", id)
}
locks := 0
@@ -164,16 +163,16 @@ func TestTreatmentKitReplayLockExpiryAndClinicShareTreatment(t *testing.T) {
}
world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:])
- deadline := player.treatmentLockedUntil
+ deadline := player.skillLocks[124]
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
+ locked := player.skillLocks[124]
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() ||
+ if player.health != 31 || player.inventory.Items[0].Count != 49 || !locked.Equal(deadline) || !player.skillLocks[124].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)
@@ -204,10 +203,10 @@ func TestTreatmentKitClinicLockRejectsTreatment(t *testing.T) {
if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 65, 1)[20:]); err != nil {
t.Fatal(err)
}
- deadline := player.treatmentLockedUntil
+ deadline := player.skillLocks[124]
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 {
+ if err != nil || player.health != 1 || player.inventory.Items[0].Count != 50 || !player.skillLocks[124].Equal(deadline) {
t.Fatal("laboratory bypassed or replaced the clinic's Treatment lock")
}
}
@@ -220,7 +219,7 @@ func TestTreatmentKitSavedChargeHealsDespiteClosedOwnerOutput(t *testing.T) {
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() {
+ if err == nil || player.health != 31 || player.inventory.Items[0].Count != 49 || player.skillLocks[124].IsZero() {
t.Fatalf("saved treatment charge lost its healing or lock: player=%+v err=%v", player, err)
}
}
diff --git a/server/users.go b/server/users.go
@@ -53,7 +53,6 @@ type playerProfile struct {
BrowserTokenHash string `yaml:"browser_token_hash"`
ResurrectionTerminal uint32 `yaml:"resurrection_terminal"`
ImplantChangesUntil time.Time `yaml:"implant_changes_until"`
- TreatmentLockedUntil time.Time `yaml:"treatment_locked_until"`
}
type playerPosition struct {
@@ -166,15 +165,7 @@ func (server *server) loadUsers() error {
}
}
- // Patient locks belong to the transaction that consumed the healer's 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
- }
- }
- }
- if err := server.loadSpecialAttackLocks(); err != nil {
+ if err := server.loadSkillLocks(); err != nil {
return err
}
return server.loadTeams()
diff --git a/server/weapon_special.go b/server/weapon_special.go
@@ -36,7 +36,7 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro
if target == nil || !target.npc || target.appearance>>4&7 != 6 || !client.npcs[target.id] || target.health == 0 ||
target.playfield != player.playfield || !server.combatInRange_locked(player, target, now) ||
player.sitting || player.driving() || client.equipment != nil || now.Before(client.reloadUntil) ||
- now.Before(player.specialAttackLocks[skill]) {
+ now.Before(player.skillLocks[skill]) {
server.mutex.Unlock()
return nil
}
@@ -61,7 +61,7 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro
seconds := player.weaponSpecialLockSeconds(gamedata.ItemTemplates[item.Template], skill)
damage := min(player.normalDamage(target, rand.Uint32N), target.health)
candidate := prepareDamage(player, target, damage, now)
- award, err := server.saveSpecialAttack_locked(player, &candidate, skill, now.Add(time.Duration(seconds)*time.Second), now)
+ award, err := server.saveSpecialAttack_locked(player, &candidate, skill, now.Add(time.Duration(player.skillLockSeconds(seconds))*time.Second), now)
if err != nil {
server.mutex.Unlock()
return err
diff --git a/server/world.sql b/server/world.sql
@@ -105,7 +105,6 @@ CREATE TABLE IF NOT EXISTS characters (
password_hash BLOB NOT NULL DEFAULT X'',
resurrection_terminal INTEGER NOT NULL DEFAULT 0,
implant_changes_until DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00',
- treatment_locked_until DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00',
playfield INTEGER NOT NULL DEFAULT 705,
position_x REAL NOT NULL DEFAULT 960,
position_y REAL NOT NULL DEFAULT 16.5,
@@ -129,14 +128,7 @@ CREATE TABLE IF NOT EXISTS characters (
CREATE UNIQUE INDEX IF NOT EXISTS player_login_names ON characters(name COLLATE NOCASE) WHERE length(password_hash)>0;
CREATE TABLE IF NOT EXISTS players (
id INTEGER PRIMARY KEY REFERENCES characters(id) ON DELETE CASCADE CHECK (id BETWEEN 1 AND 999999),
- credits INTEGER NOT NULL DEFAULT 0,
- first_aid_locked_until DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00'
-);
-CREATE TABLE IF NOT EXISTS treatment_locks (
- player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
- patient_id INTEGER NOT NULL,
- locked_until DATETIME NOT NULL,
- PRIMARY KEY (player_id, patient_id)
+ credits INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS buddies (
player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
@@ -145,7 +137,7 @@ CREATE TABLE IF NOT EXISTS buddies (
PRIMARY KEY (player_id, buddy_id),
CHECK (player_id != buddy_id)
);
-CREATE TABLE IF NOT EXISTS special_attack_locks (
+CREATE TABLE IF NOT EXISTS skill_locks (
player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
skill INTEGER NOT NULL,
locked_until DATETIME NOT NULL,
diff --git a/server/world_posture_test.go b/server/world_posture_test.go
@@ -39,7 +39,7 @@ func TestWorldEntryResetsSavedPostureBeforeTreatment(t *testing.T) {
world.mutex.Lock()
player := *world.characters[1]
world.mutex.Unlock()
- if player.sitting || player.health != 1 || player.inventory.Items[0].Count != 50 || !player.treatmentLockedUntil.IsZero() {
+ if player.sitting || player.health != 1 || player.inventory.Items[0].Count != 50 || !player.skillLocks[124].IsZero() {
t.Fatalf("entry retained rest or consumed a standing patient's kit: %+v", player)
}
if binary.BigEndian.Uint32(rejected[16:20]) != 0x52526858 || binary.BigEndian.Uint32(rejected[29:33]) != 2 {