aorecomp

Anarchy Online classic in the browser

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


server/self_nano_test.go (13328B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	_ "embed"
      6 	"encoding/binary"
      7 	"encoding/json"
      8 	"fmt"
      9 	"slices"
     10 	"testing"
     11 	"time"
     12 )
     13 
     14 //go:embed testdata/self-and-critical-nanos.json
     15 var selfAndCriticalNanoData []byte
     16 
     17 type selfAndCriticalNanoFixture struct {
     18 	Program, Crystal, Quality, Profession uint32
     19 	Modifiers                             [][2]int32
     20 	Gates                                 [][2]uint32
     21 	NCU, Duration                         uint32
     22 	NanoCost                              uint32 `json:"nano_cost"`
     23 	SelfOnly                              bool   `json:"self_only"`
     24 }
     25 
     26 func selfAndCriticalNanoFixtures(t *testing.T) []selfAndCriticalNanoFixture {
     27 	t.Helper()
     28 	var fixtures []selfAndCriticalNanoFixture
     29 	if err := json.Unmarshal(selfAndCriticalNanoData, &fixtures); err != nil {
     30 		t.Fatal(err)
     31 	}
     32 	return fixtures
     33 }
     34 
     35 func newSelfNanoWorld(t *testing.T) (*server, *combatTestConn) {
     36 	t.Helper()
     37 	world, conn := newSkillNanoWorld(t)
     38 	player := world.characters[1]
     39 	player.stats.NanoAiding.PsychologicalModification, player.stats.NanoAiding.SensoryImprovement = 1000, 1000
     40 	if err := world.saveUser(player); err != nil {
     41 		t.Fatal(err)
     42 	}
     43 	return world, conn
     44 }
     45 
     46 func TestSelfAndCriticalNanosUploadCastRestoreAndCancelCompleteContracts(t *testing.T) {
     47 	for _, fixture := range selfAndCriticalNanoFixtures(t) {
     48 		t.Run(fmt.Sprint(fixture.Program), func(t *testing.T) {
     49 			world, conn := newSelfNanoWorld(t)
     50 			player, client := world.characters[1], world.clients[1]
     51 			player.level, player.profession = 200, uint16(fixture.Profession)
     52 			if err := world.saveUser(player); err != nil {
     53 				t.Fatal(err)
     54 			}
     55 			if granted, err := world.grantItem(player, fixture.Crystal); err != nil || !granted {
     56 				t.Fatal(granted, err)
     57 			}
     58 			trained := player.baseStats()
     59 			before := make(map[uint32]int32)
     60 			for _, field := range trained.trainingStats() {
     61 				before[field.stat], _ = player.effectiveStat(field.stat)
     62 			}
     63 
     64 			if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil {
     65 				t.Fatal(err)
     66 			}
     67 			if len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[1][37:41]) != fixture.Quality {
     68 				t.Fatal("original crystal was rejected or changed quality")
     69 			}
     70 			completed := castTestBuff(t, world, 1, 1, fixture.Program)
     71 			cold := newTestInventoryServer(t).characters[1]
     72 
     73 			if player.baseStats() != trained || cold.baseStats() != trained || player.usedNCU() != fixture.NCU || cold.usedNCU() != fixture.NCU ||
     74 				player.nano != 50000-fixture.NanoCost || cold.nano != player.nano || player.health != 20 || cold.health != 20 ||
     75 				len(player.activeNanos) != 1 || len(cold.activeNanos) != 1 || len(cold.inventory.Items) != 2 ||
     76 				player.activeNanos[0].expiresAt.Sub(completed) != time.Duration(fixture.Duration)*10*time.Millisecond ||
     77 				!slices.Equal(cold.inventory.LearnedNanos, []uint32{fixture.Program}) {
     78 				t.Fatal("original program lost its complete lifecycle or changed trained state", player.nano, player.usedNCU())
     79 			}
     80 			for stat, base := range before {
     81 				want := base
     82 				for _, modifier := range fixture.Modifiers {
     83 					if uint32(modifier[0]) == stat {
     84 						want += modifier[1]
     85 					}
     86 				}
     87 				current, _ := player.effectiveStat(stat)
     88 				restored, _ := cold.effectiveStat(stat)
     89 				if current != want || restored != want {
     90 					t.Fatal("program lost an authored modifier or changed an unrelated skill", stat, current, restored, want)
     91 				}
     92 			}
     93 			var critical int32
     94 			for _, modifier := range fixture.Modifiers {
     95 				if modifier[0] == 379 {
     96 					critical += modifier[1]
     97 				}
     98 			}
     99 			if player.nanoBonus(379) != critical || cold.nanoBonus(379) != critical {
    100 				t.Fatal("critical Skill effect did not survive cold recovery")
    101 			}
    102 			if err := world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, fixture.Program})[20:]); err != nil {
    103 				t.Fatal(err)
    104 			}
    105 			cold = newTestInventoryServer(t).characters[1]
    106 			if len(player.activeNanos) != 0 || len(cold.activeNanos) != 0 || player.usedNCU() != 0 || cold.usedNCU() != 0 ||
    107 				player.nanoBonus(379) != 0 || cold.nanoBonus(379) != 0 {
    108 				t.Fatal("cancellation retained a critical modifier or NCU")
    109 			}
    110 			for stat, base := range before {
    111 				current, _ := player.effectiveStat(stat)
    112 				restored, _ := cold.effectiveStat(stat)
    113 				if current != base || restored != base {
    114 					t.Fatal("cancellation changed trained state or retained a contribution", stat, current, restored, base)
    115 				}
    116 			}
    117 		})
    118 	}
    119 }
    120 
    121 func TestSelfOnlyNanosRedirectEverySuppliedTargetToTheCaster(t *testing.T) {
    122 	fixtures := selfAndCriticalNanoFixtures(t)
    123 	for _, fixture := range aggDefNanoFixtures() {
    124 		fixtures = append(fixtures, selfAndCriticalNanoFixture{Program: fixture.program, NanoCost: fixture.debit, SelfOnly: true})
    125 	}
    126 	for _, fixture := range combatNanoFixtures(t) {
    127 		if fixture.Target == 2 {
    128 			fixtures = append(fixtures, selfAndCriticalNanoFixture{Program: fixture.Program, Profession: fixture.Profession,
    129 				NCU: fixture.NCU, NanoCost: fixture.Debit, SelfOnly: true})
    130 		}
    131 	}
    132 	for _, fixture := range fixtures {
    133 		if !fixture.SelfOnly {
    134 			continue
    135 		}
    136 		for _, supplied := range [][2]uint32{{0, 0}, {50000, 0}, {50000, 999}, {50000, 1000000}, {50000, 2}, {50000, 1}, {51018, 2}} {
    137 			t.Run(fmt.Sprintf("%d/%d/%d", fixture.Program, supplied[0], supplied[1]), func(t *testing.T) {
    138 				world, _ := newCombatNanoWorld(t, combatNanoFixture{Profession: fixture.Profession})
    139 				player := world.characters[1]
    140 				player.level, player.profession = 200, uint16(fixture.Profession)
    141 				player.inventory.LearnedNanos = []uint32{fixture.Program}
    142 				other := &character{id: 2, playfield: 999, health: 100, stats: testCharacterStats()}
    143 				world.characters[2] = other
    144 				world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, target: true, ready: true}
    145 
    146 				client := world.clients[1]
    147 				if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, supplied[0], supplied[1], 53019, fixture.Program})[20:]); err != nil {
    148 					t.Fatal(err)
    149 				}
    150 				if client.nanoCast == nil || client.nanoCast.target != 1 {
    151 					t.Fatal("self-only cast did not normalize the complete recipient identity")
    152 				}
    153 				world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
    154 				cold := newTestInventoryServer(t).characters[1]
    155 
    156 				if len(player.activeNanos) != 1 || len(cold.activeNanos) != 1 || player.usedNCU() != fixture.NCU ||
    157 					player.nano != 50000-fixture.NanoCost || len(other.activeNanos) != 0 || other.health != 100 || other.usedNCU() != 0 ||
    158 					len(world.characters[1000000].activeNanos) != 0 {
    159 					t.Fatal("self-only cast used the supplied identity as its recipient")
    160 				}
    161 			})
    162 		}
    163 	}
    164 }
    165 
    166 func TestCriticalSkillNanoRejectsIncompleteContractsWithoutPartialAimedShot(t *testing.T) {
    167 	for _, scenario := range []string{"missing word", "nonzero word", "short word", "integer word", "missing stat", "missing amount", "unsupported stat", "negative critical", "conditional", "repeated", "interval", "mixed targets", "target selector", "unknown function"} {
    168 		t.Run(scenario, func(t *testing.T) {
    169 			original := gamedata.NanoTemplates[32065]
    170 			definition := *original
    171 			definition.Sections = slices.Clone(original.Sections)
    172 			for index, section := range definition.Sections {
    173 				if section.Type != 2 || section.Subtype != 0 {
    174 					continue
    175 				}
    176 				functions := slices.Clone(*section.Functions)
    177 				definition.Sections[index].Functions = &functions
    178 				for index := range functions {
    179 					if functions[index].ID != 53012 {
    180 						continue
    181 					}
    182 					function := &functions[index]
    183 					function.Arguments = slices.Clone(function.Arguments)
    184 					switch scenario {
    185 					case "missing word":
    186 						function.Arguments = function.Arguments[:2]
    187 					case "nonzero word":
    188 						function.Arguments[2].BytesHex = new("01000000")
    189 					case "short word":
    190 						function.Arguments[2].BytesHex = new("000000")
    191 					case "integer word":
    192 						function.Arguments[2] = gamedata.ItemArgument{Integer: new(int32(0))}
    193 					case "missing stat":
    194 						function.Arguments[0] = gamedata.ItemArgument{}
    195 					case "missing amount":
    196 						function.Arguments[1] = gamedata.ItemArgument{}
    197 					case "unsupported stat":
    198 						function.Arguments[0].Integer = new(int32(315))
    199 					case "negative critical":
    200 						function.Arguments[1].Integer = new(int32(-4))
    201 					case "conditional":
    202 						function.Requirements = []gamedata.ItemRequirement{{Stat: 54, Operator: 2, Value: 1}}
    203 					case "repeated":
    204 						function.TickCount = 2
    205 					case "interval":
    206 						function.TickInterval = 1
    207 					case "mixed targets":
    208 						function.Target = 2
    209 					case "target selector":
    210 						function.Target = 4
    211 					case "unknown function":
    212 						function.ID = 53110
    213 					}
    214 				}
    215 			}
    216 			gamedata.NanoTemplates[32065] = &definition
    217 			t.Cleanup(func() { gamedata.NanoTemplates[32065] = original })
    218 			world, conn := newSelfNanoWorld(t)
    219 			player, client := world.characters[1], world.clients[1]
    220 			player.level, player.profession = 200, 5
    221 			if granted, err := world.grantItem(player, 32106); err != nil || !granted {
    222 				t.Fatal(granted, err)
    223 			}
    224 			before, _ := player.effectiveStat(151)
    225 
    226 			if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil {
    227 				t.Fatal(err)
    228 			}
    229 			learned := len(player.inventory.LearnedNanos)
    230 			// Independently exercise cast admission without relying on the upload rejection.
    231 			player.inventory.LearnedNanos = []uint32{32065}
    232 			if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 32065})[20:]); err != nil {
    233 				t.Fatal(err)
    234 			}
    235 
    236 			after, _ := player.effectiveStat(151)
    237 			if learned != 0 || client.nanoCast != nil || player.nano != 50000 || player.nanoReserved != 0 || len(player.activeNanos) != 0 ||
    238 				player.nanoBonus(379) != 0 || after != before || len(player.inventory.Items) != 3 ||
    239 				len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 || binary.BigEndian.Uint32(conn.packets[1][29:33]) != 108 {
    240 				t.Fatal("incomplete Skill contract consumed a crystal, charged nano or granted partial Aimed Shot")
    241 			}
    242 		})
    243 	}
    244 }
    245 
    246 func TestSelfAndCriticalNanosEnforceEveryAuthoredThresholdAndProfession(t *testing.T) {
    247 	for _, fixture := range selfAndCriticalNanoFixtures(t) {
    248 		gates := append(slices.Clone(fixture.Gates), [2]uint32{60, fixture.Profession})
    249 		for _, gate := range gates {
    250 			for _, permitted := range []bool{false, true} {
    251 				t.Run(fmt.Sprintf("%d/%d/pass=%t", fixture.Program, gate[0], permitted), func(t *testing.T) {
    252 					world, _ := newSelfNanoWorld(t)
    253 					player, client := world.characters[1], world.clients[1]
    254 					player.level, player.profession = 200, uint16(fixture.Profession)
    255 					player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
    256 					value := uint16(gate[1])
    257 					if permitted {
    258 						value++
    259 					}
    260 					switch gate[0] {
    261 					case 54:
    262 						player.level = value
    263 					case 60:
    264 						if !permitted {
    265 							player.profession = 0
    266 						}
    267 					default:
    268 						for _, field := range player.stats.trainingStats() {
    269 							if field.stat == gate[0] {
    270 								*field.value = value
    271 							}
    272 						}
    273 					}
    274 					if granted, err := world.grantItem(player, fixture.Crystal); err != nil || !granted {
    275 						t.Fatal(granted, err)
    276 					}
    277 
    278 					if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil {
    279 						t.Fatal(err)
    280 					}
    281 					learned := len(player.inventory.LearnedNanos)
    282 					player.inventory.LearnedNanos = []uint32{fixture.Program}
    283 					if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, fixture.Program})[20:]); err != nil {
    284 						t.Fatal(err)
    285 					}
    286 
    287 					if permitted {
    288 						if learned != 1 || client.nanoCast == nil || player.nanoReserved != fixture.NanoCost || len(player.inventory.Items) != 2 {
    289 							t.Fatal("one point above an authored threshold rejected upload or cast")
    290 						}
    291 					} else if learned != 0 || client.nanoCast != nil || player.nano != 50000 || player.nanoReserved != 0 ||
    292 						len(player.activeNanos) != 0 || player.usedNCU() != 0 || len(player.inventory.Items) != 3 {
    293 						t.Fatal("an equal skill/level threshold or wrong profession consumed a crystal or started a cast")
    294 					}
    295 				})
    296 			}
    297 		}
    298 	}
    299 }
    300 
    301 func TestSelfSelectorsRedirectTheWholeContract(t *testing.T) {
    302 	for _, targets := range [][2]uint32{{1, 1}, {1, 2}, {2, 1}, {2, 2}} {
    303 		t.Run(fmt.Sprint(targets), func(t *testing.T) {
    304 			original := gamedata.NanoTemplates[32065]
    305 			definition := *original
    306 			definition.Sections = slices.Clone(definition.Sections)
    307 			for index := range definition.Sections {
    308 				section := &definition.Sections[index]
    309 				if section.Type != 2 {
    310 					continue
    311 				}
    312 				functions := slices.Clone(*section.Functions)
    313 				section.Functions = &functions
    314 				for index := range functions {
    315 					functions[index].Target = targets[index]
    316 				}
    317 			}
    318 			gamedata.NanoTemplates[32065] = &definition
    319 			t.Cleanup(func() { gamedata.NanoTemplates[32065] = original })
    320 			world, _ := newSelfNanoWorld(t)
    321 			player := world.characters[1]
    322 			player.profession = 5
    323 			player.inventory.LearnedNanos = []uint32{32065}
    324 
    325 			castTestBuff(t, world, 1, 999, 32065)
    326 
    327 			if player.nanoBonus(151) != 130 || player.nanoBonus(379) != 4 || len(player.activeNanos) != 1 {
    328 				t.Fatal("self selectors lost a companion effect or retained the supplied target")
    329 			}
    330 		})
    331 	}
    332 }