aorecomp

Anarchy Online classic in the browser

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


server/skill_nano_test.go (16242B)


      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/ordinary-skill-nanos.json
     15 var ordinarySkillNanoData []byte
     16 
     17 type ordinarySkillNanoFixture struct {
     18 	Program, Crystal, Quality, Profession uint32
     19 	Modifiers                             [][2]int32
     20 	NCU, Duration                         uint32
     21 	NanoCost                              uint32 `json:"nano_cost"`
     22 }
     23 
     24 func ordinarySkillNanoFixtures(t *testing.T) []ordinarySkillNanoFixture {
     25 	t.Helper()
     26 	var fixtures []ordinarySkillNanoFixture
     27 	if err := json.Unmarshal(ordinarySkillNanoData, &fixtures); err != nil {
     28 		t.Fatal(err)
     29 	}
     30 	return fixtures
     31 }
     32 
     33 func newSkillNanoWorld(t *testing.T) (*server, *combatTestConn) {
     34 	t.Helper()
     35 	world, conn := newStatBuffWorld(t)
     36 	player := world.characters[1]
     37 	for _, field := range player.stats.trainingStats() {
     38 		*field.value = 900
     39 	}
     40 	// Keep combat events viable against this fixture's highly trained player.
     41 	world.characters[1000000].stats.Body.MartialArts = 900
     42 	player.stats.Body.NanoPool, player.nano = 30000, 50000
     43 	if err := world.saveUser(player); err != nil {
     44 		t.Fatal(err)
     45 	}
     46 	// The original shoulder container adds five NCU to the fixture's 47-NCU ear.
     47 	if granted, err := world.grantItem(player, 168658); err != nil || !granted {
     48 		t.Fatal(granted, err)
     49 	}
     50 	inventory := player.inventory
     51 	inventory.Items = slices.Clone(inventory.Items)
     52 	inventory.Items[1].Slot = 22
     53 	if err := world.saveInventory(player, inventory); err != nil {
     54 		t.Fatal(err)
     55 	}
     56 	conn.packets = nil
     57 	return world, conn
     58 }
     59 
     60 func TestOrdinarySkillNanoOriginalProgramsCastRestoreAndCancel(t *testing.T) {
     61 	for _, fixture := range ordinarySkillNanoFixtures(t) {
     62 		t.Run(fmt.Sprint(fixture.Program), func(t *testing.T) {
     63 			world, conn := newSkillNanoWorld(t)
     64 			player, client := world.characters[1], world.clients[1]
     65 			player.profession = uint16(fixture.Profession)
     66 			if err := world.saveUser(player); err != nil {
     67 				t.Fatal(err)
     68 			}
     69 			if fixture.Crystal != 0 {
     70 				if granted, err := world.grantItem(player, fixture.Crystal); err != nil || !granted {
     71 					t.Fatal(granted, err)
     72 				}
     73 			} else {
     74 				// This original program has no ordinary uploader; seed only its learned entry.
     75 				player.inventory.LearnedNanos = []uint32{fixture.Program}
     76 				if err := world.saveInventory(player, player.inventory); err != nil {
     77 					t.Fatal(err)
     78 				}
     79 			}
     80 			trained := player.baseStats()
     81 			before := make(map[uint32]int32)
     82 			for _, field := range trained.trainingStats() {
     83 				before[field.stat], _ = player.effectiveStat(field.stat)
     84 			}
     85 
     86 			if fixture.Crystal != 0 {
     87 				if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil {
     88 					t.Fatal(err)
     89 				}
     90 				if len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[1][37:41]) != fixture.Quality {
     91 					t.Fatal("original skill crystal was rejected or changed quality")
     92 				}
     93 			}
     94 			completed := castTestBuff(t, world, 1, 1, fixture.Program)
     95 			cold := newTestInventoryServer(t).characters[1]
     96 
     97 			if player.usedNCU() != fixture.NCU || cold.usedNCU() != fixture.NCU || player.nano != 50000-fixture.NanoCost || cold.nano != player.nano ||
     98 				player.baseStats() != trained || cold.baseStats() != trained || player.health != 20 || cold.health != 20 ||
     99 				len(player.activeNanos) != 1 || player.activeNanos[0].expiresAt.Sub(completed) != time.Duration(fixture.Duration)*10*time.Millisecond ||
    100 				!slices.Equal(cold.inventory.LearnedNanos, []uint32{fixture.Program}) || len(cold.inventory.Items) != 2 {
    101 				t.Fatal("skill buff changed trained values, lost its complete contract or failed cold recovery", player.nano, player.usedNCU())
    102 			}
    103 			for stat, base := range before {
    104 				want := base
    105 				for _, modifier := range fixture.Modifiers {
    106 					if uint32(modifier[0]) == stat {
    107 						want += modifier[1]
    108 					}
    109 				}
    110 				current, _ := player.effectiveStat(stat)
    111 				restored, _ := cold.effectiveStat(stat)
    112 				if current != want || restored != want {
    113 					t.Fatal("skill buff lost a modifier or changed an unrelated skill", stat, current, restored, want)
    114 				}
    115 			}
    116 			if err := world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, fixture.Program})[20:]); err != nil {
    117 				t.Fatal(err)
    118 			}
    119 			cold = newTestInventoryServer(t).characters[1]
    120 			if player.usedNCU() != 0 || len(cold.activeNanos) != 0 || cold.usedNCU() != 0 {
    121 				t.Fatal("cancelled skill buff retained its NCU or durable effect")
    122 			}
    123 			for stat, base := range before {
    124 				current, _ := player.effectiveStat(stat)
    125 				restored, _ := cold.effectiveStat(stat)
    126 				if current != base || restored != base {
    127 					t.Fatal("skill cancellation retained a modifier", stat, current, restored, base)
    128 				}
    129 			}
    130 		})
    131 	}
    132 }
    133 
    134 func TestSkillNanoOmittedStatsUseOriginalConstructorDefaults(t *testing.T) {
    135 	for _, omitted := range []uint32{8, 54, 75, 210, 287, 294, 407} {
    136 		t.Run(fmt.Sprint(omitted), func(t *testing.T) {
    137 			world, _ := newSkillNanoWorld(t)
    138 			player, client := world.characters[1], world.clients[1]
    139 			player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
    140 			player.stats.Speed.NanoInitiative, player.aggDef = 0, 0
    141 			player.inventory.LearnedNanos = []uint32{26339, 26336}
    142 			if err := world.saveUser(player); err != nil {
    143 				t.Fatal(err)
    144 			}
    145 			if err := world.saveInventory(player, player.inventory); err != nil {
    146 				t.Fatal(err)
    147 			}
    148 			// A synthetic omission isolates default loading from an authored zero.
    149 			original := gamedata.NanoTemplates[26339]
    150 			program := *original
    151 			program.Stats = slices.DeleteFunc(slices.Clone(original.Stats), func(stat [2]uint32) bool { return stat[0] == omitted })
    152 			gamedata.NanoTemplates[26339] = &program
    153 			t.Cleanup(func() { gamedata.NanoTemplates[26339] = original })
    154 			target := player
    155 			if omitted == 287 {
    156 				recipient := *player
    157 				recipient.id, recipient.position = 2, [3]float32{17, 0, 0}
    158 				recipient.name = "Recipient"
    159 				recipient.inventory = playerInventory{}
    160 				world.characters[2], world.nextCharacter = &recipient, 2
    161 				world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true}
    162 				if err := world.saveUser(&recipient); err != nil {
    163 					t.Fatal(err)
    164 				}
    165 				target = &recipient
    166 			}
    167 
    168 			before := time.Now()
    169 			if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 26339})[20:]); err != nil {
    170 				t.Fatal(err)
    171 			}
    172 			if client.nanoCast == nil {
    173 				t.Fatal("omitted native attribute was treated as zero")
    174 			}
    175 			deadline, after := client.nanoCast.readyAt, time.Now()
    176 			completed := deadline.Add(time.Nanosecond)
    177 			world.advanceNanos(completed)
    178 			cold := newTestInventoryServer(t).characters[target.id]
    179 
    180 			duration, ncu, debit, recharge := 30*time.Minute, uint32(2), uint32(24), 499999988*time.Nanosecond
    181 			if omitted == 8 {
    182 				duration = 10 * time.Second
    183 			}
    184 			if omitted == 54 {
    185 				ncu = 1
    186 			}
    187 			if omitted == 407 {
    188 				debit = 0
    189 			}
    190 			if omitted == 210 {
    191 				recharge = 1999999955 * time.Nanosecond
    192 			}
    193 			if deadline.Before(before.Add(2*time.Second)) || deadline.After(after.Add(2*time.Second)) ||
    194 				len(target.activeNanos) != 1 || target.activeNanos[0].expiresAt.Sub(completed) != duration || cold.activeNanos[0].remaining != duration ||
    195 				target.usedNCU() != ncu || cold.usedNCU() != ncu || player.nano != 50000-debit || player.nanoRechargeUntil.Sub(completed) != recharge {
    196 				t.Fatal("constructor default was lost in casting, duration, NCU, cost or recharge", player.nano, player.nanoRechargeUntil.Sub(completed))
    197 			}
    198 			if omitted == 75 {
    199 				player.nanoRechargeUntil = time.Time{}
    200 				castTestBuff(t, world, 1, 1, 26336)
    201 				if len(player.activeNanos) != 2 || player.usedNCU() != 6 || player.nanoBonus(102) != 30 {
    202 					t.Fatal("omitted strain did not default to the program identity")
    203 				}
    204 			}
    205 		})
    206 	}
    207 }
    208 
    209 func TestSkillNanoAnchorsMovingRecipientOnApplicationAndExpiry(t *testing.T) {
    210 	world, _ := newSkillNanoWorld(t)
    211 	player := world.characters[1]
    212 	player.inventory.LearnedNanos = []uint32{27172}
    213 	recipient := *player
    214 	recipient.id, recipient.name, recipient.running = 2, "Moving Recipient", true
    215 	recipient.inventory = playerInventory{}
    216 	recipient.stats.Speed.RunSpeed = 100
    217 	recipient.health = recipient.maximumHealth()
    218 	recipient.position, recipient.rotation = [3]float32{0, 0, 3}, [4]float32{0, 0, 0, 1}
    219 	world.characters[2], world.nextCharacter = &recipient, 2
    220 	client := &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true}
    221 	world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], 1, time.Now())
    222 	world.clients[2] = client
    223 	if err := world.saveUser(&recipient); err != nil {
    224 		t.Fatal(err)
    225 	}
    226 	if err := world.handleNanoCast(world.clients[1], characterActionPacket(1, [5]uint32{19, 50000, 2, 53019, 27172})[20:]); err != nil {
    227 		t.Fatal(err)
    228 	}
    229 	at := world.clients[1].nanoCast.readyAt.Add(time.Nanosecond)
    230 	world.characters[client.id].movement.updatedAt = at.Add(-time.Second)
    231 
    232 	world.advanceNanos(at)
    233 	position := predictedPosition(&recipient, at.Add(time.Second))
    234 
    235 	if world.characters[client.id].movement.updatedAt != at || recipient.position[2] < 7.499 || recipient.position[2] > 7.501 || position[2] < 12.049 || position[2] > 12.051 {
    236 		t.Fatal("RunSpeed buff repriced the previous segment or omitted the new speed", recipient.position, position)
    237 	}
    238 
    239 	// Expiry must retain the buffed speed for the preceding segment only.
    240 	expires := recipient.activeNanos[0].expiresAt
    241 	recipient.position = [3]float32{0, 0, 3}
    242 	world.characters[client.id].movement.updatedAt = expires.Add(-time.Second)
    243 	world.advanceNanos(expires)
    244 	position = predictedPosition(&recipient, expires.Add(time.Second))
    245 	if world.characters[client.id].movement.updatedAt != expires || recipient.position[2] < 7.549 || recipient.position[2] > 7.551 || position[2] < 12.049 || position[2] > 12.051 ||
    246 		recipient.nanoBonus(156) != 0 || len(newTestInventoryServer(t).characters[2].activeNanos) != 0 {
    247 		t.Fatal("expired RunSpeed buff changed the previous segment or remained active", recipient.position, position)
    248 	}
    249 }
    250 
    251 func TestSkillNanoModifiersGateLearningAndCastingWithoutChangingTraining(t *testing.T) {
    252 	world, conn := newSkillNanoWorld(t)
    253 	player, client := world.characters[1], world.clients[1]
    254 	caster := *player
    255 	caster.id, caster.name = 2, "Skill Caster"
    256 	caster.inventory = playerInventory{LearnedNanos: []uint32{27137}}
    257 	world.characters[2], world.nextCharacter = &caster, 2
    258 	world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true}
    259 	if err := world.saveUser(&caster); err != nil {
    260 		t.Fatal(err)
    261 	}
    262 	if err := world.saveInventory(&caster, caster.inventory); err != nil {
    263 		t.Fatal(err)
    264 	}
    265 	player.stats.Abilities = characterAbilitiesStats{10, 10, 10, 10, 10, 10}
    266 	player.stats.NanoAiding.PsychologicalModification = 45
    267 	if err := world.saveUser(player); err != nil {
    268 		t.Fatal(err)
    269 	}
    270 	if granted, err := world.grantItem(player, 27262); err != nil || !granted {
    271 		t.Fatal(granted, err)
    272 	}
    273 
    274 	if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil {
    275 		t.Fatal(err)
    276 	}
    277 	if len(player.inventory.LearnedNanos) != 0 || len(player.inventory.Items) != 3 {
    278 		t.Fatal("below-threshold upload consumed the crystal or granted its program")
    279 	}
    280 	castTestBuff(t, world, 2, 1, 27137)
    281 	if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 2)[20:]); err != nil {
    282 		t.Fatal(err)
    283 	}
    284 	castTestBuff(t, world, 1, 1, 27127)
    285 	if err := world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, 27137})[20:]); err != nil {
    286 		t.Fatal(err)
    287 	}
    288 	player.nanoRechargeUntil = time.Time{}
    289 	before, packets := player.nano, len(conn.packets)
    290 	if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 27127})[20:]); err != nil {
    291 		t.Fatal(err)
    292 	}
    293 	cold := newTestInventoryServer(t).characters[1]
    294 
    295 	if player.stats.NanoAiding.PsychologicalModification != 45 || cold.stats.NanoAiding.PsychologicalModification != 45 ||
    296 		player.nanoBonus(129) != 0 || player.nanoBonus(112) != 20 || cold.nanoBonus(112) != 20 ||
    297 		!slices.Equal(cold.inventory.LearnedNanos, []uint32{27127}) || len(cold.inventory.Items) != 2 ||
    298 		client.nanoCast != nil || player.nano != before || len(conn.packets) != packets+1 || binary.BigEndian.Uint32(conn.packets[packets][29:33]) != 108 {
    299 		t.Fatal("skill buff leaked into training, lost its learned entry or allowed a cast after cancellation")
    300 	}
    301 }
    302 
    303 func TestSkillNanoEnablesWeaponWearAndCancellationPreservesTheInstance(t *testing.T) {
    304 	world, _ := newSkillNanoWorld(t)
    305 	player, client := world.characters[1], world.clients[1]
    306 	player.profession = 8
    307 	player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
    308 	player.stats.TradeRepair.Psychology = 280
    309 	if err := world.saveUser(player); err != nil {
    310 		t.Fatal(err)
    311 	}
    312 	for _, template := range []uint32{27271, 205736} {
    313 		if granted, err := world.grantItem(player, template); err != nil || !granted {
    314 			t.Fatal(granted, err)
    315 		}
    316 	}
    317 	if err := world.handleInventory(client, inventoryMovePacket(1, 65, 6)[20:]); err != nil || client.equipment != nil {
    318 		t.Fatal("below-threshold weapon wear succeeded", err)
    319 	}
    320 
    321 	if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil {
    322 		t.Fatal(err)
    323 	}
    324 	castTestBuff(t, world, 1, 1, 27135)
    325 	if err := world.handleInventory(client, inventoryMovePacket(1, 65, 6)[20:]); err != nil || client.equipment == nil {
    326 		t.Fatal("buffed weapon wear failed", err)
    327 	}
    328 	world.advanceEquipment(client.equipment.readyAt)
    329 	if player.attackRating() != 300 {
    330 		t.Fatal("weapon rating omitted the skill buff", player.attackRating())
    331 	}
    332 	if err := world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, 27135})[20:]); err != nil {
    333 		t.Fatal(err)
    334 	}
    335 	cold := newTestInventoryServer(t).characters[1]
    336 
    337 	if player.attackRating() != 280 || cold.attackRating() != 280 || cold.stats.TradeRepair.Psychology != 280 ||
    338 		len(cold.inventory.Items) != 3 || cold.inventory.Items[2].ID != 4 || cold.inventory.Items[2].Slot != 6 ||
    339 		cold.inventory.Items[2].Template != 205736 || cold.inventory.Items[2].Quality != 100 || len(cold.activeNanos) != 0 {
    340 		t.Fatal("cancellation changed training or lost the equipped instance", cold.inventory)
    341 	}
    342 }
    343 
    344 func TestSkillNanoChangesArmorEffectivenessAndClampsHealthOnCancellation(t *testing.T) {
    345 	world, _ := newSkillNanoWorld(t)
    346 	player, client := world.characters[1], world.clients[1]
    347 	player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
    348 	player.stats.TradeRepair.ComputerLiteracy = 665
    349 	if granted, err := world.grantItem(player, 200461); err != nil || !granted {
    350 		t.Fatal(granted, err)
    351 	}
    352 	// GM placement isolates effectiveness of an already worn original armor item.
    353 	inventory := player.inventory
    354 	inventory.Items = slices.Clone(inventory.Items)
    355 	inventory.Items[2].Slot = 19
    356 	inventory.LearnedNanos = []uint32{26425}
    357 	if err := world.saveInventory(player, inventory); err != nil {
    358 		t.Fatal(err)
    359 	}
    360 	player.health = player.maximumHealth()
    361 	if err := world.saveUser(player); err != nil {
    362 		t.Fatal(err)
    363 	}
    364 	before, armor := player.maximumHealth(), player.equipmentBonus(90)
    365 
    366 	castTestBuff(t, world, 1, 1, 26425)
    367 	if player.maximumHealth() != before+22 || player.equipmentBonus(90) != armor+300 || player.health != before {
    368 		t.Fatal("skill buff did not restore armor effectiveness without granting HP", player.maximumHealth(), before, player.equipmentBonus(90), armor)
    369 	}
    370 	player.health = player.maximumHealth()
    371 	if err := world.saveUser(player); err != nil {
    372 		t.Fatal(err)
    373 	}
    374 	if err := world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, 26425})[20:]); err != nil {
    375 		t.Fatal(err)
    376 	}
    377 	cold := newTestInventoryServer(t).characters[1]
    378 
    379 	if player.maximumHealth() != before || player.health != before || cold.health != before || cold.maximumHealth() != before ||
    380 		player.equipmentBonus(90) != armor || cold.equipmentBonus(90) != armor || cold.stats.TradeRepair.ComputerLiteracy != 665 ||
    381 		len(cold.inventory.Items) != 3 || cold.inventory.Items[2].Slot != 19 || cold.inventory.Items[2].ID != 3 {
    382 		t.Fatal("cancellation retained effectiveness or lost armor ownership", cold.inventory)
    383 	}
    384 }