aorecomp

Anarchy Online classic in the browser

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


commit eeb81fe88f851c646d8f8a530097923dc784588a
parent d177a5cb61dfe8d5414e820a285639675d770d67
Author: anon <anon@example.com>
Date:   Fri, 23 Oct 2026 00:26:54 +0000

Implement Winter's Bite creature casts

Learn the Bureaucrat startup program and resolve its native cast timing, cold damage, cancellation and recharge. Share weapon death and loot handling, preserve lifecycle state, and document the recovered arithmetic and unresolved server policies.

Diffstat:
MTODO.md | 8+++++++-
Adocs/nano-damage.md | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/nano-learning.md | 11+++++++----
Mserver/backpacks.go | 4++--
Mserver/combat.go | 100+++++++++++++++++++++++++++++++++++++++++++------------------------------------
Mserver/control.go | 3++-
Mserver/main.go | 7+++++++
Aserver/nano_casting.go | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/nano_casting_test.go | 312+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/nano_learning.go | 23+++++++++++++++--------
Mserver/nano_learning_test.go | 4++--
Mserver/resurrection.go | 1+
Mserver/roaming.go | 1+
Mserver/state.go | 4++++
Mserver/stats.go | 9++++++---
Mserver/target_protocol_test.go | 2+-
Mserver/world.go | 1+
Mserver/world_actions.go | 17+++++++++++++++++
Mtools/data/extract_nano_learning.py | 8++++----
19 files changed, 780 insertions(+), 71 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -270,7 +270,7 @@ checks are recorded in [treatment kits](docs/treatment-kit.md). agree with the chosen program and appear correctly in the native client. - [ ] Cancel an in-progress cast. Check: the applicable cancellation/refund rule is followed and no delayed heal or duplicate result occurs. -- [ ] Cast one direct-damage program on a creature. Check: target validation, +- [x] Cast one direct-damage program on a creature. Check: target validation, damage and death handling work without starting an unintended weapon attack. - [ ] Apply one temporary stat buff. Check: the native effect appears, the stat changes once, and expiration removes exactly that contribution. @@ -295,6 +295,12 @@ single consumption, duplicate rejection, program-window updates and restart. The exact route, learned-list layout and casting boundary are in [nano learning](docs/nano-learning.md). +Winter's Bite now supports the QL 1 Bureaucrat crystal and a native single-hit +cast against creatures, including death and loot handling. Cancellation and +weapon scheduling have prototype support, with unresolved historical refund +and interruption policies kept open. Catalog evidence, timing arithmetic, +client rendering fixes and checks are in [nano damage](docs/nano-damage.md). + ## Quests - [ ] Accept one quest through an existing NPC conversation. Check: the choice diff --git a/docs/nano-damage.md b/docs/nano-damage.md @@ -0,0 +1,165 @@ +# Winter's Bite in 14.9.1 + +The QL 1 Bureaucrat startup crystal 29625 uploads program 29618, Winter's +Bite. The server supports this exact single-hit program against a visible, +living creature in the same playfield. Casting does not start the caster's +weapon attack. A surviving creature retaliates through the existing combat +loop; a kill uses its normal contribution-based loot rights, corpse and +respawn handling. + +## Catalog and character stats + +Both crystal and program require VisualProfession 368 equal to 8, effective +Psychological Modification 129 greater than 8 and Matter Creation 130 greater +than 7. The crystal is type 51005, with Count 1 and Can `0x29`. Its sole +OnUse 53019 event uploads program 29618 using the existing atomic learning +and consumption path described in [nano learning](nano-learning.md). + +The program's RDB kind is 1040005, header type 51051 and runtime identity +`53019:29618`. Its sole OnUse Hit 53002 targets the selected actor and carries +`{27,-10,-23,95}`: 10 through 23 cold damage to health. Authored NanoCost 407 +is 10, ItemDelay 294 is 261 centiseconds, RechargeDelay 210 is 100 +centiseconds and NFRange 287 is 25 metres. Attack weights are 47% Matter +Creation / 53% Psychological Modification; the defense entry is 75% Nano +Resist. These entries alone do not establish the server's resistance roll. + +Psychological Modification starts at 5 (`kkr.dll 1007288d`), with ability +weights `[0,0,0,80,20,0]` in STR/AGI/STA/INT/SEN/PSY order. Nano Initiative 149 +starts at 5 (`10072939`), with weights `[0,40,0,0,60,0]`. Both trained values +persist in profiles and are sent in owner FullCharacter. Missing fields in +older profiles retain these defaults. Effective skills use the existing +native ability trickle calculation. + +`python3 tools/data/extract_nano_learning.py` retains both supported crystal / +program pairs and their skill weights in +`local/reports/nano-learning-14.9.1.json`. Selected payload SHA-256 values: + +- Crystal: `6078d0c652af888528473e08eebfd5d005e007a893c87715e647dbd5c8c00551`. +- Program: `5897ff28022186c9fe29e4a4aac320347e99ff1f8f9ebb8fe685694ed1553b62`. + +## Native timing and outcome protocol + +`kkr.dll 100651b4..1006526b` computes execution seconds from the raw delay, +Nano Initiative and integer-truncated AggDef/100. Initiative reduction is +`I*0.5` through 1200, then `600+(I-1200)*float32(1/6)`. It stores that reduction +and the final duration as float32; centiseconds use `float32(0.01)`. There is +no execution-time floor in this function. With default abilities, effective +initiative is 7: neutral execution is 2.575000047683716 seconds; full +aggression / defense gives 1.5749999284744263 / 3.575000047683716 seconds. +Recharge uses the authored delay without an initiative reduction. + +C2S CharacterAction 19 carries target `50000:targetID` and program +`53019:29618`. Accepted casts receive S2C action 18 with the same target and +B identity `0:29618`. The zero B type matters: a nonzero value suppresses the +normal local cast HUD. Native helper `actor+158` queues an execution entry +with a deadline and server gate. Action 107, B instance 29618, releases that +gate; the client also waits for its local deadline before entering recharge. +The server admits one cast at a time and rejects requests throughout recharge. + +Hit 53002 is server-owned on this client path (`100bfb40..100bfb61`), so +18/107 alone do not change target health. NanoAttack `4727213e` uses the +victim as its packet identity, followed by a signed negative health delta +and cold damage type 95. Its consumer always emits damage feedback; it is +appropriate here, unlike for a healing result. A lethal result also sends +the normal death action 99 and corpse creation. Action 153, reason 5, then +forces native nano-death HP to zero. StopFight must drain queued weapon +results before this final reset. This ordering is a reconstruction policy; +the original server's packet ordering has not been captured. + +Native admission includes standing still, including keyboard turning, and +excludes swimming, falling and flight. The supported server checks forward, +strafe and turn state, posture, driving, pending equipment and the caster's +weapon phase. Movement commands 1/3/5/7/13 or a changed position cancel a +pending cast. Orientation-only updates do not infer an interruption rule. +The native range predicate uses direct three-dimensional distance without +creature extents; the server checks the 25-metre boundary at admission and +completion. Active casts defer an existing or newly started weapon attack; +weapon recharge is never shortened. + +## Resource arithmetic and policy limits + +The native cost eligibility/refund expression truncates +`rawCost * NanoCostModifier318 * float32(0.01)`. Default modifier 318 is 100 +(`10072b27`, `10072ebe`). At double precision this truncates Winter's Bite's +10 to **9**. Clientr.exe startup `405800` calls `_controlfp(0x10000,0x30000)`, +selecting 53-bit arithmetic. The selected WASM implementation also uses +double precision for this expression. A 24-bit x87 intermediate could round +the same product to 10. Startup is not proof of every original runtime +thread's later control word, especially after graphics-driver calls. + +The prototype reserves 9 points on admission and refunds that reservation +once on explicit cancellation, movement, lifecycle cancellation or an invalid +completion target, capped at the current maximum. This agrees with the +selected client arithmetic; the original server's debit amount, debit time +and voluntary-cancellation refund policy remain unverified. Action 108 +cancels the native queue; action 117 is avoided because it independently +refunds client nano and would double-refund with an authoritative stat update. + +Damage currently rolls uniformly across the authored inclusive endpoints. +That distribution is provisional. Resistance, fumbles, incoming-hit +interruption probability, line of sight and nano AC ordering are not +implemented. Current PvE creatures have no equipment AC, so no weapon AC +formula is substituted for the unresolved nano formula. The server has no +reliable falling/swimming state; the ordinary native client supplies those +admission gates. Rechecking range at completion and limiting targets to the +existing PvE creature set are prototype policies, not recovered universal +PvP or friendly-target rules. + +Shipped help, `Nano Programs and their Importance.txt`, supports stationary +execution, movement interruption and explicit target selection. Period +manual and local fandom evidence do not resolve the numeric server policies +above. Exact evidence, original bytes, arithmetic experiments and bounded +unknowns are retained in `local/nano-damage-research/`, +`local/nano-casting-research/` and `local/fpu-precision-research/`. + +## Client adapter + +Winter's Bite's effect requests Direct3D COLOROP and ALPHAOP 6, MODULATE4X. +The adapter and shared OpenGL/WebGL shader multiply the selected color or +alpha arguments by four and clamp the stage result before the next stage. Color and alpha +retain independently selected operations. This follows Microsoft's +[D3DTEXTUREOP contract](https://learn.microsoft.com/en-us/windows/win32/direct3d9/d3dtextureop). +The previous adapter exited on this request, stopping both caster and observer. +A device-level pixel regression uses two stages to detect missing modulation +or a missing intermediate clamp. + +## Verification + +`TestWinterBite*` covers learning and persistence, requirement boundaries, +invalid sessions/targets/resources, exact execution timing, the 3D range +boundary, single debit/result under concurrent requests, strict completion +and recharge gates, cancellation/refund, locomotion, profile changes, +weapon scheduling and shared lethal contribution/corpse/respawn handling. + +Two WASM clients completed the cast through the normal program UI. The first +hit reduced the fixture's 65 HP creature to 44 on the server and both clients, +with one 9-point debit and no owner weapon attack. Read-only native samples +observed execution, recharge, gate release and queue removal; the sampled +admission-to-impact interval was 2585 ms. A movement-cancelled cast restored +the server reservation without later damage and cleared the native queue. +A one-HP creature died without an owner weapon attack. Another kill occurred +during weapon combat after native weapon results had been queued; death +stopped the fight and reached zero HP or removal on both clients. The native +corpse opened and transferred its fixture loot. Restart restored that loot, +Bureaucrat profession, trained skills and native learned-program entry. + +The run passed 43 checks in `local/nano-damage-smoke/verification.json`, with +packet logs, UI screenshots and read-only guest-memory samples. The final run +had no adapter errors; connection refusals occurred during the intentional +restart. Native OpenGL and WASM WebGL device suites also passed color and +alpha modulation tests, including clamping before a subsequent stage. +Both clients and every temporary server were closed afterward. + +The smoke fixture supplies a larger Body Development value to survive manual +inspection, fills nano on cold start and omits periodic regeneration. Long +samples therefore include player resource prediction drift; they are not +proof of resource persistence or long-running regeneration convergence. +The immediate first-hit comparison and lethal zero/reset checks above avoid +that ambiguity. Native creature regeneration also remains outside the +server's implemented resource loop, as tracked by the NPC resource TODO. + +The full `go test ./server/...` suite passed (server: 92.491 seconds). +`go test -race ./server -run '^TestWinterBite' -count=5` passed (95.034 +seconds), including all new casting, learning, movement and lifecycle cases. +The three WASM publication unit tests passed, and the published bundle's +source-input and file hashes match the current client sources. diff --git a/docs/nano-learning.md b/docs/nano-learning.md @@ -1,10 +1,13 @@ # Learning a nano in 14.9.1 -The supported crystal is the exact QL 1 Meta-Physicist startup crystal 43330, -item type 51005. Its OnUse event contains function 53019 with program ID 43324, +The QL 1 Meta-Physicist startup crystal 43330 has item type 51005. Its OnUse event contains function 53019 with program ID 43324, Lesser Anger Manifestation. Other crystals and arbitrary qualities are not inferred from this endpoint. Acquisition uses the existing fixture grant. +Winter's Bite uses the same upload route for Bureaucrat crystal 29625 and +program 29618. Its requirements and supported damage cast are documented in +[nano damage](nano-damage.md). + ## Requirements and character data The crystal's Use action requires effective Matter Creation 130 greater than 7, @@ -96,8 +99,8 @@ list readers and field names. REA evidence independently decompiles the original 53019 handler. Its retained snapshot is `kkr-handler.rea.json`; the native analysis session was closed afterward. -Learning does not claim pet creation or casting support. The native cast -request and the selected summon record are retained for that next step. +This summon program does not yet have pet creation or casting support. The +native cast request and selected summon record are retained for that next step. The exact original PT50 pet definition, lifetime units and server policies remain unresolved in `local/pet-research/`. diff --git a/server/backpacks.go b/server/backpacks.go @@ -71,10 +71,10 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error client.useSequence = sequence if binary.BigEndian.Uint32(body[40:44]) == 104 { index := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { - return item.Slot == binary.BigEndian.Uint32(body[44:48]) && (item.Template == 43552 || item.Template == 85366 || item.Template == 25812 || item.Template == 43330) + return item.Slot == binary.BigEndian.Uint32(body[44:48]) && (item.Template == 43552 || item.Template == 85366 || item.Template == 25812 || item.Template == 43330 || item.Template == 29625) }) if index >= 0 { - if player.inventory.Items[index].Template == 43330 { + if player.inventory.Items[index].Template == 43330 || player.inventory.Items[index].Template == 29625 { return server.learnNano_locked(client, index, body) } if player.inventory.Items[index].Template == 85366 { diff --git a/server/combat.go b/server/combat.go @@ -221,6 +221,9 @@ func (server *server) startAttack_locked(attacker, target *character, now time.T if attacker.nextAttack.Before(attacker.rechargeUntil) { attacker.nextAttack = attacker.rechargeUntil } + if client := server.clients[attacker.id]; client != nil && client.nanoCast != nil && attacker.nextAttack.Before(client.nanoCast.readyAt) { + attacker.nextAttack = client.nanoCast.readyAt + } attack, _ := attacker.attackDelays() attacker.nextAttack = attacker.nextAttack.Add(attack) server.fighting[attacker.id] = attacker @@ -249,6 +252,9 @@ func (server *server) cancelCombat_locked(id uint32, updates map[*worldClient][] server.stopAttack_locked(attacker, updates) } } + if client := server.clients[id]; client != nil { + server.abortNano_locked(client, time.Now(), updates) + } } func (server *server) advanceCombat(now time.Time) { @@ -298,59 +304,63 @@ func (server *server) advanceCombat(now time.Time) { } } target.health -= damage - // Keep individual contributions for this NPC life, including stopped attacks. - if target.npc && !attacker.npc { - if target.damageContributors == nil { - target.damageContributors = make(map[uint32]uint32) - } - target.damageContributors[attacker.id] += damage - // Equal totals retain the first contributor to reach that total. - if target.damageContributors[attacker.id] > target.damageContributors[target.leadingContributor] { - target.leadingContributor = attacker.id - } - } attack, recharge := attacker.attackDelays() attacker.rechargeUntil = now.Add(recharge) attacker.nextAttack = attacker.rechargeUntil.Add(attack) server.queueCombat_locked(updates, attacker, target, hitPacket(attacker, target, damage)) - if target.health == 0 { - if target.roaming != nil && target.roaming.moving { - target.roaming.moving = false - server.queueCombat_locked(updates, target, target, npcMovementPacket(target, 2)) - } - if !target.npc { - client := server.clients[target.id] - target.position = predictedPosition_locked(target, client, now) - client.forward = 0 - client.reclaimItems = nil - client.backpacks = nil - } - server.cancelCombat_locked(target.id, updates) - 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)) + server.finishDamage_locked(attacker, target, damage, now, updates) + } + server.mutex.Unlock() + server.sendCombatUpdates(updates) +} + +func (server *server) finishDamage_locked(attacker, target *character, damage uint32, now time.Time, updates map[*worldClient][][]byte) { + // Keep individual contributions for this NPC life, including stopped attacks. + if target.npc && !attacker.npc { + if target.damageContributors == nil { + target.damageContributors = make(map[uint32]uint32) + } + target.damageContributors[attacker.id] += damage + // Equal totals retain the first contributor to reach that total. + if target.damageContributors[attacker.id] > target.damageContributors[target.leadingContributor] { + target.leadingContributor = attacker.id + } + } + if target.health == 0 { + if target.roaming != nil && target.roaming.moving { + target.roaming.moving = false + server.queueCombat_locked(updates, target, target, npcMovementPacket(target, 2)) + } + if !target.npc { + client := server.clients[target.id] + target.position = predictedPosition_locked(target, client, now) + client.forward = 0 + client.reclaimItems = nil + client.backpacks = nil + } + server.cancelCombat_locked(target.id, updates) + 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{} } - if target.npc && target.combatProfile != nil && target.combatProfile.RespawnSeconds != 0 { - server.npcRespawns = append(server.npcRespawns, npcRespawn{ - npc: target, at: now.Add(time.Duration(target.combatProfile.RespawnSeconds) * time.Second), - }) + 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) } - } else if target.npc && target.fighting == 0 { - server.startAttack_locked(target, attacker, now, updates) + server.queueCombat_locked(updates, target, target, corpsePacket(target)) + } + if target.npc && target.combatProfile != nil && target.combatProfile.RespawnSeconds != 0 { + server.npcRespawns = append(server.npcRespawns, npcRespawn{ + npc: target, at: now.Add(time.Duration(target.combatProfile.RespawnSeconds) * time.Second), + }) } + } else if target.npc && target.fighting == 0 { + server.startAttack_locked(target, attacker, now, updates) } - server.mutex.Unlock() - server.sendCombatUpdates(updates) } func (server *server) queueCombat_locked(updates map[*worldClient][][]byte, character, target *character, packets ...[]byte) { diff --git a/server/control.go b/server/control.go @@ -243,15 +243,16 @@ func (server *server) updateUser_locked(destination userData) error { updated.savedPosition = character.savedPosition updated.nextPositionSave = character.nextPositionSave updated.health = min(character.health, updated.maximumHealth()) - updated.nano = min(character.nano, updated.maximumNano()) updated.aggDef = character.aggDef updated.rechargeUntil = character.rechargeUntil + updated.nanoRechargeUntil = character.nanoRechargeUntil if err := server.saveUser_locked(updated); err != nil { server.mutex.Unlock() return err } updates := make(map[*worldClient][][]byte) server.cancelCombat_locked(character.id, updates) + updated.nano = min(character.nano, updated.maximumNano()) *character = *updated client := server.clients[character.id] if client == nil || !client.ready { diff --git a/server/main.go b/server/main.go @@ -444,6 +444,10 @@ func (server *server) serveWorldClient(client *worldClient) error { return fmt.Errorf("short character action message") } switch binary.BigEndian.Uint32(body[16:20]) { + case 19: + if err := server.handleNanoCast(client, body); err != nil { + return err + } case 109, 110: if err := server.handleReclaim(client, body); err != nil { return err @@ -474,6 +478,9 @@ func (server *server) serveWorldClient(client *worldClient) error { return err } case 108: + if err := server.handleNanoCast(client, body); err != nil { + return err + } loggingOut = false if err := conn.SetReadDeadline(time.Time{}); err != nil { return err diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -0,0 +1,171 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "fmt" + "math/rand/v2" + "slices" + "time" +) + +type nanoCast struct { + target uint32 + readyAt time.Time +} + +func characterActionPacket(id uint32, fields [5]uint32) []byte { + var body []byte + for _, value := range fields { + body = binary.BigEndian.AppendUint32(body, value) + } + return n3Packet(0x5e477770, 50000, id, body) +} + +func nanoPointsPacket(player *character) []byte { + body := binary.BigEndian.AppendUint32(nil, 214) + body = binary.BigEndian.AppendUint32(body, player.nano) + return n3Packet(0x2b333d6e, 50000, player.id, body) +} + +func winterBiteCost() uint32 { + // Native default cost modifier 318 is 100; retain the x87 float32 constant. + return uint32(float64(itemStat(gamedata.NanoTemplates[29618], 407)*100) * float64(float32(0.01))) +} + +func (player *character) winterBiteCastDelay() time.Duration { + // kkr.dll 100651b4..1006526b stores initiative reduction before the final duration. + stats := player.baseStats() + initiative := stats.effectiveSkill(stats.NanoInitiative, [6]uint32{0, 40, 0, 0, 60, 0}) + reduction := float32(float64(initiative) * 0.5) + if initiative > 1200 { + reduction = float32(600 + float64(initiative-1200)*float64(float32(1.0/6))) + } + delay := float32(float64(itemStat(gamedata.NanoTemplates[29618], 294))*float64(float32(0.01)) - + float64(reduction)*float64(float32(0.01)) - float64(player.aggDef/100)) + return time.Duration(float64(delay) * float64(time.Second)) +} + +func (server *server) winterBiteTarget_locked(player, target *character, client *worldClient, now time.Time) bool { + if target == nil || !target.npc || target.appearance>>4&7 != 6 || !client.npcs[target.id] || + target.health == 0 || target.playfield != player.playfield { + return false + } + position := predictedPosition_locked(player, client, now) + x, y, z := position[0]-target.position[0], position[1]-target.position[1], position[2]-target.position[2] + return x*x+y*y+z*z <= 25*25 +} + +func (server *server) handleNanoCast(client *worldClient, body []byte) error { + if len(body) != 36 { + return fmt.Errorf("invalid nano action length") + } + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + player := server.characters[client.id] + if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || + binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id { + server.mutex.Unlock() + return nil + } + + now := time.Now() + updates := make(map[*worldClient][][]byte) + if binary.BigEndian.Uint32(body[16:20]) == 108 { + if binary.BigEndian.Uint64(body[20:28]) == 0 && binary.BigEndian.Uint64(body[28:36]) == 0 { + server.abortNano_locked(client, now, updates) + } + server.mutex.Unlock() + server.sendCombatUpdates(updates) + return nil + } + if binary.BigEndian.Uint32(body[16:20]) != 19 || client.nanoCast != nil || !now.After(player.nanoRechargeUntil) { + server.mutex.Unlock() + return nil + } + + // Admit only the learned QL 1 program against a visible living creature. + target := server.characters[binary.BigEndian.Uint32(body[24:28])] + stats := player.baseStats() + accepted := binary.BigEndian.Uint32(body[20:24]) == 50000 && binary.BigEndian.Uint32(body[28:32]) == 53019 && + binary.BigEndian.Uint32(body[32:36]) == 29618 && slices.Contains(player.inventory.LearnedNanos, 29618) && + player.profession == 8 && stats.effectiveSkill(stats.PsychologicalModification, [6]uint32{0, 0, 0, 80, 20, 0}) > 8 && + stats.effectiveSkill(stats.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7 && player.nano >= winterBiteCost() && + !player.sitting && !player.driving() && client.forward == 0 && !client.strafing && !client.turning && client.equipment == nil && + (player.fighting == 0 || now.Before(player.rechargeUntil)) && server.winterBiteTarget_locked(player, target, client, now) + if !accepted { + updates[client] = append(updates[client], characterActionPacket(player.id, [5]uint32{108})) + server.mutex.Unlock() + server.sendCombatUpdates(updates) + return nil + } + + // Reserve the cost once; the server releases the native effect gate at the deadline. + player.nano -= winterBiteCost() + client.nanoCast = &nanoCast{target: target.id, readyAt: now.Add(player.winterBiteCastDelay())} + if player.fighting != 0 && client.nanoCast.readyAt.After(player.rechargeUntil) { + attack, _ := player.attackDelays() + player.nextAttack = client.nanoCast.readyAt.Add(attack) + } + server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{18, 50000, target.id, 0, 29618})) + updates[client] = append(updates[client], nanoPointsPacket(player)) + server.mutex.Unlock() + server.sendCombatUpdates(updates) + return nil +} + +func (server *server) abortNano_locked(client *worldClient, now time.Time, updates map[*worldClient][][]byte) { + if client.nanoCast == nil { + return + } + player := server.characters[client.id] + client.nanoCast = nil + player.nano = min(player.maximumNano(), player.nano+winterBiteCost()) + if player.fighting != 0 { + attack, _ := player.attackDelays() + player.nextAttack = now + if now.Before(player.rechargeUntil) { + player.nextAttack = player.rechargeUntil + } + player.nextAttack = player.nextAttack.Add(attack) + } + server.queueCombat_locked(updates, player, player, characterActionPacket(player.id, [5]uint32{108})) + updates[client] = append(updates[client], nanoPointsPacket(player)) +} + +func (server *server) advanceNanos(now time.Time) { + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + updates := make(map[*worldClient][][]byte) + for id, client := range server.clients { + if client.nanoCast == nil || !now.After(client.nanoCast.readyAt) { + continue + } + player := server.characters[id] + target := server.characters[client.nanoCast.target] + if !client.ready || client.loading || player.health == 0 || !server.winterBiteTarget_locked(player, target, client, now) { + server.abortNano_locked(client, now, updates) + continue + } + + // Only this result changes HP; the native Hit effect is server-owned. + client.nanoCast = nil + recharge := float64(itemStat(gamedata.NanoTemplates[29618], 210)) * float64(float32(0.01)) + player.nanoRechargeUntil = now.Add(time.Duration(recharge * float64(time.Second))) + damage := min(10+rand.Uint32N(14), target.health) + target.health -= damage + body := binary.BigEndian.AppendUint32(nil, uint32(-int32(damage))) + body = binary.BigEndian.AppendUint32(body, 95) + server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{107, 0, 0, 0, 29618})) + server.queueCombat_locked(updates, target, target, n3Packet(0x4727213e, 50000, target.id, body)) + server.finishDamage_locked(player, target, damage, now, updates) + if target.health == 0 { + // StopFight drains pending weapon results before the explicit nano death reset. + server.queueCombat_locked(updates, target, target, characterActionPacket(target.id, [5]uint32{153, 0, 0, 0, 5})) + } + } + server.mutex.Unlock() + server.sendCombatUpdates(updates) +} diff --git a/server/nano_casting_test.go b/server/nano_casting_test.go @@ -0,0 +1,312 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "slices" + "sync" + "testing" + "time" +) + +func newNanoCastingWorld() (*server, *combatTestConn) { + world, conn := newCombatWorld() + player := world.characters[1] + player.profession, player.nano = 8, 30 + player.appearance, player.level = 0x315, 1 + player.stats = defaultCharacterStats() + player.stats.PsychologicalModification, player.stats.MatterCreation = 7, 6 + player.health = player.maximumHealth() + player.inventory.LearnedNanos = []uint32{29618} + return world, conn +} + +func TestWinterBiteTimesOneResultAndRecharge(t *testing.T) { + world, conn := newNanoCastingWorld() + player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] + request := characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 29618})[20:] + observer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950, health: 100} + world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true, npcs: map[uint32]bool{npc.id: true}} + + if err := world.handleNanoCast(client, request); err != nil { + t.Fatal(err) + } + deadline := client.nanoCast.readyAt + world.handleNanoCast(client, request) + world.advanceNanos(deadline) + if player.nano != 21 || npc.health != 100 || len(conn.packets) != 2 || len(observer.packets) != 1 { + t.Fatal("duplicate or early result", player.nano, npc.health) + } + world.advanceNanos(deadline.Add(time.Nanosecond)) + health := npc.health + world.advanceNanos(deadline.Add(500 * time.Millisecond)) + world.handleNanoCast(client, request) + + if player.nano != 21 || npc.health != health || health < 77 || health > 90 || client.nanoCast != nil || player.fighting != 0 || npc.fighting != player.id { + t.Fatalf("cast state: nano=%d health=%d pending=%+v fights=%d/%d", player.nano, npc.health, client.nanoCast, player.fighting, npc.fighting) + } + if player.nanoRechargeUntil != deadline.Add(999999978*time.Nanosecond) || len(conn.packets) != 5 || len(observer.packets) != 4 { + t.Fatal("recharge or duplicate packets", player.nanoRechargeUntil.Sub(deadline), len(conn.packets), len(observer.packets)) + } + if binary.BigEndian.Uint32(conn.packets[0][41:45]) != 0 || binary.BigEndian.Uint32(conn.packets[0][45:49]) != 29618 || binary.BigEndian.Uint32(conn.packets[2][29:33]) != 107 || binary.BigEndian.Uint32(conn.packets[3][16:20]) != 0x4727213e || int32(binary.BigEndian.Uint32(conn.packets[3][29:33])) != int32(health)-100 || binary.BigEndian.Uint32(conn.packets[3][33:37]) != 95 { + t.Fatalf("native nano packets: %x", conn.packets) + } + if len(npc.damageContributors) != 1 || npc.damageContributors[1] != 100-health { + t.Fatal("missing damage contribution", npc.damageContributors) + } +} + +func TestWinterBiteRejectsInvalidAdmission(t *testing.T) { + for _, scenario := range []string{"unlearned", "profession", "psychology", "creation", "nano", "sitting", "forward", "strafe", "turn", "equipment", "weapon attack", "hidden", "dead target", "player target", "wrong zone", "range", "range vertical", "wrong program", "wrong resource", "foreign owner", "loading", "not ready", "stale", "dead caster"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newNanoCastingWorld() + player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] + fields := [5]uint32{19, 50000, npc.id, 53019, 29618} + owner := uint32(1) + switch scenario { + case "unlearned": + player.inventory.LearnedNanos = nil + case "profession": + player.profession = 12 + case "psychology": + player.stats.PsychologicalModification = 6 + case "creation": + player.stats.MatterCreation = 5 + case "nano": + player.nano = 8 + case "sitting": + player.sitting = true + case "forward": + client.forward = 1 + case "strafe": + client.strafing = true + case "turn": + client.turning = true + case "equipment": + client.equipment = &equipmentMove{} + case "weapon attack": + player.fighting = npc.id + case "hidden": + delete(client.npcs, npc.id) + case "dead target": + npc.health = 0 + case "player target": + npc.npc = false + case "wrong zone": + npc.playfield = 705 + case "range": + npc.position = [3]float32{25.001, 0, 0} + case "range vertical": + npc.position = [3]float32{0, 25.001, 0} + case "wrong program": + fields[4] = 43324 + case "wrong resource": + fields[3] = 1040005 + case "foreign owner": + owner = 2 + case "loading": + client.loading = true + case "not ready": + client.ready = false + case "stale": + world.clients[1] = &worldClient{id: 1} + case "dead caster": + player.health = 0 + } + before := player.nano + err := world.handleNanoCast(client, characterActionPacket(owner, fields)[20:]) + world.advanceNanos(time.Now().Add(time.Hour)) + if err != nil || client.nanoCast != nil || player.nano != before || npc.health != 100 && scenario != "dead target" { + t.Fatal("invalid cast changed state", err, player.nano, npc.health) + } + }) + } +} + +func TestWinterBiteNativeTimingAndRangeBoundary(t *testing.T) { + for _, scenario := range []struct { + agg int32 + delay time.Duration + }{{0, 2575000047}, {100, 1574999928}, {-100, 3575000047}} { + t.Run(time.Duration(scenario.agg).String(), func(t *testing.T) { + world, _ := newNanoCastingWorld() + player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] + player.aggDef = scenario.agg + npc.position = [3]float32{15, 20, 0} + before := time.Now() + err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 29618})[20:]) + after := time.Now() + if err != nil || client.nanoCast == nil || client.nanoCast.readyAt.Before(before.Add(scenario.delay)) || client.nanoCast.readyAt.After(after.Add(scenario.delay)) { + t.Fatal("native timing/range", err, client.nanoCast, player.winterBiteCastDelay()) + } + }) + } +} + +func TestWinterBiteCancellationAndInvalidatedTargetRefundOnce(t *testing.T) { + for _, scenario := range []string{"request", "target moved", "target dead", "hidden", "lifecycle"} { + t.Run(scenario, func(t *testing.T) { + world, conn := newNanoCastingWorld() + player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 29618})[20:]) + deadline := client.nanoCast.readyAt + switch scenario { + case "request": + for range 2 { + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{108})[20:]); err != nil { + t.Fatal(err) + } + } + case "target moved": + npc.position[0] = 26 + case "target dead": + npc.health = 0 + case "hidden": + delete(client.npcs, npc.id) + case "lifecycle": + updates := make(map[*worldClient][][]byte) + world.cancelCombat_locked(1, updates) + world.sendCombatUpdates(updates) + } + world.advanceNanos(deadline.Add(time.Second)) + world.advanceNanos(deadline.Add(time.Hour)) + if client.nanoCast != nil || player.nano != 30 || player.nanoRechargeUntil != (time.Time{}) || npc.health != 100 && scenario != "target dead" || len(conn.packets) != 4 { + t.Fatal("cancel did not refund exactly once", player.nano, npc.health, len(conn.packets)) + } + }) + } +} + +func TestWinterBiteDeathUsesSharedLootAndStopsPendingWeapons(t *testing.T) { + world, conn := newNanoCastingWorld() + player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] + npc.health, npc.monsterData = 1, 17655 + npc.combatProfile = &gamedata.NPCCombatProfile{CorpseSeconds: 60, RespawnSeconds: 90} + npc.damageContributors = map[uint32]uint32{2: 10} + npc.leadingContributor = 2 + world.handleCombat(client, attackPacket(1, npc.id)[20:]) + player.rechargeUntil = time.Now().Add(time.Second) + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 29618})[20:]) + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + if npc.health != 0 || npc.corpse == nil || npc.corpse.looter != 2 || len(world.corpseExpiry) != 1 || len(world.npcRespawns) != 1 || len(world.fighting) != 0 || player.fighting != 0 { + t.Fatalf("nano death lost shared lifecycle: %+v", npc) + } + last := conn.packets[len(conn.packets)-1] + if binary.BigEndian.Uint32(last[29:33]) != 153 || binary.BigEndian.Uint32(last[45:49]) != 5 { + t.Fatalf("final death reset must follow queued weapon drain: %x", conn.packets) + } +} + +func TestWinterBiteConcurrentRequestsReserveOneCost(t *testing.T) { + world, conn := newNanoCastingWorld() + client := world.clients[1] + request := characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:] + var workers sync.WaitGroup + for range 8 { + workers.Go(func() { + if err := world.handleNanoCast(client, request); err != nil { + t.Error(err) + } + }) + } + workers.Wait() + if client.nanoCast == nil || world.characters[1].nano != 21 || len(conn.packets) != 2 { + t.Fatal("concurrent cast duplicated admission") + } +} + +func TestWinterBiteCrystalPersistsLearnedProgram(t *testing.T) { + world, _ := newNanoLearningWorld(t) + player := world.characters[1] + player.profession = 8 + player.stats.PsychologicalModification = 7 + player.inventory.Items = nil + if ok, err := world.grantItem_locked(player, 29625); !ok || err != nil { + t.Fatal(ok, err) + } + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 2)[20:]) + restored := newTestInventoryServer(t).characters[1] + if err != nil || !slices.Equal(restored.inventory.LearnedNanos, []uint32{29618}) || len(restored.inventory.Items) != 0 { + t.Fatal("winter crystal did not persist consumption and learning", err, restored.inventory) + } +} + +func TestWinterBiteMovementCancelsBeforeDelayedResult(t *testing.T) { + for _, action := range []uint32{1, 3, 5, 7, 13} { + t.Run(time.Duration(action).String(), func(t *testing.T) { + t.Chdir(t.TempDir()) + world, _ := newNanoCastingWorld() + player, client := world.characters[1], world.clients[1] + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]) + deadline := client.nanoCast.readyAt + body := encodeMovement1491(npcMovementPacket(player, action)[36:]) + err := world.handleMovement(client, append(make([]byte, 16), body...)) + world.advanceNanos(deadline.Add(time.Second)) + if err != nil || client.nanoCast != nil || player.nano != 30 || world.characters[1000000].health != 100 { + t.Fatal("movement left delayed damage", err, player.nano) + } + }) + } +} + +func TestWinterBiteWeaponRechargeCannotAccelerateAnAttack(t *testing.T) { + world, _ := newNanoCastingWorld() + player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] + world.handleCombat(client, attackPacket(1, npc.id)[20:]) + player.rechargeUntil = time.Now().Add(time.Second) + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 29618})[20:]) + deadline := client.nanoCast.readyAt + next := player.nextAttack + world.advanceCombat(deadline) + world.handleCombat(client, stopFightPacket(1)[20:]) + world.handleCombat(client, attackPacket(1, npc.id)[20:]) + if npc.health != 100 || player.nextAttack != next || !next.After(deadline) { + t.Fatal("cast/start/stop bypassed weapon timing", next, player.nextAttack, deadline, npc.health) + } +} + +func TestWinterBiteProfileChangeRefundsPendingCast(t *testing.T) { + t.Chdir(t.TempDir()) + world, _ := newNanoCastingWorld() + player, client := world.characters[1], world.clients[1] + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]) + deadline := client.nanoCast.readyAt + destination := player.userData() + destination.Playfield = 705 + err := world.updateUser(destination) + world.advanceNanos(deadline.Add(time.Second)) + if err != nil || client.nanoCast != nil || player.nano != 30 || world.characters[1000000].health != 100 || player.playfield != 705 { + t.Fatal("profile update lost refund or kept delayed cast", err, player.nano, player.playfield) + } +} + +func TestWinterBiteCrystalRejectsNativeRequirementBoundaries(t *testing.T) { + for _, scenario := range []string{"psychology 8", "creation 7", "profession"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newNanoLearningWorld(t) + player := world.characters[1] + player.profession = 8 + player.stats.PsychologicalModification = 7 + player.inventory.Items = nil + if ok, err := world.grantItem_locked(player, 29625); !ok || err != nil { + t.Fatal(ok, err) + } + switch scenario { + case "psychology 8": + player.stats.PsychologicalModification = 6 + case "creation 7": + player.stats.MatterCreation = 5 + case "profession": + player.profession = 12 + } + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 2)[20:]) + if err != nil || len(player.inventory.LearnedNanos) != 0 || len(player.inventory.Items) != 1 || player.inventory.Items[0].Template != 29625 { + t.Fatal("invalid winter upload consumed crystal", err, player.inventory) + } + }) + } +} diff --git a/server/nano_learning.go b/server/nano_learning.go @@ -9,17 +9,24 @@ func (server *server) learnNano_locked(client *worldClient, index int, body []by player := server.characters[client.id] item := player.inventory.Items[index] stats := player.baseStats() - accepted := item.Type == 51005 && item.Template == 43330 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 && - player.profession == 12 && - stats.effectiveSkill(stats.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7 && - stats.effectiveSkill(stats.TimeAndSpace, [6]uint32{0, 20, 0, 80, 0, 0}) > 7 && - !slices.Contains(player.inventory.LearnedNanos, 43324) + program := uint32(43324) + accepted := item.Type == 51005 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 && + stats.effectiveSkill(stats.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7 + if item.Template == 29625 { + program = 29618 + accepted = accepted && player.profession == 8 && + stats.effectiveSkill(stats.PsychologicalModification, [6]uint32{0, 0, 0, 80, 20, 0}) > 8 + } else { + accepted = accepted && player.profession == 12 && + stats.effectiveSkill(stats.TimeAndSpace, [6]uint32{0, 20, 0, 80, 0, 0}) > 7 + } + accepted = accepted && !slices.Contains(player.inventory.LearnedNanos, program) if accepted { // Consume the crystal and grant the program in one atomic save. inventory := player.inventory inventory.Items = slices.Clone(inventory.Items) inventory.Items = slices.Delete(inventory.Items, index, index+1) - inventory.LearnedNanos = append(slices.Clone(inventory.LearnedNanos), 43324) + inventory.LearnedNanos = append(slices.Clone(inventory.LearnedNanos), program) if err := server.saveInventory_locked(player, inventory); err != nil { return err } @@ -40,14 +47,14 @@ func (server *server) learnNano_locked(client *worldClient, index int, body []by // OnUse adds the learned entry before DeleteItem removes the empty proxy. var action []byte - for _, value := range []uint32{43330, 43330, 1, 1, 3, 104, item.Slot, 50000, client.id} { + for _, value := range []uint32{item.Template, item.Template, 1, 1, 3, 104, item.Slot, 50000, client.id} { action = binary.BigEndian.AppendUint32(action, value) } if err := client.send(n3Packet(0x35505644, 50000, client.id, action)); err != nil { return err } var removal []byte - for _, value := range []uint32{112, 104, item.Slot, 43330, 43330} { + for _, value := range []uint32{112, 104, item.Slot, item.Template, item.Template} { removal = binary.BigEndian.AppendUint32(removal, value) } return client.send(n3Packet(0x5e477770, 50000, client.id, removal)) diff --git a/server/nano_learning_test.go b/server/nano_learning_test.go @@ -159,7 +159,7 @@ func TestNanoLearningLoadsDefaultsForOlderProfiles(t *testing.T) { t.Fatal(err) } profile := string(data) - for _, field := range []string{"profession: 12\n", " matter_creation: 6\n", " time_and_space: 6\n"} { + for _, field := range []string{"profession: 12\n", " matter_creation: 6\n", " time_and_space: 6\n", " psychological_modification: 5\n", " nano_initiative: 5\n"} { if !strings.Contains(profile, field) { t.Fatal("missing profile fixture field", field) } @@ -171,7 +171,7 @@ func TestNanoLearningLoadsDefaultsForOlderProfiles(t *testing.T) { restored := newTestInventoryServer(t).characters[1] - if restored.profession != 1 || restored.stats.MatterCreation != 5 || restored.stats.TimeAndSpace != 5 { + if restored.profession != 1 || restored.stats.MatterCreation != 5 || restored.stats.TimeAndSpace != 5 || restored.stats.PsychologicalModification != 5 || restored.stats.NanoInitiative != 5 { t.Fatalf("older profile lost its native defaults: profession=%d stats=%+v", restored.profession, restored.stats) } } diff --git a/server/resurrection.go b/server/resurrection.go @@ -33,6 +33,7 @@ func (server *server) handleResurrection(client *worldClient, body []byte) error updated.fighting = 0 updated.nextAttack = time.Time{} updated.rechargeUntil = time.Time{} + updated.nanoRechargeUntil = time.Time{} if err := server.savePosition_locked(&updated); err != nil { server.mutex.Unlock() return err diff --git a/server/roaming.go b/server/roaming.go @@ -24,6 +24,7 @@ func (server *server) roamNPCs() { server.advanceNPCs(now) server.advanceEquipment(now) server.advanceItemEffects(now) + server.advanceNanos(now) server.advanceCombat(now) server.advanceRegeneration(now) } diff --git a/server/state.go b/server/state.go @@ -45,6 +45,7 @@ type character struct { resurrectionTerminal uint32 implantChangesUntil time.Time treatmentLockedUntil time.Time + nanoRechargeUntil time.Time savedProfile playerProfile savedPosition playerPosition nextPositionSave time.Time @@ -59,12 +60,15 @@ type worldClient struct { id uint32 target bool forward float32 + strafing bool + turning bool movementStarted time.Time regenerationAt time.Time regenerationSeconds uint32 npcs map[uint32]bool dialogue *npcDialogue equipment *equipmentMove + nanoCast *nanoCast lootCorpse uint32 reclaimItems []uint32 backpacks map[uint32]backpackHandle diff --git a/server/stats.go b/server/stats.go @@ -20,12 +20,15 @@ type characterStats struct { FirstAid uint16 `yaml:"first_aid"` VehicleGround uint16 `yaml:"vehicle_ground"` VehicleAir uint16 `yaml:"vehicle_air"` - MatterCreation uint16 `yaml:"matter_creation"` - TimeAndSpace uint16 `yaml:"time_and_space"` + + MatterCreation uint16 `yaml:"matter_creation"` + TimeAndSpace uint16 `yaml:"time_and_space"` + PsychologicalModification uint16 `yaml:"psychological_modification"` + NanoInitiative uint16 `yaml:"nano_initiative"` } func defaultCharacterStats() characterStats { - return characterStats{10, 10, 10, 10, 10, 10, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5} + return characterStats{10, 10, 10, 10, 10, 10, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5} } func (character *character) baseStats() characterStats { diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go @@ -98,7 +98,7 @@ initialized: if hex.EncodeToString(npc[60:89]) != "000001cb0b456469746564204e50430000000000000000000000000007" { t.Fatalf("target NPC appearance, name and new stats: %x", npc[60:89]) } - if hex.EncodeToString(full[57:73]) != "000003f1000091d50000003600000001" { + if hex.EncodeToString(full[57:73]) != "000003f1000099b70000003600000001" { t.Fatalf("target seventh list and first stat: %x", full[57:73]) } } diff --git a/server/world.go b/server/world.go @@ -194,6 +194,7 @@ func fullCharacterPacket(character *character) []byte { stats := [][2]uint32{{54, uint32(character.level)}, {4, uint32(character.appearance >> 4 & 7)}, {60, uint32(max(1, character.profession))}, {33, uint32(character.appearance >> 9 & 3)}, {59, uint32(character.appearance >> 7 & 3)}, {156, 100}, {16, uint32(base.Strength)}, {17, uint32(base.Agility)}, {18, uint32(base.Stamina)}, {19, uint32(base.Intelligence)}, {20, uint32(base.Sense)}, {21, uint32(base.Psychic)}, {27, character.health}, {1, character.maximumHealth()}, {123, uint32(base.FirstAid)}, {124, uint32(base.Treatment)}, {37, character.titleLevel()}} stats = append(stats, [2]uint32{368, uint32(max(1, character.profession))}, [2]uint32{130, uint32(base.MatterCreation)}, [2]uint32{131, uint32(base.TimeAndSpace)}) + stats = append(stats, [2]uint32{129, uint32(base.PsychologicalModification)}, [2]uint32{149, uint32(base.NanoInitiative)}) stats = append(stats, [2]uint32{51, uint32(character.aggDef)}, [2]uint32{161, uint32(base.ComputerLiteracy)}, [2]uint32{61, character.inventory.Credits}) stats = append(stats, [2]uint32{166, uint32(base.VehicleGround)}) stats = append(stats, [2]uint32{139, uint32(base.VehicleAir)}) diff --git a/server/world_actions.go b/server/world_actions.go @@ -62,6 +62,7 @@ func (server *server) handleMovement(client *worldClient, body []byte) error { server.mutex.Unlock() return nil } + previousPosition := character.position for i := range character.position { character.position[i] = math.Float32frombits(binary.BigEndian.Uint32(body[20+i*4:])) } @@ -77,13 +78,28 @@ func (server *server) handleMovement(client *worldClient, body []byte) error { client.forward = -1 case 2, 4: client.forward = 0 + case 5, 7: + client.strafing = true + case 6, 8: + client.strafing = false + case 9, 11: + client.turning = true + case 10, 12: + client.turning = false case 22, 23: character.running = binary.BigEndian.Uint32(body[16:20]) == 23 } + // Locomotion interrupts an admitted cast; rotation-only updates do not. + updates := make(map[*worldClient][][]byte) + action := binary.BigEndian.Uint32(body[16:20]) + if character.position != previousPosition || action == 1 || action == 3 || action == 5 || action == 7 || action == 13 { + server.abortNano_locked(client, client.movementStarted, updates) + } traceLog.Printf("Character %d action=%d position=%v", character.id, binary.BigEndian.Uint32(body[16:20]), character.position) destination := server.zoneDestination_locked(character, client) if destination != nil { server.mutex.Unlock() + server.sendCombatUpdates(updates) traceLog.Printf("Character %d zoning %d -> %d", client.id, playfield, destination.Playfield) return server.updateUser_locked(*destination) } @@ -92,6 +108,7 @@ func (server *server) handleMovement(client *worldClient, body []byte) error { return err } server.mutex.Unlock() + server.sendCombatUpdates(updates) server.broadcast(playfield, client.id, n3Packet(0x54111123, 50000, client.id, body[16:])) return nil } diff --git a/tools/data/extract_nano_learning.py b/tools/data/extract_nano_learning.py @@ -12,9 +12,9 @@ def main(): assert (client / 'version.id').read_text().strip() == '14.9.1' database = ao_database.Database(client) - # Retain the exact startup crystal and the program it uploads. + # Retain each supported startup crystal and the program it uploads. records = [] - for kind, identity in ((1000020, 43330), (1040005, 43324)): + for kind, identity in ((1000020, 43330), (1040005, 43324), (1000020, 29625), (1040005, 29618)): raw = database.read(kind, identity) item = extract_items.parse_item(raw, kind, identity) assert item['quality'] == 1 @@ -22,9 +22,9 @@ def main(): assert records[0]['record']['header_words'][0] == 51005 assert records[1]['record']['header_words'][0] == 51051 - # Matter Creation and Time and Space have distinct ability weights. + # Keep the supported nano skill and initiative ability weights. weights = {} - for stat in (130, 131): + for stat in (129, 130, 131, 149): raw = database.read(1000204, stat) weights[stat] = dict(weights=struct.unpack('<6i', raw), payload_hex=raw.hex(), payload_sha256=hashlib.sha256(raw).hexdigest())