commit 520b905fe51f6b6b073ff887ddfe17be9e74849a
parent 5d1c0d028c66d1595b30380a95b49fcf36f74a13
Author: anon <anon@example.com>
Date: Fri, 23 Oct 2026 04:08:18 +0000
Persist world state in SQLite and simplify control panel editing
Diffstat:
91 files changed, 3759 insertions(+), 1017 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -21,6 +21,7 @@ node_modules/
/client/build/
# Local proprietary assets and mutable server state.
+/data/world.sqlite*
/data/*.bin
/data/npc_spawns*.yaml
/data/*.tmp
diff --git a/docs/backpacks.md b/docs/backpacks.md
@@ -91,15 +91,16 @@ Evidence:
## Persistence and boundaries
-`inventory.yaml` stores a `containers` map from backpack ID to its owned item
-rows. Each item occurs in exactly one location. Startup rejects orphan contents,
+The world database stores each backpack's contents as item locations. Its YAML
+editor shows 21 named slots containing item IDs or null. Each item occurs in
+exactly one location. Startup rejects orphan contents,
duplicate IDs/slots, nested bags, zero quantities and positions outside 0..20.
Transfers preserve instance IDs and quantities; split creates a fresh global
ID using the existing atomic inventory transaction. Stack split/join and item
deletion also understand packed bag positions. A rejected optimistic bag split
receives an authoritative InventoryUpdate for that Chest.
-Contents follow their backpack into and out of reclaim in the same owner file;
+Contents follow their backpack into and out of reclaim in the shared item store;
an unavailable bag cannot be addressed through an old session handle. The current
delete operation removes a bag and its contents in one transaction, then retires
its handle. Native DeleteItem does not check whether a bag is filled, and Chest
diff --git a/docs/combat-regeneration.md b/docs/combat-regeneration.md
@@ -8,27 +8,37 @@ server's scheduler is not established by those rules.
## Character data
-The existing character editor at `/users/<id>` includes a persistent `stats`
-section. All six abilities and eight trained skills are editable:
+The character editor at `/control/users/<id>` shows one YAML document
+with every field and its current value. The `stats`
+section contains all six abilities and 69 skills under the
+classic UI categories: abilities, body, melee, misc weapons, ranged, speed,
+trade/repair, nano/aiding, spying and navigation. For example:
```yaml
stats:
- strength: 10
- agility: 10
- stamina: 60
- intelligence: 10
- sense: 10
- psychic: 120
- martial_arts: 100
- one_hand_edged: 5
- melee_initiative: 5
- brawling: 5
- fast_attack: 5
- physical_initiative: 600
- body_development: 200
- nano_pool: 100
+ improvement_points: 1500
+ abilities:
+ strength: 10
+ agility: 10
+ stamina: 60
+ intelligence: 10
+ sense: 10
+ psychic: 120
+ body:
+ martial_arts: 100
+ body_development: 200
+ nano_pool: 100
+ speed:
+ physical_initiative: 600
```
+The editor expands this abbreviated example to include every other skill.
+All skills default to base 5, except the fixture's Run Speed of 100; abilities
+default to 10. Available IP is persisted as `improvement_points` and sent as
+native stat 53. Its initial value of 1500 matches the default in
+`client/game/kkr.dll/lifted-0034.c`, `sub_36072760`. This adds storage and client
+replication, not native IP spending or level-based IP awards.
+
Skills here are trained/base values. Effective skill adds the integer ability
contribution from the shipped resource type 1000204. Weights follow Strength,
Agility, Stamina, Intelligence, Sense, Psychic:
@@ -58,21 +68,18 @@ float store before AggDef subtraction. At effective initiative 387 and AggDef
-100, recharge truncates to 170 centiseconds; the algebraically simplified
division would give 171. This boundary is covered by a regression test.
-Older profiles with no stats retain abilities 10 and these eight base skills 5.
-Profiles saved before the four melee skills were added receive base values 5
-for the missing fields. Explicitly saved zero skill values remain zero. The
-native Skills window displays 7 for each new skill at the default abilities,
-including ability trickle. QL 1 Kinetic Axe attacks use Melee Initiative;
-unequipping restores fists and Physical Initiative. Its requirements also use
-the effective 1h Edged, Brawling and Fast Attack values.
-Saving writes the explicit stats to `data/players/<id>/player.yaml`. Values
-survive profile edits, teleporting and restart; location saving still writes
-only `position.yaml`. Lowering resource maximums clamps current health/nano.
-Resources remain session state: restart initializes full health and zero nano.
-
-This does not implement native IP spending, profession selection, equipment
-modifiers or MA selecting fist QL. Other skills still use the existing client
-and fixture defaults. Increasing Martial Arts must not be presented as a
+Omitted nested fields retain their current values; explicitly saved zero skills
+remain zero.
+QL 1 Kinetic Axe attacks use Melee Initiative; unequipping restores fists and
+Physical Initiative. Its requirements also use the effective 1h Edged,
+Brawling and Fast Attack values.
+Saving writes explicit stats, location, resources and inventory to native SQLite
+fields in one transaction. Values survive editing, teleporting and restart.
+Routine movement saves update position fields without rewriting profile fields.
+Lowering resource maximums clamps current health/nano.
+
+Native IP spending and unsupported skill-dependent game mechanics remain
+separate work. Every saved ability and skill is sent to the client. Increasing Martial Arts must not be presented as a
complete server damage-scaling implementation while that calculation remains
unresolved.
diff --git a/docs/corpse-credits.md b/docs/corpse-credits.md
@@ -1,8 +1,8 @@
# Corpse credits
Cash is native stat 61. The server persists a player's balance in the same
-`inventory.yaml` replacement as owned items and supplies it in FullCharacter
-on login. Older inventories default to zero. Creature cash amounts remain
+world database transaction as owned items and supplies it in FullCharacter
+on login. New characters start at zero. Creature cash amounts remain
unconfigured; controlled fixtures supply known amounts for this milestone.
## Native collection
diff --git a/docs/inventory-stacks.md b/docs/inventory-stacks.md
@@ -66,12 +66,11 @@ cap remains unresolved. Overflow assembly evidence:
## Persistence and rejection
-Each owned item now has a ushort Count in `inventory.yaml`; pre-quantity saved
-items and reclaim entries with an absent/zero count load as one individual.
-The supported Essence and QL 1 Simple Nano Kit can have counts above one. FullCharacter,
-corpse and reclaim entries serialize the quantity rather than a constant one.
-The existing atomic inventory replacement publishes both changed counts and
-any newly allocated ID together, after saving successfully.
+Each instance has a ushort count in the world database. The supported Essence
+and QL 1 Simple Nano Kit can have counts above one. FullCharacter, corpse and
+reclaim entries serialize the quantity rather than a constant one. Atomic
+replacement of the shared store commits the counts, slot references and any
+newly allocated ID together, after saving successfully.
A split requires `1 <= retained < currentCount` and an empty ordinary slot.
The server gives the new stack the first free slot and a fresh global ID.
diff --git a/docs/inventory.md b/docs/inventory.md
@@ -1,18 +1,48 @@
# Inventory behavior and 14.9.1 evidence
-The server persists individual owned items in
-`data/players/<owner>/inventory.yaml`, separately from the editable character
-profile. Each item has an instance ID, native identity type, exact template,
-quality, quantity and logical inventory slot. The first fixture uses QL 1 Solar-Powered
-Pistol, template 121567, identity type 51018. Players do not receive a fixture
-item automatically.
-
-The ordinary inventory has 30 slots. Saved inventories and the shared 11.0
+`data/world.sqlite` stores mutable world state. Its `items` table has one row
+per instantiated item; `item_locations` records player, backpack and corpse
+placement. Transactions commit quantities, ownership, credits, reclaim and
+consumable locks together. See [world storage](world-state.md).
+
+An instance ID is unique across all characters, equipment, backpacks and
+reclaim. The template identifies the catalog definition; different instances
+can share a template and quality. Stackable consumables have one ID and a
+quantity. A use decrements that quantity; consuming the last charge removes
+the instance. Splitting allocates another global ID, while merging removes
+one ID and keeps the other. The global high-water mark survives deletion.
+
+Each player's `slots` has `inventory_slot_1` through `inventory_slot_30`,
+containing an item ID or `null`. `equipment` uses names such as
+`weapons_right_hand`, `clothes_left_arm` and `implants_left_arm`. A backpack item record contains
+its own `slots`, numbered 1 through 21. These reference item IDs too;
+backpacks cannot contain backpacks. Item properties and placement have one
+authoritative source rather than being duplicated in each player's save.
+
+`/control/items` lists instances with names, qualities, counts, owners and
+locations. Search matches instance IDs, templates, names and owners. Clicking
+an instance opens its editable YAML properties and read-only catalog record.
+Both lists show 500 matching rows per page and retain filters in navigation.
+`/control/items/catalog` filters templates by name or ID. Each row creates an
+unassigned instance at its exact catalog quality.
+Its assignment form offers only free compatible player/equipment/backpack
+slots. Admin equipment assignment bypasses gameplay skill requirements.
+
+The character page at `/control/users/<owner>` shows one editable YAML document
+for the character, position, vitals and inventory, with all empty slots visible. Moving an
+ID preserves the instance; clearing its slot leaves it unassigned. Duplicate
+references and unknown IDs are rejected, including during startup. Native
+consumption and deletion remove the item record instead of unassigning it.
+
+The first fixture uses QL 1 Solar-Powered Pistol, template 121567, identity
+type 51018. Players do not receive a fixture item automatically.
+
+The ordinary inventory has 30 slots. Runtime inventories and the shared 11.0
protocol use 64 through 93; the 14.9.1 wire uses 48 through 77. Grants choose an
empty saved slot and return failure when all are occupied. Inventory changes
-use the existing atomic file replacement and become visible in memory after the save
-succeeds. A persisted last-issued ID preserves the allocation high-water mark,
-including after deleting the last item. Startup takes the maximum across owners.
+use a SQLite transaction and become visible in memory after the save
+succeeds. The shared store preserves the allocation high-water mark even after the
+last item has been deleted.
Profile edits and zoning preserve inventory independently of profile fields.
Items use exact catalog qualities with identical template endpoints. Essence
diff --git a/docs/nano-learning.md b/docs/nano-learning.md
@@ -62,7 +62,7 @@ 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`.
+The program list and crystal removal commit together in the world database.
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.
diff --git a/docs/playfield-validation.md b/docs/playfield-validation.md
@@ -62,7 +62,7 @@ loading a scene; that startup failure is not playfield-specific.
The sweep needs Go, a C compiler, SDL2/OpenGL development libraries, Python 3.11
or newer with Pillow, `gnome-session-inhibit`, and `xset`. It reserves ports
-7520, 7521 and 8082. It does not use the user's server or `data/players/` files.
+7520, 7521 and 8082. It does not use the user's server or world database.
Preferences and diagnostics are private to the run; large immutable assets
are shared. Results remain under `local/playfield-sweep/playfield-sweep-*`.
Ctrl-C stops the owned processes and keeps completed results.
diff --git a/docs/project-notes.md b/docs/project-notes.md
@@ -81,7 +81,7 @@ advertise the configured ports. Each flag can be used on its own.
Point a separate client's dimension-list URL at the second instance's HTTP
port; the direct-launch Python helpers still use their fixed default ports.
Run each instance from a separate working directory with its own `data/`
-copy, especially `data/players/`, so the instances cannot overwrite each
+copy, especially `data/world.sqlite`, so the instances cannot overwrite each
other's saved users. Build an executable first to run it outside this checkout.
The main server selects the recovered 14.9.1 world layout from its cookie
@@ -101,17 +101,17 @@ in a YAML textarea or teleport them by selecting a location on their map. Offlin
users and users reconnecting during a teleport stay on the list.
The page uses plain HTML forms and a small JavaScript canvas map. The world starts at
13:30. Rubi-Ka has a 27-hour day, running at 15 game seconds per real second.
-Hour values range from 0 to 26; minutes range from 0 to 59. The clock resets when
-the server restarts. Zones and received movement positions are saved every
-20 seconds in `data/players/<id>/position.yaml`; identity and character
-properties live in `player.yaml`. Both are restored at startup. Each local
-user currently owns one character, with a stable ID. Walk/run mode is saved
-in the `running` YAML field. The server supplies that
-mode in the initial vehicle state on login and zone reconnect; older records
-without the field start in walking mode. Saving character data
+Hour values range from 0 to 26; minutes range from 0 to 59. The clock, characters,
+items, NPCs and other variable state live in `data/world.sqlite` and survive
+restarts. Player movement saves every 20 seconds. The world checks for pending
+saves every second; routine NPC saves are staggered at 20-second intervals in
+occupied zones. See [world storage](world-state.md). Each local user currently
+owns one character, with a stable ID. Walk/run mode is saved in the `running`
+field and supplied in the initial vehicle state on login and zone reconnect.
+Saving character data
refreshes an online character through the native zone reconnect sequence.
-Edit a user's file directly while the server is stopped, or use the web editor while
-it runs. The storage files are local development data and are ignored by Git.
+Use the web editor while the server runs. Its YAML text represents database
+records. The database is local development data and is ignored by Git.
To extract the control UI's map tiles from `anarchy-vanilla-14.9.1`, run from
the repository root:
diff --git a/docs/reclaim.md b/docs/reclaim.md
@@ -92,17 +92,17 @@ the private window via `0x1005dc40` and `0x10053160`.
## Persistence and validation
-`inventory.yaml` contains both ordinary `items` and optional `reclaim` entries.
-Each reclaim entry contains the complete owned item plus `available_at`.
-`last_id` covers both locations, and loading rejects duplicate identities
-within or across them. The item's old inventory slot is retained as metadata;
+The world database contains item records and each player's slot references and reclaim entries.
+Each reclaim entry references an item ID and records `available_at`.
+Properties live in the shared item record. The global `last_id` covers all
+locations, and loading rejects duplicate assignments within or across players. The item's old inventory slot is retained as metadata;
collection selects a currently free slot. Repeated deaths can therefore retain
items that occupied the same old slot without treating them as duplicates.
A lethal hit saves the inventory/reclaim transfer before changing health or
publishing death. Failed persistence logs the error, cancels the fight and
leaves the player alive with the original items. Retrieval saves both sides in
-one atomic file replacement before its move reply. Full inventory, failed
+one SQLite transaction before its move reply. Full inventory, failed
writes, repeated pickups and stale sessions keep the source unchanged.
Ordinary grants, moves, deletion, equipment changes and corpse loot preserve
pending reclaim entries.
diff --git a/docs/repository-packaging.md b/docs/repository-packaging.md
@@ -51,8 +51,8 @@ support DLLs, saved users, logs and screenshots are excluded. No resource archiv
or file splitting is used.
The binary serves static files directly, including HTTP byte ranges, without
-unpacking them. Mutable state goes to `data/`: saved characters in `data/players/`
-and certificates in `data/https/`. Server logs go to `logs/server.log`; the
+unpacking them. Mutable world state goes to `data/world.sqlite`; certificates
+stay in `data/https/`. Server logs go to `logs/server.log`; the
terminal shows startup, connections and errors. Browser profiles go to `logs/profiles/`.
Old unpacked assets and `.runtime-bundle` markers are no longer read by the
server. Rebuild the Go binary after updating any static inputs or NPC code.
diff --git a/docs/world-state.md b/docs/world-state.md
@@ -0,0 +1,54 @@
+# World storage
+
+The server stores mutable game state in `data/world.sqlite`. Static catalogs,
+NPC definitions, terrain, maps and client assets remain embedded resources.
+The database contains:
+
+- `world`: item/player/NPC identity counters and the clock's starting time.
+- `characters`: individual profile, ability/skill, appearance, position and vital columns.
+- `players`: player identity, credits and first-aid cooldown.
+- `learned_nanos` and `treatment_locks`: one row per learned program or patient lock.
+- `npcs`: live NPC poses, health, roaming state, damage contributors, corpse
+ cash/ownership/expiry and respawn deadlines, including expired actors whose
+ replacements are still pending.
+- `items`: globally unique item IDs and instance properties.
+- `item_locations`: inventory, equipment, backpack, reclaim and corpse slots.
+- `chat_history`: private history per participant, indexed by owner and order.
+
+All mutable state uses native SQL scalar columns and related rows. There are
+no YAML/JSON state blobs or earlier-format readers. Item identity and placement
+use relational columns: foreign keys reject missing
+owners or instances, the item ID allows only one location, and unique indexes
+reject two items in an occupied slot. Backpacks cannot contain backpacks.
+
+The connection uses WAL, full synchronous commits and foreign keys. Inventory
+changes, corpse loot transfers and cash transfers commit atomically before
+success is published. Profiles and admin clock changes save immediately.
+Player movement saves at staggered 20-second intervals. NPC state is checked
+on the one-second world tick, but routine writes occur at least 20 seconds
+apart, with random starting phases, only in zones with a connected player.
+The last player leaving a zone triggers one final snapshot. Unchanged rows
+are skipped. Corpse ownership and cash changes save immediately with their
+loot transaction. A new database takes one initial population snapshot.
+SIGINT/SIGTERM flush pending state before closing the database. A crash can
+lose simulation changes since the relevant checkpoint. Network sessions
+and in-progress client requests are recreated on connection.
+
+Restarts restore NPC instances rather than adding a new copy of the static
+population. Only a new database seeds NPCs from the static definitions. The
+world clock continues advancing across downtime. Reconnecting chat clients
+receive their latest 500 history entries, in chronological order.
+
+The character control page presents one YAML editing document for profile,
+position, vitals and inventory. Appearance has separate race, fatness, breed,
+sex, side and head fields, with comments explaining native codes. Every skill
+and empty slot is visible. Equipment uses names such as `clothes_left_arm` and
+`implants_left_arm`; ordinary inventory uses `inventory_slot_1` through
+`inventory_slot_30`. Backpack item pages use `slot_1` through `slot_21`.
+Saving the character document commits all sections and item placements in one
+transaction. YAML is only an editing format; the server does not read or write
+mutable YAML files. There is no migration path for previous server databases.
+To reset the world,
+stop the server and delete `data/world.sqlite` and any matching `-wal`/`-shm`
+files before restarting. Server builds require CGO and a C compiler for the
+[SQLite driver](https://github.com/mattn/go-sqlite3).
diff --git a/go.mod b/go.mod
@@ -4,5 +4,6 @@ go 1.24
require (
github.com/coder/websocket v1.8.15
+ github.com/mattn/go-sqlite3 v1.14.52
go.yaml.in/yaml/v3 v3.0.5
)
diff --git a/go.sum b/go.sum
@@ -1,4 +1,6 @@
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
+github.com/mattn/go-sqlite3 v1.14.52 h1:wVbm2Qnf4OXkqhBTSPuCRZDRnxfbVrrmiCEroVdog8U=
+github.com/mattn/go-sqlite3 v1.14.52/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
diff --git a/server/appearance.go b/server/appearance.go
@@ -0,0 +1,52 @@
+package main
+
+import (
+ "fmt"
+
+ "go.yaml.in/yaml/v3"
+)
+
+type appearanceFields struct {
+ Race uint16 `yaml:"race"`
+ Fatness uint16 `yaml:"fatness"`
+ Breed uint16 `yaml:"breed"`
+ Sex uint16 `yaml:"sex"`
+ Side uint16 `yaml:"side"`
+ Head uint16 `yaml:"head"`
+}
+
+func unpackAppearance(value uint16) appearanceFields {
+ return appearanceFields{value & 3, value >> 2 & 3, value >> 4 & 7, value >> 7 & 3, value >> 9 & 3, value >> 11 & 31}
+}
+
+func (appearance appearanceFields) packed() uint16 {
+ return appearance.Race | appearance.Fatness<<2 | appearance.Breed<<4 | appearance.Sex<<7 | appearance.Side<<9 | appearance.Head<<11
+}
+
+func (appearance appearanceFields) validate() error {
+ if appearance.Race > 3 || appearance.Fatness > 3 || appearance.Breed > 7 || appearance.Sex > 3 || appearance.Side > 3 || appearance.Head > 31 {
+ return fmt.Errorf("appearance fields exceed their client bit ranges")
+ }
+ return nil
+}
+
+func (appearance appearanceFields) MarshalYAML() (any, error) {
+ // Annotate the editing document without storing presentation text in SQLite.
+ type fields appearanceFields
+ var node yaml.Node
+ if err := node.Encode(fields(appearance)); err != nil {
+ return nil, err
+ }
+ comments := []string{
+ "Native race code: 0-3; current players and creatures use 1.",
+ "Native body build: 0-3; 1 is normal.",
+ "Breed: 1 Solitus, 2 Opifex, 3 Nanomage, 4 Atrox, 6 creature; native range 0-7.",
+ "Sex: 2 male, 3 female; creatures use 1. Native range 0-3.",
+ "Side: 0 neutral, 1 Clan, 2 Omni-Tek; native range 0-3.",
+ "Head selection: 0-31 on the wire; current Solitus meshes support 0-7.",
+ }
+ for index, comment := range comments {
+ node.Content[index*2].HeadComment = comment
+ }
+ return &node, nil
+}
diff --git a/server/armor_damage_test.go b/server/armor_damage_test.go
@@ -13,7 +13,7 @@ func newArmorDamageWorld(t *testing.T) (*server, *combatTestConn) {
t.Helper()
world, conn := newArmorWorld(t)
player := world.characters[1]
- player.stats.Strength, player.stats.Agility = 461, 511
+ player.stats.Abilities.Strength, player.stats.Abilities.Agility = 461, 511
if err := world.saveUser_locked(player); err != nil {
t.Fatal(err)
}
@@ -164,7 +164,7 @@ func TestArmorDamageHighQualityChestRequirements(t *testing.T) {
t.Run(scenario.name, func(t *testing.T) {
world, _ := newArmorWorld(t)
player := world.characters[1]
- player.stats.Strength, player.stats.Agility = scenario.strength, scenario.agility
+ player.stats.Abilities.Strength, player.stats.Abilities.Agility = scenario.strength, scenario.agility
if granted, err := world.grantItem_locked(player, 85685); err != nil || !granted {
t.Fatalf("grant: %v %v", granted, err)
}
diff --git a/server/armor_test.go b/server/armor_test.go
@@ -5,7 +5,6 @@ import (
"bytes"
"encoding/binary"
"net"
- "os"
"reflect"
"testing"
"time"
@@ -14,7 +13,7 @@ import (
func newArmorWorld(t *testing.T) (*server, *combatTestConn) {
t.Helper()
world, conn := newEquipmentWorld(t)
- world.characters[1].stats.Strength, world.characters[1].stats.Agility = 8, 8
+ world.characters[1].stats.Abilities.Strength, world.characters[1].stats.Abilities.Agility = 8, 8
for _, template := range []uint32{85686, 85638} {
if granted, err := world.grantItem_locked(world.characters[1], template); err != nil || !granted {
t.Fatalf("grant armor: %v %v", granted, err)
@@ -28,7 +27,7 @@ func TestArmorNativeMoveDelayAndRestart(t *testing.T) {
observer := &combatTestConn{}
world.characters[2] = &character{id: 2, playfield: 950, health: 100}
world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true}
- before, err := os.ReadFile("data/players/1/inventory.yaml")
+ before, err := readTestItemStore(world)
if err != nil {
t.Fatal(err)
}
@@ -44,7 +43,7 @@ func TestArmorNativeMoveDelayAndRestart(t *testing.T) {
}
world.handleInventory(world.clients[1], request)
world.advanceEquipment(finish.Add(-time.Nanosecond))
- unchanged, err := os.ReadFile("data/players/1/inventory.yaml")
+ unchanged, err := readTestItemStore(world)
if err != nil || !bytes.Equal(before, unchanged) || len(conn.packets) != 0 {
t.Fatalf("pending wear changed state: %v", err)
}
@@ -117,9 +116,9 @@ func TestArmorRejectsRequirementsAndInterruptedWear(t *testing.T) {
destination := uint32(21)
switch scenario {
case "strength":
- player.stats.Strength = 7
+ player.stats.Abilities.Strength = 7
case "agility":
- player.stats.Agility = 7
+ player.stats.Abilities.Agility = 7
case "wrong slot":
destination = 30
case "unsupported quality":
@@ -137,10 +136,9 @@ func TestArmorRejectsRequirementsAndInterruptedWear(t *testing.T) {
t.Fatal("valid armor move was rejected")
}
if scenario == "changed requirement" {
- player.stats.Agility = 7
+ player.stats.Abilities.Agility = 7
} else {
- os.Remove("data/players/1/inventory.yaml")
- os.Mkdir("data/players/1/inventory.yaml", 0700)
+ failDatabaseWrites(t, world)
}
world.advanceEquipment(world.clients[1].equipment.readyAt)
}
@@ -219,14 +217,14 @@ func TestArmorFullInventoryRetainsEquippedPiece(t *testing.T) {
t.Fatalf("fill inventory: %v %v", granted, err)
}
}
- before, err := os.ReadFile("data/players/1/inventory.yaml")
+ before, err := readTestItemStore(world)
if err != nil {
t.Fatal(err)
}
conn.packets = nil
err = world.handleInventory(world.clients[1], itemMovePacket(1, 21, 111)[20:])
- after, readErr := os.ReadFile("data/players/1/inventory.yaml")
+ after, readErr := readTestItemStore(world)
if err != nil || readErr != nil || !bytes.Equal(before, after) || world.clients[1].equipment != nil || len(conn.packets) != 1 ||
binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x47537a24 || binary.BigEndian.Uint32(conn.packets[0][45:49]) != 21 {
diff --git a/server/assets/map.js b/server/assets/map.js
@@ -23,7 +23,7 @@ class AOMap {
}
async start() {
- const response = await fetch("map-assets/manifest.json");
+ const response = await fetch("control/map-assets/manifest.json");
if (!response.ok) {
this.status.textContent = "Map data is missing. Run tools/data/extract_maps.py from the repository root.";
return;
@@ -227,7 +227,7 @@ class AOMap {
async poll() {
try {
if (!document.hidden) {
- const response = await fetch("map-players", {cache: "no-store"});
+ const response = await fetch("control/map-players", {cache: "no-store"});
if (!response.ok) throw new Error(`Player feed returned HTTP ${response.status}`);
this.players = (await response.json()).players;
if (!this.initialized) {
@@ -263,7 +263,7 @@ class AOMap {
if (tile.bitmap || tile.failed || tile.loading) continue;
tile.loading = true;
this.loadingTiles++;
- fetch(`map-assets/${path}`, {cache: "force-cache"}).then(response => {
+ fetch(`control/map-assets/${path}`, {cache: "force-cache"}).then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.blob();
}).then(blob => createImageBitmap(blob)).then(bitmap => {
@@ -320,7 +320,7 @@ class AOMap {
if (!point) continue;
const screen = this.toScreen(...point);
if (Math.hypot(x - screen[0], y - screen[1]) < 9 && player.id !== this.character) {
- window.location.href = new URL(`users/${player.id}`, document.baseURI);
+ window.location.href = new URL(`control/users/${player.id}`, document.baseURI);
return;
}
}
diff --git a/server/attack_rating_test.go b/server/attack_rating_test.go
@@ -22,7 +22,7 @@ func TestAttackRatingAxeDamageEndpoints(t *testing.T) {
t.Run(scenario.name, func(t *testing.T) {
world, _ := newEquipmentWorld(t)
player := world.characters[1]
- player.stats.OneHandEdged, player.stats.MartialArts = scenario.skill, 2000
+ player.stats.Melee.OneHandEdged, player.stats.Body.MartialArts = scenario.skill, 2000
world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:])
world.advanceEquipment(world.clients[1].equipment.readyAt)
@@ -39,7 +39,7 @@ func TestAttackRatingAxeDamageEndpoints(t *testing.T) {
func TestAttackRatingUnequipAndRestartSelectTheCurrentSkill(t *testing.T) {
world, _ := newEquipmentWorld(t)
player := world.characters[1]
- player.stats.OneHandEdged, player.stats.MartialArts = 398, 798
+ player.stats.Melee.OneHandEdged, player.stats.Body.MartialArts = 398, 798
if err := world.saveUser_locked(player); err != nil {
t.Fatal(err)
}
@@ -68,8 +68,8 @@ func TestAttackRatingFistEndpointsIncludeZeroSkill(t *testing.T) {
{0, 3, 5}, {400, 6, 10}, {800, 9, 15},
} {
attacker := &character{stats: defaultCharacterStats()}
- attacker.stats.Strength, attacker.stats.Agility, attacker.stats.Psychic = 0, 0, 0
- attacker.stats.MartialArts, attacker.stats.OneHandEdged = scenario.skill, 2000
+ attacker.stats.Abilities.Strength, attacker.stats.Abilities.Agility, attacker.stats.Abilities.Psychic = 0, 0, 0
+ attacker.stats.Body.MartialArts, attacker.stats.Melee.OneHandEdged = scenario.skill, 2000
target := &character{}
minimum := attacker.normalDamage(target, func(uint32) uint32 { return 0 })
@@ -86,7 +86,7 @@ func TestAttackRatingScaledMinimumPrecedesArmor(t *testing.T) {
attacker := &character{stats: defaultCharacterStats(), inventory: playerInventory{
Items: []ownedItem{{1, 51018, 209283, 1, 6, 1}},
}}
- attacker.stats.OneHandEdged = 398
+ attacker.stats.Melee.OneHandEdged = 398
var hits []uint32
for _, roll := range []uint32{0, 15, 30} {
@@ -106,7 +106,7 @@ func TestAttackRatingScaledMinimumPrecedesArmor(t *testing.T) {
func TestAttackRatingNativeDamageMatchesBothObservers(t *testing.T) {
world, owner := newEquipmentWorld(t)
player, target := world.characters[1], world.characters[1000000]
- player.stats.OneHandEdged = 398
+ player.stats.Melee.OneHandEdged = 398
world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:])
world.advanceEquipment(world.clients[1].equipment.readyAt)
observer := &combatTestConn{}
diff --git a/server/backpacks_test.go b/server/backpacks_test.go
@@ -4,7 +4,6 @@ import (
"bytes"
"encoding/binary"
"net"
- "os"
"reflect"
"slices"
"sync"
@@ -191,14 +190,14 @@ func TestBackpackRejectsInvalidOwnershipAndPlacement(t *testing.T) {
case "stale session":
world.clients[1] = &worldClient{id: 1}
}
- before, err := os.ReadFile("data/players/1/inventory.yaml")
+ before, err := readTestItemStore(world)
if err != nil {
t.Fatal(err)
}
packets := len(conn.packets)
err = world.handleInventory(client, request)
- after, readErr := os.ReadFile("data/players/1/inventory.yaml")
+ after, readErr := readTestItemStore(world)
if err != nil || readErr != nil || !bytes.Equal(before, after) || len(conn.packets) != packets {
t.Fatal("invalid placement changed persisted ownership or sent success", err, readErr)
@@ -252,12 +251,7 @@ func TestBackpackConcurrentTransferAndFailedSave(t *testing.T) {
workers.Wait()
close(errors)
before := world.characters[1].inventory
- 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)
- }
+ failDatabaseWrites(t, world)
err := world.handleInventory(client, backpackMoveRequest(107, 1<<16, 50000, 1, 111)[20:])
for err := range errors {
@@ -347,7 +341,7 @@ func TestBackpackDeleteRemovesContentsAtomically(t *testing.T) {
}
}
-func TestBackpackLoadRejectsOrphanedAndDuplicateContents(t *testing.T) {
+func TestBackpackSaveRejectsOrphanedAndDuplicateContents(t *testing.T) {
for _, scenario := range []string{"orphan", "duplicate", "nested", "outside capacity", "occupied"} {
t.Run(scenario, func(t *testing.T) {
world, _ := newBackpackWorld(t)
@@ -367,12 +361,8 @@ func TestBackpackLoadRejectsOrphanedAndDuplicateContents(t *testing.T) {
case "occupied":
inventory.Containers[3] = append(inventory.Containers[3], ownedItem{7, 51018, 121567, 1, 0, 1})
}
- if err := world.saveInventory_locked(world.characters[1], inventory); err != nil {
- t.Fatal(err)
- }
- restarted := &server{characters: make(map[uint32]*character)}
- err := restarted.loadUsers()
+ err := world.saveInventory_locked(world.characters[1], inventory)
if err == nil {
t.Fatal("invalid backpack ownership or placement was accepted")
diff --git a/server/belts_test.go b/server/belts_test.go
@@ -4,7 +4,6 @@ import (
"bytes"
"encoding/binary"
"fmt"
- "os"
"reflect"
"strings"
"testing"
@@ -14,7 +13,7 @@ import (
func newBeltWorld(t *testing.T) (*server, *combatTestConn) {
t.Helper()
world, conn := newArmorWorld(t)
- world.characters[1].stats.ComputerLiteracy = 4
+ world.characters[1].stats.TradeRepair.ComputerLiteracy = 4
if err := world.saveUser_locked(world.characters[1]); err != nil {
t.Fatal(err)
}
@@ -37,7 +36,7 @@ func TestBeltNCUEquipDelaysAndRestart(t *testing.T) {
source, destination uint32
delay time.Duration
}{{67, 7, 70 * time.Second}, {68, 9, 10 * time.Second}} {
- before, err := os.ReadFile("data/players/1/inventory.yaml")
+ before, err := readTestItemStore(world)
if err != nil {
t.Fatal(err)
}
@@ -54,7 +53,7 @@ func TestBeltNCUEquipDelaysAndRestart(t *testing.T) {
t.Fatalf("catalog equip delay: %v", finish.Sub(started))
}
world.advanceEquipment(finish.Add(-time.Nanosecond))
- unchanged, err := os.ReadFile("data/players/1/inventory.yaml")
+ unchanged, err := readTestItemStore(world)
if err != nil || !bytes.Equal(before, unchanged) || len(conn.packets) != packets {
t.Fatalf("pending equipment changed before its deadline: %v", err)
}
@@ -63,7 +62,7 @@ func TestBeltNCUEquipDelaysAndRestart(t *testing.T) {
restored := newTestInventoryServer(t).characters[1]
if player.inventory.equipmentBonus(45) != 1 || player.maximumNCU() != 10 || restored.maximumNCU() != 10 ||
- !reflect.DeepEqual(restored.inventory, player.inventory) || restored.stats.ComputerLiteracy != 4 {
+ !reflect.DeepEqual(restored.inventory.Items, player.inventory.Items) || restored.inventory.LastID != 6 || restored.stats.TradeRepair.ComputerLiteracy != 4 {
t.Fatalf("belt or NCU state did not persist: %+v", restored)
}
if len(conn.packets) != 4 || len(observer.packets) != 2 || len(equippedItemPackets(restored)) != 2 {
@@ -104,7 +103,7 @@ func TestBeltRemovalRequiresEmptyDeck(t *testing.T) {
t.Fatal("belt removal stranded installed memory")
}
// Removal does not require retaining the install skill.
- player.stats.ComputerLiteracy = 0
+ player.stats.TradeRepair.ComputerLiteracy = 0
for _, slot := range []uint32{9, 7} {
world.handleInventory(client, itemMovePacket(1, slot, 111)[20:])
if client.equipment == nil {
@@ -137,7 +136,7 @@ func TestBeltAndMemoryRequireComputerLiteracySix(t *testing.T) {
world.advanceEquipment(client.equipment.readyAt)
source = 68
}
- player.stats.ComputerLiteracy = skill
+ player.stats.TradeRepair.ComputerLiteracy = skill
request := inventoryMovePacket(1, source-16, slot)[20:]
decodeInventory1491(request)
@@ -203,10 +202,9 @@ func TestNCUPendingMoveRechecksBeltAndRequirement(t *testing.T) {
case "belt removed":
player.inventory.Items[3].Slot = 67
case "skill lost":
- player.stats.ComputerLiteracy = 3
+ player.stats.TradeRepair.ComputerLiteracy = 3
case "failed save":
- os.Remove("data/players/1/inventory.yaml")
- os.Mkdir("data/players/1/inventory.yaml", 0700)
+ failDatabaseWrites(t, world)
}
world.advanceEquipment(finish)
@@ -218,7 +216,7 @@ func TestNCUPendingMoveRechecksBeltAndRequirement(t *testing.T) {
}
}
-func TestNCULoadRejectsStrandedEquipment(t *testing.T) {
+func TestNCUSaveRejectsStrandedEquipment(t *testing.T) {
for _, scenario := range []string{"without belt", "disabled slot"} {
t.Run(scenario, func(t *testing.T) {
world, _ := newBeltWorld(t)
@@ -228,15 +226,11 @@ func TestNCULoadRejectsStrandedEquipment(t *testing.T) {
player.inventory.Items[3].Slot = 7
player.inventory.Items[4].Slot = 10
}
- if err := world.saveInventory_locked(player, player.inventory); err != nil {
- t.Fatal(err)
- }
- restored := &server{characters: make(map[uint32]*character)}
- err := restored.loadUsers()
+ err := world.saveInventory_locked(player, player.inventory)
if err == nil {
- t.Fatal("loaded NCU memory without its enabled deck position")
+ t.Fatal("saved NCU memory without its enabled deck position")
}
})
}
@@ -306,24 +300,3 @@ func TestNCURemovalRejectsWrongPageAndFullInventory(t *testing.T) {
t.Fatal("rejected memory removal lost the item or its capacity")
}
}
-
-func TestBeltLoadsMissingComputerLiteracy(t *testing.T) {
- newBeltWorld(t)
- contents, err := os.ReadFile("data/players/1/player.yaml")
- if err != nil {
- t.Fatal(err)
- }
- profile := strings.ReplaceAll(string(contents), " computer_literacy: 4\n", "")
- if strings.Contains(profile, "computer_literacy") {
- t.Fatal("fixture still contains Computer Literacy")
- }
- if err := os.WriteFile("data/players/1/player.yaml", []byte(profile), 0600); err != nil {
- t.Fatal(err)
- }
-
- restored := newTestInventoryServer(t).characters[1]
-
- if restored.stats.ComputerLiteracy != 5 || restored.stats.Strength != 8 || restored.maximumNCU() != 8 {
- t.Fatalf("missing trained skill did not retain the native default: %+v", restored.stats)
- }
-}
diff --git a/server/character_editor.go b/server/character_editor.go
@@ -0,0 +1,22 @@
+package main
+
+// YAML is only a presentation format; each section maps to native SQL fields.
+type characterEditor struct {
+ playerProfile `yaml:",inline"`
+ playerPosition `yaml:",inline"`
+ Vitals playerVitals `yaml:"vitals"`
+ Inventory inventoryReferences `yaml:"inventory"`
+}
+
+func (character *character) editor() characterEditor {
+ record := character.record()
+ return characterEditor{record.Profile, record.Position.editor(), record.Vitals, character.inventory.references()}
+}
+
+func (data characterEditor) character() *character {
+ position := storedPosition{Playfield: data.Playfield, Position: data.Position, Rotation: data.Rotation}
+ if data.ReturnDoor != nil {
+ position.ReturnPlayfield, position.ReturnDoor = data.ReturnDoor.Playfield, data.ReturnDoor.Door
+ }
+ return (characterRecord{data.playerProfile, position, data.Vitals}).character()
+}
diff --git a/server/chat_history.go b/server/chat_history.go
@@ -1,11 +1,9 @@
package main
import (
- "encoding/json"
"fmt"
- "io"
"log"
- "os"
+ "slices"
"time"
)
@@ -33,108 +31,62 @@ func (server *server) logChat_locked(entry chatHistoryEntry, recipients []*chatC
}
entry.Message = string(message)
entry.Time = time.Now().UTC()
- data, err := json.Marshal(entry)
- if err != nil {
- log.Printf("Chat history: %v", err)
- return
- }
- data = append(data, '\n')
-
- // Keep the same record in the sender's and each recipient's private history.
+ // The sender's and recipients' copies commit together.
owners := []uint32{entry.SenderID}
for _, recipient := range recipients {
- if recipient.id != entry.SenderID {
+ if !slices.Contains(owners, recipient.id) {
owners = append(owners, recipient.id)
}
}
- for _, id := range owners {
- if err := server.appendChatHistory_locked(id, data); err != nil {
- log.Printf("Chat history for character %d: %v", id, err)
- }
+ if err := server.appendChatHistory_locked(owners, entry); err != nil {
+ log.Printf("Chat history: %v", err)
}
}
-func (server *server) appendChatHistory_locked(id uint32, data []byte) error {
- directory := fmt.Sprintf("data/players/%d", id)
- if err := os.MkdirAll(directory, 0700); err != nil {
+func (server *server) appendChatHistory_locked(owners []uint32, entry chatHistoryEntry) error {
+ db, err := server.database()
+ if err != nil {
return err
}
-
- // Rotate whole records at 10 MiB, keeping the five most recent archives.
- path := directory + "/chat.ndjson"
- info, err := os.Stat(path)
- if err != nil && !os.IsNotExist(err) {
+ tx, err := db.Begin()
+ if err != nil {
return err
}
- if info != nil && info.Size()+int64(len(data)) > 10*1024*1024 {
- if err := os.Remove(path + ".5"); err != nil && !os.IsNotExist(err) {
+ defer tx.Rollback()
+ for _, id := range owners {
+ if _, err := tx.Exec("INSERT INTO chat_history (owner, time, channel, sender_id, sender, recipient_id, recipient, playfield, message) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ id, entry.Time.UTC().Format(time.RFC3339Nano), entry.Channel, entry.SenderID, entry.Sender, entry.RecipientID, entry.Recipient, entry.Playfield, entry.Message); err != nil {
return err
}
- for index := 4; index >= 0; index-- {
- source := path
- if index != 0 {
- source = fmt.Sprintf("%s.%d", path, index)
- }
- if err := os.Rename(source, fmt.Sprintf("%s.%d", path, index+1)); err != nil && !os.IsNotExist(err) {
- return err
- }
- }
- }
- file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
- if err != nil {
- return err
}
- if _, err := file.Write(data); err != nil {
- file.Close()
- return err
- }
- if err := file.Sync(); err != nil {
- file.Close()
- return err
- }
- return file.Close()
+ return tx.Commit()
}
func (server *server) chatHistory_locked(id uint32) ([]chatHistoryEntry, error) {
- // Read only this player's files, starting with the newest, for 500 entries.
+ db, err := server.database()
+ if err != nil {
+ return nil, err
+ }
+ rows, err := db.Query("SELECT time, channel, sender_id, sender, recipient_id, recipient, playfield, message FROM chat_history WHERE owner = ? ORDER BY id DESC LIMIT 500", id)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
var history []chatHistoryEntry
- for archive := 0; archive <= 5 && len(history) < 500; archive++ {
- path := fmt.Sprintf("data/players/%d/chat.ndjson", id)
- if archive != 0 {
- path = fmt.Sprintf("%s.%d", path, archive)
- }
- file, err := os.Open(path)
- if os.IsNotExist(err) {
- continue
+ for rows.Next() {
+ var entry chatHistoryEntry
+ var timestamp string
+ if err := rows.Scan(×tamp, &entry.Channel, &entry.SenderID, &entry.Sender, &entry.RecipientID, &entry.Recipient, &entry.Playfield, &entry.Message); err != nil {
+ return nil, err
}
+ entry.Time, err = time.Parse(time.RFC3339Nano, timestamp)
if err != nil {
return nil, err
}
-
- // Retain the file's newest entries in a bounded ring, in original order.
- entries := make([]chatHistoryEntry, 0, 500-len(history))
- next := 0
- decoder := json.NewDecoder(file)
- for {
- var entry chatHistoryEntry
- if err := decoder.Decode(&entry); err == io.EOF {
- break
- } else if err != nil {
- file.Close()
- return nil, fmt.Errorf("%s: %w", path, err)
- }
- if len(entries) < cap(entries) {
- entries = append(entries, entry)
- } else {
- entries[next] = entry
- next = (next + 1) % len(entries)
- }
- }
- file.Close()
- ordered := append(entries[next:], entries[:next]...)
- history = append(ordered, history...)
+ history = append(history, entry)
}
- return history, nil
+ slices.Reverse(history)
+ return history, rows.Err()
}
func (entry chatHistoryEntry) packet() []byte {
diff --git a/server/chat_history_test.go b/server/chat_history_test.go
@@ -48,11 +48,11 @@ func TestChatHistoryRecordsChannelsAndLegacyText(t *testing.T) {
server.sendVicinity(2, kind, message)
}
- data, err := os.ReadFile("data/players/1/chat.ndjson")
+ data, err := readTestChatHistory(server, 1)
if err != nil {
t.Fatal(err)
}
- bobData, err := os.ReadFile("data/players/2/chat.ndjson")
+ bobData, err := readTestChatHistory(server, 2)
if err != nil {
t.Fatal(err)
}
@@ -78,51 +78,21 @@ func TestChatHistoryRecordsChannelsAndLegacyText(t *testing.T) {
}
}
-func TestChatHistoryRotatesAndDeletesOldestArchive(t *testing.T) {
+func TestChatHistoryPersistsAcrossDatabaseConnections(t *testing.T) {
world := chatTestServer(t)
world.sendVicinity(1, 0, "first")
- path := "data/players/1/chat.ndjson"
- file, err := os.OpenFile(path, os.O_WRONLY, 0600)
- if err != nil {
- t.Fatal(err)
- }
- if err := file.Truncate(10 * 1024 * 1024); err != nil {
- file.Close()
- t.Fatal(err)
- }
- file.Close()
- for index := 1; index <= 5; index++ {
- if err := os.WriteFile(fmt.Sprintf("%s.%d", path, index), []byte(fmt.Sprint(index)), 0600); err != nil {
- t.Fatal(err)
- }
- }
-
- world.sendVicinity(1, 0, "second")
- // A new server instance appends to the same transcript after a restart.
restarted := &server{characters: world.characters, clients: world.clients}
- restarted.sendVicinity(1, 0, "third")
- data, err := os.ReadFile(path)
- if err != nil || bytes.Count(data, []byte{'\n'}) != 2 || !bytes.Contains(data, []byte(`"message":"second"`)) || !bytes.Contains(data, []byte(`"message":"third"`)) {
- t.Fatalf("active history: %q %v", data, err)
- }
- info, err := os.Stat(path + ".1")
- if err != nil || info.Size() != 10*1024*1024 {
- t.Fatalf("first archive: %v %v", info, err)
- }
- for index := 2; index <= 5; index++ {
- data, err := os.ReadFile(fmt.Sprintf("%s.%d", path, index))
- if err != nil || string(data) != fmt.Sprint(index-1) {
- t.Fatalf("archive %d: %q %v", index, data, err)
- }
- }
- files, err := os.ReadDir("data/players/1")
- if err != nil || len(files) != 6 {
- t.Fatalf("history files: %v %v", files, err)
+ restarted.sendVicinity(1, 0, "second")
+ defer restarted.db.Close()
+ history, err := restarted.chatHistory_locked(1)
+ info, statErr := os.Stat("data/world.sqlite")
+
+ if err != nil || len(history) != 2 || history[0].Message != "first" || history[1].Message != "second" {
+ t.Fatalf("history across connections: %+v %v", history, err)
}
- info, err = os.Stat(path)
- if err != nil || runtime.GOOS != "windows" && info.Mode().Perm()&0077 != 0 {
- t.Fatalf("history permissions: %v %v", info, err)
+ if statErr != nil || runtime.GOOS != "windows" && info.Mode().Perm()&0077 != 0 {
+ t.Fatalf("database permissions: %v %v", info, statErr)
}
}
@@ -135,7 +105,7 @@ func TestChatHistoryExcludesRejectedMessages(t *testing.T) {
server.sendVicinity(1, 3, "invalid kind")
server.sendVicinity(3, 0, "unknown sender")
- if _, err := os.Stat("data/players"); !os.IsNotExist(err) {
+ if _, err := os.Stat("data/world.sqlite"); !os.IsNotExist(err) {
t.Fatalf("rejected messages created history: %v", err)
}
}
@@ -153,7 +123,7 @@ func TestChatHistoryKeepsConcurrentMessagesIntact(t *testing.T) {
}
writers.Wait()
- data, err := os.ReadFile("data/players/1/chat.ndjson")
+ data, err := readTestChatHistory(server, 1)
if err != nil {
t.Fatal(err)
}
@@ -172,9 +142,7 @@ func TestChatHistoryKeepsConcurrentMessagesIntact(t *testing.T) {
func TestChatHistoryFailureDoesNotPreventDelivery(t *testing.T) {
server := chatTestServer(t)
alice := loginChatTest(t, server, 1)
- if err := os.WriteFile("data", []byte("blocks history directory"), 0600); err != nil {
- t.Fatal(err)
- }
+ failDatabaseWrites(t, server)
done := make(chan struct{})
go func() {
@@ -275,47 +243,27 @@ func TestChatHistoryRestoresTellsOnlyForTheirParticipants(t *testing.T) {
if err != nil || kind != 100 {
t.Fatalf("private history leaked to Carol: %d %v", kind, err)
}
- aliceData, err := os.ReadFile("data/players/1/chat.ndjson")
+ aliceData, err := readTestChatHistory(world, 1)
if err != nil {
t.Fatal(err)
}
- bobData, err := os.ReadFile("data/players/2/chat.ndjson")
+ bobData, err := readTestChatHistory(world, 2)
if err != nil || !bytes.Equal(aliceData, bobData) {
t.Fatalf("tell history was not duplicated for both participants: %v", err)
}
}
-func TestChatHistoryRestoresNewestEntriesAcrossOwnArchives(t *testing.T) {
+func TestChatHistoryRestoresNewestEntriesOnlyForItsOwner(t *testing.T) {
world := chatTestServer(t)
- if err := os.MkdirAll("data/players/1", 0700); err != nil {
- t.Fatal(err)
- }
entry := chatHistoryEntry{Time: time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC), Channel: "say", SenderID: 1, Sender: "Alice"}
- for _, archive := range []struct {
- path string
- start, end int
- }{
- {"data/players/1/chat.ndjson.1", 0, 505},
- {"data/players/1/chat.ndjson", 505, 508},
- } {
- var data []byte
- for index := archive.start; index < archive.end; index++ {
- entry.Message = fmt.Sprintf("message %d", index)
- line, err := json.Marshal(entry)
- if err != nil {
- t.Fatal(err)
- }
- data = append(data, append(line, '\n')...)
- }
- if err := os.WriteFile(archive.path, data, 0600); err != nil {
+ for index := 0; index < 508; index++ {
+ entry.Message = fmt.Sprintf("message %d", index)
+ if err := world.appendChatHistory_locked([]uint32{1}, entry); err != nil {
t.Fatal(err)
}
}
- // Another player's malformed file must never be opened for Alice's history.
- if err := os.MkdirAll("data/players/2", 0700); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile("data/players/2/chat.ndjson", []byte("unrelated invalid JSON"), 0600); err != nil {
+ entry.Message = "Bob's private history"
+ if err := world.appendChatHistory_locked([]uint32{2}, entry); err != nil {
t.Fatal(err)
}
diff --git a/server/chat_integration_test.go b/server/chat_integration_test.go
@@ -9,7 +9,6 @@ import (
"net"
"net/http"
"net/http/httptest"
- "os"
"strings"
"testing"
"time"
@@ -305,7 +304,7 @@ func TestBrowserChatHistoryFollowsPlayerAcrossSessionsAndTokenChanges(t *testing
if len(history) != 2 || history[0] != history[1] || !strings.Contains(history[0], "[say] Bob: remember across browsers") {
t.Fatalf("history did not follow the player: %q", history)
}
- data, err := os.ReadFile("data/players/1/chat.ndjson")
+ data, err := readTestChatHistory(world, 1)
if err != nil || bytes.Count(data, []byte{'\n'}) != 1 {
t.Fatalf("restoring history recorded duplicate messages: %q %v", data, err)
}
diff --git a/server/chat_test.go b/server/chat_test.go
@@ -13,7 +13,7 @@ import (
func chatTestServer(t *testing.T) *server {
t.Helper()
t.Chdir(t.TempDir())
- return &server{
+ world := &server{
characters: map[uint32]*character{
1: {id: 1, name: "Alice", playfield: 710},
2: {id: 2, name: "Bob", playfield: 710},
@@ -21,6 +21,12 @@ func chatTestServer(t *testing.T) *server {
clients: map[uint32]*worldClient{1: {id: 1, ready: true}, 2: {id: 2, ready: true}},
chats: make(map[uint32]*chatClient),
}
+ t.Cleanup(func() {
+ if world.db != nil {
+ world.db.Close()
+ }
+ })
+ return world
}
func startChatTest(t *testing.T, server *server, boundID uint32) (net.Conn, <-chan error) {
diff --git a/server/combat.go b/server/combat.go
@@ -94,10 +94,10 @@ func (character *character) attackDelays() (time.Duration, time.Duration) {
stats := character.baseStats()
weapon := character.meleeWeapon()
if weapon != nil {
- initiative := stats.effectiveSkill(stats.MeleeInitiative, [6]uint32{0, 10, 0, 10, 60, 20})
+ initiative := stats.effectiveSkill(stats.Speed.MeleeInitiative, [6]uint32{0, 10, 0, 10, 60, 20})
return weaponDelays(weapon, int32(initiative), character.aggDef)
}
- initiative := stats.effectiveSkill(stats.PhysicalInitiative, [6]uint32{0, 10, 0, 10, 60, 20})
+ initiative := stats.effectiveSkill(stats.Speed.PhysicalInitiative, [6]uint32{0, 10, 0, 10, 60, 20})
return weaponDelays(nil, int32(initiative), character.aggDef)
}
@@ -121,7 +121,7 @@ func (character *character) maximumHealth() uint32 {
// kkr.dll FUN_10075910; breed 1000203 and profession/title 1000200 coefficients.
stats := [8][3]uint32{{2, 2, 2}, {10, 6, 3}, {15, 5, 3}, {10, 5, 2}, {25, 6, 4}, {15, 8, 6}, {2, 2, 2}, {2, 2, 2}}[character.appearance>>4&7]
base := character.baseStats()
- bodyDevelopment := base.effectiveSkill(base.BodyDevelopment, [6]uint32{0, 0, 100, 0, 0, 0})
+ bodyDevelopment := base.effectiveSkill(base.Body.BodyDevelopment, [6]uint32{0, 0, 100, 0, 0, 0})
return stats[0] + uint32(character.level)*(stats[1]+gamedata.ProfessionTitles[max(1, character.profession)].Health[character.titleLevel()-1]) + bodyDevelopment*stats[2]
}
@@ -129,7 +129,7 @@ func (character *character) maximumNano() uint32 {
// kkr.dll FUN_10075910 uses real profession and stored title, as for health.
stats := [8][3]uint32{{2, 2, 2}, {10, 4, 3}, {10, 3, 3}, {15, 5, 4}, {8, 2, 2}, {50, 2, 1}, {2, 2, 2}, {2, 2, 2}}[character.appearance>>4&7]
base := character.baseStats()
- nanoPool := base.effectiveSkill(base.NanoPool, [6]uint32{0, 0, 10, 10, 10, 70})
+ nanoPool := base.effectiveSkill(base.Body.NanoPool, [6]uint32{0, 0, 10, 10, 10, 70})
return stats[0] + uint32(character.level)*(stats[1]+gamedata.ProfessionTitles[max(1, character.profession)].Nano[character.titleLevel()-1]) + nanoPool*stats[2]
}
@@ -151,14 +151,14 @@ func (attacker *character) normalDamage(target *character, roll func(uint32) uin
// NPC attack skills remain unknown. Fractional endpoint truncation is provisional.
if !attacker.npc {
stats := attacker.baseStats()
- rating := stats.effectiveSkill(stats.MartialArts, [6]uint32{20, 50, 0, 0, 0, 30})
+ rating := stats.effectiveSkill(stats.Body.MartialArts, [6]uint32{20, 50, 0, 0, 0, 30})
if weapon != nil {
- rating = stats.effectiveSkill(stats.OneHandEdged, [6]uint32{30, 40, 30, 0, 0, 0})
+ rating = stats.effectiveSkill(stats.Melee.OneHandEdged, [6]uint32{30, 40, 30, 0, 0, 0})
// The axe's three action-8 requirements are 4. Native OE checks them all.
// FUN_10090f10/100ab8a0: tier = trunc(5*(1-skill/requirement)).
- brawling := stats.effectiveSkill(stats.Brawling, [6]uint32{60, 0, 40, 0, 0, 0})
- fastAttack := stats.effectiveSkill(stats.FastAttack, [6]uint32{0, 60, 0, 0, 40, 0})
+ brawling := stats.effectiveSkill(stats.Body.Brawling, [6]uint32{60, 0, 40, 0, 0, 0})
+ fastAttack := stats.effectiveSkill(stats.Melee.FastAttack, [6]uint32{0, 60, 0, 0, 40, 0})
skill := min(rating, brawling, fastAttack)
if skill < 4 {
tier := min(4, (4-skill)*5/4)
diff --git a/server/control.go b/server/control.go
@@ -29,17 +29,17 @@ func (server *server) controlPage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, "<!doctype html><html><head><base href='%s'><title>Server controls</title></head><body><h1>Server controls</h1><p><a href='control'>Refresh</a></p>", html.EscapeString(server.baseURL))
fmt.Fprintf(w, "<p>Game time: %02d:%02d. A day has 27 hours; time advances at 15x.</p>", seconds/3600, seconds/60%60)
- fmt.Fprintf(w, "<form method='post' action='time'><label>Hour <input type='number' name='hour' min='0' max='26' value='%d' required></label> <label>Minute <input type='number' name='minute' min='0' max='59' value='%d' required></label> <button>Set time</button></form>", seconds/3600, seconds/60%60)
+ fmt.Fprintf(w, "<form method='post' action='control/time'><label>Hour <input type='number' name='hour' min='0' max='26' value='%d' required></label> <label>Minute <input type='number' name='minute' min='0' max='59' value='%d' required></label> <button>Set time</button></form>", seconds/3600, seconds/60%60)
controlMap(w, 0)
- fmt.Fprint(w, "<h2>Users</h2><table><tr><th>ID</th><th>Name</th><th>Status</th><th>Zone</th><th>Map</th></tr>")
+ fmt.Fprint(w, "<p><a href='control/items'>Items</a></p><h2>Users</h2><table><tr><th>ID</th><th>Name</th><th>Status</th><th>Zone</th><th>Map</th></tr>")
for _, player := range players {
status := "Offline"
if connected[player.ID] {
status = "Connected"
}
- fmt.Fprintf(w, "<tr data-map-player='%d'><td>%d</td><td><a href='users/%d'>%s</a></td><td>%s</td><td>%s (%d)</td><td data-map-placement></td></tr>", player.ID, player.ID, player.ID, html.EscapeString(player.Name), status, html.EscapeString(gamedata.Playfields[player.Playfield].Name), player.Playfield)
+ fmt.Fprintf(w, "<tr data-map-player='%d'><td>%d</td><td><a href='control/users/%d'>%s</a></td><td>%s</td><td>%s (%d)</td><td data-map-placement></td></tr>", player.ID, player.ID, player.ID, html.EscapeString(player.Name), status, html.EscapeString(gamedata.Playfields[player.Playfield].Name), player.Playfield)
}
- fmt.Fprint(w, "</table><h2>Create user</h2><form method='post' action='users'><label>Name <input name='name' required maxlength='254'></label> <button>Create user</button></form></body></html>")
+ fmt.Fprint(w, "</table><h2>Create user</h2><form method='post' action='control/users'><label>Name <input name='name' required maxlength='254'></label> <button>Create user</button></form></body></html>")
}
func (server *server) userPage(w http.ResponseWriter, r *http.Request) {
@@ -57,19 +57,23 @@ func (server *server) userPage(w http.ResponseWriter, r *http.Request) {
}
data := player.userData()
connected := server.clients[data.ID] != nil && server.clients[data.ID].ready
- server.mutex.Unlock()
- contents, err := yaml.Marshal(data)
+
+ // One document exposes the complete editable character and all empty slots.
+ contents, err := yaml.Marshal(player.editor())
if err != nil {
+ server.mutex.Unlock()
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
+ server.mutex.Unlock()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, "<!doctype html><html><head><base href='%s'><title>User</title></head><body><p><a href='control'>All users</a></p>", html.EscapeString(server.baseURL))
fmt.Fprintf(w, "<h1>%s</h1><p>User %d. Connected: %t.</p>", html.EscapeString(data.Name), data.ID, connected)
controlMap(w, data.ID)
- fmt.Fprintf(w, "<h2>Character data</h2><p>ID is fixed. Position is XYZ; rotation is XYZW. Saving reconnects an online character to apply the data.</p><form method='post' action='users/%d'><textarea name='data' rows='20' cols='80' required>%s</textarea><p><button>Save character</button></p></form>", data.ID, html.EscapeString(string(contents)))
- fmt.Fprint(w, "<p>The stats section contains base abilities and trained skills. Displayed skills also include bonuses from abilities.</p>")
+ fmt.Fprint(w, "<h2>Character data</h2><p>This YAML document edits the character in the world database. Slots contain item IDs or null. Saving reconnects an online character. ID is fixed; position is XYZ and rotation is XYZW.</p>")
+ fmt.Fprintf(w, "<form method='post' action='control/users/%d'><p><label>Character:<br><textarea name='data' rows='40' cols='100' required>%s</textarea></label></p><button>Save character</button></form>", data.ID, html.EscapeString(string(contents)))
+ fmt.Fprint(w, "<p>Inventory uses inventory_slot_1 through inventory_slot_30; equipment uses named weapons, clothes and implants positions. Slots contain item IDs or null. Clearing a slot unassigns its item. <a href='control/items'>Browse and create item instances</a>. Backpack slots are edited on the backpack's item page. improvement_points is the available IP balance; native IP spending is not implemented.</p>")
fmt.Fprint(w, "</body></html>")
}
@@ -95,7 +99,7 @@ func (server *server) createUser(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
- http.Redirect(w, r, fmt.Sprintf("%susers/%d", server.baseURL, player.id), http.StatusSeeOther)
+ http.Redirect(w, r, fmt.Sprintf("%scontrol/users/%d", server.baseURL, player.id), http.StatusSeeOther)
}
func (server *server) editUser(w http.ResponseWriter, r *http.Request) {
@@ -104,32 +108,69 @@ func (server *server) editUser(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Invalid user", http.StatusBadRequest)
return
}
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
server.mutex.Lock()
- player := server.characters[uint32(id)]
- exists := player != nil && !player.npc
- server.mutex.Unlock()
- if !exists {
+ character := server.characters[uint32(id)]
+ if character == nil || character.npc {
+ server.mutex.Unlock()
http.NotFound(w, r)
return
}
- var data userData
- if err := decodeUsers(strings.NewReader(r.FormValue("data")), &data); err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
+
+ // Validate the document and ownership graph before starting the SQL transaction.
+ data := character.editor()
+ err = decodeUsers(strings.NewReader(r.FormValue("data")), &data)
+ updated := data.character()
+ updated.nextPositionSave = character.nextPositionSave
+ if err == nil && data.ID != character.id {
+ err = fmt.Errorf("user ID cannot change")
}
- if data.ID != uint32(id) {
- http.Error(w, "User ID cannot change", http.StatusBadRequest)
- return
+ if err == nil {
+ err = data.Appearance.validate()
+ }
+ if err == nil {
+ err = updated.userData().validate()
+ }
+ if err == nil && data.ResurrectionTerminal != 0 && data.ResurrectionTerminal != 0xc00202c1 {
+ err = fmt.Errorf("unknown resurrection terminal")
+ }
+ if err == nil {
+ updated.inventory, err = data.Inventory.inventory(server.items, server.nextItem)
+ }
+ var store itemStore
+ if err == nil {
+ store, err = server.itemStore_locked(character, updated.inventory)
+ }
+ if err == nil {
+ // Clearing a slot keeps its item available for reassignment.
+ for _, item := range character.inventory.allItems() {
+ if _, remains := store.Items[item.ID]; !remains {
+ store.Items[item.ID] = server.items[item.ID]
+ }
+ }
+ err = store.validate()
}
- if err := data.validate(); err != nil {
+ if err != nil {
+ server.mutex.Unlock()
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
- if err := server.updateUser(data); err != nil {
+ server.prepareUser_locked(character, updated)
+ store.edited = updated
+ err = server.writeItemStore_locked(store)
+ if err != nil {
+ server.mutex.Unlock()
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
- http.Redirect(w, r, fmt.Sprintf("%susers/%d", server.baseURL, data.ID), http.StatusSeeOther)
+ updated.savedProfile, updated.savedPosition, updated.savedVitals = updated.profile(), data.playerPosition, updated.vitals()
+ server.nextItem = max(server.nextItem, updated.inventory.LastID)
+ if err := server.applyUser_locked(character, updated); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ http.Redirect(w, r, fmt.Sprintf("%scontrol/users/%d", server.baseURL, id), http.StatusSeeOther)
}
func (server *server) setGameTime(w http.ResponseWriter, r *http.Request) {
@@ -142,8 +183,18 @@ func (server *server) setGameTime(w http.ResponseWriter, r *http.Request) {
// Update the clock and notify players across all playfields.
server.mutex.Lock()
+ db, err := server.database()
+ started := time.Now()
+ if err == nil {
+ _, err = db.Exec("UPDATE world SET game_seconds=?, clock_started=? WHERE id=1", hour*3600+minute*60, started.UTC().Format(time.RFC3339Nano))
+ }
+ if err != nil {
+ server.mutex.Unlock()
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
server.gameSeconds = float64(hour*3600 + minute*60)
- server.clockStarted = time.Now()
+ server.clockStarted = started
var clients []*worldClient
for _, client := range server.clients {
if client.ready {
@@ -215,7 +266,7 @@ func (server *server) teleportPlayer(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
- http.Redirect(w, r, fmt.Sprintf("%susers/%d", server.baseURL, id), http.StatusSeeOther)
+ http.Redirect(w, r, fmt.Sprintf("%scontrol/users/%d", server.baseURL, id), http.StatusSeeOther)
}
func (server *server) updateUser(destination userData) error {
@@ -232,7 +283,6 @@ func (server *server) updateUser_locked(destination userData) error {
server.mutex.Unlock()
return fmt.Errorf("unknown user")
}
- previousPlayfield := character.playfield
updated := destination.character()
updated.inventory = character.inventory
updated.browserTokenHash = character.browserTokenHash
@@ -242,17 +292,34 @@ func (server *server) updateUser_locked(destination userData) error {
updated.savedProfile = character.savedProfile
updated.savedPosition = character.savedPosition
updated.nextPositionSave = character.nextPositionSave
- updated.health = min(character.health, updated.maximumHealth())
updated.aggDef = character.aggDef
updated.rechargeUntil = character.rechargeUntil
updated.nanoRechargeUntil = character.nanoRechargeUntil
+ updated.health, updated.nano = character.health, character.nano
+ server.prepareUser_locked(character, updated)
if err := server.saveUser_locked(updated); err != nil {
server.mutex.Unlock()
return err
}
+ return server.applyUser_locked(character, updated)
+}
+
+func (server *server) prepareUser_locked(character, updated *character) {
+ // Reconnection cancels a pending cast; preserve its refund unless nano was edited.
+ if client := server.clients[character.id]; client != nil && client.nanoCast != nil && updated.nano == character.nano {
+ updated.nano = min(character.maximumNano(), character.nano+winterBiteCost())
+ }
+ updated.health = min(updated.health, updated.maximumHealth())
+ updated.nano = min(updated.nano, updated.maximumNano())
+}
+
+func (server *server) applyUser_locked(character, updated *character) error {
+ // Hold updateMutex and mutex; release mutex before sending reconnect packets.
+ previousPlayfield := character.playfield
updates := make(map[*worldClient][][]byte)
server.cancelCombat_locked(character.id, updates)
- updated.nano = min(character.nano, updated.maximumNano())
+ updated.fighting = 0
+ updated.nextAttack = time.Time{}
*character = *updated
client := server.clients[character.id]
if client == nil || !client.ready {
@@ -264,7 +331,7 @@ func (server *server) updateUser_locked(destination userData) error {
delete(server.clients, character.id)
server.mutex.Unlock()
server.sendCombatUpdates(updates)
- return server.teleportUser_locked(client, destination, previousPlayfield)
+ return server.teleportUser_locked(client, updated.userData(), previousPlayfield)
}
func (server *server) teleportUser_locked(client *worldClient, destination userData, previousPlayfield uint32) error {
diff --git a/server/control_data_test.go b/server/control_data_test.go
@@ -0,0 +1,386 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "html"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+
+ "go.yaml.in/yaml/v3"
+)
+
+func TestControlItemCatalogPaginatesAndFilters(t *testing.T) {
+ world := &server{baseURL: "/share/test/"}
+ handler := world.httpHandler()
+
+ first, second, filtered := httptest.NewRecorder(), httptest.NewRecorder(), httptest.NewRecorder()
+ handler.ServeHTTP(first, httptest.NewRequest("GET", "/share/test/control/items/catalog?catalog=armor", nil))
+ handler.ServeHTTP(second, httptest.NewRequest("GET", "/share/test/control/items/catalog?catalog=armor&page=2", nil))
+ handler.ServeHTTP(filtered, httptest.NewRequest("GET", "/share/test/control/items/catalog?catalog=121567", nil))
+
+ for _, response := range []*httptest.ResponseRecorder{first, second} {
+ if response.Code != http.StatusOK || strings.Count(response.Body.String(), "<button name='template' value='") != 500 {
+ t.Fatalf("catalog page: HTTP %d, expected 500 templates", response.Code)
+ }
+ }
+ if !strings.Contains(first.Body.String(), "href='control/items/catalog?catalog=armor&page=2'") ||
+ !strings.Contains(second.Body.String(), "href='control/items/catalog?catalog=armor&page=1'") ||
+ !strings.Contains(first.Body.String(), "<base href='/share/test/'>") {
+ t.Fatal("pagination lost the filter or public mounting path")
+ }
+ ids := regexp.MustCompile(`<button name='template' value='([0-9]+)'>`).FindAllStringSubmatch(first.Body.String(), -1)
+ for _, id := range ids {
+ if strings.Contains(second.Body.String(), "<button name='template' value='"+id[1]+"'>") {
+ t.Fatal("pages overlap")
+ }
+ }
+ if filtered.Code != http.StatusOK || strings.Count(filtered.Body.String(), "<button name='template' value='") != 1 ||
+ !strings.Contains(filtered.Body.String(), "<td>Solar-Powered Pistol</td>") || !strings.Contains(filtered.Body.String(), "value='121567'>Create</button>") {
+ t.Fatal("catalog filter did not select the exact template")
+ }
+}
+
+func TestControlInstancesPaginateFilteredResults(t *testing.T) {
+ world := &server{baseURL: "/", items: make(map[uint32]itemRecord)}
+ for id := uint32(1); id <= 1001; id++ {
+ world.items[id] = itemRecord{Type: 51018, Template: 121567, Quality: 1, Count: 1}
+ }
+ handler := world.httpHandler()
+
+ first, second, last, empty := httptest.NewRecorder(), httptest.NewRecorder(), httptest.NewRecorder(), httptest.NewRecorder()
+ handler.ServeHTTP(first, httptest.NewRequest("GET", "/control/items?q=pistol", nil))
+ handler.ServeHTTP(second, httptest.NewRequest("GET", "/control/items?q=pistol&page=2", nil))
+ handler.ServeHTTP(last, httptest.NewRequest("GET", "/control/items?q=pistol&page=999999999", nil))
+ handler.ServeHTTP(empty, httptest.NewRequest("GET", "/control/items?q=missing&page=-1", nil))
+
+ if strings.Count(first.Body.String(), "<tr>") != 501 || strings.Count(second.Body.String(), "<tr>") != 501 ||
+ strings.Count(last.Body.String(), "<tr>") != 2 || strings.Count(empty.Body.String(), "<tr>") != 1 {
+ t.Fatal("instance pages did not contain 500, 500, 1 and 0 rows")
+ }
+ if !strings.Contains(second.Body.String(), "href='control/items/501'") || strings.Contains(second.Body.String(), "href='control/items/500'") ||
+ !strings.Contains(first.Body.String(), "href='control/items?page=2&q=pistol'") || !strings.Contains(last.Body.String(), "Page 3 of 3") || !strings.Contains(empty.Body.String(), "Page 1 of 1") {
+ t.Fatal("instance boundaries or retained filter are incorrect")
+ }
+}
+
+func postControlForm(world *server, path string, fields url.Values) *httptest.ResponseRecorder {
+ request := httptest.NewRequest("POST", path, strings.NewReader(fields.Encode()))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ response := httptest.NewRecorder()
+ world.httpHandler().ServeHTTP(response, request)
+ return response
+}
+
+func TestControlItemsShareOneRegistryAndShowOwnersAndBackpackContents(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}})
+
+ pistol := postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ bag := postControlForm(world, "/control/items", url.Values{"template": {"99228"}})
+ contained := postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ placed := postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1, inventory_slot_2: 2}\n"}})
+ filled := postControlForm(world, "/control/items/2", url.Values{"data": {"type: 51017\ntemplate: 99228\nquality: 1\ncount: 1\nslots: {slot_1: 3}\n"}})
+ restarted := newServer()
+ page := httptest.NewRecorder()
+ restarted.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/items?q=Explorer", nil))
+ details := httptest.NewRecorder()
+ restarted.httpHandler().ServeHTTP(details, httptest.NewRequest("GET", "/control/items/1", nil))
+
+ for _, response := range []*httptest.ResponseRecorder{pistol, bag, contained, placed, filled} {
+ if response.Code != http.StatusSeeOther {
+ t.Fatalf("item operation: %d %s", response.Code, response.Body.String())
+ }
+ }
+ if len(restarted.items) != 3 || restarted.nextItem != 3 || restarted.items[1].Template != 121567 || restarted.items[2].Template != 99228 {
+ t.Fatalf("global registry: %+v", restarted.items)
+ }
+ inventory := restarted.characters[1].inventory
+ if len(inventory.Items) != 2 || inventory.Items[0] != (ownedItem{1, 51018, 121567, 1, 64, 1}) || inventory.Items[1] != (ownedItem{2, 51017, 99228, 1, 65, 1}) ||
+ len(inventory.Containers[2]) != 1 || inventory.Containers[2][0] != (ownedItem{3, 51018, 121567, 1, 0, 1}) {
+ t.Fatalf("slot references lost their items: %+v", inventory)
+ }
+ if page.Code != http.StatusOK || !strings.Contains(page.Body.String(), "Solar-Powered Pistol") || !strings.Contains(page.Body.String(), "Explorer (1)") ||
+ !strings.Contains(page.Body.String(), "Backpack 2, slot_1") || !strings.Contains(page.Body.String(), "href='control/items/3'") {
+ t.Fatalf("item list: %d %s", page.Code, page.Body.String())
+ }
+ if details.Code != http.StatusOK || !strings.Contains(details.Body.String(), "Instance properties") || !strings.Contains(details.Body.String(), "Catalog properties") {
+ t.Fatalf("item properties: %d %s", details.Code, details.Body.String())
+ }
+ contents, err := readTestItemStore(world)
+ if err != nil || !strings.Contains(string(contents), "slot_30: null") || !strings.Contains(string(contents), "slot_21: null") || strings.Contains(string(contents), "slot: 64") {
+ t.Fatalf("shared YAML is not slot-based: %s, %v", contents, err)
+ }
+}
+
+func TestControlItemCanBeUnassignedAndTransferredWithoutChangingID(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"First"}})
+ postControlForm(world, "/control/users", url.Values{"name": {"Second"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}})
+
+ cleared := postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: null}\n"}})
+ unassigned := newServer()
+ transferred := postControlForm(world, "/control/users/2", url.Values{"data": {"inventory:\n slots: {inventory_slot_30: 1}\n"}})
+ restarted := newServer()
+ postControlForm(restarted, "/control/items", url.Values{"template": {"121567"}})
+
+ if cleared.Code != http.StatusSeeOther || transferred.Code != http.StatusSeeOther || len(unassigned.items) != 1 || len(unassigned.characters[1].inventory.Items) != 0 {
+ t.Fatalf("unassignment or transfer failed: %d %d", cleared.Code, transferred.Code)
+ }
+ if len(restarted.characters[1].inventory.Items) != 0 || len(restarted.characters[2].inventory.Items) != 1 ||
+ restarted.characters[2].inventory.Items[0] != (ownedItem{1, 51018, 121567, 1, 93, 1}) || restarted.nextItem != 2 {
+ t.Fatal("transfer lost identity or reused a global ID")
+ }
+}
+
+func TestControlInventoryRejectsDuplicateUnknownAndInvalidSlotsAtomically(t *testing.T) {
+ for _, contents := range []string{
+ "slots: {inventory_slot_1: 1}\n",
+ "slots: {inventory_slot_1: 2, inventory_slot_2: 2}\n",
+ "slots: {inventory_slot_1: 99}\n",
+ "slots: {inventory_slot_31: 2}\n",
+ "slots: {inventory_slot_1: 2, inventory_slot_1: null}\n",
+ "slots: {inventory_slot_1: {id: 2}}\n",
+ } {
+ t.Run(contents, func(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"First"}})
+ postControlForm(world, "/control/users", url.Values{"name": {"Second"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}})
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ response := postControlForm(world, "/control/users/2", url.Values{"data": {"inventory:\n " + contents}})
+ after, readError := readTestItemStore(world)
+
+ if response.Code != http.StatusBadRequest || readError != nil || !bytes.Equal(before, after) || len(world.characters[2].inventory.Items) != 0 || world.nextItem != 2 {
+ t.Fatalf("invalid inventory edit changed state: %d %s", response.Code, response.Body.String())
+ }
+ })
+ }
+}
+
+func TestControlItemCreationKeepsStateWhenSavingFails(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ failDatabaseWrites(t, world)
+
+ response := postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+
+ if response.Code != http.StatusInternalServerError || world.nextItem != 0 || len(world.items) != 0 {
+ t.Fatalf("failed save changed registry: %d %s", response.Code, response.Body.String())
+ }
+}
+
+func TestControlEditorShowsAllSkillCategoriesAndDefaultFields(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}})
+ contents := "id: 1\nname: Explorer\nappearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}\nlevel: 1\nstats:\n body:\n martial_arts: 0\n"
+ if response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}}); response.Code != http.StatusSeeOther {
+ t.Fatal(response.Body.String())
+ }
+
+ page := httptest.NewRecorder()
+ world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/users/1", nil))
+ editors := regexp.MustCompile(`(?s)<textarea[^>]*>(.*?)</textarea>`).FindAllStringSubmatch(page.Body.String(), -1)
+
+ if page.Code != http.StatusOK || len(editors) != 1 {
+ t.Fatalf("editors: %d %s", page.Code, page.Body.String())
+ }
+ var profile map[string]any
+ if err := yaml.Unmarshal([]byte(html.UnescapeString(editors[0][1])), &profile); err != nil {
+ t.Fatal(err)
+ }
+ stats := profile["stats"].(map[string]any)
+ for category, count := range map[string]int{"abilities": 6, "body": 8, "melee": 10, "misc_weapons": 3, "ranged": 13, "speed": 9, "trade_repair": 10, "nano_aiding": 8, "spying": 4, "navigation": 4} {
+ if len(stats[category].(map[string]any)) != count {
+ t.Fatalf("incomplete %s category: %v", category, stats[category])
+ }
+ }
+ if stats["improvement_points"] != 1500 || stats["body"].(map[string]any)["martial_arts"] != 0 || stats["abilities"].(map[string]any)["strength"] != 10 || stats["ranged"].(map[string]any)["rifle"] != 5 || stats["speed"].(map[string]any)["run_speed"] != 100 {
+ t.Fatalf("incorrect defaults: %v", stats)
+ }
+ var data characterEditor
+ if err := decodeUsers(strings.NewReader(html.UnescapeString(editors[0][1])), &data); err != nil {
+ t.Fatal(err)
+ }
+ if data.Inventory.Credits != 0 || len(data.Inventory.Slots) != 30 || len(data.Inventory.Equipment) != 43 || data.Inventory.Slots["inventory_slot_1"] != nil || data.Inventory.Slots["inventory_slot_30"] != nil || !strings.Contains(editors[0][1], "return_door: null\n") {
+ t.Fatal("empty inventory slots or optional fields are hidden")
+ }
+}
+
+func TestControlNestedSkillsAndImprovementPointsPersistAndReachClient(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}})
+ contents := "id: 1\nname: Explorer\nappearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}\nlevel: 1\nstats:\n improvement_points: 12345\n ranged:\n rifle: 42\n spying:\n concealment: 87\n"
+
+ response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}})
+ restarted := newServer()
+ packet := fullCharacterPacket(restarted.characters[1])
+ values := make(map[uint32]uint32)
+ count := binary.BigEndian.Uint32(packet[64:68])/1009 - 1
+ for offset := 68; offset < 68+int(count)*8; offset += 8 {
+ values[binary.BigEndian.Uint32(packet[offset:])] = binary.BigEndian.Uint32(packet[offset+4:])
+ }
+
+ if response.Code != http.StatusSeeOther || restarted.characters[1].stats.ImprovementPoints != 12345 || restarted.characters[1].stats.Ranged.Rifle != 42 || restarted.characters[1].stats.Spying.Concealment != 87 {
+ t.Fatalf("nested skills or IP lost: %d %s", response.Code, response.Body.String())
+ }
+ if values[53] != 12345 || values[113] != 42 || values[164] != 87 || values[102] != 5 || values[16] != 10 || values[156] != 100 {
+ t.Fatalf("native stats: %v", values)
+ }
+}
+
+func TestControlRoutesRequireControlPrefix(t *testing.T) {
+ world := &server{baseURL: "/"}
+ handler := world.httpHandler()
+
+ for _, path := range []string{"users/1", "users", "items", "items/1", "time", "teleport/1", "map-players", "map-assets/manifest.json", "control-map.js"} {
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, httptest.NewRequest("GET", "/"+path, nil))
+
+ if response.Code != http.StatusNotFound {
+ t.Fatalf("unprefixed route %s: %d", path, response.Code)
+ }
+ }
+}
+
+func TestControlCharacterDocumentSavesNativeFieldsAndNamedSlots(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}})
+ for _, template := range []string{"121567", "85686", "101173"} {
+ postControlForm(world, "/control/items", url.Values{"template": {template}})
+ }
+ page := httptest.NewRecorder()
+ world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/users/1", nil))
+ document := html.UnescapeString(regexp.MustCompile(`(?s)<textarea[^>]*>(.*?)</textarea>`).FindStringSubmatch(page.Body.String())[1])
+ var data characterEditor
+ if err := decodeUsers(strings.NewReader(document), &data); err != nil {
+ t.Fatal(err)
+ }
+ data.Name, data.Position, data.Appearance.Head = "Edited", [3]float32{53, 14, 60}, 31
+ data.Stats.ImprovementPoints, data.Stats.Ranged.Rifle, data.Vitals.Health = 12345, 42, 31
+ data.Inventory.Credits = 913
+ pistol, armor, implant := uint32(1), uint32(2), uint32(3)
+ data.Inventory.Slots["inventory_slot_7"] = &pistol
+ data.Inventory.Equipment["clothes_chest"], data.Inventory.Equipment["implants_chest"] = &armor, &implant
+ contents, err := yaml.Marshal(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ response := postControlForm(world, "/control/users/1", url.Values{"data": {string(contents)}})
+ restarted := newServer()
+ defer restarted.db.Close()
+ var name string
+ var x float32
+ var head, points, rifle, health, credits uint32
+ err = restarted.db.QueryRow("SELECT name, position_x, appearance_head, improvement_points, ranged_rifle, health, credits FROM characters JOIN players USING(id) WHERE id=1").Scan(&name, &x, &head, &points, &rifle, &health, &credits)
+
+ if response.Code != http.StatusSeeOther || err != nil || name != "Edited" || x != 53 || head != 31 || points != 12345 || rifle != 42 || health != 31 || credits != 913 {
+ t.Fatalf("native character fields were not saved: %d %s, %v", response.Code, response.Body.String(), err)
+ }
+ if !strings.Contains(document, "# Breed: 1 Solitus") || !strings.Contains(document, "# Sex: 2 male, 3 female") || strings.Count(page.Body.String(), "<textarea") != 1 {
+ t.Fatal("the unified editor lost its appearance documentation")
+ }
+ if restarted.characters[1].appearance != 64277 || restarted.characters[1].position != [3]float32{53, 14, 60} || restarted.characters[1].inventory.Credits != 913 {
+ t.Fatal("the native row did not restore the edited character")
+ }
+ for _, placement := range [][2]uint32{{1, 70}, {2, 21}, {3, 37}} {
+ var slot uint32
+ if err := restarted.db.QueryRow("SELECT slot FROM item_locations WHERE item_id=? AND player_id=1", placement[0]).Scan(&slot); err != nil || slot != placement[1] {
+ t.Fatalf("named slot placement %v: slot %d, %v", placement, slot, err)
+ }
+ }
+}
+
+func TestControlCharacterDocumentRollsBackAllSections(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ if _, err := world.db.Exec("CREATE TRIGGER reject_editor BEFORE UPDATE ON world BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil {
+ t.Fatal(err)
+ }
+ contents := "name: Changed\nposition: [53, 14, 60]\ninventory:\n credits: 913\n slots: {inventory_slot_7: 1}\n"
+
+ response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}})
+ restarted := newServer()
+ defer restarted.db.Close()
+ var name string
+ var credits, locations uint32
+ if err := restarted.db.QueryRow("SELECT name, credits FROM characters JOIN players USING(id) WHERE id=1").Scan(&name, &credits); err != nil {
+ t.Fatal(err)
+ }
+ if err := restarted.db.QueryRow("SELECT count(*) FROM item_locations").Scan(&locations); err != nil {
+ t.Fatal(err)
+ }
+
+ if response.Code != http.StatusInternalServerError || name != "Explorer" || credits != 0 || locations != 0 {
+ t.Fatalf("a rejected save committed part of the document: %d %s", response.Code, response.Body.String())
+ }
+ if world.characters[1].name != "Explorer" || world.characters[1].position != [3]float32{52.625, 14.75, 56.875} || len(world.characters[1].inventory.Items) != 0 ||
+ restarted.characters[1].position != [3]float32{52.625, 14.75, 56.875} {
+ t.Fatal("a rejected save changed the live or persisted character")
+ }
+}
+
+func TestControlAppearanceRejectsPackedScalarsAndOutOfRangeFields(t *testing.T) {
+ for _, contents := range []string{"appearance: 789\n", "appearance: {head: 32}\n", "appearance: {breed: 8}\n"} {
+ t.Run(contents, func(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}})
+
+ response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}})
+
+ if response.Code != http.StatusBadRequest || world.characters[1].appearance != 789 {
+ t.Fatalf("invalid appearance changed the character: %d %s", response.Code, response.Body.String())
+ }
+ })
+ }
+}
+
+func TestControlCharacterDocumentPreservesCastRefundAndExplicitNanoEdits(t *testing.T) {
+ for _, contents := range []string{"name: Edited\n", "name: Edited\nvitals: {nano: 13}\n"} {
+ t.Run(contents, func(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, _ := newNanoCastingWorld()
+ world.baseURL = "/"
+ player, client := world.characters[1], world.clients[1]
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ defer world.db.Close()
+ world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:])
+
+ response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}})
+ var nano uint32
+ err := world.db.QueryRow("SELECT nano FROM characters WHERE id=1").Scan(&nano)
+
+ expected := uint32(30)
+ if strings.Contains(contents, "nano: 13") {
+ expected = 13
+ }
+ if response.Code != http.StatusSeeOther || err != nil || nano != expected || player.nano != expected || client.nanoCast != nil {
+ t.Fatalf("cast cancellation lost refund or explicit edit: %d, nano %d/%d, %v: %s", response.Code, nano, player.nano, err, response.Body.String())
+ }
+ })
+ }
+}
diff --git a/server/control_items.go b/server/control_items.go
@@ -0,0 +1,44 @@
+package main
+
+import "slices"
+
+type controlItemSlot struct {
+ bag uint32
+ slot uint32
+}
+
+func controlItemSlots(inventory playerInventory, item ownedItem) []controlItemSlot {
+ var slots []controlItemSlot
+ for slot := uint32(1); slot < 94; slot++ {
+ if slot < 64 && (!item.fitsEquipmentSlot(slot) || slot >= 9 && slot <= 14 && slot-9 >= inventory.equipmentBonus(45)) {
+ continue
+ }
+ if !slices.ContainsFunc(inventory.Items, func(other ownedItem) bool { return other.Slot == slot }) {
+ slots = append(slots, controlItemSlot{slot: slot})
+ }
+ }
+ if item.Type != 51017 {
+ for _, bag := range inventory.Items {
+ if !bag.isSmallBackpack() {
+ continue
+ }
+ for slot := uint32(0); slot < 21; slot++ {
+ if !slices.ContainsFunc(inventory.Containers[bag.ID], func(other ownedItem) bool { return other.Slot == slot }) {
+ slots = append(slots, controlItemSlot{bag: bag.ID, slot: slot})
+ }
+ }
+ }
+ }
+ return slots
+}
+
+func (inventory playerInventory) allItems() []ownedItem {
+ items := slices.Clone(inventory.Items)
+ for _, entry := range inventory.Reclaim {
+ items = append(items, entry.Item)
+ }
+ for _, contents := range inventory.Containers {
+ items = append(items, contents...)
+ }
+ return items
+}
diff --git a/server/control_test.go b/server/control_test.go
@@ -19,7 +19,7 @@ func TestSetGameTimeUpdatesConnectedPlayer(t *testing.T) {
defer connection.Close()
client.SetDeadline(time.Now().Add(5 * time.Second))
world.clients[player.id] = &worldClient{conn: connection, ready: true, id: player.id}
- request := httptest.NewRequest("POST", "/time", strings.NewReader("hour=26&minute=45"))
+ request := httptest.NewRequest("POST", "/control/time", strings.NewReader("hour=26&minute=45"))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response := httptest.NewRecorder()
done := make(chan struct{})
@@ -46,7 +46,7 @@ func TestSetGameTimeUpdatesConnectedPlayer(t *testing.T) {
func TestSetGameTimeRejectsHourOutsideOriginalDay(t *testing.T) {
world := newTestServer(t)
- request := httptest.NewRequest("POST", "/time", strings.NewReader("hour=27&minute=0"))
+ request := httptest.NewRequest("POST", "/control/time", strings.NewReader("hour=27&minute=0"))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response := httptest.NewRecorder()
@@ -61,9 +61,12 @@ func TestUserPageHasMapTeleportAndZoneFinder(t *testing.T) {
world := newTestServer(t)
player := world.newCharacter()
world.clients[player.id] = &worldClient{ready: true}
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
response := httptest.NewRecorder()
- request := httptest.NewRequest("GET", "/users/1", nil)
+ request := httptest.NewRequest("GET", "/control/users/1", nil)
request.SetPathValue("character", "1")
world.userPage(response, request)
@@ -71,7 +74,7 @@ func TestUserPageHasMapTeleportAndZoneFinder(t *testing.T) {
if !strings.Contains(body, "<select data-map-find>") || !strings.Contains(body, "data-map-teleport>") {
t.Fatalf("missing map controls")
}
- if strings.Count(body, "action='teleport/1'") != 1 || strings.Contains(body, "<button>Teleport</button>") {
+ if strings.Count(body, "action='control/teleport/1'") != 1 || strings.Contains(body, "<button>Teleport</button>") {
t.Fatalf("generic zone teleport is still present")
}
}
@@ -80,8 +83,8 @@ func TestTeleportRejectsZoneWithoutOriginalAssets(t *testing.T) {
world := newTestServer(t)
player := world.newCharacter()
mux := http.NewServeMux()
- mux.HandleFunc("POST /teleport/{character}", world.teleportPlayer)
- request := httptest.NewRequest("POST", "/teleport/1", strings.NewReader("playfield=690"))
+ mux.HandleFunc("POST /control/teleport/{character}", world.teleportPlayer)
+ request := httptest.NewRequest("POST", "/control/teleport/1", strings.NewReader("playfield=690"))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response := httptest.NewRecorder()
diff --git a/server/corpse_credits_test.go b/server/corpse_credits_test.go
@@ -2,7 +2,6 @@ package main
import (
"encoding/binary"
- "os"
"sync"
"testing"
"time"
@@ -130,8 +129,7 @@ func TestCorpseCreditsInvalidUseAndFailedSaveRetainCash(t *testing.T) {
case "replaced":
world.clients[1] = &worldClient{id: 1}
case "failed save":
- os.Remove("data/players/1/inventory.yaml")
- os.Mkdir("data/players/1/inventory.yaml", 0700)
+ failDatabaseWrites(t, world)
}
err := world.handleLootUse(client, request)
@@ -214,8 +212,8 @@ func TestCorpseCreditsSavedAwardSurvivesClosedOwnerOutput(t *testing.T) {
func TestCorpseCreditsRejectOutOfRangePersistentBalance(t *testing.T) {
t.Chdir(t.TempDir())
- newCorpseCreditWorld(t)
- if err := os.WriteFile("data/players/1/inventory.yaml", []byte("last_id: 0\ncredits: 1000000001\nitems: []\n"), 0600); err != nil {
+ saved, _ := newCorpseCreditWorld(t)
+ if _, err := saved.db.Exec(`UPDATE players SET credits=1000000001 WHERE id=1`); err != nil {
t.Fatal(err)
}
world := &server{characters: make(map[uint32]*character)}
diff --git a/server/database.go b/server/database.go
@@ -0,0 +1,202 @@
+package main
+
+import (
+ "database/sql"
+ _ "embed"
+ "fmt"
+ "os"
+ "strings"
+ "time"
+
+ _ "github.com/mattn/go-sqlite3"
+)
+
+//go:embed world.sql
+var worldSchema string
+
+func (server *server) database() (*sql.DB, error) {
+ server.databaseMutex.Lock()
+ defer server.databaseMutex.Unlock()
+ if server.db != nil {
+ return server.db, nil
+ }
+ if err := os.MkdirAll("data", 0700); err != nil {
+ return nil, err
+ }
+ file, err := os.OpenFile("data/world.sqlite", os.O_CREATE|os.O_RDWR, 0600)
+ if err != nil {
+ return nil, err
+ }
+ if err := file.Close(); err != nil {
+ return nil, err
+ }
+ db, err := sql.Open("sqlite3", "data/world.sqlite?_foreign_keys=on&_journal_mode=WAL&_synchronous=FULL&_busy_timeout=5000")
+ if err != nil {
+ return nil, err
+ }
+ // One connection orders chat and world transactions; WAL permits external readers.
+ db.SetMaxOpenConns(1)
+ _, err = db.Exec(worldSchema)
+ if err == nil {
+ _, err = db.Exec("INSERT OR IGNORE INTO world (id, clock_started) VALUES (1, ?)", time.Now().UTC().Format(time.RFC3339Nano))
+ }
+ if err != nil {
+ db.Close()
+ return nil, err
+ }
+ if err := os.Chmod("data/world.sqlite", 0600); err != nil {
+ db.Close()
+ return nil, err
+ }
+ server.db = db
+ return db, nil
+}
+
+type playerVitals struct {
+ Health uint32 `yaml:"health"`
+ Nano uint32 `yaml:"nano"`
+ Sitting bool `yaml:"sitting"`
+ AggDef int32 `yaml:"agg_def"`
+ RechargeUntil time.Time `yaml:"recharge_until"`
+ NanoRechargeUntil time.Time `yaml:"nano_recharge_until"`
+ RegenerationAt time.Time `yaml:"regeneration_at"`
+ RegenerationSeconds uint32 `yaml:"regeneration_seconds"`
+}
+
+func (character *character) profile() playerProfile {
+ return playerProfile{character.id, character.name, unpackAppearance(character.appearance), character.monsterData,
+ character.level, max(1, character.profession), character.baseStats(), character.running, character.browserTokenHash, character.resurrectionTerminal,
+ character.implantChangesUntil, character.treatmentLockedUntil}
+}
+
+func (character *character) vitals() playerVitals {
+ return playerVitals{character.health, character.nano, character.sitting, character.aggDef,
+ character.rechargeUntil, character.nanoRechargeUntil, character.regenerationAt, character.regenerationSeconds}
+}
+
+func (character *character) applyVitals(vitals playerVitals) {
+ character.health, character.nano, character.sitting, character.aggDef = vitals.Health, vitals.Nano, vitals.Sitting, vitals.AggDef
+ character.rechargeUntil, character.nanoRechargeUntil = vitals.RechargeUntil, vitals.NanoRechargeUntil
+ character.regenerationAt, character.regenerationSeconds = vitals.RegenerationAt, vitals.RegenerationSeconds
+}
+
+// Character records contain scalar SQL values, including each trained skill.
+const positionColumns = "playfield, position_x, position_y, position_z, rotation_x, rotation_y, rotation_z, rotation_w, return_playfield, return_door"
+const vitalColumns = "health, nano, sitting, agg_def, recharge_until, nano_recharge_until, regeneration_at, regeneration_seconds"
+const characterColumns = profileColumns + ", " + positionColumns + ", " + vitalColumns
+
+type storedPosition struct {
+ Playfield uint32
+ Position [3]float32
+ Rotation [4]float32
+ ReturnPlayfield uint32
+ ReturnDoor uint32
+}
+
+func (position *storedPosition) fields() []any {
+ return []any{&position.Playfield, &position.Position[0], &position.Position[1], &position.Position[2],
+ &position.Rotation[0], &position.Rotation[1], &position.Rotation[2], &position.Rotation[3], &position.ReturnPlayfield, &position.ReturnDoor}
+}
+
+func (position storedPosition) editor() playerPosition {
+ result := playerPosition{Playfield: position.Playfield, Position: position.Position, Rotation: position.Rotation}
+ if position.ReturnPlayfield != 0 {
+ result.ReturnDoor = &doorOrigin{position.ReturnPlayfield, position.ReturnDoor}
+ }
+ return result
+}
+
+func (vitals *playerVitals) fields() []any {
+ return []any{&vitals.Health, &vitals.Nano, &vitals.Sitting, &vitals.AggDef, &vitals.RechargeUntil,
+ &vitals.NanoRechargeUntil, &vitals.RegenerationAt, &vitals.RegenerationSeconds}
+}
+
+type characterRecord struct {
+ Profile playerProfile
+ Position storedPosition
+ Vitals playerVitals
+}
+
+func (character *character) record() characterRecord {
+ position := storedPosition{Playfield: character.playfield, Position: character.position, Rotation: character.rotation}
+ if character.returnDoor != nil {
+ position.ReturnPlayfield, position.ReturnDoor = character.returnDoor.Playfield, character.returnDoor.Door
+ }
+ return characterRecord{character.profile(), position, character.vitals()}
+}
+
+func (record *characterRecord) fields() []any {
+ fields := append(record.Profile.fields(), record.Position.fields()...)
+ return append(fields, record.Vitals.fields()...)
+}
+
+func (record characterRecord) character() *character {
+ profile, position := record.Profile, record.Position.editor()
+ data := userData{profile.ID, profile.Name, position.Playfield, position.Position, position.Rotation,
+ profile.Appearance.packed(), profile.MonsterData, profile.Level, profile.Profession, profile.Stats, profile.Running, position.ReturnDoor, profile.BrowserTokenHash}
+ player := data.character()
+ player.applyVitals(record.Vitals)
+ player.resurrectionTerminal = profile.ResurrectionTerminal
+ player.implantChangesUntil, player.treatmentLockedUntil = profile.ImplantChangesUntil, profile.TreatmentLockedUntil
+ player.savedProfile, player.savedPosition, player.savedVitals = profile, position, record.Vitals
+ return player
+}
+
+func insertRecord(tx *sql.Tx, table string, id uint32, columns string, fields []any) error {
+ query := "INSERT OR IGNORE INTO " + table + " (id, " + columns + ") VALUES (?" + strings.Repeat(", ?", len(fields)) + ")"
+ _, err := tx.Exec(query, append([]any{id}, fields...)...)
+ return err
+}
+
+func upsertRecordSQL(table, columns string) string {
+ names := strings.Split(columns, ", ")
+ assignments := make([]string, len(names))
+ for index, name := range names {
+ assignments[index] = name + " = excluded." + name
+ }
+ return "INSERT INTO " + table + " (id, " + columns + ") VALUES (?" + strings.Repeat(", ?", len(names)) + ") ON CONFLICT(id) DO UPDATE SET " + strings.Join(assignments, ", ")
+}
+
+func updateRecord(tx *sql.Tx, table string, id uint32, columns string, fields []any) error {
+ assignments := strings.ReplaceAll(columns, ", ", " = ?, ") + " = ?"
+ _, err := tx.Exec("UPDATE "+table+" SET "+assignments+" WHERE id = ?", append(fields, id)...)
+ return err
+}
+
+func insertPlayer(tx *sql.Tx, player *character) error {
+ record := player.record()
+ if err := insertRecord(tx, "characters", player.id, characterColumns, record.fields()); err != nil {
+ return err
+ }
+ _, err := tx.Exec("INSERT OR IGNORE INTO players (id) VALUES (?)", player.id)
+ return err
+}
+
+func (server *server) loadPlayers() error {
+ db, err := server.database()
+ if err != nil {
+ return err
+ }
+ rows, err := db.Query("SELECT id, " + characterColumns + " FROM characters JOIN players USING(id) ORDER BY id")
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var record characterRecord
+ if err := rows.Scan(append([]any{&record.Profile.ID}, record.fields()...)...); err != nil {
+ return err
+ }
+ player := record.character()
+ if err := player.userData().validate(); err != nil {
+ return fmt.Errorf("player %d: %w", player.id, err)
+ }
+ if record.Profile.ResurrectionTerminal != 0 && record.Profile.ResurrectionTerminal != 0xc00202c1 {
+ return fmt.Errorf("player %d: unknown resurrection terminal", player.id)
+ }
+ player.nextPositionSave = time.Now().Add(time.Duration(player.id%20) * time.Second)
+ server.characters[player.id] = player
+ server.nextCharacter = max(server.nextCharacter, player.id)
+ }
+ return rows.Err()
+}
diff --git a/server/database_test.go b/server/database_test.go
@@ -0,0 +1,301 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "go.yaml.in/yaml/v3"
+)
+
+func readTestPlayerRecord(id uint32, name string) ([]byte, error) {
+ world := &server{}
+ db, err := world.database()
+ if err != nil {
+ return nil, err
+ }
+ defer db.Close()
+ var record characterRecord
+ err = db.QueryRow("SELECT id, "+characterColumns+" FROM characters WHERE id=?", id).Scan(append([]any{&record.Profile.ID}, record.fields()...)...)
+ if err != nil {
+ return nil, err
+ }
+ switch name {
+ case "player":
+ return yaml.Marshal(record.Profile)
+ case "position":
+ return yaml.Marshal(record.Position.editor())
+ default:
+ return nil, fmt.Errorf("unknown test record %q", name)
+ }
+}
+
+func writeTestPlayerRecord(id uint32, name string, contents []byte) error {
+ world := &server{}
+ db, err := world.database()
+ if err != nil {
+ return err
+ }
+ defer db.Close()
+ tx, err := db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ var profile playerProfile
+ if name != "player" {
+ return fmt.Errorf("unknown test record %q", name)
+ }
+ if err := decodeUsers(strings.NewReader(string(contents)), &profile); err != nil {
+ return err
+ }
+ if err := updateRecord(tx, "characters", id, profileColumns, profile.fields()); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+func readTestItemStore(world *server) ([]byte, error) {
+ store, err := world.readItems()
+ if err != nil {
+ return nil, err
+ }
+ return yaml.Marshal(store)
+}
+
+func readTestChatHistory(world *server, id uint32) ([]byte, error) {
+ entries, err := world.chatHistory_locked(id)
+ if err != nil {
+ return nil, err
+ }
+ var data []byte
+ for _, entry := range entries {
+ line, err := json.Marshal(entry)
+ if err != nil {
+ return nil, err
+ }
+ data = append(data, line...)
+ data = append(data, '\n')
+ }
+ return data, nil
+}
+func failDatabaseWrites(t *testing.T, world *server) {
+ t.Helper()
+ db, err := world.database()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := db.Exec("PRAGMA query_only=ON"); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { db.Exec("PRAGMA query_only=OFF") })
+}
+
+func TestWorldDatabaseRestoresNPCStateAndPlayerVitals(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}})
+ player := world.characters[1]
+ player.health, player.nano, player.sitting, player.aggDef = 27, 11, true, 33
+ player.inventory.Credits = 913
+ player.nanoRechargeUntil = time.Now().Add(30 * time.Second)
+ now := time.Now().UTC()
+ npc := world.characters[1000000]
+ npc.health, npc.position = 0, [3]float32{53, 14, 57}
+ npc.roaming = &npcRoaming{home: [3]float32{52, 14, 56}, destination: [3]float32{54, 14, 58}, nextMove: now.Add(time.Second)}
+ npc.corpse = &npcCorpse{looter: 1, credits: 87, expiresAt: now.Add(180 * time.Second),
+ items: []ownedItem{{17, 51018, 121567, 1, 0, 1}}}
+ world.corpseExpiry = []*character{npc}
+ world.npcRespawns = []npcRespawn{{npc, now.Add(100 * time.Second)}}
+ response := postControlForm(world, "/control/time", url.Values{"hour": {"9"}, "minute": {"17"}})
+
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ restarted := newServer()
+ defer restarted.db.Close()
+ var integrity string
+ if err := restarted.db.QueryRow("PRAGMA integrity_check").Scan(&integrity); err != nil {
+ t.Fatal(err)
+ }
+ var itemCount int
+ if err := restarted.db.QueryRow("SELECT count(*) FROM items").Scan(&itemCount); err != nil {
+ t.Fatal(err)
+ }
+
+ restored := restarted.characters[1]
+ corpse := restarted.characters[1000000]
+ if response.Code != http.StatusSeeOther || integrity != "ok" || itemCount != 1 || len(restarted.characters) != 2 {
+ t.Fatalf("world state: response=%d integrity=%s items=%d characters=%d", response.Code, integrity, itemCount, len(restarted.characters))
+ }
+ if restored.health != 27 || restored.nano != 11 || !restored.sitting || restored.aggDef != 33 || restored.inventory.Credits != 913 || !restored.nanoRechargeUntil.Equal(player.nanoRechargeUntil) {
+ t.Fatal("player vitals, credits or cooldown were lost")
+ }
+ if corpse.health != 0 || corpse.position != [3]float32{53, 14, 57} || corpse.roaming.home != [3]float32{52, 14, 56} ||
+ corpse.corpse.credits != 87 || corpse.corpse.looter != 1 || len(corpse.corpse.items) != 1 || corpse.corpse.items[0].ID != 17 || restarted.nextItem != 17 {
+ t.Fatal("NPC pose, corpse ownership, loot or identity counter was lost")
+ }
+ if len(restarted.npcRespawns) != 1 || !restarted.npcRespawns[0].at.Equal(now.Add(100*time.Second)) ||
+ len(restarted.corpseExpiry) != 1 || !corpse.corpse.expiresAt.Equal(now.Add(180*time.Second)) {
+ t.Fatal("corpse or respawn deadline was lost")
+ }
+ if restarted.gameSeconds != 33420 || !restarted.clockStarted.Equal(world.clockStarted) {
+ t.Fatal("world clock reset")
+ }
+ for _, path := range []string{"data/players", "data/items.yaml"} {
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("mutable YAML state still exists at %s", path)
+ }
+ }
+}
+
+func TestWorldDatabaseKeepsRespawnAfterCorpseExpires(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ now := time.Now().UTC()
+ npc := world.characters[1000000]
+ npc.health = 0
+ npc.roaming = &npcRoaming{home: [3]float32{52, 14, 56}}
+ npc.corpse = &npcCorpse{expiresAt: now.Add(time.Second), items: []ownedItem{{17, 51018, 121567, 1, 0, 1}}}
+ world.corpseExpiry = []*character{npc}
+ world.npcRespawns = []npcRespawn{{npc, now.Add(3 * time.Second)}}
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+
+ world.advanceCorpseExpiry(now.Add(time.Second))
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ restarted := newServer()
+ defer restarted.db.Close()
+ if restarted.characters[1000000] != nil || len(restarted.npcRespawns) != 1 || len(restarted.items) != 0 {
+ t.Fatal("expired corpse was restored or its respawn source was discarded")
+ }
+ restarted.advanceNPCRespawns(now.Add(3 * time.Second))
+ if err := restarted.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ again := newServer()
+ defer again.db.Close()
+
+ if len(again.characters) != 1 || again.characters[1000001] == nil || again.characters[1000001].position != [3]float32{52, 14, 56} ||
+ len(again.npcRespawns) != 0 || len(again.corpseExpiry) != 0 || len(again.roamingNPCs[950]) != 1 || again.nextItem != 17 || again.nextNPC != 1000002 {
+ t.Fatal("respawn duplicated the source, lost home or reused an identity")
+ }
+}
+
+func TestWorldDatabaseRollsBackCorpseCashWithInventory(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, _ := newCorpseCreditWorld(t)
+ defer world.db.Close()
+ world.characters[1].inventory.Credits = 10
+ world.characters[1000000].corpse.credits = 32
+ if err := world.saveInventory_locked(world.characters[1], world.characters[1].inventory); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec("CREATE TRIGGER reject_world BEFORE UPDATE ON world BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ saveErr := world.handleLootUse(world.clients[1], lootUseRequest(1))
+ restarted := newTestInventoryServer(t)
+ if _, err := world.db.Exec("DROP TRIGGER reject_world"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleLootUse(world.clients[1], lootUseRequest(2)); err != nil {
+ t.Fatal(err)
+ }
+ committed := newTestInventoryServer(t)
+
+ if saveErr == nil || restarted.characters[1].inventory.Credits != 10 || restarted.characters[1000000].corpse.credits != 32 ||
+ committed.characters[1].inventory.Credits != 42 || committed.characters[1000000].corpse.credits != 0 {
+ t.Fatalf("corpse cash and player inventory did not commit together: %v", saveErr)
+ }
+}
+
+func TestProfileEditorCommitsCurrentResourcesWithProfile(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}})
+ world.characters[1].health, world.characters[1].nano = 30, 12
+
+ response := postControlForm(world, "/control/users/1", url.Values{"data": {"id: 1\nname: Explorer\nappearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}\nlevel: 2\n"}})
+ restarted := newServer()
+ defer restarted.db.Close()
+
+ if response.Code != http.StatusSeeOther || restarted.characters[1].level != 2 || restarted.characters[1].health != 30 || restarted.characters[1].nano != 12 {
+ t.Fatal("profile edit saved stale health or nano")
+ }
+}
+
+func TestWorldDatabasePersistsContributorChangesAfterRestart(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ world.characters[1000000].damageContributors = map[uint32]uint32{1: 4}
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ restarted := newServer()
+ defer restarted.db.Close()
+
+ restarted.characters[1000000].damageContributors[1] = 9
+ if err := restarted.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ again := newServer()
+ defer again.db.Close()
+ var damage uint32
+ err := again.db.QueryRow("SELECT damage FROM npc_damage_contributors WHERE npc_id=1000000 AND player_id=1").Scan(&damage)
+
+ if err != nil || damage != 9 || again.characters[1000000].damageContributors[1] != 9 {
+ t.Fatalf("NPC contribution change was not checkpointed: %d, %v", damage, err)
+ }
+}
+
+func TestNPCCheckpointsSkipEmptyZonesAndLimitRoutineWrites(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}})
+ now := time.Now()
+ if err := world.checkpointWorld(now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec("CREATE TABLE npc_updates (id INTEGER); CREATE TRIGGER npc_update AFTER UPDATE ON characters WHEN NEW.id>=1000000 BEGIN INSERT INTO npc_updates VALUES (NEW.id); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ steps := []struct {
+ seconds int
+ present bool
+ x float32
+ }{{60, false, 53}, {61, true, 53}, {62, true, 54}, {80, true, 54}, {102, true, 54}, {103, true, 55}, {104, false, 55}, {165, false, 56}}
+ var counts [8]int
+ var positions [8]float32
+ for index, step := range steps {
+ if step.present {
+ world.clients[1] = &worldClient{id: 1, ready: true}
+ } else {
+ delete(world.clients, 1)
+ }
+ world.characters[1000000].position[0] = step.x
+ if err := world.checkpointWorld(now.Add(time.Duration(step.seconds) * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.db.QueryRow("SELECT count(*) FROM npc_updates").Scan(&counts[index]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.db.QueryRow("SELECT position_x FROM characters WHERE id=1000000").Scan(&positions[index]); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if counts != [8]int{0, 1, 1, 1, 2, 2, 3, 3} || positions != [8]float32{52, 53, 53, 53, 54, 54, 55, 55} {
+ t.Fatalf("empty zones or early checkpoints rewrote NPC state: counts=%v positions=%v", counts, positions)
+ }
+}
diff --git a/server/embedded_resources_test.go b/server/embedded_resources_test.go
@@ -24,9 +24,9 @@ func TestEmbeddedResourcesServeWithoutExternalFiles(t *testing.T) {
mux.HandleFunc("GET /browser-resource-index", browserResourceIndex)
mux.HandleFunc("GET /wasm/", (&server{baseURL: "/"}).browserClient)
mux.HandleFunc("GET /{$}", (&server{baseURL: "/"}).browserClient)
- mux.Handle("GET /map-assets/", http.StripPrefix("/map-assets/", http.FileServerFS(maps)))
+ mux.Handle("GET /control/map-assets/", http.StripPrefix("/control/map-assets/", http.FileServerFS(maps)))
- for _, path := range []string{"/", "/wasm/game.js", "/wasm/build.json", "/browser-manifest", "/browser-resource-index", "/map-assets/manifest.json", "/browser-assets/version.id", "/browser-assets/cd_image/text/help/What%20%27s-This%20General%20Help.txt"} {
+ for _, path := range []string{"/", "/wasm/game.js", "/wasm/build.json", "/browser-manifest", "/browser-resource-index", "/control/map-assets/manifest.json", "/browser-assets/version.id", "/browser-assets/cd_image/text/help/What%20%27s-This%20General%20Help.txt"} {
response := httptest.NewRecorder()
mux.ServeHTTP(response, httptest.NewRequest("GET", path, nil))
diff --git a/server/equipment.go b/server/equipment.go
@@ -51,29 +51,29 @@ func (character *character) canEquip(item ownedItem) bool {
if item.isKodaik() {
stats := character.baseStats()
return gamedata.Playfields[character.playfield].Outdoor && !character.driving() &&
- stats.effectiveSkill(stats.VehicleGround, [6]uint32{0, 20, 0, 20, 60, 0}) > 80
+ stats.effectiveSkill(stats.Navigation.VehicleGround, [6]uint32{0, 20, 0, 20, 60, 0}) > 80
}
if item.isYalmaha() {
stats := character.baseStats()
return gamedata.Playfields[character.playfield].Outdoor && !character.driving() &&
- stats.effectiveSkill(stats.VehicleAir, [6]uint32{0, 20, 0, 20, 60, 0}) > 80
+ stats.effectiveSkill(stats.Navigation.VehicleAir, [6]uint32{0, 20, 0, 20, 60, 0}) > 80
}
if item.fitsEquipmentSlot(7) || item.fitsEquipmentSlot(9) {
stats := character.baseStats()
- return stats.effectiveSkill(stats.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 5
+ return stats.effectiveSkill(stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 5
}
if item.fitsEquipmentSlot(37) {
stats := character.baseStats()
- return stats.Strength > 5 && stats.effectiveSkill(stats.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 10
+ return stats.Abilities.Strength > 5 && stats.effectiveSkill(stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 10
}
if item.isKineticAxe() {
return character.canWieldKineticAxe()
}
if item.Template == 85685 {
- return character.baseStats().Strength > 460 && character.baseStats().Agility > 510
+ return character.baseStats().Abilities.Strength > 460 && character.baseStats().Abilities.Agility > 510
}
// Both QL 1 Metaplast pieces require Strength and Agility greater than 7.
- return character.baseStats().Strength > 7 && character.baseStats().Agility > 7
+ return character.baseStats().Abilities.Strength > 7 && character.baseStats().Abilities.Agility > 7
}
func (inventory playerInventory) equipmentBonus(stat uint32) uint32 {
@@ -140,9 +140,9 @@ func itemStat(item *gamedata.Item, stat uint32) uint32 {
func (character *character) canWieldKineticAxe() bool {
// Template 209283's Wield action requires all three effective skills > 4.
stats := character.baseStats()
- return stats.effectiveSkill(stats.OneHandEdged, [6]uint32{30, 40, 30, 0, 0, 0}) >= 5 &&
- stats.effectiveSkill(stats.Brawling, [6]uint32{60, 0, 40, 0, 0, 0}) >= 5 &&
- stats.effectiveSkill(stats.FastAttack, [6]uint32{0, 60, 0, 0, 40, 0}) >= 5
+ return stats.effectiveSkill(stats.Melee.OneHandEdged, [6]uint32{30, 40, 30, 0, 0, 0}) >= 5 &&
+ stats.effectiveSkill(stats.Body.Brawling, [6]uint32{60, 0, 40, 0, 0, 0}) >= 5 &&
+ stats.effectiveSkill(stats.Melee.FastAttack, [6]uint32{0, 60, 0, 0, 40, 0}) >= 5
}
func itemMovePacket(owner, source, destination uint32) []byte {
diff --git a/server/equipment_test.go b/server/equipment_test.go
@@ -5,7 +5,6 @@ import (
"bytes"
"encoding/binary"
"encoding/hex"
- "os"
"reflect"
"testing"
"time"
@@ -34,7 +33,7 @@ func TestEquipmentDelayedNativeMoveAndRestart(t *testing.T) {
world.characters[2] = &character{id: 2, playfield: 950, health: 100}
world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true}
request := inventoryMovePacket(1, 64, 6)[20:]
- before, err := os.ReadFile("data/players/1/inventory.yaml")
+ before, err := readTestItemStore(world)
if err != nil {
t.Fatal(err)
}
@@ -50,7 +49,7 @@ func TestEquipmentDelayedNativeMoveAndRestart(t *testing.T) {
world.handleInventory(world.clients[1], request)
world.handleInventory(world.clients[1], inventoryDeletePacket(1, 64)[20:])
world.advanceEquipment(finish.Add(-time.Nanosecond))
- unchanged, err := os.ReadFile("data/players/1/inventory.yaml")
+ unchanged, err := readTestItemStore(world)
if err != nil || !bytes.Equal(before, unchanged) || len(conn.packets) != 0 || world.clients[1].equipment.readyAt != finish {
t.Fatalf("pending equip changed the item or timer: %v", err)
}
@@ -88,21 +87,21 @@ func TestEquipmentRequiresEachEffectiveSkillAtFive(t *testing.T) {
t.Run(skill, func(t *testing.T) {
world, _ := newEquipmentWorld(t)
player := world.characters[1]
- player.stats.OneHandEdged, player.stats.Brawling, player.stats.FastAttack = 3, 3, 3
+ player.stats.Melee.OneHandEdged, player.stats.Body.Brawling, player.stats.Melee.FastAttack = 3, 3, 3
switch skill {
case "one hand edged":
- player.stats.OneHandEdged = 2
+ player.stats.Melee.OneHandEdged = 2
case "brawling":
- player.stats.Brawling = 2
+ player.stats.Body.Brawling = 2
case "fast attack":
- player.stats.FastAttack = 2
+ player.stats.Melee.FastAttack = 2
}
err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:])
if err != nil || world.clients[1].equipment != nil || player.inventory.Items[0].Slot != 64 {
t.Fatalf("effective skill 4 equipped the axe: %v", err)
}
- player.stats.OneHandEdged, player.stats.Brawling, player.stats.FastAttack = 3, 3, 3
+ player.stats.Melee.OneHandEdged, player.stats.Body.Brawling, player.stats.Melee.FastAttack = 3, 3, 3
err = world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:])
if err != nil || world.clients[1].equipment == nil {
t.Fatalf("effective skill 5 failed to equip: %v", err)
@@ -124,7 +123,7 @@ func TestEquipmentCompletionRechecksStateAndPreservesFailedSave(t *testing.T) {
finish := world.clients[1].equipment.readyAt
switch scenario {
case "requirements":
- world.characters[1].stats.Brawling = 0
+ world.characters[1].stats.Body.Brawling = 0
case "own combat":
world.characters[1].fighting = 1000000
world.fighting[1] = world.characters[1]
@@ -140,8 +139,7 @@ func TestEquipmentCompletionRechecksStateAndPreservesFailedSave(t *testing.T) {
case "replaced session":
world.clients[1] = &worldClient{id: 1, ready: true}
case "failed save":
- os.Remove("data/players/1/inventory.yaml")
- os.Mkdir("data/players/1/inventory.yaml", 0700)
+ failDatabaseWrites(t, world)
}
world.advanceEquipment(finish)
@@ -173,8 +171,8 @@ func TestEquipmentFullInventoryDoesNotLoseEquippedWeapon(t *testing.T) {
func TestEquipmentSelectsAxeDamageSlotAndMeleeInitiative(t *testing.T) {
world, conn := newEquipmentWorld(t)
- world.characters[1].stats.PhysicalInitiative = 600
- world.characters[1].stats.MeleeInitiative = 0
+ world.characters[1].stats.Speed.PhysicalInitiative = 600
+ world.characters[1].stats.Speed.MeleeInitiative = 0
world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:])
world.advanceEquipment(world.clients[1].equipment.readyAt)
@@ -197,8 +195,8 @@ func TestEquipmentSelectsAxeDamageSlotAndMeleeInitiative(t *testing.T) {
func TestEquipmentUnequipRestoresFistTimingAndSlot(t *testing.T) {
world, conn := newEquipmentWorld(t)
- world.characters[1].stats.PhysicalInitiative = 600
- world.characters[1].stats.MeleeInitiative = 0
+ world.characters[1].stats.Speed.PhysicalInitiative = 600
+ world.characters[1].stats.Speed.MeleeInitiative = 0
world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:])
world.advanceEquipment(world.clients[1].equipment.readyAt)
diff --git a/server/flying_vehicle_test.go b/server/flying_vehicle_test.go
@@ -17,7 +17,7 @@ func newFlyingVehicleWorld(t *testing.T) (*server, *combatTestConn) {
world, conn := newCombatWorld()
player := world.newCharacter()
player.playfield, player.position = 800, [3]float32{600, 67, 700}
- player.stats.VehicleAir = 79 // Effective 81 with the fixture's abilities.
+ player.stats.Navigation.VehicleAir = 79 // Effective 81 with the fixture's abilities.
if err := world.saveUser_locked(player); err != nil {
t.Fatal(err)
}
@@ -48,7 +48,7 @@ func TestFlyingVehicleEquipRemovalAndRestart(t *testing.T) {
}
world.advanceEquipment(client.equipment.readyAt)
restored := newTestInventoryServer(t).characters[1]
- if !restored.flying() || restored.stats.VehicleAir != 79 || restored.inventory.equipmentBonus(156) != 150 ||
+ if !restored.flying() || restored.stats.Navigation.VehicleAir != 79 || restored.inventory.equipmentBonus(156) != 150 ||
restored.inventory.Items[0] != (ownedItem{1, 51022, 117322, 30, 1, 1}) || len(equippedItemPackets(restored)) != 1 {
t.Fatal("worn Yalmaha, flight effects or trained skill did not survive restart")
}
@@ -56,7 +56,7 @@ func TestFlyingVehicleEquipRemovalAndRestart(t *testing.T) {
if err := world.handleCombat(client, attackPacket(1, 1000000)[20:]); err != nil || player.fighting != 0 {
t.Fatal("a Yalmaha pilot started fighting")
}
- player.stats.VehicleAir = 0
+ player.stats.Navigation.VehicleAir = 0
if err := world.handleInventory(client, itemMovePacket(1, 1, 111)[20:]); err != nil {
t.Fatal(err)
}
@@ -84,9 +84,9 @@ func TestFlyingVehicleRejectsIneligibleEquipment(t *testing.T) {
request := inventoryMovePacket(1, 64, 1)[20:]
switch scenario {
case "skill 80":
- player.stats.VehicleAir = 78
+ player.stats.Navigation.VehicleAir = 78
case "ground skill only":
- player.stats.VehicleAir, player.stats.VehicleGround = 5, 79
+ player.stats.Navigation.VehicleAir, player.stats.Navigation.VehicleGround = 5, 79
case "indoor":
player.playfield = 1183
case "Grid":
@@ -125,7 +125,7 @@ func TestFlyingVehicleRechecksRequirementsAfterDelay(t *testing.T) {
finish := client.equipment.readyAt
switch scenario {
case "skill":
- player.stats.VehicleAir = 78
+ player.stats.Navigation.VehicleAir = 78
case "playfield":
player.playfield = 1183
case "combat":
diff --git a/server/grid_test.go b/server/grid_test.go
@@ -12,7 +12,7 @@ func newGridWorld(t *testing.T) (*server, *combatTestConn) {
player := world.newCharacter()
player.playfield = 800
player.position = [3]float32{637, 67.3, 728}
- player.stats.ComputerLiteracy = 89 // Effective 91 with Intelligence 10.
+ player.stats.TradeRepair.ComputerLiteracy = 89 // Effective 91 with Intelligence 10.
player.returnDoor = &doorOrigin{1183, 0xc000049f}
if err := world.saveUser_locked(player); err != nil {
t.Fatal(err)
@@ -55,7 +55,7 @@ func TestGridTerminalRejectsIneligibleUse(t *testing.T) {
request := gridUseRequest(1)
switch scenario {
case "skill 90":
- player.stats.ComputerLiteracy = 88
+ player.stats.TradeRepair.ComputerLiteracy = 88
case "outgoing combat":
player.fighting = 1000000
case "incoming combat":
@@ -138,7 +138,7 @@ func TestGridExitRequiresSkillAndNearbyLivingSession(t *testing.T) {
client.forward, client.movementStarted = 1, time.Now()
switch scenario {
case "skill 90":
- player.stats.ComputerLiteracy = 88
+ player.stats.TradeRepair.ComputerLiteracy = 88
case "distance":
player.position[0] += 3
case "height":
diff --git a/server/http.go b/server/http.go
@@ -10,7 +10,7 @@ import (
func (server *server) httpHandler() http.Handler {
mux := http.NewServeMux()
// Directory redirects must keep the public prefix and query string.
- for _, directory := range []string{"wasm", "map-assets"} {
+ for _, directory := range []string{"wasm", "control/map-assets"} {
mux.HandleFunc("GET /"+directory, func(w http.ResponseWriter, r *http.Request) {
location := server.baseURL + directory + "/"
if r.URL.RawQuery != "" {
@@ -21,17 +21,22 @@ func (server *server) httpHandler() http.Handler {
}
mux.HandleFunc("GET /control", server.controlPage)
- mux.HandleFunc("GET /users/{character}", server.userPage)
- mux.HandleFunc("POST /users", server.createUser)
- mux.HandleFunc("POST /users/{character}", server.editUser)
- mux.HandleFunc("GET /control-map.js", controlMapScript)
- mux.HandleFunc("GET /map-players", server.mapPlayers)
+ mux.HandleFunc("GET /control/users/{character}", server.userPage)
+ mux.HandleFunc("POST /control/users", server.createUser)
+ mux.HandleFunc("POST /control/users/{character}", server.editUser)
+ mux.HandleFunc("GET /control/items", server.itemsPage)
+ mux.HandleFunc("GET /control/items/catalog", server.itemCatalogPage)
+ mux.HandleFunc("POST /control/items", server.createItem)
+ mux.HandleFunc("GET /control/items/{item}", server.itemPage)
+ mux.HandleFunc("POST /control/items/{item}", server.editItem)
+ mux.HandleFunc("GET /control/control-map.js", controlMapScript)
+ mux.HandleFunc("GET /control/map-players", server.mapPlayers)
mapResources, err := fs.Sub(resources, "maps")
if err != nil {
log.Fatal(err)
}
- mapFiles := http.StripPrefix("/map-assets/", http.FileServerFS(mapResources))
- mux.HandleFunc("GET /map-assets/", func(w http.ResponseWriter, r *http.Request) {
+ mapFiles := http.StripPrefix("/control/map-assets/", http.FileServerFS(mapResources))
+ mux.HandleFunc("GET /control/map-assets/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, ".png") {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
} else {
@@ -48,8 +53,8 @@ func (server *server) httpHandler() http.Handler {
mux.HandleFunc("POST /browser-profile/{session}", browserProfile)
mux.HandleFunc("GET /wasm/", server.browserClient)
mux.HandleFunc("GET /{$}", server.browserClient)
- mux.HandleFunc("POST /time", server.setGameTime)
- mux.HandleFunc("POST /teleport/{character}", server.teleportPlayer)
+ mux.HandleFunc("POST /control/time", server.setGameTime)
+ mux.HandleFunc("POST /control/teleport/{character}", server.teleportPlayer)
// Keep the original launcher's dimension list available.
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
traceLog.Printf("HTTP %s %s", r.Method, r.URL.Path)
diff --git a/server/http_test.go b/server/http_test.go
@@ -55,7 +55,7 @@ func TestHTTPHandlerMountsGameAndControls(t *testing.T) {
if game.Code != http.StatusOK || !strings.Contains(game.Body.String(), `<base href="`+baseURL+`">`) || strings.Contains(game.Body.String(), "__AO_BASE_URL__") {
t.Fatalf("game page: HTTP %d, missing public base URL", game.Code)
}
- if controls.Code != http.StatusOK || !strings.Contains(controls.Body.String(), "<base href='"+baseURL+"'>") || !strings.Contains(controls.Body.String(), "action='users'") {
+ if controls.Code != http.StatusOK || !strings.Contains(controls.Body.String(), "<base href='"+baseURL+"'>") || !strings.Contains(controls.Body.String(), "action='control/users'") {
t.Fatalf("control page: HTTP %d, missing scoped forms", controls.Code)
}
if asset.Code != http.StatusOK || strings.TrimSpace(asset.Body.String()) != "14.9.1" {
@@ -70,7 +70,7 @@ func TestHTTPHandlerScopesVisitorCookieAndRedirects(t *testing.T) {
world := newTestServer(t)
world.baseURL = "/share/demo/"
handler := world.httpHandler()
- request := httptest.NewRequest("POST", world.baseURL+"time", strings.NewReader("hour=13&minute=30"))
+ request := httptest.NewRequest("POST", world.baseURL+"control/time", strings.NewReader("hour=13&minute=30"))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
redirect := httptest.NewRecorder()
@@ -97,7 +97,7 @@ func TestHTTPHandlerPreservesBaseURLInDirectoryRedirects(t *testing.T) {
handler := world.httpHandler()
for _, redirect := range []struct{ from, to string }{
{"/share/demo/wasm?profile=1", "/share/demo/wasm/?profile=1"},
- {"/share/demo/map-assets", "/share/demo/map-assets/"},
+ {"/share/demo/control/map-assets", "/share/demo/control/map-assets/"},
} {
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest("GET", redirect.from, nil))
diff --git a/server/implants.go b/server/implants.go
@@ -29,7 +29,7 @@ func (server *server) useClinic_locked(client *worldClient, index int, body []by
now := time.Now()
accepted := client.selectedTarget == [2]uint32{50000, client.id} && slot >= 64 && slot < 94 &&
player.inventory.Items[index].Type == 51005 && player.inventory.Items[index].Template == 43552 && player.inventory.Items[index].Quality == 1 &&
- stats.effectiveSkill(stats.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 5 && !now.Before(player.treatmentLockedUntil)
+ stats.effectiveSkill(stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 5 && !now.Before(player.treatmentLockedUntil)
if accepted {
// Save the cooldown and access window before acknowledging any authored effects.
updated := *player
diff --git a/server/implants_test.go b/server/implants_test.go
@@ -3,7 +3,6 @@ package main
import (
"bytes"
"encoding/binary"
- "os"
"reflect"
"testing"
"time"
@@ -12,7 +11,7 @@ import (
func newImplantWorld(t *testing.T) (*server, *combatTestConn) {
t.Helper()
world, conn := newArmorWorld(t)
- world.characters[1].stats.Treatment = 9
+ world.characters[1].stats.NanoAiding.Treatment = 9
world.clients[1].selectedTarget = [2]uint32{50000, 1}
for _, template := range []uint32{43552, 101173} {
if granted, err := world.grantItem_locked(world.characters[1], template); err != nil || !granted {
@@ -48,9 +47,9 @@ func TestImplantClinicEquipBonusesAndRestart(t *testing.T) {
if player.inventory.equipmentBonus(91) != 14 || player.inventory.equipmentBonus(90) != 6 || player.inventory.equipmentBonus(94) != 2 || player.meleeWeapon() == nil {
t.Fatalf("independent equipment bonuses: %+v", player.inventory.Items)
}
- if !reflect.DeepEqual(restored.inventory, player.inventory) || restored.inventory.equipmentBonus(91) != 14 ||
+ if !reflect.DeepEqual(restored.inventory.Items, player.inventory.Items) || restored.inventory.LastID != 5 || restored.inventory.equipmentBonus(91) != 14 ||
restored.implantChangesUntil.UnixNano() != player.implantChangesUntil.UnixNano() ||
- restored.treatmentLockedUntil.UnixNano() != player.treatmentLockedUntil.UnixNano() || restored.stats.Treatment != 9 {
+ restored.treatmentLockedUntil.UnixNano() != player.treatmentLockedUntil.UnixNano() || restored.stats.NanoAiding.Treatment != 9 {
t.Fatalf("implant or clinic state did not persist: %+v", restored)
}
last := conn.packets[len(conn.packets)-1]
@@ -81,11 +80,11 @@ func TestImplantRequirementsAndNativeSlotConversion(t *testing.T) {
destination := uint32(37)
switch scenario {
case "treatment 10":
- player.stats.Treatment = 8
+ player.stats.NanoAiding.Treatment = 8
case "strength 5":
- player.stats.Strength = 5
+ player.stats.Abilities.Strength = 5
case "strength 6":
- player.stats.Strength = 6
+ player.stats.Abilities.Strength = 6
case "no clinic":
player.implantChangesUntil = time.Time{}
case "wrong slot":
@@ -135,7 +134,7 @@ func TestImplantRemovalRetainsOtherEquipmentAndNeedsClinic(t *testing.T) {
world.advanceItemEffects(player.treatmentLockedUntil)
world.handleOwnedItemUse(client, backpackUseRequest(1, 67, 2)[20:])
// Removal does not recheck the implant's install requirements.
- player.stats.Treatment, player.stats.Strength = 0, 1
+ player.stats.NanoAiding.Treatment, player.stats.Abilities.Strength = 0, 1
conn.packets = nil
world.handleInventory(client, itemMovePacket(1, 37, 111)[20:])
world.advanceEquipment(client.equipment.readyAt)
@@ -161,8 +160,7 @@ func TestImplantPendingMoveRechecksClinicAndSave(t *testing.T) {
if scenario == "expired clinic" {
player.implantChangesUntil = finish
} else {
- os.Remove("data/players/1/inventory.yaml")
- os.Mkdir("data/players/1/inventory.yaml", 0700)
+ failDatabaseWrites(t, world)
}
world.advanceEquipment(finish)
@@ -264,7 +262,7 @@ func TestPortableClinicRejectsInvalidUseAndFailedSave(t *testing.T) {
request := backpackUseRequest(1, 67, 1)[20:]
switch scenario {
case "treatment 5":
- player.stats.Treatment = 3
+ player.stats.NanoAiding.Treatment = 3
case "no target":
client.selectedTarget = [2]uint32{}
case "other target":
@@ -282,8 +280,7 @@ func TestPortableClinicRejectsInvalidUseAndFailedSave(t *testing.T) {
case "loading":
client.loading = true
case "failed save":
- os.Remove("data/players/1/player.yaml")
- os.Mkdir("data/players/1/player.yaml", 0700)
+ failDatabaseWrites(t, world)
}
before := player.inventory
diff --git a/server/insurance.go b/server/insurance.go
@@ -38,7 +38,7 @@ func (server *server) handleTerminalUse(client *worldClient, body []byte) error
// Borealis statel 0xc0040320 requires Computer Literacy > 90 and no combat.
x, y, z := position[0]-636.4026, position[1]-66.81002, position[2]-728.8094
accepted = client.target && player.playfield == 800 && x*x+y*y+z*z <= 5*5 && player.fighting == 0 &&
- player.stats.effectiveSkill(player.stats.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 90
+ player.stats.effectiveSkill(player.stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 90
for _, attacker := range server.fighting {
if attacker.fighting == player.id {
accepted = false
diff --git a/server/insurance_test.go b/server/insurance_test.go
@@ -185,12 +185,14 @@ func TestInsuranceUnknownSavedScannerFailsLoading(t *testing.T) {
if err := world.saveUser_locked(player); err != nil {
t.Fatal(err)
}
- file, err := os.OpenFile("data/players/1/player.yaml", os.O_APPEND|os.O_WRONLY, 0600)
+ contents, err := readTestPlayerRecord(1, "player")
if err != nil {
t.Fatal(err)
}
- file.WriteString("resurrection_terminal: 123\n")
- file.Close()
+ contents = []byte(strings.Replace(string(contents), "resurrection_terminal: 0", "resurrection_terminal: 123", 1))
+ if err := writeTestPlayerRecord(1, "player", contents); err != nil {
+ t.Fatal(err)
+ }
loaded := &server{characters: make(map[uint32]*character)}
err = loaded.loadUsers()
diff --git a/server/inventory.go b/server/inventory.go
@@ -7,33 +7,31 @@ import (
"maps"
"slices"
"time"
-
- "go.yaml.in/yaml/v3"
)
type ownedItem struct {
- ID uint32 `yaml:"id"`
- Type uint32 `yaml:"type"`
- Template uint32 `yaml:"template"`
- Quality uint32 `yaml:"quality"`
- Slot uint32 `yaml:"slot"`
- Count uint16 `yaml:"count"`
+ ID uint32
+ Type uint32
+ Template uint32
+ Quality uint32
+ Slot uint32
+ Count uint16
}
type reclaimItem struct {
- Item ownedItem `yaml:"item"`
- AvailableAt time.Time `yaml:"available_at"`
+ Item ownedItem
+ AvailableAt time.Time
}
type playerInventory struct {
- LastID uint32 `yaml:"last_id"`
- Credits uint32 `yaml:"credits,omitempty"`
- Items []ownedItem `yaml:"items"`
- Reclaim []reclaimItem `yaml:"reclaim,omitempty"`
- 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"`
+ LastID uint32
+ Credits uint32
+ Items []ownedItem
+ Reclaim []reclaimItem
+ Containers map[uint32][]ownedItem
+ FirstAidLockedUntil time.Time
+ TreatmentLocks map[uint32]time.Time
+ LearnedNanos []uint32
}
func (inventory playerInventory) validate() error {
@@ -95,11 +93,14 @@ func (inventory playerInventory) validate() error {
}
func (server *server) saveInventory_locked(character *character, inventory playerInventory) error {
- contents, err := yaml.Marshal(inventory)
+ if err := inventory.validate(); err != nil {
+ return err
+ }
+ store, err := server.itemStore_locked(character, inventory)
if err != nil {
return err
}
- if err := writeFileAtomic(fmt.Sprintf("data/players/%d/inventory.yaml", character.id), contents, 0600); err != nil {
+ if err := server.writeItemStore_locked(store); err != nil {
return err
}
character.inventory = inventory
@@ -137,7 +138,7 @@ func (server *server) grantItem_locked(character *character, template uint32) (b
if err := server.saveInventory_locked(character, inventory); err != nil {
return false, err
}
- server.nextItem = inventory.LastID
+ server.nextItem = max(server.nextItem, inventory.LastID)
return true, nil
}
diff --git a/server/inventory_test.go b/server/inventory_test.go
@@ -4,7 +4,6 @@ import (
"encoding/binary"
"encoding/hex"
"net"
- "os"
"reflect"
"testing"
"time"
@@ -166,10 +165,14 @@ func TestInventoryNativeMoveDeleteAndRestart(t *testing.T) {
func newTestInventoryServer(t *testing.T) *server {
t.Helper()
- world := &server{characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), fighting: make(map[uint32]*character)}
+ world := &server{characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), fighting: make(map[uint32]*character), roamingNPCs: make(map[uint32][]*character)}
+ if _, err := world.loadNPCs(); err != nil {
+ t.Fatal(err)
+ }
if err := world.loadUsers(); err != nil {
t.Fatal(err)
}
+ t.Cleanup(func() { world.db.Close() })
return world
}
@@ -178,7 +181,7 @@ func TestInventoryRejectsForeignOccupiedAndStaleRequests(t *testing.T) {
t.Run(scenario, func(t *testing.T) {
t.Chdir(t.TempDir())
world, conn := newCombatWorld()
- os.MkdirAll("data/players/1", 0700)
+
world.characters[1].inventory = playerInventory{LastID: 2, Items: []ownedItem{
{1, 51018, 121567, 1, 64, 1}, {2, 51018, 121567, 1, 65, 1},
}}
@@ -226,22 +229,21 @@ func TestInventoryRejectsForeignOccupiedAndStaleRequests(t *testing.T) {
func TestInventoryFullGrantAndFailedSavePreserveItems(t *testing.T) {
t.Chdir(t.TempDir())
- os.MkdirAll("data/players/1", 0700)
+
world, _ := newCombatWorld()
for range 30 {
if granted, err := world.grantItem_locked(world.characters[1], 121567); err != nil || !granted {
t.Fatalf("grant: %v %v", granted, err)
}
}
- before, err := os.ReadFile("data/players/1/inventory.yaml")
+ before, err := readTestItemStore(world)
if err != nil {
t.Fatal(err)
}
granted, err := world.grantItem_locked(world.characters[1], 121567)
- after, readErr := os.ReadFile("data/players/1/inventory.yaml")
- os.Remove("data/players/1/inventory.yaml")
- os.Mkdir("data/players/1/inventory.yaml", 0700)
+ after, readErr := readTestItemStore(world)
+ failDatabaseWrites(t, world)
saveErr := world.handleInventory(world.clients[1], inventoryDeletePacket(1, 64)[20:])
if granted || err != nil || readErr != nil || string(before) != string(after) || saveErr == nil ||
diff --git a/server/item_database.go b/server/item_database.go
@@ -0,0 +1,294 @@
+package main
+
+import (
+ "database/sql"
+ "fmt"
+ "time"
+)
+
+type itemPlacement struct {
+ Player, Backpack, Corpse, Slot uint32
+ ReclaimAt string
+}
+
+func (server *server) persistItems_locked(store itemStore) error {
+ db, err := server.database()
+ if err != nil {
+ return err
+ }
+ tx, err := db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ // Keep placement separate from item identity, with one location per instance.
+ placements := make(map[uint32]itemPlacement)
+ for id, references := range store.Players {
+ inventory, err := references.inventory(store.Items, store.LastID)
+ if err != nil {
+ return err
+ }
+ for _, item := range inventory.Items {
+ placements[item.ID] = itemPlacement{Player: id, Slot: item.Slot}
+ }
+ for _, entry := range inventory.Reclaim {
+ placements[entry.Item.ID] = itemPlacement{Player: id, Slot: entry.Item.Slot, ReclaimAt: entry.AvailableAt.UTC().Format(time.RFC3339Nano)}
+ }
+ player := *server.characters[id]
+ if store.edited != nil && store.edited.id == id {
+ player = *store.edited
+ }
+ if err := insertPlayer(tx, &player); err != nil {
+ return err
+ }
+ player.inventory = inventory
+ vitals := player.vitals()
+ vitals.Health, vitals.Nano = min(vitals.Health, player.maximumHealth()), min(vitals.Nano, player.maximumNano())
+ if err := updateRecord(tx, "characters", id, vitalColumns, vitals.fields()); err != nil {
+ return err
+ }
+ if _, err := tx.Exec("UPDATE players SET credits=?, first_aid_locked_until=? WHERE id=?", references.Credits, references.FirstAidLockedUntil, id); err != nil {
+ return err
+ }
+ if _, err := tx.Exec("DELETE FROM treatment_locks WHERE player_id=?", id); err != nil {
+ return err
+ }
+ for patient, deadline := range references.TreatmentLocks {
+ if _, err := tx.Exec("INSERT INTO treatment_locks (player_id, patient_id, locked_until) VALUES (?, ?, ?)", id, patient, deadline); err != nil {
+ return err
+ }
+ }
+ if _, err := tx.Exec("DELETE FROM learned_nanos WHERE player_id=?", id); err != nil {
+ return err
+ }
+ for _, nano := range references.LearnedNanos {
+ if _, err := tx.Exec("INSERT INTO learned_nanos (player_id, nano_id) VALUES (?, ?)", id, nano); err != nil {
+ return err
+ }
+ }
+
+ }
+ for id, record := range store.Items {
+ contents, err := referencedItems(record.Slots, 0, 21, store.Items)
+ if err != nil {
+ return err
+ }
+ for _, item := range contents {
+ placements[item.ID] = itemPlacement{Backpack: id, Slot: item.Slot}
+ }
+ }
+ for id, items := range store.Corpses {
+ for _, item := range items {
+ placements[item.ID] = itemPlacement{Corpse: id, Slot: item.Slot}
+ }
+ }
+
+ // Delete changed locations first so swaps respect the unique slot constraints.
+ for id, previous := range server.itemPlacements {
+ if next, exists := placements[id]; !exists || previous != next {
+ if _, err := tx.Exec("DELETE FROM item_locations WHERE item_id = ?", id); err != nil {
+ return err
+ }
+ }
+ }
+ zones := make(map[uint32]bool)
+ for id, client := range server.clients {
+ if client.ready {
+ zones[server.characters[id].playfield] = true
+ }
+ }
+ savedNPCs, err := server.writeNPCs_locked(tx, store, zones)
+ if err != nil {
+ return err
+ }
+ for id, record := range store.Items {
+ previous, exists := server.items[id]
+ if exists && previous.Type == record.Type && previous.Template == record.Template && previous.Quality == record.Quality && previous.Count == record.Count {
+ continue
+ }
+ if _, err := tx.Exec("INSERT INTO items (id, type, template, quality, count) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET type=excluded.type, template=excluded.template, quality=excluded.quality, count=excluded.count", id, record.Type, record.Template, record.Quality, record.Count); err != nil {
+ return err
+ }
+ }
+ for id := range server.items {
+ if _, exists := store.Items[id]; !exists {
+ if _, err := tx.Exec("DELETE FROM items WHERE id = ?", id); err != nil {
+ return err
+ }
+ }
+ }
+ for id, placement := range placements {
+ if previous, exists := server.itemPlacements[id]; exists && previous == placement {
+ continue
+ }
+ var player, backpack, corpse, reclaim any
+ if placement.Player != 0 {
+ player = placement.Player
+ }
+ if placement.Backpack != 0 {
+ backpack = placement.Backpack
+ }
+ if placement.Corpse != 0 {
+ corpse = placement.Corpse
+ }
+ if placement.ReclaimAt != "" {
+ reclaim = placement.ReclaimAt
+ }
+ if _, err := tx.Exec("INSERT INTO item_locations (item_id, player_id, backpack_id, corpse_id, slot, reclaim_at) VALUES (?, ?, ?, ?, ?, ?)", id, player, backpack, corpse, placement.Slot, reclaim); err != nil {
+ return err
+ }
+ }
+ if store.edited != nil {
+ record := store.edited.record()
+ if err := updateRecord(tx, "characters", store.edited.id, characterColumns, record.fields()); err != nil {
+ return err
+ }
+ }
+ started := server.clockStarted
+ if started.IsZero() {
+ started = time.Now()
+ }
+ if _, err := tx.Exec("UPDATE world SET last_item_id=?, last_character_id=max(last_character_id, ?), last_npc_id=?, game_seconds=?, clock_started=?, npcs_initialized=1 WHERE id=1",
+ store.LastID, server.nextCharacter, server.nextNPC, server.gameSeconds, started.UTC().Format(time.RFC3339Nano)); err != nil {
+ return err
+ }
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+ server.itemPlacements, server.savedNPCs, server.npcZones = placements, savedNPCs, zones
+ return nil
+}
+
+func (server *server) readItems() (itemStore, error) {
+ store := itemStore{Items: make(map[uint32]itemRecord), Players: make(map[uint32]inventoryReferences), Corpses: make(map[uint32][]ownedItem)}
+ db, err := server.database()
+ if err != nil {
+ return store, err
+ }
+ if err := db.QueryRow("SELECT last_item_id FROM world WHERE id=1").Scan(&store.LastID); err != nil {
+ return store, err
+ }
+ rows, err := db.Query("SELECT id, type, template, quality, count FROM items")
+ if err != nil {
+ return store, err
+ }
+ for rows.Next() {
+ var id uint32
+ var record itemRecord
+ if err := rows.Scan(&id, &record.Type, &record.Template, &record.Quality, &record.Count); err != nil {
+ rows.Close()
+ return store, err
+ }
+ if (ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality}).isSmallBackpack() {
+ record.Slots = emptyItemSlots(21)
+ }
+ store.Items[id] = record
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ return store, err
+ }
+ rows.Close()
+ rows, err = db.Query("SELECT id, credits, first_aid_locked_until FROM players")
+ if err != nil {
+ return store, err
+ }
+ for rows.Next() {
+ var id uint32
+ references := inventoryReferences{Slots: emptyInventorySlots(), Equipment: emptyEquipmentSlots()}
+ if err := rows.Scan(&id, &references.Credits, &references.FirstAidLockedUntil); err != nil {
+ rows.Close()
+ return store, err
+ }
+ store.Players[id] = references
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ return store, err
+ }
+ rows.Close()
+ rows, err = db.Query("SELECT player_id, patient_id, locked_until FROM treatment_locks")
+ if err != nil {
+ return store, err
+ }
+ for rows.Next() {
+ var id, patient uint32
+ var deadline time.Time
+ if err := rows.Scan(&id, &patient, &deadline); err != nil {
+ rows.Close()
+ return store, err
+ }
+ references := store.Players[id]
+ if references.TreatmentLocks == nil {
+ references.TreatmentLocks = make(map[uint32]time.Time)
+ }
+ references.TreatmentLocks[patient] = deadline
+ store.Players[id] = references
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ return store, err
+ }
+ rows.Close()
+ rows, err = db.Query("SELECT player_id, nano_id FROM learned_nanos ORDER BY player_id, nano_id")
+ if err != nil {
+ return store, err
+ }
+ for rows.Next() {
+ var id, nano uint32
+ if err := rows.Scan(&id, &nano); err != nil {
+ rows.Close()
+ return store, err
+ }
+ references := store.Players[id]
+ references.LearnedNanos = append(references.LearnedNanos, nano)
+ store.Players[id] = references
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ return store, err
+ }
+ rows.Close()
+ rows, err = db.Query("SELECT item_id, player_id, backpack_id, corpse_id, slot, reclaim_at FROM item_locations")
+ if err != nil {
+ return store, err
+ }
+ defer rows.Close()
+ server.itemPlacements = make(map[uint32]itemPlacement)
+ for rows.Next() {
+ var id, slot uint32
+ var player, backpack, corpse sql.NullInt64
+ var reclaim sql.NullString
+ if err := rows.Scan(&id, &player, &backpack, &corpse, &slot, &reclaim); err != nil {
+ return store, err
+ }
+ server.itemPlacements[id] = itemPlacement{uint32(player.Int64), uint32(backpack.Int64), uint32(corpse.Int64), slot, reclaim.String}
+ switch {
+ case player.Valid:
+ references := store.Players[uint32(player.Int64)]
+ if reclaim.Valid {
+ deadline, err := time.Parse(time.RFC3339Nano, reclaim.String)
+ if err != nil {
+ return store, err
+ }
+ references.Reclaim = append(references.Reclaim, reclaimReference{id, fmt.Sprintf("inventory_slot_%d", slot-63), deadline})
+ } else if slot >= 64 {
+ references.Slots[fmt.Sprintf("inventory_slot_%d", slot-63)] = &id
+ } else {
+ references.Equipment[equipmentSlots[slot]] = &id
+ }
+ store.Players[uint32(player.Int64)] = references
+ case backpack.Valid:
+ store.Items[uint32(backpack.Int64)].Slots[fmt.Sprintf("slot_%d", slot+1)] = &id
+ case corpse.Valid:
+ npc := server.characters[uint32(corpse.Int64)]
+ if npc == nil || npc.corpse == nil {
+ return store, fmt.Errorf("item %d belongs to unknown corpse %d", id, corpse.Int64)
+ }
+ record := store.Items[id]
+ store.Corpses[npc.id] = append(store.Corpses[npc.id], ownedItem{id, record.Type, record.Template, record.Quality, slot, record.Count})
+ }
+ }
+ return store, rows.Err()
+}
diff --git a/server/item_pages.go b/server/item_pages.go
@@ -0,0 +1,378 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "cmp"
+ "fmt"
+ "html"
+ "maps"
+ "net/http"
+ "slices"
+ "strconv"
+ "strings"
+
+ "go.yaml.in/yaml/v3"
+)
+
+type itemLocation struct {
+ owner uint32
+ label string
+}
+
+func itemPagination(w http.ResponseWriter, r *http.Request, total int) (int, int) {
+ pages := max(1, (total+499)/500)
+ page, _ := strconv.Atoi(r.FormValue("page"))
+ page = max(1, min(page, pages))
+ fmt.Fprintf(w, "<p>%d matches. Page %d of %d. ", total, page, pages)
+ query := r.URL.Query()
+ for _, link := range []struct {
+ page int
+ text string
+ }{{page - 1, "Previous"}, {page + 1, "Next"}} {
+ if link.page >= 1 && link.page <= pages {
+ query.Set("page", strconv.Itoa(link.page))
+ fmt.Fprintf(w, "<a href='%s?%s'>%s</a> ", html.EscapeString(strings.TrimPrefix(r.URL.Path, "/")), html.EscapeString(query.Encode()), link.text)
+ }
+ }
+ fmt.Fprint(w, "</p>")
+ return (page - 1) * 500, min(page*500, total)
+}
+
+func (server *server) itemLocations_locked() map[uint32]itemLocation {
+ locations := make(map[uint32]itemLocation)
+ for _, player := range server.characters {
+ if player.npc {
+ if player.corpse != nil {
+ for _, item := range player.corpse.items {
+ locations[item.ID] = itemLocation{label: fmt.Sprintf("NPC corpse %d, slot_%d", player.id, item.Slot)}
+ }
+ }
+ continue
+ }
+ for _, item := range player.inventory.Items {
+ label := equipmentSlots[item.Slot]
+ if item.Slot >= 64 {
+ label = fmt.Sprintf("inventory_slot_%d", item.Slot-63)
+ }
+ locations[item.ID] = itemLocation{player.id, label}
+ }
+ for _, entry := range player.inventory.Reclaim {
+ locations[entry.Item.ID] = itemLocation{player.id, "Reclaim"}
+ }
+ }
+ for id, record := range server.items {
+ for slot, contained := range record.Slots {
+ if contained != nil {
+ locations[*contained] = itemLocation{locations[id].owner, fmt.Sprintf("Backpack %d, %s", id, slot)}
+ }
+ }
+ }
+ return locations
+}
+
+func (server *server) itemsPage(w http.ResponseWriter, r *http.Request) {
+ query := strings.ToLower(strings.TrimSpace(r.FormValue("q")))
+ server.mutex.Lock()
+ records := maps.Clone(server.items)
+ locations := server.itemLocations_locked()
+ users := server.users_locked()
+ server.mutex.Unlock()
+ names := make(map[uint32]string)
+ for _, user := range users {
+ names[user.ID] = user.Name
+ }
+ ids := slices.Sorted(maps.Keys(records))
+ ids = slices.DeleteFunc(ids, func(id uint32) bool {
+ name := "Unknown template"
+ if definition := gamedata.ItemTemplates[records[id].Template]; definition != nil {
+ name = definition.Name
+ }
+ owner := "Unassigned"
+ if locations[id].owner != 0 {
+ owner = names[locations[id].owner]
+ }
+ search := fmt.Sprintf("%d %s %d %s %d", id, name, records[id].Template, owner, locations[id].owner)
+ return query != "" && !strings.Contains(strings.ToLower(search), query)
+ })
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ fmt.Fprintf(w, "<!doctype html><html><head><base href='%s'><title>Items</title></head><body><p><a href='control'>Server controls</a></p><h1>Item instances</h1><p><a href='control/items/catalog'>Create item: browse catalog</a></p><form method='get' action='control/items'><label>Filter ID, name, template or owner <input name='q' value='%s'></label> <button>Filter</button></form>", html.EscapeString(server.baseURL), html.EscapeString(r.FormValue("q")))
+ start, end := itemPagination(w, r, len(ids))
+ fmt.Fprint(w, "<table><tr><th>ID</th><th>Name</th><th>QL</th><th>Count</th><th>Owner</th><th>Location</th></tr>")
+ for _, id := range ids[start:end] {
+ record := records[id]
+ definition := gamedata.ItemTemplates[record.Template]
+ name := "Unknown template"
+ if definition != nil {
+ name = definition.Name
+ }
+ location := locations[id]
+ owner := "Unassigned"
+ if location.owner != 0 {
+ owner = names[location.owner]
+ }
+ fmt.Fprintf(w, "<tr><td><a href='control/items/%d'>%d</a></td><td><a href='control/items/%d'>%s</a></td><td>%d</td><td>%d</td><td>", id, id, id, html.EscapeString(name), record.Quality, record.Count)
+ if location.owner == 0 {
+ fmt.Fprint(w, owner)
+ } else {
+ fmt.Fprintf(w, "<a href='control/users/%d'>%s (%d)</a>", location.owner, html.EscapeString(owner), location.owner)
+ }
+ fmt.Fprintf(w, "</td><td>%s</td></tr>", html.EscapeString(location.label))
+ }
+ fmt.Fprint(w, "</table>")
+ itemPagination(w, r, len(ids))
+ fmt.Fprint(w, "</body></html>")
+}
+
+func (server *server) itemCatalogPage(w http.ResponseWriter, r *http.Request) {
+ catalog := strings.ToLower(strings.TrimSpace(r.FormValue("catalog")))
+ var matches []*gamedata.Item
+ for _, definition := range gamedata.ItemTemplates {
+ if definition.Quality != nil && (catalog == "" || strings.Contains(strings.ToLower(definition.Name), catalog) || strconv.FormatUint(uint64(definition.ID), 10) == catalog) {
+ matches = append(matches, definition)
+ }
+ }
+ slices.SortFunc(matches, func(a, b *gamedata.Item) int {
+ if a.Name != b.Name {
+ return strings.Compare(a.Name, b.Name)
+ }
+ return cmp.Compare(a.ID, b.ID)
+ })
+
+ // Filter before paging so every page refers to the same ordered result set.
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ fmt.Fprintf(w, "<!doctype html><html><head><base href='%s'><title>Create item</title></head><body><p><a href='control/items'>Item instances</a></p><h1>Create item</h1><p>Each row is a catalog template at its listed quality. Create makes an unassigned instance.</p><form method='get' action='control/items/catalog'><label>Filter by name or template ID <input name='catalog' value='%s'></label> <button>Filter</button> <a href='control/items/catalog'>Clear filter</a></form>", html.EscapeString(server.baseURL), html.EscapeString(r.FormValue("catalog")))
+ start, end := itemPagination(w, r, len(matches))
+ fmt.Fprint(w, "<form method='post' action='control/items'><table><tr><th>Name</th><th>Template</th><th>QL</th><th></th></tr>")
+ for _, definition := range matches[start:end] {
+ fmt.Fprintf(w, "<tr><td>%s</td><td>%d</td><td>%d</td><td><button name='template' value='%d'>Create</button></td></tr>", html.EscapeString(definition.Name), definition.ID, *definition.Quality, definition.ID)
+ }
+ fmt.Fprint(w, "</table></form>")
+ itemPagination(w, r, len(matches))
+ fmt.Fprint(w, "</body></html>")
+}
+
+func (server *server) createItem(w http.ResponseWriter, r *http.Request) {
+ template, err := strconv.ParseUint(r.FormValue("template"), 10, 32)
+ definition := gamedata.ItemTemplates[uint32(template)]
+ if err != nil || definition == nil || definition.Quality == nil {
+ http.Error(w, "Invalid item template", http.StatusBadRequest)
+ return
+ }
+ server.mutex.Lock()
+ defer server.mutex.Unlock()
+ if server.nextItem == ^uint32(0) {
+ http.Error(w, "Item IDs exhausted", http.StatusBadRequest)
+ return
+ }
+ id := server.nextItem + 1
+ record := recordItem(ownedItem{ID: id, Type: definition.HeaderWords[0], Template: definition.ID, Quality: *definition.Quality, Count: 1}, nil)
+ if (ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality}).isStackable() {
+ record.Count = uint16(itemStat(definition, 212))
+ }
+ // Snapshot all inventories and add an unassigned instance in the same transaction.
+ store, err := server.itemStore_locked(&character{}, playerInventory{})
+ if err == nil {
+ store.LastID = id
+ store.Items[id] = record
+ err = server.writeItemStore_locked(store)
+ }
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ http.Redirect(w, r, fmt.Sprintf("%scontrol/items/%d", server.baseURL, id), http.StatusSeeOther)
+}
+
+func (server *server) itemPage(w http.ResponseWriter, r *http.Request) {
+ id, err := strconv.ParseUint(r.PathValue("item"), 10, 32)
+ if err != nil {
+ http.Error(w, "Invalid item", http.StatusBadRequest)
+ return
+ }
+ server.mutex.Lock()
+ record, exists := server.items[uint32(id)]
+ if !exists {
+ server.mutex.Unlock()
+ http.NotFound(w, r)
+ return
+ }
+ location := server.itemLocations_locked()[uint32(id)]
+ users := server.users_locked()
+ ownerName := ""
+ if location.owner != 0 {
+ ownerName = server.characters[location.owner].name
+ }
+ owner, ownerError := strconv.ParseUint(r.FormValue("owner"), 10, 32)
+ selectedName := ""
+ var selectedInventory playerInventory
+ selected := server.characters[uint32(owner)]
+ if ownerError == nil && selected != nil && !selected.npc {
+ selectedName, selectedInventory = selected.name, selected.inventory
+ }
+ server.mutex.Unlock()
+ contents, err := yaml.Marshal(record)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ definition := gamedata.ItemTemplates[record.Template]
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ fmt.Fprintf(w, "<!doctype html><html><head><base href='%s'><title>Item %d</title></head><body><p><a href='control/items'>All items</a></p><h1>Item %d</h1>", html.EscapeString(server.baseURL), id, id)
+ if definition != nil {
+ fmt.Fprintf(w, "<h2>%s</h2><p>%s</p>", html.EscapeString(definition.Name), html.EscapeString(definition.Description))
+ }
+ if location.owner != 0 {
+ fmt.Fprintf(w, "<p>Owner: <a href='control/users/%d'>%s (%d)</a>. %s.</p>", location.owner, html.EscapeString(ownerName), location.owner, html.EscapeString(location.label))
+ } else {
+ fmt.Fprintf(w, "<p>Unassigned. %s</p>", html.EscapeString(location.label))
+ }
+ if location.label == "" {
+ fmt.Fprintf(w, "<h2>Assign item</h2><form method='get' action='control/items/%d'><label>Player <select name='owner' required>", id)
+ for _, user := range users {
+ fmt.Fprintf(w, "<option value='%d'>%s (%d)</option>", user.ID, html.EscapeString(user.Name), user.ID)
+ }
+ fmt.Fprint(w, "</select></label> <button>Choose player</button></form>")
+ if selectedName != "" {
+ fmt.Fprintf(w, "<form method='post' action='control/items/%d'><input type='hidden' name='action' value='assign'><input type='hidden' name='owner' value='%d'><label>Free slot for %s <select name='destination' required>", id, owner, html.EscapeString(selectedName))
+ item := ownedItem{ID: uint32(id), Type: record.Type, Template: record.Template, Quality: record.Quality, Count: record.Count}
+ for _, destination := range controlItemSlots(selectedInventory, item) {
+ label := equipmentSlots[destination.slot]
+ if destination.bag != 0 {
+ label = fmt.Sprintf("Backpack %d, slot_%d", destination.bag, destination.slot+1)
+ } else if destination.slot >= 64 {
+ label = fmt.Sprintf("inventory_slot_%d", destination.slot-63)
+ }
+ fmt.Fprintf(w, "<option value='%d:%d'>%s</option>", destination.bag, destination.slot, label)
+ }
+ fmt.Fprint(w, "</select></label> <button>Assign item</button></form>")
+ }
+ }
+ fmt.Fprintf(w, "<h2>Instance properties</h2><p>ID %d is fixed. Slots contain instance IDs or null; backpacks have 21 slots. Saving reconnects the owner.</p><form method='post' action='control/items/%d'><textarea name='data' rows='25' cols='80' required>%s</textarea><p><button>Save item</button></p></form>", id, id, html.EscapeString(string(contents)))
+ if definition != nil {
+ catalog, err := yaml.Marshal(definition)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ fmt.Fprintf(w, "<h2>Catalog properties</h2><textarea rows='25' cols='80' readonly>%s</textarea>", html.EscapeString(string(catalog)))
+ }
+ fmt.Fprint(w, "</body></html>")
+}
+
+func (server *server) editItem(w http.ResponseWriter, r *http.Request) {
+ if r.FormValue("action") == "assign" {
+ server.assignItem(w, r)
+ return
+ }
+ id, err := strconv.ParseUint(r.PathValue("item"), 10, 32)
+ var record itemRecord
+ if err == nil {
+ err = decodeUsers(strings.NewReader(r.FormValue("data")), &record)
+ }
+ definition := gamedata.ItemTemplates[record.Template]
+ if err != nil || definition == nil || definition.Quality == nil || record.Type != definition.HeaderWords[0] || record.Quality != *definition.Quality {
+ http.Error(w, "Invalid item properties; use an exact catalog template, type and quality", http.StatusBadRequest)
+ return
+ }
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ if _, exists := server.items[uint32(id)]; !exists {
+ server.mutex.Unlock()
+ http.NotFound(w, r)
+ return
+ }
+ location := server.itemLocations_locked()[uint32(id)]
+ store, err := server.itemStore_locked(&character{}, playerInventory{})
+ if err == nil {
+ store.Items[uint32(id)] = record
+ err = store.validate()
+ }
+ if err != nil {
+ server.mutex.Unlock()
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ if err := server.writeItemStore_locked(store); err != nil {
+ server.mutex.Unlock()
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ if location.owner != 0 {
+ player := server.characters[location.owner]
+ updated := *player
+ updated.inventory, _ = store.Players[location.owner].inventory(store.Items, store.LastID)
+ if err := server.applyUser_locked(player, &updated); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ } else {
+ server.mutex.Unlock()
+ }
+ http.Redirect(w, r, fmt.Sprintf("%scontrol/items/%d", server.baseURL, id), http.StatusSeeOther)
+}
+
+func (server *server) assignItem(w http.ResponseWriter, r *http.Request) {
+ id, idError := strconv.ParseUint(r.PathValue("item"), 10, 32)
+ owner, ownerError := strconv.ParseUint(r.FormValue("owner"), 10, 32)
+ var destination controlItemSlot
+ _, slotError := fmt.Sscanf(r.FormValue("destination"), "%d:%d", &destination.bag, &destination.slot)
+ if idError != nil || ownerError != nil || slotError != nil || fmt.Sprintf("%d:%d", destination.bag, destination.slot) != r.FormValue("destination") {
+ http.Error(w, "Invalid item, owner or slot", http.StatusBadRequest)
+ return
+ }
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ player := server.characters[uint32(owner)]
+ record, exists := server.items[uint32(id)]
+ if !exists || player == nil || player.npc {
+ server.mutex.Unlock()
+ http.NotFound(w, r)
+ return
+ }
+ item := ownedItem{ID: uint32(id), Type: record.Type, Template: record.Template, Quality: record.Quality, Count: record.Count}
+ if server.itemLocations_locked()[uint32(id)].label != "" || !slices.Contains(controlItemSlots(player.inventory, item), destination) {
+ server.mutex.Unlock()
+ http.Error(w, "Item is already assigned or destination is not a free compatible slot", http.StatusBadRequest)
+ return
+ }
+ store, err := server.itemStore_locked(&character{}, playerInventory{})
+ if err == nil {
+ if destination.bag == 0 {
+ references := player.inventory.references()
+ if destination.slot >= 64 {
+ references.Slots[fmt.Sprintf("inventory_slot_%d", destination.slot-63)] = &item.ID
+ } else {
+ references.Equipment[equipmentSlots[destination.slot]] = &item.ID
+ }
+ store.Players[player.id] = references
+ } else {
+ bag := store.Items[destination.bag]
+ bag.Slots = maps.Clone(bag.Slots)
+ bag.Slots[fmt.Sprintf("slot_%d", destination.slot+1)] = &item.ID
+ store.Items[destination.bag] = bag
+ }
+ err = store.validate()
+ }
+ if err != nil {
+ server.mutex.Unlock()
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ updated := *player
+ updated.inventory, err = store.Players[player.id].inventory(store.Items, store.LastID)
+ if err == nil {
+ err = server.writeItemStore_locked(store)
+ }
+ if err != nil {
+ server.mutex.Unlock()
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ if err := server.applyUser_locked(player, &updated); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ http.Redirect(w, r, fmt.Sprintf("%scontrol/items/%d", server.baseURL, id), http.StatusSeeOther)
+}
diff --git a/server/item_store.go b/server/item_store.go
@@ -0,0 +1,314 @@
+package main
+
+import (
+ "cmp"
+ "fmt"
+ "maps"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+)
+
+type itemRecord struct {
+ Type uint32 `yaml:"type"`
+ Template uint32 `yaml:"template"`
+ Quality uint32 `yaml:"quality"`
+ Count uint16 `yaml:"count"`
+ Slots map[string]*uint32 `yaml:"slots,omitempty"`
+}
+
+type reclaimReference struct {
+ ID uint32 `yaml:"id"`
+ Slot string `yaml:"original_slot"`
+ AvailableAt time.Time `yaml:"available_at"`
+}
+
+type inventoryReferences struct {
+ Credits uint32 `yaml:"credits"`
+ Slots map[string]*uint32 `yaml:"slots"`
+ Equipment map[string]*uint32 `yaml:"equipment"`
+ Reclaim []reclaimReference `yaml:"reclaim"`
+ FirstAidLockedUntil time.Time `yaml:"first_aid_locked_until"`
+ TreatmentLocks map[uint32]time.Time `yaml:"treatment_locks"`
+ LearnedNanos []uint32 `yaml:"learned_nanos"`
+}
+
+type itemStore struct {
+ LastID uint32 `yaml:"last_id"`
+ Items map[uint32]itemRecord `yaml:"items"`
+ Players map[uint32]inventoryReferences `yaml:"players"`
+ Corpses map[uint32][]ownedItem
+ edited *character
+ npcSaveAt time.Time
+ flushNPCs bool
+}
+
+func emptyItemSlots(count uint32) map[string]*uint32 {
+ slots := make(map[string]*uint32, count)
+ for slot := uint32(1); slot <= count; slot++ {
+ slots[fmt.Sprintf("slot_%d", slot)] = nil
+ }
+ return slots
+}
+
+func (inventory playerInventory) references() inventoryReferences {
+ result := inventoryReferences{Credits: inventory.Credits, Slots: emptyInventorySlots(), Equipment: emptyEquipmentSlots(),
+ FirstAidLockedUntil: inventory.FirstAidLockedUntil, TreatmentLocks: maps.Clone(inventory.TreatmentLocks), LearnedNanos: slices.Clone(inventory.LearnedNanos)}
+ for _, item := range inventory.Items {
+ if item.Slot >= 64 {
+ result.Slots[fmt.Sprintf("inventory_slot_%d", item.Slot-63)] = &item.ID
+ } else {
+ result.Equipment[equipmentSlots[item.Slot]] = &item.ID
+ }
+ }
+ for _, entry := range inventory.Reclaim {
+ result.Reclaim = append(result.Reclaim, reclaimReference{entry.Item.ID, fmt.Sprintf("inventory_slot_%d", entry.Item.Slot-63), entry.AvailableAt})
+ }
+ return result
+}
+
+func recordItem(item ownedItem, contents []ownedItem) itemRecord {
+ record := itemRecord{Type: item.Type, Template: item.Template, Quality: item.Quality, Count: item.Count}
+ if item.isSmallBackpack() {
+ record.Slots = emptyItemSlots(21)
+ for _, contained := range contents {
+ record.Slots[fmt.Sprintf("slot_%d", contained.Slot+1)] = &contained.ID
+ }
+ }
+ return record
+}
+
+func referencedItems(slots map[string]*uint32, first, count uint32, records map[uint32]itemRecord) ([]ownedItem, error) {
+ var items []ownedItem
+ for name, id := range slots {
+ text, prefix := strings.CutPrefix(name, "slot_")
+ number, err := strconv.ParseUint(text, 10, 32)
+ if !prefix || err != nil || number == 0 || number > uint64(count) || name != fmt.Sprintf("slot_%d", number) {
+ return nil, fmt.Errorf("invalid slot %q", name)
+ }
+ if id == nil {
+ continue
+ }
+ record, exists := records[*id]
+ if !exists {
+ return nil, fmt.Errorf("slot %s references unknown item %d", name, *id)
+ }
+ items = append(items, ownedItem{*id, record.Type, record.Template, record.Quality, first + uint32(number) - 1, record.Count})
+ }
+ // Native state keeps instance order stable while placement is addressed by slot.
+ slices.SortFunc(items, func(a, b ownedItem) int { return cmp.Compare(a.ID, b.ID) })
+ return items, nil
+}
+
+func (references inventoryReferences) inventory(records map[uint32]itemRecord, lastID uint32) (playerInventory, error) {
+ inventory := playerInventory{LastID: lastID, Credits: references.Credits, FirstAidLockedUntil: references.FirstAidLockedUntil,
+ TreatmentLocks: references.TreatmentLocks, LearnedNanos: references.LearnedNanos}
+ // Named character slots map directly to the native placement numbers.
+ names := make(map[string]uint32)
+ for slot, name := range equipmentSlots {
+ names[name] = slot
+ }
+ for slot := uint32(64); slot < 94; slot++ {
+ names[fmt.Sprintf("inventory_slot_%d", slot-63)] = slot
+ }
+ for group, slots := range []map[string]*uint32{references.Slots, references.Equipment} {
+ for name, id := range slots {
+ slot, exists := names[name]
+ if !exists || (slot >= 64) != (group == 0) {
+ return inventory, fmt.Errorf("unknown character slot %q", name)
+ }
+ if id == nil {
+ continue
+ }
+ record, exists := records[*id]
+ if !exists {
+ return inventory, fmt.Errorf("slot %s references unknown item %d", name, *id)
+ }
+ inventory.Items = append(inventory.Items, ownedItem{*id, record.Type, record.Template, record.Quality, slot, record.Count})
+ }
+ }
+ slices.SortFunc(inventory.Items, func(a, b ownedItem) int { return cmp.Compare(a.ID, b.ID) })
+ for _, entry := range references.Reclaim {
+ record, exists := records[entry.ID]
+ if !exists {
+ return inventory, fmt.Errorf("reclaim references unknown item %d", entry.ID)
+ }
+ slot, exists := names[entry.Slot]
+ if !exists || slot < 64 {
+ return inventory, fmt.Errorf("invalid reclaim slot %q", entry.Slot)
+ }
+ inventory.Reclaim = append(inventory.Reclaim, reclaimItem{ownedItem{entry.ID, record.Type, record.Template, record.Quality, slot, record.Count}, entry.AvailableAt})
+ }
+ for _, item := range append(slices.Clone(inventory.Items), reclaimItems(inventory.Reclaim)...) {
+ if !item.isSmallBackpack() {
+ continue
+ }
+ contents, err := referencedItems(records[item.ID].Slots, 0, 21, records)
+ if err != nil {
+ return inventory, err
+ }
+ if len(contents) != 0 {
+ if inventory.Containers == nil {
+ inventory.Containers = make(map[uint32][]ownedItem)
+ }
+ inventory.Containers[item.ID] = contents
+ }
+ }
+ return inventory, inventory.validate()
+}
+
+func reclaimItems(entries []reclaimItem) []ownedItem {
+ items := make([]ownedItem, 0, len(entries))
+ for _, entry := range entries {
+ items = append(items, entry.Item)
+ }
+ return items
+}
+
+func (server *server) itemStore_locked(character *character, inventory playerInventory) (itemStore, error) {
+ store := itemStore{LastID: max(server.nextItem, inventory.LastID), Items: maps.Clone(server.items), Players: make(map[uint32]inventoryReferences), Corpses: make(map[uint32][]ownedItem)}
+ if store.Items == nil {
+ store.Items = make(map[uint32]itemRecord)
+ }
+ // Remove destroyed/consumed instances, retaining newly created unassigned items.
+ for _, item := range character.inventory.allItems() {
+ delete(store.Items, item.ID)
+ }
+ claimed := make(map[uint32]bool)
+ for id, player := range server.characters {
+ if player.npc && player.corpse != nil {
+ store.Corpses[id] = player.corpse.items
+ for _, item := range player.corpse.items {
+ store.Items[item.ID] = recordItem(item, nil)
+ store.LastID = max(store.LastID, item.ID)
+ }
+ }
+ if player.npc || player.savedProfile.ID == 0 && id != character.id {
+ continue
+ }
+ candidate := player.inventory
+ if id == character.id {
+ candidate = inventory
+ }
+ store.Players[id] = candidate.references()
+ store.LastID = max(store.LastID, candidate.LastID)
+ for _, item := range candidate.allItems() {
+ if claimed[item.ID] {
+ return store, fmt.Errorf("item %d is assigned more than once", item.ID)
+ }
+ claimed[item.ID] = true
+ store.Items[item.ID] = recordItem(item, candidate.Containers[item.ID])
+ store.LastID = max(store.LastID, item.ID)
+ }
+ }
+ // Expired corpses destroy their remaining loot; transferred items have new owners.
+ for id, placement := range server.itemPlacements {
+ if placement.Corpse != 0 {
+ if _, present := store.Corpses[placement.Corpse]; !present && !claimed[id] {
+ delete(store.Items, id)
+ }
+ }
+ }
+ return store, nil
+}
+
+func (server *server) writeItemStore_locked(store itemStore) error {
+ if err := store.validate(); err != nil {
+ return err
+ }
+ // Materialize every backpack slot even when an editor submitted only occupied ones.
+ for id, record := range store.Items {
+ if (ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality}).isSmallBackpack() {
+ slots := emptyItemSlots(21)
+ maps.Copy(slots, record.Slots)
+ record.Slots = slots
+ store.Items[id] = record
+ }
+ }
+ if err := server.persistItems_locked(store); err != nil {
+ return err
+ }
+ server.items = store.Items
+ server.nextItem = store.LastID
+ for id, items := range store.Corpses {
+ contents := slices.Clone(items)
+ for index, item := range contents {
+ record := store.Items[item.ID]
+ contents[index] = ownedItem{item.ID, record.Type, record.Template, record.Quality, item.Slot, record.Count}
+ }
+ server.characters[id].corpse.items = contents
+ }
+ return nil
+}
+
+func (server *server) loadItems() error {
+ store, err := server.readItems()
+ if err != nil {
+ return err
+ }
+ if err := store.validate(); err != nil {
+ return err
+ }
+ for id, references := range store.Players {
+ player := server.characters[id]
+ if player == nil || player.npc {
+ return fmt.Errorf("inventory belongs to unknown player %d", id)
+ }
+ inventory, err := references.inventory(store.Items, store.LastID)
+ if err != nil {
+ return err
+ }
+ player.inventory = inventory
+ }
+ server.items, server.nextItem = store.Items, store.LastID
+ for id, items := range store.Corpses {
+ server.characters[id].corpse.items = items
+ }
+ return nil
+}
+
+func (store itemStore) validate() error {
+ claimed := make(map[uint32]bool)
+ for _, items := range store.Corpses {
+ slots := make(map[uint32]bool)
+ for _, item := range items {
+ if claimed[item.ID] || slots[item.Slot] {
+ return fmt.Errorf("corpse item %d is assigned more than once", item.ID)
+ }
+ claimed[item.ID], slots[item.Slot] = true, true
+ }
+ }
+ for id, references := range store.Players {
+ inventory, err := references.inventory(store.Items, store.LastID)
+ if err != nil {
+ return fmt.Errorf("player %d: %w", id, err)
+ }
+ for _, item := range append(slices.Clone(inventory.Items), reclaimItems(inventory.Reclaim)...) {
+ if claimed[item.ID] {
+ return fmt.Errorf("item %d is assigned more than once", item.ID)
+ }
+ claimed[item.ID] = true
+ }
+ }
+ for id, record := range store.Items {
+ item := ownedItem{ID: id, Type: record.Type, Template: record.Template, Quality: record.Quality, Count: record.Count}
+ if id == 0 || id > store.LastID || item.Count == 0 || item.Count != 1 && !item.isStackable() {
+ return fmt.Errorf("invalid item instance %d", id)
+ }
+ if len(record.Slots) != 0 && !item.isSmallBackpack() {
+ return fmt.Errorf("item %d cannot contain slots", id)
+ }
+ contents, err := referencedItems(record.Slots, 0, 21, store.Items)
+ if err != nil {
+ return err
+ }
+ for _, contained := range contents {
+ if contained.Type == 51017 || claimed[contained.ID] {
+ return fmt.Errorf("item %d is nested or assigned more than once", contained.ID)
+ }
+ claimed[contained.ID] = true
+ }
+ }
+ return nil
+}
diff --git a/server/item_store_test.go b/server/item_store_test.go
@@ -0,0 +1,169 @@
+package main
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+func TestItemStoreConsumableChargesKeepIDUntilLastCharge(t *testing.T) {
+ for _, count := range []uint16{1, 2} {
+ t.Run(strconv.Itoa(int(count)), func(t *testing.T) {
+ world, _ := newNanoKitWorld(t)
+ player := world.characters[1]
+ player.inventory.Items[0].Count = count
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+
+ err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:])
+ restarted := newTestInventoryServer(t)
+
+ if err != nil || restarted.nextItem != 1 {
+ t.Fatalf("consumption failed or lost the ID counter: %v", err)
+ }
+ if count == 1 {
+ if len(restarted.items) != 0 || len(restarted.characters[1].inventory.Items) != 0 {
+ t.Fatal("last charge retained an item instance or slot reference")
+ }
+ } else if len(restarted.items) != 1 || restarted.items[1].Count != 1 || restarted.characters[1].inventory.Items[0].ID != 1 {
+ t.Fatal("using a charge changed identity or lost the remaining charge")
+ }
+ })
+ }
+}
+
+func TestItemStoreLoadsUnassignedInstancesWithoutCharacters(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+
+ response := postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ restarted := newServer()
+
+ if response.Code != http.StatusSeeOther || len(restarted.items) != 1 || restarted.items[1].Template != 121567 || restarted.nextItem != 1 {
+ t.Fatalf("unassigned instance was lost: %d %s", response.Code, response.Body.String())
+ }
+}
+
+func TestDatabaseRejectsSharedInstanceReferences(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"First"}})
+ postControlForm(world, "/control/users", url.Values{"name": {"Second"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}"}})
+
+ _, err := world.db.Exec("INSERT INTO item_locations (item_id, player_id, slot) VALUES (1, 2, 65)")
+ _, occupiedError := world.db.Exec("INSERT INTO item_locations (item_id, player_id, slot) VALUES (2, 1, 64)")
+ _, missingError := world.db.Exec("INSERT INTO item_locations (item_id, player_id, slot) VALUES (999, 2, 65)")
+ var owner uint32
+ if err := world.db.QueryRow("SELECT player_id FROM item_locations WHERE item_id=1").Scan(&owner); err != nil {
+ t.Fatal(err)
+ }
+
+ if err == nil || occupiedError == nil || missingError == nil || owner != 1 {
+ t.Fatal("database accepted duplicate ownership, an occupied slot or a missing item")
+ }
+}
+
+func TestControlItemAssignmentOffersOnlyFreeCompatibleSlots(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+
+ page := httptest.NewRecorder()
+ world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/items/2?owner=1", nil))
+ occupied := postControlForm(world, "/control/items/2", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:64"}})
+ placed := postControlForm(world, "/control/items/2", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:65"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"99228"}})
+ bag := postControlForm(world, "/control/items/3", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:66"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ contained := postControlForm(world, "/control/items/4", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"3:20"}})
+ restarted := newServer()
+
+ if page.Code != http.StatusOK || strings.Contains(page.Body.String(), "value='0:64'") || strings.Contains(page.Body.String(), "value='0:6'") || !strings.Contains(page.Body.String(), "value='0:65'") {
+ t.Fatal("assignment form included an occupied or incompatible slot")
+ }
+ if occupied.Code != http.StatusBadRequest || placed.Code != http.StatusSeeOther || bag.Code != http.StatusSeeOther || contained.Code != http.StatusSeeOther {
+ t.Fatalf("assignment status: %d %d %d %d: %s", occupied.Code, placed.Code, bag.Code, contained.Code, contained.Body.String())
+ }
+ if len(restarted.characters[1].inventory.Items) != 3 || restarted.characters[1].inventory.Items[1].ID != 2 || restarted.characters[1].inventory.Items[1].Slot != 65 ||
+ len(restarted.characters[1].inventory.Containers[3]) != 1 || restarted.characters[1].inventory.Containers[3][0] != (ownedItem{4, 51018, 121567, 1, 20, 1}) {
+ t.Fatal("item or backpack assignment did not survive restart")
+ }
+}
+
+func TestControlBackpackRejectsNestedBackpacksAndSharedContents(t *testing.T) {
+ for _, contents := range []string{"slot_1: 1", "slot_1: 2", "slot_1: 3, slot_2: 3", "slot_22: 3"} {
+ t.Run(contents, func(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/items", url.Values{"template": {"99228"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"99228"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+
+ response := postControlForm(world, "/control/items/1", url.Values{"data": {"type: 51017\ntemplate: 99228\nquality: 1\ncount: 1\nslots: {" + contents + "}\n"}})
+
+ if response.Code != http.StatusBadRequest || world.items[1].Slots["slot_1"] != nil || world.nextItem != 3 {
+ t.Fatalf("invalid backpack content accepted: %d %s", response.Code, response.Body.String())
+ }
+ })
+ }
+}
+
+func TestControlConcurrentCreationAllocatesUniqueGlobalIDs(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ responses := make(chan *httptest.ResponseRecorder, 8)
+
+ for range 8 {
+ go func() {
+ responses <- postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ }()
+ }
+ ids := make(map[string]bool)
+ for range 8 {
+ response := <-responses
+ if response.Code != http.StatusSeeOther {
+ t.Fatalf("creation failed: %d %s", response.Code, response.Body.String())
+ }
+ ids[response.Header().Get("Location")] = true
+ }
+ restarted := newServer()
+
+ if len(ids) != 8 || len(restarted.items) != 8 || restarted.nextItem != 8 {
+ t.Fatal("concurrent creation reused an instance ID or lost a committed instance")
+ }
+}
+
+func TestControlConcurrentAssignmentCannotShareOneInstance(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ postControlForm(world, "/control/users", url.Values{"name": {"First"}})
+ postControlForm(world, "/control/users", url.Values{"name": {"Second"}})
+ postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
+ responses := make(chan *httptest.ResponseRecorder, 2)
+
+ for _, owner := range []string{"1", "2"} {
+ go func() {
+ responses <- postControlForm(world, "/control/items/1", url.Values{"action": {"assign"}, "owner": {owner}, "destination": {"0:64"}})
+ }()
+ }
+ statuses := make(map[int]int)
+ for range 2 {
+ statuses[(<-responses).Code]++
+ }
+ restarted := newServer()
+
+ if statuses[http.StatusSeeOther] != 1 || statuses[http.StatusBadRequest] != 1 ||
+ len(restarted.characters[1].inventory.Items)+len(restarted.characters[2].inventory.Items) != 1 || len(restarted.items) != 1 {
+ t.Fatal("one instance was assigned to more than one character")
+ }
+}
diff --git a/server/loot.go b/server/loot.go
@@ -133,10 +133,12 @@ func (server *server) handleLootUse(client *worldClient, body []byte) error {
if credits <= 1000000000-inventory.Credits {
inventory.Credits += credits
}
+ previous := corpse.corpse.credits
+ corpse.corpse.credits = 0
if err := server.saveInventory_locked(player, inventory); err != nil {
+ corpse.corpse.credits = previous
return err
}
- corpse.corpse.credits = 0
// The owner must retain the amount until its deferred Use consumes it locally.
body := binary.BigEndian.AppendUint32(nil, 61)
@@ -197,11 +199,13 @@ func (server *server) takeLoot_locked(client *worldClient, body []byte) error {
inventory := player.inventory
inventory.LastID = max(player.inventory.LastID, item.ID)
inventory.Items = append(slices.Clone(player.inventory.Items), item)
+ previous := corpse.corpse.items
+ corpse.corpse.items = slices.Delete(slices.Clone(previous), index, index+1)
if err := server.saveInventory_locked(player, inventory); err != nil {
+ corpse.corpse.items = previous
return err
}
server.nextItem = max(server.nextItem, item.ID)
- corpse.corpse.items = slices.Delete(corpse.corpse.items, index, index+1)
reply := append([]byte(nil), body[16:]...)
binary.BigEndian.PutUint32(reply[16:20], slot)
return client.send(n3Packet(0x47537a24, 50000, client.id, reply))
diff --git a/server/loot_rights_test.go b/server/loot_rights_test.go
@@ -47,7 +47,7 @@ func TestLootRightsFollowAccumulatedDamageAcrossStoppedAttacks(t *testing.T) {
npc := world.characters[1000000]
npc.health = scenario.health
if scenario.name == "overkill counts remaining health" {
- world.characters[1].stats.MartialArts = 60000
+ world.characters[1].stats.Body.MartialArts = 60000
}
for _, id := range scenario.swings {
diff --git a/server/loot_test.go b/server/loot_test.go
@@ -4,7 +4,6 @@ import (
"bytes"
"encoding/binary"
"encoding/hex"
- "os"
"slices"
"sync"
"testing"
@@ -129,8 +128,8 @@ func TestLootFillsTheLastNativeInventorySlot(t *testing.T) {
len(world.characters[1000000].corpse.items) != 0 {
t.Fatalf("last-slot pickup failed: %v", err)
}
- if item := restarted.characters[1].inventory.Items[29]; item.ID != 17 || item.Slot != 93 {
- t.Fatalf("last-slot ownership changed: %+v", item)
+ if !slices.Contains(restarted.characters[1].inventory.Items, ownedItem{17, 51005, 42640, 1, 93, 1}) {
+ t.Fatalf("last-slot ownership changed: %+v", restarted.characters[1].inventory.Items)
}
}
@@ -160,9 +159,7 @@ func TestLootRejectsUnavailableItemsWithoutChangingOwnership(t *testing.T) {
world.characters[1].inventory.Items = append(world.characters[1].inventory.Items, ownedItem{ID: slot, Slot: slot, Count: 1})
}
case "save failure":
- if err := os.Mkdir("data/players/1/inventory.yaml", 0700); err != nil {
- t.Fatal(err)
- }
+ failDatabaseWrites(t, world)
case "repeat pickup":
if err := world.handleInventory(client, request); err != nil {
t.Fatal(err)
diff --git a/server/main.go b/server/main.go
@@ -12,8 +12,10 @@ import (
"net"
"net/http"
"os"
+ "os/signal"
"path"
"strings"
+ "syscall"
"time"
)
@@ -67,9 +69,29 @@ func main() {
go server.serveWorld()
go server.serveChat()
go server.roamNPCs()
- go server.savePositions()
+ go server.saveWorld()
go server.checkZoneCrossings()
+ // Commit the current simulation before a development-server restart.
+ stopping := make(chan os.Signal, 1)
+ signal.Notify(stopping, os.Interrupt, syscall.SIGTERM)
+ go func() {
+ <-stopping
+ server.updateMutex.Lock()
+ if err := server.flushPositions(time.Now().Add(20 * time.Second)); err != nil {
+ log.Printf("Saving positions on shutdown: %v", err)
+ }
+ if err := server.flushWorld(); err != nil {
+ log.Printf("Saving world on shutdown: %v", err)
+ os.Exit(1)
+ }
+ if err := server.db.Close(); err != nil {
+ log.Printf("Closing world database: %v", err)
+ os.Exit(1)
+ }
+ os.Exit(0)
+ }()
+
// Accept connections on every network interface.
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", server.loginPort))
if err != nil {
diff --git a/server/main_test.go b/server/main_test.go
@@ -115,12 +115,12 @@ func TestTeleportReconnectsSameCharacterInDestination(t *testing.T) {
t.Fatal(err)
}
mux := http.NewServeMux()
- mux.HandleFunc("POST /teleport/{character}", world.teleportPlayer)
+ mux.HandleFunc("POST /control/teleport/{character}", world.teleportPlayer)
response := httptest.NewRecorder()
done := make(chan struct{})
go func() {
- request := httptest.NewRequest("POST", "/teleport/1", strings.NewReader("playfield=800"))
+ request := httptest.NewRequest("POST", "/control/teleport/1", strings.NewReader("playfield=800"))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
mux.ServeHTTP(response, request)
close(done)
@@ -151,7 +151,7 @@ func TestTeleportReconnectsSameCharacterInDestination(t *testing.T) {
if response.Code != http.StatusSeeOther {
t.Fatalf("teleport HTTP status: %d", response.Code)
}
- if !strings.Contains(page.Body.String(), "href='users/1'>Local Explorer 1</a>") {
+ if !strings.Contains(page.Body.String(), "href='control/users/1'>Local Explorer 1</a>") {
t.Fatal("user disappeared while reconnecting")
}
if hex.EncodeToString(teleport[20:36]) != "43197d220000c3500000000100000000" || hex.EncodeToString(teleport[48:72]) != "00000001000000000000000000009c500000032000000000" {
diff --git a/server/map_test.js b/server/map_test.js
@@ -136,8 +136,8 @@ test('panning past queued tiles loads the current view next', async () => {
await new Promise(resolve => setImmediate(resolve));
map.render();
- assert.deepEqual(requests, ['/map-assets/0.png', '/map-assets/1.png', '/map-assets/2.png',
- '/map-assets/3.png', '/map-assets/4.png', '/map-assets/5.png', '/map-assets/19.png']);
+ assert.deepEqual(requests, ['control/map-assets/0.png', 'control/map-assets/1.png', 'control/map-assets/2.png',
+ 'control/map-assets/3.png', 'control/map-assets/4.png', 'control/map-assets/5.png', 'control/map-assets/19.png']);
});
test('unused terrain margins do not request tiles behind polygon clipping', () => {
diff --git a/server/maps.go b/server/maps.go
@@ -12,9 +12,9 @@ import (
func controlMap(w http.ResponseWriter, character uint32) {
fmt.Fprintf(w, "<h2>Map</h2><div data-world-map data-character='%d'><p><label>View <select data-map-view><option value='world'>Rubi-Ka</option></select></label> <label>Find zone <select data-map-find><option value=''>Choose a zone</option></select></label> <button type='button' data-map-zoom='1'>Zoom in</button> <button type='button' data-map-zoom='-1'>Zoom out</button> <button type='button' data-map-center>Center</button></p><canvas data-map-canvas width='1000' height='480' style='width:100%%;height:480px;display:block;touch-action:none;border:1px solid #888' aria-label='World and player map'></canvas><p data-map-status>Loading maps...</p><p data-map-location>Drag to pan; use the mouse wheel or buttons to zoom. Moving player positions are estimated between client reports.</p>", character)
if character != 0 {
- fmt.Fprintf(w, "<form method='post' action='teleport/%d' data-map-teleport><label data-map-zone-choice hidden>Playfield <select name='playfield' required></select></label> <input type='hidden' name='x'><input type='hidden' name='z'><button disabled>Teleport here</button></form>", character)
+ fmt.Fprintf(w, "<form method='post' action='control/teleport/%d' data-map-teleport><label data-map-zone-choice hidden>Playfield <select name='playfield' required></select></label> <input type='hidden' name='x'><input type='hidden' name='z'><button disabled>Teleport here</button></form>", character)
}
- fmt.Fprint(w, "</div><script src='control-map.js' defer></script>")
+ fmt.Fprint(w, "</div><script src='control/control-map.js' defer></script>")
}
func controlMapScript(w http.ResponseWriter, r *http.Request) {
@@ -33,6 +33,7 @@ type mapPlayer struct {
Playfield uint32 `json:"playfield"`
Zone string `json:"zone"`
Position [3]float32 `json:"position"`
+ Rotation [4]float32 `json:"rotation"`
Connected bool `json:"connected"`
Entrance *mapEntrance `json:"entrance,omitempty"`
}
@@ -44,7 +45,7 @@ func (server *server) mapPlayers(w http.ResponseWriter, r *http.Request) {
now := time.Now()
for _, user := range server.users_locked() {
player := mapPlayer{ID: user.ID, Name: user.Name, Playfield: user.Playfield,
- Zone: gamedata.Playfields[user.Playfield].Name, Position: user.Position}
+ Zone: gamedata.Playfields[user.Playfield].Name, Position: user.Position, Rotation: user.Rotation}
if client := server.clients[user.ID]; client != nil {
player.Connected = client.ready
if client.ready && !client.loading && client.forward != 0 {
diff --git a/server/maps_test.go b/server/maps_test.go
@@ -14,7 +14,7 @@ func TestMapTeleportUsesTerrainHeightAndPersists(t *testing.T) {
world := newTestServer(t)
world.newCharacter()
world.terrain[950] = &terrain{width: 1, height: 1, spacing: 128, scale: 1, heights: []byte{0, 64, 0, 64}}
- request := httptest.NewRequest("POST", "/teleport/1", strings.NewReader("playfield=950&x=52&z=56"))
+ request := httptest.NewRequest("POST", "/control/teleport/1", strings.NewReader("playfield=950&x=52&z=56"))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.SetPathValue("character", "1")
response := httptest.NewRecorder()
@@ -35,7 +35,7 @@ func TestMapTeleportRejectsInvalidCoordinatesWithoutChangingPlayer(t *testing.T)
player := world.newCharacter()
before := player.position
world.terrain[950] = &terrain{width: 1, height: 1, spacing: 128, scale: 1, heights: []byte{0, 64, 0, 64}}
- request := httptest.NewRequest("POST", "/teleport/1", strings.NewReader("playfield=950&"+coordinates))
+ request := httptest.NewRequest("POST", "/control/teleport/1", strings.NewReader("playfield=950&"+coordinates))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.SetPathValue("character", "1")
response := httptest.NewRecorder()
@@ -57,7 +57,7 @@ func TestMapPlayersPredictsMovementWithoutChangingSavedPosition(t *testing.T) {
world.clients[player.id] = &worldClient{ready: true, forward: 1, movementStarted: time.Now().Add(-time.Minute)}
response := httptest.NewRecorder()
- world.mapPlayers(response, httptest.NewRequest("GET", "/map-players", nil))
+ world.mapPlayers(response, httptest.NewRequest("GET", "/control/map-players", nil))
var feed struct {
Players []mapPlayer `json:"players"`
}
@@ -65,7 +65,7 @@ func TestMapPlayersPredictsMovementWithoutChangingSavedPosition(t *testing.T) {
t.Fatal(err)
}
- if len(feed.Players) != 1 || !feed.Players[0].Connected || feed.Players[0].Position != [3]float32{52.625, 14.75, 146.875} {
+ if len(feed.Players) != 1 || !feed.Players[0].Connected || feed.Players[0].Position != [3]float32{52.625, 14.75, 146.875} || feed.Players[0].Rotation != [4]float32{0, 0, 0, 1} {
t.Fatalf("player feed: %s", response.Body.String())
}
if player.position != [3]float32{52.625, 14.75, 56.875} {
@@ -82,7 +82,7 @@ func TestMapPlayersIncludesIndoorEntrance(t *testing.T) {
world.zoneLinks["target"][705] = zoneLinks{Doors: []zoneDoor{{ID: 1, Position: [3]float32{100, 20, 200}}}}
response := httptest.NewRecorder()
- world.mapPlayers(response, httptest.NewRequest("GET", "/map-players", nil))
+ world.mapPlayers(response, httptest.NewRequest("GET", "/control/map-players", nil))
if !strings.Contains(response.Body.String(), `"entrance":{"playfield":705,"position":[100,20,200]}`) {
t.Fatalf("missing indoor entrance: %s", response.Body.String())
diff --git a/server/nano_casting.go b/server/nano_casting.go
@@ -36,7 +36,7 @@ func winterBiteCost() uint32 {
func (player *character) winterBiteCastDelay() time.Duration {
// kkr.dll 100651b4..1006526b stores initiative reduction before the final duration.
stats := player.baseStats()
- initiative := stats.effectiveSkill(stats.NanoInitiative, [6]uint32{0, 40, 0, 0, 60, 0})
+ initiative := stats.effectiveSkill(stats.Speed.NanoInitiative, [6]uint32{0, 40, 0, 0, 60, 0})
reduction := float32(float64(initiative) * 0.5)
if initiative > 1200 {
reduction = float32(600 + float64(initiative-1200)*float64(float32(1.0/6)))
@@ -90,8 +90,8 @@ func (server *server) handleNanoCast(client *worldClient, body []byte) error {
stats := player.baseStats()
accepted := binary.BigEndian.Uint32(body[20:24]) == 50000 && binary.BigEndian.Uint32(body[28:32]) == 53019 &&
binary.BigEndian.Uint32(body[32:36]) == 29618 && slices.Contains(player.inventory.LearnedNanos, 29618) &&
- player.profession == 8 && stats.effectiveSkill(stats.PsychologicalModification, [6]uint32{0, 0, 0, 80, 20, 0}) > 8 &&
- stats.effectiveSkill(stats.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7 && player.nano >= winterBiteCost() &&
+ player.profession == 8 && stats.effectiveSkill(stats.NanoAiding.PsychologicalModification, [6]uint32{0, 0, 0, 80, 20, 0}) > 8 &&
+ stats.effectiveSkill(stats.NanoAiding.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7 && player.nano >= winterBiteCost() &&
!player.sitting && !player.driving() && client.forward == 0 && !client.strafing && !client.turning && client.equipment == nil &&
(player.fighting == 0 || now.Before(player.rechargeUntil)) && server.winterBiteTarget_locked(player, target, client, now)
if !accepted {
diff --git a/server/nano_casting_test.go b/server/nano_casting_test.go
@@ -14,8 +14,9 @@ func newNanoCastingWorld() (*server, *combatTestConn) {
player := world.characters[1]
player.profession, player.nano = 8, 30
player.appearance, player.level = 0x315, 1
+ player.rotation[3] = 1
player.stats = defaultCharacterStats()
- player.stats.PsychologicalModification, player.stats.MatterCreation = 7, 6
+ player.stats.NanoAiding.PsychologicalModification, player.stats.NanoAiding.MatterCreation = 7, 6
player.health = player.maximumHealth()
player.inventory.LearnedNanos = []uint32{29618}
return world, conn
@@ -70,9 +71,9 @@ func TestWinterBiteRejectsInvalidAdmission(t *testing.T) {
case "profession":
player.profession = 12
case "psychology":
- player.stats.PsychologicalModification = 6
+ player.stats.NanoAiding.PsychologicalModification = 6
case "creation":
- player.stats.MatterCreation = 5
+ player.stats.NanoAiding.MatterCreation = 5
case "nano":
player.nano = 8
case "sitting":
@@ -220,7 +221,7 @@ func TestWinterBiteCrystalPersistsLearnedProgram(t *testing.T) {
world, _ := newNanoLearningWorld(t)
player := world.characters[1]
player.profession = 8
- player.stats.PsychologicalModification = 7
+ player.stats.NanoAiding.PsychologicalModification = 7
player.inventory.Items = nil
if ok, err := world.grantItem_locked(player, 29625); !ok || err != nil {
t.Fatal(ok, err)
@@ -290,16 +291,16 @@ func TestWinterBiteCrystalRejectsNativeRequirementBoundaries(t *testing.T) {
world, _ := newNanoLearningWorld(t)
player := world.characters[1]
player.profession = 8
- player.stats.PsychologicalModification = 7
+ player.stats.NanoAiding.PsychologicalModification = 7
player.inventory.Items = nil
if ok, err := world.grantItem_locked(player, 29625); !ok || err != nil {
t.Fatal(ok, err)
}
switch scenario {
case "psychology 8":
- player.stats.PsychologicalModification = 6
+ player.stats.NanoAiding.PsychologicalModification = 6
case "creation 7":
- player.stats.MatterCreation = 5
+ player.stats.NanoAiding.MatterCreation = 5
case "profession":
player.profession = 12
}
diff --git a/server/nano_kit.go b/server/nano_kit.go
@@ -16,7 +16,7 @@ func (server *server) useNanoKit_locked(client *worldClient, index int, body []b
accepted := item.Type == 51005 && item.Template == 85366 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 &&
client.selectedTarget[0] == 50000 && target != nil && !target.npc && target.health > 0 &&
target.playfield == player.playfield && server.clients[target.id] != nil && server.clients[target.id].ready && !server.clients[target.id].loading &&
- stats.effectiveSkill(stats.FirstAid, [6]uint32{0, 30, 0, 30, 40, 0}) > 7 && !now.Before(player.inventory.FirstAidLockedUntil)
+ stats.effectiveSkill(stats.NanoAiding.FirstAid, [6]uint32{0, 30, 0, 30, 40, 0}) > 7 && !now.Before(player.inventory.FirstAidLockedUntil)
if accepted {
first := predictedPosition_locked(player, client, now)
second := predictedPosition_locked(target, server.clients[target.id], now)
diff --git a/server/nano_kit_test.go b/server/nano_kit_test.go
@@ -2,9 +2,7 @@ package main
import (
"encoding/binary"
- "os"
"reflect"
- "strings"
"sync"
"testing"
"time"
@@ -17,7 +15,7 @@ func newNanoKitWorld(t *testing.T) (*server, *combatTestConn) {
player := world.characters[1]
player.name, player.level, player.appearance = "Nano Kit Owner", 1, 277
player.rotation[3], player.stats = 1, defaultCharacterStats()
- player.stats.FirstAid = 6
+ player.stats.NanoAiding.FirstAid = 6
player.health = player.maximumHealth() - 20
world.clients[1].selectedTarget = [2]uint32{50000, 1}
if err := world.saveUser_locked(player); err != nil {
@@ -42,7 +40,7 @@ func TestNanoKitUseRestoresNanoConsumesAndPersistsLock(t *testing.T) {
}
if player.inventory.FirstAidLockedUntil.Before(started.Add(40*time.Second)) || player.inventory.FirstAidLockedUntil.After(time.Now().Add(40*time.Second)) ||
!reflect.DeepEqual(restored.inventory.Items, player.inventory.Items) || restored.inventory.LastID != 1 ||
- !restored.inventory.FirstAidLockedUntil.Equal(player.inventory.FirstAidLockedUntil) || restored.stats.FirstAid != 6 {
+ !restored.inventory.FirstAidLockedUntil.Equal(player.inventory.FirstAidLockedUntil) || restored.stats.NanoAiding.FirstAid != 6 {
t.Fatal("charge, skill or lock deadline did not persist together")
}
if len(conn.packets) != 5 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 1 ||
@@ -106,7 +104,7 @@ func TestNanoKitRejectsInvalidUseAndFailedSave(t *testing.T) {
request := backpackUseRequest(1, 64, 1)[20:]
switch scenario {
case "skill 7":
- player.stats.FirstAid = 5
+ player.stats.NanoAiding.FirstAid = 5
case "no target":
client.selectedTarget = [2]uint32{}
case "noncharacter":
@@ -130,8 +128,7 @@ func TestNanoKitRejectsInvalidUseAndFailedSave(t *testing.T) {
case "wrong type":
player.inventory.Items[0].Type = 51022
case "failed save":
- os.Remove("data/players/1/inventory.yaml")
- os.Mkdir("data/players/1/inventory.yaml", 0700)
+ failDatabaseWrites(t, world)
}
before, nano := player.inventory, target.nano
@@ -222,21 +219,3 @@ func TestNanoKitStacksSplitJoinAndRejectDifferentTemplate(t *testing.T) {
t.Fatalf("kit split/join changed template or total: %+v", restored.inventory.Items)
}
}
-
-func TestNanoKitMissingTrainedSkillUsesNativeDefault(t *testing.T) {
- world, _ := newNanoKitWorld(t)
- contents, err := os.ReadFile("data/players/1/player.yaml")
- if err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile("data/players/1/player.yaml", []byte(strings.ReplaceAll(string(contents), " first_aid: 6\n", "")), 0600); err != nil {
- t.Fatal(err)
- }
-
- restored := newTestInventoryServer(t).characters[1]
-
- if restored.stats.FirstAid != 5 || restored.baseStats().effectiveSkill(restored.stats.FirstAid, [6]uint32{0, 30, 0, 30, 40, 0}) != 7 ||
- world.characters[1].stats.FirstAid != 6 {
- t.Fatalf("missing First Aid did not retain base5: %+v", restored.stats)
- }
-}
diff --git a/server/nano_learning.go b/server/nano_learning.go
@@ -11,14 +11,14 @@ func (server *server) learnNano_locked(client *worldClient, index int, body []by
stats := player.baseStats()
program := uint32(43324)
accepted := item.Type == 51005 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 &&
- stats.effectiveSkill(stats.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7
+ stats.effectiveSkill(stats.NanoAiding.MatterCreation, [6]uint32{0, 0, 20, 80, 0, 0}) > 7
if item.Template == 29625 {
program = 29618
accepted = accepted && player.profession == 8 &&
- stats.effectiveSkill(stats.PsychologicalModification, [6]uint32{0, 0, 0, 80, 20, 0}) > 8
+ stats.effectiveSkill(stats.NanoAiding.PsychologicalModification, [6]uint32{0, 0, 0, 80, 20, 0}) > 8
} else {
accepted = accepted && player.profession == 12 &&
- stats.effectiveSkill(stats.TimeAndSpace, [6]uint32{0, 20, 0, 80, 0, 0}) > 7
+ stats.effectiveSkill(stats.NanoAiding.TimeAndSpace, [6]uint32{0, 20, 0, 80, 0, 0}) > 7
}
accepted = accepted && !slices.Contains(player.inventory.LearnedNanos, program)
if accepted {
diff --git a/server/nano_learning_test.go b/server/nano_learning_test.go
@@ -2,10 +2,8 @@ package main
import (
"encoding/binary"
- "os"
"reflect"
"slices"
- "strings"
"sync"
"testing"
)
@@ -16,7 +14,7 @@ func newNanoLearningWorld(t *testing.T) (*server, *combatTestConn) {
world, conn := newCombatWorld()
player := world.newCharacter()
player.profession = 12
- player.stats.MatterCreation, player.stats.TimeAndSpace = 6, 6
+ player.stats.NanoAiding.MatterCreation, player.stats.NanoAiding.TimeAndSpace = 6, 6
if err := world.saveUser_locked(player); err != nil {
t.Fatal(err)
}
@@ -38,7 +36,7 @@ func TestNanoCrystalLearnsAndConsumesOnceAcrossRestart(t *testing.T) {
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 {
+ restored.profession != 12 || restored.stats.NanoAiding.MatterCreation != 6 || restored.stats.NanoAiding.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 ||
@@ -60,9 +58,9 @@ func TestNanoCrystalRejectsInvalidUseWithoutConsumption(t *testing.T) {
request := backpackUseRequest(1, 64, 1)[20:]
switch scenario {
case "Matter Creation 7":
- player.stats.MatterCreation = 5
+ player.stats.NanoAiding.MatterCreation = 5
case "Time and Space 7":
- player.stats.TimeAndSpace = 5
+ player.stats.NanoAiding.TimeAndSpace = 5
case "wrong profession":
player.profession = 1
case "wrong quality":
@@ -82,12 +80,7 @@ func TestNanoCrystalRejectsInvalidUseWithoutConsumption(t *testing.T) {
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)
- }
+ failDatabaseWrites(t, world)
}
before := player.inventory
@@ -151,27 +144,3 @@ func TestNanoCrystalAcceptedUseSurvivesClosedOutput(t *testing.T) {
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", " psychological_modification: 5\n", " nano_initiative: 5\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 || restored.stats.PsychologicalModification != 5 || restored.stats.NanoInitiative != 5 {
- t.Fatalf("older profile lost its native defaults: profession=%d stats=%+v", restored.profession, restored.stats)
- }
-}
diff --git a/server/npcs_test.go b/server/npcs_test.go
@@ -35,10 +35,10 @@ func TestMain(m *testing.M) {
func newTestServer(t *testing.T) *server {
t.Helper()
- if err := os.RemoveAll("data/players"); err != nil {
- t.Fatal(err)
- }
- return newServer()
+ t.Chdir(t.TempDir())
+ world := newServer()
+ t.Cleanup(func() { world.db.Close() })
+ return world
}
func readWorldUpdates(t *testing.T, client net.Conn) [][]byte {
diff --git a/server/overequipping_test.go b/server/overequipping_test.go
@@ -29,9 +29,9 @@ func TestOverequippingAxeChecksEveryRequiredSkill(t *testing.T) {
player := world.characters[1]
world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:])
world.advanceEquipment(world.clients[1].equipment.readyAt)
- player.stats.Strength, player.stats.Agility, player.stats.Stamina = 1, 1, 1
- player.stats.Sense = 1
- player.stats.OneHandEdged, player.stats.Brawling, player.stats.FastAttack = scenario.oneHandEdged, scenario.brawling, scenario.fastAttack
+ player.stats.Abilities.Strength, player.stats.Abilities.Agility, player.stats.Abilities.Stamina = 1, 1, 1
+ player.stats.Abilities.Sense = 1
+ player.stats.Melee.OneHandEdged, player.stats.Body.Brawling, player.stats.Melee.FastAttack = scenario.oneHandEdged, scenario.brawling, scenario.fastAttack
minimum := player.normalDamage(world.characters[1000000], func(uint32) uint32 { return 0 })
maximum := player.normalDamage(world.characters[1000000], func(limit uint32) uint32 { return limit - 1 })
@@ -46,10 +46,10 @@ func TestOverequippingAxeChecksEveryRequiredSkill(t *testing.T) {
func TestOverequippingIncludesTrickleAndRecoversAfterRestart(t *testing.T) {
world, _ := newEquipmentWorld(t)
player := world.characters[1]
- player.stats.OneHandEdged = 398
+ player.stats.Melee.OneHandEdged = 398
world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:])
world.advanceEquipment(world.clients[1].equipment.readyAt)
- player.stats.Brawling = 1 // Two points of ability trickle give effective Brawling 3.
+ player.stats.Body.Brawling = 1 // Two points of ability trickle give effective Brawling 3.
if err := world.saveUser_locked(player); err != nil {
t.Fatal(err)
}
@@ -59,7 +59,7 @@ func TestOverequippingIncludesTrickleAndRecoversAfterRestart(t *testing.T) {
reduced := player.normalDamage(target, maximum)
restarted := newTestInventoryServer(t).characters[1]
persisted := restarted.normalDamage(target, maximum)
- restarted.stats.Brawling = 2 // Effective 4 removes the penalty without re-equipping.
+ restarted.stats.Body.Brawling = 2 // Effective 4 removes the penalty without re-equipping.
restored := restarted.normalDamage(target, maximum)
if err := world.saveUser_locked(restarted); err != nil {
t.Fatal(err)
@@ -77,7 +77,7 @@ func TestOverequippingAdjustedMinimumPrecedesArmor(t *testing.T) {
attacker := &character{stats: defaultCharacterStats(), inventory: playerInventory{
Items: []ownedItem{{1, 51018, 209283, 1, 6, 1}},
}}
- attacker.stats.OneHandEdged, attacker.stats.Brawling = 398, 1
+ attacker.stats.Melee.OneHandEdged, attacker.stats.Body.Brawling = 398, 1
damage := attacker.normalDamage(world.characters[1], func(limit uint32) uint32 {
if limit != 23 {
@@ -96,8 +96,8 @@ func TestOverequippingDoesNotPenalizeFistsAfterUnequip(t *testing.T) {
player := world.characters[1]
world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:])
world.advanceEquipment(world.clients[1].equipment.readyAt)
- player.stats.Strength, player.stats.Stamina = 1, 1
- player.stats.Brawling, player.stats.MartialArts = 0, 398
+ player.stats.Abilities.Strength, player.stats.Abilities.Stamina = 1, 1
+ player.stats.Body.Brawling, player.stats.Body.MartialArts = 0, 398
target := world.characters[1000000]
maximum := func(limit uint32) uint32 { return limit - 1 }
if err := world.saveUser_locked(player); err != nil {
@@ -118,10 +118,10 @@ func TestOverequippingDoesNotPenalizeFistsAfterUnequip(t *testing.T) {
func TestOverequippingNativeDamageMatchesBothObservers(t *testing.T) {
world, owner := newEquipmentWorld(t)
player, target := world.characters[1], world.characters[1000000]
- player.stats.OneHandEdged = 398
+ player.stats.Melee.OneHandEdged = 398
world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 6)[20:])
world.advanceEquipment(world.clients[1].equipment.readyAt)
- player.stats.Brawling = 1
+ player.stats.Body.Brawling = 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, npcs: map[uint32]bool{1000000: true}}
diff --git a/server/profile_database.go b/server/profile_database.go
@@ -0,0 +1,49 @@
+package main
+
+// These columns are shared by players and NPCs; the pointers serve SQL scans and writes.
+const profileColumns = "name, appearance_race, appearance_fatness, appearance_breed, appearance_sex, appearance_side, appearance_head, " +
+ "monster_data, level, profession, improvement_points, abilities_strength, abilities_agility, abilities_stamina, " +
+ "abilities_intelligence, abilities_sense, abilities_psychic, body_martial_arts, body_brawling, body_riposte, body_dimach, " +
+ "body_adventuring, body_swimming, body_body_development, body_nano_pool, melee_one_hand_blunt, melee_one_hand_edged, " +
+ "melee_piercing, melee_two_hand_blunt, melee_two_hand_edged, melee_melee_energy, melee_parry, melee_sneak_attack, " +
+ "melee_multi_melee, melee_fast_attack, misc_weapons_sharp_objects, misc_weapons_grenade, misc_weapons_heavy_weapons, " +
+ "ranged_bow, ranged_pistol, ranged_assault_rifle, ranged_submachine_gun, ranged_shotgun, ranged_rifle, " +
+ "ranged_ranged_energy, ranged_fling_shot, ranged_aimed_shot, ranged_burst, ranged_full_auto, ranged_bow_special_attack, " +
+ "ranged_multi_ranged, speed_melee_initiative, speed_ranged_initiative, speed_physical_initiative, speed_nano_initiative, " +
+ "speed_dodge_ranged, speed_evade_close, speed_duck_explosions, speed_nano_resist, speed_run_speed, " +
+ "trade_repair_mechanical_engineering, trade_repair_electrical_engineering, trade_repair_quantum_field_technology, " +
+ "trade_repair_weapon_smithing, trade_repair_pharmaceutical_technology, trade_repair_nano_programming, " +
+ "trade_repair_computer_literacy, trade_repair_psychology, trade_repair_chemistry, trade_repair_tutoring, " +
+ "nano_aiding_matter_metamorphosis, nano_aiding_biological_metamorphosis, nano_aiding_psychological_modification, " +
+ "nano_aiding_matter_creation, nano_aiding_time_and_space, nano_aiding_sensory_improvement, nano_aiding_first_aid, " +
+ "nano_aiding_treatment, spying_concealment, spying_breaking_and_entering, spying_trap_disarm, spying_perception, " +
+ "navigation_vehicle_air, navigation_vehicle_ground, navigation_vehicle_water, navigation_map_navigation, running, " +
+ "browser_token_hash, resurrection_terminal, implant_changes_until, treatment_locked_until"
+
+func (profile *playerProfile) fields() []any {
+ return []any{
+ &profile.Name, &profile.Appearance.Race, &profile.Appearance.Fatness, &profile.Appearance.Breed,
+ &profile.Appearance.Sex, &profile.Appearance.Side, &profile.Appearance.Head, &profile.MonsterData,
+ &profile.Level, &profile.Profession, &profile.Stats.ImprovementPoints, &profile.Stats.Abilities.Strength,
+ &profile.Stats.Abilities.Agility, &profile.Stats.Abilities.Stamina, &profile.Stats.Abilities.Intelligence, &profile.Stats.Abilities.Sense,
+ &profile.Stats.Abilities.Psychic, &profile.Stats.Body.MartialArts, &profile.Stats.Body.Brawling, &profile.Stats.Body.Riposte,
+ &profile.Stats.Body.Dimach, &profile.Stats.Body.Adventuring, &profile.Stats.Body.Swimming, &profile.Stats.Body.BodyDevelopment,
+ &profile.Stats.Body.NanoPool, &profile.Stats.Melee.OneHandBlunt, &profile.Stats.Melee.OneHandEdged, &profile.Stats.Melee.Piercing,
+ &profile.Stats.Melee.TwoHandBlunt, &profile.Stats.Melee.TwoHandEdged, &profile.Stats.Melee.MeleeEnergy, &profile.Stats.Melee.Parry,
+ &profile.Stats.Melee.SneakAttack, &profile.Stats.Melee.MultiMelee, &profile.Stats.Melee.FastAttack, &profile.Stats.MiscWeapons.SharpObjects,
+ &profile.Stats.MiscWeapons.Grenade, &profile.Stats.MiscWeapons.HeavyWeapons, &profile.Stats.Ranged.Bow, &profile.Stats.Ranged.Pistol,
+ &profile.Stats.Ranged.AssaultRifle, &profile.Stats.Ranged.SubmachineGun, &profile.Stats.Ranged.Shotgun, &profile.Stats.Ranged.Rifle,
+ &profile.Stats.Ranged.RangedEnergy, &profile.Stats.Ranged.FlingShot, &profile.Stats.Ranged.AimedShot, &profile.Stats.Ranged.Burst,
+ &profile.Stats.Ranged.FullAuto, &profile.Stats.Ranged.BowSpecialAttack, &profile.Stats.Ranged.MultiRanged, &profile.Stats.Speed.MeleeInitiative,
+ &profile.Stats.Speed.RangedInitiative, &profile.Stats.Speed.PhysicalInitiative, &profile.Stats.Speed.NanoInitiative, &profile.Stats.Speed.DodgeRanged,
+ &profile.Stats.Speed.EvadeClose, &profile.Stats.Speed.DuckExplosions, &profile.Stats.Speed.NanoResist, &profile.Stats.Speed.RunSpeed,
+ &profile.Stats.TradeRepair.MechanicalEngineering, &profile.Stats.TradeRepair.ElectricalEngineering, &profile.Stats.TradeRepair.QuantumFieldTechnology, &profile.Stats.TradeRepair.WeaponSmithing,
+ &profile.Stats.TradeRepair.PharmaceuticalTechnology, &profile.Stats.TradeRepair.NanoProgramming, &profile.Stats.TradeRepair.ComputerLiteracy, &profile.Stats.TradeRepair.Psychology,
+ &profile.Stats.TradeRepair.Chemistry, &profile.Stats.TradeRepair.Tutoring, &profile.Stats.NanoAiding.MatterMetamorphosis, &profile.Stats.NanoAiding.BiologicalMetamorphosis,
+ &profile.Stats.NanoAiding.PsychologicalModification, &profile.Stats.NanoAiding.MatterCreation, &profile.Stats.NanoAiding.TimeAndSpace, &profile.Stats.NanoAiding.SensoryImprovement,
+ &profile.Stats.NanoAiding.FirstAid, &profile.Stats.NanoAiding.Treatment, &profile.Stats.Spying.Concealment, &profile.Stats.Spying.BreakingAndEntering,
+ &profile.Stats.Spying.TrapDisarm, &profile.Stats.Spying.Perception, &profile.Stats.Navigation.VehicleAir, &profile.Stats.Navigation.VehicleGround,
+ &profile.Stats.Navigation.VehicleWater, &profile.Stats.Navigation.MapNavigation, &profile.Running, &profile.BrowserTokenHash,
+ &profile.ResurrectionTerminal, &profile.ImplantChangesUntil, &profile.TreatmentLockedUntil,
+ }
+}
diff --git a/server/reclaim_test.go b/server/reclaim_test.go
@@ -2,7 +2,6 @@ package main
import (
"encoding/binary"
- "os"
"reflect"
"slices"
"strconv"
@@ -99,12 +98,7 @@ func TestReclaimDeathKeepsEquipmentAndNoDropAtLevelTen(t *testing.T) {
func TestReclaimFailedDeathSaveDoesNotKillOrLoseItems(t *testing.T) {
world, _ := newReclaimWorld(t)
before := world.characters[1].inventory
- 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)
- }
+ failDatabaseWrites(t, world)
defeatReclaimPlayer(t, world)
@@ -147,7 +141,8 @@ func TestReclaimPendingThenPrivatePickupPersistsOnce(t *testing.T) {
}
expected := ownedItem{3, 51005, 42640, 1, 65, 1}
if len(player.inventory.Items) != 3 || player.inventory.Items[2] != expected || len(player.inventory.Reclaim) != 0 || len(conn.packets) != count ||
- !reflect.DeepEqual(player.inventory, restarted.characters[1].inventory) {
+ !reflect.DeepEqual(player.inventory.Items, restarted.characters[1].inventory.Items) ||
+ len(restarted.characters[1].inventory.Reclaim) != 0 || restarted.characters[1].inventory.LastID != player.inventory.LastID {
t.Fatal("pickup lost or duplicated an item")
}
}
@@ -222,8 +217,7 @@ func TestReclaimFullInventoryAndFailedPickupSaveRetainSource(t *testing.T) {
world.grantItem_locked(player, 42640)
}
} else {
- os.Remove("data/players/1/inventory.yaml")
- os.Mkdir("data/players/1/inventory.yaml", 0700)
+ failDatabaseWrites(t, world)
}
world.handleReclaim(client, reclaimRequest(109))
before := player.inventory
@@ -400,7 +394,7 @@ func TestReclaimNativeWireRoundTripAndRestart(t *testing.T) {
}
}
-func TestReclaimLoadRejectsDuplicateAndInvalidIdentities(t *testing.T) {
+func TestReclaimSaveRejectsDuplicateAndInvalidIdentities(t *testing.T) {
for _, scenario := range []string{"owned duplicate", "reclaim duplicate", "above watermark", "equipment slot"} {
t.Run(scenario, func(t *testing.T) {
world, _ := newReclaimWorld(t)
@@ -417,15 +411,11 @@ func TestReclaimLoadRejectsDuplicateAndInvalidIdentities(t *testing.T) {
case "equipment slot":
player.inventory.Reclaim[0].Item.Slot = 6
}
- if err := world.saveInventory_locked(player, player.inventory); err != nil {
- t.Fatal(err)
- }
- reloaded := &server{characters: make(map[uint32]*character)}
- err := reloaded.loadUsers()
+ err := world.saveInventory_locked(player, player.inventory)
if err == nil {
- t.Fatal("invalid reclaim ownership loaded successfully")
+ t.Fatal("invalid reclaim ownership saved successfully")
}
})
}
diff --git a/server/regeneration.go b/server/regeneration.go
@@ -38,8 +38,8 @@ func (server *server) advanceRegeneration(now time.Time) {
if player.fighting != 0 {
percent = 200
}
- healthInterval := uint32(max(1, int((30-float64(stats.Stamina)*float64(float32(1.0/30)))*percent*float64(float32(0.01)))))
- nanoInterval := uint32(max(1, int((30-float64(stats.Psychic)*float64(float32(1.0/30)))*percent*float64(float32(0.01))))) &^ 1
+ healthInterval := uint32(max(1, int((30-float64(stats.Abilities.Stamina)*float64(float32(1.0/30)))*percent*float64(float32(0.01)))))
+ nanoInterval := uint32(max(1, int((30-float64(stats.Abilities.Psychic)*float64(float32(1.0/30)))*percent*float64(float32(0.01))))) &^ 1
rest := uint32(100)
if player.sitting {
rest = 25
@@ -47,7 +47,7 @@ func (server *server) advanceRegeneration(now time.Time) {
healthInterval >>= 1
}
}
- bodyDevelopment := stats.effectiveSkill(stats.BodyDevelopment, [6]uint32{0, 0, 100, 0, 0, 0})
+ bodyDevelopment := stats.effectiveSkill(stats.Body.BodyDevelopment, [6]uint32{0, 0, 100, 0, 0, 0})
breed := player.appearance >> 4 & 7
if client.regenerationSeconds%healthInterval == 0 {
gain := bodyDevelopment/rest + [8]uint32{2, 3, 3, 2, 4, 6, 2, 2}[breed]
diff --git a/server/slots.go b/server/slots.go
@@ -0,0 +1,31 @@
+package main
+
+import "fmt"
+
+// Native equipment positions are shared by both supported game protocols.
+var equipmentSlots = map[uint32]string{
+ 1: "weapons_hud_1", 2: "weapons_hud_3", 3: "weapons_util_1", 4: "weapons_util_2", 5: "weapons_util_3",
+ 6: "weapons_right_hand", 7: "weapons_belt", 8: "weapons_left_hand",
+ 9: "weapons_deck_1", 10: "weapons_deck_2", 11: "weapons_deck_3", 12: "weapons_deck_4", 13: "weapons_deck_5", 14: "weapons_deck_6", 15: "weapons_hud_2",
+ 17: "clothes_neck", 18: "clothes_head", 19: "clothes_back", 20: "clothes_right_shoulder", 21: "clothes_chest",
+ 22: "clothes_right_arm", 23: "clothes_hands", 24: "clothes_left_arm", 25: "clothes_left_shoulder",
+ 26: "clothes_right_wrist", 27: "clothes_legs", 28: "clothes_left_wrist", 29: "clothes_right_finger", 30: "clothes_feet", 31: "clothes_left_finger",
+ 33: "implants_eyes", 34: "implants_head", 35: "implants_ears", 36: "implants_right_arm", 37: "implants_chest", 38: "implants_left_arm",
+ 39: "implants_right_wrist", 40: "implants_waist", 41: "implants_left_wrist", 42: "implants_right_hand", 43: "implants_legs", 44: "implants_left_hand", 45: "implants_feet",
+}
+
+func emptyInventorySlots() map[string]*uint32 {
+ slots := make(map[string]*uint32)
+ for slot := 1; slot <= 30; slot++ {
+ slots[fmt.Sprintf("inventory_slot_%d", slot)] = nil
+ }
+ return slots
+}
+
+func emptyEquipmentSlots() map[string]*uint32 {
+ slots := make(map[string]*uint32)
+ for _, name := range equipmentSlots {
+ slots[name] = nil
+ }
+ return slots
+}
diff --git a/server/stacks_test.go b/server/stacks_test.go
@@ -5,7 +5,6 @@ import (
"encoding/binary"
"encoding/hex"
"net"
- "os"
"reflect"
"slices"
"sync"
@@ -60,7 +59,7 @@ func TestStackJoinSplitRepeatAndRestartPreserveQuantities(t *testing.T) {
packet := targetPacket(fullCharacterPacket(restarted))
expected := []ownedItem{{2, 51005, 152030, 42, 65, 2}, {3, 51005, 152030, 42, 64, 4}}
- if !reflect.DeepEqual(player.inventory.Items, expected) || !reflect.DeepEqual(restarted.inventory, player.inventory) ||
+ if !reflect.DeepEqual(player.inventory.Items, expected) || !reflect.DeepEqual(restarted.inventory.Items, expected) || restarted.inventory.LastID != 3 ||
player.inventory.LastID != 3 || world.nextItem != 3 || len(conn.packets) != 2 {
t.Fatalf("split lost quantities or repeated allocation: %+v restart %+v packets %d", player.inventory, restarted.inventory, len(conn.packets))
}
@@ -166,13 +165,13 @@ func TestStackRejectsInvalidQuantitiesAndOwnership(t *testing.T) {
client.equipment = &equipmentMove{}
}
before := slices.Clone(player.inventory.Items)
- persisted, err := os.ReadFile("data/players/1/inventory.yaml")
+ persisted, err := readTestItemStore(world)
if err != nil {
t.Fatal(err)
}
err = world.handleInventory(client, request)
- after, readErr := os.ReadFile("data/players/1/inventory.yaml")
+ after, readErr := readTestItemStore(world)
if err != nil || readErr != nil || !bytes.Equal(persisted, after) || !reflect.DeepEqual(player.inventory.Items, before) || world.nextItem != 2 {
t.Fatalf("rejected stack request changed ownership/quantity: %+v %v %v", player.inventory, err, readErr)
@@ -221,12 +220,7 @@ func TestStackFullInventoryAndFailedSaveKeepQuantities(t *testing.T) {
if scenario == "join save failure" {
request = stackActionPacket(1, 53, 64, 65)[20:]
}
- 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)
- }
+ failDatabaseWrites(t, world)
}
before, next := slices.Clone(player.inventory.Items), world.nextItem
@@ -319,16 +313,12 @@ func TestStackCountsSurviveCorpseAndReclaimEncoding(t *testing.T) {
}
}
-func TestStackLegacyIndividualInventoriesDefaultToOne(t *testing.T) {
- newStackWorld(t)
- legacy := "last_id: 2\nitems:\n- id: 1\n type: 51018\n template: 121567\n quality: 1\n slot: 64\nreclaim:\n- item:\n id: 2\n type: 51018\n template: 121567\n quality: 1\n slot: 65\n available_at: 2020-01-01T00:00:00Z\n"
- if err := os.WriteFile("data/players/1/inventory.yaml", []byte(legacy), 0600); err != nil {
- t.Fatal(err)
- }
+func TestDatabaseRejectsZeroQuantity(t *testing.T) {
+ world, _ := newStackWorld(t)
- player := newTestInventoryServer(t).characters[1]
+ _, err := world.db.Exec("UPDATE items SET count=0 WHERE id=1")
- if player.inventory.Items[0].Count != 1 || player.inventory.Reclaim[0].Item.Count != 1 {
- t.Fatalf("legacy individuals lost their quantity: %+v", player.inventory)
+ if err == nil {
+ t.Fatal("zero quantity item was accepted")
}
}
diff --git a/server/state.go b/server/state.go
@@ -2,6 +2,7 @@ package main
import (
"ao/server/gamedata"
+ "database/sql"
"encoding/binary"
"fmt"
"log"
@@ -50,6 +51,7 @@ type character struct {
regenerationSeconds uint32
savedProfile playerProfile
savedPosition playerPosition
+ savedVitals playerVitals
nextPositionSave time.Time
}
@@ -91,16 +93,22 @@ func (client *worldClient) send(packet []byte) error {
}
type server struct {
- loginPort int
- worldPort int
- httpPort int
- baseURL string
- mutex sync.Mutex
+ databaseMutex sync.Mutex
+ db *sql.DB
+ savedNPCs map[uint32]savedNPC
+ npcZones map[uint32]bool
+ itemPlacements map[uint32]itemPlacement
+ loginPort int
+ worldPort int
+ httpPort int
+ baseURL string
+ mutex sync.Mutex
// Order entity-state packet batches; acquire before mutex.
updateMutex sync.Mutex
nextCharacter uint32
nextNPC uint32
nextItem uint32
+ items map[uint32]itemRecord
characters map[uint32]*character
roamingNPCs map[uint32][]*character
npcRespawns []npcRespawn
@@ -138,16 +146,22 @@ func newServer() *server {
panic(err)
}
server.zoneLinks = links
- // Create shared live instances from the loaded NPC definitions.
- spawns, err := readNPCSpawns()
+ initialized, err := server.loadNPCs()
if err != nil {
panic(err)
}
- for _, spawn := range spawns {
- server.characters[spawn.id] = &spawn
- server.nextNPC = max(server.nextNPC, spawn.id+1)
- if spawn.roaming != nil {
- server.roamingNPCs[spawn.playfield] = append(server.roamingNPCs[spawn.playfield], &spawn)
+ // Create shared live instances from the loaded NPC definitions.
+ if !initialized {
+ spawns, err := readNPCSpawns()
+ if err != nil {
+ panic(err)
+ }
+ for _, spawn := range spawns {
+ server.characters[spawn.id] = &spawn
+ server.nextNPC = max(server.nextNPC, spawn.id+1)
+ if spawn.roaming != nil {
+ server.roamingNPCs[spawn.playfield] = append(server.roamingNPCs[spawn.playfield], &spawn)
+ }
}
}
if err := server.loadUsers(); err != nil {
diff --git a/server/stats.go b/server/stats.go
@@ -1,38 +1,141 @@
package main
type characterStats struct {
- Strength uint16 `yaml:"strength"`
- Agility uint16 `yaml:"agility"`
- Stamina uint16 `yaml:"stamina"`
- Intelligence uint16 `yaml:"intelligence"`
- Sense uint16 `yaml:"sense"`
- Psychic uint16 `yaml:"psychic"`
- MartialArts uint16 `yaml:"martial_arts"`
- OneHandEdged uint16 `yaml:"one_hand_edged"`
+ ImprovementPoints uint32 `yaml:"improvement_points"`
+ Abilities characterAbilitiesStats `yaml:"abilities"`
+ Body characterBodyStats `yaml:"body"`
+ Melee characterMeleeStats `yaml:"melee"`
+ MiscWeapons characterMiscWeaponsStats `yaml:"misc_weapons"`
+ Ranged characterRangedStats `yaml:"ranged"`
+ Speed characterSpeedStats `yaml:"speed"`
+ TradeRepair characterTradeRepairStats `yaml:"trade_repair"`
+ NanoAiding characterNanoAidingStats `yaml:"nano_aiding"`
+ Spying characterSpyingStats `yaml:"spying"`
+ Navigation characterNavigationStats `yaml:"navigation"`
+}
+
+type characterAbilitiesStats struct {
+ Strength uint16 `yaml:"strength"`
+ Agility uint16 `yaml:"agility"`
+ Stamina uint16 `yaml:"stamina"`
+ Intelligence uint16 `yaml:"intelligence"`
+ Sense uint16 `yaml:"sense"`
+ Psychic uint16 `yaml:"psychic"`
+}
+
+type characterBodyStats struct {
+ MartialArts uint16 `yaml:"martial_arts"`
+ Brawling uint16 `yaml:"brawling"`
+ Riposte uint16 `yaml:"riposte"`
+ Dimach uint16 `yaml:"dimach"`
+ Adventuring uint16 `yaml:"adventuring"`
+ Swimming uint16 `yaml:"swimming"`
+ BodyDevelopment uint16 `yaml:"body_development"`
+ NanoPool uint16 `yaml:"nano_pool"`
+}
+
+type characterMeleeStats struct {
+ OneHandBlunt uint16 `yaml:"one_hand_blunt"`
+ OneHandEdged uint16 `yaml:"one_hand_edged"`
+ Piercing uint16 `yaml:"piercing"`
+ TwoHandBlunt uint16 `yaml:"two_hand_blunt"`
+ TwoHandEdged uint16 `yaml:"two_hand_edged"`
+ MeleeEnergy uint16 `yaml:"melee_energy"`
+ Parry uint16 `yaml:"parry"`
+ SneakAttack uint16 `yaml:"sneak_attack"`
+ MultiMelee uint16 `yaml:"multi_melee"`
+ FastAttack uint16 `yaml:"fast_attack"`
+}
+
+type characterMiscWeaponsStats struct {
+ SharpObjects uint16 `yaml:"sharp_objects"`
+ Grenade uint16 `yaml:"grenade"`
+ HeavyWeapons uint16 `yaml:"heavy_weapons"`
+}
+
+type characterRangedStats struct {
+ Bow uint16 `yaml:"bow"`
+ Pistol uint16 `yaml:"pistol"`
+ AssaultRifle uint16 `yaml:"assault_rifle"`
+ SubmachineGun uint16 `yaml:"submachine_gun"`
+ Shotgun uint16 `yaml:"shotgun"`
+ Rifle uint16 `yaml:"rifle"`
+ RangedEnergy uint16 `yaml:"ranged_energy"`
+ FlingShot uint16 `yaml:"fling_shot"`
+ AimedShot uint16 `yaml:"aimed_shot"`
+ Burst uint16 `yaml:"burst"`
+ FullAuto uint16 `yaml:"full_auto"`
+ BowSpecialAttack uint16 `yaml:"bow_special_attack"`
+ MultiRanged uint16 `yaml:"multi_ranged"`
+}
+
+type characterSpeedStats struct {
MeleeInitiative uint16 `yaml:"melee_initiative"`
- Brawling uint16 `yaml:"brawling"`
- FastAttack uint16 `yaml:"fast_attack"`
+ RangedInitiative uint16 `yaml:"ranged_initiative"`
PhysicalInitiative uint16 `yaml:"physical_initiative"`
- BodyDevelopment uint16 `yaml:"body_development"`
- NanoPool uint16 `yaml:"nano_pool"`
- Treatment uint16 `yaml:"treatment"`
- ComputerLiteracy uint16 `yaml:"computer_literacy"`
- FirstAid uint16 `yaml:"first_aid"`
- VehicleGround uint16 `yaml:"vehicle_ground"`
- VehicleAir uint16 `yaml:"vehicle_air"`
+ NanoInitiative uint16 `yaml:"nano_initiative"`
+ DodgeRanged uint16 `yaml:"dodge_ranged"`
+ EvadeClose uint16 `yaml:"evade_close"`
+ DuckExplosions uint16 `yaml:"duck_explosions"`
+ NanoResist uint16 `yaml:"nano_resist"`
+ RunSpeed uint16 `yaml:"run_speed"`
+}
+type characterTradeRepairStats struct {
+ MechanicalEngineering uint16 `yaml:"mechanical_engineering"`
+ ElectricalEngineering uint16 `yaml:"electrical_engineering"`
+ QuantumFieldTechnology uint16 `yaml:"quantum_field_technology"`
+ WeaponSmithing uint16 `yaml:"weapon_smithing"`
+ PharmaceuticalTechnology uint16 `yaml:"pharmaceutical_technology"`
+ NanoProgramming uint16 `yaml:"nano_programming"`
+ ComputerLiteracy uint16 `yaml:"computer_literacy"`
+ Psychology uint16 `yaml:"psychology"`
+ Chemistry uint16 `yaml:"chemistry"`
+ Tutoring uint16 `yaml:"tutoring"`
+}
+
+type characterNanoAidingStats struct {
+ MatterMetamorphosis uint16 `yaml:"matter_metamorphosis"`
+ BiologicalMetamorphosis uint16 `yaml:"biological_metamorphosis"`
+ PsychologicalModification uint16 `yaml:"psychological_modification"`
MatterCreation uint16 `yaml:"matter_creation"`
TimeAndSpace uint16 `yaml:"time_and_space"`
- PsychologicalModification uint16 `yaml:"psychological_modification"`
- NanoInitiative uint16 `yaml:"nano_initiative"`
+ SensoryImprovement uint16 `yaml:"sensory_improvement"`
+ FirstAid uint16 `yaml:"first_aid"`
+ Treatment uint16 `yaml:"treatment"`
+}
+
+type characterSpyingStats struct {
+ Concealment uint16 `yaml:"concealment"`
+ BreakingAndEntering uint16 `yaml:"breaking_and_entering"`
+ TrapDisarm uint16 `yaml:"trap_disarm"`
+ Perception uint16 `yaml:"perception"`
+}
+
+type characterNavigationStats struct {
+ VehicleAir uint16 `yaml:"vehicle_air"`
+ VehicleGround uint16 `yaml:"vehicle_ground"`
+ VehicleWater uint16 `yaml:"vehicle_water"`
+ MapNavigation uint16 `yaml:"map_navigation"`
}
func defaultCharacterStats() characterStats {
- return characterStats{10, 10, 10, 10, 10, 10, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}
+ return characterStats{
+ ImprovementPoints: 1500,
+ Abilities: characterAbilitiesStats{10, 10, 10, 10, 10, 10},
+ Body: characterBodyStats{5, 5, 5, 5, 5, 5, 5, 5},
+ Melee: characterMeleeStats{5, 5, 5, 5, 5, 5, 5, 5, 5, 5},
+ MiscWeapons: characterMiscWeaponsStats{5, 5, 5},
+ Ranged: characterRangedStats{5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5},
+ Speed: characterSpeedStats{5, 5, 5, 5, 5, 5, 5, 5, 100},
+ TradeRepair: characterTradeRepairStats{5, 5, 5, 5, 5, 5, 5, 5, 5, 5},
+ NanoAiding: characterNanoAidingStats{5, 5, 5, 5, 5, 5, 5, 5},
+ Spying: characterSpyingStats{5, 5, 5, 5},
+ Navigation: characterNavigationStats{5, 5, 5, 5},
+ }
}
func (character *character) baseStats() characterStats {
- // Profiles saved before stats were editable retain their original defaults.
if character.stats == (characterStats{}) {
return defaultCharacterStats()
}
@@ -41,7 +144,7 @@ func (character *character) baseStats() characterStats {
func (stats characterStats) effectiveSkill(base uint16, weights [6]uint32) uint32 {
// kkr.dll FUN_10073fa0, weights from resource type 1000204.
- abilities := [6]uint16{stats.Strength, stats.Agility, stats.Stamina, stats.Intelligence, stats.Sense, stats.Psychic}
+ abilities := [6]uint16{stats.Abilities.Strength, stats.Abilities.Agility, stats.Abilities.Stamina, stats.Abilities.Intelligence, stats.Abilities.Sense, stats.Abilities.Psychic}
var weighted uint32
for index, ability := range abilities {
weighted += uint32(ability) * weights[index]
@@ -49,3 +152,84 @@ func (stats characterStats) effectiveSkill(base uint16, weights [6]uint32) uint3
// Preserve the native float constants before truncating at integer boundaries.
return uint32(base) + uint32(float64(weighted)*float64(float32(0.01))*0.25)
}
+
+func (stats characterStats) nativeStats() [][2]uint32 {
+ return [][2]uint32{
+ {53, stats.ImprovementPoints},
+ {16, uint32(stats.Abilities.Strength)},
+ {17, uint32(stats.Abilities.Agility)},
+ {18, uint32(stats.Abilities.Stamina)},
+ {19, uint32(stats.Abilities.Intelligence)},
+ {20, uint32(stats.Abilities.Sense)},
+ {21, uint32(stats.Abilities.Psychic)},
+ {100, uint32(stats.Body.MartialArts)},
+ {142, uint32(stats.Body.Brawling)},
+ {143, uint32(stats.Body.Riposte)},
+ {144, uint32(stats.Body.Dimach)},
+ {137, uint32(stats.Body.Adventuring)},
+ {138, uint32(stats.Body.Swimming)},
+ {152, uint32(stats.Body.BodyDevelopment)},
+ {132, uint32(stats.Body.NanoPool)},
+ {102, uint32(stats.Melee.OneHandBlunt)},
+ {103, uint32(stats.Melee.OneHandEdged)},
+ {106, uint32(stats.Melee.Piercing)},
+ {107, uint32(stats.Melee.TwoHandBlunt)},
+ {105, uint32(stats.Melee.TwoHandEdged)},
+ {104, uint32(stats.Melee.MeleeEnergy)},
+ {145, uint32(stats.Melee.Parry)},
+ {146, uint32(stats.Melee.SneakAttack)},
+ {101, uint32(stats.Melee.MultiMelee)},
+ {147, uint32(stats.Melee.FastAttack)},
+ {108, uint32(stats.MiscWeapons.SharpObjects)},
+ {109, uint32(stats.MiscWeapons.Grenade)},
+ {110, uint32(stats.MiscWeapons.HeavyWeapons)},
+ {111, uint32(stats.Ranged.Bow)},
+ {112, uint32(stats.Ranged.Pistol)},
+ {116, uint32(stats.Ranged.AssaultRifle)},
+ {114, uint32(stats.Ranged.SubmachineGun)},
+ {115, uint32(stats.Ranged.Shotgun)},
+ {113, uint32(stats.Ranged.Rifle)},
+ {133, uint32(stats.Ranged.RangedEnergy)},
+ {150, uint32(stats.Ranged.FlingShot)},
+ {151, uint32(stats.Ranged.AimedShot)},
+ {148, uint32(stats.Ranged.Burst)},
+ {167, uint32(stats.Ranged.FullAuto)},
+ {121, uint32(stats.Ranged.BowSpecialAttack)},
+ {134, uint32(stats.Ranged.MultiRanged)},
+ {118, uint32(stats.Speed.MeleeInitiative)},
+ {119, uint32(stats.Speed.RangedInitiative)},
+ {120, uint32(stats.Speed.PhysicalInitiative)},
+ {149, uint32(stats.Speed.NanoInitiative)},
+ {154, uint32(stats.Speed.DodgeRanged)},
+ {155, uint32(stats.Speed.EvadeClose)},
+ {153, uint32(stats.Speed.DuckExplosions)},
+ {168, uint32(stats.Speed.NanoResist)},
+ {156, uint32(stats.Speed.RunSpeed)},
+ {125, uint32(stats.TradeRepair.MechanicalEngineering)},
+ {126, uint32(stats.TradeRepair.ElectricalEngineering)},
+ {157, uint32(stats.TradeRepair.QuantumFieldTechnology)},
+ {158, uint32(stats.TradeRepair.WeaponSmithing)},
+ {159, uint32(stats.TradeRepair.PharmaceuticalTechnology)},
+ {160, uint32(stats.TradeRepair.NanoProgramming)},
+ {161, uint32(stats.TradeRepair.ComputerLiteracy)},
+ {162, uint32(stats.TradeRepair.Psychology)},
+ {163, uint32(stats.TradeRepair.Chemistry)},
+ {141, uint32(stats.TradeRepair.Tutoring)},
+ {127, uint32(stats.NanoAiding.MatterMetamorphosis)},
+ {128, uint32(stats.NanoAiding.BiologicalMetamorphosis)},
+ {129, uint32(stats.NanoAiding.PsychologicalModification)},
+ {130, uint32(stats.NanoAiding.MatterCreation)},
+ {131, uint32(stats.NanoAiding.TimeAndSpace)},
+ {122, uint32(stats.NanoAiding.SensoryImprovement)},
+ {123, uint32(stats.NanoAiding.FirstAid)},
+ {124, uint32(stats.NanoAiding.Treatment)},
+ {164, uint32(stats.Spying.Concealment)},
+ {165, uint32(stats.Spying.BreakingAndEntering)},
+ {135, uint32(stats.Spying.TrapDisarm)},
+ {136, uint32(stats.Spying.Perception)},
+ {139, uint32(stats.Navigation.VehicleAir)},
+ {166, uint32(stats.Navigation.VehicleGround)},
+ {117, uint32(stats.Navigation.VehicleWater)},
+ {140, uint32(stats.Navigation.MapNavigation)},
+ }
+}
diff --git a/server/stats_test.go b/server/stats_test.go
@@ -2,18 +2,16 @@ package main
import (
"encoding/binary"
- "os"
- "strings"
"testing"
"time"
)
func TestCharacterStatsDeriveHealthNanoAndAttackTiming(t *testing.T) {
stats := defaultCharacterStats()
- stats.Stamina, stats.Psychic = 60, 120
- stats.BodyDevelopment, stats.NanoPool = 200, 100
- stats.MartialArts, stats.PhysicalInitiative = 100, 100
- stats.OneHandEdged, stats.MeleeInitiative, stats.Brawling, stats.FastAttack = 4, 20, 6, 7
+ stats.Abilities.Stamina, stats.Abilities.Psychic = 60, 120
+ stats.Body.BodyDevelopment, stats.Body.NanoPool = 200, 100
+ stats.Body.MartialArts, stats.Speed.PhysicalInitiative = 100, 100
+ stats.Melee.OneHandEdged, stats.Speed.MeleeInitiative, stats.Body.Brawling, stats.Melee.FastAttack = 4, 20, 6, 7
data := userData{ID: 1, Level: 1, Appearance: 1 << 4, Stats: stats}
player := data.character()
@@ -40,61 +38,31 @@ func TestCharacterStatsPersistThroughProfileEditAndRestart(t *testing.T) {
world := newTestServer(t)
player := world.newCharacter()
destination := player.userData()
- destination.Stats.Stamina = 60
- destination.Stats.BodyDevelopment = 200
- destination.Stats.OneHandEdged, destination.Stats.MeleeInitiative = 0, 120
- destination.Stats.Brawling, destination.Stats.FastAttack = 25, 15
+ destination.Stats.Abilities.Stamina = 60
+ destination.Stats.Body.BodyDevelopment = 200
+ destination.Stats.Melee.OneHandEdged, destination.Stats.Speed.MeleeInitiative = 0, 120
+ destination.Stats.Body.Brawling, destination.Stats.Melee.FastAttack = 25, 15
if err := world.updateUser(destination); err != nil {
t.Fatal(err)
}
restarted := newServer()
- if restarted.characters[1].baseStats().Stamina != 60 || restarted.characters[1].baseStats().BodyDevelopment != 200 || restarted.characters[1].health != 658 {
- t.Fatalf("stats lost across restart: %+v", restarted.characters[1])
+ if restarted.characters[1].baseStats().Abilities.Stamina != 60 || restarted.characters[1].baseStats().Body.BodyDevelopment != 200 ||
+ restarted.characters[1].maximumHealth() != 658 || restarted.characters[1].health != 37 {
+ t.Fatalf("stats or current health lost across restart: %+v", restarted.characters[1])
}
if restarted.characters[1].baseStats() != destination.Stats {
t.Fatalf("trained skills lost across restart: %+v", restarted.characters[1].baseStats())
}
}
-func TestCharacterStatsLoadMissingMeleeSkills(t *testing.T) {
- world := newTestServer(t)
- player := world.newCharacter()
- player.stats.Strength, player.stats.MartialArts = 30, 0
- if err := world.saveUser_locked(player); err != nil {
- t.Fatal(err)
- }
- contents, err := os.ReadFile("data/players/1/player.yaml")
- if err != nil {
- t.Fatal(err)
- }
- profile := string(contents)
- for _, field := range []string{"one_hand_edged", "melee_initiative", "brawling", "fast_attack"} {
- profile = strings.ReplaceAll(profile, " "+field+": 5\n", "")
- }
- if strings.Contains(profile, "one_hand_edged") {
- t.Fatal("fixture still contains the new skills")
- }
- if err := os.WriteFile("data/players/1/player.yaml", []byte(profile), 0600); err != nil {
- t.Fatal(err)
- }
-
- restarted := newServer()
- stats := restarted.characters[1].baseStats()
-
- if stats.Strength != 30 || stats.MartialArts != 0 || stats.OneHandEdged != 5 ||
- stats.MeleeInitiative != 5 || stats.Brawling != 5 || stats.FastAttack != 5 {
- t.Fatalf("older profile skills: %+v", stats)
- }
-}
-
func TestCharacterStatsProfileEditClampsBothResources(t *testing.T) {
t.Chdir(t.TempDir())
world, _, _ := newRegenerationWorld()
world.characters[1].stats = defaultCharacterStats()
- world.characters[1].stats.BodyDevelopment = 300
- world.characters[1].stats.NanoPool = 300
+ world.characters[1].stats.Body.BodyDevelopment = 300
+ world.characters[1].stats.Body.NanoPool = 300
world.characters[1].health, world.characters[1].nano = 500, 500
destination := world.characters[1].userData()
destination.Stats = defaultCharacterStats()
@@ -110,8 +78,8 @@ func TestRegenerationUsesEditedAbilitiesAndBodyDevelopment(t *testing.T) {
for _, sitting := range []bool{false, true} {
world, _, start := newRegenerationWorld()
world.characters[1].stats = defaultCharacterStats()
- world.characters[1].stats.Stamina, world.characters[1].stats.Psychic = 60, 120
- world.characters[1].stats.BodyDevelopment, world.characters[1].stats.NanoPool = 200, 100
+ world.characters[1].stats.Abilities.Stamina, world.characters[1].stats.Abilities.Psychic = 60, 120
+ world.characters[1].stats.Body.BodyDevelopment, world.characters[1].stats.Body.NanoPool = 200, 100
world.characters[1].sitting = sitting
for second := 2; second <= 54; second += 2 {
@@ -131,7 +99,7 @@ func TestRegenerationUsesEditedAbilitiesAndBodyDevelopment(t *testing.T) {
func TestRegenerationHandlesMinimumIntervals(t *testing.T) {
world, _, start := newRegenerationWorld()
world.characters[1].stats = defaultCharacterStats()
- world.characters[1].stats.Stamina, world.characters[1].stats.Psychic = 1000, 1000
+ world.characters[1].stats.Abilities.Stamina, world.characters[1].stats.Abilities.Psychic = 1000, 1000
world.advanceRegeneration(start.Add(2 * time.Second))
@@ -142,7 +110,7 @@ func TestRegenerationHandlesMinimumIntervals(t *testing.T) {
func TestCharacterStatsAttackTimingPreservesNativeFloatRounding(t *testing.T) {
stats := defaultCharacterStats()
- stats.PhysicalInitiative = 385
+ stats.Speed.PhysicalInitiative = 385
player := (&userData{ID: 1, Level: 1, Appearance: 1 << 4, Stats: stats}).character()
player.aggDef = -100
diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go
@@ -45,8 +45,8 @@ func TestTargetCharactersIncludeUnarmedWeapon(t *testing.T) {
func TestTargetCharacterSnapshotPreservesPhysicalAbilities(t *testing.T) {
player := &character{id: 1, name: "Player", appearance: 0x315, level: 1, health: 100}
player.stats = defaultCharacterStats()
- player.stats.Strength, player.stats.Agility, player.stats.Stamina = 11, 22, 33
- player.stats.Intelligence = 44
+ player.stats.Abilities.Strength, player.stats.Abilities.Agility, player.stats.Abilities.Stamina = 11, 22, 33
+ player.stats.Abilities.Intelligence = 44
packet := targetPacket(characterPacket(player))
@@ -98,7 +98,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]) != "000003f1000099b70000003600000001" {
+ if hex.EncodeToString(full[57:73]) != "000003f1000166ab0000003600000001" {
t.Fatalf("target seventh list and first stat: %x", full[57:73])
}
}
@@ -289,7 +289,7 @@ func TestTargetTeleportIncludesFullPlayfieldProxy(t *testing.T) {
binary.BigEndian.PutUint16(ping[2:4], 11)
client.Write(ping)
readPacket(client)
- request := httptest.NewRequest("POST", "/teleport/1", strings.NewReader("playfield=800"))
+ request := httptest.NewRequest("POST", "/control/teleport/1", strings.NewReader("playfield=800"))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.SetPathValue("character", "1")
done := make(chan struct{})
diff --git a/server/treatment_kit.go b/server/treatment_kit.go
@@ -16,7 +16,7 @@ func (server *server) useTreatmentKit_locked(client *worldClient, index int, bod
accepted := item.Type == 51005 && item.Template == 25812 && item.Quality == 1 && item.Slot >= 64 && item.Slot < 94 &&
client.selectedTarget[0] == 50000 && target != nil && !target.npc && target.health > 0 && target.sitting &&
target.playfield == player.playfield && server.clients[target.id] != nil && server.clients[target.id].ready && !server.clients[target.id].loading &&
- stats.effectiveSkill(stats.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 7 && !now.Before(target.treatmentLockedUntil) &&
+ stats.effectiveSkill(stats.NanoAiding.Treatment, [6]uint32{0, 30, 0, 50, 20, 0}) > 7 && !now.Before(target.treatmentLockedUntil) &&
player.fighting == 0 && target.fighting == 0
if accepted {
// InBattle includes incoming combat; its original server producer is unknown.
diff --git a/server/treatment_kit_test.go b/server/treatment_kit_test.go
@@ -2,7 +2,6 @@ package main
import (
"encoding/binary"
- "os"
"reflect"
"sync"
"testing"
@@ -16,7 +15,7 @@ func newTreatmentKitWorld(t *testing.T) (*server, *combatTestConn) {
player := world.characters[1]
player.name, player.level, player.appearance = "Treatment Kit Owner", 1, 277
player.rotation[3], player.stats = 1, defaultCharacterStats()
- player.stats.Treatment, player.health, player.sitting = 6, 1, true
+ player.stats.NanoAiding.Treatment, player.health, player.sitting = 6, 1, true
world.clients[1].selectedTarget = [2]uint32{50000, 1}
if err := world.saveUser_locked(player); err != nil {
t.Fatal(err)
@@ -62,7 +61,7 @@ func TestTreatmentKitRejectsInvalidUseWithoutConsumption(t *testing.T) {
case "standing patient":
target.sitting = false
case "skill 7":
- player.stats.Treatment = 5
+ player.stats.NanoAiding.Treatment = 5
case "patient lock":
target.treatmentLockedUntil = time.Now().Add(time.Minute)
case "healer attacking":
@@ -97,8 +96,7 @@ func TestTreatmentKitRejectsInvalidUseWithoutConsumption(t *testing.T) {
case "foreign owner":
binary.BigEndian.PutUint32(request[8:12], 2)
case "failed save":
- os.Remove("data/players/1/inventory.yaml")
- os.Mkdir("data/players/1/inventory.yaml", 0700)
+ failDatabaseWrites(t, world)
}
before, health, deadline := player.inventory, target.health, target.treatmentLockedUntil
diff --git a/server/users.go b/server/users.go
@@ -2,15 +2,12 @@ package main
import (
"ao/server/gamedata"
- "bytes"
"errors"
"fmt"
"io"
"log"
"math"
"math/rand/v2"
- "os"
- "path/filepath"
"sort"
"strings"
"time"
@@ -20,42 +17,42 @@ import (
// User IDs are stable; each local user currently owns one character.
type userData struct {
- ID uint32 `yaml:"id"`
- Name string `yaml:"name"`
- Playfield uint32 `yaml:"playfield"`
- Position [3]float32 `yaml:"position,flow"`
- Rotation [4]float32 `yaml:"rotation,flow"`
- 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"`
+ ID uint32
+ Name string
+ Playfield uint32
+ Position [3]float32
+ Rotation [4]float32
+ Appearance uint16
+ MonsterData uint32
+ Level uint16
+ Profession uint16
+ Stats characterStats
+ Running bool
+ ReturnDoor *doorOrigin
- BrowserTokenHash string `yaml:"browser_token_hash,omitempty"`
+ BrowserTokenHash string
}
type playerProfile struct {
- ID uint32 `yaml:"id"`
- Name string `yaml:"name"`
- 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"`
- ResurrectionTerminal uint32 `yaml:"resurrection_terminal,omitempty"`
- ImplantChangesUntil time.Time `yaml:"implant_changes_until,omitempty"`
- TreatmentLockedUntil time.Time `yaml:"treatment_locked_until,omitempty"`
+ ID uint32 `yaml:"id"`
+ Name string `yaml:"name"`
+ Appearance appearanceFields `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"`
+ ResurrectionTerminal uint32 `yaml:"resurrection_terminal"`
+ ImplantChangesUntil time.Time `yaml:"implant_changes_until"`
+ TreatmentLockedUntil time.Time `yaml:"treatment_locked_until"`
}
type playerPosition struct {
Playfield uint32 `yaml:"playfield"`
Position [3]float32 `yaml:"position,flow"`
Rotation [4]float32 `yaml:"rotation,flow"`
- ReturnDoor *doorOrigin `yaml:"return_door,omitempty"`
+ ReturnDoor *doorOrigin `yaml:"return_door"`
}
func (character *character) userData() userData {
@@ -92,8 +89,8 @@ func (data userData) validate() error {
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) {
+ if data.Stats != (characterStats{}) && (data.Stats.Abilities.Strength == 0 || data.Stats.Abilities.Agility == 0 || data.Stats.Abilities.Stamina == 0 ||
+ data.Stats.Abilities.Intelligence == 0 || data.Stats.Abilities.Sense == 0 || data.Stats.Abilities.Psychic == 0) {
return fmt.Errorf("abilities must be at least 1")
}
for index, value := range data.Position {
@@ -129,94 +126,14 @@ func decodeUsers(reader io.Reader, value any) error {
}
func (server *server) loadUsers() error {
- files, err := os.ReadDir("data/players")
- if os.IsNotExist(err) {
- return nil
- }
- if err != nil {
+ if err := server.loadPlayers(); err != nil {
return err
}
- for _, file := range files {
- if !file.IsDir() {
- continue
- }
- path := filepath.Join("data/players", file.Name(), "player.yaml")
- contents, err := os.ReadFile(path)
- if err != nil {
- return err
- }
- // Missing trained skills in older profiles retain their starting values.
- profile := playerProfile{Profession: 1, Stats: defaultCharacterStats()}
- if err := decodeUsers(bytes.NewReader(contents), &profile); err != nil {
- return fmt.Errorf("%s: %w", path, err)
- }
- positionPath := filepath.Join("data/players", file.Name(), "position.yaml")
- contents, err = os.ReadFile(positionPath)
- if err != nil {
- return err
- }
- var position playerPosition
- if err := decodeUsers(bytes.NewReader(contents), &position); err != nil {
- return fmt.Errorf("%s: %w", positionPath, err)
- }
- 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,
- }
- if err := user.validate(); err != nil {
- return fmt.Errorf("user %d: %w", user.ID, err)
- }
- if file.Name() != fmt.Sprint(user.ID) {
- return fmt.Errorf("%s: player ID %d does not match directory", path, user.ID)
- }
- if server.characters[user.ID] != nil {
- return fmt.Errorf("duplicate user ID %d", user.ID)
- }
- server.characters[user.ID] = user.character()
- if profile.ResurrectionTerminal != 0 && profile.ResurrectionTerminal != 0xc00202c1 {
- return fmt.Errorf("%s: unknown resurrection terminal", path)
- }
- server.characters[user.ID].resurrectionTerminal = profile.ResurrectionTerminal
- server.characters[user.ID].implantChangesUntil = profile.ImplantChangesUntil
- server.characters[user.ID].treatmentLockedUntil = profile.TreatmentLockedUntil
- inventoryPath := filepath.Join("data/players", file.Name(), "inventory.yaml")
- contents, err = os.ReadFile(inventoryPath)
- if err != nil && !os.IsNotExist(err) {
- return err
- }
- if err == nil {
- if err := decodeUsers(bytes.NewReader(contents), &server.characters[user.ID].inventory); err != nil {
- return fmt.Errorf("%s: %w", inventoryPath, err)
- }
- // Inventories saved before quantities existed contain individual items.
- for index := range server.characters[user.ID].inventory.Items {
- if server.characters[user.ID].inventory.Items[index].Count == 0 {
- server.characters[user.ID].inventory.Items[index].Count = 1
- }
- }
- for index := range server.characters[user.ID].inventory.Reclaim {
- if server.characters[user.ID].inventory.Reclaim[index].Item.Count == 0 {
- server.characters[user.ID].inventory.Reclaim[index].Item.Count = 1
- }
- }
- if err := server.characters[user.ID].inventory.validate(); err != nil {
- return fmt.Errorf("%s: %w", inventoryPath, err)
- }
- server.nextItem = max(server.nextItem, server.characters[user.ID].inventory.LastID)
- }
- server.characters[user.ID].savedProfile = profile
- server.characters[user.ID].savedPosition = position
- server.characters[user.ID].nextPositionSave = time.Now().Add(time.Duration(rand.Int64N(int64(20 * time.Second))))
- if user.ID > server.nextCharacter {
- server.nextCharacter = user.ID
- }
+ if err := server.loadItems(); err != nil {
+ return err
}
- // Patient locks are saved with the healer's consumed inventory charge.
+ // Patient locks belong to the transaction that consumed the healer's charge.
for _, player := range server.characters {
for id, deadline := range player.inventory.TreatmentLocks {
if patient := server.characters[id]; patient != nil && deadline.After(patient.treatmentLockedUntil) {
@@ -239,51 +156,68 @@ 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, max(1, character.profession), character.baseStats(), character.running, character.browserTokenHash, character.resurrectionTerminal,
- character.implantChangesUntil, character.treatmentLockedUntil}
+ profile := character.profile()
if profile == character.savedProfile {
return nil
}
- contents, err := yaml.Marshal(profile)
+ db, err := server.database()
if err != nil {
return err
}
-
- directory := fmt.Sprintf("data/players/%d", character.id)
- if err := os.MkdirAll(directory, 0700); err != nil {
+ tx, err := db.Begin()
+ if err != nil {
return err
}
- // New players need an initial position before their profile becomes visible.
- if character.savedProfile.ID == 0 {
- if err := server.savePosition_locked(character); err != nil {
- return err
- }
+ defer tx.Rollback()
+ if err := insertPlayer(tx, character); err != nil {
+ return err
+ }
+ vitals := character.vitals()
+ if err := updateRecord(tx, "characters", character.id, profileColumns+", "+vitalColumns, append(profile.fields(), vitals.fields()...)); err != nil {
+ return err
}
- if err := writeFileAtomic(directory+"/player.yaml", contents, 0600); err != nil {
+ if _, err := tx.Exec("UPDATE world SET last_character_id = max(last_character_id, ?) WHERE id = 1", character.id); err != nil {
+ return err
+ }
+ if err := tx.Commit(); err != nil {
return err
}
if character.savedProfile.ID == 0 {
+ character.savedPosition = playerPosition{character.playfield, character.position, character.rotation, character.returnDoor}
+ character.savedVitals = character.vitals()
character.nextPositionSave = time.Now().Add(time.Duration(rand.Int64N(int64(20 * time.Second))))
}
character.savedProfile = profile
+ character.savedVitals = character.vitals()
return nil
}
func (server *server) savePosition_locked(character *character) error {
position := playerPosition{character.playfield, character.position, character.rotation, character.returnDoor}
- if position == character.savedPosition {
+ vitals := character.vitals()
+ if position == character.savedPosition && vitals == character.savedVitals {
return nil
}
- contents, err := yaml.Marshal(position)
+ db, err := server.database()
+ if err != nil {
+ return err
+ }
+ tx, err := db.Begin()
if err != nil {
return err
}
- if err := writeFileAtomic(fmt.Sprintf("data/players/%d/position.yaml", character.id), contents, 0600); err != nil {
+ defer tx.Rollback()
+ if err := insertPlayer(tx, character); err != nil {
return err
}
- character.savedPosition = position
+ record := character.record()
+ if err := updateRecord(tx, "characters", character.id, positionColumns+", "+vitalColumns, append(record.Position.fields(), vitals.fields()...)); err != nil {
+ return err
+ }
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+ character.savedPosition, character.savedVitals = position, vitals
return nil
}
@@ -310,10 +244,13 @@ func (server *server) flushPositions(now time.Time) error {
return saveErr
}
-func (server *server) savePositions() {
+func (server *server) saveWorld() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for now := range ticker.C {
+ if err := server.checkpointWorld(now); err != nil {
+ log.Printf("Saving world: %v", err)
+ }
if err := server.flushPositions(now); err != nil {
log.Printf("Saving player positions: %v", err)
}
diff --git a/server/users_test.go b/server/users_test.go
@@ -8,7 +8,6 @@ import (
"net/http"
"net/http/httptest"
"net/url"
- "os"
"strings"
"testing"
"time"
@@ -16,18 +15,19 @@ import (
"go.yaml.in/yaml/v3"
)
-func TestUserFilesAreSeparateAndOnlyUpdatedUserIsRewritten(t *testing.T) {
+func TestUserRowsAreSeparateAndOnlyUpdatedProfileChanges(t *testing.T) {
useNPCData(t, testNPCData())
world := newTestServer(t)
for _, name := range []string{"First", "Second"} {
- request := httptest.NewRequest("POST", "/users", strings.NewReader("name="+name))
- request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- world.createUser(httptest.NewRecorder(), request)
+ postControlForm(world, "/control/users", url.Values{"name": {name}})
}
- before, err := os.Stat("data/players/2/player.yaml")
+ before, err := readTestPlayerRecord(2, "player")
if err != nil {
t.Fatal(err)
}
+ if _, err := world.db.Exec("CREATE TABLE profile_updates (player INTEGER); CREATE TRIGGER profile_update AFTER UPDATE OF name ON characters BEGIN INSERT INTO profile_updates VALUES (NEW.id); END"); err != nil {
+ t.Fatal(err)
+ }
edited := world.characters[1].userData()
edited.Name = "Edited First"
@@ -35,37 +35,15 @@ func TestUserFilesAreSeparateAndOnlyUpdatedUserIsRewritten(t *testing.T) {
t.Fatal(err)
}
restarted := newServer()
-
- files, err := os.ReadDir("data/players")
- if err != nil {
+ defer restarted.db.Close()
+ after, err := readTestPlayerRecord(2, "player")
+ var count, id int
+ if err := world.db.QueryRow("SELECT count(*), player FROM profile_updates").Scan(&count, &id); err != nil {
t.Fatal(err)
}
- if len(files) != 2 || files[0].Name() != "1" || files[1].Name() != "2" || !files[0].IsDir() || !files[1].IsDir() {
- t.Fatalf("user files: %v", files)
- }
- for _, expected := range []struct {
- path string
- id uint32
- name string
- }{{"data/players/1/player.yaml", 1, "Edited First"}, {"data/players/2/player.yaml", 2, "Second"}} {
- contents, err := os.ReadFile(expected.path)
- if err != nil {
- t.Fatal(err)
- }
- var user userData
- if err := yaml.Unmarshal(contents, &user); err != nil {
- t.Fatal(err)
- }
- if user.ID != expected.id || user.Name != expected.name || restarted.characters[expected.id].name != expected.name {
- t.Fatalf("saved user in %s: %+v", expected.path, user)
- }
- }
- after, err := os.Stat("data/players/2/player.yaml")
- if err != nil {
- t.Fatal(err)
- }
- if !os.SameFile(before, after) {
- t.Fatal("editing the first user rewrote the second user's file")
+
+ if err != nil || !bytes.Equal(before, after) || count != 1 || id != 1 || restarted.characters[1].name != "Edited First" || restarted.characters[2].name != "Second" {
+ t.Fatalf("profiles did not update independently: %d %d %v", count, id, err)
}
}
@@ -73,26 +51,23 @@ func TestUserCreationEditingAndOfflineTeleportSurviveRestart(t *testing.T) {
useNPCData(t, testNPCData())
world := newTestServer(t)
mux := http.NewServeMux()
- mux.HandleFunc("POST /users", world.createUser)
- mux.HandleFunc("POST /users/{character}", world.editUser)
- mux.HandleFunc("POST /teleport/{character}", world.teleportPlayer)
- creation := httptest.NewRequest("POST", "/users", strings.NewReader("name=Explorer"))
+ mux.HandleFunc("POST /control/users", world.createUser)
+ mux.HandleFunc("POST /control/users/{character}", world.editUser)
+ mux.HandleFunc("POST /control/teleport/{character}", world.teleportPlayer)
+ creation := httptest.NewRequest("POST", "/control/users", strings.NewReader("name=Explorer"))
creation.Header.Set("Content-Type", "application/x-www-form-urlencoded")
created := httptest.NewRecorder()
data := `id: 1
name: Edited Explorer
-playfield: 950
-position: [53, 14, 60]
-rotation: [0, 0, 0, 1]
-appearance: 789
+appearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}
monster_data: 0
level: 7
running: true
`
- edition := httptest.NewRequest("POST", "/users/1", strings.NewReader(url.Values{"data": {data}}.Encode()))
+ edition := httptest.NewRequest("POST", "/control/users/1", strings.NewReader(url.Values{"data": {data}}.Encode()))
edition.Header.Set("Content-Type", "application/x-www-form-urlencoded")
edited := httptest.NewRecorder()
- teleport := httptest.NewRequest("POST", "/teleport/1", strings.NewReader("playfield=800"))
+ teleport := httptest.NewRequest("POST", "/control/teleport/1", strings.NewReader("playfield=800"))
teleport.Header.Set("Content-Type", "application/x-www-form-urlencoded")
teleported := httptest.NewRecorder()
@@ -107,7 +82,7 @@ running: true
restarted.controlPage(page, httptest.NewRequest("GET", "/control", nil))
for _, response := range []*httptest.ResponseRecorder{created, edited, teleported} {
- if response.Code != http.StatusSeeOther || response.Header().Get("Location") != "/users/1" {
+ if response.Code != http.StatusSeeOther || response.Header().Get("Location") != "/control/users/1" {
t.Fatalf("user form response: %d %s", response.Code, response.Body.String())
}
}
@@ -115,10 +90,10 @@ running: true
if player.name != "Edited Explorer" || player.playfield != 800 || player.level != 7 || player.appearance != 789 || player.position != [3]float32{679.625, 74.75, 537.875} || !player.running {
t.Fatalf("saved character: %+v", player)
}
- if restarted.nextCharacter != 1 || !strings.Contains(page.Body.String(), "href='users/1'>Edited Explorer</a>") || !strings.Contains(page.Body.String(), "Offline") {
+ if restarted.nextCharacter != 1 || !strings.Contains(page.Body.String(), "href='control/users/1'>Edited Explorer</a>") || !strings.Contains(page.Body.String(), "Offline") {
t.Fatalf("offline user disappeared: %s", page.Body.String())
}
- contents, err := os.ReadFile("data/players/1/player.yaml")
+ contents, err := readTestPlayerRecord(1, "player")
if err != nil {
t.Fatal(err)
}
@@ -194,20 +169,20 @@ func TestMovementModePersistsAndIsSuppliedOnReconnect(t *testing.T) {
func TestUserEditorRejectsUnknownFieldsWithoutChangingSavedData(t *testing.T) {
useNPCData(t, testNPCData())
world := newTestServer(t)
- creation := httptest.NewRequest("POST", "/users", strings.NewReader("name=Explorer"))
+ creation := httptest.NewRequest("POST", "/control/users", strings.NewReader("name=Explorer"))
creation.Header.Set("Content-Type", "application/x-www-form-urlencoded")
world.createUser(httptest.NewRecorder(), creation)
- before, err := os.ReadFile("data/players/1/player.yaml")
+ before, err := readTestPlayerRecord(1, "player")
if err != nil {
t.Fatal(err)
}
- request := httptest.NewRequest("POST", "/users/1", strings.NewReader(url.Values{"data": {"id: 1\nname: Changed\nlevle: 7\n"}}.Encode()))
+ request := httptest.NewRequest("POST", "/control/users/1", strings.NewReader(url.Values{"data": {"id: 1\nname: Changed\nlevle: 7\n"}}.Encode()))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.SetPathValue("character", "1")
response := httptest.NewRecorder()
world.editUser(response, request)
- after, err := os.ReadFile("data/players/1/player.yaml")
+ after, err := readTestPlayerRecord(1, "player")
if err != nil {
t.Fatal(err)
}
@@ -221,7 +196,7 @@ func TestLauncherListsSavedUsersAndSelectsRequestedCharacter(t *testing.T) {
useNPCData(t, testNPCData())
world := newTestServer(t)
for _, name := range []string{"First", "Second"} {
- request := httptest.NewRequest("POST", "/users", strings.NewReader("name="+name))
+ request := httptest.NewRequest("POST", "/control/users", strings.NewReader("name="+name))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
world.createUser(httptest.NewRecorder(), request)
}
@@ -253,11 +228,15 @@ func TestLauncherListsSavedUsersAndSelectsRequestedCharacter(t *testing.T) {
func TestEditedCharacterLevelAndPositionReachWorldClient(t *testing.T) {
useNPCData(t, testNPCData())
world := newTestServer(t)
- request := httptest.NewRequest("POST", "/users", strings.NewReader("name=Explorer"))
+ request := httptest.NewRequest("POST", "/control/users", strings.NewReader("name=Explorer"))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
world.createUser(httptest.NewRecorder(), request)
- data := "id: 1\nname: Explorer\nplayfield: 950\nposition: [53, 14, 60]\nrotation: [0, 0, 0, 1]\nappearance: 789\nmonster_data: 0\nlevel: 7\n"
- request = httptest.NewRequest("POST", "/users/1", strings.NewReader(url.Values{"data": {data}}.Encode()))
+ data := "id: 1\nname: Explorer\nappearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}\nmonster_data: 0\nlevel: 7\n"
+ request = httptest.NewRequest("POST", "/control/users/1", strings.NewReader(url.Values{"data": {data}}.Encode()))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ request.SetPathValue("character", "1")
+ world.editUser(httptest.NewRecorder(), request)
+ request = httptest.NewRequest("POST", "/control/users/1", strings.NewReader(url.Values{"data": {"playfield: 950\nposition: [53, 14, 60]\nrotation: [0, 0, 0, 1]\n"}}.Encode()))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.SetPathValue("character", "1")
world.editUser(httptest.NewRecorder(), request)
@@ -292,10 +271,10 @@ func TestEditedCharacterLevelAndPositionReachWorldClient(t *testing.T) {
func TestPlayerDirectoryPreservesProfileAndChatAfterRestart(t *testing.T) {
useNPCData(t, testNPCData())
world := newTestServer(t)
- request := httptest.NewRequest("POST", "/users", strings.NewReader("name=Explorer"))
+ request := httptest.NewRequest("POST", "/control/users", strings.NewReader("name=Explorer"))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
world.createUser(httptest.NewRecorder(), request)
- profile, err := os.ReadFile("data/players/1/player.yaml")
+ profile, err := readTestPlayerRecord(1, "player")
if err != nil {
t.Fatal(err)
}
@@ -307,7 +286,7 @@ func TestPlayerDirectoryPreservesProfileAndChatAfterRestart(t *testing.T) {
peer := loginChatTest(t, restarted, 1)
kind, body, err := readChatPacket(peer)
message, valid := readChatString(&body)
- savedProfile, readErr := os.ReadFile("data/players/1/player.yaml")
+ savedProfile, readErr := readTestPlayerRecord(1, "player")
if err != nil || kind != 36 || !valid || !strings.Contains(message, "[say] Explorer: saved under player ID") {
t.Fatalf("chat history after restart: %d %q %v", kind, message, err)
@@ -315,8 +294,8 @@ func TestPlayerDirectoryPreservesProfileAndChatAfterRestart(t *testing.T) {
if readErr != nil || !bytes.Equal(profile, savedProfile) || restarted.characters[1].id != 1 {
t.Fatalf("chat changed the saved player profile: %q %v", savedProfile, readErr)
}
- if _, err := os.Stat("data/players/1/chat.ndjson"); err != nil {
- t.Fatal(err)
+ if history, err := restarted.chatHistory_locked(1); err != nil || len(history) != 1 {
+ t.Fatalf("saved chat: %v %v", history, err)
}
}
@@ -324,15 +303,15 @@ func TestPositionUpdatesDoNotRewritePlayerProfile(t *testing.T) {
useNPCData(t, testNPCData())
world := newTestServer(t)
world.browserLaunch(httptest.NewRecorder(), httptest.NewRequest("POST", "/browser-launch", nil))
- profile, err := os.ReadFile("data/players/1/player.yaml")
+ profile, err := readTestPlayerRecord(1, "player")
if err != nil {
t.Fatal(err)
}
- before, err := os.Stat("data/players/1/player.yaml")
+ before, err := readTestPlayerRecord(1, "player")
if err != nil {
t.Fatal(err)
}
- positionBefore, err := os.Stat("data/players/1/position.yaml")
+ positionBefore, err := readTestPlayerRecord(1, "position")
if err != nil {
t.Fatal(err)
}
@@ -343,37 +322,37 @@ func TestPositionUpdatesDoNotRewritePlayerProfile(t *testing.T) {
if err := world.updateUser(destination); err != nil {
t.Fatal(err)
}
- positionPending, err := os.Stat("data/players/1/position.yaml")
+ positionPending, err := readTestPlayerRecord(1, "position")
if err != nil {
t.Fatal(err)
}
- if !os.SameFile(positionBefore, positionPending) || world.characters[1].position != destination.Position {
- t.Fatal("movement must update memory without writing the position file")
+ if !bytes.Equal(positionBefore, positionPending) || world.characters[1].position != destination.Position {
+ t.Fatal("movement must update memory without writing the position record")
}
if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil {
t.Fatal(err)
}
- positionFlushed, err := os.Stat("data/players/1/position.yaml")
+ positionFlushed, err := readTestPlayerRecord(1, "position")
if err != nil {
t.Fatal(err)
}
if err := world.flushPositions(time.Now().Add(40 * time.Second)); err != nil {
t.Fatal(err)
}
- positionUnchanged, err := os.Stat("data/players/1/position.yaml")
+ positionUnchanged, err := readTestPlayerRecord(1, "position")
if err != nil {
t.Fatal(err)
}
restarted := newServer()
- after, err := os.Stat("data/players/1/player.yaml")
+ after, err := readTestPlayerRecord(1, "player")
if err != nil {
t.Fatal(err)
}
- savedProfile, err := os.ReadFile("data/players/1/player.yaml")
+ savedProfile, err := readTestPlayerRecord(1, "player")
if err != nil {
t.Fatal(err)
}
- positionYAML, err := os.ReadFile("data/players/1/position.yaml")
+ positionYAML, err := readTestPlayerRecord(1, "position")
if err != nil {
t.Fatal(err)
}
@@ -382,10 +361,10 @@ func TestPositionUpdatesDoNotRewritePlayerProfile(t *testing.T) {
t.Fatal(err)
}
- if os.SameFile(positionBefore, positionFlushed) || !os.SameFile(positionFlushed, positionUnchanged) {
+ if bytes.Equal(positionBefore, positionFlushed) || !bytes.Equal(positionFlushed, positionUnchanged) {
t.Fatal("position flush must replace changed files and leave unchanged files alone")
}
- if !os.SameFile(before, after) || !bytes.Equal(profile, savedProfile) {
+ if !bytes.Equal(before, after) || !bytes.Equal(profile, savedProfile) {
t.Fatal("a position update rewrote the stable player profile")
}
if bytes.Contains(profile, []byte("position:")) || bytes.Contains(profile, []byte("rotation:")) || bytes.Contains(profile, []byte("playfield:")) {
@@ -399,20 +378,15 @@ func TestPositionUpdatesDoNotRewritePlayerProfile(t *testing.T) {
}
}
-func TestFailedPositionReplacementPreservesPlayerProfile(t *testing.T) {
+func TestFailedPositionTransactionPreservesProfileAndRetries(t *testing.T) {
useNPCData(t, testNPCData())
world := newTestServer(t)
world.browserLaunch(httptest.NewRecorder(), httptest.NewRequest("POST", "/browser-launch", nil))
- profile, err := os.ReadFile("data/players/1/player.yaml")
+ profile, err := readTestPlayerRecord(1, "player")
if err != nil {
t.Fatal(err)
}
- if err := os.Remove("data/players/1/position.yaml"); err != nil {
- t.Fatal(err)
- }
- if err := os.Mkdir("data/players/1/position.yaml", 0700); err != nil {
- t.Fatal(err)
- }
+ failDatabaseWrites(t, world)
destination := world.characters[1].userData()
destination.Position = [3]float32{960, 16.375, 510}
@@ -420,31 +394,18 @@ func TestFailedPositionReplacementPreservesPlayerProfile(t *testing.T) {
t.Fatal(err)
}
saveErr := world.flushPositions(time.Now().Add(20 * time.Second))
- savedProfile, err := os.ReadFile("data/players/1/player.yaml")
- if err != nil {
- t.Fatal(err)
- }
- files, err := os.ReadDir("data/players/1")
- if err != nil {
- t.Fatal(err)
- }
-
- if saveErr == nil || !bytes.Equal(profile, savedProfile) || world.characters[1].name != "Visitor1" {
- t.Fatalf("failed position save changed the profile: %s %v", savedProfile, saveErr)
- }
- if len(files) != 2 || files[0].Name() != "player.yaml" || files[1].Name() != "position.yaml" {
- t.Fatalf("failed save left temporary files: %v", files)
- }
-
- // A failed flush leaves the latest position pending for the next interval.
- if err := os.Remove("data/players/1/position.yaml"); err != nil {
+ savedProfile, err := readTestPlayerRecord(1, "player")
+ if _, err := world.db.Exec("PRAGMA query_only=OFF"); err != nil {
t.Fatal(err)
}
if err := world.flushPositions(time.Now().Add(40 * time.Second)); err != nil {
t.Fatal(err)
}
- if newServer().characters[1].position != destination.Position {
- t.Fatal("position was not retried after a failed flush")
+ restarted := newServer()
+ defer restarted.db.Close()
+
+ if saveErr == nil || err != nil || !bytes.Equal(profile, savedProfile) || restarted.characters[1].position != destination.Position {
+ t.Fatalf("position rollback or retry failed: %v %v", saveErr, err)
}
}
@@ -453,7 +414,7 @@ func TestPositionSavesFollowEachPlayersFixedSchedule(t *testing.T) {
world := newTestServer(t)
created := time.Now()
for _, name := range []string{"First", "Second"} {
- request := httptest.NewRequest("POST", "/users", strings.NewReader("name="+name))
+ request := httptest.NewRequest("POST", "/control/users", strings.NewReader("name="+name))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
world.createUser(httptest.NewRecorder(), request)
}
@@ -462,11 +423,11 @@ func TestPositionSavesFollowEachPlayersFixedSchedule(t *testing.T) {
t.Fatalf("player %d has no initial save offset: %v", id, world.characters[id].nextPositionSave)
}
}
- firstBefore, err := os.Stat("data/players/1/position.yaml")
+ firstBefore, err := readTestPlayerRecord(1, "position")
if err != nil {
t.Fatal(err)
}
- secondBefore, err := os.Stat("data/players/2/position.yaml")
+ secondBefore, err := readTestPlayerRecord(2, "position")
if err != nil {
t.Fatal(err)
}
@@ -486,43 +447,43 @@ func TestPositionSavesFollowEachPlayersFixedSchedule(t *testing.T) {
if err := world.flushPositions(now.Add(2 * time.Second)); err != nil {
t.Fatal(err)
}
- firstEarly, err := os.Stat("data/players/1/position.yaml")
+ firstEarly, err := readTestPlayerRecord(1, "position")
if err != nil {
t.Fatal(err)
}
if err := world.flushPositions(now.Add(3 * time.Second)); err != nil {
t.Fatal(err)
}
- firstDue, err := os.Stat("data/players/1/position.yaml")
+ firstDue, err := readTestPlayerRecord(1, "position")
if err != nil {
t.Fatal(err)
}
- secondEarly, err := os.Stat("data/players/2/position.yaml")
+ secondEarly, err := readTestPlayerRecord(2, "position")
if err != nil {
t.Fatal(err)
}
if err := world.flushPositions(now.Add(13 * time.Second)); err != nil {
t.Fatal(err)
}
- secondDue, err := os.Stat("data/players/2/position.yaml")
+ secondDue, err := readTestPlayerRecord(2, "position")
if err != nil {
t.Fatal(err)
}
if err := world.flushPositions(now.Add(44 * time.Second)); err != nil {
t.Fatal(err)
}
- firstUnchanged, err := os.Stat("data/players/1/position.yaml")
+ firstUnchanged, err := readTestPlayerRecord(1, "position")
if err != nil {
t.Fatal(err)
}
- if !os.SameFile(firstBefore, firstEarly) || os.SameFile(firstBefore, firstDue) {
+ if !bytes.Equal(firstBefore, firstEarly) || bytes.Equal(firstBefore, firstDue) {
t.Fatal("the first player was not saved at its three-second offset")
}
- if !os.SameFile(secondBefore, secondEarly) || os.SameFile(secondBefore, secondDue) {
+ if !bytes.Equal(secondBefore, secondEarly) || bytes.Equal(secondBefore, secondDue) {
t.Fatal("the second player was not saved at its thirteen-second offset")
}
- if !os.SameFile(firstDue, firstUnchanged) {
+ if !bytes.Equal(firstDue, firstUnchanged) {
t.Fatal("an unchanged position was rewritten on a later cycle")
}
if !world.characters[1].nextPositionSave.Equal(now.Add(63*time.Second)) || !world.characters[2].nextPositionSave.Equal(now.Add(53*time.Second)) {
@@ -533,19 +494,15 @@ func TestPositionSavesFollowEachPlayersFixedSchedule(t *testing.T) {
func TestOfflinePositionSaveWithSparsePlayerIDs(t *testing.T) {
useNPCData(t, testNPCData())
t.Chdir(t.TempDir())
- if err := os.MkdirAll("data/players/7", 0700); err != nil {
+ world := newServer()
+ defer world.db.Close()
+ player := (userData{ID: 7, Name: "Explorer", Appearance: 789, Level: 1, Playfield: 950,
+ Position: [3]float32{53, 14, 60}, Rotation: [4]float32{0, 0, 0, 1}}).character()
+ world.characters[7], world.nextCharacter = player, 7
+ if err := world.saveUser_locked(player); err != nil {
t.Fatal(err)
}
- for name, contents := range map[string]string{
- "player.yaml": "id: 7\nname: Explorer\nappearance: 789\nlevel: 1\n",
- "position.yaml": "playfield: 950\nposition: [53, 14, 60]\nrotation: [0, 0, 0, 1]\n",
- } {
- if err := os.WriteFile("data/players/7/"+name, []byte(contents), 0600); err != nil {
- t.Fatal(err)
- }
- }
- world := newServer()
- request := httptest.NewRequest("POST", "/teleport/7", strings.NewReader("playfield=800"))
+ request := httptest.NewRequest("POST", "/control/teleport/7", strings.NewReader("playfield=800"))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response := httptest.NewRecorder()
diff --git a/server/vehicle_test.go b/server/vehicle_test.go
@@ -15,7 +15,7 @@ func newVehicleWorld(t *testing.T) (*server, *combatTestConn) {
world, conn := newCombatWorld()
player := world.newCharacter()
player.playfield, player.position = 800, [3]float32{600, 67, 700}
- player.stats.VehicleGround = 79 // Effective 81 with the fixture's abilities.
+ player.stats.Navigation.VehicleGround = 79 // Effective 81 with the fixture's abilities.
if err := world.saveUser_locked(player); err != nil {
t.Fatal(err)
}
@@ -47,7 +47,7 @@ func TestGroundVehicleNativeEquipDelayAndRestart(t *testing.T) {
world.advanceEquipment(finish)
restored := newTestInventoryServer(t).characters[1]
- if restored.inventory.Items[0].Slot != 1 || restored.inventory.equipmentBonus(156) != 150 || restored.stats.VehicleGround != 79 ||
+ if restored.inventory.Items[0].Slot != 1 || restored.inventory.equipmentBonus(156) != 150 || restored.stats.Navigation.VehicleGround != 79 ||
len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x35505644 || binary.BigEndian.Uint32(conn.packets[1][45:49]) != 6 {
t.Fatal("vehicle identity, speed bonus, skill or native wear effect did not persist")
}
@@ -76,7 +76,7 @@ func TestGroundVehicleRejectsIneligibleEquipment(t *testing.T) {
request := inventoryMovePacket(1, 64, 1)[20:]
switch scenario {
case "skill 80":
- player.stats.VehicleGround = 78
+ player.stats.Navigation.VehicleGround = 78
case "indoor":
player.playfield = 1183
case "Grid":
@@ -127,7 +127,7 @@ func TestGroundVehicleRechecksRequirementsAfterDelay(t *testing.T) {
finish := client.equipment.readyAt
switch scenario {
case "skill":
- player.stats.VehicleGround = 78
+ player.stats.Navigation.VehicleGround = 78
case "playfield":
player.playfield = 1183
case "combat":
@@ -162,7 +162,7 @@ func TestGroundVehicleRemovalRestoresEffectsAndAllowsCombat(t *testing.T) {
if math.Abs(float64(player.physicalExtent())-0.4) > 0.000001 || len(equippedItemPackets(player)) != 1 {
t.Fatal("worn vehicle did not apply its native scale or reconnect effects")
}
- player.stats.VehicleGround = 0
+ player.stats.Navigation.VehicleGround = 0
if err := world.handleInventory(client, itemMovePacket(1, 1, 111)[20:]); err != nil {
t.Fatal(err)
}
@@ -203,7 +203,7 @@ func TestGroundVehicleMovementUsesNativeRunSpeed(t *testing.T) {
t.Run(scenario.name, func(t *testing.T) {
world, _ := newVehicleWorld(t)
player, client := world.characters[1], world.clients[1]
- player.appearance, player.stats.BodyDevelopment = 277, 26 // Maximum HP 100.
+ player.appearance, player.stats.Body.BodyDevelopment = 277, 26 // Maximum HP 100.
player.position, player.rotation = [3]float32{}, [4]float32{0, 0, 0, 1}
player.running, player.health = scenario.running, scenario.health
if scenario.worn {
diff --git a/server/world.go b/server/world.go
@@ -90,7 +90,7 @@ func characterPacket(character *character) []byte {
body = binary.BigEndian.AppendUint32(body, value)
}
stats := character.baseStats()
- for _, value := range []uint16{5, stats.Strength, stats.Agility, stats.Stamina} {
+ for _, value := range []uint16{5, stats.Abilities.Strength, stats.Abilities.Agility, stats.Abilities.Stamina} {
body = binary.BigEndian.AppendUint16(body, value)
}
}
@@ -190,23 +190,21 @@ func fullCharacterPacket(character *character) []byte {
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, 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{129, uint32(base.PsychologicalModification)}, [2]uint32{149, uint32(base.NanoInitiative)})
- 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)})
+ stats := [][2]uint32{{54, uint32(character.level)}}
+ stats = append(stats, character.baseStats().nativeStats()...)
+ stats = append(stats,
+ [2]uint32{4, uint32(character.appearance >> 4 & 7)},
+ [2]uint32{60, uint32(max(1, character.profession))},
+ [2]uint32{33, uint32(character.appearance >> 9 & 3)},
+ [2]uint32{59, uint32(character.appearance >> 7 & 3)},
+ [2]uint32{27, character.health}, [2]uint32{1, character.maximumHealth()},
+ [2]uint32{37, character.titleLevel()}, [2]uint32{368, uint32(max(1, character.profession))},
+ [2]uint32{51, uint32(character.aggDef)}, [2]uint32{61, character.inventory.Credits},
+ [2]uint32{47, uint32(character.appearance >> 2 & 3)},
+ [2]uint32{214, character.nano}, [2]uint32{221, character.maximumNano()})
if time.Now().Before(character.implantChangesUntil) {
stats = append(stats, [2]uint32{224, 16})
}
- stats = append(stats, [2]uint32{47, uint32(character.appearance >> 2 & 3)})
- stats = append(stats, [2]uint32{214, character.nano}, [2]uint32{221, character.maximumNano()})
- stats = append(stats, [2]uint32{100, uint32(base.MartialArts)}, [2]uint32{120, uint32(base.PhysicalInitiative)},
- [2]uint32{152, uint32(base.BodyDevelopment)}, [2]uint32{132, uint32(base.NanoPool)})
- stats = append(stats, [2]uint32{103, uint32(base.OneHandEdged)}, [2]uint32{118, uint32(base.MeleeInitiative)},
- [2]uint32{142, uint32(base.Brawling)}, [2]uint32{147, uint32(base.FastAttack)})
body = binary.BigEndian.AppendUint32(body, uint32(len(stats)+1)*1009)
for _, stat := range stats {
body = binary.BigEndian.AppendUint32(body, stat[0])
diff --git a/server/world.sql b/server/world.sql
@@ -0,0 +1,196 @@
+CREATE TABLE IF NOT EXISTS world (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ last_item_id INTEGER NOT NULL DEFAULT 0,
+ last_character_id INTEGER NOT NULL DEFAULT 0,
+ last_npc_id INTEGER NOT NULL DEFAULT 1000000,
+ game_seconds REAL NOT NULL DEFAULT 48600,
+ clock_started TEXT NOT NULL,
+ npcs_initialized INTEGER NOT NULL DEFAULT 0
+);
+CREATE TABLE IF NOT EXISTS characters (
+ id INTEGER PRIMARY KEY CHECK (id BETWEEN 1 AND 4294967295),
+ name TEXT NOT NULL DEFAULT '',
+ appearance_race INTEGER NOT NULL DEFAULT 0 CHECK (appearance_race BETWEEN 0 AND 3),
+ appearance_fatness INTEGER NOT NULL DEFAULT 0 CHECK (appearance_fatness BETWEEN 0 AND 3),
+ appearance_breed INTEGER NOT NULL DEFAULT 0 CHECK (appearance_breed BETWEEN 0 AND 7),
+ appearance_sex INTEGER NOT NULL DEFAULT 0 CHECK (appearance_sex BETWEEN 0 AND 3),
+ appearance_side INTEGER NOT NULL DEFAULT 0 CHECK (appearance_side BETWEEN 0 AND 3),
+ appearance_head INTEGER NOT NULL DEFAULT 0 CHECK (appearance_head BETWEEN 0 AND 31),
+ monster_data INTEGER NOT NULL DEFAULT 0,
+ level INTEGER NOT NULL DEFAULT 1,
+ profession INTEGER NOT NULL DEFAULT 1,
+ improvement_points INTEGER NOT NULL DEFAULT 1500,
+ abilities_strength INTEGER NOT NULL DEFAULT 10,
+ abilities_agility INTEGER NOT NULL DEFAULT 10,
+ abilities_stamina INTEGER NOT NULL DEFAULT 10,
+ abilities_intelligence INTEGER NOT NULL DEFAULT 10,
+ abilities_sense INTEGER NOT NULL DEFAULT 10,
+ abilities_psychic INTEGER NOT NULL DEFAULT 10,
+ body_martial_arts INTEGER NOT NULL DEFAULT 5,
+ body_brawling INTEGER NOT NULL DEFAULT 5,
+ body_riposte INTEGER NOT NULL DEFAULT 5,
+ body_dimach INTEGER NOT NULL DEFAULT 5,
+ body_adventuring INTEGER NOT NULL DEFAULT 5,
+ body_swimming INTEGER NOT NULL DEFAULT 5,
+ body_body_development INTEGER NOT NULL DEFAULT 5,
+ body_nano_pool INTEGER NOT NULL DEFAULT 5,
+ melee_one_hand_blunt INTEGER NOT NULL DEFAULT 5,
+ melee_one_hand_edged INTEGER NOT NULL DEFAULT 5,
+ melee_piercing INTEGER NOT NULL DEFAULT 5,
+ melee_two_hand_blunt INTEGER NOT NULL DEFAULT 5,
+ melee_two_hand_edged INTEGER NOT NULL DEFAULT 5,
+ melee_melee_energy INTEGER NOT NULL DEFAULT 5,
+ melee_parry INTEGER NOT NULL DEFAULT 5,
+ melee_sneak_attack INTEGER NOT NULL DEFAULT 5,
+ melee_multi_melee INTEGER NOT NULL DEFAULT 5,
+ melee_fast_attack INTEGER NOT NULL DEFAULT 5,
+ misc_weapons_sharp_objects INTEGER NOT NULL DEFAULT 5,
+ misc_weapons_grenade INTEGER NOT NULL DEFAULT 5,
+ misc_weapons_heavy_weapons INTEGER NOT NULL DEFAULT 5,
+ ranged_bow INTEGER NOT NULL DEFAULT 5,
+ ranged_pistol INTEGER NOT NULL DEFAULT 5,
+ ranged_assault_rifle INTEGER NOT NULL DEFAULT 5,
+ ranged_submachine_gun INTEGER NOT NULL DEFAULT 5,
+ ranged_shotgun INTEGER NOT NULL DEFAULT 5,
+ ranged_rifle INTEGER NOT NULL DEFAULT 5,
+ ranged_ranged_energy INTEGER NOT NULL DEFAULT 5,
+ ranged_fling_shot INTEGER NOT NULL DEFAULT 5,
+ ranged_aimed_shot INTEGER NOT NULL DEFAULT 5,
+ ranged_burst INTEGER NOT NULL DEFAULT 5,
+ ranged_full_auto INTEGER NOT NULL DEFAULT 5,
+ ranged_bow_special_attack INTEGER NOT NULL DEFAULT 5,
+ ranged_multi_ranged INTEGER NOT NULL DEFAULT 5,
+ speed_melee_initiative INTEGER NOT NULL DEFAULT 5,
+ speed_ranged_initiative INTEGER NOT NULL DEFAULT 5,
+ speed_physical_initiative INTEGER NOT NULL DEFAULT 5,
+ speed_nano_initiative INTEGER NOT NULL DEFAULT 5,
+ speed_dodge_ranged INTEGER NOT NULL DEFAULT 5,
+ speed_evade_close INTEGER NOT NULL DEFAULT 5,
+ speed_duck_explosions INTEGER NOT NULL DEFAULT 5,
+ speed_nano_resist INTEGER NOT NULL DEFAULT 5,
+ speed_run_speed INTEGER NOT NULL DEFAULT 100,
+ trade_repair_mechanical_engineering INTEGER NOT NULL DEFAULT 5,
+ trade_repair_electrical_engineering INTEGER NOT NULL DEFAULT 5,
+ trade_repair_quantum_field_technology INTEGER NOT NULL DEFAULT 5,
+ trade_repair_weapon_smithing INTEGER NOT NULL DEFAULT 5,
+ trade_repair_pharmaceutical_technology INTEGER NOT NULL DEFAULT 5,
+ trade_repair_nano_programming INTEGER NOT NULL DEFAULT 5,
+ trade_repair_computer_literacy INTEGER NOT NULL DEFAULT 5,
+ trade_repair_psychology INTEGER NOT NULL DEFAULT 5,
+ trade_repair_chemistry INTEGER NOT NULL DEFAULT 5,
+ trade_repair_tutoring INTEGER NOT NULL DEFAULT 5,
+ nano_aiding_matter_metamorphosis INTEGER NOT NULL DEFAULT 5,
+ nano_aiding_biological_metamorphosis INTEGER NOT NULL DEFAULT 5,
+ nano_aiding_psychological_modification INTEGER NOT NULL DEFAULT 5,
+ nano_aiding_matter_creation INTEGER NOT NULL DEFAULT 5,
+ nano_aiding_time_and_space INTEGER NOT NULL DEFAULT 5,
+ nano_aiding_sensory_improvement INTEGER NOT NULL DEFAULT 5,
+ nano_aiding_first_aid INTEGER NOT NULL DEFAULT 5,
+ nano_aiding_treatment INTEGER NOT NULL DEFAULT 5,
+ spying_concealment INTEGER NOT NULL DEFAULT 5,
+ spying_breaking_and_entering INTEGER NOT NULL DEFAULT 5,
+ spying_trap_disarm INTEGER NOT NULL DEFAULT 5,
+ spying_perception INTEGER NOT NULL DEFAULT 5,
+ navigation_vehicle_air INTEGER NOT NULL DEFAULT 5,
+ navigation_vehicle_ground INTEGER NOT NULL DEFAULT 5,
+ navigation_vehicle_water INTEGER NOT NULL DEFAULT 5,
+ navigation_map_navigation INTEGER NOT NULL DEFAULT 5,
+ running INTEGER NOT NULL DEFAULT 0,
+ browser_token_hash TEXT NOT NULL DEFAULT '',
+ resurrection_terminal INTEGER NOT NULL DEFAULT 0,
+ implant_changes_until DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00',
+ treatment_locked_until DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00',
+ playfield INTEGER NOT NULL DEFAULT 705,
+ position_x REAL NOT NULL DEFAULT 960,
+ position_y REAL NOT NULL DEFAULT 16.5,
+ position_z REAL NOT NULL DEFAULT 510,
+ rotation_x REAL NOT NULL DEFAULT 0,
+ rotation_y REAL NOT NULL DEFAULT 0,
+ rotation_z REAL NOT NULL DEFAULT 0,
+ rotation_w REAL NOT NULL DEFAULT 1,
+ return_playfield INTEGER NOT NULL DEFAULT 0,
+ return_door INTEGER NOT NULL DEFAULT 0,
+ health INTEGER NOT NULL DEFAULT 37,
+ nano INTEGER NOT NULL DEFAULT 35,
+ sitting INTEGER NOT NULL DEFAULT 0,
+ agg_def INTEGER NOT NULL DEFAULT 0,
+ recharge_until DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00',
+ nano_recharge_until DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00',
+ regeneration_at DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00',
+ regeneration_seconds INTEGER NOT NULL DEFAULT 0
+);
+CREATE TABLE IF NOT EXISTS players (
+ id INTEGER PRIMARY KEY REFERENCES characters(id) ON DELETE CASCADE CHECK (id BETWEEN 1 AND 999999),
+ credits INTEGER NOT NULL DEFAULT 0,
+ first_aid_locked_until DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00'
+);
+CREATE TABLE IF NOT EXISTS treatment_locks (
+ player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
+ patient_id INTEGER NOT NULL,
+ locked_until DATETIME NOT NULL,
+ PRIMARY KEY (player_id, patient_id)
+);
+CREATE TABLE IF NOT EXISTS learned_nanos (
+ player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
+ nano_id INTEGER NOT NULL,
+ PRIMARY KEY (player_id, nano_id)
+);
+CREATE TABLE IF NOT EXISTS npcs (
+ id INTEGER PRIMARY KEY REFERENCES characters(id) ON DELETE CASCADE CHECK (id >= 1000000),
+ definition TEXT NOT NULL,
+ present INTEGER NOT NULL,
+ respawn_at DATETIME NOT NULL,
+ leading_contributor INTEGER NOT NULL,
+ has_roaming INTEGER NOT NULL,
+ home_x REAL NOT NULL, home_y REAL NOT NULL, home_z REAL NOT NULL,
+ destination_x REAL NOT NULL, destination_y REAL NOT NULL, destination_z REAL NOT NULL,
+ next_move DATETIME NOT NULL,
+ moving INTEGER NOT NULL,
+ returning_home INTEGER NOT NULL,
+ has_corpse INTEGER NOT NULL,
+ looter INTEGER NOT NULL,
+ credits INTEGER NOT NULL,
+ expires_at DATETIME NOT NULL
+);
+CREATE TABLE IF NOT EXISTS npc_damage_contributors (
+ npc_id INTEGER NOT NULL REFERENCES npcs(id) ON DELETE CASCADE,
+ player_id INTEGER NOT NULL,
+ damage INTEGER NOT NULL,
+ PRIMARY KEY (npc_id, player_id)
+);
+CREATE TABLE IF NOT EXISTS items (
+ id INTEGER PRIMARY KEY CHECK (id BETWEEN 1 AND 4294967295),
+ type INTEGER NOT NULL,
+ template INTEGER NOT NULL,
+ quality INTEGER NOT NULL,
+ count INTEGER NOT NULL CHECK (count BETWEEN 1 AND 65535)
+);
+CREATE TABLE IF NOT EXISTS item_locations (
+ item_id INTEGER PRIMARY KEY REFERENCES items(id),
+ player_id INTEGER REFERENCES players(id),
+ backpack_id INTEGER REFERENCES items(id),
+ corpse_id INTEGER REFERENCES npcs(id),
+ slot INTEGER NOT NULL,
+ reclaim_at TEXT,
+ CHECK ((player_id IS NOT NULL) + (backpack_id IS NOT NULL) + (corpse_id IS NOT NULL) = 1),
+ CHECK ((player_id IS NOT NULL AND slot BETWEEN 1 AND 93) OR
+ (backpack_id IS NOT NULL AND slot BETWEEN 0 AND 20) OR
+ (corpse_id IS NOT NULL AND slot >= 0)),
+ CHECK (reclaim_at IS NULL OR (player_id IS NOT NULL AND slot BETWEEN 64 AND 93))
+);
+CREATE UNIQUE INDEX IF NOT EXISTS player_slots ON item_locations(player_id, slot) WHERE reclaim_at IS NULL;
+CREATE UNIQUE INDEX IF NOT EXISTS backpack_slots ON item_locations(backpack_id, slot);
+CREATE UNIQUE INDEX IF NOT EXISTS corpse_slots ON item_locations(corpse_id, slot);
+CREATE TABLE IF NOT EXISTS chat_history (
+ id INTEGER PRIMARY KEY,
+ owner INTEGER NOT NULL,
+ time TEXT NOT NULL,
+ channel TEXT NOT NULL,
+ sender_id INTEGER NOT NULL,
+ sender TEXT NOT NULL,
+ recipient_id INTEGER NOT NULL,
+ recipient TEXT NOT NULL,
+ playfield INTEGER NOT NULL,
+ message TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS chat_owner ON chat_history(owner, id);
diff --git a/server/world_store.go b/server/world_store.go
@@ -0,0 +1,252 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "database/sql"
+ "maps"
+ "math/rand/v2"
+ "time"
+)
+
+type roamingState struct {
+ Home [3]float32
+ Destination [3]float32
+ NextMove time.Time
+ Moving bool
+ Returning bool
+}
+
+type corpseState struct {
+ Looter uint32
+ Credits uint32
+ ExpiresAt time.Time
+}
+
+type npcState struct {
+ Character characterRecord
+ Definition string
+ Roaming roamingState
+ HasRoaming bool
+ Corpse corpseState
+ HasCorpse bool
+ Present bool
+ RespawnAt time.Time
+ LeadingContributor uint32
+}
+
+type savedNPC struct {
+ State npcState
+ Contributors map[uint32]uint32
+ NextSave time.Time
+}
+
+const npcColumns = "definition, present, respawn_at, leading_contributor, has_roaming, home_x, home_y, home_z, destination_x, destination_y, destination_z, next_move, moving, returning_home, has_corpse, looter, credits, expires_at"
+
+func (state *npcState) fields() []any {
+ return []any{&state.Definition, &state.Present, &state.RespawnAt, &state.LeadingContributor, &state.HasRoaming,
+ &state.Roaming.Home[0], &state.Roaming.Home[1], &state.Roaming.Home[2], &state.Roaming.Destination[0], &state.Roaming.Destination[1], &state.Roaming.Destination[2],
+ &state.Roaming.NextMove, &state.Roaming.Moving, &state.Roaming.Returning, &state.HasCorpse, &state.Corpse.Looter, &state.Corpse.Credits, &state.Corpse.ExpiresAt}
+}
+
+func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[uint32]bool) (map[uint32]savedNPC, error) {
+ characters := maps.Clone(server.characters)
+ deadlines := make(map[uint32]time.Time)
+ for _, respawn := range server.npcRespawns {
+ characters[respawn.npc.id] = respawn.npc
+ deadlines[respawn.npc.id] = respawn.at
+ }
+
+ // Prepare the bulk writes once for the initial population checkpoint.
+ characterWrite, err := tx.Prepare(upsertRecordSQL("characters", characterColumns))
+ if err != nil {
+ return nil, err
+ }
+ defer characterWrite.Close()
+ npcWrite, err := tx.Prepare(upsertRecordSQL("npcs", npcColumns))
+ if err != nil {
+ return nil, err
+ }
+ defer npcWrite.Close()
+
+ // Routine checkpoints are staggered; unobserved zones retain their last snapshot.
+ now := store.npcSaveAt
+ if now.IsZero() {
+ now = time.Now()
+ }
+ saved := maps.Clone(server.savedNPCs)
+ if saved == nil {
+ saved = make(map[uint32]savedNPC)
+ }
+ for id, npc := range characters {
+ if !npc.npc {
+ continue
+ }
+ previous, exists := server.savedNPCs[id]
+ leaving := server.npcZones[npc.playfield] && !zones[npc.playfield]
+ corpse := corpseState{}
+ if npc.corpse != nil {
+ corpse = corpseState{npc.corpse.looter, npc.corpse.credits, npc.corpse.expiresAt}
+ }
+ // Loot transactions must persist corpse ownership and cash atomically.
+ lootChanged := npc.corpse != nil && (!exists || !previous.State.HasCorpse || previous.State.Corpse != corpse)
+ if server.savedNPCs != nil && !store.flushNPCs && !leaving && !lootChanged && (!zones[npc.playfield] || exists && now.Before(previous.NextSave)) {
+ continue
+ }
+ state := npcState{Character: npc.record(), Definition: npc.npcDefinitionID,
+ Present: server.characters[id] != nil, RespawnAt: deadlines[id], LeadingContributor: npc.leadingContributor}
+ state.Character.Profile.Stats, state.Character.Profile.Profession = npc.stats, npc.profession
+ if npc.roaming != nil {
+ state.HasRoaming = true
+ state.Roaming = roamingState{npc.roaming.home, npc.roaming.destination, npc.roaming.nextMove, npc.roaming.moving, npc.roaming.returning}
+ }
+ if npc.corpse != nil {
+ state.HasCorpse = true
+ state.Corpse = corpseState{npc.corpse.looter, npc.corpse.credits, npc.corpse.expiresAt}
+ }
+ nextSave := previous.NextSave
+ if nextSave.IsZero() || !server.npcZones[npc.playfield] && zones[npc.playfield] {
+ nextSave = now.Add(20*time.Second + time.Duration(rand.Int64N(int64(20*time.Second))))
+ } else if !now.Before(nextSave) {
+ nextSave = now.Add(20 * time.Second)
+ }
+ saved[id] = savedNPC{state, maps.Clone(npc.damageContributors), nextSave}
+ if exists && previous.State == state && maps.Equal(previous.Contributors, npc.damageContributors) {
+ continue
+ }
+ if _, err := characterWrite.Exec(append([]any{id}, state.Character.fields()...)...); err != nil {
+ return nil, err
+ }
+ if _, err := npcWrite.Exec(append([]any{id}, state.fields()...)...); err != nil {
+ return nil, err
+ }
+ if _, err := tx.Exec("DELETE FROM npc_damage_contributors WHERE npc_id=?", id); err != nil {
+ return nil, err
+ }
+ for player, damage := range npc.damageContributors {
+ if _, err := tx.Exec("INSERT INTO npc_damage_contributors (npc_id, player_id, damage) VALUES (?, ?, ?)", id, player, damage); err != nil {
+ return nil, err
+ }
+ }
+ }
+ for id, previous := range server.savedNPCs {
+ if characters[id] != nil {
+ continue
+ }
+ zone := previous.State.Character.Position.Playfield
+ if !store.flushNPCs && !zones[zone] && !server.npcZones[zone] {
+ continue
+ }
+ if _, err := tx.Exec("DELETE FROM characters WHERE id = ?", id); err != nil {
+ return nil, err
+ }
+ delete(saved, id)
+ }
+ return saved, nil
+}
+
+func (server *server) loadNPCs() (bool, error) {
+ db, err := server.database()
+ if err != nil {
+ return false, err
+ }
+ var initialized bool
+ var started string
+ if err := db.QueryRow("SELECT npcs_initialized, last_item_id, last_character_id, last_npc_id, game_seconds, clock_started FROM world WHERE id = 1").Scan(
+ &initialized, &server.nextItem, &server.nextCharacter, &server.nextNPC, &server.gameSeconds, &started); err != nil {
+ return false, err
+ }
+ server.clockStarted, err = time.Parse(time.RFC3339Nano, started)
+ if err != nil || !initialized {
+ return initialized, err
+ }
+ rows, err := db.Query("SELECT id, " + characterColumns + ", " + npcColumns + " FROM characters JOIN npcs USING(id)")
+ if err != nil {
+ return false, err
+ }
+ server.savedNPCs = make(map[uint32]savedNPC)
+ characters := make(map[uint32]*character)
+ for rows.Next() {
+ var state npcState
+ fields := append([]any{&state.Character.Profile.ID}, state.Character.fields()...)
+ if err := rows.Scan(append(fields, state.fields()...)...); err != nil {
+ rows.Close()
+ return false, err
+ }
+ npc := state.Character.character()
+ npc.npc, npc.npcDefinitionID = true, state.Definition
+ npc.stats, npc.profession = state.Character.Profile.Stats, state.Character.Profile.Profession
+ npc.combatProfile = gamedata.NPCCombatProfiles[npc.monsterData][npc.level]
+ npc.leadingContributor = state.LeadingContributor
+ if state.HasRoaming {
+ npc.roaming = &npcRoaming{state.Roaming.Home, state.Roaming.Destination, state.Roaming.NextMove, state.Roaming.Moving, state.Roaming.Returning}
+ }
+ if state.HasCorpse {
+ npc.corpse = &npcCorpse{looter: state.Corpse.Looter, credits: state.Corpse.Credits, expiresAt: state.Corpse.ExpiresAt}
+ }
+ if state.Present {
+ server.characters[npc.id] = npc
+ if npc.roaming != nil && npc.health != 0 {
+ server.roamingNPCs[npc.playfield] = append(server.roamingNPCs[npc.playfield], npc)
+ }
+ if npc.corpse != nil && !npc.corpse.expiresAt.IsZero() {
+ server.corpseExpiry = append(server.corpseExpiry, npc)
+ }
+ }
+ if !state.RespawnAt.IsZero() {
+ server.npcRespawns = append(server.npcRespawns, npcRespawn{npc, state.RespawnAt})
+ }
+ characters[npc.id] = npc
+ server.savedNPCs[npc.id] = savedNPC{State: state, NextSave: time.Now().Add(time.Duration(rand.Int64N(int64(20 * time.Second))))}
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ return false, err
+ }
+ rows.Close()
+
+ // Contribution rows include hidden respawn sources as well as visible NPCs.
+ rows, err = db.Query("SELECT npc_id, player_id, damage FROM npc_damage_contributors")
+ if err != nil {
+ return false, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id, player, damage uint32
+ if err := rows.Scan(&id, &player, &damage); err != nil {
+ return false, err
+ }
+ if characters[id].damageContributors == nil {
+ characters[id].damageContributors = make(map[uint32]uint32)
+ }
+ characters[id].damageContributors[player] = damage
+ saved := server.savedNPCs[id]
+ if saved.Contributors == nil {
+ saved.Contributors = make(map[uint32]uint32)
+ }
+ saved.Contributors[player] = damage
+ server.savedNPCs[id] = saved
+ }
+ return true, rows.Err()
+}
+
+func (server *server) flushWorld() error {
+ server.mutex.Lock()
+ defer server.mutex.Unlock()
+ store, err := server.itemStore_locked(&character{}, playerInventory{})
+ if err != nil {
+ return err
+ }
+ store.flushNPCs = true
+ return server.writeItemStore_locked(store)
+}
+
+func (server *server) checkpointWorld(now time.Time) error {
+ server.mutex.Lock()
+ defer server.mutex.Unlock()
+ store, err := server.itemStore_locked(&character{}, playerInventory{})
+ if err != nil {
+ return err
+ }
+ store.npcSaveAt = now
+ return server.writeItemStore_locked(store)
+}
diff --git a/server/zoning.go b/server/zoning.go
@@ -67,7 +67,7 @@ func (server *server) zoneDestination_locked(character *character, client *world
// Grid statel 0xc04c0098 runs LineTeleport on collision with its exit beam.
// Use a provisional two-metre envelope until the native mesh is recovered.
if client.target && character.playfield == 152 &&
- character.stats.effectiveSkill(character.stats.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 90 {
+ character.stats.effectiveSkill(character.stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) > 90 {
x, y, z := character.position[0]-242.31323, character.position[1]-4.199992, character.position[2]-199.41223
if x*x+y*y+z*z <= 2*2 {
destination := character.userData()
diff --git a/tools/client/server_fixture.py b/tools/client/server_fixture.py
@@ -0,0 +1,19 @@
+"""Create the isolated character used by native and browser smoke checks."""
+import pathlib
+import sqlite3
+
+
+def create_player(directory, name, rotation):
+ root = pathlib.Path(__file__).resolve().parents[2]
+ (directory / 'data').mkdir(parents=True, exist_ok=True)
+ with sqlite3.connect(directory / 'data/world.sqlite') as database:
+ database.executescript((root / 'server/world.sql').read_text())
+ database.execute(
+ "INSERT INTO characters (id, name, appearance_race, appearance_fatness, appearance_breed, "
+ "appearance_sex, appearance_side, rotation_x, rotation_y, rotation_z, rotation_w) "
+ "VALUES (73, ?, 1, 1, 1, 2, 1, ?, ?, ?, ?) "
+ "ON CONFLICT(id) DO UPDATE SET name=excluded.name, playfield=705, "
+ "position_x=960, position_y=16.5, position_z=510, rotation_x=excluded.rotation_x, "
+ "rotation_y=excluded.rotation_y, rotation_z=excluded.rotation_z, rotation_w=excluded.rotation_w",
+ (name, *rotation))
+ database.execute("INSERT OR IGNORE INTO players (id) VALUES (73)")
diff --git a/tools/client/sweep_browser.py b/tools/client/sweep_browser.py
@@ -1,7 +1,6 @@
"""Run an isolated WASM sweep; open the printed URL and press Start WASM sweep."""
import base64
import hashlib
-import html
import http.server
import json
import pathlib
@@ -17,6 +16,7 @@ import urllib.request
root = pathlib.Path(__file__).resolve().parents[2]
sys.path.insert(0, str(root))
import tools.client.playfield_catalog
+import tools.client.server_fixture
work = root / 'local/playfield-sweep'
assert len(sys.argv) <= 2, 'usage: sweep_browser.py [previous-run-directory]'
@@ -46,9 +46,7 @@ if not resuming:
(fixture / 'data').mkdir(parents=True)
(fixture / 'client').mkdir()
(fixture / 'anarchy-assets-14.9.1').symlink_to(root / 'anarchy-assets-14.9.1')
- (fixture / 'data/players/73').mkdir(parents=True)
- (fixture / 'data/players/73/player.yaml').write_text('id: 73\nname: WASM Sweep\nappearance: 789\nmonster_data: 0\nlevel: 1\n')
- (fixture / 'data/players/73/position.yaml').write_text('playfield: 705\nposition: [960, 16.5, 510]\nrotation: [0, 0, 0, 1]\n')
+ tools.client.server_fixture.create_player(fixture, 'WASM Sweep', [0, 0, 0, 1])
for name in ['sweep-game.js', 'sweep-game.wasm']:
shutil.copyfile(build / name, fixture / 'client' / name)
shutil.copyfile(build / 'build.json', output / 'client-build.json')
@@ -97,15 +95,14 @@ def request(path, fields=None):
def character_pose():
- page = request('/users/73').decode()
- data = html.unescape(re.search(r'<textarea[^>]*>(.*?)</textarea>', page, re.S)[1])
- return {field: json.loads(re.search(r'^' + field + r': (\[.*\])$', data, re.M)[1])
- for field in ['position', 'rotation']}
+ # Live pose comes from the player feed.
+ player = next(player for player in json.loads(request('/control/map-players'))['players'] if player['id'] == 73)
+ return {field: player[field] for field in ['position', 'rotation']}
def tick(message):
global active, instance, need_launch, disconnect_started
- player = json.loads(request('/map-players'))['players'][0]
+ player = json.loads(request('/control/map-players'))['players'][0]
if active is None:
if not queue:
return {'action': 'done'}
@@ -119,8 +116,8 @@ def tick(message):
disconnect_started = None
queue.pop(0)
log_start = (fixture / 'logs/server.log').stat().st_size
- request('/teleport/73', {'playfield': zone['id']})
- request('/time', {'hour': 13, 'minute': 30})
+ request('/control/teleport/73', {'playfield': zone['id']})
+ request('/control/time', {'hour': 13, 'minute': 30})
active = dict(zone, phase=phase, started=time.time(), status='loading',
server_log_start=log_start, cold_start=need_launch, user_agent=message['user_agent'])
if need_launch:
@@ -129,7 +126,7 @@ def tick(message):
active['instance'] = instance
return {'action': 'launch', 'instance': instance, 'id': zone['id'], 'phase': phase}
active['instance'] = instance
- player = json.loads(request('/map-players'))['players'][0]
+ player = json.loads(request('/control/map-players'))['players'][0]
# Main-page heartbeats remain responsive even if the game worker faults or blocks.
assert message['instance'] == instance
diff --git a/tools/client/sweep_playfields.py b/tools/client/sweep_playfields.py
@@ -1,6 +1,5 @@
"""Exercise every available 14.9.1 playfield in an isolated native client/server."""
import hashlib
-import html
import json
import os
import pathlib
@@ -18,6 +17,7 @@ import PIL.Image
root = pathlib.Path(__file__).resolve().parents[2]
sys.path.insert(0, str(root))
import tools.client.playfield_catalog
+import tools.client.server_fixture
work = root / 'local/playfield-sweep'
work.mkdir(parents=True, exist_ok=True)
@@ -47,9 +47,7 @@ if not resuming:
shutil.copy2(source, assets / source.name)
active.mkdir()
(fixture / 'data').mkdir(parents=True)
- (fixture / 'data/players/73').mkdir(parents=True)
- (fixture / 'data/players/73/player.yaml').write_text('id: 73\nname: Playfield Sweep\nappearance: 789\nmonster_data: 0\nlevel: 1\n')
- (fixture / 'data/players/73/position.yaml').write_text('playfield: 705\nposition: [960, 16.5, 510]\nrotation: [0, 0, 0, 1]\n')
+ tools.client.server_fixture.create_player(fixture, 'Playfield Sweep', [0, 0, 0, 1])
for port in [7520, 7521, 8082]:
with socket.socket() as connection:
assert connection.connect_ex(('127.0.0.1', port)) != 0, port
@@ -93,11 +91,9 @@ def request(path, fields=None):
def character_pose():
- # Read the existing character editor's live state, including server rotation.
- page = request('/users/73').decode()
- data = html.unescape(re.search(r'<textarea[^>]*>(.*?)</textarea>', page, re.S)[1])
- return {field: json.loads(re.search(r'^' + field + r': (\[.*\])$', data, re.M)[1])
- for field in ['position', 'rotation']}
+ # Live pose comes from the player feed.
+ player = next(player for player in json.loads(request('/control/map-players'))['players'] if player['id'] == 73)
+ return {field: player[field] for field in ['position', 'rotation']}
def stop_client():
@@ -118,12 +114,12 @@ def run_zone(zone, phase):
previous_pid = client.pid if client is not None else None
if client is None:
deadline = time.monotonic() + 10
- while json.loads(request('/map-players'))['players'][0]['connected']:
+ while json.loads(request('/control/map-players'))['players'][0]['connected']:
assert time.monotonic() < deadline, 'server did not observe client disconnect'
time.sleep(.1)
server_log_start = (fixture / 'logs/server.log').stat().st_size
- request('/teleport/73', {'playfield': zone['id']})
- request('/time', {'hour': 13, 'minute': 30})
+ request('/control/teleport/73', {'playfield': zone['id']})
+ request('/control/time', {'hour': 13, 'minute': 30})
started = time.monotonic()
result = {'phase': phase, 'id': zone['id'], 'name': zone['name'], 'started': time.time(), 'status': 'timeout', 'previous_pid': previous_pid, 'run_started': metadata['started']}
if client is None:
@@ -146,7 +142,7 @@ def run_zone(zone, phase):
if client.poll() is not None:
result.update(status='client-exit', exit_code=client.returncode)
break
- player = json.loads(request('/map-players'))['players'][0]
+ player = json.loads(request('/control/map-players'))['players'][0]
if ready is not None and player['playfield'] != zone['id']:
result.update(status='zoned-during-movement', destination=player['playfield'])
break
diff --git a/tools/client/verify_client_1491.py b/tools/client/verify_client_1491.py
@@ -26,16 +26,16 @@ with socket.create_connection(('127.0.0.1', 7510), timeout=10) as connection:
character_id = struct.unpack_from('>I', body, 12)[0]
# View Bronto Burger and the building behind it from street level to the southwest.
-url = f'http://127.0.0.1:8081/users/{character_id}'
+url = f'http://127.0.0.1:8081/control/users/{character_id}'
page = urllib.request.urlopen(url).read().decode()
data = html.unescape(re.search(r'<textarea[^>]*>(.*?)</textarea>', page, re.S)[1])
-assert 'return_door:' not in data
+assert 'return_door: null' in data
data = re.sub(r'(?m)^playfield:.*$', 'playfield: 705', data)
data = re.sub(r'(?m)^position:.*$', 'position: [960, 16.5, 510]', data)
data = re.sub(r'(?m)^rotation:.*$', 'rotation: [0, 0.9238795, 0, -0.3826834]', data)
request = urllib.parse.urlencode({'data': data}).encode()
urllib.request.urlopen(url, request).read()
-urllib.request.urlopen('http://127.0.0.1:8081/time', b'hour=13&minute=30').read()
+urllib.request.urlopen('http://127.0.0.1:8081/control/time', b'hour=13&minute=30').read()
# Suppress first-run tutorials so each fresh test character has an unobstructed view.
preferences = client / 'Prefs/localtest'
diff --git a/tools/client/verify_game.py b/tools/client/verify_game.py
@@ -40,15 +40,15 @@ with socket.create_connection(("127.0.0.1", 7510), timeout=10) as connection:
character_id = struct.unpack_from(">I", body, 12)[0]
# Match the approved stock Bronto Burger view and suppress first-run tutorials.
-url = f"http://127.0.0.1:8081/users/{character_id}"
+url = f"http://127.0.0.1:8081/control/users/{character_id}"
page = urllib.request.urlopen(url).read().decode()
data = html.unescape(re.search(r"<textarea[^>]*>(.*?)</textarea>", page, re.S)[1])
-assert "return_door:" not in data
+assert "return_door: null" in data
data = re.sub(r"(?m)^playfield:.*$", "playfield: 705", data)
data = re.sub(r"(?m)^position:.*$", "position: [960, 16.5, 510]", data)
data = re.sub(r"(?m)^rotation:.*$", "rotation: [0, 0.9238795, 0, -0.3826834]", data)
urllib.request.urlopen(url, urllib.parse.urlencode({"data": data}).encode()).read()
-urllib.request.urlopen("http://127.0.0.1:8081/time", b"hour=13&minute=30").read()
+urllib.request.urlopen("http://127.0.0.1:8081/control/time", b"hour=13&minute=30").read()
preferences = client / "Prefs/localtest"
character_preferences = preferences / f"Char{character_id}"
character_preferences.mkdir(exist_ok=True)
diff --git a/tools/client/verify_linux_game.py b/tools/client/verify_linux_game.py
@@ -6,11 +6,14 @@ import pathlib
import re
import socket
import subprocess
+import sys
import time
import urllib.request
root = pathlib.Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(root))
+import tools.client.server_fixture
work = root / 'local/client'
client = root / 'anarchy-assets-14.9.1'
fixture = work / 'linux-server-probe'
@@ -32,6 +35,7 @@ def run_linux():
with socket.socket() as connection:
assert connection.connect_ex(('127.0.0.1', port)) != 0, 'Server port already in use: %d' % port
+ tools.client.server_fixture.create_player(fixture, 'Linux Smoke', [0, 0.9238795, 0, -0.3826834])
(fixture / 'logs').mkdir(exist_ok=True)
(fixture / 'logs/server.log').write_text('')
with (output / 'server.log').open('w') as log:
@@ -47,7 +51,7 @@ def run_linux():
break
time.sleep(.1)
assert ready, 'Isolated server did not become ready; inspect server.log'
- urllib.request.urlopen('http://127.0.0.1:8081/time', b'hour=13&minute=30', timeout=5).read()
+ urllib.request.urlopen('http://127.0.0.1:8081/control/time', b'hour=13&minute=30', timeout=5).read()
# GDB injects SDL events and reads completed game frames before desktop clipping.
environment = os.environ.copy()
@@ -84,19 +88,12 @@ def run_windows():
for name in ['stderr.txt', 'DXDiagOutput.txt', 'AnarchyCrashLog.txt']:
path = client / name
backups[path] = path.read_bytes() if path.exists() else None
- users = fixture / 'data/players/73/player.yaml'
- backups[users] = users.read_bytes()
- positions = fixture / 'data/players/73/position.yaml'
- backups[positions] = positions.read_bytes()
+ database = fixture / 'data/world.sqlite'
+ backups[database] = database.read_bytes() if database.exists() else None
output.mkdir(exist_ok=True)
for path in output.glob('*.json'):
path.unlink()
try:
- assert re.findall(r'(?m)^id: (\d+)$', users.read_text()) == ['73'], 'Expected the isolated character fixture'
- data = positions.read_text()
- data = re.sub(r'(?m)^position:.*$', 'position: [960, 16.5, 510]', data)
- data = re.sub(r'(?m)^rotation:.*$', 'rotation: [0, 0.9238795, 0, -0.3826834]', data)
- positions.write_text(data)
with (output / 'client.log').open('w') as log:
subprocess.run([
'wsl', '-d', 'Ubuntu-26.04', '--cd', '/path/to/ao',