commit 2f4d2982e3e60a846df671e7a2578ae5831c0493 parent f0debd4139a55f9c7c6b49d4f9bae29de522827f Author: anon <anon@example.com> Date: Wed, 28 Oct 2026 00:31:41 +0000 Bind persistent native doors to open mission passages Diffstat:
27 files changed, 651 insertions(+), 57 deletions(-)
diff --git a/TODO.md b/TODO.md @@ -457,12 +457,14 @@ capacity checks are recorded in [belts and NCU](docs/belts-ncu.md). distinguish clear-path attack results from occluded target selection; those client selection checks alone do not establish server rejection. See [combat visibility](docs/combat-visibility.md) for evidence and policy limits. -- [ ] [P0] Synchronize native visibility across open mission passages. The current - empty-door-identity passage is traversable, but read-only WASM probes still show - room0/room1's visibility pair as open0. Recover the shared registration/status - rule or bind real authored doors; verify clear cross-room targeting, ordinary - damage presentation and nano casting in both directions. Keep this separate - from ray obstruction and do not hardcode a particular room pair as visible. +- [x] [P0] Synchronize native visibility across open mission passages. Acceptance + atomically creates stable native door identities at paired original portals; + entry/reconnect replay their full updates followed by open, latched status. + Read-only WASM probes show the real door and open1 visibility pair. Native + targeting, ordinary damage and nano execution work across the passage in both + directions. Tests cover rollback/retry, concurrent owners, cold replay and + retirement. Historical door style and automatic/locked access remain P1 below. + See [mission doors](docs/mission-doors.md#persistent-open-mission-passages). - [x] Reconcile quiet health without phantom damage feedback. Check: after a long native fight, prediction drift is corrected to server HP without extra nanobot-damage chat or floating damage, including for an observer. @@ -1549,13 +1551,14 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). NPC/corpse/objective retirement now shares assignment revocation and occupant evacuation in one transaction. Complete the remaining cross-instance negative cases, including nanos, inspection, trade and vicinity chat. -- [ ] [P1] Bind original mission doors and recover their style/access policy. +- [ ] [P1] Recover original mission-door style and access policy. The extractor decodes298 rooms from four ACD libraries and3692 door placements with53 templates. Shared builders preserve authored door flags and optional QL; published-WASM fixtures verify locked blocking, unlock/open, relocking and return. Shared movement uses original tile/mesh geometry, paired portals, room admission and floor/ceiling queries. Four rotations and native wall/doorway stops match. - The live prototype uses the native empty-door-identity branch for open passages. + The live prototype binds persistent doors using native-tested template41565 + and holds them unlocked/open; this does not establish historical style choice. Recover real template/style selection, auto-open timing and locked/keyed access; test forged reports, both sides, concurrent use, reconnect and revocation. See [mission doors](docs/mission-doors.md) and the interior research above. diff --git a/docs/combat-visibility.md b/docs/combat-visibility.md @@ -18,14 +18,12 @@ Both dungeon endpoints must belong to rooms. The same room passes the room gate; different rooms require an open direct visibility-pair entry. Original `IsDoorOpenBetweenRooms` at `0x1002bfd0` checks a sorted room pair and requires its status byte to equal 1. It does not search for a path through other rooms. -Current generated missions have paired passages without dynamic door identities; -their existing room links supply those open pairs. Closed animated doors and -broader visibility-pair initialization remain future work. - -Read-only WASM probes still report the empty-identity client pair as open0. -Server passage admission follows the existing traversable-link policy; matching -client visibility status is an explicit P0 follow-up. A clear server ray across -that passage does not prove that the client's LOS-dependent presentation works. +Current generated missions bind persistent native doors to those paired portals +and replay full updates followed by open, latched status. Read-only WASM probes +confirm the real door identity and open1 visibility entry. Ordinary melee damage +and targeted nano execution have been checked across the passage in both +directions. See [mission doors](mission-doors.md#persistent-open-mission-passages) +for lifecycle checks and the remaining style/access-policy limits. The maintained equivalents are `sub_360721D0` in `client/game/kkr.dll/lifted-0033.c`, `sub_3802C090`, `sub_3802C170` and diff --git a/docs/mission-doors.md b/docs/mission-doors.md @@ -1,9 +1,11 @@ # Original mission door contracts -Private mission entry remains unimplemented. These contracts and owned native -fixtures extend the [mission interior investigation](mission-interiors.md); -there is no production door-state consumer yet. No server or client runtime -change was needed for these protocol experiments. +Accepted private missions create persistent native doors at paired interior +portals. Their full updates and open status make cross-room visibility agree +with the server's open-passage policy. The current template and held-open policy +are explicit reconstruction choices; historical style selection, automatic +opening and locked/keyed interior access remain unresolved. The earlier protocol +fixtures below extend the [mission interior investigation](mission-interiors.md). ## Native messages @@ -28,7 +30,7 @@ Apply `0x100b02d0` creates the absent Door, applies its template/stats and world position, and calls `0x1008da10` to link it to nearby room portals. That routine records the packed room pair, registers internal doors with the room-link table, and handles unmatched exterior entrances separately. Initial opening -depends on Flags bit128. The prototype uses original template41884/mesh41798; +depends on Flags bit128. The early fixture uses original template41884/mesh41798; this is not a recovered mission-style-to-door assignment. The status reader/writer (`0x100b0460` / `0x100b06f0`) carry: @@ -96,8 +98,8 @@ identify separate static model42850 with a black material at that portal. Rotating the entrance template to leave the black portal as the exterior fixes the adjoining view without a client patch. Reciprocal links and exactly one exterior door do not by themselves validate authored portal selection. Keep -status flag semantics, mission/world/key allocation, movement/terrain, isolation -and retirement open. +status flag semantics open; these client-side fixtures do not establish +mission/world/key allocation, movement/terrain, isolation or retirement. Corrected-layout published-WASM fixtures281/282 verify open/close/reopen with 41884 and41565, including room disablement after the deferred close. Both also @@ -116,7 +118,7 @@ no authored QL; their updates omit stat701 rather than inventing a quality. Status serialization keeps lock, open and the additional latch independent; stat195 remains zero and the identity list empty in this supported subset. The extra flag's producer policy and the additional full-update DWORD remain -unresolved. These are packet builders, with no production admission consumer. +unresolved. The live mission consumer uses these builders as described below. Original SimpleItem Apply `KKR:0x100b25c0` maps Flags bit0x200 to `n3Dynel_t::SetTellCollinfo`. That does not establish it as a requirement for @@ -172,3 +174,87 @@ Complete evidence bundles: `kkr-door-messages-evidence.json`, - Room registration: `ev_31100d524c5f3d3ab2ab6a1d56fe9bb472071b8035656f441b0bac84160ca5e6`. - Key hashing: `ev_357e5b852dc22d8e79b1b755e1f0f48831608614a42575692f563b85a9787662`. - Frame evaluation: `ev_10496a0c940675df68a5c8cf50aa2569089fb3c91fc8e86f38ef7c7f026a339e`. + +## Persistent open mission passages + +An empty native door identity is sufficient for walking between paired rooms, +but not for visibility. Original KKR `ConnectRooms` at `0x100f2f30` writes +reciprocal room neighbors without opening their visibility entry. Original +`IsDynelRoomTransitionAllowed` at `0x1014cf70` accepts a found empty identity; +LLR `RoomCanSeeFromTo` separately requires status1. The maintained LLR +`sub_3802C270` in `client/game/llr.dll/lifted-0018.c` initializes paired entries +with status0 and identity0/0. Registering a Door changes the identity; opening +that Door changes the status. No missing adapter or mistranslated initializer +was established by the bounded audit. + +A DoorStatus update resolves an existing Door_t. It cannot create one or use +its unused identity list to address arbitrary room pairs. The server therefore +creates concrete doors at the matched original portal poses, using the shared +full-update and status serializers. The unmatched exterior return portal remains +under the existing key-gated private-world admission path. + +`passage_door` in the mission content selects original template41565 for the +fixed prototype. Its physical fit and room registration are native-tested; +its selection for historical331 missions is unproven. The generator packet has +no door-template field. The audit found no direct mapping in the298 room records, +four library suffixes or static placements:331,341 and351 contain no type51016 +placements;346 has one authored41883 placement, which does not establish a rule +for every generated portal. Template41565's prevalence in public placements also +does not establish such a rule. Keep style recovery open. + +Acceptance stages one door per paired portal and inserts its concrete template, +passage index and identity in `mission_doors` in the same transaction as the key, +assignment and encounters. SQLite allocates monotonically increasing identities +within type51016; these do not consume item or NPC IDs. Rollback publishes +nothing. Restart reads these records instead of regenerating their templates +from mutable content. Missing or unpaired saved bindings fail replay explicitly. +There is no legacy-door synthesis or schema migration. + +Entry and reconnect send the generated world before each door's full update and +open/latched status. Replay is scoped to the exact runtime mission world and +works for guests without duplicating ownership. Doors remain unlocked and held +open; the extra status flag keeps the original client from immediately closing +them. This is the supported open-passage policy, not recovered automatic timing +or access rules. Completion retains doors with the occupied world until its +original deadline. Abandonment/expiry delete them with the assignment and +occupant returns in one transaction, then notify clients before redirects. + +Tests cover real socket initialization order, owner/guest replay, multiple paired +portals, retained portal poses at all four rotations, cold restoration, offered +content changes, invalid templates, incomplete bindings, concurrent-owner IDs, +failed/ignored/rewritten inserts and failed deferred commits. Retirement tests +cover failure/retry while occupied, completed-world retention, copied-key guests, +expiry and nonreuse of retired identities. Shared movement and combat visibility +checks continue to use the same portal graph and obstruction queries. + +The unmodified published WASM client ran on the GPU against the sole +HTTPS8443 preview. Normal native journal abandonment and terminal acceptance +created mission41/world65540 and door51016/1 through the production server. +Read-only probes show room0/room1's pair at open1 with that real identity, including +reconnect after restoring the test character's normal profile. Ordinary melee +landed across the passage in both directions:4 damage to Leet1068622 and5 to +Leet1068621. Native Winter's Bite29618 completed across it northward for18 cold +damage to1068620 and southward for17 to1068622, with normal execution and damage +feedback. Initial low-skill attempts were rejected by native requirements and +are excluded from the successful-cast evidence. No client patch, packet rewrite, +page exception or adapter abort occurred. Two resource404 console messages +remain baseline observations. + +Evidence is retained in `local/mission-passage-research/`: `runtime/`, +`runtime-nano/`, `native-verification.json`, `empty-door-initialization-audit.md` +and `data-and-integration-audit.md`. Original KKR evidence is in +`kkr-evidence.json`: ConnectRooms +`ev_9822044d0ecbf142b314d0e91b339309399eb8857bde9a85de079b6515e46b18` +and transition admission +`ev_ca4275de1f93820fa3e93fa6609a6c7009b96838e4cd16c82fa0485aca77abb1`. +The earlier original door-message and LLR visibility evidence above supplies +the status/LOS contracts. The owned browsers and analysis sessions are closed; +normal player skills, profession, learned programs and vitals are restored. +Earned items, XP, cash and the fresh assignment are retained. SQLite integrity, +foreign keys and the five surviving mission NPCs were rechecked. + +The final regression run passes134 test functions and839 test/subtest results +across `./server/...` with the mission, door and visibility filter. Race detection +passes24 functions and55 results covering door lifecycle, concurrent acceptance, +retirement and visibility. `go vet ./server/...`, the final server build and cold +native reconnect pass. diff --git a/docs/mission-interiors.md b/docs/mission-interiors.md @@ -588,15 +588,16 @@ players, keys and journal for retry. Geometry is removed only after committed returns are published, and the owner's journal retirement precedes its redirect. Startup expiry loads the saved scene before evacuating occupants. Remaining floor objectives now retire in that same transaction; collected books keep -ordinary inventory ownership. NPCs and mission corpses do not exist in this -prototype; their eventual retirement remains part of population work. - -The two rooms retain empty native door identities, which mean open passages. -This establishes a usable fixed prototype, not recovered style selection or -locked internal doors. Their actual templates, automatic opening and access -policy remain open in [mission doors](mission-doors.md). The mission now supports -[bound floor-item collection](mission-objectives.md); enemies, objective -completion and rewards remain open. +ordinary inventory ownership. Mission NPCs and corpses also retire in that +transaction; completion retains the occupied world until its original deadline. + +The paired interior portal now has a persistent native door, replayed open and +latched after the generated world update. An empty door identity admits movement +but leaves native visibility closed; real full/status updates fix cross-room +melee and nanos. Historical style selection, automatic opening and locked access +remain open in [mission doors](mission-doors.md#persistent-open-mission-passages). +The current mission also supports [bound floor-item collection](mission-objectives.md), +encounters, objective completion and cash/item rewards. An owned GPU WASM client on the single HTTPS8443 preview accepted the mission through the normal terminal, walked through the Surveillance Office entrance diff --git a/server/combat_visibility.go b/server/combat_visibility.go @@ -33,7 +33,7 @@ func (geometry *sceneGeometry) lineOfSight(playfield uint32, origin, end [3]floa if first != second { linked := false for _, link := range scene.links { - if link == [2]*placedRoom{first, second} || link == [2]*placedRoom{second, first} { + if link.rooms == [2]*placedRoom{first, second} || link.rooms == [2]*placedRoom{second, first} { linked = true break } diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -193,6 +193,9 @@ func init() { // Accepted contracts retain the advertised selected quality, including intermediates. for booth, mission := range MissionTemplates { + if ItemTemplates[mission.PassageDoor] == nil || ItemTemplates[mission.PassageDoor].HeaderWords[0] != 51016 { + panic(fmt.Errorf("invalid mission door %d: template %d", booth, mission.PassageDoor)) + } if (mission.RewardItem != 0 || mission.RewardQuality != 0) && !ItemQualitySupported(mission.RewardItem, mission.RewardQuality) { panic(fmt.Errorf("invalid mission reward %d: template %d quality %d", booth, mission.RewardItem, mission.RewardQuality)) } diff --git a/server/gamedata/mission_booths_test.go b/server/gamedata/mission_booths_test.go @@ -88,7 +88,7 @@ func TestStarterMissionTemplateReferencesOriginalAssets(t *testing.T) { item := ItemTemplates[definition.ObjectiveItem] if definition.Playfield != booth.Playfield || definition.Playfield != 3000 || definition.Entrance != 3221228472 || - definition.RewardItem != 85596 || definition.RewardQuality != 2 || !ItemQualitySupported(definition.RewardItem, definition.RewardQuality) || + definition.RewardItem != 85596 || definition.RewardQuality != 2 || !ItemQualitySupported(definition.RewardItem, definition.RewardQuality) || definition.PassageDoor != 41565 || definition.Position != [3]float32{89.30216217041016, 115.14443969726562, 151.16087341308594} || item == nil || item.ID != 40822 || item.Quality == nil || *item.Quality != 1 || item.PayloadSHA256 != "645b946ec12830a3695e1c27659dc37676dbc2b884cb1f19e4fda1692e7066fe" { diff --git a/server/gamedata/missions.yaml b/server/gamedata/missions.yaml @@ -20,6 +20,9 @@ reward_item: 85596 reward_quality: 2 + # Native-tested open passage; historical mission-style selection is unresolved. + passage_door: 41565 + # Fixed encounter selection and positions are reconstruction policy. # Species appearance, weapon and loot use the shared admitted NPC profile. encounters: diff --git a/server/gamedata/types.go b/server/gamedata/types.go @@ -31,6 +31,7 @@ type MissionTemplate struct { RewardItem uint32 `yaml:"reward_item"` RewardQuality uint32 `yaml:"reward_quality"` Encounters []MissionEncounter `yaml:"encounters"` + PassageDoor uint32 `yaml:"passage_door"` } type MissionEncounter struct { diff --git a/server/item_database.go b/server/item_database.go @@ -309,15 +309,34 @@ func (server *server) persistItems_locked(store itemStore) error { return fmt.Errorf("mission NPC %d state changed before commit", npc.id) } } + if store.mission != nil { + var count int + if err := tx.QueryRow("SELECT count(*) FROM mission_doors WHERE mission_id=?", store.mission.id).Scan(&count); err != nil { + return err + } + if count != len(store.mission.doors) { + return fmt.Errorf("mission %d door count changed before commit", store.mission.id) + } + for _, door := range store.mission.doors { + var saved missionDoor + if err := tx.QueryRow("SELECT id,passage,template FROM mission_doors WHERE id=? AND mission_id=?", door.id, store.mission.id).Scan(&saved.id, &saved.passage, &saved.template); err != nil { + return err + } + if saved != door { + return fmt.Errorf("mission door %d changed before commit", door.id) + } + } + } if store.removedMission != nil { var remaining int if err := tx.QueryRow(`SELECT (SELECT count(*) FROM characters WHERE id>=1000000 AND playfield=?) + - (SELECT count(*) FROM missions WHERE id=?)`, store.removedMission.world, store.removedMission.id).Scan(&remaining); err != nil { + (SELECT count(*) FROM missions WHERE id=?) + + (SELECT count(*) FROM mission_doors WHERE mission_id=?)`, store.removedMission.world, store.removedMission.id, store.removedMission.id).Scan(&remaining); err != nil { return err } if remaining != 0 { - return fmt.Errorf("retired mission %d retains its assignment or NPCs", store.removedMission.id) + return fmt.Errorf("retired mission %d retains its assignment, NPCs or doors", store.removedMission.id) } } if err := tx.Commit(); err != nil { diff --git a/server/main.go b/server/main.go @@ -420,6 +420,13 @@ func (server *server) serveWorldClient(client *worldClient) error { updates = append(updates, equippedWeaponPackets(character)...) updates = append(updates, server.combatInterest_locked(client, nil)...) if client.target { + doors, err := server.missionDoorPackets_locked(character) + if err != nil { + server.mutex.Unlock() + server.updateMutex.Unlock() + return err + } + updates = append(updates, doors...) updates = append(updates, server.worldItemPackets_locked(character)...) for id, machine := range gamedata.ShopMachines { if machine.Playfield == character.playfield { diff --git a/server/mission_completion_test.go b/server/mission_completion_test.go @@ -388,9 +388,13 @@ func TestMissionReturnPreservesGuestsUntilOriginalDeadline(t *testing.T) { cold = reloadMissionEntranceWorld(t) if len(cold.missionExpiry) != 0 || cold.geometry.mission(65536) != nil || cold.characters[2].playfield != 3000 || - cold.characters[3].playfield != 3000 || cold.characters[1].inventory.Credits != 24 || len(output.packets) != 0 || len(guestOutput.packets) != 2 { + cold.characters[3].playfield != 3000 || cold.characters[1].inventory.Credits != 24 || len(output.packets) != 0 || len(guestOutput.packets) != 3 { t.Fatal("completed-world deadline failed to evacuate guests or sent a false expiry/reward", output.packets, guestOutput.packets) } + if !bytes.Equal(guestOutput.packets[0][16:], targetPacket(n3Packet(0x36510078, 51016, 1, nil))[16:]) || + binary.BigEndian.Uint32(guestOutput.packets[1][16:20]) != 0x43197d22 { + t.Fatal("expired-world door removal must precede guest evacuation", guestOutput.packets) + } } func TestMissionReturnCancelsCopiedKeyTradeOnlyAfterCommit(t *testing.T) { diff --git a/server/mission_doors.go b/server/mission_doors.go @@ -0,0 +1,90 @@ +package main + +import ( + "ao/server/gamedata" + "fmt" + "math" +) + +type missionDoor struct { + id, passage, template uint32 +} + +func (server *server) stageMissionDoors_locked(mission *acceptedMission) error { + definition := gamedata.ItemTemplates[mission.offer.definition.PassageDoor] + if definition == nil || definition.HeaderWords[0] != 51016 { + return fmt.Errorf("unsupported mission passage door %d", mission.offer.definition.PassageDoor) + } + layout, err := decodeMissionLayout(mission.layout) + if err != nil { + return err + } + scene, err := server.geometry.missionScene(layout) + if err != nil { + return err + } + if err := scene.connectRooms(layout); err != nil { + return err + } + for passage := range scene.links { + mission.doors = append(mission.doors, missionDoor{passage: uint32(passage), template: mission.offer.definition.PassageDoor}) + } + return nil +} + +func (server *server) loadMissionDoors() error { + rows, err := server.db.Query("SELECT id,mission_id,passage,template FROM mission_doors ORDER BY id") + if err != nil { + return err + } + defer rows.Close() + missions := make(map[uint32]int) + for index := range server.missionExpiry { + missions[server.missionExpiry[index].id] = index + } + for rows.Next() { + var door missionDoor + var mission uint32 + if err := rows.Scan(&door.id, &mission, &door.passage, &door.template); err != nil { + return err + } + index, exists := missions[mission] + definition := gamedata.ItemTemplates[door.template] + if !exists || definition == nil || definition.HeaderWords[0] != 51016 { + return fmt.Errorf("invalid saved mission door %d", door.id) + } + server.missionExpiry[index].doors = append(server.missionExpiry[index].doors, door) + } + return rows.Err() +} + +func (server *server) missionDoorPackets_locked(player *character) ([][]byte, error) { + mission := server.missionWorld_locked(player.playfield) + if mission == nil { + return nil, nil + } + scene, err := server.prepareMissionWorld_locked(mission) + if err != nil { + return nil, err + } + if len(mission.doors) != len(scene.links) { + return nil, fmt.Errorf("mission %d has incomplete passage doors", mission.id) + } + var packets [][]byte + for _, door := range mission.doors { + if uint64(door.passage) >= uint64(len(scene.links)) { + return nil, fmt.Errorf("mission door %d has no paired passage", door.id) + } + link := scene.links[door.passage] + angle := float64(link.direction) * math.Pi / 4 + placed := worldDoor{id: door.id, template: door.template, position: link.position, + rotation: [4]float32{0, float32(math.Sin(angle)), 0, float32(math.Cos(angle))}, open: true} + packet, err := doorPacket(player.playfield, placed) + if err != nil { + return nil, err + } + // Door status updates need an existing Door_t; latch the authored open passage. + packets = append(packets, packet, doorStatusPacket(door.id, false, true, true)) + } + return packets, nil +} diff --git a/server/mission_doors_test.go b/server/mission_doors_test.go @@ -0,0 +1,337 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "net" + "reflect" + "testing" + "time" +) + +func newMissionDoorOfferWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + world, output := newMissionOfferWorld(t) + t.Cleanup(func() { world.db.Close() }) + if err := world.handleMissionOffers(world.clients[1], missionOffersRequest()); err != nil { + t.Fatal(err) + } + output.packets = nil + return world, output +} + +func TestMissionDoorsAcceptRestoreAndReplayOnlyWithinTheirWorld(t *testing.T) { + world, _ := newMissionDoorOfferWorld(t) + client := world.clients[1] + + if err := world.handleMissionAcceptance(client, missionAcceptanceRequest(*client.missionOffer)); err != nil { + t.Fatal(err) + } + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + mission := cold.characters[1].missions[0] + player := cold.characters[1] + player.playfield = mission.world + packets, err := cold.missionDoorPackets_locked(player) + guest := *player + guest.id, guest.missions = 2, nil + guestPackets, guestErr := cold.missionDoorPackets_locked(&guest) + guest.playfield++ + otherPackets, otherErr := cold.missionDoorPackets_locked(&guest) + + if err != nil || guestErr != nil || otherErr != nil || len(packets) != 2 || len(otherPackets) != 0 || + !reflect.DeepEqual(guestPackets, packets) || !reflect.DeepEqual(mission.doors, []missionDoor{{id: 1, passage: 0, template: 41565}}) || + !reflect.DeepEqual(mission.doors, world.characters[1].missions[0].doors) || mission.offer.definition.PassageDoor != 0 { + t.Fatal("door identity, concrete template or world replay changed", err, guestErr, otherErr, mission.doors) + } + full, fullErr := doorPacket(65536, worldDoor{id: 1, template: 41565, position: [3]float32{15, 0, 29.999}, rotation: [4]float32{0, 0, 0, 1}, open: true}) + if fullErr != nil || !bytes.Equal(packets[0], full) || !bytes.Equal(packets[1], doorStatusPacket(1, false, true, true)) { + t.Fatal("original portal pose or native creation/status order changed", fullErr) + } +} + +func TestMissionDoorsNativeSocketReplaysAfterPlayfieldAndBeforeReady(t *testing.T) { + world, _ := newMissionDoorOfferWorld(t) + if err := world.handleMissionAcceptance(world.clients[1], missionAcceptanceRequest(*world.clients[1].missionOffer)); err != nil { + t.Fatal(err) + } + player := world.characters[1] + player.playfield, player.position = 65536, [3]float32{15, .011, 29} + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + connection, remote := net.Pipe() + connection.SetDeadline(time.Now().Add(5 * time.Second)) + done := make(chan error, 1) + go func() { + defer remote.Close() + done <- cold.serveWorldConnection(remote) + }() + defer func() { connection.Close(); <-done }() + + cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) + binary.BigEndian.PutUint16(cookie, 0xdfdf) + if _, err := connection.Write(cookie); err != nil { + t.Fatal(err) + } + var keys []uint32 + for { + packet, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + key := binary.BigEndian.Uint32(packet[16:20]) + keys = append(keys, key) + if key == 0x5f52412e { + break + } + } + + full, status := -1, -1 + for index, key := range keys { + if key == 0x365a5071 { + full = index + } + if key == 0x4c7d403b { + status = index + } + } + if keys[0] != 0x5f4b1a39 || full < 1 || status != full+1 { + t.Fatal("door status arrived without its generated world or full update", keys) + } +} + +func TestMissionDoorAcceptanceFailureKeepsOfferCashAndIdentityAllocation(t *testing.T) { + for _, statement := range []string{ + "CREATE TRIGGER fail_door BEFORE INSERT ON mission_doors BEGIN SELECT RAISE(FAIL, 'test door'); END", + "CREATE TRIGGER fail_door BEFORE INSERT ON mission_doors BEGIN SELECT RAISE(IGNORE); END", + "CREATE TRIGGER fail_door AFTER INSERT ON mission_doors BEGIN UPDATE mission_doors SET template=41884 WHERE id=NEW.id; END", + "CREATE TRIGGER fail_door AFTER INSERT ON mission_doors BEGIN UPDATE mission_doors SET id=2 WHERE id=NEW.id; END", + "CREATE TRIGGER fail_door AFTER INSERT ON mission_doors BEGIN INSERT INTO mission_doors (mission_id,passage,template) VALUES (NEW.mission_id,1,41565); END", + "CREATE TABLE pending_door (mission_id INTEGER REFERENCES missions(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_door AFTER INSERT ON mission_doors BEGIN INSERT INTO pending_door VALUES (999999); END", + } { + t.Run(statement, func(t *testing.T) { + world, output := newMissionDoorOfferWorld(t) + client, player := world.clients[1], world.characters[1] + request := missionAcceptanceRequest(*client.missionOffer) + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + + err := world.handleMissionAcceptance(client, request) + var doors, missions, items int + if queryErr := world.db.QueryRow("SELECT (SELECT count(*) FROM mission_doors),(SELECT count(*) FROM missions),(SELECT count(*) FROM items)").Scan(&doors, &missions, &items); queryErr != nil { + t.Fatal(queryErr) + } + + if err == nil || doors != 0 || missions != 0 || items != 1 || len(player.missions) != 0 || client.missionOffer == nil || + player.inventory.Credits != 4 || world.nextItem != 1 || len(output.packets) != 0 || len(world.missionExpiry) != 0 { + t.Fatal("failed door allocation leaked its acceptance", err, doors, missions, items) + } + if _, err := world.db.Exec("DROP TRIGGER fail_door"); err != nil { + t.Fatal(err) + } + if err := world.handleMissionAcceptance(client, request); err != nil { + t.Fatal(err) + } + if world.characters[1].missions[0].doors[0].id != 1 { + t.Fatal("rollback consumed an unpublished door identity") + } + }) + } +} + +func TestMissionDoorsRetainOnCompletionAndRetireAtomically(t *testing.T) { + for _, complete := range []bool{false, true} { + t.Run(map[bool]string{false: "abandon", true: "complete then expire"}[complete], func(t *testing.T) { + world, _ := newMissionDoorOfferWorld(t) + if err := world.handleMissionAcceptance(world.clients[1], missionAcceptanceRequest(*world.clients[1].missionOffer)); err != nil { + t.Fatal(err) + } + mission := world.characters[1].missions[0] + updates := make(map[*worldClient][][]byte) + + if _, err := world.endMission_locked(mission, complete, updates); err != nil { + t.Fatal(err) + } + if complete { + cold := reloadMissionEntranceWorld(t) + if len(cold.missionExpiry) != 1 || len(cold.missionExpiry[0].doors) != 1 { + t.Fatal("completion retired retained-world doors") + } + if err := world.expireMissions_locked(mission.expiresAt, updates); err != nil { + t.Fatal(err) + } + } + cold := reloadMissionEntranceWorld(t) + var doors int + if err := cold.db.QueryRow("SELECT count(*) FROM mission_doors").Scan(&doors); err != nil { + t.Fatal(err) + } + + if doors != 0 || len(cold.missionExpiry) != 0 { + t.Fatal("retired assignment retained its native doors") + } + if err := world.handleMissionOffers(world.clients[1], missionOffersRequest()); err != nil { + t.Fatal(err) + } + if world.clients[1].missionOffer == nil { + t.Fatal("cannot browse the next assignment") + } + if err := world.handleMissionAcceptance(world.clients[1], missionAcceptanceRequest(*world.clients[1].missionOffer)); err != nil { + t.Fatal(err) + } + if world.characters[1].missions[0].doors[0].id != 2 { + t.Fatal("retired door identity was reused") + } + }) + } +} + +func TestMissionDoorRetirementFailureKeepsOccupiedWorldAndReplay(t *testing.T) { + world, output := newMissionDoorOfferWorld(t) + client := world.clients[1] + if err := world.handleMissionAcceptance(world.clients[1], missionAcceptanceRequest(*world.clients[1].missionOffer)); err != nil { + t.Fatal(err) + } + mission := world.characters[1].missions[0] + player := world.characters[1] + player.playfield, player.position = mission.world, [3]float32{15, .011, 29} + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + if _, err := world.prepareMissionWorld_locked(&mission); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec("CREATE TRIGGER fail_door BEFORE DELETE ON mission_doors BEGIN SELECT RAISE(FAIL, 'test retirement'); END"); err != nil { + t.Fatal(err) + } + output.packets = nil + updates := make(map[*worldClient][][]byte) + + departures, err := world.endMission_locked(mission, false, updates) + cold := reloadMissionEntranceWorld(t) + packets, replayErr := cold.missionDoorPackets_locked(cold.characters[1]) + + if err == nil || replayErr != nil || len(packets) != 2 || len(departures) != 0 || len(updates) != 0 || len(output.packets) != 0 || + player.playfield != 65536 || cold.characters[1].playfield != 65536 || len(world.missionExpiry) != 1 || len(cold.missionExpiry[0].doors) != 1 { + t.Fatal("failed retirement changed the occupied world or its door replay", err, replayErr) + } + if _, err := world.db.Exec("DROP TRIGGER fail_door"); err != nil { + t.Fatal(err) + } + departures, err = world.endMission_locked(mission, false, updates) + if err != nil || len(departures) != 1 || world.characters[1].playfield != 3000 || len(world.missionExpiry) != 0 { + t.Fatal("retirement retry failed to evacuate and revoke the world", err) + } + removed := false + for _, packet := range updates[client] { + if bytes.Equal(packet, n3Packet(0x36510078, 51016, 1, nil)) { + removed = true + } + } + if !removed { + t.Fatalf("retirement omitted the native door removal: updates=%x output=%x", updates[client], output.packets) + } +} + +func TestMissionDoorsReplayEveryPairedPassage(t *testing.T) { + world, _ := newMissionDoorOfferWorld(t) + if err := world.handleMissionAcceptance(world.clients[1], missionAcceptanceRequest(*world.clients[1].missionOffer)); err != nil { + t.Fatal(err) + } + layout := missionLayout{template: 331, width: 4, depth: 8, floorHeight: 10, + rooms: []missionRoom{{template: 0, x: 1, z: 5, rotation: 2}, {template: 0, x: 1, z: 3, rotation: 2}, {template: 37, x: 1, z: 1}}} + blob, err := layout.blob() + if err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec("UPDATE missions SET layout=? WHERE id=2", blob); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec("INSERT INTO mission_doors (mission_id,passage,template) VALUES (2,1,41565)"); err != nil { + t.Fatal(err) + } + + cold := reloadMissionEntranceWorld(t) + cold.characters[1].playfield = 65536 + packets, err := cold.missionDoorPackets_locked(cold.characters[1]) + + if err != nil || len(packets) != 4 || !reflect.DeepEqual(cold.missionExpiry[0].doors, []missionDoor{{1, 0, 41565}, {2, 1, 41565}}) { + t.Fatal("multi-passage replay lost a concrete door", err) + } + first, err := doorPacket(65536, worldDoor{id: 1, template: 41565, position: [3]float32{15, 0, 29.999}, rotation: [4]float32{0, 0, 0, 1}, open: true}) + if err != nil || !bytes.Equal(packets[0], first) || !bytes.Equal(packets[1], doorStatusPacket(1, false, true, true)) { + t.Fatal("first passage replay differs", err) + } + second, err := doorPacket(65536, worldDoor{id: 2, template: 41565, position: [3]float32{15, 0, 49.999}, rotation: [4]float32{0, 0, 0, 1}, open: true}) + if err != nil || !bytes.Equal(packets[2], second) || !bytes.Equal(packets[3], doorStatusPacket(2, false, true, true)) { + t.Fatal("second passage replay differs", err) + } +} + +func TestMissionDoorsRejectMissingOrInvalidConfiguredTemplates(t *testing.T) { + for _, scenario := range []struct { + name string + template uint32 + }{{"missing", 0}, {"unknown", 999999}, {"medical item", 85366}} { + t.Run(scenario.name, func(t *testing.T) { + world, output := newMissionDoorOfferWorld(t) + client := world.clients[1] + client.missionOffer.definition.PassageDoor = scenario.template + + err := world.handleMissionAcceptance(client, missionAcceptanceRequest(*client.missionOffer)) + + if err == nil || client.missionOffer == nil || len(world.missionExpiry) != 0 || len(world.characters[1].missions) != 0 || + world.characters[1].inventory.Credits != 4 || world.nextItem != 1 || len(output.packets) != 0 { + t.Fatal("invalid configured door admitted an unusable passage", err) + } + }) + } +} + +func TestMissionDoorsKeepTheOfferedTemplateWhenContentChanges(t *testing.T) { + world, _ := newMissionDoorOfferWorld(t) + definition := gamedata.MissionTemplates[3221228472] + definition.PassageDoor = 41884 + gamedata.MissionTemplates[3221228472] = definition + client := world.clients[1] + + if err := world.handleMissionAcceptance(client, missionAcceptanceRequest(*client.missionOffer)); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + + if cold.missionExpiry[0].doors[0].template != 41565 || world.characters[1].missions[0].doors[0].template != 41565 { + t.Fatal("acceptance regenerated its door from mutable template content") + } +} + +func TestMissionDoorReplayRejectsIncompleteOrUnpairedBindings(t *testing.T) { + for _, statement := range []string{ + "DELETE FROM mission_doors", + "UPDATE mission_doors SET passage=1", + } { + t.Run(statement, func(t *testing.T) { + world, _ := newMissionDoorOfferWorld(t) + if err := world.handleMissionAcceptance(world.clients[1], missionAcceptanceRequest(*world.clients[1].missionOffer)); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + cold.characters[1].playfield = 65536 + + packets, err := cold.missionDoorPackets_locked(cold.characters[1]) + + if err == nil || len(packets) != 0 { + t.Fatal("corrupt passage binding silently replayed a different world", err, packets) + } + }) + } +} diff --git a/server/mission_encounters_test.go b/server/mission_encounters_test.go @@ -19,8 +19,6 @@ func newMissionEncounterOfferWorld(t *testing.T) (*server, *combatTestConn) { definition := gamedata.MissionTemplates[3221228472] definition.Encounters = encounters gamedata.MissionTemplates[3221228472] = definition - world.geometry = missionGeometryFixture(t) - world.geometry.models = make(map[uint32]collisionSphere) world.nextNPC = 2000000 if err := world.handleMissionOffers(world.clients[1], missionOffersRequest()); err != nil { t.Fatal(err) diff --git a/server/mission_entrance_test.go b/server/mission_entrance_test.go @@ -13,8 +13,6 @@ func newMissionEntranceWorld(t *testing.T) (*server, *combatTestConn) { t.Helper() world, output := newAcceptedMissionWorld(t) t.Cleanup(func() { world.db.Close() }) - world.geometry = missionGeometryFixture(t) - world.geometry.models = make(map[uint32]collisionSphere) player := world.characters[1] player.geometry = world.geometry player.position, player.rotation = [3]float32{89.30216, 115.75, 152.5}, [4]float32{0, 1, 0, 0} @@ -372,12 +370,17 @@ func TestMissionRetirementReturnsAllKeyHoldersAtomically(t *testing.T) { restored := reloadMissionEntranceWorld(t) if restored.characters[1].playfield != 3000 || restored.characters[2].playfield != 3000 || len(restored.characters[1].missions) != 0 || - len(restored.characters[2].inventory.Items) != 0 || len(owner.packets) != 4 || len(output.packets) != 3 || world.geometry.mission(65536) != nil { + len(restored.characters[2].inventory.Items) != 0 || len(owner.packets) != 5 || len(output.packets) != 4 || world.geometry.mission(65536) != nil { t.Fatal("retirement failed to return all bound-key holders together", owner.packets, output.packets) } - if binary.BigEndian.Uint32(owner.packets[1][16:]) != 0x212c487a || binary.BigEndian.Uint32(owner.packets[2][16:]) != 0x43197d22 { + if binary.BigEndian.Uint32(owner.packets[2][16:]) != 0x212c487a || binary.BigEndian.Uint32(owner.packets[3][16:]) != 0x43197d22 { t.Fatal("journal retirement must precede the owner's redirect", owner.packets) } + for _, packets := range [][][]byte{owner.packets, output.packets} { + if !bytes.Equal(packets[1][16:], targetPacket(n3Packet(0x36510078, 51016, 1, nil))[16:]) { + t.Fatal("retirement omitted the occupied world's native door", packets) + } + } } func TestMissionStartupExpiryReturnsPrivateOccupantsBeforeServing(t *testing.T) { diff --git a/server/mission_instance_test.go b/server/mission_instance_test.go @@ -215,6 +215,9 @@ func TestMissionAssignmentsIsolateConcurrentOwners(t *testing.T) { first.world+second.world != 131073 || first.id == second.id || !bytes.Equal(first.layout, second.layout) { t.Fatal("concurrent owners shared an assignment, identity or key binding", first, second) } + if len(first.doors) != 1 || len(second.doors) != 1 || first.doors[0].id == second.doors[0].id || first.doors[0].id+second.doors[0].id != 3 { + t.Fatal("concurrent owners shared a native door identity", first.doors, second.doors) + } } func TestMissionLoadRejectsCorruptGeneratorWithoutSubstitutingDefaults(t *testing.T) { diff --git a/server/mission_movement.go b/server/mission_movement.go @@ -38,9 +38,9 @@ func (player *character) vetoPosition(position, previous *[3]float32) bool { room := scene.roomAt(*position) allowed := room != nil && (player.roomState.room == nil || player.roomState.room == room) if room != nil && player.roomState.room != nil && player.roomState.room != room { - // client/game/kkr.dll/lifted-0096.c, sub_3614CF70: links with an empty door identity. + // client/game/kkr.dll/lifted-0096.c::sub_3614CF70 admits empty or open passages. for _, link := range scene.links { - if link == [2]*placedRoom{player.roomState.room, room} || link == [2]*placedRoom{room, player.roomState.room} { + if link.rooms == [2]*placedRoom{player.roomState.room, room} || link.rooms == [2]*placedRoom{room, player.roomState.room} { allowed = true break } diff --git a/server/mission_offers_test.go b/server/mission_offers_test.go @@ -249,6 +249,8 @@ func newMissionOfferWorld(t *testing.T) (*server, *combatTestConn) { gamedata.MissionTemplates[3221228472] = cashOnly t.Cleanup(func() { gamedata.MissionTemplates[3221228472] = definition }) world, output := newEquipmentWorld(t) + world.geometry = missionGeometryFixture(t) + world.geometry.models = make(map[uint32]collisionSphere) player := world.characters[1] player.playfield, player.position = 3000, [3]float32{100, 115.75, 145} inventory := player.inventory @@ -265,7 +267,7 @@ func newMissionOfferWorld(t *testing.T) (*server, *combatTestConn) { func TestMissionOfferNativeSocketSeparatesBrowsingFromAcceptance(t *testing.T) { newMissionOfferWorld(t) - world := newTestInventoryServer(t) + world := reloadMissionEntranceWorld(t) connection := connectZoningClient(t, world, true) defer connection.Close() before := world.characters[1].userData() diff --git a/server/mission_retirement.go b/server/mission_retirement.go @@ -297,6 +297,11 @@ func (server *server) endMission_locked(mission acceptedMission, completed bool, } } for _, client := range server.clients { + if !completed && server.characters[client.id].playfield == mission.world { + for _, door := range mission.doors { + changes[client] = append(changes[client], n3Packet(0x36510078, 51016, door.id, nil)) + } + } if retiredNPCs[client.lootCorpse] { changes[client] = append(changes[client], lootClosePacket(client.id, client.lootCorpse)) client.lootCorpse = 0 diff --git a/server/mission_retirement_test.go b/server/mission_retirement_test.go @@ -27,7 +27,7 @@ func newAcceptedMissionWorld(t *testing.T) (*server, *combatTestConn) { func TestMissionRemovalNativeDispatchAndNextAssignment(t *testing.T) { newAcceptedMissionWorld(t) - world := newTestInventoryServer(t) + world := reloadMissionEntranceWorld(t) connection := connectZoningClient(t, world, true) defer connection.Close() diff --git a/server/mission_scene.go b/server/mission_scene.go @@ -8,12 +8,18 @@ import ( type missionScene struct { ground *dungeonTilemap rooms []placedRoom - links [][2]*placedRoom + links []roomLink entrance *placedRoom exitPosition [3]float32 exitDirection byte } +type roomLink struct { + rooms [2]*placedRoom + position [3]float32 + direction byte +} + type placedRoom struct { template *dungeonRoom position [3]float32 diff --git a/server/mission_world.go b/server/mission_world.go @@ -106,7 +106,7 @@ func (scene *missionScene) connectRooms(layout missionLayout) error { continue } first.paired, portals[match].paired = true, true - scene.links = append(scene.links, [2]*placedRoom{first.room, portals[match].room}) + scene.links = append(scene.links, roomLink{[2]*placedRoom{first.room, portals[match].room}, first.position, first.direction}) } if scene.entrance == nil { return fmt.Errorf("dungeon has no exterior portal") @@ -120,9 +120,9 @@ func (scene *missionScene) connectRooms(layout missionLayout) error { queue = queue[1:] for _, link := range scene.links { for side := range 2 { - if link[side] == room && !visited[link[1-side]] { - visited[link[1-side]] = true - queue = append(queue, link[1-side]) + if link.rooms[side] == room && !visited[link.rooms[1-side]] { + visited[link.rooms[1-side]] = true + queue = append(queue, link.rooms[1-side]) } } } diff --git a/server/mission_world_test.go b/server/mission_world_test.go @@ -36,12 +36,15 @@ func TestMissionWorldRegistersOriginalPortalLinksAtEveryRotation(t *testing.T) { second, opposite := scene.portal(&scene.rooms[1], 10) geometry.removeMission(9000001) - if scene.entrance != &scene.rooms[0] || len(scene.links) != 1 || scene.links[0] != [2]*placedRoom{&scene.rooms[0], &scene.rooms[1]} { + if scene.entrance != &scene.rooms[0] || len(scene.links) != 1 || scene.links[0].rooms != [2]*placedRoom{&scene.rooms[0], &scene.rooms[1]} { t.Fatal("original portal pairing or unique exterior room", scene.entrance, scene.links) } if surfaceDistanceSquared(first, scenario.first) > .000000001 || surfaceDistanceSquared(second, scenario.second) > .000000001 || (direction+2)&3 != opposite { t.Fatal("native portal positions and opposing directions", first, second, direction, opposite) } + if scene.links[0].position != first || scene.links[0].direction != direction { + t.Fatal("door replay lost the matched portal pose", scene.links[0]) + } if scene.roomAt(scene.safePosition()) != scene.entrance || geometry.physical(9000001) { t.Fatal("safe room or retired world lookup", scene.safePosition()) } diff --git a/server/missions.go b/server/missions.go @@ -20,6 +20,7 @@ type acceptedMission struct { layout []byte objective uint32 completed bool + doors []missionDoor } const missionColumns = "owner_id, booth_id, seed, difficulty, dimension_0, dimension_1, dimension_2, dimension_3, dimension_4, dimension_5, originator, description, playfield, entrance, position_x, position_y, position_z, objective_item, credits, experience, reward_item, reward_quality, expires_at, world_id, layout, objective_id, completed" @@ -46,6 +47,12 @@ func insertMission(tx *sql.Tx, mission *acceptedMission) error { if err := tx.QueryRow("INSERT INTO mission_keys (item_id, mission_id) VALUES (?, ?) RETURNING item_id", mission.id, mission.id).Scan(&saved); err != nil { return fmt.Errorf("save mission %d key: %w", mission.id, err) } + for index := range mission.doors { + door := &mission.doors[index] + if err := tx.QueryRow("INSERT INTO mission_doors (mission_id,passage,template) VALUES (?,?,?) RETURNING id", mission.id, door.passage, door.template).Scan(&door.id); err != nil { + return fmt.Errorf("save mission %d door: %w", mission.id, err) + } + } return nil } @@ -69,7 +76,11 @@ func (server *server) loadMissions() error { } server.missionExpiry = append(server.missionExpiry, mission) } - return rows.Err() + if err := rows.Err(); err != nil { + return err + } + rows.Close() + return server.loadMissionDoors() } func missionJournalPacket(mission acceptedMission, now time.Time) []byte { @@ -130,12 +141,16 @@ func (server *server) handleMissionAcceptance(client *worldClient, body []byte) return err } store.mission = &mission + if err := server.stageMissionDoors_locked(&mission); err != nil { + return err + } store.spawnedNPCs, err = server.stageMissionEncounters_locked(&mission) if err != nil { return err } - // The accepted contract retains concrete NPC rows rather than a spawn recipe. + // Retain concrete world objects after acceptance, rather than their recipes. mission.offer.definition.Encounters = nil + mission.offer.definition.PassageDoor = 0 if err := server.writeItemStore_locked(store); err != nil { return err } diff --git a/server/missions_test.go b/server/missions_test.go @@ -24,7 +24,7 @@ func missionAcceptanceRequest(offer missionOffer) []byte { func TestMissionAcceptanceNativeDispatchCommitsKeyAndJournal(t *testing.T) { newMissionOfferWorld(t) - world := newTestInventoryServer(t) + world := reloadMissionEntranceWorld(t) connection := connectZoningClient(t, world, true) defer connection.Close() request := missionOffersRequest() diff --git a/server/world.sql b/server/world.sql @@ -245,6 +245,13 @@ CREATE TABLE IF NOT EXISTS mission_keys ( item_id INTEGER PRIMARY KEY REFERENCES items(id) ON DELETE CASCADE, mission_id INTEGER NOT NULL REFERENCES missions(id) ON DELETE CASCADE ); +CREATE TABLE IF NOT EXISTS mission_doors ( + id INTEGER PRIMARY KEY AUTOINCREMENT CHECK (id BETWEEN 1 AND 4294967295), + mission_id INTEGER NOT NULL REFERENCES missions(id) ON DELETE CASCADE, + passage INTEGER NOT NULL CHECK (passage >= 0), + template INTEGER NOT NULL, + UNIQUE (mission_id, passage) +); CREATE TABLE IF NOT EXISTS chat_history ( id INTEGER PRIMARY KEY, owner INTEGER NOT NULL,