aorecomp

Anarchy Online classic in the browser

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


commit b1c1c6cdb906730f97fc8a60f4b3fcaca7fba4ba
parent 5e889b08193b959b06f9571204c0902e7ccbceb9
Author: anon <anon@example.com>
Date:   Mon,  2 Nov 2026 23:25:42 +0000

Place admitted fallback NPCs on dry district terrain

Diffstat:
MTODO.md | 9+++++++++
Mdocs/npc-mapping-integration.md | 5+++++
Adocs/npc-placement.md | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_fallback_placement_test.go | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/npc_fallback_placement_test.go | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/npc_placement.go | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/state.go | 1+
Atools/client/test_fallback_placement.mjs | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 434 insertions(+), 0 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -748,6 +748,15 @@ for exact records, protocol, tests and remaining reconstruction assumptions. spawn height, and verify ordinary selection, approach and melee after repair. Preserve authored placement evidence and use shared placement rules. Evidence: `local/early-melee/runtime/pair-earned-bat-normal-combat.json`. + The center grid is inside the original pond, not an inaccessible ledge. + Initial placement now uses distinct dry terrain samples inside the original + district cells for all 23 admitted fallback combatants; authored points and + raw records stay unchanged. A controlled two-client WASM check verifies real + selection, walking and melee at the repaired shore spawn, with matching HP. + Keep this open: a deterministic ordinary four-metre roaming route returns + that Leet to the pond through the existing terrain-offset movement path. + Resolve roaming/pursuit water eligibility before claiming usable wandering; + original sampling remains provisional. See [fallback placement](docs/npc-placement.md). - [ ] [P1] Incorporate the reviewed NPC mappings from the NPC mapping research. Read its `README.md` and `reports/all-npc-code-assignments.json`, then merge relevant changes surgically into the current checkout. Preserve per-context diff --git a/docs/npc-mapping-integration.md b/docs/npc-mapping-integration.md @@ -16,6 +16,11 @@ The runtime now separates 68,023 character placements from 586 static resources. Among the characters, 13,291 placements retain `best_effort` status; filling a name or body does not recover its historical stats, equipment, loot or AI. +Initial runtime placement separately adjusts the 23 admitted district-center +fallback combatants to dry samples within their original district cells. The +catalog and raw coordinates above remain intact. Original sampling and the +remaining roaming-water failure are documented in [NPC placement](npc-placement.md). + `tools/data/npc_assignments.py` validates maintained choices against the complete catalog. Population generation reapplies maintained per-group metadata after source allocation, preserving those evidence comments and current level ranges. diff --git a/docs/npc-placement.md b/docs/npc-placement.md @@ -0,0 +1,55 @@ +# Generated NPC placement + +Initial district-center fallbacks for admitted ground combatants use distinct +dry terrain samples inside their original district cells. The shared path runs +only during initial population creation. Authored and fixed points, unreviewed +combat contracts, raw source coordinates, population counts, identities and +level ranges remain unchanged. Existing saved worlds retain their saved state; +no migration or per-tick placement writes are added. + +The selected 14.9.1 Omni Training population source has SHA-256 +`12bf3d50785c8a40983fd6842054d46b4a8e995b1d780f2efdaddb97a2c57344`. +Source district 5 has center `[140,10.8,100]`, four LEET and two ML01 entries, +and no spawn points. Its original 36-entry zone map assigns it the cell at +X120..160/Z80..120 in the shipped 6-by-6 grid. The center is in the pond. +It does not provide six individual underwater spawn coordinates. + +The old generated Leet point `[138,10.8,98]` lies below the terrain at Y11 +and water near Y13.5166. The native floor query's Y12.3166 contact includes +its water-minus-1.2 clamp; treating this as a static floor was incorrect. +A controlled WASM trial at that raised underwater point still cannot start +ordinary melee while the player swims. Raising only Y does not repair this +placement. + +The replacement samples terrain-tile centers inside cells assigned to the +source district. It uses the existing scene floor/water query, excludes points +below water, and assigns the closest unused sample in stable population order. +The first Leet now starts at `[130,14,98]`. Its motion home uses the same point, +so cold recovery and ordinary replacement preserve the selected initial home. +Missing source/geometry and exhausted dry samples retain the existing generated +placement; this does not establish support for those unresolved cases. + +This deterministic sampling is a reconstruction, not the original random spawn +algorithm or a recovered aquatic/flying NPC policy. All 23 currently admitted +fallback combatants pass the production census: distinct positions, dry contact, +original district membership and matching home. The focused fixture checks all +six placements, immutable raw points, untouched fixed/unreviewed entries, +respawn and cold recovery. + +The two-client WASM check uses controlled default level-1 players and holds idle roaming +while isolating initial placement. Real first-person camera input selects the +downhill Leet; ordinary walking enters range and Q starts/stops combat. The +single five-point hit leaves both native replicas and the server at 95/100 HP. +This is neither earned progression nor proof of usable wandering. The related +Go selection passes in 15.004s; focused race checks pass in 107.346s; vet and +Node syntax checks pass. The final native run takes 25.46s, or 33.086s including +Go. Reviewed screenshots, complete traces, independent verification and earlier +failed trials are under `local/fallback-placement/`; the successful capture is +`20261102-152355/`. + +The placement TODO remains open. A deterministic follow-up through +`advanceNPCs` gives the first Leet an ordinary four-metre idle destination +`[134,14,98]`. The existing terrain-offset movement reaches approximately +`[133.01001,11.892994,98]` under water at Y13.520653. Ground/water eligibility +for roaming and pursuit remains unresolved; moving the initial home alone +does not solve that path. See `roaming-followup.log` and its retained reproducer. diff --git a/server/browser_fallback_placement_test.go b/server/browser_fallback_placement_test.go @@ -0,0 +1,108 @@ +package main + +import ( + "ao/server/assets" + "ao/server/gamedata" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestBrowserFallbackPlacementMelee(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for the focused fallback placement check") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/fallback-placement", time.Now().Format("20060102-150405")) + data := testNPCData() + for _, playfield := range gamedata.NPCs.Playfields { + if playfield.ID == 950 { + data.Playfields[0] = playfield + for _, district := range playfield.Districts { + if district.SourceIndex != nil && *district.SourceIndex == 5 { + data.Playfields[0].Districts = []gamedata.NPCDistrict{district} + } + } + } + } + data.Playfields[0].Districts[0].Groups[0] = *gamedata.NPCGroups["950/district/5/group/0/district_center_fallback"] + data.PlacementStatuses["district_center_fallback"] = gamedata.NPCs.PlacementStatuses["district_center_fallback"] + useNPCData(t, data) + useResources(t, assets.Files) + world := newTestServer(t) + enemy := world.characters[1000000] + for _, npc := range world.mobileNPCs[950] { + npc.motion.nextMove = time.Now().Add(time.Hour) + } + var players []*character + for index := 0; index < 2; index++ { + player := world.newCharacter() + player.name = fmt.Sprint("Fallback", index) + player.position = [3]float32{enemy.position[0] - 4, 20, enemy.position[2] + float32(index)*4} + point, normal := player.position, [3]float32{} + world.geometry.floor(950, world.terrain[950], player.position, &point, &normal) + player.position[1] = point[1] + .01 + player.rotation = [4]float32{0, .70710677, 0, .70710677} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("fallback-", index)))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + players = append(players, player) + } + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + defer world.mutex.Unlock() + json.NewEncoder(w).Encode(map[string]any{"enemy": enemy.id, "position": enemy.position, "home": enemy.motion.home, + "near": [2]float32{enemy.motion.home[0] - .75, enemy.motion.home[2]}, + "health": enemy.health, "owner": players[0].id, "ownerPosition": predictedPosition_locked(players[0], time.Now()), + "ownerFighting": players[0].fighting}) + }) + host := httptest.NewServer(mux) + defer host.Close() + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + stopped := make(chan struct{}) + go func() { + defer close(stopped) + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + select { + case now := <-ticker.C: + world.advancePlayerMovement(now) + world.advanceNPCs(now) + world.advanceCombat(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_fallback_placement.mjs"), host.URL, output) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + cancel() + <-stopped + t.Logf("Browser artifacts: %s", output) + + if err != nil { + t.Fatal(err) + } + if enemy.health >= 100 || enemy.motion.home[1] == 10.8 { + t.Fatal("native approach and melee did not reach the grounded fallback", enemy.position, enemy.health) + } +} diff --git a/server/npc_fallback_placement_test.go b/server/npc_fallback_placement_test.go @@ -0,0 +1,103 @@ +package main + +import ( + "ao/server/assets" + "ao/server/gamedata" + "testing" + "time" +) + +func TestFallbackNPCsUseDryDistrictCellsWithoutChangingSourcePoints(t *testing.T) { + data := testNPCData() + for _, playfield := range gamedata.NPCs.Playfields { + if playfield.ID == 950 { + data.Playfields[0] = playfield + for _, district := range playfield.Districts { + if district.SourceIndex != nil && *district.SourceIndex == 5 { + data.Playfields[0].Districts = []gamedata.NPCDistrict{district} + } + } + } + } + leet := *gamedata.NPCGroups["950/district/5/group/0/district_center_fallback"] + malle := *gamedata.NPCGroups["950/district/5/group/1/district_center_fallback"] + fixed := leet + fixed.ID, fixed.PlacementStatus, fixed.Positions = "test/fixed", "fixed_point", [][3]float32{{138, 10.8, 98}} + unreviewed := fixed + unreviewed.ID, unreviewed.TemplateCode, unreviewed.PlacementStatus = "test/unreviewed", "UNKNOWN", "district_center_fallback" + unreviewed.AppearanceStatus = "placeholder_creature" + data.Playfields[0].Districts[0].Groups = []gamedata.NPCGroup{leet, malle, fixed, unreviewed} + data.PlacementStatuses["district_center_fallback"] = gamedata.NPCs.PlacementStatuses["district_center_fallback"] + useNPCData(t, data) + useResources(t, assets.Files) + + world := newTestServer(t) + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + + for _, current := range []*server{world, cold} { + for index, expected := range [][3]float32{{130, 14, 98}, {134, 15.199999, 90}, {150, 14.200001, 106}, {130, 16, 94}, {146, 14.6, 110}, {150, 15.6, 110}} { + npc := current.characters[1000000+uint32(index)] + if npc.position != expected || npc.motion.home != npc.position { + t.Fatal("generated fallback lost its dry source-cell sample", npc.id, npc.position, npc.motion.home) + } + } + if current.characters[1000006].position != [3]float32{138, 10.8, 98} { + t.Fatal("ground adjustment changed an authored fixed point") + } + if current.characters[1000007].position != [3]float32{138, 10.8, 98} || current.characters[1000007].combatProfile != nil { + t.Fatal("ground placement admitted an unreviewed combat contract") + } + } + if gamedata.NPCGroups[leet.ID].Positions[0] != [3]float32{138, 10.8, 98} || gamedata.NPCGroups[malle.ID].Positions[0] != [3]float32{140, 10.8, 100} { + t.Fatal("runtime placement rewrote raw source points") + } + + source := world.characters[1000000] + source.health = 0 + now := time.Now() + world.npcRespawns = []npcRespawn{{source, now}} + world.advanceNPCRespawns(now) + restored := newTestInventoryServer(t) + + respawn := restored.characters[world.nextNPC-1] + if respawn.position != [3]float32{130, 14, 98} || respawn.motion.home != respawn.position || respawn.health != 100 { + t.Fatal("respawn or cold recovery lost the dry home", respawn.position, respawn.motion.home) + } +} + +func TestFallbackNPCPlacementCoversEveryAdmittedProductionActor(t *testing.T) { + world := newTestServer(t) + byGroup := make(map[string][]*character) + for _, npc := range world.characters { + if npc.npc && npc.combatProfile != nil && gamedata.NPCGroups[npc.npcDefinitionID].PlacementStatus == "district_center_fallback" { + byGroup[npc.npcDefinitionID] = append(byGroup[npc.npcDefinitionID], npc) + } + } + count := 0 + + for _, playfield := range gamedata.NPCs.Playfields { + layout := world.geometry.playfields[playfield.ID] + seen := make(map[[3]float32]bool) + for _, district := range playfield.Districts { + for _, group := range district.Groups { + for _, npc := range byGroup[group.ID] { + point, normal := npc.position, [3]float32{} + water := world.geometry.floor(npc.playfield, world.terrain[npc.playfield], npc.position, &point, &normal) + cell, inside := layout.cellIndex(npc.position) + if !inside || playfield.Source.ZoneToDistrictMap[cell] != uint16(*district.SourceIndex) || + water.height > point[1] || npc.motion.home != npc.position || seen[npc.position] { + t.Fatal("production fallback lost its distinct dry source-district position", group.ID, npc.id, npc.position) + } + seen[npc.position] = true + count++ + } + } + } + } + if count != 23 { + t.Fatal("admitted fallback population coverage changed", count) + } +} diff --git a/server/npc_placement.go b/server/npc_placement.go @@ -0,0 +1,73 @@ +package main + +import "ao/server/gamedata" + +func (server *server) placeFallbackNPCs(spawns []character) { + // Collect admitted combatants without changing the catalog's source placements. + byGroup := make(map[string][]*character) + for index := range spawns { + spawn := &spawns[index] + if spawn.combatProfile != nil && gamedata.NPCGroups[spawn.npcDefinitionID].PlacementStatus == "district_center_fallback" { + byGroup[spawn.npcDefinitionID] = append(byGroup[spawn.npcDefinitionID], spawn) + } + } + + // Only generated combat placements use dry ground; authored points stay intact. + for _, playfield := range gamedata.NPCs.Playfields { + layout, exists := server.geometry.playfields[playfield.ID] + ground := server.terrain[playfield.ID] + if !exists || ground == nil || playfield.Source == nil || len(playfield.Source.ZoneToDistrictMap) != layout.cellsX*layout.cellsZ { + continue + } + for _, district := range playfield.Districts { + if district.SourceIndex == nil { + continue + } + var generated []*character + for _, group := range district.Groups { + generated = append(generated, byGroup[group.ID]...) + } + if len(generated) == 0 { + continue + } + + // Sample original terrain tiles only inside this district's source cells. + var candidates [][3]float32 + for cell, source := range playfield.Source.ZoneToDistrictMap { + if source != uint16(*district.SourceIndex) { + continue + } + x, z := float32(cell%layout.cellsX)*layout.cellWidth, float32(cell/layout.cellsX)*layout.cellDepth + for sampleZ := z + ground.spacing/2; sampleZ < z+layout.cellDepth; sampleZ += ground.spacing { + for sampleX := x + ground.spacing/2; sampleX < x+layout.cellWidth; sampleX += ground.spacing { + height, inside := ground.elevation(sampleX, sampleZ) + if !inside { + continue + } + point, normal := [3]float32{sampleX, height, sampleZ}, [3]float32{} + water := server.geometry.floor(playfield.ID, ground, point, &point, &normal) + if water.height <= point[1] { + candidates = append(candidates, point) + } + } + } + } + + // Use the closest unused dry tile; identity and raw source records are unchanged. + for _, spawn := range generated { + if len(candidates) == 0 { + break + } + closest := 0 + for candidate := 1; candidate < len(candidates); candidate++ { + if surfaceDistanceSquared(spawn.position, candidates[candidate]) < surfaceDistanceSquared(spawn.position, candidates[closest]) { + closest = candidate + } + } + spawn.position = candidates[closest] + spawn.motion.home = spawn.position + candidates = append(candidates[:closest], candidates[closest+1:]...) + } + } + } +} diff --git a/server/state.go b/server/state.go @@ -194,6 +194,7 @@ func newServer() *server { if err != nil { panic(err) } + server.placeFallbackNPCs(spawns) for _, spawn := range spawns { server.characters[spawn.id] = &spawn server.nextNPC = max(server.nextNPC, spawn.id+1) diff --git a/tools/client/test_fallback_placement.mjs b/tools/client/test_fallback_placement.mjs @@ -0,0 +1,80 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import {GameTest} from './game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const [url, output] = process.argv.slice(2); +const browser = await chromium.launch({executablePath: '/usr/bin/chromium', + args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +const games = [], evidence = {}; +const state = async () => (await games[0].page.request.get(url+'/test-state')).json(); +const actor = (game, id) => game.state.actors.find(actor => actor.type === 50000 && actor.id === id); +try { + for (let index = 0; index < 2; ++index) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'fallback-'+index, url}]); + const page = await context.newPage(); + const game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + } + const [owner] = games; + evidence.initial = await state(); + assert.equal(evidence.initial.health, 100); + if (!owner.state.camera.firstPerson) await owner.key('F8'); + + // Tilt the real camera down the shore before asking the native picker to select. + const cameraPoint = await owner.point(512, 300); + let mouseY = cameraPoint.y, sequence = owner.sequence; + await owner.page.mouse.move(cameraPoint.x, mouseY); + await owner.page.mouse.down({button: 'right'}); + try { + await owner.waitInput(sequence, 1025); + const deadline = Date.now()+10000; + for (;;) { + await owner.snapshot(); + const screenY = actor(owner, evidence.initial.enemy).screenPosition[1]; + if (screenY >= 350 && screenY <= 540) break; + assert(Date.now() < deadline, 'Camera did not frame the Leet above chat'); + mouseY += screenY > 540 ? 20 : -20; + await owner.page.mouse.move(cameraPoint.x, mouseY, {steps: 2}); + } + } finally { + sequence = owner.sequence; + await owner.page.mouse.up({button: 'right'}); + } + await owner.waitInput(sequence, 1026); + const pixel = await owner.pick(50000, evidence.initial.enemy); + await owner.click(...pixel); + await owner.wait('ordinary target selection', snapshot => snapshot.selected[1] === evidence.initial.enemy); + await owner.walk(...evidence.initial.near); + evidence.approach = {server: await state(), native: owner.local().position}; + assert(Math.hypot(...evidence.approach.server.ownerPosition.map((value, axis) => value-evidence.approach.native[axis])) < .5); + await owner.save(output+'/approach'); + await owner.key('KeyQ'); + const deadline = Date.now()+12000; + for (;;) { + evidence.hit = await state(); + if (evidence.hit.health < 100) break; + assert(Date.now() < deadline, 'Ordinary melee did not damage the fallback'); + await owner.snapshot(); + } + await owner.key('KeyQ'); + await owner.wait('ordinary stop attack', () => owner.local().combatTarget === 0); + evidence.stopped = await state(); + await Promise.all(games.map(game => game.wait('both native replicas retain the melee hit', () => + actor(game, evidence.initial.enemy)?.stats[27] === evidence.stopped.health))); + evidence.clients = games.map(game => ({position: actor(game, evidence.initial.enemy).position, + health: actor(game, evidence.initial.enemy).stats[27]})); + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: real walking, native picking and ordinary melee reach the grounded generated fallback on both clients'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output+'/verification.json', JSON.stringify(evidence, null, 2)); + await Promise.all(games.map((game, index) => game.save(output+'/final-'+index))); + } finally { await browser.close(); } +}