aorecomp

Anarchy Online classic in the browser

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


commit edf7c0f9e64c620c4db33fcd36597d106ae8dc79
parent db258a21b50b383f00affdfe2d18304c98d05bd4
Author: anon <anon@example.com>
Date:   Thu,  5 Nov 2026 22:10:22 +0000

Support complete Meta-Physicist starter Mind Pain effects

Diffstat:
MTODO.md | 3++-
Mdocs/early-shop-stock.md | 7++++---
Mdocs/nano-direct-damage.md | 4+++-
Mdocs/nano-initiative-debuffs.md | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Aserver/browser_mind_pain_test.go | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/initiative_debuff_test.go | 118+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Aserver/mind_pain_test.go | 190+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/nano_buffs.go | 2+-
Mserver/nano_damage.go | 26++++++++++++++------------
Atools/client/test_mind_pain.mjs | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 592 insertions(+), 72 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -120,7 +120,8 @@ research separately. More screenshots and test cases do not count as new gamepla supported contracts; all 36 pass native buy/sell, cancel, upload/cast and reconnect/cold recovery, with every row covered by server regressions. 123 placements remain empty and visibly identify unsupported purchases while - retaining loot sales. Meta-Physicist combat nanos and pet attacks, + retaining loot sales. The Meta-Physicist starter Mind Pain now executes its + complete damage and six-skill debuff; useful shop upgrades and pet attacks, Engineer robots and other unfinished profession essentials remain open, alongside the bounded ordinary-play affordability check. New mission offers now pay an explicit provisional 500 credits per selected mission level; diff --git a/docs/early-shop-stock.md b/docs/early-shop-stock.md @@ -305,9 +305,10 @@ or affordability requirements. ### Remaining profession essentials Stock is not a claim that each profession has its complete early combat path. -Engineer Feeble Automaton (43329 -> 43325) is not supported. Meta-Physicist Mind -Pain (29193 -> 29114) has an additional linked effect and fails complete-contract -admission; Lesser Anger Manifestation can summon/follow but lacks pet attack +Engineer Feeble Automaton (43329 -> 43325) is not supported. Meta-Physicist +[Mind Pain](nano-initiative-debuffs.md#meta-physicist-starter-mind-pain) +(29193 -> 29114) now supports its complete damage and linked six-skill debuff. +Lesser Anger Manifestation can summon/follow but lacks pet attack commands. These are concrete A5/A7 dependencies. Trader Weak Delayed Health Payment (43378 -> 43374) is also unsupported, though its separate starter Weak Health Funnel is supported. None of those incomplete crystals is sold here. diff --git a/docs/nano-direct-damage.md b/docs/nano-direct-damage.md @@ -53,7 +53,9 @@ one point less. For example Fire Stream reserves 14 and Corrosive Spray 11. Ice Flechette 28612 additionally supports its full Hit followed by CastNano 53051 of 144632: four initiative debuffs for 6000 cs. Its child installation, refresh, expiry and persistence are covered in -[initiative debuffs](nano-initiative-debuffs.md). Other secondary contracts and +[passive debuffs](nano-initiative-debuffs.md). Mind Pain 29114 and Mind Scream +29298 also support their complete six-nano-skill children 144616/144619. +Other secondary contracts and area programs such as Radiation Pulse 28631 remain excluded. An additional 27 complete Hit plus TauntNPC programs now share the instant damage path; see [NPC threat and taunts](npc-threat.md) for their separate census and policy. diff --git a/docs/nano-initiative-debuffs.md b/docs/nano-initiative-debuffs.md @@ -1,4 +1,4 @@ -# Ice Flechette and hostile initiative effects +# Hostile initiative and nano-skill effects Ice Flechette 28612 now executes its complete original contract: 13..17 cold damage and child nano 144632, which lowers Melee, Ranged, Physical and Nano @@ -12,17 +12,18 @@ range is 25 metres. The direct-damage reader accepts one immediate health Hit, optionally followed by one unconditional selected-target CastNano whose entire child contract is -supported. The child reader requires a passive hostile nano, four distinct -negative initiative Modifies, one tick, no interval or function conditions, +supported. The child reader requires a passive hostile nano, either four distinct +negative initiative Modifies or all six negative nano-skill Modifies, one tick, +no interval or function conditions, the complete attack/zero-resistance dictionaries, and no extra sections or casting action. Unknown or partial child effects close the parent and crystal as well. No program-ID dispatch or damage-only fallback is used. The original resource census finds two programs containing only negative initiative Modifies. Red Tape 30090 also has an area/casting contract and fails -this passive-child reader. Only child 144632 and its parent 28612 pass. The -single-Hit/initiative-child subset is consequently 33 single-Hit programs plus -Ice Flechette, with 32 ordinary single-program crystal uploaders in total. +this passive-child reader. The full passive-child census admits Ice Flechette +(28612 -> 144632), Mind Pain (29114 -> 144616), and Mind Scream +(29298 -> 144619). Mixed, incomplete and duplicate stat sets are rejected. The additional complete Hit plus TauntNPC family is covered in [NPC threat and taunts](npc-threat.md). This does not admit arbitrary CastNano chains, hostile player casting, area @@ -133,3 +134,63 @@ occurred. The read-only probes and transport/database checks are retained in Cleanup removed only owned fixtures. Hashes of every unrelated table row were unchanged, foreign keys and SQLite integrity passed, and unrelated players remained. The shared preview remains a single process on the default ports. + +## Meta-Physicist starter Mind Pain + +Original startup crystal 29193 uploads Mind Pain 29114. Both require visual +profession 12, Matter Creation greater than 8 and Psychological Modification +greater than 6. Its original Hit deals 9..23 energy damage at a 20-metre range; +raw cost 15 debits 14 under the shared native float policy. Attack/recharge are +261/100 centiseconds (stats 294/210). Its CastNano child 144616 applies -5 to +Matter Metamorphosis, +Biological Metamorphosis, Psychological Modification, Sensory Improvement, +Matter Creation and Time and Space for six seconds, with strain 221 and NCU 1. +The hostile child does not consume player NCU. Damage, all six penalties, cost +and recharge share the existing atomic transaction. Refresh leaves one child; +expiry removes all six penalties. + +The original records are in `server/gamedata/items/items_001.yaml` (crystal), +`items_167.yaml` (parent), and `items_171.yaml` (child). Payload SHA-256: + +| Resource | ID | SHA-256 | +| --- | --- | --- | +| Crystal | 29193 | `fcd566eb6763a36bf2fb5beea7f40e1df4a222e50c799036e1fa1cf97d046ec4` | +| Parent | 29114 | `594303ddf15d3341c4b14033d96985d7e7e950a2d5a2e0aa4bbc2e7fdfe264c4` | +| Child | 144616 | `584fbb458c82c5cb4bf0f84730f3e5c63af5fd47add0205fd3421b4bfbd744f0` | + +The same complete shape admits Mind Scream 29298 with child 144619: 78..146 +energy damage, -20 to all six skills for nine seconds, and raw cost 78 (debit 77). +Crystal 29395 is QL37 and requires MC >182 / PM >158, so it is not early shop +stock. The server regression uploads and executes this additionally admitted +contract; no new shop rows or arbitrary child chains are introduced. + +`TestMindPainUploadAndCastEnforceBothSkillsAndProfession` covers each strict +skill boundary and profession. `TestMindPainDamageDebuffsRefreshExpiryAndColdRestore` +checks damage, six effective skill changes, no stacking, expiry and cold recovery. +Rejected, silently ignored and failed-commit child writes leave damage, resources +and modifiers unchanged and allow retry. The passive-child mutation regression +checks all three admitted parents and rejects incomplete contracts at both +upload and cast admission. Existing Ice Flechette lifecycle and failure tests +remain applicable to the shared transaction. + +`TestCreatedMetaPhysicistCanUploadMindPainAtLevelOne` uses ordinary Solitus +creation, the issued crystal, normal IP/cap-checked MC 8 / PM 6 training, and idle +regeneration advanced on a controlled clock. No experience or credits are earned +by this fixture. This closes the starter nano admission gap, not pet attack, +useful shop upgrades, NPC spellcasting or the full A5/A7 progression gates. + +`TestBrowserMindPain` and `tools/client/test_mind_pain.mjs` use that created +level-one character with 1474 IP remaining and 32 recovered nano, plus a nearby +controlled 100-HP Leet. Real inventory right-click, native school selection, +Tab targeting and program right-click upload and cast the starter nano. The +passing capture shows 17 energy damage, 14 nano spent, one delivered child, +all six server penalties, explicit removal at expiry, and unchanged ownership +after reconnect and cold recovery. Refresh is covered by the server regression; +the browser does not claim a refresh check. An initial repeat-click fixture +arrived while the native client still reported a busy nano action. + +Fifteen focused server test roots pass, including the existing Ice Flechette +checks. Native verification passed in 27.54 seconds with artifacts under +`local/alpha-mind-pain/20261105-140914/`; the initial rejection reproduction, +regressions and browser logs are in `local/alpha-mind-pain/`. The test server +and browser were closed. This adds no new historical server-policy evidence. diff --git a/server/browser_mind_pain_test.go b/server/browser_mind_pain_test.go @@ -0,0 +1,156 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func newCreatedMindPainWorld(t *testing.T) *server { + t.Helper() + world := newTestServer(t) + fields := creationForm() + fields.Set("profession", "12") + if response := creationRequest(world, accountVisitor(t, world), fields); response.Code != http.StatusNoContent { + t.Fatal(response.Code, response.Body.String()) + } + player := world.characters[2] + client := &worldClient{id: 2, conn: &combatTestConn{}, target: true, ready: true} + world.clients[2] = client + if player.level != 1 || player.experience != 0 || player.inventory.Credits != 0 || player.stats.ImprovementPoints != 1500 { + t.Fatal("fixture did not use ordinary level-one creation") + } + + // Use the normal cap/cost checks, then advance idle recovery to a full pool. + trained := player.baseStats() + trained.NanoAiding.MatterCreation, trained.NanoAiding.PsychologicalModification = 8, 6 + request := skillTrainingRequest(trained) + binary.BigEndian.PutUint32(request[28:32], player.id) + if err := world.handleSkillTraining(client, request[20:]); err != nil { + t.Fatal(err) + } + if player.stats.NanoAiding.MatterCreation != 8 || player.stats.NanoAiding.PsychologicalModification != 6 || player.stats.ImprovementPoints != 1474 { + t.Fatal("starter skills did not fit the level-one caps and IP budget", player.stats) + } + start := time.Now() + client.regenerationAt = start + for second := 2; second <= 600 && player.nano < player.maximumNano(); second += 2 { + world.advanceRegeneration(start.Add(time.Duration(second) * time.Second)) + } + if player.nano != player.maximumNano() { + t.Fatal("idle regeneration did not recover the starter pool") + } + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + return world +} + +func TestCreatedMetaPhysicistCanUploadMindPainAtLevelOne(t *testing.T) { + world := newCreatedMindPainWorld(t) + player := world.characters[2] + before := slices.Clone(player.inventory.Items) + if before[5].Template != 29193 || before[5].Slot != 69 { + t.Fatal("ordinary starter inventory omitted Mind Pain") + } + + if err := world.handleOwnedItemUse(world.clients[2], backpackUseRequest(2, 69, 1)[20:]); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t).characters[2] + + if !slices.Equal(cold.inventory.LearnedNanos, []uint32{29114}) || len(cold.inventory.Items) != len(before)-1 || + cold.stats.NanoAiding.MatterCreation != 8 || cold.stats.NanoAiding.PsychologicalModification != 6 || cold.level != 1 || cold.experience != 0 { + t.Fatal("ordinary trained start could not persist its uploaded program", cold.inventory) + } + t.Logf("Level-one Solitus: %d IP remaining, %d/%d nano", player.stats.ImprovementPoints, player.nano, player.maximumNano()) +} + +func TestBrowserMindPain(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for the Meta-Physicist starter crystal") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/alpha-mind-pain", time.Now().Format("20060102-150405")) + world := newCreatedMindPainWorld(t) + delete(world.clients, 2) + player := world.characters[2] + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("mind-pain"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + // Keep one original level-one Leet close to the created character. + var target *character + for _, actor := range world.characters { + if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (target == nil || actor.id < target.id) { + target = actor + } + } + if target == nil { + t.Fatal("missing original Leet fixture") + } + forward, _ := bodyAxes(player.rotation) + target.position = [3]float32{player.position[0] + 2*forward[0], player.position[1], player.position[2] + 2*forward[2]} + target.health = 100 + world.combatRoll = landedCombatRoll + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + defer world.mutex.Unlock() + var effects []uint32 + var bonuses []int32 + for _, effect := range target.activeNanos { + effects = append(effects, effect.program) + } + for _, stat := range []uint32{122, 127, 128, 129, 130, 131} { + bonuses = append(bonuses, target.nanoBonus(stat)) + } + json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "target": target.id, "health": target.health, + "nano": player.nano, "reserved": player.nanoReserved, "recharging": time.Now().Before(player.nanoRechargeUntil), + "effects": effects, "bonuses": bonuses, "level": player.level, "ip": player.stats.ImprovementPoints}) + }) + host := httptest.NewServer(mux) + defer host.Close() + defer closeTestSessions(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + clock := time.NewTicker(time.Second / 60) + defer clock.Stop() + for { + select { + case now := <-clock.C: + world.advancePlayerMovement(now) + world.advanceNanos(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_mind_pain.mjs"), host.URL, output) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + if err := command.Run(); err != nil { + t.Fatal(err) + } + closeTestSessions(t, world) + cold := newTestInventoryServer(t) + if !slices.Equal(cold.characters[2].inventory.LearnedNanos, []uint32{29114}) || len(cold.characters[target.id].activeNanos) != 0 || cold.characters[2].nano != player.maximumNano()-14 { + t.Fatal("starter upload, cast cost or expired child changed during cold recovery") + } + t.Logf("Browser artifacts: %s", output) +} diff --git a/server/initiative_debuff_test.go b/server/initiative_debuff_test.go @@ -35,11 +35,11 @@ func castIceFlechette(t *testing.T, world *server) time.Time { return at } -func TestInitiativeDebuffCatalogAdmitsOnlyTheCompletePassiveChild(t *testing.T) { +func TestPassiveDebuffCatalogAdmitsOnlyCompleteChildren(t *testing.T) { var children, parents []uint32 for program := range gamedata.NanoTemplates { - if initiativeDebuffNano(program) { + if passiveDebuffNano(program) { children = append(children, program) } if directDamageNano(program) != nil && damageNanoSecondary(program) != 0 { @@ -47,7 +47,9 @@ func TestInitiativeDebuffCatalogAdmitsOnlyTheCompletePassiveChild(t *testing.T) } } - if !slices.Equal(children, []uint32{144632}) || !slices.Equal(parents, []uint32{28612}) || nanoCrystalProgram(28815) != 28612 || + slices.Sort(children) + slices.Sort(parents) + if !slices.Equal(children, []uint32{144616, 144619, 144632}) || !slices.Equal(parents, []uint32{28612, 29114, 29298}) || nanoCrystalProgram(28815) != 28612 || nanoCrystalProgram(29193) != 29114 || statBuffNano(144632) || directDamageNano(144632) != nil || nanoStat(144632, 75) != 144632 || nanoStat(144632, 8) != 6000 || nanoStat(144632, 54) != 1 { t.Fatal("compound admission or passive child defaults changed", children, parents) } @@ -56,6 +58,9 @@ func TestInitiativeDebuffCatalogAdmitsOnlyTheCompletePassiveChild(t *testing.T) t.Fatal("original signed initiative modifier changed", stat) } } + if statBuffNano(144616) || directDamageNano(144616) != nil || nanoStat(144616, 75) != 221 || nanoStat(144616, 8) != 600 || nanoStat(144616, 54) != 1 { + t.Fatal("Mind Pain's passive child metadata changed") + } } func TestIceFlechetteUploadAndCastEnforceItsAuthoredRequirements(t *testing.T) { @@ -317,54 +322,71 @@ func TestIceFlechetteDeathRemovesTheChildAndRespawnsWithoutIt(t *testing.T) { } } -func TestIceFlechetteRejectsIncompleteSecondaryContracts(t *testing.T) { - for _, scenario := range []string{"missing modifier", "duplicate initiative", "other stat", "positive", "periodic", "conditional", "self", "area", "other function", "opaque", "other flags", "unknown section"} { - t.Run(scenario, func(t *testing.T) { - original := gamedata.NanoTemplates[144632] - child := *original - child.Stats, child.Sections = slices.Clone(child.Stats), slices.Clone(child.Sections) - functions := slices.Clone(*child.Sections[2].Functions) - functions[0].Arguments = slices.Clone(functions[0].Arguments) - child.Sections[2].Functions = &functions - value := int32(0) - switch scenario { - case "missing modifier": - functions = functions[:3] - case "duplicate initiative": - value = 118 - functions[0].Arguments[0].Integer = &value - case "other stat": - value = 156 - functions[0].Arguments[0].Integer = &value - case "positive": - value = 6 - functions[0].Arguments[1].Integer = &value - case "periodic": - functions[0].TickCount = 2 - case "conditional": - functions[0].Requirements = []gamedata.ItemRequirement{{Stat: 54, Value: 20, Operator: 2}} - case "self": - functions[0].Target = 2 - case "area", "other flags": - for index, stat := range child.Stats { - if scenario == "area" && stat[0] == 405 || scenario == "other flags" && stat[0] == 0 { - child.Stats[index][1] = 4 +func TestPassiveDebuffRejectsIncompleteSecondaryContracts(t *testing.T) { + for _, fixture := range []struct { + name string + child, parent, crystal uint32 + }{ + {"Ice Flechette", 144632, 28612, 28815}, + {"Mind Pain", 144616, 29114, 29193}, + {"Mind Scream", 144619, 29298, 29395}, + } { + t.Run(fixture.name, func(t *testing.T) { + for _, scenario := range []string{"missing modifier", "duplicate stat", "other stat", "mixed set", "positive", "periodic", "conditional", "self", "area", "other function", "opaque", "other flags", "unknown section"} { + t.Run(scenario, func(t *testing.T) { + original := gamedata.NanoTemplates[fixture.child] + child := *original + child.Stats, child.Sections = slices.Clone(child.Stats), slices.Clone(child.Sections) + functions := slices.Clone(*child.Sections[2].Functions) + functions[0].Arguments = slices.Clone(functions[0].Arguments) + child.Sections[2].Functions = &functions + value := int32(0) + switch scenario { + case "missing modifier": + functions = functions[:len(functions)-1] + case "duplicate stat": + value = *functions[1].Arguments[0].Integer + functions[0].Arguments[0].Integer = &value + case "mixed set": + value = 130 + if fixture.child != 144632 { + value = 118 + } + functions[0].Arguments[0].Integer = &value + case "other stat": + value = 156 + functions[0].Arguments[0].Integer = &value + case "positive": + value = 6 + functions[0].Arguments[1].Integer = &value + case "periodic": + functions[0].TickCount = 2 + case "conditional": + functions[0].Requirements = []gamedata.ItemRequirement{{Stat: 54, Value: 20, Operator: 2}} + case "self": + functions[0].Target = 2 + case "area", "other flags": + for index, stat := range child.Stats { + if scenario == "area" && stat[0] == 405 || scenario == "other flags" && stat[0] == 0 { + child.Stats[index][1] = 4 + } + } + case "other function": + functions[0].ID = 53051 + case "opaque": + functions[0].Arguments[1].Integer = nil + case "unknown section": + child.Sections = append(child.Sections, gamedata.ItemSection{Type: 99}) } - } - case "other function": - functions[0].ID = 53051 - case "opaque": - functions[0].Arguments[1].Integer = nil - case "unknown section": - child.Sections = append(child.Sections, gamedata.ItemSection{Type: 99}) - } - gamedata.NanoTemplates[144632] = &child - t.Cleanup(func() { gamedata.NanoTemplates[144632] = original }) + gamedata.NanoTemplates[fixture.child] = &child + t.Cleanup(func() { gamedata.NanoTemplates[fixture.child] = original }) - accepted, parent, crystal := initiativeDebuffNano(144632), directDamageNano(28612), nanoCrystalProgram(28815) + accepted, parent, crystal := passiveDebuffNano(fixture.child), directDamageNano(fixture.parent), nanoCrystalProgram(fixture.crystal) - if accepted || parent != nil || crystal != 0 { - t.Fatal("incomplete secondary allowed a partial Ice Flechette upload or cast", scenario) + if accepted || parent != nil || crystal != 0 { + t.Fatal("incomplete secondary allowed a partial upload or cast", scenario) + } + }) } }) } diff --git a/server/mind_pain_test.go b/server/mind_pain_test.go @@ -0,0 +1,190 @@ +package main + +import ( + "encoding/binary" + "slices" + "testing" + "time" +) + +func newMindPainWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + world, conn := newDirectDamageWorld(t, directDamageNanoFixture{Crystal: 29193, Profession: 12}) + if err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + if !slices.Equal(world.characters[1].inventory.LearnedNanos, []uint32{29114}) || len(world.characters[1].inventory.Items) != 0 { + t.Fatal("Mind Pain's starter crystal did not upload its complete program") + } + conn.packets = nil + return world, conn +} + +func castMindPain(t *testing.T, world *server) time.Time { + t.Helper() + client := world.clients[1] + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29114})[20:]); err != nil { + t.Fatal(err) + } + if client.nanoCast == nil { + t.Fatal("qualified Mind Pain was rejected") + } + at := client.nanoCast.readyAt.Add(time.Nanosecond) + world.advanceNanos(at) + return at +} + +func TestMindPainUploadAndCastEnforceBothSkillsAndProfession(t *testing.T) { + for _, scenario := range []struct { + name string + profession uint16 + matter uint16 + psycho uint16 + accepted bool + }{ + {"matter equality", 12, 8, 7, false}, + {"psycho equality", 12, 9, 6, false}, + {"both above", 12, 9, 7, true}, + {"other profession", 11, 9, 7, false}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, _ := newDirectDamageWorld(t, directDamageNanoFixture{Crystal: 29193, Profession: 12}) + player, client := world.characters[1], world.clients[1] + player.profession = scenario.profession + player.stats.NanoAiding.MatterCreation = scenario.matter + player.stats.NanoAiding.PsychologicalModification = scenario.psycho + + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + learned := slices.Equal(player.inventory.LearnedNanos, []uint32{29114}) + // A learned entry cannot bypass the cast's own requirements. + player.inventory.LearnedNanos = []uint32{29114} + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29114})[20:]); err != nil { + t.Fatal(err) + } + + if learned != scenario.accepted || (client.nanoCast != nil) != scenario.accepted || + scenario.accepted && (len(player.inventory.Items) != 0 || player.nano != 49986 || player.nanoReserved != 14) || + !scenario.accepted && (len(player.inventory.Items) != 1 || player.nano != 50000 || player.nanoReserved != 0) { + t.Fatal("upload or casting ignored Mind Pain's requirements", player.nano, player.nanoReserved) + } + }) + } +} + +func TestMindPainDamageDebuffsRefreshExpiryAndColdRestore(t *testing.T) { + world, conn := newMindPainWorld(t) + player, target := world.characters[1], world.characters[1000000] + var skills []int32 + for _, stat := range []uint32{122, 127, 128, 129, 130, 131} { + value, _ := target.effectiveStat(stat) + skills = append(skills, value) + } + + castMindPain(t, world) + firstHealth := target.health + firstDeadline := target.activeNanos[0].expiresAt + cold := newTestInventoryServer(t).characters[1000000] + player.nanoRechargeUntil = time.Time{} + refreshed := castMindPain(t, world) + deadline := target.activeNanos[0].expiresAt + world.advanceNanos(deadline.Add(-time.Nanosecond)) + + if firstHealth < 77 || firstHealth > 91 || firstHealth-target.health < 9 || firstHealth-target.health > 23 || + player.nano != 49972 || player.nanoReserved != 0 || len(target.activeNanos) != 1 || len(cold.activeNanos) != 1 || + cold.activeNanos[0].program != 144616 || cold.activeNanos[0].remaining != 6*time.Second || cold.usedNCU() != 0 || + !deadline.Equal(refreshed.Add(6*time.Second)) || !deadline.After(firstDeadline) { + t.Fatal("damage, debit, duration, refresh or cold recovery changed", player.nano, target.activeNanos, cold.activeNanos) + } + for index, stat := range []uint32{122, 127, 128, 129, 130, 131} { + value, _ := target.effectiveStat(stat) + if target.nanoBonus(stat) != -5 || cold.nanoBonus(stat) != -5 || value != skills[index]-5 { + t.Fatal("complete six-skill debuff was omitted or stacked", stat) + } + } + before := len(conn.packets) + world.advanceNanos(deadline) + world.advanceNanos(deadline.Add(time.Second)) + restored := newTestInventoryServer(t).characters[1000000] + if len(target.activeNanos) != 0 || len(restored.activeNanos) != 0 || len(conn.packets) != before+1 || + binary.BigEndian.Uint32(conn.packets[before][29:33]) != 65 || binary.BigEndian.Uint32(conn.packets[before][45:49]) != 144616 { + t.Fatal("expiry did not remove and persist the child exactly once") + } + for index, stat := range []uint32{122, 127, 128, 129, 130, 131} { + value, _ := target.effectiveStat(stat) + if target.nanoBonus(stat) != 0 || value != skills[index] { + t.Fatal("expiry retained a skill penalty", stat) + } + } +} + +func TestMindPainFailedChildWriteRollsBackDamageAndCost(t *testing.T) { + for _, statement := range []string{ + "CREATE TRIGGER fail_mind BEFORE INSERT ON active_nanos BEGIN SELECT RAISE(FAIL, 'child'); END", + "CREATE TRIGGER fail_mind BEFORE INSERT ON active_nanos BEGIN SELECT RAISE(IGNORE); END", + "CREATE TABLE pending_mind (id INTEGER REFERENCES characters(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_mind AFTER INSERT ON active_nanos BEGIN INSERT INTO pending_mind VALUES (999999); END", + } { + t.Run(statement, func(t *testing.T) { + world, conn := newMindPainWorld(t) + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + + client := world.clients[1] + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29114})[20:]); err != nil || client.nanoCast == nil { + t.Fatal("Mind Pain did not start", err) + } + conn.packets = nil + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + cold := newTestInventoryServer(t) + + for _, state := range []*server{world, cold} { + if state.characters[1].nano != 50000 || state.characters[1].nanoReserved != 0 || state.characters[1000000].health != 100 || len(state.characters[1000000].activeNanos) != 0 { + t.Fatal("failed child write published partial damage, cost or modifiers") + } + } + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) != 108 { + t.Fatal("failed cast published success") + } + } + if _, err := world.db.Exec("DROP TRIGGER fail_mind"); err != nil { + t.Fatal(err) + } + castMindPain(t, world) + if world.characters[1].nano != 49986 || world.characters[1000000].health >= 100 || len(world.characters[1000000].activeNanos) != 1 { + t.Fatal("cast could not retry after rollback") + } + }) + } +} + +func TestMindScreamExecutesTheSameCompleteSixSkillContract(t *testing.T) { + world, _ := newDirectDamageWorld(t, directDamageNanoFixture{Crystal: 29395, Profession: 12}) + player, target, client := world.characters[1], world.characters[1000000], world.clients[1] + target.health = 1000 + + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + if !slices.Equal(player.inventory.LearnedNanos, []uint32{29298}) { + t.Fatal("Mind Scream crystal did not upload") + } + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29298})[20:]); err != nil || client.nanoCast == nil { + t.Fatal("Mind Scream did not start", err) + } + at := client.nanoCast.readyAt.Add(time.Nanosecond) + world.advanceNanos(at) + cold := newTestInventoryServer(t).characters[1000000] + + if target.health < 854 || target.health > 922 || player.nano != 49923 || len(cold.activeNanos) != 1 || + cold.activeNanos[0].program != 144619 || cold.activeNanos[0].remaining != 9*time.Second || !target.activeNanos[0].expiresAt.Equal(at.Add(9*time.Second)) { + t.Fatal("Mind Scream's damage, cost or duration changed", target.health, player.nano, cold.activeNanos) + } + for _, stat := range []uint32{122, 127, 128, 129, 130, 131} { + if target.nanoBonus(stat) != -20 || cold.nanoBonus(stat) != -20 { + t.Fatal("Mind Scream omitted a skill penalty", stat) + } + } +} diff --git a/server/nano_buffs.go b/server/nano_buffs.go @@ -320,7 +320,7 @@ func (server *server) loadActiveNanos() error { } periodic := damageOverTimeNano(effect.program) healing := healingOverTimeNano(effect.program) - if effect.program != 157490 && !statBuffNano(effect.program) && !initiativeDebuffNano(effect.program) && controlNano(effect.program) == nil && periodic == nil && healing == nil || effect.remaining < 0 || server.characters[id] == nil { + if effect.program != 157490 && !statBuffNano(effect.program) && !passiveDebuffNano(effect.program) && controlNano(effect.program) == nil && periodic == nil && healing == nil || effect.remaining < 0 || server.characters[id] == nil { return fmt.Errorf("character %d has an unsupported active nano %d", id, effect.program) } if periodic != nil { diff --git a/server/nano_damage.go b/server/nano_damage.go @@ -160,7 +160,7 @@ func hostileHitNano(program uint32, periodic bool) *gamedata.ItemFunction { } switch secondary.ID { case 53051: - if len(secondary.Arguments) != 1 || secondary.Arguments[0].Integer == nil || !initiativeDebuffNano(uint32(*secondary.Arguments[0].Integer)) { + if len(secondary.Arguments) != 1 || secondary.Arguments[0].Integer == nil || !passiveDebuffNano(uint32(*secondary.Arguments[0].Integer)) { return nil } case 53117: @@ -217,7 +217,7 @@ func nanoTaunt(program uint32) int32 { return 0 } -func initiativeDebuffNano(program uint32) bool { +func passiveDebuffNano(program uint32) bool { definition := gamedata.NanoTemplates[program] if definition == nil || definition.RecordType != 1040005 || definition.HeaderWords[0] != 51051 || definition.Undecoded != nil || itemStat(definition, 0) != 0x80018000 || itemStat(definition, 30) != 0 || itemStat(definition, 76) != 0 || @@ -249,11 +249,17 @@ func initiativeDebuffNano(program uint32) bool { total += weight[1] } section := definition.Sections[2] - if total != 100 || section.Type != 2 || section.Subtype != 0 || section.Functions == nil || len(*section.Functions) != 4 { + if total != 100 || section.Type != 2 || section.Subtype != 0 || section.Functions == nil { return false } - // One signed Modify for each initiative; reject partial or repeated effects. + // Admit complete initiative or nano-skill sets, without mixing the two. + stats := []int32{118, 119, 120, 149} + if len(*section.Functions) == 6 { + stats = []int32{122, 127, 128, 129, 130, 131} + } else if len(*section.Functions) != 4 { + return false + } var seen uint32 for _, function := range *section.Functions { if function.ID != 53045 || function.HeaderWords != [2]uint32{0, 4} || function.ArgumentHeader != 9 || function.Target != 3 || @@ -261,19 +267,15 @@ func initiativeDebuffNano(program uint32) bool { function.Arguments[0].Integer == nil || function.Arguments[1].Integer == nil || *function.Arguments[1].Integer >= 0 { return false } - var bit uint32 - switch *function.Arguments[0].Integer { - case 118, 119, 120: - bit = 1 << (*function.Arguments[0].Integer - 118) - case 149: - bit = 8 - default: + index := slices.Index(stats, *function.Arguments[0].Integer) + if index == -1 { return false } + bit := uint32(1) << index if seen&bit != 0 { return false } seen |= bit } - return seen == 15 + return seen == (1<<len(stats))-1 } diff --git a/tools/client/test_mind_pain.mjs b/tools/client/test_mind_pain.mjs @@ -0,0 +1,85 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import {GameTest} from './game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const [url, output] = process.argv.slice(2); +const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [ + '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +let game; +const evidence = {}; +try { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'mind-pain', url}]); + const page = await context.newPage(); + game = await GameTest.attach(page); + const server = async () => (await page.request.get(url + '/test-state')).json(); + const waitServer = (label, predicate) => game.waitFor(label, async () => predicate(await server())); + const cell = (type, slot) => game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === type && cell.identity[1] === slot && !cell.dummy); + const use = async source => { + assert(source, 'expected native inventory or program cell is present'); + await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2, 'right'); + }; + await page.goto(url); + await game.ready(); + if (!game.state.camera.firstPerson) await game.key('F8'); + evidence.initial = await server(); + assert.equal(evidence.initial.level, 1); + await game.key('KeyI'); + await game.wait('starter crystal visible', () => cell(104, 53)); + await use(cell(104, 53)); + await waitServer('starter Mind Pain uploaded', state => state.inventory.LearnedNanos?.includes(29114)); + evidence.uploaded = await server(); + assert.deepEqual(evidence.uploaded.inventory.Items, evidence.initial.inventory.Items.filter(item => item.Template !== 29193)); + await page.keyboard.press('Control+8'); + for (const [x, y] of [[865, 76], [974, 76], [865, 96], [927, 96], [987, 96]]) { + if (cell(53019, 29114)) break; + await game.click(x, y); + await game.snapshot(); + } + await game.key('Tab'); + await game.wait('native Tab selects Leet', state => state.selected[0] === 50000 && state.selected[1] === evidence.initial.target); + + await waitServer('nano recharge completed', state => !state.recharging); + const before = await server(); + const sequence = game.sequence; + await use(cell(53019, 29114)); + await waitServer('Mind Pain damages and debuffs target', state => state.health < before.health && state.reserved === 0); + const after = evidence.cast = await server(); + assert(before.health - after.health >= 9 && before.health - after.health <= 23); + assert.equal(after.nano, before.nano - 14); + assert.deepEqual(after.effects, [144616]); + assert.deepEqual(after.bonuses, [-5, -5, -5, -5, -5, -5]); + await game.wait('original child effect delivered', () => game.events.some(event => { + if (event.sequence <= sequence || event.direction !== 'framereceived' || event.opcode !== '5e477770') return false; + const packet = Buffer.from(event.hex, 'hex'); + return packet.readUInt32BE(29) === 177 && packet.readUInt32BE(37) === 144616; + })); + await game.wait('native target health matches server', state => + state.actors.find(actor => actor.type === 50000 && actor.id === after.target)?.stats[27] === after.health); + await game.save(output + '/cast'); + await waitServer('six-second child expires', state => !state.effects?.length); + evidence.expired = await server(); + assert.deepEqual(evidence.expired.bonuses, [0, 0, 0, 0, 0, 0]); + await game.wait('child removal delivered', () => game.events.some(event => { + if (event.direction !== 'framereceived' || event.opcode !== '5e477770') return false; + const packet = Buffer.from(event.hex, 'hex'); + return packet.readUInt32BE(29) === 65 && packet.readUInt32BE(45) === 144616; + })); + await page.reload(); + await game.ready(); + evidence.reconnected = await server(); + assert.deepEqual(evidence.reconnected.inventory, evidence.uploaded.inventory); + assert.equal(evidence.reconnected.nano, evidence.initial.nano - 14); + assert.deepEqual(game.errors, []); + console.log('PASS: level-one Mind Pain upload, damage, child delivery, expiry and reconnect'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n'); + if (game) await game.save(output + '/final'); + } finally { await browser.close(); } +}