aorecomp

Anarchy Online classic in the browser

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


commit 7b9b44289189dc6a2db343d01113a792ed8bdf31
parent fca2cbedf18963a79ddeaf893f16c7dcd77c7bec
Author: anon <anon@example.com>
Date:   Thu,  5 Nov 2026 20:12:45 +0000

Share native door state on early city and shop routes

Diffstat:
MDEVELOPERS.md | 4++++
MTODO.md | 15+++++++++++++++
Mclient/runtime/browser_testing.c | 11++++++++++-
Mclient/tests/browser_testing.c | 22++++++++++++++++++++++
Adocs/city-doors.md | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_city_doors_test.go | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/city_doors.go | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/city_doors_test.go | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/state.go | 9+++++++++
Mserver/world_items.go | 1+
Mserver/zoning.go | 3+++
Mserver/zoning_test.go | 5+++++
Atools/client/test_city_doors.mjs | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13 files changed, 636 insertions(+), 1 deletion(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -516,6 +516,10 @@ category 5. Its `weapons` entries include signed `loadedAmmo` from the native WeaponItem stat container; infinite ammunition and unbound controllers use -1. These reads do not invoke guest getters or change queues. Inventory remains local-player-only. +Door actors (type51016) expose `door.flags`, `latched`, `duration` and `time`. +These read the existing native object and animation frame without advancing it. +`TestBrowserCityDoors` checks shared approach, opening, withdrawal, reconnect and +passage on the selected city/shop routes; see [city doors](docs/city-doors.md). Short key/click helpers release on the fresh consumed SDL event, then read the next full snapshot. Reading a large snapshot while holding a skill button can trigger native autorepeat and buy more points than intended. diff --git a/TODO.md b/TODO.md @@ -88,6 +88,14 @@ research separately. More screenshots and test cases do not count as new gamepla both clients, in both directions, including after reconnect. Check a Clan and Neutral shop/zone route using the same implementation. Record portals that genuinely have no moving door rather than inventing an animation. + November 5: ten audited endpoints now share native opening/closing state and + replay it after reconnect. Nine endpoints pass the full two-client scenario. + The Old Athen approach needs its original side ramp and a forward jump over + the threshold; passage and source closure work, but the destination retains + server Y=5 while the native client lands at Y=4.26. Public shop interiors lack + server collision geometry. Keep this gate open until the Clan arrival agrees + with the native floor; retain the strict failing arrival assertion. See + [door implementation and remaining verification](docs/city-doors.md). - [ ] **A5: Useful, nonempty early shop stock.** Inventory every terminal in the selected starter and basic shops for all three factions. Supported purchases @@ -147,6 +155,13 @@ rewriting this document does not close them. ## P1: bounded follow-up work +- [ ] **Keep account UI changes in the browser source when publishing.** + November 5: publishing the door-observation client exposed existing drift + between `client/browser/index.html` and the checked-in served page: regeneration + would remove the password-change form and other account fixes. The door bundle + preserves the served page. Reconcile the source with those existing features, + regenerate normally and pass the account UI regressions so future client + publications preserve them without a manual page restoration. - [x] **Repair the admin browser scenario's adopted-player fixture.** The fixture now claims its visitor through the current account endpoint and keeps the rotated browser token. `TestAdminBrowser` passes through player diff --git a/client/runtime/browser_testing.c b/client/runtime/browser_testing.c @@ -147,6 +147,15 @@ static void actor(FILE *output, uint32_t object, uint32_t type, uint32_t id, int vector(output, vehicle + 0x7c, 4); fprintf(output, ",\"playfield\":%u,\"deleting\":%s", MEM32(object + 0x78), MEM8(object + 0x94) ? "true" : "false"); + if (type == 51016) { + /* KKR Door_t embeds n3Dynel at +0x8c; BBR retains animation time on + the VisualMesh's root RRefFrame. Read without advancing animation. */ + uint32_t door = object - 0x8c, mesh = MEM32(object + 0xc4); + uint32_t frame = mesh ? MEM32(mesh + 0x10) : 0; + fprintf(output, ",\"door\":{\"flags\":%u,\"latched\":%s,\"duration\":%.9g,\"time\":%.9g}", + MEM32(door + 0x34), MEM8(door + 0x1c5) ? "true" : "false", + mesh ? MEMF(mesh + 0x24) : 0, frame ? MEMF(frame + 0x12c) : 0); + } if (type == 50000) { /* KKR's stat dictionary has 1024 raw entries; modifiers are separate. */ uint32_t stats = MEM32(MEM32(object + 0xe8) + 4); @@ -231,7 +240,7 @@ static void directory(FILE *output, uint32_t node, uint32_t nil, uint32_t local, if (node == nil) return; directory(output, MEM32(node), nil, local, count, local_id); uint32_t type = MEM32(node + 12), id = MEM32(node + 16), object = MEM32(node + 20); - if ((type == 50000 || type == 51005 || type == 51035 || type == 51050 || type == 51059 || + if ((type == 50000 || type == 51005 || type == 51016 || type == 51035 || type == 51050 || type == 51059 || type == 56001 || type == 56006) && MEM32(object + 0x60)) { if ((*count)++) fputc(',', output); actor(output, object, type, id, object == local); diff --git a/client/tests/browser_testing.c b/client/tests/browser_testing.c @@ -369,6 +369,27 @@ static void snapshots_distinguish_raw_and_effective_armor_without_mutation(void) MEM32(0x50001154) = 0; } +static void snapshots_observe_door_animation_without_mutation(void) +{ + /* Place a Door_t at the existing statel directory entry. */ + MEM32(0x5000070c) = 51016; + uint32_t object = 0x5000a000, door = object - 0x8c; + MEM32(door + 0x34) = 128; + MEM8(door + 0x1c5) = 1; + MEM32(object + 0xc4) = 0x5000d000; + MEM32(0x5000d010) = 0x5000e000; + MEMF(0x5000d024) = 0.75f; + MEMF(0x5000e12c) = 0.25f; + + browser_test_request(); + browser_test_frame(); + + assert(strstr(snapshot, "\"door\":{\"flags\":128,\"latched\":true,\"duration\":0.75,\"time\":0.25}")); + assert(MEM32(door + 0x34) == 128 && MEM8(door + 0x1c5) == 1); + assert(MEMF(0x5000e12c) == 0.25f); + assert(g_eax == 123 && g_esp == 456); +} + int main(void) { snapshot_copies_native_state_without_changing_guest_registers(); @@ -382,6 +403,7 @@ int main(void) snapshots_record_dragged_identity_without_mutation(); snapshots_record_uploaded_mission_identities_without_mutation(); snapshots_distinguish_raw_and_effective_armor_without_mutation(); + snapshots_observe_door_animation_without_mutation(); free(snapshot); puts("PASS: frame snapshots, native inventory, directory clearing and guest state preservation"); } diff --git a/docs/city-doors.md b/docs/city-doors.md @@ -0,0 +1,156 @@ +# Shared early-route city doors + +The server now sends native DoorStatus updates to the existing authored city +objects. It opens a selected door when a living, ready 14.9.1 player approaches +within five horizontal metres and eight vertical metres, and closes it after +the last eligible player leaves a six-metre horizontal envelope. The extra +metre prevents repeated reversals around the opening boundary. These distances +are reconstruction policy, not recovered historical server constants. + +State is shared per playfield/door, remains in memory and is replayed after scene +loading. The existing movement checks, access requirements, shop return context +and authored destinations still decide zoning. A door update does not grant +entry or replace the original object, mesh, transform, events or other stats. +No new persistence writes occur on approach or departure. + +## Finite route scope + +All ten selected statels are authored unlocked, initially closed, and without +stat259 bit64 (which would prevent native closure). The implementation deliberately +does not unlock unrelated mission, apartment or restricted entrances. + +| Route endpoint | Door identity | Template | Placed mesh | +| --- | --- | --- | --- | +| Entertainment to Trade | 705 / `0xc00502c1` | 96272 | 40820 | +| Trade to Entertainment | 710 / `0xc00002c6` | 96272 | 40820 | +| Entertainment Emporium Equipment | 705 / `0xc01102c1` | 41565 | 42857 | +| Emporium interior return | 1183 / `0xc000049f` | 41888 | 41831 | +| Entertainment Special Shop | 705 / `0xc03902c1` | 41565 | 85399 | +| Special Shop interior return | 1191 / `0xc00004a7` | 41888 | 41831 | +| Old Athen basic supermarket | 540 / `0xc01d021c` | 41565 | 55887 | +| Clan shop interior return | 1180 / `0xc000049c` | 41551 | 41469 | +| Borealis basic supermarket | 800 / `0xc0170320` | 41565 | 55886 | +| Neutral shop interior return | 1186 / `0xc00004a2` | 41893 | 41847 | + +The Special Shop entrance at approximately [855, 18.68, 447] is the closest mapped +shop entrance to the Bronto Burger visitor spawn at [960, 16.5, 510]. This is the +working interpretation of the reported nearby shop; Emporium at [765, 19.13, 516] +is also included. No specific shop name or coordinates accompanied the report. + +The selected type51016 placements come from original resource1000026. The mesh +column includes descriptor overrides rather than assuming the template's default +mesh. The retained resource audit is `local/city-doors/routes.txt`, derived from +`local/old/mission-interior/door-placements.json` and `door-catalog.json`, whose +index digest is `46e5dc54af9358cc9bff05f4358e86af630e497bc677f361c133c88073b84d71`. +Their positions and links agree with `server/assets/zone_links.yaml`. + +## Native state contract + +Original 14.9.1 `kkr.dll` SHA256 is +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. +Status Apply at `0x100b07a0` finds the existing Door_t, applies lock/open state +and sets Door byte+0x1c5 when the additional latch flag is true. A false flag does +not clear that latch. The periodic update at `0x1008ce90` otherwise closes an open +door when its local character-collision set empties. Latching an unlocked door +therefore lets the server own closure across observers. Collision can still open +locally; the server's earlier approach update keeps that path from being the only +source of presentation. + +Opening at `0x1008e090` sets Flags bit128; closing at `0x1008e140` clears it and +reverses animation unless stat259 bit64 prevents closure. The existing packet +builder preserves the status format; no native animation code is changed. +See [mission door protocol evidence](mission-doors.md) for serializers and the +remaining unknown original producer policy. + +Reused evidence: `ev_11f652b6807fe3fa84d277db4a9fefb8037f452364a933b752440f84a9d5a123` +(status Apply) and `ev_20aaec6976d9af9989fa5293d7db5fc6ed96b58271d485bd331cd982efdf92c2` +(collision), retained under `local/old/mission-interior/`. The maintained lifted +symbols are `client/game/kkr.dll/lifted-0052.c::sub_360B07A0` and +`client/game/kkr.dll/lifted-0041.c::sub_3608CE90`. + +The read-only browser harness now includes type51016, its flags/latch and native +animation duration/time. Door_t embeds n3Dynel at+0x8c. The mesh pointer is +n3Dynel+0xc4; its root frame and duration are at+0x10/+0x24, and root-frame time +at+0x12c. These follow `llr.dll::sub_3803DBC0`, `bbr.dll::sub_2509B3A0` and +`bbr.dll::sub_250E3010`. Snapshot tests verify that observing these fields does +not mutate guest state or advance animation. + +## Reproduction and verification + +The original server baseline at `local/city-doors/20261105-113316/` shows Emporium +closed on both clients with the traveler approximately three metres away. +The first shared-state captures at `20261105-113922/` show its panel raised on +both replicas, with native time reaching its 0.333333-second endpoint. +The whom-pah's mesh40820 also has a real moving panel: 0.666667 seconds, exposing +a blue tunnel when raised. Its template name `Dummy wompah noselect` is not +evidence that the visible portal lacks a door. + +`TestBrowserCityDoors` uses controlled starts eight metres in front of each +original endpoint. Ordinary browser walking drives approach, withdrawal and +passage. Both clients must reach the matching native flags and animation +endpoints. An observer reconnects once while open and once while closed. Passage +must reach the expected native and authoritative playfield, preserve the remaining +observer's world, and close the departed entrance. Each direction uses its own +fixture; shop returns carry the normal originating-door context. + +Go regressions cover shared state, no duplicate transition packets, the last +visitor keeping a door open, hysteresis, unavailable players, access requirements, +scene replay and opening before held-movement zoning. Existing door serializers, +whom-pah mapping and shop return persistence checks protect the unchanged +admission/destination paths. These controlled fixtures do not establish earned +progression or original timing policy beyond the actual asset animation lengths. + +The Old Athen storefront has a raised platform with a ramp across its front. +Its fixture follows that ramp rather than walking into the platform edge. A +roughly 0.12-metre doorway lip then stops ordinary walking even with the panel +fully raised. The same native stall occurs with server movement corrections +disabled (`20261105-120350/clan-shop`, `browser-native-only.log`). A bounded +comparison of `server/player_collision.go::alignSurface` with original +`qqr.dll::sub_42012A50` found no discrepancy in the relevant raised-probe path; +this is not evidence of a general step-up guarantee. The passage fixture uses +ordinary Space input at this threshold. No collision, zoning radius or original +geometry is changed to bypass it. + +### November 5 result ledger + +Nine of ten endpoints pass the full two-client scenario, including passage, +open/closed reconnect and authoritative arrival: + +| Capture directory under `local/city-doors/` | Passing endpoints | +| --- | --- | +| `20261105-114234` | Entertainment shop, Entertainment to Trade, Trade to Entertainment | +| `20261105-115652` | Emporium return, Special Shop return | +| `20261105-114805` | Entertainment Special Shop | +| `20261105-115113` | Clan shop return, Borealis shop, Neutral shop return | + +Some batches also contain failed scenarios; these are per-endpoint results, +not a claim that every batch passed. Interior observer positions were tightened +to avoid columns, and reconnect now restores the same first-person framing. +All selected portals have moving panels; none needs a synthetic animation. + +`20261105-120928/clan-shop` demonstrates normal forward-jump passage into 1180, +correct source closure and visibly settled native arrival. Its final assertion +still fails: native position is approximately [201.01, 4.26, 160.5], versus server +[201.00072, 5, 160.50998]. `sceneGeometry.physical` currently supports outdoor +terrain and generated missions, not public shop interiors. Consequently the +server keeps the authored door height instead of following this native floor. +The strict 0.5-metre three-dimensional arrival assertion remains in the test. +A4 is still open; this is the specific remaining acceptance failure. + +The earlier `20261105-120737` jump attempt fired during turning and landed before +forward movement. The fixture now waits for the actual forward key event. +The bounded collision audit and native-only diagnostic answer only the exterior +threshold question; they do not establish interior collision support. Further +work should reproduce the 1180 arrival directly and add its missing geometry, +without repeating the nine passing routes or broad native step-up research. + +Nineteen focused Go test roots passed (`go-regressions.log`), along with +`go vet ./server`, the native browser snapshot test, JavaScript syntax and diff +checks. Test-owned browsers and temporary servers were closed after every run. + +Published raw WASM SHA256 is +`9ced727e853ba145c8945a31a001ea3c3ff997373603135628a44d4b2d5cc45f`. +The native changes only expose read-only observations. Publishing exposed prior +drift between the source HTML and served account UI, so the served page was +preserved with its updated decoded download size; the manifest matches the +published files. Source reconciliation is recorded separately in TODO.md. diff --git a/server/browser_city_doors_test.go b/server/browser_city_doors_test.go @@ -0,0 +1,141 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "math" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestBrowserCityDoors(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for city door approaches") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/city-doors", time.Now().Format("20060102-150405")) + for _, route := range []struct { + name string + playfield, id uint32 + origin doorOrigin + }{ + {"entertainment-shop", 705, 0xc01102c1, doorOrigin{}}, + {"shop-entertainment", 1183, 0xc000049f, doorOrigin{705, 0xc01102c1}}, + {"bronto-shop", 705, 0xc03902c1, doorOrigin{}}, + {"shop-bronto", 1191, 0xc00004a7, doorOrigin{705, 0xc03902c1}}, + {"entertainment-trade", 705, 0xc00502c1, doorOrigin{}}, + {"trade-entertainment", 710, 0xc00002c6, doorOrigin{}}, + {"clan-shop", 540, 0xc01d021c, doorOrigin{}}, + {"shop-clan", 1180, 0xc000049c, doorOrigin{540, 0xc01d021c}}, + {"neutral-shop", 800, 0xc0170320, doorOrigin{}}, + {"shop-neutral", 1186, 0xc00004a2, doorOrigin{800, 0xc0170320}}, + } { + t.Run(route.name, func(t *testing.T) { + world := newTestServer(t) + var door zoneDoor + for _, candidate := range world.zoneLinks["target"][route.playfield].Doors { + if candidate.ID == route.id { + door = candidate + } + } + if door.ID == 0 { + t.Fatal("missing route") + } + forward, right := bodyAxes(door.Rotation) + start, near := door.Position, door.Position + for _, axis := range []int{0, 2} { + start[axis] += 8 * forward[axis] + near[axis] += 3 * forward[axis] + } + approach := [][3]float32{near} + if route.name == "clan-shop" { + // The original storefront's ramp runs across its raised platform. + ramp := door.Position + for _, axis := range []int{0, 2} { + ramp[axis] += 3.5*forward[axis] + 4.5*right[axis] + } + approach = append([][3]float32{ramp}, approach...) + } + for index := 0; index < 2; index++ { + player := world.newCharacter() + player.name, player.playfield, player.position = fmt.Sprint("Doorobserver", index), route.playfield, start + if route.origin.Playfield != 0 { + player.returnDoor = &route.origin + } + if index == 1 { + offset := float32(3) + if door.Return { + // Keep the observer inside the narrow interior entry corridor. + offset = 1 + } + for _, axis := range []int{0, 2} { + player.position[axis] += offset * right[axis] + } + } + if ground := world.terrain[player.playfield]; ground != nil { + if height, inside := ground.elevation(player.position[0], player.position[2]); inside { + player.position[1] = height + .5 + } + } + yaw := math.Atan2(float64(door.Position[0]-player.position[0]), float64(door.Position[2]-player.position[2])) + player.rotation = [4]float32{0, float32(math.Sin(yaw / 2)), 0, float32(math.Cos(yaw / 2))} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("city-door-", index)))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + } + 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() + players := []any{} + for _, id := range []uint32{1, 2} { + p := world.characters[id] + players = append(players, map[string]any{"playfield": p.playfield, "position": p.position}) + } + destination := door.Destination + if door.Return { + destination = route.origin.Playfield + } + json.NewEncoder(w).Encode(map[string]any{"door": door, "start": start, "approach": approach, "players": players, + "destination": destination, "open": world.cityDoors[doorOrigin{route.playfield, route.id}]}) + }) + host := httptest.NewServer(mux) + defer host.Close() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + ticker := time.NewTicker(time.Second / 60) + defer ticker.Stop() + for { + select { + case now := <-ticker.C: + world.advancePlayerMovement(now) + world.advanceZoneCrossings(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_city_doors.mjs"), host.URL, filepath.Join(output, route.name)) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + t.Logf("Browser artifacts: %s", filepath.Join(output, route.name)) + if err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/server/city_doors.go b/server/city_doors.go @@ -0,0 +1,66 @@ +package main + +import ( + "math" + "time" +) + +func (server *server) cityDoorPackets_locked(player *character) [][]byte { + var packets [][]byte + for _, door := range server.zoneLinks["target"][player.playfield].Doors { + if open, enabled := server.cityDoors[doorOrigin{player.playfield, door.ID}]; enabled { + packets = append(packets, doorStatusPacket(door.ID, false, open, true)) + } + } + return packets +} + +func (server *server) advanceCityDoors_locked(now time.Time, updates map[*worldClient][][]byte) { + for origin, wasOpen := range server.cityDoors { + var door *zoneDoor + for index := range server.zoneLinks["target"][origin.Playfield].Doors { + candidate := &server.zoneLinks["target"][origin.Playfield].Doors[index] + if candidate.ID == origin.Door { + door = candidate + break + } + } + if door == nil { + continue + } + + // Open before the zoning envelope; retain a metre of hysteresis so + // small position corrections cannot repeatedly reverse the animation. + radius := float32(5) + if wasOpen { + radius = 6 + } + open := false + for id, client := range server.clients { + player := server.characters[id] + if !client.target || !client.ready || client.loading || player.health == 0 || player.playfield != origin.Playfield || + !requirementsMet(door.Requirements, player.meetsStatRequirement) { + continue + } + position := predictedPosition_locked(player, now) + dx, dz := position[0]-door.Position[0], position[2]-door.Position[2] + if dx*dx+dz*dz < radius*radius && math.Abs(float64(position[1]-door.Position[1])) < 8 { + open = true + break + } + } + if open == wasOpen { + continue + } + + // The authored statel already exists on each client. Latching disables + // its local idle closure; this shared state decides when to close it. + server.cityDoors[origin] = open + packet := doorStatusPacket(origin.Door, false, open, true) + for id, client := range server.clients { + if client.target && client.ready && !client.loading && server.characters[id].playfield == origin.Playfield { + updates[client] = append(updates[client], packet) + } + } + } +} diff --git a/server/city_doors_test.go b/server/city_doors_test.go @@ -0,0 +1,102 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "testing" + "time" +) + +func cityDoorWorld() (*server, []*combatTestConn) { + world := &server{ + zoneLinks: map[string]map[uint32]zoneLinks{"target": {705: {Doors: []zoneDoor{{ID: 0xc01102c1, Position: [3]float32{10, 2, 20}}}}}}, + cityDoors: map[doorOrigin]bool{{705, 0xc01102c1}: false}, + characters: map[uint32]*character{}, clients: map[uint32]*worldClient{}, + } + var outputs []*combatTestConn + for id := uint32(1); id <= 2; id++ { + output := &combatTestConn{} + outputs = append(outputs, output) + world.characters[id] = &character{id: id, playfield: 705, position: [3]float32{10, 2, 28}, health: 1} + world.clients[id] = &worldClient{id: id, conn: output, target: true, ready: true} + } + return world, outputs +} + +func TestCityDoorSharesApproachAndLastVisitorDeparture(t *testing.T) { + world, outputs := cityDoorWorld() + world.characters[1].position[2] = 24 + now := time.Now() + + world.advanceZoneCrossings(now) + world.advanceZoneCrossings(now) + + for _, output := range outputs { + if len(output.packets) != 1 || !bytes.Equal(output.packets[0][16:], targetPacket(doorStatusPacket(0xc01102c1, false, true, true))[16:]) { + t.Fatal("approach did not send one native open update to each observer", output.packets) + } + } + + // Another nearby player keeps the shared door open after the first leaves. + world.characters[2].position[2] = 25.5 + world.characters[1].position[2] = 28 + world.advanceZoneCrossings(now) + for _, output := range outputs { + if len(output.packets) != 1 { + t.Fatal("door closed on the remaining visitor") + } + } + world.characters[2].position[2] = 28 + world.advanceZoneCrossings(now) + for _, output := range outputs { + if len(output.packets) != 2 || !bytes.Equal(output.packets[1][16:], targetPacket(doorStatusPacket(0xc01102c1, false, false, true))[16:]) { + t.Fatal("last visitor departure did not close both replicas") + } + } +} + +func TestCityDoorIgnoresUnavailableVisitors(t *testing.T) { + for _, kind := range []string{"loading", "unready", "dead", "other-world", "old-client", "height", "boundary", "requirement"} { + t.Run(kind, func(t *testing.T) { + world, outputs := cityDoorWorld() + player, client := world.characters[1], world.clients[1] + player.position[2] = 24 + switch kind { + case "loading": + client.loading = true + case "unready": + client.ready = false + case "dead": + player.health = 0 + case "other-world": + player.playfield = 710 + case "old-client": + client.target = false + case "height": + player.position[1] = 11 + case "boundary": + player.position[2] = 25 + case "requirement": + world.zoneLinks["target"][705].Doors[0].Requirements = []gamedata.ItemRequirement{{Stat: 54, Value: 2, Operator: 2}} + } + + world.advanceZoneCrossings(time.Now()) + + if world.cityDoors[doorOrigin{705, 0xc01102c1}] || len(outputs[0].packets) != 0 || len(outputs[1].packets) != 0 { + t.Fatal("ineligible visitor opened city door") + } + }) + } +} + +func TestCityDoorReplaysCurrentStateWithoutReplacingAuthoredObject(t *testing.T) { + world, _ := cityDoorWorld() + world.characters[1].position[2] = 24 + world.advanceZoneCrossings(time.Now()) + + packets, err := world.worldScenePackets_locked(world.characters[2]) + + if err != nil || len(packets) != 1 || !bytes.Equal(packets[0], doorStatusPacket(0xc01102c1, false, true, true)) { + t.Fatal("scene replay must send current status for the existing statel", len(packets), err) + } +} diff --git a/server/state.go b/server/state.go @@ -162,6 +162,7 @@ type server struct { terrain map[uint32]*terrain geometry *sceneGeometry zoneLinks map[string]map[uint32]zoneLinks + cityDoors map[doorOrigin]bool } func newServer() *server { @@ -191,6 +192,14 @@ func newServer() *server { panic(err) } server.zoneLinks = links + // Audited unlocked entrances on the early city/shop routes. + server.cityDoors = map[doorOrigin]bool{ + {705, 0xc00502c1}: false, {710, 0xc00002c6}: false, + {705, 0xc01102c1}: false, {1183, 0xc000049f}: false, + {705, 0xc03902c1}: false, {1191, 0xc00004a7}: false, + {540, 0xc01d021c}: false, {1180, 0xc000049c}: false, + {800, 0xc0170320}: false, {1186, 0xc00004a2}: false, + } server.worldResources, err = readWorldResources() if err != nil { panic(err) diff --git a/server/world_items.go b/server/world_items.go @@ -73,6 +73,7 @@ func (server *server) worldScenePackets_locked(player *character) ([][]byte, err if err != nil { return nil, err } + packets = append(packets, server.cityDoorPackets_locked(player)...) packets = append(packets, server.worldItemPackets_locked(player)...) for id, machine := range gamedata.ShopMachines { if machine.Playfield == player.playfield { diff --git a/server/zoning.go b/server/zoning.go @@ -226,6 +226,8 @@ func (server *server) advanceZoneCrossings(now time.Time) { // The native client sends start/stop controls rather than every walking frame. server.mutex.Lock() var destinations []userData + updates := make(map[*worldClient][][]byte) + server.advanceCityDoors_locked(now, updates) messages := make(map[*chatClient][][]byte) for id, client := range server.clients { if !client.ready || client.loading { @@ -256,6 +258,7 @@ func (server *server) advanceZoneCrossings(now time.Time) { } } server.mutex.Unlock() + server.sendCombatUpdates(updates) for client, packets := range messages { for _, packet := range packets { if err := client.send(packet); err != nil { diff --git a/server/zoning_test.go b/server/zoning_test.go @@ -2,6 +2,7 @@ package main import ( "ao/server/gamedata" + "bytes" "encoding/binary" "math" "net" @@ -145,6 +146,10 @@ func TestHeldWalkingCrossesDoorWithoutAnotherMovementPacket(t *testing.T) { world.advanceZoneCrossings(now) } }() + opening, err := readPacket(client) + if err != nil || !bytes.Equal(opening[16:], targetPacket(doorStatusPacket(0xc01102c1, false, true, true))[16:]) { + t.Fatal("approach did not open the authored shop door before zoning", err) + } teleport, err := readPacket(client) if err != nil { world.mutex.Lock() diff --git a/tools/client/test_city_doors.mjs b/tools/client/test_city_doors.mjs @@ -0,0 +1,102 @@ +import assert from 'node:assert/strict'; +import {createRequire} from 'node:module'; +import fs from 'node:fs/promises'; +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 = []; +let expected; +const state = async () => (await games[0].page.request.get(url + '/test-state')).json(); +const door = game => game.state.actors.find(actor => actor.type === 51016 && actor.id === expected.door.ID)?.door; +async function pose(game, open) { + await game.wait(open ? 'shared door fully open' : 'shared door fully closed', () => { + const value = door(game); + return value && value.latched && !!(value.flags & 128) === open && + Math.abs(value.time - (open ? value.duration : 0)) < .001; + }); +} +async function save(label) { + await Promise.all(games.map((game, index) => game.save(`${output}/${label}-${index}`))); + await fs.writeFile(`${output}/${label}-server.json`, JSON.stringify(await state(), null, 2) + '\n'); +} +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: `city-door-${index}`, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + if (!game.state.camera.firstPerson) await game.key('F8'); + } + expected = await state(); + const [traveler, observer] = games; + await Promise.all(games.map(game => pose(game, false))); + assert(door(traveler).duration > 0, 'Selected route has no moving door; inspect its original model'); + await save('closed'); + + // Approach through normal input, then replay an observer while the door is open. + for (const point of expected.approach) await traveler.walk(point[0], point[2]); + await Promise.all(games.map(game => pose(game, true))); + assert.equal((await state()).open, true); + await save('approach'); + await observer.page.reload(); + await observer.ready(); + if (!observer.state.camera.firstPerson) await observer.key('F8'); + await pose(observer, true); + await save('open-reconnect'); + + // Withdrawal closes both replicas. Reconnect must preserve the closed pose too. + await traveler.walk(expected.start[0], expected.start[2]); + await Promise.all(games.map(game => pose(game, false))); + assert.equal((await state()).open, false); + await save('withdrawn'); + await observer.page.reload(); + await observer.ready(); + if (!observer.state.camera.firstPerson) await observer.key('F8'); + await pose(observer, false); + await save('closed-reconnect'); + + // Cross the actual portal and compare native arrival against authoritative zoning. + for (const point of expected.approach) await traveler.walk(point[0], point[2]); + await Promise.all(games.map(game => pose(game, true))); + if (expected.players[0].playfield === 540) { + // The original Old Athen threshold also stops the native client without + // server corrections. Clear its raised lip with ordinary jump input. + const sequence = traveler.sequence; + await Promise.all([ + traveler.walk(expected.door.Position[0], expected.door.Position[2]), + (async () => { + await traveler.wait('walk forward into the Old Athen doorway', () => traveler.events.some(event => + event.sequence > sequence && event.kind === 'browser-input' && event.type === 'keydown' && event.code === 'KeyW')); + await traveler.key('Space'); + })(), + ]); + } else { + await traveler.walk(expected.door.Position[0], expected.door.Position[2]); + } + await traveler.wait('native destination after passage', () => traveler.local()?.playfield === expected.destination, 45000); + await traveler.ready(); + await pose(observer, false); + // Exterior door transforms are height anchors; wait for normal landing. + await traveler.waitFor('native and server arrival settle together', async () => { + await traveler.snapshot(); + const current = await state(); + return Math.hypot(...traveler.local().position.map((value, axis) => value - current.players[0].position[axis])) < .5; + }); + const arrived = await state(); + assert.equal(arrived.players[0].playfield, expected.destination); + assert.equal(arrived.players[1].playfield, expected.players[1].playfield); + assert.equal(arrived.open, false); + assert(Math.hypot(...traveler.local().position.map((value, axis) => value - arrived.players[0].position[axis])) < .5); + await save('passage'); + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: shared approach, opening, withdrawal, reconnect and passage; native duration', door(observer).duration); +} finally { + try { if (games.length) await save('final'); } + finally { await browser.close(); } +}