commit 8b8df51c425472002458c0e3a7868664d2aac1bf
parent d69ece014c201cfbb008fe77007eb5b193f27001
Author: anon <anon@example.com>
Date: Thu, 5 Nov 2026 18:48:04 +0000
Render original outfits on starter NPCs
Diffstat:
14 files changed, 414 insertions(+), 12 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -66,6 +66,13 @@ research separately. More screenshots and test cases do not count as new gamepla
Completion: inspect those actors in the real client, including a second
observer and reconnect, with intended bodies, textures and equipment visible.
Label uncertain outfit choices as provisional; do not block on all world NPCs.
+ November 5: shared humanoid NPC equipment delivery now outfits the seven
+ Trade Elite Guards and five starter vendors. Female/Atrox guards and all five
+ vendors pass two-observer/reconnect checks; the humanoid NPC spawn path fixes
+ a reproduced clothing-compositing crash. Garments are original assets, with
+ provisional actor assignments. Early-route guides/guards, human enemies and
+ representative creature appearance checks remain. See
+ [NPC appearance scope and evidence](docs/npc-appearances.md).
- [ ] **A4: Doors visibly open where players enter.** Reproduce Entertainment
<-> Trade and the Entertainment shop near Bronto Burger. Zoning already works;
diff --git a/docs/npc-appearances.md b/docs/npc-appearances.md
@@ -0,0 +1,92 @@
+# Early-route NPC outfits
+
+The first A3 implementation equips the seven Omni Trade Elite Guards, both
+Food Providers and the three faction training-ground Secondhand Peddlers.
+The garments and body/head meshes come from the original 14.9.1 catalogs.
+Assigning these particular outfits to those actors is provisional, rather than
+recovered server outfit data.
+
+| Actors | Garment templates and equipment slots |
+| --- | --- |
+| Trade Elite Guards: `710/district/0/fixed/8,9,10`, `710/district/1/fixed/0,2,6,7` | QL 200 Omni-Pol Elite: helmet 22250/18, body 22068/21, sleeves 21959/23 and /25, gloves 22200/24, pants 22335/27, boots 22146/30 |
+| Trade Food Providers: `710/district/0/fixed/18,19` | QL 1 uniform: shirt 82912/21, sleeves 82919/23 and /25, pants 82911/27, boots 82913/30 |
+| Secondhand Peddlers: `950/district/1/fixed/0`, `952/district/3/fixed/0`, `954/district/1/fixed/0` | QL 1 rustic clothing: shirt 82102/21, sleeves 82092/23 and /25, pants 82101/27, boots 82100/30 |
+
+`gamedata.NPCOutfits` supplies definition equipment on spawn, world reload and
+respawn. It uses the shared item wear and armor consumers. Equipment has no
+transferable item identity and creates no player `items` rows; the separate
+authored corpse-loot table still determines rewards. Head meshes use the
+selected MonsterData template's stat 64. This does not establish the historical
+guard protection values or add rifle equipment.
+
+## Native initialization order
+
+Clothing requires SimpleChar flag bit 3 (CanChangeClothes, stat 223), followed
+by ordinary TemplateAction wear messages. Sending those alone crashed a Food
+Provider when the original client composited its shirt with naked skin.
+
+The retained diagnostic at
+`local/npc-appearances/browser-food-skin-http.log` showed the actor's render
+object had breed 0 / sex 1 and requested `_<nothing>male_naked.png`, although
+the actor's final stats were Solitus male. These translated native consumers
+explain the mismatch:
+
+- `client/game/kkr.dll/lifted-0038.c:sub_36082AD0` sets NPC MonsterData at
+ `0x36082BF6`, before packed breed/sex at `0x36082C74`.
+- `client/game/kkr.dll/lifted-0033.c:sub_3606E590` dispatches stat 359 to
+ `client/game/kkr.dll/lifted-0031.c:sub_36067540`. Its nonzero path installs
+ the monster mesh using the actor's current breed/sex. Its zero path does
+ nothing if the current MonsterData is already zero.
+- `client/game/llr.dll/lifted-0024.c:sub_3803DBE0` returns early for an already
+ installed mesh ID. Later appearance initialization therefore retains the
+ render object's incorrect breed/sex.
+- `client/game/bbr.dll/lifted-0032.c:sub_25095F50` expects the skin texture
+ lookup to succeed; compositing the missing texture caused the crash.
+
+The client also has a humanoid NPC path. The original `N3Msg_IsNpc` export at
+`0x10025A80` (`client/game/kkr.dll/lifted-0015.c:sub_36025A80`) accepts either
+the monster-instance marker or status flag
+`0x00800000`. SimpleChar bit 18 supplies that status flag at
+`0x36082BB5-0x36082BCC`, independently of bit 0. With bit 0 clear, the native
+initializer applies breed/sex before MonsterData.
+
+Outfitted human NPCs now use bit 18, InPlay bit 1 and the humanoid field layout.
+Their actual MonsterData and explicit head/textures remain in the same spawn
+packet, followed by equipment replay. All observers use the same interest-entry
+path, including reconnect. No translated native code or published browser
+assets are changed. The historical name of bit 18 is unknown; its native
+classification behavior is established by the consumer.
+
+The rejected zero-MonsterData/deferred-stat experiment made NPCs invisible:
+SimpleChar activation skipped its visibility/material setup without a mesh.
+The working protocol keeps mesh construction inside the original activation.
+
+## Verification and remaining scope
+
+`TestNPCEliteOutfitSurvivesReload` checks exact garment identities, head,
+absence of transferable items, and the login packet order before and after a
+cold world load. `TestBrowserNPCOutfits` uses the published browser bundle at
+the original placements, with two observers, native picking, reconnect,
+packet inspection and effective armor comparisons against server state.
+
+November 5 runs passed for female and Atrox Elite Guards, both Food Providers
+and all three Peddlers. The published WASM SHA-256 was
+`48d48eaccef7c4eccd877a7f30b1e655bb3358e177cfad64076ac07a1688dd3b`.
+The first Food Provider's capture is under
+`local/npc-appearances/20261105-103434/`; the other six are under
+`local/npc-appearances/20261105-103658/`. Both observers inspect the same NPC
+before and after reconnect; the guard's eight native effective ACs equal
+`3500, 3500, 3500, 872, 3059, 3059, 3059, 3059`, matching the server.
+The Food Provider also passes the existing right-click/E, buy/sell, cancel,
+reconnect and range-rejection scenario with the new humanoid NPC flags;
+captures are under `local/npc-vendors/20261105-104244/`.
+
+The focused server checks cover outfit reload and packet order, NPC shops,
+interest boundaries, population membership and respawn persistence. Shop
+fixtures now construct valid NPC definitions. The population membership fixture
+places actors in range and uses the authored 1,842-actor count for playfield
+646; its previous range-dependent expectations also failed on the prior build.
+
+A3 remains open for the remaining early-route guards/guides, human enemies and
+representative creature appearances. These controlled appearance checks do not
+establish earned progression, encounter balance or exact historical outfits.
diff --git a/docs/protocol.md b/docs/protocol.md
@@ -279,6 +279,13 @@ 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 local/reports/full-population-runtime-evidence.json.
+Outfitted human NPCs use the humanoid field layout with bit 0 clear and bit 18
+set. The latter supplies status flag `0x00800000`, which the native `IsNpc`
+consumer recognizes independently of the monster-instance marker. This path
+initializes breed/sex before MonsterData and avoids constructing clothing skin
+with breed zero. InPlay bit 1 remains explicit. See
+[NPC appearances](npc-appearances.md) for the native consumers and verification.
+
The asset identifier was first suggested by the later CellAO database and was
corroborated by original-client runtime rendering. See local/reports/npc.png.
diff --git a/server/browser_npc_outfits_test.go b/server/browser_npc_outfits_test.go
@@ -0,0 +1,78 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "math"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestBrowserNPCOutfits(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for two-client NPC outfits")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/npc-appearances", time.Now().Format("20060102-150405"))
+ for _, route := range []string{"710/district/0/fixed/8", "710/district/1/fixed/2", "710/district/0/fixed/18", "710/district/0/fixed/19",
+ "950/district/1/fixed/0", "952/district/3/fixed/0", "954/district/1/fixed/0"} {
+ t.Run(route, func(t *testing.T) {
+ world := newTestServer(t)
+ var npc *character
+ for _, actor := range world.characters {
+ if actor.npcDefinitionID == route {
+ npc = actor
+ break
+ }
+ }
+ if npc == nil {
+ t.Fatal("outfit actor is absent from the original population")
+ }
+ for index, offset := range []float32{-1, 1} {
+ player := world.newCharacter()
+ player.playfield, player.position = npc.playfield, npc.position
+ player.position[0] += offset
+ player.position[1] += .75
+ player.position[2] -= 3
+ yaw := math.Atan2(float64(-offset), 3)
+ player.rotation = [4]float32{0, float32(math.Sin(yaw / 2)), 0, float32(math.Cos(yaw / 2))}
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("npc-outfit-%d", index))))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ }
+ mux := http.NewServeMux()
+ mux.Handle("/", world.httpHandler())
+ mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ armor := [8]int32{}
+ for index := range armor {
+ armor[index] = npc.equipmentBonus(90 + uint32(index))
+ }
+ json.NewEncoder(w).Encode(map[string]any{"id": npc.id, "route": route, "head": npc.headMesh,
+ "items": npc.inventory.Items, "armor": armor, "position": npc.position})
+ })
+ host := httptest.NewServer(mux)
+ t.Cleanup(host.Close)
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_npc_outfits.mjs"), host.URL, filepath.Join(output, route))
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ err := command.Run()
+ t.Logf("Browser artifacts: %s", filepath.Join(output, route))
+ if err != nil {
+ t.Fatal(err)
+ }
+ })
+ }
+}
diff --git a/server/gamedata/npc_outfits.go b/server/gamedata/npc_outfits.go
@@ -0,0 +1,35 @@
+package gamedata
+
+type NPCOutfitItem struct {
+ Template uint32
+ Slot uint32
+}
+
+// Original garments; assigning these outfits to the selected NPCs is provisional.
+var npcEliteOutfit = []NPCOutfitItem{
+ {22250, 18}, {22068, 21}, {21959, 23}, {22200, 24},
+ {21959, 25}, {22335, 27}, {22146, 30},
+}
+
+var npcUniformOutfit = []NPCOutfitItem{
+ {82912, 21}, {82919, 23}, {82919, 25}, {82911, 27}, {82913, 30},
+}
+
+var npcRusticOutfit = []NPCOutfitItem{
+ {82102, 21}, {82092, 23}, {82092, 25}, {82101, 27}, {82100, 30},
+}
+
+var NPCOutfits = map[string][]NPCOutfitItem{
+ "710/district/0/fixed/8": npcEliteOutfit,
+ "710/district/0/fixed/9": npcEliteOutfit,
+ "710/district/0/fixed/10": npcEliteOutfit,
+ "710/district/1/fixed/0": npcEliteOutfit,
+ "710/district/1/fixed/2": npcEliteOutfit,
+ "710/district/1/fixed/6": npcEliteOutfit,
+ "710/district/1/fixed/7": npcEliteOutfit,
+ "710/district/0/fixed/18": npcUniformOutfit,
+ "710/district/0/fixed/19": npcUniformOutfit,
+ "950/district/1/fixed/0": npcRusticOutfit,
+ "952/district/3/fixed/0": npcRusticOutfit,
+ "954/district/1/fixed/0": npcRusticOutfit,
+}
diff --git a/server/interest.go b/server/interest.go
@@ -61,6 +61,7 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim
updates = append(updates, corpsePacket(other))
} else {
updates = append(updates, characterPacket(other))
+ updates = append(updates, equippedItemPackets(other)...)
if other.pet != nil {
owner := server.characters[other.pet.owner]
updates = append(updates, petIdentityPacket(0x194e4f76, owner.id, other.id), petCounterPacket(owner))
diff --git a/server/npc_outfits_test.go b/server/npc_outfits_test.go
@@ -0,0 +1,77 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "net"
+ "reflect"
+ "testing"
+ "time"
+)
+
+func TestNPCEliteOutfitSurvivesReload(t *testing.T) {
+ data := testNPCData()
+ data.Playfields[0].Districts[0].Groups[0] = *gamedata.NPCGroups["710/district/0/fixed/8"]
+ useNPCData(t, data)
+ world := newTestServer(t)
+
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+
+ want := []ownedItem{
+ {Type: 51022, Template: 22250, Quality: 200, Slot: 18, Count: 1},
+ {Type: 51022, Template: 22068, Quality: 200, Slot: 21, Count: 1},
+ {Type: 51022, Template: 21959, Quality: 200, Slot: 23, Count: 1},
+ {Type: 51022, Template: 22200, Quality: 200, Slot: 24, Count: 1},
+ {Type: 51022, Template: 21959, Quality: 200, Slot: 25, Count: 1},
+ {Type: 51022, Template: 22335, Quality: 200, Slot: 27, Count: 1},
+ {Type: 51022, Template: 22146, Quality: 200, Slot: 30, Count: 1},
+ }
+ for _, current := range []*server{world, cold} {
+ npc := current.characters[1000000]
+ if !reflect.DeepEqual(npc.inventory.Items, want) || npc.headMesh != 40629 {
+ t.Fatalf("guard outfit absent or changed after reload: head=%d items=%+v", npc.headMesh, npc.inventory.Items)
+ }
+ if binary.BigEndian.Uint32(characterPacket(npc)[37:41])&8 == 0 {
+ t.Fatal("human NPC spawn disables native clothing changes")
+ }
+
+ // Observe the actual login sequence, including after a cold world load.
+ player := current.newCharacter()
+ player.playfield, player.position = npc.playfield, npc.position
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); current.serveWorldConnection(connection) }()
+ client.Write(systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}))
+ var packets [][]byte
+ for _, packet := range readWorldUpdates(t, client) {
+ if binary.BigEndian.Uint32(packet[28:32]) == npc.id {
+ packets = append(packets, packet)
+ }
+ }
+ if len(packets) < 8 || binary.BigEndian.Uint32(packets[0][20:24]) != 0x271b3a6b {
+ t.Fatalf("missing outfit spawn sequence: %x", packets)
+ }
+ nameEnd := 70 + int(packets[0][69])
+ if binary.BigEndian.Uint32(packets[0][37:41])&0x40003 != 0x40002 ||
+ binary.BigEndian.Uint32(packets[0][nameEnd+29:nameEnd+33]) != 26090 {
+ t.Fatal("outfitted NPC must retain IsNpc and MonsterData using humanoid initialization")
+ }
+ for index, item := range want {
+ packet := packets[index+1]
+ if binary.BigEndian.Uint32(packet[20:24]) != 0x35505644 ||
+ binary.BigEndian.Uint32(packet[36:40]) != item.Template || binary.BigEndian.Uint32(packet[44:48]) != 200 ||
+ binary.BigEndian.Uint32(packet[52:56]) != 6 || binary.BigEndian.Uint32(packet[60:64]) != item.Slot {
+ t.Fatalf("outfit action %d: %x", index, packet)
+ }
+ }
+ client.Close()
+ }
+ var items int
+ if err := cold.db.QueryRow("SELECT count(*) FROM items").Scan(&items); err != nil || items != 0 {
+ t.Fatalf("definition equipment allocated transferable player items: %d %v", items, err)
+ }
+}
diff --git a/server/npc_shops_test.go b/server/npc_shops_test.go
@@ -13,8 +13,9 @@ func TestNPCShopRoutesBuySellAndReload(t *testing.T) {
world, conn := newEquipmentWorld(t)
player, client := world.characters[1], world.clients[1]
player.appearance = 0x515
- npc := &character{id: 1000001, npc: true, health: 100, npcDefinitionID: route, playfield: player.playfield, position: player.position}
- world.characters[npc.id] = npc
+ npc := makeNPCSpawn(gamedata.NPCGroups[route], 1, player.position)
+ npc.id, npc.playfield = 1000001, player.playfield
+ world.characters[npc.id] = &npc
client.npcs = map[uint32]bool{npc.id: true}
player.inventory.Credits = 1000
if err := world.saveInventory_locked(player, player.inventory); err != nil {
@@ -57,8 +58,9 @@ func TestNPCShopRevalidatesSellerOnStartAndAccept(t *testing.T) {
t.Run(stage+"/"+invalid, func(t *testing.T) {
world, _ := newEquipmentWorld(t)
player, client := world.characters[1], world.clients[1]
- npc := &character{id: 1000001, npc: true, health: 100, npcDefinitionID: "950/district/1/fixed/0", playfield: player.playfield, position: player.position}
- world.characters[npc.id] = npc
+ npc := makeNPCSpawn(gamedata.NPCGroups["950/district/1/fixed/0"], 1, player.position)
+ npc.id, npc.playfield = 1000001, player.playfield
+ world.characters[npc.id] = &npc
client.npcs = map[uint32]bool{npc.id: true}
before := player.inventory
request := shopTradePacket([2]uint32{50000, 1}, 0, [2]uint32{50000, npc.id}, [2]uint32{})
@@ -104,8 +106,9 @@ func TestNPCShopRevalidatesSellerOnStartAndAccept(t *testing.T) {
func TestNPCShopKeyboardUseAndCancellation(t *testing.T) {
world, conn := newEquipmentWorld(t)
player, client := world.characters[1], world.clients[1]
- npc := &character{id: 1000001, npc: true, health: 100, npcDefinitionID: "950/district/1/fixed/0", playfield: player.playfield, position: player.position}
- world.characters[npc.id] = npc
+ npc := makeNPCSpawn(gamedata.NPCGroups["950/district/1/fixed/0"], 1, player.position)
+ npc.id, npc.playfield = 1000001, player.playfield
+ world.characters[npc.id] = &npc
client.npcs = map[uint32]bool{npc.id: true}
before := player.inventory
request := shopUseRequest(1)
@@ -137,7 +140,9 @@ func TestNPCShopKeyboardUseAndCancellation(t *testing.T) {
func TestNPCShopMovementCancelsOutsideRange(t *testing.T) {
world, _ := newEquipmentWorld(t)
player, client := world.characters[1], world.clients[1]
- world.characters[1000001] = &character{id: 1000001, npc: true, health: 100, npcDefinitionID: "950/district/1/fixed/0", playfield: player.playfield}
+ npc := makeNPCSpawn(gamedata.NPCGroups["950/district/1/fixed/0"], 1, player.position)
+ npc.id, npc.playfield = 1000001, player.playfield
+ world.characters[npc.id] = &npc
client.npcs = map[uint32]bool{1000001: true}
before := player.inventory
for _, packet := range [][]byte{
diff --git a/server/npcs.go b/server/npcs.go
@@ -21,6 +21,7 @@ func makeNPCSpawn(group *gamedata.NPCGroup, level uint16, position [3]float32) c
spawn := character{name: group.Name, position: position, rotation: [4]float32{0, 0, 0, 1},
appearance: group.Appearance, monsterData: group.MonsterData, level: level, npc: true,
combatProfile: npcCombatProfile(group.ID, group.MonsterData, level), npcDefinitionID: group.ID}
+ spawn.equipNPCOutfit()
spawn.health = spawn.maximumHealth()
// Idle placement is independent of admitted combat movement.
roaming := group.PlacementStatus != "fixed_point" && group.Appearance>>4&7 == 6
@@ -30,6 +31,24 @@ func makeNPCSpawn(group *gamedata.NPCGroup, level uint16, position [3]float32) c
return spawn
}
+func (npc *character) equipNPCOutfit() {
+ if len(gamedata.NPCOutfits[npc.npcDefinitionID]) == 0 {
+ return
+ }
+ // Definition equipment uses the shared wear/bonus consumers without allocating
+ // transferable item identities. Loot remains the separate authored drop table.
+ npc.inventory.Items = nil
+ for _, entry := range gamedata.NPCOutfits[npc.npcDefinitionID] {
+ item := gamedata.ItemTemplates[entry.Template]
+ npc.inventory.Items = append(npc.inventory.Items, ownedItem{
+ Type: item.HeaderWords[0], Template: entry.Template, Quality: *item.Quality, Slot: entry.Slot, Count: 1,
+ })
+ }
+ if npc.headMesh == 0 {
+ npc.headMesh = gamedata.MonsterTemplates[npc.monsterData].Stats[64]
+ }
+}
+
func readNPCSpawns() ([]character, error) {
data := gamedata.NPCs
diff --git a/server/npcs_test.go b/server/npcs_test.go
@@ -59,11 +59,16 @@ func readWorldUpdates(t *testing.T, client net.Conn) [][]byte {
func TestPopulationsAreSharedAndZoneScoped(t *testing.T) {
world := newTestServer(t)
+ // Keep each population in range so the fixture isolates zone membership.
+ for _, npc := range world.characters {
+ npc.position = [3]float32{100, 0, 100}
+ }
var clients []net.Conn
zones := []uint32{950, 950, 952, 954, 646}
for _, zone := range zones {
player := world.newCharacter()
player.playfield = zone
+ player.position = [3]float32{100, 0, 100}
client, connection := net.Pipe()
clients = append(clients, client)
defer client.Close()
@@ -78,7 +83,7 @@ func TestPopulationsAreSharedAndZoneScoped(t *testing.T) {
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 {
+ if binary.BigEndian.Uint32(packet[20:24]) == 0x271b3a6b && binary.BigEndian.Uint32(packet[37:41])&0x40001 != 0 {
population[binary.BigEndian.Uint32(packet[28:32])] = packet
}
}
@@ -97,7 +102,7 @@ func TestPopulationsAreSharedAndZoneScoped(t *testing.T) {
}
}
- if len(populations[0]) != 50 || len(populations[1]) != 50 || len(populations[2]) != 58 || len(populations[3]) != 88 || len(populations[4]) != 10 {
+ if len(populations[0]) != 50 || len(populations[1]) != 50 || len(populations[2]) != 58 || len(populations[3]) != 88 || len(populations[4]) != 1842 {
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
diff --git a/server/respawn.go b/server/respawn.go
@@ -32,6 +32,7 @@ func (server *server) advanceNPCRespawns(now time.Time) {
monsterData: respawn.npc.monsterData, level: respawn.npc.level, npc: true,
combatProfile: npcCombatProfile(respawn.npc.npcDefinitionID, respawn.npc.monsterData, respawn.npc.level), npcDefinitionID: respawn.npc.npcDefinitionID,
}
+ npc.equipNPCOutfit()
npc.health = npc.maximumHealth()
if respawn.npc.motion != nil {
npc.position = respawn.npc.motion.home
diff --git a/server/world.go b/server/world.go
@@ -61,8 +61,15 @@ func characterPacket(character *character) []byte {
flags |= 0x2000
}
human := character.appearance>>4&7 < 6
+ humanoidNPC := character.npc && human && len(character.inventory.Items) != 0
if character.npc {
- flags |= 1
+ if humanoidNPC {
+ // kkr.dll sub_36082AD0: bit 18 retains IsNpc on the humanoid path.
+ // Bit 0 constructs a monster mesh before initializing breed and sex.
+ flags |= 0x40002
+ } else {
+ flags |= 1
+ }
// kkr.dll 0x100821d0: bit 27 supplies HasKnuBotData (stat 768).
if gamedata.NPCScripts[character.npcDefinitionID].Talk != nil {
flags |= 0x08000000
@@ -71,7 +78,7 @@ func characterPacket(character *character) []byte {
if human {
flags |= 0x90
// kkr.dll FUN_100821d0: bit 3 enables CanChangeClothes (stat 223).
- if !character.npc {
+ if !character.npc || len(character.inventory.Items) != 0 {
flags |= 8
}
}
@@ -93,7 +100,7 @@ func characterPacket(character *character) []byte {
body = append(body, 0)
// Flags, auxiliary state, Swimming, physical abilities, level and health.
- if !character.npc {
+ if !character.npc || humanoidNPC {
for _, value := range []uint32{0, 0, 0} {
body = binary.BigEndian.AppendUint32(body, value)
}
diff --git a/server/world_store.go b/server/world_store.go
@@ -244,6 +244,7 @@ func (server *server) loadNPCs() (bool, error) {
}
npc := state.Character.character()
npc.npc, npc.npcDefinitionID = true, state.Definition
+ npc.equipNPCOutfit()
npc.stats, npc.profession = state.Character.Profile.Stats, state.Character.Profile.Profession
npc.combatProfile = npcCombatProfile(npc.npcDefinitionID, npc.monsterData, npc.level)
npc.leadingContributor = state.LeadingContributor
diff --git a/tools/client/test_npc_outfits.mjs b/tools/client/test_npc_outfits.mjs
@@ -0,0 +1,67 @@
+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 = [];
+// Bound startup below the fixture deadline so native failures retain diagnostics.
+async function ready(game) {
+ let timer;
+ try {
+ await Promise.race([game.ready(), new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error('NPC outfit client startup timed out')), 45000);
+ })]);
+ } finally { clearTimeout(timer); }
+}
+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: `npc-outfit-${index}`, url}]);
+ const page = await context.newPage();
+ const game = await GameTest.attach(page);
+ games.push(game);
+ await page.goto(url, {waitUntil: 'domcontentloaded'});
+ await ready(game);
+ console.log(`client ${index}: ready`);
+ }
+ const expected = await (await games[0].page.request.get(url + '/test-state')).json();
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output + '/server.json', JSON.stringify(expected, null, 2) + '\n');
+
+ for (const phase of ['initial', 'reconnected']) {
+ for (const [index, game] of games.entries()) {
+ if (phase === 'reconnected') {
+ await game.page.reload({waitUntil: 'domcontentloaded'});
+ await game.page.waitForFunction(() => typeof Module !== 'undefined' && typeof Module._browser_test_request === 'function');
+ await ready(game);
+ }
+ await game.page.waitForFunction(() => touchRegion(500, 400)?.world === true);
+ if (!game.state.camera.firstPerson) await game.key('F8');
+ await game.wait('NPC clothing and armor applied', state => {
+ const actor = state.actors.find(actor => actor.type === 50000 && actor.id === expected.id);
+ return actor?.stats[223] === 1 && expected.armor.every((value, i) => actor.effectiveArmor[i] === value);
+ });
+ const wear = game.events.filter(event => event.kind === 'packet' && event.navigation === game.navigation &&
+ event.direction === 'framereceived' && event.opcode === '35505644' && event.actor?.[1] === expected.id)
+ .map(event => { const packet = Buffer.from(event.hex, 'hex');
+ return [packet.readUInt32BE(29), packet.readUInt32BE(37), packet.readUInt32BE(45), packet.readUInt32BE(53)]; });
+ assert.deepEqual(wear, expected.items.map(item => [item.Template, item.Quality, 6, item.Slot]));
+ await game.click(...await game.pick(50000, expected.id));
+ await game.wait('NPC selected', state => state.selected[0] === 50000 && state.selected[1] === expected.id);
+ await game.save(`${output}/${phase}-${index}`);
+ assert.deepEqual(game.errors, []);
+ }
+ }
+ console.log('PASS:', expected.route, 'matching native outfit and armor on two clients before and after reconnect');
+} catch (error) {
+ console.error(error);
+ throw error;
+} finally {
+ try { await Promise.all(games.map((game, index) => game.save(`${output}/final-${index}`))); }
+ finally { await browser.close(); }
+}