commit 3b0bec1bc28cc36a203448e01cda0758e9566ad8
parent 4a4eb376c2832c787e53176e22b304f5712b35b6
Author: anon <anon@example.com>
Date: Wed, 4 Nov 2026 06:13:22 +0000
Implement authenticated pet follow with native owner replay
Diffstat:
14 files changed, 597 insertions(+), 12 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -3136,8 +3136,19 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah
master/type metadata, HP/nano, raw combat stats, weapon selection and spawn
transform/collision behavior from original-server evidence. The current body
and17HP/25nano subset is a reconstruction, not proof from later wiki aliases.
-- [ ] [P1] Make the pet follow. Check: it follows its owner across a simple route
+- [x] [P1] Make the pet follow. Check: it follows its owner across a simple route
without changing another player's pet.
+ Native `/pet follow` now installs the authenticated owner's target and uses
+ shared NPC arrival/surface motion. Two owned pets verify real forward/strafe
+ legs, unchanged peer pose/cost, observer replay and resumed owner-page motion.
+ Commands/ticks do not write SQLite; unavailable owners and expired pets
+ suspend motion.
+ See [pet follow](docs/pet-follow.md).
+- [ ] [P2] Recover remaining pet-follow fidelity. Check: named commands select
+ only matching owned pets, and obstacle/lost-target routes match the original
+ NPC breadcrumb behavior. The admitted empty selector targets the owner's set;
+ shared server route planning does not establish original breadcrumb insertion
+ or loss recovery. Default summon mode and cold-mode policy remain unverified.
- [ ] [P1] Make the pet wait. Check: it stays at the commanded position while its
owner moves, until another valid command changes its behavior.
- [ ] [P1] Order the pet to attack. Check: it validates the target and begins combat
diff --git a/docs/pet-follow.md b/docs/pet-follow.md
@@ -0,0 +1,83 @@
+# Owned pet follow
+
+The original `/pet follow` command now installs its authenticated owner's
+character as the owned pet's movement target. A short controlled route verifies
+that the pet moves on the server and both WASM clients while another owner's
+pet stays in place. This is fixture evidence, not earned progression.
+
+## Original evidence
+
+Real keyboard input in `TestBrowserPetOwnerProtocol` captures PetCommand
+`6b333303`, envelope50000:owner, with body words `1, 0, 1009, 0, 0`.
+Command1 is follow; the empty encoded selector list addresses the owner's set.
+The capture is retained in `local/pet-owner-protocol/20261103-214316/`.
+Original `cd_image/text/help/Pet Commands.txt` also documents named commands;
+their wire selectors are not yet admitted.
+
+Original `kkr.dll` SHA256 is
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+The retained analysis in `local/pet-follow/native-kkr.json` establishes:
+
+- NPCVehicle steering1004af50 calls target-position helper10048430 with false,
+ then Vehicle_t::SteeringDirArrive. The maintained port is
+ `client/game/kkr.dll/lifted-0024.c::sub_3604AF50`.
+- With that false argument, the helper stops at a clear two-metre approach and
+ otherwise consumes a thirty-entry breadcrumb path. PlayerVehicle's true
+ argument instead computes a four-metre arrival point. The controllers differ.
+- FollowTargetIIR activation1007e690 accepts an NPC vehicle, applies its control
+ byte and installs the target through10048260. The maintained port is
+ `client/game/kkr.dll/lifted-0037.c::sub_3607E690`.
+
+The implementation sends FollowTarget `260f3671` with an owner identity,
+running control23, current pose and no authored waypoints. Its scalar is zero;
+the installer does not read the player's request scalar as stopping distance.
+Pose corrections use extended action20 (`0x94`), which preserves the target.
+
+## Server behavior and limits
+
+Only the captured all-pets follow request is admitted. Actor identity and the
+current ready client must match; named selectors, arguments and other commands
+are refused. The server selects entities from its ownership map rather than
+trusting pet IDs supplied by a client. Dead, expired or other-playfield pets
+cannot start following.
+
+Pet motion advances after player motion and visits only the active-pet list.
+It shares the existing NPC native arrival forces, surface collision and route
+planning. Nearby arrival retains follow mode so movement resumes when the
+owner moves again. Movement ticks and commands do not write SQLite; ordinary
+world checkpoints retain NPC poses. Follow mode is transient across a cold
+server start, matching the current transient player-follow implementation.
+
+An unavailable, loading, dead or other-playfield owner suspends movement and
+clears the native target once. Availability resumes the retained follow mode.
+Interest entry and owner bootstrap replay the current target after actor
+snapshots. This suspension is a bounded implementation policy, not evidence of
+the original server's disconnect grace period or pet retirement rules.
+
+The simple route does not establish original obstacle-following behavior.
+Server routing currently uses the shared NPC route planner; the exact original
+breadcrumb insertion, loss recovery and default-on-summon mode remain evidence
+gaps. Combat, wait and owner-disconnect lifecycle are separate TODOs.
+
+## Focused verification
+
+The public-handler baseline left the pet at its summon position with no follow
+target. Go regressions cover motion/arrival without tick database writes,
+authentication and unsupported selectors, unavailable-owner halt/resume,
+expiry suspension and snapshot-before-controller interest replay.
+
+`TestBrowserPetFollow` prepares two players and completes one ordinary summon
+for each before opening the browsers. Real chat input orders only the first
+owner's pet to follow. Real forward and strafe inputs cover eight- and
+four-metre legs, then a return leg after owner reload. Server/native positions,
+unchanged second ownership/cost/pose, observer replay and resumed owner motion
+are checked. The route is bounded; no leveling or supply farming is involved.
+
+The native phase passes in38.46 seconds in
+`local/pet-follow/20261103-220754/`. Its combined run subsequently failed only
+the unit assertion that confused declared length with padded buffer length;
+the corrected related run passes45 roots/137 results. The race-detector native
+run passes in43.97 seconds in `local/pet-follow/20261103-221049/`, additionally
+checking the peer pet's unchanged native pose on both clients. All eight saved
+traces have no client errors or dropped events. Vet, driver syntax checks and
+the retained evidence validation in `local/pet-follow/validation.json` pass.
diff --git a/docs/pet-owner-protocol.md b/docs/pet-owner-protocol.md
@@ -21,6 +21,8 @@ PetCommand `6b333303` reads a command, argument, encoded identity list, boolean
and bounded string. Native `/pet report` with no name filter emits body words
`14, 0, 1009, 0, 0`: the owner set is implicit, and no explicit pet identity is
present. This establishes the request, not a server report response.
+The same native input captures `/pet follow` as `1, 0, 1009, 0, 0`; the owned
+server implementation is documented in [pet follow](pet-follow.md).
The NPC full-update reader at `10082da0` reads four compact fields after its
flags. Activation at `100821d0` publishes these as stats455,466,512,388.
diff --git a/docs/pet-summoning.md b/docs/pet-summoning.md
@@ -26,7 +26,8 @@ a bounded reconstruction. The HP/nano values come from retained2006..2010 wiki
data, not an original14.9.1 server measurement. The later data's four-point skill
requirements are not imported: the original requires eight. Weapon selection,
raw combat stats, master/type metadata and exact spawn placement remain open.
-Player-versus-pet combat and pet commands are not admitted by this summon slice.
+Player-versus-pet combat remains unsupported. The owned pet separately admits
+the original all-pets [follow command](pet-follow.md).
TimeExist is interpreted as seconds. A
[later compiled nano chart](https://www.slideshare.net/slideshow/nano-formulas/7124531)
diff --git a/server/browser_pet_follow_test.go b/server/browser_pet_follow_test.go
@@ -0,0 +1,88 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestBrowserPetFollow(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for native pet follow")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/pet-follow", time.Now().Format("20060102-150405"))
+ world := newBrowserPetWorld(t)
+ // Controlled checkpoint: both players have completed the ordinary summon action.
+ for id := uint32(1); id <= 2; id++ {
+ client := &worldClient{id: id, target: true, ready: true, conn: &combatTestConn{}, npcs: make(map[uint32]bool)}
+ world.clients[id] = client
+ if err := world.handleNanoCast(client, characterActionPacket(id, [5]uint32{19, 0, 0, 53019, 43324})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if client.nanoCast == nil {
+ t.Fatal("controlled owner could not summon", id)
+ }
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ }
+ clear(world.clients)
+ mux := http.NewServeMux()
+ mux.Handle("/", world.httpHandler())
+ mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ var owners []map[string]any
+ for id := uint32(1); id <= 2; id++ {
+ owner := world.characters[id]
+ pet := world.characters[1000000+id]
+ owners = append(owners, map[string]any{"id": id, "position": owner.position, "nano": owner.nano,
+ "pet": pet.id, "petPosition": pet.position, "follow": pet.followTarget, "paused": pet.pet.paused})
+ }
+ json.NewEncoder(w).Encode(owners)
+ })
+ host := httptest.NewServer(mux)
+ t.Cleanup(host.Close)
+ closeTestBrowserStreams(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 2*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.advanceNanos(now)
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+ defer func() { cancel(); <-stopped }()
+
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_pet_follow.mjs"), host.URL, output)
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ err := command.Run()
+
+ t.Logf("Browser artifacts: %s", output)
+ if err != nil {
+ t.Fatal(err)
+ }
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ if world.characters[1000001].followTarget != 1 || world.characters[1000002].followTarget != 0 ||
+ world.characters[1].nano != 25 || world.characters[2].nano != 25 {
+ t.Fatal("follow changed another owner's pet or charged another summon")
+ }
+}
diff --git a/server/browser_pet_summon_test.go b/server/browser_pet_summon_test.go
@@ -16,13 +16,8 @@ import (
"time"
)
-func TestBrowserPetSummon(t *testing.T) {
- if os.Getenv("AO_GAME_TEST") != "1" {
- t.Skip("set AO_GAME_TEST=1 for native pet summoning")
- }
- _, source, _, _ := runtime.Caller(0)
- root := filepath.Dir(filepath.Dir(source))
- output := filepath.Join(root, "local/pet-summon", time.Now().Format("20060102-150405"))
+func newBrowserPetWorld(t *testing.T) *server {
+ t.Helper()
data := testNPCData()
data.Playfields[0].ID = 705
data.Playfields[0].Districts[0].Groups[0].Positions = [][3]float32{{1000, 16.5, 550}}
@@ -45,6 +40,17 @@ func TestBrowserPetSummon(t *testing.T) {
t.Fatal(err)
}
}
+ return world
+}
+
+func TestBrowserPetSummon(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for native pet summoning")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/pet-summon", time.Now().Format("20060102-150405"))
+ world := newBrowserPetWorld(t)
for _, phase := range []string{"live", "cold"} {
if phase == "cold" {
if err := world.db.Close(); err != nil {
diff --git a/server/interest.go b/server/interest.go
@@ -55,7 +55,9 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim
updates = append(updates, deathPacket(other))
}
}
- if other.motion != nil && other.motion.moving {
+ if other.pet != nil && other.followTarget != 0 && !other.pet.paused {
+ updates = append(updates, petFollowPacket(other, other.followTarget))
+ } else if other.pet == nil && other.motion != nil && other.motion.moving {
updates = append(updates, npcRoutePacket(other, other.position))
}
}
diff --git a/server/main.go b/server/main.go
@@ -411,8 +411,11 @@ func (server *server) serveWorldClient(client *worldClient) error {
var petUpdates [][]byte
if len(character.pets) != 0 {
petUpdates = append(petUpdates, petCounterPacket(character))
- for id := range character.pets {
+ for id, pet := range character.pets {
petUpdates = append(petUpdates, petIdentityPacket(0x194e4f76, character.id, id))
+ if pet.followTarget != 0 && pet.playfield == character.playfield && !pet.pet.paused {
+ petUpdates = append(petUpdates, petFollowPacket(pet, character.id))
+ }
}
}
updates = append(updates, petUpdates...)
@@ -581,6 +584,10 @@ func (server *server) serveWorldClient(client *worldClient) error {
if err := server.handleCombat(client, body); err != nil {
return err
}
+ case 0x6b333303:
+ if err := server.handlePetCommand(client, body); err != nil {
+ return err
+ }
case 0x3b132d64, 0x2103247d, 0x270a4c62:
if err := server.handleNPCDialogue(client, body); err != nil {
return err
diff --git a/server/pet_follow.go b/server/pet_follow.go
@@ -0,0 +1,116 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "math"
+ "time"
+)
+
+func (server *server) handlePetCommand(client *worldClient, body []byte) error {
+ if len(body) < 36 {
+ return fmt.Errorf("invalid pet command length")
+ }
+ // Original /pet follow: command 1, no argument, empty encoded selector list.
+ if len(body) != 36 || !client.target || binary.BigEndian.Uint32(body[4:8]) != 50000 ||
+ binary.BigEndian.Uint32(body[8:12]) != client.id || binary.BigEndian.Uint32(body[16:20]) != 1 ||
+ binary.BigEndian.Uint32(body[20:24]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 1009 ||
+ binary.BigEndian.Uint32(body[28:32]) != 0 || binary.BigEndian.Uint32(body[32:36]) != 0 {
+ return nil
+ }
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ owner := server.characters[client.id]
+ if server.clients[client.id] != client || !client.ready || client.loading || owner.health == 0 {
+ server.mutex.Unlock()
+ return nil
+ }
+ now := time.Now()
+ updates := make(map[*worldClient][][]byte)
+ for _, pet := range owner.pets {
+ if pet.health == 0 || pet.playfield != owner.playfield || !now.Before(pet.pet.expiresAt) {
+ continue
+ }
+ pet.geometry = server.geometry
+ pet.followTarget = owner.id
+ pet.pet.paused = false
+ pet.motion = &npcMotion{home: pet.position}
+ pet.movement.prepare(pet, now)
+ pet.movement.updatedAt = now
+ pet.movement.action(pet, 23)
+ server.queueCombat_locked(updates, pet, owner, petFollowPacket(pet, owner.id))
+ }
+ server.mutex.Unlock()
+ server.sendCombatUpdates(updates)
+ return nil
+}
+
+func petFollowPacket(pet *character, target uint32) []byte {
+ // KKR FollowTargetIIR 1007e690 installs an NPC owner target without waypoints.
+ body := make([]byte, 29)
+ body[12] = 19
+ if target != 0 {
+ binary.BigEndian.PutUint32(body, 50000)
+ binary.BigEndian.PutUint32(body[4:], target)
+ body[12] = 23
+ }
+ for axis, value := range pet.position {
+ binary.BigEndian.PutUint32(body[13+axis*4:], math.Float32bits(value))
+ }
+ return n3Packet(0x260f3671, 50000, pet.id, body)
+}
+
+func (server *server) advancePetFollowing_locked(now time.Time, updates map[*worldClient][][]byte) {
+ for _, pet := range server.petExpiry {
+ if pet.followTarget == 0 {
+ continue
+ }
+ seconds := min(.25, max(0, now.Sub(pet.movement.updatedAt).Seconds()))
+ pet.movement.updatedAt = now
+ owner, client := server.characters[pet.pet.owner], server.clients[pet.pet.owner]
+ available := pet.health != 0 && now.Before(pet.pet.expiresAt) && owner.health != 0 &&
+ owner.playfield == pet.playfield && client != nil && client.ready && !client.loading
+ if !available {
+ if !pet.pet.paused {
+ pet.pet.paused = true
+ pet.motion.route, pet.motion.moving = nil, false
+ pet.movement.velocity, pet.movement.speed = [3]float32{}, 0
+ server.queueCombat_locked(updates, pet, pet, petFollowPacket(pet, 0))
+ }
+ continue
+ }
+ if pet.pet.paused {
+ pet.pet.paused = false
+ server.queueCombat_locked(updates, pet, owner, petFollowPacket(pet, owner.id))
+ }
+ if pet.pursuitArrived(owner.position) {
+ pet.motion.route, pet.motion.moving = nil, false
+ pet.movement.velocity, pet.movement.speed = [3]float32{}, 0
+ continue
+ }
+
+ // Share NPC route planning and native arrival forces, not player follow's 4m offset.
+ if pet.geometry.physical(pet.playfield) {
+ if surfaceDistanceSquared(pet.motion.destination, owner.position) >= 1 ||
+ len(pet.motion.route) == 0 && !now.Before(pet.motion.routeRetry) {
+ pet.motion.route = planNPCRoute(pet, owner.position)
+ pet.motion.destination = owner.position
+ pet.motion.routeRetry = now.Add(time.Second)
+ }
+ if len(pet.motion.route) == 0 {
+ continue
+ }
+ }
+ previous := pet.position
+ _, blocked := pet.advanceNPCMotion(owner.position, seconds)
+ pet.motion.moving = !blocked
+ if blocked {
+ pet.motion.route = nil
+ pet.motion.routeRetry = now.Add(time.Second)
+ }
+ if pet.position != previous {
+ server.queueCombat_locked(updates, pet, pet, npcMovementPacket(pet, 0x94))
+ }
+ }
+}
diff --git a/server/pet_follow_test.go b/server/pet_follow_test.go
@@ -0,0 +1,169 @@
+package main
+
+import (
+ "encoding/binary"
+ "testing"
+ "time"
+)
+
+func petFollowRequest(owner uint32) []byte {
+ var body []byte
+ for _, value := range []uint32{1, 0, 1009, 0, 0} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x6b333303, 50000, owner, body)
+}
+
+func TestPetFollowMovesItsOwnedEntityWithoutRoutinePersistence(t *testing.T) {
+ world, output := newPetSummonWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:])
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ pet := player.pets[1000001]
+ start := pet.position
+ player.position = [3]float32{10, 0, 0}
+ output.packets = nil
+ auditCheckpointWrites(t, world)
+
+ err := world.handlePetCommand(client, petFollowRequest(1)[20:])
+ now := time.Now()
+ for step := 1; step <= 600; step++ {
+ world.advancePlayerMovement(now.Add(time.Duration(step) * time.Second / 60))
+ }
+
+ if err != nil || pet.followTarget != 1 || pet.position[0] < start[0]+3 || surfaceDistanceSquared(pet.position, player.position) >= 5 ||
+ player.nano != 25 || len(checkpointWrites(t, world)) != 0 {
+ t.Fatal("owned pet did not follow without routine persistence", err, pet.followTarget, pet.position)
+ }
+ follows := 0
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x260f3671 && binary.BigEndian.Uint32(packet[24:28]) == pet.id {
+ follows++
+ if binary.BigEndian.Uint32(packet[29:33]) != 50000 || binary.BigEndian.Uint32(packet[33:37]) != 1 {
+ t.Fatalf("pet received an unrelated follow target: %x", packet)
+ }
+ }
+ }
+ if follows != 1 {
+ t.Fatal("follow did not install exactly one native owner target", follows)
+ }
+}
+
+func TestPetFollowRejectsUnsupportedOrUnavailableRequests(t *testing.T) {
+ for _, scenario := range []string{"foreign actor", "stale client", "loading", "not ready", "owner dead", "pet dead", "zone", "expired", "command", "argument", "selectors", "boolean", "name"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, output := newPetSummonWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:])
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ pet := player.pets[1000001]
+ request := petFollowRequest(1)[20:]
+ switch scenario {
+ case "foreign actor":
+ binary.BigEndian.PutUint32(request[8:], 2)
+ case "stale client":
+ world.clients[1] = &worldClient{id: 1}
+ case "loading":
+ client.loading = true
+ case "not ready":
+ client.ready = false
+ case "owner dead":
+ player.health = 0
+ case "pet dead":
+ pet.health = 0
+ case "zone":
+ pet.playfield++
+ case "expired":
+ pet.pet.expiresAt = time.Now().Add(-time.Second)
+ case "command":
+ binary.BigEndian.PutUint32(request[16:], 14)
+ case "argument":
+ binary.BigEndian.PutUint32(request[20:], 1000001)
+ case "selectors":
+ binary.BigEndian.PutUint32(request[24:], 1010)
+ case "boolean":
+ binary.BigEndian.PutUint32(request[28:], 1)
+ case "name":
+ binary.BigEndian.PutUint32(request[32:], 1)
+ request = append(request, 'x')
+ }
+ output.packets = nil
+
+ err := world.handlePetCommand(client, request)
+
+ if err != nil || pet.followTarget != 0 || pet.motion != nil || len(output.packets) != 0 || player.nano != 25 {
+ t.Fatal("rejected command changed the pet or owner", err, pet.followTarget, len(output.packets), player.nano)
+ }
+ })
+ }
+}
+
+func TestPetFollowSuspendsAndResumesWithItsOwner(t *testing.T) {
+ world, output := newPetSummonWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:])
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ pet := player.pets[1000001]
+ world.handlePetCommand(client, petFollowRequest(1)[20:])
+ player.position = [3]float32{10, 0, 0}
+ now := pet.movement.updatedAt
+ world.advancePlayerMovement(now.Add(250 * time.Millisecond))
+ start := pet.position
+ client.loading = true
+ output.packets = nil
+
+ world.advancePlayerMovement(now.Add(500 * time.Millisecond))
+ world.advancePlayerMovement(now.Add(time.Second))
+ if pet.position != start || !pet.pet.paused || len(output.packets) != 1 ||
+ binary.BigEndian.Uint32(output.packets[0][29:33]) != 0 {
+ t.Fatal("unavailable owner did not halt the native pet exactly once", pet.position, start, len(output.packets))
+ }
+ client.loading = false
+ world.advancePlayerMovement(now.Add(1250 * time.Millisecond))
+ pet.pet.expiresAt = now.Add(1500 * time.Millisecond)
+ world.advancePlayerMovement(pet.pet.expiresAt)
+ stopped := pet.position
+ world.advancePlayerMovement(now.Add(2 * time.Second))
+
+ if start == stopped || pet.position != stopped || !pet.pet.paused || pet.followTarget != 1 ||
+ pet.movement.velocity != [3]float32{} {
+ t.Fatal("pet failed to resume or moved after its deadline", start, stopped, pet.position)
+ }
+}
+
+func TestPetFollowInterestReplaysOwnerTargetAfterSnapshot(t *testing.T) {
+ world, output := newPetSummonWorld(t)
+ client := world.clients[1]
+ world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:])
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ world.handlePetCommand(client, petFollowRequest(1)[20:])
+ delete(client.npcs, 1000001)
+ output.packets = nil
+
+ packets := world.updateNPCInterest_locked(client, time.Now())
+ for _, packet := range packets {
+ if err := client.send(packet); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ spawned, followed := false, 0
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[24:28]) != 1000001 {
+ continue
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x271b3a6b {
+ spawned = true
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x260f3671 {
+ followed++
+ if !spawned || binary.BigEndian.Uint32(packet[33:37]) != 1 || binary.BigEndian.Uint16(packet[6:8]) != 58 ||
+ packet[41] != 23 || binary.BigEndian.Uint32(packet[54:58]) != 0 {
+ t.Fatalf("replay did not follow the owner after spawn: %x", packet)
+ }
+ }
+ }
+ if followed != 1 {
+ t.Fatal("pet interest did not replay exactly one owner controller", followed)
+ }
+}
diff --git a/server/pets.go b/server/pets.go
@@ -13,6 +13,7 @@ type ownedPet struct {
owner uint32
program uint32
expiresAt time.Time
+ paused bool
}
func petSummonNano(program uint32) bool {
@@ -59,7 +60,7 @@ func (server *server) summonPet_locked(caster *character, now time.Time) error {
position[2] += 4 * (caster.rotation[0]*caster.rotation[2] - caster.rotation[1]*caster.rotation[3])
pet := &character{id: server.nextNPC, name: "Anger Manifestation", playfield: caster.playfield,
position: position, rotation: caster.rotation, appearance: 229, monsterData: 96195,
- level: 1, npc: true, npcDefinitionID: "pet/PT50", pet: &ownedPet{caster.id, 43324, now.Add(600 * time.Second)}}
+ level: 1, npc: true, npcDefinitionID: "pet/PT50", pet: &ownedPet{owner: caster.id, program: 43324, expiresAt: now.Add(600 * time.Second)}}
pet.health, pet.nano = pet.maximumHealth(), pet.maximumNano()
db, err := server.database()
if err != nil {
diff --git a/server/player_movement.go b/server/player_movement.go
@@ -663,6 +663,7 @@ func (server *server) advancePlayerMovement_locked(now time.Time, updates map[*w
}
}
}
+ server.advancePetFollowing_locked(now, updates)
// Resource/range effects see all participants at the completed frame.
for id, client := range server.clients {
player := server.characters[id]
diff --git a/tools/client/test_pet_follow.mjs b/tools/client/test_pet_follow.mjs
@@ -0,0 +1,89 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import {createRequire} from 'node:module';
+import {GameTest} from './game_test.mjs';
+
+const {chromium} = createRequire(import.meta.url)('playwright');
+const [url, output] = process.argv.slice(2);
+const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [
+ '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage',
+ '--disable-background-timer-throttling', '--disable-renderer-backgrounding']});
+const games = [], evidence = {samples: []};
+const actor = (game, id) => game.state.actors.find(actor => actor.type === 50000 && actor.id === id);
+const distance = (first, second) => Math.hypot(...first.map((value, axis) => value - second[axis]));
+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: 'pet-cast-' + index, url}]);
+ const page = await context.newPage(), game = await GameTest.attach(page);
+ games.push(game);
+ await page.goto(url);
+ await game.ready();
+ await page.waitForFunction(() => touchRegion(500, 400)?.world === true);
+ await game.snapshot();
+ }
+ const [owner, observer] = games;
+ const state = async () => (await owner.page.request.get(url + '/test-state')).json();
+ await Promise.all(games.map(game => game.wait('both owned manifestations visible', () =>
+ actor(game, 1000001) && actor(game, 1000002) && actor(game, 1).stats[458] === 1 && actor(game, 2).stats[458] === 1)));
+ evidence.before = await state();
+ evidence.peerBefore = games.map(game => actor(game, 1000002).position);
+ const sequence = owner.sequence;
+ await owner.key('Enter');
+ await owner.page.keyboard.type('/pet follow');
+ await owner.key('Enter');
+ await owner.wait('follow command receives the owned NPC controller', () => owner.events.some(event =>
+ event.sequence > sequence && event.direction === 'framereceived' && event.opcode === '260f3671' &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(24) === 1000001));
+ evidence.command = owner.events.find(event => event.sequence > sequence && event.direction === 'framesent' && event.opcode === '6b333303');
+ const request = Buffer.from(evidence.command.hex, 'hex');
+ assert.deepEqual([29, 33, 37, 41, 45].map(offset => request.readUInt32BE(offset)), [1, 0, 1009, 0, 0]);
+
+ async function arrived(label) {
+ const deadline = Date.now() + 12000;
+ for (;;) {
+ await Promise.all(games.map(game => game.snapshot()));
+ const server = await state();
+ const clients = games.map(game => actor(game, 1000001).position);
+ const sample = {label, server, clients};
+ evidence.samples.push(sample);
+ assert.deepEqual(server[1].petPosition, evidence.before[1].petPosition);
+ games.forEach((game, index) => assert.deepEqual(actor(game, 1000002).position, evidence.peerBefore[index]));
+ assert.equal(server[1].follow, 0);
+ assert(server.every(owner => owner.nano === 25));
+ if (distance(server[0].petPosition, server[0].position) < 2.1 &&
+ clients.every(position => distance(position, server[0].petPosition) < .4)) return sample;
+ assert(Date.now() < deadline, label + ': ' + JSON.stringify(sample));
+ }
+ }
+
+ // Real inputs cross two short legs from the controlled summon checkpoint.
+ const start = owner.local().position;
+ await owner.hold('KeyW', 'owner walks eight metres ahead', snapshot => owner.local(snapshot).position[2] > start[2] + 8);
+ evidence.firstLeg = await arrived('forward arrival');
+ assert(distance(evidence.before[0].petPosition, evidence.firstLeg.server[0].petPosition) > 5);
+ await Promise.all(games.map((game, index) => game.save(output + '/first-leg-' + index)));
+ const corner = owner.local().position;
+ await owner.hold('KeyC', 'owner strafes four metres across the route', snapshot =>
+ Math.abs(owner.local(snapshot).position[0] - corner[0]) > 4);
+ evidence.secondLeg = await arrived('sideways arrival');
+ await observer.page.reload();
+ await observer.ready();
+ await observer.wait('following NPC replays for observer', () => !!actor(observer, 1000001));
+ evidence.replayed = await arrived('observer replay');
+ await owner.page.reload();
+ await owner.ready();
+ await owner.page.waitForFunction(() => touchRegion(500, 400)?.world === true);
+ await owner.wait('owned pet replays after owner reload', () => !!actor(owner, 1000001));
+ const reloaded = owner.local().position;
+ await owner.hold('KeyS', 'reloaded owner returns four metres along the open route', snapshot => owner.local(snapshot).position[2] < reloaded[2] - 4);
+ evidence.final = await arrived('owner replay and resumed motion');
+ assert(games.every(game => game.errors.length === 0));
+ console.log('PASS: native owner follow across two short legs, other owned pet unchanged, observer and owner reload');
+} finally {
+ try {
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n');
+ await Promise.all(games.map((game, index) => game.save(output + '/final-' + index)));
+ } finally { await browser.close(); }
+}
diff --git a/tools/client/test_pet_owner_protocol.mjs b/tools/client/test_pet_owner_protocol.mjs
@@ -48,6 +48,15 @@ try {
evidence.report = owner.events.find(event => event.sequence > sequence && event.direction === 'framesent' && event.opcode === '6b333303');
const packet = Buffer.from(evidence.report.hex, 'hex');
assert.deepEqual([29, 33, 37, 41, 45].map(offset => packet.readUInt32BE(offset)), [14, 0, 1009, 0, 0]);
+ const follow = owner.sequence;
+ await owner.key('Enter');
+ await owner.page.keyboard.type('/pet follow');
+ await owner.key('Enter');
+ await owner.wait('native follow request for the owner pet set', () => owner.events.some(event =>
+ event.sequence > follow && event.direction === 'framesent' && event.opcode === '6b333303'));
+ evidence.follow = owner.events.find(event => event.sequence > follow && event.direction === 'framesent' && event.opcode === '6b333303');
+ const followPacket = Buffer.from(evidence.follow.hex, 'hex');
+ assert.deepEqual([29, 33, 37, 41, 45].map(offset => followPacket.readUInt32BE(offset)), [1, 0, 1009, 0, 0]);
assert((await owner.page.request.post(url + '/test-counter')).ok());
await Promise.all(games.map(game => game.wait('packed count is independent from owner list size', () => actor(game, 1).stats[251] === 1)));
evidence.counter = counts();