commit ecf71180395022e3aeb89062ba881dea4d0511a7
Author: anon <anon@example.com>
Date: Mon, 12 Oct 2026 22:15:16 +0000
Record AO client research and local server baseline
Diffstat:
| A | .gitignore | | | 22 | ++++++++++++++++++++++ |
| A | README.md | | | 174 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | docs/README.md | | | 88 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | docs/browser-porting.md | | | 172 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | docs/client-behavior.md | | | 153 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | docs/game-data.md | | | 344 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | docs/open-questions.md | | | 118 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | docs/protocol.md | | | 508 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | docs/reverse-engineering.md | | | 239 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | docs/versions-and-patches.md | | | 236 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | go.mod | | | 5 | +++++ |
| A | go.sum | | | 2 | ++ |
| A | protocol.md | | | 7 | +++++++ |
| A | server/control.go | | | 147 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | server/control_test.go | | | 91 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | server/main.go | | | 314 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | server/main_test.go | | | 314 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | server/npc_data_test.go | | | 159 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | server/npcs.go | | | 130 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | server/npcs_test.go | | | 174 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | server/playfields.go | | | 385 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | server/roaming.go | | | 134 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | server/roaming_test.go | | | 275 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | server/state.go | | | 114 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | server/terrain.go | | | 65 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | server/terrain_test.go | | | 43 | +++++++++++++++++++++++++++++++++++++++++++ |
| A | server/world.go | | | 146 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | tools/extract_monsters.py | | | 61 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | tools/extract_npc_spawns.py | | | 97 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | tools/extract_playfields.py | | | 120 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | tools/extract_terrain.py | | | 114 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | tools/generate_npcs.py | | | 179 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
32 files changed, 5130 insertions(+), 0 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -0,0 +1,22 @@
+*.iso
+client-*/
+venv/
+tools/unshield/
+tools/*.7z
+tools/*.exe
+tools/*.log
+tools/cellao-reference/
+tools/browser-reference/
+tools/*.json
+tools/*.png
+tools/*.jpg
+tools/strings.txt
+patches/*
+!patches/manifest.json
+data/*.bin
+data/npc_spawns.yaml
+data/users.yaml
+data/users.yaml.tmp
+node_modules/
+browser/dist/
+__pycache__/
diff --git a/README.md b/README.md
@@ -0,0 +1,174 @@
+# Anarchy Online 11.0
+
+The first milestone is running the original 2001 Windows client against a
+minimal local Go server, entering a playfield, and walking. The eventual goal
+is a web remake of that experience.
+
+Start with [docs/README.md](docs/README.md) for original-client research:
+observed behavior, recovered protocol, extracted game data, reverse-engineering
+evidence, historical-server inferences, and open questions.
+
+The mounted release disc was extracted with Unshield rather than installed.
+`client-original/Gamefiles` is the untouched reference. `client-local` is the
+working copy; `client-peer` is a second copy for multiplayer checks. The modern
+installation at `C:\Funcom\Anarchy Online` is untouched.
+
+## Run
+
+From this directory in PowerShell:
+
+```powershell
+.\venv\Scripts\python.exe tools\patch_local.py
+& 'C:\Program Files\Go\bin\go.exe' run ./server
+```
+
+Then launch `client-local\anarchy.exe` with `client-local` as its working
+directory. Use the synthetic username and password `localtest`. Select
+`Local Rubi-Ka`, choose a graphics device, and keep `Run in window` checked.
+The patch script also sets `FullScreen 0` in `Prefs/Main.cfg`.
+
+The server binds only to localhost: HTTP 8080, login 7500, and world 7501.
+No executable bytes are patched. Local URL files and a dimension entry with
+version `11.0` let the launcher log in without requesting a game update.
+
+To quit, press X to sit, then choose OPT > Quit > To Windows. The original
+logout countdown takes 30 seconds. Pressing X to stand prevents logout,
+although the client's countdown bar currently remains visible.
+
+Open http://127.0.0.1:8080/control to see connected players, change the game
+time immediately, and select a teleport destination from the original zone
+catalog. Each player has a dropdown with 373 entries. The 25 names without
+disc assets and four internal dependency maps are disabled; 344 maps have assets.
+The page is plain HTML forms with no JavaScript or CSS. The world starts at
+13:30. Rubi-Ka has a 27-hour day, running at 15 game seconds per real second.
+Hour values range from 0 to 26; minutes range from 0 to 59. Settings reset when
+the server restarts.
+
+For an autonomous two-client check, start the server and run:
+
+```powershell
+.\venv\Scripts\python.exe tools\launch_clients.py
+```
+
+This uses the existing `client-local` and `client-peer` directories, creates
+two synthetic local sessions, and supplies the original launcher's environment.
+Both working copies have windowed graphics configured.
+
+## Verified progress
+
+- The original launcher loads the local dimension list and informational page.
+- The login challenge and character list are accepted.
+- A level 1 Soldier named Local Explorer appears in character selection.
+- Play launches the original 3D client and connects to the local world port.
+- The world client sends its character cookie and periodic ping packets.
+- The local server loads the original Omni Training playfield (950).
+- The original 3D scene, welcome message, and player body render in a window.
+- Walking and turning work; the server receives changing player coordinates.
+- Two original clients connect with separate identities and render each other.
+- Compressed client movement is decoded and relayed to players in the same zone.
+- Original-district points generate shared NPC populations across the world.
+- Creatures wander near their spawn points, with pauses between walks.
+- Teleporting to Borealis reconnects the same character and loads that zone.
+- Returning to training removes and respawns the player in the other client.
+- Player heads render with the original Solitus head mesh.
+- Game time initializes daylight and can change live through the control page.
+- Original hand skin textures replace the solid-green default hand material.
+- The complete original map catalog is available in each player's dropdown.
+- X toggles sitting and standing; Quit to Windows finishes after 30 seconds.
+
+The first two milestones are working. Each login creates a synthetic level-1
+Solitus Soldier. Positions and zone membership are shared in memory. Movement
+is simulated by the original client; the server relays it without validation.
+Creature roaming is provisional: paths stay within four metres of each spawn,
+with 1.5-metre-per-second walking and three-to-eight-second pauses. The client
+continues moving between start and stop commands. Fixed
+spawns and human placeholders stay at their posts. Only occupied zones are
+simulated. Outdoor roaming follows decoded terrain while preserving each spawn's
+authored ground offset. Indoor floor sampling, wall avoidance and pathfinding,
+combat, other NPC behavior, chat, account security, and disk persistence remain
+unimplemented. These are the original Windows clients; the
+browser remake has not started.
+
+The server loads outdoor height grids from `data/terrain.bin` at startup. To
+rebuild that file from the original disc data, run
+`venv\Scripts\python.exe tools\extract_terrain.py` from this directory. It checks
+every block's dimensions, corner heights and shared edges. Height interpolation
+is approximate; buildings, walls and incorrect initial spawn heights still need
+separate handling.
+
+Screenshots are saved in `tools/multiplayer.png`, `tools/npc.png`, and
+`tools/borealis.png`. `tools/daylight-heads.png` shows the corrected heads and
+daylight; `tools/control.jpg` shows the controls. The appearance and character
+stats are placeholders.
+
+`tools/hands-fixed.png` and `tools/control-dropdown.jpg` show the hand fix and
+zone dropdown. Old Athen also loads through the dropdown. Not every map has
+been verified: the Grid shows error textures and the nightclub arrival can
+place the camera inside geometry. Indoor arrivals need tuning. World map
+origins outside Borealis are currently zero.
+
+The catalog comes from the release resource database and launcher name list.
+Outdoor arrivals use decoded terrain heights; indoor arrivals use district
+coordinates. Regenerate it from the original files with
+`venv\Scripts\python.exe tools\extract_playfields.py`, then run `gofmt` on
+`server/playfields.go`. Extracted data is retained in `tools/original-playfields.json`.
+
+See [docs/protocol.md](docs/protocol.md) for original-client evidence.
+REA bundles and provider snapshots are saved under `tools`.
+
+## Original NPC data
+
+The disc contains population directives: 6,178 template-code/count entries,
+33,151 spawn points with radii and 1,560 fixed NPC positions across 348 maps.
+Omni Training has 97 ordinary points and two fixed entries near the start.
+All original district records decode with exact record alignment. There are
+also 179 original monster appearance definitions, including Leet, Reet and
+Rollerrat. The population codes still need to be connected to complete NPC
+templates. The provisional generator represents all 62,175 requested NPCs in
+226 playable maps. Internal dependency maps are excluded. Inferred species
+models account for 39,190 NPCs; 4,467 human and 18,518 creature placeholders
+are named `Placeholder CODE`. Human placeholders use the original Solitus male
+model with the working head and clothing; creature placeholders reuse the Leet model.
+
+Fixed positions and minimum levels are preserved, including a level-400 entry.
+Ordinary points are assigned in order and reused with small offsets inside their
+radii when necessary. Districts without points use a grid around their centre.
+These placement rules and appearances are approximations, not recovered server
+logic. `tools/npc-coverage.json` records counts, appearance classifications and
+placement types. AI, combat, dialogue and respawn are not implemented.
+
+NPC batches live in `data/npc_spawns.yaml`, grouped by playfield, district and
+original template code. Edit their names, MonsterData, packed appearance,
+levels or XYZ rows directly. `appearance_status` and `placement_status` refer
+to structured confidence notes at the top of the file; each batch also has a
+free-text `comment`. YAML `#` comments are supported. A fixed coordinate can be
+authored while the appearance remains a placeholder. Levels use the authored
+minimum; the original server's level selection remains uncertain.
+
+The server reads this file from disk when started from the project root.
+Use **Reload NPC data** on `/control` to apply edits without restarting or
+rebuilding. It replaces NPC instances in connected players' zones and keeps
+the players connected. Invalid YAML, unknown fields or undefined statuses
+leave the current population intact and return an error. Reloading does not
+rerun the generator. Regenerating the YAML overwrites manual edits and comments.
+
+Regenerate the extracted catalogs from this directory:
+
+```powershell
+.\venv\Scripts\python.exe tools\extract_npc_spawns.py
+.\venv\Scripts\python.exe tools\extract_monsters.py
+.\venv\Scripts\python.exe tools\generate_npcs.py
+```
+
+The outputs are `tools/original-npc-spawns.json`,
+`tools/original-monsters.json`, `data/npc_spawns.yaml` and `tools/npc-coverage.json`.
+The coverage report describes the generator output; manual YAML edits are not
+reflected in that report. [docs/game-data.md](docs/game-data.md) records the decoded layout,
+original training-area entries and evidence. Research leads for other
+server projects are in [docs/open-questions.md](docs/open-questions.md).
+
+## Validate
+
+```powershell
+& 'C:\Program Files\Go\bin\go.exe' test ./server
+```
diff --git a/docs/README.md b/docs/README.md
@@ -0,0 +1,88 @@
+# Original Anarchy Online research
+
+This is a record of findings about the original 2001 Anarchy Online 11.0
+client, its wire protocol, and its shipped assets. The eventual goal is a web
+remake of that experience. The original Windows client provides a reference
+for recovering behavior and checking our interpretation.
+
+These documents describe the original artifacts and recorded experiments.
+They do not inventory the Go server's functions, state fields, tests, or
+current feature status. Read the source for implementation details and the
+[root README](../README.md) for local launch commands.
+
+## Where to start
+
+| Document | Contents |
+| --- | --- |
+| [versions-and-patches.md](versions-and-patches.md) | Provisional 13.24 target, historical cutoff evidence, city-layout uncertainty, recovered patch inventory, and upgrade handoff checks. |
+| [client-behavior.md](client-behavior.md) | Launch requirements, client simulation, visibility, appearance, lighting, logout, and inferred responsibilities of the historical server. |
+| [protocol.md](protocol.md) | Framing, compression, login, entity messages, zoning, time, appearance, and original reader/activation addresses. |
+| [game-data.md](game-data.md) | Resource database, map/terrain decoding, original district populations, monster appearances, and unresolved template links. |
+| [reverse-engineering.md](reverse-engineering.md) | Original binary hashes, saved evidence/snapshots, capture locations, and analysis recovery. |
+| [open-questions.md](open-questions.md) | Unknown semantics, failed experiments worth preserving, and other server projects as research leads. |
+| [browser-porting.md](browser-porting.md) | Browser-port examples, emulation/static translation versus reconstruction, and an untested feasibility proposal for AO. |
+
+For a fresh session, read this page and client-behavior.md, then use the
+protocol and game-data documents for the feature under investigation. Consult
+saved evidence before repeating native analysis. Choose further work from the
+user's latest instructions; the open questions are research leads.
+
+The selected historical target is now provisionally **13.24**, while the
+findings below remain evidence about **11.0**. Read versions-and-patches.md
+before any upgrade: the exact 13.24 binary path and preservation of the city
+gathering area are not yet verified. No upgrade was performed in that research.
+
+## Evidence standard
+
+- A decoded field or procedure should refer to original bytes, a retained
+ evidence ID, or a resource/capture that can be inspected again.
+- Static reader code establishes a layout. Activation code helps establish
+ its meaning. A successful experiment establishes that the tested input was
+ accepted, not that it matches every historical server behavior.
+- Distinguish observed behavior, plausible inference, and unresolved questions.
+ Later emulators suggest names and approaches but do not specify 11.0 layouts.
+- Preserve negative results with their search scope or exact attempted payload.
+ An unsuccessful bounded search does not prove that data never existed.
+
+Update these documents when an original-client finding changes or an unknown
+is resolved. Routine Go changes do not require matching documentation edits.
+Keep captures and implementation tests with the code that produces them.
+
+## Original artifacts and workspace
+
+The investigation took place at `C:\path\to\ao` on Windows. The
+reference is `Anarchy Online 11.0.iso`, 669872128 bytes, initially mounted at D:.
+Drive letters and running processes must be rediscovered after a restart.
+
+| Path | Role |
+| --- | --- |
+| `client-original/Gamefiles/` | Pristine release files extracted from the disc. |
+| `client-local/`, `client-peer/` | Working original clients used for experiments. |
+| `server/` | Local Go implementation; consult the source directly. |
+| `tools/` | Extractors, decoded catalogs, REA snapshots, evidence, captures, and launch helpers. |
+| `venv/` | Python environment used by the tools. |
+| `C:\Funcom\Anarchy Online` | Separate modern installation, left untouched. |
+
+The release files were extracted with Unshield rather than installed. This
+avoided an installer conflict with the modern installation. The verified local
+launch required URL/preference edits, not executable-byte patches. Binary
+identities are recorded in reverse-engineering.md.
+
+If extraction must be reproduced, discover the mounted ISO drive and extract
+the Gamefiles group into a fresh directory, for example:
+
+```powershell
+.\tools\unshield\unshield.exe -d client-extracted-check -g Gamefiles x D:\data1.cab
+```
+
+Compare original hashes before replacing a reference. Historical experiment
+binaries and logs are evidence, not necessarily the current implementation.
+
+## Working preferences
+
+Keep the original 2001 release as the fidelity reference, and always run it
+windowed. Test routine inputs autonomously; do not wait for the user to press
+W or X. The control UI should remain plain HTML without SPA frameworks,
+branding, or decorative design. Prefer focused, straightforward changes and
+ASCII source; use the existing Python environment. Read applicable AGENTS.md
+and installed skills in the future session and respect the latest user edits.
diff --git a/docs/browser-porting.md b/docs/browser-porting.md
@@ -0,0 +1,172 @@
+# Browser-port approaches for the original AO client
+
+Primary-source research recorded on 2026-10-12. This compares ways to preserve
+an old game's behavior in a browser and applies them to the release 11.0
+client. It is a research recommendation, not an implemented browser port.
+AO has not been tested with the runtimes or translators discussed here.
+Recheck project capabilities before choosing a dependency; their support
+status can change independently of the original-client findings.
+
+## The approaches are different
+
+| Approach | Input | What must be supplied |
+| --- | --- | --- |
+| Compile available source | Portable C/C++ or other supported source | Browser graphics, input, audio, files, main loop, and networking adaptations. |
+| Reconstruct source, then compile | Original binary plus manually recovered source | Correct algorithms/data structures, then the platform adaptations above. |
+| Reimplement an engine | Original assets and recovered behavior | New renderer, simulation, UI, and asset readers that reproduce the original. |
+| Emulate or dynamically translate | Original executable and dependencies | CPU execution and the operating-system/API environment expected by the binary. |
+| Statically translate a binary | Original executable plus control-flow knowledge | Generated executable code, a compatible memory/runtime model, and API replacements. |
+
+Compiling recovered source and translating instructions are not the same task.
+Source reconstruction seeks meaningful functions and structures. A translator
+can retain registers and guest memory in generated code without recovering the
+original high-level design. Both still need the surrounding platform contract.
+
+## Source ports: QuakeJS
+
+[QuakeJS](https://github.com/inolen/quakejs) ports ioquake3 using Emscripten.
+Its README documents WebSocket networking and repackaging assets into
+map-specific packages. This demonstrates that compiling the engine is only
+part of a browser port: networking and content delivery need adaptations too.
+The original project's web/native networking restriction is a property of
+that implementation, not an unavoidable rule for all browser games.
+
+For AO, this route becomes attractive if we obtain or reconstruct suitable
+source. The extracted EXE/DLLs are not directly compilable engine source.
+
+## Recovered source: Super Mario 64 and Diablo
+
+[sm64-port](https://github.com/sm64-port/sm64-port) builds on the Super Mario 64
+decompilation. Its [Makefile](https://github.com/sm64-port/sm64-port/blob/master/Makefile)
+contains TARGET_WEB, an emcc compiler path, and SDL/OpenGL browser support.
+This is a concrete recovered-source-to-Emscripten/WebGL route.
+[sm64js](https://github.com/sm64js/sm64js) instead ports that decompilation to
+native JavaScript. The implementation language can change while retaining
+recovered game algorithms.
+
+[Devilution](https://github.com/diasurgical/devilution) reconstructed Diablo's
+source using binary analysis, including symbols accidentally retained in a
+PlayStation release and debug/assert information in a PC build. It deliberately
+preserved original behavior, including bugs, as a base for further ports.
+That unusually helpful evidence matters when estimating comparable work for AO.
+
+Do not treat every announced browser build as a finished faithful port.
+The examined [DevilutionX build guide](https://github.com/diasurgical/devilutionX/blob/master/docs/building.md)
+called its Emscripten port work in progress and said it built without doing more.
+A separately hosted [browser build](https://devilutionx.app/) advertised an
+Emscripten build with MPQ loading. Those are distinct reports; neither establishes
+AO compatibility or complete fidelity of that browser build.
+
+For AO, manual reconstruction of the entire client would be substantial.
+Selected algorithms may be worth reconstructing independently without making
+complete source recovery a prerequisite for the first browser scene.
+
+## Engine reconstruction: OpenLara and noclip.website
+
+[OpenLara](https://github.com/XProger/OpenLara) is an open-source classic Tomb
+Raider engine with a WebGL demo. Its [WASM build script](https://github.com/XProger/OpenLara/blob/master/src/platform/web/build_wasm.bat)
+compiles C++ using em++ with WebGL2 and preloads game files. This is an example
+of a reconstructed engine using original game data and a browser platform layer.
+
+[noclip.website](https://github.com/magcius/noclip.website) presents original
+game levels using reverse-engineered model formats. Its source includes web
+code and Rust/WASM components. It is a useful reference for asset decoding and
+scene reconstruction, not evidence that displaying a level recovers gameplay,
+collision, UI, or server rules.
+
+For AO, an incremental reconstruction could first reproduce one original zone,
+then character animation, movement/collision, entities, and UI. Original
+geometry and textures help establish visual fidelity; camera, fog, lighting,
+animation timing, and movement still need comparison with the release client.
+
+## Original-binary execution: Boxedwine and CheerpX
+
+[Boxedwine](https://github.com/danoon2/Boxedwine) runs 16/32-bit Windows programs
+through Wine and includes Emscripten/WASM builds. Its examined README explicitly
+listed the web build as slow, with a JIT still needed and audio issues in the
+multithreaded build. General graphics support in the project is not proof that
+AO's particular browser graphics path works or performs adequately.
+
+[CheerpX](https://cheerpx.io/docs/overview) combines an x86 interpreter with a
+JIT that generates WASM for hot code. It runs existing 32-bit binaries without
+source reconstruction and currently focuses on a Linux-compatible user-mode
+system-call environment. Its use for virtualizing the original Flash player
+demonstrates binary preservation, but does not supply a ready Win32 environment
+for AO. Windows compatibility would be an additional requirement.
+
+Executing the original client could preserve many otherwise difficult details
+of its UI and simulation. For AO that benefit is conditional on executable/DLL
+loading, API compatibility, graphics, input, audio, networking, and performance.
+None of those conditions has been verified in a browser for our release client.
+
+## Static translation: Theseus
+
+[Theseus](https://github.com/evmar/theseus) translates DOS and 32-bit Windows
+x86 code into Rust, alongside implementations of some DOS/Win32 APIs. The
+generated program can target a native platform or WASM. Its README calls it
+very experimental and warns that unfamiliar programs are likely not to work.
+
+The author's [April explanation](https://neugierig.org/software/blog/2026/04/theseus.html)
+describes translating instructions into source operations and resolving system
+calls to API replacements. It also explains control-flow discovery problems
+and the need for manual assistance on particular programs. This is not a
+general claim that any Windows binary can be translated automatically.
+
+The [May browser follow-up](https://neugierig.org/software/blog/2026/05/theseus-wasm.html)
+demonstrates WASM output and describes running translated threads in workers,
+with shared-memory/atomic coordination for synchronous calls to the browser
+host. Its examples still had bugs. This resolves the older April article's
+statement that the web target was not implemented at that time.
+
+Theseus is particularly relevant because AO's reference client is 32-bit
+Windows code. That makes it a candidate to investigate, not a demonstrated AO
+solution. Translation of instructions would still leave the game's DLLs and
+Windows/graphics/audio/input/network API dependencies to handle.
+
+## What Emscripten does and does not provide
+
+[Emscripten](https://emscripten.org/docs/introducing_emscripten/about_emscripten.html)
+uses Clang/LLVM to compile C/C++ and suitable LLVM-based language inputs into
+WASM with JavaScript support. Its documentation discusses portable code and
+adaptations to graphics, the main loop, and file handling. It does not accept
+an arbitrary Windows EXE as a substitute for portable source.
+
+Ghidra pseudocode is analysis output, not a complete portable source tree.
+Recovered types, globals, calls, object layouts, and dependencies need checking
+before compiling a reconstructed subsystem. A compiled version also needs
+behavioral comparison; successful compilation alone does not establish fidelity.
+
+Normal browser pages cannot directly open AO's TCP sockets.
+[Emscripten's networking guide](https://emscripten.org/docs/porting/networking.html)
+documents WebSocket access and socket-proxy approaches. A WebSocket-to-TCP
+bridge could carry original AO frames to the local server for a translated
+client. A new client could instead use a browser transport while preserving
+the recovered entity/game semantics. Choosing that transport is an
+implementation decision, separate from the original protocol.
+
+## Proposed decision process for AO
+
+This is a proposal; the compatibility experiments below have not been run.
+
+1. Make a bounded compatibility assessment of Theseus and Boxedwine against
+ the release client and its DLLs. Record the actual first blockers instead
+ of inferring compatibility from another game's demo.
+2. Define success as entering Omni Training, walking, rendering correctly,
+ accepting input, and maintaining a server session at usable performance.
+ Reaching a launcher window or drawing a test triangle is insufficient.
+3. Keep the native release client as a behavioral reference under either route.
+ Compare identical scenes, positions, times, and input sequences. Captures
+ should distinguish rendering, movement, animation, UI, and network behavior.
+4. If binary compatibility requires extensive emulator work, reconstruct a
+ bounded browser scene using original assets, then expand from measured
+ differences. Recover individual native algorithms where that provides
+ fidelity; use WASM selectively rather than assuming every subsystem needs it.
+
+The recommendation is to resolve binary-preservation feasibility before
+committing to an entire engine rewrite. It is not a decision to adopt a runtime,
+change the existing server, or begin both approaches in parallel.
+
+All routes still need the missing server reconstructed. Preserving the client
+does not recover private 2001 NPC templates, combat/loot rules, scripts,
+persistence, or encounter decisions. Existing original-client protocol and
+asset findings remain useful whichever browser approach is selected.
diff --git a/docs/client-behavior.md b/docs/client-behavior.md
@@ -0,0 +1,153 @@
+# Original-client behavior and server responsibilities
+
+These findings concern the release 11.0 binaries identified in
+[reverse-engineering.md](reverse-engineering.md). Wire layouts and native
+procedure references are in [protocol.md](protocol.md). Runtime observations
+come from retained original-client experiments, not a live inventory of the
+local server.
+
+## Launching the original client
+
+The launcher obtains a dimension list from the host/path in
+`DimensionServer.url`, appending `/dimensions.txt`. A dimension record with
+version 11.0 and local endpoints was sufficient to reach login and Play
+without applying an official update. No executable-byte patch was needed
+for that experiment. This does not establish a complete patch-service format.
+
+The launcher supplies the game executable's working directory, environment,
+and connection arguments. Clientr.exe accepts positional arguments:
+
+```text
+Clientr.exe USERNAME PASSWORD CHARACTER_ID [NUMERIC_IPV4 PORT COOKIE1 COOKIE2]
+```
+
+There are either three or seven arguments. The verified localhost launch used
+2130706433 for the IPv4 value and set `ANARCHY_CD=cd_image` and
+`ANARCHY_SETUP=Setupf`, with the client directory as the working directory.
+The extracted game ran without the disc remaining mounted. The preference
+`FullScreen 0` selects windowed mode.
+
+The Python launch helper performs a short login exchange to obtain a character
+ID before launching the native executable. Its socket closes before the game
+starts. It is not a proxy or an ongoing game dependency. The original launcher
+can perform the same login-to-world handoff; the helper is an experimental
+shortcut. Consult its source for the local server's current login behavior.
+
+## Entering the world and becoming visible
+
+The world connection sends a character cookie. Connecting already triggers
+the client's internal logged-in event; system opcode 0x10 signals a character
+error. Replying with 0x10 as an acknowledgement sent the client back to the
+launcher and produced a GUI cleanup crash in an early experiment.
+
+Original playfield, SimpleCharFullUpdate, and FullCharacter messages were
+sufficient to load Omni Training and permit walking. FullCharacter activation
+sends an unblock request and CharInPlay. Its acknowledgement uses the player
+identity with no subclass body.
+
+Remote-player SCFU activation hides a character whose InPlay stat 194 is zero.
+Sending SCFU followed by CharInPlay made another player visible. This explains
+why a correctly instantiated remote character can still be absent from the
+rendered scene. The transport recipient and the N3 entity identity are distinct:
+a message about player A delivered to player B addresses B in the outer frame
+and A in the N3 prefix.
+
+## Movement
+
+The original client simulates local walking and turning and emits CharDCMove
+messages containing an action, position, quaternion, and two additional floats.
+Captured packets include individual zlib-compressed bodies. Relaying those
+updates to another original client reproduces visible peer movement.
+
+This establishes a client prediction/update path. It does not establish how
+the historical server validated movement, corrected position, checked collision,
+or simulated NPCs. The two trailing movement floats and vehicle path/control
+semantics need further work before reconstructing authoritative movement.
+
+The retained walking capture records position changes from
+(52.625,14.722409,56.875) to (55.962704,14.0,63.920597), including turn and stop
+commands. Coordinates are evidence of that experiment, not universal spawn
+requirements.
+
+The shipped `keyboard map.GIF` is a useful original control reference. In a
+recorded autonomous movement check, numpad 0 started sustained forward walking;
+a W tap stopped it and emitted the final position. The camera followed movement,
+and collision stopped the player at the training fence. These controls allow
+movement checks without relying on a held-key API or a user keypress.
+
+## Appearance is explicit state
+
+A packed race/breed/sex value alone did not supply a complete player appearance.
+SCFU activation unconditionally applies HeadMesh to stat 64. Omitting the
+optional field leaves it zero and removes the head. An explicit original
+Solitus male head mesh, 40682, restored local and remote heads.
+
+Likewise, the original Solitus body's default hands texture is actually solid
+green. Supplying original skin texture 8773 through the named TextureDataList
+restored skin. A hands-only list removed other body materials; the tested
+complete list included arms, feet, hands, legs, and body. Appearance problems
+can therefore reflect missing network state rather than corrupt game assets.
+
+NPCs use a separate SCFU branch selected by flag bit 0. MonsterData stat 359
+selects a monster appearance. A Leet using original MonsterData 17655 rendered
+and could be selected without a FullCharacter message. This proves an NPC
+creation/rendering path, not combat, AI, loot, or historical spawn selection.
+
+## Lighting and time
+
+The original GameTime_t constructor defines a 27-hour day and a clock speed
+of 15 game seconds per real second. Full daylight is between hours 10 and 18;
+dawn is 5-10 and dusk is 18-23. A dark scene is consistent with nighttime,
+and does not by itself indicate broken terrain or materials.
+
+Sending a GameTime update for midnight visibly darkened the scene; sending
+13:30 restored daylight without reconnecting. Its original payload contains
+seconds within the day, day period, and day number. The examined Update
+function uses seconds and day number but does not use the supplied period.
+
+## Travel and departure
+
+The original teleport message distinguishes a move within a playfield from
+playfield teardown. A zone-change teleport followed by system redirect 0x3c
+caused the client to connect again and send the existing character cookie,
+without a new login or character identity. Destination initialization then
+loaded the new playfield. Training, Borealis, and Old Athen rendered in the
+recorded experiments.
+
+Sending n3ToClientQuitIIR_t to peers removed the addressed entity. Its activation
+excludes the local player. Departure and return were visible across two
+clients. Disconnect cleanup and zoning must therefore account for the same
+character identity having a replacement connection.
+
+Map presence does not guarantee a safe arrival. A Grid scene loaded with error
+textures, and a nightclub arrival intersected geometry. Terrain/district
+coordinates are useful candidates, not proof of walkability.
+
+## Sitting, quitting, and cancellation
+
+Captured character actions identify sit 86, stand 87, cancel 108, and logout
+120. Acknowledging sitting allowed the expected posture change. Quit to Windows
+starts a 30-second client progress bar. Closing the world connection after
+that interval completed normal quitting in the recorded experiment.
+
+Standing prevented the delayed connection close, but the client progress bar
+remained. Echoing action 108 and sending an empty StopLogoutIIR_t both failed
+to clear it. The original cancellation UI contract is unresolved; normal quit
+success does not resolve cancellation.
+
+## What the historical server probably supplied
+
+The evidence supports the following division, with important gaps:
+
+| Area | Evidence and inference |
+| --- | --- |
+| Accounts and character state | Login responses and FullCharacter carry lists/stats; historical validation and persistence are not recovered. |
+| Entity existence and visibility | SCFU, CharInPlay, and despawn control original-client entities. A real server needed to select recipients and entity lifetimes; its interest rules are unknown. |
+| NPC populations | Disc districts contain template codes/counts and points, while messages create live instances. Server-side selection and template resolution are plausible; exact algorithms and any separate server data are unknown. |
+| NPC simulation | The client accepts positioned NPCs and movement updates. Patrol pointers exist, but authored routes and historical simulation have not been recovered. |
+| Appearance | Head, named materials, and MonsterData are transmitted state. Exact historical outfit/skin selection remains unknown. |
+| Clock and travel | GameTime and teleport/redirect messages supply shared time and transitions. Historical scheduling and zone-server topology are not established. |
+| Combat, loot, nanos, dialogue | Rendering/selection does not recover their rules. No complete original server implementation or data set has been found. |
+
+Original client code reveals what it reads and does. It cannot, by itself,
+prove the complete decisions or private data of the 2001 server.
diff --git a/docs/game-data.md b/docs/game-data.md
@@ -0,0 +1,344 @@
+# Original assets, zones, and NPC population data
+
+The reference data is the extracted 11.0 disc, under
+`client-original/Gamefiles/cd_image/data`. Extractors read this copy, not the
+modern installation or a patched resource database.
+
+## Resource database container
+
+The database consists of `db/ResourceDatabase.idx` and
+`db/ResourceDatabase.dat`. The retained placement evidence records index SHA256
+`e339c9be1a302420d6b1c7b48cae37d2955760167f0b758fa8ef1761bb591eca`.
+Do not assume the index and data formats are uniformly big-endian or little-endian.
+
+| Structure | Layout used by the extractors |
+| --- | --- |
+| Index header | Offset 72: little-endian uint32 pointer to first linked block. |
+| Index block | Offset 0: next-block uint32 LE; offset 8: entry count uint16 LE; entries begin at 18. |
+| Index entry | 12 bytes: data-file offset uint32 LE, resource type uint32 BE, resource ID uint32 BE. |
+| Data record header | 34 bytes; type and ID uint32 LE at offsets 10 and 14; size field uint32 LE at 18. |
+| Payload | Immediately after the 34-byte header; byte count is size field minus 12. |
+
+The three extractors share this container interpretation. Their assertions
+check identities, relevant format versions, and alignment. Do not silently
+skip malformed records or use a later-version decoder without checking the
+actual original payload.
+
+## Known resource families
+
+| Type | Established use and boundary |
+| --- | --- |
+| 1000001 | Playfield definitions; 348 original records, all version 8. |
+| 1000009 | CHGA outdoor ground archives with compressed height blocks; GNDA records examined here have no such table. |
+| 1000010:1 | Filename registry; resource ID and padded filename strings. |
+| 1000014 | Playfield districts and population directives; 348 version-5 records. |
+| 1000021 | PlayfieldWalls. An independent decoder matched all 179 original records to EOF. It is not identified patrol data. |
+| 1000026 | RDBDynelLoader input for static world objects. Static dynels do not imply NPC population templates. |
+| 1000029 | Region metadata and descriptive text. |
+| 1000030 | PlayfieldDoors. |
+| 1010002 | Model/material resources; 5907 is the examined Solitus body resource. |
+| 1010004 | Examined PNG texture family, including green default hands 8712. |
+| 1010011 | Examined JPEG texture family, including hand skin 8773. |
+| 1040023 | Monster appearance definitions; 179 extracted original records. |
+
+The original DLLs and database contain more families. This table is the subset
+examined during world/entity recovery, not a full
+resource-format inventory.
+
+## Regeneration and outputs
+
+From the workspace root:
+
+```powershell
+.\venv\Scripts\python.exe tools\extract_playfields.py
+& 'C:\Program Files\Go\bin\gofmt.exe' -w server/playfields.go
+.\venv\Scripts\python.exe tools\extract_npc_spawns.py
+.\venv\Scripts\python.exe tools\extract_monsters.py
+.\venv\Scripts\python.exe tools\extract_terrain.py
+```
+
+| Extractor | Outputs and side effects |
+| --- | --- |
+| `tools/extract_playfields.py` | Overwrites `server/playfields.go` and `tools/original-playfields.json`. |
+| `tools/extract_npc_spawns.py` | Overwrites `tools/original-npc-spawns.json`. |
+| `tools/extract_monsters.py` | Overwrites `tools/original-monsters.json`. |
+| `tools/extract_terrain.py` | Writes `data/terrain.bin` and `tools/terrain-extraction-evidence.json`. |
+
+These scripts use relative input/output paths, so their working directory must
+be the workspace root. They use the Python standard library. Review manual
+changes to generated output before regenerating it. These tools document
+the original data; runtime use of their output is an implementation choice.
+
+## Zone catalog and arrival derivation
+
+The playfield name is the NUL-terminated ASCII field at payload bytes 8-39.
+The launcher's `launcher/pfnrmap.dat` adds 25 names without corresponding map
+records. Combined, the catalog has 373 names. Four resource-backed maps
+(100, 102, 103, 1410) were identified as internal dependencies, leaving 344
+maps with assets considered suitable for exploration experiments.
+
+For 180 usable outdoor maps, the extractor reads CHGA width, height, tile size,
+and height scale. It samples the map center. Height blocks are zlib-compressed
+byte deltas with reconstruction:
+
+```text
+height_byte = (delta + left + above - diagonal) modulo 256
+```
+
+The extractor checks selected decoded corners against the corresponding
+small-height record. It derives the sampled Y as height byte times scale plus
+0.5. This validates that sample, not collision or walkability of the whole map.
+For the 164 usable indoor maps, arrival is the first district center XYZ from
+1000014, beginning at payload offset 7.
+
+Two arrivals were exercised: training 950 at (52.625,14.75,56.875), and
+Borealis 800 at (679.625,74.75,537.875). These are verified experimental
+coordinates, not recovered universal spawn requirements. Borealis loaded with
+world origin (37107,38360); other origins have not been established.
+Geometry resource keys use `(playfieldID << 16) | tileIndex`. Original zone
+names often include internal labels and dungeon suffixes; preserve those
+names rather than introducing later-world assumptions.
+
+### Complete outdoor ground archives
+
+The ground payload contains a serialized `AnarchyGroundDataDB_t` archive after
+the CHGA header and texture IDs. Its `map_width`, `map_height`, and `map_modulo`
+fields give the actual vertex grid. The CHGA display dimensions at offsets
+12 and 14 can differ substantially: Avalon 505 reports 860x1160 there, but its
+archive contains 897x1537 vertices. Tir County 646 has 1025x513 vertices despite
+a 910x460 header. Do not use the display width to select a compressed block.
+The older center-arrival extractor does so; its generated arrivals outside
+individually verified maps require rechecking before regeneration.
+
+The native archive constructor at original bbr.dll 0x1004d7a0 reads these named
+fields. Its helper at 0x1004d630 counts trailing zero bits, rather than computing
+floor(log2). The block cell count is the smaller of the least-significant set
+bits of `(map_width-1)` and `(map_height-1)`, capped at 64. Thus most blocks
+contain 65x65 height vertices, while map 540 uses 33x33. Blocks are stored in
+row-major order with shared edge vertices; native `Height` at 0x10047b30 uses
+the archived grid width to calculate the block row stride.
+
+The retained decoder recognizes fields 4-7 immediately before the compressed
+table. Each is 17 bytes: one field-number byte, uint32 LE type 3, uint32 LE
+type size 4, uint32 LE value size 4, then uint32 LE value. These represent
+vertex width, vertex height, row modulo and texture count, respectively.
+The height-table marker is `08 09 00 00 00 00 00 00 00`, followed by its
+uint32 LE byte count and repeated uint32 LE compressed-length/zlib-block pairs.
+Reconstruct the decompressed byte deltas using the formula above.
+
+The following small-height table starts with
+`09 09 00 00 00 00 00 00 00` and a uint32 LE byte count. It has eight bytes
+per block; bytes 4-7 match that block's top-left, top-right, bottom-left and
+bottom-right height bytes. The first four bytes remain opaque here.
+Every decoded block's corners and every shared horizontal/vertical edge were
+checked exactly across all 180 usable outdoor grids. These contain 31,336,884
+unique vertex bytes. Another 54 usable ground records have no compressed table.
+The source identities and decoded-grid digests are retained in
+`tools/terrain-extraction-evidence.json`.
+
+World X/Z are local metres with the CHGA horizontal spacing (four metres in
+the examined grids); vertex altitude is the byte value times the CHGA height
+scale. This supplies terrain, not building floors, water behavior or a navigation
+mesh. Smooth four-corner interpolation is a useful reconstruction approximation.
+The native `InterpolatedHeight` at 0x1004ee50 has checkerboard-dependent branches;
+its retained assembly does not establish equivalence to ordinary bilinear
+sampling or to the client's collision surface. Exact collision/interpolation
+semantics remain open.
+
+`data/terrain.bin` is a derived export, not an original AO format. It begins
+with ASCII `AOTERR01` and uint32 LE record count. Each record has playfield
+uint32 LE, cell width/height uint16 LE, horizontal spacing/height scale float32
+LE, then `(width+1)*(height+1)` row-major height bytes. It includes the full
+archived grid, including terrain beyond the smaller display dimensions.
+
+Runtime has verified training, Borealis, and Old Athen rendering. The original
+Grid and a nightclub load, but the Grid shows error textures and the nightclub
+arrival intersects geometry. Asset-backed availability must remain distinct
+from individually verified, safe arrival.
+
+## The disc contains NPC placement directives
+
+Live NPC instances are created from server messages, but placement was not
+entirely absent from the disc. Resource 1000014 provides authored district
+populations and fixed spawn coordinates. The retained catalog contains:
+
+| Item | Count |
+| --- | ---: |
+| Playfields | 348 |
+| Districts | 1977 |
+| Population template-code/count entries | 6178 |
+| Ordinary spawn points with radius | 33151 |
+| Fixed spawns | 1560 |
+| Opaque six-byte extra-info entries | 4812 |
+
+Every original district resource decodes as version 5 to exact EOF, and every
+map-cell district index is valid. A separate experimental parser agreed with
+the retained extractor across all maps. That temporary parser was not retained;
+the permanent extractor and its alignment assertions are available.
+
+### Version-5 district layout
+
+Resource header: uint16 version, int32 zone-map byte count, uint8 district count.
+All numeric fields in this payload use little-endian representation.
+
+Each district contains, in order:
+
+1. Center XYZ: three float32; name: fixed 32-byte ASCII field.
+2. Nine uint16 stats and four opaque bytes.
+3. Minimum/maximum NPC level: two uint8.
+4. Respawn chance uint8, respawn time int32, fight mode uint8.
+5. Five uint8 counts: population groups, extra-info entries, music pairs,
+ ordinary points, and fixed spawns.
+6. Groups: template code uint32 and requested count uint16.
+7. Extra-info entries: six opaque bytes each.
+8. Music pairs: two uint16 each.
+9. Ordinary points: XYZ and radius, four float32 each.
+10. Fixed spawns: the layout below.
+
+A fixed spawn is 32 bytes in the examined original records:
+
+```text
+XYZ float32[3]
+radius float32
+angles int16[2]
+template_hash uint32
+min_level uint16
+max_level uint16
+respawn_chance uint8
+flags uint8
+respawn_time uint16
+```
+
+All original fixed-spawn flags are zero. The retained extractor asserts this
+rather than inventing support for later optional tails. After all districts,
+the resource carries exactly the declared number of map-cell district bytes.
+
+Template codes are four-character strings packed into uint32 values. Many
+are readable abbreviations, such as LEET, ANUN, and RR01, rather than opaque
+hash outputs. The JSON field `template_hash` retains the external decoder's
+terminology; no hashing algorithm was recovered for this field. Their
+on-disk byte order is reversed: the extractor reads uint32 LE and emits its
+four bytes in BE order. Treat them as template references, not MonsterData IDs.
+Heading-angle units, radius selection rules, respawn-time units, fight-mode
+semantics, the nine stats, and the extra-info fields remain unresolved.
+
+### Omni Training 950
+
+There are 97 ordinary points and two fixed spawns across six districts:
+
+| District | Level range | Groups | Ordinary points |
+| --- | --- | --- | ---: |
+| Outside District | 1-1 | None | 0 |
+| Level 1-2 Area | 1-2 | H320 x1, LE02 x3, SN01 x4 | 16 |
+| Level 1 Area | 1-1 | LE01 x6, RT01 x6, SN01 x1 | 28 |
+| Level 1-2 Area | 1-2 | H366 x1, LE01 x4, RT01 x4 | 23 |
+| Level 2-4 Area | 2-4 | H476 x1, ML01 x3, SN02 x2, SR01 x4 | 30 |
+| Level 1-3 Area | 1-3 | LEET x4, ML01 x2 | 0 |
+
+The repeated names are different districts, not duplicate records. Group
+counts describe population directives; they do not establish a one-to-one
+assignment to the listed points or imply all entries must appear simultaneously.
+
+Some populated districts have no ordinary points, and others request more
+instances than points. A reconstruction must choose an allocation policy or
+approximate missing positions; dropping these groups loses authored population
+coverage. The original server's point selection, distribution within radii and
+ground-height adjustment have not been recovered.
+
+Fixed minimum levels use uint16, unlike the district's uint8 levels. Newland
+City (566) contains a FEPA fixed entry with minimum level 400. The SCFU reader
+supports a uint16 level when flag 0x1000 is set, so the wire format can represent
+this value. Its template identity and intended behavior remain unresolved.
+
+| Fixed code | XYZ | Raw angles | Levels | Radius | Chance | Raw respawn time |
+| --- | --- | --- | --- | --- | --- | --- |
+| OTBG | 57.673809, 13.999916, 55.950287 | 0, 30 | 200-200 | 1 | 100 | 2 |
+| OTGD | 49.648979, 14.099686, 61.600853 | 48, 30 | 200-200 | 1 | 100 | 2 |
+
+These entries are near the player's starting point. The numbers are established
+disc data. Their names, models, professions, dialogue, and behavior have not
+been established. Do not identify them from their code spelling alone.
+
+## Appearance definitions are a separate catalog
+
+`tools/original-monsters.json` contains MonsterData ID, explicit name, mesh ID,
+mesh filename, initial stat dictionary, and data-record offset for 179 resources.
+
+Their initial layout is version 15, section 23, followed by encoded count
+`(n+1)*1009` and n pairs of uint32 stat ID/value. Stat 12 gives mesh ID. The
+extractor verifies that section 14 follows this initial list. It locates the
+terminal name section `(6,28,1009)`, checks its explicit length, final NUL, and
+exact EOF. Intermediate sections have not all been semantically decoded.
+
+The filename registry includes an ID and a padded length before the ASCII
+filename. The footprint is `(len(filename)//4 + 1)*4`, including room for the
+terminator. Requiring length to equal visible string length was incorrect.
+All 179 extracted appearances resolve through the original filename registry.
+
+| Appearance | MonsterData | Mesh ID | Original mesh filename |
+| --- | ---: | ---: | --- |
+| Leet | 17655 | 15222 | cutecreature.cir |
+| Rollerrat | 17687 | 15272 | rollerrat_exp.cir |
+| Giant snake | 30252 | 23353 | giant_snake.cir |
+| Minibull | 30360 | 26904 | minibull.cir |
+| Reet candidate, named cute birdy | 30365 | 25733 | cute_birdy.cir |
+
+The `_exp` spelling is present in the original Rollerrat filename; it does not
+by itself identify later expansion content. The retained runtime experiment
+directly verified Leet rendering; the other entries are original asset findings.
+
+## Unresolved links and routes
+
+Authored district names corroborate some creature families without resolving
+complete templates. Omni Forest 716's Leet Burrows contains only LE03 and LE04;
+Wailing Wastes 551's Rollerrat Den contains RR01 through RR10. Newland Desert's
+Rhinoman Camp/Base and Varmint Woods' rhino villages use RH codes. Aegean's
+snakez and the Snake Valley districts in 790/791 support SN/SNAK as snakes.
+The separate RR family makes Reet a better provisional interpretation of RT
+than Rollerrat, but no direct RT-to-appearance link was recovered. AD/EY/LZ
+assignments have no species-named district corroboration from this search.
+`tools/world-population-evidence.json` preserves original record/district
+offsets, payload hashes, exact groups, appearance candidates, and limits.
+
+A bounded search for training codes in resource families 1000010, 1000015,
+1000020, 1000026, 1000029, 1000032, and 1040023 did not recover the mapping to
+complete templates. That negative result is not proof that no original mapping
+exists elsewhere or in a packed representation. Appearance names and IDs do
+not supply complete stats, loot, dialogue, or AI.
+
+A further bounded search compared all original resource IDs with 1,359
+population code values and inspected 2,242 administrative/script records
+(1,231,555 payload bytes) for nine training codes in both byte orders. No
+direct mapping was recovered. Exact families and searches are retained in
+world-population-evidence.json; this does not establish absence elsewhere.
+
+Further species inferences can use code spelling, authored district names,
+and original appearance names together. AN occurs in Anun Feeding Pit, BR in
+Bronto Compound, CY in Cyborg Barracks/Enclave, ME in The medusa city, MN in
+Mantis Hunting Ground, and YU in Yuttos Camp. These support base species
+models, but do not resolve the original numbered variants. Other assignments
+based on abbreviation similarity alone have weaker support. The original
+district offsets/groups, candidate appearance records, and inference limits
+are retained separately in `tools/population-code-evidence.json`.
+
+Original kkr.dll playfield getters expose area data at +0xd0, districts at
++0xd4, and patrol data at +0xd8. GetPatrolLists at 0x10132cb0 returns its pointer;
+the observed xref was an export-table pointer, not a route-consuming caller.
+The examined constructor zeroes the field. Actual patrol routes are unresolved.
+
+Region 1000029:595 mentions Medusa Territory, the Foul Forest, gators, and
+swampghoul colonies; 1000029:610 mentions Pendpods. These are useful broad
+ecological hints, not exact spawn coordinates. Original text, offsets, payload
+hashes, and limits are in `tools/npc-placement-evidence.json`.
+
+## External decoding references
+
+The district decoder was cross-checked against
+[AODB PlayfieldDistrictInfo_1000014.cs](https://gitlab.com/never-knows-best/aodb/-/blob/a772622bf39f7ac07a1761b90765214304d15107/AODB.Common/RDBObjects/PlayfieldDistrictInfo_1000014.cs),
+commit a772622bf39f7ac07a1761b90765214304d15107. The examined source SHA256 was
+2e1ad3e2d43f73707efaad542f395b7ad4c0445c946ed7be35b14e837e73e65c.
+[AORebirth's DistrictExporter](https://github.com/subarumike/AORebirth/blob/master/Tools/RDBDataExtractor/DistrictExporter.cs)
+uses that format to export district and spawn data. The AODB 1.0.10 NuGet
+SourceLink metadata supplied the source revision; temporary package files were
+removed after analysis. Exact original-record validation is the stronger
+evidence for the layout used here.
diff --git a/docs/open-questions.md b/docs/open-questions.md
@@ -0,0 +1,118 @@
+# Open questions and research leads
+
+These are gaps in the recovered original behavior, not a checklist of Go
+features. Resolve them with original bytes/captures where possible and keep
+an emulator-derived hypothesis separate from an established 11.0 finding.
+
+## Population codes and complete NPC templates
+
+The disc supplies packed four-character population codes such as LE01, RT01, SN01, OTBG,
+and OTGD, plus counts, levels, points, and fixed placements. It separately
+supplies MonsterData appearances. The link between them is unresolved.
+
+A bounded search of original families 1000010, 1000015, 1000020, 1000026,
+1000029, 1000032, and 1040023 did not recover a mapping. This does not prove
+the mapping is absent from all client data or was exclusively server-side.
+Search loading code and other resource families without identifying a
+template from its code spelling alone.
+
+Unknown population semantics include selection of points/radii, allocation of
+groups to points, respawn units/chance, heading angles, fight mode, district
+stats, and six-byte extra-info entries. The exact original layout and training
+entries are in [game-data.md](game-data.md).
+
+## Movement, controls, and patrols
+
+The CharDCMove reader accepts two floats after XYZ/quaternion whose meanings
+remain unresolved. Vehicle serialization contains velocity, byte controls,
+control state, and a path count. The positive-count reader accepts a float and
+X/Z waypoint pairs and restarts PathGuide_t, but only a stationary instance has
+been exercised in initial entity updates. Original FollowTarget carries an
+identity and one float, unlike the later coordinate-list packet. Recover its
+activation and the live path-update mechanism before copying later serializers.
+See the original movement findings in [protocol.md](protocol.md).
+
+GetPatrolLists in kkr.dll at 0x10132cb0 is an accessor, with an observed export
+reference rather than a route-consuming caller. The examined constructor
+zeroes its pointer. No original patrol routes were recovered. Resource 1000021
+is walls, not patrols; static RDB dynels also do not establish NPC routes.
+
+CharDCMove actions 1 and 2 now have a native NPC motion experiment: a Leet
+changed position and heading in both original clients. The shared packet test
+checks entity identity and matching motion across two connections. This does
+not establish historical AI, speed, or pathfinding. Outdoor terrain grids now
+decode completely with corner and shared-edge checks; see [game-data.md](game-data.md).
+Roaming uses approximate interpolation and preserves the spawn's authored
+ground offset. Exact terrain collision, steep-slope rules, building/wall
+avoidance, indoor floors and historical flying behavior remain unresolved.
+See [protocol.md](protocol.md), tools/npc-roaming-runtime-evidence.json and
+tools/npc-terrain-runtime-evidence.json.
+
+## Logout cancellation
+
+The client progress bar remained after standing cancelled a delayed disconnect.
+An action-108 echo and an empty StopLogoutIIR_t message did not clear it.
+Preserve these failures rather than repeating them as an assumed fix.
+
+The string at kkr.dll 0x10185490 names StopLogoutIIR_t; its XOR key is
+0x56353038. Recover its reader and activation, including target/payload and
+conditions. The camp/quit UI in ddr.dll is another lead. A convincing check
+must observe the bar disappearing and the connection remaining alive beyond
+the old deadline, then verify that a subsequent normal quit still completes.
+
+## Playfield origins, materials, and arrivals
+
+Borealis has established world origin (37107,38360); other playfield origins
+have not been established by this investigation. Find their source rather
+than treating a zero used in an experiment as a recovered historical value.
+
+The nightclub arrival intersected geometry, while Grid materials showed error
+textures. These are separate questions: arrival coordinates/ground clearance
+versus asset/material selection. Extracted terrain heights and district centers
+do not guarantee valid standing space. Geometry keys use
+`(playfieldID << 16) | tileIndex`; retain that distinction from a public zone ID.
+
+## Other projects as leads
+
+The following describe the sources examined during the investigation. Recheck
+public project status if a new decision depends on it. Later-client behavior
+and layouts must be verified against the original binaries before reuse.
+
+- [CellAO-NightPredator](https://github.com/CellAO/CellAO-NightPredator): local
+ checkout `tools/cellao-reference`, examined commit
+ ca77f375a7dabe3be769da94e6c2a3d093344c2c. NPCs use its own mobspawns database,
+ stats, positions, orientations, waypoints, and dialogue-script names. The
+ bundled spawn SQL contained schema rather than historical placement rows;
+ templates were incomplete and mixed classic/expansion creatures. Useful
+ paths under CellAO/Server/ZoneEngine are Core/Playfields/Playfield.cs,
+ ChatCommands/Npc.cs, Core/Controllers/NPCController.cs, and
+ Core/MessageHandlers/FollowTargetMessageHandler.cs.
+- [AODB district decoder](https://gitlab.com/never-knows-best/aodb/-/blob/a772622bf39f7ac07a1761b90765214304d15107/AODB.Common/RDBObjects/PlayfieldDistrictInfo_1000014.cs)
+ and [AORebirth exporter](https://github.com/subarumike/AORebirth/blob/master/Tools/RDBDataExtractor/DistrictExporter.cs):
+ leads for district/spawn decoding. Original version-5 records were validated
+ separately to exact EOF. Later optional fields are not evidence for 11.0.
+- [Project Rubi-Ka FAQ](https://project-rk.com/pages/about/) and
+ [changelog](https://project-rk.com/pages/changelog/): examined descriptions
+ targeted 18.4 and a non-public emulator, with traffic-based reverse engineering
+ and encounter, patrol, respawn, and pathfinding work. Useful behavior clues,
+ not public original-release server sources.
+- [AOCapture](https://github.com/philippelatulippe/AOCapture): capture parsing
+ and proposed spawn/movement inference. The examined extraction/inference
+ work contained TODOs; it did not establish an available spawn archive.
+
+## Limits on historical reconstruction
+
+The disc and client readers do not establish original account validation,
+server persistence, combat rules, NPC stats/loot, encounter scripts, dialogue,
+interest management, or zone-server topology. Explicit experiments may help
+recover the client contract, but invented defaults should remain labeled as
+such rather than becoming historical claims.
+
+For a browser remake, the original meshes/materials, terrain, animations, UI,
+audio, and screenshots are fidelity references. A browser transport or local
+implementation choice is separate from what the 2001 client expected. Document
+newly recovered behavior here, and let the implementation explain its own code.
+
+See [browser-porting.md](browser-porting.md) for researched porting approaches,
+primary-source examples, and the proposed original-binary compatibility check.
+No browser runtime has yet been verified against the AO release client.
diff --git a/docs/protocol.md b/docs/protocol.md
@@ -0,0 +1,508 @@
+# Original 11.0 protocol investigation
+
+This records recovered layouts and original-client experiments. Read
+[client-behavior.md](client-behavior.md) for behavior and historical-server
+inferences, and [reverse-engineering.md](reverse-engineering.md) for evidence.
+Paths beginning with tools are relative to the workspace root. Examples below
+are tested inputs, not a specification of every packet the 2001 server sent.
+Original bytes and runtime captures take precedence over an inferred recovered
+type or a later emulator's serialization.
+
+Runtime observations refer to the extracted release client, not the modern
+installation. Ghidra pseudocode is static evidence and can contain recovered
+types or boundaries that need checking against execution.
+
+## Launcher and login
+
+`DimensionServer.url` contains a host, port, and path without an HTTP scheme.
+The launcher appends `/dimensions.txt`. Dimension records use STARTINFO and
+ENDINFO with connect, description, version, ports, and url fields.
+
+- Parser: anarchy.exe FUN_004170d6,
+ `ev_33e8bc62c8229c8caddbfbddc16629ad91ccdc959de2f38ef58b40207e2acf24`.
+- Downloader: FUN_00414058,
+ `ev_df27a34ca56c28d2657a7941727509edc3296672494c7e03859731e06c65fcf7`.
+
+Packets begin with four big-endian uint16 fields (message ID, type, fragment
+count, byte length), then big-endian uint32 sender and receiver. Transmitted
+length rounds up to a multiple of four; the length field excludes padding.
+System packets have type 1 and an opcode at offset 16.
+
+- Header conversion: FUN_00415dbb,
+ `ev_db7aea0f1e90bf578d43cf58a7a3f4ce6517ab55111cfe82d8ee665e393c63a2`.
+- Login request 0x22 is 84 bytes. Response 0x24 carries a 33-byte salt including
+ its terminating zero. Request 0x25 carries encrypted credential text.
+- Response 0x0e carries the character list. The login experiments used
+ synthetic credentials/characters; historical authentication and persistence
+ were not recovered.
+- Character-list parser: FUN_00405c5e,
+ `ev_5626f7424d9122b74d91f98fd9fea9549e678297e9eac589ef1dc799176b3a62`.
+- Character-info parser: FUN_0040a8f1,
+ `ev_10cc3042eab7ae8877f87b50afdf223fce8b4fa6310f823b6d99a42c26492bcd`.
+
+Selection request 0x16 carries a character ID. Response 0x17 carries uint32
+character ID, uint32 IPv4 address, uint16 port, and two uint32 cookies.
+A response with address bytes 7f000001 and port 7501 successfully directed
+the original client to 127.0.0.1.
+
+## Original world connection
+
+Clientr.exe takes 3 or 7 positional command-line arguments, not the later
+client's named switches: username, password, character ID, and optionally
+numeric IPv4 address, port, cookie 1, cookie 2.
+
+- Startup: FUN_00402bb0,
+ `ev_34306b5e968156945f88211f169a8c7097e6c39f0faedc8e04d9707bb2cfd4f9`.
+- Redirect: ffr.dll Client_t::DoClientRedirect (0x10002bb0),
+ `ev_1562287c5432b2fd3ca0a5769670a8a685c403377b291a5f2a14f0043f451a59`.
+- Cookie: ffr.dll Client_t::SendClientCookie (0x10002610),
+ `ev_af1b293b8c1fcf29f98b806f3ef7289b180d6fa5e96974cb670ffb3d3d532ab4`.
+
+Observed first world packet, with character ID 1 and zero cookies:
+
+```
+0004 0001 0001 0020 00000001 00000002 0000001b
+00000001 00000000 00000000
+```
+
+Periodic client ping packets use type 11 and length 40. The world connection
+uses the same four-byte-aligned framing. The original transport passes received
+TCP bytes directly to the packet parser; it has no initial stream compression
+negotiation in this path.
+
+Connecting already signals PACKET_TYPE_CHARACTER_LOGGED_IN internally.
+System response 0x10 instead signals PACKET_TYPE_CHARACTER_NOT_OK and must not
+be used as a successful cookie acknowledgement. The event registration writes
+the logged-in event to 0x10018794 and the error event to 0x10018798.
+
+- Logged-in event registration: ffr.dll instruction 0x100013b0 and following
+ bytes, `ev_6f60fc0a821eb8302da2002966ceacf8955fe6feb343e79f2cc2f5de6ec0ecea`.
+- Error event string reference: 0x10001380,
+ `ev_22aa9961d21c96120003592054bed5c4e6479d9e653dce4bad15a1437325b678`.
+
+An experimental 0x10 reply caused the client to return to the launcher and
+crash during GUI texture cleanup. The reply was removed. This did not establish
+a failure of the world renderer or playfield data; that experiment preceded
+the successful world-initialization sequence described below.
+
+- er.dll Connection_t::Receive (0x10001c50),
+ `ev_832d2deedadfad26a11880fc600879dab037174c3512f62444642d4688572703`.
+- er.dll TcpHandler_t::handle_input (0x1000b790),
+ `ev_727bf61aa2be17cf6d2435497d05944aea7e632c22eb65b2b254437901d476f8`.
+
+N3 packets use type 10. Offset 16 is the uncompressed body length, not the N3
+opcode. Zero means the body at offset 20 is uncompressed. Nonzero means that
+individual body is zlib-compressed. This differs from later emulator streams.
+
+- nr.dll N3Message_t constructor (0x10003bb0),
+ `ev_b792649334a7590b245aade74c79687a7e6649bf1aac5216a46654106ee3039c`.
+- nr.dll N3Message_t::CreateDataBlock (0x10004000),
+ `ev_262149366436e252813e9ac659490b6958ef5333da927a23f45895ad57ec94d9`.
+
+## World initialization
+
+The uncompressed N3 body starts with four big-endian uint32 fields: message
+key, identity type, identity instance, and pass-on flag. The original flag is
+four bytes, so this prefix occupies 16 bytes. Message keys XOR the ASCII name
+bytes into successive byte lanes, wrapping every four bytes.
+
+- llr.dll n3InfoItemRemote_t::MapToKey (0x10020690), Construct (0x10020820),
+ and Write (0x10020a60); retained in tools/engine-evidence.json.
+
+The successful world-loading experiment sent these messages after the cookie:
+
+| Message | Key | Identity | Layout |
+| --- | --- | --- | --- |
+| PlayfieldAnarchyFIIR_t | 0x5f4b1a39 | 40016:950 | version 4 |
+| SimpleCharFullUpdateIIR_t | 0x271b3a6b | 50000:1 | byte version, compact player state |
+| FullCharacterIIR_t | 0x29304349 | 50000:1 | version 16 |
+
+Playfield version 4 contains three spawn floats, byte 'a', a six-uint32 proxy,
+an optional database-object identity (zero here), world X/Z origins, uint32
+name length, and the name bytes. The tested proxy was
+51100:950, resource 950, zero, 40016:950. The original proxy has no additional
+eight-byte trailer. Playfield 950 assets exist on the release disc.
+
+- llr.dll n3PlayfieldFullUpdate_t::ReadSubClass (0x1003b3e0) and proxy reader
+ FUN_10042810, tools/engine-evidence.json.
+- kkr.dll playfield reader FUN_10133d80 and activation FUN_10133ba0,
+ `ev_543348b5eee9f00a2282718dec7eb1671e38df0f9c96fc8c1b4102659b79aa54`.
+
+Flags 0x240 include playfield ID and four-float orientation. The tested
+player flags 0x2d0 additionally include the head and named textures described
+later; the tested NPC flags were 0x241.
+Absolute X/Z are uint16 in eighths; Y is int16 in sixteenths. The appearance
+uint16 contains race at bits 0-1, fatness at 2-3, breed at 4-6, sex at 7-8,
+side at 9-10, and head selection at 11-15. Male Solitus uses breed 1 and sex 2.
+Packing race 1, fatness 1, breed 1, sex 2, side 1 gives 0x315.
+The character name has a byte length including its terminating zero.
+
+The length-prefixed vehicle state contains three velocity floats, ten byte
+movement controls, uint32 control state, and int16 path count. Its stationary
+defaults are 28 bytes: zero velocity, controls 2/1/0/1/0/1/0/1/0/1, state 2,
+and no path. This is shorter than the later emulator's player state.
+
+- Player reader FUN_1006d9d0 and activation FUN_1006d260,
+ `ev_543348b5eee9f00a2282718dec7eb1671e38df0f9c96fc8c1b4102659b79aa54`.
+- Breed/sex resource selection FUN_1005a380,
+ `ev_c4249b242aaefcbee50804660b75dc82306d24b6af6bea33626cccf16b8a5a5d`.
+- Movement byte reader FUN_1003ce20,
+ `ev_152866063d2d67796ffe8005925eb093c1c11807b603ea6bff0bb3e49314464e`.
+- Movement defaults FUN_1003cd50,
+ `ev_55efad4776655710a3f94c5eac8061f2bce6aadaab068d6f63e0454c22481cdf`.
+- Vehicle path reader FUN_1003db30,
+ `ev_f4f7f3e27c24d461282a66474c91acff0d8ac3bc05b1a41343871890ac440005`.
+
+FullCharacter accepts version 16 (and legacy 15). List counts generally encode
+(count + 1) * 1009; the stat map uses a plain count. Six lists precede four stat
+lists. A small level-1 stat list and empty inventories were sufficient for
+the loading experiment. Activation sends an unblock request, then
+CharInPlayIIR_t (0x570c2039). An acknowledgement with the player identity and
+no subclass body was accepted.
+
+- Full character reader FUN_1006ad80,
+ `ev_543348b5eee9f00a2282718dec7eb1671e38df0f9c96fc8c1b4102659b79aa54`.
+- Full character activation FUN_1006a7a0,
+ `ev_ac1ad9ec5e7bc86e86878c53aa27d8b03176cdce3275dec3ba4b607e98dca46f`.
+- CharInPlay reader and activation FUN_100694d0/FUN_100694f0,
+ `ev_6b608d27c4b2e84d429d96ccfe5b52bc884b9c4bd58d2f42f73ed62a2ee30ee7`.
+
+## Runtime verification and scope
+
+The original client accepted this sequence, left its loading screen, rendered
+Omni Training, and displayed the welcome and entering-area messages. The player
+body renders after correcting the packed appearance fields. Movement commands
+use compressed N3 key 0x54111123, with uint32 action followed by three position
+floats after the 16-byte IIR prefix. The user confirmed held-W walking, and the
+server recorded movement from (52.625, 14.722409, 56.875) to
+(55.962704, 14.0, 63.920597), including turn and stop commands.
+The captured packet bytes and decoded coordinates are in
+tools/movement-evidence.json. This establishes windowed original-client
+world rendering and walking against localhost for that initialization input.
+
+Two original clients rendered each other after receiving separate entity
+identities and peer updates. The transport receiver is the recipient's character
+ID, distinct from the N3 entity identity. Remote player spawning in this
+experiment needed SCFU followed by CharInPlay; SCFU activation hides a remote
+player whose InPlay stat (194) is zero.
+
+CharDCMoveIIR_t hashes to 0x54111123. The original subclass is uint32 action,
+three position floats, quaternion XYZW, and two additional floats.
+Decompressing and relaying the subclass with pass-on flag zero reproduced
+movement in the second client. The meanings of the last two floats remain
+unresolved. The original reader and activation are FUN_100691a0/FUN_10069000:
+`ev_4793fbc0c17a0796d5c374ba0e3e5887f0c8214664a21ddf569eff68c3bf28ae`.
+
+This message also moves NPC identities. A native experiment sent action 1
+with changing XYZ and heading, then action 2 at the destination, using zero
+for both trailing floats. A Leet moved and changed heading in both original
+clients without being despawned. These controls do not establish historical
+NPC routes or server pathfinding. See tools/npc-roaming-runtime-evidence.json.
+
+Ordinary CharDCMove activation calls SetRelPosRot before applying the movement
+control. Repeated absolute updates therefore reset the remote vehicle rather
+than selecting an interpolation mode. Action 1 starts forward motion and action
+2 stops it; the client continues simulating movement between these messages.
+The trailing floats are not established as tween flags. The original player
+capture sends zeros there during ordinary movement.
+
+The original movement state machine, kkr.dll FUN_10039950, maps commands 22 to
+walking (mode 2), 23 to running (mode 3), and 24 to crawling (mode 4). These differ
+from the later CellAO movement numbers. FUN_1003c3d0 chooses a walking base speed
+of 1.5 m/s; running forward uses 4 + RunSpeed * 0.01 through FUN_1003c0d0.
+Mass/carrying adjustments and vehicle acceleration/braking also affect motion.
+The stationary SCFU vehicle's first control byte 2 selects walking.
+Evidence: ev_1639240ca823282546431b081293d1310959e2d9821a9db2be99dbdc93128dd1,
+ev_5d70044da9d5fa578f99b894bcc3362c1d435bf9df8ff53a3db93a5253c34ba4,
+and ev_e1694aa91ae0324cea5ddffe685eb4441c15accdc442f28632add44d5e44dd48
+in tools/npc-motion-native-evidence.json.
+
+CharDCMoveUpdateIIR_t reads only a uint32 control, with no position or rotation
+(FUN_10069350), and its activation applies that control to the vehicle
+(FUN_100692f0). Original FollowTargetIIR_c reads an identity and one float
+(FUN_10069fe0); it is not the later coordinate-list destination packet. Its
+activation entry at 0x1006a090 was not defined by this Ghidra analysis, so that
+behavior remains unresolved. Reader evidence:
+ev_61fec3ba0659aae2b952c8f34359f9d78b938a7841f2dcdace3ff72760d25fb0.
+
+The original SCFU vehicle path reader FUN_1003db30 accepts an int16 point count,
+then, for a positive count, a float and X/Z float pairs. It builds Y=0 waypoints
+and restarts PathGuide_t with the vehicle speed and the extra float. This is
+static layout evidence; native waypoint motion and the extra float's meaning
+have not been verified. SCFU cannot update an existing entity, so this path
+layout alone does not establish a live route-update message.
+
+## Monster rendering
+
+A stationary Leet, identity 50000:1000000, renders and can be selected in the
+original client. Its SCFU uses flags 0x241, appearance 0x00e5, MonsterData 17655,
+and MonsterScale 100. Flag bit 0 skips the player-only fields after the name;
+the original reader does not replace them with the later NPC family/height data.
+The remaining level, health, model, vehicle, and empty-list fields follow the
+verified original layout. A FullCharacter message is not sent for the NPC.
+
+SCFU activation in kkr.dll FUN_1006d260 returns early when the entity identity
+already exists. Sending NPC quit packets followed immediately by SCFU with
+reused identities left replacements invisible in a native experiment. Using
+fresh identities rendered replacements during play; edits to a guard's name
+and position were visible without reconnecting. The precise timing of entity
+removal remains unresolved. See tools/npc-yaml-runtime-evidence.json.
+
+The level is uint8 by default and uint16 with flag 0x1000. Flag bit 0 is
+independent of the head (0x80) and named-texture (0x10) flags: NPCs can carry
+both while still omitting the player-only fields. These branches are explicit
+in kkr.dll FUN_1006d9d0, retained as
+`ev_feda6a56e933fffc88305214dd3607aa3558de13ba0ee41189db4e689c4185fe`
+in tools/npc-native-evidence.json.
+
+Flag bit 0 also sets the NPC state in FUN_1006d750; it is not merely a field
+omission switch. Using a human breed with this bit and MonsterData 0 produced
+the magenta default mesh in a native test. Human NPCs need an appearance
+resource supplying mesh stat 12, unlike the working player packet with
+MonsterData 0. Original Solitus male resource 26092 supplies mesh 5907;
+with the head and named-texture fields it rendered a selectable human
+placeholder at the OTGD fixed point in windowed Omni Training. No CharInPlay
+message was needed for this NPC. Runtime packets and observations are retained
+in tools/full-population-runtime-evidence.json.
+
+The asset identifier was first suggested by the later CellAO database and was
+corroborated by original-client runtime rendering. See tools/npc.png.
+
+Packed appearance is not ignored for monsters. Value 0x00e5 decodes to race 1,
+fatness 1, breed 6, sex 1, side 0, and face 0. Ribosome application
+FUN_1006d750 applies MonsterData and passes breed/sex to FUN_10058ec0. That
+function recognizes breeds 6 and 7 and calls n3VisualDynel_t::SetCatMesh using
+mesh stat 12. No Leet-specific branch was found in that path. This supports
+trying other nonhuman MonsterData meshes with breed 6, but does not establish
+historical appearance fields for every species or human NPCs. Evidence in
+tools/npc-native-evidence.json:
+`ev_9bcc29b64b27f66d16dce069c74cea46261878aa5e114f9df4a3437903c54255`
+and `ev_9a70c1dc1af2fbe9c601cbe40980574fabe30c4bc655dced9dc258072cc2ecb0`.
+
+## NPC population data
+
+Original SCFU reader 0x1006d9d0 receives playfield, compact XYZ, appearance,
+and MonsterData; activation 0x1006d260 creates the character at that position
+and applies MonsterData stat 359. Live NPC instances are server-controlled.
+This does not establish that the client lacks spawn-design metadata. Evidence:
+ev_543348b5eee9f00a2282718dec7eb1671e38df0f9c96fc8c1b4102659b79aa54
+in tools/world-evidence.json.
+
+The disc also contains original population placement directives in resource
+1000014. tools/extract_npc_spawns.py implements the version-5 layout described
+by [AODB's PlayfieldDistrictInfo decoder](https://gitlab.com/never-knows-best/aodb/-/blob/a772622bf39f7ac07a1761b90765214304d15107/AODB.Common/RDBObjects/PlayfieldDistrictInfo_1000014.cs),
+used by [AORebirth's district exporter](https://github.com/subarumike/AORebirth/blob/master/Tools/RDBDataExtractor/DistrictExporter.cs).
+The downloaded reference source SHA256 is
+2e1ad3e2d43f73707efaad542f395b7ad4c0445c946ed7be35b14e837e73e65c.
+All 348 original district resources are version 5 and decode to exact EOF.
+Every map-cell district index is valid. A separately written parser agrees
+with the retained extractor's data for every map.
+
+tools/original-npc-spawns.json contains 1,977 districts, 6,178 population
+entries (template code and count), 33,151 ordinary spawn points (XYZ and
+radius), and 1,560 fixed spawns. Districts carry NPC level ranges, respawn
+chance/time and fight mode. Fixed spawns carry their own template code, XYZ,
+radius, heading, levels and respawn fields. All original fixed-spawn flags
+are zero. The nine district stats and 4,812 six-byte extra entries remain
+opaque. Respawn time units and selection rules are not established. Codes
+are four-character text packed into uint32 values, obtained by reversing their
+on-disk bytes. The `template_hash` JSON field follows the external decoder's
+terminology; no hashing algorithm was recovered for these readable codes.
+
+Omni Training 950 has 97 ordinary spawn points. Its Level 1 Area requests
+LE01 x6, RT01 x6 and SN01 x1. Two fixed level-200 entries are OTBG at
+(57.673809, 13.999916, 55.950287) and OTGD at
+(49.648979, 14.099686, 61.600853). These are original directives; the mapping
+from codes to complete NPC templates is unresolved. A bounded search for
+training codes in resources 1000010, 1000015, 1000020, 1000026, 1000029,
+1000032 and 1040023 found no mapping.
+
+tools/extract_monsters.py extracts all 179 original appearance definitions
+from type 1040023 into tools/original-monsters.json. Their initial stat lists
+use version 15, section 23 and count encoding (n+1)*1009. Stat 12 supplies
+the mesh ID. The final section (6,28,1009) contains an explicit-length name.
+The filename registry pads names including their terminator to four bytes.
+All 179 meshes have original filename registrations. Confirmed appearances
+include Leet 17655, Rollerrat 17687, Snake 30252 and Minibull 30360. Resource
+30365 is named cute birdy and is a Reet candidate, not a recovered template link.
+Appearance definitions do not establish population-code mappings or combat
+templates. Leet rendering was directly verified; other identifications here
+come from original appearance/filename data, not runtime tests of every model.
+
+Original kkr.dll getters return area data at +0xd0, district data at +0xd4,
+and patrol data at +0xd8. GetPatrolLists (0x10132cb0) only returns that pointer;
+the observed reference is an export-table pointer, not a caller using routes.
+CreateRDBDynels creates objects from RDBDynelLoader resource 1000026. Evidence:
+ev_e39c2546bf3f184a1742289525b576c89b33974e6b71d7205614fb8e4199da1a,
+ev_36102166011ed364d9868cb1f8feb99d17f5134f9cdb30422b19b5f366c2553c,
+and ev_dad412a08a7c107c3257916888918c44a54dc9918d47be1d94a2ff46a381aa93
+in tools/npc-native-evidence.json. Patrol routes remain unresolved. Resource
+1000021 is PlayfieldWalls, not patrol data; its decoder matches all 179
+original records to EOF. Resource 1000030 is PlayfieldDoors.
+
+Region resource 1000029:595 describes Medusa Territory and the Foul Forest,
+including Medusas, gators and swampghoul colonies. Resource 1000029:610
+describes an area suited to Pendpods. tools/npc-placement-evidence.json
+retains the original strings, resource offsets and payload digests.
+
+## Other server references
+
+See [research leads](open-questions.md#other-projects-as-leads) for the examined
+CellAO source revision, NPC/waypoint storage, and other emulator/capture
+projects. Their serializers and behavior target later releases; original
+reader/activation code and runtime captures determine the 11.0 contract.
+
+## Zoning and despawn
+
+The original n3TeleportIIR_t key is 0x43197d22. Its subclass is:
+
+```text
+XYZ float32
+zone-change flag uint32
+identity (two uint32)
+identity (two uint32)
+stream length uint32, followed by that many bytes (reader limit 1000)
+```
+
+A successful zone-change experiment sent flag 1, identity 0:0, identity
+40016:destination, and an empty stream. A nonzero flag starts playfield teardown;
+flag zero moves the dynel within the existing playfield. This differs from the
+later CellAO quaternion/proxy serialization. Original reader and activation:
+llr.dll n3TeleportIIR_t::ReadSubClass 0x1003b8c0 and Activate 0x1003b7d0,
+`ev_0269c4b3391e212de971391a8e0474631a7a1cd2dcf6a81c9e30e1ce53d2d96e`.
+
+System opcode 0x3c followed, with IPv4 bytes and a uint16 port.
+The original Client_t::Receive opens that connection and sends the existing
+character cookie again, without a new login or character ID. Evidence:
+`ev_60f1b4c3c51ee49118e4251bacb2142d244561b4c3102eae2497640a1a9394ee`.
+Normal playfield/SCFU/FullCharacter initialization loads the destination.
+
+Other players receive key 0x36510078, originally n3ToClientQuitIIR_t, with no
+subclass body. Its activation removes the addressed dynel unless it is the local
+player. Original llr.dll FUN_1003ba50:
+`ev_1065386bed85408d9b98d66a503381d4330759a003dc1929cbda3c9da7d48779`.
+Runtime verifies disappearance on departure and reappearance on return.
+
+Omni Training (950) and Borealis (800) both load from the release assets.
+Borealis loaded with world origin (37107, 38360) and an arrival back from
+the whom-pah entrance. Resource-derived map names and arrival candidates are
+documented in [game-data.md](game-data.md#zone-catalog-and-arrival-derivation).
+These experiments do not establish every map's origin or safe arrival.
+
+## Game time and player heads
+
+The original GameTimeIIR_t key is 0x5f52412e. Its subclass has only three fields:
+float32 game seconds within the day, uint32 day period, and uint32 day number.
+The original reader/writer are kkr.dll FUN_10038860/FUN_100388b0, evidence
+`ev_94a3373a480f455e712df52e00896bba99026bed5655bd80dff9f51dd680259e`.
+The activation at 0x100388f0 is absent from Ghidra's procedure inventory, so its
+bytes were inspected separately: it passes the three fields to
+GameTime_t::GetInstance then GameTime_t::Update (0x1000f3a0). Evidence for those
+activation bytes: `ev_ec6027bb103fe75e7a13526296a57c52743443341ae1faeed07724b37289ad1f`.
+Update computes hour/minute/second from the first field and stores the day
+number; the supplied day-period field is not used by this implementation.
+The later emulator's fourth float is absent from the release client layout.
+
+GameTime_t's constructor sets 27 hours, 3600 seconds per hour, 97200 seconds
+per day, and speed 15. GetDayIntensity (0x1000ed40) returns full daylight
+between hours 10 and 18; dawn spans 5-10, dusk 18-23. Constructor evidence:
+`ev_51afd2bf719422418df910d3470808768ec22fd91dc3aec583c4f7c962a1fa42`;
+day intensity evidence is in the reader/writer batch above. Sending midnight
+visibly darkened the original scene; sending 13:30 restored daylight without
+client reconnection. This verifies that lighting responds to live GameTime
+messages, independent of any local control-panel implementation.
+
+SCFU flag 0x80 includes a uint32 HeadMesh after the vehicle blob and before
+RunSpeed. Without it, the field defaults to zero. SCFU activation
+FUN_1006d260 unconditionally writes this field to stat 64 and refreshes the
+character's appearance, replacing the default head with zero. Evidence:
+`ev_c0ded740ce0d8fbf61f6fb11c4f0fd7203fa4ac45d782b2109bbaed489f46543`.
+Player SCFU uses HeadMesh 40682, the original asset
+head_solitusmale01.abiff. The original resource registry stores its identifier
+immediately before the filename at offset 0x00e53e80. Default selection in
+FUN_1005a380 corroborates that filename for breed 1 / sex 2:
+`ev_c4249b242aaefcbee50804660b75dc82306d24b6af6bea33626cccf16b8a5a5d`.
+The tested head field restored both local and remote player heads. See
+tools/daylight-heads.png and tools/appearance-time-evidence.json.
+
+## Named material textures
+
+The original SCFU flag 0x10 carries a named TextureDataList after RunSpeed.
+Its count uses (N+1)*1009. Each entry is a NUL-terminated material name followed
+by three uint32 values. The decoder is kkr.dll FUN_10137500/FUN_101374c0:
+`ev_a50901b23580019f7b3db933d0945abee3b1b64232172cd198c203dbc37a3ae6`,
+`ev_19330c26502c80e6b9dbe66d31be549dedd216085470afc0d3a4996427c39d48`.
+SCFU's ribosome applies that list through n3VisualDynel_t::SetTextureDataList;
+the original llr.dll method copies 44-byte entries (32-byte name and three
+integers), `ev_7a25b45eaf31795bd912fe126f63c4caf35991cf9c9ab984c8cb368a43cfd9bf`.
+The later numeric texture placement format does not apply to this client.
+
+The original Solitus body resource 1010002:5907 contains material names arms,
+feet, hands, legs, body and their default texture filenames. Its hands material
+uses hands_solitusmale_default.png, ID 8712. Resource 1010004:8712 at database
+offset 129747185 is a 128x64 solid bright-green PNG (the database replaces the
+first four PNG signature bytes with version 2). The decoded image is retained
+as tools/default-hands.png. This confirms the default material itself is green.
+The filename registry identifies hands_solitusmale_caucation_naked.png as ID
+8773 at filename offset 0x00ee5db8; its original JPEG resource 1010011:8773 at
+offset 61133259 is retained as tools/skin-hands.jpg.
+
+The successful SCFU used flags 0x2d0. Five named entries supplied arms 8714, feet 8710,
+legs 8713, body 8709 and replace hands with 8773. Each entry sends the resource
+ID followed by two zero state values. Supplying only hands removes the other
+materials, so the complete five-material list is necessary. Runtime verifies
+skin on both local and remote hands while retaining the other body textures.
+See tools/hands-fixed.png and tools/hands-evidence.json.
+
+## Complete release map catalog
+
+tools/extract_playfields.py reads the original index's linked blocks. Header
+offset 72 points to the first block; each block has a next pointer at 0, uint16
+entry count at 8, and 12-byte entries from offset 18. Entries contain a little-
+endian database offset, then big-endian resource type and ID. Database records
+have a 34-byte header; type/ID at offset 10 and size-minus-12 at offset 18.
+There are 348 version-8 playfield records of type 1000001. The name occupies
+bytes 8-39. Adding the launcher's 25 name-only entries yields 373 choices.
+Four maps (100, 102, 103, 1410) were identified as internal dependencies;
+the other 344 resource-backed maps supplied exploration candidates.
+
+180 usable outdoor maps have original CHGA ground records (type 1000009).
+Their header gives tile width/height, spacing, and height scale. Compressed
+height blocks use a left+above-diagonal byte predictor modulo 256. Decoded
+corners match each block's original small-height record; center samples provide
+the outdoor spawn heights. The 164 indoor maps use the first district XYZ from
+type 1000014, starting at offset 7. The proxy retains each public playfield ID;
+original geometry keys are (playfieldID<<16)|tileIndex.
+
+tools/original-playfields.json retains the extracted catalog. Old Athen
+rendered and the original Grid/nightclub interiors loaded in experiments, but
+Grid materials showed error textures and the nightclub arrival intersected
+geometry. Resource-backed entries are exploration candidates, not a claim
+that every arrival or scene has been verified. World origins outside the
+established Borealis value remain unresolved.
+
+## Sitting and logout
+
+Original runtime captures in tools/quit-runtime.log and tools/quit-verified.log
+identify character-action messages as N3 key 0x5e477770. Their body is 36 bytes:
+the 16-byte N3 prefix, a uint32 action, and 16 trailing bytes. The observed
+sit, stand, cancel, and logout actions are 86, 87, 108, and 120 respectively.
+These requests may be individually zlib-compressed like movement messages.
+
+Sitting required an acknowledgement addressed to the character in the
+experiment; relaying the action reproduced posture for peers. Logout starts
+the original client's 30-second progress bar. Closing the connection after
+that interval caused Quit to Windows to complete. X sitting and standing were
+also runtime verified. The historical server's complete logout scheduling and
+cancellation contract have not been recovered.
+
+The client progress bar remains visible after standing cancels logout, although
+the session stays connected beyond its original deadline. The original kkr.dll
+string at 0x10185490 names StopLogoutIIR_t, whose string-XOR key is 0x56353038.
+An empty message with that key and echoing character action 108 both failed to
+clear the bar. Its required payload or activation conditions remain unknown.
+
+Later [CellAO sources](https://github.com/CellAO/CellAO-NightPredator) supplied
+candidate names and a training-area spawn position. Original-client static and
+runtime evidence determines the recovered layouts; later serialization cannot
+be assumed valid for 11.0.
diff --git a/docs/reverse-engineering.md b/docs/reverse-engineering.md
@@ -0,0 +1,239 @@
+# Resuming reverse engineering and reading evidence
+
+Use the original shipped client and its saved evidence for protocol claims.
+Ordinary analysis of the Go/Python source does not require native REA analysis.
+Do not run a new decompiler session merely to read an already retained result.
+The tool paths and recovery experiments below were recorded on 2026-10-12;
+they are historical investigation context, not requirements for future tools.
+
+## Original binary identities
+
+These SHA256 values were recomputed from client-original/Gamefiles during the
+documentation handoff. Addresses in the protocol notes refer to these 32-bit
+PE files, not the modern installation. Most DLL addresses use image base
+0x10000000; executable addresses commonly use 0x00400000. Keep virtual addresses,
+file offsets, export names, and actual procedure entries distinct.
+
+| Binary | SHA256 |
+| --- | --- |
+| anarchy.exe | d739724f4c852dcbe1579b693f1b42c193a04e69df737b8f3e121a1a4caaa529 |
+| Clientr.exe | e529a9a327a0d3a0d878c1125f01e2d005458c3ab6ab3c606c9ff8210bc83228 |
+| ffr.dll | db3d15e99bab9289595ecfeca090d5f3b60942f5242db212f8b022ef9f187275 |
+| er.dll | f36d7820adb97439421f56aad7502ef4da51ac58541afc934eefaf2b5ed197e8 |
+| nr.dll | 40c0b1490a395c75267df571daba5763519d4d15bb948fb0158f61d5fa8f8abd |
+| llr.dll | 863205715f80f05470cfa3201d586b7db5fb6843cace6b638c8ea08a29c09156 |
+| kkr.dll | 01ad7624eebc42c23b5a2ac9d90554e484d5a07c374cb6516df114ad52e80d5a |
+| ddr.dll | 6145c5ee5b26f427dee8cbad6f9de173427b0087ad63d859ca63244d66f7e95c |
+| qqr.dll | f833d5e6d79f9391196a17aa08449be1b8f1f7e65b4e44205117058fee8f4b74 |
+| bbr.dll | 50994e37be641173d182faa493f8e989c72d66fbd785e007ea2f720b7682428f |
+
+The qqr.dll value is retained in its analysis snapshot rather than recomputed
+in this handoff. Verify a hash before interpreting an address in a changed file.
+
+## Retained evidence and snapshots
+
+Portable `*-evidence.json` REA bundles normally contain top-level records plus
+artifact/provider/environment metadata. Each record has an evidence ID,
+operation, parameters, subject, normalized result, confidence/authority, and
+limitations. Static pseudocode is an interpretation of shipped bytes; it is not
+a runtime observation and may have uncertain types or function boundaries.
+
+`*-analysis.json` files are importable REA analysis snapshots. Their top-level
+keys are binding, entries, evidence_bundle, target, and workflow_entries.
+Binding includes provider and analysis profile; target includes the binary
+SHA256. Import requires a matching target, provider, and canonical profile.
+These snapshots preserve cached evidence and metadata, not a guarantee that
+every future native query will avoid fresh Ghidra initialization.
+
+| Evidence bundle | Primary target and topic | Snapshot to consult |
+| --- | --- | --- |
+| launcher-evidence.json | anarchy.exe: dimensions, login, character list, framing | launcher-analysis.json |
+| clientr-evidence.json | Clientr.exe: startup arguments | clientr-analysis.json |
+| network-client-evidence.json | ffr.dll: redirect and cookie | network-client-analysis.json |
+| network-client-crash-evidence.json | ffr.dll: logged-in/error event distinction, failed acknowledgement | network-client-analysis.json |
+| transport-evidence.json | er.dll: TCP input and packet transport | transport-analysis.json |
+| message-evidence.json | nr.dll: N3 envelope and compression | message-analysis.json |
+| engine-evidence.json | llr.dll: N3 key hashing and base/playfield serialization | engine-analysis.json |
+| skin-engine-evidence.json | llr.dll: appearance and named texture list | skin-engine-analysis.json |
+| vehicle-evidence.json | qqr.dll: vehicle serialization | vehicle-analysis.json |
+| world-evidence.json | kkr.dll: original world, SCFU, FullCharacter | world-analysis.json |
+| multiplayer-evidence.json | kkr.dll: peer visibility and movement | world-analysis.json |
+| appearance-time-evidence.json | kkr.dll: game clock and head mesh | world-analysis.json |
+| hands-evidence.json | kkr.dll: named textures and original hand resources | world-analysis.json |
+| npc-native-evidence.json | kkr.dll: latest population/patrol/native investigation | world-analysis.json |
+| npc-motion-native-evidence.json | kkr.dll: movement controls, speed, follow/update readers | npc-motion-analysis.json |
+| zoning-evidence.json | llr.dll: original teleport, redirect, despawn | skin-engine-analysis.json |
+| login3d-evidence.json | ddr.dll: 3D login flow | login3d-analysis.json |
+| terrain-native-evidence.json | bbr.dll: archived grid dimensions, delta decompression and interpolation assembly | No snapshot retained |
+
+All table paths are under tools. The kkr.dll bundles are cumulative exports at
+different stages and contain overlapping records. npc-native-evidence.json is
+the kkr.dll export used for this record, with 87 records on 2026-10-12. Do not count
+repeated records in different exports as independent corroboration. Some
+llr.dll zoning records are retained in later snapshots as well; inspect their
+embedded records rather than assuming a file's name covers every operation.
+
+The following files have different schemas:
+
+- `movement-evidence.json` is a manual packet/coordinate capture with records,
+ not a portable REA ledger.
+- `runtime-evidence.json` records runtime observations, historical binary/log
+ hashes, screenshots, validation, and limits.
+- `npc-placement-evidence.json` records source/index hash, resource observations,
+ strings, offsets, payload digests, and limitations.
+- `world-population-evidence.json` records authored district-name corroboration
+ for population families, appearance candidates, and further bounded searches.
+- `population-code-evidence.json` records provisional numbered-family species
+ assignments with original district offsets/groups and appearance candidates.
+- `world-population-runtime-evidence.json` records the earlier population
+ experiment, its runtime observations, and its verification limits.
+- `population-codes-runtime-evidence.json` records the expanded code-mapping
+ experiment and its validation and arrival limits.
+
+Their historical server digests identify the experiment that produced them;
+they are not hashes of the current rebuilt server.
+
+## Read an evidence record without dumping the entire bundle
+
+Large JSON files are often one line. Running rg on a broad term can print an
+entire megabyte line and obscure the useful result. Parse the file and select
+an evidence ID, procedure, or operation. For example, save this as a temporary
+Python script and run it using the venv from the workspace root:
+
+```python
+import json
+import pathlib
+
+bundle = json.loads(pathlib.Path('tools/world-evidence.json').read_text())
+record = next(record for record in bundle['records']
+ if record['evidence_id'] ==
+ 'ev_543348b5eee9f00a2282718dec7eb1671e38df0f9c96fc8c1b4102659b79aa54')
+print(json.dumps(record, indent=2))
+```
+
+Batch decompile records have normalized_result.items, with procedure metadata
+and pseudocode per item. Search results usually have an array of address/value
+matches. Inspect the selected operation's actual schema. Preserve its limitations
+when documenting a conclusion.
+
+## REA tools and recovery on this PC
+
+The installed skill is
+`.agents/skills/reverse-engineer-anything/SKILL.md`.
+Read it and its native/artifact guide before a fresh native investigation.
+If registration is missing or a provider is unavailable, use its connection
+and recovery guide. Installed skills and installed npm packages do not themselves
+prove the MCP tools are connected in a new Codex session.
+
+The investigated environment used REA 6.4.0, Ghidra 12.1.4, and Java 21. Paths
+verified at handoff:
+
+```text
+Node: C:\Program Files\nodejs\node.exe
+Ghidra: C:\tools\rea-tools\ghidra_12.1.4_PUBLIC
+Java: C:\tools\rea-tools\jdk-21.0.12.1+1
+REA entry: node_modules/rea-agents/scripts/rea.mjs
+MCP SDK: same node_modules directory, under @modelcontextprotocol/client/dist
+```
+
+The npm cache path is incidental and may change. Use connected tools first.
+Do not upgrade working tools or edit configuration just to repeat a saved query.
+
+A focused native session typically consists of:
+
+1. open_binary with the original absolute binary path and matching snapshot_path.
+2. search_strings/search_procedures for the specific feature, or xrefs from a
+ retained string/entry address.
+3. Resolve containing procedures before decompiling interior call addresses.
+4. batch_decompile explicit canonical entries; retain each result and uncertainty.
+5. export_evidence_bundle to a workspace path.
+6. close_binary with the matching snapshot_path and overwrite enabled.
+
+Check the actual tool schemas in the future session. Reopening, provider
+switching, missing functions, and unresolved labels should be explicit; never
+silently substitute a modern binary or an unrelated procedure.
+
+### Slow Ghidra startup and the prior SDK workaround
+
+New kkr.dll analysis queries sometimes required six to seven minutes of Ghidra
+startup, exceeding a roughly five-minute MCP call timeout. Importing cached
+snapshot metadata could complete quickly while the first uncached query still
+required that startup. Repeating the same timed-out request did not solve it.
+
+The successful workaround used the official MCP JavaScript SDK to start the
+existing REA entry over stdio. It supplied these environment values:
+
+```text
+GHIDRA_INSTALL_DIR=C:/tools/rea-tools/ghidra_12.1.4_PUBLIC
+JAVA_HOME=C:/tools/rea-tools/jdk-21.0.12.1+1
+REA_GHIDRA_STARTUP_TIMEOUT_MS=1500000
+```
+
+Client setup used Client from `@modelcontextprotocol/client/dist/index.mjs`
+and StdioClientTransport/getDefaultEnvironment from its client/dist/stdio.mjs.
+The transport command was the existing Node executable, with arguments
+`[REA_ENTRY, '--mcp']`. Individual calls used:
+
+```javascript
+await client.callTool(
+ {name: 'open_binary', arguments: {
+ path: 'C:/path/to/ao/client-original/Gamefiles/kkr.dll',
+ snapshot_path: 'C:/path/to/ao/tools/world-analysis.json'
+ }},
+ {timeout: 1800000}
+);
+```
+
+The temporary helper accepted one JSON tool request per stdin line. A persistent
+exec session kept the provider alive between sequential requests. After startup,
+focused queries were fast. Export and close saved the target before stopping
+the helper. Those temporary helper scripts are not retained; recreate this
+small SDK bridge only if the same measured timeout recurs. It is an analysis
+workaround, not part of the AO server or a second REA implementation.
+
+Long-running tool sessions should yield while the agent gives progress updates.
+Do not block communication with an uninterruptible multi-minute sleep, and do
+not issue dependent commands before the prior operation has completed.
+
+## Runtime evidence and Windows computer use
+
+Use the installed computer-use skill and its currently supported APIs for
+Windows input/capture. The previous working native path was node_repl with
+`@oai/sky`. Native control through cua_repl was disabled in that environment.
+Browser UI tooling remains a separate capability.
+
+Initialize sky in a fresh REPL, list current windows, and select exactly one
+returned original-client window by its full process path. Get fresh state,
+inspect the screenshot, perform one state-derived input, then refresh. Do not
+reuse screenshot IDs or window objects across a reboot/reset. Read the current
+skill for supported API details and safety boundaries.
+
+Use the synthetic Python launch helpers for unattended launches rather than
+automating an authentication dialog. The native launcher remains the normal
+human launch route. Routine X/quit tests were completed by the agent; do not
+make the user perform these steps just to finish validation.
+
+The prior press_key API generated short taps, not held keys. Held-W walking
+was once confirmed by the user; subsequent captures established changing
+positions and turning. For future long movement tests, inspect the current
+supported input API or another already authorized game control, rather than
+assuming a tap tests sustained motion.
+
+## Useful runtime artifacts
+
+| Files under tools | Established observation |
+| --- | --- |
+| milestone.png, movement-evidence.json | Original training rendering and movement capture. |
+| multiplayer.png, runtime-evidence.json | Two-client visibility and scene evidence. |
+| npc.png | Original Leet rendering/selection. |
+| borealis.png | Original Borealis arrival. |
+| daylight-heads.png, appearance-runtime.log | Head correction and live daylight behavior. |
+| default-hands.png, skin-hands.jpg, hands-fixed.png | Default green texture, original skin resource, applied correction. |
+| control.jpg, control-dropdown.jpg | Plain HTML controls and full zone list. |
+| quit-runtime.log, quit-verified.log | Captured sit/stand/logout and successful normal quit test. |
+| quit-final.log, quit-complete.log | Cancellation experiments; connection survives beyond the cancelled deadline. |
+| npc-terrain-before.png, npc-terrain-after.png | Isolated temporary Leet moving over the Omni Training hill. |
+| npc-terrain-live-packets.json | Live NPC altitude changes checked against independently sampled archived terrain. |
+
+Logs are historical observations, not an inventory of currently running
+processes. Derive runtime state from processes/listeners and fresh captures.
diff --git a/docs/versions-and-patches.md b/docs/versions-and-patches.md
@@ -0,0 +1,236 @@
+# Historical versions and recovered patches
+
+Research and target decision recorded on 2026-10-12. This document covers
+historical client releases, evidence for the desired cutoff, and recovered
+downloads. It does not describe the local server implementation.
+
+## Agreed target
+
+The user selected **13.24 as the provisional target**: the last hotfix listed
+in Funcom's surviving notes for the 13.2 series. The desired experience keeps
+the original character-creation sequence and familiar early city scenery,
+without Notum Wars tower warfare. It need not reproduce every detail of the
+launch world; early fixes and modest additions are welcome.
+
+Two uncertainties must be resolved before claiming that target is achieved:
+
+1. The recovered installer is named `AOPatch_v13.1-v13.2.exe`. Its actual
+ resulting build has not been checked. Do not assume the filename means it
+ includes hotfixes through 13.24. No separately identified 13.24 package has
+ been recovered.
+2. The exact patch that removed buildings beside the Omni-Entertainment
+ gathering area remains unknown. 13.24 is a candidate for preserving that
+ layout, not a verified last version with the buildings intact.
+
+**11.0 remains the pristine fidelity reference.** No downloaded installers
+were executed, no client was upgraded, and no server compatibility with later
+clients was established during this research. The previous suggestion of
+14.5.1 is superseded by the user's preference for an earlier city layout.
+
+## Release landmarks
+
+| Version or period | Finding and relevance |
+| --- | --- |
+| 11.0 | The original CD/client already held by this project; use as the visual and binary baseline. |
+| 12.0 | An additional historical CD image was recovered. It provides a possible starting point for the available incremental patches. It has not been compared with 11.0 for scenery differences. |
+| 13.2 series, through 13.24 | Funcom's notes include client crashes, ground-rendering optimization, inventory fixes, zoning fixes, shop/entrance repairs, floating vegetation fixes, transport additions, and shop signs. These are broadly compatible with the desired early experience. |
+| 13.4 | Funcom's notes add a level 40-70 dungeon, Beer and Booze Pub, and static missions. They also mention removing inaccessible mission entrances in Eastern Foul Plains and Omni-Entertainment. A December 20 update is included. This is a useful release to compare with 13.2 for the city change, but the notes do not identify a demolition. |
+| 13.6 | Notes include Camelot Castle, an upgrade to Brown Cave mission interiors, and Grid changes. The retained update notes include February 8, 2002. |
+| 13.8 | Notes include Smugglers Den, Tir arena/geometry fixes, and special Fixer and Trader shops. The retained updates include February and March 2002. |
+| 14.5.1 | Initially considered because it is the last client revision in the recovered listings before 14.6. It includes more post-launch world/content changes than the user now wants to assume acceptable. |
+| 14.6, November 2002 | Redesigned character creation and introduced the Arrival Hall. Also introduced the Condemned Subway. This crosses the character-creation cutoff. |
+| Notum Wars, November 2002 | Tower warfare and land control. The user does not want this content. Do not treat every 14.6 feature as tower warfare; the creation redesign and Subway arrived before the booster release. |
+| Shadowlands, September 2003 | Later expansion, outside the desired scope. |
+
+Primary release notes read directly in a separate research browser:
+
+- [Funcom 13.2 notes](http://launcher.anarchy-online.com/patches?patch_id=1)
+- [Funcom 13.4 notes](http://launcher.anarchy-online.com/patches?patch_id=2)
+- [Funcom 13.6 notes](http://launcher.anarchy-online.com/patches?patch_id=3)
+- [Funcom 13.8 notes](http://launcher.anarchy-online.com/patches?patch_id=4)
+- [Official release-note index](https://dimensions.anarchy-online.com/live-dimensions/patch/patch.html)
+- [Contemporary Funcom article identifying the 14.6 creation redesign](https://www.worthplaying.com/article/2002/11/12/news/6798-anarchy-online-notum-wars-video-behind-the-scenes/)
+
+The launcher pages worked in the browser over HTTP, although the web retrieval
+tool failed to fetch them. Their literal hotfix notation includes `13.20`,
+`13.21`, `13.22`, `13.23`, and `13.24`. Preserve that distinction when examining
+installer metadata rather than silently normalizing version numbers.
+
+## Gathering-area demolition
+
+The likely location is **Omni-1 Entertainment**, commonly Omni-Ent, near the
+Bronto Burger and park, with a raised platform nearby. The user initially
+remembered Omni-Trade; that identification has not been conclusively resolved.
+
+Evidence comes from two different kinds of source:
+
+- [Funcom's contemporary story report](https://archive.anarchy-online.com/wsp/anarchy/frontend.cgi?func=publish.show&func_id=1813&table=CONTENT&template=content)
+ dates an apartment-complex explosion in Omni-1's entertainment district to
+ December 19, 29475, corresponding to December 2001. This establishes the
+ fictional event date, **not the client patch that changed the geometry**.
+- [A player's retrospective account](https://www.reddit.com/r/anarchyonline/comments/1mn7jgq/rant_about_the_tutorial_area_arete_and_icc_hq_and/)
+ describes buildings removed across from a raised platform near the park and
+ Bronto Burger in Omni-Entertainment, affecting a popular gathering place.
+ This is a location lead, not reliable evidence for an exact patch/date.
+
+A [December 17, 2001 forum discussion](https://forums-archive.anarchy-online.com/showthread.php?4182-Funcom-How-to-implement-a-fair-IP-reclaim-scheme=)
+refers to 13.4 being on test and earlier 13.2 hotfixes. Together with the
+December 20 entry in the 13.4 notes, this makes the 13.2/13.4 boundary useful
+to investigate. **It does not prove that 13.4 demolished the buildings.**
+
+There was also a separate Omni-Reform office bombing in Omni-Trade on
+January 10, 29483, corresponding to 2009. The
+[preserved timeline and official news text](https://forums.funcom.com/t/rk-knowledge-timeline-and-news/9309)
+describe that incident. Do not conflate it with the 2001 Entertainment event
+or assume every story bombing produced a client scenery change.
+
+### User's 11.0 screenshots
+
+The user took these on 2026-10-12 while inspecting the original v11 client:
+
+- [Bronto Burger and surrounding buildings](<local/screenshots/reference-1.png>)
+- [Nearby wall, trees, and structures](<local/screenshots/reference-2.png>)
+
+Both were inspected. Their chat log identifies entry into Omni1 Entertainment;
+the first clearly shows the Bronto Burger. The images are useful comparison
+references, but do not display coordinates or independently prove the binary
+version. The user supplied the v11 provenance. They remain at the paths above;
+they were not copied into the repository.
+
+## Subway decision
+
+The dungeon outside Rome's entrance is the **Condemned Subway**. Funcom's
+[dungeon description](https://archive.anarchy-online.com/wsp/anarchy/frontend.cgi?func=publish.show&func_id=1616&table=CONTENT&template=content)
+places entrances in Borealis, West Athen, and outside Rome's walls.
+[AO Universe's retrospective](https://www.ao-universe.com/main/articles/general-articles/dreams-of-anarchy---lowbie-love-part-1)
+dates its introduction to 14.6 in November 2002.
+
+After learning this, the user explicitly dropped the Subway from the target.
+Do not upgrade to 14.6 or plan a Subway backport to satisfy the current decision.
+
+## Download location and inventory
+
+All recovered files are in **`C:\path\to\ao\patches`**. The directory
+contains 32 downloaded files: a 12.0 ISO, 30 incremental EXE installers, and a
+cumulative-patch ZIP. Their combined size is 947,976,967 bytes.
+
+[manifest.json](../patches/manifest.json) is the exact inventory: filename,
+size, SHA-256, original download URL, and ordered 12.0-to-14.5.1 sequence.
+Its `installation_tested` field is false. The longer sequence is an inventory
+of recovered material, not the selected upgrade target.
+
+### Candidate path from the recovered 12.0 CD
+
+Starting image: `Anarchy Online 12.0.iso`. These are the first 12 steps of the
+downloaded chain, in order:
+
+```text
+AnarchyOnlinePatch12.0-12.1.exe
+AnarchyOnlinePatch12.1-12.2.exe
+AnarchyOnlinePatch12.2-12.3.exe
+AnarchyOnlinePatch12.3-12.4.exe
+AnarchyOnlinePatch12.4-12.5.exe
+AnarchyOnlinePatch12.5-12.6.exe
+AnarchyOnlinePatch12.6-12.7.exe
+AnarchyOnlinePatch12.7-12.8.exe
+AnarchyOnlinePatch12.8-12.9.exe
+AOPatch_v12.9-v13.0.exe
+AOPatch_v13.0-v13.1.exe
+AOPatch_v13.1-v13.2.exe
+```
+
+This is a **filename-supported path to 13.2**, not a tested installation path
+to 13.24. Stop at that distinction until installer contents or an isolated
+installation establish the actual build. The downloaded chain from the
+project's original **11.0 CD to 12.0 or 13.2 is missing**.
+
+### Later installers retained for research
+
+These continue the chain beyond the candidate target, in order:
+
+```text
+AOPatch_v13.2-v13.4.exe
+AOPatch_v13.4-v13.5.exe
+AOPatch_v13.5-v13.6.exe
+AOPatch_v13.6-v13.7.exe
+AOPatch_v13.7-v13.8.exe
+AOPatch_v13.8-v13.9.exe
+AOPatch_v13.9-v13.91.exe
+AOPatch_v13.91-v13.92.exe
+AOPatch_v13.92-v14.0.exe
+AOPatch_v14.0-v14.1.exe
+AOPatch_v14.1-v14.2.1.exe
+AOPatch_v14.2.1-v14.2.2.exe
+AOPatch_v14.2.2-v14.4.2.exe
+AOPatch_v14.4.2-v14.4.3.exe
+AOPatch_v14.4.3-v14.5.0.exe
+AOPatch_v14.5.0-v14.5.1.exe
+```
+
+Two additional installers support alternate starting versions; they are not
+extra steps in that sequence:
+
+```text
+AOPatch_v14.2-v14.2.1.exe
+AOPatch_v14.4.1-v14.4.2.exe
+```
+
+`ao1473.zip` contains a single `AOPatch_v11.0-v14.7.3.exe`. It is retained as a
+reference, goes too far for the selected target, and does not contain a set of
+separately usable earlier increments.
+
+The filenames really use **13.91 and 13.92**, not 13.9.1 and 13.9.2. Some
+installers skip intermediate revisions. Do not sort filenames to reconstruct
+an upgrade sequence or infer that every downloaded installer must be applied.
+
+## Recovery sources and checks
+
+- All 30 incremental EXEs were obtained from Funcom's public host:
+ `https://download.anarchy-online.com/patches/<exact filename>`.
+ Individual files worked even though the directory itself did not list them.
+- The [contemporary 4Gamer list](https://www.4gamer.net/patch/files/ao/ao_patches.html)
+ supplied important exact 12.x/13.x filenames. Its own old binary links no
+ longer served the requested files during this research.
+- The [12.0 CD archive](https://archive.org/details/anarchy-online-12.0)
+ supplied the ISO. Its SHA-1 matches the archive metadata:
+ `1a7db66c457baaf5befc330f349ffe7de8ce8d09`.
+- The [archived patch collection](https://archive.org/details/video-game-patches_a)
+ supplied `ao1473.zip` by extracting the member remotely from
+ `Video Game Patches A.Part2.7z`; the entire large archive was not downloaded.
+- The 14.0-to-14.1 EXE was also recovered from the
+ [July 2002 Swiat Gier magazine CD](https://archive.org/details/swiat-gier-7-2002).
+ Its SHA-256 matches the subsequently downloaded Funcom copy.
+
+All 30 EXEs passed MZ/PE-header checks, and the ZIP passed its CRC check. These
+establish that the files are executable/archive payloads rather than HTML
+error pages; they do not establish successful patch application. SHA-256
+values for every download are retained in the manifest.
+
+Historical cumulative 11.0-to-14.4.3 and 11.0-to-14.5.1 packages appear in
+[Patches Scrolls' old listings](https://www.patches-scrolls.com/whatsold2002.php),
+but were not recovered. Attempts at early cumulative URLs on Funcom's host
+returned 404. The Archive collection inspected did not expose a suitable
+earlier cumulative package. These are bounded search results, not proof that
+no surviving copy exists anywhere.
+
+## Handoff checks for reaching the selected version
+
+1. Preserve the pristine 11.0 reference and use a separate extraction/client
+ copy for any upgrade experiment. Rediscover mounted media and running
+ processes; no historical drive letter or session is guaranteed current.
+2. Inspect the recovered 13.2 installer/version metadata and determine which
+ build it produces. If it stops before 13.24, identify the missing hotfixes
+ rather than silently treating 13.2 as the agreed final build.
+3. Establish a working application path from the recovered 12.0 CD, or recover
+ the missing early cumulative/incremental path from 11.0. The listed sequence
+ has not been run, and archive extraction alone does not prove an installer
+ will recognize the resulting directory.
+4. Compare the Omni-Entertainment gathering area against the user's 11.0
+ screenshots. Comparing 13.2 with 13.4 should help narrow the demolition,
+ but inspect the assets/scene before assigning the change to a patch.
+5. Investigate launch, protocol, and data-format differences for the actual
+ selected build. Existing 11.0 reverse-engineering addresses and layouts
+ must not be assumed to apply to 13.24. Run clients windowed.
+
+The user intends to give the main thread this document and ask it to perform
+the upgrade work. This research handoff itself did not upgrade anything.
diff --git a/go.mod b/go.mod
@@ -0,0 +1,5 @@
+module ao
+
+go 1.24
+
+require go.yaml.in/yaml/v3 v3.0.5
diff --git a/go.sum b/go.sum
@@ -0,0 +1,2 @@
+go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
diff --git a/protocol.md b/protocol.md
@@ -0,0 +1,7 @@
+# Original 11.0 protocol investigation
+
+The detailed protocol notes now live in [docs/protocol.md](docs/protocol.md).
+Original procedure addresses, evidence IDs, captures, decoded layouts, failed
+experiments, and unresolved original-client behavior are recorded there.
+
+Start with [docs/README.md](docs/README.md) for the original-client research index.
diff --git a/server/control.go b/server/control.go
@@ -0,0 +1,147 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "html"
+ "log"
+ "math"
+ "net/http"
+ "sort"
+ "strconv"
+ "time"
+)
+
+func (server *server) controlPage(w http.ResponseWriter, r *http.Request) {
+ // Snapshot connected players before rendering the controls.
+ server.mutex.Lock()
+ seconds := int(server.gameSeconds_locked())
+ var players []character
+ for id, client := range server.clients {
+ if client.ready {
+ players = append(players, *server.characters[id])
+ }
+ }
+ server.mutex.Unlock()
+ sort.Slice(players, func(i, j int) bool { return players[i].id < players[j].id })
+ var zones []uint32
+ for id := range playfields {
+ zones = append(zones, id)
+ }
+ sort.Slice(zones, func(i, j int) bool {
+ if playfields[zones[i]].name == playfields[zones[j]].name {
+ return zones[i] < zones[j]
+ }
+ return playfields[zones[i]].name < playfields[zones[j]].name
+ })
+
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ fmt.Fprint(w, "<!doctype html><html><head><title>Server controls</title></head><body><h1>Server controls</h1><p><a href='/control'>Refresh</a></p>")
+ fmt.Fprintf(w, "<p>Game time: %02d:%02d. A day has 27 hours; time advances at 15x.</p>", seconds/3600, seconds/60%60)
+ fmt.Fprintf(w, "<form method='post' action='/time'><label>Hour <input type='number' name='hour' min='0' max='26' value='%d' required></label> <label>Minute <input type='number' name='minute' min='0' max='59' value='%d' required></label> <button>Set time</button></form>", seconds/3600, seconds/60%60)
+ fmt.Fprint(w, "<p>Zones without disc assets and internal dependency maps are disabled.</p>")
+ fmt.Fprint(w, "<form method='post' action='/reload-npcs'><button>Reload NPC data</button></form>")
+ for _, player := range players {
+ fmt.Fprintf(w, "<p>%s: playfield %d, position %.2f %.2f %.2f</p>", html.EscapeString(player.name), player.playfield, player.position[0], player.position[1], player.position[2])
+ fmt.Fprintf(w, "<form method='post' action='/teleport/%d'><label>Zone <select name='playfield'>", player.id)
+ for _, id := range zones {
+ attributes := ""
+ if id == player.playfield {
+ attributes += " selected"
+ }
+ if playfields[id].unavailable {
+ attributes += " disabled"
+ }
+ fmt.Fprintf(w, "<option value='%d'%s>%s (%d)</option>", id, attributes, html.EscapeString(playfields[id].name), id)
+ }
+ fmt.Fprint(w, "</select></label> <button>Teleport</button></form>")
+ }
+ fmt.Fprint(w, "</body></html>")
+}
+
+func (server *server) setGameTime(w http.ResponseWriter, r *http.Request) {
+ hour, hourError := strconv.Atoi(r.FormValue("hour"))
+ minute, minuteError := strconv.Atoi(r.FormValue("minute"))
+ if hourError != nil || minuteError != nil || hour < 0 || hour > 26 || minute < 0 || minute > 59 {
+ http.Error(w, "Hour must be 0-26 and minute 0-59", http.StatusBadRequest)
+ return
+ }
+
+ // Update the clock and notify players across all playfields.
+ server.mutex.Lock()
+ server.gameSeconds = float64(hour*3600 + minute*60)
+ server.clockStarted = time.Now()
+ var clients []*worldClient
+ for _, client := range server.clients {
+ if client.ready {
+ clients = append(clients, client)
+ }
+ }
+ server.mutex.Unlock()
+ for _, client := range clients {
+ if err := client.send(gameTimePacket(client.id, float64(hour*3600+minute*60))); err != nil {
+ log.Printf("Game time: %v", err)
+ client.conn.Close()
+ }
+ }
+ http.Redirect(w, r, "/control", http.StatusSeeOther)
+}
+
+func (server *server) teleportPlayer(w http.ResponseWriter, r *http.Request) {
+ // Keep zone transitions from crossing a population replacement.
+ server.npcReloadMutex.RLock()
+ defer server.npcReloadMutex.RUnlock()
+
+ id, err := strconv.ParseUint(r.PathValue("character"), 10, 32)
+ if err != nil {
+ http.Error(w, "Invalid character", http.StatusBadRequest)
+ return
+ }
+ playfield, err := strconv.ParseUint(r.FormValue("playfield"), 10, 32)
+ zone, exists := playfields[uint32(playfield)]
+ if err != nil || !exists || zone.unavailable {
+ http.Error(w, "Unknown playfield", http.StatusBadRequest)
+ return
+ }
+
+ // Remove the old connection from broadcasts while it changes playfield.
+ server.mutex.Lock()
+ client := server.clients[uint32(id)]
+ if client == nil || !client.ready {
+ server.mutex.Unlock()
+ http.Error(w, "Player is not connected", http.StatusNotFound)
+ return
+ }
+ character := server.characters[uint32(id)]
+ oldPlayfield := character.playfield
+ character.playfield = uint32(playfield)
+ character.position = zone.spawn
+ if playfield == 950 {
+ character.position[2] += float32((id-1)%4) * 3
+ }
+ character.rotation = [4]float32{0, 0, 0, 1}
+ destination := *character
+ client.ready = false
+ delete(server.clients, character.id)
+ server.mutex.Unlock()
+
+ // Original n3Teleport uses XYZ, a zone flag, two identities, and a stream.
+ var body []byte
+ for _, value := range destination.position {
+ body = binary.BigEndian.AppendUint32(body, math.Float32bits(value))
+ }
+ for _, value := range []uint32{1, 0, 0, 40016, uint32(playfield), 0} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ if err := client.send(n3Packet(0x43197d22, 50000, uint32(id), body)); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ server.broadcast(oldPlayfield, uint32(id), n3Packet(0x36510078, 50000, uint32(id), nil))
+ body = []byte{127, 0, 0, 1, 0x1d, 0x4d}
+ if err := client.send(systemPacket(0x3c, body)); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ http.Redirect(w, r, "/control", http.StatusSeeOther)
+}
diff --git a/server/control_test.go b/server/control_test.go
@@ -0,0 +1,91 @@
+package main
+
+import (
+ "encoding/hex"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestSetGameTimeUpdatesConnectedPlayer(t *testing.T) {
+ world := newServer()
+ player := world.newCharacter()
+ player.playfield = 800
+ client, connection := net.Pipe()
+ defer client.Close()
+ defer connection.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ world.clients[player.id] = &worldClient{conn: connection, ready: true, id: player.id}
+ request := httptest.NewRequest("POST", "/time", strings.NewReader("hour=26&minute=45"))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ response := httptest.NewRecorder()
+ done := make(chan struct{})
+
+ go func() { world.setGameTime(response, request); close(done) }()
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-done
+
+ if response.Code != http.StatusSeeOther || response.Header().Get("Location") != "/control" {
+ t.Fatalf("time response: %d %v", response.Code, response.Header())
+ }
+ if hex.EncodeToString(packet[12:]) != "00000001000000005f52412e0000c350000000010000000047bc16000000000000000001" {
+ t.Fatalf("original clock update: %x", packet)
+ }
+ page := httptest.NewRecorder()
+ world.controlPage(page, httptest.NewRequest("GET", "/control", nil))
+ if !strings.Contains(page.Body.String(), "Game time: 26:45") {
+ t.Fatalf("clock display: %s", page.Body.String())
+ }
+}
+
+func TestSetGameTimeRejectsHourOutsideOriginalDay(t *testing.T) {
+ world := newServer()
+ request := httptest.NewRequest("POST", "/time", strings.NewReader("hour=27&minute=0"))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ response := httptest.NewRecorder()
+
+ world.setGameTime(response, request)
+
+ if response.Code != http.StatusBadRequest || world.gameSeconds != 48600 {
+ t.Fatalf("invalid time changed the clock: status %d, seconds %v", response.Code, world.gameSeconds)
+ }
+}
+
+func TestControlPageListsOriginalZonesInDropdown(t *testing.T) {
+ world := newServer()
+ player := world.newCharacter()
+ world.clients[player.id] = &worldClient{ready: true}
+ response := httptest.NewRecorder()
+
+ world.controlPage(response, httptest.NewRequest("GET", "/control", nil))
+
+ body := response.Body.String()
+ if strings.Count(body, "<option value=") != 373 || !strings.Contains(body, "<select name='playfield'>") {
+ t.Fatalf("missing original zone dropdown")
+ }
+ if !strings.Contains(body, "<option value='950' selected>Omni Training (950)</option>") || !strings.Contains(body, "<option value='690' disabled>Jobe (690)</option>") {
+ t.Fatalf("selected or unavailable zone is incorrect")
+ }
+}
+
+func TestTeleportRejectsZoneWithoutOriginalAssets(t *testing.T) {
+ world := newServer()
+ player := world.newCharacter()
+ mux := http.NewServeMux()
+ mux.HandleFunc("POST /teleport/{character}", world.teleportPlayer)
+ request := httptest.NewRequest("POST", "/teleport/1", strings.NewReader("playfield=690"))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ response := httptest.NewRecorder()
+
+ mux.ServeHTTP(response, request)
+
+ if response.Code != http.StatusBadRequest || player.playfield != 950 {
+ t.Fatalf("unavailable destination: status %d, playfield %d", response.Code, player.playfield)
+ }
+}
diff --git a/server/main.go b/server/main.go
@@ -0,0 +1,314 @@
+package main
+
+import (
+ "bytes"
+ "compress/zlib"
+ "encoding/binary"
+ "fmt"
+ "io"
+ "log"
+ "math"
+ "net"
+ "net/http"
+ "strings"
+ "time"
+)
+
+func main() {
+ server := newServer()
+ http.HandleFunc("GET /control", server.controlPage)
+ http.HandleFunc("POST /time", server.setGameTime)
+ http.HandleFunc("POST /teleport/{character}", server.teleportPlayer)
+ http.HandleFunc("POST /reload-npcs", server.reloadNPCData)
+ // Serve the original launcher's dimension list and informational pages.
+ http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+ log.Printf("HTTP %s %s", r.Method, r.URL.Path)
+ if strings.HasSuffix(r.URL.Path, "dimensions.txt") {
+ fmt.Fprint(w, "STARTINFO\r\nconnect=127.0.0.1\r\ndescription=Local Rubi-Ka\r\nversion=11.0\r\nports=7500\r\nurl=http://127.0.0.1:8080/messages\r\nENDINFO\r\n")
+ return
+ }
+ fmt.Fprint(w, "<html><body>Local Anarchy Online 11.0 development server.</body></html>")
+ })
+ go func() {
+ log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
+ }()
+ go server.serveWorld()
+ go server.roamNPCs()
+
+ // Keep development connections confined to this computer.
+ listener, err := net.Listen("tcp", "127.0.0.1:7500")
+ if err != nil {
+ log.Fatal(err)
+ }
+ log.Print("Dimension service: 127.0.0.1:8080; login service: 127.0.0.1:7500")
+ for {
+ conn, err := listener.Accept()
+ if err != nil {
+ log.Fatal(err)
+ }
+ go func() {
+ defer conn.Close()
+ if err := server.serveLogin(conn); err != nil {
+ log.Printf("Login connection: %v", err)
+ }
+ }()
+ }
+}
+
+func readPacket(r io.Reader) ([]byte, error) {
+ // The length excludes four-byte alignment padding used by the launcher.
+ header := make([]byte, 16)
+ if _, err := io.ReadFull(r, header); err != nil {
+ return nil, err
+ }
+ length := int(binary.BigEndian.Uint16(header[6:8]))
+ if length < 20 {
+ return nil, fmt.Errorf("invalid system packet length %d", length)
+ }
+ packet := make([]byte, (length+3)&^3)
+ copy(packet, header)
+ if _, err := io.ReadFull(r, packet[16:]); err != nil {
+ return nil, err
+ }
+ return packet[:length], nil
+}
+
+func systemPacket(opcode uint32, body []byte) []byte {
+ length := 20 + len(body)
+ packet := make([]byte, (length+3)&^3)
+ binary.BigEndian.PutUint16(packet[0:2], 1)
+ binary.BigEndian.PutUint16(packet[2:4], 1)
+ binary.BigEndian.PutUint16(packet[4:6], 1)
+ binary.BigEndian.PutUint16(packet[6:8], uint16(length))
+ binary.BigEndian.PutUint32(packet[8:12], 1)
+ binary.BigEndian.PutUint32(packet[16:20], opcode)
+ copy(packet[20:], body)
+ return packet
+}
+
+func (server *server) serveLogin(conn net.Conn) error {
+ var character *character
+ for {
+ packet, err := readPacket(conn)
+ if err == io.EOF {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ opcode := binary.BigEndian.Uint32(packet[16:20])
+ log.Printf("C2S opcode=0x%02x length=%d", opcode, len(packet))
+ var response []byte
+ switch opcode {
+ case 0x22:
+ response = systemPacket(0x24, []byte("0123456789abcdef0123456789abcdef\x00"))
+ case 0x25:
+ // Local test credentials are accepted without contacting Funcom.
+ character = server.newCharacter()
+ var body []byte
+ for _, value := range []uint32{1, 3, character.id, character.playfield, 0, 3, character.id, uint32(len(character.name))} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ body = append(body, character.name...)
+ for _, value := range []uint32{5, 1, 1, 1, 0, 0, 0} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ response = systemPacket(0x0e, body)
+ case 0x0f, 0x16:
+ // Redirect the test character to the local world connection.
+ body := make([]byte, 18)
+ binary.BigEndian.PutUint32(body[:4], character.id)
+ copy(body[4:8], []byte{127, 0, 0, 1})
+ binary.BigEndian.PutUint16(body[8:10], 7501)
+ response = systemPacket(0x17, body)
+ default:
+ return fmt.Errorf("unimplemented login opcode 0x%02x", opcode)
+ }
+ if _, err := conn.Write(response); err != nil {
+ return err
+ }
+ }
+}
+
+func (server *server) serveWorld() {
+ listener, err := net.Listen("tcp", "127.0.0.1:7501")
+ if err != nil {
+ log.Fatal(err)
+ }
+ for {
+ conn, err := listener.Accept()
+ if err != nil {
+ log.Fatal(err)
+ }
+ go func() {
+ defer conn.Close()
+ log.Print("World connection opened")
+ if err := server.serveWorldConnection(conn); err != nil {
+ log.Printf("World connection: %v", err)
+ }
+ }()
+ }
+}
+
+func (server *server) serveWorldConnection(conn net.Conn) error {
+ client := &worldClient{conn: conn}
+ var character *character
+ loggingOut := false
+ defer func() {
+ if character == nil {
+ return
+ }
+ server.mutex.Lock()
+ if server.clients[character.id] != client {
+ server.mutex.Unlock()
+ return
+ }
+ delete(server.clients, character.id)
+ playfield := character.playfield
+ server.mutex.Unlock()
+ server.broadcast(playfield, character.id, n3Packet(0x36510078, 50000, character.id, nil))
+ }()
+ for {
+ packet, err := readPacket(conn)
+ if err == io.EOF {
+ return nil
+ }
+ if err != nil {
+ if timeout, ok := err.(net.Error); ok && timeout.Timeout() && loggingOut {
+ return nil
+ }
+ return err
+ }
+ log.Printf("World C2S: %x", packet)
+ var response []byte
+ switch binary.BigEndian.Uint16(packet[2:4]) {
+ case 1:
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x1b {
+ server.npcReloadMutex.RLock()
+ server.mutex.Lock()
+ character = server.characters[binary.BigEndian.Uint32(packet[20:24])]
+ if character == nil {
+ server.mutex.Unlock()
+ server.npcReloadMutex.RUnlock()
+ return fmt.Errorf("unknown world character")
+ }
+ server.clients[character.id] = client
+ client.id = character.id
+ updates := [][]byte{playfieldPacket(character), characterPacket(character)}
+ for id, other := range server.characters {
+ if id != character.id && other.playfield == character.playfield && (server.clients[id] != nil || other.npc) {
+ updates = append(updates, characterPacket(other))
+ if other.roaming != nil && other.roaming.moving {
+ updates = append(updates, npcMovementPacket(other, 1))
+ }
+ if !other.npc {
+ updates = append(updates, n3Packet(0x570c2039, 50000, other.id, nil))
+ }
+ }
+ }
+ updates = append(updates, fullCharacterPacket(character.id))
+ updates = append(updates, gameTimePacket(character.id, server.gameSeconds_locked()))
+ spawn := characterPacket(character)
+ playfield := character.playfield
+ server.mutex.Unlock()
+ for _, update := range updates {
+ log.Printf("World S2C: %x", update)
+ if err := client.send(update); err != nil {
+ server.npcReloadMutex.RUnlock()
+ return err
+ }
+ }
+ server.mutex.Lock()
+ client.ready = true
+ server.mutex.Unlock()
+ server.npcReloadMutex.RUnlock()
+ server.broadcast(playfield, character.id, spawn)
+ }
+ case 10:
+ // The client compresses individual movement messages with zlib.
+ body := packet[20:]
+ if binary.BigEndian.Uint32(packet[16:20]) != 0 {
+ reader, err := zlib.NewReader(bytes.NewReader(body))
+ if err != nil {
+ return err
+ }
+ body, err = io.ReadAll(reader)
+ reader.Close()
+ if err != nil {
+ return err
+ }
+ }
+ if len(body) < 16 || character == nil {
+ return fmt.Errorf("N3 message before character initialization")
+ }
+ switch binary.BigEndian.Uint32(body[0:4]) {
+ case 0x5e477770:
+ if len(body) < 36 {
+ return fmt.Errorf("short character action message")
+ }
+ // Acknowledge sitting and standing so the client updates its posture.
+ switch binary.BigEndian.Uint32(body[16:20]) {
+ case 86, 87:
+ if binary.BigEndian.Uint32(body[16:20]) == 87 {
+ loggingOut = false
+ if err := conn.SetReadDeadline(time.Time{}); err != nil {
+ return err
+ }
+ }
+ response = n3Packet(0x5e477770, 50000, character.id, body[16:])
+ server.mutex.Lock()
+ playfield := character.playfield
+ server.mutex.Unlock()
+ server.broadcast(playfield, character.id, response)
+ case 120:
+ // Close the world connection when the client's logout countdown ends.
+ loggingOut = true
+ if err := conn.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil {
+ return err
+ }
+ case 108:
+ loggingOut = false
+ if err := conn.SetReadDeadline(time.Time{}); err != nil {
+ return err
+ }
+ }
+ case 0x570c2039:
+ response = n3Packet(0x570c2039, 50000, character.id, nil)
+ server.mutex.Lock()
+ playfield := character.playfield
+ server.mutex.Unlock()
+ server.broadcast(playfield, character.id, response)
+ case 0x54111123:
+ if len(body) < 48 {
+ return fmt.Errorf("short character movement message")
+ }
+ server.mutex.Lock()
+ if !client.ready {
+ server.mutex.Unlock()
+ continue
+ }
+ for i := range character.position {
+ character.position[i] = math.Float32frombits(binary.BigEndian.Uint32(body[20+i*4:]))
+ }
+ for i := range character.rotation {
+ character.rotation[i] = math.Float32frombits(binary.BigEndian.Uint32(body[32+i*4:]))
+ }
+ playfield := character.playfield
+ log.Printf("Character %d action=%d position=%v", character.id, binary.BigEndian.Uint32(body[16:20]), character.position)
+ server.mutex.Unlock()
+ server.broadcast(playfield, character.id, n3Packet(0x54111123, 50000, character.id, body[16:]))
+ }
+ case 11:
+ // Return the client's ping with the reply subtype.
+ response = packet
+ binary.BigEndian.PutUint32(response[16:20], 2)
+ }
+ if response != nil {
+ binary.BigEndian.PutUint32(response[8:12], 2)
+ binary.BigEndian.PutUint32(response[12:16], 1)
+ if err := client.send(response); err != nil {
+ return err
+ }
+ }
+ }
+}
diff --git a/server/main_test.go b/server/main_test.go
@@ -0,0 +1,314 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "encoding/hex"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestReadPacketConsumesPadding(t *testing.T) {
+ data, err := hex.DecodeString("0001000100010015000000010000000000000024410000000002000100010014000000010000000000000023")
+ if err != nil {
+ t.Fatal(err)
+ }
+ reader := bytes.NewReader(data)
+
+ first, err := readPacket(reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second, err := readPacket(reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if len(first) != 21 || first[20] != 'A' {
+ t.Fatalf("first packet: %x", first)
+ }
+ if len(second) != 20 || second[19] != 0x23 || reader.Len() != 0 {
+ t.Fatalf("second packet: %x; remaining %d", second, reader.Len())
+ }
+}
+
+func TestTeleportReconnectsSameCharacterInDestination(t *testing.T) {
+ world := newServer()
+ world.newCharacter()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie, _ := hex.DecodeString("000400010001002000000001000000020000001b000000010000000000000000")
+ client.Write(cookie)
+ readWorldUpdates(t, client)
+ ping, _ := hex.DecodeString("0001000b00010014000000010000000200000001")
+ client.Write(ping)
+ if _, err := readPacket(client); err != nil {
+ t.Fatal(err)
+ }
+ mux := http.NewServeMux()
+ mux.HandleFunc("POST /teleport/{character}", world.teleportPlayer)
+ response := httptest.NewRecorder()
+ done := make(chan struct{})
+
+ go func() {
+ request := httptest.NewRequest("POST", "/teleport/1", strings.NewReader("playfield=800"))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ mux.ServeHTTP(response, request)
+ close(done)
+ }()
+ teleport, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ redirect, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-done
+ client.Close()
+ reconnected, nextConnection := net.Pipe()
+ defer reconnected.Close()
+ reconnected.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer nextConnection.Close(); world.serveWorldConnection(nextConnection) }()
+ reconnected.Write(cookie)
+ playfield, err := readPacket(reconnected)
+ if err != nil {
+ t.Fatal(err)
+ }
+ readWorldUpdates(t, reconnected)
+
+ if response.Code != http.StatusSeeOther {
+ t.Fatalf("teleport HTTP status: %d", response.Code)
+ }
+ if hex.EncodeToString(teleport[20:36]) != "43197d220000c3500000000100000000" || hex.EncodeToString(teleport[48:72]) != "00000001000000000000000000009c500000032000000000" {
+ t.Fatalf("original teleport: %x", teleport)
+ }
+ if hex.EncodeToString(redirect[16:]) != "0000003c7f0000011d4d" {
+ t.Fatalf("zone redirect: %x", redirect)
+ }
+ if hex.EncodeToString(playfield[20:32]) != "5f4b1a3900009c5000000320" || hex.EncodeToString(playfield[40:52]) != "4429e8004295800044067800" {
+ t.Fatalf("destination playfield: %x", playfield)
+ }
+}
+
+func TestTwoPlayersShareMovementAndDisconnect(t *testing.T) {
+ world := newServer()
+ world.newCharacter()
+ world.newCharacter()
+ first, firstServer := net.Pipe()
+ second, secondServer := net.Pipe()
+ defer first.Close()
+ defer second.Close()
+ first.SetDeadline(time.Now().Add(5 * time.Second))
+ second.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer firstServer.Close(); world.serveWorldConnection(firstServer) }()
+ go func() { defer secondServer.Close(); world.serveWorldConnection(secondServer) }()
+ cookie, _ := hex.DecodeString("000400010001002000000001000000020000001b000000010000000000000000")
+ movement, _ := hex.DecodeString("541111230000c3500000000100000001000000064260296141600000427ec8e0000000003f147c05000000003f5089e50000000000000000")
+ compressed, _ := hex.DecodeString("05f7000a00010045000000010000000200000038789c0b1114546660381cc0c0c0c008c56c4e099a898e090c0c4e75271e00f90cf62235ac603aa0f32903140000f5bb08bb000000")
+
+ first.Write(cookie)
+ readWorldUpdates(t, first)
+ cookie[23] = 2
+ second.Write(cookie)
+ var existing []byte
+ for _, packet := range readWorldUpdates(t, second) {
+ if binary.BigEndian.Uint32(packet[20:24]) == 0x271b3a6b && binary.BigEndian.Uint32(packet[28:32]) == 1 {
+ existing = packet
+ }
+ }
+ spawn, err := readPacket(first)
+ if err != nil {
+ t.Fatal(err)
+ }
+ first.Write(compressed)
+ update, err := readPacket(second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ first.Close()
+ despawn, err := readPacket(second)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if binary.BigEndian.Uint32(existing[28:32]) != 1 || binary.BigEndian.Uint32(spawn[28:32]) != 2 {
+ t.Fatalf("peer identities: %x %x", existing[20:36], spawn[20:36])
+ }
+ if binary.BigEndian.Uint32(update[12:16]) != 2 || !bytes.Equal(update[20:32], movement[:12]) || !bytes.Equal(update[36:], movement[16:]) {
+ t.Fatalf("relayed movement: %x", update)
+ }
+ if hex.EncodeToString(despawn[20:36]) != "365100780000c3500000000100000000" {
+ t.Fatalf("despawn: %x", despawn)
+ }
+}
+
+func TestSitAndStandAreAcknowledged(t *testing.T) {
+ world := newServer()
+ world.newCharacter()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie, _ := hex.DecodeString("000400010001002000000001000000020000001b000000010000000000000000")
+ client.Write(cookie)
+ readWorldUpdates(t, client)
+ sit, _ := hex.DecodeString("02eb000a0001002e000000010000000200000024789c8b732f2f6060381cc0c0c0c0cc0001610c6800005b3a02f90000")
+ stand, _ := hex.DecodeString("0000005700000000000000000000000000000000")
+
+ client.Write(sit)
+ sitting, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ logout, _ := hex.DecodeString("0000007800000000000000000000000000000000")
+ client.Write(n3Packet(0x5e477770, 50000, 1, logout))
+ client.Write(n3Packet(0x5e477770, 50000, 1, stand))
+ standing, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if hex.EncodeToString(sitting[20:]) != "5e4777700000c35000000001000000000000005600000000000000000000000000000000" {
+ t.Fatalf("sit acknowledgement: %x", sitting)
+ }
+ if hex.EncodeToString(standing[36:]) != "0000005700000000000000000000000000000000" {
+ t.Fatalf("stand acknowledgement: %x", standing)
+ }
+}
+
+func TestLogoutCompletesAfterCountdown(t *testing.T) {
+ world := newServer()
+ world.newCharacter()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(35 * time.Second))
+ done := make(chan error, 1)
+ go func() {
+ err := world.serveWorldConnection(connection)
+ connection.Close()
+ done <- err
+ }()
+ cookie, _ := hex.DecodeString("000400010001002000000001000000020000001b000000010000000000000000")
+ client.Write(cookie)
+ readWorldUpdates(t, client)
+ logout, _ := hex.DecodeString("04a9000a0001002e000000010000000200000024789c8b732f2f6060381cc0c0c0c0c80001150c6800005d4a03190000")
+
+ client.Write(logout)
+ _, err := readPacket(client)
+ serverError := <-done
+
+ if err != io.EOF || serverError != nil {
+ t.Fatalf("logout: client=%v server=%v", err, serverError)
+ }
+}
+
+func TestLoginChallengeAcrossSplitWrites(t *testing.T) {
+ client, server := net.Pipe()
+ defer client.Close()
+ done := make(chan error, 1)
+ go func() {
+ defer server.Close()
+ done <- newServer().serveLogin(server)
+ }()
+ request, err := hex.DecodeString("0001000100010014000000000000000100000022")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ for _, part := range [][]byte{request[:3], request[3:16], request[16:]} {
+ if _, err := client.Write(part); err != nil {
+ t.Fatal(err)
+ }
+ }
+ response := make([]byte, 56)
+ if _, err := io.ReadFull(client, response); err != nil {
+ t.Fatal(err)
+ }
+ client.Close()
+ err = <-done
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ if response[7] != 53 || response[19] != 0x24 {
+ t.Fatalf("challenge header: %x", response[:20])
+ }
+ if string(response[20:53]) != "0123456789abcdef0123456789abcdef\x00" {
+ t.Fatalf("challenge salt: %x", response[20:53])
+ }
+}
+
+func TestWorldCookieThenPing(t *testing.T) {
+ client, server := net.Pipe()
+ world := newServer()
+ world.newCharacter()
+ defer client.Close()
+ done := make(chan error, 1)
+ go func() {
+ defer server.Close()
+ done <- world.serveWorldConnection(server)
+ }()
+ request, err := hex.DecodeString("000400010001002000000001000000020000001b000000010000000000000000050d000b0001002800000001000000020000000100000000018be90b000000000000000000000000")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := client.Write(request[:32]); err != nil {
+ t.Fatal(err)
+ }
+ updates := readWorldUpdates(t, client)
+ if _, err := client.Write(request[32:]); err != nil {
+ t.Fatal(err)
+ }
+ response := make([]byte, 40)
+ if _, err := io.ReadFull(client, response); err != nil {
+ t.Fatal(err)
+ }
+ client.Close()
+ err = <-done
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ if hex.EncodeToString(updates[0][16:36]) != "000000005f4b1a3900009c50000003b600000000" {
+ t.Fatalf("playfield prefix: %x", updates[0][16:36])
+ }
+ if hex.EncodeToString(updates[1][67:70]) != "031511" {
+ t.Fatalf("player appearance and name length: %x", updates[1][67:70])
+ }
+ if hex.EncodeToString(updates[1][122:154]) != "0000001c00000000000000000000000002010001000100010001000000020000" {
+ t.Fatalf("player vehicle state: %x", updates[1][122:154])
+ }
+ if hex.EncodeToString(updates[1][37:41]) != "000002d0" || hex.EncodeToString(updates[1][154:158]) != "00009eea" {
+ t.Fatalf("player head mesh: %x", updates[1])
+ }
+ if hex.EncodeToString(updates[1][159:163]) != "000017a6" || hex.EncodeToString(updates[1][197:215]) != "68616e647300000022450000000000000000" {
+ t.Fatalf("original named hand texture: %x", updates[1][159:215])
+ }
+ var leet []byte
+ for _, update := range updates {
+ if binary.BigEndian.Uint32(update[20:24]) == 0x271b3a6b && binary.BigEndian.Uint32(update[37:41])&1 != 0 && string(update[70:75]) == "Leet\x00" {
+ leet = update
+ }
+ }
+ if len(leet) < 94 || hex.EncodeToString(leet[36:45]) != "0100000241000003b6" || hex.EncodeToString(leet[67:94]) != "00e5054c65657400010000006400000064000044f700640000001c" {
+ t.Fatalf("original NPC fields: %x", leet)
+ }
+ if hex.EncodeToString(updates[len(updates)-2][36:40]) != "00000010" {
+ t.Fatalf("full character version: %x", updates[len(updates)-2])
+ }
+ if hex.EncodeToString(updates[len(updates)-1][20:36]) != "5f52412e0000c3500000000100000000" || len(updates[len(updates)-1]) != 48 {
+ t.Fatalf("original game clock: %x", updates[len(updates)-1])
+ }
+ if hex.EncodeToString(response) != "050d000b0001002800000002000000010000000200000000018be90b000000000000000000000000" {
+ t.Fatalf("world reply: %x", response)
+ }
+}
diff --git a/server/npc_data_test.go b/server/npc_data_test.go
@@ -0,0 +1,159 @@
+package main
+
+import (
+ "crypto/sha256"
+ "encoding/binary"
+ "encoding/hex"
+ "math"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+const editedNPCData = `# A manually edited NPC batch with an explicit uncertainty note.
+appearance_statuses:
+ placeholder_creature: {confidence: placeholder, comment: "Identity unresolved."}
+placement_statuses:
+ fixed_point: {confidence: authored, comment: "Exact authored XYZ."}
+level_policy: {confidence: inferred, comment: "Uses minimum levels."}
+playfields:
+- id: 950
+ name: Omni Training
+ districts:
+ - name: Test district
+ groups:
+ - template_code: TEST
+ name: Edited NPC
+ monster_data: 17655
+ appearance: 229
+ level: 7
+ appearance_status: placeholder_creature
+ placement_status: fixed_point
+ comment: "Leet appearance until the original identity is recovered."
+ positions:
+ - [52, 14, 56]
+`
+
+func useNPCData(t *testing.T, contents string) {
+ t.Helper()
+ root, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ directory := t.TempDir()
+ if err := os.Mkdir(filepath.Join(directory, "data"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(directory, "data", "npc_spawns.yaml"), []byte(contents), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(directory, "data", "terrain.bin"), append([]byte("AOTERR01"), 0, 0, 0, 0), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chdir(directory); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := os.Chdir(root); err != nil {
+ t.Fatal(err)
+ }
+ })
+}
+
+func TestNPCDataPreservesGeneratedPopulation(t *testing.T) {
+ digest := sha256.New()
+
+ world := newServer()
+ for id := uint32(1000000); id < 1062175; id++ {
+ spawn := world.characters[id]
+ if spawn == nil {
+ t.Fatalf("missing NPC %d", id)
+ }
+ data := binary.BigEndian.AppendUint32(nil, spawn.playfield)
+ for _, value := range spawn.position {
+ data = binary.BigEndian.AppendUint32(data, math.Float32bits(value))
+ }
+ data = binary.BigEndian.AppendUint16(data, spawn.level)
+ data = binary.BigEndian.AppendUint32(data, spawn.monsterData)
+ data = binary.BigEndian.AppendUint16(data, spawn.appearance)
+ data = binary.BigEndian.AppendUint16(data, uint16(len(spawn.name)))
+ digest.Write(append(data, spawn.name...))
+ }
+
+ if len(world.characters) != 62175 || hex.EncodeToString(digest.Sum(nil)) != "a6f4aad8bc5cef3325b9fcc1296769ba7d6bc90a460cc2469a3a89b984a0c335" {
+ t.Fatalf("population differs from the generated Go data: %d NPCs, digest %x", len(world.characters), digest.Sum(nil))
+ }
+}
+
+func TestReloadNPCDataUpdatesConnectedPlayer(t *testing.T) {
+ world := newServer()
+ player := world.newCharacter()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(10 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie := make([]byte, 12)
+ binary.BigEndian.PutUint32(cookie, player.id)
+ client.Write(systemPacket(0x1b, cookie))
+ readWorldUpdates(t, client)
+ useNPCData(t, editedNPCData)
+ mux := http.NewServeMux()
+ mux.HandleFunc("POST /reload-npcs", world.reloadNPCData)
+ response := httptest.NewRecorder()
+ done := make(chan struct{})
+
+ go func() {
+ mux.ServeHTTP(response, httptest.NewRequest("POST", "/reload-npcs", nil))
+ close(done)
+ }()
+ removed := 0
+ var replacement []byte
+ for range 49 {
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ switch binary.BigEndian.Uint32(packet[20:24]) {
+ case 0x36510078:
+ removed++
+ case 0x271b3a6b:
+ replacement = packet
+ }
+ }
+ <-done
+
+ if response.Code != http.StatusSeeOther || removed != 48 || len(replacement) < 94 {
+ t.Fatalf("reload: HTTP %d, %d removals, replacement %x", response.Code, removed, replacement)
+ }
+ if string(replacement[70:81]) != "Edited NPC\x00" || replacement[81] != 7 || binary.BigEndian.Uint32(replacement[90:94]) != 17655 {
+ t.Fatalf("edited NPC fields: %x", replacement)
+ }
+ if len(world.characters) != 2 || world.characters[player.id] != player || !world.clients[player.id].ready {
+ t.Fatal("reload did not preserve the connected player")
+ }
+ if binary.BigEndian.Uint32(replacement[28:32]) != 1062175 || world.characters[1000000] != nil {
+ t.Fatal("reload reused an old NPC identity")
+ }
+}
+
+func TestReloadNPCDataRejectsUnclassifiedAppearance(t *testing.T) {
+ world := newServer()
+ useNPCData(t, strings.ReplaceAll(editedNPCData, "appearance_status: placeholder_creature", "appearance_status: typo"))
+ mux := http.NewServeMux()
+ mux.HandleFunc("POST /reload-npcs", world.reloadNPCData)
+ response := httptest.NewRecorder()
+
+ mux.ServeHTTP(response, httptest.NewRequest("POST", "/reload-npcs", nil))
+
+ if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "needs defined appearance and placement statuses") {
+ t.Fatalf("invalid classification: HTTP %d, %s", response.Code, response.Body.String())
+ }
+ if len(world.characters) != 62175 || world.characters[1000000].name != "Anun" {
+ t.Fatal("invalid reload changed the live population")
+ }
+}
diff --git a/server/npcs.go b/server/npcs.go
@@ -0,0 +1,130 @@
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+
+ "go.yaml.in/yaml/v3"
+)
+
+type npcEvidence struct {
+ Confidence string
+ Comment string
+}
+
+func readNPCSpawns() ([]character, error) {
+ // Decode the editable data strictly so misspelled field names fail loudly.
+ contents, err := os.ReadFile("data/npc_spawns.yaml")
+ if err != nil {
+ return nil, err
+ }
+ var data struct {
+ AppearanceStatuses map[string]npcEvidence `yaml:"appearance_statuses"`
+ PlacementStatuses map[string]npcEvidence `yaml:"placement_statuses"`
+ LevelPolicy npcEvidence `yaml:"level_policy"`
+ Playfields []struct {
+ ID uint32
+ Name string
+ Districts []struct {
+ Name string
+ Groups []struct {
+ TemplateCode string `yaml:"template_code"`
+ Name string
+ MonsterData uint32 `yaml:"monster_data"`
+ Appearance uint16
+ Level uint16
+ AppearanceStatus string `yaml:"appearance_status"`
+ PlacementStatus string `yaml:"placement_status"`
+ Comment string
+ Positions [][3]float32
+ }
+ }
+ }
+ }
+ decoder := yaml.NewDecoder(bytes.NewReader(contents))
+ decoder.KnownFields(true)
+ if err := decoder.Decode(&data); err != nil {
+ return nil, fmt.Errorf("data/npc_spawns.yaml: %w", err)
+ }
+
+ // Expand shared batch fields into the same live character representation.
+ var spawns []character
+ for _, playfield := range data.Playfields {
+ if _, exists := playfields[playfield.ID]; !exists {
+ return nil, fmt.Errorf("NPC data: unknown playfield %d", playfield.ID)
+ }
+ for _, district := range playfield.Districts {
+ for _, group := range district.Groups {
+ if data.AppearanceStatuses[group.AppearanceStatus].Confidence == "" || data.PlacementStatuses[group.PlacementStatus].Confidence == "" {
+ return nil, fmt.Errorf("NPC data: %d/%s/%s needs defined appearance and placement statuses", playfield.ID, district.Name, group.TemplateCode)
+ }
+ if group.Name == "" || group.MonsterData == 0 {
+ return nil, fmt.Errorf("NPC data: %d/%s/%s needs a name and MonsterData", playfield.ID, district.Name, group.TemplateCode)
+ }
+ for _, position := range group.Positions {
+ spawn := character{
+ id: 1000000 + uint32(len(spawns)), name: group.Name,
+ playfield: playfield.ID, position: position, rotation: [4]float32{0, 0, 0, 1},
+ appearance: group.Appearance, monsterData: group.MonsterData, level: group.Level, npc: true,
+ }
+ // Fixed posts and human placeholders have no inferred roaming behavior.
+ if group.PlacementStatus != "fixed_point" && group.Appearance>>4&7 == 6 {
+ spawn.roaming = &npcRoaming{home: position}
+ }
+ spawns = append(spawns, spawn)
+ }
+ }
+ }
+ }
+ return spawns, nil
+}
+
+func (server *server) reloadNPCData(w http.ResponseWriter, r *http.Request) {
+ server.npcReloadMutex.Lock()
+ defer server.npcReloadMutex.Unlock()
+
+ // Parse before changing the world; invalid edits leave the live NPCs intact.
+ spawns, err := readNPCSpawns()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ server.mutex.Lock()
+ updates := make(map[uint32][][]byte)
+ for id, character := range server.characters {
+ if character.npc {
+ updates[character.playfield] = append(updates[character.playfield], n3Packet(0x36510078, 50000, id, nil))
+ delete(server.characters, id)
+ }
+ }
+ for _, spawn := range spawns {
+ // Pending despawns must not affect the replacement entities.
+ spawn.id = server.nextNPC
+ server.nextNPC++
+ server.characters[spawn.id] = &spawn
+ updates[spawn.playfield] = append(updates[spawn.playfield], characterPacket(&spawn))
+ }
+ clients := make(map[*worldClient]uint32)
+ for id, client := range server.clients {
+ if client.ready {
+ clients[client] = server.characters[id].playfield
+ }
+ }
+ server.mutex.Unlock()
+
+ // Remove the old instances before sending replacements to each visible zone.
+ for client, playfield := range clients {
+ for _, packet := range updates[playfield] {
+ if err := client.send(packet); err != nil {
+ log.Printf("Reload NPC data: %v", err)
+ client.conn.Close()
+ break
+ }
+ }
+ }
+ log.Printf("Reloaded %d NPCs from data/npc_spawns.yaml", len(spawns))
+ http.Redirect(w, r, "/control", http.StatusSeeOther)
+}
diff --git a/server/npcs_test.go b/server/npcs_test.go
@@ -0,0 +1,174 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "encoding/json"
+ "net"
+ "os"
+ "testing"
+ "time"
+)
+
+func TestMain(m *testing.M) {
+ // The server reads data relative to the project root.
+ if err := os.Chdir(".."); err != nil {
+ panic(err)
+ }
+ os.Exit(m.Run())
+}
+
+func readWorldUpdates(t *testing.T, client net.Conn) [][]byte {
+ t.Helper()
+ var updates [][]byte
+ for {
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ updates = append(updates, packet)
+ if binary.BigEndian.Uint32(packet[20:24]) == 0x5f52412e {
+ return updates
+ }
+ }
+}
+
+func TestOriginalPopulationsAreSharedAndZoneScoped(t *testing.T) {
+ world := newServer()
+ var clients []net.Conn
+ zones := []uint32{950, 950, 952, 954, 646}
+ for _, zone := range zones {
+ player := world.newCharacter()
+ player.playfield = zone
+ client, connection := net.Pipe()
+ clients = append(clients, client)
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ }
+ var populations []map[uint32][]byte
+
+ for index, client := range clients {
+ cookie := make([]byte, 12)
+ binary.BigEndian.PutUint32(cookie, uint32(index+1))
+ client.Write(systemPacket(0x1b, cookie))
+ population := make(map[uint32][]byte)
+ for _, packet := range readWorldUpdates(t, client) {
+ if binary.BigEndian.Uint32(packet[20:24]) == 0x271b3a6b && binary.BigEndian.Uint32(packet[37:41])&1 != 0 {
+ population[binary.BigEndian.Uint32(packet[28:32])] = packet
+ }
+ }
+ populations = append(populations, population)
+ if index == 1 {
+ if _, err := readPacket(clients[0]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+
+ if len(populations[0]) != 48 || len(populations[1]) != 48 || len(populations[2]) != 56 || len(populations[3]) != 86 || len(populations[4]) != 1834 {
+ t.Fatalf("population counts: %d, %d, %d, %d, %d", len(populations[0]), len(populations[1]), len(populations[2]), len(populations[3]), len(populations[4]))
+ }
+ var leet []byte
+ for id, packet := range populations[0] {
+ if populations[1][id] == nil || !bytes.Equal(packet[20:], populations[1][id][20:]) {
+ t.Fatalf("NPC %d differs between players", id)
+ }
+ if populations[2][id] != nil || populations[3][id] != nil || populations[4][id] != nil {
+ t.Fatalf("Omni NPC %d leaked into another zone", id)
+ }
+ if string(packet[70:75]) == "Leet\x00" {
+ leet = packet
+ }
+ }
+ for index := 2; index < len(populations); index++ {
+ for _, packet := range populations[index] {
+ if binary.BigEndian.Uint32(packet[41:45]) != zones[index] || binary.BigEndian.Uint32(packet[12:16]) != uint32(index+1) {
+ t.Fatalf("NPC zone or recipient: %x", packet)
+ }
+ }
+ }
+ if leet[75] != 1 || binary.BigEndian.Uint32(leet[84:88]) != 17655 {
+ t.Fatalf("Leet level and appearance: %x", leet)
+ }
+}
+
+func TestEveryAuthoredPopulationIsSent(t *testing.T) {
+ data, err := os.ReadFile("tools/original-npc-spawns.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var catalog []struct {
+ Playfield uint32
+ Districts []struct {
+ SpawnGroups []struct{ Count int } `json:"spawn_groups"`
+ FixedSpawns []json.RawMessage `json:"fixed_spawns"`
+ }
+ }
+ if err := json.Unmarshal(data, &catalog); err != nil {
+ t.Fatal(err)
+ }
+ world := newServer()
+ total, populated := 0, 0
+ var guard, highLevel []byte
+
+ for _, playfield := range catalog {
+ if playfield.Playfield == 100 || playfield.Playfield == 102 || playfield.Playfield == 103 || playfield.Playfield == 1410 {
+ continue
+ }
+ requested := 0
+ for _, district := range playfield.Districts {
+ requested += len(district.FixedSpawns)
+ for _, group := range district.SpawnGroups {
+ requested += group.Count
+ }
+ }
+ if requested == 0 {
+ continue
+ }
+ player := world.newCharacter()
+ player.playfield = playfield.Playfield
+ client, connection := net.Pipe()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie := make([]byte, 12)
+ binary.BigEndian.PutUint32(cookie, player.id)
+ client.Write(systemPacket(0x1b, cookie))
+ count := 0
+ for _, packet := range readWorldUpdates(t, client) {
+ if binary.BigEndian.Uint32(packet[20:24]) != 0x271b3a6b || binary.BigEndian.Uint32(packet[37:41])&1 == 0 {
+ continue
+ }
+ count++
+ if binary.BigEndian.Uint32(packet[41:45]) != playfield.Playfield || binary.BigEndian.Uint32(packet[12:16]) != player.id {
+ t.Fatalf("incorrect NPC zone or recipient: %x", packet)
+ }
+ name := string(packet[70 : 69+int(packet[69])])
+ if playfield.Playfield == 950 && name == "Placeholder OTBG" {
+ guard = packet
+ }
+ if playfield.Playfield == 566 && name == "Placeholder FEPA" && binary.BigEndian.Uint32(packet[37:41])&0x1000 != 0 {
+ highLevel = packet
+ }
+ }
+ client.Close()
+ if count != requested {
+ t.Fatalf("playfield %d: got %d NPCs, disc requests %d", playfield.Playfield, count, requested)
+ }
+ total += count
+ populated++
+ }
+
+ if total != 62175 || populated != 226 {
+ t.Fatalf("coverage: %d NPCs in %d playfields", total, populated)
+ }
+ if len(guard) < 195 || binary.BigEndian.Uint32(guard[37:41]) != 0x2d1 || binary.BigEndian.Uint32(guard[134:138]) != 40682 || !bytes.Equal(guard[177:195], []byte("hands\x00\x00\x00\x22\x45\x00\x00\x00\x00\x00\x00\x00\x00")) {
+ t.Fatalf("human NPC head and hand material: %x", guard)
+ }
+ if binary.BigEndian.Uint32(guard[96:100]) != 26092 {
+ t.Fatal("human NPC did not receive the original Solitus model")
+ }
+ if len(highLevel) < 91 || binary.BigEndian.Uint32(highLevel[37:41]) != 0x1241 || binary.BigEndian.Uint16(highLevel[87:89]) != 400 {
+ t.Fatalf("original fixed NPC level: %x", highLevel)
+ }
+}
diff --git a/server/playfields.go b/server/playfields.go
@@ -0,0 +1,385 @@
+package main
+
+type playfield struct {
+ name string
+ origin [2]uint32
+ spawn [3]float32
+ unavailable bool
+}
+
+// Map names and spawn coordinates extracted from the original release assets.
+var playfields = map[uint32]playfield{
+ 100: {name: "Needed PF-stuff", unavailable: true},
+ 102: {name: "Monster and NPC dependencies", unavailable: true},
+ 103: {name: "Shop and Item Dependencies", unavailable: true},
+ 152: {name: "TheGrid2(dng)", spawn: [3]float32{206.0, 0.0, 188.0}},
+ 320: {name: "AutocontentMidtech(dung)", spawn: [3]float32{28.0, 5.0, 380.0}},
+ 321: {name: "AutocontentHITech(dung)", spawn: [3]float32{30.0, 5.0, 368.0}},
+ 322: {name: "Autocontentdungcave(dung)", spawn: [3]float32{28.0, 4.5, 338.0}},
+ 324: {name: "AutocontentClan(dung)", spawn: [3]float32{32.0, 5.0, 378.0}},
+ 331: {name: "ACD tarm (dng)", spawn: [3]float32{24.0, 0.0, 368.0}},
+ 341: {name: "ACD Grey Caves-Mines dng", spawn: [3]float32{128.0, 5.0, 182.0}},
+ 346: {name: "ACD Omnilab (dng)", spawn: [3]float32{12.0, 10.0, 388.0}},
+ 351: {name: "ACD Subway - Ventil (dng)", spawn: [3]float32{18.0, 9.9999, 386.0}},
+ 500: {name: "Parnassos", spawn: [3]float32{300.0, 0.5, 240.0}},
+ 505: {name: "Avalon", spawn: [3]float32{1720.0, 11.5, 2320.0}},
+ 510: {name: "Broken Crest", unavailable: true},
+ 515: {name: "The Endless Plains", unavailable: true},
+ 520: {name: "Sandsend", unavailable: true},
+ 525: {name: "Sparta", unavailable: true},
+ 530: {name: "Striate Rubi", unavailable: true},
+ 535: {name: "The Big One", unavailable: true},
+ 540: {name: "Old Athen", spawn: [3]float32{400.0, 14.5, 400.0}},
+ 545: {name: "West Athens", spawn: [3]float32{400.0, 5.7, 400.0}},
+ 550: {name: "Athen Shire", spawn: [3]float32{1520.0, 48.3, 1200.0}},
+ 551: {name: "Wailing Wastes", spawn: [3]float32{1520.0, 27.9, 2000.0}},
+ 555: {name: "Dry Wastes", unavailable: true},
+ 560: {name: "Mort", spawn: [3]float32{1960.0, 36.3, 2000.0}},
+ 565: {name: "Newland Desert", spawn: [3]float32{1960.0, 37.4, 1640.0}},
+ 566: {name: "Newland City GOLD", spawn: [3]float32{300.0, 32.9, 300.0}},
+ 567: {name: "Newland", spawn: [3]float32{1000.0, 43.9, 740.0}},
+ 570: {name: "The Perpetual Wastelands", spawn: [3]float32{2160.0, 68.6, 1840.0}},
+ 575: {name: "Plains of Salt", unavailable: true},
+ 580: {name: "Three Craters", unavailable: true},
+ 585: {name: "Aegean", spawn: [3]float32{1320.0, 21.5, 1560.0}},
+ 586: {name: "Wartorn Valley", spawn: [3]float32{620.0, 8.6, 660.0}},
+ 590: {name: "Central Artery Valley", spawn: [3]float32{1920.0, 12.2, 1680.0}},
+ 595: {name: "Deep Artery Valley", spawn: [3]float32{1800.0, 39.7, 2200.0}},
+ 600: {name: "Varmint Woods", spawn: [3]float32{2300.0, 16.4, 1700.0}},
+ 605: {name: "Belial Forest GOLD", spawn: [3]float32{1800.0, 30.3, 1720.0}},
+ 610: {name: "Southern Artery Valley", spawn: [3]float32{1920.0, 22.7, 1600.0}},
+ 615: {name: "Southern Fouls Hills", spawn: [3]float32{1560.0, 31.7, 1800.0}},
+ 620: {name: "Eastern Fouls Plains", spawn: [3]float32{1560.0, 25.1, 2200.0}},
+ 625: {name: "Milky Way", spawn: [3]float32{2620.0, 45.2, 1540.0}},
+ 630: {name: "Pleasant Meadows", spawn: [3]float32{1800.0, 0.5, 1560.0}},
+ 635: {name: "Stret East Bank GOLD", spawn: [3]float32{1200.0, 49.7, 1720.0}},
+ 640: {name: "Tir", spawn: [3]float32{400.0, 8.5, 400.0}},
+ 645: {name: "Tir County", unavailable: true},
+ 646: {name: "Tir County", spawn: [3]float32{1820.0, 16.4, 920.0}},
+ 647: {name: "Greater Tir County", spawn: [3]float32{1820.0, 21.2, 1740.0}},
+ 650: {name: "Upper Stret East Bank GOLD", spawn: [3]float32{1200.0, 7.1, 1680.0}},
+ 655: {name: "Andromeda", spawn: [3]float32{2600.0, 0.5, 1520.0}},
+ 660: {name: "Bay of Rome", unavailable: true},
+ 665: {name: "Broken Shores", spawn: [3]float32{1320.0, 3.9, 2600.0}},
+ 670: {name: "Clondyke GOLD", spawn: [3]float32{1600.0, 8.7, 2360.0}},
+ 675: {name: "Coast of Peace", unavailable: true},
+ 680: {name: "Coasts of Winds", unavailable: true},
+ 685: {name: "Galway County GOLD", spawn: [3]float32{1560.0, 39.5, 1560.0}},
+ 687: {name: "Galway Shire GOLD", spawn: [3]float32{640.0, 24.1, 1240.0}},
+ 690: {name: "Jobe", unavailable: true},
+ 695: {name: "Lush Fields", spawn: [3]float32{2000.0, 12.3, 2000.0}},
+ 696: {name: "Mutant Domain", spawn: [3]float32{720.0, 11.9, 900.0}},
+ 700: {name: "Omni1-HEADQUARTER", spawn: [3]float32{600.0, 9.3, 400.0}},
+ 705: {name: "Omni1 Entertainment", spawn: [3]float32{600.0, 4.1, 600.0}},
+ 710: {name: "Omni-1 Trade", spawn: [3]float32{400.0, 17.5, 400.0}},
+ 715: {name: "Omni Forest", unavailable: true},
+ 716: {name: "Omni Forest", spawn: [3]float32{680.0, 38.1, 1800.0}},
+ 717: {name: "Greater Omni Forest", spawn: [3]float32{1300.0, 0.5, 1800.0}},
+ 720: {name: "Plains of Divaad", unavailable: true},
+ 725: {name: "Reck Peninsula", unavailable: true},
+ 730: {name: "Rome Park", spawn: [3]float32{320.0, 14.1, 320.0}},
+ 735: {name: "Rome Blue", spawn: [3]float32{500.0, 17.9, 320.0}},
+ 740: {name: "Rome Green", spawn: [3]float32{500.0, 14.1, 320.0}},
+ 745: {name: "Sea of Jobe", unavailable: true},
+ 750: {name: "The Reck", unavailable: true},
+ 755: {name: "The Spur", unavailable: true},
+ 760: {name: "4 Holes", spawn: [3]float32{1200.0, 14.1, 1400.0}},
+ 765: {name: "Gangly Mountains", unavailable: true},
+ 770: {name: "Great Cathedral Park", unavailable: true},
+ 775: {name: "Kapar", unavailable: true},
+ 780: {name: "Nebula Mountains", unavailable: true},
+ 785: {name: "Road to Kapar", unavailable: true},
+ 790: {name: "Stret West Bank", spawn: [3]float32{1400.0, 0.5, 1840.0}},
+ 791: {name: "Holes in the Wall", spawn: [3]float32{660.0, 1.3, 1180.0}},
+ 795: {name: "The Longest Road", spawn: [3]float32{2320.0, 44.5, 1000.0}},
+ 800: {name: "Borealis", origin: [2]uint32{37107, 38360}, spawn: [3]float32{679.625, 74.75, 537.875}},
+ 896: {name: "Character Creation Lab Dng", spawn: [3]float32{224.0, 0.0, 200.0}},
+ 950: {name: "Omni Training", spawn: [3]float32{52.625, 14.75, 56.875}},
+ 952: {name: "Clan Training", spawn: [3]float32{120.0, 15.3, 120.0}},
+ 954: {name: "Neutral Training", spawn: [3]float32{160.0, 14.3, 120.0}},
+ 1001: {name: "Senitel rec_centre (wine) GOLD", spawn: [3]float32{188.0, 0.0, 144.0}},
+ 1002: {name: "medical/eating (wine) GOLD", spawn: [3]float32{194.0, 0.0, 146.0}},
+ 1003: {name: "Wine hq (wine) GOLD", spawn: [3]float32{174.0, 0.0, 144.0}},
+ 1004: {name: "barracks (wine) GOLD", spawn: [3]float32{168.0, 0.0, 156.0}},
+ 1005: {name: "storage (wine) GOLD", spawn: [3]float32{172.0, 0.0, 174.0}},
+ 1011: {name: "2HO HQ (streteast) GOLD", spawn: [3]float32{186.0, 0.0, 200.0}},
+ 1012: {name: "2HO satellite (streteast) GOLD", spawn: [3]float32{172.0, 0.0, 190.0}},
+ 1021: {name: "OMni barracks (USEB) GOLD", spawn: [3]float32{158.0, 0.0, 162.0}},
+ 1031: {name: "Avalon omni barracks", spawn: [3]float32{212.0, 0.0, 192.0}},
+ 1136: {name: "Mir shop clan", spawn: [3]float32{152.0, 5.0, 198.0}},
+ 1137: {name: "mir shop omni", spawn: [3]float32{152.0, 5.0, 192.0}},
+ 1180: {name: "ord_smarket_clan_basic", spawn: [3]float32{208.0, 5.0, 194.0}},
+ 1181: {name: "ord_smarket_clan_advanced", spawn: [3]float32{194.0, 5.0, 188.0}},
+ 1182: {name: "ord_smarket_clan_sup", spawn: [3]float32{184.0, 5.0, 164.0}},
+ 1183: {name: "ord_smarket_omni_basic", spawn: [3]float32{194.0, 5.0, 152.0}},
+ 1184: {name: "ord_smarket_omni_advanced", spawn: [3]float32{220.0, 5.0, 132.0}},
+ 1185: {name: "ord_smarket_omni_sup", spawn: [3]float32{206.0, 5.0, 120.0}},
+ 1186: {name: "ord_smarket_neut_basic", spawn: [3]float32{176.0, 5.0, 122.0}},
+ 1187: {name: "ord_smarket_neut_advanced", spawn: [3]float32{206.0, 5.0, 134.0}},
+ 1189: {name: "spec_smarket_clan_advanced", spawn: [3]float32{182.0, 5.0, 130.0}},
+ 1190: {name: "spec_smarket_clan_sup", spawn: [3]float32{180.0, 5.0, 128.0}},
+ 1191: {name: "spec_smarket_omni_advanced", spawn: [3]float32{172.0, 5.0, 138.0}},
+ 1192: {name: "spec_smarket_omni_sup", spawn: [3]float32{170.0, 5.0, 144.0}},
+ 1193: {name: "spec_smarket_neut_basic", spawn: [3]float32{202.0, 5.0, 122.0}},
+ 1211: {name: "basicomniapartment dng", spawn: [3]float32{140.0, 0.0, 106.0}},
+ 1231: {name: "Clan Small Clan Apartment", spawn: [3]float32{180.0, 5.0, 258.0}},
+ 1232: {name: "Clan Medium Clan Apartment", spawn: [3]float32{186.0, 5.0, 222.0}},
+ 1233: {name: "Clan Big Clan Apartment", spawn: [3]float32{136.0, 3.0, 208.0}},
+ 1241: {name: "Neutral Small Clan Apartment", spawn: [3]float32{142.0, 5.0, 216.0}},
+ 1242: {name: "Neutral Medium Clan Apartment", spawn: [3]float32{154.0, 5.0, 202.0}},
+ 1243: {name: "Neutral Big Clan Apartment", spawn: [3]float32{166.0, 4.9958, 182.0}},
+ 1251: {name: "Omni Small Guild", spawn: [3]float32{176.0, 5.1232, 180.0}},
+ 1321: {name: "tir clanbuilding2 dng", spawn: [3]float32{206.0, 0.0, 290.0}},
+ 1322: {name: "tir clanbuilding1 dng", spawn: [3]float32{212.0, 0.0001, 206.0}},
+ 1323: {name: "tir clanbuilding9 dng", spawn: [3]float32{120.0, 0.0, 284.0}},
+ 1324: {name: "tir clanbuilding11 dng", spawn: [3]float32{158.0, 0.0, 286.0}},
+ 1325: {name: "tir clanbuilding12 dng", spawn: [3]float32{156.0, 0.0, 280.0}},
+ 1326: {name: "tir clanbuilding3", spawn: [3]float32{210.0, 0.0, 286.0}},
+ 1327: {name: "tir clanbuilding_pod4 dng", spawn: [3]float32{196.0, 0.0, 196.0}},
+ 1328: {name: "tir clanbuilding5 dng", spawn: [3]float32{282.0, 0.0, 256.0}},
+ 1329: {name: "tir clanbuilding6 dng", spawn: [3]float32{126.0, 0.0, 206.0}},
+ 1330: {name: "tir clanbuilding7 dng", spawn: [3]float32{184.0, 0.0, 174.0}},
+ 1404: {name: "Home Citadel", spawn: [3]float32{190.0, 4.0173, 222.0}},
+ 1405: {name: "clanapartment", spawn: [3]float32{182.0, 0.0, 184.0}},
+ 1406: {name: "omniapartment", spawn: [3]float32{190.0, 0.0, 186.0}},
+ 1407: {name: "neutralapartment", spawn: [3]float32{188.0, 0.0, 144.0}},
+ 1410: {name: "items", unavailable: true},
+ 1421: {name: "avalon_building3 dng", spawn: [3]float32{188.0, 5.0, 150.0}},
+ 1422: {name: "avalon_building4 dng", spawn: [3]float32{200.0, 5.0, 166.0}},
+ 1423: {name: "avalon_building5", spawn: [3]float32{230.0, 5.0, 144.0}},
+ 1426: {name: "Clan Registration dng", spawn: [3]float32{168.0, 5.0, 234.0}},
+ 1427: {name: "Omni registration dng", spawn: [3]float32{198.0, 5.0, 168.0}},
+ 1428: {name: "Neutral organisation dng", spawn: [3]float32{198.0, 5.0, 158.0}},
+ 1501: {name: "omnimine_hq_building_06", spawn: [3]float32{178.0, 10.0, 194.0}},
+ 1502: {name: "omnimine_hq_building_02", spawn: [3]float32{198.0, 10.0, 160.0}},
+ 1503: {name: "omnimine_hq_building_04", spawn: [3]float32{212.0, 5.0, 138.0}},
+ 1504: {name: "omnimine_hq_building_07", spawn: [3]float32{194.0, 35.0, 170.0}},
+ 1505: {name: "omnimine_hq_building_08", spawn: [3]float32{190.0, 5.0, 176.0}},
+ 1506: {name: "omnimine_hq_building_09", spawn: [3]float32{204.0, 5.0, 130.0}},
+ 1507: {name: "omnimine_hq_building10", spawn: [3]float32{200.0, 5.0, 112.0}},
+ 1510: {name: "Neutral Insurance building", spawn: [3]float32{148.0, 0.0, 198.0}},
+ 1511: {name: "Neutral Mission building", spawn: [3]float32{146.0, 0.0, 198.0}},
+ 1601: {name: "athens_clanhouse1 VP dng", spawn: [3]float32{206.0, 0.0, 122.0}},
+ 1602: {name: "athens_clanhouse3 VP dng", spawn: [3]float32{196.0, 5.0, 158.0}},
+ 1603: {name: "athens_clanhouse4 VP dng", spawn: [3]float32{208.0, 5.0, 166.0}},
+ 1604: {name: "athens_clanhouse12 VP dng", spawn: [3]float32{182.0, 5.0, 138.0}},
+ 1611: {name: "Swamp_house01 VP dng", spawn: [3]float32{154.0, 5.0, 166.0}},
+ 1612: {name: "Swamp_house02", spawn: [3]float32{186.0, 5.0, 126.0}},
+ 1613: {name: "swamp_house03 VP dng", spawn: [3]float32{202.0, 5.0, 126.0}},
+ 1614: {name: "Swamp_house04 VP dng", spawn: [3]float32{170.0, 5.0, 86.0}},
+ 1621: {name: "wood_shack_01 VP dng", spawn: [3]float32{202.0, 5.0, 162.0}},
+ 1622: {name: "wood_shack_02 VP dng", spawn: [3]float32{198.0, 10.0, 156.0}},
+ 1623: {name: "wood_shack_03 VP dng", spawn: [3]float32{200.0, 10.0, 140.0}},
+ 1624: {name: "wood_shack_04 VP dng", spawn: [3]float32{210.0, 10.0, 144.0}},
+ 1625: {name: "wood_shack_05 VP dng", spawn: [3]float32{204.0, 10.0, 154.0}},
+ 1626: {name: "wood_shack_06 VP dng", spawn: [3]float32{224.0, 5.0, 170.0}},
+ 1627: {name: "wood_shack_07 VP dng", spawn: [3]float32{198.0, 5.0, 152.0}},
+ 1641: {name: "lowtech_building1 VP dng", spawn: [3]float32{190.0, 5.0, 170.0}},
+ 1642: {name: "lowtech_building2 VP dng", spawn: [3]float32{190.0, 5.0, 166.0}},
+ 1643: {name: "lowtech_building3 VP dng", spawn: [3]float32{152.0, 5.0, 158.0}},
+ 1644: {name: "lowtech_building4 VP dng", spawn: [3]float32{218.0, 5.0, 164.0}},
+ 1645: {name: "lowtech_building5 VP dng", spawn: [3]float32{220.0, 5.0, 164.0}},
+ 1646: {name: "lowtech_building6 VP dng", spawn: [3]float32{194.0, 5.0, 162.0}},
+ 1647: {name: "lowtech_building7 VP dng", spawn: [3]float32{196.0, 5.0, 148.0}},
+ 1648: {name: "lowtech_waterwell VP dng", spawn: [3]float32{190.0, 5.0, 160.0}},
+ 1651: {name: "rome_shopbuilding1 VP dng", spawn: [3]float32{210.0, 10.0, 162.0}},
+ 1652: {name: "rome_simplebuilding VP dng", spawn: [3]float32{204.0, 5.0, 160.0}},
+ 1653: {name: "rome_simplebuilding1 VP dng", spawn: [3]float32{182.0, 5.0, 152.0}},
+ 1661: {name: "rhino_house1 VP dng", spawn: [3]float32{198.0, 10.0, 152.0}},
+ 1662: {name: "rhino_house2 VP dng", spawn: [3]float32{188.0, 5.0, 188.0}},
+ 1663: {name: "rhino_house3 VP dng", spawn: [3]float32{214.0, 5.0, 170.0}},
+ 1671: {name: "reck_trading_outpost_bunker1 VP", spawn: [3]float32{194.0, 5.0, 180.0}},
+ 1672: {name: "reck_trading_outpost_bunker2 VP", spawn: [3]float32{190.0, 5.0, 200.0}},
+ 1674: {name: "reck_trading_outpost_bunker4 VP", spawn: [3]float32{174.0, 5.0, 190.0}},
+ 1675: {name: "reck_trading_outpost_bunker5 VP", spawn: [3]float32{164.0, 5.0, 194.0}},
+ 1701: {name: "Home VP dng 1 medium", spawn: [3]float32{202.0, 5.0, 128.0}},
+ 1702: {name: "Home VP dng 2 big", spawn: [3]float32{236.0, 5.0, 98.0}},
+ 1703: {name: "Home VP dng 3 small", spawn: [3]float32{204.0, 5.0, 136.0}},
+ 1711: {name: "Factory VP dng barracks", spawn: [3]float32{170.0, 5.0, 142.0}},
+ 1712: {name: "Factory VP dng factory", spawn: [3]float32{174.0, 5.0, 146.0}},
+ 1721: {name: "LD VP dng 1", spawn: [3]float32{190.0, 5.0, 124.0}},
+ 1722: {name: "LD VP dng 2", spawn: [3]float32{192.0, 5.0, 116.0}},
+ 1741: {name: "enigma_tree01", spawn: [3]float32{188.0, 5.0, 134.0}},
+ 1742: {name: "enigma_tree02", spawn: [3]float32{204.0, 5.0, 154.0}},
+ 1743: {name: "enigma_tree03", spawn: [3]float32{184.0, 5.0, 140.0}},
+ 1826: {name: "Dancing Atrox Bar", spawn: [3]float32{222.0, 5.0, 180.0}},
+ 1827: {name: "Omni Military Barracks", spawn: [3]float32{206.0, 5.0, 172.0}},
+ 1836: {name: "Baboons Nightclub", spawn: [3]float32{214.0, 4.0, 98.0}},
+ 1846: {name: "McRiid's Office", spawn: [3]float32{150.0, 5.0, 86.0}},
+ 1862: {name: "The Smugglers Den", spawn: [3]float32{124.0, 3.5, 146.0}},
+ 1866: {name: "The HQ of Omni-Mine", spawn: [3]float32{128.0, 5.0, 190.0}},
+ 1886: {name: "Versailles Tower", spawn: [3]float32{194.0, 22.9991, 172.0}},
+ 1887: {name: "Treepine Hut", spawn: [3]float32{204.0, 5.0, 278.0}},
+ 1891: {name: "The Happy Rebel Inn", spawn: [3]float32{182.0, 5.0, 220.0}},
+ 1892: {name: "Enjoy it While it Lasts", spawn: [3]float32{214.0, 5.0, 236.0}},
+ 1893: {name: "The Cup", spawn: [3]float32{216.0, 5.0, 210.0}},
+ 1894: {name: "Clan Registration Office", spawn: [3]float32{214.0, 5.0, 226.0}},
+ 1901: {name: "Neutral Organisation Office", spawn: [3]float32{152.0, 0.0, 246.0}},
+ 1902: {name: "Neuters 'R' Us", spawn: [3]float32{166.0, 0.0007, 216.0}},
+ 2001: {name: "clan_basic_weapons_shop", spawn: [3]float32{212.0, 5.0, 162.0}},
+ 2002: {name: "clan_basic_armor_shop", spawn: [3]float32{230.0, 5.0, 170.0}},
+ 2003: {name: "clan_basic_pharmasist_shop", spawn: [3]float32{198.0, 5.0, 166.0}},
+ 2004: {name: "clan_basic_clothes_shop", spawn: [3]float32{220.0, 5.0, 162.0}},
+ 2005: {name: "clan_basic_implants_shop", spawn: [3]float32{196.0, 5.0, 170.0}},
+ 2010: {name: "clan_advanced_weapons_shop", spawn: [3]float32{196.0, 5.0, 194.0}},
+ 2011: {name: "clan_advanced_armor_shop", spawn: [3]float32{206.0, 5.0, 186.0}},
+ 2012: {name: "clan_advanced_pharmacist_shop", spawn: [3]float32{202.0, 5.0, 198.0}},
+ 2013: {name: "clan_advanced_implants_shop", spawn: [3]float32{200.0, 5.0, 200.0}},
+ 2020: {name: "clan_sup_weapons_shop", spawn: [3]float32{216.0, 5.0, 218.0}},
+ 2021: {name: "clan_sup_armor_shop", spawn: [3]float32{212.0, 5.0, 212.0}},
+ 2022: {name: "clan_sup_pharmacist_shop", spawn: [3]float32{220.0, 5.0, 214.0}},
+ 2023: {name: "clan_sup_implants_shop", spawn: [3]float32{216.0, 5.0, 212.0}},
+ 2030: {name: "omni_basic_weapons_shop", spawn: [3]float32{116.0, 5.0, 214.0}},
+ 2031: {name: "omni_basic_armor_shop", spawn: [3]float32{114.0, 5.0, 216.0}},
+ 2032: {name: "omni_basic_pharmacist", spawn: [3]float32{118.0, 5.0, 210.0}},
+ 2033: {name: "omni_basic_clothes_shop", spawn: [3]float32{118.0, 5.0, 218.0}},
+ 2034: {name: "omni_basic_implants_shop", spawn: [3]float32{120.0, 5.0, 220.0}},
+ 2040: {name: "omni_advanced_weapons_shop", spawn: [3]float32{204.0, 5.0, 192.0}},
+ 2041: {name: "omni_advanced_armor_shop", spawn: [3]float32{200.0, 5.0, 200.0}},
+ 2042: {name: "omni_advanced_pharmacist_shop", spawn: [3]float32{200.0, 5.0, 200.0}},
+ 2043: {name: "omni_advanced_implants_shop", spawn: [3]float32{204.0, 5.0, 204.0}},
+ 2050: {name: "omni_sup_weapons_shop", spawn: [3]float32{194.0, 5.0, 194.0}},
+ 2051: {name: "omni_sup_armor_shop", spawn: [3]float32{198.0, 5.0, 204.0}},
+ 2052: {name: "omni_sup_pharmacist_shop", spawn: [3]float32{196.0, 5.0, 204.0}},
+ 2053: {name: "omni_sup_implants_shop", spawn: [3]float32{204.0, 5.0, 202.0}},
+ 2060: {name: "neut_basic_weapon _shop", spawn: [3]float32{170.0, 5.0, 164.0}},
+ 2061: {name: "neut_basic_armor_shop", spawn: [3]float32{210.0, 5.0, 184.0}},
+ 2062: {name: "neut_basic_pharmacist_shop", spawn: [3]float32{196.0, 5.0, 194.0}},
+ 2063: {name: "neut_basic_clothes_shop", spawn: [3]float32{218.0, 5.0, 174.0}},
+ 2064: {name: "neut_basic_implants_shop", spawn: [3]float32{192.0, 5.0, 158.0}},
+ 2070: {name: "neut_advanced_weapons_shop", spawn: [3]float32{210.0, 5.0, 192.0}},
+ 2071: {name: "neut_advanced_armor_shop", spawn: [3]float32{206.0, 5.0, 204.0}},
+ 2072: {name: "neut_advanced_pharmacist_shop", spawn: [3]float32{206.0, 5.0, 200.0}},
+ 2073: {name: "neut_advanced_implants_shop", spawn: [3]float32{206.0, 5.0, 200.0}},
+ 2096: {name: "4holes Fashion", spawn: [3]float32{162.0, 5.0, 234.0}},
+ 3000: {name: "Omni-1 Entertainment Backyard 1", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3001: {name: "Omni-1 Entertainment Backyard 2", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3002: {name: "Omni-1 Entertainment Backyard 3", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3003: {name: "Omni-1 Entertainment Backyard 4", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3004: {name: "Omni-1 Entertainment Backyard 5", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3005: {name: "Omni-1 Entertainment Backyard 6", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3006: {name: "Omni-1 Entertainment Backyard 7", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3007: {name: "Omni-1 Entertainment Backyard 8", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3008: {name: "Omni-1 Entertainment Backyard 9", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3009: {name: "Omni-1 Entertainment Backyard 10", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3010: {name: "Omni-1 Entertainment Backyard 11", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3011: {name: "Omni-1 Entertainment Backyard 12", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3012: {name: "Omni-1 Entertainment Backyard 13", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3013: {name: "Omni-1 Entertainment Backyard 14", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3014: {name: "Omni-1 Entertainment Backyard 15", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3015: {name: "Omni-1 Entertainment Backyard 16", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3016: {name: "Omni-1 Entertainment Backyard 17", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3017: {name: "Omni-1 Entertainment Backyard 18", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3018: {name: "Omni-1 Entertainment Backyard 19", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3019: {name: "Omni-1 Entertainment Backyard 20", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3020: {name: "Omni-1 Trade Backyard 1", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3021: {name: "Omni-1 Trade Backyard 2", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3022: {name: "Omni-1 Trade Backyard 3", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3023: {name: "Omni-1 Trade Backyard 4", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3024: {name: "Omni-1 Trade Backyard 5", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3025: {name: "Omni-1 Trade Backyard 6", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3026: {name: "Omni-1 Trade Backyard 7", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3027: {name: "Omni-1 Trade Backyard 8", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3028: {name: "Omni-1 Trade Backyard 9", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3029: {name: "Omni-1 Trade Backyard 10", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3030: {name: "Omni-1 Trade Backyard 11", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3031: {name: "Omni-1 Trade Backyard 12", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3032: {name: "Omni-1 Trade Backyard 13", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3033: {name: "Omni-1 Trade Backyard 14", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3034: {name: "Omni-1 Trade Backyard 15", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3035: {name: "Omni-1 Trade Backyard 16", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3036: {name: "Omni-1 Trade Backyard 17", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3037: {name: "Omni-1 Trade Backyard 18", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3038: {name: "Omni-1 Trade Backyard 19", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3039: {name: "Omni-1 Trade Backyard 20", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3040: {name: "Rome Blue Backyard 1", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3041: {name: "Rome Blue Backyard 2", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3042: {name: "Rome Blue Backyard 3", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3043: {name: "Rome Blue Backyard 4", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3044: {name: "Rome Blue Backyard 5", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3045: {name: "Rome Blue Backyard 6", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3046: {name: "Rome Blue Backyard 7", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3047: {name: "Rome Blue Backyard 8", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3048: {name: "Rome Blue Backyard 9", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3049: {name: "Rome Blue Backyard 10", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3050: {name: "Rome Green Backyard 1", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3051: {name: "Rome Green Backyard 2", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3052: {name: "Rome Green Backyard 3", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3053: {name: "Rome Green Backyard 4", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3054: {name: "Rome Green Backyard 5", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3055: {name: "Rome Green Backyard 6", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3056: {name: "Rome Green Backyard 7", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3057: {name: "Rome Green Backyard 8", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3058: {name: "Rome Green Backyard 9", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3059: {name: "Rome Green Backyard 10", spawn: [3]float32{100.0, 115.5, 120.0}},
+ 3060: {name: "Newland Backyard 1", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3061: {name: "Newland Backyard 2", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3062: {name: "Newland Backyard 3", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3063: {name: "Newland Backyard 4", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3064: {name: "Newland Backyard 5", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3065: {name: "Newland Backyard 6", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3066: {name: "Newland Backyard 7", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3067: {name: "Newland Backyard 8", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3068: {name: "Newland Backyard 9", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3069: {name: "Newland Backyard 10", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3070: {name: "Newland Backyard 11", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3071: {name: "Newland Backyard 12", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3080: {name: "Borealis Backyard 1", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3081: {name: "Borealis Backyard 2", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3082: {name: "Borealis Backyard 3", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3083: {name: "Borealis Backyard 4", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3084: {name: "Borealis Backyard 5", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3085: {name: "Borealis Backyard 6", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3086: {name: "Borealis Backyard 7", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3087: {name: "Borealis Backyard 8", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3088: {name: "Borealis Backyard 9", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3089: {name: "Borealis Backyard 10", spawn: [3]float32{100.0, 39.5, 100.0}},
+ 3100: {name: "Tir Backyard 1", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3101: {name: "Tir Backyard 2", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3102: {name: "Tir Backyard 3", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3103: {name: "Tir Backyard 4", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3104: {name: "Tir Backyard 5", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3105: {name: "Tir Backyard 6", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3106: {name: "Tir Backyard 7", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3107: {name: "Tir Backyard 8", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3108: {name: "Tir Backyard 9", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3109: {name: "Tir Backyard 10", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3110: {name: "Tir Backyard 11", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3111: {name: "Tir Backyard 12", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3112: {name: "Tir Backyard 13", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3113: {name: "Tir Backyard 14", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3114: {name: "Tir Backyard 15", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3115: {name: "Tir Backyard 16", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3116: {name: "Tir Backyard 17", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3117: {name: "Tir Backyard 18", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3120: {name: "Old Athen Backyard 1", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3121: {name: "Old Athen Backyard 2", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3122: {name: "Old Athen Backyard 3", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3123: {name: "Old Athen Backyard 4", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3124: {name: "Old Athen Backyard 5", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3125: {name: "Old Athen Backyard 6", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3126: {name: "Old Athen Backyard 7", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3127: {name: "Old Athen Backyard 8", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3128: {name: "Old Athen Backyard 9", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3129: {name: "Old Athen Backyard 10", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3130: {name: "Old Athen Backyard 11", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3131: {name: "Old Athen Backyard 12", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3132: {name: "Old Athen Backyard 13", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3133: {name: "Old Athen Backyard 14", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3134: {name: "Old Athen Backyard 15", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3135: {name: "Old Athen Backyard 16", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3136: {name: "Old Athen Backyard 17", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3137: {name: "Old Athen Backyard 18", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3138: {name: "Old Athen Backyard 19", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3139: {name: "Old Athen Backyard 20", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3140: {name: "West Athen Backyard 1", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3141: {name: "West Athen Backyard 2", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3142: {name: "West Athen Backyard 3", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3143: {name: "West Athen Backyard 4", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3144: {name: "West Athen Backyard 5", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3145: {name: "West Athen Backyard 6", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3146: {name: "West Athen Backyard 7", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3147: {name: "West Athen Backyard 8", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3148: {name: "West Athen Backyard 9", spawn: [3]float32{80.0, 25.5, 80.0}},
+ 3149: {name: "West Athen Backyard 10", spawn: [3]float32{80.0, 25.5, 80.0}},
+}
diff --git a/server/roaming.go b/server/roaming.go
@@ -0,0 +1,134 @@
+package main
+
+import (
+ "encoding/binary"
+ "log"
+ "math"
+ "math/rand/v2"
+ "time"
+)
+
+type npcRoaming struct {
+ home [3]float32
+ destination [3]float32
+ nextMove time.Time
+ moving bool
+}
+
+func (server *server) roamNPCs() {
+ ticker := time.NewTicker(250 * time.Millisecond)
+ defer ticker.Stop()
+ for now := range ticker.C {
+ server.advanceNPCs(now)
+ }
+}
+
+func (server *server) advanceNPCs(now time.Time) {
+ // Keep motion packets ordered with population reloads and zone initialization.
+ server.npcReloadMutex.Lock()
+ defer server.npcReloadMutex.Unlock()
+ server.mutex.Lock()
+ seconds := math.Min(now.Sub(server.lastNPCUpdate).Seconds(), 0.25)
+ server.lastNPCUpdate = now
+ clients := make(map[*worldClient]uint32)
+ zones := make(map[uint32]bool)
+ for id, client := range server.clients {
+ if client.ready {
+ clients[client] = server.characters[id].playfield
+ zones[server.characters[id].playfield] = true
+ }
+ }
+ updates := make(map[uint32][][]byte)
+ for _, character := range server.characters {
+ if character.roaming == nil || !zones[character.playfield] {
+ continue
+ }
+ if character.roaming.nextMove.IsZero() {
+ character.roaming.nextMove = now.Add(time.Duration(1+character.id%32) * 250 * time.Millisecond)
+ }
+ if now.Before(character.roaming.nextMove) {
+ continue
+ }
+
+ // Pick a nearby destination relative to home, so repeated walks never drift.
+ started := !character.roaming.moving
+ if !character.roaming.moving {
+ angle := rand.Float64() * 2 * math.Pi
+ distance := 4 * math.Sqrt(rand.Float64())
+ character.roaming.destination = [3]float32{
+ character.roaming.home[0] + float32(math.Sin(angle)*distance),
+ character.roaming.home[1],
+ character.roaming.home[2] + float32(math.Cos(angle)*distance),
+ }
+ character.roaming.moving = true
+ }
+ x := float64(character.roaming.destination[0] - character.position[0])
+ z := float64(character.roaming.destination[2] - character.position[2])
+ distance := math.Hypot(x, z)
+ angle := math.Atan2(x, z)
+ character.rotation = [4]float32{0, float32(math.Sin(angle / 2)), 0, float32(math.Cos(angle / 2))}
+ if started {
+ updates[character.playfield] = append(updates[character.playfield], npcMovementPacket(character, 1))
+ continue
+ }
+
+ // The original vehicle walks at 1.5 metres per second between commands.
+ step := 1.5 * seconds
+ action := uint32(0)
+ position := character.position
+ if distance <= step {
+ position = character.roaming.destination
+ character.roaming.moving = false
+ character.roaming.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second)
+ action = 2
+ } else {
+ position[0] += float32(x / distance * step)
+ position[2] += float32(z / distance * step)
+ }
+
+ // Follow changes in terrain height while preserving the authored ground offset.
+ if ground := server.terrain[character.playfield]; ground != nil {
+ home, available := ground.elevation(character.roaming.home[0], character.roaming.home[2])
+ if available {
+ height, inside := ground.elevation(position[0], position[2])
+ if inside {
+ position[1] = character.roaming.home[1] + height - home
+ } else {
+ position = character.position
+ character.roaming.moving = false
+ character.roaming.nextMove = now.Add(time.Duration(3+rand.IntN(6)) * time.Second)
+ action = 2
+ }
+ }
+ }
+ character.position = position
+ if action != 0 {
+ updates[character.playfield] = append(updates[character.playfield], npcMovementPacket(character, action))
+ }
+ }
+ server.mutex.Unlock()
+
+ // Every observer receives the same entity position, orientation and movement control.
+ for client, zone := range clients {
+ for _, packet := range updates[zone] {
+ if err := client.send(packet); err != nil {
+ log.Printf("NPC roaming: %v", err)
+ client.conn.Close()
+ break
+ }
+ }
+ }
+}
+
+func npcMovementPacket(character *character, action uint32) []byte {
+ // Original CharDCMove carries action, XYZ, quaternion and two trailing floats.
+ body := binary.BigEndian.AppendUint32(nil, action)
+ for _, value := range character.position {
+ body = binary.BigEndian.AppendUint32(body, math.Float32bits(value))
+ }
+ for _, value := range character.rotation {
+ body = binary.BigEndian.AppendUint32(body, math.Float32bits(value))
+ }
+ body = append(body, make([]byte, 8)...)
+ return n3Packet(0x54111123, 50000, character.id, body)
+}
diff --git a/server/roaming_test.go b/server/roaming_test.go
@@ -0,0 +1,275 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "math"
+ "net"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+func TestRoamingIsSharedBoundedAndZoneScoped(t *testing.T) {
+ data := strings.ReplaceAll(editedNPCData, "fixed_point", "authored_point") + `
+ - template_code: GUARD
+ name: Guard
+ monster_data: 26092
+ appearance: 789
+ level: 1
+ appearance_status: placeholder_creature
+ placement_status: authored_point
+ positions:
+ - [54, 14, 56]
+- id: 952
+ districts:
+ - groups:
+ - template_code: LEET
+ name: Leet
+ monster_data: 17655
+ appearance: 229
+ level: 1
+ appearance_status: placeholder_creature
+ placement_status: authored_point
+ positions:
+ - [100, 14, 100]
+`
+ useNPCData(t, data)
+ world := newServer()
+ var clients []net.Conn
+ for range 2 {
+ player := world.newCharacter()
+ client, connection := net.Pipe()
+ clients = append(clients, client)
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie := make([]byte, 12)
+ binary.BigEndian.PutUint32(cookie, player.id)
+ client.Write(systemPacket(0x1b, cookie))
+ readWorldUpdates(t, client)
+ if player.id == 2 {
+ readPacket(clients[0])
+ }
+ }
+ now := time.Now()
+
+ world.advanceNPCs(now)
+ done := make(chan struct{})
+ packets := make([][]byte, 2)
+ errors := make([]error, 2)
+ var readers sync.WaitGroup
+ for index, client := range clients {
+ readers.Add(1)
+ go func() {
+ defer readers.Done()
+ packets[index], errors[index] = readPacket(client)
+ }()
+ }
+ go func() { world.advanceNPCs(now.Add(8 * time.Second)); close(done) }()
+ readers.Wait()
+ for _, err := range errors {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ <-done
+
+ first, second := packets[0], packets[1]
+ if binary.BigEndian.Uint32(first[20:24]) != 0x54111123 || binary.BigEndian.Uint32(first[28:32]) != 1000000 {
+ t.Fatalf("creature movement: %x", first)
+ }
+ if !bytes.Equal(first[20:], second[20:]) || binary.BigEndian.Uint32(first[12:16]) != 1 || binary.BigEndian.Uint32(second[12:16]) != 2 {
+ t.Fatal("players received different NPC motion")
+ }
+ x := math.Float32frombits(binary.BigEndian.Uint32(first[40:44])) - 52
+ z := math.Float32frombits(binary.BigEndian.Uint32(first[48:52])) - 56
+ if x != 0 || z != 0 || binary.BigEndian.Uint32(first[36:40]) != 1 {
+ t.Fatalf("walk did not start at the current position: %x", first)
+ }
+ if world.characters[1000001].position != [3]float32{54, 14, 56} || world.characters[1000002].position != [3]float32{100, 14, 100} {
+ t.Fatal("human or unoccupied-zone NPC moved")
+ }
+ if math.Hypot(float64(world.characters[1000000].roaming.destination[0]-52), float64(world.characters[1000000].roaming.destination[2]-56)) > 4.001 {
+ t.Fatal("destination escaped the home radius")
+ }
+}
+
+func TestRoamingDoesNotResetPositionDuringWalk(t *testing.T) {
+ useNPCData(t, strings.ReplaceAll(editedNPCData, "fixed_point", "authored_point"))
+ world := newServer()
+ player := world.newCharacter()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie := make([]byte, 12)
+ binary.BigEndian.PutUint32(cookie, player.id)
+ client.Write(systemPacket(0x1b, cookie))
+ readWorldUpdates(t, client)
+ now := time.Now()
+ world.lastNPCUpdate = now
+ world.characters[1000000].roaming.destination = [3]float32{53.5, 14, 56}
+ world.characters[1000000].roaming.moving = true
+ world.characters[1000000].roaming.nextMove = now
+ var packets [][]byte
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ for {
+ packet, err := readPacket(client)
+ if err != nil {
+ return
+ }
+ packets = append(packets, packet)
+ }
+ }()
+
+ for tick := 1; tick <= 4; tick++ {
+ world.advanceNPCs(now.Add(time.Duration(tick) * 250 * time.Millisecond))
+ }
+ client.Close()
+ <-done
+
+ if len(packets) != 1 || binary.BigEndian.Uint32(packets[0][36:40]) != 2 {
+ t.Fatalf("received position resets during the walk: %x", packets)
+ }
+ if world.characters[1000000].position != [3]float32{53.5, 14, 56} {
+ t.Fatalf("walking speed did not match the original client: %v", world.characters[1000000].position)
+ }
+}
+
+func TestJoiningPlayerReceivesOngoingNPCMovement(t *testing.T) {
+ useNPCData(t, strings.ReplaceAll(editedNPCData, "fixed_point", "authored_point"))
+ world := newServer()
+ world.characters[1000000].position = [3]float32{53, 14, 56}
+ world.characters[1000000].roaming.moving = true
+ player := world.newCharacter()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie := make([]byte, 12)
+ binary.BigEndian.PutUint32(cookie, player.id)
+
+ client.Write(systemPacket(0x1b, cookie))
+ packets := readWorldUpdates(t, client)
+
+ var movement []byte
+ for _, packet := range packets {
+ if binary.BigEndian.Uint32(packet[20:24]) == 0x54111123 && binary.BigEndian.Uint32(packet[28:32]) == 1000000 {
+ movement = packet
+ }
+ }
+ if movement == nil || binary.BigEndian.Uint32(movement[36:40]) != 1 || math.Float32frombits(binary.BigEndian.Uint32(movement[40:44])) != 53 {
+ t.Fatalf("joining player did not receive ongoing movement: %x", movement)
+ }
+}
+
+func TestRoamingStopsAndPausesAtDestination(t *testing.T) {
+ useNPCData(t, strings.ReplaceAll(editedNPCData, "fixed_point", "authored_point"))
+ world := newServer()
+ player := world.newCharacter()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie := make([]byte, 12)
+ binary.BigEndian.PutUint32(cookie, player.id)
+ client.Write(systemPacket(0x1b, cookie))
+ readWorldUpdates(t, client)
+ now := time.Now()
+ world.characters[1000000].roaming.destination = [3]float32{52.125, 14, 56}
+ world.characters[1000000].roaming.moving = true
+ world.characters[1000000].roaming.nextMove = now
+ done := make(chan struct{})
+
+ go func() { world.advanceNPCs(now); close(done) }()
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-done
+ world.advanceNPCs(now.Add(250 * time.Millisecond))
+
+ if binary.BigEndian.Uint32(packet[36:40]) != 2 || world.characters[1000000].position != [3]float32{52.125, 14, 56} || world.characters[1000000].roaming.moving {
+ t.Fatal("NPC did not stop at its destination")
+ }
+ if world.characters[1000000].roaming.nextMove.Before(now.Add(3 * time.Second)) {
+ t.Fatal("NPC did not pause between walks")
+ }
+}
+
+func TestFixedCreatureDoesNotRoam(t *testing.T) {
+ useNPCData(t, editedNPCData)
+
+ world := newServer()
+
+ if world.characters[1000000].roaming != nil {
+ t.Fatal("fixed creature received roaming behavior")
+ }
+}
+
+func TestRoamingFollowsTerrainWithAuthoredOffset(t *testing.T) {
+ useNPCData(t, strings.ReplaceAll(editedNPCData, "fixed_point", "authored_point"))
+ world := newServer()
+ world.terrain[950] = &terrain{width: 1, height: 1, spacing: 128, scale: 1, heights: []byte{0, 64, 0, 64}}
+ player := world.newCharacter()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie := make([]byte, 12)
+ binary.BigEndian.PutUint32(cookie, player.id)
+ client.Write(systemPacket(0x1b, cookie))
+ readWorldUpdates(t, client)
+ now := time.Now()
+ world.characters[1000000].roaming.destination = [3]float32{52.25, 14, 56}
+ world.characters[1000000].roaming.moving = true
+ world.characters[1000000].roaming.nextMove = now
+ done := make(chan struct{})
+
+ go func() { world.advanceNPCs(now); close(done) }()
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-done
+
+ if world.characters[1000000].position != [3]float32{52.25, 14.125, 56} || math.Float32frombits(binary.BigEndian.Uint32(packet[44:48])) != 14.125 {
+ t.Fatalf("NPC did not follow the slope: %v", world.characters[1000000].position)
+ }
+}
+
+func TestRoamingStopsAtTerrainBoundary(t *testing.T) {
+ useNPCData(t, strings.ReplaceAll(editedNPCData, "fixed_point", "authored_point"))
+ world := newServer()
+ world.terrain[950] = &terrain{width: 1, height: 1, spacing: 64, scale: 1, heights: []byte{0, 32, 0, 32}}
+ player := world.newCharacter()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie := make([]byte, 12)
+ binary.BigEndian.PutUint32(cookie, player.id)
+ client.Write(systemPacket(0x1b, cookie))
+ readWorldUpdates(t, client)
+ now := time.Now()
+ world.characters[1000000].position = [3]float32{64, 20, 56}
+ world.characters[1000000].roaming.destination = [3]float32{64.25, 14, 56}
+ world.characters[1000000].roaming.moving = true
+ world.characters[1000000].roaming.nextMove = now
+ done := make(chan struct{})
+
+ go func() { world.advanceNPCs(now); close(done) }()
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-done
+
+ if binary.BigEndian.Uint32(packet[36:40]) != 2 || world.characters[1000000].position != [3]float32{64, 20, 56} || world.characters[1000000].roaming.moving {
+ t.Fatal("NPC walked beyond the terrain grid")
+ }
+}
diff --git a/server/state.go b/server/state.go
@@ -0,0 +1,114 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "log"
+ "math"
+ "net"
+ "sync"
+ "time"
+)
+
+type character struct {
+ id uint32
+ name string
+ playfield uint32
+ position [3]float32
+ rotation [4]float32
+ appearance uint16
+ monsterData uint32
+ level uint16
+ npc bool
+ roaming *npcRoaming
+}
+
+type worldClient struct {
+ conn net.Conn
+ mutex sync.Mutex
+ ready bool
+ id uint32
+}
+
+func (client *worldClient) send(packet []byte) error {
+ // Broadcasts and connection replies must not interleave on the TCP stream.
+ client.mutex.Lock()
+ defer client.mutex.Unlock()
+ packet = append([]byte(nil), packet...)
+ binary.BigEndian.PutUint32(packet[12:16], client.id)
+ _, err := client.conn.Write(packet)
+ return err
+}
+
+type server struct {
+ mutex sync.Mutex
+ npcReloadMutex sync.RWMutex
+ nextCharacter uint32
+ nextNPC uint32
+ characters map[uint32]*character
+ clients map[uint32]*worldClient
+ gameSeconds float64
+ clockStarted time.Time
+ lastNPCUpdate time.Time
+ terrain map[uint32]*terrain
+}
+
+func newServer() *server {
+ server := &server{
+ gameSeconds: 48600, clockStarted: time.Now(),
+ characters: make(map[uint32]*character),
+ clients: make(map[uint32]*worldClient),
+ }
+ ground, err := readTerrain()
+ if err != nil {
+ panic(err)
+ }
+ server.terrain = ground
+ // Create shared live instances from the editable NPC data.
+ spawns, err := readNPCSpawns()
+ if err != nil {
+ panic(err)
+ }
+ for _, spawn := range spawns {
+ server.characters[spawn.id] = &spawn
+ }
+ server.nextNPC = 1000000 + uint32(len(spawns))
+ return server
+}
+
+func (server *server) gameSeconds_locked() float64 {
+ // Rubi-Ka has 27-hour days and advances 15 game seconds per real second.
+ return math.Mod(server.gameSeconds+time.Since(server.clockStarted).Seconds()*15, 97200)
+}
+
+func (server *server) newCharacter() *character {
+ server.mutex.Lock()
+ defer server.mutex.Unlock()
+ server.nextCharacter++
+ character := &character{
+ id: server.nextCharacter, name: fmt.Sprintf("Local Explorer %d", server.nextCharacter),
+ playfield: 950, position: [3]float32{52.625, 14.75, 56.875 + float32((server.nextCharacter-1)%4)*3},
+ rotation: [4]float32{0, 0, 0, 1}, appearance: 0x315, level: 1,
+ }
+ server.characters[character.id] = character
+ return character
+}
+
+func (server *server) broadcast(playfield, exclude uint32, packet []byte) {
+ // Copy the connection list before performing any network writes.
+ server.mutex.Lock()
+ var clients []*worldClient
+ for id, client := range server.clients {
+ if id != exclude && client.ready && server.characters[id].playfield == playfield {
+ clients = append(clients, client)
+ }
+ }
+ server.mutex.Unlock()
+
+ for _, client := range clients {
+ if err := client.send(packet); err != nil {
+ log.Printf("World broadcast: %v", err)
+ client.conn.Close()
+ }
+ }
+}
diff --git a/server/terrain.go b/server/terrain.go
@@ -0,0 +1,65 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "math"
+ "os"
+)
+
+type terrain struct {
+ width, height int
+ spacing, scale float32
+ heights []byte
+}
+
+func readTerrain() (map[uint32]*terrain, error) {
+ data, err := os.ReadFile("data/terrain.bin")
+ if err != nil {
+ return nil, err
+ }
+ if len(data) < 12 || string(data[:8]) != "AOTERR01" {
+ return nil, fmt.Errorf("invalid terrain file header")
+ }
+ count := binary.LittleEndian.Uint32(data[8:12])
+ data = data[12:]
+ maps := make(map[uint32]*terrain)
+ for range count {
+ if len(data) < 16 {
+ return nil, fmt.Errorf("truncated terrain record")
+ }
+ id := binary.LittleEndian.Uint32(data[:4])
+ ground := &terrain{
+ width: int(binary.LittleEndian.Uint16(data[4:6])), height: int(binary.LittleEndian.Uint16(data[6:8])),
+ spacing: math.Float32frombits(binary.LittleEndian.Uint32(data[8:12])),
+ scale: math.Float32frombits(binary.LittleEndian.Uint32(data[12:16])),
+ }
+ data = data[16:]
+ size := (ground.width + 1) * (ground.height + 1)
+ if ground.width == 0 || ground.height == 0 || !(ground.spacing > 0 && ground.spacing < math.MaxFloat32) || !(ground.scale > 0 && ground.scale < math.MaxFloat32) || len(data) < size || maps[id] != nil {
+ return nil, fmt.Errorf("invalid terrain record for playfield %d", id)
+ }
+ ground.heights = data[:size]
+ maps[id] = ground
+ data = data[size:]
+ }
+ if len(data) != 0 {
+ return nil, fmt.Errorf("unexpected bytes after terrain records")
+ }
+ return maps, nil
+}
+
+func (ground *terrain) elevation(x, z float32) (float32, bool) {
+ // Interpolate the four archived vertices surrounding the local world position.
+ x, z = x/ground.spacing, z/ground.spacing
+ if !(x >= 0 && x <= float32(ground.width) && z >= 0 && z <= float32(ground.height)) {
+ return 0, false
+ }
+ column, row := min(int(x), ground.width-1), min(int(z), ground.height-1)
+ x, z = x-float32(column), z-float32(row)
+ point := row*(ground.width+1) + column
+ top := float32(ground.heights[point])*(1-x) + float32(ground.heights[point+1])*x
+ point += ground.width + 1
+ bottom := float32(ground.heights[point])*(1-x) + float32(ground.heights[point+1])*x
+ return (top*(1-z) + bottom*z) * ground.scale, true
+}
diff --git a/server/terrain_test.go b/server/terrain_test.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "math"
+ "os"
+ "testing"
+)
+
+func TestOriginalTerrainGrids(t *testing.T) {
+ maps, err := readTerrain()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ height, inside := maps[950].elevation(59.4206, 83.75195)
+ border, borderInside := maps[950].elevation(256, 256)
+ _, outside := maps[950].elevation(256.25, 256)
+
+ if len(maps) != 180 || maps[505].width != 896 || maps[505].height != 1536 || maps[540].width != 224 || maps[950].width != 64 {
+ t.Fatal("terrain dimensions differ from the original ground archives")
+ }
+ if !inside || math.Abs(float64(height-15.8081)) > 0.0001 || !borderInside || border < 0 || outside {
+ t.Fatalf("terrain sampling: height %v, border %v, inside %v/%v, outside %v", height, border, inside, borderInside, outside)
+ }
+ if maps[1000] != nil {
+ t.Fatal("indoor map without a height table received terrain")
+ }
+}
+
+func TestTerrainRejectsTruncatedGrid(t *testing.T) {
+ useNPCData(t, editedNPCData)
+ data := append([]byte("AOTERR01"), 1, 0, 0, 0)
+ data = append(data, 182, 3, 0, 0, 1, 0, 1, 0, 0, 0, 128, 64, 0, 0, 128, 63)
+ if err := os.WriteFile("data/terrain.bin", data, 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ _, err := readTerrain()
+
+ if err == nil || err.Error() != "invalid terrain record for playfield 950" {
+ t.Fatalf("truncated height grid: %v", err)
+ }
+}
diff --git a/server/world.go b/server/world.go
@@ -0,0 +1,146 @@
+package main
+
+import (
+ "encoding/binary"
+ "math"
+)
+
+func n3Packet(key, identityType, instance uint32, body []byte) []byte {
+ // The release client serializes the pass-on flag as a full uint32.
+ prefix := make([]byte, 16)
+ binary.BigEndian.PutUint32(prefix[0:4], key)
+ binary.BigEndian.PutUint32(prefix[4:8], identityType)
+ binary.BigEndian.PutUint32(prefix[8:12], instance)
+ packet := systemPacket(0, append(prefix, body...))
+ binary.BigEndian.PutUint16(packet[2:4], 10)
+ binary.BigEndian.PutUint32(packet[8:12], 2)
+ binary.BigEndian.PutUint32(packet[12:16], 1)
+ return packet
+}
+
+func gameTimePacket(id uint32, seconds float64) []byte {
+ // Original GameTime carries seconds, day period, and day number.
+ body := binary.BigEndian.AppendUint32(nil, math.Float32bits(float32(seconds)))
+ body = binary.BigEndian.AppendUint32(body, 0)
+ body = binary.BigEndian.AppendUint32(body, 1)
+ return n3Packet(0x5f52412e, 50000, id, body)
+}
+
+func playfieldPacket(character *character) []byte {
+ zone := playfields[character.playfield]
+ // Version 4 includes the spawn position and original six-field proxy.
+ body := binary.BigEndian.AppendUint32(nil, 4)
+ for _, value := range character.position {
+ body = binary.BigEndian.AppendUint32(body, math.Float32bits(value))
+ }
+ body = append(body, 'a')
+ for _, value := range []uint32{51100, character.playfield, character.playfield, 0, 40016, character.playfield, 0, 0} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+
+ // Outdoor world origin and playfield display name follow the base message.
+ for _, value := range []uint32{zone.origin[0], zone.origin[1], uint32(len(zone.name))} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ body = append(body, zone.name...)
+ return n3Packet(0x5f4b1a39, 40016, character.playfield, body)
+}
+
+func characterPacket(character *character) []byte {
+ // Include playfield and orientation; use the original compact coordinates.
+ body := []byte{1}
+ flags := uint32(0x240)
+ human := character.appearance>>4&7 < 6
+ if character.npc {
+ flags |= 1
+ }
+ if human {
+ flags |= 0x90
+ }
+ if character.level > 255 {
+ flags |= 0x1000
+ }
+ body = binary.BigEndian.AppendUint32(body, flags)
+ body = binary.BigEndian.AppendUint32(body, character.playfield)
+ for _, value := range []uint16{uint16(character.position[0] * 8), uint16(int16(character.position[1] * 16)), uint16(character.position[2] * 8)} {
+ body = binary.BigEndian.AppendUint16(body, value)
+ }
+ for _, value := range character.rotation {
+ body = binary.BigEndian.AppendUint32(body, math.Float32bits(value))
+ }
+ // Appearance packs race, fatness, breed, sex, side, and face into 16 bits.
+ body = binary.BigEndian.AppendUint16(body, character.appearance)
+ body = append(body, byte(len(character.name)+1))
+ body = append(body, character.name...)
+ body = append(body, 0)
+
+ // Flags, auxiliary state, core abilities, level, and health.
+ if !character.npc {
+ for _, value := range []uint32{0, 0, 0} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ for _, value := range []uint16{10, 10, 10, 10} {
+ body = binary.BigEndian.AppendUint16(body, value)
+ }
+ }
+ if character.level > 255 {
+ body = binary.BigEndian.AppendUint16(body, character.level)
+ } else {
+ body = append(body, byte(character.level))
+ }
+ for _, value := range []uint32{100, 100, character.monsterData} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ body = binary.BigEndian.AppendUint16(body, 100)
+ // Stationary velocity, movement commands, control state, and empty path.
+ vehicle := make([]byte, 28)
+ copy(vehicle[12:22], []byte{2, 1, 0, 1, 0, 1, 0, 1, 0, 1})
+ binary.BigEndian.PutUint32(vehicle[22:26], 2)
+ body = binary.BigEndian.AppendUint32(body, uint32(len(vehicle)))
+ body = append(body, vehicle...)
+ if human {
+ // Supply the head mesh before the client refreshes its appearance.
+ body = binary.BigEndian.AppendUint32(body, 40682)
+ }
+ body = append(body, 100)
+ if human {
+ // Keep the body materials and replace the hand material with original skin.
+ body = binary.BigEndian.AppendUint32(body, 6054)
+ for _, texture := range []struct {
+ material string
+ resource uint32
+ }{{"arms", 8714}, {"feet", 8710}, {"hands", 8773}, {"legs", 8713}, {"body", 8709}} {
+ body = append(body, texture.material...)
+ body = append(body, 0)
+ for _, value := range []uint32{texture.resource, 0, 0} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ }
+ }
+ body = binary.BigEndian.AppendUint32(body, 1009)
+ body = binary.BigEndian.AppendUint32(body, 1009)
+ return n3Packet(0x271b3a6b, 50000, character.id, body)
+}
+
+func fullCharacterPacket(id uint32) []byte {
+ // Version 16 begins with six encoded lists, followed by four stat lists.
+ body := binary.BigEndian.AppendUint32(nil, 16)
+ for range 6 {
+ body = binary.BigEndian.AppendUint32(body, 1009)
+ }
+ stats := [][2]uint32{{54, 1}, {4, 1}, {47, 1}, {60, 1}, {59, 2}, {156, 100}, {16, 10}, {17, 10}, {18, 10}, {19, 10}, {20, 10}, {21, 10}, {27, 100}, {123, 100}, {124, 100}}
+ body = binary.BigEndian.AppendUint32(body, uint32(len(stats)+1)*1009)
+ for _, stat := range stats {
+ body = binary.BigEndian.AppendUint32(body, stat[0])
+ body = binary.BigEndian.AppendUint32(body, stat[1])
+ }
+ for range 3 {
+ body = binary.BigEndian.AppendUint32(body, 1009)
+ }
+
+ // Empty stat map, remaining lists, and auxiliary identity.
+ for _, value := range []uint32{0, 1009, 0, 0, 1009} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x29304349, 50000, id, body)
+}
diff --git a/tools/extract_monsters.py b/tools/extract_monsters.py
@@ -0,0 +1,61 @@
+import json
+import pathlib
+import re
+import struct
+
+# Read the original database's resource index.
+root = pathlib.Path('client-original/Gamefiles/cd_image/data/db')
+index = (root / 'ResourceDatabase.idx').read_bytes()
+records = {}
+block = struct.unpack_from('<I', index, 72)[0]
+while block:
+ for entry in range(struct.unpack_from('<H', index, block + 8)[0]):
+ offset = block + 18 + entry * 12
+ kind, identity = struct.unpack_from('>II', index, offset + 4)
+ records[kind, identity] = struct.unpack_from('<I', index, offset)[0]
+ block = struct.unpack_from('<I', index, block)[0]
+database = open(root / 'ResourceDatabase.dat', 'rb')
+
+
+def read_record(kind, identity):
+ database.seek(records[kind, identity])
+ header = database.read(34)
+ assert struct.unpack_from('<II', header, 10) == (kind, identity)
+ return database.read(struct.unpack_from('<I', header, 18)[0] - 12)
+
+
+# Resolve model IDs through the disc's filename registry.
+registry = read_record(1000010, 1)
+filenames = {}
+for match in re.finditer(rb'[ -~]{5,}', registry):
+ identity, length = struct.unpack_from('<II', registry, match.start() - 8)
+ if length == (len(match.group()) // 4 + 1) * 4:
+ filenames[identity] = match.group().decode('ascii')
+
+catalog = []
+for kind, identity in sorted(records):
+ if kind != 1040023:
+ continue
+ payload = read_record(kind, identity)
+ version, section, encoded_count = struct.unpack_from('<III', payload)
+ assert (version, section) == (15, 23)
+ assert encoded_count % 1009 == 0
+ count = encoded_count // 1009 - 1
+ stats = dict(struct.unpack_from('<II', payload, 12 + entry * 8) for entry in range(count))
+ assert struct.unpack_from('<I', payload, 12 + count * 8)[0] == 14
+
+ # The final name section has an explicit length and a terminating zero.
+ offset = payload.rfind(b'\x06\x00\x00\x00\x1c\x00\x00\x00\xf1\x03\x00\x00')
+ assert offset >= 0, identity
+ length = struct.unpack_from('<I', payload, offset + 12)[0]
+ assert offset + 16 + length + 1 == len(payload), identity
+ assert payload[-1] == 0
+ name = payload[offset + 16:-1].decode('ascii')
+ catalog.append({'monster_data': identity, 'name': name, 'mesh': stats[12],
+ 'mesh_filename': filenames[stats[12]], 'stats': stats,
+ 'record_file_offset': records[kind, identity]})
+database.close()
+
+# Preserve appearance definitions independently of population template hashes.
+pathlib.Path('tools/original-monsters.json').write_text(json.dumps(catalog, indent=2) + '\n')
+print('Extracted', len(catalog), 'original monster appearance definitions')
diff --git a/tools/extract_npc_spawns.py b/tools/extract_npc_spawns.py
@@ -0,0 +1,97 @@
+import io
+import json
+import pathlib
+import struct
+
+# Read the release database's linked resource index.
+root = pathlib.Path('client-original/Gamefiles/cd_image/data/db')
+index = (root / 'ResourceDatabase.idx').read_bytes()
+records = {}
+block = struct.unpack_from('<I', index, 72)[0]
+seen = set()
+while block:
+ assert block not in seen
+ seen.add(block)
+ for entry in range(struct.unpack_from('<H', index, block + 8)[0]):
+ offset = block + 18 + entry * 12
+ kind, identity = struct.unpack_from('>II', index, offset + 4)
+ assert (kind, identity) not in records
+ records[kind, identity] = struct.unpack_from('<I', index, offset)[0]
+ block = struct.unpack_from('<I', index, block)[0]
+
+database = open(root / 'ResourceDatabase.dat', 'rb')
+
+
+def read_record(kind, identity):
+ database.seek(records[kind, identity])
+ header = database.read(34)
+ assert struct.unpack_from('<II', header, 10) == (kind, identity)
+ return database.read(struct.unpack_from('<I', header, 18)[0] - 12)
+
+
+def read(reader, format):
+ return list(struct.unpack('<' + format, reader.read(struct.calcsize('<' + format))))
+
+
+# Decode the version-5 layout used by the original district resources.
+# Source: AODB.Common/RDBObjects/PlayfieldDistrictInfo_1000014.cs,
+# PlayfieldDistrictInfo.ReadDistrict/ReadHashSpawnPoint, commit a772622b.
+catalog = []
+for kind, identity in sorted(records):
+ if kind != 1000014:
+ continue
+ payload = read_record(kind, identity)
+ reader = io.BytesIO(payload)
+ version, zone_count, district_count = read(reader, 'HiB')
+ assert version == 5
+ districts = []
+ for district_index in range(district_count):
+ district = {'payload_offset': reader.tell(), 'center': read(reader, '3f')}
+ district['name'] = reader.read(32).split(b'\0', 1)[0].decode('ascii')
+ district['stats'] = read(reader, '9H')
+ district['extras'] = reader.read(4).hex()
+ district['npc_min_level'], district['npc_max_level'] = read(reader, '2B')
+ district['respawn_chance'], district['respawn_time'], district['fight_mode'] = read(reader, 'BiB')
+ spawn_count, extra_count, music_count, point_count, hash_count = read(reader, '5B')
+
+ # District groups reference templates with packed four-character codes.
+ district['spawn_groups'] = []
+ for _ in range(spawn_count):
+ template_hash, count = read(reader, 'IH')
+ district['spawn_groups'].append({
+ 'template_hash': struct.pack('>I', template_hash).decode('latin1'),
+ 'count': count})
+ district['extra_infos'] = [reader.read(6).hex() for _ in range(extra_count)]
+ district['music_pairs'] = [read(reader, '2H') for _ in range(music_count)]
+ district['spawn_points'] = [read(reader, '4f') for _ in range(point_count)]
+
+ # Fixed spawns carry their own template, position, levels and respawn data.
+ district['fixed_spawns'] = []
+ for _ in range(hash_count):
+ spawn = {'payload_offset': reader.tell(), 'position': read(reader, '3f'),
+ 'radius': read(reader, 'f')[0], 'angles': read(reader, '2h')}
+ spawn['template_hash'] = struct.pack('>I', read(reader, 'I')[0]).decode('latin1')
+ spawn['min_level'], spawn['max_level'] = read(reader, '2H')
+ spawn['respawn_chance'], spawn['flags'], spawn['respawn_time'] = read(reader, '2BH')
+ assert spawn['flags'] == 0, (identity, district_index, reader.tell())
+ district['fixed_spawns'].append(spawn)
+ districts.append(district)
+
+ # Preserve the map-cell district assignments and require exact record alignment.
+ zone_map = list(reader.read(zone_count))
+ assert len(zone_map) == zone_count
+ assert all(district_index < len(districts) for district_index in zone_map)
+ assert reader.tell() == len(payload), (identity, reader.tell(), len(payload))
+ name = read_record(1000001, identity)[8:40].split(b'\0', 1)[0].decode('ascii').strip()
+ catalog.append({'playfield': identity, 'name': name, 'version': version,
+ 'record_file_offset': records[kind, identity],
+ 'districts': districts, 'zone_to_district_map': zone_map})
+database.close()
+
+# Retain original directives without guessing the missing server-side templates.
+pathlib.Path('tools/original-npc-spawns.json').write_text(json.dumps(catalog, indent=2) + '\n')
+print('Decoded', len(catalog), 'original maps with exact record alignment')
+print('Districts:', sum(len(p['districts']) for p in catalog))
+print('Spawn groups:', sum(len(d['spawn_groups']) for p in catalog for d in p['districts']))
+print('Spawn points:', sum(len(d['spawn_points']) for p in catalog for d in p['districts']))
+print('Fixed spawns:', sum(len(d['fixed_spawns']) for p in catalog for d in p['districts']))
diff --git a/tools/extract_playfields.py b/tools/extract_playfields.py
@@ -0,0 +1,120 @@
+import json
+import math
+import pathlib
+import struct
+import zlib
+
+# Read the release database's linked resource index.
+root = pathlib.Path('client-original/Gamefiles/cd_image/data')
+index = (root / 'db/ResourceDatabase.idx').read_bytes()
+records = {}
+block = struct.unpack_from('<I', index, 72)[0]
+seen = set()
+while block:
+ assert block not in seen
+ seen.add(block)
+ count = struct.unpack_from('<H', index, block + 8)[0]
+ for entry in range(count):
+ offset = block + 18 + entry * 12
+ position = struct.unpack_from('<I', index, offset)[0]
+ kind, identity = struct.unpack_from('>II', index, offset + 4)
+ assert (kind, identity) not in records
+ records[kind, identity] = position
+ block = struct.unpack_from('<I', index, block)[0]
+
+database = open(root / 'db/ResourceDatabase.dat', 'rb')
+
+
+def read_record(kind, identity):
+ database.seek(records[kind, identity])
+ header = database.read(34)
+ assert struct.unpack_from('<II', header, 10) == (kind, identity)
+ return database.read(struct.unpack_from('<I', header, 18)[0] - 12)
+
+
+# Extract names and arrivals from the original playfield and district records.
+catalog = {}
+for kind, identity in sorted(records):
+ if kind != 1000001:
+ continue
+ payload = read_record(kind, identity)
+ assert struct.unpack_from('<I', payload)[0] == 8
+ name = payload[8:40].split(b'\0', 1)[0].decode('ascii').strip()
+
+ # Decode the center terrain height and validate the compressed block corners.
+ if (1000009, identity) in records:
+ ground = read_record(1000009, identity)
+ assert ground[:4] == b'CHGA'
+ width, height, tile_size, scale = struct.unpack_from('<HHff', ground, 12)
+ spawn = [width // 2 * tile_size, 0.5, height // 2 * tile_size]
+ marker = b'\x08\x09\x00\x00\x00\x00\x00\x00\x00'
+ if marker in ground:
+ cursor = ground.index(marker)
+ blob_size = struct.unpack_from('<I', ground, cursor + 9)[0]
+ cursor += 13
+ end = cursor + blob_size
+ chunks = []
+ while cursor < end:
+ length = struct.unpack_from('<I', ground, cursor)[0]
+ cursor += 4
+ chunks.append(zlib.decompress(ground[cursor:cursor + length]))
+ cursor += length
+ assert cursor == end
+ assert ground[cursor:cursor + 9] == b'\x09\x09\x00\x00\x00\x00\x00\x00\x00'
+ small_size = struct.unpack_from('<I', ground, cursor + 9)[0]
+ small = ground[cursor + 13:cursor + 13 + small_size]
+ assert len(small) == len(chunks) * 8
+ side = math.isqrt(len(chunks[0]))
+ x, z = width // 2, height // 2
+ selected = z // (side - 1) * math.ceil(width / (side - 1)) + x // (side - 1)
+ chunk = chunks[selected]
+ assert side * side == len(chunk)
+ values = []
+ for offset, delta in enumerate(chunk):
+ column, row = offset % side, offset // side
+ left = values[-1] if column else 0
+ above = values[offset - side] if row else 0
+ diagonal = values[offset - side - 1] if column and row else 0
+ values.append((delta + left + above - diagonal) % 256)
+ corners = [0, side - 1, side * (side - 1), side * side - 1]
+ assert bytes(values[i] for i in corners) == small[selected * 8 + 4:selected * 8 + 8]
+ spawn[1] += values[z % (side - 1) * side + x % (side - 1)] * scale
+ else:
+ districts = read_record(1000014, identity)
+ assert len(districts) >= 19 and districts[6]
+ spawn = list(struct.unpack_from('<3f', districts, 7))
+ catalog[identity] = {'id': identity, 'name': name, 'origin': [0, 0],
+ 'spawn': [round(value, 4) for value in spawn],
+ 'unavailable': identity in (100, 102, 103, 1410)}
+
+# Include launcher-only names as disabled choices and keep verified arrivals.
+for line in (root / 'launcher/pfnrmap.dat').read_text().splitlines():
+ identity, name = line.split(';', 1)
+ identity = int(identity)
+ if identity not in catalog:
+ catalog[identity] = {'id': identity, 'name': name, 'origin': [0, 0],
+ 'spawn': [0, 0, 0], 'unavailable': True}
+catalog[800]['origin'] = [37107, 38360]
+catalog[800]['spawn'] = [679.625, 74.75, 537.875]
+catalog[950]['spawn'] = [52.625, 14.75, 56.875]
+database.close()
+
+# Generate the server's fixed catalog and retain the extracted data for review.
+lines = ['package main', '', 'type playfield struct {', '\tname string',
+ '\torigin [2]uint32', '\tspawn [3]float32', '\tunavailable bool', '}', '',
+ '// Map names and spawn coordinates extracted from the original release assets.',
+ 'var playfields = map[uint32]playfield{']
+for identity in sorted(catalog):
+ zone = catalog[identity]
+ value = f"\t{identity}: {{name: {json.dumps(zone['name'])}"
+ if zone['origin'] != [0, 0]:
+ value += ', origin: [2]uint32{' + ', '.join(str(n) for n in zone['origin']) + '}'
+ if zone['unavailable']:
+ value += ', unavailable: true'
+ else:
+ value += ', spawn: [3]float32{' + ', '.join(str(n) for n in zone['spawn']) + '}'
+ lines.append(value + '},')
+lines.append('}')
+pathlib.Path('server/playfields.go').write_text('\n'.join(lines) + '\n')
+pathlib.Path('tools/original-playfields.json').write_text(json.dumps([catalog[i] for i in sorted(catalog)], indent=2) + '\n')
+print(f"Extracted {len(catalog)} zones; {sum(not zone['unavailable'] for zone in catalog.values())} have map assets")
diff --git a/tools/extract_terrain.py b/tools/extract_terrain.py
@@ -0,0 +1,114 @@
+import hashlib
+import json
+import pathlib
+import struct
+import zlib
+
+# Locate the original CHGA records in the linked resource index.
+root = pathlib.Path('client-original/Gamefiles/cd_image/data/db')
+index = (root / 'ResourceDatabase.idx').read_bytes()
+records = {}
+block = struct.unpack_from('<I', index, 72)[0]
+seen = set()
+while block:
+ assert block not in seen
+ seen.add(block)
+ for entry in range(struct.unpack_from('<H', index, block + 8)[0]):
+ offset = block + 18 + entry * 12
+ kind, identity = struct.unpack_from('>II', index, offset + 4)
+ if kind == 1000009:
+ assert identity not in records
+ records[identity] = struct.unpack_from('<I', index, offset)[0]
+ block = struct.unpack_from('<I', index, block)[0]
+
+pathlib.Path('data').mkdir(exist_ok=True)
+catalog = []
+without_heights = []
+with open(root / 'ResourceDatabase.dat', 'rb') as database, open('data/terrain.bin.tmp', 'wb') as output:
+ output.write(b'AOTERR01' + struct.pack('<I', 0))
+ for identity, offset in sorted(records.items()):
+ if identity in [100, 102, 103, 1410]:
+ continue
+ database.seek(offset)
+ header = database.read(34)
+ assert struct.unpack_from('<II', header, 10) == (1000009, identity)
+ ground = database.read(struct.unpack_from('<I', header, 18)[0] - 12)
+ assert ground[:4] in [b'CHGA', b'GNDA'], (identity, ground[:24].hex())
+ display_width, display_height, spacing, scale = struct.unpack_from('<HHff', ground, 12)
+ marker = b'\x08\x09\x00\x00\x00\x00\x00\x00\x00'
+ if marker not in ground:
+ without_heights.append(identity)
+ continue
+
+ # Archive fields 4-7 hold vertex dimensions, row modulo and texture count.
+ cursor = ground.index(marker)
+ dimensions = []
+ for field in [4, 5, 6, 7]:
+ entry = cursor - (8 - field) * 17
+ assert ground[entry:entry + 13] == bytes([field]) + struct.pack('<III', 3, 4, 4)
+ dimensions.append(struct.unpack_from('<I', ground, entry + 13)[0])
+ width, height = dimensions[0] - 1, dimensions[1] - 1
+ assert dimensions[2] == width + 1
+ block_cells = min(width & -width, height & -height, 64)
+ side = block_cells + 1
+
+ # Reconstruct every delta block, validating its small-height corners.
+ size = struct.unpack_from('<I', ground, cursor + 9)[0]
+ cursor += 13
+ end = cursor + size
+ chunks = []
+ while cursor < end:
+ length = struct.unpack_from('<I', ground, cursor)[0]
+ cursor += 4
+ deltas = zlib.decompress(ground[cursor:cursor + length])
+ cursor += length
+ assert len(deltas) == side * side, (identity, len(deltas), side)
+ values = bytearray(len(deltas))
+ for point, delta in enumerate(deltas):
+ column, row = point % side, point // side
+ left = values[point - 1] if column else 0
+ above = values[point - side] if row else 0
+ diagonal = values[point - side - 1] if column and row else 0
+ values[point] = (delta + left + above - diagonal) & 255
+ chunks.append(values)
+ assert cursor == end
+ assert ground[cursor:cursor + 9] == b'\x09\x09\x00\x00\x00\x00\x00\x00\x00'
+ small_size = struct.unpack_from('<I', ground, cursor + 9)[0]
+ small = ground[cursor + 13:cursor + 13 + small_size]
+ assert len(small) == len(chunks) * 8
+ across = width // block_cells
+ assert len(chunks) == across * (height // block_cells), (identity, width, height, len(chunks), across)
+ for chunk_index, chunk in enumerate(chunks):
+ assert bytes(chunk[point] for point in [0, side - 1, side * (side - 1), side * side - 1]) == small[chunk_index * 8 + 4:chunk_index * 8 + 8]
+ if chunk_index % across:
+ assert chunk[::side] == chunks[chunk_index - 1][side - 1::side], (identity, chunk_index, 'X seam')
+ if chunk_index >= across:
+ assert chunk[:side] == chunks[chunk_index - across][-side:], (identity, chunk_index, 'Z seam')
+
+ # Stitch shared-edge tiles into the actual archived row-major vertex grid.
+ grid = bytearray((width + 1) * (height + 1))
+ for chunk_index, chunk in enumerate(chunks):
+ x, z = chunk_index % across * block_cells, chunk_index // across * block_cells
+ for row in range(side):
+ start = (z + row) * (width + 1) + x
+ grid[start:start + side] = chunk[row * side:row * side + side]
+ output.write(struct.pack('<IHHff', identity, width, height, spacing, scale))
+ output.write(grid)
+ catalog.append({'playfield': identity, 'width': width, 'height': height,
+ 'display_width': display_width, 'display_height': display_height,
+ 'spacing': spacing, 'height_scale': scale, 'chunks': len(chunks), 'block_cells': block_cells,
+ 'grid_sha256': hashlib.sha256(grid).hexdigest()})
+ output.seek(8)
+ output.write(struct.pack('<I', len(catalog)))
+pathlib.Path('data/terrain.bin.tmp').replace('data/terrain.bin')
+
+# Retain decoding coverage and identities independently of the runtime implementation.
+pathlib.Path('tools/terrain-extraction-evidence.json').write_text(json.dumps({
+ 'source_index_sha256': hashlib.sha256(index).hexdigest(),
+ 'terrain_file_sha256': hashlib.sha256(pathlib.Path('data/terrain.bin').read_bytes()).hexdigest(),
+ 'decoded': catalog, 'records_without_height_table': without_heights,
+ 'checks': ['Every compressed block matches its archived dimensions and all four small-height corners.',
+ 'Every shared X and Z block edge matches exactly.'],
+}, indent=2) + '\n')
+print('Decoded', len(catalog), 'terrain grids;', len(without_heights), 'ground records have no height table')
+print('Grid bytes:', sum((item['width'] + 1) * (item['height'] + 1) for item in catalog))
diff --git a/tools/generate_npcs.py b/tools/generate_npcs.py
@@ -0,0 +1,179 @@
+import collections
+import json
+import math
+import pathlib
+
+# These appearance assignments are provisional, not recovered NPC templates.
+appearances = {
+ 'ANDR': 17649, 'ANUN': 38389, 'ANVI': 17651, 'AQUA': 30369,
+ 'AUTO': 40059, 'BABY': 40065, 'BIOF': 30258, 'BLUB': 40075,
+ 'BREI': 17706, 'BRON': 30346, 'CARR': 40486, 'CYBO': 17643,
+ 'CLAW': 38387, 'EYEM': 17653, 'FLEA': 17657, 'HAMM': 30383,
+ 'GFLS': 17691, 'HOVE': 20614, 'LEET': 17655, 'LIZA': 22794, 'MALL': 17660,
+ 'MECH': 17720, 'NANO': 38394, 'PILI': 17710, 'PIRA': 95357, 'PIXI': 38414,
+ 'PUKO': 95355, 'REET': 30365, 'ROLL': 17687, 'SABR': 30356,
+ 'SALA': 30354, 'SCOR': 17693, 'SHAD': 30464, 'SKSP': 30379,
+ 'SLAY': 22821, 'SNAK': 30252, 'STAL': 17708, 'STAN': 85351, 'STON': 30377,
+ 'TENT': 17695, 'WARD': 17697, 'WOLV': 30348, 'YUTT': 22802,
+ 'UNBR': 45603, 'WACO': 17714,
+}
+# Numbered codes use provisional species models, not recovered variant stats.
+families = {
+ 'AD': 17649, 'AN': 38389, 'AS': 40059, 'BB': 40075, 'BE': 17706,
+ 'BR': 30346, 'CL': 38387, 'CY': 17643, 'ER': 31762, 'EY': 17653,
+ 'FL': 17657, 'GO': 17691, 'GU': 40069, 'HA': 30383, 'JU': 22798,
+ 'LE': 17655, 'LZ': 22794, 'ME': 26048, 'ML': 17660, 'MN': 30375,
+ 'NF': 38394, 'NK': 30358, 'OT': 22790, 'PI': 17710, 'PR': 95357, 'PU': 95355,
+ 'PX': 38414, 'RH': 17664, 'RR': 17687, 'RT': 30365, 'SD': 22821,
+ 'SG': 30260, 'SH': 30464, 'SK': 40067, 'SL': 17708, 'SN': 30252,
+ 'SW': 17712, 'TD': 22804, 'TM': 17695, 'WC': 17714, 'WD': 17697,
+ 'WO': 30348, 'YU': 22802,
+}
+catalog = json.loads(pathlib.Path('tools/original-npc-spawns.json').read_text())
+monsters = {monster['monster_data']: monster for monster in
+ json.loads(pathlib.Path('tools/original-monsters.json').read_text())}
+assert all(identity in monsters for identity in list(appearances.values()) + list(families.values()))
+
+
+def appearance(template_code, playfield):
+ monster_data = appearances.get(template_code)
+ if monster_data is None and template_code[2:].isdigit():
+ monster_data = families.get(template_code[:2])
+ if monster_data is not None:
+ name = 'Reet' if monster_data == 30365 else monsters[monster_data]['name'].title()
+ return name, monster_data, 0xe5, 'inferred_species', 'Species assignment is provisional; original template not recovered.'
+
+ # Human conventions are inferred from codes and their authored locations.
+ human = (template_code[:1] in ['H', 'N'] and template_code[1:].isdigit()
+ or template_code in ['OTBG', 'OTGD', 'CLBG', 'CLGD', 'NEBG', 'NEGD']
+ or 'shop' in playfield['name'].lower() or 'backyard' in playfield['name'].lower())
+ if human:
+ return ('Placeholder ' + template_code, 26092, 0x315, 'placeholder_human',
+ 'Human role inferred from code or shop/backyard location; generic Solitus appearance.')
+ return ('Placeholder ' + template_code, 17655, 0xe5, 'placeholder_creature',
+ 'Original template unresolved; Leet used as a visible stand-in.')
+
+
+def append_group(lines, code, name, monster_data, breed, level, status, placement, comment, positions):
+ # One batch shares provenance and appearance; XYZ rows remain easy to edit.
+ lines.extend([
+ f' - template_code: {json.dumps(code)}',
+ f' name: {json.dumps(name)}',
+ f' monster_data: {monster_data}',
+ f' appearance: {breed}',
+ f' level: {level}',
+ f' appearance_status: {status}',
+ f' placement_status: {placement}',
+ f' comment: {json.dumps(comment)}',
+ ' positions:',
+ ])
+ for x, y, z in positions:
+ lines.append(f' - [{x:.9g}, {y:.9g}, {z:.9g}]')
+
+# Keep every requested instance; historical templates and allocation are unknown.
+lines = [
+ '# NPC population reconstruction from the original 11.0 disc.',
+ '# Source: tools/original-npc-spawns.json and tools/original-monsters.json.',
+ '# Editable YAML. Regenerating with tools/generate_npcs.py overwrites edits and comments.',
+ '# Appearance and placement statuses are independent; neither implies recovered AI.',
+ 'appearance_statuses:',
+ ' inferred_species:',
+ ' confidence: inferred',
+ ' comment: "Species inferred from template codes; full original NPC templates remain unknown."',
+ ' placeholder_human:',
+ ' confidence: placeholder',
+ ' comment: "Human classification is inferred; name, model, clothes and role are placeholders."',
+ ' placeholder_creature:',
+ ' confidence: placeholder',
+ ' comment: "Unknown creature identity; uses the original Leet appearance as a stand-in."',
+ 'placement_statuses:',
+ ' authored_point:',
+ ' confidence: approximate',
+ ' comment: "XYZ is an authored point; assigning this NPC to it is an inferred allocation."',
+ ' spread_authored_point:',
+ ' confidence: approximate',
+ ' comment: "Generated offset within an authored radius; original sampling and ground adjustment unknown."',
+ ' district_center_fallback:',
+ ' confidence: approximate',
+ ' comment: "No points authored for this population; generated grid around the district centre."',
+ ' fixed_point:',
+ ' confidence: authored',
+ ' comment: "XYZ preserved from the fixed spawn record; original heading units remain unknown."',
+ 'level_policy:',
+ ' confidence: inferred',
+ ' comment: "Uses the authored minimum; original level selection within each range is unknown."',
+ 'playfields:',
+]
+coverage = {'appearance_counts': collections.Counter(), 'placement_counts': collections.Counter(),
+ 'templates': {}, 'playfields': []}
+total = 0
+populated_maps = 0
+for playfield in catalog:
+ if playfield['playfield'] in [100, 102, 103, 1410]:
+ continue
+ count = 0
+ playfield_lines = []
+ for district in playfield['districts']:
+ district_lines = []
+ point_index = 0
+ requested = sum(group['count'] for group in district['spawn_groups'])
+ for group in district['spawn_groups']:
+ name, monster_data, breed, status, comment = appearance(group['template_hash'], playfield)
+ coverage['appearance_counts'][status] += group['count']
+ coverage['templates'].setdefault(group['template_hash'], collections.Counter())[status] += group['count']
+ positions = collections.defaultdict(list)
+ for _ in range(group['count']):
+ if district['spawn_points']:
+ point = point_index % len(district['spawn_points'])
+ cycle = point_index // len(district['spawn_points'])
+ x, y, z, radius = district['spawn_points'][point]
+ placement = 'authored_point'
+ if cycle:
+ # Spread repeated occupants within the point radius, near its height.
+ cycles = math.ceil(requested / len(district['spawn_points']))
+ distance = min(radius, 2) * math.sqrt(cycle / cycles)
+ x += math.cos(point_index * 2.399963229728653) * distance
+ z += math.sin(point_index * 2.399963229728653) * distance
+ placement = 'spread_authored_point'
+ else:
+ # Missing point lists get a repeatable two-metre grid around the centre.
+ width = math.ceil(math.sqrt(requested))
+ x, y, z = district['center']
+ x += (point_index % width - (width - 1) / 2) * 2
+ z += (point_index // width - (width - 1) / 2) * 2
+ placement = 'district_center_fallback'
+ point_index += 1
+ count += 1
+ coverage['placement_counts'][placement] += 1
+ positions[placement].append((x, y, z))
+ for placement, points in positions.items():
+ append_group(district_lines, group['template_hash'], name, monster_data, breed,
+ district['npc_min_level'], status, placement, comment, points)
+ # Preserve all fixed positions and levels; heading units remain unknown.
+ for spawn in district['fixed_spawns']:
+ name, monster_data, breed, status, comment = appearance(spawn['template_hash'], playfield)
+ x, y, z = spawn['position']
+ count += 1
+ coverage['appearance_counts'][status] += 1
+ coverage['templates'].setdefault(spawn['template_hash'], collections.Counter())[status] += 1
+ coverage['placement_counts']['fixed_point'] += 1
+ append_group(district_lines, spawn['template_hash'], name, monster_data, breed,
+ spawn['min_level'], status, 'fixed_point', comment, [(x, y, z)])
+ if district_lines:
+ playfield_lines.extend([f' - name: {json.dumps(district["name"])}', ' groups:'])
+ playfield_lines.extend(district_lines)
+ if count:
+ populated_maps += 1
+ total += count
+ coverage['playfields'].append({'playfield': playfield['playfield'], 'name': playfield['name'], 'count': count})
+ lines.extend(['', f'- id: {playfield["playfield"]}',
+ f' name: {json.dumps(playfield["name"])}', ' districts:'])
+ lines.extend(playfield_lines)
+ print('Generated:', playfield['playfield'], playfield['name'], count, 'NPCs')
+pathlib.Path('data').mkdir(exist_ok=True)
+pathlib.Path('data/npc_spawns.yaml').write_text('\n'.join(lines) + '\n', encoding='ascii')
+print('Total:', total, 'NPCs in', populated_maps, 'playfields')
+coverage['total'] = total
+pathlib.Path('tools/npc-coverage.json').write_text(json.dumps(coverage, indent=2, sort_keys=True) + '\n')
+print('Appearances:', dict(coverage['appearance_counts']))
+print('Placement:', dict(coverage['placement_counts']))