aorecomp

Anarchy Online classic in the browser

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


commit d693c390a8229a2655a8b31ef6427c4561babf63
parent a3a072897ae6da3da6d98406344fb421ed5f3333
Author: anon <anon@example.com>
Date:   Fri, 23 Oct 2026 21:05:13 +0000

Implement native Fling Shot prototype with atomic outcomes

Diffstat:
MTODO.md | 18++++++++++++++++++
Mclient/Makefile.linux | 7+++++++
Aclient/tests/fling_result.c | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adocs/fling-shot.md | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/combat.go | 25+++++++++++++++++++------
Mserver/control.go | 1+
Aserver/fling_shot.go | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/fling_shot_test.go | 402+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/implants.go | 6++++++
Mserver/main.go | 9+++++++++
Aserver/special_locks.go | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/state.go | 1+
Mserver/users.go | 2+-
Mserver/world.sql | 6++++++
Mserver/world_store.go | 27++++++++++++++++-----------
15 files changed, 973 insertions(+), 18 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -187,6 +187,19 @@ Normal-hit additions and weapon-range modifiers are described in the action once, with native feedback and an enforced skill lock. - [ ] Implement one ranged special. Check: its damage, ammunition use and lock 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 + 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 + independent special use from normal attacks; invalid uses neither damage a + target nor create a lock. Do not import the 15.5.5 ammo/evade changes. +- [ ] Stress special outcomes with forced process termination. Check: interrupt + a shot before and after database commit, including a killing hit, and recover + exactly one outcome with matching cooldown and corpse/reward state. Fling's + lock, NPC HP, contributions and corpse/respawn state now commit together; + SQL failure and database reopen tests cover rollback and restoration. - [ ] Dual wield one verified weapon pair. Check: the actor's shared scheduling matches expected attack/recharge ordering without independent timer exploits. - [ ] Swap a weapon during combat. Check: swapping cannot bypass an existing @@ -206,6 +219,11 @@ for exact records, protocol, tests and remaining reconstruction assumptions. checked resources and combat values rather than an assumed scaling formula. - [ ] Add a second species with different behavior or equipment. Check: changing one species' profile does not change the other species. +- [ ] Reconcile recovery for currently unprofiled creatures. Check: a damaged + Reet's native HP and server HP remain equal across idle time and reconnect, + with no phantom hits. A Fling test found server HP 87 while native clients + recovered to 94/96 and then 100; only the Leet currently has synchronized + NPC regeneration. Record species inputs before generalizing recovery. - [x] Pursue a target across open ground. Check: an engaged creature follows a moving player and resumes attacks only when in range. - [x] Return a creature home after pursuit ends. Check: it disengages, returns diff --git a/client/Makefile.linux b/client/Makefile.linux @@ -172,6 +172,7 @@ test: build/linux/window build/linux/graphics build/linux/atoi build/linux/stric ./build/linux/native-input ./build/linux/weapon-range ./build/linux/ip-training + ./build/linux/fling-result ./build/linux/guest-crt ./build/linux/getenv ./build/linux/linux-platform @@ -660,3 +661,9 @@ build/linux/ip-training: tests/ip_training.c game/kkr.dll/lifted-0034.c runtime/ $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@ test: build/linux/ip-training + +build/linux/fling-result: tests/fling_result.c game/kkr.dll/lifted-0053.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h + @mkdir -p $(@D) + $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@ + +test: build/linux/fling-result diff --git a/client/tests/fling_result.c b/client/tests/fling_result.c @@ -0,0 +1,156 @@ +#include "recomp_types.h" +#include <assert.h> + +void sub_360B2CB0(void); +static unsigned lookups, names, feedbacks, reads, writes, deaths, ammo_updates; +static uint32_t missing_actor, feedback_category, death_reason; +static int32_t ammunition; + +static void actor_lookup(void) +{ + uint32_t identity = MEM32(g_esp + 4); + assert(MEM32(identity) == 50000); + uint32_t instance = MEM32(identity + 4); + assert(instance == 1 || instance == 2); + lookups++; + g_eax = instance == missing_actor ? 0 : 0x50000000 + instance * 0x1000; + g_esp += 4; +} + +static void special_name(void) +{ + assert(MEM32(g_esp + 4) == 150); + names++; + g_eax = 0x50000800; + g_esp += 4; +} + +static void feedback_interface(void) +{ + g_eax = 0x50000900; + g_esp += 4; +} + +static void feedback(void) +{ + assert(g_ecx == 0x50000900); + assert(MEM32(g_esp + 4) == feedback_category); + assert(MEM32(g_esp + 8) == 0x50002000); + assert(MEM32(g_esp + 12) == 13); + assert(MEM32(g_esp + 16) == 0x50001000); + assert(MEM32(g_esp + 20) == 0x50000800); + assert(MEM32(g_esp + 24) == 0 && MEM32(g_esp + 28) == 0); + feedbacks++; + g_esp += 32; +} + +static void health_getter(void) +{ + assert(g_ecx == 0x500020e4); + assert(MEM32(g_esp + 4) == 27 && MEM32(g_esp + 8) == 2); + reads++; + g_eax = MEM32(0x50002300); + g_esp += 12; +} + +static void health_setter(void) +{ + assert(g_ecx == 0x500020e4); + assert(MEM32(g_esp + 4) == 27 && MEM32(g_esp + 8) == 87); + writes++; + MEM32(0x50002300) = MEM32(g_esp + 8); + g_esp += 12; +} + +static void target_death(void) +{ + assert(g_ecx == 0x50002000 && MEM32(g_esp + 4) == death_reason); + assert(MEM32(0x50002300) == 87 && writes == 1); + deaths++; + g_esp += 8; +} + +static void weapon_ammunition(void) +{ + assert(g_ecx == 0x50003000 && MEM32(g_esp + 4) == 6); + assert((int32_t)MEM32(g_esp + 8) == ammunition); + assert(MEM32(0x50002300) == 87 && writes == 1); + assert(deaths == (death_reason != 0)); + ammo_updates++; + g_esp += 12; +} + +recomp_func_t recomp_lookup(uint32_t address) +{ + switch (address) { + case 0x3606da90: return actor_lookup; + case 0x3603d360: return special_name; + case 0x3601c590: return feedback_interface; + case 0x3601d0b0: return feedback; + case 0x50000400: return health_getter; + case 0x50000404: return health_setter; + case 0x36072340: return target_death; + case 0x3607c0f0: return weapon_ammunition; + default: fprintf(stderr, "unexpected special-result call: %08x\n", address); abort(); + } +} +recomp_func_t recomp_lookup_manual(uint32_t address) { return NULL; } +recomp_func_t recomp_lookup_import(uint32_t address) { abort(); } + +int main(void) +{ + assert(guest_map("special attack result fixture", 0x50000000, 0x10000)); + const struct { + unsigned attacker_local, target_local, missing; + uint32_t feedback, death; + int32_t ammo; + } cases[] = { + {1, 0, 0, 50, 0, 3}, + {0, 1, 0, 48, 0, 3}, + {0, 0, 0, 49, 0, 3}, + {1, 0, 0, 50, 7, 3}, + {1, 0, 0, 50, 0, 0}, + {1, 0, 0, 50, 0, -1}, + {1, 0, 1, 50, 0, 3}, + {1, 0, 2, 50, 0, 3} + }; + for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + lookups = names = feedbacks = reads = writes = deaths = ammo_updates = 0; + missing_actor = cases[i].missing; + feedback_category = cases[i].feedback; + death_reason = cases[i].death; + ammunition = cases[i].ammo; + MEM32(0x50000004) = MEM32(0x50000020) = 50000; + MEM32(0x50000008) = 1; + MEM32(0x50000024) = 2; + MEM32(0x50000028) = 6; + MEM32(0x5000002c) = 13; + MEM32(0x50000030) = ammunition; + MEM32(0x50000034) = 150; + MEM32(0x50000038) = death_reason; + MEM8(0x50001128) = cases[i].attacker_local; + MEM8(0x50002128) = cases[i].target_local; + MEM32(0x50001300) = MEM32(0x50002300) = 100; + MEM32(0x5000116c) = 0x50003000; + MEM32(0x500010e4) = MEM32(0x500020e4) = 0x50000100; + MEM32(0x50000104) = 0x50000400; + MEM32(0x50000108) = 0x50000404; + g_esp = 0x5000ff00; + g_ecx = 0x50000000; + + sub_360B2CB0(); + + assert(g_eax == 0 && g_esp == 0x5000ff04); + assert(lookups == 2 && MEM32(0x50001300) == 100); + if (missing_actor) { + assert(MEM32(0x50002300) == 100); + assert(names == 0 && feedbacks == 0 && reads == 0 && writes == 0); + assert(deaths == 0 && ammo_updates == 0); + } else { + assert(MEM32(0x50002300) == 87); + assert(names == 1 && feedbacks == 1 && reads == 1 && writes == 1); + assert(deaths == (death_reason != 0) && ammo_updates == 1); + } + } + puts("native Fling result: target damage, named feedback, ammunition and death routing passed"); +} diff --git a/docs/fling-shot.md b/docs/fling-shot.md @@ -0,0 +1,156 @@ +# Fling Shot: native path and remaining rules + +The QL 1 Rusty OT M-10 Flechette Pistol now supports the native Fling Shot +request, named damage feedback and a persistent shared skill lock. This is a +prototype of the normal-damage branch. The ranged-special milestone stays open: +critical outcomes and several historical rules below are not yet established. + +## Target-era evidence + +The shipped tips `LookatSolarPoweredAssaultRifle.txt` and +`LookatSawedoffSolarShotgun.txt` describe placing Fling in the native shortcut +bar from Controls (Ctrl+2). The tested keyboard binding is L. + +The February 2, 2003 +[JeuxOnline discussion](https://archives.jeuxonline.info/fils/163094.html) +reports `weapon attack delay * 15 - Fling skill / 100` seconds. The author +attributes this to forum investigations but supplies no measurements. This is +the current reconstruction's formula, not recovered original server code. +The pistol's original record 123742 has attack-delay stat 294 equal to 125 +centiseconds. With effective Fling 7 the reported formula gives 18.68 seconds. +The implementation rounds up to the native whole-second lock, 19 seconds. +Its one-second guard for extreme skills is also provisional; the original +floor, exact arithmetic, raw/effective input and rounding remain unknown. + +Period reports in +[the July 2002 MP weapon guide](https://forums-archive.anarchy-online.com/showthread.php?37266-How-to-Choose-A-Weapon-Guide-for-the-MP=) +describe specials alongside normal shooting and critical special damage without +the normal critical chat label. March 2002 +[NT weapon reports](https://forums-archive.anarchy-online.com/showthread.php?15020-nt-weapons-amp-ip=) +describe using Fling while chaincasting. A December 2002 +[dual-wield discussion](https://forums-archive.anarchy-online.com/showthread.php?76740-Calculating-damage-w-dual-wielded-weapons-how=) +reports one shared Fling reuse timer for two weapons. These observations do not +establish all execution, recharge, swap or interruption gates. + +The attributed Funcom 15.5.5 notes, dated July 20, 2004 and preserved in +[the patch-note copy](https://wiki.aodb.us/wiki/Patch_15.5#Version_15.5.5), +introduce ammunition deductions and defensive checks for Fling and other named +specials. Accordingly, this 14.9.1 implementation leaves ammunition unchanged +and does not add the later evade check. An empty clip is still rejected; +the historical empty-clip/autoreload behavior remains unresolved. The old +official article URL is unavailable. The official launcher's `patch_id=23` +URL now returns current 18.8 content, so HTTP 200 from it is not verification +of the historical text. The retained source ledger distinguishes these cases. + +## Original client protocol + +Target `kkr.dll` SHA-256: +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. + +| Path | Original address | Established contract | +| --- | --- | --- | +| `N3Msg_SecondarySpecialAttack` | `1002c090` | Checks selected/fighting target, local lock, special availability, range and line of sight before sending | +| `CharSecSpecAttackIIR_t` constructor | `1007d8e0` | Class-derived key `0x51492120` | +| Request reader | `1007d9f0` | Target identity, then special stat ID; Fling is 150 | +| Request activation | `1007da30` / `10078a40` | Queues a special through the weapon holder; this is separate from its damage result | +| `SpecialAttackInfo` reader | `100b2c00` | Slot, damage, ammo, target identity, special stat, death reason | +| Result activation | `100b2cb0` | Named feedback, one target HP subtraction, optional target death, supplied ammo assignment | +| Ammo assignment helper | `1007c0f0` | Passes the supplied count to that weapon's stat 26; it does not decrement it | + +The result key is `0x754f1115`, with the attacker in its N3 envelope. +For the tested shot its payload is `[6, damage, currentAmmo, 50000, targetID, +150, deathReason]`. Death reason 4 identifies weapon damage on a killing hit. +There is no critical-result flag in this message's recovered body. + +Fresh REA evidence is in `local/fling-shot-research/native-evidence.json`: + +- Request sender: `ev_d1476549067f47d076bbde6794f81f3340b20e34e60aeb471160525c970119b9`. +- Request reader: `ev_a5e2a269e5866ae62238141427dd0fc4daeffae938dec347021e488841b9e49b`. +- Result reader: `ev_c54ca7fd1cc0542a460106ff47cde73891fbd7210274b97d820943c90ecd1fc0`. +- Result activation: `ev_3ed136aa0222fc5ee5a9ba5bd84175a05c5ca97fbf26d944dcdcdd9f7e4cb841`. +- Ammo assignment: `ev_53e58c5ee80df0a7fe6596e8a1bde5758dc23a9bc19f0d47daf5e211cc49516d`. + +## Server behavior and limits + +The handler accepts only the authenticated, ready 14.9.1 owner, a visible living +creature in range, the supported right-hand pistol and special 150. It rejects +dead/loading/replaced sessions, other owners, player targets, empty clips, +active reload/equip, sitting, vehicles and an existing lock. Some of those action +gates are reconstruction policy pending period verification. Server line of +sight remains the existing combat TODO. + +Accepted shots currently reuse `normalDamage`, including attack rating, AC, +overequipping and damage modifiers. Fling-specific damage distribution and +critical selection are not established; the prototype emits normal damage +only. It does not reset an existing normal attack/recharge or nano cast. +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 +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. + +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 +publishing live state or success feedback. Failure leaves both actors and +feedback unchanged. Database reopen tests restore living and killing outcomes; +forced process termination immediately around commit remains a stress-test TODO. + +## Verification + +`client/tests/fling_result.c` executes unchanged `sub_360B2CB0` from +`client/game/kkr.dll/lifted-0053.c`. Eight Linux and WASM cases verify target-only +HP subtraction once, attacker/defender/observer feedback categories, ammo values +3/0/-1 forwarded unchanged, death routing and missing actors. External identity, +stat, feedback and ammo boundaries are stubbed; this does not test rendering, +the network reader or original server formulas. + +`server/fling_shot_test.go` covers owner/observer results, ammunition conservation, +concurrent duplicates, normal recharge and nano-cast independence, invalid and +malformed requests, failed lock/HP/NPC/contribution SQL writes, +profile edit/restart preservation, +remaining-lock publication, one-shot expiry, expired stored rows and kills. + +Two unchanged published WASM clients exercised the L binding against the one +HTTPS preview. The first two shots displayed matching six- and seven-point +Fling results to attacker and observer, with 20 loaded rounds and 100 loose +rounds unchanged. An immediate repeated keypress sent no second shot. Cold-start +lock replay used an explicitly extended test deadline so it remained active +through client loading; this is a persistence/UI check, not a cooldown formula +measurement. Native probes observed a restored 125-second lock, then 43 seconds, +blocked use, and the native availability notification on expiry. + +That first target was an unprofiled Reet of Paradise. Its server HP reached 87, +but after reconnect the native clients recovered independently to 94/96 and +then 100. Both native maxima were 100. The server currently synchronizes NPC +recovery only for the supported Leet; the newly recorded Reet gap prevents +claiming raw-HP agreement for that species. + +The supported Leet then received a 12-point Fling with native HP 88 in both +clients and ammunition still 20. A normal shot followed by Fling during weapon +recharge produced another matching 12-point special, with native HP 76 in both +clients. That normal shot dealt three points; regeneration occurred between +the two probes. Ammunition was 19: the normal shot consumed one round, while Fling +left it unchanged. All 192 item instances retained their identity, template, +quality and count; the pistol's one-round change was the only item change. + +On the final build a seven-point Fling took the Leet from 100 to 93 native HP. +A read-only SQLite snapshot immediately afterward contained HP 93 and the +active skill lock. Ammunition stayed 19 and all item rows were unchanged. +The three browser runs reported no page errors or unimplemented adapter calls; +their owned browser contexts were closed afterward. + +Final validation passed: `go test ./server/... -count=1` (server 299.073 seconds, +gamedata 7.776 seconds), focused Fling/combat/corpse race checks (106.796 seconds), +and eight original-client contract cases on both Linux and WASM. + +Source ledgers, exact request/result captures, native probes, screenshots, +controlled-deadline metadata and item audits are retained under +`local/fling-shot-research/`. The C contract's build logs and source identity are +under `local/fling-research/`. No production client adapters needed changes. diff --git a/server/combat.go b/server/combat.go @@ -362,6 +362,11 @@ func (server *server) advanceCombat(now time.Time) { } func (server *server) finishDamage_locked(attacker, target *character, damage uint32, now time.Time, updates map[*worldClient][][]byte) { + prepareDamage(attacker, target, damage, now) + server.finishDamageEffects_locked(attacker, target, now, updates) +} + +func prepareDamage(attacker, target *character, damage uint32, now time.Time) { // Keep individual contributions for this NPC life, including stopped attacks. if target.npc && !attacker.npc { if target.damageContributors == nil { @@ -373,6 +378,20 @@ func (server *server) finishDamage_locked(attacker, target *character, damage ui target.leadingContributor = attacker.id } } + monster := gamedata.MonsterTemplates[target.monsterData] + if target.health == 0 && target.npc && monster != nil && len(monster.DeathAnimations) != 0 { + if target.corpse == nil { + target.corpse = &npcCorpse{} + } + target.corpse.looter = target.leadingContributor + target.damageContributors = nil + if target.combatProfile != nil && target.combatProfile.CorpseSeconds != 0 { + target.corpse.expiresAt = now.Add(time.Duration(target.combatProfile.CorpseSeconds) * time.Second) + } + } +} + +func (server *server) finishDamageEffects_locked(attacker, target *character, now time.Time, updates map[*worldClient][][]byte) { if target.health == 0 { if !target.npc { client := server.clients[target.id] @@ -390,13 +409,7 @@ func (server *server) finishDamage_locked(attacker, target *character, damage ui server.queueCombat_locked(updates, target, target, deathPacket(target)) monster := gamedata.MonsterTemplates[target.monsterData] if target.npc && monster != nil && len(monster.DeathAnimations) != 0 { - if target.corpse == nil { - target.corpse = &npcCorpse{} - } - target.corpse.looter = target.leadingContributor - target.damageContributors = nil if target.combatProfile != nil && target.combatProfile.CorpseSeconds != 0 { - target.corpse.expiresAt = now.Add(time.Duration(target.combatProfile.CorpseSeconds) * time.Second) server.corpseExpiry = append(server.corpseExpiry, target) } server.queueCombat_locked(updates, target, target, corpsePacket(target)) diff --git a/server/control.go b/server/control.go @@ -308,6 +308,7 @@ func (server *server) updateUser_locked(destination userData) error { } func (server *server) prepareUser_locked(character, updated *character) { + updated.specialAttackLocks = character.specialAttackLocks // Reconnection cancels a pending cast; preserve its refund unless nano was edited. if client := server.clients[character.id]; client != nil && client.nanoCast != nil && updated.nano == character.nano { updated.nano = min(character.maximumNano(), character.nano+winterBiteCost()) diff --git a/server/fling_shot.go b/server/fling_shot.go @@ -0,0 +1,87 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "fmt" + "maps" + "math/rand/v2" + "time" +) + +func (player *character) flingShotLockSeconds() uint32 { + // February 2003 formula: attack delay * 15 - Fling Shot / 100. + // Whole-second rounding and the minimum are provisional; see docs/fling-shot.md. + skill := player.effectiveSkill(150, player.baseStats().Ranged.FlingShot, [6]uint32{0, 100, 0, 0, 0, 0}) + centiseconds := int64(itemStat(gamedata.ItemTemplates[123742], 294))*15 - int64(skill) + return uint32(max(1, (centiseconds+99)/100)) +} + +func (server *server) handleFlingShot(client *worldClient, body []byte) error { + if len(body) != 28 { + return fmt.Errorf("invalid secondary special attack length") + } + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + player := server.characters[client.id] + if server.clients[client.id] != client || !client.target || !client.ready || client.loading || player.health == 0 || + binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || + binary.BigEndian.Uint32(body[16:20]) != 50000 || binary.BigEndian.Uint32(body[24:28]) != 150 { + server.mutex.Unlock() + return nil + } + target := server.characters[binary.BigEndian.Uint32(body[20:24])] + now := time.Now() + 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[150]) { + server.mutex.Unlock() + return nil + } + var gun *ownedItem + for index := range player.inventory.Items { + if player.inventory.Items[index].Slot == 6 && player.inventory.Items[index].isFlechettePistol() { + gun = &player.inventory.Items[index] + break + } + } + if gun == nil || gun.Ammo == 0 { + server.mutex.Unlock() + return nil + } + + // Prepare a detached result so a failed transaction changes no live actor. + seconds := player.flingShotLockSeconds() + damage := min(player.normalDamage(target, rand.Uint32N), target.health) + candidate := *target + candidate.health -= damage + candidate.damageContributors = maps.Clone(target.damageContributors) + if target.corpse != nil { + corpse := *target.corpse + candidate.corpse = &corpse + } + prepareDamage(player, &candidate, damage, now) + if err := server.saveSpecialAttack_locked(player, &candidate, 150, now.Add(time.Duration(seconds)*time.Second), now); err != nil { + server.mutex.Unlock() + return err + } + *target = candidate + updates := make(map[*worldClient][][]byte) + // Pre-15.5.5 specials do not deduct ammunition or use defensive hit checks. + var result []byte + death := uint32(0) + if target.health == 0 { + death = 4 + } + for _, value := range []uint32{6, damage, gun.Ammo, 50000, target.id, 150, death} { + result = binary.BigEndian.AppendUint32(result, value) + } + server.queueCombat_locked(updates, player, target, n3Packet(0x754f1115, 50000, player.id, result)) + updates[client] = append(updates[client], skillLockPacket(player.id, 150, seconds)) + server.finishDamageEffects_locked(player, target, now, updates) + server.mutex.Unlock() + server.sendCombatUpdates(updates) + return nil +} diff --git a/server/fling_shot_test.go b/server/fling_shot_test.go @@ -0,0 +1,402 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "slices" + "sync" + "testing" + "time" +) + +func flingShotRequest(owner, target uint32) []byte { + var body []byte + for _, value := range []uint32{50000, target, 150} { + body = binary.BigEndian.AppendUint32(body, value) + } + return n3Packet(0x51492120, 50000, owner, body) +} + +func TestFlingShotDamagesOnceWithoutConsumingPre155Ammunition(t *testing.T) { + world, owner := newRangedWorld(t) + player, target := world.characters[1], world.characters[1000000] + observer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950, health: 100} + world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + started := time.Now() + + err := world.handleFlingShot(world.clients[1], flingShotRequest(1, target.id)[20:]) + restored := newTestInventoryServer(t).characters[1] + + 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 || + target.damageContributors[1] != 1000-target.health { + t.Fatalf("special result or persistent lock mismatch: HP=%d lock=%v, %v", target.health, player.specialAttackLocks, err) + } + if len(owner.packets) != 3 || len(observer.packets) != 2 || + binary.BigEndian.Uint32(owner.packets[0][16:20]) != 0x754f1115 || + !bytes.Equal(owner.packets[0][16:], observer.packets[0][16:]) || + binary.BigEndian.Uint32(owner.packets[0][29:33]) != 6 || + binary.BigEndian.Uint32(owner.packets[0][33:37]) != 1000-target.health || + binary.BigEndian.Uint32(owner.packets[0][37:41]) != 3 || + binary.BigEndian.Uint32(owner.packets[0][45:49]) != target.id || + binary.BigEndian.Uint32(owner.packets[0][49:53]) != 150 || + binary.BigEndian.Uint32(owner.packets[1][29:33]) != 170 || + binary.BigEndian.Uint32(owner.packets[1][41:45]) != 150 || + binary.BigEndian.Uint32(owner.packets[1][45:49]) != 19 { + t.Fatalf("native special result/lock publication mismatch: %x", owner.packets) + } +} + +func TestFlingShotDoesNotResetNormalAttackOrNanoClocks(t *testing.T) { + world, _ := newRangedWorld(t) + player, client := world.characters[1], world.clients[1] + world.handleCombat(client, attackPacket(1, 1000000)[20:]) + attack, recharge := player.nextAttack, player.rechargeUntil + client.nanoCast = &nanoCast{target: 1000000, readyAt: time.Now().Add(time.Second)} + cast := client.nanoCast + + err := world.handleFlingShot(client, flingShotRequest(1, 1000000)[20:]) + + if err != nil || world.characters[1000000].health == 1000 || player.nextAttack != attack || + player.rechargeUntil != recharge || client.nanoCast != cast || player.fighting != 1000000 { + t.Fatalf("Fling reset an existing attack or cast: %v", err) + } +} + +func TestFlingShotDoesNotConsumeNormalShotAndWorksDuringWeaponRecharge(t *testing.T) { + world, _ := newRangedWorld(t) + player, client := world.characters[1], world.clients[1] + world.handleCombat(client, attackPacket(1, 1000000)[20:]) + world.advanceCombat(player.nextAttack) + attack, recharge := player.nextAttack, player.rechargeUntil + health := world.characters[1000000].health + + err := world.handleFlingShot(client, flingShotRequest(1, 1000000)[20:]) + + if err != nil || world.characters[1000000].health >= health || player.inventory.Items[0].Ammo != 2 || + player.nextAttack != attack || player.rechargeUntil != recharge { + t.Fatal("weapon recharge blocked Fling or Fling consumed another normal shot", err) + } +} + +func TestFlingShotConcurrentRepeatedRequestsShareOneLock(t *testing.T) { + world, conn := newRangedWorld(t) + client := world.clients[1] + request := flingShotRequest(1, 1000000)[20:] + var calls sync.WaitGroup + + for range 8 { + calls.Go(func() { + if err := world.handleFlingShot(client, request); err != nil { + t.Error(err) + } + }) + } + calls.Wait() + count := 0 + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x754f1115 { + count++ + } + } + + if count != 1 || world.characters[1000000].health < 988 || world.characters[1].inventory.Items[0].Ammo != 3 { + t.Fatal("repeated Fling bypassed its shared lock") + } +} + +func TestFlingShotRejectsInvalidRequestsWithoutDamageOrLocks(t *testing.T) { + for _, scenario := range []string{"unready", "loading", "replaced", "old client", "dead owner", "wrong owner", "wrong type", "wrong target type", "wrong skill", "unknown target", "player target", "dead target", "hidden target", "other zone", "out of range", "sitting", "driving", "equip pending", "reloading", "locked", "empty clip", "unarmed", "wrong weapon", "stored pistol"} { + t.Run(scenario, func(t *testing.T) { + world, conn := newRangedWorld(t) + player, target, client := world.characters[1], world.characters[1000000], world.clients[1] + request := flingShotRequest(1, 1000000)[20:] + switch scenario { + case "unready": + client.ready = false + case "loading": + client.loading = true + case "replaced": + world.clients[1] = &worldClient{id: 1} + case "old client": + client.target = false + case "dead owner": + player.health = 0 + case "wrong owner": + binary.BigEndian.PutUint32(request[8:12], 2) + case "wrong type": + binary.BigEndian.PutUint32(request[4:8], 51018) + case "wrong target type": + binary.BigEndian.PutUint32(request[16:20], 51018) + case "wrong skill": + binary.BigEndian.PutUint32(request[24:28], 148) + case "unknown target": + binary.BigEndian.PutUint32(request[20:24], 2000000) + case "player target": + target.npc = false + case "dead target": + target.health = 0 + case "hidden target": + delete(client.npcs, 1000000) + case "other zone": + target.playfield = 705 + case "out of range": + target.position[0] = 100 + case "sitting": + player.sitting = true + case "driving": + player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 3, Type: 51022, Template: 117294, Quality: 15, Slot: 1, Count: 1}) + case "equip pending": + client.equipment = &equipmentMove{} + case "reloading": + client.reloadUntil = time.Now().Add(time.Hour) + case "locked": + player.specialAttackLocks = map[uint32]time.Time{150: time.Now().Add(time.Hour)} + case "empty clip": + player.inventory.Items[0].Ammo = 0 + case "unarmed": + player.inventory.Items = nil + case "wrong weapon": + player.inventory.Items[0] = ownedItem{ID: 1, Type: 51017, Template: 120967, Quality: 1, Slot: 6, Count: 1} + case "stored pistol": + player.inventory.Items[0].Slot = 65 + } + health := target.health + deadline := player.specialAttackLocks[150] + + err := world.handleFlingShot(client, request) + + if err != nil || target.health != health || player.specialAttackLocks[150] != deadline || len(conn.packets) != 0 { + t.Fatalf("rejected special changed health/lock/output: %d -> %d, %v", health, target.health, err) + } + }) + } +} + +func TestFlingShotMalformedLengthReturnsError(t *testing.T) { + for _, length := range []int{0, 27, 29} { + world, conn := newRangedWorld(t) + request := append(flingShotRequest(1, 1000000)[20:], 0)[:length] + + err := world.handleFlingShot(world.clients[1], request) + + if err == nil || world.characters[1000000].health != 1000 || len(conn.packets) != 0 { + t.Fatal("malformed special changed game state") + } + } +} + +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 { + t.Fatal(err) + } + + err := world.handleFlingShot(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 { + t.Fatal("failed special lock save published a hit or changed live state") + } +} + +func TestFlingShotOutcomeFailureRollsBackLockAndNPCState(t *testing.T) { + for _, statement := range []string{ + "CREATE TRIGGER fail_outcome BEFORE UPDATE OF health ON characters WHEN NEW.id=1000000 BEGIN SELECT RAISE(FAIL, 'test health failure'); END", + "CREATE TRIGGER fail_outcome BEFORE UPDATE ON npcs BEGIN SELECT RAISE(FAIL, 'test NPC failure'); END", + "CREATE TRIGGER fail_outcome BEFORE INSERT ON npc_damage_contributors BEGIN SELECT RAISE(FAIL, 'test contribution failure'); END", + } { + world, conn := newRangedWorld(t) + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + + err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]) + var health, locks int + 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 { + 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 { + t.Fatalf("partial special commit escaped rollback: health=%d locks=%d error=%v", health, locks, err) + } + } +} + +func TestFlingShotPersistsDamageAndContributionBeforeAnyCheckpoint(t *testing.T) { + world, _ := newRangedWorld(t) + + err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]) + var health, contribution uint32 + 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 damage FROM npc_damage_contributors WHERE npc_id=1000000 AND player_id=1").Scan(&contribution); err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(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[1] != contribution || + !restored.characters[1].specialAttackLocks[150].Equal(world.characters[1].specialAttackLocks[150]) { + t.Fatalf("published special was not durable: HP=%d contribution=%d, %v", health, contribution, err) + } +} + +func TestFlingShotKillingSaveFailurePreservesCorpseAndContributors(t *testing.T) { + world, conn := newRangedWorld(t) + target := world.characters[1000000] + target.health, target.monsterData, target.level = 1, 17655, 1 + target.combatProfile = gamedata.NPCCombatProfiles[17655][1] + target.damageContributors, target.leadingContributor = map[uint32]uint32{2: 10}, 2 + target.corpse = &npcCorpse{looter: 2, credits: 10} + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec("CREATE TRIGGER fail_kill BEFORE UPDATE ON npcs BEGIN SELECT RAISE(FAIL, 'test corpse failure'); END"); err != nil { + t.Fatal(err) + } + + err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]) + restored := newTestInventoryServer(t) + + if err == nil || target.health != 1 || target.corpse.looter != 2 || !target.corpse.expiresAt.IsZero() || + target.damageContributors[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 { + t.Fatal("failed special kill leaked staged corpse, contribution or lock state") + } +} + +func TestFlingShotLockSurvivesProfileEditAndBlocksAfterRestart(t *testing.T) { + world, _ := newRangedWorld(t) + player := world.characters[1] + if err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + deadline := player.specialAttackLocks[150] + delete(world.clients, 1) + destination := player.userData() + destination.Name = "Fling Owner" + + err := world.updateUser(destination) + 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}}} + restored.characters[1000000] = &character{id: 1000000, npc: true, appearance: 229, playfield: 950, health: 1000} + if err == nil { + err = restored.handleFlingShot(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 { + t.Fatal("profile edit or restart cleared the special lock", err) + } +} + +func TestFlingShotLockExpiryUnlocksOnceAndDoesNotChurnDatabase(t *testing.T) { + world, conn := newRangedWorld(t) + if err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + deadline := world.characters[1].specialAttackLocks[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 { + t.Fatal(err) + } + + world.advanceItemEffects(deadline.Add(-time.Nanosecond)) + if len(conn.packets) != 0 { + t.Fatal("lock expired early") + } + world.advanceItemEffects(deadline) + world.advanceItemEffects(deadline.Add(time.Second)) + + if len(conn.packets) != 1 || !world.characters[1].specialAttackLocks[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) + } +} + +func TestFlingShotExpiredStoredLockDoesNotReturnAfterRestart(t *testing.T) { + world, _ := newRangedWorld(t) + if err := world.handleFlingShot(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 { + t.Fatal(err) + } + + restored := newTestInventoryServer(t) + + if len(restored.characters[1].specialAttackLocks) != 0 { + t.Fatal("expired special lock was restored") + } +} + +func TestFlingShotReconnectPublishesRemainingLockBeforeReady(t *testing.T) { + world, _ := newRangedWorld(t) + if err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + world.clients[1].conn = &combatInterestConn{} + cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) + input := append(cookie, n3Packet(0x570c2039, 50000, 1, nil)...) + conn := &combatInterestConn{input: bytes.NewReader(input)} + + err := world.serveWorldClient(&worldClient{conn: conn, loading: true}) + locks := 0 + for _, packet := range conn.packets { + if len(packet) >= 56 && binary.BigEndian.Uint32(packet[20:24]) == 0x5e477770 && + binary.BigEndian.Uint32(packet[36:40]) == 170 && binary.BigEndian.Uint32(packet[48:52]) == 150 { + locks++ + if binary.BigEndian.Uint32(packet[52:56]) < 18 || binary.BigEndian.Uint32(packet[52:56]) > 19 { + t.Fatal("wrong remaining special lock") + } + } + } + + if err != nil || locks != 1 { + t.Fatalf("reconnect did not restore exactly one native lock: %d, %v", locks, err) + } +} + +func TestFlingShotKillingHitUsesCorpseAndContributionLifecycle(t *testing.T) { + world, conn := newRangedWorld(t) + target := world.characters[1000000] + target.health, target.monsterData = 1, 17655 + target.level = 1 + target.combatProfile = gamedata.NPCCombatProfiles[17655][1] + + err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]) + var health, looter uint32 + var corpse bool + var respawn, expiry time.Time + 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 has_corpse, looter, respawn_at, expires_at FROM npcs WHERE id=1000000").Scan(&corpse, &looter, &respawn, &expiry); err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t) + var keys []uint32 + for _, packet := range conn.packets { + keys = append(keys, binary.BigEndian.Uint32(packet[16:20])) + } + + if err != nil || target.health != 0 || target.corpse == nil || target.corpse.looter != 1 || + binary.BigEndian.Uint32(conn.packets[0][33:37]) != 1 || binary.BigEndian.Uint32(conn.packets[0][53:57]) != 4 || + !slices.Contains(keys, uint32(0x5e477770)) || world.characters[1].inventory.Items[0].Ammo != 3 || + health != 0 || !corpse || looter != 1 || respawn.IsZero() || expiry.IsZero() || len(world.npcRespawns) != 1 || + restored.characters[1000000].health != 0 || restored.characters[1000000].corpse.looter != 1 || len(restored.npcRespawns) != 1 { + t.Fatal("special kill skipped corpse ownership/death or consumed ammunition", err) + } +} diff --git a/server/implants.go b/server/implants.go @@ -82,6 +82,12 @@ func (server *server) advanceItemEffects(now time.Time) { continue } player := server.characters[id] + for skill, deadline := range player.specialAttackLocks { + if !now.Before(deadline) { + delete(player.specialAttackLocks, skill) + updates[client] = append(updates[client], characterActionPacket(id, [5]uint32{164, 0, 0, 0, skill})) + } + } if !player.implantChangesUntil.IsZero() && !now.Before(player.implantChangesUntil) { player.implantChangesUntil = time.Time{} body := binary.BigEndian.AppendUint32(nil, 224) diff --git a/server/main.go b/server/main.go @@ -365,6 +365,11 @@ func (server *server) serveWorldClient(client *worldClient) error { 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, server.combatInterest_locked(client, nil)...) updates = append(updates, gameTimePacket(character.id, server.gameSeconds_locked())) spawn := characterPacket(character) @@ -439,6 +444,10 @@ func (server *server) serveWorldClient(client *worldClient) error { decodeInventory1491(body) } switch binary.BigEndian.Uint32(body[0:4]) { + case 0x51492120: + if err := server.handleFlingShot(client, body); err != nil { + return err + } case 0x3e205660: if err := server.handleSkillTraining(client, body); err != nil { return err diff --git a/server/special_locks.go b/server/special_locks.go @@ -0,0 +1,88 @@ +package main + +import ( + "maps" + "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) error { + db, err := server.database() + if err != nil { + return err + } + tx, err := db.Begin() + if err != nil { + return err + } + 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 { + return err + } + state := target.worldState(true, time.Time{}) + if target.health == 0 { + state.Roaming.Moving, state.Roaming.Returning = false, false + if target.combatProfile != nil && target.combatProfile.RespawnSeconds != 0 { + state.RespawnAt = now.Add(time.Duration(target.combatProfile.RespawnSeconds) * time.Second) + } + } + if _, err := tx.Exec(upsertRecordSQL("characters", characterColumns), append([]any{target.id}, state.Character.fields()...)...); err != nil { + return err + } + if _, err := tx.Exec(upsertRecordSQL("npcs", npcColumns), append([]any{target.id}, state.fields()...)...); err != nil { + return err + } + if _, err := tx.Exec("DELETE FROM npc_damage_contributors WHERE npc_id=?", target.id); err != nil { + return err + } + for id, damage := range target.damageContributors { + if _, err := tx.Exec("INSERT INTO npc_damage_contributors (npc_id, player_id, damage) VALUES (?, ?, ?)", target.id, id, damage); err != nil { + return err + } + } + if err := tx.Commit(); err != nil { + return err + } + + if player.specialAttackLocks == nil { + player.specialAttackLocks = make(map[uint32]time.Time) + } + player.specialAttackLocks[skill] = deadline + if server.savedNPCs == nil { + server.savedNPCs = make(map[uint32]savedNPC) + } + nextSave := server.savedNPCs[target.id].NextSave + if nextSave.IsZero() { + nextSave = now.Add(20 * time.Second) + } + server.savedNPCs[target.id] = savedNPC{state, maps.Clone(target.damageContributors), nextSave} + return nil +} diff --git a/server/state.go b/server/state.go @@ -47,6 +47,7 @@ type character struct { implantChangesUntil time.Time treatmentLockedUntil time.Time nanoRechargeUntil time.Time + specialAttackLocks map[uint32]time.Time regenerationAt time.Time regenerationSeconds uint32 savedProfile playerProfile diff --git a/server/users.go b/server/users.go @@ -141,7 +141,7 @@ func (server *server) loadUsers() error { } } } - return nil + return server.loadSpecialAttackLocks() } func (server *server) users_locked() []userData { diff --git a/server/world.sql b/server/world.sql @@ -130,6 +130,12 @@ CREATE TABLE IF NOT EXISTS treatment_locks ( locked_until DATETIME NOT NULL, PRIMARY KEY (player_id, patient_id) ); +CREATE TABLE IF NOT EXISTS special_attack_locks ( + player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE, + skill INTEGER NOT NULL, + locked_until DATETIME NOT NULL, + PRIMARY KEY (player_id, skill) +); CREATE TABLE IF NOT EXISTS learned_nanos ( player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE, nano_id INTEGER NOT NULL, diff --git a/server/world_store.go b/server/world_store.go @@ -48,6 +48,21 @@ func (state *npcState) fields() []any { &state.Roaming.NextMove, &state.Roaming.Moving, &state.Roaming.Returning, &state.HasCorpse, &state.Corpse.Looter, &state.Corpse.Credits, &state.Corpse.ExpiresAt} } +func (npc *character) worldState(present bool, respawnAt time.Time) npcState { + state := npcState{Character: npc.record(), Definition: npc.npcDefinitionID, + Present: present, RespawnAt: respawnAt, LeadingContributor: npc.leadingContributor} + state.Character.Profile.Stats, state.Character.Profile.Profession = npc.stats, npc.profession + if npc.roaming != nil { + state.HasRoaming = true + state.Roaming = roamingState{npc.roaming.home, npc.roaming.destination, npc.roaming.nextMove, npc.roaming.moving, npc.roaming.returning} + } + if npc.corpse != nil { + state.HasCorpse = true + state.Corpse = corpseState{npc.corpse.looter, npc.corpse.credits, npc.corpse.expiresAt} + } + return state +} + func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[uint32]bool) (map[uint32]savedNPC, error) { characters := maps.Clone(server.characters) deadlines := make(map[uint32]time.Time) @@ -92,17 +107,7 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[ui if server.savedNPCs != nil && !store.flushNPCs && !leaving && !lootChanged && (!zones[npc.playfield] || exists && now.Before(previous.NextSave)) { continue } - state := npcState{Character: npc.record(), Definition: npc.npcDefinitionID, - Present: server.characters[id] != nil, RespawnAt: deadlines[id], LeadingContributor: npc.leadingContributor} - state.Character.Profile.Stats, state.Character.Profile.Profession = npc.stats, npc.profession - if npc.roaming != nil { - state.HasRoaming = true - state.Roaming = roamingState{npc.roaming.home, npc.roaming.destination, npc.roaming.nextMove, npc.roaming.moving, npc.roaming.returning} - } - if npc.corpse != nil { - state.HasCorpse = true - state.Corpse = corpseState{npc.corpse.looter, npc.corpse.credits, npc.corpse.expiresAt} - } + state := npc.worldState(server.characters[id] != nil, deadlines[id]) nextSave := previous.NextSave if nextSave.IsZero() || !server.npcZones[npc.playfield] && zones[npc.playfield] { nextSave = now.Add(20*time.Second + time.Duration(rand.Int64N(int64(20*time.Second))))