commit e122813f451660d724a1574f1ea31e4e02d7650f
parent 49067b3650099f5af0ee98290751228ac71602fe
Author: anon <anon@example.com>
Date: Thu, 22 Oct 2026 23:11:25 +0000
Persist native nano learning and consume its crystal once
Diffstat:
15 files changed, 458 insertions(+), 12 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -264,7 +264,7 @@ checks are recorded in [treatment kits](docs/treatment-kit.md).
## Nanos and effects
-- [ ] Learn one nano program. Check: consuming its crystal adds a persistent
+- [x] Learn one nano program. Check: consuming its crystal adds a persistent
native program entry and cannot learn or consume it twice accidentally.
- [ ] Cast one self-heal. Check: cast time, nano cost, health gain and recharge
agree with the chosen program and appear correctly in the native client.
@@ -289,6 +289,12 @@ checks are recorded in [treatment kits](docs/treatment-kit.md).
- [ ] Coordinate a nano with weapon combat. Check: casting, interruption and
recharge follow shared action rules without accelerating either action.
+The QL 1 Meta-Physicist startup crystal now learns Lesser Anger Manifestation
+through the native upload effect. Two WASM clients verified requirements,
+single consumption, duplicate rejection, program-window updates and restart.
+The exact route, learned-list layout and casting boundary are in
+[nano learning](docs/nano-learning.md).
+
## Quests
- [ ] Accept one quest through an existing NPC conversation. Check: the choice
diff --git a/docs/combat-client-effect-handlers.md b/docs/combat-client-effect-handlers.md
@@ -179,7 +179,7 @@ render/text/appearance call; an evocative name alone was not enough.
| --- | --- | --- |
| 53012 Skill | `100bd600` | Decoded: additive character modifier. |
| 53014 TimedEffect | special branch, `100bd370` | Decoded core: timed modifier and internal expiry; cancellation boundary above. |
-| 53019 Nano | `100be540` | Decoded immediate path: learned nano-list lookup/add/remove helpers `10064eb0`/`10064dd0`/`10064e60`, messages; not a cast/damage outcome. Guard behavior remains as written. |
+| 53019 Nano | `100be540` | Decoded immediate path: learned nano-list lookup/add/remove helpers `10064eb0`/`10064dd0`/`10064e60`, messages; [startup crystal learning](nano-learning.md) uses this path. Guard behavior remains as written. |
| 53026 Set | `100bd380` | Decoded: subject stat setter with restricted cases. |
| 53028 AddSkill | `100bd550` | Decoded: item skill-list pair insertion/update. |
| 53030 GfxEffect | `100be720` | Partial presentation: creates/deletes visual effects, stores effect identity and duration. |
diff --git a/docs/nano-learning.md b/docs/nano-learning.md
@@ -0,0 +1,137 @@
+# Learning a nano in 14.9.1
+
+The supported crystal is the exact QL 1 Meta-Physicist startup crystal 43330,
+item type 51005. Its OnUse event contains function 53019 with program ID 43324,
+Lesser Anger Manifestation. Other crystals and arbitrary qualities are not
+inferred from this endpoint. Acquisition uses the existing fixture grant.
+
+## Requirements and character data
+
+The crystal's Use action requires effective Matter Creation 130 greater than 7,
+effective Time and Space 131 greater than 7, and VisualProfession 368 equal
+to 12 (Meta-Physicist). The crystal has no pet-count requirement. That check
+belongs to casting the learned program. No additional server upload timer is
+inferred: the crystal has no authored attack, recharge or use-delay override.
+
+The trained skills default to 5. Their shipped ability weights, in
+STR/AGI/STA/INT/SEN/PSY order, are:
+
+| Skill | Stat | Weights |
+| --- | --- | --- |
+| Matter Creation | 130 | `[0,0,20,80,0,0]` |
+| Time and Space | 131 | `[0,20,0,80,0,0]` |
+
+The native effective-skill calculation truncates weighted abilities multiplied
+by `float32(0.01) * 0.25`. With abilities of 10, trained 5/6 gives effective
+7/8. The native initializer writes base 5 at `10072898` / `100728a4`.
+First-party registration at `10038af4` / `10038b26` confirms the two names;
+these stat labels must not be reversed.
+
+Character profiles persist `profession`, `matter_creation` and `time_and_space`.
+Missing fields retain the existing Soldier profession 1 and native skill
+starting values. The original twelve professions are accepted. Owner
+FullCharacter publishes real Profession 60 and VisualProfession 368 explicitly;
+visual profession defaults to zero in the native initializer, and no fallback
+to real profession is established. The supported state has no false-profession
+effect, so both values use the saved profession. Observer profession updates
+through InfoPacket are a separate unimplemented path.
+
+## Native upload and consumption
+
+A successful use sends these owner messages in order:
+
+1. GenericCmd `52526858`, success state 1 and the original request sequence.
+2. UseTemplateAction `35505644`, DWORDs
+ `{43330,43330,1,1,3,104,sourceSlot,50000,ownerID}`.
+3. CharacterAction `5e477770`, DeleteItem 112 for the source slot/template.
+
+Native quantity helper `1005e790` debits once on the successful acknowledgement.
+The crystal has Count 26 equal to 1 and Can 30 equal to `0x29`, including Eat
+`0x20`. Reaching zero emits an ItemRemoved event; the separate DeleteItem path
+removes its proxy row. The crystal lacks UseEmptyDestruct flag `0x800`.
+
+UseTemplateAction `1005e980` constructs a fresh template, dispatches action 3
+through `100902b0` to event 0, and runs function 53019. It does not debit the
+crystal again. Handler `100be540` checks learned-list helper `10064eb0`, adds
+through `10064dd0` and refreshes the local program UI. A known entry produces
+native already-known feedback without another insertion. The server rejects
+duplicates before a successful acknowledgement, preserving the spare crystal.
+The original server's exact duplicate failure text is not established; no
+later protocol's upload action is substituted for this verified route.
+
+The program list and crystal removal commit together in `inventory.yaml`.
+Failure publishes no success and changes neither state; an output failure
+after commit is recovered through the next FullCharacter. Program learning
+is private to the owner. Other players receive no learned-entry effect.
+
+## Reconnect layout
+
+The native FullCharacter reader `1007f5b0` consumes inventory, an intermediate
+complex list, then the learned DWORD list at object offset `+0x24`. Its learned
+list uses count `(N+1)*1009` followed by plain program IDs, not identities.
+Activation `1007f102` splices it into the actor's learned-program helper.
+Runtime program identity `53019:43324` is constructed separately by `100b4000`.
+The catalog resource header's type 51051 is not the runtime nano identity type.
+
+The shared-protocol converter inserts the intermediate empty list immediately
+after the inventory entries, at raw offset `44+32*inventoryCount`. Its previous
+fixed offset included five subsequent list headers and only worked while all
+were empty. Supplying a learned list now leaves every following list and stat
+at its native position, including when ordinary inventory remains non-empty.
+
+## Evidence and scope
+
+`python3 tools/data/extract_nano_learning.py` produces
+`local/reports/nano-learning-14.9.1.json` with selected records and skill weights.
+Crystal payload SHA-256:
+`be4420aa89b25161bee7913c3279114e41b15067bf550df04bdc97b372f1f2f4`.
+Program payload SHA-256:
+`8ededbebfc5cf5ff9e13dadb4fe6c73c629009c969ab0c747ef5bcff27230d56`.
+The selected client/index and DLL hashes match [vehicles](vehicles.md).
+
+`local/nano-learning-research/crystal-native.json` and
+`native-program-protocol.json` retain original bytes, source procedures,
+list readers and field names. REA evidence
+`ev_24aa77ca0c925a090a16180a3fc48a2e611ef24c5ff1676599d7f1671f7daffb`
+independently decompiles the original 53019 handler. Its retained snapshot is
+`kkr-handler.rea.json`; the native analysis session was closed afterward.
+
+Learning does not claim pet creation or casting support. The native cast
+request and the selected summon record are retained for that next step.
+The exact original PT50 pet definition, lifetime units and server policies
+remain unresolved in `local/pet-research/`.
+
+## Verification
+
+`TestNanoCrystal*` reproduces the missing upload and checks atomic learning
+and crystal consumption across restart, native message ordering, owner-only
+publication, the learned-list layout, effective skill 7/8, profession, item
+kind/quality, foreign/stale/loading/dead sessions and save failure. Concurrent
+uses of two crystals retain the spare and publish one effect; a closed output
+after commit recovers through reload. `TestNanoLearningLoadsDefaultsForOlderProfiles`
+checks missing profession/skill fields.
+
+Two WASM clients verified native rejection at effective Matter Creation 7 and
+for a Soldier with both skills at 8. After the existing character editor raised
+the Meta-Physicist's trained Matter Creation to 6, normal right-click use
+consumed crystal 501, displayed the native upload message and added program
+43324 to the Space tab. Read-only native list probes found one entry. A spare
+crystal's right-click emitted another native use request, which did not consume
+it or insert another entry. A full server restart restored the same program,
+profession, skills, remaining crystal and unrelated three-charge First Aid
+stack. Repeating the spare crystal after restart was also rejected. The
+observer retained its own crystal and empty program list throughout.
+
+The run passed 34 evidence checks in
+`local/nano-learning-smoke/verification.json`, with UI screenshots, packets,
+profile snapshots and read-only native probes. The program icon and tooltip
+were inspected after reconnect. Only expected connection refusals during the
+intentional restart were recorded. No client adapter changes were required.
+Both clients and the temporary server were closed before the full test runs.
+
+The full `go test ./server/...` run passed (server 91.831 seconds). Five
+repeated race runs of the nano-learning, profile-edit persistence and native
+thirty-slot inventory tests passed in 180.874 seconds. Their logs are retained
+under `local/nano-learning-research/`. Restoring the previous converter offset
+through a temporary Go overlay makes the learned-list regression fail at its
+neighboring-list assertion, recorded in `old-layout-regression.log`.
diff --git a/server/backpacks.go b/server/backpacks.go
@@ -71,9 +71,12 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error
client.useSequence = sequence
if binary.BigEndian.Uint32(body[40:44]) == 104 {
index := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool {
- return item.Slot == binary.BigEndian.Uint32(body[44:48]) && (item.Template == 43552 || item.Template == 85366 || item.Template == 25812)
+ return item.Slot == binary.BigEndian.Uint32(body[44:48]) && (item.Template == 43552 || item.Template == 85366 || item.Template == 25812 || item.Template == 43330)
})
if index >= 0 {
+ if player.inventory.Items[index].Template == 43330 {
+ return server.learnNano_locked(client, index, body)
+ }
if player.inventory.Items[index].Template == 85366 {
return server.useNanoKit_locked(client, index, body)
}
diff --git a/server/gamedata/load.go b/server/gamedata/load.go
@@ -24,6 +24,7 @@ var (
MonsterTemplates = make(map[uint32]*Monster)
Items ItemCatalog
ItemTemplates = make(map[uint32]*Item)
+ NanoTemplates = make(map[uint32]*Item)
MapCoordinates MapCoordinateData
TerrainEvidence TerrainExtractionEvidence
Playfields map[uint32]Playfield
@@ -117,6 +118,8 @@ func init() {
for index := range Items.Items {
if Items.Items[index].RecordType == 1000020 {
ItemTemplates[Items.Items[index].ID] = &Items.Items[index]
+ } else if Items.Items[index].RecordType == 1040005 {
+ NanoTemplates[Items.Items[index].ID] = &Items.Items[index]
}
}
diff --git a/server/inventory.go b/server/inventory.go
@@ -33,12 +33,20 @@ type playerInventory struct {
Containers map[uint32][]ownedItem `yaml:"containers,omitempty"`
FirstAidLockedUntil time.Time `yaml:"first_aid_locked_until,omitempty"`
TreatmentLocks map[uint32]time.Time `yaml:"treatment_locks,omitempty"`
+ LearnedNanos []uint32 `yaml:"learned_nanos,omitempty"`
}
func (inventory playerInventory) validate() error {
if inventory.Credits > 1000000000 {
return fmt.Errorf("credit balance exceeds the native limit")
}
+ learned := make(map[uint32]bool)
+ for _, id := range inventory.LearnedNanos {
+ if gamedata.NanoTemplates[id] == nil || learned[id] {
+ return fmt.Errorf("invalid or duplicate learned nano program")
+ }
+ learned[id] = true
+ }
ids := make(map[uint32]bool)
slots := make(map[uint32]bool)
bags := make(map[uint32]bool)
diff --git a/server/nano_learning.go b/server/nano_learning.go
@@ -0,0 +1,54 @@
+package main
+
+import (
+ "encoding/binary"
+ "slices"
+)
+
+func (server *server) learnNano_locked(client *worldClient, index int, body []byte) error {
+ player := server.characters[client.id]
+ item := player.inventory.Items[index]
+ stats := player.baseStats()
+ accepted := item.Type == 51005 && item.Template == 43330 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 &&
+ player.profession == 12 &&
+ stats.effectiveSkill(stats.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7 &&
+ stats.effectiveSkill(stats.TimeAndSpace, [6]uint32{0, 20, 0, 80, 0, 0}) > 7 &&
+ !slices.Contains(player.inventory.LearnedNanos, 43324)
+ if accepted {
+ // Consume the crystal and grant the program in one atomic save.
+ inventory := player.inventory
+ inventory.Items = slices.Clone(inventory.Items)
+ inventory.Items = slices.Delete(inventory.Items, index, index+1)
+ inventory.LearnedNanos = append(slices.Clone(inventory.LearnedNanos), 43324)
+ if err := server.saveInventory_locked(player, inventory); err != nil {
+ return err
+ }
+ }
+
+ // A success acknowledgement debits the native crystal quantity once.
+ reply := append([]byte(nil), body[16:]...)
+ binary.BigEndian.PutUint32(reply, 2)
+ if accepted {
+ binary.BigEndian.PutUint32(reply, 1)
+ }
+ if err := client.send(n3Packet(0x52526858, 50000, client.id, reply)); err != nil {
+ return err
+ }
+ if !accepted {
+ return nil
+ }
+
+ // OnUse adds the learned entry before DeleteItem removes the empty proxy.
+ var action []byte
+ for _, value := range []uint32{43330, 43330, 1, 1, 3, 104, item.Slot, 50000, client.id} {
+ action = binary.BigEndian.AppendUint32(action, value)
+ }
+ if err := client.send(n3Packet(0x35505644, 50000, client.id, action)); err != nil {
+ return err
+ }
+ var removal []byte
+ for _, value := range []uint32{112, 104, item.Slot, 43330, 43330} {
+ removal = binary.BigEndian.AppendUint32(removal, value)
+ }
+ return client.send(n3Packet(0x5e477770, 50000, client.id, removal))
+}
diff --git a/server/nano_learning_test.go b/server/nano_learning_test.go
@@ -0,0 +1,177 @@
+package main
+
+import (
+ "encoding/binary"
+ "os"
+ "reflect"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+)
+
+func newNanoLearningWorld(t *testing.T) (*server, *combatTestConn) {
+ t.Helper()
+ t.Chdir(t.TempDir())
+ world, conn := newCombatWorld()
+ player := world.newCharacter()
+ player.profession = 12
+ player.stats.MatterCreation, player.stats.TimeAndSpace = 6, 6
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(player, 43330); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ return world, conn
+}
+
+func TestNanoCrystalLearnsAndConsumesOnceAcrossRestart(t *testing.T) {
+ world, conn := newNanoLearningWorld(t)
+ client := world.clients[1]
+ observer := &combatTestConn{}
+ world.characters[2] = &character{id: 2, playfield: 950, health: 100}
+ world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true}
+
+ err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:])
+ restored := newTestInventoryServer(t).characters[1]
+ packet := targetPacket(fullCharacterPacket(restored))
+
+ if err != nil || !slices.Equal(restored.inventory.LearnedNanos, []uint32{43324}) || len(restored.inventory.Items) != 0 ||
+ restored.profession != 12 || restored.stats.MatterCreation != 6 || restored.stats.TimeAndSpace != 6 {
+ t.Fatalf("crystal and learned program did not persist together: %+v, %v", restored.inventory, err)
+ }
+ if len(observer.packets) != 0 || len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 1 ||
+ binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x35505644 || binary.BigEndian.Uint32(conn.packets[1][45:49]) != 3 ||
+ binary.BigEndian.Uint32(conn.packets[2][29:33]) != 112 {
+ t.Fatalf("native crystal upload messages: %x", conn.packets)
+ }
+ if binary.BigEndian.Uint32(packet[37:41]) != 1009 || binary.BigEndian.Uint32(packet[41:45]) != 2018 ||
+ binary.BigEndian.Uint32(packet[45:49]) != 43324 || binary.BigEndian.Uint32(packet[49:53]) != 1009 {
+ t.Fatalf("native learned list displaced its neighboring lists: %x", packet[33:69])
+ }
+}
+
+func TestNanoCrystalRejectsInvalidUseWithoutConsumption(t *testing.T) {
+ for _, scenario := range []string{"Matter Creation 7", "Time and Space 7", "wrong profession", "wrong quality", "wrong type", "foreign owner", "stale session", "loading", "not ready", "dead", "already learned", "failed save"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, conn := newNanoLearningWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ request := backpackUseRequest(1, 64, 1)[20:]
+ switch scenario {
+ case "Matter Creation 7":
+ player.stats.MatterCreation = 5
+ case "Time and Space 7":
+ player.stats.TimeAndSpace = 5
+ case "wrong profession":
+ player.profession = 1
+ case "wrong quality":
+ player.inventory.Items[0].Quality = 2
+ case "wrong type":
+ player.inventory.Items[0].Type = 51022
+ case "foreign owner":
+ binary.BigEndian.PutUint32(request[8:12], 2)
+ case "stale session":
+ world.clients[1] = &worldClient{id: 1}
+ case "loading":
+ client.loading = true
+ case "not ready":
+ client.ready = false
+ case "dead":
+ player.health = 0
+ case "already learned":
+ player.inventory.LearnedNanos = []uint32{43324}
+ case "failed save":
+ if err := os.Remove("data/players/1/inventory.yaml"); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Mkdir("data/players/1/inventory.yaml", 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ before := player.inventory
+
+ err := world.handleOwnedItemUse(client, request)
+
+ if (err != nil) != (scenario == "failed save") || !reflect.DeepEqual(player.inventory, before) || len(conn.packets) > 1 {
+ t.Fatalf("invalid upload consumed crystal or changed learned programs: %+v, %v", player.inventory, err)
+ }
+ if len(conn.packets) == 1 && binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 {
+ t.Fatal("invalid upload acknowledged successful consumption")
+ }
+ })
+ }
+}
+
+func TestNanoCrystalConcurrentDuplicatesConsumeOnlyOneCrystal(t *testing.T) {
+ world, conn := newNanoLearningWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ if granted, err := world.grantItem_locked(player, 43330); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ var workers sync.WaitGroup
+ errors := make(chan error, 2)
+
+ for _, use := range [][2]uint32{{64, 1}, {65, 2}} {
+ workers.Go(func() { errors <- world.handleOwnedItemUse(client, backpackUseRequest(1, use[0], use[1])[20:]) })
+ }
+ workers.Wait()
+ close(errors)
+ for err := range errors {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ restored := newTestInventoryServer(t).characters[1]
+
+ if !slices.Equal(restored.inventory.LearnedNanos, []uint32{43324}) || len(restored.inventory.Items) != 1 ||
+ restored.inventory.Items[0].Template != 43330 || restored.inventory.Items[0].Count != 1 {
+ t.Fatalf("concurrent upload consumed two crystals or duplicated the nano: %+v", restored.inventory)
+ }
+ actions := 0
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x35505644 {
+ actions++
+ }
+ }
+ if actions != 1 {
+ t.Fatal("concurrent uploads published more than one learning effect")
+ }
+}
+
+func TestNanoCrystalAcceptedUseSurvivesClosedOutput(t *testing.T) {
+ world, _ := newNanoLearningWorld(t)
+ client := world.clients[1]
+ client.writeWake, client.writeClosed = make(chan struct{}, 1), true
+
+ err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:])
+ restored := newTestInventoryServer(t).characters[1]
+
+ if err == nil || !slices.Equal(restored.inventory.LearnedNanos, []uint32{43324}) || len(restored.inventory.Items) != 0 {
+ t.Fatalf("closed output lost the committed nano or refunded its crystal: %+v, %v", restored.inventory, err)
+ }
+}
+
+func TestNanoLearningLoadsDefaultsForOlderProfiles(t *testing.T) {
+ newNanoLearningWorld(t)
+ data, err := os.ReadFile("data/players/1/player.yaml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ profile := string(data)
+ for _, field := range []string{"profession: 12\n", " matter_creation: 6\n", " time_and_space: 6\n"} {
+ if !strings.Contains(profile, field) {
+ t.Fatal("missing profile fixture field", field)
+ }
+ profile = strings.ReplaceAll(profile, field, "")
+ }
+ if err := os.WriteFile("data/players/1/player.yaml", []byte(profile), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ restored := newTestInventoryServer(t).characters[1]
+
+ if restored.profession != 1 || restored.stats.MatterCreation != 5 || restored.stats.TimeAndSpace != 5 {
+ t.Fatalf("older profile lost its native defaults: profession=%d stats=%+v", restored.profession, restored.stats)
+ }
+}
diff --git a/server/state.go b/server/state.go
@@ -20,6 +20,7 @@ type character struct {
appearance uint16
monsterData uint32
level uint16
+ profession uint16
stats characterStats
inventory playerInventory
corpse *npcCorpse
@@ -165,7 +166,7 @@ func (server *server) newCharacter_locked() *character {
character := &character{
id: server.nextCharacter, name: fmt.Sprintf("Local Explorer %d", server.nextCharacter),
playfield: 950, position: [3]float32{52.625, 14.75, 56.875 + float32((server.nextCharacter-1)%4)*3},
- rotation: [4]float32{0, 0, 0, 1}, appearance: 0x315, level: 1,
+ rotation: [4]float32{0, 0, 0, 1}, appearance: 0x315, level: 1, profession: 1,
stats: defaultCharacterStats(),
}
character.health = character.maximumHealth()
diff --git a/server/stats.go b/server/stats.go
@@ -20,10 +20,12 @@ type characterStats struct {
FirstAid uint16 `yaml:"first_aid"`
VehicleGround uint16 `yaml:"vehicle_ground"`
VehicleAir uint16 `yaml:"vehicle_air"`
+ MatterCreation uint16 `yaml:"matter_creation"`
+ TimeAndSpace uint16 `yaml:"time_and_space"`
}
func defaultCharacterStats() characterStats {
- return characterStats{10, 10, 10, 10, 10, 10, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}
+ return characterStats{10, 10, 10, 10, 10, 10, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}
}
func (character *character) baseStats() characterStats {
diff --git a/server/target_protocol.go b/server/target_protocol.go
@@ -84,7 +84,7 @@ func targetPacket(packet []byte) []byte {
case 0x29304349:
// FullCharacter has seven encoded lists before its stats.
inventoryCount := int(binary.BigEndian.Uint32(packet[40:44])/1009 - 1)
- inventoryEnd := 64 + inventoryCount*32
+ inventoryEnd := 44 + inventoryCount*32
for index := 0; index < inventoryCount; index++ {
cursor := 44 + index*32
slot := binary.BigEndian.Uint32(packet[cursor:])
diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go
@@ -82,7 +82,7 @@ initialized:
if hex.EncodeToString(npc[60:89]) != "000001cb0b456469746564204e50430000000000000000000000000007" {
t.Fatalf("target NPC appearance, name and new stats: %x", npc[60:89])
}
- if hex.EncodeToString(full[57:73]) != "000003f1000086020000003600000001" {
+ if hex.EncodeToString(full[57:73]) != "000003f1000091d50000003600000001" {
t.Fatalf("target seventh list and first stat: %x", full[57:73])
}
}
diff --git a/server/users.go b/server/users.go
@@ -28,6 +28,7 @@ type userData struct {
Appearance uint16 `yaml:"appearance"`
MonsterData uint32 `yaml:"monster_data"`
Level uint16 `yaml:"level"`
+ Profession uint16 `yaml:"profession"`
Stats characterStats `yaml:"stats"`
Running bool `yaml:"running"`
ReturnDoor *doorOrigin `yaml:"return_door,omitempty"`
@@ -41,6 +42,7 @@ type playerProfile struct {
Appearance uint16 `yaml:"appearance"`
MonsterData uint32 `yaml:"monster_data"`
Level uint16 `yaml:"level"`
+ Profession uint16 `yaml:"profession"`
Stats characterStats `yaml:"stats"`
Running bool `yaml:"running"`
BrowserTokenHash string `yaml:"browser_token_hash,omitempty"`
@@ -58,12 +60,13 @@ type playerPosition struct {
func (character *character) userData() userData {
return userData{character.id, character.name, character.playfield, character.position,
- character.rotation, character.appearance, character.monsterData, character.level, character.baseStats(), character.running, character.returnDoor, character.browserTokenHash}
+ character.rotation, character.appearance, character.monsterData, character.level, max(1, character.profession), character.baseStats(), character.running, character.returnDoor, character.browserTokenHash}
}
func (data userData) character() *character {
character := &character{id: data.ID, name: data.Name, playfield: data.Playfield, position: data.Position,
rotation: data.Rotation, appearance: data.Appearance, monsterData: data.MonsterData, level: data.Level,
+ profession: max(1, data.Profession),
running: data.Running,
stats: data.Stats,
returnDoor: data.ReturnDoor, browserTokenHash: data.BrowserTokenHash}
@@ -86,6 +89,9 @@ func (data userData) validate() error {
if data.Level == 0 {
return fmt.Errorf("level must be at least 1")
}
+ if data.Profession > 12 {
+ return fmt.Errorf("profession must be one of the twelve original professions")
+ }
if data.Stats != (characterStats{}) && (data.Stats.Strength == 0 || data.Stats.Agility == 0 || data.Stats.Stamina == 0 ||
data.Stats.Intelligence == 0 || data.Stats.Sense == 0 || data.Stats.Psychic == 0) {
return fmt.Errorf("abilities must be at least 1")
@@ -140,7 +146,7 @@ func (server *server) loadUsers() error {
return err
}
// Missing trained skills in older profiles retain their starting values.
- profile := playerProfile{Stats: defaultCharacterStats()}
+ profile := playerProfile{Profession: 1, Stats: defaultCharacterStats()}
if err := decodeUsers(bytes.NewReader(contents), &profile); err != nil {
return fmt.Errorf("%s: %w", path, err)
}
@@ -156,6 +162,7 @@ func (server *server) loadUsers() error {
user := userData{
ID: profile.ID, Name: profile.Name, Appearance: profile.Appearance,
MonsterData: profile.MonsterData, Level: profile.Level, Stats: profile.Stats, Running: profile.Running,
+ Profession: profile.Profession,
BrowserTokenHash: profile.BrowserTokenHash,
Playfield: position.Playfield, Position: position.Position,
Rotation: position.Rotation, ReturnDoor: position.ReturnDoor,
@@ -234,7 +241,7 @@ func (server *server) users_locked() []userData {
func (server *server) saveUser_locked(character *character) error {
// Ordinary movement never rewrites identity, credentials or character properties.
profile := playerProfile{character.id, character.name, character.appearance, character.monsterData,
- character.level, character.baseStats(), character.running, character.browserTokenHash, character.resurrectionTerminal,
+ character.level, max(1, character.profession), character.baseStats(), character.running, character.browserTokenHash, character.resurrectionTerminal,
character.implantChangesUntil, character.treatmentLockedUntil}
if profile == character.savedProfile {
return nil
diff --git a/server/world.go b/server/world.go
@@ -182,11 +182,18 @@ func fullCharacterPacket(character *character) []byte {
body = binary.BigEndian.AppendUint32(body, value)
}
}
- for range 5 {
+ // The learned program list stores plain template IDs, not item identities.
+ body = binary.BigEndian.AppendUint32(body, uint32(len(character.inventory.LearnedNanos)+1)*1009)
+ for _, id := range character.inventory.LearnedNanos {
+ body = binary.BigEndian.AppendUint32(body, id)
+ }
+ for range 4 {
body = binary.BigEndian.AppendUint32(body, 1009)
}
base := character.baseStats()
- stats := [][2]uint32{{54, uint32(character.level)}, {4, uint32(character.appearance >> 4 & 7)}, {60, 1}, {33, uint32(character.appearance >> 9 & 3)}, {59, uint32(character.appearance >> 7 & 3)}, {156, 100}, {16, uint32(base.Strength)}, {17, uint32(base.Agility)}, {18, uint32(base.Stamina)}, {19, uint32(base.Intelligence)}, {20, uint32(base.Sense)}, {21, uint32(base.Psychic)}, {27, character.health}, {1, character.maximumHealth()}, {123, uint32(base.FirstAid)}, {124, uint32(base.Treatment)}, {37, character.titleLevel()}}
+ stats := [][2]uint32{{54, uint32(character.level)}, {4, uint32(character.appearance >> 4 & 7)}, {60, uint32(max(1, character.profession))}, {33, uint32(character.appearance >> 9 & 3)}, {59, uint32(character.appearance >> 7 & 3)}, {156, 100}, {16, uint32(base.Strength)}, {17, uint32(base.Agility)}, {18, uint32(base.Stamina)}, {19, uint32(base.Intelligence)}, {20, uint32(base.Sense)}, {21, uint32(base.Psychic)}, {27, character.health}, {1, character.maximumHealth()}, {123, uint32(base.FirstAid)}, {124, uint32(base.Treatment)}, {37, character.titleLevel()}}
+ stats = append(stats, [2]uint32{368, uint32(max(1, character.profession))},
+ [2]uint32{130, uint32(base.MatterCreation)}, [2]uint32{131, uint32(base.TimeAndSpace)})
stats = append(stats, [2]uint32{51, uint32(character.aggDef)}, [2]uint32{161, uint32(base.ComputerLiteracy)}, [2]uint32{61, character.inventory.Credits})
stats = append(stats, [2]uint32{166, uint32(base.VehicleGround)})
stats = append(stats, [2]uint32{139, uint32(base.VehicleAir)})
diff --git a/tools/data/extract_nano_learning.py b/tools/data/extract_nano_learning.py
@@ -0,0 +1,41 @@
+import hashlib
+import json
+import pathlib
+import struct
+
+import ao_database
+import extract_items
+
+
+def main():
+ client = pathlib.Path('anarchy-vanilla-14.9.1')
+ assert (client / 'version.id').read_text().strip() == '14.9.1'
+ database = ao_database.Database(client)
+
+ # Retain the exact startup crystal and the program it uploads.
+ records = []
+ for kind, identity in ((1000020, 43330), (1040005, 43324)):
+ raw = database.read(kind, identity)
+ item = extract_items.parse_item(raw, kind, identity)
+ assert item['quality'] == 1
+ records.append(dict(record=item, payload_sha256=hashlib.sha256(raw).hexdigest()))
+ assert records[0]['record']['header_words'][0] == 51005
+ assert records[1]['record']['header_words'][0] == 51051
+
+ # Matter Creation and Time and Space have distinct ability weights.
+ weights = {}
+ for stat in (130, 131):
+ raw = database.read(1000204, stat)
+ weights[stat] = dict(weights=struct.unpack('<6i', raw), payload_hex=raw.hex(),
+ payload_sha256=hashlib.sha256(raw).hexdigest())
+ database.close()
+
+ output = pathlib.Path('local/reports/nano-learning-14.9.1.json')
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(json.dumps(dict(index_sha256=hashlib.sha256(database.index).hexdigest(),
+ records=records, skill_weights=weights), indent=2) + '\n')
+ print(output)
+
+
+if __name__ == '__main__':
+ main()