commit 58176fc4765feb0ee1c9d05b50e522ea5b034d56
parent 5b9e25d7898a0c09320d376eaf8790a19b81e0de
Author: anon <anon@example.com>
Date: Tue, 27 Oct 2026 23:37:49 +0000
Populate fixed missions through shared NPC combat and loot
Commit concrete encounter lives with acceptance and retire NPCs, unclaimed
corpse loot and runtime queues atomically with their private assignment.
Reuse shared combat, kill XP, loot and inventory delivery; preserve transferred
items and retain completed populations until expiry. Apply indoor collision
handling and ground the entrance encounter on its actual mesh surface.
Verify 299 focused roots/1959 results, 35 race roots/84 results, vet, build and
GPU WASM acceptance, cold population recovery, combat, loot, expiry and
abandonment. Document controlled fixtures, exact item accounting and remaining
LOS, navigation, token eligibility and generation work.
Diffstat:
20 files changed, 968 insertions(+), 55 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -63,7 +63,9 @@ entry, traversal, reconnect and return. Its bound book can be collected and
survives restart without respawning. Returning that exact book to its issuing
booth now completes the fixed contract and atomically grants authored cash
and a selected-quality equipment reward. The fixed selection is provisional;
-mission enemies, conditional token/XP and historical reward generation remain open.
+the fixed mission now has five level-1 Leets using shared combat and loot.
+Conditional completion token/XP, obstacle routing and historical population/reward
+generation remain open.
After fixing an inactive-mesh projectile that blocked repeated native casts,
a fresh Atrox Nano-Technician completed fifteen ordinary Leet kills without
a death, reaching level 2 with 1500 cumulative XP and exactly 4000 new IP.
@@ -445,8 +447,12 @@ capacity checks are recorded in [belts and NCU](docs/belts-ncu.md).
construction. See `local/aggdef-nano-fist-clock-research/findings.md`.
- [x] Replace the approximate melee range check. Check: two actors at known
positions and sizes are accepted or rejected at the recovered range boundary.
-- [ ] [P1] Reject attacks through one solid obstruction. Check: the same stationary
- encounter works in the open and fails with a wall between the actors.
+- [ ] [P0] Reject attacks through solid obstructions. Check: the same stationary
+ encounter works in the open and fails with a wall between the actors. Include
+ vertically separated actors around raised mission scenery: native testing
+ allowed fighting a small NPC below the tongue while the player stood above
+ it, making corpse picking awkward. Recover shared eye/body LOS and verify
+ the actual collision surface; do not add species-specific exceptions.
- [x] Reconcile quiet health without phantom damage feedback. Check: after a
long native fight, prediction drift is corrected to server HP without extra
nanobot-damage chat or floating damage, including for an observer.
@@ -1521,8 +1527,8 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
poses and correct owners without applying observer yaw twice. GPU WASM
verifies normal acceptance, real exterior entry, both rooms, reconnect and exit
without substituting client world packets. The fixed prototype has open native
- room links and no enemies. Returning its objective pays the authored cash
- and selected-quality item reward; qualifying token/XP remains open. The approach volume
+ room links and a fixed reconstruction population. Returning its objective pays
+ the authored cash and selected-quality item reward; qualifying token/XP remains open. The approach volume
and 2.5-unit arrival offsets remain provisional.
See [mission interiors](docs/mission-interiors.md#key-gated-live-entry-and-atomic-return).
- [ ] [P0] Verify private-instance boundaries across the complete playable loop.
@@ -1530,8 +1536,9 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
chat between same-instance guests and different owners at identical coordinates.
Existing runtime IDs separate geometry and shared broadcast/inspection paths;
expand negative and reconnect coverage as mission enemies/objectives are added.
- Retire spawned NPCs, objectives and corpses with their assignment, preserving
- other worlds and evacuating occupants atomically on expiry/abandonment.
+ NPC/corpse/objective retirement now shares assignment revocation and occupant
+ evacuation in one transaction. Complete the remaining cross-instance negative
+ cases, including nanos, inspection, trade and vicinity chat.
- [ ] [P1] Bind original mission doors and recover their style/access policy.
The extractor decodes298 rooms from four ACD libraries and3692 door placements
with53 templates. Shared builders preserve authored door flags and optional QL;
@@ -1590,13 +1597,34 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
effects. The original book's right-click emits GenericCmd action3, while its
explicit R/Pick Up emits InventoryMove; preserve that distinction and resolve
actual instances before the existing type51005 terminal handling.
+- [x] Populate the fixed mission through shared admitted NPC profiles. Acceptance
+ commits five concrete level-1 Leets with the assignment and key; reconnect,
+ reentry and cold load retain those lives without re-reading a spawn recipe.
+ Shared combat supplies kill XP, cash and Monster Parts. Private deaths have
+ no replacement timer; abandonment/expiry retire living actors, corpse loot,
+ combat and queues atomically. Completion retains the population until expiry,
+ and transferred loot remains owned by its player. Selection, count, positions
+ and the one-life policy are reconstruction choices. GPU WASM checks cover
+ a controlled full-health fight, shared100XP/loot/cash, native pickup, corpse
+ expiry, cold population recovery and abandonment with exact item accounting.
+ Combat LOS and general navigation remain open. See
+ [mission encounters](docs/mission-encounters.md).
+- [ ] [P0] Route indoor combatants around actual mesh obstructions. Shared body,
+ room, floor and wall handling now bounds pursuit and return; it does not find
+ detours. The entrance Leet now spawns on the actual tongue-mesh surface;
+ both its route and the z28-to-z43 portal route pass. Native waypoint
+ retry/discard does not step up; recover or reconstruct reusable detours
+ without enlarging bodies or tunnelling through walls. Cover small/large bodies, disconnected rooms and return routes.
- [ ] [P0] Recover token/XP eligibility and implement atomic eligible mission
rewards. The original offer details qualify XP with "Which you get when you
- receive a token." Period notes increase token chance with kills; the empty
- prototype grants cash only. Establish the kill threshold/formula, faction
- exceptions and XP arithmetic before awarding XP/tokens. Add mission enemies
- and generated useful item rewards through shared progression/inventory settlement,
- including full-inventory and failed-commit/retry checks.
+ receive a token." Period notes increase token chance with kills; completion
+ grants cash/items while ordinary kills independently grant XP. Establish the kill threshold/formula, faction
+ exceptions and XP arithmetic before awarding completion XP/tokens. Original
+ faction token Use descriptors recover level-dependent value and Unique/side
+ checks, but do not establish mission eligibility. Keep token acquisition and
+ right-click upload distinct. Commit any required mission kill-progress ledger
+ with the shared kill outcome; expiring corpses must not erase earned eligibility. Cover full inventory and failed-commit/retry; see
+ [token evidence](docs/mission-encounters.md#completion-token-evidence).
- [ ] [P1] Extend return-item submission to native carried-backpack sources after
verifying their original producer/callback. Main-inventory hand-in is verified;
banked, unknown and other players' items must stay ineligible.
@@ -1614,8 +1642,7 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
all key locations, copied bindings, pending trades, stale/foreign/repeated
requests, concurrent expiry/abandonment and output failure. Native WASM verifies
online expiry and empty inventory/journal after a cold server restart.
- Player evacuation is now atomic with retirement; cleanup of future spawned
- NPCs and corpses remains part of the instance work above; floor objectives
+ Player evacuation, spawned NPCs, unclaimed corpse loot and floor objectives
now retire in the same transaction.
See [mission retirement](docs/mission-retirement.md).
- [ ] [P2] Retire uploaded waypoints when their mission expires. Native
diff --git a/docs/mission-encounters.md b/docs/mission-encounters.md
@@ -0,0 +1,127 @@
+# Fixed mission encounters
+
+The Surveillance Office contract selects five level-1 Leets from the same
+admitted species/profile as the outdoor training population. Selection, count
+and positions in `server/gamedata/missions.yaml` are reconstruction data. They
+are not recovered original mission population rules. Encounter level/difficulty,
+other species and useful equipment-drop selection remain open work.
+
+Acceptance validates the saved layout's actual room/floor, the original NPC
+definition and an admitted combat level. It commits concrete NPC rows, their
+identity allocation, assignment and bound key in one transaction. The accepted
+contract then has no spawn recipe: entry, reconnect and cold loading restore
+existing lives rather than regenerating actors from changed YAML. The book is
+still allocated once on first entry through its separate existing transaction.
+
+These actors use ordinary combat, contributions, kill XP, generated loot,
+credit collection and inventory transfers. They add no mission-specific damage,
+loot or XP formula. A private mission death has no scheduled replacement life;
+this one-life policy is reconstruction policy, not a recovered original server
+respawn timer. Public NPC replacement timers remain unchanged.
+
+Abandonment and expiry revoke credentials, evacuate occupants, remove private
+NPCs and destroy unclaimed corpse loot in the same transaction. Failure leaves
+actors, loot windows, known objects and runtime queues untouched for retry.
+Only after commit are combat, interest, corpse/respawn queues and geometry
+removed. Periodic checkpoints cannot recreate retired actors. Items already
+transferred to a player retain their identities and ownership. Successful
+objective settlement retains the population until the assignment's existing
+deadline, including surviving enemies and dead remains; it does not reset them.
+
+## Indoor movement limits
+
+Indoor pursuit now applies the shared model-specific collision body, room veto,
+swept walls, sphere response and floors. Small time steps, gravity and slope
+projection follow the existing player movement machinery. Position changes stay
+in memory until the existing periodic NPC checkpoint. Both the entrance and
+z28-to-z43 routes cross the actual inter-room portal and return home without per-tick writes. The entrance spawn is grounded on
+the tongue mesh at y1.476895, rather than the lower floor beneath that scenery.
+
+Straight steering still has no detour planner. Native testing exposed an
+authored entrance spawn below the tongue mesh; correcting its vertical placement
+lets shared collision handling traverse the rib in both directions. General
+obstacle routes remain a separate navigation task. Making a Leet use a
+humanoid collision sphere or skipping walls would conceal missing route behavior.
+
+Original KKR `FUN_10048430`, maintained as
+`client/game/kkr.dll/lifted-0023.c:sub_36048430`, does not establish an original
+server path planner. Its low/high half-metre LOS probes at heights .11 and 1.2
+retry a suspicious waypoint and discard it after five checks; they do not raise
+the actor. A separate within-one-metre waypoint reconciliation projects downward
+two metres and ignores collision only when follower owner and follow target
+identities differ. Our native routes target self, excluding that branch.
+Shared QQR `Vehicle::Run` still invokes surface alignment after integration.
+Evidence and exact addresses are retained in
+`local/npc-pursuit-research/followSteering.json` and
+`local/mission-encounter-research/integration-audit.md`.
+
+## Completion token evidence
+
+Mission completion XP/token eligibility remains unresolved. Ordinary kill XP
+must not be confused with the separately advertised completion reward.
+The recovered original item descriptors establish token upload behavior:
+
+- Mission Tokens96349/96350 are physical Unique items restricted to Omni/Clan.
+- Right-click Use evaluates the user's current level and adds token values to
+ stats75/62. It starts at1, adding1 above levels14,49 (Omni) or50 (Clan),74,99,
+ 124,149,174 and189. Preserve the original faction boundary difference.
+- QL250 token designs152932/152933 add25. Bravery Tokens158421/158422 add1.
+
+These are upload effects, not proof that completing a contract should create a
+particular token, pay XP, or grant several copies. The exact kill threshold,
+chance formula, grey-enemy denominator, faction/backyard exceptions and completion
+XP arithmetic have not been recovered. Do not infer them from later approximate
+player advice. Extracted descriptors, contemporary source notes and uncertainty
+are retained in `local/mission-encounter-research/token-eligibility.md` and
+`original-token-records.json` there.
+
+## Verification
+
+Go tests cover atomic acceptance and allocation, unsupported definitions/levels,
+invalid placements, cold population recovery, shared kill XP/loot/cash, no private
+replacement life, portal pursuit/return, wall rejection and checkpoint cadence.
+Lifecycle tests cover abandonment, active/completed expiry, settlement retaining
+actors, preserving transferred loot, and no resurrection on later checkpoints.
+SQLite faults include aborted/ignored actor, NPC, item, mission and counter
+writes, late actor mutation/deletion/reinsertion, and deferred commit failure.
+Each failed operation is retried through the same public handler.
+
+The focused server regression selection passed299 test roots and1959 results;
+race checks passed35 roots and84 results. Vet and the preview build passed.
+A completed-expiry fixture correction was checked again through the retirement
+handler. Logs and assertion-based accounting are retained under
+`local/mission-encounter-research/`.
+
+GPU WASM checks used ordinary terminal acceptance, keyed entry, targeting,
+combat, corpse interaction and journal abandonment. Cold loading restored all
+five original actor identities. A native unarmed visitor death preserved the
+assignment; that character lacked its issued starter weapon. Outcome testing
+then used an explicitly controlled player with raw Body Development100 and
+300HP. One enemy was pre-injured; a second began at its full original100HP.
+These are protocol/lifecycle checks, not ordinary fresh-character balance proof.
+
+Both deaths granted100 kill XP each. The first corpse expired with an unclaimed
+Monster Part37 and two credits, without a replacement life. The full-health
+fight generated Part38; native corpse opening collected three credits and the
+native inventory transfer retained that same instance. Abandonment removed the
+key35, objective36 and all private NPC state while returning the player outside.
+The two existing glove instances3/34, equipped hands slot24, Part38,200XP and
+45credits remained. The next native acceptance charged its one-credit fee
+and allocated a separate world with five fresh identities, including the
+corrected entrance height. Native expiry closed the corpse window; open-window mission
+retirement is additionally covered by the Go fault/retry tests. No browser
+exceptions or adapter aborts were recorded. Existing unattributed404 console
+messages remain in the captured logs.
+
+Fighting around raised scenery also exposed the existing lack of combat LOS
+rejection. A small actor below the tongue could fight a player above it; its
+corpse was easier to select from the other side. This remains P0 work alongside
+general detour routing, separately from the corrected authored entrance spawn.
+
+A final cold restart restored the test character's original raw Body
+Development5 and normal HP while retaining200XP,44credits after the next request
+fee, both gloves, Part38, key39 and bound objective40. The fresh world retained
+exactly five full-health Leets, with the corrected entrance height, and the
+retired world's NPCs remained absent. Native inventory/equipment replay and SQL
+integrity/foreign-key checks passed. The owned browsers were closed afterward;
+the single LAN preview remains on HTTPS8443 with the normal default game ports.
diff --git a/docs/npc-pursuit.md b/docs/npc-pursuit.md
@@ -31,16 +31,18 @@ server as 4.5 metres/second. Selecting that default for admitted pursuit and ret
is provisional; it is not an original-server species speed measurement. The
close-approach threshold comes from native NPC steering `FUN_10048430`, whose
near-target branch checks squared distance below 4 and line of sight. The
-server currently assumes open ground; it has no obstruction or navigation
-mesh check. Its existing terrain-height interpolation preserves the authored
-spawn offset, and each scheduler step remains capped at 0.25 seconds.
+server still steers straight toward the destination without detour planning.
+Outdoor terrain-height interpolation preserves the authored spawn offset.
+Indoor pursuit now uses shared collision bodies, walls, room veto, floor and
+gravity in small steps; see [mission movement limits](mission-encounters.md#indoor-movement-limits).
+Each scheduler step remains capped at 0.25 seconds.
Return to the retained spawn is an explicit reconstruction policy. A bounded
source search found no period Leet rule proving that exact destination or its
timing. Return continues without observers. Health uses the separate
[recovery rule](npc-regeneration.md), including while returning. Unprofiled
appearance stand-ins do not acquire combat pursuit. Proximity aggression,
-obstruction rejection and obstacle navigation remain separate TODOs.
+outdoor obstruction rejection and general obstacle navigation remain separate TODOs.
Motion state retains home, destination, idle-wandering eligibility and return
progress independently of combat capability. It uses the existing periodic NPC
diff --git a/server/combat.go b/server/combat.go
@@ -556,9 +556,9 @@ func (server *server) finishDamageEffects_locked(attacker, target *character, pr
}
server.queueCombat_locked(updates, target, target, corpsePacket(target))
}
- if target.npc && target.combatProfile != nil && target.combatProfile.RespawnSeconds != 0 {
+ if respawn := server.npcRespawnAt_locked(target, now); target.npc && !respawn.IsZero() {
server.npcRespawns = append(server.npcRespawns, npcRespawn{
- npc: target, at: now.Add(time.Duration(target.combatProfile.RespawnSeconds) * time.Second),
+ npc: target, at: respawn,
})
}
} else if target.npc && !attacker.npc {
diff --git a/server/corpse_credits_test.go b/server/corpse_credits_test.go
@@ -216,7 +216,7 @@ func TestCorpseCreditsRejectOutOfRangePersistentBalance(t *testing.T) {
if _, err := saved.db.Exec(`UPDATE players SET credits=1000000001 WHERE id=1`); err != nil {
t.Fatal(err)
}
- world := &server{characters: make(map[uint32]*character)}
+ world := &server{db: saved.db, characters: make(map[uint32]*character)}
err := world.loadUsers()
diff --git a/server/gamedata/missions.yaml b/server/gamedata/missions.yaml
@@ -19,3 +19,15 @@
# A fixed reconstruction selection; original mission reward-pool selection is unresolved.
reward_item: 85596
reward_quality: 2
+
+ # Fixed encounter selection and positions are reconstruction policy.
+ # Species appearance, weapon and loot use the shared admitted NPC profile.
+ encounters:
+ - definition: 950/district/2/group/0/authored_point
+ level: 1
+ positions:
+ - [15, 0, 48]
+ - [15, 0, 43]
+ - [15, 0, 36]
+ - [15, 0, 28]
+ - [15, 1, 20]
diff --git a/server/gamedata/types.go b/server/gamedata/types.go
@@ -21,15 +21,22 @@ type MissionBooth struct {
}
type MissionTemplate struct {
- Description string `yaml:"description"`
- Playfield uint32 `yaml:"playfield"`
- Entrance uint32 `yaml:"entrance"`
- Position [3]float32 `yaml:"position"`
- ObjectiveItem uint32 `yaml:"objective_item"`
- Credits uint32 `yaml:"credits"`
- Experience uint32 `yaml:"experience"`
- RewardItem uint32 `yaml:"reward_item"`
- RewardQuality uint32 `yaml:"reward_quality"`
+ Description string `yaml:"description"`
+ Playfield uint32 `yaml:"playfield"`
+ Entrance uint32 `yaml:"entrance"`
+ Position [3]float32 `yaml:"position"`
+ ObjectiveItem uint32 `yaml:"objective_item"`
+ Credits uint32 `yaml:"credits"`
+ Experience uint32 `yaml:"experience"`
+ RewardItem uint32 `yaml:"reward_item"`
+ RewardQuality uint32 `yaml:"reward_quality"`
+ Encounters []MissionEncounter `yaml:"encounters"`
+}
+
+type MissionEncounter struct {
+ Definition string `yaml:"definition"`
+ Level uint16 `yaml:"level"`
+ Positions [][3]float32 `yaml:"positions"`
}
type ItemCombination struct {
diff --git a/server/item_database.go b/server/item_database.go
@@ -132,6 +132,9 @@ func (server *server) persistItems_locked(store itemStore) error {
zones[server.characters[id].playfield] = true
}
}
+ if store.removedMission != nil {
+ delete(zones, store.removedMission.world)
+ }
savedNPCs, err := server.writeNPCs_locked(tx, store, zones)
if err != nil {
return err
@@ -191,6 +194,15 @@ func (server *server) persistItems_locked(store itemStore) error {
if err := insertMission(tx, store.mission); err != nil {
return err
}
+ // The selected population commits with its assignment, independently of entry.
+ for _, npc := range store.spawnedNPCs {
+ npc.playfield = store.mission.world
+ state := npc.worldState(true, time.Time{})
+ if err := writeNPCState_locked(tx, npc, &state); err != nil {
+ return err
+ }
+ savedNPCs[npc.id] = savedNPC{State: state, NextSave: time.Now().Add(20 * time.Second)}
+ }
}
if store.updatedMission != nil {
mission := store.updatedMission
@@ -239,17 +251,18 @@ func (server *server) persistItems_locked(store itemStore) error {
if started.IsZero() {
started = time.Now()
}
+ nextNPC := server.nextNPC + uint32(len(store.spawnedNPCs))
if _, err := tx.Exec(`UPDATE world SET last_item_id=?1, last_character_id=max(last_character_id, ?2),
last_npc_id=?3, game_seconds=?4, clock_started=?5, npcs_initialized=1
WHERE id=1 AND (last_item_id, last_character_id, last_npc_id, game_seconds, clock_started, npcs_initialized)
IS NOT (?1, max(last_character_id, ?2), ?3, ?4, ?5, 1)`,
- store.LastID, server.nextCharacter, server.nextNPC, server.gameSeconds, started.UTC().Format(time.RFC3339Nano)); err != nil {
+ store.LastID, server.nextCharacter, nextNPC, server.gameSeconds, started.UTC().Format(time.RFC3339Nano)); err != nil {
return err
}
var savedID uint32
if err := tx.QueryRow(`SELECT id FROM world WHERE id=1 AND last_item_id=? AND last_character_id>=?
AND (last_npc_id, game_seconds, clock_started, npcs_initialized) IS (?, ?, ?, 1)`,
- store.LastID, server.nextCharacter, server.nextNPC, server.gameSeconds, started.UTC().Format(time.RFC3339Nano)).Scan(&savedID); err != nil {
+ store.LastID, server.nextCharacter, nextNPC, server.gameSeconds, started.UTC().Format(time.RFC3339Nano)).Scan(&savedID); err != nil {
return fmt.Errorf("world inventory allocation was not saved: %w", err)
}
if store.mission != nil {
@@ -285,6 +298,28 @@ func (server *server) persistItems_locked(store itemStore) error {
}
}
}
+ for _, npc := range store.spawnedNPCs {
+ var state npcState
+ fields := append([]any{&state.Character.Profile.ID}, state.Character.fields()...)
+ if err := tx.QueryRow("SELECT id, "+characterColumns+", "+npcColumns+" FROM characters JOIN npcs USING(id) WHERE id=?", npc.id).
+ Scan(append(fields, state.fields()...)...); err != nil {
+ return fmt.Errorf("mission NPC %d was not saved: %w", npc.id, err)
+ }
+ if state != npc.worldState(true, time.Time{}) {
+ return fmt.Errorf("mission NPC %d state changed before commit", npc.id)
+ }
+ }
+ if store.removedMission != nil {
+ var remaining int
+ if err := tx.QueryRow(`SELECT
+ (SELECT count(*) FROM characters WHERE id>=1000000 AND playfield=?) +
+ (SELECT count(*) FROM missions WHERE id=?)`, store.removedMission.world, store.removedMission.id).Scan(&remaining); err != nil {
+ return err
+ }
+ if remaining != 0 {
+ return fmt.Errorf("retired mission %d retains its assignment or NPCs", store.removedMission.id)
+ }
+ }
if err := tx.Commit(); err != nil {
return err
}
diff --git a/server/item_store.go b/server/item_store.go
@@ -57,6 +57,7 @@ type itemStore struct {
mission *acceptedMission
updatedMission *acceptedMission
removedMission *acceptedMission
+ spawnedNPCs []*character
inventoryPlayers []uint32
checkpointAt time.Time
flush bool
@@ -267,6 +268,14 @@ func (server *server) writeItemStore_locked(store itemStore) error {
server.items = store.Items
server.worldItems = store.WorldItems
server.nextItem = store.LastID
+ for _, npc := range store.spawnedNPCs {
+ server.characters[npc.id] = npc
+ if server.mobileNPCs == nil {
+ server.mobileNPCs = make(map[uint32][]*character)
+ }
+ server.mobileNPCs[npc.playfield] = append(server.mobileNPCs[npc.playfield], npc)
+ server.nextNPC = npc.id + 1
+ }
if store.updatedMission != nil {
mission := store.updatedMission
for index := range server.missionExpiry {
diff --git a/server/mission_completion.go b/server/mission_completion.go
@@ -85,7 +85,7 @@ func (server *server) handleMissionReturn(client *worldClient, body []byte) erro
return nil
}
- // Empty prototypes have no qualifying kills for the separately conditional XP/token.
+ // Completion XP/token eligibility is separate from ordinary kill rewards.
mission := player.missions[index]
updates := make(map[*worldClient][][]byte)
if _, err := server.endMission_locked(mission, true, updates); err != nil {
diff --git a/server/mission_encounter_lifecycle_test.go b/server/mission_encounter_lifecycle_test.go
@@ -0,0 +1,311 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "fmt"
+ "reflect"
+ "slices"
+ "testing"
+ "time"
+)
+
+func killedMissionEncounterWorld(t *testing.T) (*server, *worldClient, *combatTestConn, time.Time) {
+ t.Helper()
+ world, client, output := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000004]
+ player.position = npc.position
+ player.position[2]--
+ npc.health = 1
+ world.combatRoll = func(uint32) uint32 { return 0 }
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleCombat(client, attackPacket(1, npc.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ killed := player.nextAttack
+ world.advanceCombat(killed)
+ if npc.health != 0 {
+ t.Fatal("ordinary attack did not kill the mission encounter", npc.health, player.fighting)
+ }
+ output.packets = nil
+ return world, client, output, killed
+}
+
+func TestMissionEncounterKillLootAndColdRestartDoNotCreateAnotherLife(t *testing.T) {
+ world, client, _, killed := killedMissionEncounterWorld(t)
+ before := world.nextItem
+ request := lootUseRequest(1)
+ binary.BigEndian.PutUint32(request[44:48], 2000004)
+
+ if err := world.handleLootUse(client, request); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleInventory(client, lootTakeRequest()); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(killed.Add(time.Hour))
+ world.advanceNPCRespawns(killed.Add(time.Hour))
+ cold := reloadMissionEntranceWorld(t)
+ cold.advanceNPCRespawns(killed.Add(time.Hour))
+
+ for _, current := range []*server{world, cold} {
+ player, npc := current.characters[1], current.characters[2000004]
+ if player.experience != 100 || player.inventory.Credits != 5 || npc.health != 0 || npc.corpse == nil ||
+ len(npc.corpse.items) != 0 || npc.corpse.credits != 0 || len(current.npcRespawns) != 0 || current.nextNPC != 2000005 || current.nextItem != before {
+ t.Fatal("mission kill, loot, XP or one-life population changed", player.experience, player.inventory, npc.corpse, current.npcRespawns)
+ }
+ if !slices.Contains(player.inventory.Items, ownedItem{ID: before, Type: 51005, Template: 42640, Quality: 1, Slot: 66, Count: 1}) {
+ t.Fatal("shared generated loot did not retain its identity", player.inventory.Items)
+ }
+ }
+}
+
+func TestMissionEncounterRetirementRemovesActorsLootAndQueuesAfterCommit(t *testing.T) {
+ for _, reason := range []string{"abandon", "expiry", "completed expiry"} {
+ t.Run(reason, func(t *testing.T) {
+ world, client, output, killed := killedMissionEncounterWorld(t)
+ mission := world.characters[1].missions[0]
+ drop := world.characters[2000004].corpse.items[0].ID
+ client.lootCorpse = 2000004
+ other := world.characters[2000003]
+ other.fighting = 1
+ world.fighting[other.id] = other
+ world.characters[1].fighting = other.id
+ world.fighting[1] = world.characters[1]
+ if reason == "completed expiry" {
+ mission.completed = true
+ world.characters[1].missions[0] = mission
+ world.missionExpiry[0] = mission
+ if _, err := world.db.Exec("UPDATE missions SET completed=1 WHERE id=?", mission.id); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if reason == "abandon" {
+ if err := world.handleMissionRemoval(client, missionRemovalPacket(1, mission.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ world.advanceMissions(mission.expiresAt.Add(time.Nanosecond))
+ }
+ world.advanceNPCRespawns(killed.Add(time.Hour))
+ world.advanceCorpseExpiry(killed.Add(time.Hour))
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ cold := reloadMissionEntranceWorld(t)
+
+ for _, current := range []*server{world, cold} {
+ if current.characters[1].playfield != 3000 || current.characters[1].experience != 100 ||
+ len(current.characters[1].missions) != 0 || len(current.mobileNPCs[65536]) != 0 ||
+ len(current.npcRespawns) != 0 || len(current.corpseExpiry) != 0 || current.characters[1000000] == nil {
+ t.Fatal("retirement lost player progress or retained a private world", current.characters[1], current.npcRespawns)
+ }
+ for id := uint32(2000000); id < 2000005; id++ {
+ if current.characters[id] != nil || current.savedNPCs[id].State.Character.Profile.ID != 0 || current.fighting[id] != nil {
+ t.Fatal("retired NPC was retained or recreated", id)
+ }
+ }
+ if _, exists := current.items[drop]; exists {
+ t.Fatal("unclaimed corpse loot outlived its private world", drop)
+ }
+ }
+ if client.lootCorpse != 0 || len(world.fighting) != 0 || world.geometry.mission(65536) != nil || len(output.packets) == 0 {
+ t.Fatal("committed retirement retained combat, loot or geometry")
+ }
+ })
+ }
+}
+
+func TestMissionEncounterRetirementFailurePreservesPopulationThenRetries(t *testing.T) {
+ for _, statement := range []string{
+ "CREATE TRIGGER reject_retirement BEFORE DELETE ON characters WHEN OLD.id>=2000000 BEGIN SELECT RAISE(ABORT, 'actor'); END",
+ "CREATE TRIGGER reject_retirement BEFORE DELETE ON characters WHEN OLD.id>=2000000 BEGIN SELECT RAISE(IGNORE); END",
+ "CREATE TRIGGER reject_retirement BEFORE DELETE ON npcs WHEN OLD.id>=2000000 BEGIN SELECT RAISE(IGNORE); END",
+ "CREATE TRIGGER reject_retirement BEFORE DELETE ON items WHEN OLD.template=42640 BEGIN SELECT RAISE(IGNORE); END",
+ "CREATE TRIGGER reject_retirement BEFORE DELETE ON missions BEGIN SELECT RAISE(IGNORE); END",
+ "CREATE TRIGGER reject_retirement AFTER UPDATE OF last_item_id ON world BEGIN INSERT INTO characters SELECT * FROM retired_actor; INSERT INTO npcs SELECT * FROM retired_npc; END",
+ "CREATE TABLE pending_retirement (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_retirement AFTER DELETE ON npcs BEGIN INSERT INTO pending_retirement VALUES (999999); END",
+ } {
+ t.Run(fmt.Sprint(statement), func(t *testing.T) {
+ world, client, output, _ := killedMissionEncounterWorld(t)
+ mission := world.characters[1].missions[0]
+ client.lootCorpse = 2000004
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ known := len(client.npcs)
+ corpses := slices.Clone(world.corpseExpiry)
+ if _, err := world.db.Exec("CREATE TABLE retired_actor AS SELECT * FROM characters WHERE id=2000000; CREATE TABLE retired_npc AS SELECT * FROM npcs WHERE id=2000000"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+
+ failure := world.handleMissionRemoval(client, missionRemovalPacket(1, mission.id)[20:])
+ after, err := readTestItemStore(world)
+ cold := reloadMissionEntranceWorld(t)
+
+ if failure == nil || err != nil || !reflect.DeepEqual(before, after) || len(output.packets) != 0 || len(client.npcs) != known ||
+ client.lootCorpse != 2000004 || !slices.Equal(corpses, world.corpseExpiry) || world.geometry.mission(65536) == nil {
+ t.Fatal("failed retirement published partial changes", failure, err)
+ }
+ for _, current := range []*server{world, cold} {
+ if current.characters[1].playfield != 65536 || len(current.characters[1].missions) != 1 || current.characters[2000000] == nil ||
+ current.characters[2000004].corpse == nil || len(current.characters[2000004].corpse.items) != 1 {
+ t.Fatal("failed retirement changed durable mission actors or loot")
+ }
+ }
+
+ if _, err := world.db.Exec("DROP TRIGGER reject_retirement"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleMissionRemoval(client, missionRemovalPacket(1, mission.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+
+ if world.characters[2000000] != nil || world.characters[2000004] != nil || world.characters[1].playfield != 3000 || client.lootCorpse != 0 {
+ t.Fatal("retirement retry retained actors or loot")
+ }
+ })
+ }
+}
+
+func TestMissionEncounterCompletionKeepsPopulationAndClaimedLoot(t *testing.T) {
+ world, client, _, _ := killedMissionEncounterWorld(t)
+ player := world.characters[1]
+ mission := player.missions[0]
+ loot := world.nextItem
+ request := lootUseRequest(1)
+ binary.BigEndian.PutUint32(request[44:48], 2000004)
+ if err := world.handleLootUse(client, request); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleInventory(client, lootTakeRequest()); err != nil {
+ t.Fatal(err)
+ }
+ player.position = world.worldItems[mission.objective].position
+ if err := world.handleInventory(client, worldPickupRequest(1, mission.objective)); err != nil {
+ t.Fatal(err)
+ }
+ destination := player.userData()
+ destination.Playfield, destination.Position = 3000, gamedata.MissionBooths[3221228472].Position
+ if err := world.updateUser_locked(destination); err != nil {
+ t.Fatal(err)
+ }
+ world.clients[1], client.ready, client.loading = client, true, false
+
+ returnRequest := missionReturnRequest(2)
+ binary.BigEndian.PutUint32(returnRequest[44:48], 67)
+ if err := world.handleMissionReturn(client, returnRequest); err != nil {
+ t.Fatal(err)
+ }
+ cold := reloadMissionEntranceWorld(t)
+
+ for _, current := range []*server{world, cold} {
+ living := 0
+ for _, npc := range current.mobileNPCs[65536] {
+ if npc.health != 0 {
+ living++
+ }
+ }
+ if len(current.characters[1].missions) != 0 || living != 4 || !current.missionExpiry[0].completed ||
+ current.characters[2000000].health != 100 || current.characters[2000004].health != 0 || current.characters[2000004].corpse == nil ||
+ current.characters[1].experience != 100 || current.characters[1].inventory.Credits != 25 || current.items[loot].Template != 42640 {
+ t.Fatal("completion retired the population, repeated kill XP or lost claimed loot")
+ }
+ }
+
+ world.advanceMissions(mission.expiresAt)
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ cold = reloadMissionEntranceWorld(t)
+
+ if cold.characters[2000000] != nil || cold.characters[2000004] != nil || cold.items[loot].Template != 42640 ||
+ cold.itemPlacements[loot] != (itemPlacement{Player: 1, Slot: 66}) || cold.characters[1].experience != 100 {
+ t.Fatal("completed-world retirement destroyed transferred loot or recreated its source", cold.itemPlacements[loot])
+ }
+}
+
+func TestMissionEncounterDifferentWorldRejectsCombatNanoAndLoot(t *testing.T) {
+ for _, action := range []string{"attack", "nano", "corpse", "pickup"} {
+ t.Run(action, func(t *testing.T) {
+ world, client, _, _ := killedMissionEncounterWorld(t)
+ player := world.characters[1]
+ player.playfield = 65537
+ player.profession, player.nano = 8, 30
+ player.stats.NanoAiding.PsychologicalModification, player.stats.NanoAiding.MatterCreation = 7, 6
+ player.inventory.LearnedNanos = []uint32{29618}
+ client.lootCorpse = 2000004
+ // Stale known-object state must not confer authority across private worlds.
+ client.npcs[2000003], client.npcs[2000004] = true, true
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ switch action {
+ case "attack":
+ err = world.handleCombat(client, attackPacket(1, 2000003)[20:])
+ world.advanceCombat(time.Now().Add(time.Minute))
+ case "nano":
+ err = world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 2000003, 53019, 29618})[20:])
+ world.advanceNanos(time.Now().Add(time.Minute))
+ case "corpse":
+ client.lootCorpse = 0
+ request := lootUseRequest(1)
+ binary.BigEndian.PutUint32(request[44:48], 2000004)
+ err = world.handleLootUse(client, request)
+ case "pickup":
+ err = world.handleInventory(client, lootTakeRequest())
+ }
+ after, readErr := readTestItemStore(world)
+
+ if err != nil || readErr != nil || !reflect.DeepEqual(before, after) || player.fighting != 0 || client.nanoCast != nil ||
+ player.nano != 30 || player.nanoReserved != 0 || player.experience != 100 || world.characters[2000003].health != 100 ||
+ len(world.characters[2000004].corpse.items) != 1 || world.characters[2000004].corpse.credits != 1 {
+ t.Fatal("private-world boundary admitted a stale target, cast or loot source", err, readErr)
+ }
+ })
+ }
+}
+
+func TestMissionEncounterRetirementRemovesHiddenSourcesWithoutTouchingAnotherWorld(t *testing.T) {
+ world, client, _, killed := killedMissionEncounterWorld(t)
+ mission := world.characters[1].missions[0]
+ hidden := world.characters[2000004]
+ delete(world.characters, hidden.id)
+ world.npcRespawns = append(world.npcRespawns, npcRespawn{npc: hidden, at: killed.Add(time.Hour)})
+ other := makeNPCSpawn(gamedata.NPCGroups[hidden.npcDefinitionID], 1, hidden.position)
+ other.id, other.playfield = 2000005, 65537
+ world.characters[other.id] = &other
+ world.mobileNPCs[other.playfield] = []*character{&other}
+ world.nextNPC++
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := world.handleMissionRemoval(client, missionRemovalPacket(1, mission.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceNPCRespawns(killed.Add(2 * time.Hour))
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ cold := reloadMissionEntranceWorld(t)
+
+ for _, current := range []*server{world, cold} {
+ if current.characters[hidden.id] != nil || len(current.npcRespawns) != 0 || current.characters[other.id] == nil ||
+ current.characters[other.id].playfield != 65537 || current.characters[other.id].health != 100 || len(current.mobileNPCs[65537]) != 1 {
+ t.Fatal("retired hidden source returned or retirement changed another world's encounter")
+ }
+ }
+}
diff --git a/server/mission_encounters.go b/server/mission_encounters.go
@@ -0,0 +1,61 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "fmt"
+ "math"
+ "time"
+)
+
+func (server *server) stageMissionEncounters_locked(mission *acceptedMission) ([]*character, error) {
+ if len(mission.offer.definition.Encounters) == 0 {
+ return nil, nil
+ }
+ layout, err := decodeMissionLayout(mission.layout)
+ if err != nil {
+ return nil, err
+ }
+ scene, err := server.geometry.missionScene(layout)
+ if err != nil {
+ return nil, err
+ }
+ var spawned []*character
+ for _, encounter := range mission.offer.definition.Encounters {
+ group := gamedata.NPCGroups[encounter.Definition]
+ if group == nil || npcCombatProfile(group.ID, group.MonsterData, encounter.Level) == nil || len(encounter.Positions) == 0 {
+ return nil, fmt.Errorf("unsupported mission encounter %s level %d", encounter.Definition, encounter.Level)
+ }
+ for _, position := range encounter.Positions {
+ if uint64(server.nextNPC)+uint64(len(spawned))+1 > math.MaxUint32 {
+ return nil, fmt.Errorf("mission NPC identities exhausted")
+ }
+ for _, value := range position {
+ if math.IsNaN(float64(value)) || math.IsInf(float64(value), 0) {
+ return nil, fmt.Errorf("invalid mission encounter position")
+ }
+ }
+ // Ground encounters use the saved layout's actual floor and room admission.
+ origin := position
+ origin[1]++
+ var normal [3]float32
+ position[1] = -9999
+ scene.floor(origin, &position, &normal)
+ position[1] += .01
+ if scene.roomAt(position) == nil || normal[1] <= 0 {
+ return nil, fmt.Errorf("mission encounter has no floor at %v", position)
+ }
+ npc := makeNPCSpawn(group, encounter.Level, position)
+ npc.id, npc.geometry = server.nextNPC+uint32(len(spawned)), server.geometry
+ npc.motion.roaming = false
+ spawned = append(spawned, &npc)
+ }
+ }
+ return spawned, nil
+}
+
+func (server *server) npcRespawnAt_locked(npc *character, now time.Time) time.Time {
+ if server.missionWorld_locked(npc.playfield) != nil || npc.combatProfile == nil || npc.combatProfile.RespawnSeconds == 0 {
+ return time.Time{}
+ }
+ return now.Add(time.Duration(npc.combatProfile.RespawnSeconds) * time.Second)
+}
diff --git a/server/mission_encounters_test.go b/server/mission_encounters_test.go
@@ -0,0 +1,234 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "math"
+ "reflect"
+ "testing"
+ "time"
+)
+
+func newMissionEncounterOfferWorld(t *testing.T) (*server, *combatTestConn) {
+ t.Helper()
+ encounters := gamedata.MissionTemplates[3221228472].Encounters
+ world, output := newMissionOfferWorld(t)
+ t.Cleanup(func() { world.db.Close() })
+ definition := gamedata.MissionTemplates[3221228472]
+ definition.Encounters = encounters
+ gamedata.MissionTemplates[3221228472] = definition
+ world.geometry = missionGeometryFixture(t)
+ world.geometry.models = make(map[uint32]collisionSphere)
+ world.nextNPC = 2000000
+ if err := world.handleMissionOffers(world.clients[1], missionOffersRequest()); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+ return world, output
+}
+
+func TestMissionEncounterAcceptanceCommitsConcretePopulationAndRestoresIt(t *testing.T) {
+ world, output := newMissionEncounterOfferWorld(t)
+ client := world.clients[1]
+ request := missionAcceptanceRequest(*client.missionOffer)
+
+ if err := world.handleMissionAcceptance(client, request); err != nil {
+ t.Fatal(err)
+ }
+ cold := reloadMissionEntranceWorld(t)
+ mission := world.characters[1].missions[0]
+
+ if world.nextNPC != 2000005 || cold.nextNPC != 2000005 || len(world.mobileNPCs[65536]) != 5 ||
+ len(cold.mobileNPCs[65536]) != 5 || !reflect.DeepEqual(mission, cold.characters[1].missions[0]) || len(output.packets) != 2 {
+ t.Fatal("accepted population or contract changed on restart", world.nextNPC, cold.nextNPC, output.packets)
+ }
+ for index, z := range []float32{48, 43, 36, 28, 20} {
+ id := 2000000 + uint32(index)
+ npc, restored := world.characters[id], cold.characters[id]
+ if npc == nil || restored == nil || npc.id != id || npc.playfield != 65536 || npc.level != 1 || npc.monsterData != 17655 ||
+ npc.name != "Leet" || npc.health != 100 || npc.position[0] != 15 || npc.position[2] != z || npc.combatProfile == nil ||
+ npc.motion == nil || npc.motion.roaming || npc.motion.home != npc.position ||
+ npc.npcDefinitionID != "950/district/2/group/0/authored_point" || npc.worldState(true, time.Time{}) != restored.worldState(true, time.Time{}) {
+ t.Fatal("selected encounter lost its admitted profile, placement or identity", id, npc, restored)
+ }
+ height := float32(.011)
+ if index == 4 {
+ height = 1.476895
+ }
+ if math.Abs(float64(npc.position[1]-height)) > .000001 {
+ t.Fatal("encounter was placed beneath its actual mesh floor", npc.position)
+ }
+ }
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x29304349 {
+ t.Fatal("private population leaked into the exterior")
+ }
+ }
+}
+
+func TestMissionEncounterInvalidSelectionCannotConsumeOfferOrKey(t *testing.T) {
+ for _, scenario := range []string{"unknown definition", "unsupported level", "empty positions", "outside", "nan", "identities"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, output := newMissionEncounterOfferWorld(t)
+ client := world.clients[1]
+ definition := client.missionOffer.definition
+ definition.Encounters = []gamedata.MissionEncounter{{Definition: "950/district/2/group/0/authored_point", Level: 1, Positions: [][3]float32{{15, 0, 43}}}}
+ switch scenario {
+ case "unknown definition":
+ definition.Encounters[0].Definition = "missing"
+ case "unsupported level":
+ definition.Encounters[0].Level = 3
+ case "empty positions":
+ definition.Encounters[0].Positions = nil
+ case "outside":
+ definition.Encounters[0].Positions[0] = [3]float32{500, 0, 500}
+ case "nan":
+ definition.Encounters[0].Positions[0][0] = float32(math.NaN())
+ case "identities":
+ world.nextNPC = math.MaxUint32
+ }
+ client.missionOffer.definition = definition
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ failure := world.handleMissionAcceptance(client, missionAcceptanceRequest(*client.missionOffer))
+ after, err := readTestItemStore(world)
+
+ if failure == nil || err != nil || !bytes.Equal(before, after) || len(world.characters) != 2 ||
+ client.missionOffer == nil || len(world.characters[1].missions) != 0 || len(output.packets) != 0 {
+ t.Fatal("unsupported encounter consumed the offer or published partial state", failure, err)
+ }
+ })
+ }
+}
+
+func TestMissionEncounterAcceptanceRollsBackPopulationAndRetries(t *testing.T) {
+ for _, statement := range []string{
+ "CREATE TRIGGER reject_population BEFORE INSERT ON characters WHEN NEW.id>=2000000 BEGIN SELECT RAISE(ABORT, 'actor'); END",
+ "CREATE TRIGGER reject_population BEFORE INSERT ON characters WHEN NEW.id>=2000000 BEGIN SELECT RAISE(IGNORE); END",
+ "CREATE TRIGGER reject_population BEFORE INSERT ON npcs WHEN NEW.id>=2000000 BEGIN SELECT RAISE(ABORT, 'npc'); END",
+ "CREATE TRIGGER reject_population BEFORE INSERT ON npcs WHEN NEW.id>=2000000 BEGIN SELECT RAISE(IGNORE); END",
+ "CREATE TRIGGER reject_population BEFORE UPDATE OF last_npc_id ON world BEGIN SELECT RAISE(IGNORE); END",
+ "CREATE TRIGGER reject_population AFTER UPDATE OF last_item_id ON world BEGIN UPDATE characters SET level=2 WHERE id=2000000; END",
+ "CREATE TRIGGER reject_population AFTER UPDATE OF last_item_id ON world BEGIN DELETE FROM npcs WHERE id=2000000; END",
+ "CREATE TABLE pending_population (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_population AFTER INSERT ON npcs WHEN NEW.id>=2000000 BEGIN INSERT INTO pending_population VALUES (999999); END",
+ } {
+ t.Run(statement, func(t *testing.T) {
+ world, output := newMissionEncounterOfferWorld(t)
+ client := world.clients[1]
+ request := missionAcceptanceRequest(*client.missionOffer)
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+
+ failure := world.handleMissionAcceptance(client, request)
+ cold := newTestInventoryServer(t)
+ after, err := readTestItemStore(world)
+
+ if failure == nil || err != nil || !bytes.Equal(before, after) || world.nextNPC != 2000000 ||
+ len(world.characters) != 2 || len(cold.characters) != 2 || len(world.characters[1].missions) != 0 ||
+ len(cold.characters[1].missions) != 0 || len(world.mobileNPCs) != 0 || len(output.packets) != 0 || client.missionOffer == nil {
+ t.Fatal("failed acceptance leaked encounter state, allocation or publication", failure, err)
+ }
+
+ if _, err := world.db.Exec("DROP TRIGGER reject_population"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleMissionAcceptance(client, request); err != nil {
+ t.Fatal(err)
+ }
+ cold = newTestInventoryServer(t)
+
+ if world.nextNPC != 2000005 || cold.nextNPC != 2000005 || len(world.characters) != 7 || len(cold.characters) != 7 ||
+ len(output.packets) != 2 || len(world.mobileNPCs[65536]) != 5 {
+ t.Fatal("retry did not commit exactly one original population", world.nextNPC, cold.nextNPC)
+ }
+ })
+ }
+}
+
+func enteredMissionEncounterWorld(t *testing.T) (*server, *worldClient, *combatTestConn) {
+ t.Helper()
+ world, output := newMissionEncounterOfferWorld(t)
+ client := world.clients[1]
+ if err := world.handleMissionAcceptance(client, missionAcceptanceRequest(*client.missionOffer)); err != nil {
+ t.Fatal(err)
+ }
+ player := world.characters[1]
+ player.geometry = world.geometry
+ player.position, player.rotation = [3]float32{89.30216, 115.75, 152.5}, [4]float32{0, 1, 0, 0}
+ if err := world.handleMovement(client, playerMovementRequest(player, 1)); err != nil {
+ t.Fatal(err)
+ }
+ if player.playfield != 65536 {
+ t.Fatal("encounter fixture failed ordinary keyed entry", player.playfield)
+ }
+ world.clients[1], client.ready, client.loading = client, true, false
+ player.movement = playerMovement{}
+ world.updateNPCInterest_locked(client, time.Now())
+ output.packets = nil
+ return world, client, output
+}
+
+func TestMissionEncounterPursuitCrossesPortalAndReturnsWithoutDatabaseChurn(t *testing.T) {
+ for _, id := range []uint32{2000003, 2000004} {
+ t.Run(fmt.Sprint(id), func(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[id]
+ player.position = [3]float32{15, .011, 43}
+ npc.fighting = 1
+ world.fighting[npc.id] = npc
+ start := time.Now()
+ world.lastNPCUpdate = start
+
+ for tick := 1; tick <= 32; tick++ {
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+ far := npc.position
+ player.health = 0
+ for tick := 33; tick <= 80; tick++ {
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+ var storedZ float32
+ if err := world.db.QueryRow("SELECT position_z FROM characters WHERE id=?", id).Scan(&storedZ); err != nil {
+ t.Fatal(err)
+ }
+
+ if far[2] < 41 || far[2] > 43 || math.Abs(float64(far[1]-.011)) > .02 || npc.fighting != 0 || npc.motion.moving || npc.motion.returning ||
+ surfaceDistanceSquared(npc.position, npc.motion.home) >= .01 || storedZ != npc.motion.home[2] {
+ t.Fatal("indoor pursuit escaped its floor, failed to return or persisted each tick", far, npc.position, npc.motion, storedZ)
+ }
+ })
+ }
+}
+
+func TestMissionEncounterPursuitCannotCrossTheOriginalRoomWall(t *testing.T) {
+ for _, tickCount := range []int{1, 80} {
+ t.Run(fmt.Sprint(tickCount), func(t *testing.T) {
+ world, _, _ := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ player.position = [3]float32{100, .011, 28}
+ npc.fighting = 1
+ world.fighting[npc.id] = npc
+ start := time.Now()
+ world.lastNPCUpdate = start
+
+ for tick := 1; tick <= tickCount; tick++ {
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+
+ if npc.position[0] <= 15 || npc.position[0] >= 18 || math.Abs(float64(npc.position[2]-28)) > 1 ||
+ npc.position[1] < .001 || npc.position[1] > 1 || world.geometry.mission(65536).roomAt(npc.position) == nil {
+ t.Fatal("NPC pursuit crossed the original mesh wall or lost its floor", npc.position)
+ }
+ })
+ }
+}
diff --git a/server/mission_offers_test.go b/server/mission_offers_test.go
@@ -245,6 +245,7 @@ func newMissionOfferWorld(t *testing.T) (*server, *combatTestConn) {
definition := gamedata.MissionTemplates[3221228472]
cashOnly := definition
cashOnly.RewardItem, cashOnly.RewardQuality = 0, 0
+ cashOnly.Encounters = nil
gamedata.MissionTemplates[3221228472] = cashOnly
t.Cleanup(func() { gamedata.MissionTemplates[3221228472] = definition })
world, output := newEquipmentWorld(t)
diff --git a/server/mission_retirement.go b/server/mission_retirement.go
@@ -136,6 +136,34 @@ func (server *server) endMission_locked(mission acceptedMission, completed bool,
return nil, err
}
store.inventoryPlayers = nil
+ retiredNPCs := make(map[uint32]bool)
+ if !completed {
+ // Include hidden corpse/respawn sources, even when the world has no observers.
+ for id, npc := range server.characters {
+ if npc.npc && npc.playfield == mission.world {
+ retiredNPCs[id] = true
+ }
+ }
+ for id, npc := range server.savedNPCs {
+ if npc.State.Character.Position.Playfield == mission.world {
+ retiredNPCs[id] = true
+ }
+ }
+ for id, items := range store.Corpses {
+ if !retiredNPCs[id] {
+ continue
+ }
+ for _, item := range items {
+ for _, child := range store.Items[item.ID].Slots {
+ if child != nil {
+ delete(store.Items, *child)
+ }
+ }
+ delete(store.Items, item.ID)
+ }
+ delete(store.Corpses, id)
+ }
+ }
for id, inventory := range inventories {
client := server.clients[id]
if client != nil {
@@ -269,9 +297,18 @@ func (server *server) endMission_locked(mission acceptedMission, completed bool,
}
}
for _, client := range server.clients {
- if corpses[client.lootCorpse] {
+ if retiredNPCs[client.lootCorpse] {
+ changes[client] = append(changes[client], lootClosePacket(client.id, client.lootCorpse))
+ client.lootCorpse = 0
+ } else if corpses[client.lootCorpse] {
changes[client] = append(changes[client], lootInventoryPacket(client.id, server.characters[client.lootCorpse], false))
}
+ for id := range retiredNPCs {
+ if client.npcs[id] {
+ delete(client.npcs, id)
+ changes[client] = append(changes[client], n3Packet(0x36510078, 50000, id, nil), n3Packet(0x36510078, 51050, id, nil))
+ }
+ }
for index, item := range client.reclaimItems {
if removed[item] {
client.reclaimItems[index] = 0
@@ -295,8 +332,18 @@ func (server *server) endMission_locked(mission acceptedMission, completed bool,
}
player := server.characters[mission.owner]
player.missions = slices.DeleteFunc(player.missions, func(other acceptedMission) bool { return other.id == mission.id })
- if !completed && server.geometry != nil {
- server.geometry.removeMission(mission.world)
+ if !completed {
+ for id := range retiredNPCs {
+ server.cancelCombat_locked(id, updates)
+ delete(server.characters, id)
+ delete(server.fighting, id)
+ }
+ delete(server.mobileNPCs, mission.world)
+ server.npcRespawns = slices.DeleteFunc(server.npcRespawns, func(respawn npcRespawn) bool { return respawn.npc.playfield == mission.world })
+ server.corpseExpiry = slices.DeleteFunc(server.corpseExpiry, func(corpse *character) bool { return corpse.playfield == mission.world })
+ if server.geometry != nil {
+ server.geometry.removeMission(mission.world)
+ }
}
return departures, nil
}
diff --git a/server/missions.go b/server/missions.go
@@ -130,6 +130,12 @@ func (server *server) handleMissionAcceptance(client *worldClient, body []byte)
return err
}
store.mission = &mission
+ store.spawnedNPCs, err = server.stageMissionEncounters_locked(&mission)
+ if err != nil {
+ return err
+ }
+ // The accepted contract retains concrete NPC rows rather than a spawn recipe.
+ mission.offer.definition.Encounters = nil
if err := server.writeItemStore_locked(store); err != nil {
return err
}
diff --git a/server/npc_outcome.go b/server/npc_outcome.go
@@ -15,9 +15,7 @@ func (server *server) writeNPCOutcome_locked(tx *sql.Tx, target *character, now
state := target.worldState(true, time.Time{})
if target.health == 0 {
state.Motion.Moving, state.Motion.Returning = false, false
- if target.combatProfile != nil && target.combatProfile.RespawnSeconds != 0 {
- state.RespawnAt = now.Add(time.Duration(target.combatProfile.RespawnSeconds) * time.Second)
- }
+ state.RespawnAt = server.npcRespawnAt_locked(target, now)
}
if err := writeNPCState_locked(tx, target, &state); err != nil {
return state, err
diff --git a/server/npc_pursuit.go b/server/npc_pursuit.go
@@ -24,7 +24,7 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
destination = predictedPosition_locked(target, now)
// Open-ground arrival threshold from NPC steering FUN_10048430.
x, y, z := destination[0]-npc.position[0], destination[1]-npc.position[1], destination[2]-npc.position[2]
- if x*x+y*y+z*z < 4 {
+ if x*x+y*y+z*z < 4 && !npc.movement.falling {
server.stopNPCMotion_locked(npc, updates)
return true
}
@@ -55,14 +55,40 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
position[1] = npc.motion.home[1] + height - home
}
}
+ previous := npc.position
npc.position = position
+ if server.geometry != nil && server.geometry.mission(npc.playfield) != nil {
+ // Indoor actors use the same body, room veto, swept walls and floors as players.
+ npc.geometry = server.geometry
+ npc.position = previous
+ frames := max(1, int(math.Ceil(seconds*60)))
+ frameSeconds := float32(seconds) / float32(frames)
+ for range frames {
+ before := npc.position
+ displacement := [3]float32{}
+ for _, axis := range []int{0, 2} {
+ displacement[axis] = (position[axis] - previous[axis]) / float32(frames)
+ }
+ if npc.movement.normal[1] > .001 {
+ displacement[1] = -(npc.movement.normal[0]*displacement[0] + npc.movement.normal[2]*displacement[2]) / npc.movement.normal[1]
+ }
+ for axis := range npc.position {
+ npc.position[axis] += displacement[axis]
+ }
+ if npc.movement.falling {
+ npc.movement.verticalVelocity = max(float32(-50), npc.movement.verticalVelocity-20*frameSeconds)
+ npc.position[1] += npc.movement.verticalVelocity * frameSeconds
+ }
+ npc.alignSurface(before, false)
+ }
+ }
if distance != 0 {
angle := math.Atan2(x, z)
npc.rotation = [4]float32{0, float32(math.Sin(angle / 2)), 0, float32(math.Cos(angle / 2))}
}
// Complete the return before allowing another idle roaming destination.
- if npc.fighting == 0 && distance <= step {
+ if npc.fighting == 0 && !npc.movement.falling && distance <= step && surfaceDistanceSquared(npc.position, destination) < .01 {
server.stopNPCMotion_locked(npc, updates)
npc.motion.returning = false
npc.motion.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second)
diff --git a/server/npcs.go b/server/npcs.go
@@ -17,6 +17,19 @@ func npcCombatProfile(definition string, monster uint32, level uint16) *gamedata
return profile
}
+func makeNPCSpawn(group *gamedata.NPCGroup, level uint16, position [3]float32) character {
+ spawn := character{name: group.Name, position: position, rotation: [4]float32{0, 0, 0, 1},
+ appearance: group.Appearance, monsterData: group.MonsterData, level: level, npc: true,
+ combatProfile: npcCombatProfile(group.ID, group.MonsterData, level), npcDefinitionID: group.ID}
+ spawn.health = spawn.maximumHealth()
+ // Idle placement is independent of admitted combat movement.
+ roaming := group.PlacementStatus != "fixed_point" && group.Appearance>>4&7 == 6
+ if roaming || spawn.combatProfile != nil {
+ spawn.motion = &npcMotion{roaming: roaming, home: position}
+ }
+ return spawn
+}
+
func readNPCSpawns() ([]character, error) {
data := gamedata.NPCs
@@ -40,19 +53,8 @@ func readNPCSpawns() ([]character, error) {
for index, position := range group.Positions {
// Spread placements across the authored inclusive range; selection is provisional.
level := group.Levels[0] + uint16(index%(int(group.Levels[1])-int(group.Levels[0])+1))
- spawn := character{
- id: 1000000 + uint32(len(spawns)), name: group.Name,
- playfield: playfield.ID, position: position, rotation: [4]float32{0, 0, 0, 1},
- appearance: group.Appearance, monsterData: group.MonsterData, level: level, npc: true,
- combatProfile: npcCombatProfile(group.ID, group.MonsterData, level),
- npcDefinitionID: group.ID,
- }
- spawn.health = spawn.maximumHealth()
- // Idle placement is independent of admitted combat movement.
- roaming := group.PlacementStatus != "fixed_point" && group.Appearance>>4&7 == 6
- if roaming || spawn.combatProfile != nil {
- spawn.motion = &npcMotion{roaming: roaming, home: position}
- }
+ spawn := makeNPCSpawn(&group, level, position)
+ spawn.id, spawn.playfield = 1000000+uint32(len(spawns)), playfield.ID
spawns = append(spawns, spawn)
}
}
diff --git a/server/world_store.go b/server/world_store.go
@@ -70,6 +70,13 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[ui
characters[respawn.npc.id] = respawn.npc
deadlines[respawn.npc.id] = respawn.at
}
+ if store.removedMission != nil {
+ for id, npc := range characters {
+ if npc.npc && npc.playfield == store.removedMission.world {
+ delete(characters, id)
+ }
+ }
+ }
// Prepare the bulk writes once for the initial population checkpoint.
characterWrite, err := tx.Prepare(upsertRecordSQL("characters", characterColumns))
@@ -143,7 +150,8 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[ui
continue
}
zone := previous.State.Character.Position.Playfield
- if !store.flush && !zones[zone] && !server.npcZones[zone] {
+ retiring := store.removedMission != nil && zone == store.removedMission.world
+ if !retiring && !store.flush && !zones[zone] && !server.npcZones[zone] {
continue
}
if _, err := tx.Exec("DELETE FROM characters WHERE id = ?", id); err != nil {