commit 63d7678043b7d1a0d91c659ab92e854d3a9b7e48
parent b617f411c82f6672141dd25dd3d17b400a6e31e7
Author: anon <anon@example.com>
Date: Tue, 3 Nov 2026 01:45:26 +0000
Route outdoor NPC pursuit around collision geometry
Diffstat:
8 files changed, 392 insertions(+), 21 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -1164,8 +1164,13 @@ for exact records, protocol, tests and remaining reconstruction assumptions.
only the new target; reconnect did not restore old threat. The real WebSocket
expiry regression checks retained swing timing and independent damage credit.
See [native grace verification](docs/npc-threat.md#verification).
-- [ ] [P1] Navigate around one simple obstacle. Check: a pursuing creature takes a
+- [x] [P1] Navigate around one simple obstacle. Check: a pursuing creature takes a
valid route around a wall rather than walking through it.
+ Outdoor pursuit/return now share bounded collision-checked detours with indoor
+ navigation. Original Omni Training scenery passes with Leet and Wardroid body
+ probes; two native clients verify the Leet detour, ordinary combat, observer
+ replay and return. Close targets across a wall no longer count as arrival.
+ See [outdoor detours](docs/npc-pursuit.md#outdoor-obstacle-detours).
- [x] Recover NPC resources outside combat. Check: one profile follows an
evidenced recovery/reset policy without healing twice on disengagement.
@@ -1177,7 +1182,7 @@ Admitted NPC profiles now pursue moving targets and return after concrete
target loss, independently of idle wandering. Native waypoint routes also drive
idle walking. Evidence, checks and the provisional speed/return policy are in
[NPC pursuit](docs/npc-pursuit.md).
-Historical outdoor give-up timing and obstacle navigation remain open.
+Historical outdoor give-up timing and wider route-selection fidelity remain open.
## Death and recovery
diff --git a/docs/npc-pursuit.md b/docs/npc-pursuit.md
@@ -30,12 +30,11 @@ routes use this server's fixed RunSpeed 100 and run mode, represented on the
server as a 4.5 metres/second speed cap. Selecting that default for admitted pursuit and return
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
-outdoor server controller still steers straight toward its destination.
+near-target branch checks squared distance below 4 and line of sight.
Physical outdoor and indoor scenes use shared collision bodies, floor, water
and gravity; terrain-height offsets remain only when physical geometry is
-unavailable. Indoor pursuit plans bounded detours through walls and room veto
-in small steps; see
+unavailable. Pursuit and return plan bounded physical detours, retaining room
+and passage admission indoors; see
[indoor navigation](mission-encounters.md#indoor-navigation).
Each scheduler step remains capped at 0.25 seconds, with force/velocity integration
subdivided at 60Hz. Walking retains its native 1.5 metres/second cap. Both modes
@@ -48,7 +47,7 @@ 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,
-outdoor detour planning and broader navigation fidelity remain separate TODOs.
+original outdoor route selection and broader navigation fidelity remain separate TODOs.
Motion state retains home, destination, idle-wandering eligibility and return
progress independently of combat capability. It uses the existing periodic NPC
@@ -77,7 +76,8 @@ entry immediately changes the cap. Walk/run requests use the same action
admission as the native state machine: swimming rejects those toggles and
retains its prior preference until exit. Route stops clear velocity and apply
the controls already sent to observers. A body blocked by geometry stops its
-idle route rather than continuing through it; outdoor detours remain unplanned.
+idle route rather than continuing through it. Pursuit and return use the
+detour planner below.
These changes use in-memory motion and the existing periodic checkpoints.
A native floor contact at the pond includes a water-minus-1.2 clamp. Starting
@@ -100,6 +100,45 @@ snapshot. Both browser error lists are empty; this older harness's event rings
overflow, so its separately saved motion samples establish the stop checks.
The water scenario above retains both complete event traces.
+## Outdoor obstacle detours
+
+An engaged Leet previously stopped at X47.5656/Z57.8868 against original Omni
+Training scenery while its player target remained on the other side. It could
+neither approach nor land a visible attack. Physical outdoor scenes now share
+the existing half-metre, 4096-node route search and shortcut probes with indoor
+navigation. Outdoor goals must lie within the original terrain bounds; indoor
+goals retain their room check. Nearby pursuit arrival also requires a physically
+clear approach outdoors. Cached routes and one-second failed-search retries
+use the existing motion state; movement retains its periodic checkpoint cadence.
+
+`TestOutdoorNPCDetoursAroundOriginalTrainingScenery` checks the original
+enclosure with both Leet and Wardroid collision bodies. Additional public
+simulation checks cover close targets behind the wall, a changed walkable
+target and the return home. Existing indoor detours, disconnected rooms, route
+replay, death/control cleanup and outdoor water/cold-return checks remain green.
+
+`TestBrowserOutdoorNPCNavigation` uses two controlled WASM clients and a Leet
+checkpoint at `(46,14.01,58)`. Fixture engagement and disengagement isolate the
+route; they are not earned progression or historical aggression measurements.
+Both replicas take the detour before damage becomes possible. Native Tab/Q then
+delivers one ordinary five-point hit. Three incoming eight-point hits, observer
+reload and the physical return are independently accounted for. Movement poses
+are compared with server reads bracketing each fresh native snapshot; settled
+arrival/replay/return require direct agreement within .15 metres. All58 measured
+comparisons are within .125 metres. The unchanged native water regression also
+passes roaming, both page reloads, dry return, ordinary melee and living water pursuit.
+
+The related Go selection passes66 roots/157 individual results in22.998s;
+11 focused roots/15 results pass under the race detector in133.283s. Wall WASM
+takes47.19s and water50.50s, or105.305s for their combined Go invocation. All ten
+final retained traces have no errors or dropped events. Vet, Node syntax, gofmt
+and whitespace checks pass. Evidence and trial limits are retained in
+`local/outdoor-navigation/`, with final wall captures in `20261102-173640/` and
+water captures in `local/npc-water-motion/20261102-173550/`.
+
+This reuses a reconstruction planner; it does not recover the original server's
+route search, path preference, outdoor water eligibility or give-up timing.
+
## Native route contract
Original 14.9.1 `kkr.dll` SHA-256:
@@ -126,7 +165,7 @@ replays carry the current position. Ongoing route changes carry a zero reconcile
position: the original receiver skips relocation for that value while still
updating the route. Sending the current position on each target change repeatedly
teleported native prediction to the server pose.
-Straight routes contain two points: current position and destination. Indoor
+Straight routes contain two points: current position and destination. Planned
detours contain current position followed by up to 29 remaining waypoints;
turns refresh that remaining route. Pursuit and return use run
control 23; ordinary idle roaming uses walk control 22. The native setter
diff --git a/server/browser_outdoor_navigation_test.go b/server/browser_outdoor_navigation_test.go
@@ -0,0 +1,119 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestBrowserOutdoorNPCNavigation(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for the focused outdoor wall detour")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/outdoor-navigation", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ world.combatRoll = landedCombatRoll
+ var npc *character
+ for _, actor := range world.characters {
+ if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (npc == nil || actor.id < npc.id) {
+ npc = actor
+ }
+ }
+ if npc == nil {
+ t.Fatal("no admitted Leet for controlled outdoor navigation")
+ }
+ npc.position, npc.movement = [3]float32{46, 14.01, 58}, playerMovement{}
+ npc.motion = &npcMotion{home: npc.position}
+ world.mobileNPCs = map[uint32][]*character{950: {npc}}
+ for index := 0; index < 2; index++ {
+ player := world.newCharacter()
+ player.name, player.profession, player.level, player.appearance = fmt.Sprint("Detour", index), 9, 100, 0x315
+ player.position, player.rotation = [3]float32{50.0453, 14.01, 69.887344}, [4]float32{0, 1, 0, 0}
+ if index == 1 {
+ player.position = [3]float32{44, 14.21, 74}
+ }
+ player.stats.Abilities = characterAbilitiesStats{200, 200, 200, 200, 200, 200}
+ player.health, player.nano = player.maximumHealth(), player.maximumNano()
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("detour-", index))))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ }
+ owner := world.characters[1]
+ if world.combatVisible_locked(npc, owner, time.Now()) {
+ t.Fatal("original wall does not separate the controlled actors")
+ }
+ mux := http.NewServeMux()
+ mux.Handle("/", world.httpHandler())
+ mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ json.NewEncoder(w).Encode(map[string]any{"enemy": npc.id, "position": npc.position, "home": npc.motion.home,
+ "route": npc.motion.route, "moving": npc.motion.moving, "returning": npc.motion.returning,
+ "health": npc.health, "fighting": npc.fighting, "ownerHealth": owner.health, "ownerFighting": owner.fighting,
+ "targetPosition": predictedPosition_locked(owner, time.Now()),
+ "visible": world.combatVisible_locked(npc, owner, time.Now())})
+ })
+ // Controlled engagement and target loss reach the wall scenario without a playthrough.
+ for _, action := range []string{"pursue", "return"} {
+ mux.HandleFunc("POST /test-"+action, func(w http.ResponseWriter, r *http.Request) {
+ world.updateMutex.Lock()
+ defer world.updateMutex.Unlock()
+ world.mutex.Lock()
+ updates := make(map[*worldClient][][]byte)
+ if action == "pursue" {
+ world.startAttack_locked(npc, owner, time.Now(), updates)
+ } else {
+ world.cancelCombat_locked(owner.id, updates)
+ }
+ world.mutex.Unlock()
+ world.sendCombatUpdates(updates)
+ w.WriteHeader(http.StatusNoContent)
+ })
+ }
+ host := httptest.NewServer(mux)
+ t.Cleanup(host.Close)
+ closeTestBrowserStreams(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+ stopped := make(chan struct{})
+ go func() {
+ defer close(stopped)
+ ticker := time.NewTicker(20 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case now := <-ticker.C:
+ world.advancePlayerMovement(now)
+ world.advanceNPCs(now)
+ world.advanceCombat(now)
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+ defer func() { cancel(); <-stopped }()
+
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_outdoor_navigation.mjs"), host.URL, output)
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ err := command.Run()
+ cancel()
+ <-stopped
+ t.Logf("Browser artifacts: %s", output)
+
+ if err != nil || npc.motion.returning || npc.motion.moving || npc.fighting != 0 || owner.fighting != 0 ||
+ surfaceDistanceSquared(npc.position, npc.motion.home) >= 1.01 || npc.health == 0 || owner.health == 0 {
+ t.Fatal("native detour, combat or return failed", err, npc.position, npc.motion)
+ }
+}
diff --git a/server/npc_motion.go b/server/npc_motion.go
@@ -7,10 +7,10 @@ func (npc *character) pursuitArrived(destination [3]float32) bool {
if npc.movement.falling || surfaceDistanceSquared(npc.position, destination) >= 4 {
return false
}
- if npc.geometry == nil || npc.geometry.mission(npc.playfield) == nil {
+ if !npc.geometry.physical(npc.playfield) {
return true
}
- arrived, clear := indoorWalk(*npc, destination)
+ arrived, clear := probeNPCWalk(*npc, destination)
return clear && surfaceDistanceSquared(arrived.position, destination) < .01
}
diff --git a/server/npc_navigation.go b/server/npc_navigation.go
@@ -27,7 +27,7 @@ func (npc *character) walkSurface(position [3]float32, seconds float64) {
}
}
-func indoorWalk(npc character, destination [3]float32) (character, bool) {
+func probeNPCWalk(npc character, destination [3]float32) (character, bool) {
// Keep routing shortcuts visible above the floor as well as physically walkable.
origin, end := npc.position, destination
origin[1] += .11
@@ -70,13 +70,17 @@ func (queue *navigationQueue) Pop() any {
return node
}
-func indoorRoute(npc *character, destination [3]float32) [][3]float32 {
+func planNPCRoute(npc *character, destination [3]float32) [][3]float32 {
// This bounded half-metre search is reconstruction policy, not a recovered
// original server algorithm. Probe copies never alter the live actor or DB.
- if npc.geometry.mission(npc.playfield).roomAt(destination) == nil {
+ if scene := npc.geometry.mission(npc.playfield); scene != nil {
+ if scene.roomAt(destination) == nil {
+ return nil
+ }
+ } else if _, inside := npc.geometry.terrain[npc.playfield].elevation(destination[0], destination[2]); !inside {
return nil
}
- if arrived, ok := indoorWalk(*npc, destination); ok && surfaceDistanceSquared(arrived.position, destination) < .01 {
+ if arrived, ok := probeNPCWalk(*npc, destination); ok && surfaceDistanceSquared(arrived.position, destination) < .01 {
return [][3]float32{destination}
}
start := &navigationNode{actor: *npc}
@@ -85,7 +89,7 @@ func indoorRoute(npc *character, destination [3]float32) [][3]float32 {
for visited := 0; queue.Len() != 0 && visited < 4096; visited++ {
node := heap.Pop(&queue).(*navigationNode)
if surfaceDistanceSquared(node.actor.position, destination) < 1 {
- if arrived, ok := indoorWalk(node.actor, destination); ok && surfaceDistanceSquared(arrived.position, destination) < .01 {
+ if arrived, ok := probeNPCWalk(node.actor, destination); ok && surfaceDistanceSquared(arrived.position, destination) < .01 {
points := [][3]float32{destination}
for at := node; at.parent != nil; at = at.parent {
points = append(points, at.actor.position)
@@ -98,7 +102,7 @@ func indoorRoute(npc *character, destination [3]float32) [][3]float32 {
actor := *npc
for len(points) != 0 {
for i := len(points) - 1; i >= 0; i-- {
- arrived, ok := indoorWalk(actor, points[i])
+ arrived, ok := probeNPCWalk(actor, points[i])
if ok && surfaceDistanceSquared(arrived.position, points[i]) < .01 {
route = append(route, points[i])
actor, points = arrived, points[i+1:]
@@ -115,7 +119,7 @@ func indoorRoute(npc *character, destination [3]float32) [][3]float32 {
for _, offset := range [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}} {
x, z := node.x+offset[0], node.z+offset[1]
point := [3]float32{npc.position[0] + float32(x)*.5, node.actor.position[1], npc.position[2] + float32(z)*.5}
- actor, ok := indoorWalk(node.actor, point)
+ actor, ok := probeNPCWalk(node.actor, point)
if !ok {
continue
}
diff --git a/server/npc_outdoor_navigation_test.go b/server/npc_outdoor_navigation_test.go
@@ -0,0 +1,113 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "fmt"
+ "testing"
+ "time"
+)
+
+func newOutdoorNavigationWorld(t *testing.T) (*server, time.Time) {
+ t.Helper()
+ world := newPlayerCollisionWorld(t)
+ player, npc := world.characters[1], world.characters[1000000]
+ player.playfield, player.position = 950, [3]float32{42, 14.01, 62}
+ npc.playfield, npc.position, npc.geometry = 950, [3]float32{42, 14.01, 58}, world.geometry
+ npc.monsterData, npc.level, npc.combatProfile = 17655, 1, gamedata.NPCCombatProfiles[17655][1]
+ npc.motion = &npcMotion{home: npc.position}
+ npc.fighting, world.fighting[npc.id] = player.id, npc
+ world.mobileNPCs = map[uint32][]*character{950: {npc}}
+ start := time.Now()
+ world.lastNPCUpdate = start
+ npc.nextAttack = start.Add(1750 * time.Millisecond)
+ return world, start
+}
+
+func TestOutdoorNPCDetoursAroundOriginalTrainingScenery(t *testing.T) {
+ for _, row := range []struct {
+ monster uint32
+ level uint16
+ start [3]float32
+ end [3]float32
+ }{
+ {17655, 1, [3]float32{42, 14.01, 58}, [3]float32{42, 14.01, 62}},
+ {17655, 1, [3]float32{46, 14.01, 58}, [3]float32{50, 14.01, 58}},
+ {17655, 1, [3]float32{46, 14.01, 58}, [3]float32{50.0453, 14.01, 69.887344}},
+ {30354, 4, [3]float32{46, 14.01, 58}, [3]float32{50, 14.01, 58}},
+ } {
+ t.Run(fmt.Sprint(row.monster, "/", row.start[0], "/", row.end[2]), func(t *testing.T) {
+ world, start := newOutdoorNavigationWorld(t)
+ player, npc := world.characters[1], world.characters[1000000]
+ player.position, npc.position, npc.motion.home = row.end, row.start, row.start
+ npc.monsterData, npc.level, npc.combatProfile = row.monster, row.level, gamedata.NPCCombatProfiles[row.monster][row.level]
+ deadline := npc.nextAttack
+ if world.combatVisible_locked(npc, player, start) {
+ t.Fatal("original scenery no longer separates the fixture actors")
+ }
+
+ for tick := 1; tick <= 96; tick++ {
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+
+ if !npc.pursuitArrived(player.position) || !world.combatVisible_locked(npc, player, start.Add(24*time.Second)) ||
+ npc.motion.moving || npc.fighting != player.id || npc.nextAttack != deadline {
+ t.Fatal("outdoor pursuit stopped on the wrong side of original scenery", npc.position, npc.motion.route)
+ }
+ })
+ }
+}
+
+func TestOutdoorNPCDetourReturnsHomeAfterTargetLoss(t *testing.T) {
+ world, start := newOutdoorNavigationWorld(t)
+ player, npc := world.characters[1], world.characters[1000000]
+ player.position, npc.position = [3]float32{50, 14.01, 58}, [3]float32{46, 14.01, 58}
+ npc.motion.home = npc.position
+ for tick := 1; tick <= 96; tick++ {
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+ if !npc.pursuitArrived(player.position) {
+ t.Fatal("fixture did not reach the far side of the original wall", npc.position)
+ }
+
+ player.health = 0
+ for tick := 97; tick <= 192; tick++ {
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+
+ if npc.motion.returning || npc.motion.moving || npc.fighting != 0 || surfaceDistanceSquared(npc.position, npc.motion.home) >= 1.01 {
+ t.Fatal("outdoor return did not detour back to the retained home", npc.position, npc.motion)
+ }
+}
+
+func TestOutdoorNPCDoesNotDeclareArrivalThroughOriginalWall(t *testing.T) {
+ world, start := newOutdoorNavigationWorld(t)
+ player, npc := world.characters[1], world.characters[1000000]
+ npc.position, player.position = [3]float32{47.4, 14.01, 58}, [3]float32{49.3, 14.01, 58}
+ if world.combatVisible_locked(npc, player, start) {
+ t.Fatal("fixture no longer places the close target behind the original wall")
+ }
+
+ world.advanceNPCs(start.Add(250 * time.Millisecond))
+
+ if !npc.motion.moving || len(npc.motion.route) < 2 || npc.pursuitArrived(player.position) {
+ t.Fatal("nearby target across a wall was mistaken for a clear arrival", npc.position, npc.motion)
+ }
+}
+
+func TestOutdoorNPCRouteFollowsAChangingTarget(t *testing.T) {
+ world, start := newOutdoorNavigationWorld(t)
+ player, npc := world.characters[1], world.characters[1000000]
+ player.position, npc.position = [3]float32{50, 14.01, 58}, [3]float32{46, 14.01, 58}
+ for tick := 1; tick <= 4; tick++ {
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+
+ player.position = [3]float32{60.5, 14.01, 70}
+ for tick := 5; tick <= 60; tick++ {
+ world.advanceNPCs(start.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+
+ if !npc.pursuitArrived(player.position) || npc.motion.moving || npc.fighting != player.id {
+ t.Fatal("outdoor route retained a stale target behind the original wall", npc.position, npc.motion)
+ }
+}
diff --git a/server/npc_pursuit.go b/server/npc_pursuit.go
@@ -12,7 +12,7 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
if npc.combatProfile == nil || npc.fighting == 0 && !npc.motion.returning {
return false
}
- indoor := server.geometry != nil && server.geometry.mission(npc.playfield) != nil
+ physical := server.geometry.physical(npc.playfield)
destination := npc.motion.home
if npc.fighting != 0 {
target := server.characters[npc.fighting]
@@ -31,13 +31,13 @@ func (server *server) advanceNPCPursuit_locked(npc *character, now time.Time, se
}
changed := !npc.motion.moving || npc.motion.destination != destination
- if indoor {
+ if physical {
replan := len(npc.motion.route) == 0 && !now.Before(npc.motion.routeRetry)
if len(npc.motion.route) != 0 {
replan = surfaceDistanceSquared(npc.motion.route[len(npc.motion.route)-1], destination) >= 1
}
if replan {
- npc.motion.route = indoorRoute(npc, destination)
+ npc.motion.route = planNPCRoute(npc, destination)
if len(npc.motion.route) == 0 {
npc.motion.routeRetry = now.Add(time.Second)
} else {
diff --git a/tools/client/test_outdoor_navigation.mjs b/tools/client/test_outdoor_navigation.mjs
@@ -0,0 +1,91 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import {createRequire} from 'node:module';
+import {GameTest} from './game_test.mjs';
+
+const {chromium} = createRequire(import.meta.url)('playwright');
+const [url, output] = process.argv.slice(2);
+const browser = await chromium.launch({executablePath: '/usr/bin/chromium', headless: false,
+ args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage',
+ '--disable-background-timer-throttling', '--disable-renderer-backgrounding']});
+const games = [], evidence = {samples: []};
+let enemy;
+const actor = game => game.state.actors.find(actor => actor.type === 50000 && actor.id === enemy);
+const state = async () => (await games[0].page.request.get(url + '/test-state')).json();
+// Fresh native snapshots arrive between these two authoritative pose reads.
+const matches = sample => {
+ const delta = sample.server.position.map((value, axis) => value - sample.before.position[axis]);
+ const length = delta.reduce((sum, value) => sum + value * value, 0);
+ return sample.clients.every(client => {
+ const along = length ? Math.max(0, Math.min(1, delta.reduce((sum, value, axis) =>
+ sum + value * (client.position[axis] - sample.before.position[axis]), 0) / length)) : 0;
+ return Math.hypot(...client.position.map((value, axis) =>
+ value - sample.before.position[axis] - along * delta[axis])) < .4;
+ });
+};
+const settled = sample => sample.clients.every(client =>
+ Math.hypot(...client.position.map((value, axis) => value - sample.server.position[axis])) < .15);
+async function observe(label, complete) {
+ const deadline = Date.now() + 20000;
+ for (;;) {
+ const before = await state();
+ await Promise.all(games.map(game => game.snapshot()));
+ const sample = {before, server: await state(), clients: games.map(game => ({position: actor(game).position,
+ target: actor(game).combatTarget, health: actor(game).stats[27]}))};
+ evidence.samples.push(sample);
+ if (complete(sample)) return sample;
+ assert(Date.now() < deadline, label + ': ' + JSON.stringify(sample.server));
+ }
+}
+try {
+ for (let index = 0; index < 2; ++index) {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'detour-' + index, url}]);
+ const page = await context.newPage(), game = await GameTest.attach(page);
+ games.push(game);
+ await page.goto(url);
+ await game.ready();
+ }
+ const [owner, observer] = games;
+ evidence.initial = await state();
+ enemy = evidence.initial.enemy;
+ await Promise.all(games.map(game => game.wait('original wall actors', () => !!actor(game))));
+ if (!observer.state.camera.firstPerson) await observer.key('F8');
+ assert.equal(evidence.initial.visible, false);
+ assert((await owner.page.request.post(url + '/test-pursue')).ok());
+ evidence.detour = await observe('original outdoor wall detour did not progress', sample =>
+ sample.server.position[2] > 65 && sample.server.moving && matches(sample));
+ assert.equal(evidence.detour.server.ownerHealth, evidence.initial.ownerHealth);
+ await Promise.all(games.map((game, index) => game.save(output + '/detour-' + index)));
+ evidence.arrived = await observe('pursuing Leet did not reach usable attack range', sample =>
+ !sample.server.moving && sample.server.visible && sample.server.ownerHealth < evidence.initial.ownerHealth && settled(sample));
+ assert.equal(evidence.arrived.server.fighting, 1);
+
+ // Native Tab and Q verify an ordinary attack after the physical detour.
+ await owner.key('Tab');
+ await owner.wait('native Leet selection', snapshot => snapshot.selected[0] === 50000 && snapshot.selected[1] === enemy);
+ await owner.key('KeyQ');
+ evidence.hit = await observe('ordinary native attack after arrival did not hit', sample => sample.server.health < evidence.initial.health);
+ await owner.key('KeyQ');
+ await owner.wait('ordinary attack stops', () => owner.local().combatTarget === 0);
+ await Promise.all(games.map((game, index) => game.save(output + '/combat-' + index)));
+ await observer.page.reload();
+ await observer.ready();
+ await observer.wait('settled actor replay', () => !!actor(observer));
+ evidence.replayed = await observe('observer replay changed the settled NPC pose', sample => !sample.server.moving && settled(sample));
+ assert((await owner.page.request.post(url + '/test-return')).ok());
+ evidence.returning = await observe('return did not walk around the same wall', sample =>
+ sample.server.position[2] > 65 && sample.server.returning && sample.server.moving && matches(sample));
+ evidence.returned = await observe('NPC did not reach its controlled home', sample =>
+ !sample.server.returning && !sample.server.moving && settled(sample));
+ assert.equal(evidence.returned.server.fighting, 0);
+ assert(Math.hypot(...evidence.returned.server.position.map((value, axis) => value - evidence.initial.home[axis])) < 1.01);
+ assert(games.every(game => game.errors.length === 0));
+ console.log('PASS: both native replicas follow the original outdoor wall detour, ordinary combat, observer replay and return home');
+} finally {
+ try {
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2));
+ await Promise.all(games.map((game, index) => game.save(output + '/final-' + index)));
+ } finally { await browser.close(); }
+}